Files
Shade/packages/shade-media/src/client.ts

115 lines
4.4 KiB
TypeScript
Raw Normal View History

/**
* 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 MediaList {
items: { id: string; size: number; createdAt: number }[];
usage: number;
}
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 Blob,
});
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<MediaList> {
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 (await res.json()) as MediaList;
}
}
/** 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);
}