/** * Cotton groups on the Worker (20 Nov 2026): a group envelope fans out to * each member's object as a one-to-one envelope would, naming the group; * a member of a group the owner says they are in is no stranger there, and * nobody else is: anyone else's group envelope reaches no phone (the first * contact gate, src/chat/gate.ts, DISCOVERY OFF 3). The Worker keeps no * roster and opens no box. Every number is synthetic. */import { env, runInDurableObject } from"cloudflare:test";import { afterEach, beforeEach, describe, expect, it, vi } from"vitest";import { bearer, fakes, open, typeFakes } from"./calling.ts";import { arrived, chatPhone, settle, typeChatPhone } from"./chat.ts";import { GROUP_MEMBERS_MAX, LOOKUPS_PER_HOUR, STALE_DEVICES } from"../src/chat/chat.ts";import { NEW_NUMBERS_PER_HOUR } from"../src/chat/gate.ts";vi.setConfig({ testTimeout: 60_000 });let world: Fakes;let n = 0;const number = (): string => `+91900002${String(1000 + ++n).padStart(4, "0")}`;const GROUP = "ab".repeat(16);beforeEach(() => { world = fakes();});afterEach(() => { vi.restoreAllMocks();});/** Asha knows Ben and Chen; Ben and Chen have never written to each other. */asyncfunction three(): Promise<{ asha: ChatPhone; ben: ChatPhone; chen: ChatPhone }> {const asha = await chatPhone(number(), "asha-phone");const ben = await chatPhone(number(), "ben-phone");const chen = await chatPhone(number(), "chen-phone");for (const [x, y] of [[asha, ben], [ben, asha], [asha, chen], [chen, asha]] asconst) await x.say("accept", y.number);return { asha, ben, chen };}asyncfunction objectRows(phone: ChatPhone, sql: string): Promise<unknown[]> {const slug = await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).lookup(phone.number);const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug!));return runInDurableObject(stub, async (_i, state) => state.storage.sql.exec(sql).toArray());}describe("a group envelope", () => { it("reaches each member's devices, naming the group, sealed for each alone", async () => {const { asha, ben, chen } = await three();const sent = await asha.writeGroup(GROUP, [ben.number, chen.number], "dinner at eight"); expect(sent.status, JSON.stringify(sent.body)).toBe(200);const [b] = await arrived(ben);const [c] = await arrived(chen); expect(b).toMatchObject({ kind: "message", peer: asha.number, out: false, request: false, group: GROUP }); expect(c).toMatchObject({ peer: asha.number, group: GROUP, request: false }); expect(await ben.open(b!.box)).toMatchObject({ body: "dinner at eight", to: ben.number, group: GROUP }); expect(await chen.open(b!.box)).toBeNull(); }); it("from a member the owner never accepted reaches nothing until the owner's phone says they are in the group, then lands", async () => {const { asha, ben, chen } = await three();// Ben writes in the group to Chen, a stranger to him: Chen's keys are not given to him, and nothing lands.await ben.writeGroup(GROUP, [asha.number, chen.number], "hello Chen");await arrived(asha);await settle(); expect(await chen.inbox()).toEqual([]);// Chen's phone, having folded the group, says Ben is in it: Ben's words in it land, never a request. expect((await chen.joinGroup(GROUP, [asha.number, ben.number])).status).toBe(200);await ben.writeGroup(GROUP, [chen.number], "hello again"); expect((await arrived(chen))[0]).toMatchObject({ peer: ben.number, request: false, group: GROUP });await ben.writeGroup(GROUP, [chen.number], "delivered", undefined, "receipt");await arrived(chen, 2);// Being in a group with someone makes them none of Chen's people.const people = await open<{ people: { number: string }[] }>("GET", "/v1/chat/people", undefined, bearer(chen.credential)); expect(people.body.people.map((p) => p.number)).not.toContain(ben.number); }); it("from someone the owner says is not in the group, or after the owner left it, reaches nothing", async () => {const { asha, ben, chen } = await three();await chen.joinGroup(GROUP, [asha.number]);await ben.writeGroup(GROUP, [chen.number], "let me in");await settle(); expect(await chen.inbox()).toEqual([]);await chen.joinGroup(GROUP, []);await asha.writeGroup(GROUP, [chen.number], "still there?");// Asha is Chen's own person: her words are never a request. expect((await arrived(chen))[0]).toMatchObject({ request: false, peer: asha.number }); expect(await objectRows(chen, "SELECT * FROM chat_group")).toEqual([]); }); it("is never taken from someone the owner blocked, group or not", async () => {const { asha, ben, chen } = await three();await chen.joinGroup(GROUP, [asha.number, ben.number]);await chen.say("block", ben.number);await ben.writeGroup(GROUP, [chen.number], "blocked words");await settle(); expect(await chen.inbox()).toEqual([]);void asha; }); it("lands copies on the sender's own other devices with their own number as the peer", async () => {const { ben, chen } = await three();const asha = await chatPhone(number(), "asha-phone");const tablet = await chatPhone(asha.number, "asha-tablet");await asha.writeGroup(GROUP, [ben.number, chen.number], "from my phone");const [copy] = await arrived(tablet); expect(copy).toMatchObject({ out: true, peer: asha.number, group: GROUP, kind: "message" }); expect(await tablet.open(copy!.box)).toMatchObject({ to: asha.number, from: asha.number }); }); it("is refused when sealed for a member's devices of before, so their phone signed in since gets it after a reseal", async () => {const { asha, ben, chen } = await three();const keys = async () => (await open<{ peers: Record<string, { device: string; key: string }[]>; own: { device: string; key: string }[] }>("POST", "/v1/chat/keys", { numbers: [ben.number, chen.number] }, bearer(asha.credential))).body;const sealed = async (k: Awaited<ReturnType<typeof keys>>, id: string) => {const to: Record<string, Record<string, string>> = {};for (const m of [ben.number, chen.number]) { to[m] = {};for (const d of k.peers[m]!) to[m]![d.device] = await asha.seal(d.key, { v: 1, id, kind: "message", from: asha.number, to: m, body: "new phone?", group: GROUP }); }return open<Record<string, unknown>>("POST", "/v1/chat/group/send", { id, kind: "message", group: GROUP, to, check: true }, bearer(asha.credential)); };const kept = await keys();const tablet = await chatPhone(ben.number, "ben-tablet");const id = crypto.randomUUID();const stale = await sealed(kept, id); expect(stale.status).toBe(409); expect(stale.body).toMatchObject({ code: STALE_DEVICES }); expect((await sealed(await keys(), id)).status).toBe(200); expect(await tablet.open((await arrived(tablet))[0]!.box)).toMatchObject({ body: "new phone?", group: GROUP }); expect(await arrived(chen)).toHaveLength(1); }); it("is refused when it is badly made, and a resend goes nowhere", async () => {const { asha, ben } = await three();const bad = await open("POST", "/v1/chat/group/send", { id: "abcdefgh", kind: "message", group: "nope", to: {} }, bearer(asha.credential)); expect(bad.status).toBe(400);const typing = await open("POST", "/v1/chat/group/send", { id: "abcdefgh", kind: "typing", group: GROUP, to: {} }, bearer(asha.credential)); expect(typing.status).toBe(400);const many = Object.fromEntries(Array.from({ length: GROUP_MEMBERS_MAX + 1 }, (_, i) => [`+9190000390${String(i).padStart(2, "0")}`, {}])); expect((await open("POST", "/v1/chat/group/send", { id: "abcdefgh", kind: "message", group: GROUP, to: many }, bearer(asha.credential))).status).toBe(400);const id = crypto.randomUUID();await asha.writeGroup(GROUP, [ben.number], "once", id);await asha.writeGroup(GROUP, [ben.number], "once", id);await arrived(ben);await settle(); expect((await ben.inbox()).length).toBe(1); }); it("carries no words, names or members the Worker can read", async () => {const { asha, ben, chen } = await three();await chen.joinGroup(GROUP, [asha.number, ben.number]);await asha.writeGroup(GROUP, [ben.number, chen.number], "the secret recipe");await arrived(chen);for (const phone of [asha, ben, chen]) {const rows = JSON.stringify(await objectRows(phone, "SELECT * FROM chat_group")) + JSON.stringify(await objectRows(phone, "SELECT * FROM chat_held")); expect(rows).not.toContain("secret recipe"); expect(rows).not.toContain(ben.number.slice(1) + '"'); } }); it("pushes an alert to a member with no socket open, as one-to-one does", async () => {const asha = await chatPhone(number(), "asha-phone");const ben = await chatPhone(number(), "ben-phone", { platform: "ios", token: "b1".repeat(32) });await ben.say("accept", asha.number);await asha.writeGroup(GROUP, [ben.number], "ping");await vi.waitFor(() => expect(world.pushes.filter((p) => p.body.chat === 1).length).toBeGreaterThan(0), { timeout: 3000 }); });});describe("keys for a group", () => { it("answers every member's devices, a made-up one for a number nobody holds, and this person's own", async () => {const { asha, ben } = await three();const nobody = number();const res = await open<{ me: string; peers: Record<string, { device: string; key: string }[]>; own: unknown[] }>("POST", "/v1/chat/keys", { numbers: [ben.number, nobody, asha.number] }, bearer(asha.credential)); expect(res.status).toBe(200); expect(res.body.me).toBe(asha.number); expect(res.body.peers[ben.number]).toEqual([{ device: expect.any(String), key: ben.publicKey }]); expect(res.body.peers[nobody]).toHaveLength(1); expect(res.body.peers[asha.number]).toBeUndefined();// The made-up key is the one a single lookup answers: a batch says nothing more about a number. expect((await asha.keysFor(nobody)).devices).toEqual(res.body.peers[nobody]); }); it("counts each new number against the hourly lookups, and a number asked again costs nothing", async () => {const asha = await chatPhone(number(), "asha-phone");// A number neither one of hers nor in a group with her is one of her new numbers (src/chat/gate.ts): a few an hour.const strangers = Array.from({ length: NEW_NUMBERS_PER_HOUR + 1 }, () => number()); expect((await open("POST", "/v1/chat/keys", { numbers: strangers }, bearer(asha.credential))).status).toBe(429);// Members of her groups cost none of them; the hour's lookups still count each.const members = Array.from({ length: LOOKUPS_PER_HOUR + 1 }, () => number());for (let i = 0; i < members.length; i += 60) expect((await asha.joinGroup(String(i).padStart(32, "c"), members.slice(i, i + 60))).status).toBe(200);const batch = members.slice(0, 60); expect((await open("POST", "/v1/chat/keys", { numbers: batch }, bearer(asha.credential))).status).toBe(200); expect((await open("POST", "/v1/chat/keys", { numbers: batch }, bearer(asha.credential))).status).toBe(200);const more = members.slice(60); expect((await open("POST", "/v1/chat/keys", { numbers: more.slice(0, 60) }, bearer(asha.credential))).status).toBe(200); expect((await open("POST", "/v1/chat/keys", { numbers: more.slice(60) }, bearer(asha.credential))).status).toBe(429); });});describe("a stranger's group", () => { it("reaches nothing and is no ask: a group's invitation reaches only someone who accepted the inviter", async () => {const asha = await chatPhone(number(), "asha-phone");const chen = await chatPhone(number(), "chen-phone");for (let i = 0; i < 3; i++) await asha.writeGroup(GROUP, [chen.number], `invite ${i}`, undefined, "group");await settle(); expect(await chen.inbox()).toEqual([]);const people = await open<{ asking: unknown[] }>("GET", "/v1/chat/people", undefined, bearer(chen.credential)); expect(people.body.asking).toEqual([]);// Accepted, her invitation lands.await chen.say("accept", asha.number);await asha.writeGroup(GROUP, [chen.number], "invite again", undefined, "group"); expect((await arrived(chen))[0]).toMatchObject({ kind: "group", group: GROUP, request: false }); });});