feat(media): browser playback, live WebM and log streaming, shade media/live CLI

- Service Worker plays sealed files in native <video>/<audio>/<img> with
  Range seeking; watch page served by the relay itself (#shade= fragment
  links, grant never sent to a server)
- MSE live player with keyframe-aware joining, gap detection, latency control
- WebM splitter (init + clusters, keyframe detection) that puts blocks in
  timecode order — Chrome rejects ffmpeg's interleaved Opus/VP8 otherwise
- Link mode for live channels: epoch seeds from a channel secret, so a
  link survives publisher restarts and scheduled rotations
- File store streams byte ranges itself (Bun.file().slice() in a Response
  sent whole files to Range requests)
- shade media serve|put|get|ls|rm, shade live text|webm|watch

Verified end to end in headless Chromium: VP9/Opus film plays and seeks,
live VP8/Opus at 2.9 s latency, live logs, sealed JPEG and Opus audio.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 21:01:52 +02:00
parent 9e64ec87be
commit f359cbd9ad
28 changed files with 1796 additions and 40 deletions

View File

@@ -55,6 +55,7 @@ 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]);
@@ -75,6 +76,15 @@ export function epochKeys(
};
}
/**
* 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) };
@@ -100,6 +110,18 @@ export interface PublisherOptions {
/** 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 {
@@ -111,6 +133,8 @@ export interface GrantOptions {
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 {
@@ -140,6 +164,8 @@ export class LivePublisher {
/** 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);
@@ -149,11 +175,26 @@ export class LivePublisher {
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.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;
}
@@ -232,9 +273,15 @@ export class LivePublisher {
...(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
@@ -248,7 +295,7 @@ export class LivePublisher {
this.snapshots = [];
this.chainKey.fill(0);
this.stickyKey.fill(0);
const k = epochKeys(randomBytes(32), this.channelId, this.epochValue);
const k = epochKeys(this.seedFor(this.epochValue), this.channelId, this.epochValue);
this.chainKey = k.chainKey;
this.stickyKey = k.stickyKey;
const content = this.stickyContent;
@@ -290,7 +337,7 @@ export interface ReceivedFrame {
}
interface EpochState {
grant: LiveGrant;
stickyKey: Uint8Array;
nextSeq: number;
chainKey: Uint8Array;
skipped: Map<number, Uint8Array>;
@@ -307,6 +354,8 @@ export class LiveSubscriber {
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;
@@ -315,6 +364,28 @@ export class LiveSubscriber {
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');
@@ -323,10 +394,13 @@ export class LiveSubscriber {
// 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, {
grant: g,
stickyKey: g.stickyKey.slice(),
nextSeq: g.seq,
chainKey: g.chainKey.slice(),
skipped: new Map(),
@@ -339,6 +413,7 @@ export class LiveSubscriber {
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);
}
@@ -357,7 +432,7 @@ export class LiveSubscriber {
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);
const st = this.epochState(h.epoch);
if (st === undefined) {
throw new LiveKeyError(`no grant for epoch ${h.epoch} (have ${[...this.epochs.keys()].join(', ')})`);
}
@@ -366,7 +441,7 @@ export class LiveSubscriber {
let plain: Uint8Array;
if (sticky) {
if (st.stickySeen.has(h.seq)) return null;
plain = await openOnce(st.grant.stickyKey, nonce, f.ciphertext, f.headerBytes);
plain = await openOnce(st.stickyKey, nonce, f.ciphertext, f.headerBytes);
st.stickySeen.add(h.seq);
} else {
const mk = this.messageKey(st, h.seq);
@@ -425,6 +500,8 @@ export class LiveSubscriber {
close(): void {
this.forgetBefore(Number.MAX_SAFE_INTEGER);
this.link?.secret.fill(0);
this.link = null;
}
}