feat(media): @shade/media — seekable sealed media (SMF1), live channels, media routes and live relay

SMF1 seals a film, video, image or song once into a file any Range-capable
store can serve; the reader fetches only segments under the playhead and
checks each against a digest table pinned by the grant's root digest.
Live channels use a sender-key chain with per-frame Ed25519 signatures,
sticky init frames and keyframe snapshots for late joiners, and epoch
rotation to remove a viewer. Server side: a disk-backed media store with
signed owner uploads and a WebSocket relay with bounded backlog.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 20:41:31 +02:00
parent fb7f2e55c0
commit 9e64ec87be
25 changed files with 3994 additions and 26 deletions

View File

@@ -0,0 +1,24 @@
{
"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",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",
"exports": {
".": "./src/index.ts",
"./node": "./src/node.ts",
"./server": "./src/server.ts",
"./browser": "./src/browser/index.ts"
},
"dependencies": {
"@noble/curves": "^2.0.1",
"@noble/hashes": "^2.0.1",
"hono": "^4.12.18"
},
"scripts": {
"test": "bun test",
"typecheck": "tsc --noEmit",
"build:sw": "bun build src/browser/sw.ts --outfile dist/shade-media-sw.js --target browser --minify"
}
}

View File

@@ -0,0 +1,83 @@
/**
* AES-256-GCM with a caller-supplied nonce.
*
* `CryptoProvider.aesGcmEncrypt` draws a random nonce, which is right for
* objects sealed one at a time. A sealed film is not: segment `i` must be
* decryptable from its index alone, so a reader can seek to it without a
* per-segment nonce table. That is safe because every key used here is
* unique to one file (or one live frame) and every nonce is unique under it.
*
* Imported keys are cached: importing per segment is a measurable share of
* the cost of playing a film.
*/
import { bs } from './bytes.js';
import { MediaIntegrityError } from './errors.js';
export const NONCE_BYTES = 12;
export const TAG_BYTES = 16;
export class AeadKey {
private keyPromise: Promise<CryptoKey> | null;
constructor(raw: Uint8Array) {
if (raw.length !== 32) throw new Error('AES-256-GCM key must be 32 bytes');
this.keyPromise = globalThis.crypto.subtle.importKey('raw', bs(raw), 'AES-GCM', false, [
'encrypt',
'decrypt',
]);
}
private key(): Promise<CryptoKey> {
if (this.keyPromise === null) throw new Error('AeadKey used after destroy()');
return this.keyPromise;
}
async seal(nonce: Uint8Array, plaintext: Uint8Array, aad: Uint8Array): Promise<Uint8Array> {
if (nonce.length !== NONCE_BYTES) throw new Error('nonce must be 12 bytes');
const out = await globalThis.crypto.subtle.encrypt(
{ name: 'AES-GCM', iv: bs(nonce), additionalData: bs(aad) },
await this.key(),
bs(plaintext),
);
return new Uint8Array(out);
}
async open(nonce: Uint8Array, ciphertext: Uint8Array, aad: Uint8Array): Promise<Uint8Array> {
if (nonce.length !== NONCE_BYTES) throw new Error('nonce must be 12 bytes');
try {
const out = await globalThis.crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: bs(nonce), additionalData: bs(aad) },
await this.key(),
bs(ciphertext),
);
return new Uint8Array(out);
} catch {
throw new MediaIntegrityError('AEAD authentication failed');
}
}
/** Drop the reference; a non-extractable CryptoKey cannot be zeroed further. */
destroy(): void {
this.keyPromise = null;
}
}
/** One-shot open/seal for keys used exactly once (live frame keys). */
export async function sealOnce(
key: Uint8Array,
nonce: Uint8Array,
plaintext: Uint8Array,
aad: Uint8Array,
): Promise<Uint8Array> {
return new AeadKey(key).seal(nonce, plaintext, aad);
}
export async function openOnce(
key: Uint8Array,
nonce: Uint8Array,
ciphertext: Uint8Array,
aad: Uint8Array,
): Promise<Uint8Array> {
return new AeadKey(key).open(nonce, ciphertext, aad);
}

View File

@@ -0,0 +1,103 @@
/**
* Byte helpers shared by the sealed-media and live formats.
*
* Everything here is pure and synchronous so it behaves the same in Bun, a
* browser tab and a Service Worker — the three places a media file is read.
*/
import { MediaFormatError } from './errors.js';
export const enc = new TextEncoder();
export const dec = new TextDecoder('utf-8', { fatal: true });
export function concat(parts: readonly Uint8Array[]): Uint8Array {
let total = 0;
for (const p of parts) total += p.length;
const out = new Uint8Array(total);
let off = 0;
for (const p of parts) {
out.set(p, off);
off += p.length;
}
return out;
}
export function u32be(n: number): Uint8Array {
const out = new Uint8Array(4);
new DataView(out.buffer).setUint32(0, n, false);
return out;
}
export function u64be(n: number | bigint): Uint8Array {
const out = new Uint8Array(8);
new DataView(out.buffer).setBigUint64(0, BigInt(n), false);
return out;
}
/** Read a u64 that must fit in a JS number (2^53) — sizes and counts do. */
export function readU64(view: DataView, offset: number): number {
const v = view.getBigUint64(offset, false);
if (v > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new MediaFormatError('u64 field exceeds 2^53');
}
return Number(v);
}
export function equalBytes(a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;
return diff === 0;
}
export function randomBytes(n: number): Uint8Array {
const out = new Uint8Array(n);
globalThis.crypto.getRandomValues(out);
return out;
}
export function toHex(b: Uint8Array): string {
let s = '';
for (const v of b) s += v.toString(16).padStart(2, '0');
return s;
}
export function fromHex(s: string, expectedLen?: number): Uint8Array {
if (!/^(?:[0-9a-f]{2})*$/.test(s)) throw new MediaFormatError('not lowercase hex');
const out = new Uint8Array(s.length / 2);
for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
if (expectedLen !== undefined && out.length !== expectedLen) {
throw new MediaFormatError(`expected ${expectedLen} bytes, got ${out.length}`);
}
return out;
}
/** base64url without padding — what grants and capability links carry. */
export function toB64u(b: Uint8Array): string {
let bin = '';
for (let i = 0; i < b.length; i += 0x8000) {
bin += String.fromCharCode(...b.subarray(i, i + 0x8000));
}
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
export function fromB64u(s: string, expectedLen?: number): Uint8Array {
if (!/^[A-Za-z0-9_-]*$/.test(s)) throw new MediaFormatError('not base64url');
const pad = s.length % 4 === 0 ? '' : '='.repeat(4 - (s.length % 4));
const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/') + pad);
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
if (expectedLen !== undefined && out.length !== expectedLen) {
throw new MediaFormatError(`expected ${expectedLen} bytes, got ${out.length}`);
}
return out;
}
/** SubtleCrypto takes BufferSource; the DOM alias is not worth the lib churn. */
export function bs(u: Uint8Array): ArrayBuffer {
return u as unknown as ArrayBuffer;
}
export async function sha256(data: Uint8Array): Promise<Uint8Array> {
return new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bs(data)));
}

View File

@@ -0,0 +1,109 @@
/**
* Client for the media routes: upload sealed files, list and delete your
* own, and open anything you hold a grant for.
*/
import { randomBytes, sha256, toB64u, toHex } from './bytes.js';
import { MediaFormatError } from './errors.js';
import { mediaGrantFrom, mediaKeysOf } from './grant.js';
import type { MediaGrant } from './grant.js';
import { READ_HASH_HEADER, READ_TOKEN_HEADER } from './owner.js';
import type { OwnerKey } from './owner.js';
import { MediaReader, sealMediaBytes } from './sealed.js';
import type { MediaMeta, ReaderOptions, SealOptions, SealResult } from './sealed.js';
import { HttpRangeSource } from './source.js';
export function mediaUrl(server: string, mediaId: Uint8Array): string {
return `${server.replace(/\/$/, '')}/v1/media/${toHex(mediaId)}`;
}
export interface PutOptions {
/** Token viewers must present. Default: a fresh random one per file. `null` = public ciphertext. */
readToken?: Uint8Array | null;
/** Copied into the grant so a library can list titles without opening each file. */
meta?: MediaMeta;
}
export class MediaClient {
private readonly fetchFn: typeof fetch;
constructor(
private readonly server: string,
private readonly owner: OwnerKey,
opts: { fetch?: typeof fetch } = {},
) {
this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
}
/**
* Upload an already sealed file. `body` must be exactly `result.sealedSize`
* bytes — a Blob/`Bun.file` streams from disk without loading the film.
*/
async putSealed(result: SealResult, body: Blob | Uint8Array, opts: PutOptions = {}): Promise<MediaGrant> {
const size = body instanceof Uint8Array ? body.length : body.size;
if (size !== result.sealedSize) {
throw new MediaFormatError(`body is ${size} bytes, the seal produced ${result.sealedSize}`);
}
const readToken = opts.readToken === undefined ? randomBytes(32) : opts.readToken;
const readTokenHash = readToken === null ? '' : toHex(await sha256(readToken));
const id = toHex(result.mediaId);
const url = mediaUrl(this.server, result.mediaId);
const res = await this.fetchFn(url, {
method: 'PUT',
headers: {
'content-type': 'application/vnd.shade.smf1',
'content-length': String(size),
...(readTokenHash !== '' ? { [READ_HASH_HEADER]: readTokenHash } : {}),
...this.owner.headers({ op: 'put', id, size, readTokenHash }),
},
body: body as BodyInit,
});
if (res.status !== 201) {
throw new Error(`upload failed: HTTP ${res.status} ${await res.text().catch(() => '')}`);
}
return mediaGrantFrom(result, {
url,
...(readToken !== null ? { readToken } : {}),
...(opts.meta !== undefined ? { meta: opts.meta } : {}),
});
}
/** Seal in memory and upload — images, clips, documents. */
async uploadBytes(plaintext: Uint8Array, opts: SealOptions & PutOptions = {}): Promise<MediaGrant> {
const { bytes, result } = await sealMediaBytes(plaintext, opts);
return this.putSealed(result, bytes, opts.meta !== undefined ? { ...opts, meta: opts.meta } : opts);
}
async delete(mediaId: Uint8Array): Promise<boolean> {
const id = toHex(mediaId);
const res = await this.fetchFn(mediaUrl(this.server, mediaId), {
method: 'DELETE',
headers: this.owner.headers({ op: 'delete', id }),
});
if (res.status === 404) return false;
if (!res.ok) throw new Error(`delete failed: HTTP ${res.status}`);
return true;
}
async list(): Promise<{ items: { id: string; size: number; createdAt: number }[]; usage: number }> {
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();
}
}
/** Open a granted file over HTTP. */
export function openGrant(
grant: MediaGrant,
opts: ReaderOptions & { fetch?: typeof fetch; url?: string } = {},
): Promise<MediaReader> {
const url = opts.url ?? grant.url;
if (url === undefined) throw new MediaFormatError('grant has no URL');
const source = new HttpRangeSource(url, {
...(grant.readToken !== undefined ? { headers: { [READ_TOKEN_HEADER]: toB64u(grant.readToken) } } : {}),
...(opts.fetch !== undefined ? { fetch: opts.fetch } : {}),
});
return MediaReader.open(source, mediaKeysOf(grant), opts);
}

View File

@@ -0,0 +1,84 @@
/**
* Ed25519 for per-frame signatures.
*
* Live frames are signed one by one, so the signature is on the hot path: a
* log stream can carry thousands of frames a second. WebCrypto's Ed25519
* (Bun, Chrome ≥ 137, Firefox ≥ 129, Safari ≥ 17) is ~10× faster than the
* pure-JS implementation; that one remains the fallback where the runtime
* lacks it. Both produce identical RFC 8032 signatures — Ed25519 is
* deterministic — so a frame signed one way verifies the other.
*/
import { ed25519 } from '@noble/curves/ed25519.js';
import { bs, concat } from './bytes.js';
/** PKCS#8 prefix for a raw 32-byte Ed25519 seed (RFC 8410). */
const PKCS8_PREFIX = new Uint8Array([
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
]);
let subtleOk: Promise<boolean> | null = null;
function hasSubtleEd25519(): Promise<boolean> {
subtleOk ??= (async () => {
try {
const seed = new Uint8Array(32);
const k = await globalThis.crypto.subtle.importKey('pkcs8', bs(concat([PKCS8_PREFIX, seed])), { name: 'Ed25519' }, false, ['sign']);
const sig = new Uint8Array(await globalThis.crypto.subtle.sign('Ed25519', k, bs(new Uint8Array(1))));
// Guard against a runtime whose "Ed25519" disagrees with RFC 8032.
return ed25519.verify(sig, new Uint8Array(1), ed25519.getPublicKey(seed));
} catch {
return false;
}
})();
return subtleOk;
}
export class Ed25519Signer {
readonly publicKey: Uint8Array;
private key: Promise<CryptoKey | null>;
constructor(private readonly seed: Uint8Array) {
this.publicKey = ed25519.getPublicKey(seed);
this.key = hasSubtleEd25519().then((ok) =>
ok
? globalThis.crypto.subtle.importKey('pkcs8', bs(concat([PKCS8_PREFIX, seed])), { name: 'Ed25519' }, false, ['sign'])
: null,
);
}
async sign(message: Uint8Array): Promise<Uint8Array> {
const k = await this.key;
if (k === null) return ed25519.sign(message, this.seed);
return new Uint8Array(await globalThis.crypto.subtle.sign('Ed25519', k, bs(message)));
}
}
export class Ed25519Verifier {
private key: Promise<CryptoKey | null>;
constructor(readonly publicKey: Uint8Array) {
this.key = hasSubtleEd25519().then((ok) =>
ok
? globalThis.crypto.subtle
.importKey('raw', bs(publicKey), { name: 'Ed25519' }, false, ['verify'])
// An invalid point is refused at import by some runtimes; let the
// pure-JS path give the (false) answer instead of throwing.
.catch(() => null)
: null,
);
}
async verify(signature: Uint8Array, message: Uint8Array): Promise<boolean> {
if (signature.length !== 64) return false;
const k = await this.key;
if (k === null) {
try {
return ed25519.verify(signature, message, this.publicKey);
} catch {
return false;
}
}
return globalThis.crypto.subtle.verify('Ed25519', k, bs(signature), bs(message));
}
}

View File

@@ -0,0 +1,18 @@
/** A file, frame or grant is malformed — bad magic, a length that does not add up. */
export class MediaFormatError extends Error {
override readonly name = 'MediaFormatError';
}
/**
* Bytes failed authentication: a segment whose hash is not in the table, an
* AEAD tag that does not verify, a live frame with a bad signature. Never
* retried silently — it means someone between the writer and us changed them.
*/
export class MediaIntegrityError extends Error {
override readonly name = 'MediaIntegrityError';
}
/** A live frame arrived that this subscriber holds no key for. */
export class LiveKeyError extends Error {
override readonly name = 'LiveKeyError';
}

View File

