// Vault email recovery (lib/vault-recovery.mjs, routes/vault-recovery.mjs): a // paid, opt-in escrow. What these pin: enrolling needs the purchase (402 with a // checkout link otherwise); the user share U goes out in the email and is never // written anywhere; a failed email leaves nothing enrolled; one-time codes have // a TTL, an attempt cap, single use and a start rate limit; a claim returns S // decrypted and, with U, reopens the vault key; disable deletes the material; // the shared CoinPay webhook settles vault_recovery once and still settles // auto_rotation; a machine key never gets in. process.env.DATABASE_URL = process.env.PWA_TEST_DATABASE_URL || ":memory:"; process.env.COINPAY_WEBHOOK_SECRET = "whsec_test"; process.env.COINPAY_API_KEY = "cp_test"; process.env.COINPAY_API_URL = "https://coinpay.test"; process.env.RESEND_API_KEY = "re_test"; process.env.VAULT_ESCROW_KEY = (await import("node:crypto")).randomBytes(32).toString("base64"); delete process.env.VAULT_ESCROW_KEY_VERSION; import test from "node:test"; import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { dirname, join } from "node:path"; import express from "express"; import { signWebhook } from "@profullstack/coinpay-onboard"; import { createVault, formatRecoveryCode, fromBase64, parseRecoveryCode, prepareEnrollment, recoverUserKeyByEmail, } from "@logicsrc/opencreds"; const here = dirname(fileURLToPath(import.meta.url)); const { db, run, get, all, isPostgres } = await import("../src/db.mjs"); const { vaultRecoveryRouter } = await import("../src/routes/vault-recovery.mjs"); const { autoRotationRouter } = await import("../src/routes/auto-rotation.mjs"); const { createApiKey } = await import("../src/lib/apikey.mjs"); const vr = await import("../src/lib/vault-recovery.mjs"); const now = Date.now(); if (isPostgres) { await db.execute("DROP SCHEMA public CASCADE"); await db.execute("CREATE SCHEMA public"); } for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql", "010_rotation_runs.sql", "011_rotation_policy.sql", "012_auto_rotation_billing.sql", "014_vault_email_recovery.sql"]) { const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8"); for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement); } // ---- outbound mail and CoinPay, intercepted; everything else (our own server) passes through ---- const realFetch = globalThis.fetch; const mail = []; let mailFails = false; let sessionSeq = 0; const sessions = new Map(); globalThis.fetch = async (url, init = {}) => { const u = String(url); if (u.startsWith("https://api.resend.com/")) { const body = JSON.parse(init.body); if (mailFails) return new Response(JSON.stringify({ message: "down" }), { status: 500 }); mail.push(body); return new Response(JSON.stringify({ id: `em_${mail.length}` }), { status: 200 }); } if (u.startsWith("https://coinpay.test/api/checkout/sessions")) { if ((init.method || "GET") === "POST") { const input = JSON.parse(init.body); const id = `cs_vr${++sessionSeq}`; const session = { id, url: `https://coinpay.test/pay/${id}`, status: "open", amount: input.amount, currency: "USD", metadata: input.metadata, account_id: input.account_id }; sessions.set(id, session); return new Response(JSON.stringify({ session }), { status: 201 }); } const id = decodeURIComponent(u.split("/").pop()); return new Response(JSON.stringify({ session: sessions.get(id) }), { status: 200 }); } return realFetch(url, init); }; test.after(() => { globalThis.fetch = realFetch; }); // ---- people, keys and a team (for the auto-rotation dispatch check) ---- const users = ["u_a", "u_b", "u_c", "u_d", "u_e", "u_owner"]; for (const uid of users) await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, [uid, `${uid}@example.com`, now]); const keys = {}; for (const uid of users) keys[uid] = (await createApiKey(uid, "cli")).plaintext; await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, ["t_acme", "acme", "acme", "u_owner", now]); await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`, ["m1", "t_acme", "u_owner", "u_owner@example.com", "owner", "active", now]); const machine = (await createApiKey("u_a", "dev2-deploy", { kind: "machine", teamId: "t_acme", vaultScope: null, readOnly: true })).plaintext; const app = express(); app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf.toString("utf8"); } })); app.use(vaultRecoveryRouter); app.use(autoRotationRouter); const server = app.listen(0); await new Promise((r) => server.once("listening", r)); const base = `http://127.0.0.1:${server.address().port}`; test.after(() => new Promise((r) => server.close(r))); async function call(token, method, path, body, headers = {}) { const raw = body === undefined ? undefined : typeof body === "string" ? body : JSON.stringify(body); const res = await realFetch(base + path, { method, headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(raw ? { "content-type": "application/json" } : {}), ...headers }, body: raw, }); const text = await res.text(); return { status: res.status, body: text ? JSON.parse(text) : null }; } // One real vault for everything below (PBKDF2 at the floor, to keep this quick). const vault = await createVault("old master password", { params: { kdf: "pbkdf2-sha256", iterations: 100_000 } }); async function enrollPayload() { const prepared = await prepareEnrollment(vault.meta, vault.userKey); return { ...prepared.payload }; } const grant = (uid, cs = `cs_grant_${uid}`) => run(`INSERT INTO vault_recovery_payments (checkout_session_id, user_id, status, created_at, settled_at) VALUES (?,?,?,?,?)`, [cs, uid, "settled", now, now]); const lastMailTo = (to) => [...mail].reverse().find((m) => m.to === to); const codeIn = (text) => /\b([0-9A-Z]{5}(?:-[0-9A-Z]{5}){11})\b/.exec(text)?.[1]; const otpIn = (text) => /One-time code: (\d{8})/.exec(text)?.[1]; async function enrolled(uid) { await grant(uid); const payload = await enrollPayload(); const r = await call(keys[uid], "POST", "/api/opencreds/recovery/enroll", payload); assert.equal(r.status, 201, JSON.stringify(r.body)); return payload; } test("no key: 401; a machine key is refused everywhere", async () => { assert.equal((await call(null, "GET", "/api/opencreds/recovery")).status, 401); for (const [method, path] of [["GET", "/api/opencreds/recovery"], ["POST", "/api/opencreds/recovery/enroll"], ["POST", "/api/opencreds/recovery/start"], ["POST", "/api/opencreds/recovery/claim"], ["DELETE", "/api/opencreds/recovery"], ["POST", "/api/opencreds/recovery/checkout"]]) { const r = await call(machine, method, path, method === "POST" ? {} : undefined); assert.equal(r.status, 403, `${method} ${path}`); assert.equal(r.body.code, "machine_key_forbidden"); } }); test("enroll without the purchase: 402 with a checkout link, and nothing stored", async () => { const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", await enrollPayload()); assert.equal(r.status, 402); assert.equal(r.body.code, "payment_required"); assert.equal(r.body.priceUsd, 5); assert.match(r.body.checkoutUrl, /^https:\/\/coinpay\.test\/pay\/cs_vr\d+$/); assert.equal(Number((await get(`SELECT COUNT(*) AS n FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_a"])).n), 0); const status = await call(keys.u_a, "GET", "/api/opencreds/recovery"); assert.deepEqual({ ...status.body, enrolledAt: null }, { enrolled: false, enrolledAt: null, email: "u***@example.com", purchased: false, priceUsd: 5, configured: true }); }); test("webhook: settles vault_recovery once (replay is a no-op) and still settles auto_rotation", async () => { const checkout = await call(keys.u_a, "POST", "/api/opencreds/recovery/checkout"); assert.equal(checkout.status, 201); const cs = checkout.body.sessionId; const created = sessions.get(cs); assert.equal(created.metadata.purpose, "vault_recovery"); assert.equal(created.metadata.user_id, "u_a"); assert.ok(created.metadata.payment_ref); assert.equal((await get(`SELECT status FROM vault_recovery_payments WHERE checkout_session_id = ?`, [cs])).status, "pending"); const event = (id, data) => JSON.stringify({ id, type: "payment.confirmed", data: { payment_id: `pay_${id}`, status: "confirmed", amount_usd: 5, blockchain: "USDC_POL", property: "app.logicsrc.com", ...data } }); const vrEvent = event("vr1", { checkout_session_id: cs, metadata: { purpose: "vault_recovery", user_id: "u_a", payment_ref: created.metadata.payment_ref } }); assert.equal((await call(null, "POST", "/api/coinpay/webhook", vrEvent, { "x-coinpay-signature": "t=1,v1=bad" })).status, 401); const first = await call(null, "POST", "/api/coinpay/webhook", vrEvent, { "x-coinpay-signature": signWebhook(vrEvent, "whsec_test") }); assert.equal(first.status, 200); assert.equal(first.body.purpose, "vault_recovery"); assert.equal(first.body.action, "settled"); const replay = await call(null, "POST", "/api/coinpay/webhook", vrEvent, { "x-coinpay-signature": signWebhook(vrEvent, "whsec_test") }); assert.equal(replay.body.duplicate, true); const row = await get(`SELECT * FROM vault_recovery_payments WHERE checkout_session_id = ?`, [cs]); assert.equal(row.status, "settled"); assert.equal((await all(`SELECT * FROM vault_recovery_payments WHERE user_id = ? AND status = 'settled'`, ["u_a"])).length, 1); assert.equal((await call(keys.u_a, "GET", "/api/opencreds/recovery")).body.purchased, true); assert.equal((await call(keys.u_a, "POST", "/api/opencreds/recovery/checkout")).status, 409); // The same endpoint, an auto-rotation purchase: routed to the old settler, unchanged. const arEvent = event("ar1", { checkout_session_id: "cs_ar1", metadata: { purpose: "auto_rotation", team_id: "t_acme", user_id: "u_owner" } }); const ar = await call(null, "POST", "/api/coinpay/webhook", arEvent, { "x-coinpay-signature": signWebhook(arEvent, "whsec_test") }); assert.equal(ar.body.action, "activated"); assert.equal(Number((await get(`SELECT rotation_auto_approve FROM credshare_teams WHERE id = ?`, ["t_acme"])).rotation_auto_approve), 1); assert.equal(Number((await get(`SELECT COUNT(*) AS n FROM vault_recovery_payments WHERE checkout_session_id = ?`, ["cs_ar1"])).n), 0); // An unpaid vault_recovery event settles nothing. const pending = JSON.stringify({ id: "vr2", type: "payment.pending", data: { status: "pending", metadata: { purpose: "vault_recovery", user_id: "u_b" } } }); assert.equal((await call(null, "POST", "/api/coinpay/webhook", pending, { "x-coinpay-signature": signWebhook(pending, "whsec_test") })).body.handled, false); assert.equal(await vr.isEntitled("u_b"), false); }); test("enroll rolls back when the email does not send (a prior enrollment survives)", async () => { mailFails = true; try { const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", await enrollPayload()); assert.equal(r.status, 502); assert.equal(r.body.code, "email_failed"); } finally { mailFails = false; } assert.equal(Number((await get(`SELECT COUNT(*) AS n FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_a"])).n), 0); await enrolled("u_c"); const before = await get(`SELECT id FROM vault_recovery_enrollments WHERE user_id = ? AND status = 'active'`, ["u_c"]); mailFails = true; try { assert.equal((await call(keys.u_c, "POST", "/api/opencreds/recovery/enroll", await enrollPayload())).status, 502); } finally { mailFails = false; } const rows = await all(`SELECT id, status FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_c"]); assert.deepEqual(rows.map((r) => [r.id, r.status]), [[before.id, "active"]]); }); test("enroll emails U as a checksummed code and never stores it; a re-enroll replaces the old one", async () => { const payload = await enrollPayload(); const sent = mail.length; const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", payload); assert.equal(r.status, 201); assert.deepEqual(r.body, { enrolled: true, email: "u***@example.com" }); assert.ok(!JSON.stringify(r.body).includes(payload.userShare)); assert.equal(mail.length, sent + 1); const email = mail.at(-1); assert.equal(email.to, "u_a@example.com"); assert.equal(email.subject, "Your LogicSRC vault email-recovery code — keep this email"); const code = codeIn(email.text); assert.ok(code, "a recovery code in the email"); const U = fromBase64(payload.userShare); // The server's renderer and the CLI's agree, and the CLI parses it back to U. assert.equal(code, await formatRecoveryCode(U)); assert.deepEqual(await parseRecoveryCode(code), U); // U is nowhere at rest: no column for it, and no value in any table holds it in any encoding. const tables = ["vault_recovery_enrollments", "vault_recovery_codes", "vault_recovery_payments", "vault_recovery_audit", "users", "api_keys"]; const needles = [payload.userShare, Buffer.from(U).toString("hex"), Buffer.from(U).toString("base64url"), code, code.replace(/-/g, "")]; for (const table of tables) { for (const row of await all(`SELECT * FROM ${table}`)) { for (const [column, value] of Object.entries(row)) { assert.ok(!/user_?share/i.test(column), `${table}.${column}`); if (typeof value !== "string") continue; for (const needle of needles) assert.ok(!value.includes(needle), `U found in ${table}.${column}`); } } } // S is stored only encrypted. const active = await get(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ? AND status = 'active'`, ["u_a"]); assert.notEqual(active.server_share_ct, payload.serverShare); assert.equal(Number(active.key_version), 1); assert.equal(active.escrow_blob, payload.escrowBlob); // Re-enroll: a single active row, the old one revoked with its material deleted. const again = await enrollPayload(); assert.equal((await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", again)).status, 201); const rows = await all(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ? ORDER BY enrolled_at, status`, ["u_a"]); assert.equal(rows.filter((x) => x.status === "active").length, 1); const old = rows.find((x) => x.id === active.id); assert.equal(old.status, "revoked"); assert.equal(old.escrow_blob, null); assert.equal(old.server_share_ct, null); }); test("start + claim: emails a code, wrong code counts, the right one returns S decrypted and reopens K, once", async () => { const payload = await enrolled("u_d"); const U = await parseRecoveryCode(codeIn(lastMailTo("u_d@example.com").text)); const start = await call(keys.u_d, "POST", "/api/opencreds/recovery/start"); assert.deepEqual(start.body, { sent: true, email: "u***@example.com" }); const otp = otpIn(lastMailTo("u_d@example.com").text); assert.match(otp, /^\d{8}$/); const row = await get(`SELECT * FROM vault_recovery_codes WHERE user_id = ? AND used_at IS NULL`, ["u_d"]); assert.ok(!row.code_hash.includes(otp)); assert.equal(Number(row.expires_at) - Number(row.created_at), 15 * 60 * 1000); const wrong = await call(keys.u_d, "POST", "/api/opencreds/recovery/claim", { code: otp === "00000000" ? "11111111" : "00000000" }); assert.equal(wrong.status, 401); assert.equal(wrong.body.attemptsLeft, 4); const notices = mail.length; const claim = await call(keys.u_d, "POST", "/api/opencreds/recovery/claim", { code: otp }); assert.equal(claim.status, 200); assert.deepEqual(claim.body, { escrowBlob: payload.escrowBlob, escrowIv: payload.escrowIv, serverShare: payload.serverShare, vaultCreatedAt: vault.meta.createdAt }); assert.equal(mail.at(-1).subject, "Your LogicSRC vault email recovery was used"); assert.equal(mail.length, notices + 1); assert.ok((await all(`SELECT action FROM vault_recovery_audit WHERE user_id = ?`, ["u_d"])).some((a) => a.action === "claim")); // S from the server + U from the enrollment email = the vault's own key. const K = await recoverUserKeyByEmail({ meta: vault.meta, material: claim.body, userShare: U }); assert.deepEqual(K, vault.userKey); // Single use. assert.equal((await call(keys.u_d, "POST", "/api/opencreds/recovery/claim", { code: otp })).status, 410); }); test("codes expire after 15 minutes and die after 5 wrong tries", async () => { await enrolled("u_e"); await call(keys.u_e, "POST", "/api/opencreds/recovery/start"); const expired = otpIn(lastMailTo("u_e@example.com").text); await run(`UPDATE vault_recovery_codes SET expires_at = ? WHERE user_id = ? AND used_at IS NULL`, [Date.now() - 1, "u_e"]); const late = await call(keys.u_e, "POST", "/api/opencreds/recovery/claim", { code: expired }); assert.equal(late.status, 410); assert.equal(late.body.code, "code_expired"); await call(keys.u_e, "POST", "/api/opencreds/recovery/start"); const otp = otpIn(lastMailTo("u_e@example.com").text); const bad = otp === "99999999" ? "88888888" : "99999999"; let r; for (let i = 0; i < 5; i++) r = await call(keys.u_e, "POST", "/api/opencreds/recovery/claim", { code: bad }); assert.equal(r.status, 401); assert.equal(r.body.attemptsLeft, 0); const after = await call(keys.u_e, "POST", "/api/opencreds/recovery/claim", { code: otp }); assert.equal(after.status, 410, "the right code is dead after five wrong ones"); }); test("start is rate limited to 3 per hour per user", async () => { // u_e has used 2 starts above; one more is allowed, the next is not. assert.equal((await call(keys.u_e, "POST", "/api/opencreds/recovery/start")).status, 200); const limited = await call(keys.u_e, "POST", "/api/opencreds/recovery/start"); assert.equal(limited.status, 429); assert.equal(limited.body.code, "rate_limited"); assert.ok(limited.body.retryAfter > 0); }); test("start/claim need an active enrollment; disable deletes the material and kills live codes", async () => { assert.equal((await call(keys.u_b, "POST", "/api/opencreds/recovery/start")).status, 404); await enrolled("u_b"); await call(keys.u_b, "POST", "/api/opencreds/recovery/start"); const otp = otpIn(lastMailTo("u_b@example.com").text); const off = await call(keys.u_b, "DELETE", "/api/opencreds/recovery"); assert.deepEqual(off.body, { disabled: true }); const rows = await all(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_b"]); assert.ok(rows.every((x) => x.status === "revoked" && x.escrow_blob === null && x.escrow_iv === null && x.server_share_ct === null && x.server_share_iv === null)); assert.equal((await call(keys.u_b, "POST", "/api/opencreds/recovery/claim", { code: otp })).status, 410); assert.equal((await call(keys.u_b, "POST", "/api/opencreds/recovery/start")).status, 404); const status = (await call(keys.u_b, "GET", "/api/opencreds/recovery")).body; assert.equal(status.enrolled, false); assert.equal(status.purchased, true, "disabling does not burn the purchase"); assert.deepEqual((await call(keys.u_b, "DELETE", "/api/opencreds/recovery")).body, { disabled: false }); }); test("escrow keyring: a rotated key still opens rows sealed under the old version", () => { const share = Buffer.alloc(32, 7); const v1 = vr.escrowKeyring({ VAULT_ESCROW_KEY: process.env.VAULT_ESCROW_KEY }); const sealed = vr.sealServerShare(share, "u_x", v1); const rotated = vr.escrowKeyring({ VAULT_ESCROW_KEY: Buffer.alloc(32, 1).toString("base64"), VAULT_ESCROW_KEY_VERSION: "2", VAULT_ESCROW_KEY_V1: process.env.VAULT_ESCROW_KEY }); assert.equal(rotated.version, 2); const row = { user_id: "u_x", server_share_ct: sealed.ct, server_share_iv: sealed.iv, key_version: sealed.version }; assert.deepEqual(vr.openServerShare(row, rotated), share); // Bound to the user: the same ciphertext under another user id does not open. assert.throws(() => vr.openServerShare({ ...row, user_id: "u_y" }, rotated)); assert.throws(() => vr.escrowKeyring({ VAULT_ESCROW_KEY: "dG9vLXNob3J0" }), /32 random bytes/); }); test("the Settings card: a Buy button before the purchase, the CLI hint after, a switch-off once enrolled", async () => { const { vaultRecoveryCard } = await import("../src/routes/vault-recovery.mjs"); const req = (uid) => ({ query: {}, user: { id: uid, email: `${uid}@example.com` }, csrfToken: "t" }); const unpaid = await vaultRecoveryCard(req("u_owner")); assert.match(unpaid, /Vault email recovery — \$5 lifetime/); assert.match(unpaid, /action="\/settings\/vault-recovery\/checkout"/); await grant("u_owner"); assert.match(await vaultRecoveryCard(req("u_owner")), /logicsrc vault recovery enable/); const on = await vaultRecoveryCard(req("u_a")); assert.match(on, /action="\/settings\/vault-recovery\/disable"/); assert.match(on, /u\*\*\*@example\.com/); });