import { env, runInDurableObject } from"cloudflare:test";import { describe, expect, it } from"vitest";import { OWNER_PHONE, answer, http, personalObject, refusal, PEOPLE_OPEN, PHOTOS_OPEN, TODOS_OPEN } from"./personal.ts";import { Asks } from"../src/approval.ts";import * as vaultIdentity from"../src/vault_identity.ts";/** * KEPT FOUR 3 part A and VAULT GUARD 2 (src/vault_identity.ts): the object decides which vault key an account has. * The account's identity is pinned only by a device re-declaring a row it already holds, unchanged, that is not a * founder and is its only or oldest; a new wrap never pins, and two devices disagreeing pin nothing. Once pinned, a * declared identity that differs is refused for every caller; a new version is never set by a post (a version-only * update too); a row is retired only by the same key identity wrapped to the same device; a wrap of unknown identity * (today's builds) never retires anything, and with nothing pinned the heal copies as it always did. Synthetic keys and * wraps only. */const OPEN = [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open];const PUBLIC: Record<string, string> = { a: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", b: "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", w: "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",};/** Two key check values: the account's key, and another. */const ACCOUNT = "QUNDT1VOVC1LRVktQ0hFSw";const OTHER = "T1RIRVItS0VZLUNIRUNLMQ";asyncfunction device(slug: string, deviceId: string): Promise<Record<string, string>> {const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: deviceId });const signed = await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: deviceId }); expect(signed.status, JSON.stringify(signed.body)).toBe(200);return { authorization: `Bearer ${signed.body.credential}` };}asyncfunction rows(slug: string, auth: Record<string, string>): Promise<Map<string, Record<string, unknown>>> {const res = await http<{ rows: { table: string; id: string; data: Record<string, unknown>; deleted?: boolean }[] }>(slug, "GET", "/v1/sync?since=0&tables=vault_key", undefined, auth); expect(res.status, JSON.stringify(res.body)).toBe(200);returnnewMap(res.body.rows.filter((r) => r.table === "vault_key" && !r.deleted).map((r) => [r.id, r.data]));}asyncfunction admitted(slug: string, deviceId: string, approver: string): Promise<void> {await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), async (_i, state) => {const t = Math.floor(Date.now() / 1000);const id = `cta_${deviceId}`;newAsks(state.storage.sql).add({ id, phone: OWNER_PHONE, deviceId, deviceName: null, vaultKey: PUBLIC[deviceId]!, commit: "c", createdAt: t, expiresAt: t + 180 }); state.storage.sql.exec("UPDATE approval_ask SET reveal = 'r', state = 'approved', decided_by = ?, decided_at = ? WHERE id = ?", approver, t, id); });}function act(slug: string, auth: Record<string, string>, act: string, args: Record<string, unknown>) {return http<{ code?: string }>(slug, "POST", "/v1/act", { act, args }, auth);}const published = (d: string, id = `vk-${d}`) => ({ table: "vault_key", id, data: { device_id: d, public_key: PUBLIC[d]!, wrapped_vmk: null, vmk_version: 0 } });const wrapOf = (id: string, text: string, version = 1) => ({ table: "vault_key", id, data: { wrapped_vmk: text, vmk_version: version } });/** An account founded by device a's key as today's builds found it (no identity): its row `vk-a` holds the wrap. */asyncfunction founded(slug: string): Promise<{ a: Record<string, string>; b: Record<string, string>; owner: string }> {const { owner } = await personalObject(slug, { open: OPEN });const a = await device(slug, "a");const b = await device(slug, "b"); expect((await act(slug, a, "create", published("a"))).status).toBe(200); expect((await act(slug, b, "create", published("b"))).status).toBe(200);const made = await act(slug, a, "update", wrapOf("vk-a", "w1:SYNTHETIC-account-to-a")); expect(made.status, JSON.stringify(made.body)).toBe(200);return { a, b, owner };}/** Device a re-declares the row it holds, unchanged, with `check`: what pins the account's identity. */function redeclare(slug: string, auth: Record<string, string>, id: string, wrapped: string, check: string) {return act(slug, auth, "update", { ...wrapOf(id, wrapped), vmk_check: check });}/** The identity's standing in the object (kinds and counts), and whether `version` is pinned to `check`. */asyncfunction standing(slug: string): Promise<{ pinned: number; declared: Record<vaultIdentity.Kind, number>; disagreeing: number; pin: string | null }> {return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), async (_i, state) => ({ ...vaultIdentity.standing(state.storage.sql), pin: vaultIdentity.pinOf(state.storage.sql, 1) }));}/** An account founded and pinned to ACCOUNT by device a re-declaring its row. */asyncfunction pinnedAccount(slug: string): Promise<{ a: Record<string, string>; b: Record<string, string>; owner: string }> {const made = await founded(slug);const pinned = await redeclare(slug, made.a, "vk-a", "w1:SYNTHETIC-account-to-a", ACCOUNT); expect(pinned.status, JSON.stringify(pinned.body)).toBe(200); expect((await standing(slug)).pin).toBe(ACCOUNT);return made;}describe("the account's vault key, decided by the object", () => { it("pins the identity only by a device re-declaring the row it holds; then refuses a wrap of another key, for every caller", async () => {const SLUG = "vault-guard-different";const { a, b } = await pinnedAccount(SLUG);// Device a posts a founding of ANOTHER key under a new row of its own key (the stray founder: same public key).const stray = await act(SLUG, a, "create", { table: "vault_key", id: "founder:a", data: { device_id: "a", public_key: PUBLIC.a!, wrapped_vmk: "w1:SYNTHETIC-local-key", vmk_version: 1 }, vmk_check: OTHER }); expect([stray.status, stray.body.code]).toEqual([409, "vault_key_different"]);// An approval of b with another key is refused; with the account's key it is kept.await admitted(SLUG, "b", "a"); expect((await act(SLUG, a, "update", { ...wrapOf("vk-b", "w1:SYNTHETIC-other-to-b"), vmk_check: OTHER })).body.code).toBe("vault_key_different");const approved = await act(SLUG, a, "update", { ...wrapOf("vk-b", "w1:SYNTHETIC-account-to-b"), vmk_check: ACCOUNT }); expect(approved.status, JSON.stringify(approved.body)).toBe(200);// A re-wrap of an open row with another key is refused too. expect((await act(SLUG, b, "update", { ...wrapOf("vk-b", "w1:SYNTHETIC-other-again"), vmk_check: OTHER })).body.code).toBe("vault_key_different");const held = await rows(SLUG, a); expect([held.get("vk-a")?.wrapped_vmk, held.get("vk-b")?.wrapped_vmk, held.has("founder:a")]).toEqual(["w1:SYNTHETIC-account-to-a", "w1:SYNTHETIC-account-to-b", false]); }); it("never pins by a new wrap: the first declaration, even of the wrong key, pins nothing and locks no one out", async () => {const SLUG = "vault-guard-new-never-pins";const { a, b } = await founded(SLUG);// Device a also holds a local key made before sign-in, wrapped to the same device key: its founder row of that key// passes the own-key path, declared (a new wrap): nothing is pinned.const wrong = await act(SLUG, a, "create", { table: "vault_key", id: "founder:a", data: { device_id: "a", public_key: PUBLIC.a!, wrapped_vmk: "w1:SYNTHETIC-a-local", vmk_version: 1 }, vmk_check: OTHER }); expect(wrong.status, JSON.stringify(wrong.body)).toBe(200); expect((await standing(SLUG)).pinned, "a new wrap never pins").toBe(0);// Its re-declaration of the founder row pins nothing either: counted as a founder declaration. expect((await redeclare(SLUG, a, "founder:a", "w1:SYNTHETIC-a-local", OTHER)).status).toBe(200); expect([(await standing(SLUG)).pinned, (await standing(SLUG)).declared.founder]).toEqual([0, 1]);// An honest device declaring the account's key is not refused, and pins nothing while the stray stands against it.await admitted(SLUG, "b", "a"); expect((await act(SLUG, a, "update", wrapOf("vk-b", "w1:SYNTHETIC-account-to-b"))).status).toBe(200);const honest = await redeclare(SLUG, b, "vk-b", "w1:SYNTHETIC-account-to-b", ACCOUNT); expect(honest.status, JSON.stringify(honest.body)).toBe(200);const said = await standing(SLUG); expect([said.pinned, said.disagreeing, said.pin]).toEqual([0, 1, null]); }); it("pins nothing when two devices declare different identities, and says so in kinds and counts", async () => {const SLUG = "vault-guard-disagree";const { a, b } = await founded(SLUG);await admitted(SLUG, "b", "a");// b's row is wrapped declaring one identity (a new wrap: no pin); a then re-declares its own with another. expect((await act(SLUG, a, "update", { ...wrapOf("vk-b", "w1:SYNTHETIC-account-to-b"), vmk_check: OTHER })).status).toBe(200); expect((await redeclare(SLUG, a, "vk-a", "w1:SYNTHETIC-account-to-a", ACCOUNT)).status).toBe(200);const said = await standing(SLUG); expect([said.pinned, said.disagreeing, said.declared.new, said.declared.redeclared, said.pin]).toEqual([0, 1, 1, 1, null]);// Nothing pinned: neither identity is refused. expect((await redeclare(SLUG, b, "vk-b", "w1:SYNTHETIC-account-to-b", ACCOUNT)).status).toBe(200); }); it("pins only from the device's only or oldest row, never from a newer copy", async () => {const SLUG = "vault-guard-oldest";const { a } = await founded(SLUG);// A second copy on the phone takes the same wrap onto a newer row (today's build: undeclared, both rows stay). expect((await act(SLUG, a, "create", published("a", "second-a"))).status).toBe(200); expect((await act(SLUG, a, "update", wrapOf("second-a", "w1:SYNTHETIC-account-to-a"))).status).toBe(200); expect((await redeclare(SLUG, a, "second-a", "w1:SYNTHETIC-account-to-a", ACCOUNT)).status).toBe(200); expect((await standing(SLUG)).pinned, "the newer row pins nothing").toBe(0); expect((await redeclare(SLUG, a, "vk-a", "w1:SYNTHETIC-account-to-a", ACCOUNT)).status).toBe(200); expect((await standing(SLUG)).pin, "the oldest does").toBe(ACCOUNT); }); it("keeps both rows when today's build posts its own key's founding into a held vault (no identity): nothing is retired", async () => {for (const pin of [true, false]) {const slug = `vault-guard-older-build-${pin ? "pinned" : "unpinned"}`;const { a } = pin ? await pinnedAccount(slug) : await founded(slug);const posted = await act(slug, a, "create", { table: "vault_key", id: "founder:a", data: { device_id: "a", public_key: PUBLIC.a!, wrapped_vmk: "w1:SYNTHETIC-local-key", vmk_version: 1 } }); expect(posted.status, JSON.stringify(posted.body)).toBe(200);const held = await rows(slug, a); expect(held.get("vk-a")?.wrapped_vmk, "the genuine row stays").toBe("w1:SYNTHETIC-account-to-a"); expect(held.has("founder:a")).toBe(true); } }); it("retires only a row of the same key identity wrapped to the same device", async () => {const SLUG = "vault-guard-retire";await personalObject(SLUG, { open: OPEN });const a = await device(SLUG, "a"); expect((await act(SLUG, a, "create", { table: "vault_key", id: "founder:a", data: { device_id: "a", public_key: PUBLIC.a!, wrapped_vmk: "w1:SYNTHETIC-founding", vmk_version: 1 }, vmk_check: ACCOUNT })).status).toBe(200); expect((await act(SLUG, a, "create", published("a", "signed-in-a"))).status).toBe(200);const taken = await act(SLUG, a, "update", { ...wrapOf("signed-in-a", "w1:SYNTHETIC-founding"), vmk_check: ACCOUNT }); expect(taken.status, JSON.stringify(taken.body)).toBe(200); expect([...(await rows(SLUG, a)).keys()]).toEqual(["signed-in-a"]);const SLUG2 = "vault-guard-retire-unknown";await personalObject(SLUG2, { open: OPEN });const a2 = await device(SLUG2, "a"); expect((await act(SLUG2, a2, "create", { table: "vault_key", id: "founder:a", data: { device_id: "a", public_key: PUBLIC.a!, wrapped_vmk: "w1:SYNTHETIC-founding", vmk_version: 1 }, vmk_check: ACCOUNT })).status).toBe(200); expect((await act(SLUG2, a2, "create", published("a", "signed-in-a"))).status).toBe(200); expect((await act(SLUG2, a2, "update", wrapOf("signed-in-a", "w1:SYNTHETIC-founding"))).status).toBe(200); expect([...(await rows(SLUG2, a2)).keys()].sort()).toEqual(["founder:a", "signed-in-a"]); }); it("never sets a new version by a post, a version-only update too: changing the account's key is its own act", async () => {const SLUG = "vault-guard-rotation";const { a } = await founded(SLUG);const moved = await act(SLUG, a, "update", { ...wrapOf("vk-a", "w1:SYNTHETIC-version-two", 2), vmk_check: OTHER }); expect([moved.status, moved.body.code]).toEqual([409, "vault_key_rotation"]);const unknown = await act(SLUG, a, "update", wrapOf("vk-a", "w1:SYNTHETIC-version-two", 2)); expect(unknown.body.code, "for every caller, declared or not").toBe("vault_key_rotation");const versionOnly = await act(SLUG, a, "update", { table: "vault_key", id: "vk-a", data: { vmk_version: 2 } }); expect([versionOnly.status, versionOnly.body.code], "the version alone moves no key").toEqual([409, "vault_key_rotation"]); expect((await rows(SLUG, a)).get("vk-a")?.vmk_version).toBe(1); }); it("forgets a row's identity when only its version moves, so it can neither retire nor pin by it", async () => {const SLUG = "vault-guard-version-forgets";const { a } = await pinnedAccount(SLUG);await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(SLUG)), async (_i, state) => { expect(vaultIdentity.identityOf(state.storage.sql, "vk-a")?.check).toBe(ACCOUNT); });// Down to version 0 under the same bytes (no rotation): allowed as today, the identity is no longer the row's. expect((await act(SLUG, a, "update", { table: "vault_key", id: "vk-a", data: { vmk_version: 0 } })).status).toBe(200);await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(SLUG)), async (_i, state) => { expect(vaultIdentity.identityOf(state.storage.sql, "vk-a")).toBeNull(); }); }); it("lets the first of two new phones found the account and tells the second vault_founded", async () => {const SLUG = "vault-guard-race";await personalObject(SLUG, { open: OPEN });const a = await device(SLUG, "a");const b = await device(SLUG, "b");const first = await act(SLUG, a, "create", { table: "vault_key", id: "founder:a", data: { device_id: "a", public_key: PUBLIC.a!, wrapped_vmk: "w1:SYNTHETIC-a-local", vmk_version: 1 }, vmk_check: ACCOUNT }); expect(first.status, JSON.stringify(first.body)).toBe(200);const second = await act(SLUG, b, "create", { table: "vault_key", id: "founder:b", data: { device_id: "b", public_key: PUBLIC.b!, wrapped_vmk: "w1:SYNTHETIC-b-local", vmk_version: 1 }, vmk_check: OTHER }); expect([second.status, second.body.code]).toEqual([409, "vault_founded"]); expect([...(await rows(SLUG, a)).keys()]).toEqual(["founder:a"]); expect((await standing(SLUG)).pinned, "a founding is a new wrap: it pins nothing").toBe(0); }); it("heals a device stuck waiting for approval from its undeclared row, as before, while nothing is pinned", async () => {const SLUG = "vault-guard-heal-undeclared";const { a } = await founded(SLUG);// The 22 Nov device: its key wrapped on one row, published again unwrapped on another (a second copy). expect((await act(SLUG, a, "create", published("a", "second-a"))).status).toBe(200);await rows(SLUG, a); expect((await rows(SLUG, a)).get("second-a")?.wrapped_vmk).toBe("w1:SYNTHETIC-account-to-a"); }); it("heals only from a donor of the pinned identity once the account is pinned", async () => {const SLUG = "vault-guard-heal-pinned";const { a } = await pinnedAccount(SLUG);// A stray undeclared founder of the same device key (today's build), at the same version, then an unwrapped row. expect((await act(SLUG, a, "create", { table: "vault_key", id: "founder:a", data: { device_id: "a", public_key: PUBLIC.a!, wrapped_vmk: "w1:SYNTHETIC-local-key", vmk_version: 1 } })).status).toBe(200); expect((await act(SLUG, a, "create", published("a", "second-a"))).status).toBe(200);await rows(SLUG, a); expect((await rows(SLUG, a)).get("second-a")?.wrapped_vmk).toBe("w1:SYNTHETIC-account-to-a"); }); it("refuses undo and restore_version of a vault key row", async () => {const SLUG = "vault-guard-undo";const { owner } = await founded(SLUG);const log = await answer<{ changes: { change_id: number }[] }>(SLUG, owner, "list_changes", { table: "vault_key", id: "vk-a", limit: 1 });const change = log.changes[0]!.change_id; expect(await refusal(SLUG, owner, "undo", { change_id: change })).toMatch(/owner's own devices/); expect(await refusal(SLUG, owner, "restore_version", { table: "vault_key", id: "vk-a", change_id: change })).toMatch(/owner's own devices/); }); it("refuses a vmk_check that is not a key check value", async () => {const SLUG = "vault-guard-bad-check";const { a } = await founded(SLUG);const bad = await act(SLUG, a, "update", { ...wrapOf("vk-a", "w1:SYNTHETIC-account-to-a"), vmk_check: "not a check" }); expect([bad.status, bad.body.code]).toEqual([400, "bad_args"]); });});/** RULE (VAULT GUARD 2 item 5): today's builds, end to end, with no vmk_check anywhere: they work exactly as on main. */describe("today's builds, declaring nothing", { timeout: 180_000 }, () => {const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");const hex = (bytes: Uint8Array) => [...bytes].map((x) => x.toString(16).padStart(2, "0")).join(""); it("sign in, found, approve, re-wrap on a second copy, heal, and a way back in: every write kept, nothing pinned", async () => {const SLUG = "vault-guard-todays-builds";const { a, b } = await founded(SLUG);// An approval after the codes were compared.await admitted(SLUG, "b", "a"); expect((await act(SLUG, a, "update", wrapOf("vk-b", "w1:SYNTHETIC-account-to-b"))).status).toBe(200);// A second copy on b publishes its key again and takes its own wrap over (the own-key re-wrap). expect((await act(SLUG, b, "create", published("b", "second-b"))).status).toBe(200); expect((await act(SLUG, b, "update", wrapOf("second-b", "w1:SYNTHETIC-account-to-b"))).status).toBe(200);// A third copy on a publishes unwrapped and is healed on its next pass. expect((await act(SLUG, a, "create", published("a", "third-a"))).status).toBe(200);await rows(SLUG, a);// A way back in: a recovery code set by a, opened by a new phone, which puts its own wrap on its own row.const auth = newUint8Array(32).fill(2);const way = { salt: b64url(newUint8Array(16).fill(5)), auth_hash: hex(newUint8Array(await crypto.subtle.digest("SHA-256", auth))), wrapped: "r1:" + b64url(newUint8Array(40).fill(7)) };constset = await http(SLUG, "POST", "/v1/recovery/set", { kind: "code", salt: way.salt, kdf: "scrypt:15:8:1", auth_hash: way.auth_hash, wrapped: way.wrapped, vmk_version: 1 }, a); expect(set.status, JSON.stringify(set.body)).toBe(200);const fresh = await device(SLUG, "w"); expect((await act(SLUG, fresh, "create", published("w"))).status).toBe(200); expect((await http(SLUG, "POST", "/v1/recovery/open", { kind: "code", auth: b64url(auth) }, fresh)).status).toBe(200);const back = await act(SLUG, fresh, "update", wrapOf("vk-w", "w1:SYNTHETIC-account-to-w")); expect(back.status, JSON.stringify(back.body)).toBe(200);const held = await rows(SLUG, a); expect(Object.fromEntries([...held].map(([id, data]) => [id, data.wrapped_vmk]))).toEqual({"vk-a": "w1:SYNTHETIC-account-to-a","vk-b": "w1:SYNTHETIC-account-to-b","second-b": "w1:SYNTHETIC-account-to-b","third-a": "w1:SYNTHETIC-account-to-a","vk-w": "w1:SYNTHETIC-account-to-w", });const said = await standing(SLUG); expect([said.pinned, said.disagreeing, said.declared.new + said.declared.redeclared + said.declared.founder]).toEqual([0, 0, 0]); });});