Cotton code
298 lines · 20.1 KB · TypeScriptRaw
import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import type { Business } from "../src/business.ts";import { PART_MIN_BYTES } from "../src/media.ts";import DOWNLOADS from "../../../crates/cotton-core/kits/personal/tools/downloads/manifest.json";import { ADMIN, DATABASE_ID, http, mint, personalObject } from "./personal.ts";/** A real 32×24 PNG, so the resizer has an image to read. */const PNG = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAIAAAAUMWhjAAAAJElEQVR4nGM4EaBBU8QwasGoBaMWjFowasGoBaMWjFowNCwAAOj5wC7/fbJHAAAAAElFTkSuQmCC"), (c) => c.charCodeAt(0));async function media(slug: string, method: string, key: string, auth: string | null, body?: Uint8Array, type = "image/png", query = ""): Promise<Response> {  return SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}${query}`, {    method,    headers: { ...(auth ? { authorization: `Bearer ${auth}` } : {}), ...(body ? { "content-type": type, "content-length": String(body.length) } : {}) },    body,  });}/** RULE (owner, 25 Oct 2026): media live in R2, served for the owner's scope only, images through Cloudflare image resizing at the size the phone asks; nothing makes thumbnails ahead of it. */describe("the personal object's media", () => {  const SLUG = "media-personal";  const KEY = `${DATABASE_ID}/photos/${"ab".repeat(32)}.png`;  let credential = "";  let owner = "";  it("takes the owner's bytes under the row's own key, once", async () => {    ({ credential, owner } = await personalObject(SLUG));    const put = await media(SLUG, "PUT", KEY, credential, PNG);    expect(put.status, await put.clone().text()).toBe(201);    expect(await put.json()).toEqual({ stored: true, bytes: PNG.length });    const again = await media(SLUG, "PUT", KEY, credential, PNG);    expect(await again.json(), "the same bytes again are not stored twice").toEqual({ stored: false, bytes: PNG.length });  });  it("answers which keys it does not hold yet", async () => {    const other = `${DATABASE_ID}/messages/th-1/${"cd".repeat(32)}.jpg`;    const res = await http<{ missing: string[] }>(SLUG, "POST", "/v1/media/missing", { keys: [KEY, other] }, { authorization: `Bearer ${credential}` });    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body.missing).toEqual([other]);  });  it("answers a whole batch of 500 keys, the bucket asked a few at a time (media:audit, 21 Nov 2026: 500 at once answered 500)", async () => {    const keys = [KEY, ...Array.from({ length: 499 }, (_, i) => `${DATABASE_ID}/messages/th-2/${i.toString(16).padStart(64, "0")}.jpg`)];    const res = await http<{ missing: string[] }>(SLUG, "POST", "/v1/media/missing", { keys }, { authorization: `Bearer ${credential}` });    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body.missing).toEqual(keys.slice(1));  });  it("serves the bytes whole to the owner's device, kept privately, and never to an assistant's token", async () => {    const res = await media(SLUG, "GET", KEY, credential);    expect(res.status).toBe(200);    expect(res.headers.get("content-type")).toBe("image/png");    expect(res.headers.get("cache-control")).toBe("private, max-age=31536000, immutable");    expect(new Uint8Array(await res.arrayBuffer())).toEqual(PNG);    // A photo opens in no window: an assistant's token reads none (AVATAR SEAL 4; every kind: sealed-kinds-token.test.ts).    expect((await media(SLUG, "GET", KEY, owner)).status).toBe(403);    const head = await media(SLUG, "HEAD", KEY, credential);    expect(head.status).toBe(200);    expect(head.headers.get("content-length")).toBe(String(PNG.length));  });  it("draws an image at the size the phone asks", async () => {    const res = await media(SLUG, "GET", KEY, credential, undefined, "", "?width=16&fit=scale-down");    expect(res.status, await res.clone().text()).toBe(200);    expect(res.headers.get("content-type")).toBe("image/webp");    const bytes = new Uint8Array(await res.arrayBuffer());    expect(new TextDecoder().decode(bytes.slice(0, 4))).toBe("RIFF");    expect(new TextDecoder().decode(bytes.slice(8, 12))).toBe("WEBP");  });  it("refuses anyone but the owner, another database's key, a path that climbs, a size on audio and a bad size", async () => {    const reader = await mint(SLUG, credential, "reader", ["read"]);    const nobody = await media(SLUG, "GET", KEY, null);    expect(nobody.status).toBe(403);    expect(((await nobody.json()) as { code: string }).code).toBe("owner_only");    expect((await media(SLUG, "GET", KEY, reader)).status, "a token that is not the owner's speaks only at /mcp").toBe(403);    expect((await media(SLUG, "PUT", `00000000-0000-4000-8000-000000000000/photos/x.png`, credential, PNG)).status).toBe(404);    // A URL folds a plain ../ away before it arrives; one sent encoded arrives, and is refused.    expect((await media(SLUG, "PUT", `${DATABASE_ID}/photos%2F..%2F..%2Fx.png`, credential, PNG)).status).toBe(400);    const audio = `${DATABASE_ID}/meetings/mt-1/full.m4a`;    expect((await media(SLUG, "PUT", audio, credential, new TextEncoder().encode("audio"), "audio/mp4")).status).toBe(201);    expect(((await (await media(SLUG, "GET", audio, credential, undefined, "", "?width=10")).json()) as { code: string }).code).toBe("not_an_image");    expect((await media(SLUG, "GET", KEY, credential, undefined, "", "?width=0")).status).toBe(400);    expect((await media(SLUG, "GET", `${DATABASE_ID}/photos/${"ef".repeat(32)}.png`, credential)).status).toBe(404);  });  // RULE (27 Oct 2026): one request carries at most what the host takes (100 MB), and a WhatsApp  // document is up to 2 GB: a larger file reaches the object in parts, counted once, whole.  it("takes a file in parts and puts them together under the key", async () => {    const key = `${DATABASE_ID}/messages/m-big/${"12".repeat(32)}.apk`;    const first = new Uint8Array(PART_MIN_BYTES).fill(7);    const last = new TextEncoder().encode("the last part");    const size = first.length + last.length;    const object = env.BUSINESS.get(env.BUSINESS.idFromName(SLUG));    const usage = () => runInDurableObject(object, (instance: Business) => Number((instance as unknown as { store: { meta(key: string): string | null } }).store.meta("media_bytes") ?? "0"));    const before = await usage();    const start = await media(SLUG, "POST", key, credential, new TextEncoder().encode(JSON.stringify({ size, content_type: "application/vnd.android.package-archive" })), "application/json", "?uploads");    expect(start.status, await start.clone().text()).toBe(201);    const { upload } = (await start.json()) as { upload: string };    const parts: { part: number; etag: string }[] = [];    for (const [i, bytes] of [first, last].entries()) {      const res = await media(SLUG, "PUT", key, credential, bytes, "application/octet-stream", `?upload=${encodeURIComponent(upload)}&part=${i + 1}`);      expect(res.status, await res.clone().text()).toBe(200);      parts.push((await res.json()) as { part: number; etag: string });    }    const done = await media(SLUG, "POST", key, credential, new TextEncoder().encode(JSON.stringify({ parts })), "application/json", `?upload=${encodeURIComponent(upload)}`);    expect(done.status, await done.clone().text()).toBe(201);    expect(await done.json()).toEqual({ stored: true, bytes: size });    // Read back by the owner's device: a token reads a chat file only in a window over messages (AVATAR SEAL 2).    const head = await media(SLUG, "HEAD", key, credential);    expect(head.headers.get("content-length")).toBe(String(size));    expect(head.headers.get("content-type")).toBe("application/vnd.android.package-archive");    const whole = new Uint8Array(await (await media(SLUG, "GET", key, credential)).arrayBuffer());    expect(whole.length).toBe(size);    expect(new TextDecoder().decode(whole.slice(first.length))).toBe("the last part");    expect(await usage(), "the whole file is counted once").toBe(before + size);    const again = await media(SLUG, "POST", key, credential, new TextEncoder().encode(JSON.stringify({ size })), "application/json", "?uploads");    expect(await again.json(), "a file the key holds needs no parts").toEqual({ stored: false, bytes: size });    await runInDurableObject(object, (instance: Business) => {      instance.caps.media = before + size + 1;    });    const full = await media(SLUG, "POST", `${DATABASE_ID}/messages/m-big/${"34".repeat(32)}.apk`, credential, new TextEncoder().encode(JSON.stringify({ size })), "application/json", "?uploads");    expect(full.status, "a file that would not fit is refused before any part goes").toBe(413);    expect(await full.json()).toMatchObject({ code: "object_full" });    const stray = await media(SLUG, "PUT", key, credential, last, "application/octet-stream", "?upload=no-such-upload&part=1");    expect(stray.status).toBe(404);  });  it("is the personal database's alone", async () => {    const business = "media-business";    expect((await http(business, "PUT", "/v1/admin/business", { name: "Shop", kind: "business" }, ADMIN)).status).toBe(200);    expect((await http(business, "PUT", "/v1/admin/definitions", { tools: [], tables: [] }, ADMIN)).status).toBe(200);    const res = await http<{ code: string }>(business, "GET", `/v1/media/${KEY}`, undefined, ADMIN);    expect(res.body.code).toBe("not_personal");  });});/** RULE (owner, 4 Nov 2026): a book's file is kept as media, `<database id>/books/<sha256>.<epub|pdf>`, an EPUB or a PDF up to 500 MB, sent in parts above one request's limit. */describe("a book's file", () => {  const SLUG = "media-books";  const EPUB = `${DATABASE_ID}/books/${"ab".repeat(32)}.epub`;  const PDF = `${DATABASE_ID}/books/${"cd".repeat(32)}.pdf`;  const BYTES = new TextEncoder().encode("PK\u0003\u0004 an invented book");  let credential = "";  it("keeps an EPUB and a PDF under their keys, each as its own type", async () => {    ({ credential } = await personalObject(SLUG));    for (const [key, type] of [[EPUB, "application/epub+zip"], [PDF, "application/pdf"]] as const) {      const put = await media(SLUG, "PUT", key, credential, BYTES, type);      expect(put.status, await put.clone().text()).toBe(201);      const head = await media(SLUG, "HEAD", key, credential);      expect(head.headers.get("content-type")).toBe(type);    }  });  it("refuses anything else under books/: another key's shape, a type its extension does not say, and a whole past 500 MB", async () => {    const refused = async (res: Response, status: number, code: string): Promise<void> => {      expect(res.status, await res.clone().text()).toBe(status);      expect(((await res.json()) as { code: string }).code).toBe(code);    };    await refused(await media(SLUG, "PUT", `${DATABASE_ID}/books/a-book.epub`, credential, BYTES, "application/epub+zip"), 400, "bad_key");    await refused(await media(SLUG, "PUT", `${DATABASE_ID}/books/${"ef".repeat(32)}.mobi`, credential, BYTES, "application/octet-stream"), 400, "bad_key");    await refused(await media(SLUG, "PUT", `${DATABASE_ID}/books/${"ef".repeat(32)}.epub`, credential, BYTES, "application/pdf"), 415, "bad_media");    await refused(await media(SLUG, "PUT", `${DATABASE_ID}/books/${"ef".repeat(32)}.pdf`, credential, BYTES, "application/octet-stream"), 415, "bad_media");    const tooBig = new TextEncoder().encode(JSON.stringify({ size: 500 * 1024 * 1024 + 1, content_type: "application/pdf" }));    await refused(await media(SLUG, "POST", PDF.replace("cd", "ef"), credential, tooBig, "application/json", "?uploads"), 413, "too_big");    const fits = new TextEncoder().encode(JSON.stringify({ size: 120 * 1024 * 1024, content_type: "application/pdf" }));    const start = await media(SLUG, "POST", `${DATABASE_ID}/books/${"0f".repeat(32)}.pdf`, credential, fits, "application/json", "?uploads");    expect(start.status, "a scanned book over one request's limit starts in parts").toBe(201);  });});/** RULE (Music definition, 4 Nov 2026): a song's file is kept as media, `<database id>/music/<sha256>.<ext>`, one of seven audio formats up to 1 GB, sent in parts above one request's limit. */describe("a song's file", () => {  const SLUG = "media-songs";  const BYTES = new TextEncoder().encode("ID3 an invented song");  let credential = "";  it("keeps every audio format under its key, each as its own type", async () => {    ({ credential } = await personalObject(SLUG));    const formats = [["mp3", "audio/mpeg"], ["m4a", "audio/mp4"], ["flac", "audio/flac"], ["ogg", "audio/ogg"], ["opus", "audio/ogg"], ["wav", "audio/wav"], ["aiff", "audio/aiff"]] as const;    for (const [n, [ext, type]] of formats.entries()) {      const key = `${DATABASE_ID}/music/${String(n).padStart(2, "0").repeat(32)}.${ext}`;      const put = await media(SLUG, "PUT", key, credential, BYTES, type);      expect(put.status, await put.clone().text()).toBe(201);      expect((await media(SLUG, "HEAD", key, credential)).headers.get("content-type")).toBe(type);    }  });  it("refuses anything else under music/: another key's shape, a type its extension does not say, and a whole past 1 GB", async () => {    const refused = async (res: Response, status: number, code: string): Promise<void> => {      expect(res.status, await res.clone().text()).toBe(status);      expect(((await res.json()) as { code: string }).code).toBe(code);    };    await refused(await media(SLUG, "PUT", `${DATABASE_ID}/music/a-song.mp3`, credential, BYTES, "audio/mpeg"), 400, "bad_key");    await refused(await media(SLUG, "PUT", `${DATABASE_ID}/music/${"ef".repeat(32)}.wma`, credential, BYTES, "audio/x-ms-wma"), 400, "bad_key");    await refused(await media(SLUG, "PUT", `${DATABASE_ID}/music/${"ef".repeat(32)}.flac`, credential, BYTES, "audio/mpeg"), 415, "bad_media");    await refused(await media(SLUG, "PUT", `${DATABASE_ID}/music/${"ef".repeat(32)}.mp3`, credential, BYTES, "application/octet-stream"), 415, "bad_media");    const tooBig = new TextEncoder().encode(JSON.stringify({ size: 1024 * 1024 * 1024 + 1, content_type: "audio/flac" }));    await refused(await media(SLUG, "POST", `${DATABASE_ID}/music/${"ef".repeat(32)}.flac`, credential, tooBig, "application/json", "?uploads"), 413, "too_big");    const fits = new TextEncoder().encode(JSON.stringify({ size: 300 * 1024 * 1024, content_type: "audio/flac" }));    const start = await media(SLUG, "POST", `${DATABASE_ID}/music/${"0f".repeat(32)}.flac`, credential, fits, "application/json", "?uploads");    expect(start.status, "a hi-res song over one request's limit starts in parts").toBe(201);  });});/** RULE (Cinemas definition, 5 Nov 2026): a film's file is kept under its folder, `<database id>/films/<id>/`: a whole MP4, M4V or MOV the phone plays as it is, or the upload waiting for the Mac (`source.<ext>`), each up to 20 GB, sent in parts above one request's limit. */describe("a film's file", () => {  const SLUG = "media-films";  const BYTES = new TextEncoder().encode("an invented film");  const folder = `${DATABASE_ID}/films/f-1/`;  let credential = "";  const refused = async (res: Response, status: number, code: string): Promise<void> => {    expect(res.status, await res.clone().text()).toBe(status);    expect(((await res.json()) as { code: string }).code).toBe(code);  };  const parts = (size: number, type: string): Uint8Array => new TextEncoder().encode(JSON.stringify({ size, content_type: type }));  it("keeps a whole film as its own type, and an upload as its type or untyped", async () => {    ({ credential } = await personalObject(SLUG));    for (const [ext, type] of [["mp4", "video/mp4"], ["m4v", "video/mp4"], ["mov", "video/quicktime"]] as const) {      const key = `${DATABASE_ID}/films/whole-${ext}/whole.${ext}`;      const put = await media(SLUG, "PUT", key, credential, BYTES, type);      expect(put.status, await put.clone().text()).toBe(201);      expect((await media(SLUG, "HEAD", key, credential)).headers.get("content-type")).toBe(type);    }    for (const [ext, type] of [["mkv", "video/x-matroska"], ["avi", "application/octet-stream"], ["ts", "video/mp2t"], ["wmv", "video/x-ms-wmv"]] as const) {      const put = await media(SLUG, "PUT", `${DATABASE_ID}/films/source-${ext}/source.${ext}`, credential, BYTES, type);      expect(put.status, await put.clone().text()).toBe(201);    }    const segment = await media(SLUG, "PUT", `${folder}video/seg-0001.m4s`, credential, BYTES, "video/iso.segment");    expect(segment.status, "the Mac's HLS folder passes as it did").toBe(201);  });  it("refuses a whole film the phone cannot play, an upload of no film container, and a type its extension does not say", async () => {    await refused(await media(SLUG, "PUT", `${folder}whole.mkv`, credential, BYTES, "video/x-matroska"), 400, "bad_key");    await refused(await media(SLUG, "PUT", `${folder}whole`, credential, BYTES, "video/mp4"), 400, "bad_key");    await refused(await media(SLUG, "PUT", `${folder}whole.mp4`, credential, BYTES, "application/octet-stream"), 415, "bad_media");    await refused(await media(SLUG, "PUT", `${folder}whole.mov`, credential, BYTES, "video/mp4"), 415, "bad_media");    await refused(await media(SLUG, "PUT", `${folder}source.srt`, credential, BYTES, "text/plain"), 400, "bad_key");    await refused(await media(SLUG, "PUT", `${folder}source.mkv`, credential, BYTES, "video/mp4"), 415, "bad_media");  });  it("takes a whole film over one request's limit in parts, and refuses one past 20 GB", async () => {    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(SLUG)), (instance: Business) => {      instance.caps.media = 60 * 1024 ** 3;    });    const start = await media(SLUG, "POST", `${folder}whole.mp4`, credential, parts(3 * 1024 ** 3, "video/mp4"), "application/json", "?uploads");    expect(start.status, "a 3 GB film starts in parts").toBe(201);    const source = await media(SLUG, "POST", `${folder}source.mkv`, credential, parts(20 * 1024 ** 3, "video/x-matroska"), "application/json", "?uploads");    expect(source.status, "an upload of 20 GB starts in parts").toBe(201);    await refused(await media(SLUG, "POST", `${DATABASE_ID}/films/f-2/whole.mp4`, credential, parts(20 * 1024 ** 3 + 1, "video/mp4"), "application/json", "?uploads"), 413, "too_big");    await refused(await media(SLUG, "POST", `${DATABASE_ID}/films/f-2/video/huge.m4s`, credential, parts(20 * 1024 ** 3 + 1, "video/iso.segment"), "application/json", "?uploads"), 413, "too_big");  });});/** * RULE (owner, 6 Nov 2026; coordinator, 8 Nov 2026): a kit's fan tile pictures are served by reference, * `photo:<sha256>`, from the Worker's static assets (ASSETS, scripts/kit.ts), never from its bundle; phones * fetch them through the media route as ever. */describe("a kit's tile picture", () => {  const SLUG = "media-kit-picture";  const stock = (DOWNLOADS.fan_tile as { stock: { photo: string } }).stock.photo;  let credential = "";  it("answers the PNG from the static assets, whose bytes are the picture its name says", async () => {    ({ credential } = await personalObject(SLUG));    const res = await media(SLUG, "GET", stock, credential);    expect(res.status).toBe(200);    expect(res.headers.get("content-type")).toBe("image/png");    expect(res.headers.get("cache-control")).toBe("private, max-age=31536000, immutable");    const bytes = new Uint8Array(await res.arrayBuffer());    const sha = [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((b) => b.toString(16).padStart(2, "0")).join("");    expect(`photo:${sha}`).toBe(stock);    expect(res.headers.get("content-length")).toBe(String(bytes.byteLength));    const fromAssets = await env.ASSETS.fetch(`https://assets.invalid/kit-pictures/${sha}.png`);    expect(new Uint8Array(await fromAssets.arrayBuffer())).toEqual(bytes);  });  it("answers HEAD with its length and no body", async () => {    const get = await media(SLUG, "GET", stock, credential);    const length = (await get.arrayBuffer()).byteLength;    const head = await media(SLUG, "HEAD", stock, credential);    expect(head.status).toBe(200);    expect(head.headers.get("content-length")).toBe(String(length));    expect((await head.arrayBuffer()).byteLength).toBe(0);  });  it("reads R2 for a photo reference that is no kit picture", async () => {    const res = await media(SLUG, "GET", `photo:${"0".repeat(64)}`, credential);    expect(res.status).toBe(404);  });});