/** * THE ONE GATE FOR FIRST CONTACT (DISCOVERY OFF 3, 27 Nov 2026; src/chat/gate.ts). Every route that takes a number * from a signed-in caller is listed here and classified, and each one that reaches a number is shown to go through the * gate: over the hour's new numbers it is refused the same for an account and a number nobody holds; a stranger's * sealed words, ring, keys and one-time keys never reach or leave the target; a deleted request stays deleted; no * accepted person drains another's keys; accepting a request costs nothing; and a wait made after a number had its * database never brings that person as a referral. Every number here is synthetic. */ import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it, vi } from "vitest"; import CHAT from "../src/chat/chat.ts?raw"; import CALLS from "../src/calling/calls.ts?raw"; import INVITE from "../src/invite.ts?raw"; import SEND from "../src/send/send.ts?raw"; import SECRETS from "../src/send/secrets.ts?raw"; import SHARED from "../src/send/shared.ts?raw"; import SPACE from "../src/space/routes.ts?raw"; import { CLAIMS_FROM_ONE_HOUR, NEW_NUMBERS_PER_HOUR, OVER_HOUR } from "../src/chat/gate.ts"; import type { Directory } from "../src/directory.ts"; import { keyOf } from "../src/calling/calls.ts"; import { bearer, open, signUp } from "./calling.ts"; import { b64url, chatPhone, settle, type ChatPhone } from "./chat.ts"; vi.setConfig({ testTimeout: 60_000 }); let n = 0; const number = (): string => `+9190088${String(++n).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))); const GROUP = "0123456789abcdef0123456789abcdef"; const ROOM = "fedcba9876543210fedcba9876543210"; const HANDLE = "AAAAAAAAAAAAAAAAAAAAAA"; const BOX = "c1:AAAA"; /** * Every route under the families that name a person, and how it treats the person it names: * - `gate`: it reaches a number, through gate.firstContact(s) on this object and gate.admits / admitsAny / askAdmits * / claimAdmits on theirs; * - `person`: it reaches only one of this owner's people, accepted both ways (gate.isPerson on both objects), and * answers anyone else the same as a number nobody holds; * - `local`: it names a person only to this owner's own lists (a block, a refusal, who is in a group) or reaches * them only to take back this owner's own ask, delivering nothing; * - `link`: it reaches only the person whose invitation link it holds (the code, and a secret only the link's fragment * carries, checked against its hash on the inviter's object, live and unused, guessing limited: src/chat/circle_invite.ts); * - `none`: it names no other person. */ const ROUTES: Record = { "/v1/chat/send": "gate", "/v1/chat/group/send": "gate", "/v1/chat/keys": "gate", "/v1/chat/prekeys/claim": "gate", "/v1/chat/wait": "gate", "/v1/chat/(accept|refuse|block|unblock|remove)": "gate", // accept is an add (gate); refuse, block, unblock are local; remove withdraws this owner's ask "/v1/chat/group": "local", "/v1/chat/people": "local", "/v1/chat/reach": "local", "/v1/chat/discover": "none", "/v1/chat/findable": "none", "/v1/chat/device": "none", "/v1/chat/socket": "none", "/v1/chat/circle/invite": "none", // his own link, made by his phone "/v1/chat/circle/invite/stop": "none", "/v1/chat/circle/invites": "none", "/v1/chat/circle/redeem": "link", "/v1/chat/prekeys": "none", "/v1/chat/files": "none", "/v1/chat/files/:id": "none", "/v1/chat/inbox": "none", "/v1/chat/ack": "none", "/v1/chat/dev/refuse-next": "none", "/v1/chat/profile-picture": "none", "/v1/chat/profile-pictures/:id": "none", "/v1/calls": "gate", "/v1/calls/:room/(join|enter|decline|end|invite)": "gate", // invite reaches numbers (gate); the rest act on a room this phone is in "/v1/calls/:room/status": "none", "/v1/calls/ice": "none", "/v1/calls/ack": "none", // this phone acks a ring or stop it had (its own row), reaches no number "/v1/calls/device": "none", "/v1/calls/block": "local", "/v1/calls/unblock": "local", "/v1/calls/blocked": "local", "/v1/invite/send": "person", "/v1/invite/inbox": "none", "/v1/invite/taken": "none", "/v1/send/key": "person", "/v1/send/make": "person", "/v1/send/trust": "person", "/v1/send/people": "local", "/v1/send/offer": "local", "/v1/send/weigh": "none", "/v1/send/inbox": "none", "/v1/send/keep": "none", "/v1/send/landed": "none", "/v1/send/decline": "none", "/v1/send/undo": "none", "/v1/send/:id/media": "none", "/v1/secret/share": "person", "/v1/secret/share/update": "person", "/v1/secret/ask": "person", "/v1/secret/share/take": "none", "/v1/secret/share/out": "none", "/v1/secret/share/in": "none", "/v1/secret/share/value": "none", "/v1/secret/share/drop": "none", "/v1/secret/ask/in": "none", "/v1/secret/ask/answer": "none", "/v1/secret/ask/withdraw": "none", "/v1/secret/ask/out": "none", "/v1/secret/note": "none", "/v1/secret/rewrap": "none", "/v1/shared/lists": "person", // a list's members: the founder's object tells only its owner's people (joinedIn reads gate.isPerson) "/v1/shared/list": "person", "/v1/shared/list/item": "person", "/v1/shared/list/state": "person", }; /** Routes the regexes match, as the table names them. */ const FAMILIES = ["/v1/chat/(accept|refuse|block|unblock|remove)", "/v1/chat/files/:id", "/v1/chat/profile-pictures/:id", "/v1/calls/:room/status", "/v1/calls/:room/(join|enter|decline|end|invite)", "/v1/send/:id/media"]; /** Prefixes a router checks before its routes. */ const PREFIXES = new Set(["/v1/chat", "/v1/chat/", "/v1/calls", "/v1/calls/", "/v1/invite/", "/v1/secret/", "/v1/send/", "/v1/shared/"]); describe("every route that names a person", () => { it("is listed and classified, and each that reaches a number calls the gate", () => { const found = new Set(); for (const source of [CHAT, CALLS, INVITE, SEND, SECRETS, SHARED]) { for (const [, path] of source.matchAll(/"(\/v1\/(?:chat|calls|invite|send|secret|shared)[^"]*)"/g)) if (!PREFIXES.has(path!)) found.add(path!); } found.add("/v1/calls"); const listed = new Set(Object.keys(ROUTES)); expect([...found].filter((p) => !listed.has(p)), "a route not classified here").toEqual([]); expect([...listed].filter((p) => !found.has(p) && !FAMILIES.includes(p)), "a classified route that no longer exists").toEqual([]); // The reaching routes' sources go through the gate; none keeps its own copy of the count. expect(CHAT.match(/gate\.firstContacts?\(/g)?.length ?? 0).toBeGreaterThanOrEqual(7); expect(CALLS.match(/gate\.firstContacts\(/g)?.length).toBe(2); expect(CALLS).toContain("gate.admits("); for (const source of [CHAT, CALLS, INVITE, SEND, SECRETS, SHARED]) expect(source).not.toMatch(/(INSERT|DELETE|SELECT)[^"]*chat_pick/); // Spaces share only with one's people, through the same rule (space/person.ts asks send.isPersonOf, which is gate.isPerson). expect(SPACE).toContain("/v1/spaces"); expect(SEND).toContain("gate.isPerson("); }); }); /** Each route that reaches a number, asked of `target` from `from`. */ const PROBES: Record Promise<{ status: number; body: unknown }>> = { wait: (f, t) => open("POST", "/v1/chat/wait", { number: t }, bearer(f.credential)), add: (f, t) => open("POST", "/v1/chat/accept", { number: t }, bearer(f.credential)), send: (f, t) => open("POST", "/v1/chat/send", { to: t, id: `probe-${crypto.randomUUID()}`, kind: "message", boxes: { [HANDLE]: BOX } }, bearer(f.credential)), receipt: (f, t) => open("POST", "/v1/chat/send", { to: t, id: `probe-${crypto.randomUUID()}`, kind: "receipt", boxes: { [HANDLE]: BOX } }, bearer(f.credential)), keys: (f, t) => open("GET", `/v1/chat/keys?number=${encodeURIComponent(t)}`, undefined, bearer(f.credential)), manyKeys: (f, t) => open("POST", "/v1/chat/keys", { numbers: [t] }, bearer(f.credential)), claim: (f, t) => open("POST", "/v1/chat/prekeys/claim", { number: t, devices: [HANDLE] }, bearer(f.credential)), groupSend: (f, t) => open("POST", "/v1/chat/group/send", { id: `probe-${crypto.randomUUID()}`, kind: "group", group: GROUP, to: { [t]: { [HANDLE]: BOX } } }, bearer(f.credential)), call: (f, t) => open("POST", "/v1/calls", { to: [t] }, bearer(f.credential)), callInvite: (f, t) => open("POST", `/v1/calls/${ROOM}/invite`, { to: [t] }, bearer(f.credential)), }; describe("over the hour's new numbers", () => { it("every route that reaches a number is refused the same for an account and for a number nobody holds", async () => { const a = await chatPhone(number(), "a"); const member = await chatPhone(number(), "m"); for (let i = 0; i < NEW_NUMBERS_PER_HOUR; i++) expect((await PROBES.wait!(a, number())).status).toBe(200); for (const [name, probe] of Object.entries(PROBES)) { const held = await probe(a, member.number); const nobody = await probe(a, number()); expect([name, held.status, held.body], name).toEqual([name, 429, nobody.body]); expect(JSON.stringify(held.body)).toContain(OVER_HOUR); } // One of this owner's people (and anyone asking them) costs nothing, over the limit or not. const friend = await chatPhone(number(), "f"); await runInDurableObject(objectOf(a), async (_i, state) => { state.storage.sql.exec("INSERT INTO chat_peer (key, number, at) VALUES (?, ?, ?)", await keyOf(state.storage.sql, friend.number), friend.number, new Date().toISOString()); }); expect((await PROBES.keys!(a, friend.number)).status).toBe(200); }); }); /** This owner's first device's handle, as their second device's keys lookup names it. */ async function handleOf(phone: ChatPhone): Promise<{ device: string; key: string }> { const second = await chatPhone(phone.number, `${phone.device}-2`); const keys = await second.keysFor(phone.number); return keys.own.find((k) => k.key === phone.publicKey)!; } async function asking(phone: ChatPhone): Promise { return (await open<{ asking: { number: string }[] }>("GET", "/v1/chat/people", undefined, bearer(phone.credential))).body.asking.map((x) => x.number); } describe("a stranger", () => { it("reaches no phone with sealed words: their message is their ask, their group envelope and ring go nowhere", async () => { const a = await chatPhone(number(), "a"); const b = await chatPhone(number(), "b"); const real = await handleOf(b); // Their keys lookup never gives out the real device. expect((await a.keysFor(b.number)).devices.map((d) => d.device)).not.toContain(real.device); // A box crafted for the real device: nothing held for it, and A asks instead. const crafted = await open("POST", "/v1/chat/send", { to: b.number, id: `crafted-${crypto.randomUUID()}`, kind: "message", boxes: { [real.device]: await a.seal(real.key, { v: 1, body: "hi" }) } }, bearer(a.credential)); expect(crafted.status).toBe(200); await settle(); expect(await b.inbox()).toEqual([]); expect(await asking(b)).toEqual([a.number]); // A group's envelope from someone B never accepted (whatever group A says they share): nothing, and no new ask. await a.joinGroup(GROUP, [b.number]); await open("POST", "/v1/chat/group/send", { id: `g-${crypto.randomUUID()}`, kind: "group", group: GROUP, to: { [b.number]: { [real.device]: BOX } } }, bearer(a.credential)); await settle(); expect(await b.inbox()).toEqual([]); // A ring: nothing reaches B's open phone. const socket = await b.socket(); expect((await open("POST", "/v1/calls", { to: [b.number] }, bearer(a.credential))).status).toBe(200); await settle(); expect(socket.frames.filter((f) => f.t === "ring")).toEqual([]); // Accepted, the same ring rings and a message lands. await b.say("accept", a.number); expect((await open("POST", "/v1/calls", { to: [b.number] }, bearer(a.credential))).status).toBe(200); await vi.waitFor(() => expect(socket.frames.some((f) => f.t === "ring")).toBe(true), { timeout: 3000, interval: 20 }); expect((await a.keysFor(b.number)).devices.map((d) => d.device)).toContain(real.device); }); it("whose request was deleted never alerts again until accepted", async () => { const a = await chatPhone(number(), "a"); const b = await chatPhone(number(), "b"); await open("POST", "/v1/chat/wait", { number: b.number }, bearer(a.credential)); await vi.waitFor(async () => expect(await asking(b)).toEqual([a.number]), { timeout: 3000, interval: 20 }); await b.say("refuse", a.number); const socket = await b.socket(); const real = await handleOf(b); for (let i = 0; i < 3; i++) await open("POST", "/v1/chat/send", { to: b.number, id: `again-${i}-${crypto.randomUUID()}`, kind: "message", boxes: { [real.device]: BOX } }, bearer(a.credential)); await open("POST", "/v1/chat/accept", { number: b.number }, bearer(a.credential)); await settle(); expect(await asking(b)).toEqual([]); expect(socket.frames.filter((f) => f.t === "ask" || f.t === "envelope")).toEqual([]); }); it("takes none of a device's one-time keys; an accepted person takes at most their hourly share", async () => { const a = await chatPhone(number(), "a"); const b = await chatPhone(number(), "b"); const keyText = (fill: number) => b64url(new Uint8Array(32).fill(fill)); const sigText = (fill: number) => b64url(new Uint8Array(64).fill(fill)); const res = await open("POST", "/v1/chat/device", { publicKey: b.publicKey, c2: { identity: keyText(10), signing: keyText(11), sig: sigText(2), fallback: { key: keyText(200), sig: sigText(3) }, prekeys: Array.from({ length: 3 }, (_, i) => ({ key: keyText(20 + i), sig: sigText(1) })) } }, bearer(b.credential)); expect(res.status).toBe(200); const real = await handleOf(b); const left = async () => (await open<{ prekeys?: number }>("GET", "/v1/chat/inbox", undefined, bearer(b.credential))).body.prekeys; const claim = () => open<{ prekeys: Record }>("POST", "/v1/chat/prekeys/claim", { number: b.number, devices: [real.device] }, bearer(a.credential)); expect((await claim()).body.prekeys).toEqual({}); expect(await left()).toBe(3); await b.say("accept", a.number); expect(Object.keys((await claim()).body.prekeys)).toEqual([real.device]); expect(await left()).toBe(2); for (let i = 1; i < CLAIMS_FROM_ONE_HOUR; i++) await claim(); expect((await claim()).body.prekeys, "over the hourly share").toEqual({}); }); }); describe("accepting a stranger's request", () => { it("costs the accepter none of their new numbers", async () => { const a = await chatPhone(number(), "a"); const b = await chatPhone(number(), "b"); for (let i = 0; i < NEW_NUMBERS_PER_HOUR; i++) expect((await PROBES.wait!(b, number())).status).toBe(200); await open("POST", "/v1/chat/wait", { number: b.number }, bearer(a.credential)); await vi.waitFor(async () => expect(await asking(b)).toEqual([a.number]), { timeout: 3000, interval: 20 }); expect((await open("POST", "/v1/chat/accept", { number: a.number }, bearer(b.credential))).status).toBe(200); }); }); describe("a referral", () => { it("is never credited for a wait made after the number already had its database", async () => { const waiter = await chatPhone(number(), "w"); const slug = (credential: string) => `p-${credential.split("_")[1]}`; // Waited for before they had a database, then signed up: brought by the waiter. const later = number(); expect((await open("POST", "/v1/chat/wait", { number: later }, bearer(waiter.credential))).status).toBe(200); const joined = slug(await signUp(later, "j")); // Waited for when they already had one: never brought by anyone. const member = number(); const memberSlug = slug(await signUp(member, "m")); expect((await open("POST", "/v1/chat/wait", { number: member }, bearer(waiter.credential))).status).toBe(200); await runInDurableObject(dir(), async (instance: Directory) => { await instance.joined(joined, later, true); await instance.joined(memberSlug, member, true); }); const rows = await runInDurableObject(dir(), (_i, state) => state.storage.sql.exec<{ friend: string }>("SELECT friend FROM referral WHERE referrer = ?", slugOf(waiter)).toArray().map((r) => r.friend)); expect(rows).toContain(joined); expect(rows).not.toContain(memberSlug); }); });