Cotton code
236 lines · 14.4 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import vector from "../../../crates/cotton-rules/vectors/open_bundle.json";import type { Business } from "../src/business.ts";import { OPEN_BUNDLE_KITS } from "../src/mcp/tools/open_bundle.ts";import { isDeviceSealedKind } from "../src/table_files.ts";import { crc32 } from "../src/zip.ts";import { sealRow } from "./seal-device.ts";import { answer, DATABASE_ID, http, mint, PERSONAL_TABLES, personalObject, put, refusal, tool } from "./personal.ts";type Row = Record<string, unknown>;type Held = { text: string } | { base64: string };interface KitVector {  tables: Record<string, Row[]>;  media: Record<string, Held>;  tree: string[];  missing_media: string[];}const KITS = vector.kits as unknown as Record<keyof typeof OPEN_BUNDLE_KITS, KitVector>;function expectedTree(kit: keyof typeof KITS): string[] {  return KITS[kit].tree;}/** The order rows are seeded in, so every link names a row already there. */const SEED_ORDER = ["record_group", "group_member", "book", "highlight", "film", "film_season", "film_episode", "watch"];interface Exported {  document: string;  files: number;  missing_media: string[];  sealed_left_out: number;  bytes: number;}function bytesOf(held: Held): Uint8Array {  return "text" in held ? new TextEncoder().encode(held.text) : Uint8Array.from(atob(held.base64), (c) => c.charCodeAt(0));}/** A media key's bucket path in the object at `slug` (src/media.ts `bucketKey`). */function bucket(slug: string, key: string): string {  expect(key.startsWith(`${DATABASE_ID}/`)).toBe(true);  return `${slug}/${key.slice(DATABASE_ID.length + 1)}`;}/** * The vector's rows and media into a fresh object: rows through the admin * import under the fixture's own ids (two books of one author and title are * told apart by id), bytes straight into R2. * The store's synthetic rows leave a few columns empty that the object * requires (a listen's song, an episode's title); each is filled — a link * with the first row of its table, text with a word — in a way that names no * file and moves no path in the tree. *//** The kits' tables, opened as a fixture: the bundle's tree over open rows (a sealed library is read in a window, below). */const LIBRARY_OPEN = { open: ["book", "highlight", "film", "film_season", "film_episode", "watch", "record_group", "group_member"] };async function seeded(slug: string, kit: keyof typeof KITS): Promise<string> {  const { owner } = await personalObject(slug, { ...LIBRARY_OPEN, arrival: true, windows: true });  const v = KITS[kit];  for (const [key, held] of Object.entries(v.media)) await env.MEDIA.put(bucket(slug, key), bytesOf(held));  const rows: Row[] = [];  for (const table of SEED_ORDER.filter((t) => t in v.tables)) {    const def = PERSONAL_TABLES.find((t) => t.id === table)!;    const defined = def.columns as { key: string; type: string; required?: boolean; link_to?: string; computed?: unknown }[];    const columns = new Set(defined.filter((c) => !c.computed).map((c) => c.key));    for (const row of v.tables[table]!) {      const data: Row = {};      for (const [key, value] of Object.entries(row)) {        if (!columns.has(key) || key === "created_at") continue;        data[key] = value;      }      for (const c of defined.filter((c) => c.required && (data[c.key] === undefined || data[c.key] === null))) {        if (c.type === "link") data[c.key] = v.tables[c.link_to!]![0]!.id;        else if (c.type === "text" || c.type === "longtext") data[c.key] = "Untitled";        else throw new Error(`${table}.${c.key} is required and the vector leaves it empty`);      }      rows.push({ id: row.id, table, data });    }  }  await put(slug, rows);  return owner;}/** A stored ZIP read back whole: each entry's name and bytes, its CRC checked against its local header's descriptor and the central directory. */function unzip(zip: Uint8Array): { name: string; bytes: Uint8Array }[] {  const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);  const end = zip.byteLength - 22;  expect(view.getUint32(end, true)).toBe(0x06054b50);  const count = view.getUint16(end + 10, true);  let at = view.getUint32(end + 16, true);  const out: { name: string; bytes: Uint8Array }[] = [];  for (let i = 0; i < count; i++) {    expect(view.getUint32(at, true)).toBe(0x02014b50);    const crc = view.getUint32(at + 16, true);    const size = view.getUint32(at + 20, true);    const nameLength = view.getUint16(at + 28, true);    const local = view.getUint32(at + 42, true);    const name = new TextDecoder().decode(zip.subarray(at + 46, at + 46 + nameLength));    expect(view.getUint32(local, true)).toBe(0x04034b50);    expect(view.getUint16(local + 8, true), "stored").toBe(0);    const data = local + 30 + view.getUint16(local + 26, true) + view.getUint16(local + 28, true);    const bytes = zip.subarray(data, data + size);    expect(crc32(bytes), name).toBe(crc);    expect(view.getUint32(data + size, true)).toBe(0x08074b50);    expect(view.getUint32(data + size + 4, true)).toBe(crc);    out.push({ name, bytes });    at += 46 + nameLength + view.getUint16(at + 30, true) + view.getUint16(at + 32, true);  }  return out;}async function stored(slug: string, owner: string, made: Exported): Promise<{ record: Row; entries: { name: string; bytes: Uint8Array }[] }> {  // Documents are sealed (e2e rulings R1): the bundle's record is read as stored, its name inside its seal.  void owner;  const record = { data: await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, state) => JSON.parse(state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'document' AND id = ?", made.document).one().data) as Row) };  const key = String(record.data.storage_path);  const object = await env.MEDIA.get(bucket(slug, key));  expect(object, key).not.toBeNull();  const zip = new Uint8Array(await object!.arrayBuffer());  expect(zip.byteLength).toBe(made.bytes);  return { record: record.data, entries: unzip(zip) };}/** RULE (7 Nov 2026): an assistant asks for a kit's library in open formats and gets a ZIP laid by the phone's own writer, kept as the owner's document. */describe("export_open_bundle", () => {  // Music and Podcasts left with TABLE DROP 1 (owner, 27 Nov 2026): the writer's vector still holds them, the Worker lays only its own kits.  for (const kit of Object.keys(OPEN_BUNDLE_KITS) as (keyof typeof KITS)[]) {    it(`${kit}: the ZIP's entries are the fixture's tree, every sealed-kind file left out and counted, kept as a document`, async () => {      const slug = `openbundle${kit}`;      const owner = await seeded(slug, kit);      const made = await answer<Exported>(slug, owner, "export_open_bundle", { kit });      const v = KITS[kit];      const { record, entries } = await stored(slug, owner, made);      expect(made.files).toBe(entries.length);      // AVATAR SEAL 4 (4): a book's, a song's, a film's file is a kind the person's devices seal; an assistant reads      // none, so the ZIP (a plain document) lays the lists and metadata and leaves each file out, counted, not missing.      const sealedKeys = [...Object.keys(v.media), ...v.missing_media].filter((k) => isDeviceSealedKind(DATABASE_ID, k));      // Podcasts' episodes are no kind a device seals: nothing of theirs is left out.      if (sealedKeys.length) expect(made.sealed_left_out).toBeGreaterThan(0);      else expect(made.sealed_left_out).toBe(0);      expect(made.missing_media).toEqual(v.missing_media.filter((k) => !isDeviceSealedKind(DATABASE_ID, k)));      const tree = expectedTree(kit);      for (const e of entries) expect(tree, e.name).toContain(e.name);      if (sealedKeys.length) expect(entries.length).toBeLessThan(tree.length);      expect(record).toMatchObject({ mime: "application/zip", byte_size: made.bytes, source: "agent" });      expect(String(record.dek_enc)).toMatch(/^a1:/);      for (const k of ["title", "original_name"]) expect(record, k).not.toHaveProperty(k);      expect(record.sha256).toMatch(/^[0-9a-f]{64}$/);      // No held sealed-kind file's bytes are in any entry.      for (const [key, held] of Object.entries(v.media)) {        if (!isDeviceSealedKind(DATABASE_ID, key)) continue;        const want = bytesOf(held);        if (want.byteLength < 8) continue;        expect(entries.some((e) => e.bytes.byteLength === want.byteLength && e.bytes.every((b, i) => b === want[i])), key).toBe(false);      }      // Documents are sealed: an assistant reading the list back needs a window.      expect(await refusal(slug, owner, "list_records", { table: "document" })).toContain("window");    });  }  it("books: an epub is left out, its metadata and the catalogue laid", async () => {    const slug = "openbundlebooksbytes";    const owner = await seeded(slug, "books");    const { entries } = await stored(slug, owner, await answer<Exported>(slug, owner, "export_open_bundle", { kit: "books" }));    expect(entries.find((e) => e.name === "Books/Ana Vell/Harbour Lights/Harbour Lights.epub"), "an assistant reads no book's file").toBeUndefined();    expect(entries.find((e) => e.name === "Books/Ana Vell/Harbour Lights/metadata.opf")).toBeDefined();    const catalog = new TextDecoder().decode(entries.find((e) => e.name === "Books/catalog.xml")!.bytes);    expect(catalog).toContain(`<id>urn:cotton:books:${DATABASE_ID}</id>`);  });  it("media: false keeps the lists and metadata alone, and reports nothing missing", async () => {    const slug = "openbundlenomedia";    const owner = await seeded(slug, "books");    const made = await answer<Exported>(slug, owner, "export_open_bundle", { kit: "books", media: false });    expect(made.missing_media).toEqual([]);    const { entries } = await stored(slug, owner, made);    const names = entries.map((e) => e.name);    expect(names).toContain("Books/goodreads.csv");    expect(names).toContain("Books/Ana Vell/Harbour Lights/metadata.opf");    expect(names.filter((n) => /\.(epub|pdf|jpg)$/.test(n))).toEqual([]);  });  it("refuses an empty library, a kit it does not lay, a token that is not the owner's, and a ZIP past the media cap", async () => {    const slug = "openbundlerefusals";    const { credential, owner } = await personalObject(slug, { ...LIBRARY_OPEN, arrival: true, windows: true });    expect(await refusal(slug, owner, "export_open_bundle", { kit: "books" })).toBe("There are no books in this database: the Books library is empty, so there is nothing to export");    expect(await refusal(slug, owner, "export_open_bundle", { kit: "films" })).toBe("There are no films or series in this database: the Films library is empty, so there is nothing to export");    expect(await refusal(slug, owner, "export_open_bundle", { kit: "games" })).toBe("kit is one of books, films");    expect(await refusal(slug, owner, "export_open_bundle", { kit: "books", media: "yes" })).toBe("media is true or false");    const writer = await mint(slug, credential, "an assistant", ["read", "write"]);    expect(await refusal(slug, writer, "export_open_bundle", { kit: "books" })).toBe('this token does not have "owner" access. Ask the owner to reconnect with owner enabled.');    await put(slug, [{ table: "book", data: { title: "One Book", status: "want_to_read" } }]);    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance: Business) => {      Object.assign(instance.caps, { media: 0 });    });    expect(await refusal(slug, owner, "export_open_bundle", { kit: "books" })).toBe("This database's media have reached their size limit: they still read, but take nothing new.");    const docs = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE table_id = 'document'").one().n);    expect(docs).toBe(0);  });  // RULE (e2e rulings R4): a sealed library is read only inside the owner's window for the assistant, never exported as blobs.  it("asks for a window before it reads a sealed library", async () => {    const slug = "openbundlesealed";    const { credential, owner } = await personalObject(slug, { arrival: true, windows: true });    expect((await http(slug, "POST", "/v1/act", { act: "create", args: { table: "book", id: "b-sealed", data: { status: "want_to_read", ...(await sealRow(new Uint8Array(32).fill(3), "book", "b-sealed", 1, { title: "Sealed shelf" })) } } }, { authorization: `Bearer ${credential}` })).status).toBe(200);    const asked = await tool(slug, owner, "export_open_bundle", { kit: "books" });    expect(asked.isError).toBe(true);    expect(asked.content[0]!.text).toContain("window");  });  // AVATAR SEAL 3 (2), SEAL 4 (4): every tool reads a file through ctx.media; a book row pointed at a person's face  // (as its cover and as its file) never puts the face in a ZIP: the files are left out and counted (inside a window  // over person too: window.test.ts "an open bundle inside a window over person").  it("never lays a person's face that a book row names", async () => {    const slug = "openbundleface";    const { owner } = await personalObject(slug, { ...LIBRARY_OPEN, arrival: true, windows: true });    const face = `${DATABASE_ID}/people/p-1/${"5e".repeat(32)}.jpg`;    const faceAsBook = `${DATABASE_ID}/people/p-1/${"6f".repeat(32)}.epub`;    const bytes = new TextEncoder().encode("\xFF\xD8\xFF an invented face from before");    for (const key of [face, faceAsBook]) await env.MEDIA.put(bucket(slug, key), bytes);    await put(slug, [{ table: "book", data: { title: "Pointed elsewhere", status: "want_to_read", cover: face, file: faceAsBook } }]);    const made = await answer<Exported>(slug, owner, "export_open_bundle", { kit: "books" });    expect(made.sealed_left_out).toBe(2);    expect(made.missing_media).toEqual([]);    const { entries } = await stored(slug, owner, made);    expect(entries.some((e) => e.bytes.byteLength === bytes.byteLength && e.bytes.every((b, i) => b === bytes[i])), "the face is in no entry").toBe(false);  });  it("reads the tables the writer reads (cotton_rules::open_bundle::Kit::tables)", () => {    // The writer's vector still lays Music and Podcasts; the Worker lays only its own kits, each with the vector's tables.    for (const kit of Object.keys(OPEN_BUNDLE_KITS)) {      const own = Object.keys(KITS[kit as keyof typeof KITS].tables).filter((t) => t !== "record_group" && t !== "group_member");      expect([...OPEN_BUNDLE_KITS[kit as keyof typeof KITS].tables].sort(), kit).toEqual(own.sort());    }  });});