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

@@ -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]