/**
* `shade media …` and `shade live …` — the command line for streaming.
*
* shade media serve relay + media store + watch page
* shade media put film.mkv --server URL seal, upload, print a watch link
* shade media get -o out.mkv download and decrypt
* shade media ls|rm --server URL
* tail -f app.log | shade live text --server URL --name "app logs"
* ffmpeg … -f webm - | shade live webm --server URL --name "Camera"
* shade live watch a live text channel in the terminal
*
* The owner key (who may upload and delete) is created on first use under
* `$XDG_CONFIG_HOME/shade/` and reused; nothing to configure.
*/
import { chmod, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { createWriteStream } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
import { basename, extname, join } from 'node:path';
import { fromB64u, randomBytes, toB64u, toHex } from './bytes.js';
import { MediaClient, openGrant } from './client.js';
import { encodeGrant, fromCapabilityUrl, toCapabilityUrl } from './grant.js';
import type { Grant, MediaGrant } from './grant.js';
import { LivePublisher } from './live/channel.js';
import { LivePublishClient, LiveWatchClient } from './live/client.js';
import { sealFile } from './node.js';
import { OwnerKey } from './owner.js';
import type { MediaMeta } from './sealed.js';
import { WebmSplitter } from './webm.js';
type Flags = Record;
function parseArgs(argv: string[]): { pos: string[]; flags: Flags } {
const pos: string[] = [];
const flags: Flags = {};
for (let i = 0; i < argv.length; i++) {
const a = argv[i]!;
if (a.startsWith('--')) {
const [k, v] = a.slice(2).split('=', 2) as [string, string | undefined];
if (v !== undefined) flags[k] = v;
else if (argv[i + 1] !== undefined && !argv[i + 1]!.startsWith('-')) flags[k] = argv[++i]!;
else flags[k] = true;
} else if (a === '-o') {
flags.out = argv[++i] ?? '';
} else {
pos.push(a);
}
}
return { pos, flags };
}
function str(flags: Flags, k: string): string | undefined {
const v = flags[k];
return typeof v === 'string' ? v : undefined;
}
function need(flags: Flags, k: string, envName?: string): string {
const v = str(flags, k) ?? (envName !== undefined ? process.env[envName] : undefined);
if (v === undefined || v === '') throw new UsageError(`--${k} is required${envName ? ` (or ${envName})` : ''}`);
return v.replace(/\/$/, '');
}
class UsageError extends Error {}
const MIME_BY_EXT: Record = {
'.mp4': 'video/mp4', '.m4v': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm',
'.mkv': 'video/x-matroska', '.ogv': 'video/ogg', '.mp3': 'audio/mpeg', '.m4a': 'audio/mp4',
'.aac': 'audio/aac', '.ogg': 'audio/ogg', '.opus': 'audio/ogg', '.wav': 'audio/wav', '.flac': 'audio/flac',
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp',
'.avif': 'image/avif', '.txt': 'text/plain; charset=utf-8', '.log': 'text/plain; charset=utf-8',
'.md': 'text/markdown; charset=utf-8', '.json': 'application/json', '.pdf': 'application/pdf',
'.srt': 'text/plain; charset=utf-8', '.vtt': 'text/vtt',
};
export function guessMime(path: string): string | undefined {
return MIME_BY_EXT[extname(path).toLowerCase()];
}
function configDir(): string {
return join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'shade');
}
/** The owner key, created on first use and kept 0600. */
export async function loadOwnerKey(path = join(configDir(), 'media-owner.key')): Promise {
try {
return new OwnerKey(fromB64u((await readFile(path, 'utf8')).trim(), 32));
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;
}
const key = OwnerKey.generate();
await mkdir(configDir(), { recursive: true, mode: 0o700 });
await writeFile(path, `${toB64u(key.exportSecret())}\n`, { mode: 0o600, flag: 'wx' });
return key;
}
function watchLink(server: string, g: Grant): string {
return toCapabilityUrl(`${server}/watch/`, g);
}
const out = (s: string) => process.stdout.write(`${s}\n`);
const err = (s: string) => process.stderr.write(`${s}\n`);
// ─── media ───────────────────────────────────────────────────
async function mediaServe(flags: Flags): Promise {
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 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() }));
const server = Bun.serve({
port,
hostname: str(flags, 'host') ?? '0.0.0.0',
fetch: (req, srv) => app.fetch(req, { server: srv }),
websocket,
idleTimeout: 0,
});
err(`shade media: serving on http://localhost:${server.port} (data in ${dir})`);
await new Promise(() => {});
return 0;
}
async function mediaPut(pos: string[], flags: Flags): Promise {
const file = pos[0];
if (file === undefined) throw new UsageError('usage: shade media put --server URL');
const server = need(flags, 'server', 'SHADE_MEDIA_SERVER');
const meta: MediaMeta = { name: str(flags, 'name') ?? basename(file) };
const mime = str(flags, 'mime') ?? guessMime(file);
if (mime !== undefined) meta.mime = mime;
const size = (await stat(file)).size;
const tmp = join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`);
const started = Date.now();
try {
err(`sealing ${basename(file)} (${(size / 1048576).toFixed(1)} MiB)…`);
const result = await sealFile(file, tmp, { meta });
err(`uploading ${(result.sealedSize / 1048576).toFixed(1)} MiB…`);
const client = new MediaClient(server, await loadOwnerKey());
const grant = await client.putSealed(result, Bun.file(tmp), {
meta,
...(flags.public === true ? { readToken: null } : {}),
});
err(`done in ${((Date.now() - started) / 1000).toFixed(1)} s`);
out(flags.json === true ? encodeGrant(grant) : watchLink(server, grant));
} finally {
await rm(tmp, { force: true });
}
return 0;
}
async function mediaGet(pos: string[], flags: Flags): Promise {
const link = pos[0];
if (link === undefined) throw new UsageError('usage: shade media get [-o file]');
const g = fromCapabilityUrl(link);
if (g.kind !== 'shade.media-grant/v1') throw new UsageError('that link is a live channel — use `shade live watch`');
const reader = await openGrant(g);
const target = str(flags, 'out') ?? reader.meta.name ?? 'shade-media.bin';
const ws = target === '-' ? process.stdout : createWriteStream(target);
for await (const chunk of reader.stream()) {
if (!ws.write(chunk)) await new Promise((r) => ws.once('drain', () => r()));
}
if (ws !== process.stdout) await new Promise((r) => (ws as ReturnType).end(() => r()));
if (target !== '-') err(`wrote ${target} (${reader.size} bytes, verified)`);
return 0;
}
async function mediaLs(flags: Flags): Promise {
const server = need(flags, 'server', 'SHADE_MEDIA_SERVER');
const res = await new MediaClient(server, await loadOwnerKey()).list();
for (const i of res.items) out(`${i.id} ${(i.size / 1048576).toFixed(1).padStart(9)} MiB ${new Date(i.createdAt).toISOString()}`);
err(`${res.items.length} item(s), ${(res.usage / 1048576).toFixed(1)} MiB`);
return 0;
}
async function mediaRm(pos: string[], flags: Flags): Promise {
const server = need(flags, 'server', 'SHADE_MEDIA_SERVER');
const target = pos[0];
if (target === undefined) throw new UsageError('usage: shade media rm --server URL');
let id: Uint8Array;
if (/^[0-9a-f]{32}$/.test(target)) {
id = Uint8Array.from(target.match(/../g)!.map((h) => parseInt(h, 16)));
} else {
const g = fromCapabilityUrl(target) as MediaGrant;
id = g.mediaId;
}
const ok = await new MediaClient(server, await loadOwnerKey()).delete(id);
err(ok ? 'deleted' : 'not found (or not yours)');
return ok ? 0 : 1;
}
// ─── live ────────────────────────────────────────────────────
interface ChannelFile {
channelId: string;
signingSecret: string;
channelSecret: string;
readToken: string;
epoch: number;
}
/**
* A channel that outlives the process: same id, same link, next epoch. Kept
* 0600 — it holds the signing key and the link secret.
*/
async function loadChannel(path: string | undefined, meta: MediaMeta): Promise<{ pub: LivePublisher; readToken: Uint8Array }> {
const rotateEvery = 20_000;
if (path === undefined) {
return { pub: new LivePublisher({ meta, channelSecret: randomBytes(32), rotateEvery }), readToken: randomBytes(32) };
}
let cf: ChannelFile | null = null;
try {
cf = JSON.parse(await readFile(path, 'utf8')) as ChannelFile;
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;
}
const next: ChannelFile = cf
? { ...cf, epoch: cf.epoch + 1 }
: {
channelId: toB64u(randomBytes(16)),
signingSecret: toB64u(randomBytes(32)),
channelSecret: toB64u(randomBytes(32)),
readToken: toB64u(randomBytes(32)),
epoch: 0,
};
await writeFile(path, JSON.stringify(next, null, 2), { mode: 0o600 });
await chmod(path, 0o600);
return {
pub: new LivePublisher({
meta,
channelId: fromB64u(next.channelId, 16),
signingSecret: fromB64u(next.signingSecret, 32),
channelSecret: fromB64u(next.channelSecret, 32),
epoch: next.epoch,
rotateEvery,
}),
readToken: fromB64u(next.readToken, 32),
};
}
async function startPublishing(flags: Flags, meta: MediaMeta): Promise<{ client: LivePublishClient; server: string }> {
const server = need(flags, 'server', 'SHADE_MEDIA_SERVER');
const { pub, readToken } = await loadChannel(str(flags, 'channel'), meta);
const client = new LivePublishClient({
relay: server,
publisher: pub,
readToken,
onViewers: (n) => err(`viewers: ${n}`),
onError: (m) => err(`relay: ${m}`),
onState: (s) => {
if (s === 'reconnecting') err('relay connection lost — reconnecting…');
},
});
await client.whenReady();
// Link mode: the link holds the channel secret and survives restarts.
out(watchLink(server, client.grant('oldest', true)));
return { client, server };
}
async function liveText(flags: Flags): Promise {
const meta: MediaMeta = { name: str(flags, 'name') ?? 'Live log', mime: 'text/plain' };
const { client } = await startPublishing(flags, meta);
await client.send({ type: 'meta', meta }, { sticky: true });
const batchMs = Number(str(flags, 'batch-ms') ?? 100);
const keyEvery = Number(str(flags, 'keyframe-every') ?? 20);
let pending = '';
let batches = 0;
// Only whole lines go out: a batch boundary must never split a log line.
// A partial line waits for its newline — unless it grows past the cap, or
// the input ends.
const flush = async (final = false) => {
const cut = final || pending.length > 256 * 1024 ? pending.length : pending.lastIndexOf('\n') + 1;
if (cut === 0) return;
const text = pending.slice(0, cut);
pending = pending.slice(cut);
// A keyframe every N batches bounds how far back a late viewer sees.
await client.send({ type: 'text', text }, { keyframe: batches++ % keyEvery === 0 });
};
const timer = setInterval(() => void flush(), batchMs);
const dec = new TextDecoder();
for await (const chunk of Bun.stdin.stream()) {
pending += dec.decode(chunk, { stream: true });
if (pending.length > 256 * 1024) await flush();
}
clearInterval(timer);
pending += dec.decode();
await flush(true);
await client.end();
return 0;
}
async function liveWebm(flags: Flags): Promise {
const meta: MediaMeta = { name: str(flags, 'name') ?? 'Live', mime: str(flags, 'mime') ?? 'video/webm' };
const { client } = await startPublishing(flags, meta);
const splitter = new WebmSplitter();
let clusters = 0;
const send = async (pieces: ReturnType) => {
for (const p of pieces) {
if (p.type === 'init') {
await client.send({ type: 'init', mime: p.mime, bytes: p.bytes }, { sticky: true });
err(`stream: ${p.mime}`);
} else {
await client.send({ type: 'chunk', bytes: p.bytes }, { keyframe: p.keyframe });
clusters++;
}
}
};
for await (const chunk of Bun.stdin.stream()) await send(splitter.push(chunk));
await send(splitter.finish());
err(`${clusters} clusters sent`);
await client.end();
return 0;
}
async function liveWatch(pos: string[]): Promise {
const link = pos[0];
if (link === undefined) throw new UsageError('usage: shade live watch ');
const g = fromCapabilityUrl(link);
if (g.kind !== 'shade.live-grant/v1') throw new UsageError('that link is a sealed file — use `shade media get`');
await new Promise((resolve) => {
const w = new LiveWatchClient(g, {
onFrame: (f) => {
const c = f.content;
if (c.type === 'text') process.stdout.write(c.text);
else if (c.type === 'end') {
w.close();
resolve();
}
},
onState: (s) => {
if (s === 'waiting') err('(waiting for the publisher)');
},
onError: (e) => err(`! ${e.message}`),
});
});
return 0;
}
export const MEDIA_HELP = `
media serve [--port 3910] [--dir ./shade-media-data]
Run a media relay: sealed store, live relay, watch page
media put --server URL [--name N] [--mime M] [--public] [--json]
Seal a film/video/image/song, upload it, print a watch link
media get [-o file|-]
Download and decrypt a sealed file
media ls --server URL Your uploads on that server
media rm --server URL
live text --server URL [--name N] [--channel file.json]
Publish stdin as a live log (tail -f app.log | shade live text …)
live webm --server URL [--name N] [--channel file.json]
Publish a WebM stream from stdin (ffmpeg … -f webm - | …)
live watch Follow a live text channel in the terminal
`;
/** Entry for `shade media …` / `shade live …`. Returns the exit code. */
export async function runMediaCli(group: 'media' | 'live', argv: string[]): Promise {
const [sub, ...rest] = argv;
const { pos, flags } = parseArgs(rest);
try {
if (group === 'media') {
switch (sub) {
case 'serve':
return await mediaServe(flags);
case 'put':
return await mediaPut(pos, flags);
case 'get':
return await mediaGet(pos, flags);
case 'ls':
return await mediaLs(flags);
case 'rm':
return await mediaRm(pos, flags);
}
} else {
switch (sub) {
case 'text':
return await liveText(flags);
case 'webm':
return await liveWebm(flags);
case 'watch':
return await liveWatch(pos);
}
}
err(`Usage:${MEDIA_HELP}`);
return 2;
} catch (e) {
err(e instanceof UsageError ? e.message : `error: ${(e as Error).message}`);
return 1;
}
}