Cotton code
284 lines · 19.2 KB · TypeScriptRaw
/** * Cotton opens to everyone (owner, 26 Oct 2026): on the open host a number's * first sign-in makes its own personal database, and from then on its * credential and tokens name the object. */import { sealRow } from "./seal-device.ts";import { SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import { ATTEMPTS_PER_HOUR, GLOBAL_ATTEMPTS_PER_HOUR, limitsFor, SIGN_UPS_PER_HOUR } from "../src/directory.ts";import { KITS, PERSONAL as BUNDLED } from "../src/kits.ts";import { served } from "../src/retired.ts";import SHELL_KIT from "../../../crates/cotton-core/kits/shell/kit.json";import LOOM_PICTURES from "../../../crates/cotton-core/src/definitions/loom_pictures.json";import { ADMIN, http, KIT_BOARD_FILES, KIT_MANIFESTS, PERSONAL_TABLES, PERSONAL_TOOLS } from "./personal.ts";const OPEN = "https://cottondb.com";const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;type Body = Record<string, unknown>;async function open<T = Body>(method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<{ status: number; body: T }> {  const res = await SELF.fetch(`${OPEN}${path}`, {    method,    headers: { "content-type": "application/json", ...headers },    body: body === undefined ? undefined : JSON.stringify(body),  });  const text = await res.text();  return { status: res.status, body: (text ? JSON.parse(text) : null) as T };}let ips = 0;/** A network of its own, so one test's counts never reach another's. */function network(): Record<string, string> {  ips += 1;  return { "cf-connecting-ip": `198.51.100.${ips}` };}/** A number's whole sign-in on the open host. */async function signUp(phone: string, ip = network(), device = "phone-1"): Promise<{ databaseId: string; credential: string; known: boolean; host: string; role: string }> {  const code = await open<{ challenge_id: string; database_id: string; host: string; known: boolean }>("POST", "/v1/code", { phone, device_id: device }, ip);  expect(code.status, JSON.stringify(code.body)).toBe(200);  const signed = await open<{ credential: string; person: { role: string }; database_id: string; host: string }>("POST", "/v1/sign-in", { database_id: code.body.database_id, challenge_id: code.body.challenge_id, code: "123456", device_id: device }, ip);  expect(signed.status, JSON.stringify(signed.body)).toBe(200);  expect(signed.body.database_id).toBe(code.body.database_id);  return { databaseId: code.body.database_id, credential: signed.body.credential, known: code.body.known, host: signed.body.host, role: signed.body.person.role };}const bearer = (token: string): Record<string, string> => ({ authorization: `Bearer ${token}` });describe("a stranger's first sign-in on the open host", () => {  it("makes their own personal database, the number its owner, and a credential that names it", async () => {    const me = await signUp("+919000000101");    expect(me.databaseId).toMatch(UUID);    expect(me.host).toBe(OPEN);    expect(me.known).toBe(false);    expect(me.role).toBe("owner");    expect(me.credential.startsWith(`ctd_${me.databaseId}_`)).toBe(true);    const meta = await open<{ business: Body; person: Body }>("GET", "/v1/me", undefined, bearer(me.credential));    expect(meta.status, JSON.stringify(meta.body)).toBe(200);    expect(meta.body.business).toMatchObject({ kind: "personal", database_id: me.databaseId, owner_phone: "+919000000101", slug: `p-${me.databaseId}`, name: "Personal" });    const defs = await open<{ tables: { id: string }[] }>("GET", "/v1/definitions", undefined, bearer(me.credential));    expect(defs.status).toBe(200);    expect(defs.body.tables.map((t) => t.id).sort()).toEqual([...PERSONAL_TABLES.map((t) => String(t.id)), "business_message"].sort());    const sync = await open<{ rows: unknown[] }>("GET", "/v1/sync?since=0", undefined, bearer(me.credential));    expect(sync.status, JSON.stringify(sync.body)).toBe(200);  });  it("finds the same database on every later sign-in, from any device", async () => {    const first = await signUp("+919000000102");    const again = await signUp("+919000000102", network(), "phone-2");    expect(again.databaseId).toBe(first.databaseId);    // A personal database never says a number signed in before (ROUTES-AUDIT 6).    expect(again.known).toBe(false);    expect(again.role).toBe("owner");  });  it("gives every number a database of its own, and one number's bearer never reaches another's", async () => {    const a = await signUp("+919000000103");    const b = await signUp("+919000000104");    expect(a.databaseId).not.toBe(b.databaseId);    // A note goes up sealed, as a's phone seals it (e2e rulings R1).    const made = await open<Body>("POST", "/v1/act", { act: "create", args: { table: "note", id: "note-a", data: await sealRow(new Uint8Array(32).fill(7), "note", "note-a", 1, { title: "only a's" }) } }, bearer(a.credential));    expect(made.status, JSON.stringify(made.body)).toBe(200);    const seen = await open<{ rows: { table: string; data: Body }[] }>("GET", "/v1/sync?since=0", undefined, bearer(b.credential));    expect(seen.body.rows.filter((r) => r.table === "note")).toEqual([]);    // A credential that names a's database with b's secret is refused by a's object.    const forged = `ctd_${a.databaseId}_${b.credential.slice(`ctd_${b.databaseId}_`.length)}`;    expect((await open("GET", "/v1/me", undefined, bearer(forged))).status).toBe(401);  });  it("serves Cotton MCP to a token the owner mints, at the one address", async () => {    const me = await signUp("+919000000105");    const minted = await open<{ token: string }>("POST", "/v1/act", { act: "mint_token", args: { name: "my assistant", scopes: ["read"] } }, bearer(me.credential));    expect(minted.status, JSON.stringify(minted.body)).toBe(200);    expect(minted.body.token.startsWith(`ctn_${me.databaseId}_`)).toBe(true);    const listed = await open<{ result?: { tools: unknown[] } }>("POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/list" }, bearer(minted.body.token));    expect(listed.status, JSON.stringify(listed.body)).toBe(200);    expect(listed.body.result?.tools.length).toBeGreaterThan(0);  });  it("refuses a request that names no database, and one whose database does not exist", async () => {    const none = await open<Body>("GET", "/v1/sync?since=0");    expect(none).toMatchObject({ status: 401, body: { code: "no_database" } });    const unknown = await open<Body>("GET", "/v1/sync?since=0", undefined, bearer("ctd_00000000-0000-4000-8000-000000000000_abcdef"));    expect(unknown).toMatchObject({ status: 401, body: { code: "invalid_credential" } });    const proving = await open<Body>("POST", "/v1/sign-in", { database_id: "00000000-0000-4000-8000-000000000000", challenge_id: "x", code: "123456", device_id: "d" }, network());    expect(proving).toMatchObject({ status: 404, body: { code: "no_such_database" } });    expect((await open<Body>("POST", "/v1/code", { phone: "12345", device_id: "d" }, network())).body).toMatchObject({ code: "bad_phone" });    expect((await open("POST", "/internal/mcp-call", {})).status).toBe(404);    // A `/b/<slug>` prefix still names its object here, as on workers.dev.    expect((await open<Body>("GET", "/b/no-such-business/v1/definitions")).body).toMatchObject({ code: "not_onboarded" });  });});describe("the only guards: per IP, per hour", () => {  it(`makes at most ${SIGN_UPS_PER_HOUR} databases from one network, then refuses every number from it alike`, async () => {    const ip = network();    for (let i = 0; i < SIGN_UPS_PER_HOUR; i++) await signUp(`+91900000020${i}`, ip);    const sixth = await open<Body>("POST", "/v1/code", { phone: "+919000000299", device_id: "d" }, ip);    expect(sixth).toMatchObject({ status: 429, body: { code: "too_many_sign_ups" } });    expect(String(sixth.body.message)).toMatch(/try again later/);    // A number already on Cotton is refused the same from that network (ROUTES-AUDIT 6): the limit says nothing about it.    const known = await open<Body>("POST", "/v1/code", { phone: "+919000000200", device_id: "d" }, ip);    expect(known).toEqual(sixth);    await signUp("+919000000200", network());  });  it(`answers at most ${ATTEMPTS_PER_HOUR} sign-in calls from one network`, async () => {    const ip = network();    const first = await signUp("+919000000301", ip); // two calls    for (let i = 2; i < ATTEMPTS_PER_HOUR; i++) {      const res = await open<Body>("POST", "/v1/sign-in", { database_id: first.databaseId, challenge_id: "wrong", code: "000000", device_id: "d" }, ip);      expect(res.status).toBe(401);    }    const over = await open<Body>("POST", "/v1/code", { phone: "+919000000301", device_id: "d" }, ip);    expect(over).toMatchObject({ status: 429, body: { code: "too_many_attempts" } });    // Another network is not counted with it.    await signUp("+919000000301");  });});describe("a database made before the directory", () => {  const SLUG = "dir-elder";  const ID = "22222222-2222-4222-8222-222222222222";  const PHONE = "+919000000401";  it("is entered by the admin token once its object says the same id and owner, and its number then signs in to it", async () => {    expect((await http(SLUG, "PUT", "/v1/admin/business", { name: "Personal", kind: "personal", owner_phone: PHONE, database_id: ID }, ADMIN)).status).toBe(200);    expect((await http(SLUG, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables: PERSONAL_TABLES, flavour: { flavour: "personal" } }, ADMIN)).status).toBe(200);    expect((await open<Body>("POST", "/v1/admin/directory", { database_id: ID, slug: SLUG, phone: PHONE }, bearer("not-the-admin"))).status).toBe(403);    const wrong = await open<Body>("POST", "/v1/admin/directory", { database_id: "33333333-3333-4333-8333-333333333333", slug: SLUG, phone: PHONE }, ADMIN);    expect(wrong).toMatchObject({ status: 409, body: { code: "not_that_object" } });    const entered = await open<Body>("POST", "/v1/admin/directory", { database_id: ID, slug: SLUG, phone: PHONE }, ADMIN);    expect(entered, JSON.stringify(entered.body)).toMatchObject({ status: 200, body: { database_id: ID, slug: SLUG } });    expect((await open<Body>("POST", "/v1/admin/directory", { database_id: ID, slug: SLUG, phone: PHONE }, ADMIN)).status).toBe(200);    expect((await open<Body>("POST", "/v1/admin/directory", { database_id: ID, slug: "dir-other", phone: PHONE }, ADMIN))).toMatchObject({ status: 409, body: { code: "taken" } });    const me = await signUp(PHONE);    expect(me.databaseId).toBe(ID);    expect(me.known).toBe(false);    const meta = await open<{ business: Body }>("GET", "/v1/me", undefined, bearer(me.credential));    expect(meta.body.business).toMatchObject({ slug: SLUG, database_id: ID });    // Its own host, named by its first label, still answers it.    expect((await http(SLUG, "GET", "/v1/me", undefined, bearer(me.credential))).status).toBe(200);  });});describe("the personal database admits nobody but its owner", () => {  it("refuses a code to any other number, and an owner token cannot point the database at another", async () => {    const me = await signUp("+919000000501");    const stranger = await http(`p-${me.databaseId}`, "POST", "/v1/code", { phone: "+919000000502", device_id: "d" });    // Answered as a database that does not exist (it never says this one is there).    expect(stranger).toMatchObject({ status: 503, body: { code: "not_onboarded" } });    // An owner key as keys were before allows (ADMIN KEYS 4: a key minted with a list reaches no admin route at all).    const minted = await open<{ token: string }>("POST", "/v1/act", { act: "mint_token", args: { name: "owner script", scopes: ["owner"], allow: "all" } }, bearer(me.credential));    for (const key of ["siblings", "kind", "database_id"]) {      const value = key === "siblings" ? [{ id: "x", name: "Someone else", slug: "asha" }] : key === "kind" ? "business" : "44444444-4444-4444-8444-444444444444";      const res = await open<Body>("PUT", "/v1/admin/business", { [key]: value }, bearer(minted.body.token));      expect(res, key).toMatchObject({ status: 403, body: { code: "admin_only" } });    }    expect((await open<Body>("PUT", "/v1/admin/business", { timezone: "Asia/Kolkata" }, bearer(minted.body.token))).status).toBe(200);  });});describe("the bundled personal kit", () => {  it("is the kit the repository ships (pnpm -s kit)", () => {    expect(BUNDLED.own).toEqual(PERSONAL_TOOLS);    const ids = (tables: Record<string, unknown>[]) => tables.map((t) => String(t.id)).sort();    // As an object is made from it: without the tables and tools held as retired (TABLE DROP 1), which the tree still holds.    expect(ids(served(BUNDLED).tables)).toEqual(ids(PERSONAL_TABLES));    expect(served(BUNDLED).tools).toEqual(KIT_MANIFESTS);    expect(BUNDLED.boards).toEqual(KIT_BOARD_FILES);  });  it("bundles every table and board the shell kit names (pnpm -s kit)", () => {    const shell = KITS.shell!;    expect(shell.tables.map((t) => String(t.id)).sort()).toEqual(SHELL_KIT.tables.map((name) => String(name.split("/").pop())).sort());    expect(shell.boards.map((b) => String(b.id)).sort()).toEqual([...SHELL_KIT.boards].sort());  });});/** RULE (owner, 26 Oct 2026): a new number's phone fans out the kit's tools, so its object is made holding them. */describe("a new number's personal database", () => {  it("is made holding the kit's tools beside the package's, each as its manifest ships it", async () => {    const me = await signUp("+919000000177");    const defs = await open<{ tools: Body[]; tables: Body[] }>("GET", "/v1/definitions", undefined, bearer(me.credential));    expect(defs.status, JSON.stringify(defs.body)).toBe(200);    const kitIds = KIT_MANIFESTS.map((t) => String(t.id));    expect(kitIds).toEqual([      "birthdays", "books", "calendar", "documents", "downloads", "keys", "cinemas", "messages",      "notebook", "passwords", "people", "photos", "todos", "health", "story", "meetings",    ]);    expect(defs.body.tools.map((t) => String(t.id))).toEqual([...kitIds, "personal"].sort());    for (const manifest of KIT_MANIFESTS) expect(defs.body.tools.find((t) => t.id === manifest.id)).toEqual(manifest);    expect(defs.body.tables.length).toBe(PERSONAL_TABLES.length + 1);  });  /** RULE (owner, 26 Oct 2026): every object gets the whole kit — a new one is made holding the shell's boards too, at the kit's version. */  it("is made holding the shell's boards, at the kit's version", async () => {    const me = await signUp("+919000000180");    const defs = await open<{ boards: Body[] }>("GET", "/v1/definitions", undefined, bearer(me.credential));    expect(defs.status, JSON.stringify(defs.body)).toBe(200);    expect(defs.body.boards.map((b) => String(b.id)).sort()).toEqual(KIT_BOARD_FILES.map((b) => String(b.id)).sort());    const exported = await http<{ kit_version: string | null }>(`p-${me.databaseId}`, "GET", "/v1/admin/export?limit=1", undefined, ADMIN);    expect(exported.status, JSON.stringify(exported.body).slice(0, 300)).toBe(200);    expect(exported.body.kit_version).toMatch(/^[0-9a-f]{16}$/);  });  /** RULE (owner, 26 Oct 2026): Books and Cinemas come whole — every table they draw is a package table, the owner's alone. (Music left with TABLE DROP 1.) */  it("serves every table Books and Films name, each the owner's", async () => {    const me = await signUp("+919000000178");    const defs = await open<{ tables: Body[] }>("GET", "/v1/definitions", undefined, bearer(me.credential));    expect(defs.status, JSON.stringify(defs.body)).toBe(200);    const served = new Map(defs.body.tables.map((t) => [String(t.id), t]));    const named = KIT_MANIFESTS.filter((m) => ["books", "cinemas"].includes(String(m.id))).flatMap((m) => m.tables as string[]);    expect(named).toEqual(expect.arrayContaining(["book", "highlight", "film", "film_season", "film_episode"]));    for (const id of named) expect(served.get(id)?.visibility, id).toBe("owner");  });  /** RULE (owner, 26 Oct 2026): one definition per table, the rich one — the phone draws exactly what the object serves. */  it("serves each table as the package defines it: a face for every one the phone draws, none for a storage-only one", async () => {    const me = await signUp("+919000000179");    const defs = await open<{ tables: Body[] }>("GET", "/v1/definitions", undefined, bearer(me.credential));    expect(defs.status, JSON.stringify(defs.body)).toBe(200);    const served = new Map(defs.body.tables.map((t) => [String(t.id), t]));    for (const table of PERSONAL_TABLES) expect(served.get(String(table.id)), String(table.id)).toEqual(table);    const faced = PERSONAL_TABLES.filter((t) => t.slip && t.tile && t.page).map((t) => String(t.id));    expect(faced).toEqual(expect.arrayContaining(["event", "person", "film", "session", "todo", "note", "highlight", "book"]));    // Every faced table is served (the loop above); how many there are is the kit's to say, never counted here.    for (const id of ["todo", "event", "person", "note", "session"]) expect(served.get(id)?.engine, id).toBeTruthy();    for (const id of ["email_participant", "message_reaction", "oauth_code"]) expect(served.get(id)?.slip, id).toBeUndefined();  });  /** RULE (owner, 26 Oct 2026): the kit ships everything built for Personal — every table a kit tool names comes with the object, including Photos' media union. */  it("holds every table a kit tool names, and no kit picture is a photo of the owner's", async () => {    const me = await signUp("+919000000181");    const defs = await open<{ tables: Body[] }>("GET", "/v1/definitions", undefined, bearer(me.credential));    const served = new Set(defs.body.tables.map((t) => String(t.id)));    const lacking = KIT_MANIFESTS.flatMap((m) => (m.tables as string[]).filter((id) => !served.has(id)).map((id) => `${String(m.id)}:${id}`));    expect(lacking).toEqual([]);    const carried = new Set(Object.keys(import.meta.glob("../../../crates/cotton-core/kits/personal/tools/*/pictures/*.png")).map((path) => path.split("/tools/")[1]));    for (const manifest of KIT_MANIFESTS) {      const picture = manifest.picture as { photo?: string } | string | undefined;      // RULE (ToolPicture::Asset): a picture named by id is one of Loom's shipped pictures, never a photo.      if (typeof picture === "string") expect(LOOM_PICTURES, `${String(manifest.id)}'s picture is Loom's`).toContain(picture);      else if (picture) expect(carried.has(`${String(manifest.id)}/pictures/${picture.photo?.replace(/^photo:/, "")}.png`), `${String(manifest.id)}'s picture is the kit's own`).toBe(true);      expect(manifest.author, String(manifest.id)).toEqual({ device: "cotton", name: "Cotton" });      expect(manifest.signature, String(manifest.id)).toBeNull();    }  });});describe("the hour's limits", () => {  it("are the constants unless the Worker's vars name whole numbers", () => {    expect(limitsFor({})).toEqual({ attempts: ATTEMPTS_PER_HOUR, signUps: SIGN_UPS_PER_HOUR, everywhere: GLOBAL_ATTEMPTS_PER_HOUR });    expect(limitsFor({ SIGN_IN_ATTEMPTS_PER_HOUR: "500", SIGN_UPS_PER_HOUR: "100" })).toEqual({ attempts: 500, signUps: 100, everywhere: GLOBAL_ATTEMPTS_PER_HOUR });    expect(limitsFor({ SIGN_IN_ATTEMPTS_PER_HOUR: "lots", SIGN_UPS_PER_HOUR: "-1", SIGN_IN_ATTEMPTS_GLOBAL_PER_HOUR: "x" })).toEqual({ attempts: ATTEMPTS_PER_HOUR, signUps: SIGN_UPS_PER_HOUR, everywhere: GLOBAL_ATTEMPTS_PER_HOUR });  });});