feat(media): @shade/media — seekable sealed media (SMF1), live channels, media routes and live relay
SMF1 seals a film, video, image or song once into a file any Range-capable store can serve; the reader fetches only segments under the playhead and checks each against a digest table pinned by the grant's root digest. Live channels use a sender-key chain with per-frame Ed25519 signatures, sticky init frames and keyframe snapshots for late joiners, and epoch rotation to remove a viewer. Server side: a disk-backed media store with signed owner uploads and a WebSocket relay with bounded backlog. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
109
packages/shade-media/src/client.ts
Normal file
109
packages/shade-media/src/client.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Client for the media routes: upload sealed files, list and delete your
|
||||
* own, and open anything you hold a grant for.
|
||||
*/
|
||||
|
||||
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)}`;
|
||||
}
|
||||
|
||||
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 }),
|
||||
},
|
||||
body: body as BodyInit,
|
||||
});
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
async list(): Promise<{ items: { id: string; size: number; createdAt: number }[]; usage: number }> {
|
||||
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}`);
|
||||
return res.json();
|
||||
}
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
Reference in New Issue
Block a user