Cotton code
140 lines · 12.2 KB · TypeScriptRaw
import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import type { Business } from "../src/business.ts";import { answer, DATABASE_ID, mint, GROUPS_OPEN, personalObject, put, refusal, tool } from "./personal.ts";/** A real 32×24 PNG, so the resizer has an image to read. */const PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAIAAAAUMWhjAAAAJElEQVR4nGM4EaBBU8QwasGoBaMWjFowasGoBaMWjFowNCwAAOj5wC7/fbJHAAAAAElFTkSuQmCC";const PNG = Uint8Array.from(atob(PNG_BASE64), (c) => c.charCodeAt(0));const PDF = new TextEncoder().encode("%PDF-1.4\n% a synthetic statement\n%%EOF\n");function b64(bytes: Uint8Array): string {  return btoa(String.fromCharCode(...bytes));}async function putMedia(slug: string, key: string, token: string, bytes: Uint8Array, type: string): Promise<void> {  const res = await SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}`, { method: "PUT", headers: { authorization: `Bearer ${token}`, "content-type": type, "content-length": String(bytes.length) }, body: bytes });  expect(res.status, await res.clone().text()).toBe(201);}/** RULE (owner, 26 Oct 2026): Cotton MCP hands over the file a record keeps, from R2 under the record's own key, and stores a document as the imports store media. */describe("media through Cotton MCP", () => {  const slug = "mcpmedia";  let owner = "";  let reader = "";  let ids: Record<string, string> = {};  const photoKey = `${DATABASE_ID}/photos/${"ab".repeat(32)}.png`;  it("get_media refuses a photo, whole or drawn at a size: an assistant reads no photo file (AVATAR SEAL 4)", async () => {    const made = await personalObject(slug, { arrival: true });    owner = made.owner;    reader = await mint(slug, made.credential, "a reader", ["read"]);    // The owner's device lays the file; no token writes a photo's.    await putMedia(slug, photoKey, made.credential, PNG, "image/png");    ids = await put(slug, [      { ref: "photo", table: "photo", data: { key: photoKey, caption: "Beach" } },      { ref: "unstored", table: "photo", data: { key: `${DATABASE_ID}/photos/${"cd".repeat(32)}.png` } },      { ref: "bare", table: "note", data: { title: "No file here" } },    ]);    // Photos open in no window: refused whole and at a size, and the same for a photo whose file is not stored (no oracle).    for (const args of [{ id: ids.photo! }, { id: ids.photo!, table: "photo", width: 16 }, { id: ids.unstored! }]) {      expect(await refusal(slug, reader, "get_media", args), JSON.stringify(args)).toMatch(/sealed files/);    }  });  it("put_document stores the file once, makes its record, and get_media hands it back", async () => {    const made = await answer<{ record: { id: string; data: Record<string, unknown> }; stored: boolean }>(slug, owner, "put_document", { name: "March statement.pdf", kind: "bank_statement", bytes_base64: b64(PDF) });    expect(made.stored).toBe(true);    const sha = [...new Uint8Array(await crypto.subtle.digest("SHA-256", PDF))].map((b) => b.toString(16).padStart(2, "0")).join("");    // Documents are sealed (e2e rulings R1): the record is sealed as it arrives, its name inside the seal, its file's facts clear.    expect(made).toHaveProperty("sealed_at_arrival");    for (const k of ["title", "original_name"]) expect(made.record.data, k).not.toHaveProperty(k);    expect(made.record.data).toMatchObject({ mime: "application/pdf", byte_size: PDF.length, sha256: sha, storage_path: `${DATABASE_ID}/documents/${sha}.pdf`, doc_type: "bank_statement", source: "agent" });    const back = await tool(slug, reader, "get_media", { id: made.record.id });    expect(back.content[1]).toEqual({ type: "resource", resource: { uri: `cotton-media:${DATABASE_ID}/documents/${sha}.pdf`, mimeType: "application/pdf", blob: b64(PDF) } });    const again = await answer<{ stored: boolean }>(slug, owner, "put_document", { name: "copy.pdf", bytes_base64: b64(PDF) });    expect(again.stored).toBe(false);    expect(await refusal(slug, reader, "get_media", { id: made.record.id, width: 10 })).toBe("only an image is drawn at a size");  });  it("refuses what keeps no file, a file not stored yet, and a bad upload", async () => {    expect(await refusal(slug, reader, "get_media", { id: ids.bare! })).toBe(`no record ${JSON.stringify(ids.bare)} keeps a file: name a photo, a document or another record with one [get_media r3, step row]`);    expect(await refusal(slug, owner, "put_document", { name: "x.pdf" })).toBe("give the file as bytes_base64 or as url, one of them");    expect(await refusal(slug, owner, "put_document", { name: "x.pdf", bytes_base64: "AAAA", url: "https://example.test/x.pdf" })).toBe("give the file as bytes_base64 or as url, one of them");    expect(await refusal(slug, owner, "put_document", { name: "x.pdf", url: "ftp://example.test/x.pdf" })).toBe("url must be an absolute web address starting http:// or https://");    expect(await refusal(slug, owner, "put_document", { name: "x.pdf", bytes_base64: "not base64!" })).toBe("bytes_base64 is not base64");    expect(await refusal(slug, owner, "put_document", { name: "x.pdf", kind: "novel", bytes_base64: b64(PDF) })).toMatch(/^kind is one of bank_statement, /);    expect(await refusal(slug, reader, "put_document", { name: "x.pdf", bytes_base64: b64(PDF) })).toBe('this token does not have "write" access. Ask the owner to reconnect with write enabled.');  });  it("refuses an upload past the object's media cap, and makes no record", async () => {    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance: Business) => {      Object.assign(instance.caps, { media: 0 });    });    const other = new TextEncoder().encode("%PDF-1.4\n% another synthetic file\n%%EOF\n");    expect(await refusal(slug, owner, "put_document", { name: "big.pdf", bytes_base64: b64(other) })).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(2);  });});/** RULE (5 Nov 2026): a list's own picture is set over Cotton MCP the way any photo column is filled: put_document keeps the picture, and update_record on the list names its storage_path in `picture`; get_media hands it back, the object draws it at the tile's 256 px as the phone's thumbnail asks, and a null takes it off. */describe("a list's own picture through Cotton MCP", () => {  const slug = "mcplistpicture";  it("put_document then update_record { picture } on record_group, drawn at 256 px, and taken off", async () => {    const { owner } = await personalObject(slug, { ...GROUPS_OPEN, arrival: true });    const list = await answer<{ record: { id: string } }>(slug, owner, "create_record", { table: "record_group", data: { table_id: "book", name: "Synthetic shelf" } });    const kept = await answer<{ record: { data: { storage_path: string } } }>(slug, owner, "put_document", { name: "shelf.png", bytes_base64: PNG_BASE64 });    const key = kept.record.data.storage_path;    expect(key).toMatch(new RegExp(`^${DATABASE_ID}/documents/[0-9a-f]{64}\\.png$`));    const set = await answer<{ record: { data: Record<string, unknown> } }>(slug, owner, "update_record", { table: "record_group", id: list.record.id, patch: { picture: key } });    expect(set.record.data).toMatchObject({ name: "Synthetic shelf", picture: key });    const back = await tool(slug, owner, "get_media", { id: list.record.id, table: "record_group" });    expect(JSON.parse(back.content[0]!.text)).toMatchObject({ table: "record_group", column: "picture", key, content_type: "image/png" });    const thumb = await SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}?width=256`, { headers: { authorization: `Bearer ${owner}` } });    expect(thumb.status).toBe(200);    expect(thumb.headers.get("content-type")).toBe("image/webp");    await thumb.arrayBuffer();    const off = await answer<{ record: { data: Record<string, unknown> } }>(slug, owner, "update_record", { table: "record_group", id: list.record.id, patch: { picture: null } });    expect(off.record.data.picture ?? null).toBeNull();  });});/** RULE (owner, 22 Nov 2026, Comms iPhone build 19): a picture sent or kept in a chat has no photo row; it is its message's `media`, and get_media reads it from the message by index. `photo:<sha256>` with no photo row says where to look, and a file sealed on the device is refused plainly, never handed over as its sealed bytes. */describe("a chat picture through Cotton MCP", () => {  const slug = "mcpchatpicture";  it("reads a message's kept pictures by index, and says where a chat picture is", async () => {    const made = await personalObject(slug, { arrival: true });    const reader = await mint(slug, made.credential, "a reader", ["read"]);    const sha = "ef".repeat(32);    const first = `${DATABASE_ID}/messages/thread-1/${sha}.png`;    const second = `${DATABASE_ID}/messages/thread-1/${"12".repeat(32)}.png`;    const sealed = `${DATABASE_ID}/messages/thread-1/${"34".repeat(32)}.png`;    await putMedia(slug, first, made.credential, PNG, "image/png");    await putMedia(slug, second, made.credential, PNG, "image/png");    await putMedia(slug, sealed, made.credential, new TextEncoder().encode("CTF1 synthetic sealed bytes"), "application/vnd.cotton.f1");    const media = (key: string) => ({ key, contentType: "image/png", name: "p.png", sizeBytes: PNG.length, cottonKept: true });    const ids = await put(slug, [      { ref: "thread", table: "thread", data: { channel: "cotton", title: "Invented group" } },      { ref: "two", table: "message", data: { thread_id: "@thread", channel: "cotton", body: "two pictures", sent_at: "2026-11-22T08:00:00.000Z", media: [media(first), media(second)] } },      { ref: "none", table: "message", data: { thread_id: "@thread", channel: "cotton", body: "no pictures", sent_at: "2026-11-22T08:02:00.000Z", media: [] } },      { ref: "keyless", table: "message", data: { thread_id: "@thread", channel: "cotton", body: "keyless", sent_at: "2026-11-22T08:03:00.000Z", media: [{ name: "p.png", contentType: "image/png" }] } },      { ref: "sealed", table: "message", data: { thread_id: "@thread", channel: "cotton", body: "sealed", sent_at: "2026-11-22T08:01:00.000Z", media: [media(sealed)] } },    ]);    // AVATAR SEAL 3 (1): a kept chat picture still held plain from before is read only inside a window over messages,    // as a sealed one is: outside one, it asks for one (read by index in a window: window.test.ts).    expect(await refusal(slug, reader, "get_media", { table: "message", id: ids.two! })).toMatch(/^Messages are private to the owner\./);    expect(await refusal(slug, reader, "get_media", { table: "message", id: ids.two!, index: 1 })).toMatch(/^Messages are private to the owner\./);    expect(await refusal(slug, reader, "get_media", { table: "message", id: ids.two!, index: 2 })).toBe("That message keeps 2 files: index is 0 to 1 [get_media r3, step index]");    expect(await refusal(slug, reader, "get_media", { id: `photo:${sha}`, table: "photo" })).toMatch(/^no photo "photo:[0-9a-f]{64}" is here\. A picture sent or kept in a chat is its message's: get_media \{ table: "message"/);    // Each refusal names its step and says the value's shape, never what it holds.    expect(await refusal(slug, reader, "get_media", { table: "message", id: "no-such-message" })).toBe("That message is no longer here: no row of message has that id, or it is in the bin [get_media r3, step row]");    expect(await refusal(slug, reader, "get_media", { table: "message", id: ids.none! })).toBe("That message keeps no file: it is not sealed, and media is an empty list; sender_photo is absent [get_media r3, step media]");    expect(await refusal(slug, reader, "get_media", { table: "message", id: ids.keyless! })).toBe("That message keeps no file: it is not sealed, and media is a list of 1: objects with fields contentType, name; sender_photo is absent [get_media r3, step media]");    // A kept chat picture sealed on the phone (22 Nov 2026) opens inside a window over messages: outside one, it asks for one.    expect(await refusal(slug, reader, "get_media", { table: "message", id: ids.sealed! })).toMatch(/^Messages are private to the owner\./);  });});