Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,456 @@
|
||||
"use strict";
|
||||
|
||||
// Issue 1 (HIGH): a revoked session could be silently resurrected and stay
|
||||
// fully usable. express-session persists a session at response end of any
|
||||
// in-flight request whose snapshot changed (rolling: true plus the 60s
|
||||
// browser-session audit bump guarantee that), so a request that loaded the
|
||||
// session pre-destroy rewrote the complete pre-revocation record — including
|
||||
// session.user — after the revocation reported success, and nothing
|
||||
// re-checked revocation for an already-authenticated sid.
|
||||
//
|
||||
// The fix is a tombstone-based revocation: every destruction of a live
|
||||
// session durably records `adpanel:revoked-sid:<sid>` (TTL strictly greater
|
||||
// than the 365-day store entry lifetime) BEFORE the store destroy; the
|
||||
// session store's set()/touch() are wrapped to refuse (and re-destroy) any
|
||||
// write for a tombstoned sid, consulting Redis so a revocation from another
|
||||
// PM2 worker is enforced too; an early gate middleware rejects a tombstoned
|
||||
// sid outright. This file pins that architecture. It reads index.js as text,
|
||||
// like the other audit tests.
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const os = require("node:os");
|
||||
const { createSessionStoreTombstoneGuard } = require("../utils/session-store-guard");
|
||||
const { createFileSessionRevocations } = require("../utils/file-session-revocations");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const INDEX_JS = path.join(ROOT, "index.js");
|
||||
|
||||
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
||||
const guardSource = fs.readFileSync(path.join(ROOT, "utils", "session-store-guard.js"), "utf8");
|
||||
|
||||
function extractRegion(source, startMarker, endMarker) {
|
||||
const start = source.indexOf(startMarker);
|
||||
assert.ok(start >= 0, `region start marker not found: ${startMarker}`);
|
||||
const end = source.indexOf(endMarker, start + startMarker.length);
|
||||
assert.ok(end > start, `region end marker not found after start: ${endMarker}`);
|
||||
return source.slice(start, end);
|
||||
}
|
||||
|
||||
const TOMBSTONE_WRITE = "await writeRevokedSidTombstone(";
|
||||
|
||||
test("revoked-sid tombstone constants exist and outlive the store entry lifetime", () => {
|
||||
assert.match(
|
||||
indexSource,
|
||||
/const REVOKED_SID_TOMBSTONE_REDIS_PREFIX = "adpanel:revoked-sid:";/,
|
||||
"tombstones must live under the adpanel:revoked-sid: Redis namespace"
|
||||
);
|
||||
assert.match(
|
||||
indexSource,
|
||||
/const REVOKED_SID_TOMBSTONE_TTL_SECONDS = 370 \* 24 \* 60 \* 60;/,
|
||||
"tombstone TTL must be 370 days"
|
||||
);
|
||||
// Cookie maxAge (and therefore the store entry TTL) is 365 days; the
|
||||
// tombstone must strictly outlive the longest possible store entry.
|
||||
const tombstoneSeconds = 370 * 24 * 60 * 60;
|
||||
const sessionSeconds = (365 * 24 * 60 * 60 * 1000) / 1000;
|
||||
assert.ok(
|
||||
tombstoneSeconds > sessionSeconds,
|
||||
"370-day tombstone TTL must strictly exceed the 365-day store entry lifetime"
|
||||
);
|
||||
});
|
||||
|
||||
test("writeRevokedSidTombstone is durable-first and fails closed on Redis errors", () => {
|
||||
const body = extractRegion(
|
||||
indexSource,
|
||||
"async function writeRevokedSidTombstone(sid)",
|
||||
"async function isSessionSidRevoked("
|
||||
);
|
||||
assert.match(body, /redisClient\.set\(getRevokedSidTombstoneRedisKey\(id\), "1"/, "the tombstone must be written to Redis");
|
||||
assert.match(body, /rememberRevokedSidTombstoneLocally\(id\)/, "the local fast path must be populated on write");
|
||||
assert.match(body, /return false;/, "a failed Redis write must return false so callers fail closed");
|
||||
// The write must be bounded by withTimeout: the redis client has no command
|
||||
// timeout and buffers writes while disconnected, so an unbounded await would
|
||||
// hang the orphaned-session branch of GET / for as long as the stall lasts.
|
||||
assert.match(body, /await withTimeout\(\s*redisClient\.set\(/, "the Redis write must be wrapped in withTimeout");
|
||||
const setIdx = body.indexOf("redisClient.set(");
|
||||
const successIdx = body.indexOf("return true;", setIdx);
|
||||
const catchIdx = body.indexOf("} catch", setIdx);
|
||||
assert.ok(
|
||||
setIdx >= 0 && successIdx > setIdx && successIdx < catchIdx,
|
||||
"success must only be reported after the Redis write completes"
|
||||
);
|
||||
});
|
||||
|
||||
test("the store wrapper intercepts set and touch on the active store instance", () => {
|
||||
assert.match(guardSource, /function wrapSessionStoreWithTombstoneGuard\(store\)/, "the generic store wrapper must exist");
|
||||
assert.match(indexSource, /require\("\.\/utils\/session-store-guard"\)\.createSessionStoreTombstoneGuard/, "the active store uses the shared implementation");
|
||||
const wrapper = guardSource;
|
||||
assert.match(wrapper, /guardMethod\("set"\);/, "set() must be guarded");
|
||||
assert.match(wrapper, /guardMethod\("touch"\);/, "touch() must be guarded");
|
||||
assert.match(wrapper, /store\.destroy\.call\(this, sid/, "a tombstoned write must invoke the store's destroy (never wrapped) so the entry stays gone");
|
||||
assert.doesNotMatch(wrapper, /original\.destroy/, "the re-destroy must not go through the wrapped set/touch function object");
|
||||
assert.match(wrapper, /finish\(null\);/, "refusing a tombstoned write must report success to the store caller");
|
||||
assert.match(wrapper, /isSessionSidRevoked\(sid\)/, "every set/touch must consult the revocation check");
|
||||
|
||||
// The wrapper must be applied AFTER whichever store instance was created
|
||||
// (connect-redis or the file-store fallback), never before.
|
||||
const applyIdx = indexSource.indexOf("wrapSessionStoreWithTombstoneGuard(sessionStore);");
|
||||
const redisStoreIdx = indexSource.indexOf("sessionStore = new RedisStore(");
|
||||
const fileStoreIdx = indexSource.indexOf("sessionStore = new (getLazyFileStore())(");
|
||||
assert.ok(applyIdx > 0, "the wrapper must be applied to the created store");
|
||||
assert.ok(redisStoreIdx >= 0 && fileStoreIdx >= 0, "both store creation paths must still exist");
|
||||
assert.ok(applyIdx > redisStoreIdx && applyIdx > fileStoreIdx, "the wrapper must wrap whichever store instance is active");
|
||||
});
|
||||
|
||||
test("the wrapper consults Redis, not just the local cache (cross-worker safety)", () => {
|
||||
const body = extractRegion(
|
||||
indexSource,
|
||||
"async function isSessionSidRevoked(",
|
||||
"const wrapSessionStoreWithTombstoneGuard"
|
||||
);
|
||||
assert.match(body, /isRevokedSidTombstoneCachedLocally\(id\)/, "the local cache is the fast path");
|
||||
assert.match(
|
||||
body,
|
||||
/redisClient\.get\(getRevokedSidTombstoneRedisKey\(id\)\)/,
|
||||
"the wrapper's check MUST also consult Redis: another worker may have revoked the sid"
|
||||
);
|
||||
// Write path fails closed on Redis errors (default), read path opts out.
|
||||
assert.match(body, /\{ failClosed = true \} = \{\}/, "the default failure mode must be fail-closed (write path)");
|
||||
assert.match(body, /return redisClient \? failClosed : true;/, "Redis errors follow the caller mode and file-marker read errors fail closed");
|
||||
});
|
||||
|
||||
test("an early gate middleware rejects tombstoned sids before any re-authentication", () => {
|
||||
const gate = extractRegion(
|
||||
indexSource,
|
||||
"// Revoked-sid gate:",
|
||||
"await ensureRememberLoginStoreReady();"
|
||||
);
|
||||
assert.match(gate, /isSessionSidRevoked\(sid, \{ failClosed: false \}\)/, "the gate must consult the tombstone (confirmed-tombstone-only)");
|
||||
assert.match(gate, /req\.session\.destroy\(/, "a tombstoned session must be destroyed");
|
||||
assert.match(
|
||||
gate,
|
||||
/res\.clearCookie\("adpanel\.sid", \{\s*httpOnly: true,\s*sameSite: "lax",\s*secure: cookieSecureForRequest\(req\),\s*path: "\/",\s*\}\)/,
|
||||
"the adpanel.sid cookie must be cleared with the same option parity used by every other revocation path"
|
||||
);
|
||||
assert.match(gate, /pLower\.startsWith\("\/api\/"\)\)\s*\{\s*return res\.status\(401\)\.json\(\{ error: "not authenticated" \}\);/, "API requests must be rejected 401 like every other unauthenticated API request (case-insensitively: /API/ variants are the same routes)");
|
||||
assert.match(gate, /return res\.redirect\("\/login"\);/, "page requests must be sent to /login like every other unauthenticated page request");
|
||||
|
||||
// Ordering: after the session middleware (and the secure-cookie sync
|
||||
// middleware), before the remember-login restore middleware.
|
||||
const gateIdx = indexSource.indexOf("// Revoked-sid gate:");
|
||||
const sessionMwIdx = indexSource.indexOf("app.use(sessionMiddleware);");
|
||||
const restoreIdx = indexSource.indexOf("await restoreRememberedLogin(req, res);");
|
||||
assert.ok(gateIdx > sessionMwIdx, "the gate must run after the session middleware");
|
||||
assert.ok(restoreIdx > gateIdx, "the gate must run before the remember-login restore middleware");
|
||||
});
|
||||
|
||||
test("destroySessionStoreSessionVerified makes the tombstone durable BEFORE the destroy loop", () => {
|
||||
const body = extractRegion(
|
||||
indexSource,
|
||||
"async function destroySessionStoreSessionVerified(",
|
||||
"async function mapWithConcurrency("
|
||||
);
|
||||
const tombstoneIdx = body.indexOf(TOMBSTONE_WRITE);
|
||||
const destroyIdx = body.indexOf('callSessionStore("destroy", sid)');
|
||||
assert.ok(tombstoneIdx >= 0, "the verified destroy must write a tombstone");
|
||||
assert.ok(destroyIdx > tombstoneIdx, "the tombstone must be durable BEFORE the store destroy (revoke-then-destroy ordering)");
|
||||
assert.match(body, /if \(!tombstoneDurable\)\s*\{\s*[\s\S]*?return false;/, "a tombstone that cannot be made durable must fail the revocation (fail closed)");
|
||||
assert.match(body, /maxAttempts/, "the bounded verification loop must remain");
|
||||
assert.match(body, /readback/, "the post-destroy readback verification must remain");
|
||||
});
|
||||
|
||||
test("every destroy path for a live session tombstones the sid first", () => {
|
||||
// Suspension teardown middleware.
|
||||
const suspension = extractRegion(
|
||||
indexSource,
|
||||
"if (req._staticAsset || !req.session?.user) return next();",
|
||||
"// Middleware to ensure session TTL is refreshed"
|
||||
);
|
||||
const suspensionTombstoneIdx = suspension.indexOf(TOMBSTONE_WRITE);
|
||||
const suspensionDestroyIdx = suspension.indexOf("req.session.destroy(");
|
||||
assert.ok(suspensionTombstoneIdx >= 0, "the suspension teardown must tombstone the sid");
|
||||
assert.ok(suspensionDestroyIdx > suspensionTombstoneIdx, "the suspension destroy must come after the tombstone");
|
||||
|
||||
// Logout route.
|
||||
const logout = extractRegion(
|
||||
indexSource,
|
||||
'app.post("/logout"',
|
||||
"const ENV_FILE_PATH"
|
||||
);
|
||||
const logoutTombstoneIdx = logout.indexOf(TOMBSTONE_WRITE);
|
||||
const logoutDestroyIdx = logout.indexOf("req.session.destroy(");
|
||||
assert.ok(logoutTombstoneIdx >= 0, "logout must tombstone the sid");
|
||||
assert.ok(logoutDestroyIdx > logoutTombstoneIdx, "the logout destroy must come after the tombstone");
|
||||
|
||||
// Bulk eviction (password change / account delete / admin evictions).
|
||||
const bulkEvict = extractRegion(
|
||||
indexSource,
|
||||
"async function destroyBrowserSessionsForUser(",
|
||||
"function hashDestructiveActionGraceValue("
|
||||
);
|
||||
const evictTombstoneIdx = bulkEvict.indexOf(TOMBSTONE_WRITE);
|
||||
const evictDestroyIdx = bulkEvict.indexOf('callSessionStore("destroy", sessionId)');
|
||||
assert.ok(evictTombstoneIdx >= 0, "the bulk eviction must tombstone each sid");
|
||||
assert.ok(evictDestroyIdx > evictTombstoneIdx, "the bulk eviction destroy must come after the tombstone");
|
||||
assert.match(
|
||||
bulkEvict,
|
||||
/revoked-sid tombstone not durable/,
|
||||
"an undurable tombstone must surface as an eviction error so callers fail closed"
|
||||
);
|
||||
|
||||
// Admin revoke routes go through destroySessionStoreSessionVerified (which
|
||||
// tombstones) — pinned by counting its call sites.
|
||||
const verifiedCalls = indexSource.split("await destroySessionStoreSessionVerified(").length - 1;
|
||||
assert.ok(verifiedCalls >= 4, "the admin self/other revoke paths must keep using the verified destroy");
|
||||
|
||||
// The user-row-gone teardowns (GET / and the status page) destroy the
|
||||
// session too — each must tombstone first.
|
||||
const orphanBlocks = [];
|
||||
let cursor = 0;
|
||||
for (;;) {
|
||||
const at = indexSource.indexOf('if (req.session?.destroy) {', cursor);
|
||||
if (at < 0) break;
|
||||
orphanBlocks.push(indexSource.slice(at, indexSource.indexOf('return res.redirect(303, "/login");', at)));
|
||||
cursor = at + 1;
|
||||
}
|
||||
assert.ok(orphanBlocks.length >= 2, "the user-row-gone destroy paths must still exist");
|
||||
for (const block of orphanBlocks) {
|
||||
assert.match(block, /await writeRevokedSidTombstone\(req\.sessionID\)/, "every user-row-gone destroy must tombstone the sid first");
|
||||
}
|
||||
});
|
||||
|
||||
test("the per-worker tombstone cache is bounded", () => {
|
||||
assert.match(indexSource, /const REVOKED_SID_TOMBSTONE_MEMORY_MAX = 10000;/, "the in-memory cache must have a cap");
|
||||
assert.match(indexSource, /function sweepExpiredRevokedSidTombstones\(\)/, "an expiry sweep must exist");
|
||||
assert.match(indexSource, /setInterval\(sweepExpiredRevokedSidTombstones/, "the sweep must run periodically");
|
||||
const remember = extractRegion(
|
||||
indexSource,
|
||||
"function rememberRevokedSidTombstoneLocally(sid)",
|
||||
"function isRevokedSidTombstoneCachedLocally(sid)"
|
||||
);
|
||||
assert.match(remember, /REVOKED_SID_TOMBSTONE_MEMORY_MAX/, "insertions must enforce the cap");
|
||||
});
|
||||
|
||||
// ---- Review-fix pins: store-callback contract + regenerate races ----
|
||||
|
||||
test("the store wrapper reports through the store's own callback exactly once", () => {
|
||||
const wrapper = guardSource;
|
||||
|
||||
// connect-redis' set/touch are async methods: they invoke the callback AND
|
||||
// resolve a promise. The wrapper must hand the store a settle-once stand-in
|
||||
// for its callback and let that be the single reporter — listening to the
|
||||
// promise as well double-invokes express-session's completion handler and
|
||||
// masks store errors as err-then-null.
|
||||
assert.match(
|
||||
wrapper,
|
||||
/args\[args\.length - 1\] = function tombstoneGuardedStoreCallback\(err, result\)/,
|
||||
"the non-revoked path must replace the store's callback with the settle-once stand-in"
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
wrapper,
|
||||
/\.then\(\(result\) => finish\(null, result\)\)/,
|
||||
"the promise must never be used to report the outcome (double callback)"
|
||||
);
|
||||
assert.match(
|
||||
wrapper,
|
||||
/\.catch\(\(\) => \{ \}\)/,
|
||||
"the returned promise must still be drained so a store error cannot become an unhandled rejection"
|
||||
);
|
||||
|
||||
// The stand-in must be installed before the store is invoked on the
|
||||
// non-revoked path (the first original.apply is the no-sid passthrough),
|
||||
// and the revoked path keeps its settled-once destroy handling.
|
||||
const standInIdx = wrapper.indexOf("tombstoneGuardedStoreCallback");
|
||||
const applyAfterStandIn = wrapper.indexOf("original.apply(this, args)", standInIdx);
|
||||
assert.ok(standInIdx >= 0 && applyAfterStandIn > standInIdx, "the callback stand-in must be installed before the non-revoked store call");
|
||||
assert.match(wrapper, /let settled = false;/, "the revoked re-destroy path must keep its settle-once guard");
|
||||
});
|
||||
|
||||
test("in-flight session writes cannot recreate a revoked record after destroy", async () => {
|
||||
let revoked = false;
|
||||
let writeStarted;
|
||||
const started = new Promise((resolve) => { writeStarted = resolve; });
|
||||
let commitWrite;
|
||||
const records = new Map();
|
||||
const store = {
|
||||
set(sessionId, record, callback) {
|
||||
writeStarted();
|
||||
commitWrite = () => {
|
||||
records.set(sessionId, record);
|
||||
callback(null);
|
||||
};
|
||||
},
|
||||
destroy(sessionId, callback) {
|
||||
records.delete(sessionId);
|
||||
callback?.(null);
|
||||
},
|
||||
};
|
||||
const wrap = createSessionStoreTombstoneGuard({
|
||||
logger: { warn() {} },
|
||||
isSessionSidRevoked: async () => revoked,
|
||||
isRevokedSidTombstoneCachedLocally: () => revoked,
|
||||
getSessionDisplayId: () => "test-session",
|
||||
});
|
||||
wrap(store);
|
||||
const sessionId = "test-session";
|
||||
const record = { user: "owner@example.invalid", accountId: 7, accountEpoch: 42 };
|
||||
let callbacks = 0;
|
||||
const saved = new Promise((resolve, reject) => {
|
||||
store.set(sessionId, record, (error) => {
|
||||
callbacks += 1;
|
||||
if (error) reject(error);
|
||||
else resolve();
|
||||
});
|
||||
});
|
||||
await started;
|
||||
revoked = true;
|
||||
store.destroy(sessionId);
|
||||
commitWrite();
|
||||
await saved;
|
||||
assert.strictEqual(callbacks, 1, "the store completion callback runs exactly once");
|
||||
assert.strictEqual(records.has(sessionId), false, "a late admitted write must not restore a revoked record");
|
||||
});
|
||||
|
||||
test("late promise-style set and touch operations cannot restore revoked records", async () => {
|
||||
for (const method of ["set", "touch"]) {
|
||||
let revoked = false;
|
||||
let commit;
|
||||
let writeStarted;
|
||||
const started = new Promise((resolve) => { writeStarted = resolve; });
|
||||
const records = new Map();
|
||||
const store = {
|
||||
[method]: async (sessionId, record) => {
|
||||
writeStarted();
|
||||
await new Promise((resolve) => { commit = resolve; });
|
||||
records.set(sessionId, record);
|
||||
return record;
|
||||
},
|
||||
destroy: async (sessionId) => { records.delete(sessionId); },
|
||||
};
|
||||
createSessionStoreTombstoneGuard({
|
||||
isSessionSidRevoked: async () => revoked,
|
||||
isRevokedSidTombstoneCachedLocally: () => revoked,
|
||||
getSessionDisplayId: () => "test-session",
|
||||
})(store);
|
||||
const saved = store[method]("test-session", { user: "owner@example.invalid" });
|
||||
await started;
|
||||
revoked = true;
|
||||
await store.destroy("test-session");
|
||||
commit();
|
||||
assert.strictEqual(await saved, undefined);
|
||||
assert.strictEqual(records.has("test-session"), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("store errors and duplicate completion callbacks preserve single-settle behavior", async () => {
|
||||
for (const error of [null, new Error("store-failed")]) {
|
||||
let callbacks = 0;
|
||||
const store = {
|
||||
set: async (sessionId, record, callback) => { callback(error, record); callback(null, record); },
|
||||
destroy: (sessionId, callback) => callback(null),
|
||||
};
|
||||
createSessionStoreTombstoneGuard({
|
||||
isSessionSidRevoked: async () => false,
|
||||
isRevokedSidTombstoneCachedLocally: () => false,
|
||||
getSessionDisplayId: () => "test-session",
|
||||
})(store);
|
||||
const outcome = await new Promise((resolve) => store.set("test-session", {}, (seen) => { callbacks += 1; resolve(seen); }));
|
||||
assert.strictEqual(outcome, error);
|
||||
await Promise.resolve();
|
||||
assert.strictEqual(callbacks, 1);
|
||||
}
|
||||
});
|
||||
|
||||
test("file-mode revocations survive a fresh store instance and expire after their full lifetime", (context) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-session-revocations-"));
|
||||
context.after(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
let now = 1000;
|
||||
const options = { directory, ttlMs: 370 * 24 * 60 * 60 * 1000, now: () => now };
|
||||
const first = createFileSessionRevocations(options);
|
||||
assert.strictEqual(first.has("test-session"), false);
|
||||
assert.strictEqual(first.write("test-session"), true);
|
||||
const restarted = createFileSessionRevocations(options);
|
||||
assert.strictEqual(restarted.has("test-session"), true, "restart must not forget a revoked SID");
|
||||
const filenames = fs.readdirSync(directory);
|
||||
assert.strictEqual(filenames.length, 1);
|
||||
assert.match(filenames[0], /^[a-f0-9]{64}\.json$/);
|
||||
assert.strictEqual(fs.statSync(path.join(directory, filenames[0])).mode & 0o777, 0o600);
|
||||
now += options.ttlMs;
|
||||
assert.strictEqual(restarted.has("test-session"), false);
|
||||
restarted.sweep();
|
||||
assert.deepStrictEqual(fs.readdirSync(directory), []);
|
||||
});
|
||||
|
||||
test("malformed file-mode revocation markers remain revoked and failed writes cannot report success", (context) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-session-revocations-"));
|
||||
context.after(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
const store = createFileSessionRevocations({ directory, ttlMs: 1000 });
|
||||
store.write("test-session");
|
||||
const filename = path.join(directory, fs.readdirSync(directory)[0]);
|
||||
fs.writeFileSync(filename, "{");
|
||||
assert.strictEqual(store.has("test-session"), true, "corruption must not un-revoke a SID");
|
||||
store.sweep();
|
||||
assert.strictEqual(fs.existsSync(filename), true);
|
||||
const failing = createFileSessionRevocations({ directory, ttlMs: 1000, writeFile: () => { throw new Error("disk-full"); } });
|
||||
assert.throws(() => failing.write("other-session"), /disk-full/);
|
||||
});
|
||||
|
||||
test("session regeneration tombstones a live authenticated pre-regeneration sid", () => {
|
||||
// Conscious pin update (adpanel:login-bind-one-true-home): login and the
|
||||
// captcha/2FA completion flow share ONE regenerate inside
|
||||
// utils/login-session-bind.js (created by createLoginSessionBinder);
|
||||
// remember-restore keeps its own in index.js. The assertion strength is
|
||||
// preserved: remember-restore must still regenerate in index.js, the
|
||||
// shared binder must own exactly ONE regenerate for BOTH completion paths
|
||||
// (tests/login-session-bind-module.test.js pins that both paths call it),
|
||||
// and the tombstone-before-regenerate guard must still precede EVERY
|
||||
// regenerate site, now checked across BOTH files.
|
||||
const binderSource = fs.readFileSync(path.join(ROOT, "utils", "login-session-bind.js"), "utf8");
|
||||
const indexRegenerateCount = (indexSource.match(/req\.session\.regenerate\(/g) || []).length;
|
||||
const binderRegenerateCount = (binderSource.match(/req\.session\.regenerate\(/g) || []).length;
|
||||
assert.strictEqual(
|
||||
indexRegenerateCount,
|
||||
1,
|
||||
"remember-restore keeps its regenerate in index.js; the two login completion paths' regenerates live only in the shared binder"
|
||||
);
|
||||
assert.strictEqual(
|
||||
binderRegenerateCount,
|
||||
1,
|
||||
"the shared login-session binder owns exactly ONE regenerate (no parallel copies)"
|
||||
);
|
||||
|
||||
// Every regenerate must be preceded by the conditional tombstone guard:
|
||||
// re-login while authenticated leaves a live authenticated record that an
|
||||
// in-flight request could otherwise re-save after the regenerate destroys
|
||||
// it. Conscious pin update (adpanel:login-bind-preauth-pending-tombstone):
|
||||
// the shared login binder's guard is EXTENDED — pre-auth sids carrying
|
||||
// protected pending auth state (solved captcha / pending captcha login)
|
||||
// are tombstoned too, since a stolen pre-auth cookie with a matching
|
||||
// fingerprint can revive that pending login; bare pre-auth sids stay
|
||||
// skipped (login volume would bloat Redis), and remember-restore's
|
||||
// backstop adopts the same pending-state predicate
|
||||
// (adpanel:login-bind-preauth-pending-tombstone). The exact per-site
|
||||
// conditions are pinned by tests/login-session-bind-module.test.js; the
|
||||
// restore's exact condition and behavior pins live in
|
||||
// tests/remember-restore-and-confirmed-bounds.test.js.
|
||||
for (const [label, source] of [
|
||||
["index.js", indexSource],
|
||||
["utils/login-session-bind.js", binderSource],
|
||||
]) {
|
||||
for (
|
||||
let at = source.indexOf("req.session.regenerate(");
|
||||
at >= 0;
|
||||
at = source.indexOf("req.session.regenerate(", at + 1)
|
||||
) {
|
||||
const window = source.slice(Math.max(0, at - 900), at);
|
||||
assert.match(
|
||||
window,
|
||||
/if \(req\.session\?\.user(?: \|\| sessionCarriesProtectedPendingAuthState\(req\.session\))?\) \{[\s\S]*?writeRevokedSidTombstone\(preRegenerateSid\)/,
|
||||
`every session regeneration in ${label} must tombstone a pre-regeneration sid that is authenticated or carries protected pending auth state first`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user