"use strict"; // adpanel:remember-fresh-reissue — source pins + behavior pins for the fresh // identifier rule on interactive remember-cookie re-issues. // // The four interactive re-issue sites (2FA change, both password changes, // email change) run AFTER an awaited user-wide remember revocation // (destroyBrowserSessionsForUser -> revokeRememberLoginsForUser), so the // session's still-set rememberLoginId is a just-revoked identifier. Reusing it // re-classified that id as a FRESH 365-day mint: the absolute-expiry anchor // reset to now, the fingerprint excludes email (fp = sha256(password + "\n" + // secret)), the token payload carries no email beyond the entry-vs-row check // (both sides updated by the re-mint), and no iat-vs-entry binding exists — // so every stolen copy of the previous token value was resurrected with a new // lease. The fix adds an opt-in { forceFreshId: true } to setRememberLoginCookie: // the stale session id is deleted BEFORE the issue (so // ensureRememberLoginSessionId mints a NEW id into the session) and the // session's audit copy is re-synced AFTER a successful issue (mirroring // commitRotation's sync on the rotation path). The login binder omits the // flag: its session was just regenerated, the id is genuinely fresh, and // tests/login-session-bind-module.test.js pins that id-reuse semantics. // // Pins held here: // 1. All four re-issue sites run the ONE shared rebinder // (adpanel:credential-session-rebind), whose re-issue call passes // { forceFreshId: true }; no direct route re-issue remains in index.js; // the login binder passes no flag. // 2. The rebinder's flagged mint follows its awaited user-wide // destroyBrowserSessionsForUser in the same function, and that function // revokes remember logins user-wide (revokeRememberLoginsForUser). // 3. The flag implementation clears the session field before the issue and // syncs the audit copy after a successful issue, under the // adpanel:remember-fresh-reissue comment. // 4. Behavior (vm-extracted): flag present -> old id gone before the issue // runs, new id present on the session after, audit copy synced, cookie // set; flag absent -> the pre-fix behavior is byte-identical (existing id // reused, audit copy untouched), so the binder path is unchanged. 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 BINDER_JS = path.join(ROOT, "utils", "login-session-bind.js"); const REBINDER_JS = path.join(ROOT, "utils", "credential-session-rebind.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const binderSource = fs.readFileSync(BINDER_JS, "utf8"); const rebinderSource = fs.readFileSync(REBINDER_JS, "utf8"); function countOccurrences(haystack, needle) { return haystack.split(needle).length - 1; } function sliceBetween(source, startMarker, endMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `start marker not found: ${startMarker}`); const end = source.indexOf(endMarker, start + startMarker.length); assert.ok(end > start, `end marker not found after start: ${endMarker}`); return source.slice(start, end); } // Brace-balanced extraction (same shape as the extractBlock helper in // botproof-timing-safe.test.js): skips // and /* */ comments so the adpanel: // comment convention cannot desync the string/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); } // --------------------------------------------------------------------------- // Source pins — the four interactive re-issue sites // --------------------------------------------------------------------------- // Conscious pin update (adpanel:credential-session-rebind): the four // interactive re-issues no longer call setRememberLoginCookie directly in // index.js — they delegate to the ONE shared rebinder // (utils/credential-session-rebind.js), which runs the user-wide destroy // (NO self-exclusion) and then mints with { forceFreshId: true } on their // behalf. The invariant this test protects is unchanged — every interactive // re-issue after a user-wide remember revoke mints a FRESH identifier — so // the pins below moved to the delegation shape: the four routes must run the // shared rebinder, index.js must keep no direct re-issue of its own, and the // rebinder module must carry the flagged mint (and no flagless one). test("all four interactive re-issue sites run the shared rebinder, which mints with forceFreshId; no direct route re-issue remains", () => { // The four credential-change surfaces delegate to the ONE rebinder. assert.equal( countOccurrences(indexSource, "credentialSessionRebinder.rebindOwnerSession(req, res"), 4, "all four interactive re-issue routes must run the shared rebind" ); // No direct re-issue call survives in index.js: the only occurrence of the // identifier-with-call-paren is the function definition (the rebinder dep // binding passes the bare identifier, and the login binder dep binding the // same — neither is a call). assert.equal( countOccurrences(indexSource, "setRememberLoginCookie("), 1, "index.js must contain exactly the definition — every call moved behind the shared mints" ); assert.equal( countOccurrences(indexSource, 'setRememberLoginCookie(req, res, { ...user'), 0, "no route may re-issue the remember cookie directly anymore" ); // The rebinder module carries exactly ONE re-issue call and it is flagged; // no flagless re-issue exists anywhere in the module. assert.equal( countOccurrences(rebinderSource, "setRememberLoginCookie(req, res, user, { forceFreshId: true });"), 1, "the rebinder's re-issue must pass { forceFreshId: true }" ); assert.equal( countOccurrences(rebinderSource, "setRememberLoginCookie("), 1, "the flagged mint is the rebinder's only re-issue call" ); }); // Conscious pin update (adpanel:credential-session-rebind): the destroy and // the re-issue now live in the same shared function instead of the same route // handler, so the ordering pin moved into the rebinder module — the awaited // user-wide destroy MUST still precede the flagged mint inside // rebindOwnerSession, and destroyBrowserSessionsForUser must still revoke // remember logins user-wide (which is exactly why the re-issue must mint a // fresh identifier instead of reusing the revoked one). test("the shared rebind runs the user-wide revocation before its flagged re-issue, in the same function", () => { const destroyIdx = rebinderSource.indexOf("await destroyBrowserSessionsForUser(destroyAs || user)"); const mintIdx = rebinderSource.indexOf("setRememberLoginCookie(req, res, user, { forceFreshId: true });"); assert.ok(destroyIdx >= 0, "the rebinder must run the user-wide destroy itself"); assert.ok(mintIdx >= 0, "the flagged mint must exist in the rebinder"); assert.ok(destroyIdx < mintIdx, "the re-issue must follow the awaited user-wide revocation in the same function"); // Same-function proof: no function boundary between the destroy and the // mint inside the module. const between = rebinderSource.slice(destroyIdx, mintIdx); assert.ok(!between.includes("function rebindOwnerSession") && !between.includes("module.exports"), "the revoke and the re-issue must belong to the same rebinder function"); // destroyBrowserSessionsForUser (index.js) revokes remember logins // USER-WIDE — the fact that makes the fresh-id rule load-bearing. // Conscious pin update (adpanel:session-inventory-error-propagation): the // user-wide revoke moved from the result literal into the first AWAITED // statement so its Redis failures thread into result.errors via the // optional onError sink — still unconditional and still first (the literal // now only declares the shape). const destroyFn = extractBlock(indexSource, "async function destroyBrowserSessionsForUser(user, options = {}) {"); assert.ok( destroyFn.includes("result.rememberLoginsRevoked = await revokeRememberLoginsForUser(user, {"), "destroyBrowserSessionsForUser must revoke remember logins user-wide" ); }); test("the login binder passes NO flag (its id is genuinely fresh and its reuse is pinned)", () => { assert.equal( countOccurrences(binderSource, "forceFreshId"), 0, "utils/login-session-bind.js must not know about the flag" ); // Conscious pin update (adpanel:login-bind-save-failure-hygiene): the mint // and the freshness mark are two statements now — the binder captures the // issue's expiry so a post-mint failure can revoke the just-minted // credential. Assertion strength preserved: the call must stay EXACTLY // (req, res, user) — no options object, therefore no flag — and the mark // must consume that same issue's expiry. assert.ok( binderSource.includes("const rememberExpiresAt = setRememberLoginCookie(req, res, user);"), "the binder must call setRememberLoginCookie with exactly (req, res, user) — no options, no flag" ); assert.ok( binderSource.includes("markRememberLoginSessionFresh(req, rememberExpiresAt);"), "the freshness mark must consume the captured issue expiry (same pair, split only to capture it)" ); // The binder pre-mints the id via ensureRememberLoginSessionId BEFORE the // issue and builds the audit from it — with no flag, setRememberLoginCookie // must reuse exactly that id (semantics pinned by // tests/login-session-bind-module.test.js). assert.ok( binderSource.includes("const rememberLoginId = ensureRememberLoginSessionId(req);"), "the binder must pre-mint the remember id before issuing" ); }); // --------------------------------------------------------------------------- // Source pins — the flag implementation // --------------------------------------------------------------------------- test("the flag clears the session id before the issue and syncs the audit after it", () => { assert.ok( indexSource.includes("// adpanel:remember-fresh-reissue —"), "the fix must carry its adpanel: comment" ); const fnSource = extractBlock(indexSource, "function setRememberLoginCookie(req, res, user, options = {}) {"); const deleteIdx = fnSource.indexOf("delete req.session.rememberLoginId;"); const issueIdx = fnSource.indexOf("issueRememberLoginToken(req, user, now)"); const tokenGuardIdx = fnSource.indexOf("if (!token) return;"); const auditSyncIdx = fnSource.indexOf("req.session.browserSessionAudit.rememberLoginId = req.session.rememberLoginId;"); const cookieIdx = fnSource.indexOf("res.cookie(REMEMBER_LOGIN_COOKIE_NAME, token, getRememberLoginCookieOptions(req));"); assert.ok(deleteIdx >= 0, "the flag must delete the session's rememberLoginId"); assert.ok(issueIdx >= 0 && tokenGuardIdx >= 0 && auditSyncIdx >= 0 && cookieIdx >= 0, "issue/guard/audit-sync/cookie steps must all be present"); assert.ok(deleteIdx < issueIdx, "the stale id must be cleared BEFORE the issue (so a new id is minted)"); assert.ok(auditSyncIdx > tokenGuardIdx, "the audit sync must run only after a successful issue"); assert.ok(auditSyncIdx < cookieIdx, "the audit sync mirrors commitRotation's ordering (session state, then cookie)"); // The audit sync is guarded exactly like commitRotation's (no audit object -> no crash). assert.ok( fnSource.includes('if (req.session.browserSessionAudit && typeof req.session.browserSessionAudit === "object") {'), "the audit sync must guard on the audit object's presence and type" ); // The flag is opt-in: the issue itself and the cookie options path are // unchanged, so the no-flag path stays byte-identical. assert.ok( fnSource.includes("const token = issueRememberLoginToken(req, user, now);") && fnSource.includes("return now + REMEMBER_LOGIN_MAX_AGE_MS;"), "the issue and return-value contract must be unchanged" ); // The surrounding machinery was not touched: signatures the other tests // slice stay exactly as they were. assert.ok( indexSource.includes("function issueRememberLoginToken(req, user, now = Date.now()) {"), "issueRememberLoginToken's signature is unchanged (options live on setRememberLoginCookie only)" ); assert.ok( indexSource.includes("function upsertRememberLoginRegistryEntry(req, user, expiresAt, issuedAt = Date.now()) {"), "upsertRememberLoginRegistryEntry's signature is unchanged (sliced by tests/remember-rotation-action-token.test.js)" ); assert.ok( indexSource.includes("function ensureRememberLoginSessionId(req) {"), "ensureRememberLoginSessionId is unchanged" ); }); // --------------------------------------------------------------------------- // Behavior pins — vm-extracted setRememberLoginCookie // --------------------------------------------------------------------------- // Build the vm harness. The issueRememberLoginToken stub models the ONLY // session-visible behavior of the real chain (issueRememberLoginToken -> // upsertRememberLoginRegistryEntry -> ensureRememberLoginSessionId): the id // comes from the session's current rememberLoginId, or a NEW one is minted and // written back into the session. It also records the id visible AT ISSUE TIME, // which is the load-bearing ordering observation (old id must already be gone). function buildHarness() { const fnSource = extractBlock(indexSource, "function setRememberLoginCookie(req, res, user, options = {}) {"); const events = []; let mintCounter = 0; const sandbox = { REMEMBER_LOGIN_COOKIE_NAME: "adpanel_remember_test", REMEMBER_LOGIN_MAX_AGE_MS: 31536000000, // adpanel:remote-proxy-trust-gate — the mint body's issuance-gate check; // default-off/no-violation (false) keeps every pin here on the // pre-existing mint path (the opt-in + violation skip is pinned in // tests/remote-proxy-trust-gate.test.js with the REAL helper). remoteProxyTrustBlocksRememberIssuance: () => false, // Faithful model of the real chain's session-visible behavior // (issueRememberLoginToken -> upsertRememberLoginRegistryEntry -> // ensureRememberLoginSessionId): an invalid user/session rejects BEFORE // any session interaction (the real first guard), and a valid one reads // the session's current rememberLoginId or mints a NEW one and writes it // back into the session. issueSawId records the id visible AT ISSUE TIME // — the load-bearing ordering observation. issueRememberLoginToken: (req, user, now) => { events.push("issue"); if (!req?.session || !user || !user.id || !user.password) return ""; const current = String(req.session.rememberLoginId || "").trim(); events.push(`issueSawId:${current || ""}`); if (!current) { mintCounter += 1; req.session.rememberLoginId = `minted-${mintCounter}`; events.push(`minted:${req.session.rememberLoginId}`); } return `token:${req.session.rememberLoginId}:${now}`; }, getRememberLoginCookieOptions: () => ({ httpOnly: true, path: "/" }), }; const context = vm.createContext(sandbox); const fn = vm.runInContext(`(${fnSource})`, context); const makeReq = ({ rememberId, auditRememberId } = {}) => { const req = { session: { rememberLoginId: rememberId }, headers: {}, }; if (auditRememberId !== undefined) { req.session.browserSessionAudit = { email: "user@example.test", rememberLoginId: auditRememberId }; } return req; }; const makeRes = () => { const res = { cookies: [] }; res.cookie = (name, value, opts) => { events.push(`cookie:${name}`); res.cookies.push({ name, value, opts }); }; return res; }; const USER = { id: 42, email: "user@example.test", password: "hashed" }; return { fn, makeReq, makeRes, events, USER }; } test("forceFreshId: the old id is gone at issue time, a new id lands on the session, the audit copy is synced", () => { const { fn, makeReq, makeRes, events, USER } = buildHarness(); const req = makeReq({ rememberId: "revoked-id-X", auditRememberId: "revoked-id-X" }); const res = makeRes(); const timeBefore = Date.now(); const returned = fn(req, res, USER, { forceFreshId: true }); const timeAfter = Date.now(); assert.ok(events.includes("issueSawId:"), "the stale id must already be cleared when the issue runs"); assert.ok(events.includes("minted:minted-1"), "a NEW identifier must be minted"); assert.equal(req.session.rememberLoginId, "minted-1", "the session must carry the new id after the issue"); assert.equal( req.session.browserSessionAudit.rememberLoginId, "minted-1", "the session's audit copy must be re-synced to the new id (commitRotation's mirror)" ); assert.equal(res.cookies.length, 1, "the remember cookie must be set"); assert.equal(res.cookies[0].name, "adpanel_remember_test", "cookie name unchanged"); assert.match(res.cookies[0].value, /^token:minted-1:/, "the cookie must embed the NEW identifier"); assert.equal( typeof returned, "number", "the expiry return contract is preserved" ); assert.ok( returned >= timeBefore + 31536000000 && returned <= timeAfter + 31536000000, "the return value is the fresh 365-day expiry (now + REMEMBER_LOGIN_MAX_AGE_MS)" ); }); test("forceFreshId with a dead issue (no token): fail closed, no cookie, no resurrection", () => { const { fn, makeReq, makeRes, events, USER } = buildHarness(); const req = makeReq({ rememberId: "revoked-id-X", auditRememberId: "revoked-id-X" }); const res = makeRes(); // A user rejected by the issue chain's first guard (missing password) — // exactly how the real chain returns "" without touching the session. const returned = fn(req, res, { id: USER.id, email: USER.email }, { forceFreshId: true }); assert.equal(returned, undefined, "no expiry on a failed issue"); assert.equal(res.cookies.length, 0, "no cookie on a failed issue"); assert.ok(!events.includes("cookie:adpanel_remember_test"), "no cookie event"); // The real chain returns "" before touching the session when the user is // invalid, so the field stays cleared — the revoked id is never resurrected. assert.equal(req.session.rememberLoginId, undefined, "no id reappears on a failed issue"); }); test("no flag: legacy behavior preserved byte-for-byte — existing id reused, audit copy untouched", () => { const { fn, makeReq, makeRes, events, USER } = buildHarness(); const req = makeReq({ rememberId: "live-id-X", auditRememberId: "stale-audit-value" }); const res = makeRes(); const returned = fn(req, res, USER); assert.ok(events.includes("issueSawId:live-id-X"), "without the flag the existing id must be visible at issue time (binder semantics)"); assert.ok(!events.some((e) => e.startsWith("minted:")), "without the flag no new id is minted"); assert.equal(req.session.rememberLoginId, "live-id-X", "without the flag the session keeps its existing id"); assert.equal( req.session.browserSessionAudit.rememberLoginId, "stale-audit-value", "without the flag the audit copy must be untouched (byte-identical legacy behavior)" ); assert.equal(res.cookies.length, 1, "the remember cookie is still set"); assert.match(res.cookies[0].value, /^token:live-id-X:/, "the cookie still embeds the reused id"); assert.equal(typeof returned, "number", "the expiry return contract is preserved"); }); test("no session: early return without touching anything (both with and without the flag)", () => { const { fn, makeRes, events, USER } = buildHarness(); assert.equal(fn(undefined, makeRes(), USER), undefined); assert.equal(fn({ session: null }, makeRes(), USER, { forceFreshId: true }), undefined); assert.equal(fn({ session: {} }, undefined, USER, { forceFreshId: true }), undefined); assert.deepEqual(events, [], "no issue, no cookie on a missing session/res"); });