Cotton code
216 lines · 15.0 KB · TypeScriptRaw
import { sealRow } from "./seal-device.ts";import { describe, expect, it } from "vitest";import { dmThreadId, groupThreadId, msgContactId, reactionRowId, callLogId } from "../src/import/ids.ts";import { CLEAR_IMPORT_OPEN, DATABASE_ID, http, personalObject, put } from "./personal.ts";/** RULE (coordinator, 26 Oct 2026): the Mac reads sources and the object decides everything — the import engine runs here. */describe("the personal object's import", () => {  const SLUG = "import-personal";  let credential = "";  let owner = "";  const auth = (): Record<string, string> => ({ authorization: `Bearer ${credential}` });  const rows = async (table: string): Promise<{ id: string; data: Record<string, unknown> }[]> => {    const all: { id: string; table: string; data: Record<string, unknown>; deleted?: boolean }[] = [];    let next: string | undefined;    do {      const page = await http<{ rows: typeof all; next?: string }>(SLUG, "GET", next ? `/v1/sync?cursor=${next}` : "/v1/sync?since=0", undefined, auth());      all.push(...page.body.rows);      next = page.body.next;    } while (next);    return all.filter((r) => r.table === table && !r.deleted);  };  const dm = {    workspaceId: DATABASE_ID,    channel: "whatsapp",    dm: { label: "Asha Verma", phone: "919800000001" },    messages: [      { direction: "in", body: "hello there", sentAt: "2026-10-01T10:00:00.000Z", externalId: "wa-1", reactions: [{ emoji: "👍", actor: "owner" }] },      { direction: "out", body: "hi Asha", sentAt: "2026-10-01T10:01:00.000Z", externalId: "wa-2", replyToExternalId: "wa-1" },    ],  };  it("refuses anyone but the owner", async () => {    ({ credential, owner } = await personalObject(SLUG, CLEAR_IMPORT_OPEN));    const none = await http(SLUG, "POST", "/v1/import/messages", dm);    expect(none.status).toBe(403);  });  it("applies a dm batch: the contact, the thread, the messages, the reaction and the reply link, under the Rust engine's ids", async () => {    const res = await http<{ threadId: string; applied: Record<string, number>; skipped: number; unresolvedReplies: number }>(SLUG, "POST", "/v1/import/messages", dm, auth());    expect(res.status, JSON.stringify(res.body)).toBe(200);    const contact = msgContactId(DATABASE_ID, "919800000001");    expect(res.body.threadId).toBe(dmThreadId(DATABASE_ID, contact));    expect(res.body.applied).toEqual({ messages: 2, threads: 1, people: 1, reactions: 1 });    expect(res.body.unresolvedReplies).toBe(0);    const messages = await rows("message");    const first = messages.find((m) => m.data.external_id === "wa-1")!;    const second = messages.find((m) => m.data.external_id === "wa-2")!;    expect(second.data.reply_to_id).toBe(first.id);    const [thread] = await rows("thread");    expect(thread!.data).toMatchObject({ contact_id: contact, kind: "dm", last_message_at: "2026-10-01T10:01:00.000Z", last_message_preview: "hi Asha" });    const [reaction] = await rows("message_reaction");    expect(reaction!.id).toBe(reactionRowId(first.id, "self"));    const [c] = await rows("message_contact");    expect(c!.data).toMatchObject({ phone_e164: "919800000001", display_name: "Asha Verma" });  });  it("changes nothing when the same batch comes again", async () => {    const before = await http<{ version: number }>(SLUG, "GET", "/v1/me", undefined, auth());    const res = await http<{ applied: Record<string, number>; skipped: number; version: number }>(SLUG, "POST", "/v1/import/messages", dm, auth());    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body.applied).toEqual({ messages: 0, threads: 0, people: 0, reactions: 0 });    expect(res.body.skipped).toBe(2);    expect(res.body.version).toBe(before.body.version);    expect(await rows("message")).toHaveLength(2);  });  it("lands a group under its key, seats its participants and names each sender", async () => {    const group = {      workspaceId: DATABASE_ID,      channel: "whatsapp",      thread: { kind: "group", title: "Hill Walkers", externalKey: "wa:group:120363000000000001@g.us", participants: [{ label: "Asha Verma", phone: "919800000001" }, { label: "Ravi" }] },      messages: [        { direction: "in", senderLabel: "Ravi", body: "who is in?", sentAt: "2026-10-02T08:00:00.000Z", externalId: "g-1" },        { direction: "in", senderLabel: "Asha Verma", body: "me", sentAt: "2026-10-02T08:01:00.000Z", externalId: "g-2" },      ],    };    const res = await http<{ threadId: string; applied: Record<string, number> }>(SLUG, "POST", "/v1/import/messages", group, auth());    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body.threadId).toBe(groupThreadId(DATABASE_ID, "wa:group:120363000000000001@g.us"));    expect(res.body.applied).toEqual({ messages: 2, threads: 1, people: 0, reactions: 0 });    const seats = await rows("thread_member");    expect(seats.map((s) => s.data.display_name).sort()).toEqual(["Asha Verma", "Ravi"]);    const asha = seats.find((s) => s.data.display_name === "Asha Verma")!;    expect(asha.data.contact_id).toBe(msgContactId(DATABASE_ID, "919800000001"));    const g2 = (await rows("message")).find((m) => m.data.external_id === "g-2")!;    expect(g2.data.sender_participant_id).toBe(asha.id);  });  // RULE (27 Oct 2026): a thread block's participants are the people its inbound messages name. A  // page of the WhatsApp helper's outbox can hold only the owner's own message in a group, and that  // batch carries no participants; refusing it held every later message (live ones too) behind it.  it("lands a group page that holds only the owner's own messages, with no participants", async () => {    const own = {      workspaceId: DATABASE_ID,      channel: "whatsapp",      thread: { kind: "group", title: "Hill Walkers", externalKey: "wa:group:120363000000000001@g.us", participants: [] },      messages: [{ direction: "out", body: "see you at six", sentAt: "2026-10-02T09:00:00.000Z", externalId: "g-own-1" }],    };    const res = await http<{ threadId: string; applied: Record<string, number> }>(SLUG, "POST", "/v1/import/messages", own, auth());    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body.threadId, "the group the earlier page made").toBe(groupThreadId(DATABASE_ID, "wa:group:120363000000000001@g.us"));    expect(res.body.applied.messages).toBe(1);    const mine = (await rows("message")).find((m) => m.data.external_id === "g-own-1")!;    expect(mine.data.direction).toBe("out");    expect(mine.data.thread_id).toBe(res.body.threadId);    expect((await rows("thread_member")).map((s) => s.data.display_name).sort(), "nobody seated, nobody removed").toEqual(["Asha Verma", "Ravi"]);  });  it("finds a contact by a person's handle, and keeps the name the object already has", async () => {    await put(SLUG, [      { verb: "put", table: "person", id: "p-meera", data: { full_name: "Meera Iyer" } },      { verb: "put", table: "person_handle", id: "h-meera", data: { person_id: "p-meera", kind: "phone", value: "+91 98000 00002", normalised: "919800000002" } },    ]);    const res = await http(SLUG, "POST", "/v1/import/messages", { workspaceId: DATABASE_ID, channel: "whatsapp", messages: [{ phone: "919800000002", direction: "in", body: "hey", sentAt: "2026-10-03T09:00:00.000Z", externalId: "m-1" }] }, auth());    expect(res.status, JSON.stringify(res.body)).toBe(200);    const contact = (await rows("message_contact")).find((c) => c.id === msgContactId(DATABASE_ID, "919800000002"))!;    expect(contact.data).toMatchObject({ person_id: "p-meera", display_name: "Meera Iyer" });  });  it("takes a full batch: 500 messages with 20 attachments, replies and reactions, and skips all 500 the second time", async () => {    const t0 = Date.parse("2026-09-01T00:00:00.000Z");    const full = {      workspaceId: DATABASE_ID,      channel: "whatsapp",      dm: { label: "Kiran Rao", phone: "919800000050" },      messages: Array.from({ length: 500 }, (_, i) => ({        direction: i % 3 ? "in" : "out",        body: `line ${i}`,        sentAt: new Date(t0 + i * 61_000).toISOString(),        externalId: `full-${i}`,        ...(i % 25 === 0 ? { media: [{ key: `${DATABASE_ID}/messages/m/${String(i).padStart(64, "0")}.jpg`, contentType: "image/jpeg" }] } : {}),        ...(i % 10 === 5 ? { replyToExternalId: `full-${i - 1}` } : {}),        ...(i % 7 === 0 ? { reactions: [{ emoji: "❤️", actor: "owner" }] } : {}),      })),    };    const first = await http<{ applied: Record<string, number>; unresolvedReplies: number }>(SLUG, "POST", "/v1/import/messages", full, auth());    expect(first.status, JSON.stringify(first.body)).toBe(200);    expect(first.body.applied).toEqual({ messages: 500, threads: 1, people: 1, reactions: 72 });    expect(first.body.unresolvedReplies).toBe(0);    const again = await http<{ applied: Record<string, number>; skipped: number }>(SLUG, "POST", "/v1/import/messages", full, auth());    expect(again.body.applied.messages).toBe(0);    expect(again.body.skipped).toBe(500);  });  it("refuses a batch that breaks the contract, naming the first problem as the Rust names it", async () => {    const bad = await http<{ message: string }>(SLUG, "POST", "/v1/import/messages", { ...dm, messages: [{ ...dm.messages[0], sentAt: "yesterday" }] }, auth());    expect(bad.status).toBe(400);    expect(bad.body.message).toBe('messages[0].sentAt: expected an ISO-8601 instant, got "yesterday"');    const many = Array.from({ length: 501 }, (_, i) => ({ direction: "in", body: `m${i}`, sentAt: "2026-10-01T10:00:00.000Z", externalId: `x-${i}` }));    const big = await http<{ message: string }>(SLUG, "POST", "/v1/import/messages", { ...dm, messages: many }, auth());    expect(big.body.message).toBe("batch.messages: 501 exceeds the 500-message cap");    const other = await http<{ code: string }>(SLUG, "POST", "/v1/import/messages", { ...dm, workspaceId: "22222222-2222-4222-8222-222222222222" }, auth());    expect(other.body.code).toBe("wrong_database");    const nameless = await http<{ message: string }>(SLUG, "POST", "/v1/import/messages", { workspaceId: DATABASE_ID, channel: "whatsapp", messages: [{ direction: "in", body: "x", sentAt: "2026-10-01T10:00:00.000Z", externalId: "n-1" }] }, auth());    expect(nameless.body.message).toBe("An imported message arrived with no usable phone or email and the batch names no counterpart");  });  it("applies calls once per (source, external id), matched to the contact and its person", async () => {    const calls = [      { source: "callhistory", externalId: "c-1", provider: "phone", direction: "in", outcome: "answered", startedAt: "2026-10-04T12:00:00.000Z", durationS: 61, handle: "+91 98000 00002", handleKind: "phone", name: null, device: "iphone", meta: {} },      { source: "callhistory", externalId: "c-2", provider: "facetime", direction: "out", outcome: "missed", startedAt: "2026-10-04T13:00:00.000Z", durationS: 0, handle: "*123#", handleKind: "phone", name: "Meera Iyer", device: null, meta: { video: true } },    ];    const res = await http<{ applied: Record<string, number> }>(SLUG, "POST", "/v1/import/calls", { calls }, { authorization: `Bearer ${owner}` });    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body.applied).toEqual({ calls: 2, people: 2 });    const held = await rows("call");    const c1 = held.find((c) => c.id === callLogId(DATABASE_ID, "callhistory", "c-1"))!;    expect(c1.data).toMatchObject({ handle: "919800000002", contact_id: msgContactId(DATABASE_ID, "919800000002"), person_id: "p-meera", duration_s: 61 });    const c2 = held.find((c) => c.id === callLogId(DATABASE_ID, "callhistory", "c-2"))!;    expect(c2.data).toMatchObject({ handle: "*123#", contact_id: null, person_id: "p-meera", meta: { video: true } });    const again = await http<{ applied: Record<string, number> }>(SLUG, "POST", "/v1/import/calls", { calls }, { authorization: `Bearer ${owner}` });    expect(again.body.applied.calls).toBe(0);  });});/** The phone queues a message, the Mac reads the queue and marks the row: the outbox (coordinator, 26 Oct 2026). */describe("the personal object's outbox", () => {  const SLUG = "import-outbox";  it("takes the phone's row through /v1/act, lists it by status for the Mac, and takes the Mac's marks", async () => {    const { credential, owner } = await personalObject(SLUG);    const phone = { authorization: `Bearer ${credential}` };    const mac = { authorization: `Bearer ${owner}` };    // The outbox is sealed (e2e rulings R1): the phone sends who and what inside its seal; the Mac, a device, opens them to send.    const id = "out-invented-1";    const made = await http<{ made: { id: string } }>(SLUG, "POST", "/v1/act", { act: "create", args: { table: "outbox", id, data: { channel: "whatsapp", ...(await sealRow(new Uint8Array(32).fill(4), "outbox", id, 1, { to: "919800000001", body: "on my way" })) } } }, phone);    expect(made.status, JSON.stringify(made.body)).toBe(200);    const clear = await http(SLUG, "POST", "/v1/act", { act: "create", args: { table: "outbox", data: { channel: "whatsapp", to: "919800000001", body: "on my way" } } }, phone);    expect((clear.body as { code: string }).code, "a phone never sends the words in the clear").toBe("sealed_in_clear");    const queued = await http<{ rows: { id: string; data: Record<string, unknown> }[] }>(SLUG, "GET", "/v1/outbox?status=queued", undefined, mac);    expect(queued.body.rows.map((r) => [r.id, r.data.status, r.data.channel])).toEqual([[id, "queued", "whatsapp"]]);    expect(String(queued.body.rows[0]!.data.sealed_enc)).toMatch(/^s1:/);    expect(JSON.stringify(queued.body.rows)).not.toContain("on my way");    const marked = await http(SLUG, "POST", "/v1/act", { act: "update", args: { table: "outbox", id, data: { status: "sent", sent_at: "2026-10-26T09:00:00.000Z", sent_external_id: "wa-out-1" } } }, mac);    expect(marked.status, JSON.stringify(marked.body)).toBe(200);    expect((await http<{ rows: unknown[] }>(SLUG, "GET", "/v1/outbox?status=queued", undefined, mac)).body.rows).toEqual([]);    expect((await http<{ rows: unknown[] }>(SLUG, "GET", "/v1/outbox?status=sent", undefined, mac)).body.rows).toHaveLength(1);    expect((await http(SLUG, "GET", "/v1/outbox?status=lost", undefined, mac)).status).toBe(400);    expect((await http(SLUG, "GET", "/v1/outbox")).status).toBe(403);  });});// ROUTES-AUDIT 11 (23 Nov 2026): the old routes never seal on arrival, so a database that seals their tables refuses them.describe("the old message and call import routes on a sealed database", () => {  it("are refused 410 and write nothing in the clear", async () => {    const slug = "import-sealed";    const { owner } = await personalObject(slug);    const auth = { authorization: `Bearer ${owner}` };    for (const [path, body] of [["/v1/import/messages", { workspaceId: DATABASE_ID }], ["/v1/import/message_changes", { workspaceId: DATABASE_ID, changes: [] }], ["/v1/import/calls", { calls: [] }]] as const) {      const res = await http<{ code: string }>(slug, "POST", path, body, auth);      expect([res.status, res.body.code], path).toEqual([410, "decided_on_the_mac"]);    }  });});