"use strict"; // Issue 2 (HIGH): "saved browser login" revocation was worker-local. The // remember-login registry was loaded from Redis once per process and never // re-read; revokeRememberLoginRegistryEntry only mutated the per-process // in-memory map and rewrote the WHOLE Redis hash from that snapshot. On the // PM2 cluster topology a revoke processed by worker W1 was invisible to // W2..WN (the revoked adpanel.remember cookie restored a full session // anywhere else), and any stale worker's next whole-hash persist rewrote the // revoked entry back into Redis — durable resurrection. // // The fix makes Redis the source of truth: revoke = targeted HDEL of the one // field + INCR of a registry version key; every write is a per-field, // version-checked HSET (guarded Lua) so a stale worker can never write back // an entry another worker revoked; the in-memory snapshot is guarded by the // version key and reloaded on drift. 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 ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const { REMEMBER_LOGIN_REGISTRY_GUARDED_WRITE_LUA, REVOKED_REMEMBER_LOGIN_TTL_SECONDS } = require("../utils/remember-login-redis"); 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); } test("the whole-hash registry writers are gone — no snapshot rewrites can resurrect", () => { assert.ok( !indexSource.includes("writeRememberLoginRedisHash"), "writeRememberLoginRedisHash (DEL + HSET of the full hash from memory) must not exist anymore" ); assert.ok( !indexSource.includes("persistRememberLoginLegacyCutoffs"), "the legacy-cutoff whole-hash persist must not exist anymore" ); assert.ok( !/multi\.del\(\w*[Kk]ey\)/.test(indexSource), "no remember-login writer may DEL a whole hash built from an in-memory snapshot" ); }); test("revoke is a targeted HDEL plus a version bump, never a hash rewrite", () => { const body = extractRegion( indexSource, "function revokeRememberLoginRegistryEntry(rememberId)", "function findRememberLoginIdBySessionId(sessionId" ); assert.match( body, /deleteRememberLoginRegistryFields\(\[id\]\)/, "the revoke must queue a targeted per-field Redis delete" ); assert.ok( !body.includes("persistRememberLoginRegistry()"), "the revoke must not rewrite the registry hash from this worker's snapshot" ); // adpanel:remember-revoke-durable — the delete used to ride the serialized // write queue fire-and-forget; the queue swallows Redis failures, so a // blip at revocation time left the credential alive on every OTHER worker. // It is now AWAITED directly (bypassing the error-swallowing queue like the // Confirmed twin) — same targeted-HDEL substance, strictly more durable. assert.doesNotMatch(body, /queueRememberLoginRedisPersist/, "the delete must bypass the error-swallowing write queue"); assert.match(body, /await deleteRememberLoginRegistryFields\(\[id\]\)/, "the targeted Redis delete must be awaited, not queued fire-and-forget"); assert.match( body, /const existed = !!rememberLoginRegistry\[id\];/, "the revoke must still delete the local snapshot entry" ); const deleter = extractRegion( indexSource, "async function deleteRememberLoginRegistryFields(fields)", "function queueRememberLoginRedisPersist(" ); assert.match(deleter, /multi\.hDel\(REMEMBER_LOGIN_REGISTRY_REDIS_KEY, id\)/, "exactly the revoked fields must be HDELed"); assert.match( deleter, /multi\.incr\(REMEMBER_LOGIN_REGISTRY_VERSION_REDIS_KEY\)/, "the delete must bump the registry version so every other worker reloads" ); }); test("registry loads are atomic (version, hash) snapshots", () => { const loader = extractRegion( indexSource, "async function loadRememberLoginRegistrySnapshot()", "async function reloadRememberLoginRegistryFromRedis()" ); assert.match( loader, /\.multi\(\)\s*\.get\(REMEMBER_LOGIN_REGISTRY_VERSION_REDIS_KEY\)\s*\.hGetAll\(REMEMBER_LOGIN_REGISTRY_REDIS_KEY\)\s*\.exec\(\)/, "version and hash must be read in one MULTI so a concurrent INCR cannot fake freshness" ); const init = extractRegion( indexSource, "async function initializeRememberLoginStores()", "async function ensureRememberLoginStoreReady()" ); assert.match(init, /loadRememberLoginRegistrySnapshot\(\)/, "the per-process load must use the atomic snapshot"); assert.match( init, /rememberLoginRegistryVersion = redisSnapshot\.version;/, "the observed version must be recorded at load time" ); }); test("freshness gate: version check, reload on drift, single-flight, poller", () => { const body = extractRegion( indexSource, "async function ensureRememberLoginRegistryFresh()", "async function getRememberLoginRegistryRemoteVersion()" ); assert.match(body, /rememberLoginRegistryFreshPromise/, "concurrent checks must be single-flight"); assert.match(body, /remoteVersion === rememberLoginRegistryVersion/, "freshness must be judged by the version key"); assert.match(body, /reloadRememberLoginRegistryFromRedis\(\)/, "version drift must trigger a full reload from Redis"); assert.match(body, /return false;/, "an unverifiable check must report not-fresh so writers refuse"); const poller = extractRegion( indexSource, "setInterval(() => {\n ensureRememberLoginRegistryFresh()", "// Guarded per-field write:" ); assert.match(poller, /REMEMBER_LOGIN_REGISTRY_FRESH_POLL_MS/, "a background poller must re-check idle workers"); }); test("registry writes are per-field and version-guarded (stale worker cannot resurrect)", () => { const lua = REMEMBER_LOGIN_REGISTRY_GUARDED_WRITE_LUA; assert.doesNotMatch(indexSource, /const REMEMBER_LOGIN_REGISTRY_GUARDED_WRITE_LUA = \[/, "the shared module must own the script"); assert.match(lua, /if v ~= ARGV\[1\] then return -1 end/, "the write must be refused when the registry version drifted"); assert.match(lua, /redis\.call\('HSET', KEYS\[2\], ARGV\[2\], ARGV\[3\]\)/, "the write must be a single-field HSET"); assert.match(lua, /redis\.call\('INCR', KEYS\[1\]\)/, "the HSET and the version bump must be atomic in one script"); assert.ok( lua.indexOf("if v ~= ARGV[1] then return -1 end") < lua.indexOf("redis.call('HSET'"), "the version check must gate the HSET" ); const sync = extractRegion( indexSource, "async function syncRememberLoginRegistryToRedis()", "async function initializeRememberLoginStores()" ); assert.match( sync, /snapshot\.version !== rememberLoginRegistryVersion/, "the sync must detect version drift at execution time" ); const driftIdx = sync.indexOf("rememberLoginRegistry = { ...remote, ...preservedMintedEntries };"); const writeIdx = sync.indexOf("guardedRememberLoginRegistryFieldWrite("); // On drift the sync adopts the remote view as the base and may keep only // locally minted entries that are ABSENT remotely — no remote revocation // can target a field that never existed in Redis, so nothing // remotely-revoked can come back. assert.ok(driftIdx > 0 && writeIdx > driftIdx, "on drift the sync must adopt the remote view (plus never-synced local mints) before any guarded write"); assert.match( sync, /locallyMintedRememberLoginIds\.has\(mintedId\) && !remote\[mintedId\]/, "drift preservation must be restricted to locally minted entries that are absent remotely (resurrection-proof)" ); assert.match( sync, /if \(!written\)\s*\{\s*[\s\S]*?return true;/, "a refused guarded write must stop the sync instead of writing blind" ); }); test("all delayed registry writers check identifier and lineage revocation before HSET", () => { const lua = REMEMBER_LOGIN_REGISTRY_GUARDED_WRITE_LUA; assert.ok(lua.indexOf("redis.call('EXISTS', KEYS[3])") < lua.indexOf("redis.call('HSET'")); assert.match(lua, /redis\.call\('EXISTS', KEYS\[4\]\) == 1 then return -2 end/); assert.ok(REVOKED_REMEMBER_LOGIN_TTL_SECONDS > 365 * 24 * 60 * 60, "markers must outlive all remembered credentials"); const writer = extractRegion(indexSource, "async function guardedRememberLoginRegistryFieldWrite(", "async function deleteRememberLoginRegistryFields("); assert.match(writer, /getRevokedRememberLoginRedisKey\(field\)/); assert.match(writer, /getRevokedRememberLoginRedisKey\(entry.lineage \|\| field\)/); assert.match(writer, /if \(Number\(reply\) === -2\) \{[\s\S]*delete rememberLoginRegistry\[field\];[\s\S]*locallyMintedRememberLoginIds.delete\(field\)/); const deleter = extractRegion(indexSource, "async function deleteRememberLoginRegistryFields(", "function queueRememberLoginRedisPersist("); assert.ok(deleter.indexOf("multi.set(getRevokedRememberLoginRedisKey(id)") < deleter.indexOf("multi.hDel("), "targeted revocation must atomically forbid later writes"); }); test("audit sync and normalization propagate targeted writes, not snapshot rewrites", () => { const audit = extractRegion( indexSource, "function syncRememberLoginRegistryAudit(rememberId, audit, email = \"\")", "function isManagedRememberLoginToken(" ); assert.match(audit, /ensureRememberLoginRegistryFresh\(\)/, "the audit write must verify freshness first"); assert.match( audit, /guardedRememberLoginRegistryFieldWrite\(rememberLoginRegistryVersion, id, freshEntry\)/, "the audit update must be a version-guarded single-field write" ); assert.ok( !audit.includes("persistRememberLoginRegistry()"), "the audit sync must not rewrite the whole hash" ); assert.match(audit, /const freshEntry = rememberLoginRegistry\[id\];\s*if \(!freshEntry\) return true;/, "an entry revoked remotely must be dropped, not written back"); const normalize = extractRegion( indexSource, "function normalizeRememberLoginRegistryInMemory()", "async function getBrowserLoginSessionsInventory(" ); assert.match(normalize, /deleteRememberLoginRegistryFields\(droppedIds\)/, "normalization must HDEL exactly the expired entries"); assert.ok(!normalize.includes("persistRememberLoginRegistry()"), "normalization must not rewrite the whole hash"); const cutoff = extractRegion( indexSource, "function setRememberLoginLegacyCutoff(userId)", // Conscious marker update (adpanel:session-inventory-error-propagation): // the user-wide revoke gained the optional additive options sink — the // signature change is mechanical, the cutoff write contract is untouched. "function revokeRememberLoginsForUser(user, options = {})" ); assert.match( cutoff, /redisClient\.hSet\(REMEMBER_LOGIN_LEGACY_CUTOFF_REDIS_KEY, id, String\(cutoff\)\)/, "legacy cutoffs must be written per field" ); }); test("validation never trusts stale memory: the restore path awaits the freshness gate", () => { // Anchor on the unique remember middleware body (the other // ensureRememberLoginStoreReady call site is the startup pre-flight), and // end at the middleware that follows it so the restore call stays inside. const rememberMw = extractRegion( indexSource, 'await ensureRememberLoginStoreReady();\n // The remember-cookie validation/restore below must not trust this', "if (req._staticAsset || !req.session?.user) return next();" ); const freshIdx = rememberMw.indexOf("await ensureRememberLoginRegistryFresh();"); const cookieIdx = rememberMw.indexOf("await ensureRememberLoginCookie(req, res);"); const restoreIdx = rememberMw.indexOf("await restoreRememberedLogin(req, res);"); assert.ok(freshIdx >= 0, "the remember middleware must await the registry freshness gate"); assert.ok(cookieIdx > freshIdx, "ensureRememberLoginCookie must run after the freshness gate"); assert.ok(restoreIdx > freshIdx, "restoreRememberedLogin must run after the freshness gate"); const getter = extractRegion( indexSource, "function getRememberLoginRegistryEntry(rememberId)", "function ensureRememberLoginSessionId(req)" ); assert.match( getter, /ensureRememberLoginRegistryFresh\(\)\.catch\(\(\) => false\);/, "registry reads kick the single-flight freshness check before trusting memory" ); assert.match( getter, /deleteRememberLoginRegistryFields\(\[id\]\)/, "expired entries are removed with a targeted delete" ); }); test("user-wide revocation also sweeps the Redis hash for entries this worker never saw", () => { const body = extractRegion( indexSource, // Conscious marker update (adpanel:session-inventory-error-propagation): // optional additive options sink added to the signature. "function revokeRememberLoginsForUser(user, options = {})", "function getRememberLoginRegistryEntry(rememberId)" ); assert.match(body, /deleteRememberLoginRegistryFields\(revokedIds\)/, "known entries are HDELed individually"); assert.match( body, /redisClient\.hGetAll\(REMEMBER_LOGIN_REGISTRY_REDIS_KEY\)/, "a user-wide revoke must sweep the hash itself: entries created on other workers are invisible to local memory" ); assert.ok(!body.includes("persistRememberLoginRegistry()"), "the user-wide revoke must not rewrite the whole hash"); }); test("suspension, password-change/account-delete eviction and logout revoke through the shared cluster-safe functions", () => { const suspension = extractRegion( indexSource, "if (req._staticAsset || !req.session?.user) return next();", "// Middleware to ensure session TTL is refreshed" ); // Conscious pin update (adpanel:remember-logout-lineage, WAVE-3): the // suspension branch's single-id revoke was upgraded to the lineage-scoped // helper — a rotation committing between the user-wide sweep's hGetAll // read and its HDEL batch would otherwise leave a milliseconds-rotated // replacement live exactly when the account is being suspended (the // compromise-response path). Strength preserved (strengthened): suspension // still revokes through the shared, cluster-safe machinery (targeted HDEL // + version bump inside the lineage helper, never a raw Redis call), and // the user-wide sweep stays UNCONDITIONAL right after it — the two // compose (lineage closes the rotate race; the sweep covers chains this // worker's snapshot cannot see). assert.match(suspension, /revokeRememberLoginLineage\(rememberLoginId/, "suspension revokes the session's saved login — whole rotation lineage — via the shared function"); assert.match(suspension, /revokeRememberLoginsForUser\(user\)/, "suspension revokes all of the user's saved logins via the shared function"); const logout = extractRegion( indexSource, 'app.post("/logout"', "const ENV_FILE_PATH" ); // Conscious pin update (adpanel:remember-logout-lineage): logout's revoke // was upgraded from the single-id helper to the lineage-scoped helper — the // single-id call text could no longer survive the rotation race it exists // to close. Assertion strength preserved (strengthened): logout must revoke // through the shared cluster-safe lineage machinery, which itself performs // the targeted HDEL + version bump (pinned in // tests/remember-logout-lineage.test.js), and must NOT bypass it with raw // Redis calls. assert.match(logout, /await revokeRememberLoginLineage\(rememberLoginId/, "logout revokes the saved login — whole rotation lineage — via the shared function"); assert.doesNotMatch(logout, /redisClient\.sendCommand/, "logout must not issue raw Redis calls itself"); const evict = extractRegion( indexSource, "async function destroyBrowserSessionsForUser(", "function hashDestructiveActionGraceValue(" ); // Conscious regex update (adpanel:session-inventory-error-propagation): // the user-wide revoke call now passes the additive onError sink; same // shared function, same unconditional-first position. assert.match(evict, /revokeRememberLoginsForUser\(user, \{/, "bulk eviction revokes saved logins via the shared function"); // Conscious pin update (adpanel:remember-logout-lineage): the per-target // revoke was upgraded to the lineage-scoped helper (a cache record's // identifier can already have been rotated away — the replacement must die // with the eviction). Strength preserved: still the shared, cluster-safe // revoke machinery, never a raw Redis call. assert.match(evict, /revokeRememberLoginLineage\(rememberLoginId/, "bulk eviction revokes per-session saved logins — whole rotation lineage — via the shared function"); });