import { describe, expect, it } from "vitest"; import { EmailRecoveryError } from "@logicsrc/opencreds"; import { createRecoveryClient } from "./vault-sync.js"; type Call = { url: string; method: string; auth: string | null; body: unknown }; function fakeFetch(answers: Record) { const calls: Call[] = []; const impl = (async (url: string, init: RequestInit = {}) => { const method = init.method ?? "GET"; calls.push({ url, method, auth: new Headers(init.headers).get("authorization"), body: init.body ? JSON.parse(String(init.body)) : undefined, }); const answer = answers[`${method} ${new URL(url).pathname}`] ?? { status: 404, body: { error: "nope" } }; return new Response(JSON.stringify(answer.body), { status: answer.status }); }) as unknown as typeof fetch; return { impl, calls }; } describe("the email-recovery client", () => { it("talks to /api/opencreds/recovery with the person's key", async () => { const { impl, calls } = fakeFetch({ "GET /api/opencreds/recovery": { status: 200, body: { enrolled: true, enrolledAt: "2026-11-30T00:00:00.000Z", email: "m***@x.test", purchased: true, priceUsd: 5 } }, "POST /api/opencreds/recovery/claim": { status: 200, body: { escrowBlob: "b", escrowIv: "i", serverShare: "s", vaultCreatedAt: "c" } }, "DELETE /api/opencreds/recovery": { status: 200, body: { disabled: true } }, }); const client = createRecoveryClient("https://app.example/", "lsk_test", "me@x.test", impl); expect(client.label).toBe("app.example (me@x.test)"); expect((await client.status()).enrolled).toBe(true); expect(await client.claim("12345678")).toEqual({ escrowBlob: "b", escrowIv: "i", serverShare: "s", vaultCreatedAt: "c" }); expect(await client.disable()).toEqual({ disabled: true }); expect(calls.map((c) => `${c.method} ${c.url}`)).toEqual([ "GET https://app.example/api/opencreds/recovery", "POST https://app.example/api/opencreds/recovery/claim", "DELETE https://app.example/api/opencreds/recovery", ]); expect(calls.every((c) => c.auth === "Bearer lsk_test")).toBe(true); expect(calls[1]!.body).toEqual({ code: "12345678" }); }); it("surfaces a 402 with the checkout link", async () => { const { impl } = fakeFetch({ "POST /api/opencreds/recovery/enroll": { status: 402, body: { error: "Email recovery is a $5 lifetime add-on and is not purchased yet.", code: "payment_required", checkoutUrl: "https://coinpay.test/pay/cs_1" }, }, }); const client = createRecoveryClient("https://app.example", "lsk_test", undefined, impl); const err = await client .enroll({ escrowBlob: "", escrowIv: "", serverShare: "", userShare: "", vaultCreatedAt: "" }) .catch((e: unknown) => e); expect(err).toBeInstanceOf(EmailRecoveryError); expect((err as EmailRecoveryError).status).toBe(402); expect((err as EmailRecoveryError).code).toBe("payment_required"); expect((err as EmailRecoveryError).checkoutUrl).toBe("https://coinpay.test/pay/cs_1"); }); });