"use strict"; // Tests for the template-store crash-path guards (review finding: "Sync and // store-install handlers can crash the entire panel on a transient DB error"). // // findUserByEmail re-throws database errors (its catch only handles the // ER_BAD_FIELD_ERROR legacy-column fallback, else `throw err`), Express 4 does // not catch async-handler rejections, and the process-level unhandledRejection // handler is only a crash backstop, never a response path — so a single MySQL // hiccup, failover or 8s query // timeout at the wrong moment turned into an unhandled rejection and a full // process exit: every tenant's session dropped, with PM2 restarting into the // same failing state while the DB is degraded. The template create/update/ // delete routes already carried a full-body per-route guard for exactly this // (generic 500, full error in the server log) — but the two template-store // routes did not: // - POST /api/settings/template-store/sync: findUserByEmail and the // step-up call sat OUTSIDE the inner try (which only wrapped // ensureTemplateStoreCacheFresh → 502); // - POST /api/settings/templates/store-install: findUserByEmail, the step-up // and withKeyedLock sat outside any try. // Two helpers on the same path could also reject into unguarded territory: // - persistDestructiveActionGrace ran setSessionRevokeGrace BEFORE its try // block, so any DB throw from the grant INSERT escaped to the caller; // - setSessionRevokeGrace treated EVERY first-INSERT failure as "the table // predates the scope_hash migration" and retried an UNCAUGHT unscoped // INSERT — on a real DB failure the fallback threw and the rejection // escaped. Worse, on total failure it would still have minted the // memory/session state for a DB row that was never written (a phantom // grant: getVerifiedSessionRevokeGraceState re-validates against the DB // and fails closed on the missing row). // // The remediation locked here: // - Both store routes wrap their FULL handler body in try/catch (starting at // the first statement, so the session/DB-backed isAdmin is covered too), // mirroring the create route: catch logs with a [template-store] tag and // answers 500 only when !res.headersSent. The sync route's inner // try/catch (→ 502 for sync failures) stays inside the outer guard, so // the 502-vs-500 distinction survives. // - persistDestructiveActionGrace mints the grant INSIDE its try; a failure // returns 0, i.e. "no reusable grace window" — the already-paid step-up // verification still authorizes exactly the one action (fail-closed- // stricter, this codebase's explicit policy). // - setSessionRevokeGrace wraps the unscoped fallback INSERT in its own // try/catch, tracks a `persisted` flag, and returns 0 before touching // destructiveActionGraceMemory or req.session.sessionRevoke2fa when both // inserts fail — no phantom grants. Success-path behavior (memory grant, // session state, return expiresAt) is unchanged. // // index.js boots servers on require, so the contract is pinned with source // assertions in the extract-and-regex style of // tests/destructive-route-guards.test.js, plus behavioral tests that slice // persistDestructiveActionGrace and setSessionRevokeGrace out of the source // and execute them in a vm sandbox with stubbed db/session (same technique as // tests/template-store-sync-backoff.test.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 INDEX_JS = path.join(__dirname, "..", "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); // Strip full-line // comments FIRST, then block comments, so prose cannot // satisfy or violate assertions (same approach as // tests/db-teardown-stepup-gates.test.js). function stripComments(src) { return src .replace(/^[ \t]*\/\/.*$/gm, "") .replace(/\/\*[\s\S]*?\*\//g, ""); } function extractRoute(source, routeMarker, nextRouteMarker) { const start = source.indexOf(routeMarker); assert.ok(start >= 0, `route marker not found: ${routeMarker}`); const end = source.indexOf(nextRouteMarker, start); assert.ok(end > start, `next route marker not found after route: ${nextRouteMarker}`); return source.slice(start, end); } // Slice a `{ ... }`-balanced function body starting at startMarker (same // brace-count extractor as tests/template-store-sync-backoff.test.js). function endIndexOfFunction(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker ${startMarker} not found in index.js`); const bodyStart = source.indexOf("{", start); let depth = 0; for (let i = bodyStart; i < source.length; i += 1) { if (source[i] === "{") depth += 1; else if (source[i] === "}") { depth -= 1; if (depth === 0) return i + 1; } } assert.fail(`unbalanced braces after marker ${startMarker}`); } const SYNC_ROUTE = indexSource.slice( indexSource.indexOf('app.post("/api/settings/template-store/sync"'), indexSource.indexOf('app.get("/api/settings/template-store/:category"') ); const INSTALL_ROUTE = indexSource.slice( indexSource.indexOf('app.post("/api/settings/templates/store-install"'), indexSource.indexOf("function constructTemplateDefinition(body) {") ); const CREATE_ROUTE = extractRoute( indexSource, 'app.post("/api/settings/templates",', 'app.put("/api/settings/templates/:id"' ); const SYNC_STRIPPED = stripComments(SYNC_ROUTE); const INSTALL_STRIPPED = stripComments(INSTALL_ROUTE); const CREATE_STRIPPED = stripComments(CREATE_ROUTE); // The route's body must start with try { as its FIRST statement (only // whitespace may sit between the arrow and the try — comments are stripped // first, so a comment-only prelude cannot fake this). Everything else in the // handler — isAdmin, findUserByEmail, the step-up, withKeyedLock — is then // necessarily inside the guard. function assertBodyStartsWithTry(strippedRoute, label) { assert.match( strippedRoute, /async \(req, res\) => \{\s*try \{/, `${label} handler body must begin with try { (the whole body, including the session/DB-backed isAdmin gate, must sit inside the per-route crash guard)` ); } // The OUTER catch: from the last "} catch (err) {" in the route to the end of // the registration — the route registration closes right after it. function outerCatchOf(strippedRoute) { const at = strippedRoute.lastIndexOf("} catch (err) {"); assert.ok(at >= 0, "outer catch not found"); return strippedRoute.slice(at); } function assertGuardCatch(catchText, label, logTag) { assert.match( catchText, new RegExp(`console\\.error\\("${logTag}:", err\\?\\.message \\|\\| err\\);`), `${label} outer catch must log the full error under the ${logTag} tag` ); assert.match( catchText, /if \(!res\.headersSent\) return res\.status\(500\)\.json\(\{ error: "internal error" \}\);/, `${label} outer catch must answer a generic 500 only when headers were not already sent` ); // The 500 must NEVER be answered unconditionally (that is what "only when // !res.headersSent" pins): no res.status(500) outside the headersSent guard. const withoutGuard = catchText.replace(/if \(!res\.headersSent\) return res\.status\(500\)\.json\(\{ error: "internal error" \}\);/g, ""); assert.ok( !withoutGuard.includes("res.status(500)"), `${label} outer catch must not answer 500 by any other path` ); } // --------------------------------------------------------------------------- // (a) Per-route crash guard on both store routes // --------------------------------------------------------------------------- test("sync route: full-body try guard with a headersSent-gated 500 catch", () => { assertBodyStartsWithTry(SYNC_STRIPPED, "template-store sync"); assertGuardCatch(outerCatchOf(SYNC_STRIPPED), "template-store sync", "\\[template-store\\] Manual sync failed"); // The inner sync-failure try/catch (→ 502) must survive INSIDE the outer // guard, preserving the 502-vs-500 distinction: the 502 answer (and its // catch) sits before the outer catch. const innerIdx = SYNC_STRIPPED.indexOf('return res.status(502).json({ error: err?.message || "template store sync failed" });'); const outerAt = SYNC_STRIPPED.lastIndexOf("} catch (err) {"); assert.ok(innerIdx > 0 && innerIdx < outerAt, "the ensureTemplateStoreCacheFresh 502 catch must stay inside the outer guard"); // The DB-backed gates the report named are covered: they sit inside the try. const tryIdx = SYNC_STRIPPED.indexOf("try {"); for (const [name, marker] of [ ["isAdmin", "if (!(await isAdmin(req)))"], ["findUserByEmail", "const currentUser = await findUserByEmail(req.session.user);"], ["step-up", "requireDestructiveActionStepUp(req, res, currentUser"], ]) { const at = SYNC_STRIPPED.indexOf(marker); assert.ok(at > tryIdx, `sync route: ${name} must run inside the outer try guard`); } // The crash rationale must be documented on the route (same style as the // create route's guard comment) — asserted pre-strip. assert.match(SYNC_ROUTE, /unhandledRejection handler/, "the route must carry the crash-path rationale comment"); assert.match(SYNC_ROUTE, /every tenant's session/, "the route comment must name the blast radius"); }); test("store-install route: full-body try guard with a headersSent-gated 500 catch", () => { assertBodyStartsWithTry(INSTALL_STRIPPED, "template-store install"); assertGuardCatch(outerCatchOf(INSTALL_STRIPPED), "template-store install", "\\[template-store\\] Store install failed"); const tryIdx = INSTALL_STRIPPED.indexOf("try {"); for (const [name, marker] of [ ["isAdmin", "if (!(await isAdmin(req)))"], ["cache read", "await readTemplateStoreCategoryFromCache(categoryId).catch(() => null)"], ["findUserByEmail", "const currentUser = await findUserByEmail(req.session.user);"], ["step-up", "requireDestructiveActionStepUp(req, res, currentUser"], ["keyed lock", 'withKeyedLock("templates-write"'], ]) { const at = INSTALL_STRIPPED.indexOf(marker); assert.ok(at > tryIdx, `store-install route: ${name} must run inside the outer try guard`); } // The cache read keeps its own .catch(() => null) → 502 fail-closed answer. assert.match( INSTALL_STRIPPED, /if \(!store\) return res\.status\(502\)\.json\(\{ error: "template store cache unavailable" \}\);/, "the self-guarded cache read must keep its 502 answer" ); assert.match(INSTALL_ROUTE, /unhandledRejection handler/, "the route must carry the crash-path rationale comment"); }); // --------------------------------------------------------------------------- // (d) Regression guard: the create route's existing guard is still intact // --------------------------------------------------------------------------- test("template create route: the original full-body guard pattern is unchanged", () => { assertBodyStartsWithTry(CREATE_STRIPPED, "template create"); assertGuardCatch(outerCatchOf(CREATE_STRIPPED), "template create", "\\[templates\\] Template create failed"); assert.match(CREATE_ROUTE, /unhandledRejection handler/, "the create route's rationale comment must survive"); }); // --------------------------------------------------------------------------- // (b) persistDestructiveActionGrace: grant mint runs inside the try // --------------------------------------------------------------------------- const PERSIST_FN = indexSource.slice( indexSource.indexOf("async function persistDestructiveActionGrace"), endIndexOfFunction(indexSource, "async function persistDestructiveActionGrace") ); function buildPersistSandbox(stubs = {}) { const sandbox = { console: { log() { }, warn() { }, error() { } }, Promise, Date, // Faithful mirror of index.js's withTimeout: persistDestructiveActionGrace // bounds the grant mint and the session save with it, so the sandbox must // provide the same primitive for the behavioral tests to exercise the // real control flow. withTimeout: (promise, ms, label = "timeout") => { let timer; return Promise.race([ Promise.resolve(promise), new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(label)), ms); }), ]).finally(() => clearTimeout(timer)); }, setSessionRevokeGrace: async () => 0, getVerifiedSessionRevokeGraceState: async () => null, ...stubs, }; vm.createContext(sandbox); vm.runInContext(PERSIST_FN, sandbox); return sandbox; } test("source: persistDestructiveActionGrace awaits setSessionRevokeGrace inside its try and catches to 0", () => { const stripped = stripComments(PERSIST_FN); const tryIdx = stripped.indexOf("try {"); const callIdx = stripped.indexOf("setSessionRevokeGrace(req, currentUser, context, scopeKey, proofStrength)"); const catchIdx = stripped.indexOf("} catch (err) {"); assert.ok(tryIdx >= 0 && callIdx > tryIdx && catchIdx > callIdx, "the setSessionRevokeGrace grant mint must run inside the try block"); // The mint is bounded by withTimeout (a hang in the grant INSERT chain would // otherwise park the already-verified action's route indefinitely), and it // threads the achieved proof strength (adpanel:stepup-proof-strength) so // every minted grant records how strong its minting verification was. assert.match(stripped, /await withTimeout\(\s*setSessionRevokeGrace\(req, currentUser, context, scopeKey, proofStrength\)/, "the grant mint must be wrapped in withTimeout"); assert.match(stripped, /catch \(err\) \{\s*console\.warn\(`\[security\] Failed to persist \$\{context\} grace window:`, err\?\.message \|\| err\);\s*return 0;\s*\}/, "the catch must warn and return 0 — no rejection may escape to the route"); assert.doesNotMatch(stripped, /let graceExpiresAt = await setSessionRevokeGrace/, "the old form (grant mint BEFORE the try) must be gone"); }); test("persistDestructiveActionGrace: a setSessionRevokeGrace DB rejection is swallowed to 0, not rethrown", async () => { let verifiedCalls = 0; let saveCalls = 0; const sandbox = buildPersistSandbox({ setSessionRevokeGrace: async () => { throw new Error("mysql failover"); }, getVerifiedSessionRevokeGraceState: async () => { verifiedCalls += 1; return null; }, }); sandbox.req = { session: { user: "admin@example.com", save: (cb) => { saveCalls += 1; cb(); } } }; const out = await vm.runInContext( "persistDestructiveActionGrace(req, { id: 7, email: 'admin@example.com' }, 'Test action', 'user:admin@example.com')", sandbox ); assert.equal(out, 0, "a grant-mint DB failure must degrade to 'no grace window' (0), not reject"); assert.equal(saveCalls, 0, "the session save must be skipped when the mint fails"); assert.equal(verifiedCalls, 0, "the DB re-verification must be skipped when the mint fails"); }); test("persistDestructiveActionGrace: success path still returns the minted expiry", async () => { const sandbox = buildPersistSandbox({ setSessionRevokeGrace: async () => 1234567, getVerifiedSessionRevokeGraceState: async () => ({ expiresAt: 1234567 }), }); sandbox.req = { session: { user: "admin@example.com", save: (cb) => cb() } }; const out = await vm.runInContext( "persistDestructiveActionGrace(req, { id: 7, email: 'admin@example.com' }, 'Test action', 'user:admin@example.com')", sandbox ); assert.equal(out, 1234567, "the success path must be unchanged"); }); test("persistDestructiveActionGrace: a session-save failure still returns 0 (unchanged fail-safe)", async () => { const sandbox = buildPersistSandbox({ setSessionRevokeGrace: async () => 1234567, getVerifiedSessionRevokeGraceState: async () => { throw new Error("must not be reached"); }, }); sandbox.req = { session: { user: "admin@example.com", save: (cb) => cb(new Error("session store down")) } }; const out = await vm.runInContext( "persistDestructiveActionGrace(req, { id: 7, email: 'admin@example.com' }, 'Test action')", sandbox ); assert.equal(out, 0, "a session-save failure must keep degrading to 0"); }); // --------------------------------------------------------------------------- // (c) setSessionRevokeGrace: both INSERTs survivable, no phantom grants // --------------------------------------------------------------------------- const SET_FN = indexSource.slice( indexSource.indexOf("async function setSessionRevokeGrace"), endIndexOfFunction(indexSource, "async function setSessionRevokeGrace") ); // Executes the REAL sliced setSessionRevokeGrace against a stubbed db. The // hash helpers are stubbed (they are pure HMAC wrappers tested elsewhere); // everything else — the insert sequence, the persisted flag, the early // return, the memory/session minting — is the verbatim index.js code. function runSetSessionRevokeGrace(dbStub, { scopeKey = "user:admin@example.com", proofStrength = null } = {}) { const queries = []; const warns = []; const memory = new Map(); const sandbox = { console: { log() { }, warn: (msg, detail) => warns.push(`${msg} ${detail || ""}`), error() { } }, crypto: require("node:crypto"), Date, Promise, DESTRUCTIVE_ACTION_GRACE_TABLE: "destructive_action_graces", SESSION_REVOKE_2FA_GRACE_MS: 10 * 60 * 1000, cleanupExpiredDestructiveActionGrants: async () => { }, getSessionRevokeGraceSessionHash: () => "a".repeat(64), getSessionRevokeGraceIpHash: () => "b".repeat(64), getSessionRevokeGraceUaHash: () => "c".repeat(64), hashDestructiveActionGraceValue: (label, value) => `h(${label})${value}`, getDestructiveActionGraceScopeHash: (key) => (String(key || "").trim() ? "d".repeat(64) : ""), // The REAL strength vocabulary (adpanel:stepup-proof-strength): the mint // normalizes the threaded strength through it before persisting. normalizeStepUpProofStrength: require("../utils/step-up-proof-strength.js").normalizeStepUpProofStrength, destructiveActionGraceMemory: memory, db: { query: async (sql, params) => dbStub(queries, sql, params) }, }; const req = { sessionID: "sess-crash-test", session: { user: "admin@example.com" } }; sandbox.req = req; vm.createContext(sandbox); vm.runInContext(SET_FN, sandbox); return vm.runInContext( `setSessionRevokeGrace(req, { id: 7, email: "admin@example.com" }, "Test action", ${JSON.stringify(scopeKey)}, ${JSON.stringify(proofStrength)})`, sandbox ).then((result) => ({ result, queries, warns, memory, req })); } test("source: every degraded INSERT tier has its own try/catch and 0 returns before any state minting", () => { const stripped = stripComments(SET_FN); const returnZeroIdx = stripped.indexOf("if (!persisted) return 0;"); const memoryIdx = stripped.indexOf("destructiveActionGraceMemory.set("); const sessionIdx = stripped.indexOf("req.session.sessionRevoke2fa = {"); const returnExpiresIdx = stripped.indexOf("return expiresAt;"); assert.ok(returnZeroIdx >= 0, "the !persisted early return must exist"); assert.ok(memoryIdx > returnZeroIdx, "the memory grant must be minted only AFTER the !persisted early return"); assert.ok(sessionIdx > returnZeroIdx, "the session state must be minted only AFTER the !persisted early return"); // Three INSERT tiers (adpanel:stepup-proof-strength): full insert (scope + // strength) → scoped insert without strength → unscoped insert. Each // degraded tier is wrapped in its own try/catch inside the previous tier's // catch, and every tier's success sets the persisted flag. const strengthCatchIdx = stripped.indexOf("} catch (strengthColErr) {"); const scopedCatchIdx = stripped.indexOf("} catch (scopeColErr) {"); const fallbackTryIdx = stripped.indexOf("try {", scopedCatchIdx); const fallbackCatchIdx = stripped.indexOf("} catch (unscopedErr) {"); assert.ok(strengthCatchIdx > 0, "the strength INSERT catch must exist"); assert.ok(scopedCatchIdx > strengthCatchIdx, "the scoped INSERT catch must sit inside the strength catch"); assert.ok(fallbackTryIdx > scopedCatchIdx, "the unscoped fallback INSERT must sit inside its own try"); assert.ok(fallbackCatchIdx > fallbackTryIdx, "the unscoped fallback INSERT must have its own catch"); assert.match(stripped, /\[security\] Grace grant insert with proof strength failed, falling back:/, "a missing proof_strength column must degrade to the strength-less insert"); assert.match(stripped, /\[security\] Unscoped grace grant insert failed; continuing without a persisted grant:/, "total insert failure must warn that the grant is not persisted"); assert.equal(stripped.match(/persisted = true;/g)?.length, 3, "every INSERT tier's success must set persisted = true"); assert.ok(stripped.includes("proof_strength"), "the primary INSERT must carry the proof_strength column"); // Success path preserved: memory grant, session state, return expiresAt. assert.ok(memoryIdx > 0 && sessionIdx > 0 && returnExpiresIdx > sessionIdx, "the success path must still mint memory + session state and return expiresAt"); // The legacy scope-fallback rationale comment must survive. assert.match(stripped.includes("predates the scope_hash migration") ? stripped : SET_FN, /predates the scope_hash migration/, "the scope-fallback rationale comment must survive"); }); test("setSessionRevokeGrace: all INSERT tiers fail → returns 0, no memory grant, no session state (no phantom grant)", async () => { const out = await runSetSessionRevokeGrace((queries, sql) => { queries.push(sql); throw new Error("connection dead"); }); assert.equal(out.result, 0, "total insert failure must return 0 ('no grace window'), not reject"); assert.equal(out.memory.size, 0, "no memory grant may be minted without a persisted DB row"); assert.equal(out.req.session.sessionRevoke2fa, undefined, "no session state may be minted without a persisted DB row"); assert.equal(out.queries.length, 3, "all three INSERT tiers (strength, scoped, unscoped) must have been attempted"); // Tier order: scoped+strength → scoped → unscoped. assert.match(out.queries[0], /scope_hash/, "the first attempt must be the scoped INSERT"); assert.match(out.queries[0], /proof_strength/, "the first attempt must carry the strength column"); assert.ok(out.queries[1].includes("scope_hash") && !out.queries[1].includes("proof_strength"), "the second attempt must be the scoped, strength-less INSERT"); assert.ok(!out.queries[2].includes("scope_hash"), "the final attempt must be the unscoped INSERT"); assert.ok(out.warns.some((w) => w.includes("Grace grant insert with proof strength failed, falling back:")), "the strength-tier failure must warn before the legacy fallbacks"); assert.ok(out.warns.some((w) => w.includes("Scoped grace grant insert failed, falling back to unscoped:")), "the first failure must keep the legacy scope-fallback warn"); assert.ok(out.warns.some((w) => w.includes("Unscoped grace grant insert failed; continuing without a persisted grant:")), "the fallback failure must warn that no grant was persisted"); }); test("setSessionRevokeGrace: scoped INSERTs fail, unscoped fallback succeeds → grant minted, expiresAt returned (legacy path intact)", async () => { const out = await runSetSessionRevokeGrace((queries, sql, params) => { queries.push(sql); if (sql.includes("scope_hash")) throw new Error("ER_BAD_FIELD_ERROR: Unknown column 'scope_hash'"); return { affectedRows: 1, insertId: 1, params }; }); assert.ok(Number(out.result) > Date.now(), "a persisted grant must return the live expiresAt"); assert.equal(out.memory.size, 1, "the memory grant must be minted"); const memoryGrant = out.memory.values().next().value; // Pre-existing behavior (unchanged by this fix): the memory mirror carries // the requested scope hash even when the DB row was inserted unscoped — // consumption keys on the DB row's scope_hash and fails closed, so the // memory mirror is advisory only. assert.equal(memoryGrant.scopeHash, "d".repeat(64), "the memory grant mirrors the requested scope hash"); assert.equal(out.req.session.sessionRevoke2fa?.v, 2, "the session state must be minted (v2)"); assert.equal(out.req.session.sessionRevoke2fa?.expiresAt, out.result, "session and returned expiry must agree"); assert.equal(out.queries.length, 3); assert.ok(out.queries[2] && !out.queries[2].includes("scope_hash"), "the surviving insert is the unscoped tier"); assert.ok(out.warns.some((w) => w.includes("Scoped grace grant insert failed, falling back to unscoped:")), "the legacy scope-fallback warn must fire"); }); test("setSessionRevokeGrace: scoped INSERT succeeds → single insert, scoped memory grant, unchanged success path", async () => { const out = await runSetSessionRevokeGrace((queries, sql, params) => { queries.push(sql); return { affectedRows: 1, insertId: 1, params }; }); assert.ok(Number(out.result) > Date.now(), "the success path must still return the live expiresAt"); assert.equal(out.queries.length, 1, "a successful scoped INSERT must not trigger the fallback"); assert.match(out.queries[0], /proof_strength/, "the success INSERT carries the strength column"); assert.equal(out.memory.size, 1, "the memory grant must be minted"); assert.equal(out.memory.values().next().value.scopeHash, "d".repeat(64), "a scoped grant pre-binds the scope hash in memory"); assert.equal(out.req.session.sessionRevoke2fa?.v, 2, "the session state must be minted (v2)"); assert.equal(out.req.session.sessionRevoke2fa?.useCount, 0, "a fresh grant starts with useCount 0"); }); test("setSessionRevokeGrace: the threaded proof strength is normalized and recorded (adpanel:stepup-proof-strength)", async () => { // A recognized strength rides the INSERT params and the memory/session // mirrors. const captured = { params: null }; const strong = await runSetSessionRevokeGrace( (queries, sql, params) => { queries.push(sql); captured.params = params; return { affectedRows: 1, insertId: 1, params }; }, { proofStrength: "password+totp" } ); assert.equal(strong.memory.values().next().value.proofStrength, "password+totp", "the memory mirror records the strength"); assert.equal(strong.req.session.sessionRevoke2fa?.proofStrength, "password+totp", "the session state records the strength"); assert.equal(captured.params[captured.params.length - 1], "password+totp", "the INSERT persists the strength as the row's proof_strength"); // An unknown/legacy strength collapses to unknown — never recorded as a // strong value (conservative). const unknown = await runSetSessionRevokeGrace( (queries, sql, params) => { queries.push(sql); return { affectedRows: 1, insertId: 1, params }; }, { proofStrength: "garbage" } ); assert.equal(unknown.memory.values().next().value.proofStrength, "", "an unrecognized strength is stored as unknown"); }); // --------------------------------------------------------------------------- // Caller contract: 0 means "no grace window", never "unauthorized" // --------------------------------------------------------------------------- test("both step-up helpers treat a persisted-grace failure as ok:true with graceExpiresAt 0 (fail-closed-stricter)", () => { // requireDestructiveActionStepUp and requireDatabaseInstallStepUp are the // only two callers of persistDestructiveActionGrace; both must pass the // returned value straight through as ok:true — the just-verified action // proceeds WITHOUT a reusable grace window. requireDestructiveActionStepUp // has a brace-containing parameter default (options = {}), so the brace // counter cannot slice it — slice to the next top-level marker instead. const stepUpFn = stripComments(indexSource.slice( indexSource.indexOf("async function requireDestructiveActionStepUp"), indexSource.indexOf("async function requireDatabaseInstallStepUp") )); const dbInstallFn = stripComments(indexSource.slice( indexSource.indexOf("async function requireDatabaseInstallStepUp"), indexSource.indexOf("const SESSION_DISPLAY_MIN_TRUNCATABLE_LENGTH") )); // adpanel:stepup-proof-strength — both callers thread the verification's // achieved proof strength into the mint (the install helper keeps its // legacy either/or verification call and no credentialFlow option). assert.match(stepUpFn, /await persistDestructiveActionGrace\(req, currentUser, subject, scopeKey, verification\.proofStrength\)/); assert.match(stepUpFn, /ok: true,\s*graceExpiresAt,\s*graceUsesRemaining: persistGrant \? SESSION_REVOKE_2FA_GRACE_MAX_USES : 0,\s*usedFreshVerification: true,/, "requireDestructiveActionStepUp must return ok:true with the (possibly 0) expiry"); assert.match(dbInstallFn, /await persistDestructiveActionGrace\(req, currentUser, subject, "", verification\.proofStrength\)/); assert.match(dbInstallFn, /ok: true,\s*graceExpiresAt,/, "requireDatabaseInstallStepUp must return ok:true with the (possibly 0) expiry"); // Every consumer of stepUp.graceExpiresAt degrades a 0 through the // `|| (await getVerifiedSessionRevokeGraceState(...))?.expiresAt || 0` // pattern — a 0 return never changes the authorization outcome. const consumers = indexSource.match(/graceExpiresAt: stepUp\.graceExpiresAt \|\| \(await getVerifiedSessionRevokeGraceState\([^)]*\)\)\?\.expiresAt \|\| 0/g) || []; assert.ok(consumers.length >= 8, "all stepUp.graceExpiresAt consumers must fall through 0 to the DB-verified state (or 0)"); });