@@ -0,0 +1,211 @@
/**
* 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;
}
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.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),
...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]!)));
}

View File

@@ -0,0 +1,30 @@
export * from './errors.js';
export {
MediaSealer,
MediaReader,
sealMediaStream,
sealMediaBytes,
validateMeta,
decodeFooter,
encodeFooter,
segmentCountFor,
sealedSizeFor,
DEFAULT_SEGMENT_SIZE,
MIN_SEGMENT_SIZE,
MAX_SEGMENT_SIZE,
FOOTER_BYTES,
} from './sealed.js';
export type { MediaMeta, MediaKeys, SealResult, SealOptions, ReaderOptions, Footer } from './sealed.js';
export { MemorySource, HttpRangeSource } from './source.js';
export type { RangeSource, HttpRangeSourceOptions } from './source.js';
export * from './grant.js';
export { OwnerKey, verifyOwner, READ_TOKEN_HEADER, READ_HASH_HEADER } from './owner.js';
export type { OwnerOp } from './owner.js';
export { MediaClient, openGrant, mediaUrl } from './client.js';
export type { PutOptions } from './client.js';
export { LivePublisher, LiveSubscriber, epochKeys, chainStep, MAX_SKIP, MAX_SKIPPED_KEYS } from './live/channel.js';
export type { FrameOptions, PublisherOptions, GrantOptions, ReceivedFrame } from './live/channel.js';
export { encodeContent, decodeContent, decodeFrame, FLAG_STICKY, FLAG_KEYFRAME, FLAG_END } from './live/frame.js';
export type { LiveContent, FrameHeader } from './live/frame.js';
export { LivePublishClient, LiveWatchClient, liveUrl } from './live/client.js';
export type { LiveState, PublishOptions, WatchOptions } from './live/client.js';

View File

@@ -0,0 +1,430 @@
/**
* Live channels: one publisher, any number of viewers, a dumb relay between.
*
* The key schedule is Signal's **Sender Keys**, the construction WhatsApp and
* Signal use for groups, adapted to a broadcast:
*
* epochSeed random 32 bytes per epoch
* ck[0] = HKDF(epochSeed, salt = channelId ‖ u32(epoch), "shade-live/v1\0chain")
* stickyKey = HKDF(epochSeed, salt = channelId ‖ u32(epoch), "shade-live/v1\0sticky")
* mk[i] = HMAC(ck[i], 0x01) frame key for seq i, used once
* ck[i+1] = HMAC(ck[i], 0x02) one-way: ck[i] cannot be recovered
* nonce = u32(epoch) ‖ u64(seq) aad = the 48-byte frame header
*
* Every frame is also **signed** with the channel's Ed25519 key. Viewers all
* hold the same chain key, so without the signature any one of them could
* forge frames to the others through the relay; with it, only the publisher
* can speak. The signing key's public half travels in the grant, which
* travels over an authenticated Shade session — that is what binds the
* channel to a person.
*
* Joining late: a grant carries the chain key *at some seq*. The publisher
* keeps snapshots of the chain at recent keyframes (bounded), so a new viewer
* can be handed the key at a point the relay still has buffered and start
* from there — never earlier. Removing a viewer is a new epoch: fresh seed,
* fresh grants for everyone still in.
*
* Sticky frames (codec init, the channel's own description) are sealed under
* the epoch's `stickyKey` instead of the chain, so a viewer who joins an hour
* in can still decode the init segment the publisher sent at second zero.
*/
import { ed25519 } from '@noble/curves/ed25519.js';
import { hkdf } from '@noble/hashes/hkdf.js';
import { hmac } from '@noble/hashes/hmac.js';
import { sha256 } from '@noble/hashes/sha2.js';
import { openOnce, sealOnce } from '../aead.js';
import { Ed25519Signer, Ed25519Verifier } from '../ed25519.js';
import { concat, enc, equalBytes, randomBytes, toB64u, u32be, u64be } from '../bytes.js';
import { LiveKeyError, MediaFormatError, MediaIntegrityError } from '../errors.js';
import { LIVE_GRANT_KIND } from '../grant.js';
import type { LiveGrant } from '../grant.js';
import type { MediaMeta } from '../sealed.js';
import {
CHANNEL_ID_BYTES,
FLAG_END,
FLAG_KEYFRAME,
FLAG_STICKY,
MAX_FRAME_PAYLOAD,
decodeContent,
decodeFrame,
encodeContent,
encodeHeader,
} from './frame.js';
import type { LiveContent } from './frame.js';
const INFO_CHAIN = enc.encode('shade-live/v1\0chain');
const INFO_STICKY = enc.encode('shade-live/v1\0sticky');
const MK = new Uint8Array([0x01]);
const CK = new Uint8Array([0x02]);
/** Furthest a subscriber will derive forward to reach one frame. */
export const MAX_SKIP = 100_000;
/** Frame keys a subscriber keeps for frames that may still arrive out of order. */
export const MAX_SKIPPED_KEYS = 2_000;
export function epochKeys(
epochSeed: Uint8Array,
channelId: Uint8Array,
epoch: number,
): { chainKey: Uint8Array; stickyKey: Uint8Array } {
const salt = concat([channelId, u32be(epoch)]);
return {
chainKey: hkdf(sha256, epochSeed, salt, INFO_CHAIN, 32),
stickyKey: hkdf(sha256, epochSeed, salt, INFO_STICKY, 32),
};
}
/** One chain step: the frame key for this seq, and the chain key for the next. */
export function chainStep(ck: Uint8Array): { messageKey: Uint8Array; next: Uint8Array } {
return { messageKey: hmac(sha256, ck, MK), next: hmac(sha256, ck, CK) };
}
export function frameNonce(epoch: number, seq: number): Uint8Array {
return concat([u32be(epoch), u64be(seq)]);
}
export interface FrameOptions {
/** A viewer can start here (a video keyframe, a log batch boundary). */
keyframe?: boolean;
/** Keep for every late joiner, sealed under the epoch's sticky key. */
sticky?: boolean;
/** Publisher clock, ms. Defaults to `Date.now()`. */
timestamp?: number;
}
export interface PublisherOptions {
meta?: MediaMeta;
/** Chain snapshots kept for late joiners. Default 64 keyframes. */
snapshots?: number;
/** Bring your own channel identity (to resume a channel after a restart). */
channelId?: Uint8Array;
signingSecret?: Uint8Array;
}
export interface GrantOptions {
/**
* Where the viewer can start: `oldest` keyframe snapshot still kept (most
* backlog), the `latest` keyframe, or `now` (only frames sent after this).
* Default `oldest`.
*/
from?: 'oldest' | 'latest' | 'now';
url?: string;
readToken?: Uint8Array;
}
interface Snapshot {
seq: number;
chainKey: Uint8Array;
}
/**
* The sending side of a live channel. Not safe to call `frame` concurrently —
* frames are numbered in call order; await each before the next (the
* `LiveClient` does this for you).
*/
export class LivePublisher {
readonly channelId: Uint8Array;
readonly signingKey: Uint8Array;
readonly meta: MediaMeta | undefined;
private readonly signingSecret: Uint8Array;
private readonly signer: Ed25519Signer;
private epochValue = 0;
private seq = 0;
private chainKey: Uint8Array;
private stickyKey: Uint8Array;
private snapshots: Snapshot[] = [];
private readonly snapshotLimit: number;
/** Plaintext of sticky content, re-sealed into every new epoch. */
private stickyContent: { content: LiveContent; opts: FrameOptions }[] = [];
/** Sealed sticky frames of the current epoch — what a relay must keep. */
private stickyFrames: Uint8Array[] = [];
private closed = false;
constructor(opts: PublisherOptions = {}) {
this.channelId = opts.channelId ?? randomBytes(CHANNEL_ID_BYTES);
if (this.channelId.length !== CHANNEL_ID_BYTES) throw new MediaFormatError('channelId must be 16 bytes');
this.signingSecret = opts.signingSecret ?? ed25519.utils.randomSecretKey();
this.signer = new Ed25519Signer(this.signingSecret);
this.signingKey = this.signer.publicKey;
this.meta = opts.meta;
this.snapshotLimit = Math.max(1, opts.snapshots ?? 64);
const k = epochKeys(randomBytes(32), this.channelId, 0);
this.chainKey = k.chainKey;
this.stickyKey = k.stickyKey;
}
get epoch(): number {
return this.epochValue;
}
get nextSeq(): number {
return this.seq;
}
/** Sticky frames of the current epoch, in order — replay these to a fresh relay. */
get sticky(): readonly Uint8Array[] {
return this.stickyFrames;
}
/** Seal one frame. */
async frame(content: LiveContent, opts: FrameOptions = {}): Promise<Uint8Array> {
if (this.closed) throw new Error('LivePublisher is closed');
const plain = encodeContent(content);
if (plain.length > MAX_FRAME_PAYLOAD) throw new MediaFormatError('live frame payload too large');
const seq = this.seq++;
const sticky = opts.sticky === true;
const keyframe = opts.keyframe === true;
let flags = 0;
if (sticky) flags |= FLAG_STICKY;
if (keyframe) flags |= FLAG_KEYFRAME;
if (content.type === 'end') flags |= FLAG_END;
// The chain advances on every seq, sticky or not, so a viewer's position
// in the chain is always just the seq.
if (keyframe && !sticky) this.snapshot(seq, this.chainKey);
const step = chainStep(this.chainKey);
this.chainKey.fill(0);
this.chainKey = step.next;
const header = encodeHeader({
flags,
channelId: this.channelId,
epoch: this.epochValue,
seq,
timestamp: Math.floor(opts.timestamp ?? Date.now()),
ctLen: plain.length + 16,
});
const key = sticky ? this.stickyKey : step.messageKey;
const ct = await sealOnce(key, frameNonce(this.epochValue, seq), plain, header);
step.messageKey.fill(0);
const signed = concat([header, ct]);
const frame = concat([signed, await this.signer.sign(signed)]);
if (sticky) {
this.stickyFrames.push(frame);
this.stickyContent.push({ content, opts });
}
return frame;
}
private snapshot(seq: number, ck: Uint8Array): void {
this.snapshots.push({ seq, chainKey: ck.slice() });
while (this.snapshots.length > this.snapshotLimit) this.snapshots.shift()!.chainKey.fill(0);
}
/** Keys for one viewer to join from `opts.from`. Send it over a Shade session. */
grant(opts: GrantOptions = {}): LiveGrant {
const from = opts.from ?? 'oldest';
let point: Snapshot;
if (from === 'now' || this.snapshots.length === 0) {
point = { seq: this.seq, chainKey: this.chainKey };
} else {
point = from === 'latest' ? this.snapshots[this.snapshots.length - 1]! : this.snapshots[0]!;
}
return {
kind: LIVE_GRANT_KIND,
channelId: this.channelId,
signingKey: this.signingKey,
epoch: this.epochValue,
seq: point.seq,
chainKey: point.chainKey.slice(),
stickyKey: this.stickyKey.slice(),
...(opts.url !== undefined ? { url: opts.url } : {}),
...(opts.readToken !== undefined ? { readToken: opts.readToken } : {}),
...(this.meta !== undefined ? { meta: this.meta } : {}),
};
}
/**
* Start a new epoch: fresh seed, seq back to 0, snapshots dropped. Returns
* the sticky frames re-sealed for the new epoch — send them first. Grant
* everyone who should stay; anyone not re-granted is out.
*/
async rotate(): Promise<Uint8Array[]> {
if (this.epochValue >= 0xffff_ffff) throw new Error('epoch counter exhausted');
this.epochValue++;
this.seq = 0;
for (const s of this.snapshots) s.chainKey.fill(0);
this.snapshots = [];
this.chainKey.fill(0);
this.stickyKey.fill(0);
const k = epochKeys(randomBytes(32), this.channelId, this.epochValue);
this.chainKey = k.chainKey;
this.stickyKey = k.stickyKey;
const content = this.stickyContent;
this.stickyContent = [];
this.stickyFrames = [];
const out: Uint8Array[] = [];
for (const c of content) out.push(await this.frame(c.content, c.opts));
return out;
}
/** The signed hello a relay pins the channel with. */
hello(readTokenHash: Uint8Array, at = Date.now()): { body: string; signature: Uint8Array } {
const body = JSON.stringify({
kind: 'shade.live-hello/v1',
channelId: toB64u(this.channelId),
signingKey: toB64u(this.signingKey),
readTokenHash: toB64u(readTokenHash),
at,
});
return { body, signature: ed25519.sign(enc.encode(body), this.signingSecret) };
}
close(): void {
this.closed = true;
this.chainKey.fill(0);
this.stickyKey.fill(0);
for (const s of this.snapshots) s.chainKey.fill(0);
this.snapshots = [];
}
}
export interface ReceivedFrame {
epoch: number;
seq: number;
timestamp: number;
sticky: boolean;
keyframe: boolean;
content: LiveContent;
}
interface EpochState {
grant: LiveGrant;
nextSeq: number;
chainKey: Uint8Array;
skipped: Map<number, Uint8Array>;
stickySeen: Set<number>;
}
/**
* The viewing side. Feed it frames in any order; it returns each decrypted
* frame once, or `null` for one it should silently drop — a duplicate after
* a reconnect, or backlog from before the grant's starting point.
*/
export class LiveSubscriber {
private readonly epochs = new Map<number, EpochState>();
readonly channelId: Uint8Array;
readonly signingKey: Uint8Array;
private readonly verifier: Ed25519Verifier;
constructor(grant: LiveGrant) {
this.channelId = grant.channelId;
this.signingKey = grant.signingKey;
this.verifier = new Ed25519Verifier(grant.signingKey);
this.addGrant(grant);
}
/** Add the grant for a new epoch (after a rotation). Older epochs are kept until `forgetBefore`. */
addGrant(g: LiveGrant): void {
if (!equalBytes(g.channelId, this.channelId)) throw new MediaFormatError('grant is for another channel');
if (!equalBytes(g.signingKey, this.signingKey)) {
// A new signing key mid-channel would let whoever sent this grant speak
// as the publisher. A publisher that truly re-keys starts a new channel.
throw new MediaIntegrityError('grant changes the channel signing key');
}
const existing = this.epochs.get(g.epoch);
if (existing !== undefined && existing.nextSeq <= g.seq) return;
this.epochs.set(g.epoch, {
grant: g,
nextSeq: g.seq,
chainKey: g.chainKey.slice(),
skipped: new Map(),
stickySeen: new Set(),
});
}
/** Drop key state for epochs older than `epoch` (forward secrecy after rotation). */
forgetBefore(epoch: number): void {
for (const [e, st] of this.epochs) {
if (e < epoch) {
st.chainKey.fill(0);
for (const k of st.skipped.values()) k.fill(0);
this.epochs.delete(e);
}
}
}
get latestEpoch(): number {
return Math.max(...this.epochs.keys());
}
/** Verify and decrypt one frame. Throws on forgery; `null` means "drop, harmlessly". */
async open(frame: Uint8Array): Promise<ReceivedFrame | null> {
const f = decodeFrame(frame);
const h = f.header;
if (!equalBytes(h.channelId, this.channelId)) throw new MediaFormatError('frame is for another channel');
if (!(await this.verifier.verify(f.signature, f.signed))) {
throw new MediaIntegrityError('live frame signature does not verify');
}
const st = this.epochs.get(h.epoch);
if (st === undefined) {
throw new LiveKeyError(`no grant for epoch ${h.epoch} (have ${[...this.epochs.keys()].join(', ')})`);
}
const sticky = (h.flags & FLAG_STICKY) !== 0;
const nonce = frameNonce(h.epoch, h.seq);
let plain: Uint8Array;
if (sticky) {
if (st.stickySeen.has(h.seq)) return null;
plain = await openOnce(st.grant.stickyKey, nonce, f.ciphertext, f.headerBytes);
st.stickySeen.add(h.seq);
} else {
const mk = this.messageKey(st, h.seq);
if (mk === null) return null;
try {
plain = await openOnce(mk, nonce, f.ciphertext, f.headerBytes);
} finally {
mk.fill(0);
}
}
return {
epoch: h.epoch,
seq: h.seq,
timestamp: h.timestamp,
sticky,
keyframe: (h.flags & FLAG_KEYFRAME) !== 0,
content: decodeContent(plain),
};
}
private messageKey(st: EpochState, seq: number): Uint8Array | null {
if (seq < st.nextSeq) {
const k = st.skipped.get(seq);
if (k === undefined) return null; // before the grant, or already seen
st.skipped.delete(seq);
return k;
}
if (seq - st.nextSeq > MAX_SKIP) {
throw new LiveKeyError(`frame ${seq} is ${seq - st.nextSeq} ahead — beyond MAX_SKIP`);
}
// Derive forward, keeping keys for the frames we skip in case they
// arrive late. Oldest are evicted first: a frame that late is useless
// for live playback anyway.
let ck = st.chainKey;
for (let s = st.nextSeq; s < seq; s++) {
const step = chainStep(ck);
ck.fill(0);
ck = step.next;
if (seq - s <= MAX_SKIPPED_KEYS) {
st.skipped.set(s, step.messageKey);
if (st.skipped.size > MAX_SKIPPED_KEYS) {
const oldest = st.skipped.keys().next().value!;
st.skipped.get(oldest)!.fill(0);
st.skipped.delete(oldest);
}
} else {
step.messageKey.fill(0);
}
}
const step = chainStep(ck);
ck.fill(0);
st.chainKey = step.next;
st.nextSeq = seq + 1;
return step.messageKey;
}
close(): void {
this.forgetBefore(Number.MAX_SAFE_INTEGER);
}
}

View File

