Cotton code
280 lines · 17.4 KB · TypeScriptRaw
/** * Finding people on Cotton and waiting for those not on it yet (Cotton Chat, * 20 Nov 2026): the directory keeps no number in the clear, nobody is found by * their number (DISCOVERY OFF 1, 27 Nov 2026: no bulk contact discovery), and a * message to someone not on Cotton, or not yet accepting, waits until they can be written to. * Every number here is synthetic. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it, vi } from "vitest";import { NEW_NUMBERS_PER_DAY, NEW_NUMBERS_PER_HOUR } from "../src/chat/chat.ts";import { WAITS_MAX, type Directory } from "../src/directory.ts";import { keyCheck, keyOfDigest, numberDigest, numberKeyOf } from "../src/number_key.ts";import { bearer, open, OPEN, signUp } from "./calling.ts";import { chatPhone, settle, type ChatPhone } from "./chat.ts";type Body = Record<string, unknown>;let numbers = 0;/** A synthetic number of this file's own. */function number(): string {  numbers += 1;  return `+9190077${String(numbers).padStart(5, "0")}`;}const dir = () => env.DIRECTORY.get(env.DIRECTORY.idFromName("directory"));const slugOf = (phone: ChatPhone) => `p-${phone.credential.split("_")[1]}`;const objectOf = (phone: ChatPhone) => env.BUSINESS.get(env.BUSINESS.idFromName(slugOf(phone)));async function reach(phone: ChatPhone): Promise<{ reached: string[]; waiting: string[] }> {  const res = await open<{ reached: string[]; waiting: string[] }>("GET", "/v1/chat/reach", undefined, bearer(phone.credential));  expect(res.status, JSON.stringify(res.body)).toBe(200);  return res.body;}async function people(phone: ChatPhone): Promise<{ asking: { number: string }[] }> {  return (await open<{ asking: { number: string }[] }>("GET", "/v1/chat/people", undefined, bearer(phone.credential))).body;}describe("the number digest", () => {  it("is SHA-256 of the label and the E.164 number, as the phone's core makes it (the shared vectors)", async () => {    expect(await numberDigest("+919000000001")).toBe("76f4fe591c5348306e8f8d29662040092e41fe0a8f1efc8dd3ef91e97cee2100");    expect(await numberDigest("+14155550123")).toBe("61a5585842c84d5106be5664be0b07b21f6092f2c912757a2245fc8518eae8c7");  });});describe("the directory keeps no number in the clear", () => {  it("keeps a new number only as its key, and finds it again by that key", async () => {    const phone = number();    await signUp(phone, "d1");    const rows = await runInDurableObject(dir(), (_i, state) => state.storage.sql.exec<{ phone: string | null; phone_key: string | null }>("SELECT phone, phone_key FROM database").toArray());    expect(rows.every((r) => r.phone === null)).toBe(true);    const key = await keyOfDigest((await numberKeyOf(env))!, await numberDigest(phone));    expect(rows.some((r) => r.phone_key === key)).toBe(true);    // No number anywhere in the directory's storage.    const everything = await runInDurableObject(dir(), (_i, state) =>      state.storage.sql        .exec<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_cf_%'")        .toArray()        .map((t) => JSON.stringify(state.storage.sql.exec(`SELECT * FROM "${t.name}"`).toArray()))        .join("\n"),    );    expect(everything).not.toContain(phone);    expect(everything).not.toContain(phone.slice(1));  });  it("moves a row kept the old way to its key, and its number signs in to the same database (nobody lost)", async () => {    const phone = number();    const first = await open<{ database_id: string }>("POST", "/v1/code", { phone, device_id: "d" }, { "cf-connecting-ip": "203.0.113.77" });    expect(first.status).toBe(200);    // Put the row back as the directory kept it before 20 Nov 2026: its number in the clear, no key.    await runInDurableObject(dir(), (_i, state) => state.storage.sql.exec("UPDATE database SET phone = ?, phone_key = NULL WHERE id = ?", phone, first.body.database_id));    await runInDurableObject(dir(), async (instance: Directory) => instance.migrate());    const row = await runInDurableObject(dir(), (_i, state) => state.storage.sql.exec<{ phone: string | null; phone_key: string | null }>("SELECT phone, phone_key FROM database WHERE id = ?", first.body.database_id).one());    expect(row.phone).toBeNull();    expect(row.phone_key).toMatch(/^[0-9a-f]{64}$/);    const again = await open<{ database_id: string; known: boolean }>("POST", "/v1/code", { phone, device_id: "d" }, { "cf-connecting-ip": "203.0.113.78" });    expect(again.body.database_id).toBe(first.body.database_id);    // Running it again changes nothing.    await runInDurableObject(dir(), async (instance: Directory) => instance.migrate());    expect(await dir().lookup(phone)).toBe(`p-${first.body.database_id}`);  });  it("refuses every number, loudly, when its key is not the one the numbers were kept with", async () => {    const real = await keyCheck((await numberKeyOf(env))!);    await runInDurableObject(dir(), (_i, state) => state.storage.sql.exec("UPDATE directory_meta SET value = 'another key' WHERE name = 'key_check'"));    try {      await runInDurableObject(dir(), async (instance: Directory) => instance.migrate());      await expect(runInDurableObject(dir(), async (instance: Directory) => instance.lookup(number()))).rejects.toThrow(/VAULT_KEY changed/);    } finally {      await runInDurableObject(dir(), (_i, state) => state.storage.sql.exec("UPDATE directory_meta SET value = ? WHERE name = 'key_check'", real));      await runInDurableObject(dir(), async (instance: Directory) => instance.migrate());    }    expect(await dir().lookup(number())).toBeNull();  });});describe("no bulk discovery (DISCOVERY OFF 1, 27 Nov 2026)", () => {  it("answers an old build's discover with nothing found and nothing left, whatever it sends, never an error", async () => {    const a = await chatPhone(number(), "a1");    const b = await chatPhone(number(), "b1");    // b's old build still says yes to being found: it changes nothing.    const said = await open<Body>("POST", "/v1/chat/findable", { on: true }, bearer(b.credential));    expect(said.status, JSON.stringify(said.body)).toBe(200);    expect(said.body).toEqual({ findable: false });    const digests = await Promise.all([a.number, b.number, number()].map(numberDigest));    for (const body of [{ digests }, { digests: ["not a digest"] }, {}]) {      const res = await open<Body>("POST", "/v1/chat/discover", body, bearer(a.credential));      expect(res.status, JSON.stringify(res.body)).toBe(200);      expect(res.body).toEqual({ found: [], left: 0 });    }    expect((await open<Body>("GET", "/v1/chat/findable", undefined, bearer(b.credential))).body).toEqual({ me: b.number, findable: false, left: 0 });  });  it("keeps no findable mark in the directory, and asks nothing of it", async () => {    await chatPhone(number(), "a1");    const columns = await runInDurableObject(dir(), (_i: Directory, state) => state.storage.sql.exec<{ name: string }>("PRAGMA table_info(database)").toArray().map((c) => c.name));    expect(columns).not.toContain("findable");  });  it("erases the mark from a directory that held it, and every row stays", async () => {    const phone = number();    await signUp(phone, "d1");    await runInDurableObject(dir(), (_i: Directory, state) => {      state.storage.sql.exec("ALTER TABLE database ADD COLUMN findable INTEGER");      state.storage.sql.exec("UPDATE database SET findable = 1");      state.storage.sql.exec("CREATE TABLE IF NOT EXISTS discover_spend (slug TEXT NOT NULL, n INTEGER NOT NULL, at INTEGER NOT NULL)");      state.storage.sql.exec("INSERT INTO discover_spend (slug, n, at) VALUES ('p-old', 3, 1)");    });    const before = await runInDurableObject(dir(), (_i: Directory, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM database").one().n);    await runInDurableObject(dir(), async (instance: Directory) => instance.migrate());    const after = await runInDurableObject(dir(), (_i: Directory, state) => ({      columns: state.storage.sql.exec<{ name: string }>("PRAGMA table_info(database)").toArray().map((c) => c.name),      n: state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM database").one().n,    }));    expect(after.columns).not.toContain("findable");    expect(after.n).toBe(before);    const tables = await runInDurableObject(dir(), (_i: Directory, state) => state.storage.sql.exec<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'table'").toArray().map((t) => t.name));    expect(tables).not.toContain("discover_spend");    expect(await dir().lookup(phone)).not.toBeNull();  });  it("refuses a phone that is not signed in", async () => {    expect((await open("POST", "/v1/chat/discover", { digests: [] })).status).toBe(401);  });});describe("the one lookup left: one number the person picks (POST /v1/chat/wait)", () => {  it(`counts new numbers by number, ${NEW_NUMBERS_PER_HOUR} an hour, refused the same whether or not they are on Cotton`, async () => {    const a = await chatPhone(number(), "a1");    const onCotton = await chatPhone(number(), "c1");    const picked = [onCotton.number, ...Array.from({ length: NEW_NUMBERS_PER_HOUR - 1 }, number)];    for (const n of picked) expect((await open<Body>("POST", "/v1/chat/wait", { number: n }, bearer(a.credential))).status).toBe(200);    // The same numbers again cost nothing.    for (const n of picked) expect((await open<Body>("POST", "/v1/chat/wait", { number: n }, bearer(a.credential))).body).toEqual({ state: "waiting" });    const another = await chatPhone(number(), "c2");    const toCotton = await open<Body>("POST", "/v1/chat/wait", { number: another.number }, bearer(a.credential));    const toNobody = await open<Body>("POST", "/v1/chat/wait", { number: number() }, bearer(a.credential));    expect(toCotton.status).toBe(429);    expect(toCotton.body).toEqual(toNobody.body);    expect(toCotton.body).toMatchObject({ code: "too_many_numbers" });    // An add from Your people is the same pick.    expect((await open("POST", "/v1/chat/accept", { number: number() }, bearer(a.credential))).status).toBe(429);  });  it(`counts at most ${NEW_NUMBERS_PER_DAY} new numbers in a day`, async () => {    const a = await chatPhone(number(), "a1");    await runInDurableObject(objectOf(a), (_i, state) => {      for (let i = 0; i < NEW_NUMBERS_PER_DAY - 1; i++) state.storage.sql.exec("INSERT INTO chat_pick (key, at) VALUES (?, ?)", `earlier-${i}`, Date.now() - 2 * 3_600_000);    });    expect((await open("POST", "/v1/chat/wait", { number: number() }, bearer(a.credential))).status).toBe(200);    expect((await open("POST", "/v1/chat/wait", { number: number() }, bearer(a.credential))).status).toBe(429);  });  it(`answers the cap of ${WAITS_MAX} waits the same for a number on Cotton and one nobody holds`, async () => {    const a = await chatPhone(number(), "a1");    const b = await chatPhone(number(), "b1");    const slug = slugOf(a);    await runInDurableObject(dir(), (_i: Directory, state) => {      for (let i = 0; i < WAITS_MAX; i++) state.storage.sql.exec("INSERT INTO waiting (key, slug, ticket, at) VALUES (?, ?, ?, ?)", `k-${i}`, slug, `t-${i}`, Date.now());    });    const toB = await runInDurableObject(dir(), async (instance: Directory) => instance.wait(slug, await numberDigest(b.number)));    const toNobody = await runInDurableObject(dir(), async (instance: Directory) => instance.wait(slug, await numberDigest(number())));    expect(toB).toEqual(toNobody);    expect(toB).toMatchObject({ refused: { status: 429, code: "too_many_waits" } });  });  it("keeps a wait for a number on Cotton as for one nobody holds", async () => {    const a = await chatPhone(number(), "a1");    const b = await chatPhone(number(), "b1");    await open("POST", "/v1/chat/wait", { number: b.number }, bearer(a.credential));    await open("POST", "/v1/chat/wait", { number: number() }, bearer(a.credential));    const rows = await runInDurableObject(dir(), (_i: Directory, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM waiting WHERE slug = ?", slugOf(a)).one().n);    expect(rows).toBe(2);  });});describe("a request the person deleted", () => {  it("never alerts them again from the same asker, until they accept", async () => {    const a = await chatPhone(number(), "a1");    const b = await chatPhone(number(), "b1");    await open("POST", "/v1/chat/wait", { number: b.number }, bearer(a.credential));    await vi.waitFor(async () => expect((await people(b)).asking.map((p) => p.number)).toEqual([a.number]), { timeout: 20000, interval: 50 });    expect((await open("POST", "/v1/chat/refuse", { number: a.number }, bearer(b.credential))).status).toBe(200);    expect((await people(b)).asking).toEqual([]);    // a takes the wait back and asks again: b hears nothing.    await open("DELETE", "/v1/chat/wait", { number: b.number }, bearer(a.credential));    await open("POST", "/v1/chat/wait", { number: b.number }, bearer(a.credential));    await open("POST", "/v1/chat/accept", { number: b.number }, bearer(a.credential));    await settle();    expect((await people(b)).asking).toEqual([]);  });});describe("a message to someone not on Cotton yet", () => {  it("waits, and when they join they are asked, and reached once they accept: nobody is found by their number", async () => {    const a = await chatPhone(number(), "a1");    const later = number();    expect((await open<Body>("POST", "/v1/chat/wait", { number: later }, bearer(a.credential))).body).toEqual({ state: "waiting" });    expect(await reach(a)).toEqual({ reached: [], waiting: [later] });    // They sign up (an old build saying they may be found changes nothing), then their chat device comes.    const b = await chatPhone(later, "l1");    expect((await open("POST", "/v1/chat/findable", { on: true }, bearer(b.credential))).status).toBe(200);    await vi.waitFor(async () => expect((await people(b)).asking.map((p) => p.number)).toEqual([a.number]), { timeout: 20000, interval: 50 });    expect(await reach(a)).toEqual({ reached: [], waiting: [later] });    await b.say("accept", a.number);    await vi.waitFor(async () => expect(await reach(a)).toEqual({ reached: [later], waiting: [] }), { timeout: 20000, interval: 50 });  });  it("answers the same for someone already on Cotton as for a number nobody holds", async () => {    const a = await chatPhone(number(), "a1");    const b = await chatPhone(number(), "b1");    const nobody = number();    const toB = await open<Body>("POST", "/v1/chat/wait", { number: b.number }, bearer(a.credential));    const toNobody = await open<Body>("POST", "/v1/chat/wait", { number: nobody }, bearer(a.credential));    expect(toB.body).toEqual(toNobody.body);    expect(toB.body).toEqual({ state: "waiting" });    // b is asked, as an add from Your people asks.    await vi.waitFor(async () => expect((await people(b)).asking.map((p) => p.number)).toEqual([a.number]), { timeout: 20000, interval: 50 });  });  it("a wait taken back goes: the number joining later reaches nobody", async () => {    const a = await chatPhone(number(), "a1");    const later = number();    await open("POST", "/v1/chat/wait", { number: later }, bearer(a.credential));    expect((await open("DELETE", "/v1/chat/wait", { number: later }, bearer(a.credential))).status).toBe(200);    expect(await reach(a)).toEqual({ reached: [], waiting: [] });    const credential = await signUp(later, "l1");    await open("POST", "/v1/chat/device", { publicKey: a.publicKey.replace(/^./, "C") }, bearer(credential));    await settle();    expect(await reach(a)).toEqual({ reached: [], waiting: [] });  });  it("is reached when the person waited for writes first", async () => {    const a = await chatPhone(number(), "a1");    const b = await chatPhone(number(), "b1");    await open("POST", "/v1/chat/wait", { number: b.number }, bearer(a.credential));    const keys = await b.keysFor(a.number);    expect(keys.devices).toHaveLength(1);    expect((await b.write(a.number, "hello, got your invite")).status).toBe(200);    await vi.waitFor(async () => expect((await reach(a)).reached).toEqual([b.number]), { timeout: 20000, interval: 50 });  });});describe("a person's picture as the people they write to see it", () => {  it("is put up sealed, fetched by its id, and replaced (the old one goes)", async () => {    const a = await chatPhone(number(), "a1");    const sealed = new Uint8Array([0x63, 0x66, 0x31, ...crypto.getRandomValues(new Uint8Array(40))]);    const put = async (bytes: Uint8Array) => (await SELF.fetch(`${OPEN}/v1/chat/profile-picture`, { method: "PUT", headers: bearer(a.credential), body: bytes })).json<{ file: string }>();    const first = await put(sealed);    expect(first.file).toMatch(/^[0-9a-f]{32}$/);    const got = await SELF.fetch(`${OPEN}/v1/chat/profile-pictures/${first.file}`, { headers: bearer(a.credential) });    expect(new Uint8Array(await got.arrayBuffer())).toEqual(sealed);    const second = await put(sealed);    expect((await SELF.fetch(`${OPEN}/v1/chat/profile-pictures/${first.file}`, { headers: bearer(a.credential) })).status).toBe(404);    expect((await SELF.fetch(`${OPEN}/v1/chat/profile-pictures/${second.file}`, { headers: bearer(a.credential) })).status).toBe(200);    expect((await SELF.fetch(`${OPEN}/v1/chat/profile-picture`, { method: "PUT", headers: bearer(a.credential), body: "plain words" })).status).toBe(400);    expect((await open<Body>("GET", "/v1/chat/findable", undefined, bearer(a.credential))).body).toMatchObject({ me: a.number });  });});