/** * DEVICE ROWS, PROVEN ON DEV (coordinator, 25 Nov 2026; src/device_reports.ts). One invented +1555 account, ONE * device credential (as the iPhone apps share one keychain group), two apps on it: * 1. Words (build 31) syncs and reports; then Comms (build 37) syncs and reports: in turn. * 2. Words' older report (build 30, an earlier last_exchange_at) lands late: out of order. * 3. An old client reports with no bundleId: still taken (200), written at the top level as before. * After each, list_devices over MCP (the sign-in's owner token) is read for this device's row, and what it says is * printed. Exit 0 only when both apps' newest reports stand and the old client's write was taken. * * pnpm -s exec tsx scripts/device-rows-proof.ts [--base ] [--code-file ] * * Invented data only; nothing secret is printed. */ import { readFileSync } from "node:fs"; import { homedir } from "node:os"; import { signIn } from "./dev-seed/client.ts"; import { devBase } from "./dev-server"; const arg = (name: string, fallback?: string) => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? process.argv[i + 1]! : fallback; }; const DEV = arg("base", devBase())!; if (DEV !== devBase() && !/^http:\/\/127\.0\.0\.1:\d+$/.test(DEV)) throw new Error("--base is the dev Worker or a local wrangler dev"); const CODE = readFileSync(arg("code-file", `${homedir()}/.cotton-credentials/cotton/dev-otp`)!, "utf8").replace(/\D/g, ""); const NUMBER = `+1555${String(Math.floor(1_000_000 + Math.random() * 8_999_999))}`; const say = (line: string) => console.log(`[device-rows] ${line}`); type Answer = { status: number; body: Record }; async function call(method: string, path: string, bearer: string, body?: unknown): Promise { const res = await fetch(`${DEV}${path}`, { method, headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${bearer}` }, body: body === undefined ? undefined : JSON.stringify(body) }); const text = await res.text(); const json = text.trimStart().startsWith("{") ? text : (text.split("\n").find((l) => l.startsWith("data:"))?.slice(5) ?? ""); let parsed: Record = {}; try { parsed = json ? (JSON.parse(json) as Record) : {}; } catch { parsed = { text: text.slice(0, 200) }; } return { status: res.status, body: parsed }; } let failed = 0; function check(ok: boolean, what: string): void { if (!ok) failed++; say(`${ok ? "ok " : "FAIL"} ${what}`); } async function main(): Promise { const s = await signIn(DEV, NUMBER, CODE); say(`signed in an invented number (database ${s.databaseId.slice(0, 8)}…), one device credential`); const page = async (build: string): Promise => { const q = new URLSearchParams({ since: "0", limit: "50", device_name: "Invented iPhone", platform: "ios", app_version: `1.0.0 (${build})` }); const a = await call("GET", `/v1/sync?${q}`, s.credential); if (a.status !== 200 || typeof a.body.device !== "string") throw new Error(`sync answered ${a.status} ${JSON.stringify(a.body).slice(0, 200)}`); return a.body.device; }; const report = (id: string, reported_state: Record) => call("POST", "/v1/act", s.credential, { act: "update", args: { table: "device", id, data: { reported_state } } }); const listed = async (id: string): Promise> => { const a = await call("POST", "/mcp", s.token, { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "list_devices", arguments: {} } }); const result = a.body.result as { structuredContent?: { devices?: Record[] }; content?: { text: string }[] } | undefined; const devices = result?.structuredContent?.devices ?? (JSON.parse(result?.content?.[0]?.text ?? "{}") as { devices?: Record[] }).devices ?? []; const row = devices.find((d) => d.id === id); if (!row) throw new Error(`list_devices has no row ${id} (${a.status})`); return row; }; const show = (row: Record) => { const top = (row.reportedState ?? {}) as Record; say(` list_devices: appVersion ${String(row.appVersion)}; reportedState top: bundleId ${String(top.bundleId ?? "-")} build ${String(top.build ?? "-")} last_exchange_at ${String(top.last_exchange_at ?? "-")}`); for (const a of (row.apps ?? []) as Record[]) say(` apps: ${String(a.bundleId)} build ${String(a.build)} last_exchange_at ${String(a.lastExchangeAt)} last_answer ${String(a.lastAnswer)} unsent ${String(a.unsent)}`); }; const apps = (row: Record) => Object.fromEntries(((row.apps ?? []) as Record[]).map((a) => [String(a.bundleId), a])); const t = Date.now(); const at = (minutesAgo: number) => new Date(t - minutesAgo * 60_000).toISOString(); // 1. In turn: Words, then Comms, on the same credential. const id = await page("31"); check((await report(id, { bundleId: "com.cottondb.notes.dev", build: "31", last_exchange_at: at(2), last_answer: "ok", unsent: 0 })).status === 200, "Words 31 reported on the shared row"); const id2 = await page("37"); check(id2 === id, "Comms 37 on the same credential is filed under the same row"); check((await report(id, { bundleId: "com.cottondb.messages.dev", build: "37", last_exchange_at: at(1), last_answer: "ok", unsent: 10 })).status === 200, "Comms 37 reported on the shared row"); let row = await listed(id); show(row); check(apps(row)["com.cottondb.notes.dev"]?.build === "31" && apps(row)["com.cottondb.messages.dev"]?.build === "37", "in turn: list_devices keeps both apps' reports"); // 2. Out of order: Words' older report lands after Comms'. check((await report(id, { bundleId: "com.cottondb.notes.dev", build: "30", last_exchange_at: at(30), last_answer: "offline", unsent: 4 })).status === 200, "Words' older report (build 30, 30 minutes back) taken without error"); row = await listed(id); show(row); const words = apps(row)["com.cottondb.notes.dev"]; check(words?.build === "31" && words?.lastAnswer === "ok" && words?.unsent === 0, "out of order: the older report did not overwrite Words' newer one"); check((row.reportedState as Record).bundleId === "com.cottondb.messages.dev", "out of order: the top level is still the newest report (Comms')"); // 3. An old client: no bundleId. const old = await report(id, { build: "7", last_answer: "ok", unsent: 0 }); check(old.status === 200, `an old client's report without a bundleId is taken (${old.status})`); row = await listed(id); show(row); check((row.reportedState as Record).build === "7", "old client: its report is written at the top level, as before"); check(apps(row)["com.cottondb.notes.dev"]?.build === "31" && apps(row)["com.cottondb.messages.dev"]?.build === "37", "old client: both apps' reports still stand"); say(failed ? `FAILED ${failed}` : "DEVICE ROWS PROVEN"); process.exit(failed ? 1 : 0); } main().catch((e: unknown) => { say(`FAILED: ${e instanceof Error ? e.message : String(e)}`); process.exit(1); });