@@ -0,0 +1,256 @@
/**
* WebSocket clients for the live relay — the same code in Bun, a browser tab
* and Node ≥ 22 (anything with a global `WebSocket`).
*
* Both sides reconnect with backoff. A publisher re-sends the epoch's sticky
* frames after every reconnect (a restarted relay has no backlog) and queues
* a bounded number of frames while down; a viewer simply re-subscribes, and
* the subscriber drops whatever it has already seen.
*/
import { bs, sha256, toB64u } from '../bytes.js';
import { LiveSubscriber } from './channel.js';
import type { FrameOptions, LivePublisher, ReceivedFrame } from './channel.js';
import type { LiveContent } from './frame.js';
import type { LiveGrant } from '../grant.js';
export type LiveState = 'connecting' | 'live' | 'waiting' | 'reconnecting' | 'closed';
interface Backoff {
next(): number;
reset(): void;
}
function backoff(minMs = 250, maxMs = 10_000): Backoff {
let n = 0;
return {
next: () => Math.min(maxMs, minMs * 2 ** n++) * (0.75 + Math.random() * 0.5),
reset: () => {
n = 0;
},
};
}
/** `https://relay` + channel → `wss://relay/v1/live/<id>`. */
export function liveUrl(base: string, channelId: Uint8Array): string {
const u = new URL(base);
u.protocol = u.protocol === 'https:' || u.protocol === 'wss:' ? 'wss:' : 'ws:';
u.pathname = `${u.pathname.replace(/\/$/, '')}/v1/live/${toB64u(channelId)}`;
return u.toString();
}
export interface PublishOptions {
/** Relay base URL (`https://relay.example`) — the channel path is appended. */
relay: string;
publisher: LivePublisher;
/** Bearer token viewers must present. Its hash goes to the relay; the token goes in grants. */
readToken: Uint8Array;
/** Frames held while disconnected. Older ones are dropped first. Default 2000. */
queueLimit?: number;
onState?: (s: LiveState) => void;
onViewers?: (n: number) => void;
onError?: (message: string) => void;
}
export class LivePublishClient {
readonly url: string;
private ws: WebSocket | null = null;
private ready = false;
private closed = false;
private queue: Uint8Array[] = [];
private sending: Promise<unknown> = Promise.resolve();
private readonly retry = backoff();
private readonly limit: number;
private readTokenHash: Promise<Uint8Array>;
private openedOnce: Promise<void>;
private resolveOpened!: () => void;
constructor(private readonly opts: PublishOptions) {
this.url = liveUrl(opts.relay, opts.publisher.channelId);
this.limit = opts.queueLimit ?? 2000;
this.readTokenHash = sha256(opts.readToken);
this.openedOnce = new Promise((r) => {
this.resolveOpened = r;
});
this.connect();
}
/** Resolves once the relay has accepted the publisher the first time. */
whenReady(): Promise<void> {
return this.openedOnce;
}
/** 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 });
}
/** Seal and send one frame. Frames are numbered in call order. */
send(content: LiveContent, opts: FrameOptions = {}): Promise<void> {
const p = this.sending.then(async () => {
const frame = await this.opts.publisher.frame(content, opts);
this.transmit(frame, opts.sticky === true);
});
this.sending = p.catch(() => {});
return p;
}
/** Rotate the epoch (after removing a viewer) and send the re-sealed sticky frames. */
rotate(): Promise<void> {
const p = this.sending.then(async () => {
for (const f of await this.opts.publisher.rotate()) this.transmit(f, true);
});
this.sending = p.catch(() => {});
return p;
}
/** Wait until everything sent so far has left this process. */
async flush(): Promise<void> {
await this.sending;
const ws = this.ws;
while (ws !== null && this.ready && ws.bufferedAmount > 0) await new Promise((r) => setTimeout(r, 10));
}
private transmit(frame: Uint8Array, sticky: boolean): void {
if (this.ready && this.ws !== null) {
this.ws.send(bs(frame));
return;
}
// Sticky frames are re-sent from the publisher on reconnect; queue the rest.
if (sticky) return;
this.queue.push(frame);
if (this.queue.length > this.limit) this.queue.shift();
}
private connect(): void {
if (this.closed) return;
this.opts.onState?.(this.ws === null ? 'connecting' : 'reconnecting');
const ws = new WebSocket(this.url);
ws.binaryType = 'arraybuffer';
this.ws = ws;
ws.onopen = async () => {
const hello = this.opts.publisher.hello(await this.readTokenHash);
ws.send(JSON.stringify({ type: 'publish', hello: hello.body, signature: toB64u(hello.signature) }));
};
ws.onmessage = (ev) => {
if (typeof ev.data !== 'string') return;
const msg = JSON.parse(ev.data) as { type: string; count?: number; message?: string };
if (msg.type === 'ready') {
this.ready = true;
this.retry.reset();
for (const f of this.opts.publisher.sticky) ws.send(bs(f));
for (const f of this.queue) ws.send(bs(f));
this.queue = [];
this.opts.onState?.('live');
this.resolveOpened();
} else if (msg.type === 'viewers') {
this.opts.onViewers?.(msg.count ?? 0);
} else if (msg.type === 'error') {
this.opts.onError?.(msg.message ?? 'relay error');
}
};
ws.onclose = () => {
this.ready = false;
if (this.closed) return;
this.opts.onState?.('reconnecting');
setTimeout(() => this.connect(), this.retry.next());
};
ws.onerror = () => {};
}
/** Send `end`, flush, and close. */
async end(): Promise<void> {
await this.send({ type: 'end' });
await this.flush();
this.close();
}
close(): void {
this.closed = true;
this.ws?.close();
this.opts.onState?.('closed');
}
}
export interface WatchOptions {
onFrame: (f: ReceivedFrame) => void | Promise<void>;
onState?: (s: LiveState) => void;
/** A frame failed to verify or decrypt. The stream continues. */
onError?: (e: Error) => void;
/** Override the grant's URL (e.g. a different relay mirroring the channel). */
url?: string;
}
/** Watch a live channel from a grant. */
export class LiveWatchClient {
readonly subscriber: LiveSubscriber;
private ws: WebSocket | null = null;
private closed = false;
private readonly retry = backoff();
private chain: Promise<void> = Promise.resolve();
private readonly url: string;
private readonly token: string;
constructor(
grant: LiveGrant,
private readonly opts: WatchOptions,
) {
if (grant.url === undefined && opts.url === undefined) throw new Error('grant has no relay URL');
if (grant.readToken === undefined) throw new Error('grant has no read token');
this.url = opts.url ?? grant.url!;
this.token = toB64u(grant.readToken);
this.subscriber = new LiveSubscriber(grant);
this.connect();
}
/** Hand over the grant for a new epoch (it arrives over the Shade session). */
addGrant(g: LiveGrant): void {
this.subscriber.addGrant(g);
this.subscriber.forgetBefore(g.epoch);
}
private connect(): void {
if (this.closed) return;
this.opts.onState?.(this.ws === null ? 'connecting' : 'reconnecting');
const ws = new WebSocket(this.url);
ws.binaryType = 'arraybuffer';
this.ws = ws;
ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe', token: this.token }));
ws.onmessage = (ev) => {
if (typeof ev.data === 'string') {
const msg = JSON.parse(ev.data) as { type: string; live?: boolean; message?: string };
if (msg.type === 'ready') {
this.retry.reset();
this.opts.onState?.(msg.live ? 'live' : 'waiting');
} else if (msg.type === 'error') {
this.opts.onError?.(new Error(msg.message ?? 'relay error'));
}
return;
}
const bytes = new Uint8Array(ev.data as ArrayBuffer);
// Frames are opened strictly in arrival order — the chain derivation
// and the player both expect it.
this.chain = this.chain.then(async () => {
try {
const f = await this.subscriber.open(bytes);
if (f !== null) await this.opts.onFrame(f);
} catch (e) {
this.opts.onError?.(e as Error);
}
});
};
ws.onclose = () => {
if (this.closed) return;
this.opts.onState?.('reconnecting');
setTimeout(() => this.connect(), this.retry.next());
};
ws.onerror = () => {};
}
close(): void {
this.closed = true;
this.ws?.close();
this.subscriber.close();
this.opts.onState?.('closed');
}
}

View File

@@ -0,0 +1,180 @@
/**
* SLF1 — Shade Live Frame v1.
*
* One frame is one unit a live channel carries: a log line batch, a chat
* message, a WebM cluster, an Opus page, a JPEG from a camera.
*
* 0..4 "SLF1"
* 4 version = 1
* 5 flags: 0x01 sticky · 0x02 keyframe · 0x04 end — other bits 0
* 6..8 reserved = 0
* 8..24 channelId
* 24..28 epoch u32
* 28..36 seq u64
* 36..44 timestamp ms u64 (publisher clock)
* 44..48 ctLen u32
* 48.. AES-256-GCM ciphertext ‖ tag (ctLen bytes, aad = bytes 0..48)
* ..+64 Ed25519 signature over everything before it
*
* The header is in the clear because the relay needs it: `sticky` frames
* (codec init, channel description) are kept for every late joiner, and
* `keyframe` marks where a new viewer can start. What the frame *is* — text,
* video, an image — is inside the ciphertext.
*/
import { concat, dec, enc, equalBytes, readU64 } from '../bytes.js';
import { MediaFormatError } from '../errors.js';
import { validateMeta } from '../sealed.js';
import type { MediaMeta } from '../sealed.js';
export const SLF_MAGIC = new Uint8Array([0x53, 0x4c, 0x46, 0x31]); // "SLF1"
export const SLF_VERSION = 1;
export const HEADER_BYTES = 48;
export const SIGNATURE_BYTES = 64;
export const CHANNEL_ID_BYTES = 16;
export const FLAG_STICKY = 0x01;
export const FLAG_KEYFRAME = 0x02;
export const FLAG_END = 0x04;
const KNOWN_FLAGS = FLAG_STICKY | FLAG_KEYFRAME | FLAG_END;
/** Largest frame a relay or subscriber accepts: 16 MiB of payload. */
export const MAX_FRAME_PAYLOAD = 16 * 1024 * 1024;
export interface FrameHeader {
flags: number;
channelId: Uint8Array;
epoch: number;
seq: number;
timestamp: number;
ctLen: number;
}
export function encodeHeader(h: FrameHeader): Uint8Array {
const out = new Uint8Array(HEADER_BYTES);
const v = new DataView(out.buffer);
out.set(SLF_MAGIC, 0);
out[4] = SLF_VERSION;
out[5] = h.flags;
out.set(h.channelId, 8);
v.setUint32(24, h.epoch, false);
v.setBigUint64(28, BigInt(h.seq), false);
v.setBigUint64(36, BigInt(h.timestamp), false);
v.setUint32(44, h.ctLen, false);
return out;
}
/** Parse and bounds-check a frame's header. Does not verify anything cryptographic. */
export function decodeFrame(frame: Uint8Array): {
header: FrameHeader;
headerBytes: Uint8Array;
ciphertext: Uint8Array;
signed: Uint8Array;
signature: Uint8Array;
} {
if (frame.length < HEADER_BYTES + 16 + SIGNATURE_BYTES) {
throw new MediaFormatError('live frame too short');
}
if (!equalBytes(frame.subarray(0, 4), SLF_MAGIC)) throw new MediaFormatError('not an SLF1 frame');
if (frame[4] !== SLF_VERSION) throw new MediaFormatError(`unsupported SLF version ${frame[4]}`);
const flags = frame[5]!;
if ((flags & ~KNOWN_FLAGS) !== 0 || frame[6] !== 0 || frame[7] !== 0) {
throw new MediaFormatError('unknown SLF flags or reserved bytes');
}
const v = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
const ctLen = v.getUint32(44, false);
if (ctLen < 16 || ctLen > MAX_FRAME_PAYLOAD + 17) throw new MediaFormatError('bad ctLen');
if (frame.length !== HEADER_BYTES + ctLen + SIGNATURE_BYTES) {
throw new MediaFormatError('live frame length does not match its header');
}
return {
header: {
flags,
channelId: frame.slice(8, 24),
epoch: v.getUint32(24, false),
seq: readU64(v, 28),
timestamp: readU64(v, 36),
ctLen,
},
headerBytes: frame.subarray(0, HEADER_BYTES),
ciphertext: frame.subarray(HEADER_BYTES, HEADER_BYTES + ctLen),
signed: frame.subarray(0, HEADER_BYTES + ctLen),
signature: frame.subarray(HEADER_BYTES + ctLen),
};
}
// ─── Content (inside the ciphertext) ─────────────────────────
/**
* What a frame carries. `init` and `image` name their MIME type so a player
* knows what it is feeding — `video/webm; codecs="vp8,opus"` goes straight to
* `MediaSource.addSourceBuffer`.
*/
export type LiveContent =
| { type: 'text'; text: string }
| { type: 'binary'; bytes: Uint8Array }
| { type: 'init'; mime: string; bytes: Uint8Array }
| { type: 'chunk'; bytes: Uint8Array }
| { type: 'image'; mime: string; bytes: Uint8Array }
| { type: 'meta'; meta: MediaMeta }
| { type: 'end' };
const KIND = { text: 1, binary: 2, init: 3, chunk: 4, image: 5, meta: 6, end: 7 } as const;
function withMime(kind: number, mime: string, bytes: Uint8Array): Uint8Array {
const m = enc.encode(mime);
if (m.length === 0 || m.length > 255) throw new MediaFormatError('mime must be 1–255 bytes');
return concat([new Uint8Array([kind, m.length]), m, bytes]);
}
export function encodeContent(c: LiveContent): Uint8Array {
switch (c.type) {
case 'text':
return concat([new Uint8Array([KIND.text]), enc.encode(c.text)]);
case 'binary':
return concat([new Uint8Array([KIND.binary]), c.bytes]);
case 'init':
return withMime(KIND.init, c.mime, c.bytes);
case 'chunk':
return concat([new Uint8Array([KIND.chunk]), c.bytes]);
case 'image':
return withMime(KIND.image, c.mime, c.bytes);
case 'meta':
return concat([new Uint8Array([KIND.meta]), enc.encode(JSON.stringify(validateMeta(c.meta)))]);
case 'end':
return new Uint8Array([KIND.end]);
}
}
export function decodeContent(p: Uint8Array): LiveContent {
if (p.length === 0) throw new MediaFormatError('empty live payload');
const body = p.subarray(1);
const mimeBody = (): { mime: string; bytes: Uint8Array } => {
const n = body[0];
if (n === undefined || n === 0 || body.length < 1 + n) throw new MediaFormatError('bad mime prefix');
return { mime: dec.decode(body.subarray(1, 1 + n)), bytes: body.subarray(1 + n) };
};
switch (p[0]) {
case KIND.text:
return { type: 'text', text: dec.decode(body) };
case KIND.binary:
return { type: 'binary', bytes: body };
case KIND.init:
return { type: 'init', ...mimeBody() };
case KIND.chunk:
return { type: 'chunk', bytes: body };
case KIND.image:
return { type: 'image', ...mimeBody() };
case KIND.meta:
try {
return { type: 'meta', meta: validateMeta(JSON.parse(dec.decode(body))) };
} catch (e) {
if (e instanceof MediaFormatError) throw e;
throw new MediaFormatError('meta frame is not JSON');
}
case KIND.end:
return { type: 'end' };
default:
throw new MediaFormatError(`unknown live content kind ${p[0]}`);
}
}

View File

@@ -0,0 +1,70 @@
/**
* Server-side and CLI helpers that touch the filesystem. Kept out of the main
* entry so the browser bundle and the Service Worker never pull in `node:fs`.
*/
import { open, stat } from 'node:fs/promises';
import type { FileHandle } from 'node:fs/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { sealMediaStream } from './sealed.js';
import type { SealOptions, SealResult } from './sealed.js';
import type { RangeSource } from './source.js';
/** Range reads from a sealed file on disk. */
export class FileSource implements RangeSource {
private handle: Promise<FileHandle> | null = null;
constructor(private readonly path: string) {}
async size(): Promise<number> {
return (await stat(this.path)).size;
}
async read(offset: number, length: number): Promise<Uint8Array> {
this.handle ??= open(this.path, 'r');
const fh = await this.handle;
const out = new Uint8Array(length);
let got = 0;
while (got < length) {
const { bytesRead } = await fh.read(out, got, length - got, offset + got);
if (bytesRead === 0) break;
got += bytesRead;
}
return out.subarray(0, got);
}
async close(): Promise<void> {
if (this.handle !== null) await (await this.handle).close();
this.handle = null;
}
}
/** Read a file as a web stream of Uint8Array chunks (constant memory). */
export function fileChunks(path: string): AsyncIterable<Uint8Array> {
const rs = createReadStream(path, { highWaterMark: 1024 * 1024 });
return (async function* () {
for await (const chunk of rs) yield new Uint8Array(chunk as Buffer);
})();
}
/** Seal `inputPath` into `outputPath` in one streaming pass. */
export async function sealFile(
inputPath: string,
outputPath: string,
opts: SealOptions = {},
): Promise<SealResult> {
const { stream, result } = sealMediaStream(fileChunks(inputPath), opts);
const ws = createWriteStream(outputPath);
const done = new Promise<void>((res, rej) => {
ws.on('finish', () => res());
ws.on('error', rej);
});
const reader = stream.getReader();
for (;;) {
const { value, done: end } = await reader.read();
if (end) break;
if (!ws.write(value)) await new Promise<void>((r) => ws.once('drain', () => r()));
}
ws.end();
await done;
return result;
}

View File

