feat(media): albums — one link for a season or a photo album; fix path traversal in media get

An album is a sealed file (shade.album/v1) listing grants, so the relay
cannot tell it from a film. `shade media put dir/` uploads every file and
the album (subdirectories nest, natural order); `media get` brings an
album back as a directory; /watch/ shows a grid with decrypted previews
and Back returns to the album without putting grants in history. Kotlin
reads albums (Albums.read) against a new shared vector.

Fixed: `media get` used the sealer-chosen meta.name as the output path.
Fixed a relay test race (flush() is sent, not received); the relay now
reports framesIn.

Verified: 64 TS tests x3, Kotlin 81/0, a 6-file album with a nested album
uploaded, browsed, played and downloaded back bit-identical.

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

View File

@@ -0,0 +1,91 @@
/**
* Albums: one link for many files.
*
* A season of a series, a photo album, a playlist, a wall of cameras. An
* album is itself a sealed file (SMF1) whose plaintext is a list of grants,
* with the MIME type `application/vnd.shade.album+json`. So:
*
* - one capability link opens every item, and nothing else;
* - the relay stores it like any other object: it cannot tell an album
* from a film, let alone count or name what is in it;
* - an album may hold live grants (a camera wall) and other albums.
*
* Holding an album means holding every item's keys. Deleting the album
* object does not revoke them from anyone who already opened it — delete
* the items to do that.
*/
import { MediaFormatError } from './errors.js';
import { encodeGrant, parseGrant } from './grant.js';
import type { Grant, MediaGrant } from './grant.js';
import type { MediaMeta } from './sealed.js';
export const ALBUM_KIND = 'shade.album/v1';
export const ALBUM_MIME = 'application/vnd.shade.album+json';
/** Enough for any season or camera roll, small enough to parse without thought. */
export const MAX_ALBUM_ITEMS = 10_000;
const MAX_TITLE = 512;
export interface Album {
title: string;
items: Grant[];
}
const enc = new TextEncoder();
const dec = new TextDecoder('utf-8', { fatal: true });
export function encodeAlbum(album: Album): Uint8Array {
checkTitle(album.title);
if (album.items.length > MAX_ALBUM_ITEMS) throw new MediaFormatError(`album holds more than ${MAX_ALBUM_ITEMS} items`);
// Grants are embedded as objects, each in its own wire form.
const items = album.items.map((g) => JSON.parse(encodeGrant(g)) as unknown);
return enc.encode(JSON.stringify({ kind: ALBUM_KIND, title: album.title, items }));
}
/** Parse an album's plaintext, strictly: every item must be a valid grant. */
export function parseAlbum(bytes: Uint8Array): Album {
let o: unknown;
try {
o = JSON.parse(dec.decode(bytes));
} catch {
throw new MediaFormatError('album is not UTF-8 JSON');
}
if (typeof o !== 'object' || o === null || Array.isArray(o)) throw new MediaFormatError('album must be an object');
const r = o as Record<string, unknown>;
if (r.kind !== ALBUM_KIND) throw new MediaFormatError(`not an album (kind ${String(r.kind)})`);
if (typeof r.title !== 'string') throw new MediaFormatError('album.title must be a string');
checkTitle(r.title);
if (!Array.isArray(r.items)) throw new MediaFormatError('album.items must be an array');
if (r.items.length > MAX_ALBUM_ITEMS) throw new MediaFormatError(`album holds more than ${MAX_ALBUM_ITEMS} items`);
const items = r.items.map((it, i) => {
if (typeof it !== 'object' || it === null || Array.isArray(it)) throw new MediaFormatError(`album item ${i} is not a grant`);
try {
return parseGrant(JSON.stringify(it));
} catch (e) {
throw new MediaFormatError(`album item ${i}: ${(e as Error).message}`);
}
});
return { title: r.title, items };
}
/** Does this grant (by its meta preview) or this sealed meta name an album? */
export function isAlbum(x: Grant | MediaMeta | undefined): boolean {
if (x === undefined) return false;
const meta = 'kind' in x ? x.meta : x;
return meta?.mime === ALBUM_MIME;
}
/** The meta an album's sealed file carries. */
export function albumMeta(title: string): MediaMeta {
return { mime: ALBUM_MIME, name: title };
}
/** Narrow for callers that only take sealed files. */
export function isMediaGrant(g: Grant): g is MediaGrant {
return g.kind === 'shade.media-grant/v1';
}
function checkTitle(t: string): void {
if (t.length > MAX_TITLE) throw new MediaFormatError(`album title longer than ${MAX_TITLE} characters`);
}

