"use strict"; // adpanel:async-handler-containment — behavior pins for the settings GET belt // and the session-revoke pre-flight: every fallible await (admin gate, // acting-admin lookup, destructive-action security scan, inventory scan, // one-time token consumption) must sit inside a try-with-catch so a transient // rejection (DB hiccup, Redis timeout) answers a bounded 500 instead of // hanging the client — Express 4 does not catch rejected handler promises and // the process-level unhandledRejection handler only logs. // // Locked here: // - an injected rejection at every covered await of GET // /api/settings/security, /api/settings/maintenance, /api/settings/ // action-tokens, /api/settings/sessions, GET /api/maintenance/status and // the pre-try awaits of POST /api/settings/sessions/revoke produces a // settled handler (never a rejection), a 500 JSON with the route's // established safe wording, and no internals leaked in the body; // - Cache-Control: no-store is still set for GET responses that fail AFTER // the header position (and still absent for pre-gate failures, matching // today's 403 behavior); // - the exact early-return 403 shapes and their ORDER are preserved; // - the action-tokens mint pool keeps its documented shape (refreshable // tokens only — no per-account delete/suspension tokens); // - BOTH admin 2FA-reset thin adapters bound an injected db failure to the // guarded 500 (the service's never-rejects contract); // - the R7 sibling routes — POST /api/settings/captcha, POST and DELETE // /api/settings/maintenance — bound an injected rejection at each of // their pre-flight awaits (admin gate, action-token gate, acting-admin // lookup) to the guarded 500 carrying the route's own established // wording, while the never-reject step-up/grace helpers stay unwrapped; // - the two inner catches that lacked the headersSent discipline (GET // /api/settings/sessions' inventory catch and the admin recovery-reset // route's final catch) end an already-answered response exactly once // instead of attempting a second res.status. // // Harness: the house vm-extraction technique — the REAL route statements are // extracted from index.js verbatim and run against fake req/res + stub deps. 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 { createAdminTwoFactorResetService } = require(MODULE_JS); 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 statements = { securityGet: extractRouteStatement(indexSource, 'app.get("/api/settings/security"'), maintenanceGet: extractRouteStatement(indexSource, 'app.get("/api/settings/maintenance"'), actionTokens: extractRouteStatement(indexSource, 'app.get("/api/settings/action-tokens"'), sessionsGet: extractRouteStatement(indexSource, 'app.get("/api/settings/sessions"'), maintenanceStatus: extractRouteStatement(indexSource, 'app.get("/api/maintenance/status"'), sessionsRevoke: extractRouteStatement(indexSource, 'app.post("/api/settings/sessions/revoke", sessionRevoke2faRateLimiter'), reset2fa: extractRouteStatement(indexSource, 'app.post("/api/admin/user/reset-2fa", sessionRevoke2faRateLimiter'), confirm2faReset: extractRouteStatement(indexSource, 'app.post("/api/admin/user/confirm-2fa-reset", sessionRevoke2faRateLimiter'), captchaPost: extractRouteStatement(indexSource, 'app.post("/api/settings/captcha", sessionRevoke2faRateLimiter'), maintenancePost: extractRouteStatement(indexSource, 'app.post("/api/settings/maintenance", sessionRevoke2faRateLimiter'), maintenanceDelete: extractRouteStatement(indexSource, 'app.delete("/api/settings/maintenance"'), resetRecoveryCodes: extractRouteStatement(indexSource, 'app.post("/api/admin/user/reset-recovery-codes", sessionRevoke2faRateLimiter'), }; function makeRes() { const res = { statusCode: 0, body: null, headersSent: false, endCalls: 0, headers: {}, }; res.set = (k, v) => { res.headers[k] = v; return res; }; res.status = (code) => { res.statusCode = code; res.headersSent = true; return res; }; res.json = (body) => { res.body = body; return res; }; res.end = () => { res.endCalls += 1; return res; }; return res; } function makeReq({ body, query, session } = {}) { return { body: body || {}, query: query || {}, headers: { "user-agent": "test-agent" }, sessionID: "admin-sid", session: session || { user: "admin@example.test" }, }; } // Runs the captured handler the way Express 4 does and reports whether the // promise settled (correct) or rejected (the bug — an unanswered request). async function runHandler(handler, req, res) { let rejection = null; try { await handler(req, res); } catch (err) { rejection = err; } return { rejection }; } // Loads a route statement into a sandbox and returns the registered handler. function loadRoute(statementKey, sandbox) { const captured = []; const ctx = vm.createContext({ ...sandbox, app: { get: (...args) => captured.push(args), post: (...args) => captured.push(args), delete: (...args) => captured.push(args), use: (...args) => captured.push(args) }, console: { log: () => {}, error: () => {}, warn: () => {} }, String, Number, Boolean, Math, Date, Object, Array, JSON, Promise, Symbol, Error, RegExp, }); vm.runInContext(statements[statementKey], ctx, { filename: `index.js[${statementKey}]` }); assert.equal(captured.length, 1, "exactly one route registration per statement"); const handler = captured[0][captured[0].length - 1]; assert.equal(typeof handler, "function", "the last registration argument is the handler"); return handler; } const ADMIN_USER = { id: 7, email: "admin@example.test", admin: 1 }; // --------------------------------------------------------------------------- // GET /api/settings/security // --------------------------------------------------------------------------- function securitySandbox(overrides = {}) { return { isAdmin: async () => true, findUserByEmail: async () => ADMIN_USER, readEnvFile: () => ({ SITE_KEY: "site-key-123456", SECRET_KEY: "secret-key-123456" }), security: { rate_limiting: true, limit: 5, window_seconds: 120, trusted_subnets: ["10.0.0.0/8"] }, getDestructiveActionSecurityAsync: async () => ({ twoFactorEnabled: false, requiresVerification: false }), issueActionToken: () => "token-stub", ...overrides, }; } test("GET /api/settings/security success: body shape and mint pool unchanged", async () => { const handler = loadRoute("securityGet", securitySandbox()); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null); assert.equal(res.statusCode, 0, "200 via res.json"); assert.deepEqual(Object.keys(res.body), ["rate_limiting", "limit", "window_seconds", "trusted_subnets", "captcha_enabled", "revokeSecurity", "actionTokens"], "the response body keeps its exact key set"); assert.equal(res.body.captcha_enabled, true); assert.deepEqual(Object.keys(res.body.actionTokens), ["updateSecurity", "updateCaptcha"]); assert.equal(res.headers["Cache-Control"], "no-store", "the no-store header is still set"); }); for (const [depName, makeOverride, expectNoStore] of [ ["isAdmin", () => ({ isAdmin: () => Promise.reject(new Error("db down in isAdmin")) }), false], ["findUserByEmail", () => ({ findUserByEmail: () => Promise.reject(new Error("db down in the acting-admin lookup")) }), true], ["getDestructiveActionSecurityAsync", () => ({ getDestructiveActionSecurityAsync: () => Promise.reject(new Error("redis down in the security scan")) }), true], ]) { test(`GET /api/settings/security: a rejected ${depName} answers a bounded 500 (no hang, no rejection, no internals)`, async () => { const handler = loadRoute("securityGet", securitySandbox(makeOverride())); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null, `${depName}: the rejection must NOT escape the handler (Express 4 would hang the request)`); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "failed to load security settings" }, "the guarded 500 body (route's established wording, no internals)"); assert.equal(res.body.error.includes("db down"), false, "no internal error text leaked"); assert.equal(res.endCalls, 0, "the 500 path answers exactly once"); assert.equal(!!res.headers["Cache-Control"], expectNoStore, expectNoStore ? "no-store was already set before the failure" : "a pre-gate failure behaves like today's pre-gate 403 (no header yet)"); }); } // --------------------------------------------------------------------------- // GET /api/settings/maintenance // --------------------------------------------------------------------------- function maintenanceSandbox(overrides = {}) { return { isAdmin: async () => true, findUserByEmail: async () => ADMIN_USER, getMaintenanceState: () => ({ enabled: false, scheduled_at: null, reason: null }), isMaintenanceActive: () => false, getDestructiveActionSecurityAsync: async () => ({ twoFactorEnabled: false }), issueActionToken: () => "token-stub", ...overrides, }; } test("GET /api/settings/maintenance success: body shape unchanged", async () => { const handler = loadRoute("maintenanceGet", maintenanceSandbox()); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null); assert.equal(res.statusCode, 0); assert.equal(res.body.enabled, false); assert.equal(res.body.is_active, false); assert.deepEqual(Object.keys(res.body.actionTokens), ["enableMaintenance", "disableMaintenance"]); assert.equal(res.headers["Cache-Control"], "no-store"); }); for (const [depName, makeOverride, expectNoStore] of [ ["isAdmin", () => ({ isAdmin: () => Promise.reject(new Error("db down in isAdmin")) }), false], ["findUserByEmail", () => ({ findUserByEmail: () => Promise.reject(new Error("db down in the acting-admin lookup")) }), true], ["getDestructiveActionSecurityAsync", () => ({ getDestructiveActionSecurityAsync: () => Promise.reject(new Error("redis down in the security scan")) }), true], ]) { test(`GET /api/settings/maintenance: a rejected ${depName} answers a bounded 500`, async () => { const handler = loadRoute("maintenanceGet", maintenanceSandbox(makeOverride())); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null, `${depName}: the rejection must NOT escape the handler`); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "failed to load maintenance settings" }, "the guarded 500 body (route's established wording, no internals)"); assert.equal(res.endCalls, 0); assert.equal(!!res.headers["Cache-Control"], expectNoStore); }); } // --------------------------------------------------------------------------- // GET /api/settings/action-tokens // --------------------------------------------------------------------------- function actionTokensSandbox(overrides = {}) { return { isAdmin: async () => true, agentFeature: { enabled: true }, issueActionToken: () => "token-stub", ...overrides, }; } test("GET /api/settings/action-tokens success: refreshable mint pool keeps its documented shape", async () => { const handler = loadRoute("actionTokens", actionTokensSandbox()); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null); assert.equal(res.statusCode, 0); assert.equal(res.body.ok, true); const pool = res.body.actionTokens; for (const key of ["updateSecurity", "updateCaptcha", "enableMaintenance", "disableMaintenance", "revokeSession", "addAccess", "removeAccess", "setAgentAccess", "grantPerms", "changePassword", "createUser", "reset2fa", "confirmReset2fa", "resetRecoveryCodes", "saveWebhook", "testWebhook", "checkUpdate", "setAutoUpdate", "updateBranding", "updateLoginBackground", "createAlert"]) { assert.ok(key in pool, `the refresh pool keeps ${key}`); } assert.equal(JSON.stringify(pool).includes("deleteToken:"), false, "no per-account delete token in the pool"); assert.equal(Object.keys(pool).some((k) => k.includes("suspensionToken")), false, "no per-account suspension token in the pool"); assert.equal(res.headers["Cache-Control"], "no-store"); }); test("GET /api/settings/action-tokens with Agent OFF omits only the Agent grant token", async () => { const enabled = loadRoute("actionTokens", actionTokensSandbox()); const disabled = loadRoute("actionTokens", actionTokensSandbox({ agentFeature: { enabled: false } })); const enabledRes = makeRes(); const disabledRes = makeRes(); assert.equal((await runHandler(enabled, makeReq(), enabledRes)).rejection, null); assert.equal((await runHandler(disabled, makeReq(), disabledRes)).rejection, null); const { setAgentAccess, ...ordinary } = enabledRes.body.actionTokens; assert.ok(setAgentAccess); assert.deepEqual(Object.keys(disabledRes.body.actionTokens).sort(), Object.keys(ordinary).sort()); }); test("GET /api/settings/action-tokens: a rejected isAdmin answers a bounded 500", async () => { const handler = loadRoute("actionTokens", actionTokensSandbox({ isAdmin: () => Promise.reject(new Error("db down in isAdmin")) })); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null, "the rejection must NOT escape the handler"); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "failed to issue action tokens" }, "the guarded 500 body (route's established wording, no internals)"); assert.equal(res.endCalls, 0); }); test("GET /api/settings/action-tokens: a throwing token mint inside the response answers a bounded 500 (the mint pool is inside the guard)", async () => { const handler = loadRoute("actionTokens", actionTokensSandbox({ issueActionToken: () => { throw new Error("session store down while minting"); }, })); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null, "a sync throw inside the async handler rejects its promise — the guard must answer it"); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "failed to issue action tokens" }); }); // --------------------------------------------------------------------------- // GET /api/settings/sessions // --------------------------------------------------------------------------- function sessionsSandbox(overrides = {}) { return { isAdmin: async () => true, findUserByEmail: async () => ADMIN_USER, getBrowserLoginSessionsInventory: async () => [], getSessionDisplayId: (sid) => `display(${sid})`, getRememberLoginDisplayId: (rid) => `remember(${rid})`, describeUserAgent: () => "UA-label", maskIpAddress: () => "1.2.3.0", issueSessionRevokeTargetToken: () => "revoke-token-stub", getDestructiveActionSecurityAsync: async () => ({ twoFactorEnabled: false }), issueActionToken: () => "token-stub", ACTIVE_BROWSER_SESSION_SEARCH_MAX: 100, ACTIVE_BROWSER_SESSION_PAGE_SIZE: 10, ...overrides, }; } test("GET /api/settings/sessions success: body shape unchanged", async () => { const handler = loadRoute("sessionsGet", sessionsSandbox()); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null); assert.equal(res.statusCode, 0); assert.deepEqual(res.body.items, []); assert.equal(res.body.total, 0); assert.deepEqual(Object.keys(res.body.actionTokens), ["revokeSession"]); assert.equal(res.headers["Cache-Control"], "no-store"); }); for (const [depName, makeOverride] of [ ["isAdmin", () => ({ isAdmin: () => Promise.reject(new Error("db down in isAdmin")) })], ["findUserByEmail", () => ({ findUserByEmail: () => Promise.reject(new Error("db down in the acting-admin lookup")) })], ["getBrowserLoginSessionsInventory", () => ({ getBrowserLoginSessionsInventory: () => Promise.reject(new Error("session store down")) })], ]) { test(`GET /api/settings/sessions: a rejected ${depName} answers a bounded 500`, async () => { const handler = loadRoute("sessionsGet", sessionsSandbox(makeOverride())); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null, `${depName}: the rejection must NOT escape the handler`); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "failed to load sessions" }, "the route's established failure wording (no internals)"); assert.equal(res.endCalls, 0); assert.equal(res.body.error.includes("session store"), false, "no internal error text leaked"); }); } // --------------------------------------------------------------------------- // GET /api/maintenance/status // --------------------------------------------------------------------------- function maintenanceStatusSandbox(overrides = {}) { return { getMaintenanceState: () => ({ scheduled_at: null }), isMaintenanceActive: () => false, isAuthenticated: async () => true, ...overrides, }; } test("GET /api/maintenance/status success: payload shape unchanged", async () => { const handler = loadRoute("maintenanceStatus", maintenanceStatusSandbox()); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null); assert.equal(res.statusCode, 0); assert.deepEqual(res.body, { active: false, scheduled_at: null }); assert.equal(res.headers["Cache-Control"], "no-store"); }); test("GET /api/maintenance/status: a rejected isAuthenticated answers a bounded 500", async () => { const handler = loadRoute("maintenanceStatus", maintenanceStatusSandbox({ isAuthenticated: () => Promise.reject(new Error("session store down")), })); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null, "the rejection must NOT escape the handler"); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "internal error" }, "the guarded 500 body (no internals)"); assert.equal(res.endCalls, 0); assert.equal(res.headers["Cache-Control"], "no-store", "the pre-auth poller's no-store header was set before the failure and stays"); }); // --------------------------------------------------------------------------- // POST /api/settings/sessions/revoke — the pre-try awaits // --------------------------------------------------------------------------- function sessionsRevokeSandbox(overrides = {}) { const calls = { tokenGates: [], lookups: [], consumptions: [] }; const sandbox = { sessionRevoke2faRateLimiter: { name: "sessionRevoke2faRateLimiter" }, isAdmin: async () => true, requireActionTokenOr403: async (req, res, action) => { calls.tokenGates.push(action); return true; }, findUserByEmail: async (email) => { calls.lookups.push(email); return ADMIN_USER; }, consumeSessionRevokeTargetToken: async (req, token) => { calls.consumptions.push(token); return null; }, calls, ...overrides, }; return { sandbox, calls }; } test("POST /api/settings/sessions/revoke flow order preserved: 403 gate, no-store, token gate, admin 403, expired-target 400 all keep their shapes", async () => { const { sandbox, calls } = sessionsRevokeSandbox(); const handler = loadRoute("sessionsRevoke", sandbox); // non-admin gate first const nonAdminSandbox = sessionsRevokeSandbox({ isAdmin: async () => false }).sandbox; const nonAdminHandler = loadRoute("sessionsRevoke", nonAdminSandbox); const res403 = makeRes(); const r1 = await runHandler(nonAdminHandler, makeReq({ body: { revokeToken: "t" } }), res403); assert.equal(r1.rejection, null); assert.equal(res403.statusCode, 403); assert.deepEqual(res403.body, { error: "not authorized" }); // admin passes; token gate and admin re-check keep their order const res = makeRes(); const r2 = await runHandler(handler, makeReq({ body: { revokeToken: "some-token" } }), res); assert.equal(r2.rejection, null); assert.deepEqual(calls.tokenGates, ["POST /api/settings/sessions/revoke"], "the token gate ran"); assert.deepEqual(calls.lookups, ["admin@example.test"], "the acting-admin lookup ran after the token gate"); assert.equal(res.statusCode, 400, "the consumed-token miss answers the established 400"); assert.deepEqual(res.body, { error: "Session action expired. Reload Sessions and try again.", code: "session-action-expired" }); }); for (const [depName, override] of [ ["isAdmin", { isAdmin: () => Promise.reject(new Error("db down in isAdmin")) }], ["requireActionTokenOr403", { requireActionTokenOr403: () => Promise.reject(new Error("db down in the action-token gate")) }], ["findUserByEmail", { findUserByEmail: () => Promise.reject(new Error("db down in the acting-admin lookup")) }], ["consumeSessionRevokeTargetToken", { consumeSessionRevokeTargetToken: () => Promise.reject(new Error("redis down consuming the target token")) }], ]) { test(`POST /api/settings/sessions/revoke: a rejected ${depName} in the pre-try section answers a bounded 500`, async () => { const { sandbox } = sessionsRevokeSandbox(override); const handler = loadRoute("sessionsRevoke", sandbox); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq({ body: { revokeToken: "some-token" } }), res); assert.equal(rejection, null, `${depName}: the rejection must NOT escape the handler (Express 4 would hang the request)`); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "internal error" }, "the guarded 500 body (no internals)"); assert.equal(res.endCalls, 0); assert.equal(res.body.error.includes("redis"), false, "no internal error text leaked"); }); } // --------------------------------------------------------------------------- // Both admin 2FA-reset thin adapters: injected db failure stays bounded // --------------------------------------------------------------------------- const TARGET_2FA = { id: 42, email: "target@example.test", admin: 0, secret: "sealed:TOTPSEED" }; const ADMIN_ACTING = { id: 7, email: "admin@example.test", admin: 1 }; function make2faDeps(db) { return { isAdmin: async () => true, requireActionTokenOr403: async () => true, findUserByEmail: async (email) => (email === ADMIN_ACTING.email ? ADMIN_ACTING : TARGET_2FA), requireDestructiveActionStepUp: async () => ({ ok: true }), db, destroyBrowserSessionsForUser: async () => ({ destroyed: 2, rememberLoginsRevoked: 1, errors: [] }), disconnectSocketsForUser: () => 3, recordActivity: () => {}, getRequestIp: () => "127.0.0.1", normalizeAdminTargetEmail: (raw) => (typeof raw === "string" && raw.includes("@") ? raw.trim() : null), stripLogControlChars: (s) => String(s == null ? "" : s), logger: { log: () => {}, error: () => {}, warn: () => {} }, }; } for (const [key, route] of [["reset2fa", "/api/admin/user/reset-2fa"], ["confirm2faReset", "/api/admin/user/confirm-2fa-reset"]]) { test(`2FA adapter containment: an injected db failure on ${route} yields a bounded 500 (never a hang, never a rejection)`, async () => { const service = createAdminTwoFactorResetService(make2faDeps({ async query() { throw new Error("db down during the write"); }, })); const captured = []; const ctx = vm.createContext({ app: { post: (...args) => captured.push(args) }, sessionRevoke2faRateLimiter: { name: "sessionRevoke2faRateLimiter" }, handleAdmin2faReset: service.handleAdmin2faReset, console: { log: () => {}, error: () => {}, warn: () => {} }, String, Number, Object, JSON, Promise, Date, Math, Error, }); vm.runInContext(statements[key], ctx, { filename: `index.js[${key}]` }); assert.equal(captured.length, 1, "exactly one registration"); const adapter = captured[0][2]; const res = makeRes(); const { rejection } = await runHandler(adapter, makeReq({ body: { email: TARGET_2FA.email, expectedTargetId: TARGET_2FA.id } }), res); assert.equal(rejection, null, `${route}: the injected db failure must NOT escape the thin adapter`); assert.equal(res.statusCode, 500, `${route}: the request is answered (no hanging client)`); assert.deepEqual(res.body, { error: "internal error" }, `${route}: the flat guarded 500 body`); assert.equal(res.endCalls, 0); }); } // --------------------------------------------------------------------------- // POST /api/settings/captcha — pre-flight containment // --------------------------------------------------------------------------- function captchaSandbox(overrides = {}) { const calls = { tokenGates: [], stepUps: [], envWrites: [] }; const sandbox = { sessionRevoke2faRateLimiter: { name: "sessionRevoke2faRateLimiter" }, isAdmin: async () => true, requireActionTokenOr403: async (req, res, action) => { calls.tokenGates.push(action); return true; }, findUserByEmail: async () => ADMIN_USER, requireDestructiveActionStepUp: async (req, res, user, subject) => { calls.stepUps.push(subject); return { ok: true, graceExpiresAt: 12345 }; }, getVerifiedSessionRevokeGraceState: async () => null, getDestructiveActionSecurityAsync: async () => ({ twoFactorEnabled: false }), writeEnvValue: (key, value) => { calls.envWrites.push([key, value]); return true; }, applyCaptchaConfig: () => {}, clearAllLoginCaptchaArming: () => {}, process: { env: {} }, EXTERNAL_CAPTCHA_PROVIDER: "cloudflare", EXTERNAL_CAPTCHA_SITE_KEY: "site-key-value-123456", calls, ...overrides, }; return sandbox; } test("POST /api/settings/captcha success: payload shape, gate order and persistence unchanged", async () => { const sandbox = captchaSandbox(); const handler = loadRoute("captchaPost", sandbox); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq({ body: { site_key: "site-key-value-123456", secret_key: "secret-key-value-123456", enabled: true } }), res); assert.equal(rejection, null); assert.equal(res.statusCode, 0, "200 via res.json"); assert.deepEqual(res.body, { ok: true, captcha_enabled: true, provider: "cloudflare", graceExpiresAt: 12345, revokeSecurity: { twoFactorEnabled: false }, }, "the success payload keeps its exact shape"); assert.equal(sandbox.process.env.SITE_KEY, "site-key-value-123456", "the runtime config hot-swap still ran"); assert.equal(sandbox.process.env.SECRET_KEY, "secret-key-value-123456"); assert.deepEqual(sandbox.calls.tokenGates, ["POST /api/settings/captcha"], "the token gate ran with the route's action string"); assert.deepEqual(sandbox.calls.stepUps, ["Captcha configuration update"], "the step-up ran after the gates"); assert.deepEqual(sandbox.calls.envWrites, [["SITE_KEY", "site-key-value-123456"], ["SECRET_KEY", "secret-key-value-123456"]], "the keys were persisted"); }); test("POST /api/settings/captcha: gates keep their order — non-admin 403 first, malformed payload 400 before the step-up", async () => { const nonAdminHandler = loadRoute("captchaPost", captchaSandbox({ isAdmin: async () => false })); const res403 = makeRes(); const r1 = await runHandler(nonAdminHandler, makeReq({ body: {} }), res403); assert.equal(r1.rejection, null); assert.equal(res403.statusCode, 403); assert.deepEqual(res403.body, { error: "not authorized" }); const sandbox = captchaSandbox(); const handler = loadRoute("captchaPost", sandbox); const res400 = makeRes(); const r2 = await runHandler(handler, makeReq({ body: { site_key: "short", secret_key: "secret-key-value-123456", enabled: true } }), res400); assert.equal(r2.rejection, null); assert.equal(res400.statusCode, 400); assert.deepEqual(res400.body, { error: "invalid site key" }, "the 400 shape keeps its exact wording"); assert.deepEqual(sandbox.calls.stepUps, [], "a malformed payload never reaches the step-up"); }); for (const [depName, override] of [ ["isAdmin", { isAdmin: () => Promise.reject(new Error("db down in isAdmin")) }], ["requireActionTokenOr403", { requireActionTokenOr403: () => Promise.reject(new Error("db down in the action-token gate")) }], ["findUserByEmail", { findUserByEmail: () => Promise.reject(new Error("db down in the acting-admin lookup")) }], ]) { test(`POST /api/settings/captcha: a rejected ${depName} in the pre-flight answers a bounded 500`, async () => { const handler = loadRoute("captchaPost", captchaSandbox(override)); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq({ body: { enabled: false } }), res); assert.equal(rejection, null, `${depName}: the rejection must NOT escape the handler (Express 4 would hang the request)`); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "failed to update configuration" }, "the guarded 500 body (the route's established wording, no internals)"); assert.equal(res.endCalls, 0, "the 500 path answers exactly once"); assert.equal(res.body.error.includes("db down"), false, "no internal error text leaked"); }); } // --------------------------------------------------------------------------- // POST /api/settings/maintenance — pre-flight containment // --------------------------------------------------------------------------- function maintenancePostSandbox(overrides = {}) { const calls = { tokenGates: [], stepUps: [], saves: [], alerts: [] }; const sandbox = { sessionRevoke2faRateLimiter: { name: "sessionRevoke2faRateLimiter" }, isAdmin: async () => true, requireActionTokenOr403: async (req, res, action) => { calls.tokenGates.push(action); return true; }, findUserByEmail: async () => ADMIN_USER, requireDestructiveActionStepUp: async (req, res, user, subject) => { calls.stepUps.push(subject); return { ok: true, graceExpiresAt: 6789 }; }, getMaintenanceState: () => ({ enabled: false, scheduled_at: null, reason: null }), saveMaintenanceState: (state) => { calls.saves.push(state); return true; }, getActiveGlobalAlert: () => null, addGlobalAlert: (message, at) => { calls.alerts.push([message, at]); return { id: "pre-alert-1" }; }, sanitizeGlobalAlertMessage: (s) => String(s), startMaintenanceChecker: () => {}, stripLogControlChars: (s) => String(s == null ? "" : s), getVerifiedSessionRevokeGraceState: async () => null, getDestructiveActionSecurityAsync: async () => ({ twoFactorEnabled: false }), isNaN, parseInt, calls, ...overrides, }; return sandbox; } test("POST /api/settings/maintenance success: payload shape and persistence flow unchanged", async () => { const sandbox = maintenancePostSandbox(); const handler = loadRoute("maintenancePost", sandbox); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq({ body: { reason: "ops window", immediate: true } }), res); assert.equal(rejection, null); assert.equal(res.statusCode, 0, "200 via res.json"); assert.deepEqual(res.body, { ok: true, state: { enabled: true, scheduled_at: null }, graceExpiresAt: 6789, revokeSecurity: { twoFactorEnabled: false }, }, "the success payload keeps its exact shape"); assert.equal(sandbox.calls.saves.length, 1, "exactly one save"); assert.equal(sandbox.calls.saves[0].enabled, true, "the state was enabled"); assert.equal(sandbox.calls.saves[0].reason, "ops window"); assert.deepEqual(sandbox.calls.tokenGates, ["POST /api/settings/maintenance"]); assert.deepEqual(sandbox.calls.stepUps, ["Maintenance activation"]); assert.deepEqual(sandbox.calls.alerts, [], "no pre-alert injection without pre_alert fields"); }); test("POST /api/settings/maintenance: gates keep their order — non-admin 403 first, token gate before the acting-admin 403", async () => { const nonAdminHandler = loadRoute("maintenancePost", maintenancePostSandbox({ isAdmin: async () => false })); const res403 = makeRes(); const r1 = await runHandler(nonAdminHandler, makeReq({ body: {} }), res403); assert.equal(r1.rejection, null); assert.equal(res403.statusCode, 403); assert.deepEqual(res403.body, { error: "not authorized" }); const nonAdminLookup = maintenancePostSandbox({ findUserByEmail: async () => ({ id: 8, email: "admin@example.test", admin: 0 }) }); const handler = loadRoute("maintenancePost", nonAdminLookup); const res2 = makeRes(); const r2 = await runHandler(handler, makeReq({ body: {} }), res2); assert.equal(r2.rejection, null); assert.equal(res2.statusCode, 403); assert.deepEqual(res2.body, { error: "not authorized" }, "the acting-admin re-check keeps its 403 shape"); assert.deepEqual(nonAdminLookup.calls.tokenGates, ["POST /api/settings/maintenance"], "the token gate ran before the acting-admin re-check"); }); for (const [depName, override] of [ ["isAdmin", { isAdmin: () => Promise.reject(new Error("db down in isAdmin")) }], ["requireActionTokenOr403", { requireActionTokenOr403: () => Promise.reject(new Error("db down in the action-token gate")) }], ["findUserByEmail", { findUserByEmail: () => Promise.reject(new Error("db down in the acting-admin lookup")) }], ]) { test(`POST /api/settings/maintenance: a rejected ${depName} in the pre-flight answers a bounded 500`, async () => { const handler = loadRoute("maintenancePost", maintenancePostSandbox(override)); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq({ body: { immediate: true } }), res); assert.equal(rejection, null, `${depName}: the rejection must NOT escape the handler (Express 4 would hang the request)`); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "Failed to save maintenance state" }, "the guarded 500 body (the route's established wording, no internals)"); assert.equal(res.endCalls, 0, "the 500 path answers exactly once"); assert.equal(res.body.error.includes("db down"), false, "no internal error text leaked"); }); } // --------------------------------------------------------------------------- // DELETE /api/settings/maintenance — pre-flight containment // --------------------------------------------------------------------------- function maintenanceDeleteSandbox(overrides = {}) { const calls = { tokenGates: [], restores: 0, saves: [] }; const sandbox = { isAdmin: async () => true, requireActionTokenOr403: async (req, res, action) => { calls.tokenGates.push(action); return true; }, findUserByEmail: async () => ADMIN_USER, getMaintenanceState: () => ({ enabled: true, reason: "ops window", pre_alert: { show: true, message: "m", minutes_before: 5, _alert_injected: true } }), restoreAlertAfterMaintenance: () => { calls.restores += 1; }, saveMaintenanceState: (state) => { calls.saves.push(state); return true; }, stripLogControlChars: (s) => String(s == null ? "" : s), calls, ...overrides, }; return sandbox; } test("DELETE /api/settings/maintenance success: reset state and { ok: true } body unchanged", async () => { const sandbox = maintenanceDeleteSandbox(); const handler = loadRoute("maintenanceDelete", sandbox); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null); assert.equal(res.statusCode, 0, "200 via res.json"); assert.deepEqual(res.body, { ok: true }); assert.equal(sandbox.calls.restores, 1, "the pre-alert restore ran before the reset"); assert.equal(sandbox.calls.saves.length, 1, "exactly one save"); assert.deepEqual(sandbox.calls.saves[0], { enabled: false, scheduled_at: null, enabled_by: null, enabled_at: null, reason: null, pre_alert: { show: false, message: null, minutes_before: null }, previous_alert_backup: null, }, "the reset state keeps its exact shape"); assert.deepEqual(sandbox.calls.tokenGates, ["DELETE /api/settings/maintenance"]); }); for (const [depName, override] of [ ["isAdmin", { isAdmin: () => Promise.reject(new Error("db down in isAdmin")) }], ["requireActionTokenOr403", { requireActionTokenOr403: () => Promise.reject(new Error("db down in the action-token gate")) }], ["findUserByEmail", { findUserByEmail: () => Promise.reject(new Error("db down in the acting-admin lookup")) }], ]) { test(`DELETE /api/settings/maintenance: a rejected ${depName} in the pre-flight answers a bounded 500`, async () => { const handler = loadRoute("maintenanceDelete", maintenanceDeleteSandbox(override)); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null, `${depName}: the rejection must NOT escape the handler (Express 4 would hang the request)`); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "Failed to save maintenance state" }, "the guarded 500 body (the route's established wording, no internals)"); assert.equal(res.endCalls, 0, "the 500 path answers exactly once"); assert.equal(res.body.error.includes("db down"), false, "no internal error text leaked"); }); } // --------------------------------------------------------------------------- // Hardened inner catches: the headersSent discipline (end-once, no second 500) // --------------------------------------------------------------------------- // Simulates a failure AFTER the response started (socket closed mid-send): // res.json records the payload, marks the headers sent, then throws — the // hardened catch must end the already-answered response exactly once and // never attempt a second res.status. function midSendFailure(res) { res.json = (body) => { res.body = body; res.headersSent = true; throw new Error("socket closed mid-send"); }; return res; } test("GET /api/settings/sessions: a failure after the response started ends the response once (headersSent guard, no second 500)", async () => { const handler = loadRoute("sessionsGet", sessionsSandbox()); const res = midSendFailure(makeRes()); const { rejection } = await runHandler(handler, makeReq(), res); assert.equal(rejection, null, "the mid-send failure must not escape the handler"); assert.equal(res.endCalls, 1, "the already-answered response is ended exactly once"); assert.equal(res.statusCode, 0, "no second res.status after the headers were sent"); assert.ok(res.body && typeof res.body === "object", "the built payload was not destroyed by the guard"); }); // --------------------------------------------------------------------------- // POST /api/admin/user/reset-recovery-codes — final-catch headersSent discipline // --------------------------------------------------------------------------- const RECOVERY_TARGET = { id: 42, email: "target@example.test", admin: 0, session_epoch: 3, recovery_codes: "[]" }; const RECOVERY_ACTING = { id: 7, email: "admin@example.test", admin: 1, suspended: 0, session_epoch: 9 }; function recoveryResetSandbox(overrides = {}) { const sandbox = { ...require("../services/account-actions"), ...require("../services/account-credentials"), sessionRevoke2faRateLimiter: { name: "sessionRevoke2faRateLimiter" }, isAdmin: async () => true, requireActionTokenOr403: async () => true, normalizeAdminTargetEmail: (raw) => (typeof raw === "string" && raw.includes("@") ? raw.trim() : null), findUserByEmail: async (email) => (email === RECOVERY_ACTING.email ? RECOVERY_ACTING : RECOVERY_TARGET), requireDestructiveActionStepUp: async () => ({ ok: true }), crypto: { randomBytes: () => Buffer.from([7]) }, bcrypt: { hash: async (code, rounds) => `hashed(${rounds}):${code}` }, BCRYPT_ROUNDS: 4, db: { async query() { return { affectedRows: 1 }; } }, stripLogControlChars: (s) => String(s == null ? "" : s), getRequestIp: () => "127.0.0.1", recordActivity: () => {}, STALE_TARGET_409_MESSAGE: "stale target", ...overrides, }; sandbox.db = require("./helpers/account-transaction").attachAccountTransaction(sandbox.db, { actor: RECOVERY_ACTING, target: RECOVERY_TARGET }); return sandbox; } test("POST /api/admin/user/reset-recovery-codes: a rejected db write at the final write answers the route's established 500 (containment)", async () => { const handler = loadRoute("resetRecoveryCodes", recoveryResetSandbox({ db: { async query() { throw new Error("db down during the recovery write"); } }, })); const res = makeRes(); const { rejection } = await runHandler(handler, makeReq({ body: { email: "target@example.test", expectedTargetId: RECOVERY_TARGET.id } }), res); assert.equal(rejection, null, "the write failure must not escape the handler"); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "Failed to reset recovery codes" }, "the route's established write-failure shape"); assert.equal(res.body.recoveryCodes, undefined, "no codes ride a failed write"); assert.equal(res.endCalls, 0, "the headersSent-false path answers exactly once via the guarded 500"); }); test("POST /api/admin/user/reset-recovery-codes: a failure after the response started ends the response once (headersSent guard, no second 500)", async () => { const handler = loadRoute("resetRecoveryCodes", recoveryResetSandbox()); const res = midSendFailure(makeRes()); const { rejection } = await runHandler(handler, makeReq({ body: { email: "target@example.test", expectedTargetId: RECOVERY_TARGET.id } }), res); assert.equal(rejection, null, "the mid-send failure must not escape the handler"); assert.equal(res.endCalls, 1, "the already-answered response is ended exactly once"); assert.equal(res.statusCode, 0, "no second res.status after the headers were sent"); assert.ok(res.body && Array.isArray(res.body.recoveryCodes), "the built payload survived the guard"); });