@@ -0,0 +1,91 @@
/**
* Owner signatures for the media routes.
*
* The store must know who may upload and delete, but not who anyone *is*:
* an owner is just an Ed25519 key. The first upload under a key is that key's
* library; nothing else ties it to an account. Requests are signed over a
* fixed string that names the operation, so a signature for one PUT cannot
* be replayed as a DELETE, and a timestamp bounds how long one stays usable.
*/
import { ed25519 } from '@noble/curves/ed25519.js';
import { enc, fromB64u, toB64u } from './bytes.js';
export const OWNER_HEADER = 'x-shade-owner';
export const SIGNATURE_HEADER = 'x-shade-signature';
export const AT_HEADER = 'x-shade-at';
export const READ_HASH_HEADER = 'x-shade-read-hash';
export const READ_TOKEN_HEADER = 'x-shade-read';
/** How far a signed request's clock may be from the server's. */
export const MAX_SKEW_MS = 10 * 60 * 1000;
export type OwnerOp =
| { op: 'put'; id: string; size: number; readTokenHash: string }
| { op: 'delete'; id: string }
| { op: 'list' };
export function ownerMessage(o: OwnerOp, at: number): Uint8Array {
switch (o.op) {
case 'put':
return enc.encode(`shade.media-put/v1|${o.id}|${o.size}|${o.readTokenHash}|${at}`);
case 'delete':
return enc.encode(`shade.media-delete/v1|${o.id}|${at}`);
case 'list':
return enc.encode(`shade.media-list/v1|${at}`);
}
}
export class OwnerKey {
readonly publicKey: Uint8Array;
constructor(private readonly secret: Uint8Array) {
if (secret.length !== 32) throw new Error('owner secret must be 32 bytes');
this.publicKey = ed25519.getPublicKey(secret);
}
static generate(): OwnerKey {
return new OwnerKey(ed25519.utils.randomSecretKey());
}
/** The secret, for persisting — e.g. in the keychain or a 0600 file. */
exportSecret(): Uint8Array {
return this.secret.slice();
}
get id(): string {
return toB64u(this.publicKey);
}
headers(o: OwnerOp, at = Date.now()): Record<string, string> {
return {
[OWNER_HEADER]: this.id,
[AT_HEADER]: String(at),
[SIGNATURE_HEADER]: toB64u(ed25519.sign(ownerMessage(o, at), this.secret)),
};
}
}
/** Verify a signed owner request. Returns the owner id, or a reason it failed. */
export function verifyOwner(
headers: { get(name: string): string | null },
o: OwnerOp,
now = Date.now(),
): { ok: true; owner: string } | { ok: false; reason: string } {
const owner = headers.get(OWNER_HEADER);
const sig = headers.get(SIGNATURE_HEADER);
const atRaw = headers.get(AT_HEADER);
if (owner === null || sig === null || atRaw === null) return { ok: false, reason: 'missing owner signature' };
const at = Number(atRaw);
if (!Number.isSafeInteger(at) || Math.abs(now - at) > MAX_SKEW_MS) {
return { ok: false, reason: 'signature timestamp outside the allowed window' };
}
try {
const pub = fromB64u(owner, 32);
if (!ed25519.verify(fromB64u(sig, 64), ownerMessage(o, at), pub)) {
return { ok: false, reason: 'bad owner signature' };
}
} catch {
return { ok: false, reason: 'malformed owner signature' };
}
return { ok: true, owner };
}

View File

@@ -0,0 +1,663 @@
/**
* SMF1 — Shade Media Format v1: a sealed file you can seek in.
*
* A film, a video, a song or an image is sealed once and then read with
* plain HTTP Range requests from any dumb store: the relay, a static file
* server, a disk. Nobody who stores or serves it learns anything but its
* size; the reader fetches only the segments under the playhead.
*
* Layout (all integers big-endian):
*
* segment[0] … segment[n-1] AES-256-GCM, plaintext `segmentSize` bytes
* each, the last one 0…segmentSize
* meta AES-256-GCM over UTF-8 JSON (`MediaMeta`)
* table n × SHA-256(segment[i] bytes)
* footer (64) "SMF1" · ver · flags · 0 · segSize u32 ·
* plainSize u64 · metaLen u32 · mediaId(16) ·
* 20 × 0 · "SMF1"
*
* The trailer (meta ‖ table ‖ footer) sits at the END so a writer can seal a
* stream of unknown length in one pass with constant memory and upload it as
* it goes — the same reason zip puts its central directory last.
*
* Keys, from a 32-byte `mediaKey` drawn fresh for every seal:
*
* segKey = HKDF(mediaKey, salt = mediaId, "shade-media/v1\0segment")
* metaKey = HKDF(mediaKey, salt = mediaId, "shade-media/v1\0meta")
* nonce_i = u32(0) ‖ u64(i) aad_i = "SMF1" ‖ mediaId ‖ u64(i) ‖ u8(last)
* nonceM = u32(1) ‖ u64(0) aadM = "SMF1-meta" ‖ mediaId
*
* Deterministic nonces are safe because no key is ever used for two files:
* the sealer refuses a caller-supplied key. `last` in the AAD makes truncation
* fail closed — shortening the file makes a non-last segment the last one.
*
* Integrity has two layers. AEAD stops the store. The table plus the
* **root digest** — SHA-256 of the whole trailer, carried in the grant over
* an authenticated Shade session — also stops every *other key holder*: a
* viewer holds the key and could otherwise forge segments for a third viewer
* through a store it controls. The reader checks each segment's hash against
* the table before decrypting it.
*/
import { hkdf } from '@noble/hashes/hkdf.js';
import { sha256 as nobleSha256 } from '@noble/hashes/sha2.js';
import { AeadKey, TAG_BYTES } from './aead.js';
import {
concat,
dec,
enc,
equalBytes,
randomBytes,
readU64,
sha256,
u32be,
u64be,
} from './bytes.js';
import { MediaFormatError, MediaIntegrityError } from './errors.js';
import type { RangeSource } from './source.js';
export const SMF_MAGIC = new Uint8Array([0x53, 0x4d, 0x46, 0x31]); // "SMF1"
export const SMF_VERSION = 1;
export const FOOTER_BYTES = 64;
export const DIGEST_BYTES = 32;
export const MEDIA_ID_BYTES = 16;
export const MEDIA_KEY_BYTES = 32;
/** 1 MiB: a 4 GB film has a 128 KiB table, fetched once on open. */
export const DEFAULT_SEGMENT_SIZE = 1024 * 1024;
export const MIN_SEGMENT_SIZE = 4 * 1024;
export const MAX_SEGMENT_SIZE = 16 * 1024 * 1024;
/** Ceiling on the sealed metadata, so a hostile footer cannot ask for 4 GB. */
export const MAX_META_BYTES = 64 * 1024;
const INFO_SEGMENT = enc.encode('shade-media/v1\0segment');
const INFO_META = enc.encode('shade-media/v1\0meta');
const AAD_META_PREFIX = enc.encode('SMF1-meta');
/** What a sealed file says about itself — encrypted, so only key holders see it. */
export interface MediaMeta {
/** RFC 6838 `type/subtype`, e.g. `video/webm`, `image/jpeg`, `text/plain`. */
mime?: string;
/** Display name — never a path on the store. */
name?: string;
durationMs?: number;
width?: number;
height?: number;
/** Epoch ms the original was made, not when it was sealed. */
createdAt?: number;
/** App-defined string fields (title, series, episode …). */
extra?: Record<string, string>;
}
/** The secret half: what a grant hands a viewer. */
export interface MediaKeys {
mediaId: Uint8Array;
mediaKey: Uint8Array;
/** SHA-256 of the trailer. Optional only for reading your own files. */
rootDigest?: Uint8Array;
}
export interface SealResult {
mediaId: Uint8Array;
mediaKey: Uint8Array;
rootDigest: Uint8Array;
plaintextSize: number;
sealedSize: number;
segmentSize: number;
segmentCount: number;
}
export interface SealOptions {
meta?: MediaMeta;
segmentSize?: number;
}
interface DerivedKeys {
seg: AeadKey;
meta: AeadKey;
}
function deriveKeys(mediaKey: Uint8Array, mediaId: Uint8Array): DerivedKeys {
if (mediaKey.length !== MEDIA_KEY_BYTES) throw new MediaFormatError('mediaKey must be 32 bytes');
if (mediaId.length !== MEDIA_ID_BYTES) throw new MediaFormatError('mediaId must be 16 bytes');
return {
seg: new AeadKey(hkdf(nobleSha256, mediaKey, mediaId, INFO_SEGMENT, 32)),
meta: new AeadKey(hkdf(nobleSha256, mediaKey, mediaId, INFO_META, 32)),
};
}
export function segmentNonce(index: number): Uint8Array {
return concat([u32be(0), u64be(index)]);
}
const META_NONCE = concat([u32be(1), u64be(0)]);
export function segmentAad(mediaId: Uint8Array, index: number, last: boolean): Uint8Array {
return concat([SMF_MAGIC, mediaId, u64be(index), new Uint8Array([last ? 1 : 0])]);
}
function metaAad(mediaId: Uint8Array): Uint8Array {
return concat([AAD_META_PREFIX, mediaId]);
}
function checkSegmentSize(s: number): void {
if (!Number.isInteger(s) || s < MIN_SEGMENT_SIZE || s > MAX_SEGMENT_SIZE) {
throw new MediaFormatError(
`segmentSize must be an integer in [${MIN_SEGMENT_SIZE}, ${MAX_SEGMENT_SIZE}], got ${s}`,
);
}
}
const MIME_RE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}(?:;[ -~]{0,200})?$/i;
/** Validate metadata the same way on both sides — a reader trusts nothing it decrypts blindly. */
export function validateMeta(m: unknown): MediaMeta {
if (typeof m !== 'object' || m === null || Array.isArray(m)) {
throw new MediaFormatError('meta must be an object');
}
const o = m as Record<string, unknown>;
const out: MediaMeta = {};
if (o.mime !== undefined) {
if (typeof o.mime !== 'string' || !MIME_RE.test(o.mime)) throw new MediaFormatError('bad mime');
out.mime = o.mime;
}
if (o.name !== undefined) {
// eslint-disable-next-line no-control-regex
if (typeof o.name !== 'string' || o.name.length > 1024 || /[\u0000-\u001f\u007f]/.test(o.name)) {
throw new MediaFormatError('bad name');
}
out.name = o.name;
}
for (const k of ['durationMs', 'width', 'height', 'createdAt'] as const) {
const v = o[k];
if (v === undefined) continue;
if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {
throw new MediaFormatError(`bad ${k}`);
}
out[k] = v;
}
if (o.extra !== undefined) {
if (typeof o.extra !== 'object' || o.extra === null || Array.isArray(o.extra)) {
throw new MediaFormatError('extra must be an object of strings');
}
const extra: Record<string, string> = {};
for (const [k, v] of Object.entries(o.extra)) {
if (typeof v !== 'string') throw new MediaFormatError('extra values must be strings');
extra[k] = v;
}
out.extra = extra;
}
return out;
}
// ─── Footer ─────────────────────────────────────────────────
export interface Footer {
segmentSize: number;
plaintextSize: number;
metaLen: number;
mediaId: Uint8Array;
}
export function encodeFooter(f: Footer): Uint8Array {
const out = new Uint8Array(FOOTER_BYTES);
const v = new DataView(out.buffer);
out.set(SMF_MAGIC, 0);
out[4] = SMF_VERSION;
// [5] flags = 0, [6..8] reserved = 0
v.setUint32(8, f.segmentSize, false);
v.setBigUint64(12, BigInt(f.plaintextSize), false);
v.setUint32(20, f.metaLen, false);
out.set(f.mediaId, 24);
// [40..60] reserved = 0
out.set(SMF_MAGIC, 60);
return out;
}
export function decodeFooter(b: Uint8Array): Footer {
if (b.length !== FOOTER_BYTES) throw new MediaFormatError('footer must be 64 bytes');
if (!equalBytes(b.subarray(0, 4), SMF_MAGIC) || !equalBytes(b.subarray(60, 64), SMF_MAGIC)) {
throw new MediaFormatError('not an SMF1 file (bad magic)');
}
if (b[4] !== SMF_VERSION) throw new MediaFormatError(`unsupported SMF version ${b[4]}`);
// Refusing beats guessing: a flag or field we do not know might change
// how the rest must be read.
if (b[5] !== 0 || b[6] !== 0 || b[7] !== 0 || b.subarray(40, 60).some((x) => x !== 0)) {
throw new MediaFormatError('unknown SMF flags or non-zero reserved bytes');
}
const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
const segmentSize = v.getUint32(8, false);
checkSegmentSize(segmentSize);
const metaLen = v.getUint32(20, false);
if (metaLen < TAG_BYTES || metaLen > MAX_META_BYTES + TAG_BYTES) {
throw new MediaFormatError(`metaLen out of range: ${metaLen}`);
}
return {
segmentSize,
plaintextSize: readU64(v, 12),
metaLen,
mediaId: b.slice(24, 40),
};
}
/** Segment count for a plaintext size: an empty file still has one (empty, last) segment. */
export function segmentCountFor(plaintextSize: number, segmentSize: number): number {
return Math.max(1, Math.ceil(plaintextSize / segmentSize));
}
/** Byte offset and sealed length of segment `i`. Every segment but the last is full. */
export function segmentSpan(f: Footer, i: number): { offset: number; length: number } {
const n = segmentCountFor(f.plaintextSize, f.segmentSize);
const full = f.segmentSize + TAG_BYTES;
const plain = i < n - 1 ? f.segmentSize : f.plaintextSize - (n - 1) * f.segmentSize;
return { offset: i * full, length: plain + TAG_BYTES };
}
/** Total sealed size the footer implies. Must equal the file size exactly. */
export function sealedSizeFor(f: Footer): number {
const n = segmentCountFor(f.plaintextSize, f.segmentSize);
return f.plaintextSize + n * TAG_BYTES + f.metaLen + n * DIGEST_BYTES + FOOTER_BYTES;
}
// ─── Sealing ────────────────────────────────────────────────
/**
* Incremental sealer: feed plaintext in any chunking, get sealed bytes out
* in order, constant memory (one segment).
*
* A segment is only emitted once more input has arrived after it, because
* whether it is the last one is part of its AAD — an input that ends exactly
* on a boundary makes its final full segment the last.
*/
export class MediaSealer {
readonly mediaId: Uint8Array;
readonly mediaKey: Uint8Array;
readonly segmentSize: number;
private readonly keys: DerivedKeys;
private readonly meta: MediaMeta;
private pending: Uint8Array[] = [];
private pendingLen = 0;
private index = 0;
private plaintextSize = 0;
private sealedSize = 0;
private readonly digests: Uint8Array[] = [];
private finished = false;
constructor(opts: SealOptions = {}) {
this.segmentSize = opts.segmentSize ?? DEFAULT_SEGMENT_SIZE;
checkSegmentSize(this.segmentSize);
this.meta = validateMeta(opts.meta ?? {});
this.mediaId = randomBytes(MEDIA_ID_BYTES);
this.mediaKey = randomBytes(MEDIA_KEY_BYTES);
this.keys = deriveKeys(this.mediaKey, this.mediaId);
}
/** Add plaintext; returns zero or more sealed segments to write, in order. */
async push(chunk: Uint8Array): Promise<Uint8Array[]> {
if (this.finished) throw new Error('MediaSealer.push after finish');
if (chunk.length === 0) return [];
this.pending.push(chunk);
this.pendingLen += chunk.length;
this.plaintextSize += chunk.length;
const out: Uint8Array[] = [];
while (this.pendingLen > this.segmentSize) {
out.push(await this.sealSegment(this.take(this.segmentSize), false));
}
return out;
}
/** Seal what is left and the trailer. Returns the final bytes and the result. */
async finish(): Promise<{ bytes: Uint8Array[]; result: SealResult }> {
if (this.finished) throw new Error('MediaSealer.finish called twice');
this.finished = true;
const last = await this.sealSegment(this.take(this.pendingLen), true);
const metaJson = enc.encode(JSON.stringify(this.meta));
if (metaJson.length > MAX_META_BYTES) throw new MediaFormatError('meta too large');
const metaBlock = await this.keys.meta.seal(META_NONCE, metaJson, metaAad(this.mediaId));
const footer = encodeFooter({
segmentSize: this.segmentSize,
plaintextSize: this.plaintextSize,
metaLen: metaBlock.length,
mediaId: this.mediaId,
});
const trailer = concat([metaBlock, ...this.digests, footer]);
this.sealedSize += trailer.length;
this.keys.seg.destroy();
this.keys.meta.destroy();
return {
bytes: [last, trailer],
result: {
mediaId: this.mediaId,
mediaKey: this.mediaKey,
rootDigest: await sha256(trailer),
plaintextSize: this.plaintextSize,
sealedSize: this.sealedSize,
segmentSize: this.segmentSize,
segmentCount: this.index,
},
};
}
private take(n: number): Uint8Array {
const out = new Uint8Array(n);
let filled = 0;
while (filled < n) {
const head = this.pending[0]!;
const want = n - filled;
if (head.length <= want) {
out.set(head, filled);
filled += head.length;
this.pending.shift();
} else {
out.set(head.subarray(0, want), filled);
this.pending[0] = head.subarray(want);
filled += want;
}
}
this.pendingLen -= n;
return out;
}
private async sealSegment(plain: Uint8Array, last: boolean): Promise<Uint8Array> {
const i = this.index++;
const sealed = await this.keys.seg.seal(segmentNonce(i), plain, segmentAad(this.mediaId, i, last));
this.digests.push(await sha256(sealed));
this.sealedSize += sealed.length;
return sealed;
}
}
type ByteInput = Uint8Array | AsyncIterable<Uint8Array> | Iterable<Uint8Array> | ReadableStream<Uint8Array>;
async function* chunksOf(input: ByteInput): AsyncGenerator<Uint8Array> {
if (input instanceof Uint8Array) {
yield input;
return;
}
if (typeof (input as ReadableStream<Uint8Array>).getReader === 'function') {
const reader = (input as ReadableStream<Uint8Array>).getReader();
try {
for (;;) {
const { value, done } = await reader.read();
if (done) return;
yield value;
}
} finally {
reader.releaseLock();
}
}
yield* input as AsyncIterable<Uint8Array>;
}
/**
* Seal a stream. The returned `stream` can go straight into a `fetch` PUT
* body or a file; `result` resolves once the last byte has been read from it.
*/
export function sealMediaStream(
input: ByteInput,
opts: SealOptions = {},
): { stream: ReadableStream<Uint8Array>; result: Promise<SealResult> } {
const sealer = new MediaSealer(opts);
let resolve!: (r: SealResult) => void;
let reject!: (e: unknown) => void;
const result = new Promise<SealResult>((res, rej) => {
resolve = res;
reject = rej;
});
// A caller that only awaits the stream must not see an unhandled rejection.
result.catch(() => {});
const it = chunksOf(input);
const stream = new ReadableStream<Uint8Array>({
async pull(controller) {
try {
for (;;) {
const { value, done } = await it.next();
if (done) {
const fin = await sealer.finish();
for (const b of fin.bytes) controller.enqueue(b);
controller.close();
resolve(fin.result);
return;
}
const out = await sealer.push(value);
if (out.length > 0) {
for (const b of out) controller.enqueue(b);
return;
}
}
} catch (e) {
reject(e);
controller.error(e);
}
},
async cancel(reason) {
reject(reason ?? new Error('seal cancelled'));
await it.return?.(undefined);
},
});
return { stream, result };
}
/** Seal bytes already in memory — images, short clips, test fixtures. */
export async function sealMediaBytes(
plaintext: Uint8Array,
opts: SealOptions = {},
): Promise<{ bytes: Uint8Array; result: SealResult }> {
const sealer = new MediaSealer(opts);
const parts = await sealer.push(plaintext);
const fin = await sealer.finish();
return { bytes: concat([...parts, ...fin.bytes]), result: fin.result };
}
// ─── Reading ────────────────────────────────────────────────
export interface ReaderOptions {
/** Decrypted segments kept for sequential small reads. Default 8. */
cacheSegments?: number;
/**
* Longest single fetch, in segments. Coalescing neighbours into one Range
* request is what makes playback cheap over HTTP; this caps the memory one
* read can pin. Default 8.
*/
maxSegmentsPerFetch?: number;
}
/**
* Random-access reader over a sealed file.
*
* `open` fetches the footer and trailer (two requests, ~130 KiB for a 4 GB
* film), checks them against the root digest, and from then on every `read`
* touches only the segments under the requested range.
*/
export class MediaReader {
readonly meta: MediaMeta;
readonly size: number;
readonly segmentSize: number;
readonly segmentCount: number;
private readonly cache = new Map<number, Uint8Array>();
private readonly inflight = new Map<number, Promise<Uint8Array>>();
private readonly cacheLimit: number;
private readonly maxPerFetch: number;
private constructor(
private readonly source: RangeSource,
private readonly footer: Footer,
private readonly table: Uint8Array,
private readonly segKey: AeadKey,
meta: MediaMeta,
opts: ReaderOptions,
) {
this.meta = meta;
this.size = footer.plaintextSize;
this.segmentSize = footer.segmentSize;
this.segmentCount = segmentCountFor(footer.plaintextSize, footer.segmentSize);
this.cacheLimit = opts.cacheSegments ?? 8;
this.maxPerFetch = Math.max(1, opts.maxSegmentsPerFetch ?? 8);
}
static async open(
source: RangeSource,
keys: MediaKeys,
opts: ReaderOptions = {},
): Promise<MediaReader> {
const total = await source.size();
if (total < FOOTER_BYTES) throw new MediaFormatError('file too short to be SMF1');
const footer = decodeFooter(await source.read(total - FOOTER_BYTES, FOOTER_BYTES));
if (!equalBytes(footer.mediaId, keys.mediaId)) {
throw new MediaIntegrityError('file is a different media item than the grant names');
}
if (sealedSizeFor(footer) !== total) {
throw new MediaIntegrityError(
`size mismatch: footer implies ${sealedSizeFor(footer)} bytes, file has ${total}`,
);
}
const n = segmentCountFor(footer.plaintextSize, footer.segmentSize);
const trailerLen = footer.metaLen + n * DIGEST_BYTES + FOOTER_BYTES;
const trailer = await source.read(total - trailerLen, trailerLen);
if (keys.rootDigest !== undefined && !equalBytes(await sha256(trailer), keys.rootDigest)) {
throw new MediaIntegrityError('trailer does not match the root digest in the grant');
}
const derived = deriveKeys(keys.mediaKey, keys.mediaId);
const metaPlain = await derived.meta.open(
META_NONCE,
trailer.subarray(0, footer.metaLen),
metaAad(keys.mediaId),
);
derived.meta.destroy();
let meta: MediaMeta;
try {
meta = validateMeta(JSON.parse(dec.decode(metaPlain)));
} catch (e) {
if (e instanceof MediaFormatError) throw e;
throw new MediaFormatError('meta is not valid JSON');
}
const table = trailer.slice(footer.metaLen, footer.metaLen + n * DIGEST_BYTES);
return new MediaReader(source, footer, table, derived.seg, meta, opts);
}
/** Plaintext bytes `[offset, offset+length)`, clamped to the end of the file. */
async read(offset: number, length: number): Promise<Uint8Array> {
if (!Number.isInteger(offset) || !Number.isInteger(length) || offset < 0 || length < 0) {
throw new RangeError('offset and length must be non-negative integers');
}
const end = Math.min(this.size, offset + length);
if (offset >= end) return new Uint8Array(0);
const first = Math.floor(offset / this.segmentSize);
const last = Math.floor((end - 1) / this.segmentSize);
const segs = await this.segments(first, last);
const joined = segs.length === 1 ? segs[0]! : concat(segs);
const base = first * this.segmentSize;
return joined.subarray(offset - base, end - base);
}
/** Decrypted segment `i`, verified against the table. */
async segment(i: number): Promise<Uint8Array> {
return (await this.segments(i, i))[0]!;
}
/**
* A lazy stream of `[start, end)`. Segments are fetched one batch at a time
* as the consumer pulls, so a `<video>` that seeks away cancels the rest.
*/
stream(start = 0, end = this.size): ReadableStream<Uint8Array> {
let pos = Math.max(0, start);
const stop = Math.min(end, this.size);
const batch = this.segmentSize * this.maxPerFetch;
return new ReadableStream<Uint8Array>({
pull: async (controller) => {
if (pos >= stop) {
controller.close();
return;
}
// Align batches to segment boundaries so consecutive pulls never
// re-fetch the segment the previous one ended in.
const next = Math.min(stop, (Math.floor(pos / this.segmentSize) * this.segmentSize) + batch);
const bytes = await this.read(pos, next - pos);
pos = next;
controller.enqueue(bytes);
},
});
}
private async segments(first: number, last: number): Promise<Uint8Array[]> {
if (first < 0 || last >= this.segmentCount || first > last) {
throw new RangeError(`segment range ${first}..${last} outside 0..${this.segmentCount - 1}`);
}
const out: Promise<Uint8Array>[] = [];
let i = first;
while (i <= last) {
const cached = this.cache.get(i) ?? this.inflight.get(i);
if (cached !== undefined) {
out.push(Promise.resolve(cached));
i++;
continue;
}
// Coalesce a run of missing segments into one Range request.
let j = i;
while (
j + 1 <= last &&
j + 1 - i < this.maxPerFetch &&
!this.cache.has(j + 1) &&
!this.inflight.has(j + 1)
) {
j++;
}
const runStart = i;
const batch = this.fetchRun(runStart, j);
for (let k = runStart; k <= j; k++) {
const p = batch.then((arr) => arr[k - runStart]!);
this.inflight.set(k, p);
p.then(
(v) => this.remember(k, v),
() => {},
).finally(() => this.inflight.delete(k));
out.push(p);
}
i = j + 1;
}
return Promise.all(out);
}
private async fetchRun(first: number, last: number): Promise<Uint8Array[]> {
const a = segmentSpan(this.footer, first);
const b = segmentSpan(this.footer, last);
const bytes = await this.source.read(a.offset, b.offset + b.length - a.offset);
if (bytes.length !== b.offset + b.length - a.offset) {
throw new MediaIntegrityError('short read from media source');
}
const work: Promise<Uint8Array>[] = [];
for (let i = first; i <= last; i++) {
const span = segmentSpan(this.footer, i);
const sealed = bytes.subarray(span.offset - a.offset, span.offset - a.offset + span.length);
work.push(this.openSegment(i, sealed));
}
return Promise.all(work);
}
private async openSegment(i: number, sealed: Uint8Array): Promise<Uint8Array> {
const want = this.table.subarray(i * DIGEST_BYTES, (i + 1) * DIGEST_BYTES);
if (!equalBytes(await sha256(sealed), want)) {
throw new MediaIntegrityError(`segment ${i} does not match its digest`);
}
return this.segKey.open(
segmentNonce(i),
sealed,
segmentAad(this.footer.mediaId, i, i === this.segmentCount - 1),
);
}
private remember(i: number, v: Uint8Array): void {
if (this.cacheLimit <= 0) return;
this.cache.delete(i);
this.cache.set(i, v);
while (this.cache.size > this.cacheLimit) {
this.cache.delete(this.cache.keys().next().value!);
}
}
close(): void {
this.cache.clear();
this.segKey.destroy();
}
}

