Cotton code
298 lines · 20.5 KB · TypeScriptRaw
/** * RULE (R7d): a trusted person, one of this person's people, holds one half of a split secret in * their own object; this person's object holds the other. A new device of this person asks; the trusted person's * phone answers with their half wrapped to that device's key; only then does this person's object release its half, * and only to the device that asked. Neither object ever holds both halves. Two synthetic people on the open host; * every key and box is a synthetic stand-in. */import { env, runInDurableObject } from "cloudflare:test";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Business } from "../src/business.ts";import { ASKS_PER_DAY } from "../src/recovery.ts";import { bearer, fakes, open } from "./calling.ts";import { chatPhone, type ChatPhone } from "./chat.ts";vi.setConfig({ testTimeout: 240_000 });let n = 0;const number = (): string => `+91900003${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));/** * The commit a new device makes (crates/cotton-core recovery_code.rs `help_commit`, BUILD 2: whose recovery, each * field said with its length), worked out here as the phone does, not with the Worker's own code. */async function commitOf(account: string, request: string, key: string, nonce: string): Promise<string> {  const bytes = (t: string) => Uint8Array.from(atob(t.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (t.length % 4)) % 4)), (c) => c.charCodeAt(0));  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(account)), ...field(enc.encode("trusted")), ...field(be(0)), ...field(enc.encode(request)), ...bytes(key), ...bytes(nonce)]);  return b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", joined)));}/** The query a BUILD 2 phone puts on every help call. */const F2 = "?flow=2";let asks = 0;/** An ask's id as a new device mints it. */const askId = () => `ask-${String(++asks).padStart(4, "0")}-synthetic-id`;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));}/** The owner's phone holds the vault: its vault_key row carries a wrap (synthetic). */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);}const trustBody = (helper: string) => ({  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,  helper_name: "Helper Walk",  share: key32(9),  box: "p1:" + b64url(new Uint8Array(120).fill(3)),});async function trusting(): Promise<{ owner: Person; helper: Person }> {  const owner = await person();  const helper = await person();  await owner.phone.say("accept", helper.number);  await helper.phone.say("accept", owner.number);  await holdsVault(owner);  return { owner, helper };}describe("a trusted person", () => {  it("is one of your people: anyone else is refused", async () => {    const owner = await person();    const stranger = await person();    await holdsVault(owner);    const refused = await owner.ask<{ code: string }>("POST", "/v1/recovery/set", trustBody(stranger.number));    expect([refused.status, refused.body.code]).toEqual([403, "not_your_person"]);  });  it("AUDIT FIX B1 (B-4): a number on no account, and an account that did not accept you back, are answered the same; no helper is recorded", async () => {    const owner = await person();    const oneSided = await person();    await holdsVault(owner);    const nobody = number();    // The owner accepts both on their own side: their own people list now names them.    await owner.phone.say("accept", nobody);    await owner.phone.say("accept", oneSided.number);    const toNobody = await owner.ask<{ code: string; message: string }>("POST", "/v1/recovery/set", trustBody(nobody));    const toOneSided = await owner.ask<{ code: string; message: string }>("POST", "/v1/recovery/set", trustBody(oneSided.number));    expect([toNobody.status, toNobody.body]).toEqual([toOneSided.status, toOneSided.body]);    expect([toNobody.status, toNobody.body.code]).toEqual([403, "not_your_person"]);    expect(await inObject(owner.slug, (sql) => sql.exec("SELECT count(*) AS n FROM recovery_trust").one().n)).toBe(0);  });  it("holds one half, the owner's object the other, and a new device gets both only after the helper approves", async () => {    const { owner, helper } = await trusting();    const set = await owner.ask("POST", "/v1/recovery/set", trustBody(helper.number));    expect(set.status, JSON.stringify(set.body)).toBe(200);    const body = trustBody(helper.number);    // The helper's object keeps the box, never the share; the owner's keeps the share, never the box.    expect(await inObject(helper.slug, (sql) => JSON.stringify(sql.exec("SELECT * FROM recovery_help_held").toArray()))).toContain(body.box);    const ownerSide = await inObject(owner.slug, (sql) => ["recovery", "recovery_trust"].map((t) => JSON.stringify(sql.exec(`SELECT * FROM ${t}`).toArray())).join(""));    expect(ownerSide).toContain(body.share);    expect(ownerSide).not.toContain(body.box);    expect(await inObject(helper.slug, (sql) => JSON.stringify(sql.exec("SELECT * FROM recovery_help_held").toArray()))).not.toContain(body.share);    const read = await owner.ask<{ trusted: Body }>("GET", "/v1/recovery");    expect(read.body.trusted).toMatchObject({ helper: helper.number, helper_name: "Helper Walk" });    expect(read.body.trusted).not.toHaveProperty("share");    // A new device of the owner asks, committing to its key and a nonce it keeps.    const fresh = as(await chatPhone(owner.number, `dev-new-${n}`), owner.slug);    const nonceA = key32(21);    const id = askId();    const commit = await commitOf(owner.number, id, key32(4), nonceA);    const asked = await fresh.ask<{ id: string; name: string }>("POST", `/v1/recovery/help/ask${F2}`, { id, device_key: key32(4), commit, name: "Pixel walk" });    expect(asked.status, JSON.stringify(asked.body)).toBe(200);    expect(asked.body.name).toBe("Helper Walk");    expect((await fresh.ask<Body>("GET", `/v1/recovery/help/ask${F2}`)).body).toEqual({ state: "asked", name: "Helper Walk" });    // The helper's phone sees who asks: the device's key, its commit and the half kept for them. No code: the code is    // worked out on both phones, never carried.    const list = await helper.ask<{ asks: Body[] }>("GET", `/v1/recovery/help${F2}`);    expect(list.body.asks).toEqual([{ id: asked.body.id, peer: owner.number, device_key: key32(4), commit, box: body.box }]);    // No answer before the two phones have compared.    const early = await helper.ask<{ code: string }>("POST", `/v1/recovery/help/answer${F2}`, { id: asked.body.id, sealed: "w1:SYNTHETIC-too-early" });    expect([early.status, early.body.code]).toEqual([409, "help_not_compared"]);    // The helper opens it with its nonce, set once.    const nonceB = key32(22);    expect((await helper.ask("POST", `/v1/recovery/help/open${F2}`, { id: asked.body.id, nonce: nonceB })).status).toBe(200);    expect((await helper.ask<Body>("POST", `/v1/recovery/help/open${F2}`, { id: asked.body.id, nonce: key32(23) })).body).toEqual({ nonce: nonceB });    expect((await fresh.ask<Body>("GET", `/v1/recovery/help/ask${F2}`)).body).toEqual({ state: "opened", name: "Helper Walk", nonce_b: nonceB });    // The device reveals its nonce: one that does not hash to its commit is refused.    const wrong = await fresh.ask<{ code: string }>("POST", `/v1/recovery/help/reveal${F2}`, { nonce: key32(24) });    expect([wrong.status, wrong.body.code]).toEqual([400, "wrong_reveal"]);    expect((await fresh.ask("POST", `/v1/recovery/help/reveal${F2}`, { nonce: nonceA })).status).toBe(200);    expect((await fresh.ask<Body>("GET", `/v1/recovery/help/ask${F2}`)).body).toEqual({ state: "compare", name: "Helper Walk", nonce_b: nonceB });    expect((await helper.ask<{ asks: Body[] }>("GET", `/v1/recovery/help${F2}`)).body.asks).toEqual([      { id: asked.body.id, peer: owner.number, device_key: key32(4), commit, nonce_b: nonceB, reveal: nonceA, box: body.box },    ]);    const answered = await helper.ask("POST", `/v1/recovery/help/answer${F2}`, { id: asked.body.id, sealed: "w1:SYNTHETIC-half-for-the-device" });    expect(answered.status, JSON.stringify(answered.body)).toBe(200);    expect((await helper.ask<{ asks: Body[] }>("GET", `/v1/recovery/help${F2}`)).body.asks).toEqual([]);    // Both halves, to the device that asked alone.    expect((await fresh.ask<Body>("GET", `/v1/recovery/help/ask${F2}`)).body).toEqual({ state: "approved", name: "Helper Walk", sealed: "w1:SYNTHETIC-half-for-the-device", share: body.share });    const other = as(await chatPhone(owner.number, `dev-other-${n}`), owner.slug);    expect((await other.ask<Body>("GET", `/v1/recovery/help/ask${F2}`)).body).toEqual({ state: "none", name: "Helper Walk" });    // An answer for an ask already answered is refused.    const again = await helper.ask<{ code: string }>("POST", `/v1/recovery/help/answer${F2}`, { id: asked.body.id, sealed: "w1:again" });    expect([again.status, again.body.code]).toEqual([404, "help_not_waiting"]);  });  // TRUSTED RECOVERY BUILD 2, review H1: the store's earlier builds keep working until the owner retires their flow.  // The request shapes are origin/main's client before BUILD 1 (crates/cotton-ffi/src/phone/recovery.rs at 09ddfaa159:  // `ask_help`, `helped`, `help_asks`, `help_answer`): no `flow` on the query, no commit, the fingerprint as `code`.  it("serves an earlier build's phones as before, a new device with an old helper, and never lets a new helper skip the digits", async () => {    // An old device and an old helper: exactly as before.    {      const { owner, helper } = await trusting();      expect((await owner.ask("POST", "/v1/recovery/set", trustBody(helper.number))).status).toBe(200);      const old = as(await chatPhone(owner.number, `dev-old-${n}`), owner.slug);      const asked = await old.ask<{ id: string; name: string }>("POST", "/v1/recovery/help/ask", { device_key: key32(4), code: "ab12 cd34", name: "Old phone" });      expect(asked.status, JSON.stringify(asked.body)).toBe(200);      const list = await helper.ask<{ asks: Body[] }>("GET", "/v1/recovery/help");      expect(list.body.asks).toEqual([{ id: asked.body.id, peer: owner.number, code: "ab12 cd34", device_key: key32(4), box: trustBody(helper.number).box }]);      expect((await helper.ask("POST", "/v1/recovery/help/answer", { id: asked.body.id, sealed: "w1:SYNTHETIC-old-half" })).status).toBe(200);      expect((await old.ask<Body>("GET", "/v1/recovery/help/ask")).body).toMatchObject({ state: "approved", sealed: "w1:SYNTHETIC-old-half", share: trustBody(helper.number).share });    }    // A new device and an old helper: the ask carries the commit and the fingerprint; the old helper answers as before.    {      const { owner, helper } = await trusting();      expect((await owner.ask("POST", "/v1/recovery/set", trustBody(helper.number))).status).toBe(200);      const fresh = as(await chatPhone(owner.number, `dev-new-${n}`), owner.slug);      const id = askId();      const commit = await commitOf(owner.number, id, key32(4), key32(21));      expect((await fresh.ask("POST", `/v1/recovery/help/ask${F2}`, { id, device_key: key32(4), commit, code: "ab12 cd34" })).status).toBe(200);      expect((await helper.ask<{ asks: Body[] }>("GET", "/v1/recovery/help")).body.asks).toEqual([{ id, peer: owner.number, code: "ab12 cd34", device_key: key32(4), box: trustBody(helper.number).box }]);      expect((await helper.ask("POST", "/v1/recovery/help/answer", { id, sealed: "w1:SYNTHETIC-half" })).status).toBe(200);      expect((await fresh.ask<Body>("GET", `/v1/recovery/help/ask${F2}`)).body).toMatchObject({ state: "approved", sealed: "w1:SYNTHETIC-half" });    }    // An old device and a new helper: the new helper's phone is told it is an earlier build's ask, and cannot answer it.    {      const { owner, helper } = await trusting();      expect((await owner.ask("POST", "/v1/recovery/set", trustBody(helper.number))).status).toBe(200);      const old = as(await chatPhone(owner.number, `dev-old-${n}`), owner.slug);      const asked = await old.ask<{ id: string }>("POST", "/v1/recovery/help/ask", { device_key: key32(4), code: "ab12 cd34" });      const seen = await helper.ask<{ asks: Body[] }>("GET", `/v1/recovery/help${F2}`);      expect(seen.body.asks).toEqual([{ id: asked.body.id, peer: owner.number, device_key: key32(4), flow: 1, box: trustBody(helper.number).box }]);      const opened = await helper.ask<{ code: string }>("POST", `/v1/recovery/help/open${F2}`, { id: asked.body.id, nonce: key32(22) });      expect([opened.status, opened.body.code]).toEqual([409, "help_old_flow"]);      const answered = await helper.ask<{ code: string }>("POST", `/v1/recovery/help/answer${F2}`, { id: asked.body.id, sealed: "w1:SYNTHETIC-downgrade" });      expect([answered.status, answered.body.code]).toEqual([409, "help_not_compared"]);      expect((await old.ask<Body>("GET", "/v1/recovery/help/ask")).body.state).toBe("asked");      // The owner's count: accounts with a one-helper setup, and devices by the flow they last spoke.      await inObject(owner.slug, (_s, b) => (b as unknown as { reportRecoveryFlow(): Promise<void> }).reportRecoveryFlow());      await inObject(helper.slug, (_s, b) => (b as unknown as { reportRecoveryFlow(): Promise<void> }).reportRecoveryFlow());      const counts = await open<{ old_setup: number; accounts_with_flow1: number; devices: { flow1: number; flow2: number } }>("GET", "/v1/admin/recovery/flows", undefined, bearer("test-admin-token"));      expect(counts.status, JSON.stringify(counts.body)).toBe(200);      expect(counts.body.old_setup).toBeGreaterThanOrEqual(1);      expect(counts.body.devices.flow1).toBeGreaterThanOrEqual(1);      expect(counts.body.devices.flow2).toBeGreaterThanOrEqual(1);      expect(JSON.stringify(counts.body)).not.toContain(owner.number);      expect((await open("GET", "/v1/admin/recovery/flows", undefined, bearer(owner.phone.credential))).status).toBe(403);    }  });  it("says no when the helper declines, and counts asks", async () => {    const { owner, helper } = await trusting();    await owner.ask("POST", "/v1/recovery/set", trustBody(helper.number));    const fresh = as(await chatPhone(owner.number, `dev-new-${n}`), owner.slug);    const asked = await fresh.ask<{ id: string }>("POST", `/v1/recovery/help/ask${F2}`, { id: askId(), device_key: key32(4), commit: key32(30) });    await helper.ask("POST", `/v1/recovery/help/answer${F2}`, { id: asked.body.id, decline: true });    expect((await fresh.ask<Body>("GET", `/v1/recovery/help/ask${F2}`)).body.state).toBe("declined");    for (let i = 1; i < ASKS_PER_DAY; i++) expect((await fresh.ask("POST", `/v1/recovery/help/ask${F2}`, { id: askId(), device_key: key32(4), commit: key32(30) })).status).toBe(200);    const over = await fresh.ask<{ code: string }>("POST", `/v1/recovery/help/ask${F2}`, { id: askId(), device_key: key32(4), commit: key32(30) });    expect([over.status, over.body.code]).toEqual([429, "help_wait"]);  });  it("takes no answer from anyone but the person trusted", async () => {    const { owner, helper } = await trusting();    await owner.ask("POST", "/v1/recovery/set", trustBody(helper.number));    const fresh = as(await chatPhone(owner.number, `dev-new-${n}`), owner.slug);    const asked = await fresh.ask<{ id: string }>("POST", `/v1/recovery/help/ask${F2}`, { id: askId(), device_key: key32(4), commit: key32(30) });    // Another of the owner's people answers by the object hop directly: ignored.    const other = await person();    await inObject(owner.slug, (_sql, b) => b.helpAnswered(other.number, { id: asked.body.id, sealed: "w1:forged" }));    await inObject(owner.slug, (_sql, b) => b.helpOpened(other.number, { id: asked.body.id, nonce: key32(31) }));    expect((await fresh.ask<Body>("GET", `/v1/recovery/help/ask${F2}`)).body.state).toBe("asked");  });  // TRUSTED RECOVERY BUILD 1, step 2: a helper leaving never kills the way back in silently.  it("tells the person when their helper removes or blocks them, and the helper keeps no half", async () => {    for (const what of ["remove", "block"] as const) {      const { owner, helper } = await trusting();      expect((await owner.ask("POST", "/v1/recovery/set", trustBody(helper.number))).status).toBe(200);      const removed = await open("POST", `/v1/chat/${what}`, { number: owner.number }, bearer(helper.phone.credential));      expect(removed.status, JSON.stringify(removed.body)).toBe(200);      expect(await inObject(helper.slug, (sql) => sql.exec("SELECT COUNT(*) AS n FROM recovery_help_held").one().n)).toBe(0);      const read = await owner.ask<{ trusted: Body }>("GET", "/v1/recovery");      expect(read.body.trusted, what).toMatchObject({ helper: helper.number, gone: true });      // A new device is told plainly, not left waiting on an ask nobody can answer.      const fresh = as(await chatPhone(owner.number, `dev-new-${n}`), owner.slug);      const asked = await fresh.ask<{ code: string }>("POST", `/v1/recovery/help/ask${F2}`, { id: askId(), device_key: key32(4), commit: key32(30) });      expect([asked.status, asked.body.code]).toEqual([410, "help_gone"]);    }  });  it("tells the person when the owner removes their helper, and the helper's object lets the half go", async () => {    const { owner, helper } = await trusting();    expect((await owner.ask("POST", "/v1/recovery/set", trustBody(helper.number))).status).toBe(200);    const removed = await open("POST", "/v1/chat/remove", { number: helper.number }, bearer(owner.phone.credential));    expect(removed.status, JSON.stringify(removed.body)).toBe(200);    expect((await owner.ask<{ trusted: Body }>("GET", "/v1/recovery")).body.trusted).toMatchObject({ gone: true });    expect(await inObject(helper.slug, (sql) => sql.exec("SELECT COUNT(*) AS n FROM recovery_help_held").one().n)).toBe(0);  });  it("tells each person a deleted helper helped, and tells a deleted person's helper to let the half go", async () => {    const { owner, helper } = await trusting();    expect((await owner.ask("POST", "/v1/recovery/set", trustBody(helper.number))).status).toBe(200);    // The erase's directory step calls this before the number is let go (src/account_delete.ts `leaveRecovery`).    await inObject(helper.slug, (_sql, b) => (b as unknown as { leaveRecovery(): Promise<string[]> }).leaveRecovery());    expect((await owner.ask<{ trusted: Body }>("GET", "/v1/recovery")).body.trusted).toMatchObject({ gone: true });    expect(await inObject(helper.slug, (sql) => sql.exec("SELECT COUNT(*) AS n FROM recovery_help_held").one().n)).toBe(0);    const second = await trusting();    expect((await second.owner.ask("POST", "/v1/recovery/set", trustBody(second.helper.number))).status).toBe(200);    await inObject(second.owner.slug, (_sql, b) => (b as unknown as { leaveRecovery(): Promise<string[]> }).leaveRecovery());    expect(await inObject(second.helper.slug, (sql) => sql.exec("SELECT COUNT(*) AS n FROM recovery_help_held").one().n)).toBe(0);  });});