fix(media,server): films over 128 MiB were refused; docs/media.md
Bun.serve refuses request bodies over 128 MiB by default, so every film larger than that got a 413 from both `shade media serve` and the container. The cap is now raised to the media object limit only when media is mounted, and every other route gets an explicit 128 MiB bodyLimit — several read the whole body before checking its size, so Bun's default was their only guard. Verified on the standalone process: 300 MiB sealed film round trip identical; a 200 MiB POST to a prekey route still 413. docs/media.md: formats (SMF1, SLF1, grants) as the cross-language contract, key schedule, what the relay learns, design notes, limits. bench/media.ts: throughput, seek latency, live fan-out → media.chart.json. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
7
bench/media-relay.ts
Normal file
7
bench/media-relay.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
/** A live relay in its own process for bench/media.ts; prints its port. */
|
||||
import { websocket } from 'hono/bun';
|
||||
import { createLiveRelay, MemoryLivePinStore } from '../packages/shade-media/src/server.js';
|
||||
|
||||
const relay = createLiveRelay({ pins: new MemoryLivePinStore(), viewerHighWater: 32 * 1024 * 1024 });
|
||||
const server = Bun.serve({ port: 0, fetch: (req, srv) => relay.app.fetch(req, { server: srv }), websocket, idleTimeout: 0 });
|
||||
console.log(server.port);
|
||||
236
bench/media.ts
Normal file
236
bench/media.ts
Normal file
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* @shade/media benchmarks — what streaming under Shade costs.
|
||||
*
|
||||
* Run: bun bench/media.ts [--big-mib 1024] [--viewers 1,10,50,200]
|
||||
*
|
||||
* 1. Seal and read throughput, sealed file on disk (1 MiB segments).
|
||||
* 2. The same read over HTTP Range from the real media routes.
|
||||
* 3. Seek: time to the first decrypted byte at a random offset over HTTP.
|
||||
* 4. Live fan-out: one publisher, N viewers, relay in its own process —
|
||||
* delivered fraction and end-to-end latency (publish → decrypted).
|
||||
*
|
||||
* Writes bench/media-results.json (raw numbers) and bench/media.chart.json
|
||||
* (charts for the log post, `scaffold-agent chart block`).
|
||||
*/
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { createWriteStream } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { Hono } from 'hono';
|
||||
import { websocket } from 'hono/bun';
|
||||
import { sealFile, FileSource } from '../packages/shade-media/src/node.js';
|
||||
import { MediaReader } from '../packages/shade-media/src/sealed.js';
|
||||
import { createMediaRoutes, FileMediaStore, mediaMaxRequestBody } from '../packages/shade-media/src/server.js';
|
||||
import { MediaClient, openGrant } from '../packages/shade-media/src/client.js';
|
||||
import { OwnerKey } from '../packages/shade-media/src/owner.js';
|
||||
import { LivePublisher } from '../packages/shade-media/src/live/channel.js';
|
||||
import { LivePublishClient, LiveWatchClient } from '../packages/shade-media/src/live/client.js';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const flag = (k: string, d: string) => {
|
||||
const i = args.indexOf(`--${k}`);
|
||||
return i >= 0 ? args[i + 1]! : d;
|
||||
};
|
||||
const BIG_MIB = Number(flag('big-mib', '1024'));
|
||||
const VIEWERS = flag('viewers', '1,10,50,200').split(',').map(Number);
|
||||
const MiB = 1024 * 1024;
|
||||
const now = () => performance.now();
|
||||
const pct = (xs: number[], p: number) => {
|
||||
const s = [...xs].sort((a, b) => a - b);
|
||||
return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]!;
|
||||
};
|
||||
const round = (x: number, d = 1) => Math.round(x * 10 ** d) / 10 ** d;
|
||||
|
||||
async function writeRandomFile(path: string, mib: number): Promise<void> {
|
||||
// Random bytes (incompressible, like video). One 1 MiB block reused with a
|
||||
// counter stamped in, so generation is not the thing being measured.
|
||||
const block = new Uint8Array(MiB);
|
||||
globalThis.crypto.getRandomValues(block.subarray(0, 65536));
|
||||
for (let i = 65536; i < MiB; i += 65536) block.copyWithin(i, 0, 65536);
|
||||
const ws = createWriteStream(path);
|
||||
for (let i = 0; i < mib; i++) {
|
||||
new DataView(block.buffer).setUint32(0, i);
|
||||
if (!ws.write(Buffer.from(block))) await new Promise<void>((r) => ws.once('drain', () => r()));
|
||||
}
|
||||
await new Promise<void>((r) => ws.end(() => r()));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'shade-media-bench-'));
|
||||
const results: Record<string, unknown> = { at: new Date().toISOString(), bun: Bun.version, bigMiB: BIG_MIB };
|
||||
try {
|
||||
// ─── 1. Seal + local read ──────────────────────────────────
|
||||
const plain = join(dir, 'film.bin');
|
||||
const sealedPath = join(dir, 'film.smf');
|
||||
await writeRandomFile(plain, BIG_MIB);
|
||||
let t = now();
|
||||
const res = await sealFile(plain, sealedPath, { meta: { mime: 'video/mp4', name: 'film.bin' } });
|
||||
const sealMs = now() - t;
|
||||
const keys = { mediaId: res.mediaId, mediaKey: res.mediaKey, rootDigest: res.rootDigest };
|
||||
t = now();
|
||||
const reader = await MediaReader.open(new FileSource(sealedPath), keys, { cacheSegments: 0, maxSegmentsPerFetch: 8 });
|
||||
let n = 0;
|
||||
for await (const c of reader.stream()) n += c.length;
|
||||
const readMs = now() - t;
|
||||
if (n !== BIG_MIB * MiB) throw new Error(`read ${n} bytes`);
|
||||
const overhead = (res.sealedSize - res.plaintextSize) / res.plaintextSize;
|
||||
results.seal = { mibPerSec: round((BIG_MIB / sealMs) * 1000), ms: round(sealMs), overheadPct: round(overhead * 100, 4) };
|
||||
results.readDisk = { mibPerSec: round((BIG_MIB / readMs) * 1000), ms: round(readMs) };
|
||||
console.log(`seal ${BIG_MIB} MiB: ${round((BIG_MIB / sealMs) * 1000)} MiB/s size overhead ${round(overhead * 100, 4)} %`);
|
||||
console.log(`read ${BIG_MIB} MiB (disk): ${round((BIG_MIB / readMs) * 1000)} MiB/s`);
|
||||
|
||||
// ─── 2 + 3. Over HTTP ──────────────────────────────────────
|
||||
const app = new Hono();
|
||||
app.route('/', createMediaRoutes(new FileMediaStore(join(dir, 'store'))));
|
||||
const server = Bun.serve({ port: 0, fetch: (req, srv) => app.fetch(req, { server: srv }), websocket, idleTimeout: 0, maxRequestBodySize: mediaMaxRequestBody() });
|
||||
const base = `http://localhost:${server.port}`;
|
||||
try {
|
||||
const client = new MediaClient(base, OwnerKey.generate());
|
||||
t = now();
|
||||
const grant = await client.putSealed(res, Bun.file(sealedPath));
|
||||
const uploadMs = now() - t;
|
||||
t = now();
|
||||
const hr = await openGrant(grant, { cacheSegments: 0, maxSegmentsPerFetch: 8 });
|
||||
n = 0;
|
||||
for await (const c of hr.stream()) n += c.length;
|
||||
const httpMs = now() - t;
|
||||
results.upload = { mibPerSec: round((BIG_MIB / uploadMs) * 1000) };
|
||||
results.readHttp = { mibPerSec: round((BIG_MIB / httpMs) * 1000), ms: round(httpMs) };
|
||||
console.log(`upload (localhost): ${round((BIG_MIB / uploadMs) * 1000)} MiB/s read over HTTP Range: ${round((BIG_MIB / httpMs) * 1000)} MiB/s`);
|
||||
|
||||
// Seek: a fresh reader per probe would measure open(); one reader with
|
||||
// no cache measures what a seek in a playing film costs.
|
||||
const opened: number[] = [];
|
||||
for (let i = 0; i < 10; i++) {
|
||||
t = now();
|
||||
await openGrant(grant);
|
||||
opened.push(now() - t);
|
||||
}
|
||||
const seeks: number[] = [];
|
||||
const sr = await openGrant(grant, { cacheSegments: 0 });
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const off = Math.floor(Math.random() * (BIG_MIB * MiB - 65536));
|
||||
t = now();
|
||||
await sr.read(off, 65536);
|
||||
seeks.push(now() - t);
|
||||
}
|
||||
results.open = { p50: round(pct(opened, 50), 2), p95: round(pct(opened, 95), 2) };
|
||||
results.seek = { p50: round(pct(seeks, 50), 2), p95: round(pct(seeks, 95), 2), max: round(Math.max(...seeks), 2) };
|
||||
console.log(`open (footer+trailer): p50 ${round(pct(opened, 50), 2)} ms seek→first byte: p50 ${round(pct(seeks, 50), 2)} ms, p95 ${round(pct(seeks, 95), 2)} ms`);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
|
||||
// ─── 4. Live fan-out ───────────────────────────────────────
|
||||
const relayProc = Bun.spawn(['bun', join(import.meta.dir, 'media-relay.ts')], { stdout: 'pipe', stderr: 'inherit' });
|
||||
const portLine = await new Response(relayProc.stdout).body!.getReader().read();
|
||||
const relayBase = `http://localhost:${new TextDecoder().decode(portLine.value).trim()}`;
|
||||
const live: Array<{ viewers: number; delivered: number; p50: number; p95: number; max: number }> = [];
|
||||
try {
|
||||
for (const v of VIEWERS) {
|
||||
const fps = 10;
|
||||
const frameBytes = 32 * 1024; // ≈ 2.6 Mbit/s, a 720p stream
|
||||
const seconds = 6;
|
||||
const pub = new LivePublisher();
|
||||
const pc = new LivePublishClient({ relay: relayBase, publisher: pub, readToken: new Uint8Array(32).fill(1) });
|
||||
await pc.whenReady();
|
||||
const grant = pc.grant('now');
|
||||
const lat: number[] = [];
|
||||
let got = 0;
|
||||
const viewers: LiveWatchClient[] = [];
|
||||
let ready = 0;
|
||||
for (let i = 0; i < v; i++) {
|
||||
viewers.push(
|
||||
new LiveWatchClient(grant, {
|
||||
onState: (s) => {
|
||||
if (s === 'live') ready++;
|
||||
},
|
||||
onFrame: (f) => {
|
||||
got++;
|
||||
lat.push(Date.now() - f.timestamp);
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
while (ready < v) await Bun.sleep(20);
|
||||
const payload = new Uint8Array(frameBytes);
|
||||
globalThis.crypto.getRandomValues(payload.subarray(0, 65536 > frameBytes ? frameBytes : 65536));
|
||||
const total = fps * seconds;
|
||||
const start = Date.now();
|
||||
for (let i = 0; i < total; i++) {
|
||||
await pc.send({ type: 'chunk', bytes: payload }, { keyframe: i % fps === 0 });
|
||||
const due = start + ((i + 1) * 1000) / fps;
|
||||
const wait = due - Date.now();
|
||||
if (wait > 0) await Bun.sleep(wait);
|
||||
}
|
||||
await Bun.sleep(1500);
|
||||
const delivered = got / (total * v);
|
||||
const row = { viewers: v, delivered: round(delivered * 100, 2), p50: pct(lat, 50), p95: pct(lat, 95), max: Math.max(...lat) };
|
||||
live.push(row);
|
||||
console.log(`live ${v} viewer(s): delivered ${row.delivered} %, latency p50 ${row.p50} ms, p95 ${row.p95} ms, max ${row.max} ms`);
|
||||
for (const w of viewers) w.close();
|
||||
pc.close();
|
||||
await Bun.sleep(300);
|
||||
}
|
||||
} finally {
|
||||
relayProc.kill();
|
||||
}
|
||||
results.live = live;
|
||||
|
||||
await writeFile(join(import.meta.dir, 'media-results.json'), `${JSON.stringify(results, null, 2)}\n`);
|
||||
const r = results as any;
|
||||
const charts = [
|
||||
{
|
||||
type: 'bar',
|
||||
title: 'Sealed media throughput (MiB/s)',
|
||||
subtitle: `${BIG_MIB} MiB of incompressible data, 1 MiB segments, one core`,
|
||||
y: { label: 'MiB/s', min: 0 },
|
||||
note: `Bun ${Bun.version}; HTTP is localhost through the real media routes; size overhead ${r.seal.overheadPct} %`,
|
||||
source: { path: 'media-results.json' },
|
||||
series: [
|
||||
{
|
||||
name: 'MiB/s',
|
||||
data: [
|
||||
['seal (disk → disk)', r.seal.mibPerSec],
|
||||
['read + verify (disk)', r.readDisk.mibPerSec],
|
||||
['upload (HTTP PUT)', r.upload.mibPerSec],
|
||||
['read + verify (HTTP Range)', r.readHttp.mibPerSec],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'bar',
|
||||
title: 'Seeking in a sealed film over HTTP (ms)',
|
||||
subtitle: 'open = footer + trailer + root check; seek = first 64 KiB at a random offset, no cache',
|
||||
y: { label: 'ms', min: 0 },
|
||||
note: 'n = 10 opens, 100 seeks; localhost',
|
||||
source: { path: 'media-results.json' },
|
||||
series: [
|
||||
{ name: 'p50', data: [['open', r.open.p50], ['seek', r.seek.p50]] },
|
||||
{ name: 'p95', data: [['open', r.open.p95], ['seek', r.seek.p95]] },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'line',
|
||||
title: 'Live fan-out: latency publish → decrypted, by viewers',
|
||||
subtitle: '10 fps × 32 KiB frames (≈ 2.6 Mbit/s) for 6 s; relay in its own process, all viewers in one',
|
||||
x: { label: 'viewers' },
|
||||
y: { label: 'ms', min: 0 },
|
||||
note: `delivered: ${live.map((l) => `${l.viewers} → ${l.delivered} %`).join(', ')}. Every viewer verifies every signature and decrypts every frame, in one process, so the curve is mostly the viewers' CPU, not the relay's.`,
|
||||
source: { path: 'media-results.json' },
|
||||
series: [
|
||||
{ name: 'p50', data: live.map((l) => [l.viewers, l.p50]) },
|
||||
{ name: 'p95', data: live.map((l) => [l.viewers, l.p95]) },
|
||||
],
|
||||
},
|
||||
];
|
||||
await writeFile(join(import.meta.dir, 'media.chart.json'), `${JSON.stringify(charts, null, 2)}\n`);
|
||||
console.log('wrote bench/media-results.json and bench/media.chart.json');
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
await main();
|
||||
process.exit(0);
|
||||
289
docs/media.md
Normal file
289
docs/media.md
Normal file
@@ -0,0 +1,289 @@
|
||||
# `@shade/media` — streaming under Shade
|
||||
|
||||
V4.15. Films, videos, songs, images, and live streams of logs, text, video and
|
||||
audio, all end-to-end encrypted. Whoever stores or relays the bytes cannot read
|
||||
them, and whoever holds a key cannot forge them for anyone else.
|
||||
|
||||
There are two shapes, because "a film" and "a log" are different problems:
|
||||
|
||||
| | Sealed media (SMF1) | Live channel (SLF1) |
|
||||
|---|---|---|
|
||||
| What | a file that exists in full: film, episode, photo, song, document | a stream that is still being made: `tail -f`, a camera, a broadcast |
|
||||
| Read how | random access over HTTP Range, so you can seek | in order over a WebSocket, joining late from a backlog |
|
||||
| Stored where | any dumb store: the relay, nginx, S3, a USB disk | the relay holds minutes of ciphertext for late joiners, then lets it go |
|
||||
| Keys | one random key per file | Sender Keys: a hash chain per epoch, every frame signed |
|
||||
| Plays in | `<video>`/`<audio>`/`<img>` through a Service Worker; ExoPlayer via `MediaReader.inputStream` | `<video>` through Media Source Extensions; a log view; the terminal |
|
||||
|
||||
Both hand their keys to a viewer as a **grant**: a small JSON message sent over an
|
||||
existing Shade session (Double Ratchet, so it is authenticated and forward-secret),
|
||||
or carried in the `#shade=` fragment of a link for a device with no session.
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
# A relay: sealed store + live relay + the /watch page, on one port.
|
||||
shade media serve --port 3910 --dir /srv/shade-media
|
||||
|
||||
# A film. Seals in one streaming pass, uploads, prints a watch link.
|
||||
shade media put Film.mkv --server https://relay.example
|
||||
# → https://relay.example/watch/#shade=eyJraW5kIjoic2hhZGUubWVkaWEtZ3JhbnQ…
|
||||
|
||||
# Back on disk, decrypted and verified.
|
||||
shade media get '<link>' -o Film.mkv
|
||||
|
||||
# Live logs.
|
||||
tail -f /var/log/app.log | shade live text --server https://relay.example --name "api logs" --channel ~/.config/shade/api-logs.json
|
||||
shade live watch '<link>' # in a terminal — or open the link in a browser
|
||||
|
||||
# Live video (and audio) from anything ffmpeg can read.
|
||||
ffmpeg -re -i camera.mp4 -c:v libvpx -deadline realtime -g 30 -c:a libopus \
|
||||
-f webm -live 1 -cluster_time_limit 1000 - \
|
||||
| shade live webm --server https://relay.example --name "Kamera 1"
|
||||
```
|
||||
|
||||
`--channel <file>` keeps a live channel's identity across restarts: the link keeps
|
||||
working, and each run starts a new epoch.
|
||||
|
||||
The owner key (who may upload, delete and open live channels) is created the first
|
||||
time it is needed, under `$XDG_CONFIG_HOME/shade/media-owner.key` (mode 0600).
|
||||
`shade media whoami` prints its public half.
|
||||
|
||||
### In the Shade container
|
||||
|
||||
```
|
||||
SHADE_MEDIA_DIR=/data/media # enables media; required (no in-memory fallback)
|
||||
SHADE_MEDIA_OWNERS=<key>,<key> # who may upload / open channels (`shade media whoami`)
|
||||
SHADE_DISABLE_MEDIA=1 # optional: off entirely
|
||||
```
|
||||
|
||||
Routes: `/v1/media/:id`, `/v1/live/:channelId` (WebSocket), `/watch/`.
|
||||
|
||||
**There is no in-memory fallback**, for the vault's reason: a library that lives in
|
||||
RAM accepts every upload and loses all of it on the next redeploy, without anything
|
||||
failing. With `SHADE_MEDIA_DIR` unset the routes are not mounted, and the log says so.
|
||||
With `SHADE_MEDIA_OWNERS` empty, the relay serves what it has and accepts nothing new.
|
||||
`*` admits every key, which is only safe on a private network.
|
||||
|
||||
## In code
|
||||
|
||||
```ts
|
||||
import { MediaClient, OwnerKey, openGrant, encodeGrant, parseGrant } from '@shade/media';
|
||||
import { sealFile } from '@shade/media/node';
|
||||
|
||||
// Owner side: seal and upload, then grant a peer over the Shade session.
|
||||
const sealed = await sealFile('Film.mkv', '/tmp/film.smf', { meta: { mime: 'video/x-matroska', name: 'Film' } });
|
||||
const grant = await new MediaClient(relay, owner).putSealed(sealed, Bun.file('/tmp/film.smf'));
|
||||
await shade.send('bob', encodeGrant(grant));
|
||||
|
||||
// Viewer side: open what was granted and read any range.
|
||||
const g = parseGrant(await shade.receive('alice', envelope));
|
||||
const film = await openGrant(g); // fetches the footer + trailer only
|
||||
const bytes = await film.read(3_000_000_000, 1 << 20); // 1 MiB from 3 GB in
|
||||
```
|
||||
|
||||
Live:
|
||||
|
||||
```ts
|
||||
import { LivePublisher, LivePublishClient, LiveWatchClient } from '@shade/media';
|
||||
|
||||
const pub = new LivePublishClient({ relay, publisher: new LivePublisher({ meta: { name: 'logs' } }), readToken, owner });
|
||||
await pub.whenReady();
|
||||
await shade.send('bob', encodeGrant(pub.grant('oldest'))); // backlog from the oldest kept keyframe
|
||||
await pub.send({ type: 'text', text: 'line\n' }, { keyframe: true });
|
||||
|
||||
// bob
|
||||
new LiveWatchClient(grant, { onFrame: (f) => console.log(f.content) });
|
||||
```
|
||||
|
||||
In a page, `installMediaWorker('/sw.js')` registers the decrypting worker, and
|
||||
`keyring.add(grant)` returns a URL to put in `<video src>`. `new LivePlayer(video, grant)`
|
||||
plays a live WebM channel. The relay serves a ready-made page at `/watch/` that does
|
||||
both from a link.
|
||||
|
||||
On Android/JVM, `no.zyon.shade.media`: `Grants.fromCapabilityUrl(link)`,
|
||||
`(grant as MediaGrant).open()` returns a `MediaReader` with `read(offset, len)` and
|
||||
`inputStream()`. `LiveSubscriber(grant).open(frame)` handles live frames, and
|
||||
`MediaSealer` and `LivePublisher` write both formats byte for byte the way TS does.
|
||||
|
||||
## SMF1 — the sealed file (cross-language contract)
|
||||
|
||||
All integers are big-endian.
|
||||
|
||||
```
|
||||
segment[0] … segment[n-1] AES-256-GCM(segKey) of `segmentSize` plaintext bytes each;
|
||||
the last holds the rest (0 … segmentSize). n ≥ 1.
|
||||
meta AES-256-GCM(metaKey) of UTF-8 JSON (MediaMeta)
|
||||
table n × SHA-256(sealed segment i)
|
||||
footer (64 bytes) "SMF1" | 0x01 | flags=0 | 0 0 | segmentSize u32 |
|
||||
plaintextSize u64 | metaLen u32 | mediaId (16) |
|
||||
20 × 0 | "SMF1"
|
||||
```
|
||||
|
||||
```
|
||||
mediaKey 32 random bytes, fresh for every seal (never caller-chosen)
|
||||
mediaId 16 random bytes
|
||||
segKey = HKDF-SHA256(ikm = mediaKey, salt = mediaId, info = "shade-media/v1\0segment", 32)
|
||||
metaKey = HKDF-SHA256(ikm = mediaKey, salt = mediaId, info = "shade-media/v1\0meta", 32)
|
||||
nonce_i = u32(0) ‖ u64(i) aad_i = "SMF1" ‖ mediaId ‖ u64(i) ‖ u8(i == n-1)
|
||||
nonce_meta = u32(1) ‖ u64(0) aad_meta = "SMF1-meta" ‖ mediaId
|
||||
rootDigest = SHA-256(meta ‖ table ‖ footer)
|
||||
```
|
||||
|
||||
- **The trailer is at the end** so a writer can seal a stream of unknown length in one
|
||||
pass with one segment of memory, and upload as it goes. A reader fetches the last 64
|
||||
bytes, then the trailer, which is about 130 KiB for a 4 GB film.
|
||||
- **Deterministic nonces are safe** because no key is ever used for two files. The
|
||||
sealer draws the key itself; the only way to pin one is `@shade/media/testing`, for
|
||||
vectors.
|
||||
- **`last` is in the AAD**, so truncation fails closed. Cutting the file makes a
|
||||
segment that was not the last one claim to be.
|
||||
- **Two layers of integrity.** AEAD protects against the store. The table, pinned by
|
||||
`rootDigest` in the grant, also protects against *other key holders*. Without it,
|
||||
a viewer who holds the key could re-encrypt forged segments and serve them to a
|
||||
third viewer through a store it controls. The reader checks every segment's hash
|
||||
before decrypting it.
|
||||
- **Strict parsing.** Unknown flags, non-zero reserved bytes, a size that does not
|
||||
match the footer, or a `metaLen` over 64 KiB are all refused, never guessed at.
|
||||
- Default segment size is 1 MiB (allowed: 4 KiB to 16 MiB). The overhead is 48 bytes
|
||||
per segment plus the trailer, about 0.005 %.
|
||||
|
||||
`MediaMeta` holds `mime`, `name`, `durationMs`, `width`, `height`, `createdAt` and
|
||||
`extra` (string → string). It is validated on both sides, and a writer serialises it
|
||||
in that key order so two languages produce the same bytes.
|
||||
|
||||
## SLF1 — the live frame (cross-language contract)
|
||||
|
||||
```
|
||||
0..4 "SLF1"
|
||||
4 version = 1
|
||||
5 flags: 0x01 sticky · 0x02 keyframe · 0x04 end (other bits refused)
|
||||
6..8 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 (aad = bytes 0..48)
|
||||
+64 Ed25519 signature over everything before it
|
||||
```
|
||||
|
||||
Payload (inside the ciphertext): one kind byte, then `1` text (UTF-8), `2` binary,
|
||||
`3` init (u8 mimeLen, mime, bytes), `4` media chunk, `5` image (mime-prefixed like
|
||||
init), `6` meta (JSON), or `7` end.
|
||||
|
||||
Keys follow Signal's Sender Keys, 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-SHA256(ck[i], 0x01) used for exactly one frame, then wiped
|
||||
ck[i+1] = HMAC-SHA256(ck[i], 0x02) one-way: ck[i] cannot be recovered
|
||||
nonce = u32(epoch) ‖ u64(seq)
|
||||
```
|
||||
|
||||
- **Every frame is signed** with the channel's Ed25519 key. All viewers hold the
|
||||
same chain, so without a signature any of them could forge frames to the others
|
||||
through the relay. The signing key's public half travels in the grant, and the
|
||||
grant travels over an authenticated Shade session; that is what ties a channel
|
||||
to a person. The relay checks signatures too, against the key the channel was
|
||||
pinned to on first use, so it never stores or forwards anything a viewer would
|
||||
reject.
|
||||
- **Sticky frames** (codec init, the channel's own description) are sealed under
|
||||
`stickyKey`, not the chain. The relay keeps them for the whole epoch, so a viewer
|
||||
who joins an hour in can still decode the init segment sent at second zero.
|
||||
- **Joining late.** The publisher keeps chain snapshots at recent keyframes (64 by
|
||||
default). A grant carries the chain key at one of them: `oldest` (the most backlog
|
||||
the relay still has), `latest`, or `now`. A viewer can never derive anything before
|
||||
its grant's point.
|
||||
- **Out of order and gaps.** A subscriber derives forward up to 100 000 frames and
|
||||
keeps keys for up to 2 000 skipped ones, evicting the oldest first. Replays are
|
||||
dropped quietly.
|
||||
- **Removing a viewer** means a new epoch: fresh seed, `seq` back to 0, and the sticky
|
||||
frames resealed. Everyone who stays gets a new grant; anyone left out is out.
|
||||
- **Link mode** (`channelSecret`): `epochSeed(e) = HKDF(channelSecret, salt =
|
||||
channelId, "shade-live/v1\0epoch" ‖ u32(e))`. A grant made with `{ link: true }`
|
||||
carries the secret, so its holder can follow every later epoch without a new grant.
|
||||
That is how a link survives publisher restarts and the CLI's scheduled rotation
|
||||
(every 20 000 frames, so catching up stays cheap). The trade-off is that there is
|
||||
no forward secrecy against a link holder and no way to remove one short of a new
|
||||
channel. Session grants never carry the secret, so they stay per-epoch either way.
|
||||
|
||||
## Grants
|
||||
|
||||
```jsonc
|
||||
// sealed file
|
||||
{ "kind": "shade.media-grant/v1", "mediaId": "<b64u 16>", "key": "<b64u 32>",
|
||||
"root": "<hex 32>", "url": "https://…/v1/media/<hex id>", "token": "<b64u>", "meta": { … } }
|
||||
// live channel
|
||||
{ "kind": "shade.live-grant/v1", "channelId": "<b64u 16>", "signingKey": "<b64u 32>",
|
||||
"epoch": 0, "seq": 1234, "chainKey": "<b64u 32>", "stickyKey": "<b64u 32>",
|
||||
"channelSecret": "<b64u 32, link grants only>", "url": "wss://…", "token": "<b64u>" }
|
||||
```
|
||||
|
||||
`token` is the relay's read token. It is a door, not a key: the relay stores only its
|
||||
SHA-256 and answers a wrong token and a missing id with the same 404, so a prober
|
||||
cannot tell which ids exist. A link is `…/watch/#shade=<b64u(grant JSON)>`. The
|
||||
fragment is never sent to a server, and the page removes it from the address bar
|
||||
once it has read it.
|
||||
|
||||
## What the relay learns
|
||||
|
||||
- **Sealed:** that an opaque id exists, its size (to within a segment), when it was
|
||||
uploaded, which owner key uploaded it, and which ranges get fetched when. Range
|
||||
patterns reveal viewing behaviour such as seeking and how far someone watched,
|
||||
but not content.
|
||||
- **Live:** that a channel is active, the frame sizes and timing (the bitrate
|
||||
envelope of a video, the burstiness of a log), keyframe and sticky flags, epoch and
|
||||
seq, and how many viewers are connected.
|
||||
- **Never:** content, file names, titles, MIME types, or who a viewer is. Viewers
|
||||
present a token, not an identity.
|
||||
|
||||
Padding sizes or frame timing would hide more, at a real cost in bandwidth. It is not
|
||||
done in v1. A deployment that needs it can pad above this layer.
|
||||
|
||||
## Testing and vectors
|
||||
|
||||
- `packages/shade-media/tests/`: format round trips at every boundary, tamper
|
||||
(flipped bytes, swapped segments, forged table, truncation), live chains (late
|
||||
join, reordering, replay, forged frames from a key holder, rotation lock-out, link
|
||||
mode across restarts), the HTTP routes and relay over real sockets, and the WebM
|
||||
splitter on real ffmpeg output.
|
||||
- `test-vectors/media.json` (`bun run scripts/generate-vectors.ts media.json`): the
|
||||
Kotlin port reads every vector and reproduces every sealed file and signed frame
|
||||
byte for byte (`MediaVectorTest`).
|
||||
- `bench/media.ts`: throughput, seek latency and live fan-out, written as
|
||||
`bench/media.chart.json`.
|
||||
|
||||
## Design notes
|
||||
|
||||
- **Why not HLS/DASH with AES-128?** Their key delivery is a URL the player fetches,
|
||||
so whoever runs the key server can read everything, and segments are not
|
||||
authenticated. SMF1 needs only a Range-capable store and puts the key in a grant.
|
||||
Because the Service Worker presents the decrypted file as an ordinary one, the
|
||||
browser's native player handles seeking, buffering and codecs.
|
||||
- **Why not `ShadeStream` (V4.11) for broadcast?** ShadeStream is a pairwise Double
|
||||
Ratchet, ideal for one server streaming a console to one client. A broadcast to N
|
||||
viewers through a relay would need N encryptions per frame, and the relay could not
|
||||
keep one backlog for late joiners. Sender Keys encrypt once and sign once. The
|
||||
signature restores what the pairwise ratchet gave for free: only the publisher can
|
||||
speak.
|
||||
- **Chrome's WebM rule.** Chrome's MSE demuxer rejects a cluster in which any block,
|
||||
on any track, has an earlier timecode than the block before it. ffmpeg's live
|
||||
muxer writes exactly that when Opus timestamps round a millisecond below an
|
||||
interleaved video frame. The splitter sorts blocks within each cluster (stable, so
|
||||
each track keeps its order). The cluster keeps its size and every block keeps its
|
||||
bytes.
|
||||
- **Bun 1.3.5.** `new Response(Bun.file(p).slice(a, b))` sent the whole file in
|
||||
answer to a Range request when the file was large. The store therefore reads the
|
||||
range itself.
|
||||
|
||||
## Limits (defaults)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| sealed file | 64 GiB per object, 256 GiB per owner (`MediaRoutesOptions`) |
|
||||
| metadata | 64 KiB |
|
||||
| live frame payload | 16 MiB |
|
||||
| live backlog | 3 keyframes, at most 32 MiB / 5000 frames per channel |
|
||||
| slow viewer | over 8 MiB buffered: frames dropped until it drains and a keyframe comes |
|
||||
| channels held | 1000 live channels per relay; pins idle for 30 days are dropped |
|
||||
@@ -104,7 +104,7 @@ const err = (s: string) => process.stderr.write(`${s}\n`);
|
||||
|
||||
async function mediaServe(flags: Flags): Promise<number> {
|
||||
const { websocket } = await import('hono/bun');
|
||||
const { createMediaService, parseOwners } = await import('./server.js');
|
||||
const { createMediaService, parseOwners, mediaMaxRequestBody } = await import('./server.js');
|
||||
const dir = str(flags, 'dir') ?? process.env.SHADE_MEDIA_DIR ?? './shade-media-data';
|
||||
const port = Number(str(flags, 'port') ?? process.env.PORT ?? 3910);
|
||||
// Closed by default: this machine's own owner key, plus any listed. `--open`
|
||||
@@ -120,6 +120,8 @@ async function mediaServe(flags: Flags): Promise<number> {
|
||||
fetch: (req, srv) => svc.app.fetch(req, { server: srv }),
|
||||
websocket,
|
||||
idleTimeout: 0,
|
||||
// Every route here bounds its own body; the 128 MiB default would refuse films.
|
||||
maxRequestBodySize: mediaMaxRequestBody(),
|
||||
});
|
||||
err(`shade media: serving on http://localhost:${server.port} (data in ${dir})`);
|
||||
err(owners === 'any' ? 'open relay: any key may upload and publish' : `owners: ${owners.join(', ')}`);
|
||||
|
||||
@@ -6,5 +6,5 @@ export { createLiveRelay, FileLivePinStore, MemoryLivePinStore } from './server/
|
||||
export type { LiveRelay, LiveRelayOptions, LivePin, LivePinStore } from './server/live-relay.js';
|
||||
export { createWatchRoutes } from './server/watch-routes.js';
|
||||
export type { WatchRoutesOptions } from './server/watch-routes.js';
|
||||
export { createMediaService, parseOwners } from './server/service.js';
|
||||
export { createMediaService, parseOwners, mediaMaxRequestBody, MEDIA_BODY_ROUTE } from './server/service.js';
|
||||
export type { MediaService, MediaServiceOptions } from './server/service.js';
|
||||
|
||||
@@ -34,6 +34,20 @@ export interface MediaService {
|
||||
stop(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Largest request body a server mounting media must accept: the largest
|
||||
* sealed file plus headroom. Bun.serve refuses anything over 128 MiB by
|
||||
* default, which would turn every film into a 413 — pass this as
|
||||
* `maxRequestBodySize`, and keep the default cap on every other route
|
||||
* (see `MEDIA_BODY_ROUTE`).
|
||||
*/
|
||||
export function mediaMaxRequestBody(opts: { media?: { maxObjectBytes?: number } } = {}): number {
|
||||
return (opts.media?.maxObjectBytes ?? 64 * 1024 ** 3) + 1024 * 1024;
|
||||
}
|
||||
|
||||
/** Path prefix whose bodies the media routes bound themselves (PUT of a sealed file). */
|
||||
export const MEDIA_BODY_ROUTE = '/v1/media/';
|
||||
|
||||
export function createMediaService(opts: MediaServiceOptions): MediaService {
|
||||
const owners = opts.owners === 'any' ? undefined : opts.owners;
|
||||
const app = new Hono();
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Hono } from 'hono';
|
||||
import { bodyLimit } from 'hono/body-limit';
|
||||
import { mediaMaxRequestBody } from '@shade/media/server';
|
||||
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
||||
import {
|
||||
createInboxRoutes,
|
||||
@@ -233,6 +235,18 @@ if (disableRateLimit) {
|
||||
// Compose the full app: metrics middleware + health + metrics + prekey routes
|
||||
const app = new Hono();
|
||||
app.use('*', metricsMiddleware());
|
||||
|
||||
// Bun.serve's own 128 MiB request cap is raised when media is mounted (a film
|
||||
// is gigabytes), so it can no longer be what protects every other route —
|
||||
// several read the whole body before checking its size. Keep that cap here,
|
||||
// explicitly, for everything but the media upload route, which counts its
|
||||
// bytes against Content-Length itself.
|
||||
const DEFAULT_MAX_BODY = 128 * 1024 * 1024;
|
||||
const generalBodyLimit = bodyLimit({
|
||||
maxSize: DEFAULT_MAX_BODY,
|
||||
onError: (c) => c.json({ error: 'PAYLOAD_TOO_LARGE', limit: DEFAULT_MAX_BODY }, 413),
|
||||
});
|
||||
app.use('*', (c, next) => (c.req.path.startsWith('/v1/media/') ? next() : generalBodyLimit(c, next)));
|
||||
app.route('/', createHealthRoutes(store, VERSION));
|
||||
app.route('/', createMetricsRoutes());
|
||||
app.route('/', createOpenApiRoutes());
|
||||
@@ -379,6 +393,7 @@ const server = Bun.serve({
|
||||
port,
|
||||
fetch: (req, srv) => app.fetch(req, srv),
|
||||
websocket: bridgeRoutes.websocket as any,
|
||||
...(mediaService !== null ? { maxRequestBodySize: mediaMaxRequestBody() } : {}),
|
||||
});
|
||||
|
||||
// ─── Graceful shutdown ───────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user