"use strict"; // adpanel:credential-change-cas + adpanel:totp-confirm-cas + // adpanel:credential-session-rebind + adpanel:credential-generation — // source pins + behavior pins for the credential-change hardenings. // // Findings pinned here: // 1. (CAS) All four credential writes are compare-and-swaps on the verified // snapshot credential (id + the pre-flight row's credential; the email // write additionally pins LOWER(email); the 2FA write pins the raw // stored secret with a NULL-safe `<=>` so a first-enrollment row's NULL // matches). affectedRows decides: a loser answers 409 (wrong-code 403 on // the 2FA confirm) and STOPS — no session invalidation, no socket // disconnect, no remember re-issue, no success fields. A keyless // email-keyed write silently overwrote a concurrent admin reset and then // evicted sessions as if its credential were current. // 2. (Rebind) No route passes excludeSessionId to the user-wide destroy // anymore, and no route re-issues the remember cookie directly: all four // delegate to the ONE shared rebinder (utils/credential-session-rebind.js), // which destroys EVERY session of the user (current sid included), // regenerates, re-binds identity, re-issues with forceFreshId, upserts // the cache entry and saves under the binder's timeouts with the login // binder's post-mint failure hygiene. // 3. (2FA rotation) The pre-write step-claim gate is GONE — it rejected a // VALID new-authenticator code whenever the confirm landed in the same // 30s window as the old-secret verification (the normal prompt flow). // The CAS publishes the new seed and its consumed step together, without // a replay-counter condition that would reject same-step rotation. The // stored-secret replay check and CAS still allow only one confirmation. // 4. (Credential generation) Every interactive credential write bumps // users.session_epoch IN THE SAME statement as the credential // (adpanel:credential-generation) and threads the NEW epoch into the // rebind payload, so the owner's regenerated session binds the // generation the CAS just committed instead of the stale pre-write // snapshot's. Non-credential writers (login bcrypt rehash, // recovery-code burn, TOTP counter claim) stay epoch-free: a lost final // CAS must not have already bumped. // // Behavior harness: the house vm-extraction technique — the REAL route // statements are extracted from index.js verbatim and run against fake db / // session / response objects, a REAL rebinder instance built from the // utils module with fake deps, and the REAL epoch generator from // utils/session-epoch.js. 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 ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const REBINDER_JS = path.join(ROOT, "utils", "credential-session-rebind.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const rebinderSource = fs.readFileSync(REBINDER_JS, "utf8"); const commitSource = fs.readFileSync(path.join(ROOT, "services", "account-credentials.js"), "utf8"); const { createCredentialSessionRebinder } = require("../utils/credential-session-rebind.js"); const { createCredentialCommitService, CREDENTIAL_COMMIT_SQL, RECOVERY_CODES_COMMIT_SQL } = require("../services/account-credentials"); const { newSessionEpoch, newSessionEpochDifferentFrom } = require("../utils/session-epoch.js"); const { credentialGenerationMismatch } = require("../utils/session-account-binding.js"); // adpanel:session-inventory-error-propagation — the route statements now // render sessionInvalidationWarnings through the ONE shared renderer, so the // vm harness injects the REAL module exactly as index.js wires it (a stub // here would let the routes drift from the real rendering contract). The // clean-path assertion below (warnings deep-equal []) is unchanged: the // renderer appends a note only when the destroyer reports scanIncomplete. const { renderSessionInvalidationWarnings } = require("../utils/session-invalidation-warnings.js"); function countOccurrences(haystack, needle) { return haystack.split(needle).length - 1; } // 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 ROUTE_PASSWORD = 'app.post("/api/account/password/change"'; const ROUTE_SETTINGS_PASSWORD = 'app.post("/api/settings/change-password"'; const ROUTE_EMAIL = 'app.post("/api/account/email/change"'; const ROUTE_CONFIRM = 'app.post("/api/account/2fa/confirm"'; // Distinguish the plain generate (accountTotpRateLimiter) from // generate-recovery (recoveryRateLimiter): BOTH stamp the pending rotation's // origin generation — the recovery path stamps with OVERWRITE semantics // (claimRecoveryCode never touches users.secret, so its fresh read IS the // origin generation, and overwriting kills a lingering standard-generate // stamp that would otherwise pin an abandoned generation). const ROUTE_GENERATE = 'app.post("/api/account/2fa/generate", accountTotpRateLimiter'; const ROUTE_GENERATE_RECOVERY = 'app.post("/api/account/2fa/generate-recovery", recoveryRateLimiter'; const statements = { password: extractRouteStatement(indexSource, ROUTE_PASSWORD), settings: extractRouteStatement(indexSource, ROUTE_SETTINGS_PASSWORD), email: extractRouteStatement(indexSource, ROUTE_EMAIL), confirm: extractRouteStatement(indexSource, ROUTE_CONFIRM), generate: extractRouteStatement(indexSource, ROUTE_GENERATE), recoveryGenerate: extractRouteStatement(indexSource, ROUTE_GENERATE_RECOVERY), }; // --------------------------------------------------------------------------- // Source pins — the four CAS writes // --------------------------------------------------------------------------- test("source: every credential write is a compare-and-swap on the verified snapshot that also bumps the epoch in-statement; the keyless shapes are gone", () => { assert.match(CREDENTIAL_COMMIT_SQL.password, /WHERE id = \? AND password = \? AND session_epoch = \?$/); assert.match(CREDENTIAL_COMMIT_SQL.email, /WHERE id = \? AND password = \? AND LOWER\(email\) = LOWER\(\?\) AND session_epoch = \?$/); assert.match(CREDENTIAL_COMMIT_SQL.twoFactor, /WHERE id = \? AND secret <=> \? AND session_epoch = \?$/); for (const [route, method] of [["password", "commitPassword"], ["settings", "commitPassword"], ["email", "commitEmail"], ["confirm", "commitTwoFactor"]]) { assert.ok(statements[route].includes(`await credentialCommitService.${method}(`), `${route}: delegate the guarded write to the shared service`); assert.ok(!statements[route].includes("UPDATE users SET"), `${route}: no parallel inline credential writer`); } for (const sql of Object.values(CREDENTIAL_COMMIT_SQL)) { assert.ok(commitSource.includes(sql), "the shared service owns the atomic credential and generation statement"); assert.match(sql, /SET .+, session_epoch = \?/); } // adpanel:credential-generation — the epoch rides the credential's own // statement everywhere: exactly these epoch-carrying shapes exist, and NO // epoch-only follow-up UPDATE may appear beside them. assert.equal(countOccurrences(indexSource, "UPDATE users SET session_epoch"), 0, "no epoch-only UPDATE may exist (the bump rides the credential's statement)"); assert.equal(countOccurrences(indexSource, "session_epoch = session_epoch"), 0, "no self-assignment generation arithmetic"); // The security-relevant disappearance: no keyless/email-keyed credential // write may come back anywhere in the monolith — and the credential shape // WITHOUT the epoch may not come back either (that would silently revert // the atomic bump). assert.equal(countOccurrences(indexSource, "UPDATE users SET password = ? WHERE LOWER(email) = LOWER(?)"), 0, "keyless password write must be gone"); assert.equal(countOccurrences(indexSource, "UPDATE users SET email = ? WHERE LOWER(email) = LOWER(?)"), 0, "email-keyed email write must be gone"); assert.equal(countOccurrences(indexSource, "UPDATE users SET secret = ?, recovery_codes = ? WHERE LOWER(email) = LOWER(?)"), 0, "email-keyed secret write must be gone"); // The CAS outcome is decided by affectedRows, and a loser stops with the // generic 409 BEFORE any eviction/re-issue machinery. Password + email // routes answer 409; the 2FA confirm keeps its uniform wrong-code 403. const STALE_409 = "Your credentials were just changed in another session or by an administrator. Re-verify and try again."; assert.equal(countOccurrences(indexSource, STALE_409), 3, "exactly the three password/email routes carry the stale-credential 409"); for (const [name, stmt, loserStatus, loserBefore] of [ ["password", statements.password, "409", "disconnectSocketsForUser"], ["settings", statements.settings, "409", "disconnectSocketsForUser"], ["email", statements.email, "409", "disconnectSocketsForUser"], ["confirm", statements.confirm, "403", "disconnectSocketsForUser"], ]) { const affectedIdx = stmt.indexOf("affectedRows"); assert.ok(affectedIdx >= 0, `${name}: the CAS outcome must be decided by affectedRows`); const loserIdx = stmt.indexOf(`res.status(${loserStatus})`, affectedIdx); assert.ok(loserIdx >= 0, `${name}: a lost CAS must answer ${loserStatus}`); const disconnectIdx = stmt.indexOf(loserBefore, affectedIdx); assert.ok(disconnectIdx > loserIdx, `${name}: the ${loserStatus} must answer BEFORE any socket disconnect / eviction`); const rebindIdx = stmt.indexOf("rebindOwnerSession"); assert.ok(rebindIdx > loserIdx, `${name}: the ${loserStatus} must answer BEFORE the session rebind`); } // The recovery-code claim still burns BEFORE the write (existing contract): // on the loser path the burned code is answered honestly with the 409. assert.ok(statements.password.indexOf("claimRecoveryCode") < statements.password.indexOf("await credentialCommitService.commitPassword("), "password: claim before write"); assert.ok(statements.email.indexOf("claimRecoveryCode") < statements.email.indexOf("await credentialCommitService.commitEmail("), "email: claim before write"); }); // --------------------------------------------------------------------------- // Source pins — non-credential writers stay epoch-free (adpanel:credential- // generation: a lost final CAS must not have already bumped) // --------------------------------------------------------------------------- test("source: the login rehash CAS, the recovery-code burn, the TOTP counter claim and the recovery-set replacements carry NO epoch", () => { // The login bcrypt rehash keeps its exact pinned shape (the byte-exact call // tests/bcrypt-cost-parity.test.js pins): no epoch param, no epoch column. const rehashCall = 'db.query("UPDATE users SET password = ? WHERE id = ? AND password = ?", [upgraded, user.id, user.password])'; assert.equal(countOccurrences(indexSource, rehashCall), 1, "the login rehash CAS is untouched by the epoch work (exactly one epoch-free shape remains)"); // claimRecoveryCode's burn: params stay [updated-json, id, current-json] — // a burn that had already bumped the epoch would let a loser of the // following credential CAS tear down sessions for a change that never // happened. const burnNeedle = '"UPDATE users SET recovery_codes = ? WHERE id = ? AND recovery_codes = ?"'; const burnIdx = indexSource.indexOf(burnNeedle); assert.ok(burnIdx >= 0, "the recovery-code burn exists"); const burnWindow = indexSource.slice(burnIdx, burnIdx + 220); assert.ok(!burnWindow.includes("session_epoch"), "the recovery-code burn stays epoch-free"); assert.ok(burnWindow.includes("[JSON.stringify(updated), user.id, JSON.stringify(currentArray)]"), "the burn's params are unchanged (no epoch param)"); // The recovery-set replacements (self-service regen route + admin recovery // reset) do not rotate a proof credential — no bump. (adpanel:admin-reset- // target-pinning: the admin reset's replacement is id-keyed with the admin // prohibition folded into the guarded write — the pin tracks the current // shape; the epoch-free intent is unchanged.) assert.ok(commitSource.includes(RECOVERY_CODES_COMMIT_SQL), "the shared service owns recovery regeneration's guarded write"); assert.match(RECOVERY_CODES_COMMIT_SQL, /AND password = \? AND session_epoch = \? AND recovery_codes <=> \?$/); assert.ok(!RECOVERY_CODES_COMMIT_SQL.split(" WHERE ")[0].includes("session_epoch"), "recovery regeneration checks the epoch but never changes it"); assert.ok(indexSource.includes("await credentialCommitService.commitRecoveryCodes("), "the regeneration route delegates to the guarded write"); const adminRecoveryNeedle = '"UPDATE users SET recovery_codes = ? WHERE id = ? AND admin = 0"'; const adminRecoveryIndex = commitSource.indexOf(adminRecoveryNeedle); assert.ok(adminRecoveryIndex >= 0, "the admin recovery reset's set replacement exists"); assert.ok(!commitSource.slice(adminRecoveryIndex, adminRecoveryIndex + 220).includes("session_epoch"), "the admin recovery reset stays epoch-free"); // The TOTP counter claim (utils/totp-claim.js) never touches the epoch. const totpClaimSource = fs.readFileSync(path.join(ROOT, "utils", "totp-claim.js"), "utf8"); assert.ok(!totpClaimSource.includes("session_epoch"), "the TOTP counter claim stays epoch-free"); }); // --------------------------------------------------------------------------- // Source pins — the shared rebind integration // --------------------------------------------------------------------------- test("source: no route keeps its own session alive; all four delegate the destroy/regenerate/re-issue to the ONE rebinder", () => { // The whole point of the fix: the current sid must never be excluded from // the user-wide sweep again, anywhere. assert.equal(countOccurrences(indexSource, "excludeSessionId: req.sessionID"), 0, "no route may exclude its own sid from the eviction"); // No route re-issues the remember cookie directly anymore: the only // setRememberLoginCookie( occurrence in index.js is the function definition // (the rebinder dep binding passes the bare identifier). assert.equal(countOccurrences(indexSource, "setRememberLoginCookie("), 1, "index.js must contain exactly the definition"); assert.equal(countOccurrences(indexSource, "setRememberLoginCookie(req, res, { ...user"), 0, "no direct route re-issue remains"); // The four interactive credential changes run the shared rebind. (The 2FA // GENERATE routes deliberately do not — they only stage pending state (and // stamp the origin generation); the confirm is the route that commits and // rebinds.) assert.equal(countOccurrences(indexSource, "credentialSessionRebinder.rebindOwnerSession(req, res"), 4, "all four routes must call the shared rebinder"); for (const [name, stmt] of Object.entries(statements).filter(([name]) => name !== "generate" && name !== "recoveryGenerate")) { assert.ok(stmt.includes("credentialSessionRebinder.rebindOwnerSession(req, res"), `${name}: must delegate to the shared rebinder`); } // The rebinder module owns the flagged mint and the exclusion-free destroy. assert.equal(countOccurrences(rebinderSource, "setRememberLoginCookie("), 1, "exactly the one flagged mint call exists in the rebinder"); assert.equal(countOccurrences(rebinderSource, "setRememberLoginCookie(req, res, user, { forceFreshId: true })"), 1, "the rebinder mints with forceFreshId (adpanel:remember-fresh-reissue)"); assert.ok(rebinderSource.includes("destroyBrowserSessionsForUser(destroyAs || user)"), "the rebinder destroys WITHOUT an exclusion"); assert.equal(countOccurrences(rebinderSource, "excludeSessionId"), 0, "the rebinder must not know an exclusion shape"); assert.ok(rebinderSource.includes("REGENERATE_TIMEOUT_MS = 5000") && rebinderSource.includes("SAVE_TIMEOUT_MS = 5000"), "the 5s store-callback bounds are structural"); assert.ok(rebinderSource.includes("writeRevokedSidTombstone(preRegenerateSid)") && rebinderSource.includes("writeRevokedSidTombstone(postFailureSid)"), "pre- and post-regeneration tombstones are structural (resurrection race)"); // The ONE binding site sits with the 2FA machinery in index.js and injects // the full dep set (the factory fails closed on any missing dep). assert.ok(indexSource.includes('const { createCredentialSessionRebinder } = require("./utils/credential-session-rebind");'), "the module is required one-way (never the reverse)"); const bindStart = indexSource.indexOf("const credentialSessionRebinder = createCredentialSessionRebinder({"); assert.ok(bindStart >= 0, "the binding site must exist"); const bindEnd = indexSource.indexOf("});", bindStart); const binding = indexSource.slice(bindStart, bindEnd); for (const dep of [ "withTimeout", "destroyBrowserSessionsForUser", "writeRevokedSidTombstone", "getSessionDisplayId", "ensureRememberLoginSessionId", "buildBrowserSessionAuditFromRequest", "setRememberLoginCookie", "markRememberLoginSessionFresh", "upsertActiveBrowserSessionCacheEntry", "clearRememberLoginCookie", "revokeRememberLoginRegistryEntry", ]) { assert.ok(binding.includes(dep), `the binding must inject ${dep}`); } }); // --------------------------------------------------------------------------- // Source pins — one commit per generate (the origin-generation stamp) // --------------------------------------------------------------------------- test("source: the generate stamps the pending rotation's origin; the confirm pins the stamp with an undefined-only fallback and clears it with the pending secret", () => { // (a) The stamp: the generate reads the RAW stored bytes alongside its // pre-flight (findUserByEmail decrypts) and records them on the session. assert.ok(statements.generate.includes('SELECT id, secret FROM users WHERE id = ? LIMIT 1'), "the generate pre-flight reads the raw stored secret bytes"); assert.ok(statements.generate.includes("req.session.pending2faPriorSecret = priorSealedSecret;"), "the generate stamps the pending rotation's origin generation"); assert.equal(countOccurrences(indexSource, "req.session.pending2faPriorSecret = priorSealedSecret;"), 2, "exactly two stamping sites (standard generate + generate-recovery's OVERWRITE stamp — the recovery origin generation is the row as of its own generate, since claimRecoveryCode never touches users.secret)"); assert.ok(statements.recoveryGenerate.includes('SELECT id, secret FROM users WHERE id = ? LIMIT 1'), "the recovery generate's pre-flight reads the raw stored secret bytes"); assert.ok(statements.recoveryGenerate.includes("req.session.pending2faPriorSecret = priorSealedSecret;"), "the recovery generate stamps (OVERWRITE) its origin generation"); assert.equal(countOccurrences(indexSource, "req.session.pending2faPriorSecret === undefined"), 1, "exactly one fallback site (the confirm's CAS pin)"); // (b) The pin: the session-stamped prior secret wins when PRESENT — the // fallback triggers on undefined only (an in-flight pre-stamp session; // both generate paths stamp, so the fallback covers only those); null is a // legitimate first-enrollment stamp and must reach the CAS as SQL NULL. assert.ok( statements.confirm.includes("req.session.pending2faPriorSecret === undefined ? storedSealedSecret : req.session.pending2faPriorSecret"), "the pin prefers the stamp with an undefined-only fallback" ); assert.ok(statements.confirm.includes("commitTwoFactor(user, sealedSecret, JSON.stringify(hashedRecoveryCodes), pinValue, newEpoch, req.session.pending2faAccountEpoch, verificationStep + verifiedDelta.delta)"), "the CAS uses the generate-time proof and the exact verified step"); for (const route of [statements.generate, statements.recoveryGenerate]) { assert.ok(route.includes("req.session.pending2faAccountEpoch = user.session_epoch;"), "both setup flows stamp the proven account generation"); } assert.ok(statements.confirm.includes('SELECT id, secret FROM users WHERE id = ? LIMIT 1'), "the fresh pre-flight read stays (the replay pre-check reads the row's PRESENT bytes, not the generation pin)"); // (c) The stamp is cleared everywhere the pending secret is cleared; on a // CAS LOSS neither is cleared, so a stale generate's retry keeps losing. assert.equal( countOccurrences(statements.confirm, "delete req.session.pending2faSecret"), countOccurrences(statements.confirm, "delete req.session.pending2faPriorSecret"), "the stamp dies with the pending secret it authorizes" ); assert.equal(countOccurrences(statements.confirm, "delete req.session.pending2faSecret"), countOccurrences(statements.confirm, "delete req.session.pending2faAccountEpoch"), "the proof generation dies with the pending secret"); }); // --------------------------------------------------------------------------- // Source pins — the 2FA confirm redesign // --------------------------------------------------------------------------- test("source: 2FA confirmation consumes the verified step in the credential CAS, never in a separate claim", () => { assert.equal(countOccurrences(indexSource, "markTotpCodeUsed(totpAccountKey(user), codeStr);"), 1, "the confirm must keep its Map burn"); assert.equal(countOccurrences(statements.confirm, "claimTotpStep"), 0, "no separate counter claim may leave the seed and counter out of sync"); assert.match(CREDENTIAL_COMMIT_SQL.twoFactor, /SET .*totp_last_counter = GREATEST\(COALESCE\(totp_last_counter, 0\), \?\) WHERE/); // The CAS pins the raw stored secret read at pre-flight (randomized sealing // forbids re-seal-and-compare), and single-use confirmation is enforced by // the stored-secret replay check. assert.ok(statements.confirm.includes('SELECT id, secret FROM users WHERE id = ? LIMIT 1'), "the pre-flight reads the raw stored secret bytes"); assert.ok(statements.confirm.includes("decryptTotpSecret"), "the stored-secret replay check (single-use confirmation) is present"); }); // --------------------------------------------------------------------------- // Behavior harness — fake db / session / res + the REAL rebinder // --------------------------------------------------------------------------- const STALE_409_MESSAGE = "Your credentials were just changed in another session or by an administrator. Re-verify and try again."; function makeRes() { const res = { statusCode: 0, body: null, headersSent: false, cookies: [], cleared: [] }; res.status = (code) => { res.statusCode = code; res.headersSent = true; return res; }; res.json = (body) => { res.body = body; return res; }; res.cookie = (name, value, opts) => res.cookies.push({ name, value, opts }); res.clearCookie = (name, opts) => res.cleared.push({ name, opts }); return res; } function makeSession({ user = "user@example.test" } = {}) { return { user, accountId: 7, accountEpoch: 3, pending2faAccountEpoch: 3, rememberLoginId: "stale-remember-id", regenerate(cb) { this.__oldSid = this.__sid || "old-sid"; this.__sid = `regenerated-${Math.random().toString(16).slice(2, 8)}`; for (const key of Object.keys(this)) { if (!["regenerate", "save", "__sid"].includes(key)) delete this[key]; } this.user = user; // express-session keeps the raw record object; identity is re-bound by the rebinder cb(null); }, save(cb) { cb(null); }, }; } // Simple fake db for the password/email routes: recognizes the CAS UPDATE by // its exact SQL and answers with the configured affectedRows; anything else // is a test bug. function makeSimpleDb({ passwordAffectedRows = 1, emailAffectedRows = 1 } = {}) { const queries = []; return { queries, async query(sql, params) { queries.push({ sql, params }); if (sql === CREDENTIAL_COMMIT_SQL.password) { return { affectedRows: passwordAffectedRows }; } if (sql === CREDENTIAL_COMMIT_SQL.email) { return { affectedRows: emailAffectedRows }; } throw new Error(`unexpected db.query in test: ${sql}`); }, }; } // Stateful fake db for the 2FA confirm route: models the NULL-safe `<=>` // predicate semantics of the CAS and the pre-flight raw-secret read. The // optional latch holds the first CAS until `latchUntil` pre-flight reads have // happened, so two handlers can be driven truly concurrently. function makeConfirmDb({ initialSecret, initialCounter = null, latchUntil = 0, onBeforeUpdate } = {}) { const state = { secret: initialSecret, recovery_codes: "[]", secretUpdates: 0, epoch: 3, counter: initialCounter }; const queries = []; let selects = 0; let release = null; const bothSelected = new Promise((r) => { release = r; }); let hook = onBeforeUpdate; return { state, queries, async query(sql, params) { queries.push({ sql, params }); if (sql === "SELECT id, secret FROM users WHERE id = ? LIMIT 1") { selects += 1; if (selects >= latchUntil && release) { const r = release; release = null; r(); } return [{ id: params[0], secret: state.secret }]; } if (sql === CREDENTIAL_COMMIT_SQL.twoFactor) { if (selects < latchUntil) await bothSelected; if (hook) { const h = hook; hook = null; h(state); } const [secret, recoveryCodes, epoch, step, , pin, provedEpoch] = params; // `secret <=> ?` semantics: NULL pin matches a NULL stored value, // non-NULL pin matches the exact stored bytes. const matches = (pin == null ? state.secret == null : state.secret === pin) && state.epoch === provedEpoch; if (matches) { state.secret = secret; state.recovery_codes = recoveryCodes; state.epoch = epoch; state.counter = Math.max(state.counter ?? 0, step); state.secretUpdates += 1; return { affectedRows: 1 }; } return { affectedRows: 0 }; } throw new Error(`unexpected db.query in test: ${sql}`); }, }; } // Randomized-sealing model (each seal of the same plaintext is a distinct // envelope — the property that forbids re-seal-and-compare). function makeCryptoStub() { let n = 0; return { encryptTotpSecret: (plain) => `sealed:${plain}:#${++n}`, decryptTotpSecret: (stored) => { if (stored == null) return null; const m = /^sealed:(.*):#\d+$/.exec(String(stored)); return m ? m[1] : String(stored); // legacy plaintext rows pass through }, }; } // Builds a vm context carrying the REAL route statement and a REAL rebinder // instance; returns the handler plus every spy log. function makeHarness({ user, db, recoveryVerified = null, twoFactorEnabled = false, claimRecoveryOk = true, verifyDelta = { delta: 0 }, totpStep = () => 12345, hash = async () => "hashed-new-password" } = {}) { const calls = []; const rebinderDeps = { withTimeout: (p) => p, destroyBrowserSessionsForUser: async (u) => { calls.push(["destroy", u && u.email, u && u.id]); return { destroyed: 2, rememberLoginsRevoked: 1, errors: [] }; }, writeRevokedSidTombstone: async (sid) => { calls.push(["tombstone", sid]); return true; }, getSessionDisplayId: (sid) => `display(${sid})`, // The audit rebuild (the login binder's step, mirrored) fails construction // closed without these two — every fake-deps construction site carries them. ensureRememberLoginSessionId: (req) => { calls.push(["ensureRememberId"]); if (!req.session.rememberLoginId) req.session.rememberLoginId = "ensured-1"; return req.session.rememberLoginId; }, buildBrowserSessionAuditFromRequest: (req, email, rememberLoginId) => { calls.push(["audit", email, rememberLoginId]); return { email, rememberLoginId, userAgent: req.headers["user-agent"] }; }, setRememberLoginCookie: (req, res, u, options) => { calls.push(["mint", u && u.email, u && u.password, u && u.secret, options]); req.session.rememberLoginId = "minted-1"; return 4102444800000; }, markRememberLoginSessionFresh: (req, exp) => calls.push(["fresh", exp]), upsertActiveBrowserSessionCacheEntry: (sid) => calls.push(["upsert", sid]), clearRememberLoginCookie: () => calls.push(["clearCookie"]), revokeRememberLoginRegistryEntry: async (id) => { calls.push(["revoke", id]); return true; }, logger: { warn: () => {} }, }; let sealCounter = 0; const sandbox = { app: { post: (...args) => calls.push(["route", ...args]) }, accountCredentialRateLimiter: {}, accountTotpRateLimiter: {}, recoveryRateLimiter: {}, isAuthenticated: async () => true, findUserByEmail: async () => user, getValidRecoveryVerification: () => recoveryVerified, getProvisionedPasswordError: () => null, bcrypt: { compare: async () => true, hash, hashSync: () => "hashed-code" }, BCRYPT_ROUNDS: 4, withTimeout: (p) => Promise.resolve(p), hasTwoFactorEnabled: () => twoFactorEnabled, verifyTotpForUser: async () => ({ ok: true, skipped: false }), verifyPasswordForUser: async () => true, claimRecoveryCode: async () => { calls.push(["claimRecoveryCode"]); return claimRecoveryOk ? { ok: true, remaining: 5 } : { ok: false }; }, db, credentialCommitService: createCredentialCommitService({ db }), stripLogControlChars: (s) => String(s == null ? "" : s), getRequestIp: () => "127.0.0.1", disconnectSocketsForUser: (email, reason, options) => { calls.push(["disconnect", email, reason, options]); return 1; }, renderSessionInvalidationWarnings, credentialSessionRebinder: (() => { // The REAL rebinder, wrapped so each call's payload is captured BEFORE // the real sequence runs: the routes must thread the NEW epoch into the // rebind payload (the rebinder binds req.session.accountEpoch from // user.session_epoch), not the pre-write snapshot's. const real = createCredentialSessionRebinder(rebinderDeps); return { rebindOwnerSession: async (req, res, payload) => { calls.push(["rebindPayload", payload && payload.user && payload.user.session_epoch, payload && payload.destroyAs && payload.destroyAs.session_epoch]); return real.rebindOwnerSession(req, res, payload); }, }; })(), newSessionEpoch, newSessionEpochDifferentFrom, console: { log: () => {}, error: () => {}, warn: () => {} }, speakeasy: { totp: { verifyDelta: ({ counter }) => { calls.push(["verifyDelta", counter]); return verifyDelta; } }, generateSecret: ({ length }) => ({ base32: `GEN${length}SECRETBASE32X`, otpauth_url: "otpauth://totp/stub" }), otpauthURL: ({ label }) => `otpauth://totp/stub?label=${encodeURIComponent(label)}`, }, qrcodeStub: { toDataURL: async () => "data:image/png;base64,stub" }, require: (name) => { if (name === "qrcode") return sandbox.qrcodeStub; throw new Error(`unexpected require in test: ${name}`); }, process: { env: {} }, totpSecretCrypto: makeCryptoStub(), markTotpCodeUsed: (key, code) => calls.push(["markTotpCodeUsed", key, code]), totpAccountKey: (u) => `id:${u && u.id}`, currentTotpStep: totpStep, crypto, JSON, Promise, Date, Symbol, Object, String, Number, Math, RegExp, Error, }; return { calls, load(statementKey) { const captured = []; const ctx = vm.createContext({ ...sandbox, app: { post: (...args) => captured.push(args) } }); vm.runInContext(statements[statementKey], ctx, { filename: `index.js[${statementKey}]` }); assert.equal(captured.length, 1, "exactly one route registration per statement"); const handler = captured[0][2]; assert.equal(typeof handler, "function"); return handler; }, }; } function makeReq({ body, session } = {}) { return { body, headers: { "user-agent": "test-agent" }, get: (k) => (k.toLowerCase() === "user-agent" ? "test-agent" : undefined), sessionID: "old-sid", session: session || makeSession(), }; } const BASE_USER = { id: 42, email: "user@example.test", password: "$2a$12$oldhash", secret: null, session_epoch: 3, admin: 0, suspended: 0 }; test("password change cannot commit after another request enables MFA", async () => { const calls = []; const db = { async query(sql, params) { calls.push({ sql, params }); assert.match(sql, /^UPDATE users SET password/); return { affectedRows: sql.includes("AND session_epoch = ?") && params.at(-1) !== 17 ? 0 : 1 }; }, }; const harness = makeHarness({ user: BASE_USER, db }); const handler = harness.load("password"); const res = makeRes(); await handler(makeReq({ body: { currentPassword: "pw", newPassword: "Newpassword1!" } }), res); assert.equal(res.statusCode, 409, "the unchanged password must not override the newer MFA generation"); assert.equal(res.body.ok, undefined); assert.equal(harness.calls.some((call) => call[0] === "rebindPayload"), false); assert.equal(calls.length, 1); }); test("pending MFA confirmation cannot regain a session after a password reset", async () => { const db = { async query(sql, params) { if (sql === "SELECT id, secret FROM users WHERE id = ? LIMIT 1") { return [{ id: BASE_USER.id, secret: SEALED_OLD }]; } assert.match(sql, /^UPDATE users SET secret/); return { affectedRows: sql.includes("AND session_epoch = ?") && params.at(-1) !== 17 ? 0 : 1 }; }, }; const harness = makeHarness({ user: { ...BASE_USER, secret: OLD_SECRET_PLAIN }, db }); const handler = harness.load("confirm"); const res = makeRes(); await handler(makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "standard", pending2faPriorSecret: SEALED_OLD, pending2faAccountEpoch: BASE_USER.session_epoch, }), }), res); assert.equal(res.statusCode, 403, "the pending proof must not adopt the password reset's generation"); assert.equal(res.body.recoveryCodes, undefined); assert.equal(harness.calls.some((call) => call[0] === "rebindPayload"), false); }); test("MFA confirmation without its generate-time account epoch fails closed", async () => { const db = makeConfirmDb({ initialSecret: SEALED_OLD }); const harness = confirmHarness(db); const req = makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "standard", pending2faPriorSecret: SEALED_OLD, }), }); delete req.session.pending2faAccountEpoch; const res = makeRes(); await harness.load("confirm")(req, res); assert.equal(res.statusCode, 403); assert.equal(res.body.recoveryCodes, undefined); assert.equal(db.state.secretUpdates, 0); assert.equal(harness.calls.some((call) => call[0] === "rebindPayload"), false); }); test("shared credential commits reject missing, malformed and stale proof generations without SQL", async () => { const queries = []; const service = createCredentialCommitService({ db: { query: async (...args) => { queries.push(args); return { affectedRows: 1 }; } } }); for (const epoch of [undefined, null, NaN, Infinity, "3", -1, 1.5]) { const user = { ...BASE_USER, session_epoch: epoch }; assert.equal((await service.commitPassword(user, "replacement", 9)).affectedRows, 0); assert.equal((await service.commitEmail(user, "new@example.test", user.email, 9)).affectedRows, 0); assert.equal((await service.commitTwoFactor(user, "sealed", "[]", SEALED_OLD, 9, epoch, 12345)).affectedRows, 0); } assert.equal((await service.commitTwoFactor({ ...BASE_USER, session_epoch: 17 }, "sealed", "[]", SEALED_OLD, 19, 3, 12345)).affectedRows, 0); for (const step of [undefined, null, NaN, Infinity, -1, 1.5, "12345"]) { assert.equal((await service.commitTwoFactor(BASE_USER, "sealed", "[]", SEALED_OLD, 9, 3, step)).affectedRows, 0); } assert.equal((await service.commitPassword(BASE_USER, "replacement", BASE_USER.session_epoch)).affectedRows, 0); assert.equal(queries.length, 0); assert.equal((await service.commitPassword({ ...BASE_USER, session_epoch: 0 }, "replacement", 9)).affectedRows, 1, "a migrated row's genuine epoch zero remains comparable"); assert.equal(queries[0][1].at(-1), 0); }); test("shared credential commits require one confirmed changed row", async () => { for (const result of [undefined, null, {}, { affectedRows: 0 }, { affectedRows: 2 }, { affectedRows: "1" }]) { const service = createCredentialCommitService({ db: { query: async () => result } }); assert.equal((await service.commitPassword(BASE_USER, "replacement", 9)).affectedRows, 0); assert.equal((await service.commitEmail(BASE_USER, "new@example.test", BASE_USER.email, 9)).affectedRows, 0); assert.equal((await service.commitTwoFactor(BASE_USER, "sealed", "[]", SEALED_OLD, 9, 3, 12345)).affectedRows, 0); } const failure = new Error("database unavailable"); const service = createCredentialCommitService({ db: { query: async () => { throw failure; } } }); await assert.rejects(service.commitPassword(BASE_USER, "replacement", 9), (err) => err === failure); }); test("email and settings-password commits cannot override a newer MFA generation", async () => { for (const route of ["email", "settings"]) { const db = { query: async (sql, params) => { assert.equal(sql, route === "email" ? CREDENTIAL_COMMIT_SQL.email : CREDENTIAL_COMMIT_SQL.password); assert.equal(params.at(-1), BASE_USER.session_epoch); return { affectedRows: 0 }; }, }; const harness = makeHarness({ user: BASE_USER, db }); const res = makeRes(); const body = route === "email" ? { currentPassword: "pw", newEmail: "new@example.test" } : { current: "pw", newPassword: "Newpassword1!", confirm: "Newpassword1!" }; await harness.load(route)(makeReq({ body }), res); assert.equal(res.statusCode, 409); assert.equal(res.body.ok, undefined); assert.equal(harness.calls.some((call) => call[0] === "rebindPayload"), false); } }); // --------------------------------------------------------------------------- // Behavior — the CAS loser stops everything; the winner path is unchanged // --------------------------------------------------------------------------- test("password change: CAS loser (affectedRows 0) answers 409 with no eviction, no socket kill, no remember re-issue, no success fields", async () => { const db = makeSimpleDb({ passwordAffectedRows: 0 }); const h = makeHarness({ user: BASE_USER, db }).load("password"); const res = makeRes(); await h(makeReq({ body: { currentPassword: "pw", newPassword: "Newpassword1!", twoFactorCode: "" } }), res); assert.equal(res.statusCode, 409); assert.equal(res.body.error, STALE_409_MESSAGE); assert.equal(res.body.ok, undefined, "no success fields on the loser"); assert.deepEqual(db.queries.map((q) => q.sql), [CREDENTIAL_COMMIT_SQL.password], "the CAS write is the only query that runs"); }); test("password change: CAS winner path is unchanged (eviction + rebind + response fields), keyed by id + the verified snapshot", async () => { const db = makeSimpleDb({ passwordAffectedRows: 1 }); const { calls, load } = makeHarness({ user: BASE_USER, db }); const h = load("password"); const req = makeReq({ body: { currentPassword: "pw", newPassword: "Newpassword1!", twoFactorCode: "" } }); const res = makeRes(); await h(req, res); assert.equal(res.statusCode, 0, "200 via res.json"); assert.equal(res.body.ok, true); assert.equal(db.queries[0].sql, CREDENTIAL_COMMIT_SQL.password); assert.equal(db.queries[0].params[4], BASE_USER.session_epoch, "the SQL pins the proven generation"); assert.deepEqual( [db.queries[0].params[0], db.queries[0].params[2], db.queries[0].params[3]], ["hashed-new-password", 42, "$2a$12$oldhash"], "the CAS pins id + the pre-flight hash" ); assert.ok(credentialGenerationMismatch(BASE_USER.session_epoch, db.queries[0].params[1]), "the CAS commits a NEW generation, different from the row's current one"); const passwordDisconnect = calls.find((call) => call[0] === "disconnect" && call[1] === "user@example.test" && call[2] === "password-changed"); assert.equal(passwordDisconnect?.[3]?.accountId, BASE_USER.id, "only the verified account's sockets are targeted"); assert.equal(passwordDisconnect[3].excludeSessionId, undefined, "sockets are disconnected WITHOUT a session exclusion"); assert.equal(passwordDisconnect[3].onlySessionId, undefined, "all sockets for the account are targeted"); assert.ok(calls.some((c) => c[0] === "destroy" && c[1] === "user@example.test"), "the rebinder destroys the user's sessions WITHOUT an exclusion"); assert.ok(calls.some((c) => c[0] === "mint" && c[1] === "user@example.test" && c[2] === "hashed-new-password" && c[4] && c[4].forceFreshId === true), "the remember re-issue carries the new password under forceFreshId"); assert.equal(res.body.sessionsDestroyed, 2); assert.equal(res.body.socketsDisconnected, 1); assert.equal(res.body.rememberLoginsRevoked, 1); assert.deepEqual(res.body.sessionInvalidationWarnings, []); }); test("settings change-password: CAS loser answers 409 and stops; winner keeps its message + response contract", async () => { const loserDb = makeSimpleDb({ passwordAffectedRows: 0 }); const loserHarness = makeHarness({ user: { ...BASE_USER, admin: 1 }, db: loserDb }); const loserH = loserHarness.load("settings"); const loserRes = makeRes(); await loserH(makeReq({ body: { current: "pw", newPassword: "Newpassword1!", confirm: "Newpassword1!" } }), loserRes); assert.equal(loserRes.statusCode, 409); assert.equal(loserRes.body.error, STALE_409_MESSAGE); assert.equal(loserRes.body.ok, undefined); const winnerDb = makeSimpleDb({ passwordAffectedRows: 1 }); const { calls, load } = makeHarness({ user: { ...BASE_USER, admin: 1 }, db: winnerDb }); const winnerH = load("settings"); const winnerRes = makeRes(); await winnerH(makeReq({ body: { current: "pw", newPassword: "Newpassword1!", confirm: "Newpassword1!" } }), winnerRes); assert.equal(winnerRes.body.ok, true); assert.equal(winnerRes.body.message, "password changed successfully"); assert.equal(winnerRes.body.sessionsDestroyed, 2); assert.ok(calls.some((c) => c[0] === "destroy" && c[1] === "user@example.test")); }); test("email change: CAS loser answers 409 and stops; winner destroys by the OLD email and rebinds to the NEW one", async () => { const loserDb = makeSimpleDb({ emailAffectedRows: 0 }); const loserH = makeHarness({ user: BASE_USER, db: loserDb }).load("email"); const loserRes = makeRes(); await loserH(makeReq({ body: { currentPassword: "pw", newEmail: "new@example.test" } }), loserRes); assert.equal(loserRes.statusCode, 409); assert.equal(loserRes.body.error, STALE_409_MESSAGE); assert.equal(loserRes.body.ok, undefined); assert.deepEqual(loserDb.queries.map((q) => q.sql), [CREDENTIAL_COMMIT_SQL.email]); const winnerDb = makeSimpleDb({ emailAffectedRows: 1 }); const { calls, load } = makeHarness({ user: BASE_USER, db: winnerDb }); const winnerH = load("email"); const winnerRes = makeRes(); await winnerH(makeReq({ body: { currentPassword: "pw", newEmail: "New@example.test" } }), winnerRes); assert.equal(winnerRes.body.ok, true); assert.equal(winnerDb.queries[0].sql, CREDENTIAL_COMMIT_SQL.email); assert.equal(winnerDb.queries[0].params[5], BASE_USER.session_epoch, "the SQL pins the proven generation"); assert.deepEqual( [winnerDb.queries[0].params[0], winnerDb.queries[0].params[2], winnerDb.queries[0].params[3], winnerDb.queries[0].params[4]], ["new@example.test", 42, "$2a$12$oldhash", "user@example.test"], "the CAS pins the row identity AND the old email the session carried" ); assert.ok(credentialGenerationMismatch(BASE_USER.session_epoch, winnerDb.queries[0].params[1]), "the CAS commits a NEW generation, different from the row's current one"); const emailDisconnect = calls.find((call) => call[0] === "disconnect" && call[1] === "user@example.test" && call[2] === "email-changed"); assert.equal(emailDisconnect?.[3]?.accountId, BASE_USER.id, "the old email cannot retarget a replacement account"); assert.equal(emailDisconnect[3].excludeSessionId, undefined, "old-email sockets are disconnected without exclusion"); assert.equal(emailDisconnect[3].onlySessionId, undefined, "all sockets for the account are targeted"); assert.ok(calls.some((c) => c[0] === "destroy" && c[1] === "user@example.test"), "the sweep matches the OLD email identity"); assert.ok(calls.some((c) => c[0] === "mint" && c[1] === "new@example.test" && c[4] && c[4].forceFreshId === true), "the remember re-issue binds the NEW email"); }); test("email change on the recovery path: the claim burns BEFORE the write and a CAS loser answers 409 honestly (no silent success)", async () => { const grant = { userId: 42, email: "user@example.test", verifiedAt: Date.now(), codeHash: "$2a$12$codehash" }; const db = makeSimpleDb({ emailAffectedRows: 0 }); const { calls, load } = makeHarness({ user: BASE_USER, db, recoveryVerified: grant }); const h = load("email"); const res = makeRes(); await h(makeReq({ body: { newEmail: "new@example.test" }, session: Object.assign(makeSession(), { recoveryVerified: grant }) }), res); assert.equal(res.statusCode, 409); assert.ok(calls.some((c) => c[0] === "claimRecoveryCode"), "the code claim ran (burn is atomic and single-use by its own CAS)"); assert.equal(calls.some((c) => c[0] === "destroy"), false, "no eviction after a burned-claim loss"); assert.equal(calls.some((c) => c[0] === "mint"), false, "no remember re-issue after a burned-claim loss"); }); // --------------------------------------------------------------------------- // Behavior — credential-generation bumps (adpanel:credential-generation): // each interactive writer commits the NEW epoch in the SAME statement as the // credential and threads it into the rebind payload, so the owner's // regenerated session binds the generation the CAS just committed instead of // the stale pre-write snapshot's (which would make the binding middleware // tear the owner down as stale on the next request). // --------------------------------------------------------------------------- function assertFreshEpochParam(epochParam, label) { assert.ok(Number.isFinite(epochParam) && Number.isInteger(epochParam), `${label}: the epoch param is a finite integer`); assert.ok(epochParam >= 1 && epochParam <= 2147483647, `${label}: the epoch param is in the established [1, 2147483647] range`); assert.notEqual(epochParam, 0, `${label}: never the 0 column default`); assert.equal(credentialGenerationMismatch(BASE_USER.session_epoch, epochParam), true, `${label}: strictly different from the row's current generation (3)`); } test("epoch bump, account password change: the CAS commits the NEW epoch in-statement and the owner's session re-binds onto it", async () => { const db = makeSimpleDb({ passwordAffectedRows: 1 }); const { calls, load } = makeHarness({ user: BASE_USER, db }); const h = load("password"); const req = makeReq({ body: { currentPassword: "pw", newPassword: "Newpassword1!", twoFactorCode: "" } }); const res = makeRes(); await h(req, res); assert.equal(res.body.ok, true); const casEpoch = db.queries[0].params[1]; assertFreshEpochParam(casEpoch, "password CAS"); const payloadCall = calls.find((c) => c[0] === "rebindPayload"); assert.ok(payloadCall, "the route rebinds through the shared rebinder"); assert.equal(payloadCall[1], casEpoch, "the rebind payload carries exactly the epoch the CAS committed (not the stale snapshot's)"); assert.equal(payloadCall[2], undefined, "no destroyAs on the password route"); assert.equal(req.session.accountEpoch, casEpoch, "the owner's regenerated session binds the NEW generation"); }); test("epoch bump, settings change-password: same in-statement commit + rebind threading", async () => { const db = makeSimpleDb({ passwordAffectedRows: 1 }); const { calls, load } = makeHarness({ user: { ...BASE_USER, admin: 1 }, db }); const h = load("settings"); const req = makeReq({ body: { current: "pw", newPassword: "Newpassword1!", confirm: "Newpassword1!" } }); const res = makeRes(); await h(req, res); assert.equal(res.body.ok, true); const casEpoch = db.queries[0].params[1]; assertFreshEpochParam(casEpoch, "settings CAS"); const payloadCall = calls.find((c) => c[0] === "rebindPayload"); assert.ok(payloadCall, "the route rebinds through the shared rebinder"); assert.equal(payloadCall[1], casEpoch, "the rebind payload carries exactly the epoch the CAS committed"); assert.equal(req.session.accountEpoch, casEpoch, "the owner's regenerated session binds the NEW generation"); }); test("epoch bump, email change: the CAS commits the NEW epoch in-statement; the rebind binds it while destroyAs stays the email-only sweep", async () => { const db = makeSimpleDb({ emailAffectedRows: 1 }); const { calls, load } = makeHarness({ user: BASE_USER, db }); const h = load("email"); const req = makeReq({ body: { currentPassword: "pw", newEmail: "new@example.test" } }); const res = makeRes(); await h(req, res); assert.equal(res.body.ok, true); const casEpoch = db.queries[0].params[1]; assertFreshEpochParam(casEpoch, "email CAS"); const payloadCall = calls.find((c) => c[0] === "rebindPayload"); assert.ok(payloadCall, "the route rebinds through the shared rebinder"); assert.equal(payloadCall[1], casEpoch, "the rebind payload carries exactly the epoch the CAS committed"); // destroyAs is deliberately the pre-write snapshot (epoch included): the // user-wide destroy and remember revoke match by EMAIL only — the epoch is // not part of their match material. assert.equal(payloadCall[2], BASE_USER.session_epoch, "destroyAs keeps the snapshot (destroy matches by email and ignores the epoch)"); assert.equal(req.session.accountEpoch, casEpoch, "the owner's regenerated session binds the NEW generation"); }); test("epoch bump, 2FA confirm: the CAS commits the NEW epoch in-statement and the owner's session re-binds onto it", async () => { const db = makeConfirmDb({ initialSecret: SEALED_OLD }); const { calls, load } = confirmHarness(db); const h = load("confirm"); const req = makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "standard" }), }); const res = makeRes(); await h(req, res); assert.equal(res.body && res.body.ok, true); const casQuery = db.queries.find((q) => q.sql.startsWith("UPDATE users SET secret")); const casEpoch = casQuery.params[2]; assertFreshEpochParam(casEpoch, "2FA confirm CAS"); assert.equal(db.state.epoch, casEpoch, "the winning CAS persisted the new generation"); const payloadCall = calls.find((c) => c[0] === "rebindPayload"); assert.ok(payloadCall, "the route rebinds through the shared rebinder"); assert.equal(payloadCall[1], casEpoch, "the rebind payload carries exactly the epoch the CAS committed"); assert.equal(req.session.accountEpoch, casEpoch, "the owner's regenerated session binds the NEW generation"); }); test("epoch bump, CAS loser: the 409 stops everything and NO generation is persisted", async () => { // Password route loser: the CAS (affectedRows 0) is the only query that // runs — the generated epoch is discarded with the lost statement. const loserDb = makeSimpleDb({ passwordAffectedRows: 0 }); const loserHarness = makeHarness({ user: BASE_USER, db: loserDb }); const loserH = loserHarness.load("password"); const loserRes = makeRes(); await loserH(makeReq({ body: { currentPassword: "pw", newPassword: "Newpassword1!", twoFactorCode: "" } }), loserRes); assert.equal(loserRes.statusCode, 409); assert.deepEqual(loserDb.queries.map((q) => q.sql), [CREDENTIAL_COMMIT_SQL.password], "the lost CAS is the only statement (no epoch follow-up write)"); assert.equal(loserHarness.calls.some((c) => c[0] === "rebindPayload"), false, "no rebind (and no epoch re-bind) after a lost CAS"); // 2FA confirm loser (concurrent admin reset): the row's generation stays // exactly as the reset left it. const confirmDb = makeConfirmDb({ initialSecret: SEALED_OLD, onBeforeUpdate: (state) => { state.secret = null; }, }); const { load } = confirmHarness(confirmDb); const h = load("confirm"); const confirmRes = makeRes(); await h(makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "standard" }), }), confirmRes); assert.equal(confirmRes.statusCode, 403); assert.equal(confirmDb.state.epoch, 3, "a lost CAS never persists an epoch — the concurrent reset's state stands"); }); // --------------------------------------------------------------------------- // Behavior — the 2FA confirm redesign (Finding 3) // --------------------------------------------------------------------------- const OLD_SECRET_PLAIN = "OLDS3CRETBASE32XQ"; const NEW_SECRET_PLAIN = "NEWS3CRETBASE32XQ"; const SEALED_OLD = `sealed:${OLD_SECRET_PLAIN}:#7`; // A DIFFERENT generation the row moved to after the stamped generate — its // plaintext differs from the confirm's pending secret so the stored-secret // replay pre-check passes and the CAS (not the pre-check) arbitrates — used // to prove the recovery confirm pins its own stamp instead of fresh-reading // a moved row. const MOVED_SECRET_PLAIN = "MOVEDS3CRETBASE32"; const SEALED_MOVED = `sealed:${MOVED_SECRET_PLAIN}:#8`; function confirmHarness(db, overrides = {}) { return makeHarness({ user: { ...BASE_USER, secret: OLD_SECRET_PLAIN }, db, twoFactorEnabled: true, ...overrides, }); } test("2FA confirm, same-step rotation: the new secret commits even when the old code already claimed that step", async () => { const db = makeConfirmDb({ initialSecret: SEALED_OLD, initialCounter: 12345 }); const { calls, load } = confirmHarness(db); const h = load("confirm"); const res = makeRes(); await h(makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "standard" }), }), res); assert.equal(res.body && res.body.ok, true, "a valid code in the same 30s window must confirm successfully"); assert.equal(res.statusCode, 0, "no error status"); assert.equal(res.body.recoveryCodes.length, 7, "the winner issues a fresh recovery set"); assert.equal(db.state.secretUpdates, 1, "the CAS committed the new generation"); assert.notEqual(db.state.secret, SEALED_OLD); assert.equal(db.state.counter, 12345, "the winner publishes the new secret with the consumed step"); assert.ok(calls.some((c) => c[0] === "markTotpCodeUsed"), "the in-process burn contract is kept"); assert.ok(calls.some((c) => c[0] === "destroy" && c[1] === "user@example.test"), "the rotation still rebinds sessions"); }); test("2FA confirm, first enrollment: the NULL-safe CAS publishes the seed with the step verified before hashing", async () => { const db = makeConfirmDb({ initialSecret: null }); let clockStep = 12345; const { calls, load } = confirmHarness(db, { user: BASE_USER, verifyDelta: { delta: -1 }, totpStep: () => clockStep, hash: async () => { clockStep = 12346; return "hashed-code"; }, }); const h = load("confirm"); const res = makeRes(); await h(makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "enable" }), }), res); assert.equal(res.body && res.body.ok, true); assert.equal(db.state.secretUpdates, 1); const casQuery = db.queries.find((q) => q.sql.startsWith("UPDATE users SET secret")); assert.match(casQuery.sql, /SET .*totp_last_counter\s*=/, "the new authenticator and its consumed step must become visible together"); const casParams = casQuery.params; assert.equal(casParams.at(-2), null, "the pin is SQL NULL for a first-enrollment row (NULL-safe <=>)"); assert.ok(credentialGenerationMismatch(BASE_USER.session_epoch, casParams[2]), "first enrollment also commits a fresh generation in-statement"); assert.deepEqual(calls.find((call) => call[0] === "verifyDelta"), ["verifyDelta", 12345]); assert.equal(db.state.counter, 12344, "the counter must reflect the library's verification time, not the time after hashing"); }); test("2FA confirm, concurrent confirms on a shared db: exactly one issues recovery codes; the loser 403s with no codes", async () => { const db = makeConfirmDb({ initialSecret: SEALED_OLD, latchUntil: 2 }); const { load } = confirmHarness(db); const h1 = load("confirm"); const h2 = load("confirm"); const mk = () => makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "standard" }), }); const res1 = makeRes(); const res2 = makeRes(); await Promise.all([h1(mk(), res1), h2(mk(), res2)]); const winners = [res1, res2].filter((r) => r.body && r.body.ok === true); const losers = [res1, res2].filter((r) => r.statusCode === 403); assert.equal(winners.length, 1, "exactly one confirm wins"); assert.equal(losers.length, 1, "exactly one confirm loses"); assert.equal(winners[0].body.recoveryCodes.length, 7, "only the winner issues recovery codes"); assert.equal(losers[0].body.recoveryCodes, undefined, "the loser never issues codes"); assert.equal(losers[0].body.error, "Incorrect code from new authenticator", "the loser keeps the uniform wrong-code contract"); assert.equal(db.state.secretUpdates, 1, "the CAS let exactly one write through"); }); test("2FA confirm, admin reset race: a secret cleared after the pre-flight read loses the CAS and answers the uniform 403", async () => { const db = makeConfirmDb({ initialSecret: SEALED_OLD, onBeforeUpdate: (state) => { state.secret = null; }, // concurrent admin 2FA reset commits between read and write }); const { load } = confirmHarness(db); const h = load("confirm"); const res = makeRes(); await h(makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "standard" }), }), res); assert.equal(res.statusCode, 403); assert.equal(res.body.error, "Incorrect code from new authenticator"); assert.equal(res.body.ok, undefined); assert.equal(res.body.recoveryCodes, undefined); assert.equal(db.state.secret, null, "the admin reset's NULL must survive (never overwritten by the stale request)"); }); test("2FA confirm, late replay: a row already carrying the pending secret is a replayed confirmation and 403s before any write", async () => { const db = makeConfirmDb({ initialSecret: `sealed:${NEW_SECRET_PLAIN}:#9` }); // the rotation already committed const { calls, load } = confirmHarness(db); const h = load("confirm"); const res = makeRes(); await h(makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "standard" }), }), res); assert.equal(res.statusCode, 403); assert.equal(res.body.error, "Incorrect code from new authenticator"); assert.equal(db.state.secretUpdates, 0, "no second rotation/recovery set from a replayed confirm"); assert.equal(calls.some((c) => c[0] === "markTotpCodeUsed"), false, "the replay is rejected before the burn"); assert.equal(db.state.counter, null, "a replayed confirmation leaves the durable counter unchanged"); }); // --------------------------------------------------------------------------- // Behavior — one commit per generate (adpanel:totp-confirm-cas): the generate // stamps the origin generation on the session and the confirm's CAS pins the // STAMP (the bytes AS OF GENERATE), falling back to the fresh pre-flight read // only for sessions with NO stamp key (undefined); NULL is a legitimate stamp. // --------------------------------------------------------------------------- const SECRET_A = "ASECRETBASE32XQA2"; const SECRET_B = "BSECRETBASE32XQB3"; test("2FA generate stamps the raw pre-flight secret: sealed bytes for a rotation, NULL for first enrollment", async () => { const db = makeConfirmDb({ initialSecret: SEALED_OLD }); const { load } = confirmHarness(db); const h = load("generate"); const res = makeRes(); const req = makeReq({ body: { currentCode: "123456" } }); await h(req, res); assert.equal(res.body && res.body.ok, true, "the rotation generate completes"); assert.equal(req.session.pending2faFrom, "standard"); assert.equal(req.session.pending2faPriorSecret, SEALED_OLD, "the stamp is the RAW stored bytes as of generate (never a decrypt/re-seal)"); assert.equal(req.session.pending2faAccountEpoch, BASE_USER.session_epoch, "setup retains the generation actually proven"); assert.ok(typeof req.session.pending2faSecret === "string" && req.session.pending2faSecret.startsWith("GEN"), "a fresh pending secret was minted"); // First enrollment: a NULL row stamps NULL — the stamp key EXISTS with a // null value, which is exactly the undefined/null distinction the confirm's // fallback logic is load-bearing for. const enableDb = makeConfirmDb({ initialSecret: null }); const enableH = makeHarness({ user: { ...BASE_USER, secret: null }, db: enableDb, twoFactorEnabled: false }).load("generate"); const enableRes = makeRes(); const enableReq = makeReq({ body: { currentPassword: "pw" } }); await enableH(enableReq, enableRes); assert.equal(enableRes.body && enableRes.body.ok, true, "the first-enrollment generate completes"); assert.equal(enableReq.session.pending2faFrom, "enable"); assert.equal(enableReq.session.pending2faPriorSecret, null, "first enrollment stamps NULL"); assert.ok("pending2faPriorSecret" in enableReq.session, "the stamp key exists with a null value (not an absent key)"); }); test("2FA confirm, two DIFFERENT generates with the same stamped origin: exactly one commit survives; the loser's stamp loses the CAS even though its fresh read pins the winner's just-committed bytes", async () => { const db = makeConfirmDb({ initialSecret: SEALED_OLD }); const { load } = confirmHarness(db); const hA = load("confirm"); const hB = load("confirm"); // Device A confirms its generate (stamped origin: the row was SEALED_OLD). const resA = makeRes(); await hA(makeReq({ body: { newCode: "123456", newSecret: SECRET_A }, session: Object.assign(makeSession(), { pending2faSecret: SECRET_A, pending2faFrom: "standard", pending2faPriorSecret: SEALED_OLD }), }), resA); // Device B confirmed a DIFFERENT generate that stamped the SAME origin; B's // fresh pre-flight SELECT lands AFTER A's commit — the pre-stamp fresh-read // pin would adopt A's just-committed bytes here and last-writer-win, // invalidating the recovery codes A's response already displayed. const resB = makeRes(); await hB(makeReq({ body: { newCode: "123456", newSecret: SECRET_B }, session: Object.assign(makeSession(), { pending2faSecret: SECRET_B, pending2faFrom: "standard", pending2faPriorSecret: SEALED_OLD }), }), resB); assert.equal(resA.body && resA.body.ok, true, "the first confirm wins and its response stands"); assert.equal(resA.body.recoveryCodes.length, 7, "the winner issues its recovery set"); assert.equal(resB.statusCode, 403, "the loser answers the uniform wrong-code 403"); assert.equal(resB.body.recoveryCodes, undefined, "the loser never issues codes"); assert.equal(db.state.secretUpdates, 1, "exactly one commit — A's recovery codes stay valid"); assert.ok(String(db.state.secret).includes(SECRET_A), "the surviving commit is A's generation"); const updates = db.queries.filter((q) => q.sql.startsWith("UPDATE users SET secret")); assert.equal(updates.length, 2); assert.equal(updates[1].params.at(-2), SEALED_OLD, "B's pin is its STAMP (as of generate), not its fresh read of A's just-committed bytes"); }); test("2FA confirm, admin reset lands between generate and confirm: the stamped pin loses the CAS and fails closed (no silent re-enroll over the reset)", async () => { // The generate stamped SEALED_OLD; an admin 2FA reset has since committed // secret = NULL. The fresh-read pin (NULL) would NULL-safe-match the reset // row and re-enroll over it; the stamp fails closed instead — the generate // authorized a rotation FROM a generation that no longer exists. const db = makeConfirmDb({ initialSecret: null }); const { load } = confirmHarness(db); const h = load("confirm"); const res = makeRes(); await h(makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "standard", pending2faPriorSecret: SEALED_OLD }), }), res); assert.equal(res.statusCode, 403); assert.equal(res.body.error, "Incorrect code from new authenticator"); assert.equal(res.body.ok, undefined); assert.equal(res.body.recoveryCodes, undefined); assert.equal(db.state.secretUpdates, 0, "the reset's NULL survives — the stale generate cannot commit"); assert.equal(db.state.secret, null); const casQuery = db.queries.find((q) => q.sql.startsWith("UPDATE users SET secret")); assert.equal(casQuery.params.at(-2), SEALED_OLD, "the pin is the stamp, not the fresh read of the reset row"); }); test("2FA confirm, two RECOVERY-flow confirms with the same stamped origin: exactly one commit survives (the recovery generate stamps, so its confirms inherit the one-commit-per-generate rule)", async () => { const db = makeConfirmDb({ initialSecret: SEALED_OLD }); const { load } = confirmHarness(db); const hA = load("confirm"); const hB = load("confirm"); // Both devices ran generate-recovery against the same unmoved row (each // burning its own recovery code), so both stamped SEALED_OLD as the origin. const resA = makeRes(); await hA(makeReq({ body: { newCode: "123456", newSecret: SECRET_A }, session: Object.assign(makeSession(), { pending2faSecret: SECRET_A, pending2faFrom: "recovery", pending2faPriorSecret: SEALED_OLD }), }), resA); const resB = makeRes(); await hB(makeReq({ body: { newCode: "123456", newSecret: SECRET_B }, session: Object.assign(makeSession(), { pending2faSecret: SECRET_B, pending2faFrom: "recovery", pending2faPriorSecret: SEALED_OLD }), }), resB); assert.equal(resA.body && resA.body.ok, true, "the first recovery confirm wins"); assert.equal(resA.body.recoveryCodes.length, 7, "the winner issues its recovery set"); assert.equal(resB.statusCode, 403, "the second recovery confirm loses the CAS on the shared origin stamp"); assert.equal(resB.body.recoveryCodes, undefined, "the loser never issues codes"); assert.equal(db.state.secretUpdates, 1, "exactly one commit — A's QR/recovery set stay valid"); assert.ok(String(db.state.secret).includes(SECRET_A), "the surviving commit is A's generation"); const updates = db.queries.filter((q) => q.sql.startsWith("UPDATE users SET secret")); assert.equal(updates.length, 2); assert.equal(updates[1].params.at(-2), SEALED_OLD, "B's pin is the shared origin stamp, not its fresh read of A's just-committed bytes"); }); test("2FA confirm, recovery flow pins ITS OWN stamp: a row that moved after the recovery generate fails closed instead of fresh-reading the new generation", async () => { // The recovery generate stamped SEALED_OLD; another rotation has since // committed a different secret. The pre-fix fresh-read pin would adopt the // new bytes and overwrite the rotation that moved the row; the recovery // stamp fails closed exactly like the standard flow's stamp. const db = makeConfirmDb({ initialSecret: SEALED_MOVED }); const { load } = confirmHarness(db); const h = load("confirm"); const res = makeRes(); await h(makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "recovery", pending2faPriorSecret: SEALED_OLD }), }), res); assert.equal(res.statusCode, 403); assert.equal(res.body.error, "Incorrect code from new authenticator"); assert.equal(res.body.ok, undefined); assert.equal(db.state.secretUpdates, 0, "the moved generation survives — the stale recovery generate cannot commit over it"); const casQuery = db.queries.find((q) => q.sql.startsWith("UPDATE users SET secret")); assert.equal(casQuery.params.at(-2), SEALED_OLD, "the pin is the recovery stamp, not the fresh read of the moved row"); }); test("recovery generate OVERWRITES a stale standard stamp with the row as of recovery-generate (behavioral)", async () => { // The crux of the stamp's OVERWRITE semantics, driven through the REAL // route: a session still carrying an abandoned standard-generate stamp // reaches generate-recovery. An only-if-absent stamp would keep the stale // pin and the confirm would then fail closed against the moved row, // wasting the just-burned recovery code; the overwrite re-anchors the pin // to the row bytes as of THIS generate (claimRecoveryCode never touches // users.secret, so the fresh read IS the origin generation). const db = makeConfirmDb({ initialSecret: SEALED_OLD }); const h = makeHarness({ user: { ...BASE_USER, secret: SEALED_OLD }, db }).load("recoveryGenerate"); const req = makeReq({ session: Object.assign(makeSession(), { recoveryVerified: { email: "user@example.test", codeHash: "hash-1", verifiedAt: Date.now() }, pending2faPriorSecret: "sealed:ABANDONEDSTANDARDGEN:#2", }), }); const res = makeRes(); await h(req, res); assert.equal(res.body && res.body.ok, true, "the recovery generate completes"); assert.equal(req.session.pending2faFrom, "recovery"); assert.equal(req.session.pending2faPriorSecret, SEALED_OLD, "the stale standard stamp was OVERWRITTEN with the row's raw bytes as of recovery-generate"); assert.equal(req.session.pending2faAccountEpoch, BASE_USER.session_epoch, "recovery setup replaces the proof-generation stamp too"); assert.ok("pending2faPriorSecret" in req.session, "the stamp key exists (not absent)"); assert.ok(typeof req.session.pending2faSecret === "string" && req.session.pending2faSecret.startsWith("GEN"), "a fresh pending secret was minted"); assert.equal(req.session.recoveryVerified, undefined, "the grant is spent by the generate"); assert.ok(db.queries.some((q) => q.sql === "SELECT id, secret FROM users WHERE id = ? LIMIT 1"), "the origin generation came from the raw row read"); assert.ok(req.session.pending2faPriorSecret !== "sealed:ABANDONEDSTANDARDGEN:#2", "the abandoned standard-generate generation did not survive"); }); test("2FA confirm, first enrollment with a NULL stamp: <=> NULL wins on the still-NULL row and issues codes", async () => { const db = makeConfirmDb({ initialSecret: null }); const { load } = confirmHarness(db, { user: { ...BASE_USER, secret: null } }); const h = load("confirm"); const res = makeRes(); await h(makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "enable", pending2faPriorSecret: null }), }), res); assert.equal(res.body && res.body.ok, true); assert.equal(db.state.secretUpdates, 1); const casParams = db.queries.find((q) => q.sql.startsWith("UPDATE users SET secret")).params; assert.equal(casParams.at(-2), null, "the pin is the NULL stamp (SQL NULL via the NULL-safe <=>)"); }); test("2FA confirm, NULL stamp but the row gained a secret meanwhile: the stamp loses the CAS (null is a real stamp, not a fallback trigger)", async () => { const ROW_GAINED = "sealed:SOMEONEELSESENROLLMENT:#11"; const db = makeConfirmDb({ initialSecret: ROW_GAINED }); const { load } = confirmHarness(db); const h = load("confirm"); const res = makeRes(); await h(makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "standard", pending2faPriorSecret: null }), }), res); assert.equal(res.statusCode, 403); assert.equal(res.body.recoveryCodes, undefined); assert.equal(db.state.secretUpdates, 0, "the other generation survives"); assert.equal(db.state.secret, ROW_GAINED); const casQuery = db.queries.find((q) => q.sql.startsWith("UPDATE users SET secret")); assert.equal(casQuery.params.at(-2), null, "the pin stays the NULL stamp — a null stamp must NOT fall back to the fresh read (which here would have won)"); }); test("2FA confirm, in-flight pre-stamp session (no stamp key): falls back to the fresh pre-flight read as the pin (today's semantics)", async () => { const db = makeConfirmDb({ initialSecret: SEALED_OLD }); const { load } = confirmHarness(db); const h = load("confirm"); const res = makeRes(); await h(makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, // No pending2faPriorSecret key at all: a session created before the stamp // existed (both generate paths stamp — the undefined-only fallback covers // only those pre-stamp sessions). session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "standard" }), }), res); assert.equal(res.body && res.body.ok, true); assert.equal(db.state.secretUpdates, 1); const casQuery = db.queries.find((q) => q.sql.startsWith("UPDATE users SET secret")); assert.equal(casQuery.params.at(-2), SEALED_OLD, "the fallback pin is the fresh pre-flight read"); }); test("2FA confirm, standard single-device rotation WITH the stamp: generate consumed old-secret step S, the stamped confirm at step S still succeeds", async () => { const db = makeConfirmDb({ initialSecret: SEALED_OLD, initialCounter: 12345 }); const { load } = confirmHarness(db); const h = load("confirm"); const res = makeRes(); await h(makeReq({ body: { newCode: "123456", newSecret: NEW_SECRET_PLAIN }, session: Object.assign(makeSession(), { pending2faSecret: NEW_SECRET_PLAIN, pending2faFrom: "standard", pending2faPriorSecret: SEALED_OLD }), }), res); assert.equal(res.body && res.body.ok, true, "the normal prompt flow is unchanged by the stamp"); assert.equal(res.body.recoveryCodes.length, 7); assert.equal(db.state.secretUpdates, 1); const casQuery = db.queries.find((q) => q.sql.startsWith("UPDATE users SET secret")); assert.equal(casQuery.params.at(-2), SEALED_OLD, "the stamp matches the row read during generation"); assert.equal(db.state.counter, 12345, "the same-step durable burn is part of the commit"); });