Cotton code
436 lines · 29.9 KB · TypeScriptRaw
/** * RULE (TRUSTED RECOVERY BUILD 1, step 4; assets/design/shared/TRUSTED-RECOVERY.md): the circle. This object keeps H * and never a piece; each helper's object keeps one sealed piece; a new device gets H only after the wait, with k * helpers' pieces wrapped to its key, each after a compare; any device of the person, any helper and the SMS link can * stop it; one open at a time, three in thirty days, a week's rest after a Stop from a device that holds the vault; a * circle replaces the one-helper trusted person; a helper who leaves is said. Synthetic people, keys and boxes. */import { env, runInDurableObject } from "cloudflare:test";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Business } from "../src/business.ts";import * as circle from "../src/recovery_circle.ts";import { DEVICE_STARTS_PER_MONTH, DEVICE_STOPS_PER_MONTH, PAUSE_MS, STARTS_PER_MONTH, WAIT_MS } from "../src/recovery_circle.ts";import { bearer, fakes, open } from "./calling.ts";import { chatPhone, type ChatPhone } from "./chat.ts";vi.setConfig({ testTimeout: 600_000 });let n = 0;const number = (): string => `+91900004${String(1000 + ++n).padStart(4, "0")}`;beforeEach(() => fakes());afterEach(() => vi.restoreAllMocks());type Body = Record<string, unknown>;const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");const key32 = (fill: number) => b64url(new Uint8Array(32).fill(fill));const fromB64 = (t: string) => Uint8Array.from(atob(t.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (t.length % 4)) % 4)), (c) => c.charCodeAt(0));/** The commit as the phone makes it (crates/cotton-core `help_commit`, BUILD 2): whose recovery, each field with its length. */async function commitOf(at: { account: string; setup: string; index: number; request: string }, key: string, nonce: string): Promise<string> {  const be = (v: number) => [(v >>> 24) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255];  const field = (f: Uint8Array | number[]) => [...be(f.length), ...f];  const enc = new TextEncoder();  const joined = new Uint8Array([...enc.encode("cotton-help-commit-v2"), ...field(enc.encode(at.account)), ...field(enc.encode(at.setup)), ...field(be(at.index)), ...field(enc.encode(at.request)), ...fromB64(key), ...fromB64(nonce)]);  return b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", joined)));}interface Person {  phone: ChatPhone;  slug: string;  number: string;  ask<T = Body>(method: string, path: string, body?: unknown): Promise<{ status: number; body: T }>;}async function slugOf(num: string): Promise<string> {  return (await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).lookup(num))!;}function as(phone: ChatPhone, slug: string): Person {  return { phone, slug, number: phone.number, ask: <T = Body>(method: string, path: string, body?: unknown) => open<T>(method, path, body, bearer(phone.credential)) };}async function person(): Promise<Person> {  const phone = await chatPhone(number(), `dev-${++n}`);  return as(phone, await slugOf(phone.number));}function inObject<T>(slug: string, fn: (sql: SqlStorage, b: Business) => T): Promise<T> {  return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance: Business, state) => fn(state.storage.sql, instance));}async function holdsVault(p: Person): Promise<void> {  const made = await p.ask("POST", "/v1/act", { act: "create", args: { table: "vault_key", id: `vault-key-${p.phone.device}`, data: { device_id: p.phone.device, public_key: key32(1), wrapped_vmk: "w1:SYNTHETIC-holder", vmk_version: 1 } } });  expect(made.status, JSON.stringify(made.body)).toBe(200);}async function befriend(a: Person, b: Person): Promise<void> {  await a.phone.say("accept", b.number);  await b.phone.say("accept", a.number);}const box = (i: number) => "p1:" + b64url(new Uint8Array(120).fill(30 + i));let setups = 0;const circleBody = (helpers: Person[], k: number) => ({  setup: b64url(new Uint8Array(16).fill(++setups)),  salt: b64url(new Uint8Array(16).fill(5)),  kdf: "none",  auth_hash: "c".repeat(64),  wrapped: "r1:" + b64url(new Uint8Array(60).fill(8)),  vmk_version: 1,  k,  held: key32(11),  members: helpers.map((h, i) => ({ number: h.number, name: `Helper ${i}`, box: box(i) })),});/** A person with a vault and `count` helpers, each one of their people. */async function circleOf(count: number): Promise<{ owner: Person; helpers: Person[] }> {  const owner = await person();  await holdsVault(owner);  const helpers: Person[] = [];  for (let i = 0; i < count; i++) {    const h = await person();    await befriend(owner, h);    helpers.push(h);  }  return { owner, helpers };}async function setAndAccept(owner: Person, helpers: Person[], k: number, accepting = helpers): Promise<string> {  const set = await owner.ask<{ setup: string; live: boolean }>("POST", "/v1/recovery/circle/set", circleBody(helpers, k));  expect(set.status, JSON.stringify(set.body)).toBe(200);  expect(set.body.live).toBe(false);  for (const h of accepting) {    const held = await h.ask<{ held: Body[] }>("GET", "/v1/recovery/circle/held");    expect(held.body.held).toHaveLength(1);    expect((await h.ask("POST", "/v1/recovery/circle/accept", { account: owner.slug, setup: set.body.setup })).status).toBe(200);  }  return set.body.setup;}/** The new device compares with helper `h` (index i) and the helper approves with a synthetic wrapped piece. */async function compareAndApprove(fresh: Person, owner: Person, h: Person, index: number, deviceKey: string): Promise<void> {  const nonceA = key32(60 + index);  const standing = (await fresh.ask<{ request: string; setup: string }>("GET", "/v1/recovery/circle/request")).body;  const at = { account: owner.number, setup: standing.setup, index, request: standing.request };  expect((await fresh.ask("POST", "/v1/recovery/circle/commit", { index, commit: await commitOf(at, deviceKey, nonceA) })).status).toBe(200);  const asks = await h.ask<{ asks: Body[] }>("GET", "/v1/recovery/circle/asks");  const ask = asks.body.asks[0]!;  expect(ask).toMatchObject({ account: owner.slug, index, device_key: deviceKey });  // No approval before the compare.  const early = await h.ask<{ code: string }>("POST", "/v1/recovery/circle/approve", { request: ask.request, account: owner.slug, sealed: "w1:too-early" });  expect([early.status, early.body.code]).toEqual([409, "help_not_compared"]);  expect((await h.ask("POST", "/v1/recovery/circle/open", { request: ask.request, account: owner.slug, nonce: key32(70 + index) })).status).toBe(200);  const wrong = await fresh.ask<{ code: string }>("POST", "/v1/recovery/circle/reveal", { index, nonce: key32(99) });  expect([wrong.status, wrong.body.code]).toEqual([400, "wrong_reveal"]);  expect((await fresh.ask("POST", "/v1/recovery/circle/reveal", { index, nonce: nonceA })).status).toBe(200);  const approved = await h.ask("POST", "/v1/recovery/circle/approve", { request: ask.request, account: owner.slug, sealed: `w1:SYNTHETIC-piece-${index}` });  expect(approved.status, JSON.stringify(approved.body)).toBe(200);}const waitIsOver = (slug: string) => inObject(slug, (sql) => sql.exec("UPDATE recovery_request SET ends_at = 0 WHERE state = 'waiting'"));describe("the circle", () => {  it("gives a new device the object's half only after the wait, with two of three helpers' pieces, each after a compare", async () => {    const { owner, helpers } = await circleOf(3);    // Not live until two have accepted: a start is refused.    const setup = await setAndAccept(owner, helpers, 2, [helpers[0]!]);    const fresh = as(await chatPhone(owner.number, `dev-new-${n}`), owner.slug);    const deviceKey = key32(4);    const early = await fresh.ask<{ code: string }>("POST", "/v1/recovery/circle/start", { device_key: deviceKey });    expect([early.status, early.body.code]).toEqual([409, "circle_not_live"]);    expect((await helpers[1]!.ask("POST", "/v1/recovery/circle/accept", { account: owner.slug, setup })).status).toBe(200);    // The object keeps H and the wrap, never a box; each helper's object keeps its own box, held by account.    const ownerSide = await inObject(owner.slug, (sql) => ["recovery", "recovery_circle", "recovery_circle_member"].map((t) => JSON.stringify(sql.exec(`SELECT * FROM ${t}`).toArray())).join(""));    expect(ownerSide).toContain(key32(11));    for (const i of [0, 1, 2]) expect(ownerSide).not.toContain(box(i));    for (const [i, h] of helpers.entries()) {      const theirs = await inObject(h.slug, (sql) => sql.exec("SELECT account, box FROM recovery_circle_held").toArray());      expect(theirs).toEqual([{ account: owner.slug, box: box(i) }]);    }    const read = await owner.ask<{ circle: Body }>("GET", "/v1/recovery");    expect(read.body.circle).toMatchObject({ k: 2, n: 3, live: true });    expect(JSON.stringify(read.body.circle)).not.toContain(key32(11));    // A start: one at a time.    const started = await fresh.ask<{ request: string; ends_at: number }>("POST", "/v1/recovery/circle/start", { device_key: deviceKey, name: "Pixel walk" });    expect(started.status, JSON.stringify(started.body)).toBe(200);    expect(started.body.ends_at - Date.now()).toBeGreaterThan(WAIT_MS - 60_000);    expect((await fresh.ask<{ code: string }>("POST", "/v1/recovery/circle/start", { device_key: deviceKey })).body.code).toBe("circle_request_open");    expect((await owner.ask<{ circle: Body }>("GET", "/v1/recovery")).body.circle).toMatchObject({ request: { id: started.body.request, state: "waiting" } });    // The helper who never accepted is not asked.    expect((await helpers[2]!.ask<{ asks: Body[] }>("GET", "/v1/recovery/circle/asks")).body.asks).toEqual([]);    await compareAndApprove(fresh, owner, helpers[0]!, 0, deviceKey);    await compareAndApprove(fresh, owner, helpers[1]!, 1, deviceKey);    // Two approvals, and the wait not over: nothing released.    const waiting = await fresh.ask<Body>("GET", "/v1/recovery/circle/request");    expect(waiting.body.state).toBe("waiting");    expect(waiting.body).not.toHaveProperty("held");    // The wait over: H and the two pieces, to the device that started it alone.    await waitIsOver(owner.slug);    const released = await fresh.ask<Body>("GET", "/v1/recovery/circle/request");    expect(released.body).toMatchObject({ state: "released", held: key32(11), pieces: [{ index: 0, sealed: "w1:SYNTHETIC-piece-0" }, { index: 1, sealed: "w1:SYNTHETIC-piece-1" }] });    const other = as(await chatPhone(owner.number, `dev-other-${n}`), owner.slug);    expect((await other.ask<Body>("GET", "/v1/recovery/circle/request")).body).toEqual({ state: "none" });    // The circle's wrap opens with the auth key, as every way back in (src/recovery.ts `open`): kind circle is listed.    expect((await owner.ask<{ circle: Body }>("GET", "/v1/recovery")).body.circle).toMatchObject({ kdf: "none", vmk_version: 1 });  });  it("is stopped by any device of the person, a helper or the SMS link, and a vault device's Stop rests it a week", async () => {    const { owner, helpers } = await circleOf(1);    await setAndAccept(owner, helpers, 1);    const fresh = as(await chatPhone(owner.number, `dev-new-${n}`), owner.slug);    const start = () => fresh.ask<{ request: string; code?: string }>("POST", "/v1/recovery/circle/start", { device_key: key32(4) });    // A helper stops it.    const first = await start();    expect(first.status, JSON.stringify(first.body)).toBe(200);    expect((await helpers[0]!.ask("POST", "/v1/recovery/circle/stop-for", { request: first.body.request, account: owner.slug })).status).toBe(200);    expect((await fresh.ask<Body>("GET", "/v1/recovery/circle/request")).body.state).toBe("stopped");    // The SMS link stops it, with its token alone; a wrong token stops nothing.    const second = await start();    expect(second.status).toBe(200);    const token = "SYNTHETIC-stop-token-abcdefgh";    const hash = b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token))));    await inObject(owner.slug, (sql) => sql.exec("INSERT INTO recovery_stop_link (token_hash, request, at) VALUES (?, ?, ?)", hash, second.body.request, Date.now()));    expect(await inObject(owner.slug, (_s, b) => b.recoveryStopByLink("SYNTHETIC-not-the-token-xyz"))).toBe(false);    expect(await inObject(owner.slug, (_s, b) => b.recoveryStopByLink(token))).toBe(true);    expect((await fresh.ask<Body>("GET", "/v1/recovery/circle/request")).body.state).toBe("stopped");    // A device that holds the vault stops it: the circle rests PAUSE_MS.    const third = await start();    expect(third.status).toBe(200);    expect((await owner.ask<Body>("POST", "/v1/recovery/circle/stop", {})).body).toEqual({ stopped: true });    const rested = await start();    expect([rested.status, rested.body.code]).toEqual([429, "circle_paused"]);    const paused = (await owner.ask<{ circle: { paused_until: number } }>("GET", "/v1/recovery")).body.circle.paused_until;    expect(paused - Date.now()).toBeGreaterThan(PAUSE_MS - 60_000);  });  // TRUSTED RECOVERY BUILD 3, review 2: a device that proved only the SMS code spends its own allowance, never the owner's.  it("lets a device signed in by SMS alone spend only its own starts and stops, never the owner's recoveries", async () => {    const { owner, helpers } = await circleOf(1);    await setAndAccept(owner, helpers, 1);    const sim = as(await chatPhone(owner.number, `dev-sim-${n}`), owner.slug);    for (let i = 0; i < DEVICE_STARTS_PER_MONTH; i++) {      expect((await sim.ask("POST", "/v1/recovery/circle/start", { device_key: key32(4) })).status, `start ${i}`).toBe(200);      expect((await sim.ask("POST", "/v1/recovery/circle/stop", {})).status, `stop ${i}`).toBe(200);    }    const over = await sim.ask<{ code: string }>("POST", "/v1/recovery/circle/start", { device_key: key32(4) });    expect([over.status, over.body.code]).toEqual([429, "circle_wait_device"]);    // The owner's own new device still starts: none of that counted against the person.    const real = as(await chatPhone(owner.number, `dev-real-${n}`), owner.slug);    const started = await real.ask<{ request: string; texted: boolean }>("POST", "/v1/recovery/circle/start", { device_key: key32(5) });    expect(started.status, JSON.stringify(started.body)).toBe(200);    // No Twilio Messaging Service here: the device is told no text went.    expect(started.body.texted).toBe(false);    // The SIM's device has used its stops: it cannot stop the owner's recovery again this month.    const stopAgain = await sim.ask<{ code: string }>("POST", "/v1/recovery/circle/stop", {});    expect(DEVICE_STOPS_PER_MONTH).toBe(3);    expect([stopAgain.status, stopAgain.body.code]).toEqual([429, "circle_stop_wait"]);    // A device that holds the vault always stops, and it never counts.    expect((await owner.ask<Body>("POST", "/v1/recovery/circle/stop", {})).body).toEqual({ stopped: true });    // Only starts that reached a helper's approval count against the person.    const counted = await inObject(owner.slug, (sql) => sql.exec("SELECT COUNT(*) AS n FROM recovery_request WHERE approved_any = 1").one().n);    expect(counted).toBe(0);    expect(STARTS_PER_MONTH).toBe(3);  });  it("is set only by a device that holds the vault, with people of theirs, as 1 of 1 or 2 of 3", async () => {    const { owner, helpers } = await circleOf(3);    const stranger = await person();    expect((await owner.ask<{ code: string }>("POST", "/v1/recovery/circle/set", circleBody([helpers[0]!, helpers[1]!], 2))).body.code).toBe("bad_members");    expect((await owner.ask<{ code: string }>("POST", "/v1/recovery/circle/set", circleBody([stranger], 1))).body.code).toBe("not_your_person");    expect((await owner.ask<{ code: string }>("POST", "/v1/recovery/circle/set", { ...circleBody(helpers, 2), k: 3 })).body.code).toBe("bad_shape");    const fresh = as(await chatPhone(owner.number, `dev-new-${n}`), owner.slug);    expect((await fresh.ask<{ code: string }>("POST", "/v1/recovery/circle/set", circleBody([helpers[0]!], 1))).body.code).toBe("vault_not_held");  });  it("replaces the one-helper trusted person, whose object lets the half go; a new circle lets the earlier helpers go", async () => {    const { owner, helpers } = await circleOf(3);    const trusted = {      kind: "trusted", salt: b64url(new Uint8Array(16).fill(5)), kdf: "none", auth_hash: "a".repeat(64), wrapped: "r1:" + b64url(new Uint8Array(60).fill(7)),      vmk_version: 1, helper: helpers[0]!.number, helper_name: "Old helper", share: key32(9), box: "p1:" + b64url(new Uint8Array(120).fill(3)),    };    expect((await owner.ask("POST", "/v1/recovery/set", trusted)).status).toBe(200);    expect(await inObject(helpers[0]!.slug, (sql) => sql.exec("SELECT COUNT(*) AS n FROM recovery_help_held").one().n)).toBe(1);    await setAndAccept(owner, [helpers[1]!], 1);    expect(await inObject(helpers[0]!.slug, (sql) => sql.exec("SELECT COUNT(*) AS n FROM recovery_help_held").one().n)).toBe(0);    const read = await owner.ask<{ trusted: Body | null; circle: Body }>("GET", "/v1/recovery");    expect(read.body.trusted).toBeNull();    // AUDIT D: the one-helper way is never set again beside a circle (it would release on one approval, no wait).    const again = await owner.ask<{ code: string }>("POST", "/v1/recovery/set", trusted);    expect([again.status, again.body.code]).toEqual([409, "circle_set"]);    expect((await owner.ask<{ trusted: Body | null }>("GET", "/v1/recovery")).body.trusted).toBeNull();    // Chosen again: the earlier circle's helper lets their piece go.    await setAndAccept(owner, [helpers[2]!], 1);    expect(await inObject(helpers[1]!.slug, (sql) => sql.exec("SELECT COUNT(*) AS n FROM recovery_circle_held").one().n)).toBe(0);  });  // TRUSTED RECOVERY BUILD 2, review M2: the old way back in stays until the new circle is live, then goes in one step.  it("keeps the one-helper setup and the live circle until the new circle is live, and goes over in one step", async () => {    const { owner, helpers } = await circleOf(3);    const trusted = {      kind: "trusted", salt: b64url(new Uint8Array(16).fill(5)), kdf: "none", auth_hash: "a".repeat(64), wrapped: "r1:" + b64url(new Uint8Array(60).fill(7)),      vmk_version: 1, helper: helpers[0]!.number, helper_name: "Old helper", share: key32(9), box: "p1:" + b64url(new Uint8Array(120).fill(3)),    };    expect((await owner.ask("POST", "/v1/recovery/set", trusted)).status).toBe(200);    const set = await owner.ask<{ setup: string; live: boolean }>("POST", "/v1/recovery/circle/set", circleBody([helpers[1]!, helpers[2]!, helpers[0]!], 2));    expect(set.status, JSON.stringify(set.body)).toBe(200);    // Set, one accepted of two needed: the trusted person still stands, and the circle is pending, not the way in.    expect((await helpers[1]!.ask("POST", "/v1/recovery/circle/accept", { account: owner.slug, setup: set.body.setup })).status).toBe(200);    let read = await owner.ask<{ trusted: Body | null; circle: Body }>("GET", "/v1/recovery");    expect(read.body.trusted).toMatchObject({ helper: helpers[0]!.number });    expect(read.body.circle).toMatchObject({ live: false, pending: { setup: set.body.setup, k: 2 } });    expect(read.body.circle).not.toHaveProperty("salt");    expect(await inObject(helpers[0]!.slug, (sql) => sql.exec("SELECT COUNT(*) AS n FROM recovery_help_held").one().n)).toBe(1);    // The second accepts: live, the circle's wrap is the way in, the trusted person and their half gone, together.    expect((await helpers[2]!.ask("POST", "/v1/recovery/circle/accept", { account: owner.slug, setup: set.body.setup })).status).toBe(200);    read = await owner.ask<{ trusted: Body | null; circle: Body }>("GET", "/v1/recovery");    expect(read.body.trusted).toBeNull();    expect(read.body.circle).toMatchObject({ live: true, setup: set.body.setup, salt: expect.any(String) });    expect(read.body.circle).not.toHaveProperty("pending");    expect(await inObject(helpers[0]!.slug, (sql) => sql.exec("SELECT COUNT(*) AS n FROM recovery_help_held").one().n)).toBe(0);  });  it("changes nothing when a set fails partway: the helpers who took a piece let it go, the old way stands", async () => {    const { owner, helpers } = await circleOf(3);    const first = await setAndAccept(owner, [helpers[0]!], 1);    const body = circleBody(helpers, 2);    // The set's second helper cannot be reached: the route over this object's own storage, with that one's hop failing.    const answer = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(owner.slug)), async (_b: Business, state) => {      const dropped: string[] = [];      const kept: string[] = [];      const host = {        sql: state.storage.sql, now: () => Date.now(), me: { account: owner.slug, number: owner.number },        isPeer: async () => true, accountOf: async (num: string) => helpers.find((h) => h.number === num)!.slug,        peer: (account: string) => ({          circleKept: async () => { if (account === helpers[1]!.slug) throw new Error("unreachable"); kept.push(account); },          circleDropped: async () => { dropped.push(account); },        }) as unknown as circle.CirclePeer,        holdsVault: () => true, tellDevices: async () => undefined, textStop: async () => false, linkBase: () => null,        retireTrustedRows: () => null, tellTrustedDropped: async () => undefined, freshDevice: () => false,        checkWrap: () => undefined, writeWrap: () => undefined,      } satisfies circle.CircleHost;      const req = new Request("https://x/v1/recovery/circle/set", { method: "POST", body: JSON.stringify(body) });      let status = 200;      let code = "";      try {        await circle.route(host, { deviceId: "dev", owner: true, token: false }, req, new URL(req.url));      } catch (e) {        const r = e as { status?: number; code?: string };        status = r.status ?? 0;        code = r.code ?? String(e);      }      return { status, code, kept, dropped, rows: state.storage.sql.exec("SELECT id, setup FROM recovery_circle ORDER BY id").toArray() };    });    expect([answer.status, answer.code]).toEqual([502, "circle_unset"]);    expect(answer.dropped).toEqual(answer.kept);    expect(answer.rows).toEqual([{ id: 1, setup: first }]);    expect((await owner.ask<{ circle: Body }>("GET", "/v1/recovery")).body.circle).toMatchObject({ live: true, setup: first });  });  // TRUSTED RECOVERY BUILD 2, review M3: a helper's Stop ends only their part; helper-ended requests do not count.  it("lets a helper step out of a request without ending it, and counts against the person only their own Stops", async () => {    const { owner, helpers } = await circleOf(3);    await setAndAccept(owner, helpers, 2);    const fresh = as(await chatPhone(owner.number, `dev-new-${n}`), owner.slug);    const started = await fresh.ask<{ request: string }>("POST", "/v1/recovery/circle/start", { device_key: key32(4) });    expect(started.status).toBe(200);    expect((await helpers[0]!.ask("POST", "/v1/recovery/circle/stop-for", { request: started.body.request, account: owner.slug })).status).toBe(200);    const standing = await fresh.ask<{ state: string; members: Body[] }>("GET", "/v1/recovery/circle/request");    expect(standing.body.state).toBe("waiting");    expect(standing.body.members.find((m) => m.index === 0)).toMatchObject({ stopped: true });    const refused = await fresh.ask<{ code: string }>("POST", "/v1/recovery/circle/commit", { index: 0, commit: key32(40) });    expect([refused.status, refused.body.code]).toEqual([409, "circle_part_stopped"]);    // A second steps out: two of three cannot be reached, so it ends, and it does not count.    expect((await helpers[1]!.ask("POST", "/v1/recovery/circle/stop-for", { request: started.body.request, account: owner.slug })).status).toBe(200);    expect((await fresh.ask<Body>("GET", "/v1/recovery/circle/request")).body.state).toBe("stopped");    // A device signed in only by SMS in the last two days is told no helper's number.    const told = await fresh.ask<{ device: { fresh: boolean }; circle: { members: Body[] } }>("GET", "/v1/recovery");    expect(told.body.device.fresh).toBe(true);    expect(JSON.stringify(told.body.circle.members)).not.toContain(helpers[0]!.number);    expect(JSON.stringify((await owner.ask<{ circle: Body }>("GET", "/v1/recovery")).body.circle)).toContain(helpers[0]!.number);  });  // TRUSTED RECOVERY BUILD 3, review 1: a helper never drops the piece of the live circle, whatever is set after it.  for (const shape of [{ k: 1, count: 1 }, { k: 2, count: 3 }]) {    it(`keeps the live circle's piece through two later sets the helper never accepted (${shape.k} of ${shape.count})`, async () => {      const { owner, helpers } = await circleOf(shape.count);      const live = await setAndAccept(owner, helpers, shape.k);      // Set A, then B, with the same helpers, none accepting: both pending, the second replacing the first.      for (let i = 0; i < 2; i++) expect((await owner.ask("POST", "/v1/recovery/circle/set", circleBody(helpers, shape.k))).status).toBe(200);      for (const h of helpers) {        const setups = await inObject(h.slug, (sql) => sql.exec<{ setup: string; live: number | null }>("SELECT setup, live FROM recovery_circle_held WHERE account = ?", owner.slug).toArray());        expect(setups.find((x) => x.setup === live), JSON.stringify(setups)).toMatchObject({ live: 1 });      }      // The person's object still calls it live, and it still works: a start reaches the helpers.      expect((await owner.ask<{ circle: Body }>("GET", "/v1/recovery")).body.circle).toMatchObject({ live: true, setup: live });      const fresh = as(await chatPhone(owner.number, `dev-new-${n}`), owner.slug);      expect((await fresh.ask("POST", "/v1/recovery/circle/start", { device_key: key32(4) })).status).toBe(200);      expect((await helpers[0]!.ask<{ asks: Body[] }>("GET", "/v1/recovery/circle/asks")).body.asks).toHaveLength(1);    });  }  it("counts only what helpers hold: a helper's object that lets a live piece go tells the person's, which says so", async () => {    const { owner, helpers } = await circleOf(1);    const live = await setAndAccept(owner, helpers, 1);    await inObject(owner.slug, (_s, b) => (b as unknown as { circleLost(f: circle.From, l: { setup: string }): Promise<void> }).circleLost({ account: helpers[0]!.slug, number: helpers[0]!.number }, { setup: live }));    const read = await owner.ask<{ circle: { live: boolean; members: Body[] } }>("GET", "/v1/recovery");    expect(read.body.circle.live).toBe(false);    expect(read.body.circle.members[0]).toMatchObject({ state: "gone" });  });  it("answers the owner's count of flows to the admin token alone", async () => {    const { owner } = await circleOf(0);    for (const credential of [owner.phone.credential, "not-a-token"]) {      const refused = await open<{ code: string }>("GET", "/v1/admin/recovery/flows", undefined, bearer(credential));      expect(refused.status).toBeGreaterThanOrEqual(401);      expect(refused.status).toBeLessThan(404);    }    expect((await open("GET", "/v1/admin/recovery/flows", undefined, bearer("test-admin-token"))).status).toBe(200);  });  it("forgets an erased account's flow row in the directory", async () => {    const { owner } = await circleOf(0);    await owner.ask("GET", "/v1/recovery?flow=2");    await inObject(owner.slug, (_s, b) => (b as unknown as { reportRecoveryFlow(): Promise<void> }).reportRecoveryFlow());    const databaseId = await inObject(owner.slug, (sql) => sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'database_id'").one().value);    const dir = env.DIRECTORY.get(env.DIRECTORY.idFromName("directory"));    const rows = () => runInDurableObject(dir, (_i, state) => state.storage.sql.exec("SELECT COUNT(*) AS n FROM recovery_flow WHERE id = ?", databaseId).one().n);    expect(await rows()).toBe(1);    await dir.forget(databaseId, owner.slug);    expect(await rows()).toBe(0);    expect(await dir.accountGone(owner.slug)).toBe(true);  });  it("AUDIT D: an approval from a helper the person removed since no longer counts toward getting back in", async () => {    const { owner, helpers } = await circleOf(3);    await setAndAccept(owner, helpers, 2);    const fresh = as(await chatPhone(owner.number, `dev-new-${n}`), owner.slug);    const deviceKey = key32(4);    expect((await fresh.ask("POST", "/v1/recovery/circle/start", { device_key: deviceKey, name: "Invented phone" })).status).toBe(200);    await compareAndApprove(fresh, owner, helpers[0]!, 0, deviceKey);    await compareAndApprove(fresh, owner, helpers[1]!, 1, deviceKey);    // The person, suspicious of helper 0, removes them; the wait ends with only one helper standing approved.    expect((await owner.ask("POST", "/v1/chat/remove", { number: helpers[0]!.number })).status).toBe(200);    expect((await owner.ask<{ circle: { members: Body[] } }>("GET", "/v1/recovery")).body.circle.members[0]).toMatchObject({ state: "gone" });    await waitIsOver(owner.slug);    const after = await fresh.ask<Body>("GET", "/v1/recovery/circle/request");    expect(after.body.state).toBe("waiting");    expect(after.body).not.toHaveProperty("held");    expect(after.body).not.toHaveProperty("pieces");  });  it("says a helper who removes the person, and lets every piece go when either side leaves", async () => {    const { owner, helpers } = await circleOf(3);    await setAndAccept(owner, helpers, 2);    expect((await open("POST", "/v1/chat/remove", { number: owner.number }, bearer(helpers[0]!.phone.credential))).status).toBe(200);    expect(await inObject(helpers[0]!.slug, (sql) => sql.exec("SELECT COUNT(*) AS n FROM recovery_circle_held").one().n)).toBe(0);    const read = await owner.ask<{ circle: { members: Body[]; live: boolean } }>("GET", "/v1/recovery");    expect(read.body.circle.members[0]).toMatchObject({ state: "gone" });    expect(read.body.circle.live).toBe(true);    // The person's account erased: the helpers let go.    await inObject(owner.slug, (_s, b) => (b as unknown as { leaveRecovery(): Promise<string[]> }).leaveRecovery());    for (const h of helpers) expect(await inObject(h.slug, (sql) => sql.exec("SELECT COUNT(*) AS n FROM recovery_circle_held").one().n)).toBe(0);  });});