Cotton code
114 lines · 6.3 KB · TypeScriptRaw
/** * Invitations between people on Cotton (src/invite.ts, CONTRACT §17), over * synthetic people's objects on the open host: a box from one of this * person's people is held and taken, one from a stranger or a blocked number * is dropped and the sender is answered the same, a box waits thirty days at * most. The boxes are opaque made-up text: the objects never open them. */import { env, runInDurableObject } from "cloudflare:test";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { BOX_MAX, HOLD_MS } from "../src/invite.ts";import { bearer, fakes, open } from "./calling.ts";import { chatPhone, type ChatPhone } from "./chat.ts";vi.setConfig({ testTimeout: 120_000 });let n = 0;const number = (): string => `+91900007${String(1000 + ++n).padStart(4, "0")}`;beforeEach(() => {  fakes();});afterEach(() => {  vi.restoreAllMocks();});type Held = { seq: number; from: string; kind: string; id: string; box: string; at: string };const box = (s: string): string => `p1:${btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`;function send(from: ChatPhone, to: ChatPhone | string, kind: string, id: string, b: string): Promise<{ status: number; body: Record<string, unknown> }> {  return open("POST", "/v1/invite/send", { to: typeof to === "string" ? to : to.number, kind, id, box: b }, bearer(from.credential));}async function inbox(p: ChatPhone): Promise<Held[]> {  const res = await open<{ held: Held[] }>("GET", "/v1/invite/inbox", undefined, bearer(p.credential));  expect(res.status, JSON.stringify(res.body)).toBe(200);  return res.body.held;}async function slugOf(p: ChatPhone): Promise<string> {  return (await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).lookup(p.number))!;}async function connected(): Promise<{ rose: ChatPhone; guest: ChatPhone }> {  const rose = await chatPhone(number(), `dev-${n}`);  const guest = await chatPhone(number(), `dev-${n}`);  await rose.say("accept", guest.number);  await guest.say("accept", rose.number);  return { rose, guest };}describe("invitations between people on Cotton", () => {  it("holds a box from one of this person's people, oldest first, and the phone's taken removes it", async () => {    const { rose, guest } = await connected();    expect(await send(rose, guest, "invite", "inv-dinner-0001", box("an invitation"))).toEqual({ status: 200, body: { ok: true } });    expect(await send(rose, guest, "cancel", "inv-dinner-0001", box("called off"))).toEqual({ status: 200, body: { ok: true } });    await vi.waitFor(async () => expect(await inbox(guest)).toHaveLength(2), { timeout: 5000, interval: 50 });    const held = await inbox(guest);    expect(held.map((h) => [h.from, h.kind, h.id, h.box])).toEqual([      [rose.number, "invite", "inv-dinner-0001", box("an invitation")],      [rose.number, "cancel", "inv-dinner-0001", box("called off")],    ]);    expect(held[0]!.seq).toBeLessThan(held[1]!.seq);    expect(Date.parse(held[0]!.at)).toBeGreaterThan(Date.now() - 60_000);    // The guest answers back the other way.    await send(guest, rose, "answer", "inv-dinner-0001", box("coming"));    await vi.waitFor(async () => expect((await inbox(rose)).map((h) => h.kind)).toEqual(["answer"]), { timeout: 5000, interval: 50 });    expect((await open("POST", "/v1/invite/taken", { seqs: [held[0]!.seq] }, bearer(guest.credential))).status).toBe(200);    expect((await inbox(guest)).map((h) => h.seq)).toEqual([held[1]!.seq]);    expect((await open("POST", "/v1/invite/taken", { seqs: "all" }, bearer(guest.credential))).status).toBe(400);  });  it("drops a box to or from a stranger, and from a blocked number, answering the sender the same", async () => {    const { rose, guest } = await connected();    const stranger = await chatPhone(number(), `dev-${n}`);    // The stranger accepted the guest, the guest never accepted them: nothing is held.    await stranger.say("accept", guest.number);    expect(await send(stranger, guest, "invite", "inv-stranger-01", box("from a stranger"))).toEqual({ status: 200, body: { ok: true } });    // Rose sends to someone she never accepted, and to a number nobody holds.    expect(await send(rose, stranger, "invite", "inv-unasked-01", box("unasked"))).toEqual({ status: 200, body: { ok: true } });    expect(await send(rose, "+919000079999", "invite", "inv-nobody-001", box("to nobody"))).toEqual({ status: 200, body: { ok: true } });    // The guest blocks Rose: what Rose sends is dropped.    await guest.say("block", rose.number);    expect(await send(rose, guest, "invite", "inv-blocked-01", box("blocked"))).toEqual({ status: 200, body: { ok: true } });    // A box that does reach (the stranger's own side) shows the hop ran: a send from the guest to Rose is dropped by the guest's own block.    await send(guest, rose, "answer", "inv-blocked-01", box("blocked both ways"));    // Give any hop time to land, then look: nothing anywhere.    await new Promise((r) => setTimeout(r, 500));    expect(await inbox(guest)).toEqual([]);    expect(await inbox(stranger)).toEqual([]);    expect(await inbox(rose)).toEqual([]);  });  it("refuses a malformed box by name, holds none over its size, and lets a box go after thirty days", async () => {    const { rose, guest } = await connected();    expect((await send(rose, guest, "rsvp", "inv-kind-0001", box("x"))).status).toBe(400);    expect((await send(rose, guest, "invite", "short", box("x"))).status).toBe(400);    expect((await send(rose, guest, "invite", "inv-plain-001", "not sealed")).status).toBe(400);    expect((await send(rose, guest, "invite", "inv-big-00001", `p1:${"A".repeat(BOX_MAX)}`)).status).toBe(413);    expect((await open("GET", "/v1/invite/inbox")).status).toBe(401);    await send(rose, guest, "invite", "inv-old-00001", box("old"));    await vi.waitFor(async () => expect(await inbox(guest)).toHaveLength(1), { timeout: 5000, interval: 50 });    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(await slugOf(guest))), (_i, state) => {      state.storage.sql.exec("UPDATE invite_held SET at = ?", Date.now() - HOLD_MS - 1000);      // Nothing of the box but its outside is kept.      expect(state.storage.sql.exec("SELECT from_number, kind, id FROM invite_held").toArray()).toEqual([{ from_number: rose.number, kind: "invite", id: "inv-old-00001" }]);    });    expect(await inbox(guest)).toEqual([]);  });});