2026-10-18 20:41:31 +02:00
|
|
|
/**
|
|
|
|
|
* Client for the media routes: upload sealed files, list and delete your
|
|
|
|
|
* own, and open anything you hold a grant for.
|
|
|
|
|
*/
|
|
|
|
|
|
2026-10-18 21:44:43 +02:00
|
|
|
import { ALBUM_MIME, albumMeta, encodeAlbum, parseAlbum } from './album.js';
|
|
|
|
|
import type { Album } from './album.js';
|
2026-10-18 20:41:31 +02:00
|
|
|
import { randomBytes, sha256, toB64u, toHex } from './bytes.js';
|
|
|
|
|
import { MediaFormatError } from './errors.js';
|
|
|
|
|
import { mediaGrantFrom, mediaKeysOf } from './grant.js';
|
|
|
|
|
import type { MediaGrant } from './grant.js';
|
|
|
|
|
import { READ_HASH_HEADER, READ_TOKEN_HEADER } from './owner.js';
|
|
|
|
|
import type { OwnerKey } from './owner.js';
|
|
|
|
|
import { MediaReader, sealMediaBytes } from './sealed.js';
|
|
|
|
|
import type { MediaMeta, ReaderOptions, SealOptions, SealResult } from './sealed.js';
|
|
|
|
|
import { HttpRangeSource } from './source.js';
|
|
|
|
|
|
|
|
|
|
export function mediaUrl(server: string, mediaId: Uint8Array): string {
|
|
|
|
|
return `${server.replace(/\/$/, '')}/v1/media/${toHex(mediaId)}`;
|
|
|
|
|
}
|
|
|
|
|
|
feat(media): browser playback, live WebM and log streaming, shade media/live CLI
- Service Worker plays sealed files in native <video>/<audio>/<img> with
Range seeking; watch page served by the relay itself (#shade= fragment
links, grant never sent to a server)
- MSE live player with keyframe-aware joining, gap detection, latency control
- WebM splitter (init + clusters, keyframe detection) that puts blocks in
timecode order — Chrome rejects ffmpeg's interleaved Opus/VP8 otherwise
- Link mode for live channels: epoch seeds from a channel secret, so a
link survives publisher restarts and scheduled rotations
- File store streams byte ranges itself (Bun.file().slice() in a Response
sent whole files to Range requests)
- shade media serve|put|get|ls|rm, shade live text|webm|watch
Verified end to end in headless Chromium: VP9/Opus film plays and seeks,
live VP8/Opus at 2.9 s latency, live logs, sealed JPEG and Opus audio.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:01:52 +02:00
|
|
|
export interface MediaList {
|
|
|
|
|
items: { id: string; size: number; createdAt: number }[];
|
|
|
|
|
usage: number;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-18 20:41:31 +02:00
|
|
|
export interface PutOptions {
|
|
|
|
|
/** Token viewers must present. Default: a fresh random one per file. `null` = public ciphertext. */
|
|
|
|
|
readToken?: Uint8Array | null;
|
|
|
|
|
/** Copied into the grant so a library can list titles without opening each file. */
|
|
|
|
|
meta?: MediaMeta;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export class MediaClient {
|
|
|
|
|
private readonly fetchFn: typeof fetch;
|
|
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
|
private readonly server: string,
|
|
|
|
|
private readonly owner: OwnerKey,
|
|
|
|
|
opts: { fetch?: typeof fetch } = {},
|
|
|
|
|
) {
|
|
|
|
|
this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Upload an already sealed file. `body` must be exactly `result.sealedSize`
|
|
|
|
|
* bytes — a Blob/`Bun.file` streams from disk without loading the film.
|
|
|
|
|
*/
|
|
|
|
|
async putSealed(result: SealResult, body: Blob | Uint8Array, opts: PutOptions = {}): Promise<MediaGrant> {
|
|
|
|
|
const size = body instanceof Uint8Array ? body.length : body.size;
|
|
|
|
|
if (size !== result.sealedSize) {
|
|
|
|
|
throw new MediaFormatError(`body is ${size} bytes, the seal produced ${result.sealedSize}`);
|
|
|
|
|
}
|
|
|
|
|
const readToken = opts.readToken === undefined ? randomBytes(32) : opts.readToken;
|
|
|
|
|
const readTokenHash = readToken === null ? '' : toHex(await sha256(readToken));
|
|
|
|
|
const id = toHex(result.mediaId);
|
|
|
|
|
const url = mediaUrl(this.server, result.mediaId);
|
|
|
|
|
const res = await this.fetchFn(url, {
|
|
|
|
|
method: 'PUT',
|
|
|
|
|
headers: {
|
|
|
|
|
'content-type': 'application/vnd.shade.smf1',
|
|
|
|
|
'content-length': String(size),
|
|
|
|
|
...(readTokenHash !== '' ? { [READ_HASH_HEADER]: readTokenHash } : {}),
|
|
|
|
|
...this.owner.headers({ op: 'put', id, size, readTokenHash }),
|
|
|
|
|
},
|
feat(media): browser playback, live WebM and log streaming, shade media/live CLI
- Service Worker plays sealed files in native <video>/<audio>/<img> with
Range seeking; watch page served by the relay itself (#shade= fragment
links, grant never sent to a server)
- MSE live player with keyframe-aware joining, gap detection, latency control
- WebM splitter (init + clusters, keyframe detection) that puts blocks in
timecode order — Chrome rejects ffmpeg's interleaved Opus/VP8 otherwise
- Link mode for live channels: epoch seeds from a channel secret, so a
link survives publisher restarts and scheduled rotations
- File store streams byte ranges itself (Bun.file().slice() in a Response
sent whole files to Range requests)
- shade media serve|put|get|ls|rm, shade live text|webm|watch
Verified end to end in headless Chromium: VP9/Opus film plays and seeks,
live VP8/Opus at 2.9 s latency, live logs, sealed JPEG and Opus audio.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:01:52 +02:00
|
|
|
body: body as Blob,
|
2026-10-18 20:41:31 +02:00
|
|
|
});
|
|
|
|
|
if (res.status !== 201) {
|
|
|
|
|
throw new Error(`upload failed: HTTP ${res.status} ${await res.text().catch(() => '')}`);
|
|
|
|
|
}
|
|
|
|
|
return mediaGrantFrom(result, {
|
|
|
|
|
url,
|
|
|
|
|
...(readToken !== null ? { readToken } : {}),
|
|
|
|
|
...(opts.meta !== undefined ? { meta: opts.meta } : {}),
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Seal in memory and upload — images, clips, documents. */
|
|
|
|
|
async uploadBytes(plaintext: Uint8Array, opts: SealOptions & PutOptions = {}): Promise<MediaGrant> {
|
|
|
|
|
const { bytes, result } = await sealMediaBytes(plaintext, opts);
|
|
|
|
|
return this.putSealed(result, bytes, opts.meta !== undefined ? { ...opts, meta: opts.meta } : opts);
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-18 21:44:43 +02:00
|
|
|
/** 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 });
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-18 20:41:31 +02:00
|
|
|
async delete(mediaId: Uint8Array): Promise<boolean> {
|
|
|
|
|
const id = toHex(mediaId);
|
|
|
|
|
const res = await this.fetchFn(mediaUrl(this.server, mediaId), {
|
|
|
|
|
method: 'DELETE',
|
|
|
|
|
headers: this.owner.headers({ op: 'delete', id }),
|
|
|
|
|
});
|
|
|
|
|
if (res.status === 404) return false;
|
|
|
|
|
if (!res.ok) throw new Error(`delete failed: HTTP ${res.status}`);
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
feat(media): browser playback, live WebM and log streaming, shade media/live CLI
- Service Worker plays sealed files in native <video>/<audio>/<img> with
Range seeking; watch page served by the relay itself (#shade= fragment
links, grant never sent to a server)
- MSE live player with keyframe-aware joining, gap detection, latency control
- WebM splitter (init + clusters, keyframe detection) that puts blocks in
timecode order — Chrome rejects ffmpeg's interleaved Opus/VP8 otherwise
- Link mode for live channels: epoch seeds from a channel secret, so a
link survives publisher restarts and scheduled rotations
- File store streams byte ranges itself (Bun.file().slice() in a Response
sent whole files to Range requests)
- shade media serve|put|get|ls|rm, shade live text|webm|watch
Verified end to end in headless Chromium: VP9/Opus film plays and seeks,
live VP8/Opus at 2.9 s latency, live logs, sealed JPEG and Opus audio.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:01:52 +02:00
|
|
|
async list(): Promise<MediaList> {
|
2026-10-18 20:41:31 +02:00
|
|
|
const res = await this.fetchFn(`${this.server.replace(/\/$/, '')}/v1/media`, {
|
|
|
|
|
headers: this.owner.headers({ op: 'list' }),
|
|
|
|
|
});
|
|
|
|
|
if (!res.ok) throw new Error(`list failed: HTTP ${res.status}`);
|
feat(media): browser playback, live WebM and log streaming, shade media/live CLI
- Service Worker plays sealed files in native <video>/<audio>/<img> with
Range seeking; watch page served by the relay itself (#shade= fragment
links, grant never sent to a server)
- MSE live player with keyframe-aware joining, gap detection, latency control
- WebM splitter (init + clusters, keyframe detection) that puts blocks in
timecode order — Chrome rejects ffmpeg's interleaved Opus/VP8 otherwise
- Link mode for live channels: epoch seeds from a channel secret, so a
link survives publisher restarts and scheduled rotations
- File store streams byte ranges itself (Bun.file().slice() in a Response
sent whole files to Range requests)
- shade media serve|put|get|ls|rm, shade live text|webm|watch
Verified end to end in headless Chromium: VP9/Opus film plays and seeks,
live VP8/Opus at 2.9 s latency, live logs, sealed JPEG and Opus audio.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:01:52 +02:00
|
|
|
return (await res.json()) as MediaList;
|
2026-10-18 20:41:31 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Open a granted file over HTTP. */
|
|
|
|
|
export function openGrant(
|
|
|
|
|
grant: MediaGrant,
|
|
|
|
|
opts: ReaderOptions & { fetch?: typeof fetch; url?: string } = {},
|
|
|
|
|
): Promise<MediaReader> {
|
|
|
|
|
const url = opts.url ?? grant.url;
|
|
|
|
|
if (url === undefined) throw new MediaFormatError('grant has no URL');
|
|
|
|
|
const source = new HttpRangeSource(url, {
|
|
|
|
|
...(grant.readToken !== undefined ? { headers: { [READ_TOKEN_HEADER]: toB64u(grant.readToken) } } : {}),
|
|
|
|
|
...(opts.fetch !== undefined ? { fetch: opts.fetch } : {}),
|
|
|
|
|
});
|
|
|
|
|
return MediaReader.open(source, mediaKeysOf(grant), opts);
|
|
|
|
|
}
|
2026-10-18 21:44:43 +02:00
|
|
|
|
|
|
|
|
/** 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));
|
|
|
|
|
}
|