Cotton code
638 lines · 35.5 KB · TypeScriptRaw
/** * Cotton to Cotton messages (12 Nov 2026): an envelope sealed on one phone, * handed from the sender's object to the recipient's, held for each device * until it is taken, pushed over the socket or as a bare alert, and what the * sender can and cannot learn. Every number is synthetic. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { bearer, fakes, open, OPEN, type Fakes } from "./calling.ts";import { arrived, chatPhone, ChatSocket, settle, type ChatPhone } from "./chat.ts";import { devServer, FROM_STRANGER_HOUR, LOOKUPS_PER_HOUR, MESSAGES_PER_HOUR, ROWS_WINDOW_MS, STALE_DEVICES } from "../src/chat/chat.ts";import { holdsWord } from "./clear-word.ts";vi.setConfig({ testTimeout: 30_000 });let world: Fakes;let n = 0;const number = (): string => `+91900001${String(1000 + ++n).padStart(4, "0")}`;beforeEach(() => {  world = fakes();});afterEach(() => {  vi.restoreAllMocks();});const TOKEN_B = "c1".repeat(32);const TOKEN_B2 = "c2".repeat(32);/** Two people who have written to each other before: neither is a request to the other. */async function friends(): Promise<{ a: ChatPhone; b: ChatPhone }> {  const a = await chatPhone(number(), "a-phone");  const b = await chatPhone(number(), "b-phone", { platform: "ios", token: TOKEN_B });  await b.say("accept", a.number);  await a.say("accept", b.number);  return { a, b };}/** Every row of every table of a person's object, as text. */async function everything(phone: ChatPhone): Promise<string> {  const slug = await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).lookup(phone.number);  expect(slug).toBeTruthy();  const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug!));  return runInDurableObject(stub, async (_instance, state) => {    const tables = 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();    return tables.map((t) => JSON.stringify(state.storage.sql.exec(`SELECT * FROM "${t.name}"`).toArray())).join("\n");  });}describe("both phones open", () => {  it("hands the envelope to the recipient's socket at once, sealed for its key alone, and pushes nothing", async () => {    const { a, b } = await friends();    const socket = await b.socket();    const sent = await a.write(b.number, "the kettle is on");    expect(sent.status, JSON.stringify(sent.body)).toBe(200);    expect(sent.body).toMatchObject({ ok: true });    const [item] = await socket.next();    expect(item).toMatchObject({ kind: "message", peer: a.number, out: false, request: false });    expect(item!.box.startsWith("c1:")).toBe(true);    expect(await b.open(item!.box)).toMatchObject({ body: "the kettle is on", from: a.number, to: b.number });    // Another phone's key opens nothing.    expect(await a.open(item!.box)).toBeNull();    expect(world.pushes).toHaveLength(0);    // Taken over the socket, it is held no more.    socket.send({ t: "ack", items: [{ id: item!.id, kind: "message" }] });    await vi.waitFor(async () => expect(await b.inbox()).toHaveLength(0));  });  it("carries typing to an open socket and keeps none of it", async () => {    const { a, b } = await friends();    const socket = await b.socket();    await a.write(b.number, "on", crypto.randomUUID(), "typing");    const [item] = await socket.next();    expect(item!.kind).toBe("typing");    expect(await b.inbox()).toHaveLength(0);  });});describe("the recipient offline, then online", () => {  it("holds the envelope, alerts the phone with a title alone, and hands it over when the phone comes back", async () => {    const { a, b } = await friends();    await a.write(b.number, "are you up");    await vi.waitFor(() => expect(world.pushes).toHaveLength(1));    const push = world.pushes[0]!;    expect(push.token).toBe(TOKEN_B);    expect(push.verified).toBe(true);    expect(push.headers["apns-push-type"]).toBe("alert");    expect(push.headers["apns-topic"]).toBe("com.cottondb.messages.dev");    // The box rides along for the extension to open on the phone; nothing else of the message, and not who sent it.    const pushed = push.body as { aps: unknown; chat: number; box: string };    expect({ ...pushed, box: undefined }).toEqual({ aps: { alert: { title: "New message" }, sound: "default", "mutable-content": 1 }, chat: 1, box: undefined });    expect((await b.open(pushed.box))?.body).toBe("are you up");    expect(JSON.stringify(push)).not.toContain(a.number);    // Back online: the socket hands over what waited, oldest first.    await a.write(b.number, "hello?");    const socket = await b.socket();    const items = await socket.next(2);    expect(await Promise.all(items.map(async (i) => (await b.open(i.box))?.body))).toEqual(["are you up", "hello?"]);    expect(items[0]!.at).toBeLessThanOrEqual(items[1]!.at);    // Taken by HTTP, gone.    await b.ack(items);    expect(await b.inbox()).toHaveLength(0);  });  it("pushes an Android phone a data message naming no one", async () => {    const a = await chatPhone(number(), "a-phone");    const b = await chatPhone(number(), "b-android", { platform: "android", token: "fcm-token-".padEnd(48, "x") });    await b.say("accept", a.number);    await a.write(b.number, "hi");    await vi.waitFor(() => expect(world.pushes).toHaveLength(1));    expect(world.pushes[0]!.message).toEqual({ token: "fcm-token-".padEnd(48, "x"), data: { kind: "chat", title: "New message" }, android: { priority: "HIGH", ttl: "86400s" } });  });});describe("devices", () => {  it("seals once for each of the recipient's devices, and each takes its own", async () => {    const { a, b } = await friends();    const tablet = await chatPhone(b.number, "b-tablet", { platform: "ios", token: TOKEN_B2 });    const keys = await a.keysFor(b.number);    expect(keys.devices).toHaveLength(2);    // Handles, never the devices' ids.    expect(JSON.stringify(keys)).not.toContain("b-phone");    await a.write(b.number, "both of you");    const [onPhone] = await arrived(b);    const [onTablet] = await arrived(tablet);    expect((await b.open(onPhone!.box))?.body).toBe("both of you");    expect((await tablet.open(onTablet!.box))?.body).toBe("both of you");    expect(await b.open(onTablet!.box)).toBeNull();    await vi.waitFor(() => expect(world.pushes.map((p) => p.token).sort()).toEqual([TOKEN_B, TOKEN_B2].sort()));    await b.ack([onPhone!]);    expect(await b.inbox()).toHaveLength(0);    expect(await tablet.inbox()).toHaveLength(1);  });  it("refuses a message sealed for yesterday's devices, so a phone signed in since is never left without it", async () => {    const { a, b } = await friends();    const kept = await a.keysFor(b.number);    const tablet = await chatPhone(b.number, "b-tablet");    const sealFor = async (keys: typeof kept, id: string) => {      const boxes: Record<string, string> = {};      for (const k of [...keys.devices, ...keys.own]) boxes[k.device] = await a.seal(k.key, { v: 1, id, kind: "message", from: a.number, to: b.number, body: "hello, new phone" });      return open<Record<string, unknown>>("POST", "/v1/chat/send", { to: b.number, id, kind: "message", boxes, check: true }, bearer(a.credential));    };    const id = crypto.randomUUID();    const stale = await sealFor(kept, id);    expect(stale.status).toBe(409);    expect(stale.body).toMatchObject({ code: STALE_DEVICES });    // Nothing went: asked again and sealed again under the same id, both phones get it once.    const sent = await sealFor(await a.keysFor(b.number), id);    expect(sent.status, JSON.stringify(sent.body)).toBe(200);    expect((await tablet.open((await arrived(tablet))[0]!.box))?.body).toBe("hello, new phone");    expect(await arrived(b)).toHaveLength(1);    // The sender's own new phone counts too.    const kept2 = await a.keysFor(b.number);    await chatPhone(a.number, "a-second");    expect((await sealFor(kept2, crypto.randomUUID())).status).toBe(409);    // An older phone, which does not say it seals again, is not refused (it would count a failed try).    const boxes: Record<string, string> = {};    for (const k of [...kept2.devices, ...kept2.own]) boxes[k.device] = await a.seal(k.key, { v: 1, id: "older-phone-1", kind: "message", from: a.number, to: b.number, body: "old app" });    expect((await open("POST", "/v1/chat/send", { to: b.number, id: "older-phone-1", kind: "message", boxes }, bearer(a.credential))).status).toBe(200);  });  it("answers the person's own devices as often as asked, uncounted, so a read is told to a phone signed in a minute ago", async () => {    const { a } = await friends();    const asks = await Promise.all(Array.from({ length: LOOKUPS_PER_HOUR + 5 }, () => open("GET", `/v1/chat/keys?number=${encodeURIComponent(a.number)}`, undefined, bearer(a.credential))));    expect(asks.every((r) => r.status === 200)).toBe(true);    const laptop = await chatPhone(a.number, "a-laptop");    expect((await a.keysFor(a.number)).own.map((k) => k.key)).toEqual([laptop.publicKey]);  });  it("gives the sender's second device its own copy, marked as the sender's own", async () => {    const { a, b } = await friends();    const laptop = await chatPhone(a.number, "a-second");    const keys = await a.keysFor(b.number);    expect(keys.own).toHaveLength(1);    await a.write(b.number, "sent from my phone");    const [copy] = await arrived(laptop);    expect(copy).toMatchObject({ peer: b.number, out: true, request: false });    expect((await laptop.open(copy!.box))?.body).toBe("sent from my phone");    // The sending phone holds nothing of its own.    expect(await a.inbox()).toHaveLength(0);  });  it("forgets a phone's key and what waits for it when it signs out", async () => {    const { a, b } = await friends();    await a.write(b.number, "later");    await arrived(b);    const out = await open("POST", "/v1/sign-out", undefined, bearer(b.credential));    expect(out.status).toBe(200);    // What is left is made up (one device, or two for some numbers, as for any number nobody holds): b's key is gone.    const left = (await a.keysFor(b.number)).devices;    expect(left.length).toBeGreaterThanOrEqual(1);    expect(left.map((d) => d.key)).not.toContain(b.publicKey);  });});describe("a resend", () => {  it("lands once, however many times the same id is sent", async () => {    const { a, b } = await friends();    const id = crypto.randomUUID();    const first = await a.write(b.number, "once", id);    const again = await a.write(b.number, "once", id);    expect(again.body).toEqual(first.body);    await settle();    expect(await arrived(b)).toHaveLength(1);    expect(world.pushes).toHaveLength(1);  });});// Several phones signed up in each, so longer than the file's thirty seconds on a loaded machine.describe("a re-send after a ratchet reset", { timeout: 300_000 }, () => {  /** What a phone holds, once it holds something: waited for longer than `arrived` does. */  const held = async (phone: ChatPhone) => {    let items: Awaited<ReturnType<ChatPhone["inbox"]>> = [];    await vi.waitFor(async () => {      items = await phone.inbox();      if (!items.length) throw new Error("nothing held");    }, { timeout: 60_000, interval: 200 });    return items;  };  /** The same message sealed again for these devices, marked as a re-send. */  const resend = async (from: ChatPhone, to: string, id: string, devices: { device: string; key: string }[], text = "lost once") => {    const boxes: Record<string, string> = {};    for (const k of devices) boxes[k.device] = await from.seal(k.key, { v: 1, id, kind: "message", from: from.number, to, body: text });    return open<Record<string, unknown>>("POST", "/v1/chat/send", { to, id, kind: "message", boxes, resend: true }, bearer(from.credential));  };  it("reaches the one device that lost it, once, at the first send's time, and nobody else", async () => {    const { a, b } = await friends();    const tablet = await chatPhone(b.number, "b-tablet");    const laptop = await chatPhone(a.number, "a-second");    const id = crypto.randomUUID();    const first = await a.write(b.number, "lost once", id);    const [onPhone] = await held(b);    await held(tablet);    await held(laptop);    await b.ack([onPhone!]);    // b's phone could not open it: a's phone seals it again for that phone alone.    const phone = (await a.keysFor(b.number)).devices.find((k) => k.key === b.publicKey)!;    const again = await resend(a, b.number, id, [phone]);    expect(again.status, JSON.stringify(again.body)).toBe(200);    expect(again.body.at).toBe(first.body.at);    const [got] = await held(b);    expect(got).toMatchObject({ id, kind: "message", peer: a.number, out: false, request: false, at: first.body.at });    expect((await b.open(got!.box))?.body).toBe("lost once");    await b.ack([got!]);    // Asked again, from either of a's phones: answered the same, and it goes nowhere.    expect((await resend(a, b.number, id, [phone])).status).toBe(200);    expect((await resend(laptop, b.number, id, [phone])).status).toBe(200);    await settle();    expect(await b.inbox()).toHaveLength(0);    // The tablet and the laptop hold only the first send.    expect(await tablet.inbox()).toHaveLength(1);    expect(await laptop.inbox()).toHaveLength(1);  });  it("re-sends a person's own copy to their own other phone", async () => {    const { a, b } = await friends();    const laptop = await chatPhone(a.number, "a-second");    const id = crypto.randomUUID();    await a.write(b.number, "my words", id);    const [copy] = await held(laptop);    await laptop.ack([copy!]);    const own = (await a.keysFor(b.number)).own;    expect((await resend(a, b.number, id, own, "my words")).status).toBe(200);    const [got] = await held(laptop);    expect(got).toMatchObject({ id, peer: b.number, out: true });    expect((await laptop.open(got!.box))?.body).toBe("my words");    // Once: asked again, nothing more for the laptop.    await laptop.ack([got!]);    expect((await resend(a, b.number, id, own, "my words")).status).toBe(200);    expect(await laptop.inbox()).toHaveLength(0);  });  it("is refused for several devices, for a message never sent, for another kind and for a device the message does not reach", async () => {    const { a, b } = await friends();    await chatPhone(b.number, "b-tablet");    const id = crypto.randomUUID();    await a.write(b.number, "once", id);    const keys = await a.keysFor(b.number);    const several = await resend(a, b.number, id, keys.devices);    expect(several.status).toBe(400);    expect(several.body).toMatchObject({ code: "bad_resend" });    const never = await resend(a, b.number, crypto.randomUUID(), [keys.devices[0]!]);    expect(never.status).toBe(409);    expect(never.body).toMatchObject({ code: "not_sent" });    const receipt = { [keys.devices[0]!.device]: await a.seal(keys.devices[0]!.key, { v: 1, id, kind: "receipt", from: a.number, to: b.number, state: "read" }) };    expect((await open("POST", "/v1/chat/send", { to: b.number, id, kind: "receipt", boxes: receipt, resend: true }, bearer(a.credential))).status).toBe(400);    const stranger = await chatPhone(number(), "c-phone");    const elsewhere = (await a.keysFor(stranger.number)).devices[0]!;    expect((await resend(a, b.number, id, [elsewhere])).status).toBe(409);  });});describe("what the sender cannot tell apart", () => {  it("answers a blocked sender, an unknown number and a reachable one the same", async () => {    const a = await chatPhone(number(), "a-phone");    const blocker = await chatPhone(number(), "blocker", { platform: "ios", token: TOKEN_B });    const friend = await chatPhone(number(), "friend");    await friend.say("accept", a.number);    await blocker.say("block", a.number);    const unknown = number();    const shapes = await Promise.all([blocker.number, unknown, friend.number].map(async (to) => {      const keys = await a.keysFor(to);      const sent = await a.write(to, "hello");      return { keys: keys.devices.map((d) => [d.device.length, d.key.length]), status: sent.status, body: Object.keys(sent.body).sort() };    }));    expect(shapes[0]).toEqual(shapes[1]);    expect(shapes[1]).toEqual(shapes[2]);    // An unknown number's made-up device is the same each time.    expect(await a.keysFor(unknown)).toEqual(await a.keysFor(unknown));    await settle();    expect(await blocker.inbox()).toHaveLength(0);    expect(world.pushes).toHaveLength(0);    expect(await friend.inbox()).toHaveLength(1);  });  it("is a block for calls too: one list", async () => {    const a = await chatPhone(number(), "a-phone");    const b = await chatPhone(number(), "b-phone");    await b.say("block", a.number);    const res = await open<{ blocked: boolean }>("GET", `/v1/calls/blocked?number=${encodeURIComponent(a.number)}`, undefined, bearer(b.credential));    expect(res.body.blocked).toBe(true);    await b.say("unblock", a.number);    await b.say("accept", a.number);    await a.write(b.number, "sorry");    expect(await arrived(b)).toHaveLength(1);  });});describe("a stranger's first message", () => {  /** Who asks to chat with this phone's owner. */  const asking = async (phone: ChatPhone) => (await open<{ asking: { number: string }[] }>("GET", "/v1/chat/people", undefined, bearer(phone.credential))).body.asking.map((x) => x.number);  it("arrives as their ask, never as words (src/chat/gate.ts); accepted, what follows is ordinary, and receipts flow", async () => {    const a = await chatPhone(number(), "a-phone");    const b = await chatPhone(number(), "b-phone");    // b has never written to a, nor accepted them.    await a.write(b.number, "we met at the station");    await vi.waitFor(async () => expect(await asking(b)).toEqual([a.number]), { timeout: 3000, interval: 20 });    expect(await b.inbox()).toEqual([]);    // A stranger's typing goes nowhere.    await a.write(b.number, "on", crypto.randomUUID(), "typing");    await b.say("accept", a.number);    await a.write(b.number, "thank you");    const items = await arrived(b);    expect(items.map((i) => i.request)).toEqual([false]);    // b reads, and says so: a's object holds b's receipt for a.    await b.write(a.number, "read", crypto.randomUUID(), "receipt");    const [receipt] = await arrived(a);    expect(receipt).toMatchObject({ kind: "receipt", peer: b.number });    expect((await a.open(receipt!.box))?.state).toBe("read");  });  it("carries a change (a reaction, an edit, a delete) sealed, held like a receipt, never an alert, and only once accepted", async () => {    const a = await chatPhone(number(), "a-phone");    const b = await chatPhone(number(), "b-phone");    await a.write(b.number, "the kite is red");    // A stranger's change goes nowhere.    await a.write(b.number, "edit", crypto.randomUUID(), "change");    await settle();    expect(await b.inbox()).toHaveLength(0);    await b.say("accept", a.number);    const before = world.pushes.length;    expect((await a.write(b.number, "react", crypto.randomUUID(), "change")).status).toBe(200);    const [change] = await arrived(b);    expect(change).toMatchObject({ kind: "change", peer: a.number, request: false });    expect(JSON.stringify(change)).not.toContain("react");    expect(world.pushes.length).toBe(before);  });  it("refused, the ask goes, stays gone, and the stranger sees nothing different", async () => {    const a = await chatPhone(number(), "a-phone");    const b = await chatPhone(number(), "b-phone");    const first = await a.write(b.number, "buy my course");    await vi.waitFor(async () => expect(await asking(b)).toEqual([a.number]), { timeout: 3000, interval: 20 });    await b.say("refuse", a.number);    expect(await asking(b)).toEqual([]);    const second = await a.write(b.number, "last chance");    expect(Object.keys(second.body).sort()).toEqual(Object.keys(first.body).sort());    // A deleted request never alerts again from the same asker, until b accepts them (DISCOVERY OFF 2).    await settle();    expect(await asking(b)).toEqual([]);    expect(await b.inbox()).toEqual([]);  });  it("is limited: a stranger's flood is one ask, unsaid", async () => {    const a = await chatPhone(number(), "a-phone");    const b = await chatPhone(number(), "b-phone");    for (let i = 0; i < FROM_STRANGER_HOUR + 3; i += 1) expect((await a.write(b.number, `ad ${i}`)).status).toBe(200);    await settle();    expect(await asking(b)).toEqual([a.number]);    expect(await b.inbox()).toEqual([]);  });});describe("a phone's own limit", () => {  it("refuses a send over the hour's messages, saying nothing of the recipient", async () => {    const { a, b } = await friends();    const slug = await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).lookup(a.number);    // The hour's count, laid as the object keeps it, rather than three hundred real sends.    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug!)), async (_i, state) => {      for (let i = 0; i < MESSAGES_PER_HOUR; i += 1) state.storage.sql.exec("INSERT INTO call_hit (who, at) VALUES (?, ?)", "chat-out:a-phone", Date.now());    });    const over = await a.write(b.number, "one more");    expect(over.status).toBe(429);    expect(over.body.code).toBe("too_many_messages");    // A receipt is not a message: it still goes.    expect((await a.write(b.number, "read", crypto.randomUUID(), "receipt")).status).toBe(200);  });});describe("the Worker cannot read a message", () => {  it("keeps nothing but ciphertext on either object, and holds no key that opens it", async () => {    const { a, b } = await friends();    const secret = "the spare key is under the third flowerpot";    await a.write(b.number, secret);    const [item] = await arrived(b);    expect((await b.open(item!.box))?.body).toBe(secret);    const kept = (await everything(a)) + (await everything(b));    expect(kept).not.toContain(secret);    expect(holdsWord(kept, "flowerpot"), "flowerpot").toBe(false);    expect(kept).toContain(item!.box);    // Only public halves were ever handed to the Worker: the private halves cannot be exported from it, and it was given none.    const route = await open("POST", "/v1/chat/device", { publicKey: b.publicKey, privateKey: "zq-private-half-never-kept" }, bearer(b.credential));    expect(route.status).toBe(200);    expect(await everything(b)).not.toContain("zq-private-half-never-kept");  });  it("refuses an envelope that is not sealed boxes", async () => {    const { a, b } = await friends();    const handle = (await a.keysFor(b.number)).devices[0]!.device;    const plain = await open("POST", "/v1/chat/send", { to: b.number, id: crypto.randomUUID(), kind: "message", boxes: { [handle]: "hello in the clear" } }, bearer(a.credential));    expect(plain.status).toBe(400);    expect((plain.body as { code: string }).code).toBe("bad_boxes");  });});describe("a picture", () => {  it("goes to the file store as the phone sealed it and comes back to the other person byte for byte", async () => {    const { a, b } = await friends();    const sealed = new Uint8Array([0x63, 0x66, 0x31, ...crypto.getRandomValues(new Uint8Array(200))]);    const put = await SELF.fetch(`${OPEN}/v1/chat/files`, { method: "PUT", headers: { ...bearer(a.credential), "content-type": "application/octet-stream" }, body: sealed });    expect(put.status).toBe(200);    const { file } = (await put.json()) as { file: string };    expect(file).toMatch(/^[0-9a-f]{32}$/);    const got = await SELF.fetch(`${OPEN}/v1/chat/files/${file}`, { headers: bearer(b.credential) });    expect(got.status).toBe(200);    expect(new Uint8Array(await got.arrayBuffer())).toEqual(sealed);    // Not a sealed file: refused.    const plain = await SELF.fetch(`${OPEN}/v1/chat/files`, { method: "PUT", headers: bearer(a.credential), body: new TextEncoder().encode("a plain picture, not sealed") });    expect(plain.status).toBe(400);  });  it("says the phone's own number on the keys and the inbox", async () => {    const { a, b } = await friends();    const keys = await open<{ me: string }>("GET", `/v1/chat/keys?number=${encodeURIComponent(b.number)}`, undefined, bearer(a.credential));    expect(keys.body.me).toBe(a.number);    const inbox = await open<{ me: string }>("GET", "/v1/chat/inbox", undefined, bearer(b.credential));    expect(inbox.body.me).toBe(b.number);  });});describe("the socket's ticket", () => {  // RULE: A chat socket opens with a ticket its object minted for that device, once and within a minute; the device's own credential never opens one.  it("opens with a ticket once, and never with the device's credential", async () => {    const { a, b } = await friends();    const credentialOnly = await SELF.fetch(`${OPEN}/v1/chat/socket`, { headers: { upgrade: "websocket", authorization: `Bearer ${b.credential}` } });    expect(credentialOnly.status).toBe(401);    const ticket = await b.ticket();    expect(ticket).toMatch(/^cts_[0-9a-f-]{36}_[A-Za-z0-9_-]{43}$/);    const opened = await SELF.fetch(`${OPEN}/v1/chat/socket`, { headers: { upgrade: "websocket", authorization: `Bearer ${ticket}` } });    expect(opened.status).toBe(101);    opened.webSocket!.accept();    const socket = new ChatSocket(opened.webSocket!);    // It opened b's socket: a's message comes down it, and nothing is pushed.    await a.write(b.number, "through the ticket");    const [item] = await socket.next();    expect((await b.open(item!.box))?.body).toBe("through the ticket");    expect(world.pushes).toHaveLength(0);    const again = await SELF.fetch(`${OPEN}/v1/chat/socket`, { headers: { upgrade: "websocket", authorization: `Bearer ${ticket}` } });    expect(again.status, "a ticket is spent by its socket").toBe(401);  });  it("is minted only for a phone that published its key, and only on asking with its credential", async () => {    const a = await chatPhone(number(), "a-phone");    const asked = await open("POST", "/v1/chat/socket", {});    expect(asked.status).toBe(401);    expect((await a.ticket()).startsWith("cts_")).toBe(true);  });  it("a stranger's ask is pushed with no box: the extension keeps 'New message'", async () => {    const a = await chatPhone(number(), "a-phone");    const b = await chatPhone(number(), "b-phone", { platform: "ios", token: TOKEN_B });    await a.write(b.number, "we met at the station");    await vi.waitFor(() => expect(world.pushes).toHaveLength(1));    expect(world.pushes[0]!.body).toEqual({ aps: { alert: { title: "New message" }, sound: "default", "mutable-content": 1 }, chat: 1 });  });});describe("read on another of the person's phones", () => {  it("nudges the person's other phones silently, and tells the other person nothing", async () => {    const { a, b } = await friends();    const tablet = await chatPhone(b.number, "b-tablet");    // The tablet read a's message: its read receipt is sealed for b's other phones alone.    const keys = await tablet.keysFor(a.number);    const id = crypto.randomUUID();    const payload = { v: 1, id, kind: "receipt", from: b.number, to: a.number, state: "read", ids: ["x-1"] };    const boxes: Record<string, string> = {};    for (const k of keys.own) boxes[k.device] = await tablet.seal(k.key, payload);    expect(Object.keys(boxes)).toHaveLength(1);    const sent = await open("POST", "/v1/chat/send", { to: a.number, id, kind: "receipt", boxes }, bearer(tablet.credential));    expect(sent.status, JSON.stringify(sent.body)).toBe(200);    await vi.waitFor(() => expect(world.pushes).toHaveLength(1));    const push = world.pushes[0]!;    expect(push.token).toBe(TOKEN_B);    expect(push.headers["apns-push-type"]).toBe("background");    expect(push.headers["apns-priority"]).toBe("5");    expect(push.body).toEqual({ aps: { "content-available": 1 }, chat: 1, read: 1 });    const [held] = await arrived(b);    expect(held).toMatchObject({ kind: "receipt", out: true, peer: a.number });    await settle();    expect(await a.inbox()).toHaveLength(0);  });});// Lane chat-open, 21 Nov 2026: someone who writes to a number whose owner keeps "can be found" off asks; the owner sees it in Chat as a request.describe("an ask to someone on Cotton", () => {  it("is in the inbox, wakes the owner's phones with nothing in it, tells the writer nothing, and goes once answered", async () => {    const b = await chatPhone(number(), "b-android", { platform: "android", token: "fcm-token-".padEnd(48, "y") });    const b2 = await chatPhone(b.number, "b-tablet");    const tablet = await b2.socket();    const a = await chatPhone(number(), "a-phone");    const wait = await open<Body>("POST", "/v1/chat/wait", { number: b.number }, bearer(a.credential));    expect(wait.body).toEqual({ state: "waiting" });    // The open phone gets a frame, the closed one an alert naming no one.    await vi.waitFor(() => expect(tablet.frames).toContainEqual({ t: "ask" }), { timeout: 3000, interval: 20 });    await vi.waitFor(() => expect(world.pushes).toHaveLength(1));    expect(world.pushes[0]!.message).toEqual({ token: "fcm-token-".padEnd(48, "y"), data: { kind: "chat", title: "New message" }, android: { priority: "HIGH", ttl: "86400s" } });    const inbox = await open<{ items: unknown[]; asks: { number: string; name: string | null; at: string }[] }>("GET", "/v1/chat/inbox", undefined, bearer(b.credential));    expect(inbox.body.items).toEqual([]);    expect(inbox.body.asks.map((x) => x.number)).toEqual([a.number]);    // Asked again (the writer writes again): no second wake.    await open("POST", "/v1/chat/wait", { number: b.number }, bearer(a.credential));    await settle();    expect(world.pushes).toHaveLength(1);    // The writer learns nothing until the owner accepts: still waiting, nothing in their inbox.    expect((await open<{ reached: string[] }>("GET", "/v1/chat/reach", undefined, bearer(a.credential))).body.reached).toEqual([]);    expect(await a.inbox()).toEqual([]);    await b.say("accept", a.number);    const after = await open<{ asks: unknown[] }>("GET", "/v1/chat/inbox", undefined, bearer(b2.credential));    expect(after.body.asks).toEqual([]);    await vi.waitFor(async () => expect((await open<{ reached: string[] }>("GET", "/v1/chat/reach", undefined, bearer(a.credential))).body.reached).toEqual([b.number]), { timeout: 3000, interval: 30 });  });  it("refused or blocked, goes from the inbox and the writer still learns nothing", async () => {    for (const what of ["refuse", "block"] as const) {      const b = await chatPhone(number(), "b-phone");      const a = await chatPhone(number(), "a-phone");      await open("POST", "/v1/chat/wait", { number: b.number }, bearer(a.credential));      await vi.waitFor(async () => expect((await open<{ asks: unknown[] }>("GET", "/v1/chat/inbox", undefined, bearer(b.credential))).body.asks).toHaveLength(1), { timeout: 3000, interval: 30 });      await b.say(what, a.number);      expect((await open<{ asks: unknown[] }>("GET", "/v1/chat/inbox", undefined, bearer(b.credential))).body.asks).toEqual([]);      await settle();      expect((await open<{ reached: string[]; waiting: string[] }>("GET", "/v1/chat/reach", undefined, bearer(a.credential))).body).toEqual({ reached: [], waiting: [b.number] });    }  });});// Lane chat-open, 21 Nov 2026: a walk proves a failed message and its Retry on a real phone by asking the dev server to refuse once.describe("a refusal a walk asks for", () => {  it("refuses the next message once, as a meant refusal, then takes the same message again", async () => {    const { a, b } = await friends();    const asked = await open<Body>("POST", "/v1/chat/dev/refuse-next", {}, bearer(a.credential));    expect(asked.body).toEqual({ left: 1 });    const first = await a.write(b.number, "this one fails");    expect(first.status).toBe(400);    expect(first.body).toMatchObject({ code: "dev_refused" });    expect(await b.inbox()).toEqual([]);    expect((await a.write(b.number, "retried")).status).toBe(200);    expect(await arrived(b)).toHaveLength(1);    expect((await open("POST", "/v1/chat/dev/refuse-next", { count: 9 }, bearer(a.credential))).status).toBe(400);  });  it("exists only on the dev server and in tests", () => {    expect([devServer({ ENV_LABEL: "dev" }), devServer({ ENV_LABEL: "test" }), devServer({ ENV_LABEL: "production" }), devServer({})]).toEqual([true, true, false, false]);  });});// Lane chat-warm-android, 23 Nov 2026: a change the Mac wrote reached the open phone 2.5 minutes late (emulator-5554), at the phone's next pull.describe("rows moved by another device", () => {  // RULE: a write that moves the person's rows tells every other open phone of theirs at once, with nothing of what moved; the writer's own socket hears nothing, and a read moves nothing.  it("tells the other open phones { t: rows } at once, never the writer, and nothing for a read", async () => {    const phone = await chatPhone(number(), "rows-phone");    const mac = await chatPhone(phone.number, "rows-mac");    const other = await phone.socket();    const own = await mac.socket();    const made = await open("POST", "/v1/act", { act: "create", args: { table: "todo", id: "todo-rows-1", data: { sealed_enc: `s1:${"A".repeat(124)}`, dek_enc: `d1:${"A".repeat(80)}`, seal_v: 1 } } }, bearer(mac.credential));    expect(made.status, JSON.stringify(made.body)).toBe(200);    await vi.waitFor(() => expect(other.frames.filter((f) => f.t === "rows")).toHaveLength(1), { timeout: 3000, interval: 10 });    const [frame] = other.frames.filter((f) => f.t === "rows");    expect(Object.keys(frame!).sort()).toEqual(["t", "v"]);    expect(typeof frame!.v).toBe("number");    // A read moves no version: nothing more is said.    expect((await open("GET", "/v1/sync?since=0", undefined, bearer(mac.credential))).status).toBe(200);    await settle();    expect(other.frames.filter((f) => f.t === "rows")).toHaveLength(1);    expect(own.frames.filter((f) => f.t === "rows"), "the writer pulls after its own push anyway").toEqual([]);  });  // RULE: a burst of writes (a Mac's import) is one frame at once and one more at the window's end saying the newest version, never a frame a write.  it("folds a burst into one frame now and one at the window's end", async () => {    const phone = await chatPhone(number(), "burst-phone");    const mac = await chatPhone(phone.number, "burst-mac");    const other = await phone.socket();    const rows = () => other.frames.filter((f) => f.t === "rows");    const heard: number[] = [];    other.ws.addEventListener("message", (event) => {      if ((JSON.parse(String(event.data)) as { t?: string }).t === "rows") heard.push(Date.now());    });    const sealed = { sealed_enc: `s1:${"A".repeat(124)}`, dek_enc: `d1:${"A".repeat(80)}`, seal_v: 1 };    const started = Date.now();    for (let i = 0; i < 20; i++) {      const made = await open("POST", "/v1/act", { act: "create", args: { table: "todo", id: `todo-burst-${i}`, data: sealed } }, bearer(mac.credential));      expect(made.status, JSON.stringify(made.body)).toBe(200);    }    const took = Date.now() - started;    const last = await open<{ version: number }>("GET", "/v1/sync?since=0", undefined, bearer(mac.credential));    await vi.waitFor(() => expect(rows().at(-1)?.v, "the last frame says the newest version").toBe(last.body.version), { timeout: ROWS_WINDOW_MS + 3000, interval: 20 });    await new Promise((r) => setTimeout(r, ROWS_WINDOW_MS + 200));    // However fast the writes came: never more than one frame a window, the first at once and the last at the end.    expect(rows().length, `${rows().length} frames for 20 writes in ${took} ms`).toBeLessThanOrEqual(Math.floor(took / ROWS_WINDOW_MS) + 2);    expect(rows().length).toBeLessThan(20);    for (let i = 1; i < heard.length; i++) expect(heard[i]! - heard[i - 1]!, "frames a window apart").toBeGreaterThanOrEqual(ROWS_WINDOW_MS - 100);    expect(rows().at(-1)?.v, "nothing after the newest").toBe(last.body.version);  });});