"use strict"; // adpanel:remember-rotation-bounded — source pins + behavior pins for the // bounded rotation CAS write. // // The remember-login rotation's Redis CAS (the REMEMBER_LOGIN_ROTATE_LUA EVAL // awaited inside rotateRememberLoginCookie) sits on the REQUEST PATH: both // silent-reissue chains (restoreRememberedLogin and the remember middleware's // ensureRememberLoginCookie refresh) await rotateRememberLoginCookie. node-redis // has no command timeout — while Redis is stalled it buffers commands instead // of erroring — so an unbounded await would wedge the request until Node's // request timeout. The fix bounds the EVAL await with // REMEMBER_ROTATION_WRITE_TIMEOUT_MS (own constant + own env knob next to the // revocation knob, same 1s/Math.max(100, ...) discipline) and — unlike the // revocation bound, which degrades to the false "unavailable" signal — the // labeled timeout rejection must PROPAGATE: no local catch converts it into the // "rotation refused" return 0, so it reaches the remember middleware's catch, // which clears the remember cookie + session state and continues // unauthenticated. commitRotation is never reached on a timeout, so a stalled // Redis can never complete a request with a half-rotated credential (fail // closed). // // Pins held here: // 1. Source: the constant + label exist (own name/env so the revocation knob // stays revocation-specific); the ONE EVAL await is wrapped with // withTimeout + the label inside rotateRememberLoginCookie — which covers // both commitRotation call sites (the file-store call site sits in the // no-redisClient branch where there is no Redis op to bound; the Redis-path // call site is strictly downstream of the bounded EVAL); no local catch // converts the labeled timeout; the Lua script itself is untouched. // 2. Behavior (vm-extracted rotateRememberLoginCookie, real-semantics // withTimeout): a never-settling eval rejects with the label within the // bound and commitRotation never runs; a late-landing eval (resolution or // rejection after the client gave up) drains without unhandledRejection // and without any local commit; success / drift / genuine-error / // file-store behavior is unchanged (no behavior change for valid inputs). // 3. The unguarded-awaited-route scanner still reports zero findings: the // bounded EVAL lives inside the rotateRememberLoginCookie helper, not in // any route body. 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 { execFileSync } = require("node:child_process"); const { getRememberLoginFingerprint } = require("../utils/remember-login-fingerprint"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); // Brace-balanced extraction (same shape as tests/remember-restore-and- // confirmed-bounds.test.js): skips // and /* */ comments so the adpanel: // comment convention cannot desync the brace tracker. function extractBlock(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker not found: ${startMarker}`); let i = start + startMarker.length; let depth; if (startMarker.endsWith("{")) { depth = 1; } else { while (i < source.length && /\s/.test(source[i])) i += 1; assert.ok(i < source.length && source[i] === "{", `no opening brace after: ${startMarker}`); depth = 1; } let inString = null; while (i < source.length && depth > 0) { i += 1; const ch = source[i]; if (inString) { if (ch === "\\") { i += 1; continue; } if (ch === inString) inString = null; continue; } if (ch === "/" && source[i + 1] === "/") { while (i < source.length && source[i] !== "\n") i += 1; continue; } if (ch === "/" && source[i + 1] === "*") { i += 2; while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i += 1; i += 1; continue; } if (ch === '"' || ch === "'" || ch === "`") inString = ch; else if (ch === "{") depth += 1; else if (ch === "}") depth -= 1; } assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`); return source.slice(start, i + 1); } const ROTATE_SOURCE = extractBlock(indexSource, "async function rotateRememberLoginCookie(req, res, user, parsedToken) {"); // Conscious extraction fix (adpanel:remember-logout-lineage): the slice now // searches from the rotation Lua's own start. The old file-wide indexOf found // the guarded-write Lua's terminator first (it sits earlier in index.js) and // silently produced an EMPTY slice, which made the "script untouched" // assertion below vacuous. The assertion now actually inspects the script — // which legitimately CHANGED to propagate the rotation lineage atomically // (CAS semantics preserved: uid match, HDEL old, version INCR, never both // live); what must stay untouched is the bound's placement (no withTimeout / // rotation-timeout identifiers inside the script — the bound wraps the // client await, not the script). const LUA_START = indexSource.indexOf("const REMEMBER_LOGIN_ROTATE_LUA = ["); const LUA_JOIN_END = '].join("\\n");'; const LUA_SOURCE = indexSource.slice( LUA_START, indexSource.indexOf(LUA_JOIN_END, LUA_START) + LUA_JOIN_END.length ); // --------------------------------------------------------------------------- // Source pins — the bound, its own knob, and the propagating timeout // --------------------------------------------------------------------------- test("the rotation bound is a named constant with its own env knob next to the revoke constants", () => { assert.match( indexSource, /const REMEMBER_ROTATION_WRITE_TIMEOUT_MS = Math\.max\(\s*\n\s*100,\s*\n\s*parseInt\(process\.env\.REDIS_REMEMBER_ROTATION_WRITE_TIMEOUT_MS \|\| "1000", 10\) \|\| 1000\s*\n\);/, "the rotation CAS write must carry the same 1s/Math.max(100, ...) discipline as the other remember writes" ); assert.match( indexSource, /const REMEMBER_ROTATION_WRITE_TIMEOUT_LABEL = "remember-rotation-write-timeout";/, "the bound must have its own label (a timeout must be identifiable as the rotation-write stall)" ); // Own name/env, NOT a reuse of the revocation knob: the two writes have // different callers and different failure postures (revoke degrades to false; // rotation's timeout propagates), so tuning one must never retune the other. assert.match( indexSource, /process\.env\.REDIS_REMEMBER_REVOKE_WRITE_TIMEOUT_MS \|\| "1000"/, "the revocation knob must remain untouched and revocation-specific" ); const revokeLabelIdx = indexSource.indexOf('const REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL = "remember-revoke-write-timeout";'); const rotationConstIdx = indexSource.indexOf("const REMEMBER_ROTATION_WRITE_TIMEOUT_MS = Math.max("); assert.ok(revokeLabelIdx >= 0 && rotationConstIdx > revokeLabelIdx, "the rotation constants must sit next to the existing remember constants"); const envNames = [...indexSource.matchAll(/process\.env\.(REDIS_REMEMBER_[A-Z_]+_MS)\b/g)].map((m) => m[1]); assert.ok(envNames.includes("REDIS_REMEMBER_REVOKE_WRITE_TIMEOUT_MS") && envNames.includes("REDIS_REMEMBER_ROTATION_WRITE_TIMEOUT_MS"), "the revoke and rotation knobs must stay distinct env names"); }); test("the ONE rotation EVAL await is wrapped with withTimeout + the label inside rotateRememberLoginCookie", () => { assert.match( ROTATE_SOURCE, /const reply = await withTimeout\(\s*\n\s*redisClient\.sendCommand\(\[\s*\n\s*"EVAL",\s*\n\s*REMEMBER_LOGIN_ROTATE_LUA,/, "the CAS EVAL must be bounded — an unbounded await wedges the request for as long as the Redis stall lasts" ); // Conscious regex update (adpanel:remember-logout-lineage): the CAS args // gained KEYS[3] (the per-lineage set key) and ARGV[5] (the set TTL) so the // lineage propagation and the set maintenance ride the SAME atomic script; // the presented id / uid / fresh id / entry JSON args are unchanged, and the // wrap must still be the rotation constant + label. assert.match( ROTATE_SOURCE, /REMEMBER_LOGIN_REGISTRY_VERSION_REDIS_KEY,\s*\n\s*REMEMBER_LOGIN_REGISTRY_REDIS_KEY,\s*\n\s*REMEMBER_LOGIN_LINEAGE_SET_REDIS_PREFIX \+ entry\.lineage,\s*\n\s*oldId,\s*\n\s*String\(user\.id\),\s*\n\s*rememberId,\s*\n\s*JSON\.stringify\(entry\),\s*\n\s*String\(REMEMBER_LOGIN_LINEAGE_SET_TTL_SECONDS\),\s*\n\s*\]\),\s*\n\s*REMEMBER_ROTATION_WRITE_TIMEOUT_MS,\s*\n\s*REMEMBER_ROTATION_WRITE_TIMEOUT_LABEL\s*\n\s*\);/, "the wrap must use the rotation constant + label (the CAS args carry the lineage set key + set TTL — the lineage propagation is atomic with the CAS)" ); assert.doesNotMatch( ROTATE_SOURCE, /await redisClient\.sendCommand\(/, "no unbounded sendCommand await may remain in the rotation path" ); assert.strictEqual( (ROTATE_SOURCE.match(/await withTimeout\(/g) || []).length, 1, "exactly ONE wrap — the single EVAL await site covers every commitRotation call site, no per-call-site wrapping" ); assert.ok( !LUA_SOURCE.includes("withTimeout") && !LUA_SOURCE.includes("REMEMBER_ROTATION"), "the rotation Lua script itself must stay untouched (the bound wraps the client await, not the script)" ); }); test("both commitRotation call sites are covered by the one wrap", () => { const boundedEvalIdx = ROTATE_SOURCE.indexOf("REMEMBER_ROTATION_WRITE_TIMEOUT_MS"); assert.ok(boundedEvalIdx >= 0, "the bounded EVAL must exist in the rotation body"); const fileStoreBranchIdx = ROTATE_SOURCE.indexOf("if (!redisClient) {"); assert.ok(fileStoreBranchIdx >= 0 && fileStoreBranchIdx < boundedEvalIdx, "the file-store branch must precede the Redis CAS (no Redis op to bound there)"); const fileStoreCommitIdx = ROTATE_SOURCE.indexOf("commitRotation();", fileStoreBranchIdx); assert.ok(fileStoreCommitIdx >= 0 && fileStoreCommitIdx < boundedEvalIdx, "call site 1 (file-store): reached without any Redis command — its synchronous memory CAS needs no bound"); const redisCommitIdx = ROTATE_SOURCE.indexOf("commitRotation();", boundedEvalIdx); assert.ok(redisCommitIdx > boundedEvalIdx, "call site 2 (Redis path): strictly downstream of the bounded EVAL — the timeout rejection can never reach it, so no partial commit"); assert.strictEqual( (ROTATE_SOURCE.match(/commitRotation\(\);/g) || []).length, 2, "exactly the two known commitRotation call sites" ); }); test("no local catch converts the labeled timeout: it propagates to the remember middleware's catch", () => { const catchIdx = ROTATE_SOURCE.indexOf("} catch (err) {"); assert.ok(catchIdx >= 0, "the rotation must keep its Redis-error catch"); const catchBody = ROTATE_SOURCE.slice(catchIdx); const rethrowIdx = catchBody.indexOf("if (err?.message === REMEMBER_ROTATION_WRITE_TIMEOUT_LABEL) throw err;"); assert.ok(rethrowIdx >= 0, "the labeled timeout must be rethrown, never catch-converted into the refused-rotation return 0"); const warnIdx = catchBody.indexOf('console.warn("[auth] Remember-login rotation failed in Redis'); const returnZeroIdx = catchBody.indexOf("return 0;"); assert.ok(warnIdx > rethrowIdx && returnZeroIdx > warnIdx, "non-timeout Redis errors keep the established refused-rotation contract AFTER the timeout rethrow"); // Both await chains end in the ONE remember middleware catch, which fails // closed (clears cookie + state, continues unauthenticated). Window anchored // on the restore call site like tests/remember-restore-and-confirmed-bounds. const restoreCallIdx = indexSource.indexOf("await restoreRememberedLogin(req, res);"); assert.ok(restoreCallIdx >= 0, "the restore call site must exist"); const middlewareStart = indexSource.lastIndexOf("app.use(async (req, res, next) => {", restoreCallIdx); assert.ok(middlewareStart >= 0 && middlewareStart < restoreCallIdx, "the call sites sit inside a middleware"); // Window sized for the delegated catch (adpanel:restore-failure- // deauthorization): the hygiene moved into the ONE // teardownFailedRememberRestore helper, and the catch now warns + delegates // + continues, so the old +7000 window shrunk accordingly. const middlewareWindow = indexSource.slice(middlewareStart, restoreCallIdx + 1200); const tryIdx = middlewareWindow.indexOf("try {"); const ensureCallIdx = middlewareWindow.indexOf("await ensureRememberLoginCookie(req, res);"); const restoreIdx = middlewareWindow.indexOf("await restoreRememberedLogin(req, res);"); assert.ok(tryIdx >= 0 && tryIdx < ensureCallIdx && tryIdx < restoreIdx, "both silent-reissue call sites must sit inside the same middleware try"); const catchInMiddleware = middlewareWindow.indexOf("} catch (err) {", restoreIdx); assert.ok(catchInMiddleware > restoreIdx, "the try must have a catch after the call sites"); const mwCatchBody = middlewareWindow.slice(catchInMiddleware); // Conscious pin update (adpanel:restore-failure-deauthorization): the catch // no longer holds the hygiene inline — it DELEGATES to the ONE teardown // helper, which owns the state/cookie clears (pinned below); the fail-closed // posture (return next(), unauthenticated) is unchanged. assert.ok(mwCatchBody.includes("await teardownFailedRememberRestore(req, res);") && mwCatchBody.includes("return next();"), "the middleware catch must delegate the fail-closed teardown to the ONE helper and continue unauthenticated"); const teardownBody = extractBlock(indexSource, "async function teardownFailedRememberRestore(req, res) {"); assert.ok(teardownBody.indexOf("clearRememberLoginSessionState(req);") >= 0 && teardownBody.indexOf("clearRememberLoginCookie(req, res);") > teardownBody.indexOf("clearRememberLoginSessionState(req);"), "the ONE teardown helper clears the remember state + cookie (fail closed, same ordering as before)"); }); // --------------------------------------------------------------------------- // Behavior pins — vm-extracted rotateRememberLoginCookie, real-semantics bound // --------------------------------------------------------------------------- // Real race semantics (verbatim discipline from // tests/remember-revoke-durable.test.js): a passthrough would make every stall // pin below prove nothing. function sandboxWithTimeout(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)); } // Anchor and presented token are derived from the REAL clock: the extracted // rotate captures its own `now = Date.now()` inside the vm, so a fixed past // anchor would (correctly) refuse the re-issue before the CAS ever runs. const HARNESS_NOW = Date.now(); const ANCHOR = HARNESS_NOW + 200 * 24 * 60 * 60 * 1000; // 200d remaining anchor const OLD_ID = "remember-id-rotate-old"; const USER = { id: 1, email: "user@example.test", password: "x" }; const PARSED = { v: 2, uid: "1", iat: HARNESS_NOW - 60000, exp: ANCHOR, fp: getRememberLoginFingerprint(USER), jti: OLD_ID }; function buildRotateHarness({ sendCommandImpl, redisClient, timeoutMs = 40 }) { const registry = { [OLD_ID]: { uid: "1", email: "user@example.test", issuedAt: HARNESS_NOW - 60000, expiresAt: ANCHOR, absoluteExpiresAt: ANCHOR }, }; const cookies = []; const warnings = []; const req = { sessionID: "sess-1", session: { rememberLoginId: OLD_ID, browserSessionAudit: { rememberLoginId: OLD_ID } }, get: () => "test-agent", }; const res = { cookie: (name, value, options) => cookies.push([name, value, options]), clearCookie: () => {}, }; const sandbox = { console: { log: () => {}, warn: (...a) => warnings.push(a.map(String).join(" ")) }, crypto: require("node:crypto"), getRememberLoginFingerprint, safeCompare: (left, right) => left === right, REMEMBER_LOGIN_MAX_AGE_MS: 365 * 24 * 60 * 60 * 1000, REMEMBER_LOGIN_COOKIE_NAME: "adpanel.remember", REMEMBER_LOGIN_ROTATE_LUA: "-- lua under test --", REMEMBER_LOGIN_REGISTRY_VERSION_REDIS_KEY: "adpanel:remember-logins-version", REMEMBER_LOGIN_REGISTRY_REDIS_KEY: "adpanel:remember-logins", // Conscious addition (adpanel:remember-logout-lineage): the CAS args // reference the lineage-set constants; the real script logic is pinned in // tests/remember-logout-lineage.test.js, here they only need to resolve. REMEMBER_LOGIN_LINEAGE_SET_REDIS_PREFIX: "adpanel:remember-lineage:", REMEMBER_LOGIN_LINEAGE_SET_TTL_SECONDS: 31622400, isValidRememberLoginId: (id) => !!String(id || "").trim() && String(id).length <= 128 && /^[A-Za-z0-9_-]+$/.test(String(id)), resolveRememberLoginAnchorMs: (oldEntry) => { const anchored = Number(oldEntry?.absoluteExpiresAt || oldEntry?.expiresAt || 0); return Number.isFinite(anchored) && anchored > 0 ? anchored : 0; }, getRequestIp: () => "203.0.113.9", normalizeBrowserSessionAudit: (existing, seed) => ({ createdAt: seed.createdAt, lastSeenAt: seed.lastSeenAt, userAgent: seed.userAgent, firstIp: seed.firstIp, lastIp: seed.lastIp, rememberLoginId: seed.rememberLoginId, }), buildRememberLoginToken: (u, rememberId, issuedAt, expiresAt) => `tok.${rememberId}.${issuedAt}.${expiresAt}`, getRememberLoginCookieOptions: () => ({ httpOnly: true, path: "/" }), rememberLoginRegistry: registry, rememberLoginRegistryFreshCheckedAt: 12345, redisClient: redisClient === undefined ? { isOpen: true, sendCommand: sendCommandImpl } : redisClient, withTimeout: sandboxWithTimeout, REMEMBER_ROTATION_WRITE_TIMEOUT_MS: timeoutMs, REMEMBER_ROTATION_WRITE_TIMEOUT_LABEL: "remember-rotation-write-timeout", req, res, cookies, warnings, }; vm.createContext(sandbox); const fn = vm.runInContext(`(${ROTATE_SOURCE})`, sandbox, { filename: "rotate-sandbox.js" }); return { fn, registry, cookies, warnings, req, res, sandbox }; } function assertNoCommit(registry, cookies, req, freshCheckedAt) { assert.strictEqual(Object.keys(registry).length, 1, "no new registry entry may appear on a failed rotation"); assert.ok(OLD_ID in registry, "the presented entry must stay untouched on a failed rotation"); assert.strictEqual(cookies.length, 0, "no re-issued cookie may be set on a failed rotation"); assert.strictEqual(req.session.rememberLoginId, OLD_ID, "the session must stay bound to the presented id on a failed rotation"); assert.notStrictEqual(freshCheckedAt(), 0, "the registry freshness mark must not be reset on a failed rotation"); } test("rotation refuses to refresh a stale saved-login proof before changing store, session or cookies", async () => { for (const redisClient of [null, { sendCommand: async () => assert.fail("stale proof reached Redis") }]) { for (const user of [ { ...USER, password: "changed-hash" }, { ...USER, session_epoch: 2 }, { ...USER, suspended: true }, { ...USER, totpSealedError: true }, ]) { const { fn, registry, cookies, req, res, sandbox } = buildRotateHarness({ redisClient }); assert.strictEqual(await fn(req, res, user, PARSED), 0); assertNoCommit(registry, cookies, req, () => sandbox.rememberLoginRegistryFreshCheckedAt); } } }); test("a never-settling rotation EVAL rejects with the label within the bound and never commits", async () => { const { fn, registry, cookies, req, sandbox } = buildRotateHarness({ // Stalled Redis: node-redis buffers the command instead of erroring — // exactly the stall this bound exists for. sendCommandImpl: () => new Promise(() => {}), }); const started = Date.now(); await assert.rejects( fn(req, {}, USER, PARSED), { message: "remember-rotation-write-timeout" }, "the bounded CAS must reject with its own label — a local catch-convert into return 0 would fail this pin" ); const elapsed = Date.now() - started; assert.ok(elapsed >= 35, `the bound must actually arm (elapsed ${elapsed}ms)`); assert.ok(elapsed < 2000, `the rejection must arrive within the bound (elapsed ${elapsed}ms) — the request must not wedge`); assertNoCommit(registry, cookies, req, () => sandbox.rememberLoginRegistryFreshCheckedAt); }); test("a late-landing rotation EVAL drains after the timeout without unhandledRejection and without any commit", async () => { let sendCalls = 0; const { fn, registry, cookies, req, sandbox } = buildRotateHarness({ timeoutMs: 40, sendCommandImpl: () => { sendCalls += 1; // The CAS lands on Redis AFTER the client already gave up: the atomic // script still completes server-side (HSET new + HDEL old + INCR), but // the local commit must never run and the late settlement must drain // silently (Promise.race attached its handlers at the timeout). return new Promise((resolve) => setTimeout(() => resolve(["1"]), 160)); }, }); const unhandled = []; const onUnhandled = (err) => unhandled.push(err); process.on("unhandledRejection", onUnhandled); try { await assert.rejects(fn(req, {}, USER, PARSED), { message: "remember-rotation-write-timeout" }); // Let the late settlement (and any hypothetical unhandled rejection) // surface. await new Promise((resolve) => setTimeout(resolve, 320)); } finally { process.off("unhandledRejection", onUnhandled); } assert.strictEqual(unhandled.length, 0, "the late-landing eval must drain without unhandledRejection"); assert.strictEqual(sendCalls, 1, "exactly one CAS attempt"); assertNoCommit(registry, cookies, req, () => sandbox.rememberLoginRegistryFreshCheckedAt); // The late REJECTION variant drains the same way. const h2 = buildRotateHarness({ timeoutMs: 40, sendCommandImpl: () => new Promise((_, reject) => setTimeout(() => reject(new Error("late ECONNRESET")), 160)), }); const unhandled2 = []; const onUnhandled2 = (err) => unhandled2.push(err); process.on("unhandledRejection", onUnhandled2); try { await assert.rejects(h2.fn(h2.req, {}, USER, PARSED), { message: "remember-rotation-write-timeout" }); await new Promise((resolve) => setTimeout(resolve, 320)); } finally { process.off("unhandledRejection", onUnhandled2); } assert.strictEqual(unhandled2.length, 0, "a late-rejecting eval must drain without unhandledRejection too"); }); test("success, drift, genuine Redis errors and file-store mode keep their established contracts", async () => { // Success: CAS wins → commitRotation runs → anchored expiry returned, no // behavior change for valid inputs. const ok = buildRotateHarness({ sendCommandImpl: async () => ["1"] }); const expiresAt = await ok.fn(ok.req, ok.res, USER, PARSED); assert.strictEqual(expiresAt, ANCHOR, "the anchored expiry (capped at the ORIGINAL anchor, 200d out) must still be returned on success"); assert.ok(OLD_ID in ok.registry === false, "the old entry must be deleted from the local snapshot"); const newIds = Object.keys(ok.registry).filter((id) => id !== OLD_ID); assert.strictEqual(newIds.length, 1, "exactly one fresh identifier registered"); const newEntry = ok.registry[newIds[0]]; assert.strictEqual(newEntry.uid, "1", "the rotated entry must keep the owner binding"); assert.strictEqual(newEntry.absoluteExpiresAt, ANCHOR, "the rotated entry must inherit the original anchor"); // Conscious addition (adpanel:remember-logout-lineage): a rotation of a // lineage-less (legacy) entry STARTS the chain at the presented id, and the // session's lineage stamp follows the fresh identifier's chain. assert.strictEqual(newEntry.lineage, OLD_ID, "a legacy entry's rotation starts the lineage at the presented id"); assert.strictEqual(ok.req.session.rememberLoginLineage, OLD_ID, "commitRotation stamps the session with the chain lineage"); assert.notStrictEqual(ok.req.session.rememberLoginId, OLD_ID, "the session must be re-bound to the fresh identifier"); assert.strictEqual(ok.req.session.browserSessionAudit.rememberLoginId, ok.req.session.rememberLoginId, "the audit copy must mirror the fresh identifier"); assert.strictEqual(ok.cookies.length, 1, "the re-issued cookie must be set"); assert.match(String(ok.cookies[0][1]), /^tok\./, "the re-issued cookie carries the rebuilt token"); assert.strictEqual(ok.sandbox.rememberLoginRegistryFreshCheckedAt, 0, "a successful rotation must force a registry version re-check (the version bump was ours)"); assert.strictEqual(ok.warnings.length, 0, "success must not warn"); // Drift (CAS lost): refused rotation, no commit. const drifted = buildRotateHarness({ sendCommandImpl: async () => ["-1"] }); assert.strictEqual(await drifted.fn(drifted.req, drifted.res, USER, PARSED), 0, "a lost CAS must fail closed with 0"); assertNoCommit(drifted.registry, drifted.cookies, drifted.req, () => drifted.sandbox.rememberLoginRegistryFreshCheckedAt); assert.ok(drifted.warnings.some((w) => w.includes("rotation drifted")), "drift keeps its loud warn"); // Genuine (non-timeout) Redis error: refused rotation, no commit — the // catch still converts NON-timeout errors (established contract). const errored = buildRotateHarness({ sendCommandImpl: () => Promise.reject(new Error("ECONNRESET")) }); assert.strictEqual(await errored.fn(errored.req, errored.res, USER, PARSED), 0, "a genuine Redis error keeps the refused-rotation signal"); assertNoCommit(errored.registry, errored.cookies, errored.req, () => errored.sandbox.rememberLoginRegistryFreshCheckedAt); assert.ok(errored.warnings.some((w) => w.includes("ECONNRESET")), "the Redis error's message surfaces in the warn"); // File-store mode: no Redis client — the synchronous memory check IS the // CAS; commitRotation runs without any bounded await. const fileOk = buildRotateHarness({ redisClient: null, sendCommandImpl: () => { throw new Error("no Redis call in file-store mode"); } }); const fileExpiresAt = await fileOk.fn(fileOk.req, fileOk.res, USER, PARSED); assert.strictEqual(fileExpiresAt, ANCHOR, "file-store success returns the same anchored expiry"); assert.notStrictEqual(fileOk.req.session.rememberLoginId, OLD_ID, "file-store success commits the rotation locally"); assert.strictEqual(fileOk.cookies.length, 1, "file-store success re-issues the cookie"); const fileDrift = buildRotateHarness({ redisClient: null }); fileDrift.registry[OLD_ID] = { ...fileDrift.registry[OLD_ID], uid: "999" }; assert.strictEqual(await fileDrift.fn(fileDrift.req, fileDrift.res, USER, PARSED), 0, "file-store drift fails closed"); assertNoCommit(fileDrift.registry, fileDrift.cookies, fileDrift.req, () => fileDrift.sandbox.rememberLoginRegistryFreshCheckedAt); }); // The bounded EVAL lives inside the rotateRememberLoginCookie HELPER, not in a // route body — the preflight scanner (which walks only app.get/post/use // windows) must keep reporting zero findings. test("the unguarded-awaited-route scanner stays at zero findings", () => { const stdout = execFileSync( process.execPath, ["scripts/find-unguarded-awaited-routes.js", "index.js", "nodes.js"], { cwd: ROOT, encoding: "utf8" } ); assert.strictEqual(stdout.trim(), "", `the scanner must report zero unguarded awaits; got:\n${stdout}`); });