- 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>
219 lines
7.6 KiB
TypeScript
219 lines
7.6 KiB
TypeScript
/**
|
||
* Grants: how a viewer gets the keys.
|
||
*
|
||
* A grant is a small JSON object the owner sends over an **existing Shade
|
||
* session** — `shade.send(peer, encodeGrant(g))`. That is the whole trust
|
||
* story: the Double Ratchet authenticates who sent it and gives it forward
|
||
* secrecy, the relay that stores the film never sees it, and a viewer
|
||
* removed later still holds only what was granted to them.
|
||
*
|
||
* For a device with no Shade session — the TV, a browser on the couch — the
|
||
* same grant can ride in a capability link: the grant sits in the URL
|
||
* *fragment*, which browsers never send to a server. Whoever holds the link
|
||
* can watch; treat it like a key.
|
||
*/
|
||
|
||
import { dec, enc, fromB64u, fromHex, toB64u, toHex } from './bytes.js';
|
||
import { MediaFormatError } from './errors.js';
|
||
import { MEDIA_ID_BYTES, MEDIA_KEY_BYTES, DIGEST_BYTES, validateMeta } from './sealed.js';
|
||
import type { MediaKeys, MediaMeta, SealResult } from './sealed.js';
|
||
|
||
export const MEDIA_GRANT_KIND = 'shade.media-grant/v1';
|
||
export const LIVE_GRANT_KIND = 'shade.live-grant/v1';
|
||
|
||
/** Keys and location of one sealed file. */
|
||
export interface MediaGrant {
|
||
kind: typeof MEDIA_GRANT_KIND;
|
||
mediaId: Uint8Array;
|
||
mediaKey: Uint8Array;
|
||
rootDigest: Uint8Array;
|
||
/** Where the sealed bytes live — any URL that answers Range requests. */
|
||
url?: string;
|
||
/** Bearer token the media routes ask for; not a key, just a door. */
|
||
readToken?: Uint8Array;
|
||
/** A preview of the sealed metadata, so a list can render before opening. */
|
||
meta?: MediaMeta;
|
||
}
|
||
|
||
/** Keys to join a live channel from a given point. */
|
||
export interface LiveGrant {
|
||
kind: typeof LIVE_GRANT_KIND;
|
||
channelId: Uint8Array;
|
||
/** Publisher's Ed25519 public key for this channel: every frame is signed by it. */
|
||
signingKey: Uint8Array;
|
||
epoch: number;
|
||
/** First seq this grant can decrypt. */
|
||
seq: number;
|
||
/** Chain key at `seq`. Earlier frames cannot be derived from it. */
|
||
chainKey: Uint8Array;
|
||
/** Key for the epoch's sticky frames (codec init, channel header). */
|
||
stickyKey: Uint8Array;
|
||
/** WebSocket URL of the relay, e.g. `wss://relay/v1/live/<id>`. */
|
||
url?: string;
|
||
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;
|
||
|
||
export function mediaGrantFrom(
|
||
r: SealResult,
|
||
extra: { url?: string; readToken?: Uint8Array; meta?: MediaMeta } = {},
|
||
): MediaGrant {
|
||
return {
|
||
kind: MEDIA_GRANT_KIND,
|
||
mediaId: r.mediaId,
|
||
mediaKey: r.mediaKey,
|
||
rootDigest: r.rootDigest,
|
||
...(extra.url !== undefined ? { url: extra.url } : {}),
|
||
...(extra.readToken !== undefined ? { readToken: extra.readToken } : {}),
|
||
...(extra.meta !== undefined ? { meta: extra.meta } : {}),
|
||
};
|
||
}
|
||
|
||
export function mediaKeysOf(g: MediaGrant): MediaKeys {
|
||
return { mediaId: g.mediaId, mediaKey: g.mediaKey, rootDigest: g.rootDigest };
|
||
}
|
||
|
||
/** Wire JSON: binary fields as base64url, the digest as hex (it is a hash, and greppable). */
|
||
export function encodeGrant(g: Grant): string {
|
||
if (g.kind === MEDIA_GRANT_KIND) {
|
||
return JSON.stringify({
|
||
kind: g.kind,
|
||
mediaId: toB64u(g.mediaId),
|
||
key: toB64u(g.mediaKey),
|
||
root: toHex(g.rootDigest),
|
||
...(g.url !== undefined ? { url: g.url } : {}),
|
||
...(g.readToken !== undefined ? { token: toB64u(g.readToken) } : {}),
|
||
...(g.meta !== undefined ? { meta: g.meta } : {}),
|
||
});
|
||
}
|
||
return JSON.stringify({
|
||
kind: g.kind,
|
||
channelId: toB64u(g.channelId),
|
||
signingKey: toB64u(g.signingKey),
|
||
epoch: g.epoch,
|
||
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 } : {}),
|
||
});
|
||
}
|
||
|
||
function str(o: Record<string, unknown>, k: string): string {
|
||
const v = o[k];
|
||
if (typeof v !== 'string') throw new MediaFormatError(`grant.${k} must be a string`);
|
||
return v;
|
||
}
|
||
|
||
function int(o: Record<string, unknown>, k: string, max: number): number {
|
||
const v = o[k];
|
||
if (typeof v !== 'number' || !Number.isInteger(v) || v < 0 || v > max) {
|
||
throw new MediaFormatError(`grant.${k} must be an integer in [0, ${max}]`);
|
||
}
|
||
return v;
|
||
}
|
||
|
||
function optUrl(o: Record<string, unknown>): { url?: string } {
|
||
if (o.url === undefined) return {};
|
||
const url = str(o, 'url');
|
||
let parsed: URL;
|
||
try {
|
||
parsed = new URL(url);
|
||
} catch {
|
||
throw new MediaFormatError('grant.url is not a URL');
|
||
}
|
||
if (!['http:', 'https:', 'ws:', 'wss:'].includes(parsed.protocol)) {
|
||
throw new MediaFormatError('grant.url must be http(s) or ws(s)');
|
||
}
|
||
return { url };
|
||
}
|
||
|
||
function optToken(o: Record<string, unknown>): { readToken?: Uint8Array } {
|
||
if (o.token === undefined) return {};
|
||
const t = fromB64u(str(o, 'token'));
|
||
if (t.length < 16 || t.length > 64) throw new MediaFormatError('grant.token must be 16–64 bytes');
|
||
return { readToken: t };
|
||
}
|
||
|
||
function optMeta(o: Record<string, unknown>): { meta?: MediaMeta } {
|
||
if (o.meta === undefined) return {};
|
||
return { meta: validateMeta(o.meta) };
|
||
}
|
||
|
||
/** Parse a grant from wire JSON, strictly. Anything unexpected is refused. */
|
||
export function parseGrant(json: string): Grant {
|
||
let o: Record<string, unknown>;
|
||
try {
|
||
o = JSON.parse(json);
|
||
} catch {
|
||
throw new MediaFormatError('grant is not JSON');
|
||
}
|
||
if (typeof o !== 'object' || o === null || Array.isArray(o)) {
|
||
throw new MediaFormatError('grant must be an object');
|
||
}
|
||
if (o.kind === MEDIA_GRANT_KIND) {
|
||
return {
|
||
kind: MEDIA_GRANT_KIND,
|
||
mediaId: fromB64u(str(o, 'mediaId'), MEDIA_ID_BYTES),
|
||
mediaKey: fromB64u(str(o, 'key'), MEDIA_KEY_BYTES),
|
||
rootDigest: fromHex(str(o, 'root'), DIGEST_BYTES),
|
||
...optUrl(o),
|
||
...optToken(o),
|
||
...optMeta(o),
|
||
};
|
||
}
|
||
if (o.kind === LIVE_GRANT_KIND) {
|
||
return {
|
||
kind: LIVE_GRANT_KIND,
|
||
channelId: fromB64u(str(o, 'channelId'), 16),
|
||
signingKey: fromB64u(str(o, 'signingKey'), 32),
|
||
epoch: int(o, 'epoch', 0xffff_ffff),
|
||
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),
|
||
};
|
||
}
|
||
throw new MediaFormatError(`unknown grant kind ${String(o.kind)}`);
|
||
}
|
||
|
||
/** Is this decrypted Shade message a grant? Cheap check before `parseGrant`. */
|
||
export function isGrantMessage(plaintext: string): boolean {
|
||
return (
|
||
plaintext.startsWith('{') &&
|
||
(plaintext.includes(`"${MEDIA_GRANT_KIND}"`) || plaintext.includes(`"${LIVE_GRANT_KIND}"`))
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Capability link: `<page>#shade=<base64url(grant JSON)>`.
|
||
*
|
||
* The fragment never leaves the browser, so the page host learns nothing;
|
||
* the page reads it, hands the grant to its Service Worker, and plays.
|
||
*/
|
||
export function toCapabilityUrl(pageUrl: string, g: Grant): string {
|
||
const u = new URL(pageUrl);
|
||
u.hash = `shade=${toB64u(enc.encode(encodeGrant(g)))}`;
|
||
return u.toString();
|
||
}
|
||
|
||
export function fromCapabilityUrl(link: string): Grant {
|
||
const hash = link.includes('#') ? link.slice(link.indexOf('#') + 1) : link;
|
||
const m = /(?:^|&)shade=([A-Za-z0-9_-]+)/.exec(hash);
|
||
if (m === null) throw new MediaFormatError('link carries no #shade= grant');
|
||
return parseGrant(dec.decode(fromB64u(m[1]!)));
|
||
}
|