/** * 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 INFO_EPOCH = enc.encode('shade-live/v1\0epoch'); 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), }; } /** * Link mode: the seed of epoch `e` derived from a long-lived channel secret, * so a holder of the secret can follow every epoch on its own — across * publisher restarts and rotations, with no one to hand it a new grant. */ export function linkEpochSeed(channelSecret: Uint8Array, channelId: Uint8Array, epoch: number): Uint8Array { return hkdf(sha256, channelSecret, channelId, concat([INFO_EPOCH, u32be(epoch)]), 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; /** * Link mode. Epoch seeds are derived from this secret instead of drawn at * random, and grants made with `{ link: true }` carry it — so a capability * link keeps working across restarts and rotations. The price: no forward * secrecy against a link holder, and no removing one short of a new * channel. Session grants stay per-epoch either way. */ channelSecret?: Uint8Array; /** First epoch (resume a channel after a restart with `lastEpoch + 1`). */ epoch?: number; /** Start a new epoch every this many frames, so catching up stays cheap. */ rotateEvery?: number; } 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; /** Include the channel secret (link mode only): the grant then covers every epoch from now on. */ link?: boolean; } 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; private readonly channelSecret: Uint8Array | null; private readonly rotateEvery: number; 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); this.channelSecret = opts.channelSecret ?? null; if (this.channelSecret !== null && this.channelSecret.length !== 32) { throw new MediaFormatError('channelSecret must be 32 bytes'); } this.rotateEvery = opts.rotateEvery ?? Number.POSITIVE_INFINITY; this.epochValue = opts.epoch ?? 0; const k = epochKeys(this.seedFor(this.epochValue), this.channelId, this.epochValue); this.chainKey = k.chainKey; this.stickyKey = k.stickyKey; } private seedFor(epoch: number): Uint8Array { return this.channelSecret !== null ? linkEpochSeed(this.channelSecret, this.channelId, epoch) : randomBytes(32); } /** True when the next frame should go out in a fresh epoch (see `rotateEvery`). */ get rotationDue(): boolean { return this.seq >= this.rotateEvery; } 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 { 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 } : {}), ...(opts.link === true ? { channelSecret: this.requireSecret().slice() } : {}), }; } private requireSecret(): Uint8Array { if (this.channelSecret === null) throw new Error('link grants need a publisher created with channelSecret'); return this.channelSecret; } /** * 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 { 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(this.seedFor(this.epochValue), 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 { stickyKey: Uint8Array; nextSeq: number; chainKey: Uint8Array; skipped: Map; stickySeen: Set; } /** * 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(); readonly channelId: Uint8Array; readonly signingKey: Uint8Array; private readonly verifier: Ed25519Verifier; /** Link mode: derive epochs from here on by ourselves. */ private link: { secret: Uint8Array; fromEpoch: number } | null = null; constructor(grant: LiveGrant) { this.channelId = grant.channelId; this.signingKey = grant.signingKey; this.verifier = new Ed25519Verifier(grant.signingKey); this.addGrant(grant); } /** Can this subscriber read epoch `e` (now, or by deriving it)? */ canRead(epoch: number): boolean { return this.epochs.has(epoch) || (this.link !== null && epoch >= this.link.fromEpoch); } private epochState(epoch: number): EpochState | undefined { const st = this.epochs.get(epoch); if (st !== undefined || this.link === null || epoch < this.link.fromEpoch) return st; const k = epochKeys(linkEpochSeed(this.link.secret, this.channelId, epoch), this.channelId, epoch); const fresh: EpochState = { stickyKey: k.stickyKey, nextSeq: 0, chainKey: k.chainKey, skipped: new Map(), stickySeen: new Set(), }; this.epochs.set(epoch, fresh); // A link viewer moves forward with the channel; old epochs are dropped. this.forgetBefore(epoch); return fresh; } /** 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'); } if (g.channelSecret !== undefined) { if (this.link === null || g.epoch < this.link.fromEpoch) this.link = { secret: g.channelSecret.slice(), fromEpoch: g.epoch }; } const existing = this.epochs.get(g.epoch); if (existing !== undefined && existing.nextSeq <= g.seq) return; this.epochs.set(g.epoch, { stickyKey: g.stickyKey.slice(), 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); st.stickyKey.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 { 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.epochState(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.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); this.link?.secret.fill(0); this.link = null; } }