Cotton code
149 lines · 9.4 KB · TypeScriptRaw
/** * Shared lists (ruling R5, 16 Nov 2026) over synthetic * people's objects on the open host. The phones' half (sealing every item to * the list's own key, wrapping that key to each member, sealing every item * again when someone is removed) is cotton-core `seal::shared_list`, proven in * Rust; here the objects are handed what those phones post — wraps and * `g1:` text — and the test proves who may read and change a list, and that * nothing either object keeps is a word of it. */import { env, runInDurableObject } from "cloudflare:test";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Business } from "../src/business.ts";import { bearer, fakes, open } from "./calling.ts";import { chatPhone, type ChatPhone } from "./chat.ts";vi.setConfig({ testTimeout: 180_000 });let n = 0;const number = (): string => `+91900003${String(1000 + ++n).padStart(4, "0")}`;beforeEach(() => {  fakes();});afterEach(() => {  vi.restoreAllMocks();});type Body = Record<string, unknown>;interface Person {  phone: ChatPhone;  slug: string;  number: string;  key: string;  ask<T = Body>(method: string, path: string, body?: unknown): Promise<{ status: number; body: T }>;}function b64url(bytes: Uint8Array): string {  let s = "";  for (const b of bytes) s += String.fromCharCode(b);  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}const opaque = (n: number): string => b64url(crypto.getRandomValues(new Uint8Array(n)));async function person(): Promise<Person> {  const phone = await chatPhone(number(), `dev-${n}`);  const slug = (await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).lookup(phone.number))!;  const key = opaque(32);  // The person's sharing key, as their phone posts it: what a list holds for them, and what reading it is checked against (AUDIT FIX B1).  const posted = await open("POST", "/v1/send/key", { key }, bearer(phone.credential));  if (posted.status !== 200) throw new Error(`send key: ${posted.status}`);  return { phone, slug, number: phone.number, key, ask: <T = Body>(method: string, path: string, body?: unknown) => open<T>(method, path, body, bearer(phone.credential)) };}async function accept(x: Person, y: Person): Promise<void> {  await x.phone.say("accept", y.number);  await y.phone.say("accept", x.number);}/** A list's state as the phones lay it: each member's key and wrap at `epoch`, and the items sealed at it. */function state(id: string, epoch: number, members: Person[], items: Record<string, number>, past: Record<string, Record<string, string>> = {}) {  const wraps: Record<string, Record<string, string>> = { ...past, [String(epoch)]: Object.fromEntries(members.map((m) => [m.number, `w1:${opaque(80)}`])) };  return {    membership: { set_id: id, epoch, members: Object.fromEntries(members.map((m) => [m.number, m.key])), wraps },    items: Object.fromEntries(Object.entries(items).map(([k, e]) => [k, `g1:${e}:${opaque(40)}`])),  };}function kept(slug: string): Promise<string> {  return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i: Business, s) => {    const rows = s.storage.sql.exec("SELECT * FROM shared_list").toArray();    const ins = s.storage.sql.exec("SELECT * FROM shared_in").toArray();    return JSON.stringify({ rows, ins });  });}describe("shared lists, sealed to their own key (R5)", () => {  it("both people see and edit the list through their own objects; the objects keep only wraps and sealed text", async () => {    const a = await person();    const b = await person();    await accept(a, b);    const founded = await a.ask("POST", "/v1/shared/lists", { id: "list-weekend", state: state("list-weekend", 1, [a, b], { i1: 1 }) });    expect(founded.status, JSON.stringify(founded.body)).toBe(200);    // b's object was told: the list stands among b's lists, read where it lives.    const mine = await b.ask<{ lists: { owner: string; id: string }[] }>("GET", "/v1/shared/lists");    expect(mine.body.lists).toContainEqual({ owner: a.number, id: "list-weekend" });    const read = await b.ask<{ state: { items: Record<string, string> } }>("GET", `/v1/shared/list?owner=${encodeURIComponent(a.number)}&id=list-weekend`);    expect(read.status).toBe(200);    expect(Object.keys(read.body.state.items)).toEqual(["i1"]);    // b edits and adds, sealed at the current epoch; a reads both.    expect((await b.ask("POST", "/v1/shared/list/item", { owner: a.number, id: "list-weekend", item: "i2", sealed: `g1:1:${opaque(40)}` })).status).toBe(200);    expect((await b.ask("POST", "/v1/shared/list/item", { owner: a.number, id: "list-weekend", item: "i1", sealed: `g1:1:${opaque(40)}` })).status).toBe(200);    const aSees = await a.ask<{ state: { items: Record<string, string> } }>("GET", "/v1/shared/list?id=list-weekend");    expect(Object.keys(aSees.body.state.items).sort()).toEqual(["i1", "i2"]);    // An item sealed at another epoch, or not sealed at all, is refused.    expect((await b.ask("POST", "/v1/shared/list/item", { owner: a.number, id: "list-weekend", item: "i3", sealed: `g1:2:${opaque(40)}` })).status).toBe(403);    expect((await b.ask("POST", "/v1/shared/list/item", { owner: a.number, id: "list-weekend", item: "i3", sealed: "Rye bread" })).status).toBe(403);    expect(await kept(a.slug)).not.toContain("Rye");  });  it("refuses a stranger everything, and a list with someone who is not one's person", async () => {    const a = await person();    const b = await person();    const z = await person();    await accept(a, b);    expect((await a.ask("POST", "/v1/shared/lists", { id: "list-camp", state: state("list-camp", 1, [a, z], {}) })).status).toBe(403);    expect((await a.ask("POST", "/v1/shared/lists", { id: "list-camp", state: state("list-camp", 1, [a, b], { i1: 1 }) })).status).toBe(200);    await accept(z, a);    expect((await z.ask("GET", `/v1/shared/list?owner=${encodeURIComponent(a.number)}&id=list-camp`)).status, "a stranger to the list is told it is not there").toBe(404);    expect((await z.ask("POST", "/v1/shared/list/item", { owner: a.number, id: "list-camp", item: "i9", sealed: `g1:1:${opaque(40)}` })).status).toBe(403);    expect((await z.ask("POST", "/v1/shared/list/state", { owner: a.number, id: "list-camp", state: state("list-camp", 1, [a, b, z], { i1: 1 }) })).status).toBe(403);    expect((await z.ask<{ lists: unknown[] }>("GET", "/v1/shared/lists")).body.lists).toEqual([]);  });  it("adds a member at the same epoch; removing one moves the epoch on, every item sealed again, and the removed member reads and writes nothing after", async () => {    const a = await person();    const b = await person();    const c = await person();    await accept(a, b);    await accept(a, c);    await accept(b, c);    const first = state("list-trip", 1, [a, b], { i1: 1, i2: 1 });    expect((await a.ask("POST", "/v1/shared/lists", { id: "list-trip", state: first })).status).toBe(200);    // b, a member, may not add c (AUDIT FIX B1: only the founder adds); a adds c: the same epoch, c's wrap beside theirs.    const added = state("list-trip", 1, [a, b, c], { i1: 1, i2: 1 });    expect((await b.ask("POST", "/v1/shared/list/state", { owner: a.number, id: "list-trip", state: added })).status).toBe(403);    expect((await a.ask("POST", "/v1/shared/list/state", { id: "list-trip", state: added })).status).toBe(200);    expect((await c.ask<{ lists: unknown[] }>("GET", "/v1/shared/lists")).body.lists).toContainEqual({ owner: a.number, id: "list-trip" });    // A removal that keeps the epoch, or leaves an item sealed under the old key, is refused.    expect((await a.ask("POST", "/v1/shared/list/state", { id: "list-trip", state: state("list-trip", 1, [a, c], { i1: 1, i2: 1 }) })).status).toBe(403);    expect((await a.ask("POST", "/v1/shared/list/state", { id: "list-trip", state: state("list-trip", 2, [a, c], { i1: 2, i2: 1 }) })).status).toBe(403);    // a removes b: epoch 2, every item sealed again, wraps only for a and c.    const removed = state("list-trip", 2, [a, c], { i1: 2, i2: 2 }, added.membership.wraps);    expect((await a.ask("POST", "/v1/shared/list/state", { id: "list-trip", state: removed })).status).toBe(200);    expect((await b.ask("GET", `/v1/shared/list?owner=${encodeURIComponent(a.number)}&id=list-trip`)).status).toBe(404);    expect((await b.ask("POST", "/v1/shared/list/item", { owner: a.number, id: "list-trip", item: "i3", sealed: `g1:2:${opaque(40)}` })).status).toBe(403);    expect((await b.ask<{ lists: unknown[] }>("GET", "/v1/shared/lists")).body.lists, "b's object was told b is out").toEqual([]);    // c carries on at epoch 2.    expect((await c.ask("POST", "/v1/shared/list/item", { owner: a.number, id: "list-trip", item: "i3", sealed: `g1:2:${opaque(40)}` })).status).toBe(200);    const read = await c.ask<{ state: { membership: { epoch: number; members: Record<string, string> }; items: Record<string, string> } }>("GET", `/v1/shared/list?owner=${encodeURIComponent(a.number)}&id=list-trip`);    expect(read.body.state.membership.epoch).toBe(2);    expect(Object.keys(read.body.state.membership.members).sort()).toEqual([a.number, c.number].sort());    expect(Object.values(read.body.state.items).every((s) => s.startsWith("g1:2:"))).toBe(true);    // The founder stays on their own list: a state without them is refused.    expect((await c.ask("POST", "/v1/shared/list/state", { owner: a.number, id: "list-trip", state: state("list-trip", 3, [c], { i1: 3, i2: 3, i3: 3 }) })).status).toBe(403);  });});