View File

@@ -0,0 +1,6 @@
export { createMediaRoutes, parseRange } from './server/media-routes.js';
export type { MediaRoutesOptions } from './server/media-routes.js';
export { FileMediaStore, MemoryMediaStore, MediaExistsError } from './server/file-store.js';
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';

View File

@@ -0,0 +1,258 @@
/**
* Sealed media on disk.
*
* Films are gigabytes, so this is a directory of files, not database rows:
* uploads stream to a temp file and are linked into place atomically, reads
* are `Bun.file().slice()` straight off the disk. Each object has a small
* JSON sidecar (owner, size, read-token hash); the in-memory index is
* rebuilt from the sidecars on open, so the directory is the only truth and
* a restart loses nothing.
*/
import { mkdir, link, readdir, readFile, rename, rm, stat, unlink, writeFile, open } from 'node:fs/promises';
import type { FileHandle } from 'node:fs/promises';
import { join } from 'node:path';
import { randomBytes, toHex } from '../bytes.js';
export interface MediaRecord {
/** Lowercase hex of the 16-byte mediaId. */
id: string;
/** base64url Ed25519 public key that uploaded it — the only key that may delete it. */
owner: string;
size: number;
/** Hex SHA-256 of the read token, or null for media anyone may fetch. */
readTokenHash: string | null;
createdAt: number;
}
export interface MediaUpload {
write(chunk: Uint8Array): Promise<void>;
/** Bytes written so far. */
readonly written: number;
/** Read back a range of what was written (for the footer check before commit). */
readBack(offset: number, length: number): Promise<Uint8Array>;
/** Link into place. Throws `MediaExistsError` if the id was taken meanwhile. */
commit(record: MediaRecord): Promise<void>;
abort(): Promise<void>;
}
export class MediaExistsError extends Error {
override readonly name = 'MediaExistsError';
}
export interface MediaStore {
get(id: string): Promise<MediaRecord | null>;
/** Total bytes stored for an owner — for quotas. */
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>;
delete(id: string): Promise<boolean>;
list(owner: string): Promise<MediaRecord[]>;
}
const ID_RE = /^[0-9a-f]{32}$/;
export class FileMediaStore implements MediaStore {
private readonly index = new Map<string, MediaRecord>();
private ready: Promise<void>;
constructor(private readonly dir: string) {
this.ready = this.load();
}
private objectPath(id: string): string {
return join(this.dir, 'objects', id.slice(0, 2), `${id}.smf`);
}
private sidecarPath(id: string): string {
return join(this.dir, 'objects', id.slice(0, 2), `${id}.json`);
}
private async load(): Promise<void> {
await mkdir(join(this.dir, 'objects'), { recursive: true });
await mkdir(join(this.dir, 'tmp'), { recursive: true });
// Uploads that never committed (a crash, a dropped connection) are garbage.
for (const f of await readdir(join(this.dir, 'tmp'))) {
await rm(join(this.dir, 'tmp', f), { force: true });
}
for (const shard of await readdir(join(this.dir, 'objects'))) {
const shardDir = join(this.dir, 'objects', shard);
for (const f of await readdir(shardDir)) {
if (!f.endsWith('.json')) continue;
const id = f.slice(0, -5);
if (!ID_RE.test(id)) continue;
try {
const rec = JSON.parse(await readFile(join(shardDir, f), 'utf8')) as MediaRecord;
const s = await stat(this.objectPath(id));
if (s.size !== rec.size) continue; // half-deleted or corrupted — not served
this.index.set(id, rec);
} catch {
// A sidecar without its object (or unreadable) is skipped, not fatal:
// one bad file must not take the whole library offline.
}
}
}
}
async get(id: string): Promise<MediaRecord | null> {
await this.ready;
return this.index.get(id) ?? null;
}
async usage(owner: string): Promise<number> {
await this.ready;
let n = 0;
for (const r of this.index.values()) if (r.owner === owner) n += r.size;
return n;
}
async totalBytes(): Promise<number> {
await this.ready;
let n = 0;
for (const r of this.index.values()) n += r.size;
return n;
}
async list(owner: string): Promise<MediaRecord[]> {
await this.ready;
return [...this.index.values()].filter((r) => r.owner === owner).sort((a, b) => b.createdAt - a.createdAt);
}
async begin(id: string): Promise<MediaUpload> {
await this.ready;
if (!ID_RE.test(id)) throw new Error('bad media id');
const tmp = join(this.dir, 'tmp', `${id}.${toHex(randomBytes(8))}.part`);
const fh: FileHandle = await open(tmp, 'wx+');
let written = 0;
let closed = false;
const finalPath = this.objectPath(id);
const sidecar = this.sidecarPath(id);
const index = this.index;
const close = async () => {
if (!closed) {
closed = true;
await fh.close();
}
};
return {
get written() {
return written;
},
async write(chunk) {
let off = 0;
while (off < chunk.length) {
const { bytesWritten } = await fh.write(chunk, off, chunk.length - off, written + off);
off += bytesWritten;
}
written += chunk.length;
},
async readBack(offset, length) {
const out = new Uint8Array(length);
const { bytesRead } = await fh.read(out, 0, length, offset);
return out.subarray(0, bytesRead);
},
async commit(record) {
await fh.sync();
await close();
await mkdir(join(finalPath, '..'), { recursive: true });
try {
// link() fails with EEXIST atomically — two racing uploads of one id
// cannot both win, and the loser cannot overwrite the winner.
await link(tmp, finalPath);
} catch (e) {
await unlink(tmp).catch(() => {});
if ((e as NodeJS.ErrnoException).code === 'EEXIST') throw new MediaExistsError(id);
throw e;
}
await unlink(tmp).catch(() => {});
const sidecarTmp = `${sidecar}.${toHex(randomBytes(4))}.tmp`;
await writeFile(sidecarTmp, JSON.stringify(record));
await rename(sidecarTmp, sidecar);
index.set(id, record);
},
async abort() {
await close();
await unlink(tmp).catch(() => {});
},
};
}
async body(id: string, start: number, end: number): Promise<Blob> {
await this.ready;
return Bun.file(this.objectPath(id)).slice(start, end);
}
async delete(id: string): Promise<boolean> {
await this.ready;
if (!this.index.has(id)) return false;
this.index.delete(id);
// Sidecar first: an object without a sidecar is ignored on load, so a
// crash between the two unlinks never resurrects a deleted film.
await rm(this.sidecarPath(id), { force: true });
await rm(this.objectPath(id), { force: true });
return true;
}
}
/** For tests only — loses everything on restart, which a media library must not. */
export class MemoryMediaStore implements MediaStore {
private readonly objects = new Map<string, { rec: MediaRecord; bytes: Uint8Array }>();
async get(id: string): Promise<MediaRecord | null> {
return this.objects.get(id)?.rec ?? null;
}
async usage(owner: string): Promise<number> {
let n = 0;
for (const o of this.objects.values()) if (o.rec.owner === owner) n += o.rec.size;
return n;
}
async totalBytes(): Promise<number> {
let n = 0;
for (const o of this.objects.values()) n += o.rec.size;
return n;
}
async list(owner: string): Promise<MediaRecord[]> {
return [...this.objects.values()].map((o) => o.rec).filter((r) => r.owner === owner);
}
async begin(id: string): Promise<MediaUpload> {
const parts: Uint8Array[] = [];
let written = 0;
const objects = this.objects;
const joined = () => {
const out = new Uint8Array(written);
let o = 0;
for (const p of parts) {
out.set(p, o);
o += p.length;
}
return out;
};
return {
get written() {
return written;
},
async write(chunk) {
parts.push(chunk.slice());
written += chunk.length;
},
async readBack(offset, length) {
return joined().slice(offset, offset + length);
},
async commit(rec) {
if (objects.has(id)) throw new MediaExistsError(id);
objects.set(id, { rec, bytes: joined() });
},
async abort() {},
};
}
async body(id: string, start: number, end: number): Promise<Blob> {
const o = this.objects.get(id);
if (o === undefined) throw new Error('not found');
return new Blob([o.bytes.slice(start, end)]);
}
async delete(id: string): Promise<boolean> {
return this.objects.delete(id);
}
}

