Cotton code
310 lines · 17.7 KB · TypeScriptRaw
/** * Blind-index search over a sealed table (sealing plan §4, * L7), on a synthetic sealed table: no kit table is sealed. The proof is that * a search by blind tokens answers exactly what the same search answers over * the clear rows, by both doors a sealed table is searched through: * * - the phone's: `GET /v1/blind` with tokens the phone made, the hits opened *   on the phone and held to the words there; * - an assistant's, in a window: `search_records` and `list_records query`, *   the Worker making the tokens from BK and holding each hit to the words in *   plaintext. * * "The same search over the clear rows" is `blindMatches` over the plaintext * this file kept before sealing: every query word but the last a word of the * text, the last a word's start. Every row and key is made here. */import { env, runInDurableObject } from "cloudflare:test";import { beforeAll, describe, expect, it } from "vitest";import matchVector from "../../../crates/cotton-conformance/vectors/seal/blind_match.json";import { blindKey, blindMatches, openRow, queryTokens, tableKey } from "../src/seal.ts";import { ADMIN, DATABASE_ID, http, mint, OWNER_PHONE, PERSONAL_TABLES, PERSONAL_TOOLS, publishPersonKey, tool, windowsOnly, type ToolResult } from "./personal.ts";import { grantFor, PERSON_PUBLIC_KEY, rowTokens, sealRow } from "./seal-device.ts";import { holdsWord } from "./clear-word.ts";import { closed } from "../src/agent_statement.ts";/** The synthetic sealed table: the date clear; a heading and a body sealed, both by word tokens; a reference sealed by an exact token. */const JOURNAL = {  format_version: 1,  id: "sealed_journal",  name: "Sealed journal",  plural: "Sealed journals",  title: "heading",  date: "written_at",  columns: [    { key: "written_at", type: "date" },    { key: "heading", type: "text" },    { key: "body", type: "longtext", required: true },    { key: "reference", type: "text" },  ],  seal: { clear: ["written_at"], blind: ["heading", "body"], blind_exact: ["reference"] },};const SPEC = JOURNAL.seal;/** * Words chosen to break a careless index: words sharing their first six * letters (conference, conferred, conferring), words of two letters, a word * that is another's start (con, cone, conifer), stopwords, accents (café, * naïve), Hindi with a nukta and vowel signs, digits and mixed case. */const VOCABULARY = [  "conference", "conferred", "conferring", "confetti", "con", "cone", "conifer",  "market", "marketing", "marmalade", "Market", "MARKETS",  "quokka", "quince", "zanzibar", "zebra", "zeal",  "go", "ox", "ai", "the", "and", "of", "a",  "café", "cafe", "naïve", "résumé",  "बाज़ार", "बाजार", "किताब", "किताबें",  "2026", "404", "40", "x9",  "pelican", "pelicans", "penguin", "pen",];/** A small fixed PRNG (mulberry32), so the corpus is the same every run. */function prng(seed: number): () => number {  let a = seed;  return () => {    a = (a + 0x6d2b79f5) | 0;    let t = Math.imul(a ^ (a >>> 15), 1 | a);    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;  };}interface Clear {  id: string;  written_at: string;  heading: string;  body: string;  reference: string;}function corpus(n: number): Clear[] {  const rand = prng(7);  const pick = (): string => VOCABULARY[Math.floor(rand() * VOCABULARY.length)]!;  const out: Clear[] = [];  for (let i = 0; i < n; i++) {    const words = (k: number): string => Array.from({ length: k }, pick).join(rand() < 0.3 ? ", " : " ");    out.push({      id: crypto.randomUUID(),      written_at: new Date(Date.UTC(2026, 9, 1) + i * 3_600_000).toISOString(),      heading: words(1 + Math.floor(rand() * 3)),      body: `${words(3 + Math.floor(rand() * 8))}.`,      reference: `ref-${i}`,    });  }  return out;}/** * The queries: every vocabulary word; starts of 1 to 8 letters of the long * ones; two- and three-word queries, some taken from a row's own words in * order, some not; case and accent variants; queries that are only a * stopword or one letter. */function queries(rows: Clear[]): string[] {  const out = new Set<string>(VOCABULARY);  for (const w of ["conference", "conferring", "marketing", "marmalade", "pelicans", "zanzibar", "किताबें"]) {    for (let n = 1; n <= Math.min(8, [...w].length); n++) out.add([...w].slice(0, n).join(""));  }  const rand = prng(11);  for (let i = 0; i < 12; i++) {    const row = rows[Math.floor(rand() * rows.length)]!;    const said = row.body.replace(/[.,]/g, "").split(" ");    const at = Math.floor(rand() * Math.max(1, said.length - 1));    out.add(said.slice(at, at + 2).join(" "));    out.add(`${said[at]} ${(said[at + 1] ?? "zz").slice(0, 3)}`);  }  for (const q of ["quokka zebra", "the market", "market the", "go market", "CONFERENCE", "Café", "CAFE", "naive", "conference conferred", "pen pelican", "zebra quo", "x", "the", "of a", "बाज़ार किताब"]) out.add(q);  return [...out];}/** RULE: the twin holds a hit to the words exactly as the core does (seal-core's `blind::matches`, vector blind_match.json). */describe("the plaintext check against the core's vector", () => {  it("agrees with blind::matches on every case", () => {    for (const c of matchVector.cases) expect(blindMatches(c.text, c.query), `${JSON.stringify(c.text)} ~ ${JSON.stringify(c.query)}`).toBe(c.matches);  });});const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));/** The rows the same search finds over the clear columns. */function clearHits(rows: Clear[], query: string): string[] {  return rows.filter((r) => SPEC.blind.some((c) => blindMatches(r[c as "heading" | "body"], query))).map((r) => r.id);}function parsed(r: ToolResult): Record<string, unknown> {  expect(r.isError, r.content[0]?.text).toBe(false);  return JSON.parse(r.content[0]!.text) as Record<string, unknown>;}const sorted = (ids: string[]): string[] => [...ids].sort();describe("blind search equals the same search over the clear rows", () => {  const slug = "blind-search";  const dk = crypto.getRandomValues(new Uint8Array(32));  const rows = corpus(60);  const asked = queries(rows);  let credential = "";  let owner = "";  let lane = "";  const phone = (): Record<string, string> => ({ authorization: `Bearer ${credential}` });  /** The object's stored row, as a phone's pull carries it. */  async function stored(id: string): Promise<Record<string, unknown>> {    return runInDurableObject(stub(slug), (_i, state) => JSON.parse(state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = ? AND id = ?", JOURNAL.id, id).one().data) as Record<string, unknown>);  }  /** Every text the object keeps of rows, the blind index, the change log and the act log. */  async function kept(): Promise<string> {    return runInDurableObject(stub(slug), (_i, state) =>      JSON.stringify([        state.storage.sql.exec("SELECT data FROM rows").toArray(),        state.storage.sql.exec("SELECT * FROM blind").toArray(),        state.storage.sql.exec("SELECT before, after FROM change").toArray(),        state.storage.sql.exec("SELECT args, outcome FROM acts").toArray(),      ]),    );  }  beforeAll(async () => {    expect((await http(slug, "PUT", "/v1/admin/business", { name: "Personal", kind: "personal", owner_phone: OWNER_PHONE, database_id: DATABASE_ID, timezone: "Asia/Kolkata" }, ADMIN)).status).toBe(200);    // A window's search: this object is kept on timed windows.    await windowsOnly(slug);    const defs = await http(slug, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables: [...PERSONAL_TABLES, JOURNAL], flavour: { flavour: "personal" } }, ADMIN);    expect(defs.status, JSON.stringify(defs.body)).toBe(200);    const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: "phone" });    const signed = await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "phone" });    credential = signed.body.credential;    await publishPersonKey(slug, credential, PERSON_PUBLIC_KEY);    owner = await mint(slug, credential, "Claude (claude.ai)", ["owner"]);    lane = await mint(slug, credential, "lane widgets", ["read", "lane:widgets"], 7);    // The phone seals every row and sends its tokens: the Worker is handed no word.    for (const r of rows) {      const { id, written_at, ...sealed } = r;      const made = await http(slug, "POST", "/v1/act", { act: "create", args: { table: JOURNAL.id, id, data: { written_at, ...(await sealRow(dk, JOURNAL.id, id, 1, sealed)) }, blind: await rowTokens(dk, JOURNAL.id, SPEC, sealed) } }, phone());      expect(made.status, JSON.stringify(made.body)).toBe(200);    }  }, 300_000);  it("finds nothing for an assistant outside a window, a lane included (a lane asks like any assistant)", async () => {    const unnamed = parsed(await tool(slug, owner, "search_records", { q: "conference" }));    expect(unnamed.hits).toEqual([]);    // Every sealed table goes unsearched outside a window: this one, and the kit's own sealed tables (Messages and Email since e3bca3c99).    // A table no assistant is ever given (Sites' list, agent_statement CLOSED) is not there for it at all, so not named either.    const sealed = [...PERSONAL_TABLES, JOURNAL].filter((t) => "seal" in t && t.seal).map((t) => String(t.id)).filter((id) => !closed(id));    expect(sealed.length, "the kit seals tables of its own").toBeGreaterThan(1);    expect([...(unnamed.sealed_not_searched as string[])].sort()).toEqual(sealed.sort());    const named = await tool(slug, owner, "search_records", { q: "conference", table: JOURNAL.id });    expect(named.isError).toBe(true);    expect(named.structuredContent?.code).toBe("window_needed");    expect((await tool(slug, owner, "list_records", { table: JOURNAL.id, query: "conference" })).structuredContent?.code).toBe("window_needed");    for (const name of ["search_records", "list_records"]) {      const r = await tool(slug, lane, name, name === "search_records" ? { q: "conference", table: JOURNAL.id } : { table: JOURNAL.id, query: "conference" });      expect(r.structuredContent?.code).toBe("window_needed");    }    // A token cannot use the phone's door either.    expect((await http(slug, "GET", `/v1/blind?table=${JOURNAL.id}&tok=1`, undefined, { authorization: `Bearer ${owner}` })).status).toBe(403);  });  it("answers the phone's tokens with exactly the rows the clear search finds, once opened and held to the words on the phone", async () => {    const bk = await blindKey(dk, DATABASE_ID, JOURNAL.id);    const tk = await tableKey(dk, DATABASE_ID, JOURNAL.id, 1);    let candidates = 0;    let dropped = 0;    for (const q of asked) {      const found = new Set<string>();      for (const column of SPEC.blind) {        const toks = await queryTokens(bk, column, q);        if (!toks.length) continue;        const res = await http<{ ids: string[]; rows: { id: string; data: Record<string, unknown> }[] }>(slug, "GET", `/v1/blind?table=${JOURNAL.id}&tok=${toks.join(",")}&limit=1000&rows=1`, undefined, phone());        expect(res.status, JSON.stringify(res.body)).toBe(200);        // The hits come sealed, as the object stores them; the phone opens them.        expect(res.body.rows.map((r) => r.id)).toEqual(res.body.ids);        for (const row of res.body.rows) {          candidates++;          expect(row.data).toEqual(await stored(row.id));          const open = await openRow(tk, DATABASE_ID, JOURNAL.id, row.id, row.data);          if (blindMatches(String(open[column] ?? ""), q)) found.add(row.id);          else dropped++;        }      }      expect(sorted([...found]), `phone search ${JSON.stringify(q)}`).toEqual(sorted(clearHits(rows, q)));    }    // The corpus is built so that some token hits are not word hits (conferred behind confer…): the check is not idle.    expect(candidates).toBeGreaterThan(0);    expect(dropped).toBeGreaterThan(0);  }, 300_000);  describe("in a window", () => {    beforeAll(async () => {      const ask = await tool(slug, owner, "request_unlock", { tables: [JOURNAL.id], reason: "blind search test" });      const requestId = String(parsed(ask).request_id);      const request = await runInDurableObject(stub(slug), (_i, state) => JSON.parse(state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'unlock_request' AND id = ?", requestId).one().data) as Record<string, unknown>);      const grant = await grantFor({ dk, requestId, tokenId: String(request.token_id), tables: [[JOURNAL.id, 1]], minutes: 15, workerPub: String(request.worker_pub) });      const allowed = await http(slug, "POST", "/v1/act", { act: "unlock_allow", args: grant }, phone());      expect(allowed.status, JSON.stringify(allowed.body)).toBe(200);    }, 120_000);    it("search_records and list_records query answer exactly the rows the clear search finds", async () => {      for (const q of asked) {        const want = sorted(clearHits(rows, q));        if ([...q].length >= 2) {          const hits = parsed(await tool(slug, owner, "search_records", { q, table: JOURNAL.id, limit: 200 })).hits as { id: string; column: string; excerpt: string }[];          expect(sorted(hits.map((h) => h.id)), `search_records ${JSON.stringify(q)}`).toEqual(want);          for (const h of hits) expect(SPEC.blind).toContain(h.column);        }        const listed = parsed(await tool(slug, owner, "list_records", { table: JOURNAL.id, query: q, limit: 1000 })).records as { id: string }[];        expect(sorted(listed.map((r) => r.id)), `list_records query ${JSON.stringify(q)}`).toEqual(want);      }    }, 300_000);    it("finds by a word's start, and drops a hit whose six-letter prefix token matched a longer word", async () => {      // "conference" asks the token of "confer": "conferred" and "conferring" share it and are dropped in plaintext.      const hits = parsed(await tool(slug, owner, "search_records", { q: "conference", table: JOURNAL.id, limit: 200 })).hits as { id: string; excerpt: string }[];      expect(hits.length).toBeGreaterThan(0);      for (const h of hits) expect(h.excerpt.toLowerCase()).toContain("conference");      const holdsOnlyLonger = rows.filter((r) => /conferr/i.test(`${r.heading} ${r.body}`) && !/conference/i.test(`${r.heading} ${r.body}`)).map((r) => r.id);      expect(holdsOnlyLonger.length).toBeGreaterThan(0);      for (const id of holdsOnlyLonger) expect(hits.map((h) => h.id)).not.toContain(id);      // A word's start finds every word it starts.      const starts = parsed(await tool(slug, owner, "search_records", { q: "conf", table: JOURNAL.id, limit: 200 })).hits as { id: string }[];      expect(sorted(starts.map((h) => h.id))).toEqual(sorted(rows.filter((r) => /\bconf/i.test(`${r.heading} ${r.body}`)).map((r) => r.id)));    });    it("fills a small page past candidates the plaintext check drops, newest first, and says when more are left", async () => {      for (const q of ["conference", "confetti", "market"]) {        const want = rows.filter((r) => clearHits([r], q).length).sort((a, b) => b.written_at.localeCompare(a.written_at)).map((r) => r.id);        for (const limit of [1, 2, 3]) {          const found = parsed(await tool(slug, owner, "search_records", { q, table: JOURNAL.id, limit }));          expect((found.hits as { id: string }[]).map((h) => h.id), `${q} limit ${limit}`).toEqual(want.slice(0, limit));          expect(found.more, `${q} limit ${limit}`).toBe(want.length > limit);        }      }    });    it("drops a hit whose stored tokens claim a word its sealed text does not hold", async () => {      // A row whose index says "walrus" (a stale or forged token set) while its sealed body never does.      const id = crypto.randomUUID();      const sealed = { heading: "plain", body: "nothing to see here" };      const lying = await rowTokens(dk, JOURNAL.id, SPEC, { body: "walrus" });      const made = await http(slug, "POST", "/v1/act", { act: "create", args: { table: JOURNAL.id, id, data: { written_at: "2026-11-20T00:00:00.000Z", ...(await sealRow(dk, JOURNAL.id, id, 1, sealed)) }, blind: lying } }, phone());      expect(made.status, JSON.stringify(made.body)).toBe(200);      const bk = await blindKey(dk, DATABASE_ID, JOURNAL.id);      const tokenHit = await http<{ ids: string[] }>(slug, "GET", `/v1/blind?table=${JOURNAL.id}&tok=${(await queryTokens(bk, "body", "walrus")).join(",")}`, undefined, phone());      expect(tokenHit.body.ids).toEqual([id]);      expect(parsed(await tool(slug, owner, "search_records", { q: "walrus", table: JOURNAL.id })).hits).toEqual([]);      expect(parsed(await tool(slug, owner, "list_records", { table: JOURNAL.id, query: "walrus" })).records).toEqual([]);    });  });  it("keeps nothing but tokens: no word of the corpus in rows, the index, the change log or the act log, and a word is no token", async () => {    const text = (await kept()).toLowerCase();    // A word is looked for only where no base64url character comes before it (test/clear-word.ts).    const clear = (haystack: string, word: string) => holdsWord(haystack, word);    // The finder is not idle: it catches a word in a string or straight after a seal's prefix, and passes a chance run.    expect([clear('{"body":"the quokka"}', "quokka"), clear('"s1:pelicanxyz"', "pelican"), clear('"s1:q9xref-1zz"', "ref-1"), clear('"heading":"ref-1"', "ref-1")]).toEqual([true, true, false, true]);    for (const w of ["conference", "marmalade", "quokka", "zanzibar", "pelican", "penguin", "résumé", "किताब", "ref-1"]) expect(clear(text, w), w).toBe(false);    const refused = await http(slug, "GET", `/v1/blind?table=${JOURNAL.id}&tok=quokka`, undefined, phone());    expect([refused.status, (refused.body as { code?: string }).code]).toEqual([400, "bad_blind"]);  });});