/** * Send (owner, 13 Nov 2026), sealed all the way (ruling R5, * 15 Nov 2026), end to end over two synthetic people's objects on the open * host. The test plays each phone (test/send-phone.ts): the sender's lays * the payload from its own copy through the one rule and seals it to the * receiver's sharing key; the objects route the box, weigh and copy bytes * they cannot read; the receiver's phone opens it, plans the landing and * writes the rows. Every number, title and byte is synthetic. */ import { env, runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { Business } from "../src/business.ts"; import { COPY, EXPIRES_MS, FROM_PEER_DAY } from "../src/send/send.ts"; import type { Store } from "../src/store.ts"; import { bearer, fakes, open, OPEN } from "./calling.ts"; import { chatPhone, type ChatPhone } from "./chat.ts"; import { held, keepSealed, landing, openBox, postSharingKey, sendSealed, writeRows, type Payload } from "./send-phone.ts"; import { holdsWord } from "./clear-word.ts"; vi.setConfig({ testTimeout: 180_000 }); let n = 0; const number = (): string => `+91900002${String(1000 + ++n).padStart(4, "0")}`; beforeEach(() => { fakes(); }); afterEach(() => { vi.restoreAllMocks(); }); type Body = Record; interface Person { phone: ChatPhone; slug: string; db: string; number: string; /** This person's sharing key's public half, as their phone posted it. */ key: string; ask(method: string, path: string, body?: unknown): Promise<{ status: number; body: T }>; } async function person(posts = true): Promise { const phone = await chatPhone(number(), `dev-${n}`); const slug = (await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).lookup(phone.number))!; const db = await inObject(slug, (b) => b.store.meta("database_id")!); const p = { phone, slug, db, number: phone.number, key: "", ask: (method: string, path: string, body?: unknown) => open(method, path, body, bearer(phone.credential)) } as Person; if (posts) p.key = await postSharingKey(p); return p; } /** Two people who accepted each other on Cotton: each other's people. */ async function people(): Promise<{ a: Person; b: Person }> { const a = await person(); const b = await person(); await a.phone.say("accept", b.phone.number); await b.phone.say("accept", a.phone.number); return { a, b }; } type Inside = { store: Store; caps: Business["caps"] }; function inObject(slug: string, fn: (b: Inside, sql: SqlStorage) => T | Promise): Promise { return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance: Business, state) => fn(instance as unknown as Inside, state.storage.sql)); } /** A row written straight into a person's object, as a sync would land it. */ function put(p: Person, table: string, data: Body, id: string = crypto.randomUUID()): Promise { return inObject(p.slug, (b) => { b.store.insert(table, id, data, null, b.store.bump()); return id; }); } function rows(p: Person, table: string): Promise<{ id: string; data: Body }[]> { return inObject(p.slug, (b) => [...b.store.scan(table)].map((r) => ({ id: r.id, data: r.data }))); } /** A book with its file and cover in the sender's media. */ async function book(p: Person, title = "The Synthetic Garden", extra: Body = {}): Promise<{ id: string; file: string; cover: string }> { const sha = crypto.randomUUID().replace(/-/g, "").padEnd(64, "0"); const file = `${p.db}/books/${sha}.epub`; const cover = `${p.db}/photos/${sha}.jpg`; await env.MEDIA.put(`${p.slug}/books/${sha}.epub`, new Uint8Array(3000).fill(7), { httpMetadata: { contentType: "application/epub+zip" } }); await env.MEDIA.put(`${p.slug}/photos/${sha}.jpg`, new Uint8Array(200).fill(9), { httpMetadata: { contentType: "image/jpeg" } }); const id = await put(p, "book", { title, author: "A. Example", file, cover, format: "epub", status: "reading", rating: 4, review: "Mine alone", isbn: `978${String(Math.floor(Math.random() * 1e10)).padStart(10, "0")}`, ...extra }); return { id, file, cover }; } function send(from: Person, to: Person, table: string, id: string): Promise<{ status: number; body: Body; payload?: Payload }> { return sendSealed(from, to, table, id); } function keep(p: Person, item: Body, tell = false): Promise<{ status: number; body: Body }> { return keepSealed(p, p.key, item, tell); } /** What the receiver's phone reads of an offer once it opens the box. */ async function opened(p: Person, item: Body): Promise { return openBox(p.key, String(item.id), String(item.box)); } function counts(payload: Payload): Record { const out: Record = {}; for (const r of payload.records) out[r.table] = (out[r.table] ?? 0) + 1; return out; } async function offered(p: Person, count = 1): Promise { let items: Body[] = []; await vi.waitFor(async () => { const res = await p.ask<{ in: Body[] }>("GET", "/v1/send/inbox"); items = res.body.in.filter((i) => i.state !== "undone"); if (items.length < count) throw new Error(`${items.length} of ${count}`); }, { timeout: 3000, interval: 20 }); return items; } async function settle(): Promise { await new Promise((resolve) => setTimeout(resolve, 200)); } /** Every value the object keeps, as text: its SQLite tables and its rows, for a test that none of them reads as what was sent. */ function everything(p: Person): Promise { return inObject(p.slug, (_b, sql) => { const tables = 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(({ name }) => JSON.stringify(sql.exec(`SELECT * FROM "${name}"`).toArray())).join("\n"); }); } describe("a book with its file", () => { it("arrives as a sealed offer the object cannot read, joins nothing until Keep, then lands as the receiver's own with its bytes copied", async () => { const { a, b } = await people(); const made = await book(a); const sent = await send(a, b, "book", made.id); expect(sent.status, JSON.stringify(sent.body)).toBe(200); expect(sent.body).toMatchObject({ state: "offered", bytes: 3200 }); expect(sent.payload!.title).toBe("The Synthetic Garden"); const [item] = await offered(b); expect(item).toMatchObject({ from: a.phone.number, table: "book", bytes: 3200, state: "offered", fits: true }); expect(String(item!.box).startsWith("p1:")).toBe(true); expect(item!.title, "the title is inside the box").toBeUndefined(); const payload = await opened(b, item!); expect(payload).toMatchObject({ title: "The Synthetic Garden", root: { table: "book" }, from: { number: a.phone.number, name: "Test Sender" } }); expect(payload.records[0]!.data.rating, "the sender's own rating never travels").toBeUndefined(); expect(await rows(b, "book"), "nothing joins the receiver's records before Keep").toHaveLength(0); // The cover draws from the offer before Keep. const cover = await SELF.fetch(`${OPEN}/v1/send/${String(item!.id)}/media?key=${encodeURIComponent(made.cover)}`, { headers: bearer(b.phone.credential) }); expect(cover.status).toBe(200); expect((await cover.arrayBuffer()).byteLength).toBe(200); const kept = await keep(b, item!, true); expect(kept.status, JSON.stringify(kept.body)).toBe(200); expect(kept.body).toMatchObject({ state: "kept" }); const [landed] = await rows(b, "book"); expect(landed!.id).not.toBe(made.id); expect(kept.body.landed).toEqual({ table: "book", id: landed!.id }); expect(landed!.data).toMatchObject({ title: "The Synthetic Garden", sent_by: "Test Sender", sent_by_number: a.phone.number, send_id: item!.id }); for (const own of ["rating", "review"]) expect(landed!.data[own] ?? null, own).toBeNull(); expect(landed!.data.status ?? null, "the sender's reading never travels").not.toBe("reading"); expect(String(landed!.data.file).startsWith(`${b.db}/books/`)).toBe(true); const copied = await env.MEDIA.get(`${b.slug}/books/${String(landed!.data.file).split("/").pop()}`); expect((await copied!.arrayBuffer()).byteLength).toBe(3000); expect(await inObject(b.slug, (x) => Number(x.store.meta("media_bytes")))).toBe(3200); // Told kept (the receiver's switch let it), the sender's hold is released. await vi.waitFor(async () => expect((await a.ask<{ out: Body[] }>("GET", "/v1/send/inbox")).body.out[0]).toMatchObject({ state: "kept" })); expect(await inObject(a.slug, (_x, sql) => sql.exec("SELECT count(*) AS n FROM send_hold").one().n)).toBe(0); // Keeping twice lands nothing twice. expect((await b.ask("POST", "/v1/send/keep", { id: item!.id })).body).toMatchObject({ state: "kept", landed: { table: "book", id: landed!.id } }); expect(await rows(b, "book")).toHaveLength(1); }); it("keeps its bytes for the copy when the sender erases the book before Keep", async () => { const { a, b } = await people(); const made = await book(a); await send(a, b, "book", made.id); const [item] = await offered(b); // The sender's erase asks for the bytes to go; the open send holds them. await inObject(a.slug, (x) => x.store.dropMediaLater(made.file)); await a.ask("GET", "/v1/send/inbox"); expect(await env.MEDIA.head(`${a.slug}/${made.file.slice(a.db.length + 1)}`)).not.toBeNull(); expect((await keep(b, item!)).body).toMatchObject({ state: "kept" }); }); }); describe("sealed all the way (R5)", () => { it("routes a note and a todo (and a photo or message row once its table sends) without either object holding a readable value of any", async () => { const { a, b } = await people(); // Each value carries a word nothing else on either object holds (a kit's own words name passports and platforms). const secret = { note: "Zanzibar ferry Qvornek at dawn", todo: "Renew the Plimzat passport", photo: "Lighthouse Kovalam Drusket", message: "Meet at Wexhollow nine" }; const sha = "a".repeat(64); await env.MEDIA.put(`${a.slug}/photos/${sha}.jpg`, new Uint8Array(500).fill(3), { httpMetadata: { contentType: "image/jpeg" } }); const sendable = (await inObject(a.slug, (x) => x.store.definitions("table").filter((t) => t.send).map((t) => String(t.id)))) as string[]; const records: [string, string][] = [["note", await put(a, "note", { title: secret.note, body: secret.note })]]; if (sendable.includes("todo")) records.push(["todo", await put(a, "todo", { title: secret.todo })]); if (sendable.includes("photo")) records.push(["photo", await put(a, "photo", { caption: secret.photo, title: secret.photo, file: `${a.db}/photos/${sha}.jpg` })]); if (sendable.includes("message")) records.push(["message", await put(a, "message", { body: secret.message, sent_at: new Date().toISOString() })]); for (const [table, id] of records) expect((await send(a, b, table, id)).status, table).toBe(200); const items = await offered(b, records.length); for (const item of items) { const payload = await opened(b, item); expect(JSON.stringify(payload)).toMatch(/Qvornek|Plimzat|Drusket|Wexhollow/); } // The wire and both objects carry only boxes and outsides. const words = ["Qvornek", "Plimzat", "Drusket", "Wexhollow"]; for (const p of [a, b]) { // What Send keeps on either object holds nothing of them (the sender's own rows are its own: this test wrote them plain, as an unsealed table's sync would). const sendTables = await inObject(p.slug, (_b, sql) => ["send_out", "send_in", "send_hold", "send_copy"].map((t) => JSON.stringify(sql.exec(`SELECT * FROM ${t}`).toArray())).join("\n")); for (const w of words) expect(holdsWord(sendTables, w), `${w} in ${p === a ? "the sender's" : "the receiver's"} send tables`).toBe(false); } // Nothing anywhere on the receiver's object reads as any of them before Keep. const receiver = await everything(b); for (const w of words) expect(receiver, `${w} on the receiver's object`).not.toContain(w); // Opened by the receiver, each lands as the receiver's own: the phone writes it. for (const item of items) expect((await keep(b, item)).body).toMatchObject({ state: "kept" }); expect((await rows(b, "note")).map((r) => r.data.title)).toContain(secret.note); }); it("hands a person's sharing key only to their people; anyone else, and a number not on Cotton, gets a made-up key that looks the same", async () => { const { a, b } = await people(); const c = await person(); const asked = await a.ask<{ key: string }>("GET", `/v1/send/key?number=${encodeURIComponent(b.number)}`); expect(asked.body.key).toBe(b.key); // c is nobody's: c's own object refuses a lookup of someone c never added, as a send to them is refused. expect((await c.ask("GET", `/v1/send/key?number=${encodeURIComponent(a.number)}`)).status).toBe(403); // c added a, but a never accepted c: c is answered a made-up key, never a's. await c.phone.say("accept", a.number); const unaccepted = await c.ask<{ key: string }>("GET", `/v1/send/key?number=${encodeURIComponent(a.number)}`); expect(unaccepted.status).toBe(200); expect(unaccepted.body.key).not.toBe(a.key); expect(unaccepted.body.key).toMatch(/^[A-Za-z0-9_-]{43}$/); // a accepts c: both accepted now, c is answered a's real key. await a.phone.say("accept", c.number); expect((await c.ask<{ key: string }>("GET", `/v1/send/key?number=${encodeURIComponent(a.number)}`)).body.key).toBe(a.key); // b blocks a: a is answered a made-up key, stable, shaped like a real one, and never b's. await b.phone.say("block", a.number); const blocked = await a.ask<{ key: string }>("GET", `/v1/send/key?number=${encodeURIComponent(b.number)}`); expect(blocked.status).toBe(200); expect(blocked.body.key).not.toBe(b.key); expect(blocked.body.key).toMatch(/^[A-Za-z0-9_-]{43}$/); expect((await a.ask<{ key: string }>("GET", `/v1/send/key?number=${encodeURIComponent(b.number)}`)).body.key).toBe(blocked.body.key); // A number on nobody's Cotton, once a has added it, is answered the same way. await a.ask("POST", "/v1/chat/accept", { number: "+919000077777" }); const nobody = await a.ask<{ key: string }>("GET", "/v1/send/key?number=%2B919000077777"); expect(nobody.status).toBe(200); expect(nobody.body.key).toMatch(/^[A-Za-z0-9_-]{43}$/); }); it("hands a person's signing key beside the sharing key, only to their people (the Circle's safety number); null while none is posted", async () => { const { a, b } = await people(); const sign = "S".repeat(43); expect((await a.ask<{ sign: string | null }>("GET", `/v1/send/key?number=${encodeURIComponent(b.number)}`)).body.sign).toBeNull(); expect((await b.ask("POST", "/v1/send/key", { key: b.key, sign })).status).toBe(200); expect((await a.ask<{ sign: string }>("GET", `/v1/send/key?number=${encodeURIComponent(b.number)}`)).body.sign).toBe(sign); // b blocks a: a is answered a made-up signing key, shaped like a real one, never b's. await b.phone.say("block", a.number); const blocked = await a.ask<{ sign: string }>("GET", `/v1/send/key?number=${encodeURIComponent(b.number)}`); expect(blocked.body.sign).not.toBe(sign); expect(blocked.body.sign).toMatch(/^[A-Za-z0-9_-]{43}$/); }); it("tells one of a person's people that no phone has posted the key yet, never a key nobody can open; a stranger still gets a made-up one", async () => { const a = await person(); const b = await person(false); const stranger = await person(); await a.phone.say("accept", b.number); await b.phone.say("accept", a.number); const early = await a.ask<{ code: string }>("GET", `/v1/send/key?number=${encodeURIComponent(b.number)}`); expect(early.status).toBe(409); expect(early.body.code).toBe("send_key_not_yet"); // A stranger who added b, unanswered, is told nothing new: a made-up key, as before. await stranger.phone.say("accept", b.number); const told = await stranger.ask<{ key: string }>("GET", `/v1/send/key?number=${encodeURIComponent(b.number)}`); expect(told.status).toBe(200); expect(told.body.key).toMatch(/^[A-Za-z0-9_-]{43}$/); // b's phone posts its key: a is answered it. b.key = await postSharingKey(b); expect((await a.ask<{ key: string }>("GET", `/v1/send/key?number=${encodeURIComponent(b.number)}`)).body.key).toBe(b.key); }); it("refuses a send in the clear by name, and a box that is not one", async () => { const { a, b } = await people(); const made = await book(a); const clear = await a.ask("POST", "/v1/send/make", { table: "book", id: made.id, to: b.number }); expect(clear.status).toBe(400); expect(JSON.stringify(clear.body)).toContain("send_sealed_only"); const bad = await a.ask("POST", "/v1/send/make", { id: "abcdefgh1234", to: b.number, box: "{\"title\":\"plain\"}", table: "book", files: [] }); expect(bad.status).toBe(400); const foreign = await a.ask("POST", "/v1/send/make", { id: "abcdefgh1235", to: b.number, box: "p1:AAAA", table: "book", files: [{ key: `${b.db}/books/x.epub` }] }); expect(foreign.status, "a send names only its own database's media").toBe(400); }); it("copies at Keep only bytes the send names, into the receiver's own database", async () => { const { a, b } = await people(); const made = await book(a); await send(a, b, "book", made.id); const [item] = await offered(b); const stray = await b.ask("POST", "/v1/send/keep", { id: item!.id, copies: [{ from: `${a.db}/books/other.epub`, to: `${b.db}/books/other.epub`, bytes: 1 }], root: { table: "book", id: "x1" } }); expect(stray.status).toBe(400); const away = await b.ask("POST", "/v1/send/keep", { id: item!.id, copies: [{ from: made.file, to: `${a.db}/books/mine.epub`, bytes: 3000 }], root: { table: "book", id: "x1" } }); expect(away.status).toBe(400); }); }); describe("a highlight alone", () => { it("lands with a shelf book made from the book's identity, never its file", async () => { const { a, b } = await people(); const made = await book(a); const h = await put(a, "highlight", { book: made.id, text: "A sentence worth keeping.", note: "Why", colour: "teal", chapter: "Three", locator: "{}" }); await send(a, b, "highlight", h); const [item] = await offered(b); expect(item!.bytes, "only the cover travels").toBe(200); await keep(b, item!); const [kept] = await rows(b, "highlight"); const [shelf] = await rows(b, "book"); expect(kept!.data.book).toBe(shelf!.id); expect(shelf!.data.file ?? null).toBeNull(); expect(shelf!.data.title).toBe("The Synthetic Garden"); }); }); describe("a list", () => { it("sends its records, and a book the receiver holds by its ISBN joins the list as theirs", async () => { const { a, b } = await people(); const one = await book(a, "First Test Book"); const two = await book(a, "Second Test Book", { isbn: "9780000000099" }); const list = await put(a, "record_group", { table_id: "book", name: "For the train" }); await put(a, "group_member", { group: list, record_id: one.id, place: 1 }); await put(a, "group_member", { group: list, record_id: two.id, place: 2 }); const mine = await put(b, "book", { title: "My own copy", isbn: "9780000000099" }); await send(a, b, "record_group", list); const [item] = await offered(b); expect(counts(await opened(b, item!))).toEqual({ record_group: 1, book: 2, group_member: 2 }); await keep(b, item!); const books = await rows(b, "book"); expect(books).toHaveLength(2); const members = (await rows(b, "group_member")).map((m) => m.data.record_id); expect(members).toContain(mine); expect(members).toContain(books.find((x) => x.id !== mine)!.id); }); }); describe("a duplicate", () => { it("says the receiver holds it already and makes nothing again", async () => { const { a, b } = await people(); const made = await book(a); const theirs = await put(b, "book", { title: "Held", isbn: (await inObject(a.slug, (x) => x.store.get("book", made.id)!.data.isbn)) as string }); await send(a, b, "book", made.id); const [item] = await offered(b); const payload = await opened(b, item!); expect((await held(b, payload)).find((h) => h.table === "book")).toMatchObject({ table: "book", id: theirs }); expect((await keep(b, item!)).body).toMatchObject({ state: "kept", landed: { table: "book", id: theirs } }); expect(await rows(b, "book")).toHaveLength(1); }); }); describe("a trusted person", () => { it("is said trusted on each arrival, for the receiver's phone to keep it as it arrives", async () => { const { a, b } = await people(); expect((await b.ask("POST", "/v1/send/trust", { number: a.phone.number, trusted: true })).status).toBe(200); await send(a, b, "book", (await book(a)).id); const [item] = await offered(b); expect(item, "the card says its sender is trusted").toMatchObject({ trusted: true, state: "offered" }); expect((await keep(b, item!)).body).toMatchObject({ state: "kept" }); expect(await rows(b, "book")).toHaveLength(1); }); }); describe("too big", () => { it("refuses Keep in words when it will not fit, and keeps nothing", async () => { const { a, b } = await people(); await inObject(b.slug, (x) => { x.caps.media = 1000; }); await send(a, b, "book", (await book(a)).id); const [item] = await offered(b); expect(item).toMatchObject({ fits: false, words: "This needs 3 KB and your Cotton has 1 KB free." }); const kept = await keep(b, item!); expect(kept.status).toBe(413); expect(JSON.stringify(kept.body)).toContain("This needs 3 KB"); expect(await rows(b, "book")).toHaveLength(0); }); }); describe("expired", () => { it("goes from both objects after two weeks, and the sender's hold with it", async () => { const { a, b } = await people(); await send(a, b, "book", (await book(a)).id); await offered(b); const old = Date.now() - EXPIRES_MS - 1000; await inObject(b.slug, (_x, sql) => sql.exec("UPDATE send_in SET at = ?", old)); await inObject(a.slug, (_x, sql) => sql.exec("UPDATE send_out SET at = ?", old)); expect((await b.ask<{ in: Body[] }>("GET", "/v1/send/inbox")).body.in).toHaveLength(0); expect((await a.ask<{ out: Body[] }>("GET", "/v1/send/inbox")).body.out[0]).toMatchObject({ state: "expired" }); expect(await inObject(a.slug, (_x, sql) => sql.exec("SELECT count(*) AS n FROM send_hold").one().n)).toBe(0); }); }); describe("blocked and removed", () => { it("drops a blocked person's send unsaid: the sender is answered as ever", async () => { const { a, b } = await people(); await b.phone.say("block", a.phone.number); const sent = await send(a, b, "book", (await book(a)).id); expect(sent.status).toBe(200); await settle(); expect((await b.ask<{ in: Body[] }>("GET", "/v1/send/inbox")).body.in).toHaveLength(0); }); it("stops sends both ways once either removes the other", async () => { const { a, b } = await people(); const r = await open("POST", "/v1/chat/remove", { number: b.phone.number }, bearer(a.phone.credential)); expect(r.status).toBe(200); const refused = await send(a, b, "book", (await book(a)).id); expect(refused.status).toBe(403); expect(JSON.stringify(refused.body)).toContain("one of your people"); // B still holds A, but A's object no longer takes B's sends. const back = await send(b, a, "book", (await book(b)).id); expect(back.status).toBe(200); await settle(); expect((await a.ask<{ in: Body[] }>("GET", "/v1/send/inbox")).body.in).toHaveLength(0); }); it("never sends to a stranger", async () => { const a = await person(); const c = await person(); expect((await send(a, c, "book", (await book(a)).id)).status).toBe(403); }); }); describe("decline and undo", () => { it("leaves nothing behind when declined", async () => { const { a, b } = await people(); await send(a, b, "book", (await book(a)).id); const [item] = await offered(b); expect((await b.ask("POST", "/v1/send/decline", { id: item!.id, tell: true })).status).toBe(200); expect(await inObject(b.slug, (_x, sql) => sql.exec("SELECT count(*) AS n FROM send_in").one().n)).toBe(0); expect(await rows(b, "book")).toHaveLength(0); await vi.waitFor(async () => expect((await a.ask<{ out: Body[] }>("GET", "/v1/send/inbox")).body.out[0]).toMatchObject({ state: "declined" })); }); }); describe("the sender's Undo", () => { it("takes back an offer not yet kept: it goes from the receiver, and the sender's hold with it", async () => { const { a, b } = await people(); const made = (await send(a, b, "book", (await book(a)).id)).body; await offered(b); expect((await a.ask("POST", "/v1/send/undo", { id: made.id })).body).toEqual({ removed: 0, state: "undone" }); expect(await inObject(a.slug, (_x, sql) => sql.exec("SELECT count(*) AS n FROM send_hold").one().n)).toBe(0); await vi.waitFor(async () => expect((await b.ask<{ in: Body[] }>("GET", "/v1/send/inbox")).body.in).toHaveLength(0)); expect((await a.ask<{ out: Body[] }>("GET", "/v1/send/inbox")).body.out[0]).toMatchObject({ state: "undone" }); }); it("cannot take back what was kept: it is the receiver's", async () => { const { a, b } = await people(); const made = (await send(a, b, "book", (await book(a)).id)).body; const [item] = await offered(b); await keep(b, item!, true); await vi.waitFor(async () => expect((await a.ask<{ out: Body[] }>("GET", "/v1/send/inbox")).body.out[0]).toMatchObject({ state: "kept" })); const undone = await a.ask("POST", "/v1/send/undo", { id: made.id }); expect(undone.status).toBe(409); expect(await rows(b, "book")).toHaveLength(1); }); }); describe("a large file", () => { it("copies on the alarm in parts that carry on where they stopped, and is kept when the last part has", async () => { const was = { ...COPY }; Object.assign(COPY, { inline: 1024 * 1024, part: 5 * 1024 * 1024, perPass: 1 }); try { const { a, b } = await people(); const sha = "f".repeat(64); const size = 11 * 1024 * 1024; const bytes = new Uint8Array(size); for (let i = 0; i < size; i += 4096) bytes[i] = (i / 4096) % 251; await env.MEDIA.put(`${a.slug}/books/${sha}.pdf`, bytes, { httpMetadata: { contentType: "application/pdf" } }); const id = await put(a, "book", { title: "A Large Test Book", file: `${a.db}/books/${sha}.pdf`, format: "pdf" }); await send(a, b, "book", id); const [item] = await offered(b); const kept = await keep(b, item!); expect(kept.body).toMatchObject({ state: "keeping", copied: { bytes: size, done: 0 } }); expect(await rows(b, "book"), "the rows wait for the bytes").toHaveLength(0); const stub = env.BUSINESS.get(env.BUSINESS.idFromName(b.slug)); const state = async (): Promise => (await b.ask<{ in: Body[] }>("GET", "/v1/send/inbox")).body.in[0]!.state; for (let pass = 0; pass < 5 && (await state()) !== "kept"; pass++) await runDurableObjectAlarm(stub); expect(await state()).toBe("kept"); // Kept, the receiver's phone writes the rows it planned. const planned = await landing(b, await opened(b, item!)); if ("error" in planned) throw new Error(planned.error); await writeRows(b, planned.ok); const [landed] = await rows(b, "book"); expect(landed!.data.file).toBe(`${b.db}/books/${sha}.pdf`); const copied = new Uint8Array(await (await env.MEDIA.get(`${b.slug}/books/${sha}.pdf`))!.arrayBuffer()); expect(copied.length).toBe(size); expect(copied[4096 * 300]).toBe(bytes[4096 * 300]); expect(await inObject(b.slug, (x) => Number(x.store.meta("media_bytes")))).toBe(size); } finally { Object.assign(COPY, was); } }); }); describe("a film", () => { it("copies its HLS folder whole under the receiver's new id, with its seasons and episodes, never its watch state nor its original", async () => { const { a, b } = await people(); const film = crypto.randomUUID(); // Its original's pieces and index lie in the folder too, and stay home: a send carries the stream. for (const [name, bytes] of [["master.m3u8", 40], ["v0.m3u8", 30], ["seg-1.m4s", 900], ["poster.jpg", 100], ["original/piece-000000.bin", 5000], ["original/index.json", 60]] as const) { await env.MEDIA.put(`${a.slug}/films/${film}/${name}`, new Uint8Array(bytes).fill(1)); } await put(a, "film", { title: "A Test Series", kind: "series", file: `${a.db}/films/${film}/master.m3u8`, status: "watching", rating: 3, imdb_id: "tt0000001" }, film); const season = await put(a, "film_season", { film, number: 1, title: "Season 1" }); await put(a, "film_episode", { season, series: film, number: 1, title: "Pilot", status: "watched" }); await send(a, b, "film", film); const [item] = await offered(b); expect(item!.bytes).toBe(1070); expect(counts(await opened(b, item!))).toEqual({ film: 1, film_season: 1, film_episode: 1 }); expect((await keep(b, item!)).body).toMatchObject({ state: "kept" }); const [kept] = await rows(b, "film"); expect(kept!.data.file).toBe(`${b.db}/films/${kept!.id}/master.m3u8`); expect(kept!.data.rating ?? null).toBeNull(); const copied = await env.MEDIA.list({ prefix: `${b.slug}/films/${kept!.id}/` }); expect(copied.objects.map((o) => o.key.split("/").pop()).sort()).toEqual(["master.m3u8", "poster.jpg", "seg-1.m4s", "v0.m3u8"]); const [s1] = await rows(b, "film_season"); const [e1] = await rows(b, "film_episode"); expect(s1!.data.film).toBe(kept!.id); expect(e1!.data).toMatchObject({ season: s1!.id, series: kept!.id, title: "Pilot" }); expect(e1!.data.status ?? "unwatched").not.toBe("watched"); }); }); describe("a note and a person", () => { it("land on the receiver's tables: a note's words, a person's card and handles, never what the sender kept of them", async () => { const { a, b } = await people(); const note = await put(a, "note", { title: "Test note", body: "Synthetic words.", pinned: true }); const who = await put(a, "person", { full_name: "Test Person", org: "Example Org", summary: "the sender's own summary" }); await put(a, "person_handle", { person_id: who, kind: "phone", value: "+15550100009", normalised: "+15550100009" }); await send(a, b, "note", note); await send(a, b, "person", who); for (const i of await offered(b, 2)) expect((await keep(b, i)).body).toMatchObject({ state: "kept" }); const [n1] = await rows(b, "note"); expect(n1!.data).toMatchObject({ title: "Test note", body: "Synthetic words." }); expect(n1!.data.pinned ?? false).toBe(false); const [p1] = (await rows(b, "person")).filter((r) => r.data.sent_by_number === a.phone.number); expect(p1!.data).toMatchObject({ full_name: "Test Person", org: "Example Org" }); expect(p1!.data.summary ?? null).toBeNull(); const [h1] = (await rows(b, "person_handle")).filter((r) => r.data.sent_by_number === a.phone.number); expect(h1!.data).toMatchObject({ person_id: p1!.id, value: "+15550100009" }); }); }); describe("adding a person by number (Send's Add a person, any Cotton app)", () => { it("adds a number typed as a person would, shows them waiting until they add back, and waiting again once they remove", async () => { const a = await person(); const b = await person(); const spaced = `${b.phone.number.slice(0, 3)} ${b.phone.number.slice(3, 8)}-${b.phone.number.slice(8)}`; const added = await a.ask("POST", "/v1/chat/accept", { number: spaced }); expect(added.status, JSON.stringify(added.body)).toBe(200); const asked = async (): Promise => (await a.ask<{ people: Body[] }>("GET", "/v1/send/people")).body.people; expect(await asked(), "the number is kept as sign-in keeps it; they have not added a back").toEqual([{ number: b.phone.number, name: null, trusted: false, waiting: true }]); await b.phone.say("accept", a.phone.number); expect(await asked()).toEqual([{ number: b.phone.number, name: null, trusted: false, waiting: false }]); expect((await b.ask("POST", "/v1/chat/remove", { number: a.phone.number })).status).toBe(200); expect(await asked(), "removed by them, a waits as if never added back").toEqual([{ number: b.phone.number, name: null, trusted: false, waiting: true }]); }); it("refuses only the owner's own number; any other valid number answers the same, on Cotton or not", async () => { const a = await person(); const b = await person(); const own = await a.ask("POST", "/v1/chat/accept", { number: a.phone.number }); expect(own.status).toBe(400); expect(JSON.stringify(own.body)).toContain("That is your own number. Add someone else's."); const nobody = await a.ask("POST", "/v1/chat/accept", { number: "+919000099999" }); const somebody = await a.ask("POST", "/v1/chat/accept", { number: b.phone.number }); expect([nobody.status, nobody.body]).toEqual([somebody.status, somebody.body]); expect(nobody.body).toEqual({ ok: true }); const listed = await a.ask<{ people: Body[] }>("GET", "/v1/chat/people"); expect(listed.body.people.map((p) => [p.number, p.waiting])).toEqual( expect.arrayContaining([["+919000099999", true], [b.phone.number, true]]), ); expect((await a.ask("POST", "/v1/chat/accept", { number: "98765" })).status).toBe(400); }); it("leaves an ask with the person added, naming the asker; accepted it makes both people, refused or blocked it goes", async () => { const a = await person(); const b = await person(); const c = await person(); await inObject(a.slug, (_x, sql) => sql.exec("UPDATE people SET name = 'Test Asker' WHERE phone = ?", a.phone.number)); await a.ask("POST", "/v1/chat/accept", { number: b.phone.number }); await c.ask("POST", "/v1/chat/accept", { number: b.phone.number }); let asking: Body[] = []; await vi.waitFor(async () => { asking = (await b.ask<{ asking: Body[] }>("GET", "/v1/chat/people")).body.asking; if (asking.length < 2) throw new Error(`${asking.length} asks`); }, { timeout: 3000, interval: 20 }); expect(asking.map((x) => x.number).sort()).toEqual([a.phone.number, c.phone.number].sort()); expect(asking.find((x) => x.number === a.phone.number)!.name, "the ask carries the asker's account name").toBe("Test Asker"); expect((await b.ask("POST", "/v1/chat/accept", { number: a.phone.number })).status).toBe(200); expect((await b.ask("POST", "/v1/chat/refuse", { number: c.phone.number })).status).toBe(200); const after = (await b.ask<{ people: Body[]; asking: Body[] }>("GET", "/v1/chat/people")).body; expect(after.asking).toEqual([]); expect(after.people).toEqual([{ number: a.phone.number, name: "Test Asker", waiting: false }]); const theirs = (await a.ask<{ people: Body[] }>("GET", "/v1/chat/people")).body.people; expect(theirs).toEqual([expect.objectContaining({ number: b.phone.number, waiting: false })]); // c's add stands on c's side, waiting; c asking again after a block leaves nothing. await b.phone.say("block", c.phone.number); await c.ask("POST", "/v1/chat/remove", { number: b.phone.number }); await c.ask("POST", "/v1/chat/accept", { number: b.phone.number }); await settle(); expect((await b.ask<{ asking: Body[] }>("GET", "/v1/chat/people")).body.asking, "a blocked person's ask is dropped").toEqual([]); }); it("lists a blocked person under blocked, apart from people and asking (what an older phone reads is as before); unblocked, they return where they were", async () => { const { a, b } = await people(); const c = await person(); await c.ask("POST", "/v1/chat/accept", { number: b.phone.number }); await vi.waitFor(async () => { if ((await b.ask<{ asking: Body[] }>("GET", "/v1/chat/people")).body.asking.length !== 1) throw new Error("no ask yet"); }, { timeout: 3000, interval: 20 }); const before = (await b.ask("GET", "/v1/chat/people")).body; expect(before.blocked).toEqual([]); expect((await b.ask("POST", "/v1/chat/block", { number: a.phone.number })).status).toBe(200); expect((await b.ask("POST", "/v1/chat/block", { number: c.phone.number })).status).toBe(200); const listed = (await b.ask("GET", "/v1/chat/people")).body; // An older phone reads only people and asking: blocked people stay out of both, as before this answer carried them. expect(listed.people).toEqual([]); expect(listed.asking).toEqual([]); expect((listed.blocked as Body[]).map((x) => x.number).sort()).toEqual([a.phone.number, c.phone.number].sort()); expect(Object.keys((listed.blocked as Body[])[0]!).sort()).toEqual(["at", "name", "number"]); // The blocked person learns nothing: b reads to a as never added back, and a still cannot reach b. const theirs = (await a.ask<{ people: Body[]; blocked: Body[] }>("GET", "/v1/chat/people")).body; expect(theirs.people).toEqual([{ number: b.phone.number, name: null, waiting: true }]); expect(theirs.blocked).toEqual([]); // Unblocked, a is one of b's people again with their name, c asks again. expect((await b.ask("POST", "/v1/chat/unblock", { number: a.phone.number })).status).toBe(200); expect((await b.ask("POST", "/v1/chat/unblock", { number: c.phone.number })).status).toBe(200); const after = (await b.ask("GET", "/v1/chat/people")).body; expect(after).toEqual({ ...before, blocked: [] }); expect((await a.ask<{ people: Body[] }>("GET", "/v1/chat/people")).body.people).toEqual([{ number: b.phone.number, name: null, waiting: false }]); }); it("returns a person unblocked from Calling where they were too", async () => { const { a, b } = await people(); await b.ask("POST", "/v1/chat/block", { number: a.phone.number }); expect((await b.ask("POST", "/v1/calls/unblock", { number: a.phone.number })).status).toBe(200); const after = (await b.ask("GET", "/v1/chat/people")).body; expect(after.blocked).toEqual([]); expect((after.people as Body[]).map((p) => p.number)).toEqual([a.phone.number]); }); it("takes an ask back when the asker removes the person", async () => { const a = await person(); const b = await person(); await a.ask("POST", "/v1/chat/accept", { number: b.phone.number }); await vi.waitFor(async () => { if ((await b.ask<{ asking: Body[] }>("GET", "/v1/chat/people")).body.asking.length !== 1) throw new Error("no ask yet"); }, { timeout: 3000, interval: 20 }); await a.ask("POST", "/v1/chat/remove", { number: b.phone.number }); await vi.waitFor(async () => { if ((await b.ask<{ asking: Body[] }>("GET", "/v1/chat/people")).body.asking.length !== 0) throw new Error("ask still held"); }, { timeout: 3000, interval: 20 }); }); }); describe("who can be sent to", () => { it("names everyone this person accepted, by number, with the name a clear Cotton thread gives and their trust", async () => { const { a, b } = await people(); const c = await person(); const d = await person(); const contact = await put(a, "message_contact", { phone_e164: b.phone.number, display_name: "Test Friend" }); await put(a, "thread", { external_key: `cotton:${b.phone.number}`, contact_id: contact, kind: "dm", last_message_at: "2026-11-13T08:00:00.000Z" }); await put(a, "thread", { external_key: `cotton:${c.phone.number}`, kind: "dm", title: "A Stranger" }); await put(a, "thread", { external_key: `cotton:${d.phone.number}`, kind: "dm", request: "pending" }); const asked = (): Promise<{ status: number; body: Body }> => a.ask("GET", "/v1/send/people"); expect((await asked()).body.people, "a thread with someone not accepted, or a request still waiting, names nobody").toEqual([{ number: b.phone.number, name: "Test Friend", trusted: false, waiting: false }]); await a.ask("POST", "/v1/send/trust", { number: b.phone.number, trusted: true }); expect((await asked()).body.people).toEqual([{ number: b.phone.number, name: "Test Friend", trusted: true, waiting: false }]); expect((await a.ask("POST", "/v1/send/trust", { number: c.phone.number, trusted: true })).status, "a stranger is never trusted").toBe(403); }); it("names an accepted person whose Cotton thread is sealed on the phone (no thread on the object), by number alone", async () => { const { a, b } = await people(); expect((await a.ask("GET", "/v1/send/people")).body.people).toEqual([{ number: b.phone.number, name: null, trusted: false, waiting: false }]); await a.phone.say("block", b.phone.number); expect((await a.ask("GET", "/v1/send/people")).body.people, "a blocked person is nobody's").toEqual([]); }); it("takes at most a day's sends from one person", () => { expect(FROM_PEER_DAY).toBeGreaterThan(10); }); });