Cotton code
805 lines · 42.1 KB · TypeScriptRaw
/** * The personal database's media: the bytes its rows name, in R2, for the * owner alone. * * A KEY IS THE ROW'S OWN. A row keeps the media key the Mac gave it — * `<database id>/photos/<sha256>.jpg`, `<database id>/messages/<thread>/<sha256>.png`, * `<database id>/meetings/<id>/full.m4a` — and the object stores those bytes in * the MEDIA bucket at `<slug>/<the rest of the key>`: `asha/photos/<sha256>.jpg`, * one folder per kind. Nothing is renamed, so a row read anywhere names its * bytes by the same key. * * - `PUT /v1/media/<key>` (the owner; the body is the bytes, with their *   content-type): stores the bytes unless the key holds them already, and *   counts what they add to the object's media; past MEDIA_CAP_BYTES *   (src/business.ts) it refuses, `object_full`. One request carries at most *   MEDIA_MAX_BYTES (the host's own request limit refuses more before the *   Worker sees it), so a larger file goes in parts: * - `POST /v1/media/<key>?uploads { size, content_type }` starts one — or *   answers `{ stored: false }` when the key holds those bytes already — and *   refuses `object_full` up front when the whole would not fit; * - `PUT /v1/media/<key>?upload=<id>&part=<n>` (n from 1) carries one part, *   every part but the last the same size and at least PART_MIN_BYTES, and *   answers its `etag`; * - `POST /v1/media/<key>?upload=<id> { parts: [{ part, etag }] }` puts them *   together under the key and counts what they add, as a PUT does. * - `POST /v1/media/missing { keys, sealed? }` (the owner, at most 500): which *   keys the bucket does not hold yet, so an import uploads only those; with *   `sealed: true`, which it does not hold sealed. * - `DELETE /v1/media/<key>` (the owner): the one key goes, and what it held *   comes off the object's media count; `{ deleted: 1, bytes }`, 404 when the *   bucket holds nothing there. * - `DELETE /v1/media/<folder>/?prefix=1` (the owner): everything under a *   folder at least two deep (`<database id>/films/<film id>/`, never a kind's *   whole folder nor the database's) goes, a thousand keys at a time, counted *   off the same way; `{ deleted, bytes }`, 404 when the folder is empty. * - `GET /v1/media/<key>[?width=&height=&fit=]` (the owner): the bytes, a *   single `Range: bytes=…` answered 206; an image asked at a size comes *   resized through the Images binding — it reads the bytes from R2 itself, *   so it works on a workers.dev host and on a custom domain alike, and the *   media need no public URL. The phone asks for the size it draws; nothing *   makes thumbnails ahead of it. * * A KIT'S TILE PICTURES ARE THE OBJECT'S TOO. A tool's fan tile names kit * pictures by reference (`photo:<sha256>`, its `fan_tile`, crates/cotton-core * `definitions::fan_tile`), and the phone asks for one as it asks for a tool's * picture: from the package's assets it holds, else here. So * `GET /v1/media/photo:<sha256>` answers a picture the Worker's kit carries * from the Worker's static assets (ASSETS, `/kit-pictures/<sha256>.png`, a * folder scripts/kit.ts generates), content-addressed and immutable, with no * R2 key, no row and no manifest: ASSETS answering 404 is the "no kit * picture" answer, and the key is read from R2 like any other. a pictogram changed in the kit reaches a * signed-in phone with the deploy, never with a new build (owner, 6 Nov 2026). * * A FILM STREAMS BY A SIGNED URL. A film is an HLS folder, * `<database id>/films/<film id>/` (master.m3u8, its variant playlist, fMP4 * init and segments, poster.jpg, sub-<lang>.vtt; the film import lays * it), and Apple's player fetches every file of it itself, with no bearer: * - `POST /v1/media/stream { key }` (the owner; the key a film's master) *   answers `{ url, expires_at }`: `<this host>/v1/stream/<token>/<key>`, the *   token an HMAC-SHA256 under STREAM_SIGNING_KEY over the key's film folder *   and an expiry STREAM_LIFE_MS away; * - `GET /v1/stream/<token>/<key>` (no bearer): any key in that folder, Range *   answered as above; a token forged, expired or for another folder is 403. *   The playlists' URIs are relative, so they resolve under the same token *   path by themselves and are never rewritten. * * A BOOK is one file, `<database id>/books/<sha256>.<epub|pdf>` * (cotton-core's `book_key`): an EPUB or a PDF up to BOOK_MAX_BYTES, sent in * parts above one request's limit like any file, and nothing else is kept * under `books/`. It streams by a signed URL too — `POST /v1/media/stream` * with the book's key signs that one key, so the reader (or a background * download on the phone) fetches it with no bearer. * * A FILM MAY ALSO BE ONE FILE (Cinemas definition, 5 Nov 2026): an MP4, M4V * or MOV the phone plays as it is goes up whole as * `<database id>/films/<folder>/whole.<ext>`, and a file it cannot play goes * up as it came, `<database id>/films/<folder>/source.<ext>`, for the Mac to * convert into the HLS folder (src/films.ts `film_converted`). The folder is * the record's id, or a fresh one when a better file replaces a held one. * Every file under `films/` weighs at most FILM_MAX_BYTES and goes in parts * above one request's limit (`admitFilm`); a whole file streams by the same * signed URL as its folder, Range answered. */import type { Env } from "./env.ts";import { json, refuse } from "./http.ts";import { rule } from "./rules/index.ts";/** What one request may carry: the Worker's request limit. A larger file goes in parts. */export const MEDIA_MAX_BYTES = 100 * 1024 * 1024;/** The least every part of a file sent in parts but its last weighs: R2's own floor. */export const PART_MIN_BYTES = 5 * 1024 * 1024;/** What the Images binding takes in. */const RESIZE_MAX_BYTES = 20 * 1024 * 1024;const FITS = new Set(["scale-down", "contain", "cover", "crop", "pad"]);/** * A FILE SEALED ON THE PERSON'S DEVICE (R6): the bytes are * f1 (crates/cotton-core/src/seal/file.rs), stored and served exactly as they * came, under this type. The object can read none of it: it never draws one * at a size, never reads a book's package from one, and a stream of one says * this type, not the type its key's extension names. The device makes its * own thumbnails and opens every byte itself. */export const SEALED_FILE_TYPE = "application/vnd.cotton.f1";/** Whether a content type is a sealed file's. */export function isSealedType(contentType: string | null | undefined): boolean {  return (contentType ?? "").split(";")[0]!.trim().toLowerCase() === SEALED_FILE_TYPE;}/** * What the phone keeps of a book, a song and a film: each kind's ceiling and * the type each extension carries, the phone's own numbers (cotton-rules * media.rs, as WASM), read once per isolate. */interface Uploads {  book: { max_bytes: number; types: Record<string, string> };  song: { max_bytes: number; types: Record<string, string> };  film: { max_bytes: number; whole: Record<string, string>; source: Record<string, string> };}let held: Uploads | null = null;function uploads(): Uploads {  held ??= rule<Uploads>("media.uploads", {});  return held;}/** What a book file is, by its key's extension. */export function bookTypes(): Record<string, string> {  return uploads().book.types;}const under = (folder: string) => new RegExp(`^[^/]+/${folder}/`);const keyed = (folder: string, types: Record<string, string>) => new RegExp(`^[^/]+/${folder}/[0-9a-f]{64}\\.(${Object.keys(types).join("|")})$`);const sizeWords = (bytes: number) => (bytes >= 1024 ** 3 && bytes % 1024 ** 3 === 0 ? `${bytes / 1024 ** 3} GB` : `${bytes / 1024 / 1024} MB`);/** Whether `key` (or its bucket path) is a book's file: `<database id or slug>/books/<sha256>.<epub|pdf>`. */export function isBookKey(key: string): boolean {  return keyed("books", uploads().book.types).test(key);}/** * A file stored under `books/` (at its bucket path `at`) is a book or it is * refused: its key a book's, its weight within the book ceiling and its type * the one its extension says. Any other path passes untouched. */export function admitBook(at: string, size: number, contentType: string): void {  if (!under("books").test(at)) return;  const { max_bytes, types } = uploads().book;  const ext = keyed("books", types).exec(at)?.[1];  if (!ext) refuse(400, "bad_key", `a book's key is <database id>/books/<sha256>.${Object.keys(types).join(" or .")}`);  if (size > max_bytes) refuse(413, "too_big", `a book is at most ${sizeWords(max_bytes)}`);  if (isSealedType(contentType)) return;  const type = contentType.split(";")[0]!.trim().toLowerCase();  if (type !== types[ext]) refuse(415, "bad_media", `a .${ext} book is ${types[ext]}, not ${type || "untyped"}`);}/** Whether `key` (or its bucket path) is a song's file: `<database id or slug>/music/<sha256>.<ext>`. */export function isSongKey(key: string): boolean {  return keyed("music", uploads().song.types).test(key);}/** * A file stored under `music/` (at its bucket path `at`) is a song or it is * refused, as admitBook holds `books/`: its key a song's, its weight within * the song ceiling and its type the one its extension says. */export function admitSong(at: string, size: number, contentType: string): void {  if (!under("music").test(at)) return;  const { max_bytes, types } = uploads().song;  const ext = keyed("music", types).exec(at)?.[1];  if (!ext) refuse(400, "bad_key", `a song's key is <database id>/music/<sha256>.<${Object.keys(types).join("|")}>`);  if (size > max_bytes) refuse(413, "too_big", `a song is at most ${sizeWords(max_bytes)}`);  if (isSealedType(contentType)) return;  const type = contentType.split(";")[0]!.trim().toLowerCase();  if (type !== types[ext]) refuse(415, "bad_media", `a .${ext} song is ${types[ext]}, not ${type || "untyped"}`);}/** A film's whole file or its upload, directly in its folder: `<db>/films/<id>/whole.<ext>` or `source.<ext>`. */const FILM_FILE = /^[^/]+\/films\/[^/]+\/(whole|source)(?:\.([^/]*))?$/;/** * A file stored under `films/` (at its bucket path `at`) weighs at most the * film ceiling, whatever it is: the HLS folder the Mac lays, a whole film or * an upload waiting for the Mac. A `whole.<ext>` is one the phone plays as it * is (of the type its extension says); a `source.<ext>` is a film container, * of its type or untyped (application/octet-stream). Any other path passes * untouched. */export function admitFilm(at: string, size: number, contentType: string): void {  if (!under("films").test(at)) return;  const { max_bytes, whole, source } = uploads().film;  if (size > max_bytes) refuse(413, "too_big", `a film's file is at most ${sizeWords(max_bytes)}`);  const named = FILM_FILE.exec(at);  if (!named) return;  const [, role, ext = ""] = named;  const type = contentType.split(";")[0]!.trim().toLowerCase();  if (role === "whole") {    const wanted = whole[ext];    if (!wanted) refuse(400, "bad_key", `a whole film's key is <database id>/films/<id>/whole.<${Object.keys(whole).join("|")}>`);    if (isSealedType(type)) return;    if (type !== wanted) refuse(415, "bad_media", `a whole .${ext} film is ${wanted}, not ${type || "untyped"}`);    return;  }  const wanted = source[ext];  if (!wanted) refuse(400, "bad_key", `a film's upload is <database id>/films/<id>/source.<${Object.keys(source).join("|")}>`);  if (isSealedType(type)) return;  if (type !== wanted && type !== "application/octet-stream") refuse(415, "bad_media", `a .${ext} film is ${wanted} or application/octet-stream, not ${type || "untyped"}`);}/** The bucket path of a row's media key, or a refusal: the key must be this database's and a plain relative path. */export function bucketKey(key: string, databaseId: string, slug: string): string {  const prefix = `${databaseId}/`;  if (!databaseId || !key.startsWith(prefix)) refuse(404, "not_found", "no such media");  const rest = key.slice(prefix.length);  const segments = rest.split("/");  const bad =    key.length > 1024 ||    !rest ||    segments.some((s) => !s || s === "." || s === ".." || s === ".meta" || s.includes(".part-")) ||    /[\s\\]/.test(rest) ||    [...rest].some((ch) => ch.charCodeAt(0) < 0x20 || ch.charCodeAt(0) === 0x7f);  if (bad) refuse(400, "bad_key", "a media key is <database id>/<kind>/<name>, a plain path");  return `${slug}/${rest}`;}/** What the object's media may still grow by, and how it is told they grew. */export interface MediaBudget {  left: number;  add(bytes: number): void;  /** How a store past `left` is refused: the database's media cap (`object_full`), or the space rules' (`space_full`, SPACE.md). */  full?: { code: string; words: string };}/** A store that does not fit: refused in the budget's own words. */export function refuseFull(budget: MediaBudget): never {  refuse(413, budget.full?.code ?? "object_full", budget.full?.words ?? OBJECT_FULL);}/** One upload's weight, refused when it is none or past MEDIA_MAX_BYTES. */export function admitLength(length: number): void {  if (length <= 0) refuse(400, "bad_media", "the media is empty");  if (length > MEDIA_MAX_BYTES) refuse(413, "too_big", `a media file is at most ${MEDIA_MAX_BYTES / 1024 / 1024} MB`);}const OBJECT_FULL = "This database's media have reached their size limit: they still read, but take nothing new.";export async function putMedia(env: Env, key: string, request: Request, budget: MediaBudget): Promise<Response> {  const length = Number(request.headers.get("content-length") ?? NaN);  if (!Number.isFinite(length)) refuse(411, "length_required", "send the media with its content-length");  admitLength(length);  const contentType = request.headers.get("content-type") ?? "application/octet-stream";  admitBook(key, length, contentType);  admitSong(key, length, contentType);  admitFilm(key, length, contentType);  const held = await env.MEDIA.head(key);  // A file sealed on a device is never replaced by its plain bytes: an app from before its kind was sealed  // (a kept chat picture, 22 Nov 2026) may still send them. The sealed one stands; the plain one is not kept.  if (held && (held.size === length || (isSealedType(held.httpMetadata?.contentType) && !isSealedType(contentType)))) {    await request.body?.cancel();    return json({ stored: false, bytes: held.size });  }  if (!request.body) refuse(400, "bad_media", "the media is empty");  const grows = length - (held?.size ?? 0);  if (grows > budget.left) {    await request.body.cancel();    refuseFull(budget);  }  // A body of a known length streams straight into R2.  const body = request.body.pipeThrough(new FixedLengthStream(length));  await env.MEDIA.put(key, body, { httpMetadata: { contentType } });  budget.add(grows);  return json({ stored: true, bytes: length }, 201);}/** Start a file sent in parts, `size` bytes in all; the key holding those bytes already needs none. */export async function startParts(env: Env, key: string, body: Record<string, unknown>, budget: MediaBudget): Promise<Response> {  const size = body.size;  if (typeof size !== "number" || !Number.isInteger(size) || size <= 0) refuse(400, "bad_request", "uploads needs size, the whole file's bytes");  const contentType = typeof body.content_type === "string" && body.content_type ? body.content_type : "application/octet-stream";  admitBook(key, size, contentType);  admitSong(key, size, contentType);  admitFilm(key, size, contentType);  const held = await env.MEDIA.head(key);  if (held && held.size === size) return json({ stored: false, bytes: held.size });  if (size - (held?.size ?? 0) > budget.left) refuseFull(budget);  const upload = await env.MEDIA.createMultipartUpload(key, { httpMetadata: { contentType } });  return json({ upload: upload.uploadId }, 201);}/** One part of a file sent in parts. */export async function putPart(env: Env, key: string, uploadId: string, part: string | null, request: Request): Promise<Response> {  const number = Number(part);  if (!Number.isInteger(number) || number < 1 || number > 10_000) refuse(400, "bad_request", "part is 1 to 10000");  const length = Number(request.headers.get("content-length") ?? NaN);  if (!Number.isFinite(length)) refuse(411, "length_required", "send the part with its content-length");  admitLength(length);  if (!request.body) refuse(400, "bad_media", "the part is empty");  const upload = env.MEDIA.resumeMultipartUpload(key, uploadId);  try {    const uploaded = await upload.uploadPart(number, request.body.pipeThrough(new FixedLengthStream(length)));    return json({ part: uploaded.partNumber, etag: uploaded.etag });  } catch (error) {    refuse(404, "no_upload", `no such upload under this key: ${error instanceof Error ? error.message : String(error)}`);  }}/** Put a file's parts together under its key, counted as a PUT counts it. */export async function finishParts(env: Env, key: string, uploadId: string, body: Record<string, unknown>, budget: MediaBudget): Promise<Response> {  const parts = body.parts;  const wellFormed =    Array.isArray(parts) &&    parts.length > 0 &&    parts.every((p) => p && typeof p === "object" && Number.isInteger((p as { part: unknown }).part) && typeof (p as { etag: unknown }).etag === "string");  if (!wellFormed) refuse(400, "bad_request", "finishing needs parts, each { part, etag } as its PUT answered");  const held = await env.MEDIA.head(key);  const upload = env.MEDIA.resumeMultipartUpload(key, uploadId);  let stored: R2Object;  try {    stored = await upload.complete((parts as { part: number; etag: string }[]).map((p) => ({ partNumber: p.part, etag: p.etag })));  } catch (error) {    refuse(400, "bad_upload", `the parts did not make a file: ${error instanceof Error ? error.message : String(error)}`);  }  budget.add(stored.size - (held?.size ?? 0));  return json({ stored: true, bytes: stored.size }, 201);}/** Bytes already in hand stored under a bucket path, as a PUT stores them: the same caps, counted the same way. */export async function storeMedia(env: Env, key: string, bytes: Uint8Array, contentType: string, budget: MediaBudget): Promise<{ stored: boolean; bytes: number }> {  admitLength(bytes.byteLength);  const held = await env.MEDIA.head(key);  if (held && held.size === bytes.byteLength) return { stored: false, bytes: held.size };  // A file sealed on a device (or at arrival) is never replaced by plain bytes, as putMedia keeps it (AVATAR SEAL 4 (2)).  if (held && isSealedType(held.httpMetadata?.contentType) && !isSealedType(contentType)) return { stored: false, bytes: held.size };  const grows = bytes.byteLength - (held?.size ?? 0);  if (grows > budget.left) refuseFull(budget);  await env.MEDIA.put(key, bytes, { httpMetadata: { contentType } });  budget.add(grows);  return { stored: true, bytes: bytes.byteLength };}/** * A file of `length` bytes written as it is made, under a bucket path: `fill` * hands each chunk to `write`, which waits on R2 before the next. Counted * against the object's media as a PUT is, and refused before a byte is * written when it does not fit. Answers its SHA-256, worked out as it passed. */export async function storeStream(  env: Env,  key: string,  length: number,  contentType: string,  budget: MediaBudget,  fill: (write: (chunk: Uint8Array) => Promise<void>) => Promise<void>,): Promise<{ bytes: number; sha256: string }> {  if (length <= 0) refuse(400, "bad_media", "the media is empty");  const held = await env.MEDIA.head(key);  const grows = length - (held?.size ?? 0);  if (grows > budget.left) refuseFull(budget);  const body = new FixedLengthStream(length);  const stored = env.MEDIA.put(key, body.readable, { httpMetadata: { contentType } });  const digest = new crypto.DigestStream("SHA-256");  const toR2 = body.writable.getWriter();  const toDigest = digest.getWriter();  try {    await fill(async (chunk) => {      await toDigest.write(chunk);      await toR2.write(chunk);    });    await toDigest.close();    await toR2.close();  } catch (error) {    await toR2.abort(error).catch(() => undefined);    await toDigest.abort(error).catch(() => undefined);    await stored.catch(() => undefined);    throw error;  }  await stored;  budget.add(grows);  const sha256 = [...new Uint8Array(await digest.digest)].map((b) => b.toString(16).padStart(2, "0")).join("");  return { bytes: length, sha256 };}/** An image drawn at a size through the Images binding, as WebP bytes; past RESIZE_MAX_BYTES it is refused, as a GET at a size is. */export async function drawMedia(env: Env, key: string, size: { width?: number; height?: number }): Promise<Uint8Array> {  const held = await env.MEDIA.head(key);  if (!held) refuse(404, "not_found", "no such media");  if (isSealedType(held.httpMetadata?.contentType)) refuse(400, SEALED_REFUSAL, SEALED_WORDS);  if (held.size > RESIZE_MAX_BYTES) refuse(413, "too_big", "an image over 20 MB is not drawn at a size; ask for it whole");  const object = await env.MEDIA.get(key);  if (!object) refuse(404, "not_found", "no such media");  const drawn = await env.IMAGES.input(object.body)    .transform({ ...size, fit: "scale-down" })    .output({ format: "image/webp" });  return new Uint8Array(await drawn.response().arrayBuffer());}/** Bytes already opened (a sealed table's kept file, opened in a window: src/table_files.ts) drawn as WebP at a size. They are never stored. */export async function drawBytes(env: Env, bytes: Uint8Array, size: { width?: number; height?: number }): Promise<Uint8Array> {  if (bytes.length > RESIZE_MAX_BYTES) refuse(413, "too_big", "an image over 20 MB is not drawn at a size; ask for it whole");  const drawn = await env.IMAGES.input(new Response(bytes).body!)    .transform({ ...size, fit: "scale-down" })    .output({ format: "image/webp" });  return new Uint8Array(await drawn.response().arrayBuffer());}/** Every byte the bucket holds under `prefix`, listed a thousand keys at a time. */export async function mediaBytes(env: Env, prefix: string): Promise<number> {  let total = 0;  let cursor: string | undefined;  for (;;) {    const page = await env.MEDIA.list({ prefix, ...(cursor ? { cursor } : {}) });    for (const object of page.objects) total += object.size;    if (!page.truncated) return total;    cursor = page.cursor;  }}/** A key the owner sends to `DELETE ?prefix=1` as the bucket folder it names, or a refusal: `<database id>/<kind>/<name>/`, at least two deep. */export function bucketFolder(key: string, databaseId: string, slug: string): string {  if (!key.endsWith("/")) refuse(400, "bad_key", "a folder ends with /: <database id>/<kind>/<name>/");  const at = bucketKey(key.slice(0, -1), databaseId, slug);  if (at.split("/").length < 3) refuse(400, "bad_key", "a folder is at least <database id>/<kind>/<name>/: never a kind's whole folder or the database's");  return `${at}/`;}/** `DELETE /v1/media/<key>`: the one key, its bytes taken off the count. */export async function deleteMedia(env: Env, at: string, budget: MediaBudget): Promise<Response> {  const held = await env.MEDIA.head(at);  if (!held) refuse(404, "not_found", "no such media");  await env.MEDIA.delete(at);  budget.add(-held.size);  return json({ deleted: 1, bytes: held.size });}/** One key's bytes, gone and taken off the count; nothing when the bucket holds none there (deleted before). */export async function dropKey(env: Env, at: string, budget: MediaBudget): Promise<void> {  const held = await env.MEDIA.head(at);  if (!held) return;  await env.MEDIA.delete(at);  budget.add(-held.size);}/** Everything the bucket holds under `prefix` (a bucket folder, ending in /), a thousand keys a call, taken off the count; what went. */export async function deleteFolder(env: Env, prefix: string, budget: MediaBudget): Promise<{ deleted: number; bytes: number }> {  let deleted = 0;  let bytes = 0;  // Each page is read from the start again: what the last call deleted is no longer listed.  for (;;) {    const page = await env.MEDIA.list({ prefix, limit: 1000 });    if (!page.objects.length) break;    await env.MEDIA.delete(page.objects.map((o) => o.key));    const weight = page.objects.reduce((n, o) => n + o.size, 0);    budget.add(-weight);    deleted += page.objects.length;    bytes += weight;  }  return { deleted, bytes };}/** * Of `keys` (each a row's key beside its bucket path), the ones the bucket does not hold; with `sealed`, the ones it * does not hold sealed (a file stored in the clear is still to be sent), and the answer says it was asked that way. *//** How many keys `missingMedia` asks the bucket about at once. */const MISSING_AT_ONCE = 25;export async function missingMedia(env: Env, keys: { key: string; at: string }[], sealed = false): Promise<Response> {  // A few at a time, never all 500 at once: a batch of 500 heads at once failed with a 500 on the personal  // object (media:audit, 21 Nov 2026). A head that fails is said by name, never as "the business did not answer".  const held: (R2Object | null)[] = [];  for (let i = 0; i < keys.length; i += MISSING_AT_ONCE) {    try {      held.push(...(await Promise.all(keys.slice(i, i + MISSING_AT_ONCE).map((k) => env.MEDIA.head(k.at)))));    } catch (error) {      const name = error instanceof Error ? `${error.name}: ${error.message}` : String(error);      console.error(`cottondb: media missing: the bucket did not answer for keys ${i}-${i + MISSING_AT_ONCE} of ${keys.length}: ${name}`);      refuse(503, "bucket_unanswered", "the media store did not answer just now: ask again");    }  }  const missing = keys.filter((_, i) => !held[i] || (sealed && !isSealedType(held[i].httpMetadata?.contentType))).map((k) => k.key);  return json(sealed ? { missing, sealed: true } : { missing });}export async function getMedia(env: Env, key: string, params: URLSearchParams, head: boolean, range: string | null = null): Promise<Response> {  const width = size(params.get("width"), "width");  const height = size(params.get("height"), "height");  const fit = params.get("fit") ?? "scale-down";  if (!FITS.has(fit)) refuse(400, "bad_request", `fit is one of ${[...FITS].join(", ")}`);  const resized = width !== null || height !== null;  if (!resized && !head) {    const answered = await bytesInOne(env, key, range);    if (answered) return answered;  }  const held = await env.MEDIA.head(key);  if (!held) refuse(404, "not_found", "no such media");  const type = held.httpMetadata?.contentType ?? "";  if (resized && isSealedType(type)) refuse(400, SEALED_REFUSAL, SEALED_WORDS);  if (resized && (!type.startsWith("image/") || type === "image/svg+xml")) refuse(400, "not_an_image", "only an image is drawn at a size");  if (resized && held.size > RESIZE_MAX_BYTES) refuse(413, "too_big", "an image over 20 MB is not drawn at a size; ask for it whole");  // The owner's own bytes, under a key that never changes: kept by the phone, never by a shared cache.  const headers = new Headers({ "cache-control": "private, max-age=31536000, immutable" });  if (resized) {    headers.set("content-type", "image/webp");    headers.set("etag", `"${held.etag}-${width ?? ""}x${height ?? ""}-${fit}"`);  } else {    held.writeHttpMetadata(headers);    headers.set("etag", held.httpEtag);  }  if (!resized) return answerBytes(env, key, held, headers, head, range);  if (head) return new Response(null, { headers });  const object = await env.MEDIA.get(key);  if (!object) refuse(404, "not_found", "no such media");  const drawn = await env.IMAGES.input(object.body)    .transform({ ...(width !== null ? { width } : {}), ...(height !== null ? { height } : {}), fit: fit as "scale-down" })    .output({ format: "image/webp" });  return new Response(drawn.response().body, { headers });}/** Why a sealed file is never drawn at a size. */export const SEALED_REFUSAL = "sealed_file";const SEALED_WORDS = "a sealed file is never drawn at a size: the device that sealed it made its own pictures";function size(value: string | null, what: string): number | null {  if (value === null) return null;  const n = Number(value);  if (!Number.isInteger(n) || n < 1 || n > 4096) refuse(400, "bad_request", `${what} is 1 to 4096 pixels`);  return n;}// ── ranges ───────────────────────────────────────────────────────────────/** The bytes a single `Range: bytes=…` asks of `size`; null for the whole (no header, several ranges, or one malformed: RFC 9110 lets a server ignore it), "unsatisfiable" past the end. */export function rangeOf(header: string | null, size: number): { offset: number; length: number } | null | "unsatisfiable" {  if (!header) return null;  const m = /^\s*bytes\s*=\s*(\d*)\s*-\s*(\d*)\s*$/i.exec(header);  if (!m || (!m[1] && !m[2])) return null;  if (!m[1]) {    const suffix = Number(m[2]);    if (suffix === 0 || size === 0) return "unsatisfiable";    const length = Math.min(suffix, size);    return { offset: size - length, length };  }  const first = Number(m[1]);  const last = m[2] ? Number(m[2]) : Infinity;  if (last < first) return null;  if (first >= size) return "unsatisfiable";  return { offset: first, length: Math.min(last, size - 1) - first + 1 };}/** * The bytes of `at`, whole or the one range asked, from ONE read of R2 (PLAYER START, 26 Nov 2026): a head and then a * get were two R2 round trips, about 210 ms each from the object on dev, on every one of a player's requests (a * 579-byte playlist took 700 ms to its first byte). Null when one read cannot say it (a range R2 refuses, past the end, * or one this does not ask R2 for): the caller answers it the long way, which says 416 or 404 as before. */async function bytesInOne(env: Env, at: string, rangeHeader: string | null): Promise<Response | null> {  let asked: R2Range | undefined;  if (rangeHeader) {    const m = /^\s*bytes\s*=\s*(\d*)\s*-\s*(\d*)\s*$/i.exec(rangeHeader);    if (!m || (!m[1] && !m[2])) {      asked = undefined; // RFC 9110: one ignored is the whole.    } else if (!m[1]) {      return null; // A suffix: the long way, which knows the size first.    } else {      const first = Number(m[1]);      const last = m[2] ? Number(m[2]) : null;      if (last !== null && last < first) asked = undefined;      else asked = last === null ? { offset: first } : { offset: first, length: last - first + 1 };    }  }  let object: R2ObjectBody | null;  try {    object = await env.MEDIA.get(at, asked ? { range: asked } : {});  } catch {    return null;  }  if (!object) return null;  const headers = new Headers({ "cache-control": "private, max-age=31536000, immutable" });  object.writeHttpMetadata(headers);  headers.set("etag", object.httpEtag);  headers.set("accept-ranges", "bytes");  if (!asked) {    headers.set("content-length", String(object.size));    return new Response(object.body, { status: 200, headers });  }  const offset = (asked as { offset: number }).offset;  if (offset >= object.size) {    await object.body.cancel();    return null;  }  const length = Math.min((asked as { length?: number }).length ?? Infinity, object.size - offset);  headers.set("content-range", `bytes ${offset}-${offset + length - 1}/${object.size}`);  headers.set("content-length", String(length));  return new Response(object.body, { status: 206, headers });}/** A held object's bytes, whole (200) or the one range asked (206, or 416 past the end), under `headers` already set. */async function answerBytes(env: Env, at: string, held: R2Object, headers: Headers, head: boolean, rangeHeader: string | null): Promise<Response> {  headers.set("accept-ranges", "bytes");  const range = rangeOf(rangeHeader, held.size);  if (range === "unsatisfiable") {    headers.set("content-range", `bytes */${held.size}`);    headers.set("content-length", "0");    return new Response(null, { status: 416, headers });  }  if (range) {    headers.set("content-range", `bytes ${range.offset}-${range.offset + range.length - 1}/${held.size}`);    headers.set("content-length", String(range.length));  } else {    headers.set("content-length", String(held.size));  }  const status = range ? 206 : 200;  if (head) return new Response(null, { status, headers });  const object = await env.MEDIA.get(at, range ? { range } : {});  if (!object) refuse(404, "not_found", "no such media");  return new Response(object.body, { status, headers });}// ── films, streamed by a signed URL ──────────────────────────────────────/** How long a stream URL plays: a film and its pauses, then the phone asks again. */export const STREAM_LIFE_MS = 12 * 60 * 60 * 1000;/** A film's folder: `<database id>/films/<film id>/`, then a file inside it. */const FILM_KEY = /^([^/]+\/films\/[^/]+\/)[^/].*$/;/** What the stream route says a film's files are, by extension (what AVPlayer expects of each), and a book's and a song's. */function streamTypes(): Record<string, string> {  return {    m3u8: "application/vnd.apple.mpegurl",    mp4: "video/mp4",    m4v: "video/mp4",    mov: "video/quicktime",    m4s: "video/iso.segment",    vtt: "text/vtt; charset=utf-8",    jpg: "image/jpeg",    ...uploads().book.types,    ...uploads().song.types,  };}/** The film folder a key lies in, or null when it lies in none. */export function filmFolder(key: string): string | null {  return FILM_KEY.exec(key)?.[1] ?? null;}/** What a stream token is signed for: a film's whole folder, or a book's or a song's one key; null for any other key. */export function streamScope(key: string): string | null {  return filmFolder(key) ?? (isBookKey(key) || isSongKey(key) ? key : null);}async function streamKey(env: Env): Promise<CryptoKey> {  const secret = env.STREAM_SIGNING_KEY;  if (!secret) refuse(503, "no_stream_key", "this Worker has no STREAM_SIGNING_KEY");  return crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);}function signed(folder: string, expires: number, slug?: string): Uint8Array {  // A token bound to its account (STREAM AT THE DOOR, 26 Nov 2026) signs the slug too, so the front Worker can admit it  // without asking the object which database the slug holds.  return new TextEncoder().encode(slug === undefined ? `${folder}\n${expires}` : `${STREAM_V2}\n${slug}\n${folder}\n${expires}`);}/** A slug-bound token's first byte (its other 40 bytes are an old token's: the expiry, then the HMAC). */const STREAM_V2 = 2;function base64url(bytes: Uint8Array): string {  let binary = "";  for (const b of bytes) binary += String.fromCharCode(b);  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}function unbase64url(text: string): Uint8Array | null {  if (!/^[A-Za-z0-9_-]+$/.test(text)) return null;  try {    return Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));  } catch {    return null;  }}/** * A token for one scope (`streamScope`: a film's folder, or a book's key): * base64url of the expiry (seconds since the epoch, 8 bytes big-endian) then * the 32-byte HMAC-SHA256 of `<scope>\n<expiry>`. The scope is not in the * token: it is the key's own, read from the path the token rides in. */export async function streamToken(env: Env, folder: string, expires: number, slug?: string): Promise<string> {  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", await streamKey(env), signed(folder, expires, slug)));  // Slug-bound (version byte 2, then the old shape): 41 bytes; the old shape, 40.  const head = slug === undefined ? 0 : 1;  const bytes = new Uint8Array(head + 8 + mac.length);  if (head) bytes[0] = STREAM_V2;  new DataView(bytes.buffer).setBigUint64(head, BigInt(expires));  bytes.set(mac, head + 8);  return base64url(bytes);}/** Whether a token is slug-bound (minted since STREAM AT THE DOOR): the front Worker admits it itself. */export function slugBound(token: string): boolean {  const bytes = unbase64url(token);  return !!bytes && bytes.length === 41 && bytes[0] === STREAM_V2;}/** A key's stream scope (its film's folder, or the book itself) when `token` was signed for it and has not expired; a refusal (403) otherwise. */export async function admitStream(env: Env, token: string, key: string, now = Date.now(), slug?: string): Promise<string> {  const folder = streamScope(key);  if (!folder) refuse(403, "outside_stream", "a stream URL reaches only its film's folder, its one book or its one song");  const bytes = unbase64url(token);  const bound = !!bytes && bytes.length === 41 && bytes[0] === STREAM_V2;  if (!bytes || (bytes.length !== 40 && !bound)) refuse(403, "bad_stream_token", "this stream URL is not one Cotton made");  // A slug-bound token is admitted only for the account it names.  if (bound && slug === undefined) refuse(403, "bad_stream_token", "this stream URL is not one Cotton made");  const head = bound ? 1 : 0;  const expires = Number(new DataView(bytes.buffer).getBigUint64(head));  const genuine = await crypto.subtle.verify("HMAC", await streamKey(env), bytes.slice(head + 8), signed(folder, expires, bound ? slug : undefined));  if (!genuine) refuse(403, "bad_stream_token", "this stream URL is not one Cotton made, or not for this film, book or song");  if (expires * 1000 <= now) refuse(403, "stream_expired", "this stream URL has expired; ask for a new one");  return folder;}/** `POST /v1/media/stream { key }`: a signed URL for the film whose master is `key`, or for the book `key` (at `at` in the bucket), good for STREAM_LIFE_MS. */export async function mintStream(env: Env, key: string, at: string, base: string, now = Date.now(), slug?: string): Promise<Response> {  const folder = streamScope(key);  if (!folder) refuse(400, "not_streamable", "a stream is a film's (<database id>/films/<film id>/<file>) a book's (<database id>/books/<sha256>.<epub|pdf>) or a song's (<database id>/music/<sha256>.<ext>)");  if (!(await env.MEDIA.head(at))) refuse(404, "not_found", "no such media");  const expires = Math.floor((now + STREAM_LIFE_MS) / 1000);  const token = await streamToken(env, folder, expires, slug);  const path = key.split("/").map(encodeURIComponent).join("/");  return json({ url: `${base}/v1/stream/${token}/${path}`, expires_at: new Date(expires * 1000).toISOString() });}/** * What a stream answers any origin (Android Cinemas, 15 Nov 2026): a cast receiver is a web page on the TV that * fetches the film's playlists and segments across origins, a Range among them. The signed URL is the whole grant * (no cookie, no bearer), so opening it to every origin hands no one more than the URL already does. */const STREAM_CROSS_ORIGIN: Record<string, string> = {  "access-control-allow-origin": "*",  "access-control-expose-headers": "content-length, content-range, accept-ranges, etag",};/** A stream's answer, readable by any origin. */export function crossOrigin(response: Response): Response {  const opened = new Response(response.body, response);  for (const [name, value] of Object.entries(STREAM_CROSS_ORIGIN)) opened.headers.set(name, value);  return opened;}/** `OPTIONS /v1/stream/<token>/<key>`: a receiver's preflight for a Range read; nothing is admitted until the GET. */export function streamPreflight(): Response {  return new Response(null, {    status: 204,    headers: { ...STREAM_CROSS_ORIGIN, "access-control-allow-methods": "GET, HEAD", "access-control-allow-headers": "range", "access-control-max-age": "86400" },  });}/** `GET /v1/stream/<token>/<key>`: a film's file or a book, by the token alone, Range answered; `at` is the key's bucket path, already admitted. */export async function streamMedia(env: Env, key: string, at: string, head: boolean, range: string | null): Promise<Response> {  const held = await env.MEDIA.head(at);  if (!held) refuse(404, "not_found", "no such media");  const headers = new Headers({ "cache-control": "private" });  const extension = /\.([a-z0-9]+)$/i.exec(key)?.[1]?.toLowerCase() ?? "";  const stored = held.httpMetadata?.contentType;  headers.set("content-type", isSealedType(stored) ? SEALED_FILE_TYPE : (streamTypes()[extension] ?? stored ?? "application/octet-stream"));  headers.set("etag", held.httpEtag);  return answerBytes(env, at, held, headers, head, range);}/** The SHA-256 a kit picture's reference names (`photo:<sha256>`), or null for any other key. */function kitPictureHash(key: string): string | null {  return /^photo:([0-9a-f]{64})$/.exec(key)?.[1] ?? null;}/** * `GET /v1/media/photo:<sha256>`: a picture a kit's fan tile names, from the * Worker's static assets (`/kit-pictures/<sha256>.png`, scripts/kit.ts); null * for any key that is not one (ASSETS answers 404), so the caller reads R2 as * for any key. */export async function kitPicture(env: Env, key: string, head: boolean): Promise<Response | null> {  const sha = kitPictureHash(key);  if (!sha) return null;  const held = await env.ASSETS.fetch(new Request(`https://assets.invalid/kit-pictures/${sha}.png`));  if (held.status === 404) return null;  if (!held.ok) throw new Error(`static assets answered ${held.status} for kit picture ${sha}`);  const bytes = await held.arrayBuffer();  const headers = { "content-type": "image/png", "content-length": String(bytes.byteLength), "cache-control": "private, max-age=31536000, immutable", etag: `"${sha}"` };  return new Response(head ? null : bytes, { status: 200, headers });}/** * STREAM AT THE DOOR (coordinator, 26 Nov 2026: on live a film's every range request waited in the owner's object's * queue behind its alarm and a phone's pull, and he could not stream for twenty minutes). A slug-bound stream URL is * answered by the front Worker from the bucket, never entering the object: the token is the whole grant (HMAC over the * slug, the film's folder and the expiry, by STREAM_SIGNING_KEY), the database id is the signed key's own first * segment, and the bucket key is `<slug>/<rest>` as the object makes it. An account marked for deletion streams * nothing. An older token (not slug-bound) still goes to the object until it expires. */export async function streamAtDoor(env: Env, slug: string, token: string, rest: string, method: string, range: string | null): Promise<Response> {  if (method === "OPTIONS") return streamPreflight();  if (method !== "GET" && method !== "HEAD") refuse(405, "method_not_allowed", "a stream takes GET and HEAD");  const key = decodeURIComponent(rest);  await admitStream(env, token, key, Date.now(), slug);  const databaseId = key.split("/")[0] ?? "";  return crossOrigin(await streamMedia(env, key, bucketKey(key, databaseId, slug), method === "HEAD", range));}