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>
2026-10-18 21:01:52 +02:00
|
|
|
/**
|
|
|
|
|
* 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',
|
2026-10-18 22:01:33 +02:00
|
|
|
// The sealed meta, for the page (subtitles, title). Never leaves the
|
|
|
|
|
// browser: this response is made here, not fetched.
|
|
|
|
|
'x-shade-meta': toB64u(new TextEncoder().encode(JSON.stringify(reader.meta))),
|
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>
2026-10-18 21:01:52 +02:00
|
|
|
};
|
|
|
|
|
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));
|
|
|
|
|
});
|