"use strict"; // Tests for the two-step recovery-code regeneration contract. // // Recovery codes are second-factor fallback credentials, so minting a fresh // set must prove BOTH factors, in order — ALWAYS, whatever the stored-code // inventory says: // // STEP 1 POST /api/account/2fa/regenerate-recovery-codes/verify-password // verifies the account's CURRENT PASSWORD and stamps a short-lived, // single-use session grant (req.session.recoveryRegenAuth) bound to // userId + email + a SHA-256 fingerprint of the stored password // hash, and answers requires: "totp" UNCONDITIONALLY — step 1 must // NEVER offer a password-only completion. // // STEP 2 POST /api/account/2fa/regenerate-recovery-codes requires that // stamp (fingerprint re-checked against the FRESH user row, so a // password rotated by another session between the steps invalidates // the grant) PLUS a live second factor: a fresh TOTP code // (consume-on-success) or a recovery grant from // /api/account/recovery/verify — burned via claimRecoveryCode when // spent (the old route merely deleted the session flag and left the // code itself valid). There is NO password-only fallback: an empty // recovery_codes array describes INVENTORY, not AUTHORIZATION — the // old degenerate zero-codes escape hatch let a healthy account whose // LAST code was legitimately consumed (claimRecoveryCode leaves the // same empty array as a legacy row) mint 7 fresh codes with no TOTP // proof at all. A genuinely locked-out legacy account has the // sanctioned terminal paths: the admin reset route (which refuses // admin targets) and the sudo-gated break-glass CLI // scripts/reset-recovery-codes.js. // // Net effect: a hijacked session needs the password AND a second factor to // mint codes — neither a stolen TOTP code nor a phished password suffices // alone anymore, and exhausting the codes never weakens the policy. // // index.js boots servers on require, so route-level behavior is locked with // source assertions (same technique as audit-l1-l2-l4-l6-hardening.test.js), // and the route statements are additionally executed against fake db/session // objects with the house vm-extraction technique (same as // credential-change-atomic-guard.test.js) so the exhaustion regression is // pinned behaviorally, not just textually. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const crypto = require("node:crypto"); const { createCredentialCommitService, RECOVERY_CODES_COMMIT_SQL } = require("../services/account-credentials"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); function countOccurrences(haystack, needle) { return haystack.split(needle).length - 1; } function sliceBetween(source, startMarker, endMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `start marker not found: ${startMarker}`); const end = source.indexOf(endMarker, start + startMarker.length); assert.ok(end > start, `end marker not found after start: ${endMarker}`); return source.slice(start, end); } function assertOrdered(haystack, sequence, label) { let cursor = 0; for (const [marker, what] of sequence) { const at = haystack.indexOf(marker, cursor); assert.ok(at >= 0, `${label} must keep ${what} (in order)`); cursor = at + marker.length; } } // The STEP 1 registration is anchored with the app.post(" prefix so the // contract-overview comment above the routes cannot satisfy the slice. const STEP1_ROUTE = sliceBetween( indexSource, 'app.post("/api/account/2fa/regenerate-recovery-codes/verify-password"', 'app.post("/api/account/2fa/regenerate-recovery-codes",' ); const STEP2_ROUTE = sliceBetween( indexSource, 'app.post("/api/account/2fa/regenerate-recovery-codes",', 'app.post("/api/account/password/verify",' ); const HELPERS = sliceBetween( indexSource, "async function readStoredRecoveryCodes(", 'app.post("/api/account/2fa/regenerate-recovery-codes/verify-password"' ); const CONSTANTS = sliceBetween( indexSource, "const RECOVERY_VERIFIED_EXPIRY_MS", "function getValidRecoveryVerification" ); // --------------------------------------------------------------------------- // Registration: two routes, two limiters, step 1 registered first // --------------------------------------------------------------------------- test("both halves of the contract are registered with their own rate limiters", () => { assert.equal( countOccurrences(indexSource, 'app.post("/api/account/2fa/regenerate-recovery-codes/verify-password", accountCredentialRateLimiter'), 1, "step 1 (password proof) must be registered exactly once, on the credential limiter" ); assert.equal( countOccurrences(indexSource, 'app.post("/api/account/2fa/regenerate-recovery-codes", accountTotpRateLimiter'), 1, "step 2 (completion) must be registered exactly once, on the TOTP limiter" ); }); test("the password step is registered immediately before the completion route", () => { const step1At = indexSource.indexOf('app.post("/api/account/2fa/regenerate-recovery-codes/verify-password"'); const step2At = indexSource.indexOf('app.post("/api/account/2fa/regenerate-recovery-codes",'); assert.ok(step1At >= 0 && step2At > step1At, "verify-password must precede the completion registration"); }); // --------------------------------------------------------------------------- // STEP 1: password proof stamps a bound, fingerprinted, count-aware grant // --------------------------------------------------------------------------- test("step 1 gates in order and stamps a fingerprint-bound grant", () => { assertOrdered(STEP1_ROUTE, [ ["if (!req.session || !req.session.user)", "the session gate"], ['if (!req.is("application/json"))', "the JSON content-type gate"], ['code: "2fa-disabled"', "the 2FA-enabled gate"], ['typeof currentPassword !== "string" || !currentPassword', "the current-password presence gate"], ['verifyPasswordForUser(user, currentPassword, "bcrypt-recovery-regen-stepup-timeout")', "the current-password verification"], ["readStoredRecoveryCodes(user)", "the fail-closed stored-code count read"], ["req.session.recoveryRegenAuth = {", "the step-1 stamp write"], ["crypto.randomBytes(16).toString(", "the nonce"], ["passwordFingerprint: sha256Hex(String(user.password))", "the password-fingerprint binding"], ], "step 1"); }); test("step 1 answers 403 on a wrong password and never logs it", () => { assert.ok(STEP1_ROUTE.includes('"Incorrect current password"'), "a wrong password must answer 403 Incorrect current password"); assert.ok(STEP1_ROUTE.includes("[SECURITY] Recovery code regeneration step 1 denied - incorrect current password"), "the denial must be security-logged"); assert.ok(STEP1_ROUTE.includes("[SECURITY] Recovery code regeneration step 1 - password verified"), "the success must be security-logged"); }); test("step 1 answers requires:\"totp\" UNCONDITIONALLY — it must never offer password-only", () => { assert.ok( STEP1_ROUTE.includes('requires: "totp"'), "the response must carry requires: \"totp\" with no stored-code condition" ); assert.ok( !STEP1_ROUTE.includes("stored.codes.length"), "the stored-code count must not decide the second factor (an empty array is inventory, not authorization)" ); assert.ok(!STEP1_ROUTE.includes('"none"'), "step 1 must never offer the password-only 'none' completion"); }); test("step 1 accepts no second factor in place of the password", () => { assert.ok(!STEP1_ROUTE.includes("verifyTotpForUser"), "step 1 must not verify TOTP codes"); assert.ok(!STEP1_ROUTE.includes("getValidRecoveryVerification"), "step 1 must not accept a recovery grant"); assert.ok(!STEP1_ROUTE.includes("recovery_codes = ?"), "step 1 must not write recovery codes"); }); // --------------------------------------------------------------------------- // STEP 2: stamp first, then the second factor // --------------------------------------------------------------------------- test("step 2 checks the password stamp BEFORE any second-factor branch", () => { assertOrdered(STEP2_ROUTE, [ ["getValidRecoveryRegenAuth(req, user)", "the step-1 stamp check"], ['code: "password-required"', "the missing-stamp rejection"], ["passwordFingerprint !== sha256Hex(String(user.password))", "the fingerprint re-check against the fresh row"], ['code: "password-stale"', "the stale-password rejection"], ["readStoredRecoveryCodes(user)", "the fail-closed stored-code read"], ["normalizeTotpCode(rawTwoFactorCode)", "the TOTP format gate"], ["verifyTotpForUser(user, twoFactorCode)", "the TOTP verification"], ["claimRecoveryCode(user, recoveryGrant.codeHash)", "the recovery-grant burn"], ['code: "2fa-required"', "the no-factor refusal"], ["await credentialCommitService.commitRecoveryCodes(", "the generation-guarded minting write"], ["delete req.session.recoveryRegenAuth", "the single-use stamp deletion"], ], "step 2"); }); test("step 2 no longer accepts a raw password or mints on credential check alone", () => { assert.ok(!STEP2_ROUTE.includes("verifyPasswordForUser"), "the completion route must not re-verify a password submitted in its own body"); assert.ok(!STEP2_ROUTE.includes("currentPassword"), "the completion route must not read a currentPassword field (the stamp is the password proof)"); }); test("step 2 burns the recovery grant via claimRecoveryCode when it is spent", () => { assert.ok(STEP2_ROUTE.includes("const claim = await claimRecoveryCode(user, recoveryGrant.codeHash)"), "the grant path must burn the matched code with the CAS claim"); assert.ok(STEP2_ROUTE.includes("if (!claim.ok)"), "the claim result must be checked"); assert.ok( STEP2_ROUTE.includes("Recovery verification expired or already used. Please verify a recovery code again."), "a lost claim must walk the client back to the recovery-code step" ); // The claim sits inside the minting try, so a DB rejection lands in the // catch that answers 500 — never a credential error (the documented // claimRecoveryCode contract: a DB error must not be answerable as // "already used"). const tryAt = STEP2_ROUTE.indexOf("try {"); const claimAt = STEP2_ROUTE.indexOf("await claimRecoveryCode(user, recoveryGrant.codeHash)"); const catchAt = STEP2_ROUTE.indexOf("catch (err)"); assert.ok(tryAt >= 0 && claimAt > tryAt && catchAt > claimAt, "claimRecoveryCode must run inside the try whose catch answers 500"); }); test("step 2 has NO password-only branch — zero stored codes cannot authorize minting", () => { assert.ok( !STEP2_ROUTE.includes("existingCodes.length === 0"), "the degenerate zero-codes escape hatch must be gone (a healthy account whose last code was consumed reaches the same empty array)" ); assert.ok( !STEP2_ROUTE.includes('method = "password"'), "no password regeneration method may be recorded" ); assert.ok( !STEP2_ROUTE.includes("password-only step-up"), "the password-only security-log line must be gone with its branch" ); assert.ok( !STEP2_ROUTE.includes("escape hatch"), "no escape-hatch branch may exist between the grant and the 2fa-required refusal" ); }); test("dashboard.js has no requires:'none' fast path — the modal always advances to the TOTP step", () => { const dashboardSource = fs.readFileSync(path.join(ROOT, "public", "js", "dashboard.js"), "utf8"); assert.ok(!dashboardSource.includes("requires === 'none'"), "the empty-body auto-complete branch must be gone from the regen modal"); assert.ok(!dashboardSource.includes("completeRegenRecovery({})"), "no empty-body completion call may remain (there is no password-only mint to reach)"); assert.ok(dashboardSource.includes("showRegenRecoveryStep('totp')"), "the modal must still advance to the TOTP step after a verified password"); }); test("step 2 deletes the single-use stamp on success and the grant flag on the grant path", () => { const stampDeletes = countOccurrences(STEP2_ROUTE, "delete req.session.recoveryRegenAuth"); assert.ok(stampDeletes >= 2, "the stamp must be deleted on the stale-fingerprint path AND on success"); const updateAt = STEP2_ROUTE.indexOf("await credentialCommitService.commitRecoveryCodes("); const successDeleteAt = STEP2_ROUTE.indexOf("delete req.session.recoveryRegenAuth", updateAt); assert.ok(successDeleteAt > updateAt, "the stamp deletion on success must follow the minting write"); const grantDeletes = countOccurrences(STEP2_ROUTE, "delete req.session.recoveryVerified"); assert.ok(grantDeletes >= 2, "the recovery flag must be cleared on claim failure AND on claim success"); }); // --------------------------------------------------------------------------- // Shared fail-closed helper // --------------------------------------------------------------------------- test("both halves read stored codes through one fail-closed shared helper", () => { assert.equal(countOccurrences(indexSource, "async function readStoredRecoveryCodes("), 1, "the shared helper must exist exactly once"); assert.ok(STEP1_ROUTE.includes("readStoredRecoveryCodes(user)"), "step 1 must use the shared helper"); assert.ok(STEP2_ROUTE.includes("readStoredRecoveryCodes(user)"), "step 2 must use the shared helper"); assert.ok(HELPERS.includes("return { ok: false }"), "the helper must fail closed on unknown state"); assert.ok(HELPERS.includes("Array.isArray(parsed)"), "the helper must reject a malformed stored array"); for (const [name, route] of [["step 1", STEP1_ROUTE], ["step 2", STEP2_ROUTE]]) { assert.ok(route.includes('res.status(500).json({ error: "Failed to regenerate recovery codes" })'), `${name} must answer 500 on a failed stored-state read`); } // The old inline read (and its per-route duplication) is gone from the routes. assert.ok(!STEP1_ROUTE.includes("JSON.parse(row.recovery_codes)"), "step 1 must not re-implement the read"); assert.ok(!STEP2_ROUTE.includes("JSON.parse(row.recovery_codes)"), "step 2 must not re-implement the read"); }); // --------------------------------------------------------------------------- // Constants and helper hygiene // --------------------------------------------------------------------------- test("the step-1 grant expiry is 5 minutes and sits beside the recovery-grant expiry", () => { assert.ok( CONSTANTS.includes("const RECOVERY_REGEN_AUTH_EXPIRY_MS = 5 * 60 * 1000"), "RECOVERY_REGEN_AUTH_EXPIRY_MS must be 5 minutes and defined next to RECOVERY_VERIFIED_EXPIRY_MS" ); assert.ok(HELPERS.includes("RECOVERY_REGEN_AUTH_EXPIRY_MS"), "the stamp guard must enforce the expiry"); }); test("the stamp guard deletes the flag on identity mismatch and expiry", () => { assertOrdered(HELPERS, [ ["const flag = req.session.recoveryRegenAuth;", "the flag read"], ["flag.email !== req.session.user || flag.userId !== user.id", "the identity binding check"], ["Date.now() - flag.verifiedAt > RECOVERY_REGEN_AUTH_EXPIRY_MS", "the expiry check"], ], "the stamp guard"); assert.equal(countOccurrences(HELPERS, "delete req.session.recoveryRegenAuth"), 2, "both invalid-stamp paths must delete the flag (fail closed, one attempt)"); }); // --------------------------------------------------------------------------- // Log hygiene: no plaintext passwords or codes anywhere // --------------------------------------------------------------------------- test("neither route logs or records plaintext passwords or codes", () => { for (const [name, route] of [["step 1", STEP1_ROUTE], ["step 2", STEP2_ROUTE]]) { for (const line of route.split("\n")) { if (!/console\.(log|error)/.test(line)) continue; for (const forbidden of ["currentPassword", "rawTwoFactorCode", "twoFactorCode", "plainRecoveryCodes", "passwordFingerprint"]) { assert.ok(!line.includes(forbidden), `${name} must not interpolate ${forbidden} into a log line`); } } const recordLine = route.split("\n").find((l) => l.includes("recordActivity(")); if (recordLine) { for (const forbidden of ["plainRecoveryCodes", "recoveryCodes", "currentPassword", "twoFactorCode"]) { assert.ok(!recordLine.includes(forbidden), `${name} must not record ${forbidden} via recordActivity`); } } } // The plaintext codes cross exactly one boundary: the step-2 response to the // code owner's own authenticated session. assert.ok(STEP2_ROUTE.includes("recoveryCodes: plainRecoveryCodes"), "the minted plaintext codes must still be returned to the owner's session"); }); test("step 2 keeps the documented success contract", () => { assert.ok(STEP2_ROUTE.includes("regeneratedVia: method"), "the response must carry regeneratedVia"); assert.ok(STEP2_ROUTE.includes("[SECURITY] Recovery codes regenerated |"), "the success must be security-logged with the method"); assert.ok(STEP2_ROUTE.includes('recordActivity("_system", "recovery_codes_regenerated"'), "the audit-trail recordActivity call must stay"); }); // --------------------------------------------------------------------------- // Behavior harness — the REAL route statements and the REAL helpers // (claimRecoveryCode / readStoredRecoveryCodes / getValidRecoveryRegenAuth / // getValidRecoveryVerification) extracted verbatim from index.js and run // against fake db / session / response objects, the house vm-extraction // technique (same as credential-change-atomic-guard.test.js). The point is // the exhaustion regression: consuming the LAST code leaves the SAME empty // array a degenerate legacy row has, and that state must refuse — not mint. // --------------------------------------------------------------------------- // Paren-balanced extraction of a full `app.post(...);` statement (skips // strings and comments so adpanel: comments cannot desync the tracker). function extractRouteStatement(source, marker) { const start = source.indexOf(marker); assert.ok(start >= 0, `route marker not found: ${marker}`); let i = start; let depth = 0; let started = false; let inString = null; while (i < source.length) { const ch = source[i]; if (inString) { if (ch === "\\") { i += 2; continue; } if (ch === inString) inString = null; i += 1; continue; } if (ch === "/" && source[i + 1] === "/") { const j = source.indexOf("\n", i); i = j < 0 ? source.length : j; continue; } if (ch === "/" && source[i + 1] === "*") { const j = source.indexOf("*/", i + 2); i = j < 0 ? source.length : j + 2; continue; } if (ch === '"' || ch === "'" || ch === "`") { inString = ch; i += 1; continue; } if (ch === "(") { depth += 1; started = true; } else if (ch === ")") { depth -= 1; } if (started && depth === 0) { let end = i + 1; while (end < source.length && source[end] === ";") end += 1; return source.slice(start, end); } i += 1; } assert.fail(`unbalanced route statement: ${marker}`); } const STEP1_STATEMENT = extractRouteStatement( indexSource, 'app.post("/api/account/2fa/regenerate-recovery-codes/verify-password", accountCredentialRateLimiter' ); const STEP2_STATEMENT = extractRouteStatement( indexSource, 'app.post("/api/account/2fa/regenerate-recovery-codes", accountTotpRateLimiter' ); // The REAL helpers, extracted verbatim (each slice is a self-contained // declaration; any comment text between helpers is inert). const VERIFY_GRANT_FN = sliceBetween( indexSource, "function getValidRecoveryVerification(", "async function claimRecoveryCode(" ); const CLAIM_FN = sliceBetween( indexSource, "async function claimRecoveryCode(", 'app.post("/api/account/recovery/verify"' ); const READ_FN = sliceBetween( indexSource, "async function readStoredRecoveryCodes(", "function getValidRecoveryRegenAuth" ); const GUARD_FN = sliceBetween( indexSource, "function getValidRecoveryRegenAuth(", 'app.post("/api/account/2fa/regenerate-recovery-codes/verify-password"' ); const sha256HexStub = (s) => crypto.createHash("sha256").update(s).digest("hex"); const REGEN_USER = { id: 42, email: "owner@example.test", password: "stored-bcrypt-hash", secret: "sealed-totp-secret", session_epoch: 17, }; // Stateful fake db modeling the recovery_codes column: the CAS UPDATE // (claimRecoveryCode) and the guarded minting UPDATE (step 2) both rewrite // state.recoveryCodes, so tests can assert exactly which writes happened. function makeRegenDb({ storedJson = "[]", readError = null, casWins = true } = {}) { const state = { recoveryCodes: storedJson, epoch: REGEN_USER.session_epoch, password: REGEN_USER.password }; const queries = []; return { state, queries, async query(sql, params) { queries.push({ sql, params }); if (sql === "SELECT recovery_codes FROM users WHERE id = ? LIMIT 1") { if (readError) throw readError; return [{ recovery_codes: state.recoveryCodes }]; } if (sql === "UPDATE users SET recovery_codes = ? WHERE id = ? AND recovery_codes = ?") { if (!casWins) return { affectedRows: 0 }; state.recoveryCodes = params[0]; return { affectedRows: 1 }; } if (sql === RECOVERY_CODES_COMMIT_SQL) { if (state.password !== params[2] || state.epoch !== params[3] || state.recoveryCodes !== params[4]) return { affectedRows: 0 }; state.recoveryCodes = params[0]; return { affectedRows: 1 }; } throw new Error(`unexpected db.query in test: ${sql}`); }, }; } function makeRegenRes() { const res = { statusCode: 0, body: null, headersSent: false }; res.status = (code) => { res.statusCode = code; res.headersSent = true; return res; }; // Express res.json() answers 200 when no status was set explicitly — both // success paths (step 1's { ok, requires } and step 2's mint) use it bare. res.json = (body) => { if (!res.statusCode) res.statusCode = 200; res.body = body; return res; }; return res; } function makeRegenReq({ body = {}, session = {} } = {}) { return { body, session, headers: {}, is: (type) => (type === "application/json" ? "application/json" : false), }; } function regenStamp(passwordFingerprint, overrides = {}) { return { userId: REGEN_USER.id, email: REGEN_USER.email, nonce: "nonce-1", verifiedAt: Date.now(), passwordFingerprint, ...overrides, }; } function makeRegenHarness({ user = REGEN_USER, db, totpOk = true } = {}) { const calls = []; const sandbox = { app: { post: (...args) => calls.push(["route", ...args]) }, accountCredentialRateLimiter: {}, accountTotpRateLimiter: {}, findUserByEmail: async () => user, hasTwoFactorEnabled: () => true, verifyPasswordForUser: async () => true, sha256Hex: sha256HexStub, normalizeTotpCode: (raw) => { const code = String(raw || "").replace(/\s+/g, ""); return /^\d{6}$/.test(code) ? code : ""; }, verifyTotpForUser: async (u, code) => { calls.push(["verifyTotpForUser", u && u.id, code]); return { ok: totpOk }; }, bcrypt: { hash: async () => "hashed-code", compare: async () => false }, BCRYPT_ROUNDS: 4, db, credentialCommitService: createCredentialCommitService({ db }), RECOVERY_REGEN_AUTH_EXPIRY_MS: 5 * 60 * 1000, RECOVERY_VERIFIED_EXPIRY_MS: 5 * 60 * 1000, stripLogControlChars: (s) => String(s == null ? "" : s), getRequestIp: () => "127.0.0.1", recordActivity: (...args) => calls.push(["recordActivity", ...args]), console: { log: (...args) => calls.push(["log", args.map(String).join(" ")]), error: (...args) => calls.push(["error", args.map(String).join(" ")]), warn: () => {}, }, crypto, JSON, Promise, Date, Object, String, Number, Math, Array, RegExp, Error, Symbol, }; return { calls, async load() { const captured = []; const ctx = vm.createContext({ ...sandbox, app: { post: (...args) => captured.push(args) }, }); vm.runInContext(VERIFY_GRANT_FN, ctx, { filename: "index.js[getValidRecoveryVerification]" }); vm.runInContext(CLAIM_FN, ctx, { filename: "index.js[claimRecoveryCode]" }); vm.runInContext(READ_FN, ctx, { filename: "index.js[readStoredRecoveryCodes]" }); vm.runInContext(GUARD_FN, ctx, { filename: "index.js[getValidRecoveryRegenAuth]" }); vm.runInContext(STEP1_STATEMENT, ctx, { filename: "index.js[step1]" }); vm.runInContext(STEP2_STATEMENT, ctx, { filename: "index.js[step2]" }); assert.equal(captured.length, 2, "exactly two route registrations per harness"); const step1 = captured.find((args) => args[0].includes("verify-password"))[2]; const step2 = captured.find((args) => args[0] === "/api/account/2fa/regenerate-recovery-codes")[2]; return { step1, step2, ctx, calls }; }, }; } function countMintWrites(db) { return db.queries.filter((q) => q.sql === RECOVERY_CODES_COMMIT_SQL).length; } test("behavior: step 1 answers requires:\"totp\" even with zero stored codes and stamps the grant", async () => { const db = makeRegenDb({ storedJson: "[]" }); const { step1 } = await makeRegenHarness({ db }).load(); const session = { user: REGEN_USER.email }; const res = makeRegenRes(); await step1(makeRegenReq({ body: { currentPassword: "whatever" }, session }), res); assert.equal(res.statusCode, 200, "step 1 succeeds on a correct password"); assert.deepEqual(res.body, { ok: true, requires: "totp" }, "the answer must be totp even when the account holds zero codes"); assert.ok(session.recoveryRegenAuth, "the step-1 stamp is written"); assert.equal(session.recoveryRegenAuth.passwordFingerprint, sha256HexStub(REGEN_USER.password), "the stamp binds the stored-hash fingerprint"); }); test("behavior: step 1 still fails closed on a stored-code read error and writes no stamp", async () => { const db = makeRegenDb({ storedJson: "[]", readError: new Error("db down") }); const { step1 } = await makeRegenHarness({ db }).load(); const session = { user: REGEN_USER.email }; const res = makeRegenRes(); await step1(makeRegenReq({ body: { currentPassword: "whatever" }, session }), res); assert.equal(res.statusCode, 500, "a DB error is a 500, not a downgrade"); assert.deepEqual(res.body, { error: "Failed to regenerate recovery codes" }); assert.ok(!session.recoveryRegenAuth, "no stamp may be written on unknown stored state"); }); test("behavior: consuming the LAST code through the real claimRecoveryCode leaves an empty array that does NOT authorize a mint", async () => { const db = makeRegenDb({ storedJson: JSON.stringify(["HASH-LAST"]) }); const harness = makeRegenHarness({ db }); const { step2, ctx } = await harness.load(); // The account owner legitimately spends their final recovery code elsewhere // (password change / generate-recovery): the shared CAS claim burns it and // the row now stores "[]" — the exact bytes a degenerate legacy row has. const claim = await ctx.claimRecoveryCode(REGEN_USER, "HASH-LAST"); assert.ok(claim.ok === true && claim.remaining === 0, "the last code burns cleanly via the real CAS claim"); assert.equal(db.state.recoveryCodes, "[]", "the row now holds the empty array"); // Step 2 with a valid password stamp but NO TOTP and NO grant: the old // length-based branch minted 7 codes here with method "password". const session = { user: REGEN_USER.email, recoveryRegenAuth: regenStamp(sha256HexStub(REGEN_USER.password)), }; const res = makeRegenRes(); await step2(makeRegenReq({ body: {}, session }), res); assert.equal(res.statusCode, 403, "an exhausted (empty) inventory must refuse, not mint"); assert.deepEqual(res.body, { error: "A valid 6-digit code is required", code: "2fa-required" }); assert.equal(countMintWrites(db), 0, "no keyless minting UPDATE may run"); assert.equal(db.state.recoveryCodes, "[]", "the stored array stays empty"); assert.ok("recoveryRegenAuth" in session, "the stamp survives the refusal (a retry with a correct TOTP stays possible)"); }); test("behavior: a legacy zero-codes row with no second factor refuses identically", async () => { const db = makeRegenDb({ storedJson: "[]" }); const { step2 } = await makeRegenHarness({ db }).load(); const session = { user: REGEN_USER.email, recoveryRegenAuth: regenStamp(sha256HexStub(REGEN_USER.password)), }; const res = makeRegenRes(); await step2(makeRegenReq({ body: {}, session }), res); assert.equal(res.statusCode, 403); assert.deepEqual(res.body, { error: "A valid 6-digit code is required", code: "2fa-required" }); assert.equal(countMintWrites(db), 0, "zero codes alone must never mint"); }); test("behavior: a valid TOTP still mints 7 codes via the totp method and consumes the stamp", async () => { const db = makeRegenDb({ storedJson: "[]" }); const { step2 } = await makeRegenHarness({ db }).load(); const session = { user: REGEN_USER.email, recoveryRegenAuth: regenStamp(sha256HexStub(REGEN_USER.password)), }; const res = makeRegenRes(); await step2(makeRegenReq({ body: { twoFactorCode: "123456" }, session }), res); assert.equal(res.statusCode, 200); assert.equal(res.body.regeneratedVia, "totp", "the TOTP method is recorded"); assert.equal(res.body.recoveryCodes.length, 7, "exactly 7 codes are minted"); for (const code of res.body.recoveryCodes) { assert.match(code, /^[A-HJ-NP-Z2-9]{8}$/, "each plaintext code matches the CSPRNG alphabet"); } assert.ok(!("recoveryRegenAuth" in session), "the single-use stamp is consumed on success"); const mints = db.queries.filter((q) => q.sql === RECOVERY_CODES_COMMIT_SQL); assert.equal(mints.length, 1, "exactly one generation-guarded minting UPDATE runs"); const written = JSON.parse(mints[0].params[0]); assert.equal(written.length, 7, "the write stores 7 hashed codes"); }); test("behavior: a credential reset during hashing refuses recovery-code minting", async () => { const user = { ...REGEN_USER, session_epoch: 17 }; const db = makeRegenDb({ storedJson: JSON.stringify(["OWNER-CODE"]) }); const { step2, ctx } = await makeRegenHarness({ user, db }).load(); let hashes = 0; ctx.bcrypt.hash = async () => { hashes += 1; if (hashes === 1) { db.state.epoch = 18; db.state.recoveryCodes = JSON.stringify(["REMEDIATED-CODE"]); } return "stale-proof-code-hash"; }; const session = { user: user.email, recoveryRegenAuth: regenStamp(sha256HexStub(user.password)), }; const res = makeRegenRes(); await step2(makeRegenReq({ body: { twoFactorCode: "123456" }, session }), res); assert.equal(res.statusCode, 409, "a reset invalidates the proof before the codes commit"); assert.ok(!res.body.recoveryCodes, "a stale proof must never receive recovery credentials"); assert.equal(db.state.recoveryCodes, JSON.stringify(["REMEDIATED-CODE"]), "the remediation's code set must survive"); assert.equal(hashes, 7, "the test interleaves the reset inside the real hashing window"); }); test("behavior: recovery minting refuses a changed password or code set even without an epoch change", async () => { for (const changedField of ["password", "recoveryCodes"]) { const db = makeRegenDb({ storedJson: JSON.stringify(["ORIGINAL-CODE"]) }); const { step2, ctx } = await makeRegenHarness({ db }).load(); ctx.bcrypt.hash = async () => { db.state[changedField] = changedField === "password" ? "new-password-hash" : JSON.stringify(["NEW-CODE-SET"]); return "stale-proof-code-hash"; }; const session = { user: REGEN_USER.email, recoveryRegenAuth: regenStamp(sha256HexStub(REGEN_USER.password)), }; const res = makeRegenRes(); await step2(makeRegenReq({ body: { twoFactorCode: "123456" }, session }), res); assert.equal(res.statusCode, 409, `${changedField}: the stale proof cannot overwrite current credentials`); assert.ok(!res.body.recoveryCodes, `${changedField}: no plaintext credentials returned`); assert.ok(!db.state.recoveryCodes.includes("stale-proof-code-hash"), `${changedField}: no stale hashes persisted`); } }); test("behavior: a missing proof epoch refuses recovery minting without a write", async () => { const db = makeRegenDb({ storedJson: "[]" }); const { step2 } = await makeRegenHarness({ user: { ...REGEN_USER, session_epoch: undefined }, db }).load(); const session = { user: REGEN_USER.email, recoveryRegenAuth: regenStamp(sha256HexStub(REGEN_USER.password)), }; const res = makeRegenRes(); await step2(makeRegenReq({ body: { twoFactorCode: "123456" }, session }), res); assert.equal(res.statusCode, 409); assert.equal(countMintWrites(db), 0); assert.ok(!res.body.recoveryCodes); }); test("behavior: a recovery commit error returns no credentials and keeps the current code set", async () => { const db = makeRegenDb({ storedJson: JSON.stringify(["OWNER-CODE"]) }); const query = db.query.bind(db); db.query = async (sql, params) => { if (sql === RECOVERY_CODES_COMMIT_SQL) throw new Error("database unavailable"); return query(sql, params); }; const { step2 } = await makeRegenHarness({ db }).load(); const session = { user: REGEN_USER.email, recoveryRegenAuth: regenStamp(sha256HexStub(REGEN_USER.password)), }; const res = makeRegenRes(); await step2(makeRegenReq({ body: { twoFactorCode: "123456" }, session }), res); assert.equal(res.statusCode, 500); assert.ok(!res.body.recoveryCodes); assert.equal(db.state.recoveryCodes, JSON.stringify(["OWNER-CODE"])); }); test("behavior: a live recovery grant still mints via the recovery-grant method and burns the code atomically", async () => { const db = makeRegenDb({ storedJson: JSON.stringify(["HASH-GRANT"]) }); const { step2 } = await makeRegenHarness({ db }).load(); const session = { user: REGEN_USER.email, recoveryRegenAuth: regenStamp(sha256HexStub(REGEN_USER.password)), recoveryVerified: { userId: REGEN_USER.id, email: REGEN_USER.email, nonce: "grant-nonce", verifiedAt: Date.now(), codeHash: "HASH-GRANT", }, }; const res = makeRegenRes(); await step2(makeRegenReq({ body: {}, session }), res); assert.equal(res.statusCode, 200); assert.equal(res.body.regeneratedVia, "recovery-grant", "the grant method is recorded"); assert.ok(!("recoveryVerified" in session), "the spent grant flag is deleted"); assert.ok(!("recoveryRegenAuth" in session), "the single-use stamp is consumed on success"); const casClaims = db.queries.filter((q) => q.sql === "UPDATE users SET recovery_codes = ? WHERE id = ? AND recovery_codes = ?"); assert.equal(casClaims.length, 1, "the grant burn runs exactly once as a CAS"); assert.equal(countMintWrites(db), 1, "the mint follows the burn"); }); test("behavior: a missing, expired or foreign stamp answers 403 password-required before any factor is even read", async () => { for (const [label, overrides] of [ ["missing", { __absent: true }], ["expired", { verifiedAt: Date.now() - 6 * 60 * 1000 }], ["foreign user", { userId: 999 }], ]) { const db = makeRegenDb({ storedJson: JSON.stringify(["HASH-SOMETHING"]) }); const { step2 } = await makeRegenHarness({ db }).load(); const session = { user: REGEN_USER.email }; if (!overrides.__absent) session.recoveryRegenAuth = regenStamp(sha256HexStub(REGEN_USER.password), overrides); const res = makeRegenRes(); await step2(makeRegenReq({ body: { twoFactorCode: "123456" }, session }), res); assert.equal(res.statusCode, 403, `${label}: the stamp gate fires first`); assert.deepEqual(res.body, { error: "Password verification required. Enter your current password to continue.", code: "password-required", }, `${label}: the flat password-required answer`); assert.equal(db.queries.length, 0, `${label}: nothing is read from the DB once the stamp is invalid`); } }); test("behavior: a stamp minted against a since-rotated password answers 403 password-stale", async () => { const db = makeRegenDb({ storedJson: "[]" }); const { step2 } = await makeRegenHarness({ db }).load(); const session = { user: REGEN_USER.email, recoveryRegenAuth: regenStamp(sha256HexStub("the-old-stored-hash")), }; const res = makeRegenRes(); await step2(makeRegenReq({ body: { twoFactorCode: "123456" }, session }), res); assert.equal(res.statusCode, 403); assert.equal(res.body.code, "password-stale", "the fresh-row fingerprint re-check fires"); assert.equal(countMintWrites(db), 0, "no minting on a stale stamp"); assert.ok(!("recoveryRegenAuth" in session), "the stale stamp is deleted (fail closed, one attempt)"); }); test("behavior: a rejected TOTP answers 403 Incorrect 2FA code and mints nothing", async () => { const db = makeRegenDb({ storedJson: JSON.stringify(["HASH-KEEP"]) }); const { step2 } = await makeRegenHarness({ db, totpOk: false }).load(); const session = { user: REGEN_USER.email, recoveryRegenAuth: regenStamp(sha256HexStub(REGEN_USER.password)), }; const res = makeRegenRes(); await step2(makeRegenReq({ body: { twoFactorCode: "999999" }, session }), res); assert.equal(res.statusCode, 403); assert.deepEqual(res.body, { error: "Incorrect 2FA code" }); assert.equal(countMintWrites(db), 0, "no minting on a wrong TOTP"); assert.equal(db.state.recoveryCodes, JSON.stringify(["HASH-KEEP"]), "the stored codes are untouched"); }); test("behavior: a malformed stored array answers 500 — distinct from zero codes", async () => { const db = makeRegenDb({ storedJson: '{"not":"an-array"}' }); const { step2 } = await makeRegenHarness({ db }).load(); const session = { user: REGEN_USER.email, recoveryRegenAuth: regenStamp(sha256HexStub(REGEN_USER.password)), }; const res = makeRegenRes(); await step2(makeRegenReq({ body: { twoFactorCode: "123456" }, session }), res); assert.equal(res.statusCode, 500, "a malformed array must not be readable as zero codes"); assert.deepEqual(res.body, { error: "Failed to regenerate recovery codes" }); assert.equal(countMintWrites(db), 0, "no minting on unknown stored state"); }); test("behavior: a DB error on the stored read answers 500, never a success or a credential error", async () => { const db = makeRegenDb({ storedJson: "[]", readError: new Error("db down") }); const { step2 } = await makeRegenHarness({ db }).load(); const session = { user: REGEN_USER.email, recoveryRegenAuth: regenStamp(sha256HexStub(REGEN_USER.password)), }; const res = makeRegenRes(); await step2(makeRegenReq({ body: { twoFactorCode: "123456" }, session }), res); assert.equal(res.statusCode, 500, "an unreachable DB is a 500"); assert.deepEqual(res.body, { error: "Failed to regenerate recovery codes" }); assert.equal(countMintWrites(db), 0, "no minting on unknown stored state"); });