View File

@@ -0,0 +1,431 @@
/**
* The live relay: one WebSocket in from the publisher, fan-out to viewers.
*
* GET /v1/live/:channelId (WebSocket)
*
* First text message decides the role:
* { "type": "publish", "hello": "<signed JSON>", "signature": "<b64u>" }
* { "type": "subscribe", "token": "<b64u read token>" }
*
* The relay holds no keys. It *does* verify every frame's Ed25519 signature
* against the key the channel was pinned with — cheap, and it means a relay
* never stores or forwards a frame its viewers would reject anyway.
*
* Backlog, per channel, so a viewer who joins late has something to start
* from: every sticky frame of the current epoch (codec init), plus the
* frames since the N-th most recent keyframe, capped in bytes and count.
* It is live data — ciphertext held for minutes — and lives in memory; the
* channel *pins* (which key owns which channel) are persistent, so a relay
* restart cannot let someone else claim a channel id a viewer already holds.
*
* A viewer that cannot keep up is not allowed to grow the relay's memory:
* past a high-water mark its non-sticky frames are dropped until its socket
* drains and the next keyframe comes along, which is exactly where a video
* decoder can pick up again.
*/
import { ed25519 } from '@noble/curves/ed25519.js';
import { Hono } from 'hono';
import { upgradeWebSocket } from 'hono/bun';
import type { WSContext } from 'hono/ws';
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import { enc, equalBytes, fromB64u, randomBytes, sha256, toB64u, toHex } from '../bytes.js';
import { decodeFrame, FLAG_END, FLAG_KEYFRAME, FLAG_STICKY } from '../live/frame.js';
import { MAX_SKEW_MS } from '../owner.js';
import { Ed25519Verifier } from '../ed25519.js';
export interface LivePin {
channelId: string; // base64url
signingKey: string; // base64url
readTokenHash: string; // base64url SHA-256
pinnedAt: number;
lastSeen: number;
}
export interface LivePinStore {
get(channelId: string): Promise<LivePin | null>;
put(pin: LivePin): Promise<void>;
}
export class MemoryLivePinStore implements LivePinStore {
private readonly pins = new Map<string, LivePin>();
async get(id: string): Promise<LivePin | null> {
return this.pins.get(id) ?? null;
}
async put(pin: LivePin): Promise<void> {
this.pins.set(pin.channelId, pin);
}
}
/**
* Pins in one JSON file, rewritten atomically. A relay has few channels
* (hundreds, not millions) and pins change only when one is created, so a
* file is enough and needs no database. Pins idle past `ttlMs` are dropped.
*/
export class FileLivePinStore implements LivePinStore {
private pins: Map<string, LivePin> | null = null;
private writing: Promise<void> = Promise.resolve();
constructor(
private readonly path: string,
private readonly ttlMs = 30 * 24 * 3600 * 1000,
) {}
private async load(): Promise<Map<string, LivePin>> {
if (this.pins !== null) return this.pins;
const pins = new Map<string, LivePin>();
try {
for (const p of JSON.parse(await readFile(this.path, 'utf8')) as LivePin[]) pins.set(p.channelId, p);
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;
}
this.pins = pins;
return pins;
}
async get(id: string): Promise<LivePin | null> {
return (await this.load()).get(id) ?? null;
}
async put(pin: LivePin): Promise<void> {
const pins = await this.load();
pins.set(pin.channelId, pin);
const cutoff = Date.now() - this.ttlMs;
for (const [k, p] of pins) if (p.lastSeen < cutoff) pins.delete(k);
const snapshot = JSON.stringify([...pins.values()]);
this.writing = this.writing.then(async () => {
await mkdir(dirname(this.path), { recursive: true });
const tmp = `${this.path}.${toHex(randomBytes(4))}.tmp`;
await writeFile(tmp, snapshot, { mode: 0o600 });
await rename(tmp, this.path);
});
await this.writing;
}
}
export interface LiveRelayOptions {
pins: LivePinStore;
/** Keyframes of history kept for late joiners. Default 3. */
backlogKeyframes?: number;
/** Byte cap on a channel's backlog (sticky frames excluded). Default 32 MiB. */
maxBacklogBytes?: number;
/** Frame-count cap on a channel's backlog. Default 5000. */
maxBacklogFrames?: number;
/** Viewer socket buffer past which frames are dropped until the next keyframe. Default 8 MiB. */
viewerHighWater?: number;
/** How long an idle channel (no publisher, no viewers) keeps its backlog. Default 10 min. */
idleRetentionMs?: number;
/** Largest frame accepted. Default 16 MiB + headers. */
maxFrameBytes?: number;
now?: () => number;
}
interface Viewer {
ws: WSContext;
lagging: boolean;
}
interface Channel {
id: string;
pin: LivePin;
verifier: Ed25519Verifier;
publisher: WSContext | null;
viewers: Set<Viewer>;
epoch: number;
sticky: Uint8Array[];
backlog: { frame: Uint8Array; keyframe: boolean }[];
backlogBytes: number;
sawKeyframe: boolean;
ended: boolean;
idleSince: number;
}
type Role = { kind: 'none' } | { kind: 'pub'; ch: Channel } | { kind: 'sub'; ch: Channel; viewer: Viewer };
function bufferedAmount(ws: WSContext): number {
const raw = ws.raw as { getBufferedAmount?: () => number } | undefined;
return raw?.getBufferedAmount?.() ?? 0;
}
function toBytes(data: unknown): Uint8Array | null {
if (data instanceof Uint8Array) return data;
if (data instanceof ArrayBuffer) return new Uint8Array(data);
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
return null;
}
export interface LiveRelay {
app: Hono;
/** Channels currently held, for metrics and tests. */
stats(): { channels: number; viewers: number; backlogBytes: number };
/** Drop idle channels now (also runs on a timer). */
sweep(): void;
stop(): void;
}
export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
const now = opts.now ?? Date.now;
const keepKeyframes = Math.max(1, opts.backlogKeyframes ?? 3);
const maxBytes = opts.maxBacklogBytes ?? 32 * 1024 * 1024;
const maxFrames = opts.maxBacklogFrames ?? 5000;
const highWater = opts.viewerHighWater ?? 8 * 1024 * 1024;
const idleMs = opts.idleRetentionMs ?? 10 * 60 * 1000;
const maxFrameBytes = opts.maxFrameBytes ?? 16 * 1024 * 1024 + 256;
const channels = new Map<string, Channel>();
async function channelFor(id: string): Promise<Channel | null> {
const have = channels.get(id);
if (have !== undefined) return have;
const pin = await opts.pins.get(id);
if (pin === null) return null;
const ch: Channel = {
id,
pin,
verifier: new Ed25519Verifier(fromB64u(pin.signingKey, 32)),
publisher: null,
viewers: new Set(),
epoch: -1,
sticky: [],
backlog: [],
backlogBytes: 0,
sawKeyframe: false,
ended: false,
idleSince: now(),
};
channels.set(id, ch);
return ch;
}
function trim(ch: Channel): void {
// Keep from the keepKeyframes-th most recent keyframe onward…
let seen = 0;
let cut = 0;
for (let i = ch.backlog.length - 1; i >= 0; i--) {
if (ch.backlog[i]!.keyframe && ++seen === keepKeyframes) {
cut = i;
break;
}
}
// …then enforce the hard caps, oldest first.
let drop = cut;
let bytes = ch.backlogBytes;
for (let i = 0; i < drop; i++) bytes -= ch.backlog[i]!.frame.length;
while (drop < ch.backlog.length && (bytes > maxBytes || ch.backlog.length - drop > maxFrames)) {
bytes -= ch.backlog[drop]!.frame.length;
drop++;
}
if (drop > 0) {
ch.backlog.splice(0, drop);
ch.backlogBytes = bytes;
}
}
function deliver(v: Viewer, frame: Uint8Array, sticky: boolean, keyframe: boolean, sawKeyframe: boolean): void {
if (!sticky) {
if (v.lagging) {
// Resume only where a decoder can: a keyframe (or any frame, on a
// channel that has none — a log stream).
if (bufferedAmount(v.ws) > highWater / 4 || (sawKeyframe && !keyframe)) return;
v.lagging = false;
} else if (bufferedAmount(v.ws) > highWater) {
v.lagging = true;
return;
}
}
v.ws.send(frame as Uint8Array<ArrayBuffer>);
}
function notifyPublisher(ch: Channel): void {
ch.publisher?.send(JSON.stringify({ type: 'viewers', count: ch.viewers.size }));
}
async function accept(ch: Channel, frame: Uint8Array): Promise<string | null> {
if (frame.length > maxFrameBytes) return 'frame too large';
let f;
try {
f = decodeFrame(frame);
} catch (e) {
return (e as Error).message;
}
if (toB64u(f.header.channelId) !== ch.id) return 'frame for another channel';
if (!(await ch.verifier.verify(f.signature, f.signed))) return 'bad frame signature';
const { epoch, flags } = f.header;
if (epoch < ch.epoch) return null; // a stale frame from before a rotation: drop quietly
if (epoch > ch.epoch) {
ch.epoch = epoch;
ch.sticky = [];
ch.backlog = [];
ch.backlogBytes = 0;
ch.sawKeyframe = false;
}
const sticky = (flags & FLAG_STICKY) !== 0;
const keyframe = (flags & FLAG_KEYFRAME) !== 0;
const copy = frame.slice();
if (sticky) {
ch.sticky.push(copy);
} else {
if (keyframe) ch.sawKeyframe = true;
ch.backlog.push({ frame: copy, keyframe });
ch.backlogBytes += copy.length;
trim(ch);
}
if ((flags & FLAG_END) !== 0) ch.ended = true;
for (const v of ch.viewers) deliver(v, copy, sticky, keyframe, ch.sawKeyframe);
return null;
}
function sweep(): void {
const t = now();
for (const [id, ch] of channels) {
if (ch.publisher === null && ch.viewers.size === 0 && t - ch.idleSince > idleMs) channels.delete(id);
}
}
const timer = setInterval(sweep, 60_000);
(timer as { unref?: () => void }).unref?.();
const app = new Hono();
app.get(
'/v1/live/:channelId',
upgradeWebSocket((c) => {
const channelId = c.req.param('channelId') ?? '';
let role: Role = { kind: 'none' };
let busy: Promise<void> = Promise.resolve();
const fail = (ws: WSContext, message: string, code = 1008) => {
ws.send(JSON.stringify({ type: 'error', message }));
ws.close(code, message.slice(0, 120));
};
async function onControl(ws: WSContext, text: string): Promise<void> {
let msg: Record<string, unknown>;
try {
msg = JSON.parse(text);
} catch {
return fail(ws, 'control message is not JSON');
}
if (role.kind !== 'none') return fail(ws, 'role already chosen');
if (!/^[A-Za-z0-9_-]{22}$/.test(channelId)) return fail(ws, 'bad channel id');
if (msg.type === 'publish') {
if (typeof msg.hello !== 'string' || typeof msg.signature !== 'string') return fail(ws, 'bad publish');
let hello: Record<string, unknown>;
try {
hello = JSON.parse(msg.hello);
} catch {
return fail(ws, 'hello is not JSON');
}
if (
hello.kind !== 'shade.live-hello/v1' ||
hello.channelId !== channelId ||
typeof hello.signingKey !== 'string' ||
typeof hello.readTokenHash !== 'string' ||
typeof hello.at !== 'number' ||
Math.abs(now() - hello.at) > MAX_SKEW_MS
) {
return fail(ws, 'hello rejected');
}
let signingKey: Uint8Array;
try {
signingKey = fromB64u(hello.signingKey, 32);
fromB64u(hello.readTokenHash, 32);
if (!ed25519.verify(fromB64u(msg.signature, 64), enc.encode(msg.hello), signingKey)) {
return fail(ws, 'hello signature does not verify');
}
} catch {
return fail(ws, 'malformed hello');
}
const existing = await opts.pins.get(channelId);
if (existing !== null && existing.signingKey !== hello.signingKey) {
return fail(ws, 'channel is pinned to another key');
}
const pin: LivePin = {
channelId,
signingKey: hello.signingKey,
readTokenHash: hello.readTokenHash,
pinnedAt: existing?.pinnedAt ?? now(),
lastSeen: now(),
};
await opts.pins.put(pin);
const ch = (await channelFor(channelId))!;
ch.pin = pin;
// A reconnecting publisher replaces the stale socket.
if (ch.publisher !== null && ch.publisher !== ws) ch.publisher.close(4000, 'replaced by a newer publisher');
ch.publisher = ws;
ch.ended = false;
role = { kind: 'pub', ch };
ws.send(JSON.stringify({ type: 'ready', role: 'publisher', epoch: ch.epoch, viewers: ch.viewers.size }));
return;
}
if (msg.type === 'subscribe') {
if (typeof msg.token !== 'string') return fail(ws, 'bad subscribe');
const ch = await channelFor(channelId);
let ok = false;
if (ch !== null) {
try {
ok = equalBytes(await sha256(fromB64u(msg.token)), fromB64u(ch.pin.readTokenHash, 32));
} catch {
ok = false;
}
}
// Same refusal for "no such channel" and "wrong token".
if (ch === null || !ok) return fail(ws, 'not found', 4404);
const viewer: Viewer = { ws, lagging: false };
ch.viewers.add(viewer);
role = { kind: 'sub', ch, viewer };
ws.send(
JSON.stringify({ type: 'ready', role: 'viewer', live: ch.publisher !== null, ended: ch.ended, epoch: ch.epoch }),
);
for (const f of ch.sticky) ws.send(f as Uint8Array<ArrayBuffer>);
for (const b of ch.backlog) deliver(viewer, b.frame, false, b.keyframe, ch.sawKeyframe);
notifyPublisher(ch);
return;
}
return fail(ws, 'unknown control message');
}
return {
onMessage(evt, ws) {
// Serialise per socket: the role is decided asynchronously (a pin
// lookup), and a frame must not race past its own hello.
busy = busy.then(async () => {
if (typeof evt.data === 'string') return onControl(ws, evt.data);
const bytes = toBytes(evt.data);
if (bytes === null) return;
if (role.kind !== 'pub') return fail(ws, 'only the publisher sends frames');
const err = await accept(role.ch, bytes);
if (err !== null) fail(ws, err);
}).catch((e) => fail(ws, String((e as Error)?.message ?? e), 1011));
},
onClose(_evt, ws) {
if (role.kind === 'pub' && role.ch.publisher === ws) {
role.ch.publisher = null;
role.ch.idleSince = now();
} else if (role.kind === 'sub') {
role.ch.viewers.delete(role.viewer);
role.ch.idleSince = now();
notifyPublisher(role.ch);
}
},
};
}),
);
return {
app,
stats() {
let viewers = 0;
let backlogBytes = 0;
for (const ch of channels.values()) {
viewers += ch.viewers.size;
backlogBytes += ch.backlogBytes;
}
return { channels: channels.size, viewers, backlogBytes };
},
sweep,
stop() {
clearInterval(timer);
},
};
}

View File

