"use strict"; // adpanel:admin-2fa-reset-preflight — behavior pins for the admin 2FA reset // pre-flight guard. // // Finding: both admin MFA-reset route aliases (POST /api/admin/user/reset-2fa // canonical and POST /api/admin/user/confirm-2fa-reset alias) delegated to a // shared async handler whose authorization/lookup/step-up awaits ran OUTSIDE // its try/catch. Express 4.22.2 ignores rejected handler promises, so any DB // rejection in those awaits escaped as an unhandled rejection and the request // was never answered (the client hung; the terminal error middleware never // sees an ignored rejection). The fix moves the whole pipeline into // services/admin-2fa-reset.js with the ENTIRE awaited pipeline inside ONE // guard try whose catch answers the headersSent-guarded 500 — the exported // handler NEVER REJECTS, which is what makes the thin expression-bodied arrow // adapters in index.js safe under Express 4. // // Harness: the house vm-extraction technique (helpers are per-file by // convention — copied from tests/credential-change-atomic-guard.test.js, not // imported): the REAL route registration statements are extracted from // index.js verbatim and run against a capturing app, with the REAL service // handler built from the module under injected fake deps. Because the // captured handler IS the arrow adapter Express 4 would call, awaiting its // return value is exactly the surface Express 4 drops on the floor. 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 ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const MODULE_JS = path.join(ROOT, "services", "admin-2fa-reset.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const moduleSource = fs.readFileSync(MODULE_JS, "utf8"); const { createAdminTwoFactorResetService } = require(MODULE_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_RESET = 'app.post("/api/admin/user/reset-2fa", sessionRevoke2faRateLimiter'; const ROUTE_CONFIRM = 'app.post("/api/admin/user/confirm-2fa-reset", sessionRevoke2faRateLimiter'; const statements = { reset: extractRouteStatement(indexSource, ROUTE_RESET), confirm: extractRouteStatement(indexSource, ROUTE_CONFIRM), }; // --------------------------------------------------------------------------- // Source pins — one implementation, thin adapters, one-way require // --------------------------------------------------------------------------- test("source: both aliases delegate to the ONE service handler with their own action scope; the pipeline lives exactly once in the module", () => { for (const [key, route] of [["reset", "/api/admin/user/reset-2fa"], ["confirm", "/api/admin/user/confirm-2fa-reset"]]) { const stmt = statements[key]; assert.ok(stmt.includes("sessionRevoke2faRateLimiter"), `${route}: the shared limiter must stay`); assert.ok(stmt.includes("(req, res) => handleAdmin2faReset(req, res, {"), `${route}: must stay a THIN expression-bodied delegation (no inline pipeline Express 4 cannot guard)`); assert.ok(stmt.includes(`action: "POST ${route}"`), `${route}: must keep its own action-token scope string`); assert.ok(!stmt.includes("await"), `${route}: the adapter must not await (delegation only)`); } assert.ok(statements.reset.includes('proofLabel: "Admin 2FA reset"') && statements.reset.includes("logSuffix: \"\""), "canonical keeps its proofLabel/logSuffix"); assert.ok(statements.confirm.includes('proofLabel: "Admin 2FA reset (confirm)"') && statements.confirm.includes('logSuffix: " (confirm)"'), "alias keeps its proofLabel/logSuffix"); // Exactly one implementation and one destructive write — in the module, not // in index.js anymore. assert.equal(countOccurrences(moduleSource, "async function handleAdmin2faReset("), 1, "exactly one shared handler, in the service module"); assert.equal(countOccurrences(indexSource, "async function handleAdmin2faReset("), 0, "no inline copy may remain in index.js"); // adpanel:credential-generation — the destructive clear bumps the account's // session epoch IN THE SAME statement (a generation committed separately // from its credential leaves a window where the stale credential // authenticates against the new generation). // adpanel:admin-reset-target-pinning — the destructive clear pins the // LOADED row's immutable id (an email-keyed write could silently land on a // replacement row recreated with the same email between the lookup and the // write); the epoch bump stays IN THE SAME statement. const commitSource = fs.readFileSync(path.join(ROOT, "services", "account-credentials.js"), "utf8"); assert.equal(countOccurrences(commitSource, "UPDATE users SET secret = NULL, recovery_codes = NULL, session_epoch = ? WHERE id = ?"), 1, "the destructive clear revokes both MFA credentials exactly once in the actor-guarded service"); assert.ok(moduleSource.includes("resetAccountTwoFactor(db, targetUser, actingAdmin)"), "both aliases use the actor-guarded commit"); assert.equal(countOccurrences(moduleSource, "UPDATE users SET secret = NULL WHERE LOWER(email) = LOWER(?)"), 0, "the epoch-free shape must be gone from the service module (replaced, not duplicated)"); assert.equal(countOccurrences(indexSource, "UPDATE users SET secret = NULL WHERE LOWER(email) = LOWER(?)"), 0, "no copy of the destructive clear may remain in index.js"); assert.deepEqual(indexSource.match(/UPDATE users SET secret = NULL[^"\r\n]*/g) || [], ["UPDATE users SET secret = NULL WHERE secret = ''"], "only startup empty-secret normalization may remain in index.js, never an admin reset copy"); // One-way require + exactly one construction site with the injected deps. assert.equal(countOccurrences(indexSource, 'require("./services/admin-2fa-reset")'), 1, "index.js requires the module one-way, exactly once"); assert.equal(countOccurrences(indexSource, "createAdminTwoFactorResetService({"), 1, "exactly one service construction site"); assert.ok(!moduleSource.includes('require("./index")') && !moduleSource.includes('require("../index")'), "the module must never require index.js"); }); // --------------------------------------------------------------------------- // Behavior harness — the REAL arrow adapters from index.js over the REAL // service handler with injected fake deps // --------------------------------------------------------------------------- const TARGET = { id: 42, email: "target@example.test", admin: 0, secret: "sealed:TOTPSEED", session_epoch: 3 }; const ADMIN = { id: 7, email: "admin@example.test", admin: 1, suspended: 0, session_epoch: 9 }; function makeRes() { const res = { statusCode: 0, body: null, headersSent: false, cookies: [], endCalls: 0, jsonCalls: 0 }; res.status = (code) => { res.statusCode = code; res.headersSent = true; return res; }; res.json = (body) => { res.jsonCalls += 1; res.body = body; return res; }; res.end = () => { res.endCalls += 1; return res; }; res.cookie = (name, value, opts) => res.cookies.push({ name, value, opts }); return res; } function makeReq({ body } = {}) { return { body: { expectedTargetId: body?.email === ADMIN.email ? ADMIN.id : TARGET.id, ...body }, headers: { "user-agent": "test-agent" }, sessionID: "admin-sid", session: { user: ADMIN.email }, }; } function makeDeps(overrides = {}) { const calls = { queries: [], activity: [], evictions: [], tokenActions: [], stepUps: [], logs: [] }; const base = { isAdmin: async (req) => true, requireActionTokenOr403: async (req, res, action) => { calls.tokenActions.push(action); return true; }, findUserByEmail: async (email) => { if (email === ADMIN.email) return ADMIN; if (email === TARGET.email) return TARGET; return null; }, requireDestructiveActionStepUp: async (req, res, actingAdmin, subject, options) => { calls.stepUps.push({ actingAdmin, subject, options }); return { ok: true }; }, db: { async query(sql, params) { calls.queries.push({ sql, params }); return { affectedRows: 1 }; }, }, destroyBrowserSessionsForUser: async (u) => { calls.evictions.push(["destroy", u && u.email]); return { destroyed: 2, rememberLoginsRevoked: 1, errors: [] }; }, disconnectSocketsForUser: (email, reason) => { calls.evictions.push(["disconnect", email, reason]); return 3; }, recordActivity: (...args) => { calls.activity.push(args); }, getRequestIp: () => "127.0.0.1", normalizeAdminTargetEmail: (raw) => { if (typeof raw !== "string") return null; const email = raw.trim(); if (!email || !email.includes("@") || email.length > 255) return null; return email; }, stripLogControlChars: (s) => String(s == null ? "" : s), logger: { log: (...args) => calls.logs.push(["log", ...args]), error: (...args) => calls.logs.push(["error", ...args]), warn: (...args) => calls.logs.push(["warn", ...args]), }, }; const deps = Object.assign(base, overrides); deps.db = require("./helpers/account-transaction").attachAccountTransaction(deps.db, { actor: ADMIN, target: TARGET }); return { deps, calls }; } function makeHarness({ deps, statementKey }) { const service = createAdminTwoFactorResetService(deps); const captured = []; const ctx = vm.createContext({ app: { post: (...args) => captured.push(args) }, sessionRevoke2faRateLimiter: { limiter: "sessionRevoke2faRateLimiter" }, handleAdmin2faReset: service.handleAdmin2faReset, }); vm.runInContext(statements[statementKey], ctx, { filename: `index.js[${statementKey}]` }); assert.equal(captured.length, 1, "exactly one route registration per statement"); assert.equal(captured[0][1], ctx.sessionRevoke2faRateLimiter, "the shared limiter stays wired"); const handler = captured[0][2]; assert.equal(typeof handler, "function"); return handler; } // Runs the arrow adapter the way Express 4 does and reports what Express 4 // would see: a settled handler (correct) or a rejected promise (the bug — // an unanswered request plus an unhandled rejection). async function runAdapter(handler, req, res) { let rejection = null; try { await handler(req, res); } catch (err) { rejection = err; } return { rejection }; } // --------------------------------------------------------------------------- // Behavior — success path is byte-for-byte unchanged (both aliases) // --------------------------------------------------------------------------- test("success path, canonical alias: exact response body, single keyed write, evictions, audit — unchanged behavior", async () => { const { deps, calls } = makeDeps(); const handler = makeHarness({ deps, statementKey: "reset" }); const res = makeRes(); const { rejection } = await runAdapter(handler, makeReq({ body: { email: TARGET.email } }), res); assert.equal(rejection, null, "the exported handler must NEVER reject (Express 4 ignores handler rejections)"); assert.equal(res.statusCode, 0, "answered 200 via res.json"); assert.deepEqual(res.body, { ok: true, email: "target@example.test", cleared: true, sessionsDestroyed: 2, socketsDisconnected: 3, rememberLoginsRevoked: 1, sessionInvalidationWarnings: [], message: "2FA has been reset. The user must set up 2FA again from their account settings.", }); assert.deepEqual(calls.tokenActions, ["POST /api/admin/user/reset-2fa"], "the action-token scope string is unchanged"); assert.equal(calls.queries.length, 1, "exactly the one destructive write"); assert.equal(calls.queries[0].sql, "UPDATE users SET secret = NULL, recovery_codes = NULL, session_epoch = ? WHERE id = ?", "both MFA credentials and the epoch change in the single id-keyed write"); assert.equal(calls.queries[0].params[1], 42, "the write stays keyed by the loaded target's immutable id (adpanel:admin-reset-target-pinning)"); assert.ok(Number.isInteger(calls.queries[0].params[0]) && calls.queries[0].params[0] >= 1 && calls.queries[0].params[0] <= 2147483647, "the epoch param is a CSPRNG generation in the established range"); assert.deepEqual(calls.stepUps, [{ actingAdmin: ADMIN, subject: "Admin 2FA reset", options: { scopeKey: "user-id:42", credentialFlow: "password-then-totp" }, }], "the step-up subject, scope key and password-first flow are unchanged"); assert.deepEqual(calls.evictions, [["destroy", "target@example.test"], ["disconnect", "target@example.test", "2fa-reset-by-admin"]], "session + socket evictions are unchanged"); assert.deepEqual(calls.activity, [["_system", "admin_reset_2fa", "Reset (cleared) 2FA for target@example.test", "admin@example.test", "127.0.0.1"]], "the audit trail is unchanged"); }); test("success path, alias: identical action except its own action-token scope and log suffix", async () => { const { deps, calls } = makeDeps(); const handler = makeHarness({ deps, statementKey: "confirm" }); const res = makeRes(); const { rejection } = await runAdapter(handler, makeReq({ body: { email: ` ${TARGET.email} ` } }), res); assert.equal(rejection, null); assert.equal(res.body.ok, true); assert.equal(res.body.email, "target@example.test"); assert.deepEqual(calls.tokenActions, ["POST /api/admin/user/confirm-2fa-reset"], "a token minted for one route must not authorize the other"); assert.equal(calls.queries.length, 1); assert.equal(calls.queries[0].sql, "UPDATE users SET secret = NULL, recovery_codes = NULL, session_epoch = ? WHERE id = ?"); assert.equal(calls.queries[0].params[1], 42); assert.ok(Number.isInteger(calls.queries[0].params[0]) && calls.queries[0].params[0] >= 1 && calls.queries[0].params[0] <= 2147483647); assert.ok(calls.logs.some((l) => l[0] === "log" && String(l[1]).startsWith("[admin] 2FA cleared (confirm) for user target@example.test")), "the alias keeps its (confirm) log suffix"); assert.ok(calls.logs.some((l) => l[0] === "log" && String(l[1]).startsWith("[SECURITY] Admin 2FA reset evictions")), "the evictions security log is kept"); }); // --------------------------------------------------------------------------- // Behavior — the gate ladder keeps every wire string and its order // --------------------------------------------------------------------------- test("gate ladder unchanged: non-admin 403, token stop, invalid email 400, unknown user 404, self-reset 400, non-admin acting user 403", async () => { const cases = [ [{ isAdmin: async () => false, }, makeReq({ body: { email: TARGET.email } }), 403, { error: "Admin access required" }, []], [{ requireActionTokenOr403: async (req, res) => { res.status(403).json({ error: "action token required" }); return false; }, }, makeReq({ body: { email: TARGET.email } }), 403, { error: "action token required" }, []], [{ // token gate passes; the sync email 400 keeps its position AFTER the gates findUserByEmail: async () => { throw new Error("findUserByEmail must not run before the email 400"); }, }, makeReq({ body: { email: "not-an-email" } }), 400, { error: "invalid email" }, []], [{ findUserByEmail: async () => null, }, makeReq({ body: { email: "ghost@example.test" } }), 404, { error: "User not found" }, []], [{ // self-reset refusal fires before the acting-admin lookup and the write findUserByEmail: async () => ADMIN, }, makeReq({ body: { email: ADMIN.email } }), 400, { error: "Cannot reset your own 2FA through admin panel. Use account settings." }, []], [{ findUserByEmail: async (email) => (email === ADMIN.email ? { ...ADMIN, admin: 0 } : TARGET), }, makeReq({ body: { email: TARGET.email } }), 403, { error: "Admin access required" }, []], ]; for (const [overrides, req, expectedStatus, expectedBody, expectedQueries] of cases) { const { deps, calls } = makeDeps(overrides); const handler = makeHarness({ deps, statementKey: "reset" }); const res = makeRes(); const { rejection } = await runAdapter(handler, req, res); assert.equal(rejection, null, "no gate may reject through the adapter"); assert.equal(res.statusCode, expectedStatus, `status for ${expectedBody.error}`); assert.deepEqual(res.body, expectedBody); assert.deepEqual(calls.queries, expectedQueries, "no db write may run behind a refused gate"); assert.deepEqual(calls.evictions, [], "no eviction behind a refused gate"); assert.deepEqual(calls.activity, [], "no audit behind a refused gate"); assert.equal(res.endCalls, 0, "a refused gate does not end the response via the catch"); } }); // --------------------------------------------------------------------------- // Behavior — the pre-flight guard: every rejection answers, none escapes // --------------------------------------------------------------------------- const REJECTING_DEPS = [ ["isAdmin", () => Promise.reject(new Error("db down in isAdmin"))], ["requireActionTokenOr403", () => Promise.reject(new Error("db down in action-token gate"))], ["findUserByEmail", () => Promise.reject(new Error("db down in target lookup"))], ["requireDestructiveActionStepUp", () => Promise.reject(new Error("redis down in step-up"))], ]; for (const [depName, makeRejector] of REJECTING_DEPS) { test(`preflight guard: a rejected ${depName} answers 500 "internal error", never rejects, and never reaches the write`, async () => { const overrides = {}; overrides[depName] = makeRejector; const { deps, calls } = makeDeps(overrides); const handler = makeHarness({ deps, statementKey: "reset" }); const res = makeRes(); const { rejection } = await runAdapter(handler, makeReq({ body: { email: TARGET.email } }), res); assert.equal(rejection, null, `${depName}: the rejection must NOT escape the adapter (Express 4 would hang the request)`); assert.equal(res.statusCode, 500, `${depName}: the request must be answered`); assert.deepEqual(res.body, { error: "internal error" }); assert.deepEqual(calls.queries, [], `no db write may run when ${depName} fails (no unauthorized mutation)`); assert.deepEqual(calls.evictions, [], "no eviction on a failed pre-flight"); assert.deepEqual(calls.activity, [], "no audit on a failed pre-flight"); assert.equal(res.endCalls, 0, "the 500 path does not also end the response"); }); } test("write-path guard: a rejected UPDATE answers 500 internal error with no eviction, no audit, no partial success", async () => { const { deps, calls } = makeDeps({ db: { async query() { throw new Error("db down during the write"); } }, }); const handler = makeHarness({ deps, statementKey: "reset" }); const res = makeRes(); const { rejection } = await runAdapter(handler, makeReq({ body: { email: TARGET.email } }), res); assert.equal(rejection, null, "the write failure must not escape the adapter"); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "internal error" }); assert.deepEqual(calls.evictions, [], "no session/socket eviction after a failed write"); assert.deepEqual(calls.activity, [], "no audit entry for a reset that did not happen"); }); test("the catch ends an already-answered response exactly once without writing again", async () => { // A gate that writes its own 403 challenge and THEN throws (the historical // requireActionTokenOr403/step-up shape): the guard must not overwrite the // challenge with a 500 nor write a second body — it ends the response once. const { deps, calls } = makeDeps({ requireDestructiveActionStepUp: async (req, res) => { res.status(403).json({ error: "step-up challenge" }); throw new Error("store blew up after the challenge was written"); }, }); const handler = makeHarness({ deps, statementKey: "confirm" }); const res = makeRes(); const { rejection } = await runAdapter(handler, makeReq({ body: { email: TARGET.email } }), res); assert.equal(rejection, null); assert.equal(res.statusCode, 403, "the already-written challenge status stands"); assert.deepEqual(res.body, { error: "step-up challenge" }, "the challenge body must not be overwritten"); assert.equal(res.jsonCalls, 1, "exactly one body write"); assert.equal(res.endCalls, 1, "the response is ended exactly once"); assert.ok(calls.logs.some((l) => l[0] === "error" && String(l[1]).startsWith("[admin-2fa-reset] pre-flight failed:")), "the guard logs its own bracketed marker"); });