View File

@@ -6,21 +6,26 @@
* A sealed file plays through the Service Worker in a native element —
* `<video>`, `<audio>`, `<img>` or a text view — with seeking. A live
* channel plays through MSE (video/audio) or as a scrolling log (text),
* with images replacing each other in place.
* with images replacing each other in place. An album shows its items as a
* grid; opening one pushes a view, and Back returns to the album.
*
* The grant never leaves the browser: it is in the fragment, which is not
* sent to the server, and the page drops it from the address bar once read.
*/
import { ALBUM_MIME, parseAlbum } from '../album.js';
import type { Album } from '../album.js';
import { fromCapabilityUrl } from '../grant.js';
import type { LiveGrant, MediaGrant } from '../grant.js';
import type { Grant, LiveGrant, MediaGrant } from '../grant.js';
import { LiveWatchClient } from '../live/client.js';
import type { ReceivedFrame } from '../live/channel.js';
import { installMediaWorker } from './index.js';
import type { MediaKeyring } from './index.js';
import { LivePlayer } from './player.js';
interface Stats {
kind: 'media' | 'live' | 'none';
kind: 'media' | 'live' | 'album' | 'none';
items?: number;
state: string;
mime?: string;
frames: number;
@@ -57,16 +62,83 @@ function human(n: number): string {
return `${n.toFixed(i === 0 ? 0 : 1)} ${u[i]}`;
}
// ─── Views ──────────────────────────────────────────────────────
//
// A stack of views mirrored in the history, so Back leaves an item for its
// album. History entries hold only the depth: the grants stay in memory.
type View = () => Promise<void> | void;
const views: View[] = [];
let cleanups: (() => void)[] = [];
function reset(): void {
for (const c of cleanups) c();
cleanups = [];
const stage = $('#stage');
for (const m of stage.querySelectorAll('video, audio')) (m as HTMLMediaElement).pause();
stage.replaceChildren();
stage.className = '';
$('#actions').replaceChildren();
$('#sub').textContent = '';
Object.assign(stats, { kind: 'none', state: 'starting', frames: 0, lines: 0, images: 0 });
delete stats.error;
delete stats.player;
delete stats.items;
}
async function render(view: View): Promise<void> {
reset();
if (views.length > 1) {
const back = document.createElement('a');
back.href = '#';
back.id = 'back';
back.textContent = '← Back';
back.addEventListener('click', (e) => {
e.preventDefault();
history.back();
});
$('#actions').append(back);
}
try {
await view();
} catch (e) {
fail(String((e as Error)?.message ?? e));
}
}
function push(view: View): Promise<void> {
views.push(view);
history.pushState({ depth: views.length - 1 }, '');
return render(view);
}
window.addEventListener('popstate', (e: PopStateEvent) => {
const depth = Math.min((e.state as { depth?: number } | null)?.depth ?? 0, views.length - 1);
views.length = depth + 1;
void render(views[depth]!);
});
let keyring: Promise<MediaKeyring> | null = null;
function ring(): Promise<MediaKeyring> {
keyring ??= installMediaWorker(new URL('sw.js', location.href).pathname, new URL('./', location.href).pathname);
return keyring;
}
async function open(g: Grant): Promise<void> {
if (g.kind === 'shade.media-grant/v1') await playMedia(g);
else playLive(g);
}
async function playMedia(g: MediaGrant): Promise<void> {
stats.kind = 'media';
setStatus('starting the decryption worker…');
const keyring = await installMediaWorker(new URL('sw.js', location.href).pathname, new URL('./', location.href).pathname);
const src = await keyring.add(g);
const src = await (await ring()).add(g);
const head = await fetch(src, { method: 'HEAD' });
if (!head.ok) return fail(`could not open: ${head.status} ${await head.text()}`);
const mime = head.headers.get('content-type') ?? 'application/octet-stream';
const size = Number(head.headers.get('content-length'));
stats.mime = mime;
if (mime === ALBUM_MIME) return showAlbum(parseAlbum(new Uint8Array(await (await fetch(src)).arrayBuffer())));
const name = decodeURIComponent(/filename\*=UTF-8''([^;]+)/.exec(head.headers.get('content-disposition') ?? '')?.[1] ?? '');
$('#title').textContent = g.meta?.name ?? (name || 'Sealed media');
$('#sub').textContent = `${mime} · ${human(size)} · end-to-end encrypted`;
@@ -105,6 +177,73 @@ async function playMedia(g: MediaGrant): Promise<void> {
$('#actions').append(a);
}
/** What an item is, from its grant's meta preview (before opening it). */
function itemKind(g: Grant): string {
if (g.kind === 'shade.live-grant/v1') return 'live';
const mime = g.meta?.mime ?? '';
if (mime === ALBUM_MIME) return 'album';
return mime.split('/')[0] || 'file';
}
const ICONS: Record<string, string> = { album: '▦', audio: '♪', text: '≡', live: '●', file: '⬚', video: '▶', image: '◩' };
async function showAlbum(album: Album): Promise<void> {
stats.kind = 'album';
stats.items = album.items.length;
$('#title').textContent = album.title || 'Album';
const counts = new Map<string, number>();
for (const it of album.items) counts.set(itemKind(it), (counts.get(itemKind(it)) ?? 0) + 1);
$('#sub').textContent = `album · ${[...counts].map(([k, n]) => `${n} ${k}`).join(', ') || 'empty'} · end-to-end encrypted`;
const stage = $('#stage');
stage.className = 'album';
const grid = document.createElement('div');
grid.className = 'grid';
stage.append(grid);
const kr = await ring();
for (const [i, item] of album.items.entries()) {
const kind = itemKind(item);
const card = document.createElement('button');
card.className = 'card';
card.dataset.kind = kind;
const thumb = document.createElement('div');
thumb.className = 'thumb';
thumb.textContent = ICONS[kind] ?? ICONS.file!;
const label = document.createElement('div');
label.className = 'name';
label.textContent = item.meta?.name ?? `Item ${i + 1}`;
const sub = document.createElement('div');
sub.className = 'kind';
sub.textContent = kind === 'live' ? 'live channel' : kind === 'album' ? 'album' : (item.meta?.mime ?? kind);
card.append(thumb, label, sub);
card.addEventListener('click', () => void push(() => open(item)));
grid.append(card);
// Previews decrypt through the worker like the item itself: an image
// shows itself, a video its first frame. Fetched only as cards scroll in.
if (item.kind === 'shade.media-grant/v1' && (kind === 'image' || kind === 'video')) {
const io = new IntersectionObserver(async (entries) => {
if (!entries.some((e) => e.isIntersecting)) return;
io.disconnect();
const src = await kr.add(item);
if (kind === 'image') {
const img = document.createElement('img');
img.alt = '';
img.addEventListener('load', () => thumb.replaceChildren(img));
img.src = src;
} else {
const v = document.createElement('video');
v.muted = true;
v.preload = 'metadata';
v.addEventListener('loadeddata', () => thumb.replaceChildren(v));
v.src = `${src}#t=1`;
}
});
io.observe(card);
cleanups.push(() => io.disconnect());
}
}
setStatus(`${album.items.length} item(s)`);
}
function playLive(g: LiveGrant): void {
stats.kind = 'live';
$('#title').textContent = g.meta?.name ?? 'Live channel';
@@ -157,9 +296,11 @@ function playLive(g: LiveGrant): void {
el.id = 'player';
stage.append(el);
const player = new LivePlayer(el, g, { onState: states, onError: onErr, onOther: other });
cleanups.push(() => player.close());
stats.player = () => ({ ...player.stats(), currentTime: el.currentTime, paused: el.paused, readyState: el.readyState });
} else {
new LiveWatchClient(g, { onFrame: other, onState: states, onError: onErr });
const client = new LiveWatchClient(g, { onFrame: other, onState: states, onError: onErr });
cleanups.push(() => client.close());
}
}
@@ -172,9 +313,9 @@ async function main(): Promise<void> {
return fail(`no grant in this link — ${(e as Error).message}`);
}
// Keep the key out of the history and out of anything that reads the URL later.
history.replaceState(null, '', location.pathname + location.search);
if (grant.kind === 'shade.media-grant/v1') await playMedia(grant);
else playLive(grant);
history.replaceState({ depth: 0 }, '', location.pathname + location.search);
views.push(() => open(grant));
await render(views[0]!);
}
main().catch((e) => fail(String((e as Error)?.message ?? e)));

View File

@@ -3,6 +3,7 @@
*
* shade media serve relay + media store + watch page
* shade media put film.mkv --server URL seal, upload, print a watch link
* shade media put Season1/ --server URL every file, plus an album: one link for all
* shade media get <link> -o out.mkv download and decrypt
* shade media ls|rm --server URL
* tail -f app.log | shade live text --server URL --name "app logs"
@@ -13,12 +14,14 @@
* `$XDG_CONFIG_HOME/shade/` and reused; nothing to configure.
*/
import { chmod, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { chmod, mkdir, readdir, 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 { ALBUM_MIME } from './album.js';
import type { Album } from './album.js';
import { MediaClient, openGrant, readAlbum } from './client.js';
import { encodeGrant, fromCapabilityUrl, toCapabilityUrl } from './grant.js';
import type { Grant, MediaGrant } from './grant.js';
import { LivePublisher } from './live/channel.js';
@@ -130,47 +133,147 @@ async function mediaServe(flags: Flags): Promise<number> {
return 0;
}
/**
* `media put a.mkv b.jpg Season1/ …`: one path that is a file uploads that
* file; several paths, a directory or `--album T` upload every file and then
* an album that holds them all, and print the album's link. Directories
* become nested albums, in natural order (episode 2 before episode 10).
*/
async function mediaPut(pos: string[], flags: Flags): Promise<number> {
const file = pos[0];
if (file === undefined) throw new UsageError('usage: shade media put <file> --server URL');
if (pos.length === 0) throw new UsageError('usage: shade media put <file|dir>… --server URL [--album T]');
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 client = new MediaClient(server, await loadOwnerKey());
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 });
const albumTitle = str(flags, 'album');
const oneDir = pos.length === 1 && (await stat(pos[0]!)).isDirectory();
let grant: MediaGrant;
if (pos.length === 1 && !oneDir && albumTitle === undefined) {
grant = await putFile(client, pos[0]!, flags, str(flags, 'name'));
} else if (oneDir) {
// The directory is the album (`--album` renames it), not an album inside one.
grant = await putPath(client, pos[0]!, flags, albumTitle);
} else {
const items: Grant[] = [];
for (const p of pos) items.push(await putPath(client, p, flags));
const title = albumTitle ?? 'Album';
grant = await client.uploadAlbum({ title, items }, putOpts(flags));
err(`album "${title}": ${items.length} item(s)`);
}
err(`done in ${((Date.now() - started) / 1000).toFixed(1)} s`);
out(flags.json === true ? encodeGrant(grant) : watchLink(server, grant));
return 0;
}
const naturally = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
/** A file, or a directory as an album of its (non-hidden) entries. */
async function putPath(client: MediaClient, path: string, flags: Flags, titled?: string): Promise<MediaGrant> {
if (!(await stat(path)).isDirectory()) return putFile(client, path, flags);
const names = (await readdir(path)).filter((n) => !n.startsWith('.')).sort(naturally.compare);
const items: Grant[] = [];
for (const n of names) items.push(await putPath(client, join(path, n), flags));
const title = titled ?? basename(path.replace(/\/+$/, ''));
err(`album "${title}": ${items.length} item(s)`);
return client.uploadAlbum({ title, items }, putOpts(flags));
}
function putOpts(flags: Flags): { readToken?: null } {
return flags.public === true ? { readToken: null } : {};
}
async function putFile(client: MediaClient, file: string, flags: Flags, name?: string): Promise<MediaGrant> {
const meta: MediaMeta = { name: name ?? basename(file) };
// --mime names one file's type; in an album every file is guessed.
const mime = (name !== undefined || flags.album === undefined ? str(flags, 'mime') : undefined) ?? guessMime(file);
if (mime !== undefined) meta.mime = mime;
const size = (await stat(file)).size;
const tmp = join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`);
try {
err(`sealing ${basename(file)} (${(size / 1048576).toFixed(1)} MiB)…`);
const result = await sealFile(file, tmp, { meta });
return await client.putSealed(result, Bun.file(tmp), { meta, ...putOpts(flags) });
} finally {
await rm(tmp, { force: true });
}
}
/**
* `media get <link> [-o path|-]`: a file is written to `path` (default: its
* own name); an album becomes a directory of its items, nested albums as
* subdirectories. Live items cannot be downloaded; their links are listed.
*/
async function mediaGet(pos: string[], flags: Flags): Promise<number> {
const link = pos[0];
if (link === undefined) throw new UsageError('usage: shade media get <link> [-o file]');
if (link === undefined) throw new UsageError('usage: shade media get <link> [-o file|dir|-]');
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 target = str(flags, 'out');
const reader = await openGrant(g);
const target = str(flags, 'out') ?? reader.meta.name ?? 'shade-media.bin';
const ws = target === '-' ? process.stdout : createWriteStream(target);
if (reader.meta.mime === ALBUM_MIME && target !== '-') {
const album = await readAlbum(reader);
const dir = target ?? safeName(album.title, 'album');
const n = await getAlbum(album, dir, server(g));
err(`wrote ${dir}/ (${n} file(s), verified)`);
return 0;
}
const path = target ?? safeName(reader.meta.name, 'shade-media.bin');
await writeReader(reader, path);
if (path !== '-') err(`wrote ${path} (${reader.size} bytes, verified)`);
return 0;
}
/** Origin of the relay a grant points at, for watch links of live items. */
function server(g: MediaGrant): string {
return g.url !== undefined ? new URL(g.url).origin : 'http://localhost';
}
async function writeReader(reader: Awaited<ReturnType<typeof openGrant>>, path: string): Promise<void> {
const ws = path === '-' ? process.stdout : createWriteStream(path);
for await (const chunk of reader.stream()) {
if (!ws.write(chunk)) await new Promise<void>((r) => ws.once('drain', () => r()));
}
if (ws !== process.stdout) await new Promise<void>((r) => (ws as ReturnType<typeof createWriteStream>).end(() => r()));
if (target !== '-') err(`wrote ${target} (${reader.size} bytes, verified)`);
return 0;
}
async function getAlbum(album: Album, dir: string, relay: string): Promise<number> {
await mkdir(dir, { recursive: true });
const taken = new Set<string>();
// Names come from whoever sealed the files: never a path, never twice.
const unique = (name: string) => {
let n = name;
const ext = extname(name);
for (let i = 2; taken.has(n.toLowerCase()); i++) n = `${name.slice(0, name.length - ext.length)} (${i})${ext}`;
taken.add(n.toLowerCase());
return n;
};
let files = 0;
for (const [i, item] of album.items.entries()) {
const fallback = `item-${i + 1}`;
if (item.kind !== 'shade.media-grant/v1') {
err(` live: ${item.meta?.name ?? fallback} ${watchLink(relay, item)}`);
continue;
}
const reader = await openGrant(item);
if (reader.meta.mime === ALBUM_MIME) {
files += await getAlbum(await readAlbum(reader), join(dir, unique(safeName(reader.meta.name, fallback))), relay);
} else {
const path = join(dir, unique(safeName(reader.meta.name, fallback)));
await writeReader(reader, path);
err(` ${path}`);
files++;
}
}
return files;
}
/**
* A display name made safe as one path component: the last segment only,
* no control characters, no leading dots (no `..`, no hidden files).
*/
export function safeName(name: string | undefined, fallback: string): string {
const last = (name ?? '').split(/[\\/]/).pop() ?? '';
const clean = last.replace(/[\u0000-\u001f\u007f]/g, '').replace(/^[.\s]+/, '').trim().slice(0, 200);
return clean.length > 0 ? clean : fallback;
}
async function mediaLs(flags: Flags): Promise<number> {
@@ -371,10 +474,11 @@ export const MEDIA_HELP = `
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|-]
Download and decrypt a sealed file
media put <file|dir>… --server URL [--album T] [--name N] [--mime M] [--public] [--json]
Seal a film/video/image/song, upload it, print a watch link.
Several files or a directory become an album: one link for all.
media get <link> [-o file|dir|-]
Download and decrypt a sealed file (an album: a directory)
media ls --server URL Your uploads on that server
media rm <link|id> --server URL
live text --server URL [--name N] [--channel file.json]

View File

@@ -3,6 +3,8 @@
* own, and open anything you hold a grant for.
*/
import { ALBUM_MIME, albumMeta, encodeAlbum, parseAlbum } from './album.js';
import type { Album } from './album.js';
import { randomBytes, sha256, toB64u, toHex } from './bytes.js';
import { MediaFormatError } from './errors.js';
import { mediaGrantFrom, mediaKeysOf } from './grant.js';
@@ -79,6 +81,12 @@ export class MediaClient {
return this.putSealed(result, bytes, opts.meta !== undefined ? { ...opts, meta: opts.meta } : opts);
}
/** Seal and upload an album; the grant opens every item in it. */
async uploadAlbum(album: Album, opts: Omit<PutOptions, 'meta'> = {}): Promise<MediaGrant> {
const meta = albumMeta(album.title);
return this.uploadBytes(encodeAlbum(album), { ...opts, meta });
}
async delete(mediaId: Uint8Array): Promise<boolean> {
const id = toHex(mediaId);
const res = await this.fetchFn(mediaUrl(this.server, mediaId), {
@@ -112,3 +120,21 @@ export function openGrant(
});
return MediaReader.open(source, mediaKeysOf(grant), opts);
}
/** An album holds at most 10 000 grants of well under 1 KiB each. */
const MAX_ALBUM_BYTES = 16 * 1024 * 1024;
/** Open a granted album and read its items. */
export async function openAlbum(
grant: MediaGrant,
opts: ReaderOptions & { fetch?: typeof fetch; url?: string } = {},
): Promise<Album> {
return readAlbum(await openGrant(grant, opts));
}
/** The items of an album already opened as a reader. */
export async function readAlbum(reader: MediaReader): Promise<Album> {
if (reader.meta.mime !== ALBUM_MIME) throw new MediaFormatError(`not an album (${reader.meta.mime ?? 'no type'})`);
if (reader.size > MAX_ALBUM_BYTES) throw new MediaFormatError('album larger than 16 MiB');
return parseAlbum(await reader.read(0, reader.size));
}

View File

@@ -20,7 +20,9 @@ export type { RangeSource, HttpRangeSourceOptions } from './source.js';
export * from './grant.js';
export { OwnerKey, verifyOwner, READ_TOKEN_HEADER, READ_HASH_HEADER } from './owner.js';
export type { OwnerOp } from './owner.js';
export { MediaClient, openGrant, mediaUrl } from './client.js';
export { MediaClient, openGrant, openAlbum, readAlbum, mediaUrl } from './client.js';
export { ALBUM_KIND, ALBUM_MIME, MAX_ALBUM_ITEMS, encodeAlbum, parseAlbum, isAlbum, albumMeta, isMediaGrant } from './album.js';
export type { Album } from './album.js';
export type { PutOptions } from './client.js';
export { LivePublisher, LiveSubscriber, epochKeys, chainStep, MAX_SKIP, MAX_SKIPPED_KEYS } from './live/channel.js';
export type { FrameOptions, PublisherOptions, GrantOptions, ReceivedFrame } from './live/channel.js';

View File

@@ -165,7 +165,8 @@ function toBytes(data: unknown): Uint8Array | null {
export interface LiveRelay {
app: Hono;
/** Channels currently held, for metrics and tests. */
stats(): { channels: number; viewers: number; backlogBytes: number };
/** `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;
@@ -178,6 +179,7 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
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;
@@ -284,6 +286,7 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
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;
}
@@ -441,7 +444,7 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
viewers += ch.viewers.size;
backlogBytes += ch.backlogBytes;
}
return { channels: channels.size, viewers, backlogBytes };
return { channels: channels.size, viewers, backlogBytes, framesIn };
},
sweep,
stop() {

View File

@@ -39,6 +39,16 @@ const HTML = `<!doctype html>
#status[data-tone="warn"]::before { background: var(--warn); }
#status[data-tone="bad"]::before { background: var(--bad); }
#status[data-tone="bad"] { color: var(--bad); }
#stage.album { background: transparent; border: 0; border-radius: 0; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 14px; }
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; cursor: pointer; text-align: left; color: inherit; font: inherit; padding: 0; display: block; }
.card:hover, .card:focus-visible { border-color: var(--dim); outline: none; }
#stage .thumb { aspect-ratio: 16 / 9; background: #000; display: grid; place-items: center; color: var(--dim); font-size: 30px; overflow: hidden; }
#stage .thumb img, #stage .thumb video { width: 100%; height: 100%; max-height: none; object-fit: cover; }
.card .name { padding: 9px 11px 2px; font-size: 13.5px; overflow-wrap: anywhere; }
.card .kind { padding: 0 11px 10px; font-size: 12px; color: var(--dim); }
.card[data-kind="live"] .thumb { color: var(--bad); }
#actions { display: inline-flex; gap: 8px; }
#actions a { color: var(--text); font-size: 13px; text-decoration: none; border: 1px solid var(--line); padding: 6px 12px; border-radius: 6px; }
#actions a:hover { border-color: var(--dim); }
</style>

View File

@@ -0,0 +1,112 @@
import { describe, test, expect } from 'bun:test';
import { Hono } from 'hono';
import { createMediaRoutes, MemoryMediaStore } from '../src/server.js';
import {
ALBUM_MIME,
MAX_ALBUM_ITEMS,
MediaClient,
MediaFormatError,
OwnerKey,
LivePublisher,
encodeAlbum,
isAlbum,
openAlbum,
openGrant,
parseAlbum,
} from '../src/index.js';
import type { Grant, MediaGrant } from '../src/index.js';
import { safeName } from '../src/cli.js';
const enc = new TextEncoder();
function serve() {
const app = new Hono();
app.route('/', createMediaRoutes(new MemoryMediaStore()));
const server = Bun.serve({ port: 0, fetch: (req) => app.fetch(req) });
return { server, base: `http://localhost:${server.port}` };
}
describe('album format', () => {
const live = new LivePublisher({ meta: { name: 'Kamera 1', mime: 'video/webm' } }).grant({ from: 'now' });
test('round trip keeps every grant, media and live, byte for byte', async () => {
const { server, base } = serve();
try {
const client = new MediaClient(base, OwnerKey.generate());
const a = await client.uploadBytes(enc.encode('one'), { meta: { name: 'E01.mkv', mime: 'video/x-matroska' } });
const b = await client.uploadBytes(enc.encode('two'), { meta: { name: 'cover.jpg', mime: 'image/jpeg' } });
const items: Grant[] = [a, b, live];
const back = parseAlbum(encodeAlbum({ title: 'Sesong 1 — «Vinter»', items }));
expect(back.title).toBe('Sesong 1 — «Vinter»');
expect(back.items).toEqual(items);
} finally {
server.stop(true);
}
});
test('strict: wrong kind, bad items, too many items, junk', () => {
const wrap = (o: unknown) => enc.encode(JSON.stringify(o));
expect(() => parseAlbum(wrap({ kind: 'shade.album/v2', title: '', items: [] }))).toThrow(MediaFormatError);
expect(() => parseAlbum(wrap({ kind: 'shade.album/v1', title: 1, items: [] }))).toThrow(/title/);
expect(() => parseAlbum(wrap({ kind: 'shade.album/v1', title: '', items: [{ kind: 'shade.media-grant/v1' }] }))).toThrow(/item 0/);
expect(() => parseAlbum(wrap({ kind: 'shade.album/v1', title: '', items: ['x'] }))).toThrow(/item 0/);
expect(() => parseAlbum(wrap({ kind: 'shade.album/v1', title: '', items: new Array(MAX_ALBUM_ITEMS + 1).fill({}) }))).toThrow(/more than/);
expect(() => parseAlbum(enc.encode('{"kind":'))).toThrow(MediaFormatError);
expect(() => parseAlbum(new Uint8Array([0xff, 0xfe]))).toThrow(MediaFormatError);
expect(() => encodeAlbum({ title: 'x'.repeat(513), items: [] })).toThrow(/title/);
});
});
describe('albums over the media routes', () => {
test('upload items + album; one grant opens all; the relay sees one more opaque object', async () => {
const { server, base } = serve();
try {
const client = new MediaClient(base, OwnerKey.generate());
const files = ['E01', 'E02', 'E10'].map((n, i) => ({ name: `${n}.webm`, bytes: enc.encode(`episode ${i}`.repeat(1000)) }));
const grants: MediaGrant[] = [];
for (const f of files) grants.push(await client.uploadBytes(f.bytes, { meta: { name: f.name, mime: 'video/webm' } }));
const inner = await client.uploadAlbum({ title: 'Extras', items: [grants[0]!] });
const album = await client.uploadAlbum({ title: 'Sesong 1', items: [...grants, inner] });
expect(isAlbum(album)).toBe(true);
expect(isAlbum(grants[0])).toBe(false);
// The grant alone is enough: open the album, then every item in it.
const opened = await openAlbum(album);
expect(opened.title).toBe('Sesong 1');
expect(opened.items.map((g) => g.meta?.name)).toEqual(['E01.webm', 'E02.webm', 'E10.webm', 'Extras']);
for (const [i, f] of files.entries()) {
const r = await openGrant(opened.items[i] as MediaGrant);
expect(Buffer.from(await r.read(0, r.size)).equals(Buffer.from(f.bytes))).toBe(true);
}
expect((await openAlbum(opened.items[3] as MediaGrant)).items[0]).toEqual(grants[0]!);
// A film is not an album.
await expect(openAlbum(grants[0]!)).rejects.toThrow(/not an album/);
// What the relay holds: five sealed objects of plain sizes, no names, no
// types, nothing linking the album to its items.
const list = await client.list();
expect(list.items.length).toBe(5);
const raw = await (await fetch(album.url!, { headers: { 'x-shade-read': Buffer.from(album.readToken!).toString('base64url') } })).arrayBuffer();
const text = Buffer.from(raw).toString('latin1');
for (const leak of ['Sesong', 'E01', ALBUM_MIME, 'shade.album', 'shade.media-grant']) expect(text.includes(leak)).toBe(false);
} finally {
server.stop(true);
}
});
});
describe('safeName: names from a sealed file never become paths', () => {
test.each([
['film.mkv', 'film.mkv'],
['../../.bashrc', 'bashrc'],
['/etc/passwd', 'passwd'],
['C:\\Windows\\evil.dll', 'evil.dll'],
['..', 'fallback'],
['.hidden', 'hidden'],
['a\u0000b\u001fc\u007f.txt', 'abc.txt'],
[' ', 'fallback'],
[undefined, 'fallback'],
] as const)('%p → %p', (input, want) => {
expect(safeName(input, 'fallback')).toBe(want);
});
});

View File

@@ -191,7 +191,9 @@ describe('live relay over real WebSockets', () => {
for (let i = 0; i < 30; i++) {
await client.send({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: i % 10 === 0 });
}
await client.flush();
// flush() means sent, not received: wait until the relay holds all 31,
// or a fast viewer joins mid-burst and (correctly) gets an older backlog.
await until(() => relay.stats().framesIn === 31);
const early: ReceivedFrame[] = [];
const grant = parseGrant(encodeGrant(client.grant('oldest'))) as LiveGrant;