@@ -0,0 +1,191 @@
/**
* HTTP routes for sealed media.
*
* PUT /v1/media/:id signed by the owner; body = the sealed SMF1 file
* HEAD /v1/media/:id size (read token if the upload set one)
* GET /v1/media/:id Range-capable read of the sealed bytes
* DELETE /v1/media/:id signed by the owner
* GET /v1/media signed by the owner; their library (ids + sizes)
*
* The server never holds a key. It checks what it can check without one —
* the footer parses, names this id, and implies exactly the uploaded size —
* so a client bug is refused at upload instead of discovered at playback.
*/
import { Hono } from 'hono';
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 type { MediaStore } from './file-store.js';
export interface MediaRoutesOptions {
/** Owner keys (base64url) allowed to upload. Unset = any key, within quota. */
allowedOwners?: readonly string[];
/** Largest single sealed file. Default 64 GiB. */
maxObjectBytes?: number;
/** Per-owner total. Default 256 GiB. */
maxOwnerBytes?: number;
/** Whole-store total. Default unlimited. */
maxTotalBytes?: number;
now?: () => number;
}
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;
try {
return toHex(await sha256(fromB64u(token))) === hash;
} catch {
return false;
}
}
export function createMediaRoutes(store: MediaStore, opts: MediaRoutesOptions = {}): Hono {
const app = new Hono();
const now = opts.now ?? Date.now;
const maxObject = opts.maxObjectBytes ?? 64 * GiB;
const maxOwner = opts.maxOwnerBytes ?? 256 * GiB;
const allowed = opts.allowedOwners !== undefined ? new Set(opts.allowedOwners) : null;
app.put('/v1/media/:id', async (c) => {
const id = c.req.param('id');
if (!ID_RE.test(id)) return c.json({ error: 'BAD_ID' }, 400);
const size = Number(c.req.header('content-length'));
if (!Number.isSafeInteger(size) || size < FOOTER_BYTES) {
return c.json({ error: 'LENGTH_REQUIRED', message: 'Content-Length of the sealed file is required' }, 411);
}
const readTokenHash = c.req.header(READ_HASH_HEADER) ?? '';
if (readTokenHash !== '' && !/^[0-9a-f]{64}$/.test(readTokenHash)) {
return c.json({ error: 'BAD_READ_HASH' }, 400);
}
const auth = verifyOwner(c.req.raw.headers, { op: 'put', id, size, readTokenHash }, now());
if (!auth.ok) return c.json({ error: 'UNAUTHORIZED', message: auth.reason }, 401);
if (allowed !== null && !allowed.has(auth.owner)) {
return c.json({ error: 'FORBIDDEN', message: 'this key may not upload here' }, 403);
}
if (size > maxObject) return c.json({ error: 'TOO_LARGE', limit: maxObject }, 413);
if ((await store.usage(auth.owner)) + size > maxOwner) {
return c.json({ error: 'QUOTA', message: 'owner quota exceeded', limit: maxOwner }, 413);
}
if (opts.maxTotalBytes !== undefined && (await store.totalBytes()) + size > opts.maxTotalBytes) {
return c.json({ error: 'STORE_FULL' }, 507);
}
if ((await store.get(id)) !== null) return c.json({ error: 'EXISTS', message: 'sealed media is immutable' }, 409);
const body = c.req.raw.body;
if (body === null) return c.json({ error: 'EMPTY_BODY' }, 400);
const up = await store.begin(id);
try {
const reader = body.getReader();
for (;;) {
const { value, done } = await reader.read();
if (done) break;
if (up.written + value.length > size) {
await reader.cancel().catch(() => {});
await up.abort();
return c.json({ error: 'LENGTH_MISMATCH', message: 'body longer than Content-Length' }, 400);
}
await up.write(value);
}
if (up.written !== size) {
await up.abort();
return c.json({ error: 'LENGTH_MISMATCH', message: `got ${up.written} of ${size} bytes` }, 400);
}
try {
const footer = decodeFooter(await up.readBack(size - FOOTER_BYTES, FOOTER_BYTES));
if (toHex(footer.mediaId) !== id) throw new Error('footer names a different media id');
if (sealedSizeFor(footer) !== size) throw new Error('footer does not match the file size');
} catch (e) {
await up.abort();
return c.json({ error: 'NOT_SMF1', message: (e as Error).message }, 422);
}
await up.commit({
id,
owner: auth.owner,
size,
readTokenHash: readTokenHash === '' ? null : readTokenHash,
createdAt: now(),
});
} catch (e) {
await up.abort().catch(() => {});
if (e instanceof MediaExistsError) return c.json({ error: 'EXISTS' }, 409);
throw e;
}
return c.json({ id, size }, 201);
});
const read = async (c: import('hono').Context, head: boolean) => {
const id = c.req.param('id') ?? '';
if (!ID_RE.test(id)) return c.json({ error: 'BAD_ID' }, 400);
const rec = await store.get(id);
// Same answer for "absent" and "wrong token": a prober learns nothing
// about which ids exist.
if (rec === null || !(await tokenMatches(rec.readTokenHash, c.req.header(READ_TOKEN_HEADER)))) {
return c.json({ error: 'NOT_FOUND' }, 404);
}
const headers: Record<string, string> = {
'accept-ranges': 'bytes',
'content-type': 'application/vnd.shade.smf1',
'cache-control': 'private, max-age=31536000, immutable',
etag: `"${id}"`,
};
const range = parseRange(c.req.header('range'), rec.size);
if (range === 'invalid') {
return new Response(null, { status: 416, headers: { ...headers, 'content-range': `bytes */${rec.size}` } });
}
const { start, end } = range ?? { start: 0, end: rec.size };
headers['content-length'] = String(end - start);
if (range !== null) headers['content-range'] = `bytes ${start}-${end - 1}/${rec.size}`;
const status = range !== null ? 206 : 200;
if (head) return new Response(null, { status, headers });
return new Response(await store.body(id, start, end), { status, headers });
};
app.on('HEAD', '/v1/media/:id', (c) => read(c, true));
app.get('/v1/media/:id', (c) => read(c, false));
app.delete('/v1/media/:id', async (c) => {
const id = c.req.param('id');
if (!ID_RE.test(id)) return c.json({ error: 'BAD_ID' }, 400);
const auth = verifyOwner(c.req.raw.headers, { op: 'delete', id }, now());
if (!auth.ok) return c.json({ error: 'UNAUTHORIZED', message: auth.reason }, 401);
const rec = await store.get(id);
if (rec === null || rec.owner !== auth.owner) return c.json({ error: 'NOT_FOUND' }, 404);
await store.delete(id);
return c.json({ id, deleted: true });
});
app.get('/v1/media', async (c) => {
const auth = verifyOwner(c.req.raw.headers, { op: 'list' }, now());
if (!auth.ok) return c.json({ error: 'UNAUTHORIZED', message: auth.reason }, 401);
const items = await store.list(auth.owner);
return c.json({
items: items.map((r) => ({ id: r.id, size: r.size, createdAt: r.createdAt })),
usage: await store.usage(auth.owner),
});
});
return app;
}

View File

@@ -0,0 +1,104 @@
/**
* Where sealed bytes come from. A reader needs exactly two things of a
* store — its size, and a byte range — which is why a film can live on the
* relay, behind nginx, in an S3 bucket or on a USB disk without the reader
* knowing which.
*/
import { MediaFormatError } from './errors.js';
export interface RangeSource {
size(): Promise<number>;
/** Exactly `length` bytes from `offset`; fewer only past the end. */
read(offset: number, length: number): Promise<Uint8Array>;
}
export class MemorySource implements RangeSource {
constructor(private readonly bytes: Uint8Array) {}
async size(): Promise<number> {
return this.bytes.length;
}
async read(offset: number, length: number): Promise<Uint8Array> {
return this.bytes.subarray(offset, offset + length);
}
}
export interface HttpRangeSourceOptions {
/** Extra headers on every request — the read token rides here. */
headers?: Record<string, string>;
fetch?: typeof fetch;
/** Attempts per range on a network error or 5xx. Default 3. */
retries?: number;
}
/**
* HTTP Range reads. Works against the Shade media routes and any server that
* honours `Range` (nginx, S3, `bun --serve`).
*/
export class HttpRangeSource implements RangeSource {
private knownSize: number | null = null;
private readonly fetchFn: typeof fetch;
private readonly headers: Record<string, string>;
private readonly retries: number;
constructor(
private readonly url: string,
opts: HttpRangeSourceOptions = {},
) {
this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
this.headers = opts.headers ?? {};
this.retries = Math.max(1, opts.retries ?? 3);
}
async size(): Promise<number> {
if (this.knownSize !== null) return this.knownSize;
const res = await this.attempt(() =>
this.fetchFn(this.url, { method: 'HEAD', headers: this.headers }),
);
const len = Number(res.headers.get('content-length'));
if (!Number.isSafeInteger(len) || len < 0) {
throw new MediaFormatError(`HEAD ${this.url} gave no usable Content-Length`);
}
this.knownSize = len;
return len;
}
async read(offset: number, length: number): Promise<Uint8Array> {
if (length === 0) return new Uint8Array(0);
const res = await this.attempt(() =>
this.fetchFn(this.url, {
headers: { ...this.headers, Range: `bytes=${offset}-${offset + length - 1}` },
}),
);
const body = new Uint8Array(await res.arrayBuffer());
if (res.status === 206) return body;
// A server that ignores Range sends the whole file with 200. Correct, if
// wasteful — slice it rather than fail, but only if it really is whole.
if (res.status === 200 && body.length >= offset + length) {
return body.subarray(offset, offset + length);
}
throw new MediaFormatError(`GET ${this.url} answered ${res.status} to a Range request`);
}
private async attempt(run: () => Promise<Response>): Promise<Response> {
let lastErr: unknown;
for (let i = 0; i < this.retries; i++) {
try {
const res = await run();
if (res.status >= 500) {
lastErr = new Error(`HTTP ${res.status} from ${this.url}`);
} else if (!res.ok) {
// 4xx will not get better by asking again — a bad token, a missing file.
throw new MediaFormatError(`HTTP ${res.status} from ${this.url}: ${await res.text().catch(() => '')}`);
} else {
return res;
}
} catch (e) {
if (e instanceof MediaFormatError) throw e;
lastErr = e;
}
await new Promise((r) => setTimeout(r, 150 * 2 ** i));
}
throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
}
}

View File

@@ -0,0 +1,133 @@
import { describe, test, expect } from 'bun:test';
import { LivePublisher, LiveSubscriber, MAX_SKIPPED_KEYS } from '../src/live/channel.js';
import { decodeFrame } from '../src/live/frame.js';
import { encodeGrant, parseGrant } from '../src/grant.js';
import type { LiveGrant } from '../src/grant.js';
import { LiveKeyError, MediaIntegrityError } from '../src/errors.js';
const text = (t: string) => ({ type: 'text' as const, text: t });
describe('live channel', () => {
test('a viewer granted at the start reads every frame, in order', async () => {
const pub = new LivePublisher({ meta: { name: 'logs' } });
const sub = new LiveSubscriber(pub.grant({ from: 'now' }));
for (let i = 0; i < 50; i++) {
const got = await sub.open(await pub.frame(text(`line ${i}`)));
expect(got?.content).toEqual(text(`line ${i}`));
expect(got?.seq).toBe(i);
}
});
test('grants survive the wire format', async () => {
const pub = new LivePublisher({ meta: { name: 'cam' } });
const g = pub.grant({ url: 'wss://relay.example/v1/live/x', readToken: new Uint8Array(32).fill(7) });
const back = parseGrant(encodeGrant(g)) as LiveGrant;
expect(back).toEqual(g);
const sub = new LiveSubscriber(back);
expect((await sub.open(await pub.frame(text('hi'))))?.content).toEqual(text('hi'));
});
test('late joiner starts at the oldest kept keyframe and reads sticky init', async () => {
const pub = new LivePublisher({ snapshots: 2 });
const frames: Uint8Array[] = [];
frames.push(await pub.frame({ type: 'init', mime: 'video/webm; codecs="vp8"', bytes: new Uint8Array([1, 2, 3]) }, { sticky: true }));
for (let i = 0; i < 30; i++) {
frames.push(await pub.frame({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: i % 10 === 0 }));
}
// Keyframes at chunk 0, 10, 20 → seqs 1, 11, 21; only the last two are kept.
const g = pub.grant();
expect(g.seq).toBe(11);
const sub = new LiveSubscriber(g);
const seen: number[] = [];
for (const f of frames) {
const r = await sub.open(f);
if (r !== null) seen.push(r.seq);
}
expect(seen[0]).toBe(0); // the sticky init, from second zero
expect(seen.slice(1)).toEqual(Array.from({ length: 20 }, (_, i) => 11 + i));
});
test('out-of-order frames decrypt once; replays are dropped', async () => {
const pub = new LivePublisher();
const sub = new LiveSubscriber(pub.grant({ from: 'now' }));
const f = [];
for (let i = 0; i < 10; i++) f.push(await pub.frame(text(String(i))));
const order = [3, 0, 9, 1, 2, 8, 4, 5, 7, 6];
for (const i of order) expect((await sub.open(f[i]!))?.seq).toBe(i);
for (const i of order) expect(await sub.open(f[i]!)).toBeNull();
});
test('forged, tampered and foreign frames are refused', async () => {
const pub = new LivePublisher();
const g = pub.grant({ from: 'now' });
const sub = new LiveSubscriber(g);
const good = await pub.frame(text('real'));
const flipped = good.slice();
flipped[60]! ^= 1;
await expect(sub.open(flipped)).rejects.toBeInstanceOf(MediaIntegrityError);
// A viewer holds the chain key — but not the signing key. A frame sealed
// correctly under the chain and signed by someone else is a forgery.
const mallory = new LivePublisher({ channelId: pub.channelId });
await expect(sub.open(await mallory.frame(text('fake')))).rejects.toBeInstanceOf(MediaIntegrityError);
const other = new LivePublisher();
await expect(sub.open(await other.frame(text('x')))).rejects.toThrow();
expect((await sub.open(good))?.content).toEqual(text('real'));
});
test('a grant cannot swap the signing key', () => {
const pub = new LivePublisher();
const sub = new LiveSubscriber(pub.grant());
const g = pub.grant();
expect(() => sub.addGrant({ ...g, signingKey: new LivePublisher().signingKey })).toThrow(MediaIntegrityError);
});
test('rotation locks out a viewer who is not re-granted', async () => {
const pub = new LivePublisher();
await pub.frame({ type: 'meta', meta: { name: 'stream' } }, { sticky: true });
const alice = new LiveSubscriber(pub.grant({ from: 'now' }));
const bob = new LiveSubscriber(pub.grant({ from: 'now' }));
expect((await bob.open(await pub.frame(text('before'))))?.content).toEqual(text('before'));
await alice.open(await pub.frame(text('b2')));
const resealed = await pub.rotate();
expect(resealed.length).toBe(1);
expect(decodeFrame(resealed[0]!).header.epoch).toBe(1);
alice.addGrant(pub.grant({ from: 'now' }));
alice.forgetBefore(1);
// seq 0 of epoch 1 is the resealed sticky meta.
expect((await alice.open(resealed[0]!))?.content).toEqual({ type: 'meta', meta: { name: 'stream' } });
const after = await pub.frame(text('after'));
expect((await alice.open(after))?.content).toEqual(text('after'));
await expect(bob.open(after)).rejects.toBeInstanceOf(LiveKeyError);
});
test('a large gap is bridged and keys stay bounded', async () => {
const pub = new LivePublisher();
const sub = new LiveSubscriber(pub.grant({ from: 'now' }));
const frames = [];
for (let i = 0; i < MAX_SKIPPED_KEYS + 500; i++) frames.push(await pub.frame(text(String(i))));
expect((await sub.open(frames[frames.length - 1]!))?.seq).toBe(frames.length - 1);
// The oldest skipped keys were not kept…
expect(await sub.open(frames[0]!)).toBeNull();
// …the recent ones were.
expect((await sub.open(frames[frames.length - 2]!))?.seq).toBe(frames.length - 2);
}, 30_000);
test('every content kind round-trips', async () => {
const pub = new LivePublisher();
const sub = new LiveSubscriber(pub.grant({ from: 'now' }));
const kinds = [
text('æøå 🎬'),
{ type: 'binary' as const, bytes: new Uint8Array([0, 255]) },
{ type: 'init' as const, mime: 'audio/webm; codecs="opus"', bytes: new Uint8Array([9]) },
{ type: 'chunk' as const, bytes: new Uint8Array(1000).fill(3) },
{ type: 'image' as const, mime: 'image/jpeg', bytes: new Uint8Array([0xff, 0xd8, 0xff]) },
{ type: 'meta' as const, meta: { name: 'x', mime: 'video/webm' } },
{ type: 'end' as const },
];
for (const k of kinds) expect((await sub.open(await pub.frame(k)))?.content).toEqual(k);
});
});

View File

