/** * Restore an earlier day from the owner's phone, end to end (RESTORE PHONE 2, 28 Nov 2026): * * cd apps/business && pnpm -s exec tsx scripts/__tests__/e2e-restore.ts * E2E_BOX=1 … cargo runs on the Linux box (pnpm box:cargo), the Worker reached through an ssh tunnel * * Starts the Worker under `wrangler dev` on a free port with its own storage (`dev-worker.ts`: ENV_LABEL dev, so the * restore routes answer; nothing here reaches a deployed Worker), onboards an invented owner, signs in a member's phone * and a second owner device, mints an owner key. Then the phone core's walks, in order * (`crates/cotton-ffi/src/phone/restore_e2e.rs`): * * 1. restore_refuses_a_device_that_is_not_the_owners a member's phone and an assistant's key are refused * 2. (here) snapshots on, invented to-dos, a weekly full, one more, a daily, then the damage: every kept to-do deleted * 3. a_restore_interrupted_and_resumed_puts_the_phone_back begun, interrupted with the rows emptied, resumed, back * 4. a_restore_is_refused_once_the_erase_starts the delete begun from the other device: refused * * Last, the admin's own view: not frozen, no restore under way. Synthetic data only; wrangler dev is stopped, the * tunnel closed and the temp dir removed however it ends. */ import { spawn, spawnSync, type ChildProcess } from "node:child_process"; import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { APP, check, OWNER, startDevWorker, stop } from "./dev-worker.ts"; import { WS } from "./fixture.ts"; const REPO = resolve(APP, "../.."); const CRATES = resolve(REPO, "crates"); const MEMBER = "+919000000071"; const BOX = process.env.E2E_BOX === "1"; const tmp = mkdtempSync(join(tmpdir(), "e2e-restore-")); let wrangler: ChildProcess | null = null; let tunnel: ChildProcess | null = null; const cleanup = (): void => { tunnel?.kill("SIGTERM"); tunnel = null; stop(wrangler); wrangler = null; rmSync(tmp, { recursive: true, force: true }); }; process.on("SIGINT", () => { cleanup(); process.exit(130); }); /** One walk of restore_e2e.rs, by name, here or on the box. */ function walk(name: string, env: Record): string { const args = ["test", "-q", "-p", "cotton-ffi", "--lib", `phone::restore::e2e::${name}`, "--", "--ignored", "--nocapture", "--test-threads=1"]; const r = BOX ? spawnSync("bash", [join(REPO, "scripts/box-cargo.sh"), ...args], { cwd: REPO, encoding: "utf8", env: { ...process.env, ...env, BOX_CARGO_ENV: Object.keys(env).join(" ") } }) : spawnSync("cargo", args, { cwd: CRATES, encoding: "utf8", env: { ...process.env, CARGO_BUILD_JOBS: "3", ...env } }); const out = `${r.stdout ?? ""}${r.stderr ?? ""}`; check(r.status === 0, `${name}${r.status === 0 ? "" : `\n${r.error ? String(r.error) : out.slice(-6000)}`}`); for (const line of out.split("\n").filter((l) => l.startsWith("E2E-RESTORE"))) console.log(` ${line}`); return out; } try { const started = await startDevWorker(tmp, WS, (child) => { wrangler = child; }); const { base, admin, credential } = started; // wrangler dev may reload while cargo runs (a watched file touched by the box's sync): a call that met the reload is // asked again, a few times, before it fails. Only "fetch failed" is asked again; every refusal is thrown as it is. const api: typeof started.api = async (method, path, body, bearer) => { for (let tries = 0; ; tries++) { try { return await started.api(method, path, body, bearer); } catch (error) { if (tries >= 10 || !String((error as Error).message).includes("fetch failed")) throw error; await new Promise((r) => setTimeout(r, 2000)); } } }; if (BOX) { // The box reaches this Mac's Worker at the same address: its loopback port forwarded here for the run's length. const port = new URL(base).port; const key = process.env.BOX_CARGO_KEY ?? join(homedir(), ".ssh/tinmen_ci_box"); // The box's login (user@host) is the caller's to give: no address is written here. const host = process.env.BOX_CARGO_HOST; if (!host) throw new Error("BOX is set but BOX_CARGO_HOST is not: give the box's login as user@host, or leave BOX unset to run cargo here"); tunnel = spawn("ssh", ["-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "ExitOnForwardFailure=yes", "-i", key, "-N", "-R", `127.0.0.1:${port}:127.0.0.1:${port}`, host], { stdio: "ignore" }); await new Promise((r) => setTimeout(r, 3000)); check(tunnel.exitCode === null, `the tunnel to the box holds port ${port}`); } const signIn = async (phone: string, device: string): Promise => { const code = await api<{ challenge_id: string }>("POST", "/v1/code", { phone, device_id: device }); const signed = await api<{ credential: string }>("POST", "/v1/sign-in", { challenge_id: code.challenge_id, code: "123456", device_id: device }); return signed.credential; }; await api("POST", "/v1/admin/person", { phone: MEMBER, role: "member" }, admin); const member = await signIn(MEMBER, "e2e-member-phone"); const other = await signIn(OWNER, "e2e-other-owner-device"); const minted = await api<{ token?: string }>("POST", "/v1/act", { act: "mint_token", args: { name: "e2e restore", scopes: ["owner"], allow: "all" } }, credential); check(typeof minted.token === "string", "an owner key minted"); const env = { COTTON_E2E_BASE: base, COTTON_E2E_CREDENTIAL: credential, COTTON_E2E_DATABASE: WS, COTTON_E2E_MEMBER: member, COTTON_E2E_TOKEN: minted.token!, COTTON_E2E_OTHER: other }; walk("restore_refuses_a_device_that_is_not_the_owners", env); // The kept day: snapshots on (off by default), invented to-dos, a weekly full, one more, a daily; then the damage. await api("POST", "/v1/admin/snapshots", { on: true }, admin); // Planted through the import with the owner's key (todo is a sealed table on dev: a device sends titles only sealed). const plant = async (id: string, title: string): Promise => { await api("POST", "/v1/admin/import", { rows: [{ table: "todo", id, data: { title, status: "open" } }] }, minted.token!); return id; }; const ids: string[] = []; for (let i = 0; i < 5; i++) ids.push(await plant(`kept-${i}`, `Kept ${i}`)); const run = async (kind: "full" | "daily"): Promise => { for (let n = 0; n < 30; n++) { const got = await api<{ done?: boolean; manifest?: unknown }>("POST", "/v1/admin/snapshots/run", n === 0 ? { kind } : {}, admin); if (got.done && got.manifest) return; } throw new Error(`the ${kind} copy never finished`); }; await run("full"); ids.push(await plant("kept-later", "Kept later")); await run("daily"); check(true, "a weekly full and a daily kept"); for (const id of ids) await api("POST", "/v1/act", { act: "delete", args: { table: "todo", id } }, credential); check(true, `the damage: ${ids.length} kept to-dos deleted`); walk("a_restore_interrupted_and_resumed_puts_the_phone_back", env); walk("a_restore_is_refused_once_the_erase_starts", env); const state = await api<{ frozen: boolean; pending: unknown }>("GET", "/v1/admin/restore/state", undefined, admin); check(state.frozen === false && state.pending === null, "the admin's view: not frozen, nothing pending"); console.log("e2e restore: passed"); } catch (error) { console.error((error as Error).message); const log = join(tmp, "wrangler.log"); if (existsSync(log)) console.error(`wrangler.log, its end:\n${readFileSync(log, "utf8").slice(-4000)}`); process.exitCode = 1; } finally { cleanup(); }