With several relays sharing pins, a viewer and the publisher could land on
different instances and never meet. LiveRelayOptions.mesh: each relay
claims the channels whose publisher it holds (LivePublisherLocator,
Postgres table shade_live_publishers, heartbeat 10 s). A relay whose
viewers want a channel published elsewhere subscribes to that relay once,
with a viewer's own read token, and fans out locally, verifying every
frame against the pin (a peer or a poisoned locator row cannot forge
one). Re-following replays a backlog; frames are passed on once (seq).
Viewers follow a publisher that moves. A token that fails the in-memory
pin is checked against the shared pin before refusal, so a publisher
back with a new read token is honoured on every instance.
SHADE_MEDIA_RELAY_URL / `media serve --advertise`.
Relays now send {"type":"state","live"} when a channel goes live or quiet
after a viewer joined; handled by the TS client (browser) and Android's
LiveWatcher.
Fixed on the way:
- The relay never saw its publisher leave: Hono gives each event its own
WSContext and the close handler compared identity. Channels stayed
"live" with nobody publishing; a replaced publisher was never closed.
- FileMediaStore on an unusable directory raised an unhandled rejection
at start; now each call fails with the reason.
Verified: 5 mesh tests (follow, late join, publisher moving A→B with
dedupe, forging peer refused, new read token) + state test, each fix
mutation-checked; Postgres locator + two media services over Postgres;
CLI relays with --advertise behind a round-robin HTTP+WS balancer:
publisher on A, Chromium viewer on B, "live", 208 lines. Suites: media
93, storage-postgres 20, server 55; Kotlin 92 (1 skipped), 0 failures.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
687 lines
26 KiB
TypeScript
687 lines
26 KiB
TypeScript
/**
|
|
* The live relay: one WebSocket in from the publisher, fan-out to viewers.
|
|
*
|
|
* GET /v1/live/:channelId (WebSocket)
|
|
*
|
|
* First text message decides the role:
|
|
* { "type": "publish", "hello": "<signed JSON>", "signature": "<b64u>" }
|
|
* { "type": "subscribe", "token": "<b64u read token>" }
|
|
*
|
|
* The relay holds no keys. It *does* verify every frame's Ed25519 signature
|
|
* against the key the channel was pinned with — cheap, and it means a relay
|
|
* never stores or forwards a frame its viewers would reject anyway.
|
|
*
|
|
* Backlog, per channel, so a viewer who joins late has something to start
|
|
* from: every sticky frame of the current epoch (codec init), plus the
|
|
* frames since the N-th most recent keyframe, capped in bytes and count.
|
|
* It is live data — ciphertext held for minutes — and lives in memory; the
|
|
* channel *pins* (which key owns which channel) are persistent, so a relay
|
|
* restart cannot let someone else claim a channel id a viewer already holds.
|
|
*
|
|
* A viewer that cannot keep up is not allowed to grow the relay's memory:
|
|
* past a high-water mark its non-sticky frames are dropped until its socket
|
|
* drains and the next keyframe comes along, which is exactly where a video
|
|
* decoder can pick up again.
|
|
*/
|
|
|
|
import { ed25519 } from '@noble/curves/ed25519.js';
|
|
import { Hono } from 'hono';
|
|
import { upgradeWebSocket } from 'hono/bun';
|
|
import type { WSContext } from 'hono/ws';
|
|
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
import { dirname } from 'node:path';
|
|
import { enc, equalBytes, fromB64u, randomBytes, sha256, toB64u, toHex } from '../bytes.js';
|
|
import { decodeFrame, FLAG_END, FLAG_KEYFRAME, FLAG_STICKY } from '../live/frame.js';
|
|
import { MAX_SKEW_MS, verifyPublishOwner } from '../owner.js';
|
|
import { Ed25519Verifier } from '../ed25519.js';
|
|
|
|
export interface LivePin {
|
|
channelId: string; // base64url
|
|
signingKey: string; // base64url
|
|
readTokenHash: string; // base64url SHA-256
|
|
pinnedAt: number;
|
|
lastSeen: number;
|
|
}
|
|
|
|
export interface LivePinStore {
|
|
get(channelId: string): Promise<LivePin | null>;
|
|
/**
|
|
* Create or refresh a pin. Must throw `LivePinTakenError` if the channel is
|
|
* pinned to another signing key — atomically, so two relays sharing the
|
|
* store cannot both pin one channel to different keys.
|
|
*/
|
|
put(pin: LivePin): Promise<void>;
|
|
}
|
|
|
|
export class LivePinTakenError extends Error {
|
|
override readonly name = 'LivePinTakenError';
|
|
constructor(channelId: string) {
|
|
super(`channel ${channelId} is pinned to another key`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Where a channel's publisher is connected, when several relays share one
|
|
* pin store. A relay with viewers but not the publisher looks the channel up
|
|
* here and follows the relay that has it (see `LiveRelayOptions.mesh`).
|
|
*/
|
|
export interface LivePublisherLocator {
|
|
/** This relay holds the channel's publisher. Called again as a heartbeat while it does. */
|
|
claim(channelId: string, relayUrl: string, at: number): Promise<void>;
|
|
/** The publisher left this relay. Only removes a claim that is still this relay's. */
|
|
release(channelId: string, relayUrl: string): Promise<void>;
|
|
/** The relay holding the publisher, if its claim was refreshed after `freshAfter`. */
|
|
find(channelId: string, freshAfter: number): Promise<string | null>;
|
|
}
|
|
|
|
/** One process's locator — for tests, and relays that share memory. */
|
|
export class MemoryLivePublisherLocator implements LivePublisherLocator {
|
|
private readonly claims = new Map<string, { url: string; at: number }>();
|
|
async claim(channelId: string, relayUrl: string, at: number): Promise<void> {
|
|
this.claims.set(channelId, { url: relayUrl, at });
|
|
}
|
|
async release(channelId: string, relayUrl: string): Promise<void> {
|
|
if (this.claims.get(channelId)?.url === relayUrl) this.claims.delete(channelId);
|
|
}
|
|
async find(channelId: string, freshAfter: number): Promise<string | null> {
|
|
const c = this.claims.get(channelId);
|
|
return c !== undefined && c.at > freshAfter ? c.url : null;
|
|
}
|
|
}
|
|
|
|
export class MemoryLivePinStore implements LivePinStore {
|
|
private readonly pins = new Map<string, LivePin>();
|
|
async get(id: string): Promise<LivePin | null> {
|
|
return this.pins.get(id) ?? null;
|
|
}
|
|
async put(pin: LivePin): Promise<void> {
|
|
const have = this.pins.get(pin.channelId);
|
|
if (have !== undefined && have.signingKey !== pin.signingKey) throw new LivePinTakenError(pin.channelId);
|
|
this.pins.set(pin.channelId, pin);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Pins in one JSON file, rewritten atomically. A relay has few channels
|
|
* (hundreds, not millions) and pins change only when one is created, so a
|
|
* file is enough and needs no database. Pins idle past `ttlMs` are dropped.
|
|
*/
|
|
export class FileLivePinStore implements LivePinStore {
|
|
private pins: Map<string, LivePin> | null = null;
|
|
private writing: Promise<void> = Promise.resolve();
|
|
|
|
constructor(
|
|
private readonly path: string,
|
|
private readonly ttlMs = 30 * 24 * 3600 * 1000,
|
|
) {}
|
|
|
|
private async load(): Promise<Map<string, LivePin>> {
|
|
if (this.pins !== null) return this.pins;
|
|
const pins = new Map<string, LivePin>();
|
|
try {
|
|
for (const p of JSON.parse(await readFile(this.path, 'utf8')) as LivePin[]) pins.set(p.channelId, p);
|
|
} catch (e) {
|
|
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;
|
|
}
|
|
this.pins = pins;
|
|
return pins;
|
|
}
|
|
|
|
async get(id: string): Promise<LivePin | null> {
|
|
return (await this.load()).get(id) ?? null;
|
|
}
|
|
|
|
async put(pin: LivePin): Promise<void> {
|
|
const pins = await this.load();
|
|
const have = pins.get(pin.channelId);
|
|
if (have !== undefined && have.signingKey !== pin.signingKey) throw new LivePinTakenError(pin.channelId);
|
|
pins.set(pin.channelId, pin);
|
|
const cutoff = Date.now() - this.ttlMs;
|
|
for (const [k, p] of pins) if (p.lastSeen < cutoff) pins.delete(k);
|
|
const snapshot = JSON.stringify([...pins.values()]);
|
|
this.writing = this.writing.then(async () => {
|
|
await mkdir(dirname(this.path), { recursive: true });
|
|
const tmp = `${this.path}.${toHex(randomBytes(4))}.tmp`;
|
|
await writeFile(tmp, snapshot, { mode: 0o600 });
|
|
await rename(tmp, this.path);
|
|
});
|
|
await this.writing;
|
|
}
|
|
}
|
|
|
|
export interface LiveRelayOptions {
|
|
pins: LivePinStore;
|
|
/**
|
|
* 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. */
|
|
maxBacklogBytes?: number;
|
|
/** Frame-count cap on a channel's backlog. Default 5000. */
|
|
maxBacklogFrames?: number;
|
|
/** Viewer socket buffer past which frames are dropped until the next keyframe. Default 8 MiB. */
|
|
viewerHighWater?: number;
|
|
/** How long an idle channel (no publisher, no viewers) keeps its backlog. Default 10 min. */
|
|
idleRetentionMs?: number;
|
|
/** Largest frame accepted. Default 16 MiB + headers. */
|
|
maxFrameBytes?: number;
|
|
/**
|
|
* Several relays, one set of channels. Each relay claims the channels whose
|
|
* publisher is connected to it; a relay with viewers of a channel published
|
|
* elsewhere subscribes to that relay, once, with a viewer's own read token,
|
|
* and fans the frames out to its viewers. It verifies every frame against
|
|
* the pin as if the publisher were its own, so a peer cannot forge one.
|
|
*/
|
|
mesh?: {
|
|
/** This relay's base URL as the other relays reach it, e.g. `http://10.0.0.5:3000`. */
|
|
self: string;
|
|
locator: LivePublisherLocator;
|
|
/** Claim refresh. Default 10 s. */
|
|
heartbeatMs?: number;
|
|
/** A claim older than this is a relay that died. Default 30 s. */
|
|
staleMs?: number;
|
|
/** How often a channel with viewers looks for a publisher that is not here. Default 2 s. */
|
|
pollMs?: number;
|
|
};
|
|
now?: () => number;
|
|
}
|
|
|
|
interface Viewer {
|
|
ws: WSContext;
|
|
lagging: boolean;
|
|
}
|
|
|
|
interface Channel {
|
|
id: string;
|
|
pin: LivePin;
|
|
verifier: Ed25519Verifier;
|
|
publisher: WSContext | null;
|
|
viewers: Set<Viewer>;
|
|
epoch: number;
|
|
sticky: Uint8Array[];
|
|
backlog: { frame: Uint8Array; keyframe: boolean }[];
|
|
backlogBytes: number;
|
|
sawKeyframe: boolean;
|
|
ended: boolean;
|
|
idleSince: number;
|
|
/** Highest seq taken this epoch — a relay followed again resends its backlog. */
|
|
lastSeq: number;
|
|
/** The relay this one follows for the channel (mesh), when its publisher is there. */
|
|
upstream: WebSocket | null;
|
|
/** A read token a viewer proved, to subscribe upstream with. */
|
|
token: string | null;
|
|
/** Pending look-up for a publisher elsewhere. */
|
|
poll: ReturnType<typeof setTimeout> | null;
|
|
}
|
|
|
|
type Role = { kind: 'none' } | { kind: 'pub'; ch: Channel } | { kind: 'sub'; ch: Channel; viewer: Viewer };
|
|
|
|
/**
|
|
* Hono hands each event its own WSContext for one socket, so `===` between
|
|
* the one seen at `publish` and the one at close is always false: compare the
|
|
* socket underneath.
|
|
*/
|
|
function sameSocket(a: WSContext | null, b: WSContext): boolean {
|
|
return a !== null && (a === b || (a.raw !== undefined && a.raw === b.raw));
|
|
}
|
|
|
|
function bufferedAmount(ws: WSContext): number {
|
|
const raw = ws.raw as { getBufferedAmount?: () => number } | undefined;
|
|
return raw?.getBufferedAmount?.() ?? 0;
|
|
}
|
|
|
|
function toBytes(data: unknown): Uint8Array | null {
|
|
if (data instanceof Uint8Array) return data;
|
|
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
return null;
|
|
}
|
|
|
|
export interface LiveRelay {
|
|
app: Hono;
|
|
/** Channels currently held, for metrics and tests. */
|
|
/** `framesIn`: frames accepted from publishers since the relay started. */
|
|
stats(): { channels: number; viewers: number; backlogBytes: number; framesIn: number };
|
|
/** Drop idle channels now (also runs on a timer). */
|
|
sweep(): void;
|
|
stop(): void;
|
|
}
|
|
|
|
export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
|
|
const now = opts.now ?? Date.now;
|
|
const keepKeyframes = Math.max(1, opts.backlogKeyframes ?? 3);
|
|
const maxBytes = opts.maxBacklogBytes ?? 32 * 1024 * 1024;
|
|
const maxFrames = opts.maxBacklogFrames ?? 5000;
|
|
const highWater = opts.viewerHighWater ?? 8 * 1024 * 1024;
|
|
const idleMs = opts.idleRetentionMs ?? 10 * 60 * 1000;
|
|
let framesIn = 0;
|
|
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,
|
|
verifier: new Ed25519Verifier(fromB64u(pin.signingKey, 32)),
|
|
publisher: null,
|
|
viewers: new Set(),
|
|
epoch: -1,
|
|
sticky: [],
|
|
backlog: [],
|
|
backlogBytes: 0,
|
|
sawKeyframe: false,
|
|
ended: false,
|
|
idleSince: now(),
|
|
lastSeq: -1,
|
|
upstream: null,
|
|
token: null,
|
|
poll: null,
|
|
};
|
|
channels.set(id, ch);
|
|
return ch;
|
|
}
|
|
|
|
/** Adopt a pin read from the shared store. A new signing key is a new channel. */
|
|
function repin(ch: Channel, pin: LivePin): void {
|
|
if (pin.signingKey !== ch.pin.signingKey) {
|
|
closeUpstream(ch);
|
|
ch.verifier = new Ed25519Verifier(fromB64u(pin.signingKey, 32));
|
|
ch.epoch = -1;
|
|
ch.sticky = [];
|
|
ch.backlog = [];
|
|
ch.backlogBytes = 0;
|
|
ch.sawKeyframe = false;
|
|
ch.lastSeq = -1;
|
|
ch.ended = false;
|
|
}
|
|
ch.pin = pin;
|
|
}
|
|
|
|
function trim(ch: Channel): void {
|
|
// Keep from the keepKeyframes-th most recent keyframe onward…
|
|
let seen = 0;
|
|
let cut = 0;
|
|
for (let i = ch.backlog.length - 1; i >= 0; i--) {
|
|
if (ch.backlog[i]!.keyframe && ++seen === keepKeyframes) {
|
|
cut = i;
|
|
break;
|
|
}
|
|
}
|
|
// …then enforce the hard caps, oldest first.
|
|
let drop = cut;
|
|
let bytes = ch.backlogBytes;
|
|
for (let i = 0; i < drop; i++) bytes -= ch.backlog[i]!.frame.length;
|
|
while (drop < ch.backlog.length && (bytes > maxBytes || ch.backlog.length - drop > maxFrames)) {
|
|
bytes -= ch.backlog[drop]!.frame.length;
|
|
drop++;
|
|
}
|
|
if (drop > 0) {
|
|
ch.backlog.splice(0, drop);
|
|
ch.backlogBytes = bytes;
|
|
}
|
|
}
|
|
|
|
function deliver(v: Viewer, frame: Uint8Array, sticky: boolean, keyframe: boolean, sawKeyframe: boolean): void {
|
|
if (!sticky) {
|
|
if (v.lagging) {
|
|
// Resume only where a decoder can: a keyframe (or any frame, on a
|
|
// channel that has none — a log stream).
|
|
if (bufferedAmount(v.ws) > highWater / 4 || (sawKeyframe && !keyframe)) return;
|
|
v.lagging = false;
|
|
} else if (bufferedAmount(v.ws) > highWater) {
|
|
v.lagging = true;
|
|
return;
|
|
}
|
|
}
|
|
v.ws.send(frame as Uint8Array<ArrayBuffer>);
|
|
}
|
|
|
|
/** Tell viewers when the channel goes live or quiet after they joined (the `ready` answer is only the start). */
|
|
function notifyViewers(ch: Channel): void {
|
|
const live = ch.publisher !== null || ch.upstream !== null;
|
|
const msg = JSON.stringify({ type: 'state', live, ended: ch.ended, epoch: ch.epoch });
|
|
for (const v of ch.viewers) v.ws.send(msg);
|
|
}
|
|
|
|
function notifyPublisher(ch: Channel): void {
|
|
ch.publisher?.send(JSON.stringify({ type: 'viewers', count: ch.viewers.size }));
|
|
}
|
|
|
|
async function accept(ch: Channel, frame: Uint8Array, fromUpstream = false): Promise<string | null> {
|
|
if (frame.length > maxFrameBytes) return 'frame too large';
|
|
let f;
|
|
try {
|
|
f = decodeFrame(frame);
|
|
} catch (e) {
|
|
return (e as Error).message;
|
|
}
|
|
if (toB64u(f.header.channelId) !== ch.id) return 'frame for another channel';
|
|
if (!(await ch.verifier.verify(f.signature, f.signed))) return 'bad frame signature';
|
|
const { epoch, flags } = f.header;
|
|
if (epoch < ch.epoch) return null; // a stale frame from before a rotation: drop quietly
|
|
if (epoch > ch.epoch) {
|
|
ch.epoch = epoch;
|
|
ch.sticky = [];
|
|
ch.backlog = [];
|
|
ch.backlogBytes = 0;
|
|
ch.sawKeyframe = false;
|
|
ch.lastSeq = -1;
|
|
}
|
|
// Following another relay again replays its backlog: pass on each frame once.
|
|
if (fromUpstream && f.header.seq <= ch.lastSeq) return null;
|
|
ch.lastSeq = Math.max(ch.lastSeq, f.header.seq);
|
|
const sticky = (flags & FLAG_STICKY) !== 0;
|
|
const keyframe = (flags & FLAG_KEYFRAME) !== 0;
|
|
const copy = frame.slice();
|
|
if (sticky) {
|
|
ch.sticky.push(copy);
|
|
} else {
|
|
if (keyframe) ch.sawKeyframe = true;
|
|
ch.backlog.push({ frame: copy, keyframe });
|
|
ch.backlogBytes += copy.length;
|
|
trim(ch);
|
|
}
|
|
if ((flags & FLAG_END) !== 0) ch.ended = true;
|
|
framesIn++;
|
|
for (const v of ch.viewers) deliver(v, copy, sticky, keyframe, ch.sawKeyframe);
|
|
return null;
|
|
}
|
|
|
|
const mesh = opts.mesh;
|
|
const heartbeatMs = mesh?.heartbeatMs ?? 10_000;
|
|
const staleMs = mesh?.staleMs ?? 30_000;
|
|
const pollMs = mesh?.pollMs ?? 2_000;
|
|
const self = mesh?.self.replace(/\/$/, '');
|
|
let stopped = false;
|
|
|
|
function closeUpstream(ch: Channel): void {
|
|
if (ch.poll !== null) {
|
|
clearTimeout(ch.poll);
|
|
ch.poll = null;
|
|
}
|
|
const up = ch.upstream;
|
|
ch.upstream = null;
|
|
up?.close(1000, 'not needed');
|
|
}
|
|
|
|
function schedulePoll(ch: Channel): void {
|
|
if (ch.poll !== null || stopped) return;
|
|
ch.poll = setTimeout(() => {
|
|
ch.poll = null;
|
|
void follow(ch);
|
|
}, pollMs);
|
|
(ch.poll as { unref?: () => void }).unref?.();
|
|
}
|
|
|
|
/** Follow the relay that has this channel's publisher, while viewers here want it. */
|
|
async function follow(ch: Channel): Promise<void> {
|
|
if (mesh === undefined || stopped) return;
|
|
if (ch.publisher !== null || ch.upstream !== null || ch.viewers.size === 0 || ch.token === null) return;
|
|
let url: string | null;
|
|
try {
|
|
url = await mesh.locator.find(ch.id, now() - staleMs);
|
|
} catch {
|
|
url = null;
|
|
}
|
|
// Re-check: the publisher may have arrived here while we looked.
|
|
if (ch.publisher !== null || ch.upstream !== null || ch.viewers.size === 0) return;
|
|
if (url === null || url.replace(/\/$/, '') === self) return schedulePoll(ch);
|
|
const ws = new WebSocket(`${url.replace(/^http/, 'ws').replace(/\/$/, '')}/v1/live/${ch.id}`);
|
|
ws.binaryType = 'arraybuffer';
|
|
ch.upstream = ws;
|
|
let chain: Promise<void> = Promise.resolve();
|
|
ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe', token: ch.token }));
|
|
ws.onmessage = (ev) => {
|
|
if (typeof ev.data === 'string') {
|
|
// The relay we follow took us: viewers here are live from now.
|
|
if (ch.upstream === ws && (JSON.parse(ev.data) as { type?: string }).type === 'ready') notifyViewers(ch);
|
|
return;
|
|
}
|
|
const bytes = new Uint8Array(ev.data as ArrayBuffer);
|
|
chain = chain.then(async () => {
|
|
if (ch.upstream !== ws) return;
|
|
// Verified like a publisher's own: a peer relay is not trusted with frames.
|
|
const err = await accept(ch, bytes, true);
|
|
if (err !== null) ws.close(1008, err.slice(0, 120));
|
|
});
|
|
};
|
|
ws.onclose = () => {
|
|
if (ch.upstream !== ws) return;
|
|
ch.upstream = null;
|
|
notifyViewers(ch);
|
|
// The publisher left that relay (or it died): look again while anyone watches.
|
|
if (ch.viewers.size > 0 && ch.publisher === null) schedulePoll(ch);
|
|
};
|
|
ws.onerror = () => {};
|
|
}
|
|
|
|
async function claim(ch: Channel): Promise<void> {
|
|
if (mesh === undefined) return;
|
|
await mesh.locator.claim(ch.id, self!, now()).catch(() => {
|
|
// The next heartbeat tries again; frames flow to local viewers meanwhile.
|
|
});
|
|
}
|
|
|
|
const heartbeat =
|
|
mesh !== undefined
|
|
? setInterval(() => {
|
|
for (const ch of channels.values()) if (ch.publisher !== null) void claim(ch);
|
|
}, heartbeatMs)
|
|
: null;
|
|
(heartbeat as { unref?: () => void } | null)?.unref?.();
|
|
|
|
function sweep(): void {
|
|
const t = now();
|
|
for (const [id, ch] of channels) {
|
|
if (ch.publisher === null && ch.viewers.size === 0 && t - ch.idleSince > idleMs) {
|
|
closeUpstream(ch);
|
|
channels.delete(id);
|
|
}
|
|
}
|
|
}
|
|
const timer = setInterval(sweep, 60_000);
|
|
(timer as { unref?: () => void }).unref?.();
|
|
|
|
const app = new Hono();
|
|
app.get(
|
|
'/v1/live/:channelId',
|
|
upgradeWebSocket((c) => {
|
|
const channelId = c.req.param('channelId') ?? '';
|
|
let role: Role = { kind: 'none' };
|
|
let busy: Promise<void> = Promise.resolve();
|
|
|
|
const fail = (ws: WSContext, message: string, code = 1008) => {
|
|
ws.send(JSON.stringify({ type: 'error', message }));
|
|
ws.close(code, message.slice(0, 120));
|
|
};
|
|
|
|
async function onControl(ws: WSContext, text: string): Promise<void> {
|
|
let msg: Record<string, unknown>;
|
|
try {
|
|
msg = JSON.parse(text);
|
|
} catch {
|
|
return fail(ws, 'control message is not JSON');
|
|
}
|
|
if (role.kind !== 'none') return fail(ws, 'role already chosen');
|
|
if (!/^[A-Za-z0-9_-]{22}$/.test(channelId)) return fail(ws, 'bad channel id');
|
|
|
|
if (msg.type === 'publish') {
|
|
if (typeof msg.hello !== 'string' || typeof msg.signature !== 'string') return fail(ws, 'bad publish');
|
|
let hello: Record<string, unknown>;
|
|
try {
|
|
hello = JSON.parse(msg.hello);
|
|
} catch {
|
|
return fail(ws, 'hello is not JSON');
|
|
}
|
|
if (
|
|
hello.kind !== 'shade.live-hello/v1' ||
|
|
hello.channelId !== channelId ||
|
|
typeof hello.signingKey !== 'string' ||
|
|
typeof hello.readTokenHash !== 'string' ||
|
|
typeof hello.at !== 'number' ||
|
|
Math.abs(now() - hello.at) > MAX_SKEW_MS
|
|
) {
|
|
return fail(ws, 'hello rejected');
|
|
}
|
|
let signingKey: Uint8Array;
|
|
try {
|
|
signingKey = fromB64u(hello.signingKey, 32);
|
|
fromB64u(hello.readTokenHash, 32);
|
|
if (!ed25519.verify(fromB64u(msg.signature, 64), enc.encode(msg.hello), signingKey)) {
|
|
return fail(ws, 'hello signature does not verify');
|
|
}
|
|
} catch {
|
|
return fail(ws, 'malformed hello');
|
|
}
|
|
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');
|
|
}
|
|
const pin: LivePin = {
|
|
channelId,
|
|
signingKey: hello.signingKey,
|
|
readTokenHash: hello.readTokenHash,
|
|
pinnedAt: existing?.pinnedAt ?? now(),
|
|
lastSeen: now(),
|
|
};
|
|
try {
|
|
await opts.pins.put(pin);
|
|
} catch (e) {
|
|
// Another relay sharing the pin store won the race for this channel.
|
|
if (e instanceof LivePinTakenError) return fail(ws, 'channel is pinned to another key');
|
|
throw e;
|
|
}
|
|
const ch = (await channelFor(channelId))!;
|
|
ch.pin = pin;
|
|
// A reconnecting publisher replaces the stale socket.
|
|
if (ch.publisher !== null && !sameSocket(ch.publisher, ws)) ch.publisher.close(4000, 'replaced by a newer publisher');
|
|
ch.publisher = ws;
|
|
ch.ended = false;
|
|
// The publisher is here now: stop following another relay, and say so.
|
|
closeUpstream(ch);
|
|
await claim(ch);
|
|
role = { kind: 'pub', ch };
|
|
notifyViewers(ch);
|
|
ws.send(JSON.stringify({ type: 'ready', role: 'publisher', epoch: ch.epoch, viewers: ch.viewers.size }));
|
|
return;
|
|
}
|
|
|
|
if (msg.type === 'subscribe') {
|
|
if (typeof msg.token !== 'string') return fail(ws, 'bad subscribe');
|
|
const ch = await channelFor(channelId);
|
|
let tokenHash: Uint8Array | null = null;
|
|
try {
|
|
tokenHash = await sha256(fromB64u(msg.token));
|
|
} catch {
|
|
tokenHash = null;
|
|
}
|
|
const matches = () => tokenHash !== null && equalBytes(tokenHash, fromB64u(ch!.pin.readTokenHash, 32));
|
|
let ok = ch !== null && matches();
|
|
if (ch !== null && !ok && ch.publisher === null && mesh !== undefined) {
|
|
// The publisher is on another relay and may have come back with a
|
|
// new read token: judge by the shared pin, not the copy held here.
|
|
const fresh = await opts.pins.get(channelId);
|
|
if (fresh !== null) {
|
|
repin(ch, fresh);
|
|
ok = matches();
|
|
}
|
|
}
|
|
// Same refusal for "no such channel" and "wrong token".
|
|
if (ch === null || !ok) return fail(ws, 'not found', 4404);
|
|
const viewer: Viewer = { ws, lagging: false };
|
|
ch.viewers.add(viewer);
|
|
role = { kind: 'sub', ch, viewer };
|
|
// The latest proven token: the one the shared pin accepts now.
|
|
ch.token = msg.token;
|
|
const live = ch.publisher !== null || ch.upstream !== null;
|
|
ws.send(JSON.stringify({ type: 'ready', role: 'viewer', live, ended: ch.ended, epoch: ch.epoch }));
|
|
for (const f of ch.sticky) ws.send(f as Uint8Array<ArrayBuffer>);
|
|
for (const b of ch.backlog) deliver(viewer, b.frame, false, b.keyframe, ch.sawKeyframe);
|
|
notifyPublisher(ch);
|
|
if (ch.publisher === null) void follow(ch);
|
|
return;
|
|
}
|
|
return fail(ws, 'unknown control message');
|
|
}
|
|
|
|
return {
|
|
onMessage(evt, ws) {
|
|
// Serialise per socket: the role is decided asynchronously (a pin
|
|
// lookup), and a frame must not race past its own hello.
|
|
busy = busy.then(async () => {
|
|
if (typeof evt.data === 'string') return onControl(ws, evt.data);
|
|
const bytes = toBytes(evt.data);
|
|
if (bytes === null) return;
|
|
if (role.kind !== 'pub') return fail(ws, 'only the publisher sends frames');
|
|
const err = await accept(role.ch, bytes);
|
|
if (err !== null) fail(ws, err);
|
|
}).catch((e) => fail(ws, String((e as Error)?.message ?? e), 1011));
|
|
},
|
|
onClose(_evt, ws) {
|
|
if (role.kind === 'pub' && sameSocket(role.ch.publisher, ws)) {
|
|
const ch = role.ch;
|
|
ch.publisher = null;
|
|
ch.idleSince = now();
|
|
notifyViewers(ch);
|
|
if (mesh !== undefined) {
|
|
void mesh.locator.release(ch.id, self!).catch(() => {});
|
|
// It may come back on another relay: viewers here follow it there.
|
|
if (ch.viewers.size > 0) schedulePoll(ch);
|
|
}
|
|
} else if (role.kind === 'sub') {
|
|
role.ch.viewers.delete(role.viewer);
|
|
role.ch.idleSince = now();
|
|
notifyPublisher(role.ch);
|
|
if (role.ch.viewers.size === 0) closeUpstream(role.ch);
|
|
}
|
|
},
|
|
};
|
|
}),
|
|
);
|
|
|
|
return {
|
|
app,
|
|
stats() {
|
|
let viewers = 0;
|
|
let backlogBytes = 0;
|
|
for (const ch of channels.values()) {
|
|
viewers += ch.viewers.size;
|
|
backlogBytes += ch.backlogBytes;
|
|
}
|
|
return { channels: channels.size, viewers, backlogBytes, framesIn };
|
|
},
|
|
sweep,
|
|
stop() {
|
|
stopped = true;
|
|
clearInterval(timer);
|
|
if (heartbeat !== null) clearInterval(heartbeat);
|
|
for (const ch of channels.values()) {
|
|
closeUpstream(ch);
|
|
if (mesh !== undefined && ch.publisher !== null) void mesh.locator.release(ch.id, self!).catch(() => {});
|
|
}
|
|
},
|
|
};
|
|
}
|