@@ -0,0 +1,197 @@
import { describe, test, expect } from 'bun:test';
import {
MediaReader,
MediaSealer,
sealMediaBytes,
sealMediaStream,
MIN_SEGMENT_SIZE,
FOOTER_BYTES,
decodeFooter,
} from '../src/sealed.js';
import { MemorySource } from '../src/source.js';
import { MediaFormatError, MediaIntegrityError } from '../src/errors.js';
const S = MIN_SEGMENT_SIZE;
function pattern(n: number, seed = 1): Uint8Array {
const out = new Uint8Array(n);
let x = seed >>> 0 || 1;
for (let i = 0; i < n; i++) {
x ^= x << 13;
x ^= x >>> 17;
x ^= x << 5;
out[i] = x & 0xff;
}
return out;
}
async function sealed(plain: Uint8Array, segmentSize = S) {
const { bytes, result } = await sealMediaBytes(plain, {
segmentSize,
meta: { mime: 'video/webm', name: 'test.webm' },
});
return { bytes, result, keys: { mediaId: result.mediaId, mediaKey: result.mediaKey, rootDigest: result.rootDigest } };
}
describe('SMF1 round trip', () => {
for (const n of [0, 1, S - 1, S, S + 1, 3 * S, 3 * S + 17]) {
test(`${n} bytes`, async () => {
const plain = pattern(n, n + 1);
const { bytes, result, keys } = await sealed(plain);
expect(result.plaintextSize).toBe(n);
expect(result.sealedSize).toBe(bytes.length);
expect(result.segmentCount).toBe(Math.max(1, Math.ceil(n / S)));
const r = await MediaReader.open(new MemorySource(bytes), keys);
expect(r.size).toBe(n);
expect(r.meta).toEqual({ mime: 'video/webm', name: 'test.webm' });
expect(await r.read(0, n)).toEqual(plain);
});
}
test('random access matches the plaintext at every boundary', async () => {
const plain = pattern(5 * S + 123, 7);
const { bytes, keys } = await sealed(plain);
const r = await MediaReader.open(new MemorySource(bytes), keys, { cacheSegments: 0 });
const points = [0, 1, S - 1, S, S + 1, 2 * S - 3, 4 * S, 5 * S, 5 * S + 122];
for (const a of points) {
for (const len of [1, 2, S, 2 * S + 5, 10 * S]) {
expect(await r.read(a, len)).toEqual(plain.subarray(a, Math.min(plain.length, a + len)));
}
}
expect((await r.read(plain.length, 10)).length).toBe(0);
});
test('stream() yields the requested range', async () => {
const plain = pattern(9 * S + 5, 3);
const { bytes, keys } = await sealed(plain);
const r = await MediaReader.open(new MemorySource(bytes), keys, { maxSegmentsPerFetch: 2 });
const got: Uint8Array[] = [];
for await (const c of r.stream(S + 7, 7 * S + 1)) got.push(c);
expect(Buffer.concat(got)).toEqual(Buffer.from(plain.subarray(S + 7, 7 * S + 1)));
});
test('streaming seal in odd chunks produces a readable file of the same size', async () => {
const plain = pattern(4 * S + 999, 11);
async function* chunks() {
let off = 0;
let k = 1;
while (off < plain.length) {
const n = Math.min(plain.length - off, (k++ * 977) % (2 * S) + 1);
yield plain.subarray(off, off + n);
off += n;
}
}
const { stream, result } = sealMediaStream(chunks(), { segmentSize: S });
const parts: Uint8Array[] = [];
for await (const p of stream) parts.push(p);
const bytes = new Uint8Array(Buffer.concat(parts));
const res = await result;
expect(res.sealedSize).toBe(bytes.length);
const r = await MediaReader.open(new MemorySource(bytes), {
mediaId: res.mediaId,
mediaKey: res.mediaKey,
rootDigest: res.rootDigest,
});
expect(await r.read(0, plain.length)).toEqual(plain);
});
test('every seal draws a fresh key and id', async () => {
const a = new MediaSealer({ segmentSize: S });
const b = new MediaSealer({ segmentSize: S });
expect(a.mediaKey).not.toEqual(b.mediaKey);
expect(a.mediaId).not.toEqual(b.mediaId);
});
});
describe('SMF1 tamper resistance', () => {
test('a flipped ciphertext byte fails that segment', async () => {
const plain = pattern(3 * S, 5);
const { bytes, keys } = await sealed(plain);
const bad = bytes.slice();
bad[S + 100]! ^= 1; // inside segment 1
const r = await MediaReader.open(new MemorySource(bad), keys);
expect(await r.read(0, 10)).toEqual(plain.subarray(0, 10));
await expect(r.read(S + 50, 10)).rejects.toBeInstanceOf(MediaIntegrityError);
});
test('swapping two segments is caught', async () => {
const plain = pattern(3 * S, 9);
const { bytes, keys } = await sealed(plain);
const seg = S + 16;
const bad = bytes.slice();
bad.set(bytes.subarray(0, seg), seg);
bad.set(bytes.subarray(seg, 2 * seg), 0);
const r = await MediaReader.open(new MemorySource(bad), keys);
await expect(r.read(0, 1)).rejects.toBeInstanceOf(MediaIntegrityError);
});
test('a key holder who rewrites the table is caught by the root digest', async () => {
// Without the root digest a forged table could vouch for forged segments;
// the grant pins the trailer, so even a holder of the key cannot.
const plain = pattern(2 * S, 2);
const { bytes, keys } = await sealed(plain);
const bad = bytes.slice();
bad[bad.length - FOOTER_BYTES - 1]! ^= 1; // last byte of the table
await expect(MediaReader.open(new MemorySource(bad), keys)).rejects.toBeInstanceOf(
MediaIntegrityError,
);
// …and without a root it still fails, at the segment.
const r = await MediaReader.open(new MemorySource(bad), { mediaId: keys.mediaId, mediaKey: keys.mediaKey });
await expect(r.read(S, 1)).rejects.toBeInstanceOf(MediaIntegrityError);
});
test('truncation and a shrunk footer both fail closed', async () => {
const plain = pattern(3 * S, 4);
const { bytes, keys } = await sealed(plain);
await expect(
MediaReader.open(new MemorySource(bytes.subarray(0, bytes.length - 1)), keys),
).rejects.toThrow();
// Rewrite the footer to claim two segments: the second becomes "last",
// which its AAD says it is not.
const f = decodeFooter(bytes.subarray(bytes.length - FOOTER_BYTES));
expect(f.plaintextSize).toBe(3 * S);
const footer = bytes.slice(bytes.length - FOOTER_BYTES);
new DataView(footer.buffer).setBigUint64(12, BigInt(2 * S), false);
const r = await MediaReader.open(
new MemorySource(
new Uint8Array(
Buffer.concat([
bytes.subarray(0, 2 * (S + 16)),
bytes.subarray(3 * (S + 16), 3 * (S + 16) + 16 + 32 * 2), // meta + 2 digests
footer,
]),
),
),
{ mediaId: keys.mediaId, mediaKey: keys.mediaKey },
).catch((e) => e);
if (r instanceof Error) {
expect(r).toBeInstanceOf(Error);
} else {
await expect(r.read(S, 1)).rejects.toBeInstanceOf(MediaIntegrityError);
}
});
test('wrong key, wrong id, bad magic', async () => {
const { bytes, keys } = await sealed(pattern(100));
await expect(
MediaReader.open(new MemorySource(bytes), { ...keys, mediaKey: new Uint8Array(32) }),
).rejects.toBeInstanceOf(MediaIntegrityError);
await expect(
MediaReader.open(new MemorySource(bytes), { ...keys, mediaId: new Uint8Array(16) }),
).rejects.toBeInstanceOf(MediaIntegrityError);
const bad = bytes.slice();
bad[bad.length - 1] = 0;
await expect(MediaReader.open(new MemorySource(bad), keys)).rejects.toBeInstanceOf(
MediaFormatError,
);
});
test('invalid metadata is refused at seal time', async () => {
await expect(sealMediaBytes(new Uint8Array(1), { meta: { mime: 'not a mime' } })).rejects.toBeInstanceOf(
MediaFormatError,
);
await expect(sealMediaBytes(new Uint8Array(1), { meta: { name: 'a\nb' } })).rejects.toBeInstanceOf(
MediaFormatError,
);
});
});

View File

@@ -0,0 +1,252 @@
import { describe, test, expect, afterAll } from 'bun:test';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { websocket } from 'hono/bun';
import { Hono } from 'hono';
import {
createMediaRoutes,
createLiveRelay,
FileMediaStore,
MemoryLivePinStore,
FileLivePinStore,
parseRange,
} from '../src/server.js';
import {
MediaClient,
OwnerKey,
openGrant,
sealMediaBytes,
LivePublisher,
LivePublishClient,
LiveWatchClient,
encodeGrant,
parseGrant,
MIN_SEGMENT_SIZE,
} from '../src/index.js';
import type { LiveGrant, ReceivedFrame } from '../src/index.js';
const dirs: string[] = [];
async function tempDir(): Promise<string> {
const d = await mkdtemp(join(tmpdir(), 'shade-media-'));
dirs.push(d);
return d;
}
afterAll(async () => {
for (const d of dirs) await rm(d, { recursive: true, force: true });
});
function serve(app: Hono) {
const server = Bun.serve({ port: 0, fetch: (req, srv) => app.fetch(req, { server: srv }), websocket });
return { server, base: `http://localhost:${server.port}` };
}
function pattern(n: number): Uint8Array {
const out = new Uint8Array(n);
for (let i = 0; i < n; i++) out[i] = (i * 31 + (i >> 8)) & 0xff;
return out;
}
const until = async (cond: () => boolean, ms = 3000) => {
const t = Date.now();
while (!cond()) {
if (Date.now() - t > ms) throw new Error('timed out');
await new Promise((r) => setTimeout(r, 10));
}
};
describe('parseRange', () => {
test('forms', () => {
expect(parseRange('bytes=0-9', 100)).toEqual({ start: 0, end: 10 });
expect(parseRange('bytes=90-', 100)).toEqual({ start: 90, end: 100 });
expect(parseRange('bytes=-5', 100)).toEqual({ start: 95, end: 100 });
expect(parseRange('bytes=50-500', 100)).toEqual({ start: 50, end: 100 });
expect(parseRange('bytes=100-', 100)).toBe('invalid');
expect(parseRange('bytes=0-1,5-6', 100)).toBe('invalid');
expect(parseRange(null, 100)).toBeNull();
});
});
describe('media routes over real HTTP', () => {
test('upload, ranged playback, token, list, delete — and it survives a restart', async () => {
const dir = await tempDir();
const app = new Hono();
app.route('/', createMediaRoutes(new FileMediaStore(dir)));
const { server, base } = serve(app);
try {
const owner = OwnerKey.generate();
const client = new MediaClient(base, owner);
const plain = pattern(10 * MIN_SEGMENT_SIZE + 77);
const grant = await client.uploadBytes(plain, {
segmentSize: MIN_SEGMENT_SIZE,
meta: { mime: 'video/webm', name: 'Film.webm' },
});
// The grant crosses a Shade session as JSON.
const g2 = parseGrant(encodeGrant(grant));
if (g2.kind !== 'shade.media-grant/v1') throw new Error('kind');
const reader = await openGrant(g2);
expect(reader.meta.name).toBe('Film.webm');
expect(await reader.read(5 * MIN_SEGMENT_SIZE - 3, 2 * MIN_SEGMENT_SIZE)).toEqual(
plain.subarray(5 * MIN_SEGMENT_SIZE - 3, 7 * MIN_SEGMENT_SIZE - 3),
);
// Without the token: the same 404 as for an id that does not exist.
const bare = await fetch(grant.url!);
expect(bare.status).toBe(404);
// Immutable.
const { bytes, result } = await sealMediaBytes(new Uint8Array(10));
await client.putSealed(result, bytes);
await expect(client.putSealed(result, bytes)).rejects.toThrow(/409/);
expect((await client.list()).items.length).toBe(2);
// Restart: a fresh store over the same directory serves the same film.
const app2 = new Hono();
app2.route('/', createMediaRoutes(new FileMediaStore(dir)));
const s2 = serve(app2);
try {
const r2 = await openGrant(g2, { url: grant.url!.replace(base, s2.base) });
expect(await r2.read(0, plain.length)).toEqual(plain);
} finally {
s2.server.stop(true);
}
// Someone else cannot delete it.
const mallory = new MediaClient(base, OwnerKey.generate());
expect(await mallory.delete(grant.mediaId)).toBe(false);
expect(await client.delete(grant.mediaId)).toBe(true);
expect((await fetch(grant.url!, { headers: { 'x-shade-read': 'x' } })).status).toBe(404);
} 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();
const app = new Hono();
app.route('/', createMediaRoutes(new FileMediaStore(dir), { allowedOwners: [allowed.id], maxObjectBytes: 1 << 20 }));
const { server, base } = serve(app);
try {
const { bytes, result } = await sealMediaBytes(new Uint8Array(100));
await expect(new MediaClient(base, OwnerKey.generate()).putSealed(result, bytes)).rejects.toThrow(/403/);
// Right owner, garbage body of the right length.
const junk = new Uint8Array(bytes.length);
const id = Buffer.from(result.mediaId).toString('hex');
const res = await fetch(`${base}/v1/media/${id}`, {
method: 'PUT',
headers: { 'content-length': String(junk.length), ...allowed.headers({ op: 'put', id, size: junk.length, readTokenHash: '' }) },
body: junk,
});
expect(res.status).toBe(422);
// Signature for a different size.
const res2 = await fetch(`${base}/v1/media/${id}`, {
method: 'PUT',
headers: { 'content-length': String(bytes.length), ...allowed.headers({ op: 'put', id, size: 1, readTokenHash: '' }) },
body: bytes,
});
expect(res2.status).toBe(401);
const big = await sealMediaBytes(new Uint8Array(2 << 20));
await expect(new MediaClient(base, allowed).putSealed(big.result, big.bytes)).rejects.toThrow(/413/);
await new MediaClient(base, allowed).putSealed(result, bytes);
} finally {
server.stop(true);
}
});
});
describe('live relay over real WebSockets', () => {
test('publish → relay → viewers, with late join from backlog and sticky init', async () => {
const relay = createLiveRelay({ pins: new MemoryLivePinStore(), backlogKeyframes: 2 });
const { server, base } = serve(relay.app);
try {
const pub = new LivePublisher({ meta: { name: 'cam' } });
const client = new LivePublishClient({ relay: base, publisher: pub, readToken: new Uint8Array(32).fill(1) });
await client.whenReady();
await client.send({ type: 'init', mime: 'video/webm; codecs="vp8"', bytes: new Uint8Array([0xaa]) }, { sticky: true });
for (let i = 0; i < 30; i++) {
await client.send({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: i % 10 === 0 });
}
await client.flush();
const early: ReceivedFrame[] = [];
const grant = parseGrant(encodeGrant(client.grant('oldest'))) as LiveGrant;
const viewer = new LiveWatchClient(grant, { onFrame: (f) => void early.push(f) });
// Backlog: init (sticky) + frames from the 2nd-latest keyframe (chunk 10, seq 11).
await until(() => early.length === 21);
expect(early[0]!.content.type).toBe('init');
expect(early[1]!.seq).toBe(11);
// Live frames arrive in order after the backlog.
for (let i = 30; i < 40; i++) await client.send({ type: 'chunk', bytes: new Uint8Array([i]) });
await until(() => early.length === 31);
expect(early.map((f) => f.seq).slice(1)).toEqual(Array.from({ length: 30 }, (_, i) => 11 + i));
expect(relay.stats().viewers).toBe(1);
// A viewer with a wrong token is turned away.
const errors: string[] = [];
const bad = new LiveWatchClient({ ...grant, readToken: new Uint8Array(32) }, {
onFrame: () => {
throw new Error('should not get frames');
},
onError: (e) => errors.push(e.message),
});
await until(() => errors.length > 0);
bad.close();
// Someone else cannot take over the channel id.
const thief = new LivePublisher({ channelId: pub.channelId });
const terr: string[] = [];
const tc = new LivePublishClient({ relay: base, publisher: thief, readToken: new Uint8Array(32), onError: (m) => terr.push(m) });
await until(() => terr.length > 0);
expect(terr[0]).toMatch(/pinned/);
tc.close();
await client.end();
await until(() => early.at(-1)?.content.type === 'end');
viewer.close();
} finally {
relay.stop();
server.stop(true);
}
});
test('rotation: a re-granted viewer continues, the other is locked out; pins persist', async () => {
const dir = await tempDir();
const pins = new FileLivePinStore(join(dir, 'pins.json'));
const relay = createLiveRelay({ pins });
const { server, base } = serve(relay.app);
try {
const pub = new LivePublisher();
const client = new LivePublishClient({ relay: base, publisher: pub, readToken: new Uint8Array(32).fill(2) });
await client.whenReady();
await client.send({ type: 'meta', meta: { name: 'logs' } }, { sticky: true });
const a: ReceivedFrame[] = [];
const b: ReceivedFrame[] = [];
const bErr: Error[] = [];
const va = new LiveWatchClient(client.grant('now'), { onFrame: (f) => void a.push(f) });
const vb = new LiveWatchClient(client.grant('now'), { onFrame: (f) => void b.push(f), onError: (e) => bErr.push(e) });
await until(() => a.length === 1 && b.length === 1);
await client.send({ type: 'text', text: 'one' });
await until(() => a.length === 2 && b.length === 2);
await client.rotate();
va.addGrant(client.grant('now'));
await client.send({ type: 'text', text: 'two' });
await until(() => a.some((f) => f.content.type === 'text' && f.content.text === 'two'));
await until(() => bErr.length >= 1);
expect(b.some((f) => f.content.type === 'text' && f.content.text === 'two')).toBe(false);
va.close();
vb.close();
client.close();
expect((await new FileLivePinStore(join(dir, 'pins.json')).get(Buffer.from(pub.channelId).toString('base64url')))?.signingKey).toBeDefined();
} finally {
relay.stop();
server.stop(true);
}
});
});

View File

@@ -0,0 +1 @@
{"extends":"../../tsconfig.json","compilerOptions":{"outDir":"dist","rootDir":"src","lib":["ES2022","DOM"]},"include":["src"]}