"use strict"; // adpanel:login-proof-generation — the captcha-completion half of the login // proof-generation finding. completePendingCaptchaLogin already re-resolved // the row and re-verified the challenge-time fingerprint before binding (the // pattern the POST /login staleness re-proof mirrors), but it recorded NO // credential generation and re-checked NOTHING after its pre-bind read: a // credential change (password reset / 2FA rotation) committing inside the // shared binder's regenerate→save window was invisible — the change-time // sweep cannot see the unbound regenerated sid or the unminted remember id, // so the completion minted a live session + a fresh 365-day remember // credential fingerprinted from the NEW hash, surviving the very change whose // revocation already ran. // // Fix (this file pins it): // 1. beginPendingCaptchaLogin records accountEpoch — the credential // generation the pending proof was minted against (raw Number(); a // legacy read yields NaN and a Redis round-trip serializes NaN to null — // both UNCOMPARABLE at mint time, the fingerprint leg then being the // sole completion authority, per the shared contract in // utils/session-account-binding.js). // 2. completePendingCaptchaLogin denies with the existing login-expired // envelope when the recorded generation differs from the live row's // (comparable epochs only, via credentialGenerationMismatch). // 3. the completion's bindLoginSession call gains a beforeSave validation: // a FRESH findUserByEmail re-read after the binder's regeneration and // before the persistence save rejects (labeled error arm:stale-completion, // which the shared binder's catch has already hygiened — remember // credential revoked, regenerated sid tombstoned — by the time it // reaches the route) on: row missing/credential-less/suspended, epoch // mismatch, fingerprint mismatch, MFA state change, seed bytes change, // or password-hash change (no re-proof is available on this path — a // rehash landing inside the window denies fail closed). Any OTHER error // rethrows to the route's existing catch unchanged. // // The harnesses use the house vm-extraction technique (the REAL pending // helpers, the REAL begin + completion bodies, the REAL shared binder over // recording deps, REAL bcryptjs at cost 4 and REAL sha256 fingerprints), so // the interleaves below are simulations of the timeline, not // re-implementations of the guard. 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 bcryptjs = require("bcryptjs"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const { createLoginSessionBinder } = require(path.join(ROOT, "utils", "login-session-bind.js")); const { credentialGenerationMismatch } = require(path.join(ROOT, "utils", "session-account-binding.js")); function indexOfOrThrow(needle, from = 0) { const idx = indexSource.indexOf(needle, from); assert.ok(idx >= 0, `expected source pin not found: ${needle}`); return idx; } function countOccurrences(needle, haystack = indexSource) { let count = 0; let pos = 0; for (;;) { const idx = haystack.indexOf(needle, pos); if (idx < 0) return count; count += 1; pos = idx + needle.length; } } // Balanced `{ ... }`-terminated block starting at a marker, brace-counting // outside strings and comments (same approach as the sibling vm-extraction // tests). function extractBalancedBlock(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker not found: ${startMarker}`); let i = start + startMarker.length; let depth; if (startMarker.endsWith("{")) { depth = 1; } else { while (i < source.length && /\s/.test(source[i])) i += 1; assert.ok(i < source.length && source[i] === "{", `no opening brace after: ${startMarker}`); depth = 1; } let inString = null; while (i < source.length && depth > 0) { i += 1; const ch = source[i]; if (inString) { if (ch === "\\") { i += 1; continue; } if (ch === inString) inString = null; continue; } if (ch === "/" && source[i + 1] === "/") { while (i < source.length && source[i] !== "\n") i += 1; continue; } if (ch === "/" && source[i + 1] === "*") { i += 2; while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i += 1; i += 1; continue; } if (ch === '"' || ch === "'" || ch === "`") inString = ch; else if (ch === "{") depth += 1; else if (ch === "}") depth -= 1; } assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`); return source.slice(start, i + 1); } const WITH_TIMEOUT_SOURCE = extractBalancedBlock(indexSource, "function withTimeout(promise, ms, label = \"timeout\") {"); const SAFE_COMPARE_SOURCE = extractBalancedBlock(indexSource, "function safeCompare(a, b) {"); const HAS_TWO_FACTOR_SOURCE = extractBalancedBlock(indexSource, "function hasTwoFactorEnabled(user) {"); const REQ_FP_SOURCE = extractBalancedBlock(indexSource, "function getPendingCaptchaLoginRequestFingerprint(req) {"); const CLEAR_PENDING_SOURCE = extractBalancedBlock(indexSource, "function clearPendingCaptchaLogin(req) {"); const GET_PENDING_SOURCE = extractBalancedBlock(indexSource, "function getPendingCaptchaLogin(req) {"); const PROTECTED_STATE_SOURCE = extractBalancedBlock(indexSource, "function sessionCarriesProtectedPendingAuthState(session) {"); const BEGIN_PENDING_SOURCE = extractBalancedBlock(indexSource, "function beginPendingCaptchaLogin(req, user, options = {}) {"); const COMPLETION_SOURCE = extractBalancedBlock(indexSource, "async function completePendingCaptchaLogin(req, res) {"); // The REAL self-contained helpers, instantiated once in minimal realms (the // crypto/Buffer-only dependencies they have in index.js). const REAL_WITH_TIMEOUT = vm.runInContext(`(${WITH_TIMEOUT_SOURCE})`, vm.createContext({ setTimeout, clearTimeout, Promise })); const SAFE_COMPARE = vm.runInContext(`(${SAFE_COMPARE_SOURCE})`, vm.createContext({ Buffer, crypto })); const { getRememberLoginFingerprint: GET_FP } = require("../utils/remember-login-fingerprint"); const HAS_TWO_FACTOR = vm.runInContext(`(${HAS_TWO_FACTOR_SOURCE})`, vm.createContext({})); const CLEAR_PENDING_FN = vm.runInContext(`(${CLEAR_PENDING_SOURCE})`, vm.createContext({})); const PROTECTED_STATE_FN = vm.runInContext(`(${PROTECTED_STATE_SOURCE})`, vm.createContext({})); // --------------------------------------------------------------------------- // Real credentials (bcryptjs, cost 4 — millisecond compares, real verdicts) // --------------------------------------------------------------------------- const PASSWORD = "correct horse battery staple"; const NEW_PASSWORD = "rotated-away password"; const OLD_HASH = bcryptjs.hashSync(PASSWORD, 4); const REHASH_HASH = bcryptjs.hashSync(PASSWORD, 4); // same password, DIFFERENT salt assert.notStrictEqual(OLD_HASH, REHASH_HASH, "two hashes of the same password must be unequal strings (the benign-rehash premise)"); assert.ok(bcryptjs.compareSync(PASSWORD, OLD_HASH) && bcryptjs.compareSync(PASSWORD, REHASH_HASH), "precondition: both same-password hashes verify"); const CANONICAL = "victim@example.test"; const USER_ID = 77; const EPOCH = 5; function row(overrides = {}) { return Object.assign( { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: EPOCH }, overrides ); } // --------------------------------------------------------------------------- // Source pins // --------------------------------------------------------------------------- test("begin source pin: the pending record carries the minted credential generation (raw, uncoerced semantics documented)", () => { const beginBody = BEGIN_PENDING_SOURCE; assert.ok(beginBody.includes("accountEpoch: Number(user.session_epoch),"), "the record carries accountEpoch as the raw Number of the row's generation"); assert.ok(beginBody.includes("adpanel:login-proof-generation"), "the record carries its adpanel tag (null/NaN = uncomparable at mint time)"); // The other bindings of the pending record stay intact (sibling pin: // tests/local-captcha-retired.test.js holds the fingerprint + TTL legs). assert.ok(beginBody.includes("requestFingerprint: getPendingCaptchaLoginRequestFingerprint(req),"), "the request fingerprint binding stays"); assert.ok(beginBody.includes("expiresAt: now + PENDING_CAPTCHA_LOGIN_TTL_MS,"), "the TTL binding stays"); }); test("completion source pins: the epoch gate sits fingerprint → 2FA-consistency → epoch → bind; the beforeSave revalidation is the fresh-read window cover", () => { const fingerprintIdx = COMPLETION_SOURCE.indexOf("const expectedUserFingerprint = getRememberLoginFingerprint(user);"); const twoFaIdx = COMPLETION_SOURCE.indexOf("if (hasTwoFactorEnabled(user) && !pending.twoFactorVerified) {"); const epochIdx = COMPLETION_SOURCE.indexOf("credentialGenerationMismatch(pending.accountEpoch, user.session_epoch)"); const bindIdx = COMPLETION_SOURCE.indexOf("await loginSessionBinder.bindLoginSession(req, res, {"); assert.ok(fingerprintIdx >= 0 && fingerprintIdx < twoFaIdx && twoFaIdx < epochIdx && epochIdx < bindIdx, "ordering is load-bearing: fingerprint → 2FA consistency → epoch gate → bind"); assert.ok(COMPLETION_SOURCE.includes("clearPendingCaptchaLogin(req);"), "denials clear the pending record"); const bindCall = extractBalancedBlock(COMPLETION_SOURCE, "await loginSessionBinder.bindLoginSession(req, res, {"); assert.ok(bindCall.includes("beforeSave: async () => {"), "the completion's bind carries the beforeSave revalidation hook"); assert.ok(bindCall.includes("const revalidated = await findUserByEmail(pending.email);"), "the hook re-reads the row fresh (never cached state)"); assert.ok(bindCall.includes("credentialGenerationMismatch(pending.accountEpoch, revalidated.session_epoch)"), "the recorded generation is re-checked against the fresh row via the ONE shared comparison"); assert.ok(bindCall.includes("getRememberLoginFingerprint(revalidated)"), "the hook re-verifies the challenge-time fingerprint against the fresh row"); assert.ok(bindCall.includes("revalidated.password !== user.password"), "a moved hash denies fail closed (no re-proof is available on this path)"); // The labeled-error helper sits at the top of the completion and the // converting wrapper after the bind call — pin them on the whole function // source. assert.ok(COMPLETION_SOURCE.includes('code: "arm:stale-completion"'), "the hook rejects through the labeled error"); assert.ok(COMPLETION_SOURCE.includes('err?.code === "arm:stale-completion"'), "the wrapper converts ONLY the labeled staleness error"); assert.ok(COMPLETION_SOURCE.includes('return { ok: false, status: 401, error: "login-expired" };'), "the labeled settle is the existing login-expired envelope"); assert.ok(COMPLETION_SOURCE.includes("throw err;"), "non-labeled errors rethrow to the route's existing catch unchanged"); // The historical interstitial hooks keep their positions. assert.ok(bindCall.includes("afterIdentityBinding: () => {") && bindCall.includes("clearPendingCaptchaLogin(req);"), "the pending clear stays in the afterIdentityBinding hook"); assert.ok(bindCall.includes("loginThrottle.resetTotpSource(pending.email, loginThrottle.ipKey(clientIp), user)"), "the TOTP budget reset stays in the beforeSave hook (after the revalidation)"); // The epoch gate is comparable-only: the null/NaN pending record (legacy // read / Redis round-trip) never denies by itself — the fingerprint leg is // then the sole authority (shared contract). const gateStart = COMPLETION_SOURCE.indexOf("// adpanel:login-proof-generation", twoFaIdx); assert.ok(gateStart >= 0 && gateStart < epochIdx, "the epoch gate carries its adpanel tag before the comparison"); const epochGate = COMPLETION_SOURCE.slice(gateStart, epochIdx + 120); assert.ok(epochGate.includes("pending.accountEpoch != null") && epochGate.includes("Number.isFinite(Number(pending.accountEpoch))"), "the gate is guarded to comparable epochs only — an absent/NULL/NaN recorded epoch is UNCOMPARABLE, never 0"); }); // --------------------------------------------------------------------------- // Behavioral harness — the REAL completion over the REAL shared binder // --------------------------------------------------------------------------- function makeCompletionSandbox({ challengeRow, liveQueue, twoFactorVerified = false, maintenanceActive = false }) { const events = []; const warns = []; const tombstones = []; const rememberMints = []; const rememberRevokes = []; const cookieClears = []; const cacheUpserts = []; const binderEvents = []; const lookups = []; // The completion's pre-bind read returns the live row; a scenario that // commits a mid-window change sets __overrideLookups (inside the barrier) // so the LATER lookup — the beforeSave hook's fresh read — consumes those // rows instead. const overrideLookups = []; // The REAL shared binder over recording deps — the extracted completion // statement runs the tombstone→regenerate→bind→serve→save core verbatim, // with the mint/hygiene machinery observable through the dep recordings. const realBinder = createLoginSessionBinder({ withTimeout: REAL_WITH_TIMEOUT, writeRevokedSidTombstone: async (sid) => { tombstones.push(String(sid)); return true; }, sessionCarriesProtectedPendingAuthState: PROTECTED_STATE_FN, getSessionDisplayId: (sid) => `sid:${sid}`, ensureRememberLoginSessionId: (r) => { if (!r.session.rememberLoginId) r.session.rememberLoginId = "rid-captcha"; return r.session.rememberLoginId; }, buildBrowserSessionAuditFromRequest: (r, email, rememberLoginId) => ({ email, rememberLoginId }), setRememberLoginCookie: () => { rememberMints.push(1); return 7776000000; }, markRememberLoginSessionFresh: (r, expiresAt) => { r.session.rememberLoginExpiresAt = expiresAt; }, upsertActiveBrowserSessionCacheEntry: (sessionId) => { cacheUpserts.push(sessionId); }, clearRememberLoginCookie: () => { cookieClears.push(1); events.push("clearCookie"); }, revokeRememberLoginRegistryEntry: async (rememberLoginId) => { rememberRevokes.push(rememberLoginId); return true; }, logger: { warn: (...p) => warns.push(p.map(String).join(" ")) }, }); const sandbox = { PENDING_CAPTCHA_LOGIN_TTL_MS: 300000, crypto, Buffer, console: { warn: (...p) => warns.push(p.map(String).join(" ")), error: () => {}, log: () => {} }, setTimeout, clearTimeout, capdbg: () => {}, isMaintenanceActive: () => maintenanceActive, credentialGenerationMismatch, hasTwoFactorEnabled: HAS_TWO_FACTOR, safeCompare: SAFE_COMPARE, getRememberLoginFingerprint: GET_FP, clearPendingCaptchaLogin: CLEAR_PENDING_FN, sessionCarriesProtectedPendingAuthState: PROTECTED_STATE_FN, getRequestIp: () => "203.0.113.7", findUserByEmail: async () => { lookups.push(1); return overrideLookups.length ? overrideLookups.shift() : liveQueue[0]; }, revokeRememberLoginsForUser: async () => { events.push("revokeUser"); }, clearRememberLoginCookie: () => { events.push("clearCookie"); cookieClears.push(1); }, loginThrottle: { ipKey: (ip) => `ip(${ip})`, resetTotpSource: async () => { events.push("totpReset"); }, }, clearLoginCaptchaGateForIp: (key) => { events.push(`gateClear:${key}`); }, loginAuditRecorder: { recordSuccessfulLoginAudit: (rec) => { events.push(`audit:${String(rec.method)}`); }, recordFailedLoginAudit: () => { events.push("audit:failed"); }, }, loginSessionBinder: { bindLoginSession: async (reqArg, resArg, opts) => { binderEvents.push("bindCall"); return realBinder.bindLoginSession(reqArg, resArg, opts); }, }, req: { sessionID: "captcha-sid-1", get: (header) => (String(header || "").toLowerCase() === "user-agent" ? "va-agent/1.0" : undefined), session: { captchaRequired: true, captchaSolved: true }, }, res: {}, __challengeRow: challengeRow, __twoFactorVerified: twoFactorVerified, __pendingAtMint: null, __pendingAtMintLive: null, __events: events, __warns: warns, __tombstones: tombstones, __rememberMints: rememberMints, __rememberRevokes: rememberRevokes, __cookieClears: cookieClears, __cacheUpserts: cacheUpserts, __binderEvents: binderEvents, __lookups: lookups, __overrideLookups: overrideLookups, }; // express-session-shaped session record over the sandbox's req. const reqSession = sandbox.req.session; reqSession.regenerate = (cb) => { binderEvents.push("regenerate"); for (const key of Object.keys(reqSession)) { if (key !== "regenerate" && key !== "save") delete reqSession[key]; } sandbox.req.sessionID = "captcha-sid-2"; Promise.resolve() .then(() => (typeof sandbox.__insideRegenerate === "function" ? sandbox.__insideRegenerate() : undefined)) .then(() => cb(null), (err) => cb(err)); }; reqSession.save = (cb) => { binderEvents.push("save"); Promise.resolve() .then(() => (typeof sandbox.__insideSave === "function" ? sandbox.__insideSave() : undefined)) .then(() => cb(null), (err) => cb(err)); }; return sandbox; } // Mints the pending record through the REAL begin helper and runs the REAL // completion body verbatim in one scenario context. function runCompletion(sandbox, { roundTripPending = true } = {}) { const context = vm.createContext(sandbox); // getPendingCaptchaLogin / beginPendingCaptchaLogin / completePendingCaptchaLogin // are realm-bound (they read their helpers as globals) — declared as real // statements per scenario context, over the sandbox's own host helpers // (the request-fingerprint helper additionally resolves getRequestIp, so // it is bound here too rather than hoisted). vm.runInContext(REQ_FP_SOURCE, context, { filename: "req-fp.js" }); vm.runInContext(GET_PENDING_SOURCE, context, { filename: "get-pending.js" }); vm.runInContext(BEGIN_PENDING_SOURCE, context, { filename: "begin-pending.js" }); vm.runInContext(COMPLETION_SOURCE, context, { filename: "completion.js" }); const minted = vm.runInContext( "beginPendingCaptchaLogin(req, __challengeRow, { twoFactorVerified: __twoFactorVerified })", context, { filename: "begin-call.js" } ); assert.strictEqual(minted, true, "scenario precondition: the pending record must mint"); sandbox.__pendingAtMintLive = { ...sandbox.req.session.pendingCaptchaLogin }; sandbox.__pendingAtMint = JSON.parse(JSON.stringify(sandbox.req.session.pendingCaptchaLogin)); // The store round-trip: express-session serializes the session record to // JSON on save, so a later request reads a NaN epoch back as null — // apply it to the LIVE record, exactly what the completion will read. if (roundTripPending) { sandbox.req.session.pendingCaptchaLogin = JSON.parse(JSON.stringify(sandbox.req.session.pendingCaptchaLogin)); } // The verify route's own solve step (POST /api/captcha/verify, after the // provider verdict): the completion is only ever reached with the captcha // solved. sandbox.req.session.captchaSolved = true; sandbox.req.session.captchaRequired = false; return vm.runInContext("completePendingCaptchaLogin(req, res)", context, { filename: "completion-call.js" }); } test("benign completion: the pending record carries a finite minted epoch, the hook re-reads fresh, and the login completes", async () => { const challengeRow = row(); const sandbox = makeCompletionSandbox({ challengeRow, liveQueue: [row()] }); const result = await runCompletion(sandbox); assert.strictEqual(sandbox.__pendingAtMint.accountEpoch, EPOCH, "the minted record carries the challenge-time credential generation"); // Field-wise: the result object was minted in the vm realm (cross-realm // deepStrictEqual fails on prototype identity). assert.strictEqual(result.ok, true, "the benign completion succeeds"); assert.strictEqual(result.redirect, "/", "the success redirect is unchanged"); assert.strictEqual(sandbox.__lookups.length, 2, "two row reads: the pre-bind re-resolution AND the beforeSave hook's fresh re-read"); assert.strictEqual(sandbox.req.session.user, CANONICAL, "the session is bound"); assert.strictEqual(sandbox.req.session.accountEpoch, EPOCH, "the session carries the account epoch binding"); assert.strictEqual(sandbox.req.session.pendingCaptchaLogin, undefined, "the pending record is cleared (regenerated session + afterIdentityBinding)"); assert.deepStrictEqual(sandbox.__events, ["totpReset", "gateClear:ip(203.0.113.7)", "audit:captcha-completion"], "the historical success choreography: TOTP reset (beforeSave) → gate clear → durable audit row"); assert.ok(sandbox.__binderEvents.includes("regenerate") && sandbox.__binderEvents.includes("save"), "the shared core ran through the save"); assert.strictEqual(sandbox.__rememberRevokes.length, 0, "no credential revoked on success"); }); test("during maintenance only an admin can complete a pending CAPTCHA login", async () => { for (const admin of [true, false]) { const user = row({ admin }); const sandbox = makeCompletionSandbox({ challengeRow: user, liveQueue: [user], maintenanceActive: true }); const result = await runCompletion(sandbox); assert.strictEqual(result.ok, admin); assert.strictEqual(sandbox.req.session.user, admin ? CANONICAL : undefined); assert.strictEqual(sandbox.__rememberMints.length, admin ? 1 : 0); assert.strictEqual(sandbox.req.session.pendingCaptchaLogin, undefined); if (!admin) { assert.strictEqual(result.status, 503); assert.strictEqual(result.error, "maintenance"); assert.deepStrictEqual(sandbox.__binderEvents, []); } } }); test("epoch bumped after the challenge (before completion) — denied with the login-expired envelope and the pending record cleared", async () => { // The password reset committed (generation bumped) while the captcha was // being solved. The pre-bind fingerprint still matches (the password and // seed bytes are unchanged), so the epoch leg is the denier — a proof // minted against the old generation is never promoted onto the new one. const challengeRow = row(); const sandbox = makeCompletionSandbox({ challengeRow, liveQueue: [row({ session_epoch: EPOCH + 1 })] }); const result = await runCompletion(sandbox); assert.strictEqual(result.ok, false, "the completion is denied"); assert.strictEqual(result.status, 401, "the existing login-expired status, unchanged"); assert.strictEqual(result.error, "login-expired", "the existing login-expired envelope, unchanged"); assert.strictEqual(sandbox.req.session.pendingCaptchaLogin, undefined, "the pending record is cleared"); assert.deepStrictEqual(sandbox.__binderEvents, [], "the completion never reached the binder — no session bind"); assert.strictEqual(sandbox.__events.includes("audit:captcha-completion"), false, "no durable success row"); assert.strictEqual(sandbox.__events.includes("gateClear:ip(203.0.113.7)"), false, "the gate clear (post-bind) never ran"); }); test("secret rotated INSIDE the binder's regenerate→save window — the beforeSave revalidation denies, the minted remember credential is revoked and the sid tombstoned", async () => { // T0: every pre-bind check passes (fingerprint over password+SEED-A // matches; epoch equal; 2FA-verified). T1, inside the regenerate: the 2FA // seed rotates (SEED-B) — the change-time sweep cannot see this login (the // regenerated sid is unbound, the remember id unminted). T2: the hook's // fresh re-read sees the new seed (fingerprint leg), rejects through the // labeled error; the shared binder's catch revokes the just-minted // remember credential and tombstones the regenerated sid; the route // settles the login-expired envelope. const challengeRow = row({ secret: "SEED-A-SEED-A" }); const sandbox = makeCompletionSandbox({ challengeRow, liveQueue: [row({ secret: "SEED-A-SEED-A" })], twoFactorVerified: true }); sandbox.__insideRegenerate = () => { sandbox.__overrideLookups.push(row({ secret: "SEED-B-SEED-B" })); }; const result = await runCompletion(sandbox); assert.strictEqual(result.ok, false, "the completion is denied"); assert.strictEqual(result.status, 401, "the existing login-expired status, unchanged"); assert.strictEqual(result.error, "login-expired", "the existing login-expired envelope, unchanged"); assert.ok(sandbox.__binderEvents.includes("regenerate"), "the binder reached the regenerate"); assert.ok(!sandbox.__binderEvents.includes("save"), "the bounded save never ran — no authenticated record persisted"); assert.strictEqual(sandbox.__rememberMints.length, 1, "the remember credential was minted before the hook ran (the hygiene has something to revoke)"); assert.deepStrictEqual(sandbox.__rememberRevokes, ["rid-captcha"], "the just-minted remember credential was revoked by the binder's catch"); assert.strictEqual(sandbox.__cookieClears.length, 1, "the remember cookie was cleared off the failed response"); assert.deepStrictEqual(sandbox.__tombstones, ["captcha-sid-1", "captcha-sid-2"], "the pending-state pre-regeneration sid AND the regenerated sid were tombstoned so a late store write cannot commit the authenticated record"); assert.strictEqual(sandbox.__events.includes("audit:captcha-completion"), false, "no durable success row"); assert.strictEqual(sandbox.__events.includes("totpReset"), false, "the TOTP budget reset never ran (the login did not complete)"); assert.strictEqual(sandbox.__events.includes("gateClear:ip(203.0.113.7)"), false, "the gate clear never ran"); }); test("password rehashed INSIDE the window (same password, new cost, epoch unchanged) — denied fail closed: no re-proof exists on this path", async () => { // The direct-login path re-proves a moved hash; the completion path has // no submitted password (its proof is the challenge-time fingerprint), so // a hash that moved inside the window denies closed — the conservative // direction a user retries through a fresh login. const challengeRow = row(); const sandbox = makeCompletionSandbox({ challengeRow, liveQueue: [row()], twoFactorVerified: false }); sandbox.__insideRegenerate = () => { sandbox.__overrideLookups.push(row({ password: REHASH_HASH })); }; const result = await runCompletion(sandbox); assert.strictEqual(result.ok, false, "the completion is denied"); assert.strictEqual(result.status, 401, "the existing login-expired status, unchanged"); assert.strictEqual(result.error, "login-expired", "the existing login-expired envelope, unchanged"); assert.ok(!sandbox.__binderEvents.includes("save"), "the save never ran"); assert.deepStrictEqual(sandbox.__rememberRevokes, ["rid-captcha"], "the minted remember credential was revoked"); assert.deepStrictEqual(sandbox.__tombstones, ["captcha-sid-1", "captcha-sid-2"], "the pending-state pre-regeneration sid AND the regenerated sid were tombstoned"); }); test("legacy pending records (null epoch after a Redis round-trip, or NaN from an epoch-less row) stay comparable-blind and complete on the fingerprint authority", async () => { for (const shape of ["null", "NaN"]) { const epochless = { session_epoch: undefined }; const challengeRow = row(epochless); const sandbox = makeCompletionSandbox({ challengeRow, liveQueue: [row(epochless)] }); const result = await runCompletion(sandbox, { roundTripPending: shape === "null" }); if (shape === "null") { assert.strictEqual(sandbox.__pendingAtMint.accountEpoch, null, "the round-trip shape: the minted NaN epoch serialized to null"); } else { assert.ok(Number.isNaN(sandbox.__pendingAtMintLive.accountEpoch), "the in-memory legacy shape: the recorded epoch is NaN"); } assert.strictEqual(result.ok, true, `${shape}: the uncomparable recorded epoch never denies an honest completion`); assert.strictEqual(result.redirect, "/", `${shape}: the success redirect is unchanged`); assert.strictEqual(sandbox.req.session.user, CANONICAL, `${shape}: the session is bound`); } }); test("a NON-labeled binder failure rethrows to the route's existing catch (no envelope conversion, hygiene still runs)", async () => { // The TOTP budget reset inside the hook fails with an infrastructure // error: the wrapper must NOT convert it to login-expired — the route's // 500 catch owns it — while the binder's own catch still revokes the // minted remember credential. const challengeRow = row(); const sandbox = makeCompletionSandbox({ challengeRow, liveQueue: [row()] }); sandbox.loginThrottle.resetTotpSource = async () => { sandbox.__events.push("totpReset"); throw new Error("totp-store-down"); }; await assert.rejects( runCompletion(sandbox), (err) => err instanceof Error && err.message === "totp-store-down", "the original error reaches the route's catch unchanged (no login-expired conversion)" ); assert.ok(!sandbox.__binderEvents.includes("save"), "the save never ran"); assert.deepStrictEqual(sandbox.__rememberRevokes, ["rid-captcha"], "the minted remember credential was revoked by the binder's catch"); assert.deepStrictEqual(sandbox.__tombstones, ["captcha-sid-1", "captcha-sid-2"], "the pending-state pre-regeneration sid AND the regenerated sid were tombstoned"); });