feat(media,server): media in the Shade container, owner-only uploads and channels

- createMediaService: sealed store + live relay + /watch in one mount, used
  by both `shade media serve` and standalone.ts
- SHADE_MEDIA_DIR enables it (no in-memory fallback, like the vault);
  SHADE_MEDIA_OWNERS lists who may upload and open live channels
- live publishers co-sign their hello with an owner key; a relay with an
  owner list refuses everyone else, and the client stops on that refusal
  instead of reconnecting forever
- relay caps live channels held at once; `shade media whoami`

Verified against the real standalone process: film round trip identical,
stranger gets 403 / refused channel, live logs and browser playback.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 21:10:43 +02:00
parent d117397b36
commit df3ca685c5
10 changed files with 225 additions and 23 deletions

View File

@@ -103,27 +103,26 @@ const err = (s: string) => process.stderr.write(`${s}\n`);
// ─── media ───────────────────────────────────────────────────
async function mediaServe(flags: Flags): Promise<number> {
const { Hono } = await import('hono');
const { cors } = await import('hono/cors');
const { websocket } = await import('hono/bun');
const { createMediaRoutes, FileMediaStore, createLiveRelay, FileLivePinStore, createWatchRoutes } = await import('./server.js');
const { createMediaService, parseOwners } = 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);
const app = new Hono();
app.use('/v1/media/*', cors({ origin: '*', allowHeaders: ['range', 'x-shade-read'], exposeHeaders: ['content-range', 'content-length', 'accept-ranges'] }));
app.route('/', createMediaRoutes(new FileMediaStore(join(dir, 'media'))));
const relay = createLiveRelay({ pins: new FileLivePinStore(join(dir, 'live-pins.json')) });
app.route('/', relay.app);
app.route('/', createWatchRoutes({ dev: flags.dev === true }));
app.get('/health', (c) => c.json({ ok: true, live: relay.stats() }));
// Closed by default: this machine's own owner key, plus any listed. `--open`
// lets every key in — for a relay on a private network only.
const own = (await loadOwnerKey()).id;
const listed = parseOwners(str(flags, 'owners') ?? process.env.SHADE_MEDIA_OWNERS);
const owners = flags.open === true || listed === 'any' ? 'any' : [own, ...listed];
const svc = createMediaService({ dir, owners, dev: flags.dev === true });
svc.app.get('/health', (c) => c.json({ ok: true, live: svc.relay.stats() }));
const server = Bun.serve({
port,
hostname: str(flags, 'host') ?? '0.0.0.0',
fetch: (req, srv) => app.fetch(req, { server: srv }),
fetch: (req, srv) => svc.app.fetch(req, { server: srv }),
websocket,
idleTimeout: 0,
});
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(', ')}`);
await new Promise(() => {});
return 0;
}
@@ -251,6 +250,7 @@ async function startPublishing(flags: Flags, meta: MediaMeta): Promise<{ client:
relay: server,
publisher: pub,
readToken,
owner: await loadOwnerKey(),
onViewers: (n) => err(`viewers: ${n}`),
onError: (m) => err(`relay: ${m}`),
onState: (s) => {
@@ -343,8 +343,10 @@ async function liveWatch(pos: string[]): Promise<number> {
}
export const MEDIA_HELP = `
media serve [--port 3910] [--dir ./shade-media-data]
Run a media relay: sealed store, live relay, watch page
media serve [--port 3910] [--dir ./shade-media-data] [--owners k1,k2] [--open]
Run a media relay: sealed store, live relay, watch page.
Only this machine's key (and --owners) may upload/publish.
media whoami Print this machine's owner key (to add to a relay's --owners)
media put <file> --server URL [--name N] [--mime M] [--public] [--json]
Seal a film/video/image/song, upload it, print a watch link
media get <link> [-o file|-]
@@ -367,6 +369,9 @@ export async function runMediaCli(group: 'media' | 'live', argv: string[]): Prom
switch (sub) {
case 'serve':
return await mediaServe(flags);
case 'whoami':
out((await loadOwnerKey()).id);
return 0;
case 'put':
return await mediaPut(pos, flags);
case 'get':

View File

@@ -13,6 +13,7 @@ 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';
import type { OwnerKey } from '../owner.js';
export type LiveState = 'connecting' | 'live' | 'waiting' | 'reconnecting' | 'closed';
@@ -45,6 +46,8 @@ export interface PublishOptions {
publisher: LivePublisher;
/** Bearer token viewers must present. Its hash goes to the relay; the token goes in grants. */
readToken: Uint8Array;
/** Co-signs the hello, for relays that only accept known owners. */
owner?: OwnerKey;
/** Frames held while disconnected. Older ones are dropped first. Default 2000. */
queueLimit?: number;
onState?: (s: LiveState) => void;
@@ -64,18 +67,23 @@ export class LivePublishClient {
private readTokenHash: Promise<Uint8Array>;
private openedOnce: Promise<void>;
private resolveOpened!: () => void;
private rejectOpened!: (e: Error) => void;
private lastError = '';
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.openedOnce = new Promise((resolve, reject) => {
this.resolveOpened = resolve;
this.rejectOpened = reject;
});
// A caller that never awaits whenReady() must not see an unhandled rejection.
this.openedOnce.catch(() => {});
this.connect();
}
/** Resolves once the relay has accepted the publisher the first time. */
/** Resolves once the relay has accepted the publisher the first time; rejects if it refuses for good. */
whenReady(): Promise<void> {
return this.openedOnce;
}
@@ -133,7 +141,15 @@ export class LivePublishClient {
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) }));
const owner = this.opts.owner;
ws.send(
JSON.stringify({
type: 'publish',
hello: hello.body,
signature: toB64u(hello.signature),
...(owner !== undefined ? { owner: owner.id, ownerSignature: owner.signPublish(hello.body) } : {}),
}),
);
};
ws.onmessage = (ev) => {
if (typeof ev.data !== 'string') return;
@@ -149,12 +165,21 @@ export class LivePublishClient {
} else if (msg.type === 'viewers') {
this.opts.onViewers?.(msg.count ?? 0);
} else if (msg.type === 'error') {
this.opts.onError?.(msg.message ?? 'relay error');
this.lastError = msg.message ?? 'relay error';
this.opts.onError?.(this.lastError);
}
};
ws.onclose = () => {
ws.onclose = (ev) => {
this.ready = false;
if (this.closed) return;
// 1008 is the relay saying no — not an owner, channel pinned to another
// key, a bad hello. Asking again will not change the answer.
if (ev.code === 1008) {
this.closed = true;
this.rejectOpened(new Error(`relay refused the channel: ${this.lastError || ev.reason || 'policy violation'}`));
this.opts.onState?.('closed');
return;
}
this.opts.onState?.('reconnecting');
setTimeout(() => this.connect(), this.retry.next());
};

View File

@@ -23,7 +23,8 @@ 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' };
| { op: 'list' }
| { op: 'publish'; hello: string };
export function ownerMessage(o: OwnerOp, at: number): Uint8Array {
switch (o.op) {
@@ -33,6 +34,9 @@ export function ownerMessage(o: OwnerOp, at: number): Uint8Array {
return enc.encode(`shade.media-delete/v1|${o.id}|${at}`);
case 'list':
return enc.encode(`shade.media-list/v1|${at}`);
case 'publish':
// The hello carries its own timestamp; the owner vouches for exactly it.
return enc.encode(`shade.live-publish/v1|${o.hello}`);
}
}
@@ -56,6 +60,11 @@ export class OwnerKey {
return toB64u(this.publicKey);
}
/** Co-sign a live channel's hello, for relays that only let known owners publish. */
signPublish(hello: string): string {
return toB64u(ed25519.sign(ownerMessage({ op: 'publish', hello }, 0), this.secret));
}
headers(o: OwnerOp, at = Date.now()): Record<string, string> {
return {
[OWNER_HEADER]: this.id,
@@ -89,3 +98,12 @@ export function verifyOwner(
}
return { ok: true, owner };
}
/** Verify an owner's co-signature on a live hello. */
export function verifyPublishOwner(owner: string, signature: string, hello: string): boolean {
try {
return ed25519.verify(fromB64u(signature, 64), ownerMessage({ op: 'publish', hello }, 0), fromB64u(owner, 32));
} catch {
return false;
}
}

View File

@@ -6,3 +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 type { MediaService, MediaServiceOptions } from './server/service.js';

View File

@@ -32,7 +32,7 @@ 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 { MAX_SKEW_MS, verifyPublishOwner } from '../owner.js';
import { Ed25519Verifier } from '../ed25519.js';
export interface LivePin {
@@ -106,6 +106,13 @@ export class FileLivePinStore implements LivePinStore {
export interface LiveRelayOptions {
pins: LivePinStore;
/**
* Owner keys (base64url) allowed to publish. A publisher then co-signs its
* hello with one of them. Unset = anyone may open a channel.
*/
allowedOwners?: readonly string[];
/** Channels held at once (live state, not pins). Default 1000. */
maxChannels?: number;
/** Keyframes of history kept for late joiners. Default 3. */
backlogKeyframes?: number;
/** Byte cap on a channel's backlog (sticky frames excluded). Default 32 MiB. */
@@ -173,12 +180,18 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
const idleMs = opts.idleRetentionMs ?? 10 * 60 * 1000;
const maxFrameBytes = opts.maxFrameBytes ?? 16 * 1024 * 1024 + 256;
const channels = new Map<string, Channel>();
const allowedOwners = opts.allowedOwners !== undefined ? new Set(opts.allowedOwners) : null;
const maxChannels = opts.maxChannels ?? 1000;
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;
if (channels.size >= maxChannels) {
sweep();
if (channels.size >= maxChannels) throw new Error('relay is at its channel limit');
}
const ch: Channel = {
id,
pin,
@@ -335,6 +348,13 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
} catch {
return fail(ws, 'malformed hello');
}
if (allowedOwners !== null) {
const owner = typeof msg.owner === 'string' ? msg.owner : '';
const osig = typeof msg.ownerSignature === 'string' ? msg.ownerSignature : '';
if (!allowedOwners.has(owner) || !verifyPublishOwner(owner, osig, msg.hello)) {
return fail(ws, 'this relay only accepts channels from its owners');
}
}
const existing = await opts.pins.get(channelId);
if (existing !== null && existing.signingKey !== hello.signingKey) {
return fail(ws, 'channel is pinned to another key');

View File

@@ -0,0 +1,76 @@
/**
* Everything a relay needs to serve media, in one mount: the sealed store,
* the live relay and the watch page — used by `shade media serve` and by
* the Shade container (`SHADE_MEDIA_DIR`), so both behave identically.
*/
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { join } from 'node:path';
import { FileMediaStore } from './file-store.js';
import { createMediaRoutes } from './media-routes.js';
import type { MediaRoutesOptions } from './media-routes.js';
import { createLiveRelay, FileLivePinStore } from './live-relay.js';
import type { LiveRelay, LiveRelayOptions } from './live-relay.js';
import { createWatchRoutes } from './watch-routes.js';
export interface MediaServiceOptions {
/** Persistent directory: `media/` for sealed files, `live-pins.json` for channel pins. */
dir: string;
/**
* Owner keys (base64url) allowed to upload and to open live channels.
* `'any'` lets every key in (bounded by quotas) — only for a private relay.
*/
owners: readonly string[] | 'any';
media?: Omit<MediaRoutesOptions, 'allowedOwners'>;
live?: Omit<LiveRelayOptions, 'pins' | 'allowedOwners'>;
/** Re-bundle the watch page per request. */
dev?: boolean;
}
export interface MediaService {
app: Hono;
relay: LiveRelay;
stop(): void;
}
export function createMediaService(opts: MediaServiceOptions): MediaService {
const owners = opts.owners === 'any' ? undefined : opts.owners;
const app = new Hono();
// Sealed bytes are safe to hand to any origin — the key is not here — and
// a player on another site needs CORS to make its Range requests.
app.use(
'/v1/media/*',
cors({
origin: '*',
allowHeaders: ['range', 'x-shade-read'],
exposeHeaders: ['content-range', 'content-length', 'accept-ranges'],
}),
);
app.route(
'/',
createMediaRoutes(new FileMediaStore(join(opts.dir, 'media')), {
...opts.media,
...(owners !== undefined ? { allowedOwners: owners } : {}),
}),
);
const relay = createLiveRelay({
...opts.live,
pins: new FileLivePinStore(join(opts.dir, 'live-pins.json')),
...(owners !== undefined ? { allowedOwners: owners } : {}),
});
app.route('/', relay.app);
app.route('/', createWatchRoutes({ dev: opts.dev === true }));
return { app, relay, stop: () => relay.stop() };
}
/** Parse `SHADE_MEDIA_OWNERS`-style config: comma-separated keys, or `*` for any. */
export function parseOwners(raw: string | undefined): readonly string[] | 'any' {
if (raw === undefined) return [];
if (raw.trim() === '*') return 'any';
const keys = raw.split(',').map((s) => s.trim()).filter((s) => s !== '');
for (const k of keys) {
if (!/^[A-Za-z0-9_-]{43}$/.test(k)) throw new Error(`not an owner key (43 base64url chars): ${k}`);
}
return keys;
}

View File

@@ -222,9 +222,8 @@ describe('live relay over real WebSockets', () => {
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);
await expect(tc.whenReady()).rejects.toThrow(/pinned/);
expect(terr[0]).toMatch(/pinned/);
tc.close();
await client.end();
await until(() => early.at(-1)?.content.type === 'end');
@@ -235,6 +234,29 @@ describe('live relay over real WebSockets', () => {
}
});
test('a relay with owners only takes channels co-signed by one of them', async () => {
const owner = OwnerKey.generate();
const relay = createLiveRelay({ pins: new MemoryLivePinStore(), allowedOwners: [owner.id] });
const { server, base } = serve(relay.app);
try {
const errs: string[] = [];
const stranger = new LivePublishClient({ relay: base, publisher: new LivePublisher(), readToken: new Uint8Array(32), onError: (m) => errs.push(m) });
await expect(stranger.whenReady()).rejects.toThrow(/owners/);
expect(errs[0]).toMatch(/owners/);
// Another owner's co-signature on this hello does not count either.
const errs2: string[] = [];
const wrong = new LivePublishClient({ relay: base, publisher: new LivePublisher(), readToken: new Uint8Array(32), owner: OwnerKey.generate(), onError: (m) => errs2.push(m) });
await until(() => errs2.length > 0);
wrong.close();
const ok = new LivePublishClient({ relay: base, publisher: new LivePublisher(), readToken: new Uint8Array(32), owner });
await ok.whenReady();
ok.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'));