"use strict"; // adpanel:login-bind-one-true-home — pins for the ONE shared login session // binder (utils/login-session-bind.js). Both authentication completion paths // (POST /login success, completePendingCaptchaLogin) previously carried // line-for-line parallel copies of the tombstone → regenerate → bind → // serve → save sequence; copies of a security-critical sequence drift, and a // guard added to one path but not the other re-opens the destroy/save // resurrection race. This file pins structurally (both paths call the same // binder; no inline regenerate copies survive in index.js) and // functionally (the binder's exact operation order, its tombstone // condition — authenticated sids AND pre-auth sids carrying protected // pending auth state, never bare pre-auth sids —, its 5s timeouts, its // interstitial hook positions, and its save-failure hygiene: a post-mint // failure revokes the just-minted remember credential, tombstones the // regenerated sid so a late store write cannot commit the authenticated // record behind the 500, and rethrows the original error). // // adpanel:binder-call-contract — the file also pins the CALL CONTRACT both // ends must agree on: the factory returns an OBJECT carrying the named // `bindLoginSession` async method (never a bare callable) and both index.js // call sites invoke that method on the instance. A bare-function factory // return made the instance-method call throw a TypeError on EVERY successful // login while every unit test still passed (they called the factory result // directly). The integration pins below connect the REAL factory to the REAL // call statements (vm-extracted and executed) so this class of mismatch can // never ship silently again. 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 indexSource = fs.readFileSync(INDEX_JS, "utf8"); const { createLoginSessionBinder } = require(BINDER_JS); function countOccurrences(haystack, needle) { let count = 0; let pos = 0; for (;;) { const idx = haystack.indexOf(needle, pos); if (idx < 0) return count; count += 1; pos = idx + needle.length; } } function indexOfOrThrow(haystack, needle, from = 0) { const idx = haystack.indexOf(needle, from); assert.ok(idx >= 0, `expected source pin not found: ${needle}`); return idx; } function loginHandlerRegion() { const start = indexOfOrThrow(indexSource, 'app.post("/login", async (req, res) => {'); const end = indexSource.indexOf('app.post("/logout"', start); assert.ok(end > start, 'app.post("/logout" must follow app.post("/login"'); return indexSource.slice(start, end); } function captchaCompletionRegion() { const start = indexOfOrThrow(indexSource, "async function completePendingCaptchaLogin("); const end = indexSource.indexOf('app.post("/api/captcha/verify"', start); assert.ok(end > start, 'app.post("/api/captcha/verify" must follow completePendingCaptchaLogin'); return indexSource.slice(start, end); } // ---- Structural pins: one module, one wiring site, two callers ---- test("the shared login-session binder module exists and exports its factory", () => { assert.strictEqual(typeof createLoginSessionBinder, "function", "createLoginSessionBinder must be exported"); assert.ok( fs.readFileSync(BINDER_JS, "utf8").includes("adpanel:login-bind-one-true-home"), "the module must carry the one-true-home constraint comment" ); }); test("index.js requires and constructs the binder exactly once, near the remember-login machinery", () => { assert.strictEqual( countOccurrences(indexSource, 'require("./utils/login-session-bind")'), 1, "exactly one require of the shared binder module" ); assert.strictEqual( countOccurrences(indexSource, "const loginSessionBinder = createLoginSessionBinder({"), 1, "exactly one construction site" ); const construction = indexSource.slice( indexOfOrThrow(indexSource, "const loginSessionBinder = createLoginSessionBinder({"), indexOfOrThrow(indexSource, "revokeRememberLoginRegistryEntry,\n});") + "revokeRememberLoginRegistryEntry,\n});".length ); // The machinery the shared core needs — the tombstone write and display // id (resurrection guard), the protected-pending-state predicate (which // pre-auth sids the resurrection guard must also cover), the // identity/audit binders, the remember issuance pair, the active-session // cache, the timeout wrapper, and the save-failure hygiene pair (cookie // clear + registry revoke) so a visibly-failed login cannot leave a live // remember credential behind. for (const dep of [ "withTimeout", "writeRevokedSidTombstone", "sessionCarriesProtectedPendingAuthState", "getSessionDisplayId", "ensureRememberLoginSessionId", "buildBrowserSessionAuditFromRequest", "setRememberLoginCookie", "markRememberLoginSessionFresh", "upsertActiveBrowserSessionCacheEntry", "clearRememberLoginCookie", "revokeRememberLoginRegistryEntry", ]) { assert.ok(construction.includes(`${dep},`), `construction must hand the binder ${dep}`); } }); test("BOTH authentication completion paths call the same binder", () => { assert.strictEqual( countOccurrences(indexSource, "loginSessionBinder.bindLoginSession("), 2, "exactly two call sites: POST /login success and completePendingCaptchaLogin" ); const loginRegion = loginHandlerRegion(); const captchaRegion = captchaCompletionRegion(); // Conscious pin update (adpanel:login-proof-generation): the POST /login // call grew a beforeSave hook, so the single-line call form became a // multi-line one; the pin's subject (both paths bind through the ONE // shared binder) is unchanged. assert.ok(loginRegion.includes("loginSessionBinder.bindLoginSession(req, res, {"), "POST /login success path binds through the shared binder"); assert.ok(loginRegion.includes("user: latestUser,"), "POST /login binds the re-read row through the shared binder"); assert.ok(captchaRegion.includes("loginSessionBinder.bindLoginSession(req, res, {"), "completePendingCaptchaLogin binds through the shared binder"); // No inline copies may survive next to the calls: the completion regions // contain neither the regenerate nor the promise-wrapped save anymore // (remember-restore keeps its own regenerate, pinned with its tombstone // guard by tests/session-resurrection-tombstone.test.js; other flows' // promise-wrapped saves are unrelated responsibilities). assert.strictEqual( countOccurrences(indexSource, "req.session.regenerate("), 1, "index.js keeps only the remember-restore regenerate; login + captcha regenerate through the shared binder" ); for (const [label, region] of [["POST /login", loginRegion], ["completePendingCaptchaLogin", captchaRegion]]) { assert.strictEqual(countOccurrences(region, "req.session.regenerate("), 0, `${label} must regenerate through the shared binder, not inline`); assert.strictEqual(countOccurrences(region, "writeRevokedSidTombstone(preRegenerateSid)"), 0, `${label} must tombstone through the shared binder, not inline`); assert.strictEqual(countOccurrences(region, "buildBrowserSessionAuditFromRequest(req"), 0, `${label} must bind the audit through the shared binder, not inline`); } // The success-path TAIL of POST /login (after the bind call) must contain // no inline save either — the handler's other branches (remember-cookie // restore failures) legitimately keep their own req.session.save calls. const loginBindIdx = loginRegion.indexOf("loginSessionBinder.bindLoginSession(req, res, {"); assert.ok(loginBindIdx >= 0, "the POST /login success path binds through the shared binder"); const loginSuccessTail = loginRegion.slice(loginBindIdx); assert.strictEqual(countOccurrences(loginSuccessTail, "req.session.save("), 0, "the POST /login success path must save through the shared binder, not inline"); }); test("each path's own steps stayed at the handlers (not absorbed into the binder)", () => { const loginRegion = loginHandlerRegion(); const captchaRegion = captchaCompletionRegion(); // POST /login: suspension re-check stays before the bind; gate clear and // TOTP reset stay after the save (no interstitial hooks). The retired // local-captcha clear is gone (adpanel:local-captcha-retired — it was a // no-op on the regenerated session). Conscious pin update // (adpanel:login-proof-generation): the bind call gained the beforeSave // completion-window revalidation, so the call-opening marker replaces the // single-line call form; the pin's subject (the handler's own steps stay // at the handler) is unchanged. assert.ok(loginRegion.includes("if (latestUser?.suspended)"), "the pre-bind suspension re-check stays in the handler"); const loginBindIdx = loginRegion.indexOf("loginSessionBinder.bindLoginSession(req, res, {"); assert.ok(loginBindIdx >= 0); // adpanel:account-throttle-collation-parity — the reset call threads the // resolved latestUser so the id-keyed TOTP budget clears with the email // key; the position pin is unchanged (after the bind, outside the core). for (const step of ["clearLoginCaptchaGateForIp(throttleIpKey);", "await loginThrottle.resetTotpSource(emailStr, throttleIpKey, latestUser);"]) { const at = loginRegion.indexOf(step, loginBindIdx); assert.ok(at > loginBindIdx, `${step} must stay after the bind (outside the shared core)`); } assert.ok(!loginRegion.includes("afterIdentityBinding"), "POST /login must not need interstitial hooks"); // Captcha path: the pending-captcha clear historically ran after identity // binding and the TOTP reset after the cache upsert — reattached via the // binder's hooks. (The retired local-captcha clear is gone — // adpanel:local-captcha-retired.) assert.ok(captchaRegion.includes("afterIdentityBinding: () => {") && captchaRegion.includes("clearPendingCaptchaLogin(req);"), "the pending-captcha clear stays at its historical position via the afterIdentityBinding hook"); assert.ok(captchaRegion.includes("beforeSave: async () => {") && captchaRegion.includes("loginThrottle.resetTotpSource(pending.email, loginThrottle.ipKey(clientIp), user)"), "the TOTP budget reset stays between the cache upsert and the save via the beforeSave hook (adpanel:account-throttle-collation-parity: the resolved user clears the id key too)"); assert.ok(captchaRegion.includes("clearLoginCaptchaGateForIp(loginThrottle.ipKey(clientIp))"), "the bucketed-IP gate clear stays after the save, in the handler"); }); // ---- Functional pins: the binder's exact semantics ---- const USER = { email: "admin@example.com", id: 42, session_epoch: 7 }; // Builds a binder over recording stubs. Returns { binder, req, events, warnings } (binder is the REAL factory instance: call binder.bindLoginSession(req, res, opts) — adpanel:binder-call-contract). // failSaveWith / failRegenerateWith inject an error into the corresponding // session callback (express-session reports store failures through err). // skipSaveWithMarker replays the tombstone-skip-signal contract (the REAL // wrapper marks the live session object with the non-enumerable registry // symbol on a READ-ERROR skip and reports SUCCESS — see // tests/tombstone-skip-signal.test.js for the wrapper half). // pendingAuthState drives the injected sessionCarriesProtectedPendingAuthState // predicate (true = the pre-auth session carries protected pending auth // state, e.g. a solved captcha / pending captcha login). function makeHarness({ authenticated = false, pendingAuthState = false, tombstoneOk = true, failSaveWith = null, failRegenerateWith = null, skipSaveWithMarker = false } = {}) { const events = []; const warnings = []; const req = { sessionID: "sid-old", session: {} }; if (authenticated) req.session.user = "previously-authenticated@example.com"; req.session.regenerate = (cb) => { events.push("regenerate"); // express-session replaces the session contents with a fresh record and // repoints req.sessionID; the callback is asynchronous. for (const key of Object.keys(req.session)) { if (key !== "regenerate" && key !== "save") delete req.session[key]; } req.sessionID = "sid-new"; process.nextTick(() => cb(failRegenerateWith || null)); }; req.session.save = (cb) => { events.push("save"); // adpanel:tombstone-skip-signal — the skipped-write shape: the REAL // wrapper installs this non-enumerable registry symbol on the live // session object and STILL reports success (finish(null)); the binder's // post-save check must convert that false success into the labeled // failure. Installed exactly like the wrapper does (defineProperty, // non-enumerable). if (skipSaveWithMarker) { Object.defineProperty(req.session, Symbol.for("adpanel:storeWriteSkipped"), { value: "tombstone-read-error", enumerable: false, }); } process.nextTick(() => cb(failSaveWith || null)); }; const res = { cookie: (name, value) => events.push(`cookie:${name}`) }; const deps = { withTimeout: (promise, ms, label) => { events.push(`timeout:${label}:${ms}`); return promise; }, writeRevokedSidTombstone: (sid) => { events.push(`tombstone:${sid}`); return Promise.resolve(tombstoneOk); }, sessionCarriesProtectedPendingAuthState: (sess) => { events.push("pendingCheck"); // The binder must consult THIS request's session — the pre-auth record // actually carrying (or not carrying) the protected pending state. return !!pendingAuthState && sess === req.session; }, getSessionDisplayId: (sid) => `disp(${sid})`, ensureRememberLoginSessionId: (r) => { if (!r.session.rememberLoginId) r.session.rememberLoginId = "rid-1"; events.push("ensureRememberId"); return r.session.rememberLoginId; }, buildBrowserSessionAuditFromRequest: (r, email, rememberLoginId) => { events.push("buildAudit"); return { email, rememberLoginId }; }, setRememberLoginCookie: (r, rs, u) => { events.push("setRememberCookie"); return 7776000000; }, markRememberLoginSessionFresh: (r, expiresAt) => { events.push(`markFresh:${expiresAt}`); r.session.rememberLoginCheckedAt = 1; r.session.rememberLoginExpiresAt = expiresAt; }, upsertActiveBrowserSessionCacheEntry: (sessionId, sess) => { events.push(`upsert:${sessionId}`); }, clearRememberLoginCookie: (r, rs) => { events.push("clearRememberCookie"); }, revokeRememberLoginRegistryEntry: (rememberLoginId) => { events.push(`revokeRemember:${rememberLoginId}`); return Promise.resolve(true); }, logger: { warn: (...parts) => warnings.push(parts.join(" ")) }, }; const binder = createLoginSessionBinder(deps); return { binder, req, res, events, warnings, user: USER }; } test("pre-auth session without protected pending state: no tombstone, regenerate still applied, identity bound", async () => { const { binder, req, res, events, user } = makeHarness({ authenticated: false, pendingAuthState: false }); await binder.bindLoginSession(req, res, { user }); assert.ok(events.includes("pendingCheck"), "the tombstone condition consults the predicate for a pre-auth session"); assert.ok(!events.some((e) => e.startsWith("tombstone:")), "a pre-auth sid without protected pending state must never be tombstoned (raw login volume would bloat Redis — the volume bound preserved)"); assert.ok(events.includes("regenerate"), "regenerate must still run"); assert.ok(events.includes("save"), "save must still run"); assert.strictEqual(req.session.user, user.email, "user binding applied to the regenerated session"); assert.strictEqual(req.session.accountId, 42, "accountId binding applied"); assert.strictEqual(req.session.accountEpoch, 7, "accountEpoch binding applied"); assert.strictEqual(req.session.rememberLoginId, "rid-1", "remember login id ensured on the regenerated session"); assert.deepStrictEqual(req.session.browserSessionAudit, { email: user.email, rememberLoginId: "rid-1" }, "browser session audit built from the new identity"); }); test("authenticated session: tombstone of the pre-regeneration sid runs BEFORE regenerate", async () => { const { binder, req, res, events, user } = makeHarness({ authenticated: true }); await binder.bindLoginSession(req, res, { user }); const tombstoneIdx = events.indexOf("tombstone:sid-old"); const regenerateIdx = events.indexOf("regenerate"); assert.ok(tombstoneIdx >= 0, "an authenticated pre-regeneration sid must be tombstoned"); assert.ok(regenerateIdx > tombstoneIdx, "the tombstone must be durable before the regenerate destroys the old sid (order pin)"); assert.ok(events.includes("tombstone:sid-old") && !events.includes("tombstone:sid-new"), "the tombstone targets the PRE-regeneration sid"); // The full shared sequence, in the one-true-home order. The session // operations (regenerate/save) are invoked synchronously when the promise // argument is constructed, before withTimeout arms its timer — so each // operation precedes its timeout record, faithfully mirroring the call // structure the former inline copies used. assert.deepStrictEqual( events.filter((e) => !e.startsWith("cookie:")), [ "tombstone:sid-old", "regenerate", "timeout:session-regenerate-timeout:5000", "ensureRememberId", "buildAudit", "setRememberCookie", "markFresh:7776000000", "upsert:sid-new", "save", "timeout:session-save-timeout:5000", ], "the shared core's operation order and 5s timeouts are pinned" ); assert.strictEqual(req.session.user, user.email, "the regenerated (post-destroy) session carries the new identity"); }); test("pre-auth session carrying protected pending auth state: tombstone of the pre-regeneration sid runs BEFORE regenerate", async () => { const { binder, req, res, events, user } = makeHarness({ authenticated: false, pendingAuthState: true }); await binder.bindLoginSession(req, res, { user }); assert.ok(events.includes("pendingCheck"), "the predicate is consulted for a pre-auth session"); const tombstoneIdx = events.indexOf("tombstone:sid-old"); const regenerateIdx = events.indexOf("regenerate"); assert.ok( tombstoneIdx >= 0, "a pre-auth sid carrying protected pending auth state must be tombstoned — a stolen pre-auth cookie plus a matching IP+UA fingerprint must not revive the captcha-cleared (2FA-verified) pending login within its TTL" ); assert.ok(regenerateIdx > tombstoneIdx, "the tombstone must be durable before the regenerate destroys the old sid (order pin)"); assert.ok(!events.includes("tombstone:sid-new"), "the tombstone targets the PRE-regeneration sid"); assert.strictEqual(req.session.user, user.email, "the login still completes normally for the pending-state carrier"); }); test("an undurable tombstone still regenerates and warns with the exact security string", async () => { const { binder, req, res, events, warnings, user } = makeHarness({ authenticated: true, tombstoneOk: false }); await binder.bindLoginSession(req, res, { user }); assert.ok(events.includes("regenerate") && events.includes("save"), "the regenerate below still applies when the tombstone cannot be written (fail-open to the fresh sid, never a wedge)"); assert.strictEqual( warnings[0], "[security] Could not tombstone pre-regeneration session disp(sid-old); the regenerate below still applies", "the tombstone-failure warning string is pinned (both former inline copies emitted exactly this)" ); }); test("interstitial hooks run at the historical positions, outside the shared core", async () => { const { binder, req, res, events, user } = makeHarness({ authenticated: false }); const ran = []; await binder.bindLoginSession(req, res, { user, afterIdentityBinding: () => { ran.push("afterIdentityBinding"); events.push("hook:afterIdentityBinding"); }, beforeSave: async () => { ran.push("beforeSave"); events.push("hook:beforeSave"); }, }); const buildAuditIdx = events.indexOf("buildAudit"); const setCookieIdx = events.indexOf("setRememberCookie"); const upsertIdx = events.indexOf("upsert:sid-new"); const saveIdx = events.indexOf("save"); const afterIdx = events.indexOf("hook:afterIdentityBinding"); const beforeSaveIdx = events.indexOf("hook:beforeSave"); assert.ok(afterIdx > buildAuditIdx && afterIdx < setCookieIdx, "afterIdentityBinding runs after identity/audit binding, before the remember-cookie issuance"); assert.ok(beforeSaveIdx > upsertIdx && beforeSaveIdx < saveIdx, "beforeSave runs after the cache upsert, before the session save"); assert.deepStrictEqual(ran, ["afterIdentityBinding", "beforeSave"], "both hooks ran exactly once"); }); // ---- Functional pins: save-failure hygiene (no credential on a failed login) ---- test("a post-mint save failure clears the remember cookie, revokes the minted id, and rethrows the original error", async () => { const saveError = new Error("session-save-timeout"); const { binder, req, res, events, user } = makeHarness({ failSaveWith: saveError }); await assert.rejects( binder.bindLoginSession(req, res, { user }), (err) => err === saveError, "the ORIGINAL save error must reach the routes' 500 handling (no swallowing, no wrapping)" ); assert.ok(events.includes("clearRememberCookie"), "the just-minted remember cookie must be cleared off the failed response"); assert.ok(events.includes("revokeRemember:rid-1"), "the just-minted registry entry must be revoked by the id captured at the mint step"); const mintIdx = events.indexOf("setRememberCookie"); const saveIdx = events.indexOf("save"); const clearIdx = events.indexOf("clearRememberCookie"); const revokeIdx = events.indexOf("revokeRemember:rid-1"); assert.ok(mintIdx >= 0 && mintIdx < saveIdx && saveIdx < clearIdx && clearIdx < revokeIdx, "cleanup runs only after the save failed, cookie-clear before the awaited revoke"); }); test("a save failure also tombstones the REGENERATED sid, after the remember hygiene, then rethrows the original error", async () => { const saveError = new Error("session-save-timeout"); const { binder, req, res, events, warnings, user } = makeHarness({ failSaveWith: saveError }); await assert.rejects( binder.bindLoginSession(req, res, { user }), (err) => err === saveError, "the ORIGINAL save error must still reach the routes' 500 handling (no swallowing, no wrapping)" ); assert.ok(events.includes("tombstone:sid-new"), "the REGENERATED sid must be tombstoned so the store's tombstone guard refuses a late-landing save of the already-authenticated record"); assert.ok(!events.includes("tombstone:sid-old"), "no pre-regeneration tombstone ran for a bare pre-auth session — sid-new is the only tombstone target"); const clearIdx = events.indexOf("clearRememberCookie"); const revokeIdx = events.indexOf("revokeRemember:rid-1"); const tombNewIdx = events.indexOf("tombstone:sid-new"); assert.ok(clearIdx >= 0 && clearIdx < revokeIdx && revokeIdx < tombNewIdx, "the post-failure tombstone runs AFTER the existing remember hygiene (cookie clear → revoke → tombstone)"); assert.strictEqual(warnings.some((w) => w.includes("disp(sid-new)")), false, "a durable tombstone write does not warn"); }); test("an undurable post-failure tombstone warns with the pinned security string and still rethrows the original error", async () => { const saveError = new Error("session-save-timeout"); const { binder, req, res, events, warnings, user } = makeHarness({ pendingAuthState: false, tombstoneOk: false, failSaveWith: saveError }); await assert.rejects(binder.bindLoginSession(req, res, { user }), (err) => err === saveError); assert.ok(events.includes("tombstone:sid-new"), "the tombstone write was attempted even though it failed"); assert.deepStrictEqual( warnings, ["[security] Could not tombstone post-regeneration session disp(sid-new); a late store write may still commit the failed login's record"], "the post-failure tombstone-failure warning mirrors the existing tombstone-warn wording (pinned verbatim)" ); }); test("a post-mint beforeSave-hook failure performs the same hygiene before rethrowing", async () => { const hookError = new Error("totp-budget-reset-failed"); const { binder, req, res, events, user } = makeHarness({}); await assert.rejects( binder.bindLoginSession(req, res, { user, beforeSave: async () => { throw hookError; } }), (err) => err === hookError ); assert.ok(events.includes("upsert:sid-new"), "the hook throws after the cache upsert (historical position kept)"); assert.ok(!events.includes("save"), "the bounded save must not run when the beforeSave hook throws"); assert.ok(events.includes("clearRememberCookie") && events.includes("revokeRemember:rid-1"), "hook failures after the mint run the same cleanup as save failures"); }); test("a regenerate failure performs no cleanup (the failure precedes the mint)", async () => { const regenerateError = new Error("session-regenerate-timeout"); const { binder, req, res, events, user } = makeHarness({ failRegenerateWith: regenerateError }); await assert.rejects( binder.bindLoginSession(req, res, { user }), (err) => err === regenerateError, "the original regenerate error rethrows unchanged" ); assert.strictEqual(events.includes("setRememberCookie"), false, "the failure precedes the mint — nothing was issued"); assert.strictEqual(events.includes("clearRememberCookie"), false, "no cookie-clear may run when nothing was minted"); assert.strictEqual(events.some((e) => e.startsWith("revokeRemember:")), false, "no revoke may run when nothing was minted"); assert.strictEqual(events.some((e) => e.startsWith("tombstone:")), false, "no tombstone of anything may run — the failure precedes the mint and nothing was sent"); assert.ok(events.includes("pendingCheck"), "the predicate was consulted pre-regenerate (a bare pre-auth sid, so it declined)"); }); test("an authenticated regenerate failure keeps the pre-regeneration tombstone but tombstones nothing post-failure", async () => { const regenerateError = new Error("session-regenerate-timeout"); const { binder, req, res, events, warnings, user } = makeHarness({ authenticated: true, failRegenerateWith: regenerateError }); await assert.rejects( binder.bindLoginSession(req, res, { user }), (err) => err === regenerateError, "the original regenerate error rethrows unchanged" ); assert.ok(events.includes("tombstone:sid-old"), "the unchanged pre-regeneration tombstone still ran (authenticated ordering untouched)"); assert.ok(!events.includes("tombstone:sid-new"), "no post-failure tombstone may run when the regenerate itself failed — there is no committed record to guard"); assert.strictEqual(events.includes("clearRememberCookie"), false, "no cookie-clear may run when nothing was minted"); assert.strictEqual(events.some((e) => e.startsWith("revokeRemember:")), false, "no revoke may run when nothing was minted"); assert.deepStrictEqual(warnings, [], "no tombstone failed, so nothing warns"); }); test("the success path issues no hygiene (the cookie stays set, nothing is revoked)", async () => { const { binder, req, res, events, user } = makeHarness({}); await binder.bindLoginSession(req, res, { user }); assert.strictEqual(events.includes("clearRememberCookie"), false, "a successful login must not clear the remember cookie"); assert.strictEqual(events.some((e) => e.startsWith("revokeRemember:")), false, "a successful login must not revoke the minted credential"); }); // ---- Functional pins: the tombstone-skip signal (adpanel:tombstone-skip-signal) ---- test("a save SKIPPED for a tombstone read error (marked session, store reported success) surfaces as the labeled failure and runs the full hygiene", async () => { const { binder, req, res, events, user } = makeHarness({ skipSaveWithMarker: true }); await assert.rejects( binder.bindLoginSession(req, res, { user }), (err) => err instanceof Error && /^session store write skipped \(tombstone-read-error\)$/.test(err.message), "the false 'save OK' of a blip-dropped login save must become the labeled failure that reaches the routes' existing 500 handling" ); assert.ok(events.includes("save"), "the skipped save still resolved through the store callback (finish(null) contract)"); // The catch's existing hygiene ran: the 500-answered login must not leave // a live remember credential, and the regenerated sid must be tombstoned // so no late store write can commit the authenticated record behind the 500. assert.ok(events.includes("clearRememberCookie"), "the just-minted remember cookie must be cleared"); assert.ok(events.includes("revokeRemember:rid-1"), "the just-minted registry entry must be revoked"); assert.ok(events.includes("tombstone:sid-new"), "the regenerated sid must be tombstoned"); const saveIdx = events.indexOf("save"); const clearIdx = events.indexOf("clearRememberCookie"); const revokeIdx = events.indexOf("revokeRemember:rid-1"); const tombIdx = events.indexOf("tombstone:sid-new"); assert.ok(saveIdx < clearIdx && clearIdx < revokeIdx && revokeIdx < tombIdx, "hygiene order: cookie clear → revoke → regenerated-sid tombstone"); }); test("an unmarked successful save still resolves OK (only the read-error skip converts to failure)", async () => { const { binder, req, res, events, user } = makeHarness({ skipSaveWithMarker: false }); await assert.doesNotReject(binder.bindLoginSession(req, res, { user }), "a save without the marker must keep the success contract"); assert.strictEqual(events.includes("clearRememberCookie"), false); assert.strictEqual(events.some((e) => e.startsWith("revokeRemember:")), false); assert.strictEqual(events.some((e) => e.startsWith("tombstone:")), false); }); test("the skip-signal marker itself never leaks into the serialized session the login would store", async () => { const { binder, req, res, user } = makeHarness({ skipSaveWithMarker: true }); await assert.rejects(binder.bindLoginSession(req, res, { user }), /session store write skipped/); assert.ok( !JSON.stringify(req.session).includes("tombstone-read-error"), "the marker mirrors the wrapper's non-enumerable installation: JSON.stringify (the express-session hash and the store record) cannot see it" ); const descriptor = Object.getOwnPropertyDescriptor(req.session, Symbol.for("adpanel:storeWriteSkipped")); assert.strictEqual(descriptor?.enumerable, false, "the marker stays non-enumerable on the binder's own session object"); }); test("the binder fails closed when the tombstone machinery is not handed over", () => { assert.throws(() => createLoginSessionBinder({ withTimeout: (p) => p }), /missing required deps: .*writeRevokedSidTombstone/, "a binder without the resurrection guard must refuse to construct"); }); test("the binder fails closed listing the full eleven-dep contract, including the pending-state predicate and the hygiene pair", () => { assert.throws( () => createLoginSessionBinder({}), (err) => { const missing = String(err?.message || "").replace(/^createLoginSessionBinder: missing required deps: /, "").split(", "); assert.deepStrictEqual( missing, [ "withTimeout", "writeRevokedSidTombstone", "sessionCarriesProtectedPendingAuthState", "getSessionDisplayId", "ensureRememberLoginSessionId", "buildBrowserSessionAuditFromRequest", "setRememberLoginCookie", "markRememberLoginSessionFresh", "upsertActiveBrowserSessionCacheEntry", "clearRememberLoginCookie", "revokeRememberLoginRegistryEntry", ], "the missing-deps error must list the complete eleven-dep contract (count and order pinned)" ); return true; }, "an empty deps object must fail closed naming every required dep" ); }); // ---- Integration pins: the REAL call contract, factory ↔ call sites ---- // adpanel:binder-call-contract — the unit tests above called the factory // result directly as a function, so a factory that returned a BARE function // passed all 21 of them while BOTH index.js call sites (which invoke // `loginSessionBinder.bindLoginSession(...)`, the instance-method form) // threw `TypeError: loginSessionBinder.bindLoginSession is not a function` // on every successful login. These pins connect the REAL factory to the REAL // call contract so that flip fails CI instead of shipping silently. // Extracts the full call statement starting at the first // "await loginSessionBinder.bindLoginSession(" in the given region, crossing // the object-literal hook arguments with a comment- and string-aware // parenthesis matcher (the captcha statement carries inline // comments). function extractBinderCallStatement(region) { const callStart = region.indexOf("await loginSessionBinder.bindLoginSession("); assert.ok(callStart >= 0, "region must contain the shared binder call statement"); let depth = 0; let inLineComment = false; let inBlockComment = false; let quote = null; let i = region.indexOf("(", callStart); assert.ok(i > callStart, "the call statement opens its argument list"); for (; i < region.length; i += 1) { const ch = region[i]; const next = region[i + 1]; if (inLineComment) { if (ch === "\n") inLineComment = false; continue; } if (inBlockComment) { if (ch === "*" && next === "/") { inBlockComment = false; i += 1; } continue; } if (quote) { if (ch === "\\") { i += 1; continue; } if (ch === quote) quote = null; continue; } if (ch === "/" && next === "/") { inLineComment = true; i += 1; continue; } if (ch === "/" && next === "*") { inBlockComment = true; i += 1; continue; } if (ch === '"' || ch === "'" || ch === "`") { quote = ch; continue; } if (ch === "(") depth += 1; else if (ch === ")") { depth -= 1; if (depth === 0) { i += 1; break; } } } assert.strictEqual(depth, 0, "the extracted call statement balances its parentheses"); while (i < region.length && (region[i] === ";" || region[i] === " ")) i += 1; const statement = region.slice(callStart, i); assert.ok(statement.endsWith(";"), "the extracted statement ends at its semicolon"); return statement; } // Runs one vm-extracted index.js statement in a fresh sandbox whose free // identifiers are the given host-side objects (the route's own locals, // stubbed). The binder itself is the REAL factory instance. function runStatementInSandbox(statement, sandbox) { const context = vm.createContext(sandbox); return vm.runInContext(`(async () => {\n${statement}\n})()`, context, { filename: "index.js:extracted-binder-call", }); } test("INTEGRATION PIN (runtime): the REAL factory returns the object-with-method contract the call sites bind against", () => { const { binder } = makeHarness({}); assert.ok(binder && typeof binder === "object", "the factory must return an OBJECT, not a bare callable — a bare-function return made every successful login throw"); assert.strictEqual( typeof binder.bindLoginSession, "function", "the returned object must carry the named bindLoginSession async method: both index.js call sites invoke .bindLoginSession(...) on the instance" ); assert.strictEqual(binder.bindLoginSession.name, "bindLoginSession", "the method keeps its name for stack traces"); }); test("INTEGRATION PIN (source): the call contract is pinned at BOTH ends — factory return shape and call-site form", () => { const binderSource = fs.readFileSync(BINDER_JS, "utf8"); // Factory end: the object-with-method return shape (adpanel:binder-call-contract). assert.ok( binderSource.includes("return { bindLoginSession };"), "the factory must return { bindLoginSession } — pin the shape so a refactor cannot flip the contract silently" ); assert.ok( !/return\s+async\s+function/.test(binderSource), "the factory must never return a bare async function (the shape that broke every login)" ); // Call-site end: the bare-function call form appears NOWHERE; both call // sites reach the binder through the named method. assert.strictEqual( countOccurrences(indexSource, "loginSessionBinder(req"), 0, "no call site may invoke the binder instance as a bare function" ); assert.strictEqual( countOccurrences(indexSource, "await loginSessionBinder."), 2, "both call sites await the named method on the instance" ); }); test("INTEGRATION PIN (runtime repro-as-pin): the REAL extracted index.js call statements execute against REAL factory instances without a TypeError", async () => { // The pasted P0, turned positive: the exact statements the two routes run, // vm-extracted from index.js and executed against binders built by the REAL // factory over recording stub deps. A contract flip makes these throw // `TypeError: loginSessionBinder.bindLoginSession is not a function` — // every successful login's failure mode — and this pin fails CI first. // (Stub-dep failures deeper than the call contract would also fail loudly; // with well-behaved stubs the full shared core completes.) // POST /login success path (index.js:24479 statement). Conscious pin // update (adpanel:login-proof-generation): the statement now carries the // beforeSave completion-window revalidation, so the hook closures' free // identifiers (the handler's own locals) are stubbed benignly here — this // pin's subject is the call contract (no TypeError, identity bound, save // ran); the hook's VALIDATION semantics are pinned by // tests/login-staleness-reproof.test.js. const loginHarness = makeHarness({}); await runStatementInSandbox(extractBinderCallStatement(loginHandlerRegion()), { loginSessionBinder: loginHarness.binder, req: loginHarness.req, res: loginHarness.res, latestUser: loginHarness.user, provedEpoch: loginHarness.user.session_epoch, findUserByEmail: async () => loginHarness.user, credentialGenerationMismatch: () => false, hasTwoFactorEnabled: () => false, passStr: "", bcrypt: { compare: async () => true }, loginBcryptAdmission: { run: (fn) => fn() }, withTimeout: (promise) => promise, rejectStaleCompletion: () => new Error("login completion rejected a stale credential state"), }); assert.strictEqual(loginHarness.req.session.user, loginHarness.user.email, "the real POST /login statement bound the identity through the real factory instance"); assert.strictEqual(loginHarness.req.session.accountId, 42, "accountId bound by the real statement"); assert.ok(loginHarness.events.includes("save"), "the real POST /login statement ran the shared core through the save"); // completePendingCaptchaLogin path (index.js:21864 statement) with its two // interstitial hooks; the hook closures' free identifiers are the handler's // own locals, stubbed in the sandbox. Conscious pin update // (adpanel:login-proof-generation): the beforeSave hook now ALSO revalidates // on a fresh read before the TOTP reset — its free identifiers stubbed // benignly here (validation semantics pinned by // tests/captcha-completion-staleness.test.js). const captchaHarness = makeHarness({}); const captchaEvents = captchaHarness.events; // The hook compares the fresh row against the resolved row — both stubs // must be the SAME password-carrying row for the benign path. const captchaUser = { email: "admin@example.com", id: 42, session_epoch: 7, password: "hash", secret: null, totpSealedError: false }; await runStatementInSandbox(extractBinderCallStatement(captchaCompletionRegion()), { loginSessionBinder: captchaHarness.binder, req: captchaHarness.req, res: captchaHarness.res, user: captchaUser, pending: { email: "pending@example.com", userId: "42", userFingerprint: "fp", twoFactorVerified: true }, clientIp: "203.0.113.9", clearPendingCaptchaLogin: () => captchaEvents.push("hook:clearPendingCaptchaLogin"), loginThrottle: { ipKey: (ip) => `ip(${ip})`, resetTotpSource: async () => { captchaEvents.push("hook:resetTotpSource"); }, }, findUserByEmail: async () => captchaUser, credentialGenerationMismatch: () => false, getRememberLoginFingerprint: () => "fp", safeCompare: (a, b) => a === b, hasTwoFactorEnabled: () => false, rejectStaleCompletion: () => new Error("login completion rejected a stale credential state"), }); assert.strictEqual(captchaHarness.req.session.user, captchaHarness.user.email, "the real captcha-completion statement bound the identity through the real factory instance"); assert.ok(captchaEvents.includes("hook:clearPendingCaptchaLogin"), "the afterIdentityBinding hook ran inside the real statement"); assert.ok(captchaEvents.includes("hook:resetTotpSource"), "the beforeSave hook ran inside the real statement"); assert.ok(captchaEvents.includes("save"), "the real captcha-completion statement ran the shared core through the save"); });