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

@@ -10,6 +10,7 @@
"@shade/core": "workspace:*",
"@shade/crypto-web": "workspace:*",
"@shade/keychain": "workspace:*",
"@shade/media": "workspace:*",
"@shade/sdk": "workspace:*",
"@shade/storage-encrypted": "workspace:*",
"@shade/storage-sqlite": "workspace:*",

View File

@@ -56,6 +56,8 @@ Commands:
rotate-storage-key Re-key the encrypted SQLite store (V3.2)
--key-source / --passphrase / … (current key — same flags as migrate)
--new-key-source / --new-passphrase / … (target key)
media … / live … E2E-encrypted streaming of films, video, images, audio and logs
(run \`shade media\` or \`shade live\` for the subcommands)
help Show this message
Config:
@@ -127,6 +129,12 @@ async function main(): Promise<void> {
await rotateStorageKeyCommand(opts);
break;
}
case 'media':
case 'live': {
const { runMediaCli } = await import('@shade/media/cli');
process.exitCode = await runMediaCli(cmd, args.slice(1));
break;
}
case 'help':
case '--help':
case '-h':

View File

@@ -1,7 +1,7 @@
{
"name": "@shade/media",
"version": "4.15.0",
"description": "End-to-end encrypted media streaming for Shade — seekable sealed films, videos, images and audio, and live channels for logs, text and live video",
"description": "End-to-end encrypted media streaming for Shade \u2014 seekable sealed films, videos, images and audio, and live channels for logs, text and live video",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",
@@ -9,7 +9,8 @@
".": "./src/index.ts",
"./node": "./src/node.ts",
"./server": "./src/server.ts",
"./browser": "./src/browser/index.ts"
"./browser": "./src/browser/index.ts",
"./cli": "./src/cli.ts"
},
"dependencies": {
"@noble/curves": "^2.0.1",

View File

@@ -0,0 +1,64 @@
/**
* Page-side helpers: hand grants to the Service Worker, and play live
* channels through Media Source Extensions.
*/
import { encodeGrant } from '../grant.js';
import type { MediaGrant } from '../grant.js';
import { toHex } from '../bytes.js';
export { LivePlayer } from './player.js';
export type { LivePlayerOptions, LivePlayerStats } from './player.js';
/**
* Register the media worker and wait until it controls this page. `scope`
* is the directory the virtual `media/<id>` URLs live under.
*/
export async function installMediaWorker(swUrl: string, scope?: string): Promise<MediaKeyring> {
if (!('serviceWorker' in navigator)) throw new Error('this browser has no Service Workers');
const reg = await navigator.serviceWorker.register(swUrl, scope !== undefined ? { scope } : {});
await navigator.serviceWorker.ready;
if (navigator.serviceWorker.controller === null) {
// First visit: the worker claims the page on activate.
await new Promise<void>((resolve) =>
navigator.serviceWorker.addEventListener('controllerchange', () => resolve(), { once: true }),
);
}
return new MediaKeyring(reg.scope);
}
/**
* The page's copy of its grants. The worker can be stopped by the browser at
* any time and loses its memory; it then asks the page, and this answers.
*/
export class MediaKeyring {
private readonly grants = new Map<string, string>();
constructor(readonly scope: string) {
navigator.serviceWorker.addEventListener('message', (e) => {
const msg = e.data as { type?: string; id?: string } | null;
if (msg?.type !== 'shade-media-need' || typeof msg.id !== 'string') return;
e.ports[0]?.postMessage(this.grants.get(msg.id) ?? null);
});
}
/** Register a grant with the worker; returns the URL to put in `src`. */
async add(grant: MediaGrant): Promise<string> {
const id = toHex(grant.mediaId);
const json = encodeGrant(grant);
this.grants.set(id, json);
const sw = navigator.serviceWorker.controller;
if (sw === null) throw new Error('media worker is not controlling this page');
const res = await new Promise<{ ok: boolean; error?: string }>((resolve) => {
const ch = new MessageChannel();
ch.port1.onmessage = (m) => resolve(m.data);
sw.postMessage({ type: 'shade-media-grant', grant: json }, [ch.port2]);
});
if (!res.ok) throw new Error(res.error ?? 'worker refused the grant');
return this.urlFor(grant);
}
urlFor(grant: MediaGrant): string {
return new URL(`media/${toHex(grant.mediaId)}`, this.scope).toString();
}
}

View File

@@ -0,0 +1,186 @@
/**
* Live video/audio in a `<video>` element via Media Source Extensions.
*
* Frames come from a `LiveWatchClient`; this turns them into SourceBuffer
* appends. The rules that make live MSE work:
*
* - the sticky `init` frame creates the SourceBuffer (its MIME names the
* codecs) and is appended first; the same init again is skipped;
* - media `chunk`s are dropped until the first keyframe — a decoder cannot
* start mid-GOP — and again after any gap, until the next keyframe;
* - a viewer that joins late has timestamps that start at, say, 37 s: the
* playhead is moved to the start of what is buffered;
* - the playhead is kept close to the live edge, and old media is evicted
* so the buffer does not hit the browser's quota.
*/
import { LiveWatchClient } from '../live/client.js';
import type { LiveState } from '../live/client.js';
import type { ReceivedFrame } from '../live/channel.js';
import type { LiveGrant } from '../grant.js';
import { equalBytes } from '../bytes.js';
export interface LivePlayerOptions {
/** Jump forward when further than this behind the live edge. Default 4 s. */
maxLatencySeconds?: number;
/** Media kept behind the playhead. Default 30 s. */
keepSeconds?: number;
onState?: (s: LiveState) => void;
onError?: (e: Error) => void;
/** Non-media frames (text, images, meta) on the same channel. */
onOther?: (f: ReceivedFrame) => void;
}
export interface LivePlayerStats {
trail: string[];
framesIn: number;
/** Times a frame was missing in the sequence (relay dropped it for a slow viewer). */
gaps: number;
appended: number;
droppedBeforeKeyframe: number;
bufferedSeconds: number;
latencySeconds: number;
}
export class LivePlayer {
readonly client: LiveWatchClient;
private readonly ms = new MediaSource();
private sb: SourceBuffer | null = null;
private lastInit: Uint8Array | null = null;
private queue: Uint8Array[] = [];
private needKeyframe = true;
private lastSeq = -1;
private lastEpoch = -1;
private readonly sourceOpen: Promise<void>;
private readonly stat = { framesIn: 0, appended: 0, droppedBeforeKeyframe: 0, gaps: 0 };
/** Last few frames handled, for diagnosing a player that stalls. */
private readonly trail: string[] = [];
constructor(
private readonly video: HTMLMediaElement,
grant: LiveGrant,
private readonly opts: LivePlayerOptions = {},
) {
this.sourceOpen = new Promise((r) => this.ms.addEventListener('sourceopen', () => r(), { once: true }));
video.src = URL.createObjectURL(this.ms);
this.client = new LiveWatchClient(grant, {
onFrame: (f) => this.onFrame(f),
...(opts.onState !== undefined ? { onState: opts.onState } : {}),
...(opts.onError !== undefined ? { onError: opts.onError } : {}),
});
setInterval(() => this.housekeeping(), 1000);
}
stats(): LivePlayerStats {
const b = this.video.buffered;
const end = b.length > 0 ? b.end(b.length - 1) : 0;
return {
...this.stat,
trail: [...this.trail],
bufferedSeconds: b.length > 0 ? end - b.start(0) : 0,
latencySeconds: Math.max(0, end - this.video.currentTime),
};
}
private async onFrame(f: ReceivedFrame): Promise<void> {
this.stat.framesIn++;
this.trail.push(`${f.epoch}/${f.seq}${f.keyframe ? '*' : ''}${f.sticky ? 's' : ''}:${f.content.type}`);
if (this.trail.length > 16) this.trail.shift();
// Every frame takes a seq, whatever it carries, so a gap is a frame lost
// (dropped by a relay for a slow viewer) — and that breaks the GOP.
// Sticky frames are replayed out of their chain position (a late joiner
// gets seq 0 then seq 119), so they do not count.
if (!f.sticky) {
if (f.epoch === this.lastEpoch && f.seq !== this.lastSeq + 1) {
this.stat.gaps++;
this.needKeyframe = true;
}
this.lastEpoch = f.epoch;
this.lastSeq = f.seq;
}
const c = f.content;
if (c.type === 'init') {
await this.sourceOpen;
if (this.lastInit !== null && equalBytes(this.lastInit, c.bytes)) return;
if (this.sb === null) {
if (!MediaSource.isTypeSupported(c.mime)) {
this.opts.onError?.(new Error(`this browser cannot play ${c.mime}`));
return;
}
this.sb = this.ms.addSourceBuffer(c.mime);
this.sb.mode = 'segments';
this.sb.addEventListener('updateend', () => this.pump());
}
this.lastInit = c.bytes.slice();
this.enqueue(c.bytes);
this.needKeyframe = true;
return;
}
if (c.type !== 'chunk') {
this.opts.onOther?.(f);
return;
}
if (this.sb === null || (this.needKeyframe && !f.keyframe)) {
this.stat.droppedBeforeKeyframe++;
return;
}
this.needKeyframe = false;
this.enqueue(c.bytes);
}
private enqueue(b: Uint8Array): void {
this.queue.push(b);
this.pump();
}
private pump(): void {
const sb = this.sb;
if (sb === null || sb.updating || this.queue.length === 0) return;
const next = this.queue.shift()!;
try {
sb.appendBuffer(next as Uint8Array<ArrayBuffer>);
this.stat.appended++;
} catch (e) {
if ((e as DOMException).name === 'QuotaExceededError') {
this.queue.unshift(next);
this.evict(5);
} else {
this.opts.onError?.(e as Error);
}
}
this.seekIntoBuffer();
}
private seekIntoBuffer(): void {
const b = this.video.buffered;
if (b.length === 0) return;
const start = b.start(0);
const end = b.end(b.length - 1);
const t = this.video.currentTime;
if (t < start || t > end) this.video.currentTime = start;
if (this.video.paused) void this.video.play().catch(() => {});
}
private evict(extra = 0): void {
const sb = this.sb;
const b = this.video.buffered;
if (sb === null || sb.updating || b.length === 0) return;
const keep = this.opts.keepSeconds ?? 30;
const cut = this.video.currentTime - keep + extra;
if (cut > b.start(0) + 1) sb.remove(b.start(0), cut);
}
private housekeeping(): void {
const b = this.video.buffered;
if (b.length === 0) return;
const end = b.end(b.length - 1);
const max = this.opts.maxLatencySeconds ?? 4;
if (end - this.video.currentTime > max) this.video.currentTime = Math.max(b.start(b.length - 1), end - 1);
this.evict();
}
close(): void {
this.client.close();
if (this.ms.readyState === 'open') this.ms.endOfStream();
}
}

View File

@@ -0,0 +1,20 @@
/** Single `bytes=` range against `size` — shared by the routes and the Service Worker. */
export function parseRange(
header: string | null | undefined,
size: number,
): { start: number; end: number } | 'invalid' | null {
if (header === null || header === undefined) return null;
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
if (m === null) return 'invalid';
const [, a, b] = m;
if (a === '' && b === '') return 'invalid';
if (a === '') {
const n = Number(b);
if (n === 0 || size === 0) return 'invalid';
return { start: Math.max(0, size - n), end: size };
}
const start = Number(a);
const end = b === '' ? size : Math.min(size, Number(b) + 1);
if (start >= size || end <= start) return 'invalid';
return { start, end };
}

View File

@@ -0,0 +1,157 @@
/**
* Service Worker: makes a sealed file look like a normal one to the browser.
*
* The page points `<video src>` (or `<audio>`, `<img>`, a download link) at
* `<scope>media/<mediaId>`. This worker answers those requests itself —
* Range requests included, so seeking works — by fetching only the sealed
* segments under the requested range from wherever the grant says the file
* lives, verifying and decrypting them, and streaming the plaintext back.
*
* Keys live in this worker's memory only. A worker the browser stopped
* forgets them; it then asks the page (which still holds the grant) again.
*/
import { parseGrant, mediaKeysOf } from '../grant.js';
import type { MediaGrant } from '../grant.js';
import { MediaReader } from '../sealed.js';
import { HttpRangeSource } from '../source.js';
import { READ_TOKEN_HEADER } from '../owner.js';
import { toB64u } from '../bytes.js';
import { parseRange } from './range.js';
// The WebWorker lib cannot be combined with DOM in one tsconfig; this is the
// small slice of the worker scope we use.
interface FetchEventLike extends Event {
request: Request;
respondWith(r: Promise<Response> | Response): void;
}
interface ExtendableEventLike extends Event {
waitUntil(p: Promise<unknown>): void;
}
interface ExtendableMessageEventLike extends Event {
data: unknown;
ports: readonly MessagePort[];
}
interface ClientLike {
postMessage(msg: unknown, transfer?: Transferable[]): void;
}
interface WorkerScope {
registration: { scope: string };
clients: { claim(): Promise<void>; matchAll(o?: { includeUncontrolled?: boolean }): Promise<ClientLike[]> };
skipWaiting(): Promise<void>;
addEventListener(type: 'install' | 'activate', cb: (e: ExtendableEventLike) => void): void;
addEventListener(type: 'fetch', cb: (e: FetchEventLike) => void): void;
addEventListener(type: 'message', cb: (e: ExtendableMessageEventLike) => void): void;
}
declare const self: WorkerScope;
const grants = new Map<string, MediaGrant>();
const readers = new Map<string, Promise<MediaReader>>();
function hexId(g: MediaGrant): string {
let s = '';
for (const b of g.mediaId) s += b.toString(16).padStart(2, '0');
return s;
}
self.addEventListener('install', () => {
void self.skipWaiting();
});
self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()));
self.addEventListener('message', (e) => {
const msg = e.data as { type?: string; grant?: string } | null;
if (msg?.type !== 'shade-media-grant' || typeof msg.grant !== 'string') return;
try {
const g = parseGrant(msg.grant);
if (g.kind !== 'shade.media-grant/v1') throw new Error('not a media grant');
grants.set(hexId(g), g);
e.ports[0]?.postMessage({ ok: true, id: hexId(g) });
} catch (err) {
e.ports[0]?.postMessage({ ok: false, error: String((err as Error).message) });
}
});
/** Ask every open page for a grant we lost (the worker was restarted). */
async function askPages(id: string): Promise<MediaGrant | null> {
const pages = await self.clients.matchAll({ includeUncontrolled: true });
const answers = pages.map(
(c) =>
new Promise<string | null>((resolve) => {
const ch = new MessageChannel();
const t = setTimeout(() => resolve(null), 3000);
ch.port1.onmessage = (m) => {
clearTimeout(t);
resolve(typeof m.data === 'string' ? m.data : null);
};
c.postMessage({ type: 'shade-media-need', id }, [ch.port2]);
}),
);
for (const a of await Promise.all(answers)) {
if (a === null) continue;
try {
const g = parseGrant(a);
if (g.kind === 'shade.media-grant/v1' && hexId(g) === id) {
grants.set(id, g);
return g;
}
} catch {
// A page answering garbage is ignored; another may answer properly.
}
}
return null;
}
function readerFor(id: string, g: MediaGrant): Promise<MediaReader> {
let r = readers.get(id);
if (r === undefined) {
if (g.url === undefined) return Promise.reject(new Error('grant has no URL'));
const source = new HttpRangeSource(g.url, {
...(g.readToken !== undefined ? { headers: { [READ_TOKEN_HEADER]: toB64u(g.readToken) } } : {}),
});
r = MediaReader.open(source, mediaKeysOf(g), { cacheSegments: 16, maxSegmentsPerFetch: 4 });
// A failed open must not be cached: the next request should retry.
r.catch(() => readers.delete(id));
readers.set(id, r);
}
return r;
}
async function serve(req: Request, id: string): Promise<Response> {
const g = grants.get(id) ?? (await askPages(id));
if (g === null) return new Response('no grant for this media in this browser', { status: 403 });
let reader: MediaReader;
try {
reader = await readerFor(id, g);
} catch (e) {
return new Response(`cannot open sealed media: ${(e as Error).message}`, { status: 502 });
}
const size = reader.size;
const headers: Record<string, string> = {
'content-type': reader.meta.mime ?? g.meta?.mime ?? 'application/octet-stream',
'accept-ranges': 'bytes',
'cache-control': 'no-store',
};
if (reader.meta.name !== undefined) {
headers['content-disposition'] = `inline; filename*=UTF-8''${encodeURIComponent(reader.meta.name)}`;
}
const range = parseRange(req.headers.get('range'), size);
if (range === 'invalid') {
return new Response(null, { status: 416, headers: { ...headers, 'content-range': `bytes */${size}` } });
}
const { start, end } = range ?? { start: 0, end: size };
headers['content-length'] = String(end - start);
if (range !== null) headers['content-range'] = `bytes ${start}-${end - 1}/${size}`;
const body = req.method === 'HEAD' ? null : reader.stream(start, end);
return new Response(body, { status: range !== null ? 206 : 200, headers });
}
self.addEventListener('fetch', (e) => {
const url = new URL(e.request.url);
const prefix = new URL('media/', self.registration.scope).pathname;
if (!url.pathname.startsWith(prefix)) return;
const id = url.pathname.slice(prefix.length);
if (!/^[0-9a-f]{32}$/.test(id)) return;
e.respondWith(serve(e.request, id));
});

View File

@@ -0,0 +1,180 @@
/**
* The watch page: open a capability link, play what it grants.
*
* /watch/#shade=<grant>
*
* A sealed file plays through the Service Worker in a native element —
* `<video>`, `<audio>`, `<img>` or a text view — with seeking. A live
* channel plays through MSE (video/audio) or as a scrolling log (text),
* with images replacing each other in place.
*
* The grant never leaves the browser: it is in the fragment, which is not
* sent to the server, and the page drops it from the address bar once read.
*/
import { fromCapabilityUrl } from '../grant.js';
import type { LiveGrant, MediaGrant } from '../grant.js';
import { LiveWatchClient } from '../live/client.js';
import type { ReceivedFrame } from '../live/channel.js';
import { installMediaWorker } from './index.js';
import { LivePlayer } from './player.js';
interface Stats {
kind: 'media' | 'live' | 'none';
state: string;
mime?: string;
frames: number;
lines: number;
images: number;
error?: string;
player?: () => unknown;
}
const stats: Stats = { kind: 'none', state: 'starting', frames: 0, lines: 0, images: 0 };
(globalThis as unknown as { __shade: Stats }).__shade = stats;
const $ = <T extends HTMLElement>(sel: string) => document.querySelector(sel) as T;
function setStatus(text: string, tone: 'ok' | 'warn' | 'bad' = 'ok'): void {
stats.state = text;
const el = $('#status');
el.textContent = text;
el.dataset.tone = tone;
}
function fail(message: string): void {
stats.error = message;
setStatus(message, 'bad');
}
function human(n: number): string {
const u = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
while (n >= 1024 && i < u.length - 1) {
n /= 1024;
i++;
}
return `${n.toFixed(i === 0 ? 0 : 1)} ${u[i]}`;
}
async function playMedia(g: MediaGrant): Promise<void> {
stats.kind = 'media';
setStatus('starting the decryption worker…');
const keyring = await installMediaWorker(new URL('sw.js', location.href).pathname, new URL('./', location.href).pathname);
const src = await keyring.add(g);
const head = await fetch(src, { method: 'HEAD' });
if (!head.ok) return fail(`could not open: ${head.status} ${await head.text()}`);
const mime = head.headers.get('content-type') ?? 'application/octet-stream';
const size = Number(head.headers.get('content-length'));
stats.mime = mime;
const name = decodeURIComponent(/filename\*=UTF-8''([^;]+)/.exec(head.headers.get('content-disposition') ?? '')?.[1] ?? '');
$('#title').textContent = g.meta?.name ?? (name || 'Sealed media');
$('#sub').textContent = `${mime} · ${human(size)} · end-to-end encrypted`;
const stage = $('#stage');
if (mime.startsWith('video/') || mime.startsWith('audio/')) {
const el = document.createElement(mime.startsWith('video/') ? 'video' : 'audio');
el.controls = true;
el.autoplay = true;
el.muted = true; // autoplay policy; the viewer unmutes
el.src = src;
el.id = 'player';
el.addEventListener('playing', () => setStatus('playing'));
el.addEventListener('waiting', () => setStatus('buffering…', 'warn'));
el.addEventListener('error', () => fail(`player error: ${el.error?.message ?? el.error?.code}`));
stage.append(el);
} else if (mime.startsWith('image/')) {
const img = document.createElement('img');
img.src = src;
img.id = 'player';
img.addEventListener('load', () => setStatus(`showing ${img.naturalWidth}×${img.naturalHeight}`));
img.addEventListener('error', () => fail('image failed to decode'));
stage.append(img);
} else if (mime.startsWith('text/') || mime === 'application/json') {
const pre = document.createElement('pre');
pre.id = 'log';
pre.textContent = await (await fetch(src)).text();
stage.append(pre);
setStatus('showing text');
} else {
setStatus('ready to download');
}
const a = document.createElement('a');
a.href = src;
a.download = name || 'download';
a.textContent = 'Download decrypted';
$('#actions').append(a);
}
function playLive(g: LiveGrant): void {
stats.kind = 'live';
$('#title').textContent = g.meta?.name ?? 'Live channel';
const mime = g.meta?.mime ?? '';
stats.mime = mime;
$('#sub').textContent = `live · ${mime || 'text'} · end-to-end encrypted`;
const stage = $('#stage');
const states = (s: string) => setStatus(s === 'live' ? 'live' : s === 'waiting' ? 'waiting for the publisher…' : s, s === 'live' ? 'ok' : 'warn');
const onErr = (e: Error) => {
stats.error = e.message;
};
let log: HTMLPreElement | null = null;
let img: HTMLImageElement | null = null;
const other = (f: ReceivedFrame) => {
stats.frames++;
const c = f.content;
if (c.type === 'text') {
if (log === null) {
log = document.createElement('pre');
log.id = 'log';
stage.append(log);
}
const atBottom = log.scrollTop + log.clientHeight >= log.scrollHeight - 4;
log.append(document.createTextNode(c.text));
stats.lines += c.text.split('\n').length - 1;
// Bound the DOM: a log stream runs for days.
while (log.childNodes.length > 5000) log.firstChild!.remove();
if (atBottom) log.scrollTop = log.scrollHeight;
} else if (c.type === 'image') {
if (img === null) {
img = document.createElement('img');
img.id = 'player';
stage.prepend(img);
}
const old = img.src;
img.src = URL.createObjectURL(new Blob([c.bytes as Uint8Array<ArrayBuffer>], { type: c.mime }));
if (old.startsWith('blob:')) URL.revokeObjectURL(old);
stats.images++;
} else if (c.type === 'end') {
setStatus('the broadcast has ended', 'warn');
}
};
if (mime.startsWith('video/') || mime.startsWith('audio/')) {
const el = document.createElement(mime.startsWith('video/') ? 'video' : 'audio');
el.controls = true;
el.autoplay = true;
el.muted = true;
el.id = 'player';
stage.append(el);
const player = new LivePlayer(el, g, { onState: states, onError: onErr, onOther: other });
stats.player = () => ({ ...player.stats(), currentTime: el.currentTime, paused: el.paused, readyState: el.readyState });
} else {
new LiveWatchClient(g, { onFrame: other, onState: states, onError: onErr });
}
}
async function main(): Promise<void> {
let grant;
try {
grant = fromCapabilityUrl(location.href);
} catch (e) {
$('#title').textContent = 'Shade';
return fail(`no grant in this link — ${(e as Error).message}`);
}
// Keep the key out of the history and out of anything that reads the URL later.
history.replaceState(null, '', location.pathname + location.search);
if (grant.kind === 'shade.media-grant/v1') await playMedia(grant);
else playLive(grant);
}
main().catch((e) => fail(String((e as Error)?.message ?? e)));

View File

@@ -0,0 +1,396 @@
/**
* `shade media …` and `shade live …` — the command line for streaming.
*
* shade media serve relay + media store + watch page
* shade media put film.mkv --server URL seal, upload, print a watch link
* shade media get <link> -o out.mkv download and decrypt
* shade media ls|rm --server URL
* tail -f app.log | shade live text --server URL --name "app logs"
* ffmpeg … -f webm - | shade live webm --server URL --name "Camera"
* shade live watch <link> a live text channel in the terminal
*
* The owner key (who may upload and delete) is created on first use under
* `$XDG_CONFIG_HOME/shade/` and reused; nothing to configure.
*/
import { chmod, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { createWriteStream } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
import { basename, extname, join } from 'node:path';
import { fromB64u, randomBytes, toB64u, toHex } from './bytes.js';
import { MediaClient, openGrant } from './client.js';
import { encodeGrant, fromCapabilityUrl, toCapabilityUrl } from './grant.js';
import type { Grant, MediaGrant } from './grant.js';
import { LivePublisher } from './live/channel.js';
import { LivePublishClient, LiveWatchClient } from './live/client.js';
import { sealFile } from './node.js';
import { OwnerKey } from './owner.js';
import type { MediaMeta } from './sealed.js';
import { WebmSplitter } from './webm.js';
type Flags = Record<string, string | true>;
function parseArgs(argv: string[]): { pos: string[]; flags: Flags } {
const pos: string[] = [];
const flags: Flags = {};
for (let i = 0; i < argv.length; i++) {
const a = argv[i]!;
if (a.startsWith('--')) {
const [k, v] = a.slice(2).split('=', 2) as [string, string | undefined];
if (v !== undefined) flags[k] = v;
else if (argv[i + 1] !== undefined && !argv[i + 1]!.startsWith('-')) flags[k] = argv[++i]!;
else flags[k] = true;
} else if (a === '-o') {
flags.out = argv[++i] ?? '';
} else {
pos.push(a);
}
}
return { pos, flags };
}
function str(flags: Flags, k: string): string | undefined {
const v = flags[k];
return typeof v === 'string' ? v : undefined;
}
function need(flags: Flags, k: string, envName?: string): string {
const v = str(flags, k) ?? (envName !== undefined ? process.env[envName] : undefined);
if (v === undefined || v === '') throw new UsageError(`--${k} is required${envName ? ` (or ${envName})` : ''}`);
return v.replace(/\/$/, '');
}
class UsageError extends Error {}
const MIME_BY_EXT: Record<string, string> = {
'.mp4': 'video/mp4', '.m4v': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm',
'.mkv': 'video/x-matroska', '.ogv': 'video/ogg', '.mp3': 'audio/mpeg', '.m4a': 'audio/mp4',
'.aac': 'audio/aac', '.ogg': 'audio/ogg', '.opus': 'audio/ogg', '.wav': 'audio/wav', '.flac': 'audio/flac',
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp',
'.avif': 'image/avif', '.txt': 'text/plain; charset=utf-8', '.log': 'text/plain; charset=utf-8',
'.md': 'text/markdown; charset=utf-8', '.json': 'application/json', '.pdf': 'application/pdf',
'.srt': 'text/plain; charset=utf-8', '.vtt': 'text/vtt',
};
export function guessMime(path: string): string | undefined {
return MIME_BY_EXT[extname(path).toLowerCase()];
}
function configDir(): string {
return join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'shade');
}
/** The owner key, created on first use and kept 0600. */
export async function loadOwnerKey(path = join(configDir(), 'media-owner.key')): Promise<OwnerKey> {
try {
return new OwnerKey(fromB64u((await readFile(path, 'utf8')).trim(), 32));
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;
}
const key = OwnerKey.generate();
await mkdir(configDir(), { recursive: true, mode: 0o700 });
await writeFile(path, `${toB64u(key.exportSecret())}\n`, { mode: 0o600, flag: 'wx' });
return key;
}
function watchLink(server: string, g: Grant): string {
return toCapabilityUrl(`${server}/watch/`, g);
}
const out = (s: string) => process.stdout.write(`${s}\n`);
const err = (s: string) => process.stderr.write(`${s}\n`);
// ─── media ───────────────────────────────────────────────────
async function mediaServe(flags: Flags): Promise<number> {
const { Hono } = await import('hono');
const { cors } = await import('hono/cors');
const { websocket } = await import('hono/bun');
const { createMediaRoutes, FileMediaStore, createLiveRelay, FileLivePinStore, createWatchRoutes } = await import('./server.js');
const dir = str(flags, 'dir') ?? process.env.SHADE_MEDIA_DIR ?? './shade-media-data';
const port = Number(str(flags, 'port') ?? process.env.PORT ?? 3910);
const app = new Hono();
app.use('/v1/media/*', cors({ origin: '*', allowHeaders: ['range', 'x-shade-read'], exposeHeaders: ['content-range', 'content-length', 'accept-ranges'] }));
app.route('/', createMediaRoutes(new FileMediaStore(join(dir, 'media'))));
const relay = createLiveRelay({ pins: new FileLivePinStore(join(dir, 'live-pins.json')) });
app.route('/', relay.app);
app.route('/', createWatchRoutes({ dev: flags.dev === true }));
app.get('/health', (c) => c.json({ ok: true, live: relay.stats() }));
const server = Bun.serve({
port,
hostname: str(flags, 'host') ?? '0.0.0.0',
fetch: (req, srv) => app.fetch(req, { server: srv }),
websocket,
idleTimeout: 0,
});
err(`shade media: serving on http://localhost:${server.port} (data in ${dir})`);
await new Promise(() => {});
return 0;
}
async function mediaPut(pos: string[], flags: Flags): Promise<number> {
const file = pos[0];
if (file === undefined) throw new UsageError('usage: shade media put <file> --server URL');
const server = need(flags, 'server', 'SHADE_MEDIA_SERVER');
const meta: MediaMeta = { name: str(flags, 'name') ?? basename(file) };
const mime = str(flags, 'mime') ?? guessMime(file);
if (mime !== undefined) meta.mime = mime;
const size = (await stat(file)).size;
const tmp = join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`);
const started = Date.now();
try {
err(`sealing ${basename(file)} (${(size / 1048576).toFixed(1)} MiB)…`);
const result = await sealFile(file, tmp, { meta });
err(`uploading ${(result.sealedSize / 1048576).toFixed(1)} MiB…`);
const client = new MediaClient(server, await loadOwnerKey());
const grant = await client.putSealed(result, Bun.file(tmp), {
meta,
...(flags.public === true ? { readToken: null } : {}),
});
err(`done in ${((Date.now() - started) / 1000).toFixed(1)} s`);
out(flags.json === true ? encodeGrant(grant) : watchLink(server, grant));
} finally {
await rm(tmp, { force: true });
}
return 0;
}
async function mediaGet(pos: string[], flags: Flags): Promise<number> {
const link = pos[0];
if (link === undefined) throw new UsageError('usage: shade media get <link> [-o file]');
const g = fromCapabilityUrl(link);
if (g.kind !== 'shade.media-grant/v1') throw new UsageError('that link is a live channel — use `shade live watch`');
const reader = await openGrant(g);
const target = str(flags, 'out') ?? reader.meta.name ?? 'shade-media.bin';
const ws = target === '-' ? process.stdout : createWriteStream(target);
for await (const chunk of reader.stream()) {
if (!ws.write(chunk)) await new Promise<void>((r) => ws.once('drain', () => r()));
}
if (ws !== process.stdout) await new Promise<void>((r) => (ws as ReturnType<typeof createWriteStream>).end(() => r()));
if (target !== '-') err(`wrote ${target} (${reader.size} bytes, verified)`);
return 0;
}
async function mediaLs(flags: Flags): Promise<number> {
const server = need(flags, 'server', 'SHADE_MEDIA_SERVER');
const res = await new MediaClient(server, await loadOwnerKey()).list();
for (const i of res.items) out(`${i.id} ${(i.size / 1048576).toFixed(1).padStart(9)} MiB ${new Date(i.createdAt).toISOString()}`);
err(`${res.items.length} item(s), ${(res.usage / 1048576).toFixed(1)} MiB`);
return 0;
}
async function mediaRm(pos: string[], flags: Flags): Promise<number> {
const server = need(flags, 'server', 'SHADE_MEDIA_SERVER');
const target = pos[0];
if (target === undefined) throw new UsageError('usage: shade media rm <link|id> --server URL');
let id: Uint8Array;
if (/^[0-9a-f]{32}$/.test(target)) {
id = Uint8Array.from(target.match(/../g)!.map((h) => parseInt(h, 16)));
} else {
const g = fromCapabilityUrl(target) as MediaGrant;
id = g.mediaId;
}
const ok = await new MediaClient(server, await loadOwnerKey()).delete(id);
err(ok ? 'deleted' : 'not found (or not yours)');
return ok ? 0 : 1;
}
// ─── live ────────────────────────────────────────────────────
interface ChannelFile {
channelId: string;
signingSecret: string;
channelSecret: string;
readToken: string;
epoch: number;
}
/**
* A channel that outlives the process: same id, same link, next epoch. Kept
* 0600 — it holds the signing key and the link secret.
*/
async function loadChannel(path: string | undefined, meta: MediaMeta): Promise<{ pub: LivePublisher; readToken: Uint8Array }> {
const rotateEvery = 20_000;
if (path === undefined) {
return { pub: new LivePublisher({ meta, channelSecret: randomBytes(32), rotateEvery }), readToken: randomBytes(32) };
}
let cf: ChannelFile | null = null;
try {
cf = JSON.parse(await readFile(path, 'utf8')) as ChannelFile;
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;
}
const next: ChannelFile = cf
? { ...cf, epoch: cf.epoch + 1 }
: {
channelId: toB64u(randomBytes(16)),
signingSecret: toB64u(randomBytes(32)),
channelSecret: toB64u(randomBytes(32)),
readToken: toB64u(randomBytes(32)),
epoch: 0,
};
await writeFile(path, JSON.stringify(next, null, 2), { mode: 0o600 });
await chmod(path, 0o600);
return {
pub: new LivePublisher({
meta,
channelId: fromB64u(next.channelId, 16),
signingSecret: fromB64u(next.signingSecret, 32),
channelSecret: fromB64u(next.channelSecret, 32),
epoch: next.epoch,
rotateEvery,
}),
readToken: fromB64u(next.readToken, 32),
};
}
async function startPublishing(flags: Flags, meta: MediaMeta): Promise<{ client: LivePublishClient; server: string }> {
const server = need(flags, 'server', 'SHADE_MEDIA_SERVER');
const { pub, readToken } = await loadChannel(str(flags, 'channel'), meta);
const client = new LivePublishClient({
relay: server,
publisher: pub,
readToken,
onViewers: (n) => err(`viewers: ${n}`),
onError: (m) => err(`relay: ${m}`),
onState: (s) => {
if (s === 'reconnecting') err('relay connection lost — reconnecting…');
},
});
await client.whenReady();
// Link mode: the link holds the channel secret and survives restarts.
out(watchLink(server, client.grant('oldest', true)));
return { client, server };
}
async function liveText(flags: Flags): Promise<number> {
const meta: MediaMeta = { name: str(flags, 'name') ?? 'Live log', mime: 'text/plain' };
const { client } = await startPublishing(flags, meta);
await client.send({ type: 'meta', meta }, { sticky: true });
const batchMs = Number(str(flags, 'batch-ms') ?? 100);
const keyEvery = Number(str(flags, 'keyframe-every') ?? 20);
let pending = '';
let batches = 0;
// Only whole lines go out: a batch boundary must never split a log line.
// A partial line waits for its newline — unless it grows past the cap, or
// the input ends.
const flush = async (final = false) => {
const cut = final || pending.length > 256 * 1024 ? pending.length : pending.lastIndexOf('\n') + 1;
if (cut === 0) return;
const text = pending.slice(0, cut);
pending = pending.slice(cut);
// A keyframe every N batches bounds how far back a late viewer sees.
await client.send({ type: 'text', text }, { keyframe: batches++ % keyEvery === 0 });
};
const timer = setInterval(() => void flush(), batchMs);
const dec = new TextDecoder();
for await (const chunk of Bun.stdin.stream()) {
pending += dec.decode(chunk, { stream: true });
if (pending.length > 256 * 1024) await flush();
}
clearInterval(timer);
pending += dec.decode();
await flush(true);
await client.end();
return 0;
}
async function liveWebm(flags: Flags): Promise<number> {
const meta: MediaMeta = { name: str(flags, 'name') ?? 'Live', mime: str(flags, 'mime') ?? 'video/webm' };
const { client } = await startPublishing(flags, meta);
const splitter = new WebmSplitter();
let clusters = 0;
const send = async (pieces: ReturnType<WebmSplitter['push']>) => {
for (const p of pieces) {
if (p.type === 'init') {
await client.send({ type: 'init', mime: p.mime, bytes: p.bytes }, { sticky: true });
err(`stream: ${p.mime}`);
} else {
await client.send({ type: 'chunk', bytes: p.bytes }, { keyframe: p.keyframe });
clusters++;
}
}
};
for await (const chunk of Bun.stdin.stream()) await send(splitter.push(chunk));
await send(splitter.finish());
err(`${clusters} clusters sent`);
await client.end();
return 0;
}
async function liveWatch(pos: string[]): Promise<number> {
const link = pos[0];
if (link === undefined) throw new UsageError('usage: shade live watch <link>');
const g = fromCapabilityUrl(link);
if (g.kind !== 'shade.live-grant/v1') throw new UsageError('that link is a sealed file — use `shade media get`');
await new Promise<void>((resolve) => {
const w = new LiveWatchClient(g, {
onFrame: (f) => {
const c = f.content;
if (c.type === 'text') process.stdout.write(c.text);
else if (c.type === 'end') {
w.close();
resolve();
}
},
onState: (s) => {
if (s === 'waiting') err('(waiting for the publisher)');
},
onError: (e) => err(`! ${e.message}`),
});
});
return 0;
}
export const MEDIA_HELP = `
media serve [--port 3910] [--dir ./shade-media-data]
Run a media relay: sealed store, live relay, watch page
media put <file> --server URL [--name N] [--mime M] [--public] [--json]
Seal a film/video/image/song, upload it, print a watch link
media get <link> [-o file|-]
Download and decrypt a sealed file
media ls --server URL Your uploads on that server
media rm <link|id> --server URL
live text --server URL [--name N] [--channel file.json]
Publish stdin as a live log (tail -f app.log | shade live text …)
live webm --server URL [--name N] [--channel file.json]
Publish a WebM stream from stdin (ffmpeg … -f webm - | …)
live watch <link> Follow a live text channel in the terminal
`;
/** Entry for `shade media …` / `shade live …`. Returns the exit code. */
export async function runMediaCli(group: 'media' | 'live', argv: string[]): Promise<number> {
const [sub, ...rest] = argv;
const { pos, flags } = parseArgs(rest);
try {
if (group === 'media') {
switch (sub) {
case 'serve':
return await mediaServe(flags);
case 'put':
return await mediaPut(pos, flags);
case 'get':
return await mediaGet(pos, flags);
case 'ls':
return await mediaLs(flags);
case 'rm':
return await mediaRm(pos, flags);
}
} else {
switch (sub) {
case 'text':
return await liveText(flags);
case 'webm':
return await liveWebm(flags);
case 'watch':
return await liveWatch(pos);
}
}
err(`Usage:${MEDIA_HELP}`);
return 2;
} catch (e) {
err(e instanceof UsageError ? e.message : `error: ${(e as Error).message}`);
return 1;
}
}

View File

@@ -17,6 +17,11 @@ export function mediaUrl(server: string, mediaId: Uint8Array): string {
return `${server.replace(/\/$/, '')}/v1/media/${toHex(mediaId)}`;
}
export interface MediaList {
items: { id: string; size: number; createdAt: number }[];
usage: number;
}
export interface PutOptions {
/** Token viewers must present. Default: a fresh random one per file. `null` = public ciphertext. */
readToken?: Uint8Array | null;
@@ -56,7 +61,7 @@ export class MediaClient {
...(readTokenHash !== '' ? { [READ_HASH_HEADER]: readTokenHash } : {}),
...this.owner.headers({ op: 'put', id, size, readTokenHash }),
},
body: body as BodyInit,
body: body as Blob,
});
if (res.status !== 201) {
throw new Error(`upload failed: HTTP ${res.status} ${await res.text().catch(() => '')}`);
@@ -85,12 +90,12 @@ export class MediaClient {
return true;
}
async list(): Promise<{ items: { id: string; size: number; createdAt: number }[]; usage: number }> {
async list(): Promise<MediaList> {
const res = await this.fetchFn(`${this.server.replace(/\/$/, '')}/v1/media`, {
headers: this.owner.headers({ op: 'list' }),
});
if (!res.ok) throw new Error(`list failed: HTTP ${res.status}`);
return res.json();
return (await res.json()) as MediaList;
}
}

View File

@@ -53,6 +53,11 @@ export interface LiveGrant {
readToken?: Uint8Array;
/** Channel title etc., as the publisher described it. */
meta?: MediaMeta;
/**
* Link mode only: the secret every epoch seed derives from. A grant with
* it reads this epoch and every later one, with no further grants.
*/
channelSecret?: Uint8Array;
}
export type Grant = MediaGrant | LiveGrant;
@@ -97,6 +102,7 @@ export function encodeGrant(g: Grant): string {
seq: g.seq,
chainKey: toB64u(g.chainKey),
stickyKey: toB64u(g.stickyKey),
...(g.channelSecret !== undefined ? { channelSecret: toB64u(g.channelSecret) } : {}),
...(g.url !== undefined ? { url: g.url } : {}),
...(g.readToken !== undefined ? { token: toB64u(g.readToken) } : {}),
...(g.meta !== undefined ? { meta: g.meta } : {}),
@@ -175,6 +181,7 @@ export function parseGrant(json: string): Grant {
seq: int(o, 'seq', Number.MAX_SAFE_INTEGER),
chainKey: fromB64u(str(o, 'chainKey'), 32),
stickyKey: fromB64u(str(o, 'stickyKey'), 32),
...(o.channelSecret !== undefined ? { channelSecret: fromB64u(str(o, 'channelSecret'), 32) } : {}),
...optUrl(o),
...optToken(o),
...optMeta(o),

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;
}
}

View File

@@ -81,13 +81,16 @@ export class LivePublishClient {
}
/** Grant for a viewer, with this relay's URL and token filled in. */
grant(from: 'oldest' | 'latest' | 'now' = 'oldest'): LiveGrant {
return this.opts.publisher.grant({ from, url: this.url, readToken: this.opts.readToken });
grant(from: 'oldest' | 'latest' | 'now' = 'oldest', link = false): LiveGrant {
return this.opts.publisher.grant({ from, url: this.url, readToken: this.opts.readToken, link });
}
/** Seal and send one frame. Frames are numbered in call order. */
send(content: LiveContent, opts: FrameOptions = {}): Promise<void> {
const p = this.sending.then(async () => {
if (this.opts.publisher.rotationDue) {
for (const f of await this.opts.publisher.rotate()) this.transmit(f, true);
}
const frame = await this.opts.publisher.frame(content, opts);
this.transmit(frame, opts.sticky === true);
});

View File

@@ -4,3 +4,5 @@ export { FileMediaStore, MemoryMediaStore, MediaExistsError } from './server/fil
export type { MediaStore, MediaRecord, MediaUpload } from './server/file-store.js';
export { createLiveRelay, FileLivePinStore, MemoryLivePinStore } from './server/live-relay.js';
export type { LiveRelay, LiveRelayOptions, LivePin, LivePinStore } from './server/live-relay.js';
export { createWatchRoutes } from './server/watch-routes.js';
export type { WatchRoutesOptions } from './server/watch-routes.js';

View File

@@ -46,8 +46,8 @@ export interface MediaStore {
usage(owner: string): Promise<number>;
totalBytes(): Promise<number>;
begin(id: string): Promise<MediaUpload>;
/** Body for `[start, end)` — a Blob so the server can stream it from disk. */
body(id: string, start: number, end: number): Promise<Blob>;
/** Body for `[start, end)`, streamed — a film is never loaded into memory. */
body(id: string, start: number, end: number): Promise<ReadableStream<Uint8Array>>;
delete(id: string): Promise<boolean>;
list(owner: string): Promise<MediaRecord[]>;
}
@@ -179,9 +179,35 @@ export class FileMediaStore implements MediaStore {
};
}
async body(id: string, start: number, end: number): Promise<Blob> {
async body(id: string, start: number, end: number): Promise<ReadableStream<Uint8Array>> {
await this.ready;
return Bun.file(this.objectPath(id)).slice(start, end);
// Read the range ourselves rather than handing `Bun.file().slice()` to a
// Response: Bun's sendfile path ignored the slice for large files
// (1.3.5) and sent the whole film to a Range request.
const fh = await open(this.objectPath(id), 'r');
let pos = start;
const CHUNK = 1024 * 1024;
return new ReadableStream<Uint8Array>({
async pull(controller) {
if (pos >= end) {
await fh.close();
controller.close();
return;
}
const buf = new Uint8Array(Math.min(CHUNK, end - pos));
const { bytesRead } = await fh.read(buf, 0, buf.length, pos);
if (bytesRead === 0) {
await fh.close();
controller.error(new Error('media file shorter than its record'));
return;
}
pos += bytesRead;
controller.enqueue(buf.subarray(0, bytesRead));
},
async cancel() {
await fh.close();
},
});
}
async delete(id: string): Promise<boolean> {
@@ -247,10 +273,16 @@ export class MemoryMediaStore implements MediaStore {
async abort() {},
};
}
async body(id: string, start: number, end: number): Promise<Blob> {
async body(id: string, start: number, end: number): Promise<ReadableStream<Uint8Array>> {
const o = this.objects.get(id);
if (o === undefined) throw new Error('not found');
return new Blob([o.bytes.slice(start, end)]);
const bytes = o.bytes.slice(start, end);
return new ReadableStream({
start(c) {
c.enqueue(bytes);
c.close();
},
});
}
async delete(id: string): Promise<boolean> {
return this.objects.delete(id);

View File

@@ -17,6 +17,8 @@ import { fromB64u, sha256, toHex } from '../bytes.js';
import { decodeFooter, FOOTER_BYTES, sealedSizeFor } from '../sealed.js';
import { READ_HASH_HEADER, READ_TOKEN_HEADER, verifyOwner } from '../owner.js';
import { MediaExistsError } from './file-store.js';
import { parseRange } from '../browser/range.js';
export { parseRange };
import type { MediaStore } from './file-store.js';
export interface MediaRoutesOptions {
@@ -34,24 +36,6 @@ export interface MediaRoutesOptions {
const ID_RE = /^[0-9a-f]{32}$/;
const GiB = 1024 * 1024 * 1024;
/** Parse a single `bytes=` range against `size`. Multi-range is not served (no client needs it). */
export function parseRange(header: string | null | undefined, size: number): { start: number; end: number } | 'invalid' | null {
if (header === null || header === undefined) return null;
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
if (m === null) return 'invalid';
const [, a, b] = m;
if (a === '' && b === '') return 'invalid';
if (a === '') {
const n = Number(b);
if (n === 0) return 'invalid';
return { start: Math.max(0, size - n), end: size };
}
const start = Number(a);
const end = b === '' ? size : Math.min(size, Number(b) + 1);
if (start >= size || end <= start) return 'invalid';
return { start, end };
}
async function tokenMatches(hash: string | null, token: string | null | undefined): Promise<boolean> {
if (hash === null) return true;
if (token === null || token === undefined) return false;

View File

@@ -0,0 +1,102 @@
/**
* Serves the watch page and its decryption worker from the relay itself, so
* a capability link `https://relay/watch/#shade=…` works with nothing else
* deployed. The page and the worker are bundled from source on first
* request (Bun's bundler) and kept in memory — no build step, no assets to
* ship separately.
*
* The page is static and keyless; the grant is in the fragment, which the
* browser never sends here.
*/
import { Hono } from 'hono';
import { fileURLToPath } from 'node:url';
const HTML = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="referrer" content="no-referrer">
<title>Shade</title>
<style>
:root { color-scheme: dark; --bg: #0d0f12; --panel: #15181d; --line: #262b33; --text: #e7e9ec; --dim: #8b929c; --ok: #6fcf97; --warn: #f2c94c; --bad: #eb5757; }
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 15px/1.45 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
main { max-width: 1180px; margin: 0 auto; padding: 28px 24px 40px; display: grid; gap: 18px; }
header { display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap; }
.mark { font-weight: 700; letter-spacing: .14em; font-size: 12px; color: var(--dim); text-transform: uppercase; }
h1 { margin: 0; font-size: 22px; font-weight: 600; flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; }
#sub { color: var(--dim); font-size: 13px; width: 100%; }
#stage { background: #000; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; display: grid; gap: 0; min-height: 120px; }
#stage video, #stage img { display: block; width: 100%; max-height: 72vh; object-fit: contain; background: #000; }
#stage audio { width: 100%; padding: 18px; }
#log { margin: 0; padding: 14px 16px; height: 62vh; overflow: auto; background: var(--panel); color: #d6dbe1; font: 12.5px/1.5 ui-monospace, "JetBrains Mono", Menlo, monospace; white-space: pre-wrap; word-break: break-word; }
footer { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; }
#status { font-size: 13px; color: var(--dim); display: inline-flex; align-items: center; gap: 8px; }
#status::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: var(--ok); }
#status[data-tone="warn"]::before { background: var(--warn); }
#status[data-tone="bad"]::before { background: var(--bad); }
#status[data-tone="bad"] { color: var(--bad); }
#actions a { color: var(--text); font-size: 13px; text-decoration: none; border: 1px solid var(--line); padding: 6px 12px; border-radius: 6px; }
#actions a:hover { border-color: var(--dim); }
</style>
</head>
<body>
<main>
<header><span class="mark">Shade</span><h1 id="title">Opening…</h1><div id="sub"></div></header>
<section id="stage" aria-live="polite"></section>
<footer><span id="status" data-tone="warn">starting…</span><span id="actions"></span></footer>
</main>
<script type="module" src="./app.js"></script>
</body>
</html>`;
const bundles = new Map<string, Promise<string>>();
function bundle(entry: string, dev: boolean): Promise<string> {
let b = dev ? undefined : bundles.get(entry);
if (b === undefined) {
b = (async () => {
if (typeof Bun === 'undefined') throw new Error('the watch page bundles itself with Bun');
const path = fileURLToPath(new URL(entry, import.meta.url));
const out = await Bun.build({ entrypoints: [path], target: 'browser', minify: true, format: 'esm' });
if (!out.success) throw new Error(out.logs.map((l) => String(l)).join('\n'));
return out.outputs[0]!.text();
})();
b.catch(() => bundles.delete(entry));
bundles.set(entry, b);
}
return b;
}
export interface WatchRoutesOptions {
/** Mount point. Default `/watch`. */
path?: string;
/** Re-bundle on every request instead of once (while working on the page). */
dev?: boolean;
}
export function createWatchRoutes(opts: WatchRoutesOptions = {}): Hono {
const base = (opts.path ?? '/watch').replace(/\/$/, '');
const app = new Hono();
const security = {
'content-security-policy':
"default-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; connect-src 'self' ws: wss: http: https:; style-src 'unsafe-inline'; script-src 'self'; worker-src 'self'; base-uri 'none'; frame-ancestors 'none'",
'referrer-policy': 'no-referrer',
'x-content-type-options': 'nosniff',
};
app.get(base, (c) => c.redirect(`${base}/`));
app.get(`${base}/`, (c) => c.html(HTML, 200, security));
app.get(`${base}/app.js`, async (c) =>
c.body(await bundle('../browser/watch-app.ts', opts.dev === true), 200, { 'content-type': 'text/javascript; charset=utf-8', ...security }),
);
app.get(`${base}/sw.js`, async (c) =>
c.body(await bundle('../browser/sw.ts', opts.dev === true), 200, {
'content-type': 'text/javascript; charset=utf-8',
'cache-control': 'no-cache',
...security,
}),
);
return app;
}

View File

@@ -0,0 +1,376 @@
/**
* WebM → live frames.
*
* A live WebM stream (ffmpeg `-f webm`, the browser's `MediaRecorder`) is an
* EBML header and a Segment whose children are Info, Tracks and then an
* endless run of Clusters. For Media Source Extensions that splits cleanly:
*
* init = everything before the first Cluster → one sticky frame
* cluster = one Cluster element → one frame, a keyframe
* if the video track's first block in it is one
*
* A viewer who joins late appends the init, then starts at the next keyframe
* cluster — exactly the two flags the live format carries.
*
* Streaming parser: push bytes in any chunking, get whole pieces out. It
* handles Segments and Clusters of unknown size (what live muxers write),
* ending such a Cluster at the next element that cannot be its child.
*/
import { concat } from './bytes.js';
import { MediaFormatError } from './errors.js';
const ID_EBML = 0x1a45dfa3;
const ID_SEGMENT = 0x18538067;
const ID_CLUSTER = 0x1f43b675;
const ID_TRACKS = 0x1654ae6b;
const ID_TRACK_ENTRY = 0xae;
const ID_TRACK_NUMBER = 0xd7;
const ID_TRACK_TYPE = 0x83;
const ID_CODEC_ID = 0x86;
const ID_SIMPLE_BLOCK = 0xa3;
const ID_BLOCK_GROUP = 0xa0;
const ID_BLOCK = 0xa1;
const ID_REFERENCE_BLOCK = 0xfb;
/** Children a Cluster may hold; anything else ends an unknown-size Cluster. */
const CLUSTER_CHILDREN = new Set([0xe7, 0xa7, 0xab, ID_SIMPLE_BLOCK, ID_BLOCK_GROUP, 0x5854, 0xaf, 0xec, 0xbf]);
export type WebmPiece =
| { type: 'init'; mime: string; bytes: Uint8Array }
| { type: 'cluster'; keyframe: boolean; bytes: Uint8Array };
interface Vint {
value: number;
length: number;
unknown: boolean;
}
/** EBML element ID: the VINT with its marker bit kept. */
function readId(b: Uint8Array, at: number): Vint | null {
const first = b[at];
if (first === undefined) return null;
let len = 1;
while (len <= 4 && (first & (0x80 >> (len - 1))) === 0) len++;
if (len > 4) throw new MediaFormatError('bad EBML id');
if (at + len > b.length) return null;
let v = 0;
for (let i = 0; i < len; i++) v = v * 256 + b[at + i]!;
return { value: v, length: len, unknown: false };
}
/** EBML size: the VINT with its marker removed; all ones means unknown. */
function readSize(b: Uint8Array, at: number): Vint | null {
const first = b[at];
if (first === undefined) return null;
let len = 1;
while (len <= 8 && (first & (0x80 >> (len - 1))) === 0) len++;
if (len > 8) throw new MediaFormatError('bad EBML size');
if (at + len > b.length) return null;
let v = first & (0xff >> len);
let allOnes = v === 0xff >> len;
for (let i = 1; i < len; i++) {
const x = b[at + i]!;
if (x !== 0xff) allOnes = false;
v = v * 256 + x;
}
return { value: v, length: len, unknown: allOnes };
}
interface TrackInfo {
number: number;
type: number;
codec: string;
}
function parseTracks(body: Uint8Array): TrackInfo[] {
const tracks: TrackInfo[] = [];
let at = 0;
while (at < body.length) {
const id = readId(body, at);
const size = id && readSize(body, at + id.length);
if (!id || !size) break;
const start = at + id.length + size.length;
if (id.value === ID_TRACK_ENTRY) {
const t: TrackInfo = { number: 0, type: 0, codec: '' };
let p = start;
const end = Math.min(body.length, start + size.value);
while (p < end) {
const cid = readId(body, p);
const csz = cid && readSize(body, p + cid.length);
if (!cid || !csz) break;
const cs = p + cid.length + csz.length;
const val = body.subarray(cs, cs + csz.value);
if (cid.value === ID_TRACK_NUMBER || cid.value === ID_TRACK_TYPE) {
let n = 0;
for (const x of val) n = n * 256 + x;
if (cid.value === ID_TRACK_NUMBER) t.number = n;
else t.type = n;
} else if (cid.value === ID_CODEC_ID) {
t.codec = new TextDecoder().decode(val);
}
p = cs + csz.value;
}
tracks.push(t);
}
at = start + size.value;
}
return tracks;
}
const CODECS: Record<string, string> = {
V_VP8: 'vp8',
V_VP9: 'vp9',
V_AV1: 'av01.0.08M.08',
A_OPUS: 'opus',
A_VORBIS: 'vorbis',
};
/** The MSE type string for a set of tracks, e.g. `video/webm; codecs="vp8,opus"`. */
export function webmMime(tracks: readonly TrackInfo[]): string {
const codecs = tracks.map((t) => CODECS[t.codec]).filter((c): c is string => c !== undefined);
const video = tracks.some((t) => t.type === 1);
return `${video ? 'video' : 'audio'}/webm${codecs.length > 0 ? `; codecs="${codecs.join(',')}"` : ''}`;
}
/** Relative timecode (signed 16-bit) of a SimpleBlock or BlockGroup body, or null. */
function blockTimecode(b: Uint8Array, id: number, body: number, end: number): number | null {
let at = body;
if (id === ID_BLOCK_GROUP) {
// Find the Block inside the group.
let found = -1;
while (at < end) {
const g = readId(b, at);
const gs = g && readSize(b, at + g.length);
if (!g || !gs) return null;
if (g.value === ID_BLOCK) {
found = at + g.length + gs.length;
break;
}
at += g.length + gs.length + gs.value;
}
if (found < 0) return null;
at = found;
} else if (id !== ID_SIMPLE_BLOCK) {
return null;
}
const track = readSize(b, at);
if (track === null || at + track.length + 2 > end) return null;
const v = (b[at + track.length]! << 8) | b[at + track.length + 1]!;
return v >= 0x8000 ? v - 0x10000 : v;
}
/**
* Put a cluster's blocks in timecode order across tracks.
*
* Chrome's WebM parser rejects a cluster in which any block — of any track —
* has an earlier timecode than the block before it ("Got a block with a
* timecode before the previous block"). ffmpeg's live muxer writes exactly
* that when Opus timestamps round a millisecond below an interleaved video
* frame. Each track's own order is already right, so a stable sort over all
* blocks only fixes the interleaving; the cluster keeps its size and every
* block its bytes.
*/
export function orderBlocks(cluster: Uint8Array): Uint8Array {
const id = readId(cluster, 0);
const size = id && readSize(cluster, id.length);
if (!id || !size) return cluster;
const bodyStart = id.length + size.length;
const children: { start: number; end: number; tc: number | null }[] = [];
let at = bodyStart;
while (at < cluster.length) {
const cid = readId(cluster, at);
const cs = cid && readSize(cluster, at + cid.length);
if (!cid || !cs) return cluster;
const body = at + cid.length + cs.length;
const end = body + cs.value;
if (end > cluster.length) return cluster;
children.push({ start: at, end, tc: blockTimecode(cluster, cid.value, body, end) });
at = end;
}
const slots = children.map((c, i) => (c.tc !== null ? i : -1)).filter((i) => i >= 0);
let ordered = true;
for (let k = 1; k < slots.length; k++) {
if (children[slots[k]!]!.tc! < children[slots[k - 1]!]!.tc!) ordered = false;
}
if (ordered) return cluster;
const blocks = slots.map((i) => children[i]!).sort((a, b) => a.tc! - b.tc!); // stable
const placed = children.slice();
slots.forEach((slot, k) => {
placed[slot] = blocks[k]!;
});
const out = new Uint8Array(cluster.length);
out.set(cluster.subarray(0, bodyStart), 0);
let w = bodyStart;
for (const c of placed) {
out.set(cluster.subarray(c.start, c.end), w);
w += c.end - c.start;
}
return out;
}
export class WebmSplitter {
private buf: Uint8Array = new Uint8Array(0);
private initDone = false;
private tracks: TrackInfo[] = [];
private videoTracks = new Set<number>();
/** Offset in `buf` where the cluster being assembled started, or -1. */
private clusterStart = -1;
/** For a known-size cluster: its end offset in `buf`. */
private clusterEnd = -1;
/** Scan position inside an unknown-size cluster. */
private scan = 0;
push(chunk: Uint8Array): WebmPiece[] {
this.buf = this.buf.length === 0 ? chunk.slice() : concat([this.buf, chunk]);
const out: WebmPiece[] = [];
if (!this.initDone) {
const init = this.tryInit();
if (init === null) return out;
out.push(init);
}
for (;;) {
const c = this.tryCluster(false);
if (c === null) break;
out.push(c);
}
return out;
}
/** End of stream: the last unknown-size cluster ends here. */
finish(): WebmPiece[] {
const out: WebmPiece[] = [];
const c = this.tryCluster(true);
if (c !== null) out.push(c);
return out;
}
private tryInit(): WebmPiece | null {
// EBML header, then the Segment header, then children until a Cluster.
let at = 0;
const ebml = readId(this.buf, at);
if (ebml === null) return null;
if (ebml.value !== ID_EBML) throw new MediaFormatError('not a WebM stream (no EBML header)');
const ebmlSize = readSize(this.buf, at + ebml.length);
if (ebmlSize === null) return null;
at += ebml.length + ebmlSize.length + ebmlSize.value;
const seg = readId(this.buf, at);
const segSize = seg && readSize(this.buf, at + seg.length);
if (!seg || !segSize) return null;
if (seg.value !== ID_SEGMENT) throw new MediaFormatError('WebM: expected Segment');
at += seg.length + segSize.length;
for (;;) {
const id = readId(this.buf, at);
if (id === null) return null;
if (id.value === ID_CLUSTER) break;
const size = readSize(this.buf, at + id.length);
if (size === null) return null;
if (size.unknown) throw new MediaFormatError('WebM: unknown-size element before the first Cluster');
const bodyStart = at + id.length + size.length;
if (bodyStart + size.value > this.buf.length) return null;
if (id.value === ID_TRACKS) this.tracks = parseTracks(this.buf.subarray(bodyStart, bodyStart + size.value));
at = bodyStart + size.value;
}
this.initDone = true;
for (const t of this.tracks) if (t.type === 1) this.videoTracks.add(t.number);
const bytes = this.buf.slice(0, at);
this.buf = this.buf.slice(at);
return { type: 'init', mime: webmMime(this.tracks), bytes };
}
private tryCluster(final: boolean): WebmPiece | null {
if (this.clusterStart < 0) {
// Skip anything between clusters that is not one (Cues, Tags, Void).
for (;;) {
const id = readId(this.buf, 0);
if (id === null) return null;
const size = readSize(this.buf, id.length);
if (size === null) return null;
if (id.value === ID_CLUSTER) {
this.clusterStart = 0;
const body = id.length + size.length;
this.clusterEnd = size.unknown ? -1 : body + size.value;
this.scan = body;
break;
}
if (size.unknown) throw new MediaFormatError('WebM: unknown-size element between clusters');
const skip = id.length + size.length + size.value;
if (skip > this.buf.length) return null;
this.buf = this.buf.slice(skip);
}
}
let end: number;
if (this.clusterEnd >= 0) {
if (this.buf.length < this.clusterEnd) return null;
end = this.clusterEnd;
} else {
// Walk children until one that cannot belong to a Cluster.
for (;;) {
const id = readId(this.buf, this.scan);
const size = id && readSize(this.buf, this.scan + id.length);
if (!id || !size) {
if (final) {
end = this.buf.length;
break;
}
return null;
}
if (!CLUSTER_CHILDREN.has(id.value)) {
end = this.scan;
break;
}
const next = this.scan + id.length + size.length + size.value;
if (next > this.buf.length) {
if (final) {
end = this.buf.length;
break;
}
return null;
}
this.scan = next;
}
}
if (end <= 0) return null;
const bytes = orderBlocks(this.buf.slice(0, end));
this.buf = this.buf.slice(end);
this.clusterStart = -1;
this.clusterEnd = -1;
return { type: 'cluster', keyframe: this.isKeyframe(bytes), bytes };
}
/** Does the first block of a video track in this cluster start a GOP? */
private isKeyframe(cluster: Uint8Array): boolean {
if (this.videoTracks.size === 0) return true; // audio only: every cluster is a start
const id = readId(cluster, 0)!;
const size = readSize(cluster, id.length)!;
let at = id.length + size.length;
while (at < cluster.length) {
const cid = readId(cluster, at);
const cs = cid && readSize(cluster, at + cid.length);
if (!cid || !cs) return false;
const body = at + cid.length + cs.length;
if (cid.value === ID_SIMPLE_BLOCK) {
const track = readSize(cluster, body);
if (track && this.videoTracks.has(track.value)) {
return (cluster[body + track.length + 2]! & 0x80) !== 0;
}
} else if (cid.value === ID_BLOCK_GROUP) {
// A BlockGroup is a keyframe iff it has no ReferenceBlock.
let p = body;
let track: Vint | null = null;
let referenced = false;
while (p < body + cs.value) {
const g = readId(cluster, p);
const gs = g && readSize(cluster, p + g.length);
if (!g || !gs) break;
if (g.value === ID_BLOCK) track = readSize(cluster, p + g.length + gs.length);
if (g.value === ID_REFERENCE_BLOCK) referenced = true;
p += g.length + gs.length + gs.value;
}
if (track && this.videoTracks.has(track.value)) return !referenced;
}
at = body + cs.value;
}
return false;
}
}

View File

@@ -131,3 +131,44 @@ describe('live channel', () => {
for (const k of kinds) expect((await sub.open(await pub.frame(k)))?.content).toEqual(k);
});
});
describe('link mode', () => {
test('a link grant follows rotations and a publisher restart on its own', async () => {
const secret = new Uint8Array(32).fill(9);
const pub = new LivePublisher({ channelSecret: secret, rotateEvery: 5 });
const g = parseGrant(encodeGrant(pub.grant({ link: true }))) as LiveGrant;
expect(g.channelSecret).toEqual(secret);
const sub = new LiveSubscriber(g);
const seen: string[] = [];
for (let i = 0; i < 12; i++) {
if (pub.rotationDue) await pub.rotate();
const r = await sub.open(await pub.frame(text(`a${i}`)));
if (r?.content.type === 'text') seen.push(r.content.text);
}
expect(seen.length).toBe(12);
expect(pub.epoch).toBe(2);
// The publisher process restarts with the same identity, one epoch on.
const restarted = new LivePublisher({
channelId: pub.channelId,
signingSecret: (pub as unknown as { signingSecret: Uint8Array }).signingSecret,
channelSecret: secret,
epoch: pub.epoch + 1,
});
// A late viewer joins mid-epoch: it derives forward from seq 0.
for (let i = 0; i < 40; i++) await restarted.frame(text(`skip${i}`));
const r = await sub.open(await restarted.frame(text('after restart')));
expect(r?.content).toEqual(text('after restart'));
expect(r?.epoch).toBe(3);
});
test('a session grant does not carry the secret, and cannot read later epochs', async () => {
const pub = new LivePublisher({ channelSecret: new Uint8Array(32).fill(1) });
const g = pub.grant({ from: 'now' });
expect(g.channelSecret).toBeUndefined();
const sub = new LiveSubscriber(g);
await pub.rotate();
await expect(sub.open(await pub.frame(text('x')))).rejects.toBeInstanceOf(LiveKeyError);
expect(() => new LivePublisher().grant({ link: true })).toThrow();
});
});

View File

@@ -47,7 +47,7 @@ function pattern(n: number): Uint8Array {
return out;
}
const until = async (cond: () => boolean, ms = 3000) => {
const until = async (cond: () => boolean, ms = 10_000) => {
const t = Date.now();
while (!cond()) {
if (Date.now() - t > ms) throw new Error('timed out');
@@ -122,6 +122,26 @@ describe('media routes over real HTTP', () => {
}
});
test('a Range request on a multi-MiB file returns exactly that range', async () => {
// Regression: Bun.file().slice() in a Response sent the whole file.
const dir = await tempDir();
const app = new Hono();
app.route('/', createMediaRoutes(new FileMediaStore(dir)));
const { server, base } = serve(app);
try {
const client = new MediaClient(base, OwnerKey.generate());
const plain = pattern(3 * 1024 * 1024 + 5);
const grant = await client.uploadBytes(plain, { readToken: null });
const res = await fetch(grant.url!, { headers: { Range: 'bytes=100-1048675' } });
expect(res.status).toBe(206);
expect((await res.arrayBuffer()).byteLength).toBe(1048576);
const r = await openGrant(grant);
expect(await r.read(0, plain.length)).toEqual(plain);
} finally {
server.stop(true);
}
});
test('refuses what is not a sealed file, bad signatures, and owners not on the list', async () => {
const dir = await tempDir();
const allowed = OwnerKey.generate();

View File

@@ -0,0 +1,89 @@
import { describe, test, expect } from 'bun:test';
import { WebmSplitter } from '../src/webm.js';
import type { WebmPiece } from '../src/webm.js';
const hasFfmpeg = Bun.which('ffmpeg') !== null;
async function ffmpegWebm(args: string[]): Promise<Uint8Array> {
const p = Bun.spawn(['ffmpeg', '-hide_banner', '-loglevel', 'error', ...args, '-f', 'webm', 'pipe:1'], {
stdout: 'pipe',
stderr: 'inherit',
});
const out = new Uint8Array(await new Response(p.stdout).arrayBuffer());
await p.exited;
return out;
}
/** Relative timecodes of the SimpleBlocks in one cluster, in file order. */
function clusterTimecodes(c: Uint8Array): number[] {
const vint = (at: number) => {
let len = 1;
while ((c[at]! & (0x80 >> (len - 1))) === 0) len++;
let v = c[at]! & (0xff >> len);
for (let i = 1; i < len; i++) v = v * 256 + c[at + i]!;
return { v, len };
};
const idLen = (at: number) => {
let len = 1;
while ((c[at]! & (0x80 >> (len - 1))) === 0) len++;
return len;
};
let at = idLen(0);
at += vint(at).len;
const out: number[] = [];
while (at < c.length) {
const il = idLen(at);
const isSimple = c[at] === 0xa3;
const sz = vint(at + il);
const body = at + il + sz.len;
if (isSimple) {
const tr = vint(body);
out.push(new DataView(c.buffer, c.byteOffset).getInt16(body + tr.len, false));
}
at = body + sz.v;
}
return out;
}
function split(bytes: Uint8Array, chunk: number): WebmPiece[] {
const s = new WebmSplitter();
const out: WebmPiece[] = [];
for (let i = 0; i < bytes.length; i += chunk) out.push(...s.push(bytes.subarray(i, i + chunk)));
out.push(...s.finish());
return out;
}
describe.skipIf(!hasFfmpeg)('WebM splitter on real ffmpeg output', () => {
test('VP8+Opus live stream: init, then keyframe clusters, bytes preserved', async () => {
const webm = await ffmpegWebm([
'-f', 'lavfi', '-i', 'testsrc=size=320x240:rate=30',
'-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000',
'-t', '4', '-c:v', 'libvpx', '-b:v', '300k', '-g', '30', '-deadline', 'realtime',
'-c:a', 'libopus', '-live', '1', '-cluster_time_limit', '1000',
]);
for (const chunk of [1, 777, 65536, webm.length]) {
const pieces = split(webm, chunk);
expect(pieces[0]!.type).toBe('init');
expect((pieces[0] as { mime: string }).mime).toBe('video/webm; codecs="vp8,opus"');
const clusters = pieces.slice(1);
expect(clusters.length).toBeGreaterThan(2);
expect(clusters.every((p) => p.type === 'cluster')).toBe(true);
// ffmpeg starts a cluster on each keyframe; with -g 30 at 30 fps that is one a second.
expect(clusters.filter((p) => p.type === 'cluster' && p.keyframe).length).toBeGreaterThanOrEqual(3);
expect(clusters[0]!.type === 'cluster' && clusters[0]!.keyframe).toBe(true);
// Same length and same bytes, give or take the block order inside a cluster.
const joined = Buffer.concat(pieces.map((p) => p.bytes));
expect(joined.length).toBe(webm.length);
expect(Buffer.from(joined).sort().equals(Buffer.from(webm).sort())).toBe(true);
// What Chrome's MSE demands: block timecodes never go backwards inside a cluster.
for (const p of clusters) expect(clusterTimecodes(p.bytes)).toEqual([...clusterTimecodes(p.bytes)].sort((a, b) => a - b));
}
}, 30_000);
test('audio-only Opus: every cluster is a starting point', async () => {
const webm = await ffmpegWebm(['-f', 'lavfi', '-i', 'sine=frequency=220', '-t', '3', '-c:a', 'libopus', '-live', '1', '-cluster_time_limit', '500']);
const pieces = split(webm, 4096);
expect((pieces[0] as { mime: string }).mime).toBe('audio/webm; codecs="opus"');
expect(pieces.slice(1).every((p) => p.type === 'cluster' && p.keyframe)).toBe(true);
}, 30_000);
});