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:
1
bun.lock
1
bun.lock
@@ -244,6 +244,7 @@
|
|||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/inbox-server": "workspace:*",
|
"@shade/inbox-server": "workspace:*",
|
||||||
"@shade/key-transparency": "workspace:*",
|
"@shade/key-transparency": "workspace:*",
|
||||||
|
"@shade/media": "workspace:*",
|
||||||
"@shade/observability": "workspace:*",
|
"@shade/observability": "workspace:*",
|
||||||
"@shade/storage-sqlite": "workspace:*",
|
"@shade/storage-sqlite": "workspace:*",
|
||||||
"@shade/vault": "workspace:*",
|
"@shade/vault": "workspace:*",
|
||||||
|
|||||||
@@ -103,27 +103,26 @@ const err = (s: string) => process.stderr.write(`${s}\n`);
|
|||||||
// ─── media ───────────────────────────────────────────────────
|
// ─── media ───────────────────────────────────────────────────
|
||||||
|
|
||||||
async function mediaServe(flags: Flags): Promise<number> {
|
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 { 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 dir = str(flags, 'dir') ?? process.env.SHADE_MEDIA_DIR ?? './shade-media-data';
|
||||||
const port = Number(str(flags, 'port') ?? process.env.PORT ?? 3910);
|
const port = Number(str(flags, 'port') ?? process.env.PORT ?? 3910);
|
||||||
const app = new Hono();
|
// Closed by default: this machine's own owner key, plus any listed. `--open`
|
||||||
app.use('/v1/media/*', cors({ origin: '*', allowHeaders: ['range', 'x-shade-read'], exposeHeaders: ['content-range', 'content-length', 'accept-ranges'] }));
|
// lets every key in — for a relay on a private network only.
|
||||||
app.route('/', createMediaRoutes(new FileMediaStore(join(dir, 'media'))));
|
const own = (await loadOwnerKey()).id;
|
||||||
const relay = createLiveRelay({ pins: new FileLivePinStore(join(dir, 'live-pins.json')) });
|
const listed = parseOwners(str(flags, 'owners') ?? process.env.SHADE_MEDIA_OWNERS);
|
||||||
app.route('/', relay.app);
|
const owners = flags.open === true || listed === 'any' ? 'any' : [own, ...listed];
|
||||||
app.route('/', createWatchRoutes({ dev: flags.dev === true }));
|
const svc = createMediaService({ dir, owners, dev: flags.dev === true });
|
||||||
app.get('/health', (c) => c.json({ ok: true, live: relay.stats() }));
|
svc.app.get('/health', (c) => c.json({ ok: true, live: svc.relay.stats() }));
|
||||||
const server = Bun.serve({
|
const server = Bun.serve({
|
||||||
port,
|
port,
|
||||||
hostname: str(flags, 'host') ?? '0.0.0.0',
|
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,
|
websocket,
|
||||||
idleTimeout: 0,
|
idleTimeout: 0,
|
||||||
});
|
});
|
||||||
err(`shade media: serving on http://localhost:${server.port} (data in ${dir})`);
|
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(() => {});
|
await new Promise(() => {});
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -251,6 +250,7 @@ async function startPublishing(flags: Flags, meta: MediaMeta): Promise<{ client:
|
|||||||
relay: server,
|
relay: server,
|
||||||
publisher: pub,
|
publisher: pub,
|
||||||
readToken,
|
readToken,
|
||||||
|
owner: await loadOwnerKey(),
|
||||||
onViewers: (n) => err(`viewers: ${n}`),
|
onViewers: (n) => err(`viewers: ${n}`),
|
||||||
onError: (m) => err(`relay: ${m}`),
|
onError: (m) => err(`relay: ${m}`),
|
||||||
onState: (s) => {
|
onState: (s) => {
|
||||||
@@ -343,8 +343,10 @@ async function liveWatch(pos: string[]): Promise<number> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const MEDIA_HELP = `
|
export const MEDIA_HELP = `
|
||||||
media serve [--port 3910] [--dir ./shade-media-data]
|
media serve [--port 3910] [--dir ./shade-media-data] [--owners k1,k2] [--open]
|
||||||
Run a media relay: sealed store, live relay, watch page
|
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]
|
media put <file> --server URL [--name N] [--mime M] [--public] [--json]
|
||||||
Seal a film/video/image/song, upload it, print a watch link
|
Seal a film/video/image/song, upload it, print a watch link
|
||||||
media get <link> [-o file|-]
|
media get <link> [-o file|-]
|
||||||
@@ -367,6 +369,9 @@ export async function runMediaCli(group: 'media' | 'live', argv: string[]): Prom
|
|||||||
switch (sub) {
|
switch (sub) {
|
||||||
case 'serve':
|
case 'serve':
|
||||||
return await mediaServe(flags);
|
return await mediaServe(flags);
|
||||||
|
case 'whoami':
|
||||||
|
out((await loadOwnerKey()).id);
|
||||||
|
return 0;
|
||||||
case 'put':
|
case 'put':
|
||||||
return await mediaPut(pos, flags);
|
return await mediaPut(pos, flags);
|
||||||
case 'get':
|
case 'get':
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { LiveSubscriber } from './channel.js';
|
|||||||
import type { FrameOptions, LivePublisher, ReceivedFrame } from './channel.js';
|
import type { FrameOptions, LivePublisher, ReceivedFrame } from './channel.js';
|
||||||
import type { LiveContent } from './frame.js';
|
import type { LiveContent } from './frame.js';
|
||||||
import type { LiveGrant } from '../grant.js';
|
import type { LiveGrant } from '../grant.js';
|
||||||
|
import type { OwnerKey } from '../owner.js';
|
||||||
|
|
||||||
export type LiveState = 'connecting' | 'live' | 'waiting' | 'reconnecting' | 'closed';
|
export type LiveState = 'connecting' | 'live' | 'waiting' | 'reconnecting' | 'closed';
|
||||||
|
|
||||||
@@ -45,6 +46,8 @@ export interface PublishOptions {
|
|||||||
publisher: LivePublisher;
|
publisher: LivePublisher;
|
||||||
/** Bearer token viewers must present. Its hash goes to the relay; the token goes in grants. */
|
/** Bearer token viewers must present. Its hash goes to the relay; the token goes in grants. */
|
||||||
readToken: Uint8Array;
|
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. */
|
/** Frames held while disconnected. Older ones are dropped first. Default 2000. */
|
||||||
queueLimit?: number;
|
queueLimit?: number;
|
||||||
onState?: (s: LiveState) => void;
|
onState?: (s: LiveState) => void;
|
||||||
@@ -64,18 +67,23 @@ export class LivePublishClient {
|
|||||||
private readTokenHash: Promise<Uint8Array>;
|
private readTokenHash: Promise<Uint8Array>;
|
||||||
private openedOnce: Promise<void>;
|
private openedOnce: Promise<void>;
|
||||||
private resolveOpened!: () => void;
|
private resolveOpened!: () => void;
|
||||||
|
private rejectOpened!: (e: Error) => void;
|
||||||
|
private lastError = '';
|
||||||
|
|
||||||
constructor(private readonly opts: PublishOptions) {
|
constructor(private readonly opts: PublishOptions) {
|
||||||
this.url = liveUrl(opts.relay, opts.publisher.channelId);
|
this.url = liveUrl(opts.relay, opts.publisher.channelId);
|
||||||
this.limit = opts.queueLimit ?? 2000;
|
this.limit = opts.queueLimit ?? 2000;
|
||||||
this.readTokenHash = sha256(opts.readToken);
|
this.readTokenHash = sha256(opts.readToken);
|
||||||
this.openedOnce = new Promise((r) => {
|
this.openedOnce = new Promise((resolve, reject) => {
|
||||||
this.resolveOpened = r;
|
this.resolveOpened = resolve;
|
||||||
|
this.rejectOpened = reject;
|
||||||
});
|
});
|
||||||
|
// A caller that never awaits whenReady() must not see an unhandled rejection.
|
||||||
|
this.openedOnce.catch(() => {});
|
||||||
this.connect();
|
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> {
|
whenReady(): Promise<void> {
|
||||||
return this.openedOnce;
|
return this.openedOnce;
|
||||||
}
|
}
|
||||||
@@ -133,7 +141,15 @@ export class LivePublishClient {
|
|||||||
this.ws = ws;
|
this.ws = ws;
|
||||||
ws.onopen = async () => {
|
ws.onopen = async () => {
|
||||||
const hello = this.opts.publisher.hello(await this.readTokenHash);
|
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) => {
|
ws.onmessage = (ev) => {
|
||||||
if (typeof ev.data !== 'string') return;
|
if (typeof ev.data !== 'string') return;
|
||||||
@@ -149,12 +165,21 @@ export class LivePublishClient {
|
|||||||
} else if (msg.type === 'viewers') {
|
} else if (msg.type === 'viewers') {
|
||||||
this.opts.onViewers?.(msg.count ?? 0);
|
this.opts.onViewers?.(msg.count ?? 0);
|
||||||
} else if (msg.type === 'error') {
|
} 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;
|
this.ready = false;
|
||||||
if (this.closed) return;
|
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');
|
this.opts.onState?.('reconnecting');
|
||||||
setTimeout(() => this.connect(), this.retry.next());
|
setTimeout(() => this.connect(), this.retry.next());
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -23,7 +23,8 @@ export const MAX_SKEW_MS = 10 * 60 * 1000;
|
|||||||
export type OwnerOp =
|
export type OwnerOp =
|
||||||
| { op: 'put'; id: string; size: number; readTokenHash: string }
|
| { op: 'put'; id: string; size: number; readTokenHash: string }
|
||||||
| { op: 'delete'; id: string }
|
| { op: 'delete'; id: string }
|
||||||
| { op: 'list' };
|
| { op: 'list' }
|
||||||
|
| { op: 'publish'; hello: string };
|
||||||
|
|
||||||
export function ownerMessage(o: OwnerOp, at: number): Uint8Array {
|
export function ownerMessage(o: OwnerOp, at: number): Uint8Array {
|
||||||
switch (o.op) {
|
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}`);
|
return enc.encode(`shade.media-delete/v1|${o.id}|${at}`);
|
||||||
case 'list':
|
case 'list':
|
||||||
return enc.encode(`shade.media-list/v1|${at}`);
|
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);
|
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> {
|
headers(o: OwnerOp, at = Date.now()): Record<string, string> {
|
||||||
return {
|
return {
|
||||||
[OWNER_HEADER]: this.id,
|
[OWNER_HEADER]: this.id,
|
||||||
@@ -89,3 +98,12 @@ export function verifyOwner(
|
|||||||
}
|
}
|
||||||
return { ok: true, owner };
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,3 +6,5 @@ export { createLiveRelay, FileLivePinStore, MemoryLivePinStore } from './server/
|
|||||||
export type { LiveRelay, LiveRelayOptions, LivePin, LivePinStore } from './server/live-relay.js';
|
export type { LiveRelay, LiveRelayOptions, LivePin, LivePinStore } from './server/live-relay.js';
|
||||||
export { createWatchRoutes } from './server/watch-routes.js';
|
export { createWatchRoutes } from './server/watch-routes.js';
|
||||||
export type { WatchRoutesOptions } 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';
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|||||||
import { dirname } from 'node:path';
|
import { dirname } from 'node:path';
|
||||||
import { enc, equalBytes, fromB64u, randomBytes, sha256, toB64u, toHex } from '../bytes.js';
|
import { enc, equalBytes, fromB64u, randomBytes, sha256, toB64u, toHex } from '../bytes.js';
|
||||||
import { decodeFrame, FLAG_END, FLAG_KEYFRAME, FLAG_STICKY } from '../live/frame.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';
|
import { Ed25519Verifier } from '../ed25519.js';
|
||||||
|
|
||||||
export interface LivePin {
|
export interface LivePin {
|
||||||
@@ -106,6 +106,13 @@ export class FileLivePinStore implements LivePinStore {
|
|||||||
|
|
||||||
export interface LiveRelayOptions {
|
export interface LiveRelayOptions {
|
||||||
pins: LivePinStore;
|
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. */
|
/** Keyframes of history kept for late joiners. Default 3. */
|
||||||
backlogKeyframes?: number;
|
backlogKeyframes?: number;
|
||||||
/** Byte cap on a channel's backlog (sticky frames excluded). Default 32 MiB. */
|
/** 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 idleMs = opts.idleRetentionMs ?? 10 * 60 * 1000;
|
||||||
const maxFrameBytes = opts.maxFrameBytes ?? 16 * 1024 * 1024 + 256;
|
const maxFrameBytes = opts.maxFrameBytes ?? 16 * 1024 * 1024 + 256;
|
||||||
const channels = new Map<string, Channel>();
|
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> {
|
async function channelFor(id: string): Promise<Channel | null> {
|
||||||
const have = channels.get(id);
|
const have = channels.get(id);
|
||||||
if (have !== undefined) return have;
|
if (have !== undefined) return have;
|
||||||
const pin = await opts.pins.get(id);
|
const pin = await opts.pins.get(id);
|
||||||
if (pin === null) return null;
|
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 = {
|
const ch: Channel = {
|
||||||
id,
|
id,
|
||||||
pin,
|
pin,
|
||||||
@@ -335,6 +348,13 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
|
|||||||
} catch {
|
} catch {
|
||||||
return fail(ws, 'malformed hello');
|
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);
|
const existing = await opts.pins.get(channelId);
|
||||||
if (existing !== null && existing.signingKey !== hello.signingKey) {
|
if (existing !== null && existing.signingKey !== hello.signingKey) {
|
||||||
return fail(ws, 'channel is pinned to another key');
|
return fail(ws, 'channel is pinned to another key');
|
||||||
|
|||||||
76
packages/shade-media/src/server/service.ts
Normal file
76
packages/shade-media/src/server/service.ts
Normal 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;
|
||||||
|
}
|
||||||
@@ -222,9 +222,8 @@ describe('live relay over real WebSockets', () => {
|
|||||||
const thief = new LivePublisher({ channelId: pub.channelId });
|
const thief = new LivePublisher({ channelId: pub.channelId });
|
||||||
const terr: string[] = [];
|
const terr: string[] = [];
|
||||||
const tc = new LivePublishClient({ relay: base, publisher: thief, readToken: new Uint8Array(32), onError: (m) => terr.push(m) });
|
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/);
|
expect(terr[0]).toMatch(/pinned/);
|
||||||
tc.close();
|
|
||||||
|
|
||||||
await client.end();
|
await client.end();
|
||||||
await until(() => early.at(-1)?.content.type === '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 () => {
|
test('rotation: a re-granted viewer continues, the other is locked out; pins persist', async () => {
|
||||||
const dir = await tempDir();
|
const dir = await tempDir();
|
||||||
const pins = new FileLivePinStore(join(dir, 'pins.json'));
|
const pins = new FileLivePinStore(join(dir, 'pins.json'));
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/inbox-server": "workspace:*",
|
"@shade/inbox-server": "workspace:*",
|
||||||
"@shade/key-transparency": "workspace:*",
|
"@shade/key-transparency": "workspace:*",
|
||||||
|
"@shade/media": "workspace:*",
|
||||||
"@shade/observability": "workspace:*",
|
"@shade/observability": "workspace:*",
|
||||||
"@shade/storage-sqlite": "workspace:*",
|
"@shade/storage-sqlite": "workspace:*",
|
||||||
"@shade/vault": "workspace:*",
|
"@shade/vault": "workspace:*",
|
||||||
|
|||||||
@@ -294,6 +294,37 @@ if (vaultDisabled) {
|
|||||||
logger.info('Vault enabled', { route: '/v1/vault/:vaultId' });
|
logger.info('Vault enabled', { route: '/v1/vault/:vaultId' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// V4.15 — media: sealed films/video/images/audio over Range, live channels
|
||||||
|
// (logs, text, live video) through a relay, and the /watch page that plays
|
||||||
|
// both. Same rule as the vault: a media library that lives in RAM loses every
|
||||||
|
// film on the next redeploy, so no directory means no media, said loudly.
|
||||||
|
// Uploads and live channels are closed to everyone but SHADE_MEDIA_OWNERS.
|
||||||
|
let mediaService: import('@shade/media/server').MediaService | null = null;
|
||||||
|
if (process.env.SHADE_DISABLE_MEDIA === '1') {
|
||||||
|
logger.info('Media disabled (SHADE_DISABLE_MEDIA=1)');
|
||||||
|
} else if (!process.env.SHADE_MEDIA_DIR) {
|
||||||
|
logger.warn(
|
||||||
|
'Media not enabled — set SHADE_MEDIA_DIR to a directory on a persistent volume. ' +
|
||||||
|
'There is no in-memory fallback on purpose: a library that forgets on redeploy is not a library.',
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const { createMediaService, parseOwners } = await import('@shade/media/server');
|
||||||
|
const owners = parseOwners(process.env.SHADE_MEDIA_OWNERS);
|
||||||
|
if (owners !== 'any' && owners.length === 0) {
|
||||||
|
logger.warn(
|
||||||
|
'Media is read-only: SHADE_MEDIA_OWNERS is empty, so nobody can upload or open a live channel. ' +
|
||||||
|
'Add owner keys (`shade media whoami`), comma-separated.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
mediaService = createMediaService({ dir: process.env.SHADE_MEDIA_DIR, owners });
|
||||||
|
app.route('/', mediaService.app);
|
||||||
|
logger.info('Media enabled', {
|
||||||
|
routes: ['/v1/media/:id', '/v1/live/:channelId', '/watch/'],
|
||||||
|
dir: process.env.SHADE_MEDIA_DIR,
|
||||||
|
owners: owners === 'any' ? 'any' : owners.length,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Optional: Observer + Dashboard ──────────────────────────
|
// ─── Optional: Observer + Dashboard ──────────────────────────
|
||||||
|
|
||||||
const observerToken = process.env.SHADE_OBSERVER_TOKEN;
|
const observerToken = process.env.SHADE_OBSERVER_TOKEN;
|
||||||
@@ -361,6 +392,7 @@ async function shutdown(signal: string) {
|
|||||||
try {
|
try {
|
||||||
cleanupTask.stop();
|
cleanupTask.stop();
|
||||||
inboxPrune.stop();
|
inboxPrune.stop();
|
||||||
|
mediaService?.stop();
|
||||||
server.stop();
|
server.stop();
|
||||||
if ('close' in store && typeof store.close === 'function') {
|
if ('close' in store && typeof store.close === 'function') {
|
||||||
await store.close();
|
await store.close();
|
||||||
|
|||||||
Reference in New Issue
Block a user