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

@@ -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)));