feat(media): @shade/media — seekable sealed media (SMF1), live channels, media routes and live relay
SMF1 seals a film, video, image or song once into a file any Range-capable store can serve; the reader fetches only segments under the playhead and checks each against a digest table pinned by the grant's root digest. Live channels use a sender-key chain with per-frame Ed25519 signatures, sticky init frames and keyframe snapshots for late joiners, and epoch rotation to remove a viewer. Server side: a disk-backed media store with signed owner uploads and a WebSocket relay with bounded backlog. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
430
packages/shade-media/src/live/channel.ts
Normal file
430
packages/shade-media/src/live/channel.ts
Normal file
@@ -0,0 +1,430 @@
|
||||
/**
|
||||
* Live channels: one publisher, any number of viewers, a dumb relay between.
|
||||
*
|
||||
* The key schedule is Signal's **Sender Keys**, the construction WhatsApp and
|
||||
* Signal use for groups, adapted to a broadcast:
|
||||
*
|
||||
* epochSeed random 32 bytes per epoch
|
||||
* ck[0] = HKDF(epochSeed, salt = channelId ‖ u32(epoch), "shade-live/v1\0chain")
|
||||
* stickyKey = HKDF(epochSeed, salt = channelId ‖ u32(epoch), "shade-live/v1\0sticky")
|
||||
* mk[i] = HMAC(ck[i], 0x01) frame key for seq i, used once
|
||||
* ck[i+1] = HMAC(ck[i], 0x02) one-way: ck[i] cannot be recovered
|
||||
* nonce = u32(epoch) ‖ u64(seq) aad = the 48-byte frame header
|
||||
*
|
||||
* Every frame is also **signed** with the channel's Ed25519 key. Viewers all
|
||||
* hold the same chain key, so without the signature any one of them could
|
||||
* forge frames to the others through the relay; with it, only the publisher
|
||||
* can speak. The signing key's public half travels in the grant, which
|
||||
* travels over an authenticated Shade session — that is what binds the
|
||||
* channel to a person.
|
||||
*
|
||||
* Joining late: a grant carries the chain key *at some seq*. The publisher
|
||||
* keeps snapshots of the chain at recent keyframes (bounded), so a new viewer
|
||||
* can be handed the key at a point the relay still has buffered and start
|
||||
* from there — never earlier. Removing a viewer is a new epoch: fresh seed,
|
||||
* fresh grants for everyone still in.
|
||||
*
|
||||
* Sticky frames (codec init, the channel's own description) are sealed under
|
||||
* the epoch's `stickyKey` instead of the chain, so a viewer who joins an hour
|
||||
* in can still decode the init segment the publisher sent at second zero.
|
||||
*/
|
||||
|
||||
import { ed25519 } from '@noble/curves/ed25519.js';
|
||||
import { hkdf } from '@noble/hashes/hkdf.js';
|
||||
import { hmac } from '@noble/hashes/hmac.js';
|
||||
import { sha256 } from '@noble/hashes/sha2.js';
|
||||
import { openOnce, sealOnce } from '../aead.js';
|
||||
import { Ed25519Signer, Ed25519Verifier } from '../ed25519.js';
|
||||
import { concat, enc, equalBytes, randomBytes, toB64u, u32be, u64be } from '../bytes.js';
|
||||
import { LiveKeyError, MediaFormatError, MediaIntegrityError } from '../errors.js';
|
||||
import { LIVE_GRANT_KIND } from '../grant.js';
|
||||
import type { LiveGrant } from '../grant.js';
|
||||
import type { MediaMeta } from '../sealed.js';
|
||||
import {
|
||||
CHANNEL_ID_BYTES,
|
||||
FLAG_END,
|
||||
FLAG_KEYFRAME,
|
||||
FLAG_STICKY,
|
||||
MAX_FRAME_PAYLOAD,
|
||||
decodeContent,
|
||||
decodeFrame,
|
||||
encodeContent,
|
||||
encodeHeader,
|
||||
} from './frame.js';
|
||||
import type { LiveContent } from './frame.js';
|
||||
|
||||
const INFO_CHAIN = enc.encode('shade-live/v1\0chain');
|
||||
const INFO_STICKY = enc.encode('shade-live/v1\0sticky');
|
||||
const MK = new Uint8Array([0x01]);
|
||||
const CK = new Uint8Array([0x02]);
|
||||
|
||||
/** Furthest a subscriber will derive forward to reach one frame. */
|
||||
export const MAX_SKIP = 100_000;
|
||||
/** Frame keys a subscriber keeps for frames that may still arrive out of order. */
|
||||
export const MAX_SKIPPED_KEYS = 2_000;
|
||||
|
||||
export function epochKeys(
|
||||
epochSeed: Uint8Array,
|
||||
channelId: Uint8Array,
|
||||
epoch: number,
|
||||
): { chainKey: Uint8Array; stickyKey: Uint8Array } {
|
||||
const salt = concat([channelId, u32be(epoch)]);
|
||||
return {
|
||||
chainKey: hkdf(sha256, epochSeed, salt, INFO_CHAIN, 32),
|
||||
stickyKey: hkdf(sha256, epochSeed, salt, INFO_STICKY, 32),
|
||||
};
|
||||
}
|
||||
|
||||
/** One chain step: the frame key for this seq, and the chain key for the next. */
|
||||
export function chainStep(ck: Uint8Array): { messageKey: Uint8Array; next: Uint8Array } {
|
||||
return { messageKey: hmac(sha256, ck, MK), next: hmac(sha256, ck, CK) };
|
||||
}
|
||||
|
||||
export function frameNonce(epoch: number, seq: number): Uint8Array {
|
||||
return concat([u32be(epoch), u64be(seq)]);
|
||||
}
|
||||
|
||||
export interface FrameOptions {
|
||||
/** A viewer can start here (a video keyframe, a log batch boundary). */
|
||||
keyframe?: boolean;
|
||||
/** Keep for every late joiner, sealed under the epoch's sticky key. */
|
||||
sticky?: boolean;
|
||||
/** Publisher clock, ms. Defaults to `Date.now()`. */
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
export interface PublisherOptions {
|
||||
meta?: MediaMeta;
|
||||
/** Chain snapshots kept for late joiners. Default 64 keyframes. */
|
||||
snapshots?: number;
|
||||
/** Bring your own channel identity (to resume a channel after a restart). */
|
||||
channelId?: Uint8Array;
|
||||
signingSecret?: Uint8Array;
|
||||
}
|
||||
|
||||
export interface GrantOptions {
|
||||
/**
|
||||
* Where the viewer can start: `oldest` keyframe snapshot still kept (most
|
||||
* backlog), the `latest` keyframe, or `now` (only frames sent after this).
|
||||
* Default `oldest`.
|
||||
*/
|
||||
from?: 'oldest' | 'latest' | 'now';
|
||||
url?: string;
|
||||
readToken?: Uint8Array;
|
||||
}
|
||||
|
||||
interface Snapshot {
|
||||
seq: number;
|
||||
chainKey: Uint8Array;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sending side of a live channel. Not safe to call `frame` concurrently —
|
||||
* frames are numbered in call order; await each before the next (the
|
||||
* `LiveClient` does this for you).
|
||||
*/
|
||||
export class LivePublisher {
|
||||
readonly channelId: Uint8Array;
|
||||
readonly signingKey: Uint8Array;
|
||||
readonly meta: MediaMeta | undefined;
|
||||
private readonly signingSecret: Uint8Array;
|
||||
private readonly signer: Ed25519Signer;
|
||||
private epochValue = 0;
|
||||
private seq = 0;
|
||||
private chainKey: Uint8Array;
|
||||
private stickyKey: Uint8Array;
|
||||
private snapshots: Snapshot[] = [];
|
||||
private readonly snapshotLimit: number;
|
||||
/** Plaintext of sticky content, re-sealed into every new epoch. */
|
||||
private stickyContent: { content: LiveContent; opts: FrameOptions }[] = [];
|
||||
/** Sealed sticky frames of the current epoch — what a relay must keep. */
|
||||
private stickyFrames: Uint8Array[] = [];
|
||||
private closed = false;
|
||||
|
||||
constructor(opts: PublisherOptions = {}) {
|
||||
this.channelId = opts.channelId ?? randomBytes(CHANNEL_ID_BYTES);
|
||||
if (this.channelId.length !== CHANNEL_ID_BYTES) throw new MediaFormatError('channelId must be 16 bytes');
|
||||
this.signingSecret = opts.signingSecret ?? ed25519.utils.randomSecretKey();
|
||||
this.signer = new Ed25519Signer(this.signingSecret);
|
||||
this.signingKey = this.signer.publicKey;
|
||||
this.meta = opts.meta;
|
||||
this.snapshotLimit = Math.max(1, opts.snapshots ?? 64);
|
||||
const k = epochKeys(randomBytes(32), this.channelId, 0);
|
||||
this.chainKey = k.chainKey;
|
||||
this.stickyKey = k.stickyKey;
|
||||
}
|
||||
|
||||
get epoch(): number {
|
||||
return this.epochValue;
|
||||
}
|
||||
|
||||
get nextSeq(): number {
|
||||
return this.seq;
|
||||
}
|
||||
|
||||
/** Sticky frames of the current epoch, in order — replay these to a fresh relay. */
|
||||
get sticky(): readonly Uint8Array[] {
|
||||
return this.stickyFrames;
|
||||
}
|
||||
|
||||
/** Seal one frame. */
|
||||
async frame(content: LiveContent, opts: FrameOptions = {}): Promise<Uint8Array> {
|
||||
if (this.closed) throw new Error('LivePublisher is closed');
|
||||
const plain = encodeContent(content);
|
||||
if (plain.length > MAX_FRAME_PAYLOAD) throw new MediaFormatError('live frame payload too large');
|
||||
const seq = this.seq++;
|
||||
const sticky = opts.sticky === true;
|
||||
const keyframe = opts.keyframe === true;
|
||||
let flags = 0;
|
||||
if (sticky) flags |= FLAG_STICKY;
|
||||
if (keyframe) flags |= FLAG_KEYFRAME;
|
||||
if (content.type === 'end') flags |= FLAG_END;
|
||||
|
||||
// The chain advances on every seq, sticky or not, so a viewer's position
|
||||
// in the chain is always just the seq.
|
||||
if (keyframe && !sticky) this.snapshot(seq, this.chainKey);
|
||||
const step = chainStep(this.chainKey);
|
||||
this.chainKey.fill(0);
|
||||
this.chainKey = step.next;
|
||||
|
||||
const header = encodeHeader({
|
||||
flags,
|
||||
channelId: this.channelId,
|
||||
epoch: this.epochValue,
|
||||
seq,
|
||||
timestamp: Math.floor(opts.timestamp ?? Date.now()),
|
||||
ctLen: plain.length + 16,
|
||||
});
|
||||
const key = sticky ? this.stickyKey : step.messageKey;
|
||||
const ct = await sealOnce(key, frameNonce(this.epochValue, seq), plain, header);
|
||||
step.messageKey.fill(0);
|
||||
const signed = concat([header, ct]);
|
||||
const frame = concat([signed, await this.signer.sign(signed)]);
|
||||
if (sticky) {
|
||||
this.stickyFrames.push(frame);
|
||||
this.stickyContent.push({ content, opts });
|
||||
}
|
||||
return frame;
|
||||
}
|
||||
|
||||
private snapshot(seq: number, ck: Uint8Array): void {
|
||||
this.snapshots.push({ seq, chainKey: ck.slice() });
|
||||
while (this.snapshots.length > this.snapshotLimit) this.snapshots.shift()!.chainKey.fill(0);
|
||||
}
|
||||
|
||||
/** Keys for one viewer to join from `opts.from`. Send it over a Shade session. */
|
||||
grant(opts: GrantOptions = {}): LiveGrant {
|
||||
const from = opts.from ?? 'oldest';
|
||||
let point: Snapshot;
|
||||
if (from === 'now' || this.snapshots.length === 0) {
|
||||
point = { seq: this.seq, chainKey: this.chainKey };
|
||||
} else {
|
||||
point = from === 'latest' ? this.snapshots[this.snapshots.length - 1]! : this.snapshots[0]!;
|
||||
}
|
||||
return {
|
||||
kind: LIVE_GRANT_KIND,
|
||||
channelId: this.channelId,
|
||||
signingKey: this.signingKey,
|
||||
epoch: this.epochValue,
|
||||
seq: point.seq,
|
||||
chainKey: point.chainKey.slice(),
|
||||
stickyKey: this.stickyKey.slice(),
|
||||
...(opts.url !== undefined ? { url: opts.url } : {}),
|
||||
...(opts.readToken !== undefined ? { readToken: opts.readToken } : {}),
|
||||
...(this.meta !== undefined ? { meta: this.meta } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new epoch: fresh seed, seq back to 0, snapshots dropped. Returns
|
||||
* the sticky frames re-sealed for the new epoch — send them first. Grant
|
||||
* everyone who should stay; anyone not re-granted is out.
|
||||
*/
|
||||
async rotate(): Promise<Uint8Array[]> {
|
||||
if (this.epochValue >= 0xffff_ffff) throw new Error('epoch counter exhausted');
|
||||
this.epochValue++;
|
||||
this.seq = 0;
|
||||
for (const s of this.snapshots) s.chainKey.fill(0);
|
||||
this.snapshots = [];
|
||||
this.chainKey.fill(0);
|
||||
this.stickyKey.fill(0);
|
||||
const k = epochKeys(randomBytes(32), this.channelId, this.epochValue);
|
||||
this.chainKey = k.chainKey;
|
||||
this.stickyKey = k.stickyKey;
|
||||
const content = this.stickyContent;
|
||||
this.stickyContent = [];
|
||||
this.stickyFrames = [];
|
||||
const out: Uint8Array[] = [];
|
||||
for (const c of content) out.push(await this.frame(c.content, c.opts));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The signed hello a relay pins the channel with. */
|
||||
hello(readTokenHash: Uint8Array, at = Date.now()): { body: string; signature: Uint8Array } {
|
||||
const body = JSON.stringify({
|
||||
kind: 'shade.live-hello/v1',
|
||||
channelId: toB64u(this.channelId),
|
||||
signingKey: toB64u(this.signingKey),
|
||||
readTokenHash: toB64u(readTokenHash),
|
||||
at,
|
||||
});
|
||||
return { body, signature: ed25519.sign(enc.encode(body), this.signingSecret) };
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
this.chainKey.fill(0);
|
||||
this.stickyKey.fill(0);
|
||||
for (const s of this.snapshots) s.chainKey.fill(0);
|
||||
this.snapshots = [];
|
||||
}
|
||||
}
|
||||
|
||||
export interface ReceivedFrame {
|
||||
epoch: number;
|
||||
seq: number;
|
||||
timestamp: number;
|
||||
sticky: boolean;
|
||||
keyframe: boolean;
|
||||
content: LiveContent;
|
||||
}
|
||||
|
||||
interface EpochState {
|
||||
grant: LiveGrant;
|
||||
nextSeq: number;
|
||||
chainKey: Uint8Array;
|
||||
skipped: Map<number, Uint8Array>;
|
||||
stickySeen: Set<number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The viewing side. Feed it frames in any order; it returns each decrypted
|
||||
* frame once, or `null` for one it should silently drop — a duplicate after
|
||||
* a reconnect, or backlog from before the grant's starting point.
|
||||
*/
|
||||
export class LiveSubscriber {
|
||||
private readonly epochs = new Map<number, EpochState>();
|
||||
readonly channelId: Uint8Array;
|
||||
readonly signingKey: Uint8Array;
|
||||
private readonly verifier: Ed25519Verifier;
|
||||
|
||||
constructor(grant: LiveGrant) {
|
||||
this.channelId = grant.channelId;
|
||||
this.signingKey = grant.signingKey;
|
||||
this.verifier = new Ed25519Verifier(grant.signingKey);
|
||||
this.addGrant(grant);
|
||||
}
|
||||
|
||||
/** Add the grant for a new epoch (after a rotation). Older epochs are kept until `forgetBefore`. */
|
||||
addGrant(g: LiveGrant): void {
|
||||
if (!equalBytes(g.channelId, this.channelId)) throw new MediaFormatError('grant is for another channel');
|
||||
if (!equalBytes(g.signingKey, this.signingKey)) {
|
||||
// A new signing key mid-channel would let whoever sent this grant speak
|
||||
// as the publisher. A publisher that truly re-keys starts a new channel.
|
||||
throw new MediaIntegrityError('grant changes the channel signing key');
|
||||
}
|
||||
const existing = this.epochs.get(g.epoch);
|
||||
if (existing !== undefined && existing.nextSeq <= g.seq) return;
|
||||
this.epochs.set(g.epoch, {
|
||||
grant: g,
|
||||
nextSeq: g.seq,
|
||||
chainKey: g.chainKey.slice(),
|
||||
skipped: new Map(),
|
||||
stickySeen: new Set(),
|
||||
});
|
||||
}
|
||||
|
||||
/** Drop key state for epochs older than `epoch` (forward secrecy after rotation). */
|
||||
forgetBefore(epoch: number): void {
|
||||
for (const [e, st] of this.epochs) {
|
||||
if (e < epoch) {
|
||||
st.chainKey.fill(0);
|
||||
for (const k of st.skipped.values()) k.fill(0);
|
||||
this.epochs.delete(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get latestEpoch(): number {
|
||||
return Math.max(...this.epochs.keys());
|
||||
}
|
||||
|
||||
/** Verify and decrypt one frame. Throws on forgery; `null` means "drop, harmlessly". */
|
||||
async open(frame: Uint8Array): Promise<ReceivedFrame | null> {
|
||||
const f = decodeFrame(frame);
|
||||
const h = f.header;
|
||||
if (!equalBytes(h.channelId, this.channelId)) throw new MediaFormatError('frame is for another channel');
|
||||
if (!(await this.verifier.verify(f.signature, f.signed))) {
|
||||
throw new MediaIntegrityError('live frame signature does not verify');
|
||||
}
|
||||
const st = this.epochs.get(h.epoch);
|
||||
if (st === undefined) {
|
||||
throw new LiveKeyError(`no grant for epoch ${h.epoch} (have ${[...this.epochs.keys()].join(', ')})`);
|
||||
}
|
||||
const sticky = (h.flags & FLAG_STICKY) !== 0;
|
||||
const nonce = frameNonce(h.epoch, h.seq);
|
||||
let plain: Uint8Array;
|
||||
if (sticky) {
|
||||
if (st.stickySeen.has(h.seq)) return null;
|
||||
plain = await openOnce(st.grant.stickyKey, nonce, f.ciphertext, f.headerBytes);
|
||||
st.stickySeen.add(h.seq);
|
||||
} else {
|
||||
const mk = this.messageKey(st, h.seq);
|
||||
if (mk === null) return null;
|
||||
try {
|
||||
plain = await openOnce(mk, nonce, f.ciphertext, f.headerBytes);
|
||||
} finally {
|
||||
mk.fill(0);
|
||||
}
|
||||
}
|
||||
return {
|
||||
epoch: h.epoch,
|
||||
seq: h.seq,
|
||||
timestamp: h.timestamp,
|
||||
sticky,
|
||||
keyframe: (h.flags & FLAG_KEYFRAME) !== 0,
|
||||
content: decodeContent(plain),
|
||||
};
|
||||
}
|
||||
|
||||
private messageKey(st: EpochState, seq: number): Uint8Array | null {
|
||||
if (seq < st.nextSeq) {
|
||||
const k = st.skipped.get(seq);
|
||||
if (k === undefined) return null; // before the grant, or already seen
|
||||
st.skipped.delete(seq);
|
||||
return k;
|
||||
}
|
||||
if (seq - st.nextSeq > MAX_SKIP) {
|
||||
throw new LiveKeyError(`frame ${seq} is ${seq - st.nextSeq} ahead — beyond MAX_SKIP`);
|
||||
}
|
||||
// Derive forward, keeping keys for the frames we skip in case they
|
||||
// arrive late. Oldest are evicted first: a frame that late is useless
|
||||
// for live playback anyway.
|
||||
let ck = st.chainKey;
|
||||
for (let s = st.nextSeq; s < seq; s++) {
|
||||
const step = chainStep(ck);
|
||||
ck.fill(0);
|
||||
ck = step.next;
|
||||
if (seq - s <= MAX_SKIPPED_KEYS) {
|
||||
st.skipped.set(s, step.messageKey);
|
||||
if (st.skipped.size > MAX_SKIPPED_KEYS) {
|
||||
const oldest = st.skipped.keys().next().value!;
|
||||
st.skipped.get(oldest)!.fill(0);
|
||||
st.skipped.delete(oldest);
|
||||
}
|
||||
} else {
|
||||
step.messageKey.fill(0);
|
||||
}
|
||||
}
|
||||
const step = chainStep(ck);
|
||||
ck.fill(0);
|
||||
st.chainKey = step.next;
|
||||
st.nextSeq = seq + 1;
|
||||
return step.messageKey;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.forgetBefore(Number.MAX_SAFE_INTEGER);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user