Files
Shade/docs/media.md

290 lines
15 KiB
Markdown
Raw Normal View History

# `@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 |