"use strict"; // adpanel:remember-logout-lineage — the rotation-lineage revocation fix. // // THE RACE (review Finding 1, P1): POST /logout revoked exactly ONE // identifier — the session snapshot's rememberLoginId. The silent refresh CAS // (REMEMBER_LOGIN_ROTATE_LUA: HSET new + HDEL old + INCR version) can swap the // presented identifier for a fresh one while the logout is in flight (another // tab refreshes; the logout request's session snapshot still holds the old // id). The replacement then SURVIVED logout, and restoreRememberedLogin // authenticated successfully with it. // // THE FIX: every registry entry carries `lineage` — the identifier of the // FIRST mint of its rotation chain (fresh mints stamp their own id, rotations // inherit, legacy entries degrade to their own id). The rotation CAS // propagates it ATOMICALLY (the Lua refuses a swap whose new entry claims a // different lineage than the Redis-side old entry's, and maintains a // per-lineage SET of live members in the same script), and revocation is // LINEAGE-scoped: revokeRememberLoginLineage(rememberId, hints) kills the // presented id AND every same-chain entry cluster-wide (one Lua: // SMEMBERS → HDEL members + presented → DEL set → INCR version). // // Why the per-lineage SET (not an in-Lua scan of the registry hash): Redis // executes Lua single-threaded; the registry hash holds every live remember // login cluster-wide, so HGETALL+filter inside a script would block ALL Redis // commands per revocation. The set holds exactly the chain's LIVE members // (the rotation SREMs the replaced id), so it stays O(1)-ish per chain, and a // zero-rotation chain needs no set at all (its only member is the presented // id, which the revoke script always HDELs directly). // // No NEW member can ever join a dead lineage: rotating a revoked id fails the // CAS (its field is gone → -1), a mint always creates a fresh id and hence a // fresh lineage, and 18-byte random identifiers never collide — so DELeting // the set at revocation time is final. // // Pins held here: // 1. Source: the Lua propagates lineage atomically (lineage check BEFORE // any write, set maintenance AFTER the CAS gate), the mint/normalizer/ // session stamps exist, the lineage revoke helper carries the twin's // contract (never rejects, DLQ on failure, bounded EVAL, file-store // branch), and logout + bulk eviction call it. // 2. Behavior (fake Redis executing the REAL scripts' semantics; the fake // asserts script identity so the JS mirror cannot drift): the review's // race — rotate while logout is in flight, then revoke the OLD id — the // REPLACEMENT dies; a mid-chain logout kills the whole chain; legacy // entries degrade to single-id; file-store mode mirrors the semantics; // Redis failure/timeout dead-letter and still resolve; restore needs NO // new check (a lineage-revoked replacement fails closed through // isManagedRememberLoginToken, and the adoption branch only adopts LIVE // entries). 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 { REMEMBER_LOGIN_LINEAGE_REVOKE_LUA: LINEAGE_REVOKE_LUA, REMEMBER_LOGIN_REGISTRY_GUARDED_WRITE_LUA: WRITE_LUA, REVOKED_REMEMBER_LOGIN_TTL_SECONDS, getRevokedRememberLoginRedisKey } = require("../utils/remember-login-redis"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); // Brace-balanced extraction (same shape as tests/remember-rotation-bounded.test.js): // skips // and /* */ comments so the adpanel: comment convention cannot // desync the brace tracker. function extractBlock(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker not found: ${startMarker}`); let i = start + startMarker.length; let depth; if (startMarker.endsWith("{")) { depth = 1; } else { while (i < source.length && /\s/.test(source[i])) i += 1; assert.ok(i < source.length && source[i] === "{", `no opening brace after: ${startMarker}`); depth = 1; } let inString = null; while (i < source.length && depth > 0) { i += 1; const ch = source[i]; if (inString) { if (ch === "\\") { i += 1; continue; } if (ch === inString) inString = null; continue; } if (ch === "/" && source[i + 1] === "/") { while (i < source.length && source[i] !== "\n") i += 1; continue; } if (ch === "/" && source[i + 1] === "*") { i += 2; while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i += 1; i += 1; continue; } if (ch === '"' || ch === "'" || ch === "`") inString = ch; else if (ch === "{") depth += 1; else if (ch === "}") depth -= 1; } assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`); return source.slice(start, i + 1); } 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 ROTATE_SOURCE = extractBlock(indexSource, "async function rotateRememberLoginCookie(req, res, user, parsedToken) {"); const LINEAGE_REVOKE_SOURCE = extractBlock(indexSource, "async function revokeRememberLoginLineage(rememberId, hints = null) {"); const MANAGED_SOURCE = extractBlock(indexSource, "function isManagedRememberLoginToken(parsedToken, user = null) {"); const UPSERT_SOURCE = extractBlock(indexSource, "function upsertRememberLoginRegistryEntry(req, user, expiresAt, issuedAt = Date.now()) {"); const NORMALIZER_SOURCE = extractBlock(indexSource, "function normalizeRememberLoginRegistry(raw) {"); const RESTORE_SOURCE = extractBlock(indexSource, "async function restoreRememberedLogin(req, res) {"); const WRITE_SOURCE = extractBlock(indexSource, "async function guardedRememberLoginRegistryFieldWrite(expectedVersion, field, entry) {"); // The REAL Lua scripts, evaluated out of index.js so the fake Redis can // assert script identity (the JS mirrors below then cannot drift from the // shipped scripts without failing here). function extractLua(source, startMarker) { const marker = source.indexOf(startMarker); assert.ok(marker >= 0, `lua start not found: ${startMarker}`); const arrayStart = source.indexOf("[", marker); assert.ok(arrayStart > marker, `lua array not found after: ${startMarker}`); const joinEnd = '].join("\\n");'; const end = source.indexOf(joinEnd, arrayStart); assert.ok(end > arrayStart, `lua join not found after: ${startMarker}`); // The array literal THROUGH the .join call (minus the statement // terminator) — an expression, evaluable as-is. return vm.runInNewContext(`(${source.slice(arrayStart, end + joinEnd.length - 1)})`, {}, { filename: "lua-extract.js" }); } const ROTATE_LUA = extractLua(indexSource, "const REMEMBER_LOGIN_ROTATE_LUA = ["); // --------------------------------------------------------------------------- // Source pins // --------------------------------------------------------------------------- test("the rotation Lua propagates the lineage atomically (check before any write, set writes after the CAS gate)", () => { // The lineage is read from the ACTUAL Redis-side old entry (defaulting to // the presented id — the chain's first mint) and the swap is refused (-2) // when the JS-provided new entry claims a different chain. assert.match( ROTATE_LUA, /local lineage = tostring\(oldEntry\.lineage or ARGV\[1\]\)/, "the new entry's lineage must be anchored to the Redis-side old entry (or the presented id)" ); assert.match( ROTATE_LUA, /if tostring\(newEntry\.lineage or ''\) ~= lineage then return -2 end/, "a lineage disagreement must fail the CAS closed (-2), never split the chain" ); // CAS gate first: no set/registry write can happen for a dead or foreign // presented id — no NEW member can join a (dead) lineage. const casGateIdx = ROTATE_LUA.indexOf("if not old then return -1 end"); const uidGateIdx = ROTATE_LUA.indexOf("tostring(oldEntry.uid) ~= ARGV[2]"); const lineageCheckIdx = ROTATE_LUA.indexOf("return -2 end"); const hsetIdx = ROTATE_LUA.indexOf("redis.call('HSET'"); const saddIdx = ROTATE_LUA.indexOf("redis.call('SADD'"); assert.ok(casGateIdx >= 0 && casGateIdx < uidGateIdx && uidGateIdx < lineageCheckIdx && lineageCheckIdx < hsetIdx && hsetIdx < saddIdx, "order must be: existence gate → uid gate → lineage check → registry swap → set maintenance"); // The per-lineage set maintenance rides the SAME atomic script: a // concurrent lineage revocation either fully precedes (CAS fails) or fully // follows (the fresh id is already a set member). assert.match(ROTATE_LUA, /redis\.call\('SADD', KEYS\[3\], ARGV\[3\]\)/, "the fresh identifier must join the lineage set"); assert.match(ROTATE_LUA, /redis\.call\('SREM', KEYS\[3\], ARGV\[1\]\)/, "the replaced identifier must leave the lineage set (live-members-only sets stay bounded)"); assert.match(ROTATE_LUA, /redis\.call\('EXPIRE', KEYS\[3\], ARGV\[5\]\)/, "the set TTL must be re-anchored on every rotation"); assert.match(ROTATE_LUA, /redis\.call\('HDEL', KEYS\[2\], ARGV\[1\]\)/, "the CAS must keep HDELing the presented id (never both live)"); assert.match(ROTATE_LUA, /redis\.call\('INCR', KEYS\[1\]\)/, "the version bump must stay part of the atomic script"); assert.ok( !ROTATE_LUA.includes("withTimeout") && !ROTATE_LUA.includes("REMEMBER_ROTATION"), "the bound wraps the client await, not the script" ); }); test("mint, re-issue and normalization carry the chain lineage; the session stamps it", () => { // Behavior: normalization passes a present lineage through and leaves a // legacy entry's lineage ABSENT (never an empty string into Redis). const normSandbox = { Date: { now: () => Date.now() } }; vm.createContext(normSandbox); const normalizeFn = vm.runInContext(`(${NORMALIZER_SOURCE})`, normSandbox, { filename: "normalizer-sandbox.js" }); const normalized = normalizeFn({ "live-chain": { uid: "1", email: "a@x.test", lineage: "chain-root-token", expiresAt: Date.now() + 86400000 }, "legacy-entry": { uid: "1", email: "a@x.test", expiresAt: Date.now() + 86400000 }, }); assert.strictEqual(normalized["live-chain"].lineage, "chain-root-token", "a present lineage survives normalization"); assert.ok(!("lineage" in normalized["legacy-entry"]), "a legacy entry keeps its lineage ABSENT (no empty-string write-back)"); // Fresh mints START the chain at their own id; a re-issued known id KEEPS // its lineage (re-grants never split the chain). assert.match( UPSERT_SOURCE, /const entryLineage = isNewRememberLoginMint\s*\n\s*\? rememberId\s*\n\s*: \(String\(rememberLoginRegistry\[rememberId\]\?\.lineage \|\| ""\)\.trim\(\) \|\| rememberId\);/, "fresh mints stamp their own id, re-issued ids keep their chain" ); assert.match(UPSERT_SOURCE, /lineage: entryLineage,/, "the entry literal must carry the lineage"); // The normalizer must PRESERVE a present lineage across snapshot // loads/syncs (a stripped field would silently degrade every lineage // revocation) — and must keep a LEGACY entry's absence as absence: writing // `"lineage":""` back (an audit sync does) would desync the rotation CAS's // Lua-truthiness check and permanently refuse that chain's rotations. assert.match( NORMALIZER_SOURCE, /\.\.\.\(entry\.lineage \? \{ lineage: String\(entry\.lineage\)\.trim\(\) \} : \{\}\)/, "normalization carries a present lineage through and keeps a legacy absence as absence" ); // Session stamps: mint (own id), rotation (inherited), adoption (the // adopted entry's own chain). assert.match( extractBlock(indexSource, "function ensureRememberLoginSessionId(req) {"), /req\.session\.rememberLoginLineage = rememberId;/, "a fresh mint must stamp the session's lineage" ); assert.match( ROTATE_SOURCE, /req\.session\.rememberLoginLineage = entry\.lineage;/, "commitRotation must re-point the session's lineage stamp at the chain" ); const adoptionBlock = extractBlock(indexSource, "if (\n parsed &&\n parsed.jti &&\n parsed.jti !== sessionRememberId &&\n isManagedRememberLoginToken(parsed, resolvedUser)\n ) {"); assert.match( adoptionBlock, /req\.session\.rememberLoginLineage = String\(rememberLoginRegistry\[parsed\.jti\]\?\.lineage \|\| parsed\.jti\)\.trim\(\) \|\| parsed\.jti;/, "the adoption branch must re-stamp from the adopted entry's own chain" ); }); test("the lineage revoke helper carries the single-entry twin's contract", () => { assert.match( LINEAGE_REVOKE_SOURCE, /^async function revokeRememberLoginLineage\(rememberId, hints = null\) \{/, "awaited, additive hints object" ); assert.match( LINEAGE_REVOKE_SOURCE, /if \(!redisClient\) \{/, "file-store mode must short-circuit: the local lineage scan IS the durable revocation there" ); assert.match( LINEAGE_REVOKE_SOURCE, /await withTimeout\(\s*\n\s*redisClient\.sendCommand\(\[\s*\n\s*"EVAL",\s*\n\s*REMEMBER_LOGIN_LINEAGE_REVOKE_LUA,/, "the lineage EVAL must be time-bounded like every revocation write" ); assert.match( LINEAGE_REVOKE_SOURCE, /REMEMBER_REVOKE_WRITE_TIMEOUT_MS,\s*\n\s*REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL/, "the bound must be the shared revocation knob + label" ); assert.doesNotMatch( LINEAGE_REVOKE_SOURCE, /queueRememberLoginRedisPersist/, "the revoke must bypass the error-swallowing write queue" ); // Never rejects: every failure path returns the existed boolean after // dead-lettering the presented id AND the locally-known chain members. const catchIdx = LINEAGE_REVOKE_SOURCE.indexOf("} catch (err) {"); assert.ok(catchIdx >= 0, "the EVAL must keep a failure catch"); const catchBody = LINEAGE_REVOKE_SOURCE.slice(catchIdx); assert.ok( catchBody.indexOf("enqueueRememberRevocationDeadLetter([id, ...lineageMemberIds]);") >= 0 && catchBody.indexOf("return existed;") > catchBody.indexOf("enqueueRememberRevocationDeadLetter([id, ...lineageMemberIds]);"), "a failed lineage revoke must dead-letter presented + known members, then return existed (never reject)" ); const unavailableIdx = LINEAGE_REVOKE_SOURCE.indexOf("if (!deleted) {"); assert.ok( unavailableIdx > catchIdx && LINEAGE_REVOKE_SOURCE.slice(unavailableIdx).includes("enqueueRememberRevocationDeadLetter([id, ...lineageMemberIds]);"), "the unavailable (timeout/false) path must dead-letter the same set" ); // The chain resolution order: live entry → session stamp → the id itself // (legacy degrade, never worse than the single-id twin). const resolveIdx = LINEAGE_REVOKE_SOURCE.indexOf("let lineage = String(presentedEntry?.lineage || hints?.lineageHint || \"\").trim();"); assert.ok(resolveIdx >= 0, "the lineage resolution must prefer the live entry, then the session stamp"); }); test("logout and bulk eviction revoke the whole lineage; the restore gate stays registry-absence-based", () => { const logout = extractRegion(indexSource, 'app.post("/logout"', "const ENV_FILE_PATH"); assert.match(logout, /await revokeRememberLoginLineage\(rememberLoginId, \{/, "logout must use the lineage-scoped revoke"); const destroyFn = extractBlock(indexSource, "async function destroyBrowserSessionsForUser(user, options = {}) {"); // Conscious update (adpanel:remember-logout-lineage): the record's lineage // stamp rides the cache record as lineageHint so a MID-CHAIN rotated-away // id still names its chain's set — same existed-based contract. assert.match(destroyFn, /await revokeRememberLoginLineage\(rememberLoginId, \{ emailHint: String\(entry\?\.email \|\| ""\), lineageHint: String\(entry\?\.lineage \|\| ""\)\s*\}\)/, "bulk eviction must use the lineage-scoped revoke"); // (f) The restore path needs NO new check: a lineage-revoked replacement // simply no longer EXISTS in the registry, and the existing gate // (isManagedRememberLoginToken → getRememberLoginRegistryEntry) fails // closed on absence. Pin the gate exactly as shipped — adding a lineage // check here would be a second implementation of the same responsibility. assert.match( RESTORE_SOURCE, /if \(parsed\.jti && !isManagedRememberLoginToken\(parsed, user\)\) \{/, "the restore's registry-absence gate is the fail-closed mechanism" ); assert.ok(!RESTORE_SOURCE.includes("Lineage"), "restore must not gain a parallel lineage check (one responsibility, one implementation)"); // ...and the adoption branch adopts only LIVE entries (a lineage-revoked id // fails the same gate and falls through to the fail-closed clear). assert.match( extractBlock(indexSource, "async function ensureRememberLoginCookie(req, res, user = null) {"), /parsed\.jti !== sessionRememberId &&\s*\n\s*isManagedRememberLoginToken\(parsed, resolvedUser\)/, "adoption requires a live registry entry" ); }); // --------------------------------------------------------------------------- // Behavior pins — fake Redis executing the REAL scripts' semantics // --------------------------------------------------------------------------- // Lua-truthiness helpers: Redis Lua's `or` treats only nil/false as falsy // (an empty STRING is truthy), so the mirrors must not use JS's ??. function luaOr(value, fallback) { return value === undefined || value === null || value === false ? fallback : String(value); } // JS mirror of REMEMBER_LOGIN_ROTATE_LUA (identity-asserted against the real // script text in the fake sendCommand below). function runRotateLua(store, keys, args) { const [, registryKey, setKey] = keys; const [oldId, uid, newId, entryJson, ttlSeconds] = args; const oldRaw = store.hash[registryKey]?.[oldId]; // HGET KEYS[2] ARGV[1] if (oldRaw === undefined) return "-1"; let oldEntry; try { oldEntry = JSON.parse(oldRaw); } catch { return "-1"; } if (!oldEntry || typeof oldEntry !== "object" || String(oldEntry.uid) !== uid) return "-1"; let newEntry; try { newEntry = JSON.parse(entryJson); } catch { return "-1"; } if (!newEntry || typeof newEntry !== "object") return "-1"; const lineage = luaOr(oldEntry.lineage, oldId); // oldEntry.lineage or ARGV[1] if (luaOr(newEntry.lineage, "") !== lineage) return "-2"; store.hash[registryKey][newId] = entryJson; // HSET delete store.hash[registryKey][oldId]; // HDEL const set = store.sets[setKey] || (store.sets[setKey] = new Set()); set.add(newId); // SADD set.delete(oldId); // SREM store.ttls[setKey] = Number(ttlSeconds); // EXPIRE store.version += 1; // INCR return "1"; } // JS mirror of REMEMBER_LOGIN_LINEAGE_REVOKE_LUA. function runLineageRevokeLua(store, keys, args) { const [, registryKey, setKey, lineageMarkerKey, idMarkerKey] = keys; const [presentedId, ttlSeconds] = args; store.strings[lineageMarkerKey] = "1"; store.strings[idMarkerKey] = "1"; store.ttls[lineageMarkerKey] = Number(ttlSeconds); store.ttls[idMarkerKey] = Number(ttlSeconds); const set = store.sets[setKey]; const members = set ? Array.from(set) : []; for (const member of members) delete store.hash[registryKey][member]; // HDEL members delete store.hash[registryKey][presentedId]; // HDEL presented (even when never rotated) delete store.sets[setKey]; // DEL store.version += 1; // INCR return "1"; } function runWriteLua(store, keys, args) { const [, registryKey, idMarkerKey, lineageMarkerKey] = keys; const [expectedVersion, rememberId, entryJson] = args; if (String(store.version) !== expectedVersion) return "-1"; if (store.strings[idMarkerKey] || store.strings[lineageMarkerKey]) return "-2"; const registry = store.hash[registryKey] || (store.hash[registryKey] = {}); registry[rememberId] = entryJson; store.version += 1; return "1"; } // Real race semantics (verbatim discipline from tests/remember-revoke-durable.test.js). function sandboxWithTimeout(promise, ms, label = "timeout") { let timer; return Promise.race([ Promise.resolve(promise), new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(label)), ms); }), ]).finally(() => clearTimeout(timer)); } function makeFakeRedis({ sendCommandImpl } = {}) { const store = { hash: {}, sets: {}, strings: {}, ttls: {}, version: 0 }; const evalCalls = []; const redisClient = { isOpen: true, sendCommand: async (cmd) => { evalCalls.push(cmd); if (sendCommandImpl) return sendCommandImpl(cmd, store); if (cmd[0] !== "EVAL") throw new Error(`fake redis: unsupported ${cmd[0]}`); const script = String(cmd[1]); const numkeys = Number(cmd[2]); const keys = cmd.slice(3, 3 + numkeys).map(String); const args = cmd.slice(3 + numkeys).map(String); // Script identity: the mirrors below implement EXACTLY the shipped // scripts — a Lua edit without a mirror update fails here. if (script === ROTATE_LUA) return [runRotateLua(store, keys, args)]; if (script === LINEAGE_REVOKE_LUA) return [runLineageRevokeLua(store, keys, args)]; if (script === WRITE_LUA) return [runWriteLua(store, keys, args)]; throw new Error("fake redis: unknown script"); }, }; redisClient.__store = store; return { redisClient, store, evalCalls }; } const HARNESS_NOW = Date.now(); const ANCHOR = HARNESS_NOW + 200 * 24 * 60 * 60 * 1000; // 200d remaining anchor const USER = { id: 1, email: "user@example.test", password: "x" }; function buildRotateHarness({ redisClient }) { const MINT_ID = "chain-root-0000000001"; const registry = { [MINT_ID]: { uid: "1", sid: "sess-1", lineage: MINT_ID, // a fresh mint stamps its own id (post-deploy entry) email: USER.email, issuedAt: HARNESS_NOW - 60000, expiresAt: ANCHOR, absoluteExpiresAt: ANCHOR, }, }; // Seed the fake Redis hash to mirror the worker's snapshot (the realistic // cluster state: this entry was minted and synced earlier); the per-lineage // set does NOT exist yet — a zero-rotation chain has no set (its only // member is the presented id itself, which the revoke script always HDELs // directly). if (redisClient && redisClient.__store) { redisClient.__store.hash["adpanel:remember-logins:v1"] = { [MINT_ID]: JSON.stringify(registry[MINT_ID]), }; } const req = { sessionID: "sess-1", session: { rememberLoginId: MINT_ID, rememberLoginLineage: MINT_ID, browserSessionAudit: { rememberLoginId: MINT_ID } }, get: () => "test-agent", }; const cookies = []; const res = { cookie: (name, value, options) => cookies.push([name, value, options]), clearCookie: () => {} }; const sandbox = { console: { log: () => {}, warn: () => {} }, crypto: require("node:crypto"), getRememberLoginFingerprint: () => "fp", safeCompare: (left, right) => left === right, REMEMBER_LOGIN_MAX_AGE_MS: 365 * 24 * 60 * 60 * 1000, REMEMBER_LOGIN_COOKIE_NAME: "adpanel.remember", REMEMBER_LOGIN_ROTATE_LUA: ROTATE_LUA, REMEMBER_LOGIN_REGISTRY_VERSION_REDIS_KEY: "adpanel:remember-registry:ver", REMEMBER_LOGIN_REGISTRY_REDIS_KEY: "adpanel:remember-logins:v1", REMEMBER_LOGIN_LINEAGE_SET_REDIS_PREFIX: "adpanel:remember-lineage:", REMEMBER_LOGIN_LINEAGE_SET_TTL_SECONDS: 31622400, isValidRememberLoginId: (id) => !!String(id || "").trim() && String(id).length <= 128 && /^[A-Za-z0-9_-]+$/.test(String(id)), resolveRememberLoginAnchorMs: (oldEntry) => { const anchored = Number(oldEntry?.absoluteExpiresAt || oldEntry?.expiresAt || 0); return Number.isFinite(anchored) && anchored > 0 ? anchored : 0; }, getRequestIp: () => "203.0.113.9", normalizeBrowserSessionAudit: (existing, seed) => ({ createdAt: seed.createdAt, lastSeenAt: seed.lastSeenAt, userAgent: seed.userAgent, firstIp: seed.firstIp, lastIp: seed.lastIp, rememberLoginId: seed.rememberLoginId, }), buildRememberLoginToken: (u, rememberId, issuedAt, expiresAt) => `tok.${rememberId}`, getRememberLoginCookieOptions: () => ({ httpOnly: true, path: "/" }), rememberLoginRegistry: registry, rememberLoginRegistryFreshCheckedAt: 12345, redisClient: redisClient === undefined ? makeFakeRedis().redisClient : redisClient, withTimeout: sandboxWithTimeout, REMEMBER_ROTATION_WRITE_TIMEOUT_MS: 40, REMEMBER_ROTATION_WRITE_TIMEOUT_LABEL: "remember-rotation-write-timeout", req, res, cookies, }; vm.createContext(sandbox); const fn = vm.runInContext(`(${ROTATE_SOURCE})`, sandbox, { filename: "rotate-lineage-sandbox.js" }); return { fn, registry, req, res, cookies, sandbox, mintId: MINT_ID }; } function makeParsed(jti, iat) { return { v: 2, uid: "1", iat, exp: ANCHOR, fp: "fp", jti }; } function buildLineageHarness({ registry, redisClient, deadLetterSink, timeoutMs = 40 }) { const warnings = []; const sandbox = { console: { log: () => {}, warn: (...a) => warnings.push(a.map(String).join(" ")) }, rememberLoginRegistry: registry, redisClient, isValidRememberLoginId: (id) => !!String(id || "").trim() && String(id).length <= 128 && /^[A-Za-z0-9_-]+$/.test(String(id)), REMEMBER_LOGIN_REGISTRY_VERSION_REDIS_KEY: "adpanel:remember-registry:ver", REMEMBER_LOGIN_REGISTRY_REDIS_KEY: "adpanel:remember-logins:v1", REMEMBER_LOGIN_LINEAGE_SET_REDIS_PREFIX: "adpanel:remember-lineage:", REMEMBER_LOGIN_LINEAGE_REVOKE_LUA: LINEAGE_REVOKE_LUA, REVOKED_REMEMBER_LOGIN_TTL_SECONDS, getRevokedRememberLoginRedisKey, REMEMBER_REVOKE_WRITE_TIMEOUT_MS: timeoutMs, REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL: "remember-revoke-write-timeout", withTimeout: sandboxWithTimeout, enqueueRememberRevocationDeadLetter: (ids) => { for (const id of Array.isArray(ids) ? ids : [ids]) sandbox.__deadLettered.push(String(id)); }, getRememberLoginDisplayId: (id) => `saved:${id}`, __deadLettered: [], }; vm.createContext(sandbox); const fn = vm.runInContext(`(${LINEAGE_REVOKE_SOURCE})`, sandbox, { filename: "lineage-revoke-sandbox.js" }); return { fn, registry, warnings, sandbox }; } test("THE RACE: a replacement rotated while logout is in flight dies with the presented id", async () => { // 1. Mint M exists (lineage M). A silent refresh rotates M → R via the REAL // CAS semantics on the fake Redis. const fake = makeFakeRedis(); const rot = buildRotateHarness({ redisClient: fake.redisClient }); const expiresAt = await rot.fn(rot.req, rot.res, USER, makeParsed(rot.mintId, HARNESS_NOW - 60000)); assert.ok(expiresAt > 0, "the rotation must succeed"); const newIds = Object.keys(rot.registry).filter((id) => id !== rot.mintId); assert.strictEqual(newIds.length, 1, "exactly one fresh identifier"); const replacementId = newIds[0]; assert.strictEqual(rot.registry[replacementId].lineage, rot.mintId, "the rotated entry inherited the chain lineage"); assert.ok(!(rot.mintId in rot.registry), "the presented id is gone (CAS HDEL)"); assert.deepStrictEqual(Array.from(fake.store.sets[`adpanel:remember-lineage:${rot.mintId}`] || []), [replacementId], "the lineage set holds exactly the live member"); // 2. The logout request's session snapshot STILL holds the old id (it was // loaded before the rotating tab's save): logout-style lineage revocation // of the OLD id must kill the replacement too. const registry = { ...rot.registry }; const harness = buildLineageHarness({ registry, redisClient: fake.redisClient }); const existed = await harness.fn(rot.mintId, { uidHint: "1", emailHint: USER.email, lineageHint: rot.mintId }); assert.strictEqual(existed, false, "the presented (stale) id was already rotated away"); assert.ok(!(replacementId in registry), "THE FIX: the replacement must NOT survive logout"); assert.deepStrictEqual(Object.keys(fake.store.hash["adpanel:remember-logins:v1"] || {}), [], "the cluster-wide registry hash must be empty after the lineage revoke"); assert.strictEqual(fake.store.sets[`adpanel:remember-lineage:${rot.mintId}`], undefined, "the lineage set is DELeted (no member can rejoin a dead chain)"); // 3. The replacement therefore fails closed through the REAL managed-token // gate (restore needs no new check — the entry is simply gone). const managedSandbox = { getRememberLoginRegistryEntry: (id) => registry[id] || null, Date: { now: () => Date.now() }, }; vm.createContext(managedSandbox); const isManaged = vm.runInContext(`(${MANAGED_SOURCE})`, managedSandbox, { filename: "managed-sandbox.js" }); assert.strictEqual(isManaged(makeParsed(replacementId, HARNESS_NOW), USER), false, "a lineage-revoked replacement must fail isManagedRememberLoginToken (restore fails closed)"); }); test("a mid-chain logout kills the whole chain (two rotations, revoke the dead middle id)", async () => { const fake = makeFakeRedis(); const rot1 = buildRotateHarness({ redisClient: fake.redisClient }); await rot1.fn(rot1.req, rot1.res, USER, makeParsed(rot1.mintId, HARNESS_NOW - 60000)); const r1 = Object.keys(rot1.registry).find((id) => id !== rot1.mintId); // Second rotation: R1 → R2 (the session/cookie now bind R1). rot1.req.session.rememberLoginId = r1; const parsedR1 = makeParsed(r1, HARNESS_NOW - 30000); const ok = await rot1.fn(rot1.req, rot1.res, USER, parsedR1); assert.ok(ok > 0, "the second rotation must succeed"); const r2 = Object.keys(rot1.registry).find((id) => id !== r1); assert.strictEqual(rot1.registry[r2].lineage, rot1.mintId, "the whole chain shares one lineage"); // Logout from a tab whose snapshot still holds R1 (dead, rotated away) and // the chain stamp M: the LIVE replacement R2 must die with it. const registry = { ...rot1.registry }; const harness = buildLineageHarness({ registry, redisClient: fake.redisClient }); await harness.fn(r1, { uidHint: "1", lineageHint: rot1.mintId }); assert.deepStrictEqual(Object.keys(registry), [], "the whole chain is dead from a mid-chain id"); assert.deepStrictEqual(Object.keys(fake.store.hash["adpanel:remember-logins:v1"] || {}), [], "cluster-wide: the whole chain is dead"); }); test("a legacy entry without lineage degrades to single-id revocation (never worse than the twin)", async () => { const fake = makeFakeRedis(); const legacyId = "legacy-id-pre-lineage"; const otherUserId = "other-user-chain-root"; fake.store.hash["adpanel:remember-logins:v1"] = { [legacyId]: JSON.stringify({ uid: "1", email: USER.email }), // pre-deploy entry: NO lineage field [otherUserId]: JSON.stringify({ uid: "2", lineage: otherUserId }), }; fake.store.sets[`adpanel:remember-lineage:${otherUserId}`] = new Set([otherUserId]); const registry = { [legacyId]: { uid: "1", email: USER.email }, // local snapshot: no lineage [otherUserId]: { uid: "2", lineage: otherUserId }, }; const harness = buildLineageHarness({ registry, redisClient: fake.redisClient }); // No live-entry lineage, no session stamp → the id itself is the chain. const existed = await harness.fn(legacyId, {}); assert.strictEqual(existed, true, "the presented legacy entry existed"); assert.ok(!(legacyId in registry), "the presented id is revoked"); assert.ok(otherUserId in registry, "an unrelated lineage is untouched locally"); assert.strictEqual(fake.store.hash["adpanel:remember-logins:v1"][otherUserId] !== undefined, true, "an unrelated chain survives cluster-wide"); assert.strictEqual(fake.store.hash["adpanel:remember-logins:v1"][legacyId], undefined, "the presented legacy id is dead cluster-wide"); assert.strictEqual(harness.warnings.some((w) => w.includes("[security]")), false, "success must not warn"); assert.deepStrictEqual(harness.sandbox.__deadLettered, [], "success must not dead-letter"); }); test("file-store mode: the local lineage scan IS the durable revocation; an absent presented id still never throws", async () => { // Chain in local memory only (redisClient null): M (root) + R (rotated). const registry = { "chain-root-filestore": { uid: "1", email: USER.email, lineage: "chain-root-filestore" }, "rotated-filestore": { uid: "1", email: USER.email, lineage: "chain-root-filestore" }, "other-user": { uid: "2", email: "b@x.test", lineage: "other-user" }, }; const harness = buildLineageHarness({ registry, redisClient: null }); const existed = await harness.fn("chain-root-filestore", { uidHint: "1", lineageHint: "chain-root-filestore" }); assert.strictEqual(existed, true); assert.deepStrictEqual(Object.keys(registry), ["other-user"], "both chain members are deleted; the other user's chain survives"); assert.strictEqual(harness.warnings.filter((w) => w.includes("[security]")).length, 0, "file-store mode must not raise false [security] alarms"); assert.deepStrictEqual(harness.sandbox.__deadLettered, [], "file-store mode never dead-letters"); // The presented id is absent from local memory (another worker minted it): // fall back to single-id semantics, never throw. const registry2 = { "only-remote": { uid: "1", email: USER.email, lineage: "chain-x" } }; const harness2 = buildLineageHarness({ registry: registry2, redisClient: null }); const existed2 = await harness2.fn("absent-id", { uidHint: "1", lineageHint: "chain-x" }); assert.strictEqual(existed2, false, "existed reflects the absent presented entry"); assert.deepStrictEqual(Object.keys(registry2), [], "the locally-known chain member is still revoked"); }); test("Redis failure: the helper never rejects, dead-letters presented + known members, and logout still completes", async () => { const registry = { "chain-root-err": { uid: "1", email: USER.email, lineage: "chain-root-err" }, "member-err": { uid: "1", email: USER.email, lineage: "chain-root-err" }, }; const fake = makeFakeRedis({ sendCommandImpl: async () => { throw new Error("ECONNRESET"); }, }); const harness = buildLineageHarness({ registry, redisClient: fake.redisClient }); const existed = await harness.fn("chain-root-err", { uidHint: "1", lineageHint: "chain-root-err" }); assert.strictEqual(existed, true, "the existed contract survives a failed Redis delete"); assert.deepStrictEqual(harness.sandbox.__deadLettered.sort(), ["chain-root-err", "member-err"], "the presented id AND the locally-known chain members are dead-lettered for the poller's retry"); assert.ok(harness.warnings.some((w) => w.includes("[security] Lineage remember-login revocation FAILED") && w.includes("ECONNRESET")), "the loud [security] warn fires with the redacted display id and the error message"); assert.ok(!("chain-root-err" in registry) && !("member-err" in registry), "the local snapshot deletes still applied (this worker is safe immediately)"); assert.ok(!harness.warnings.some((w) => w.includes("chain-root-err") && w.includes("saved:saved")), "no raw double-redaction"); // A stalled Redis (never-settling EVAL) resolves within the bound with the // same posture — logout must not wedge. const stalled = makeFakeRedis({ sendCommandImpl: () => new Promise(() => {}) }); const registry3 = { "stalled-id": { uid: "1", lineage: "stalled-id" } }; const harness3 = buildLineageHarness({ registry: registry3, redisClient: stalled.redisClient }); const started = Date.now(); const existed3 = await harness3.fn("stalled-id", { uidHint: "1", lineageHint: "stalled-id" }); const elapsed = Date.now() - started; assert.strictEqual(existed3, true); assert.ok(elapsed < 2000, `the bounded EVAL must resolve within the bound (took ${elapsed}ms)`); assert.deepStrictEqual(harness3.sandbox.__deadLettered, ["stalled-id"]); assert.ok(harness3.warnings.some((w) => w.includes("Redis stalled")), "the timeout path warns distinctly"); }); test("a lineage disagreement fails the CAS closed (-2) instead of splitting the chain", async () => { // A stale worker snapshot claiming the wrong lineage must never swap: the // Lua compares the claimed lineage against the Redis-side old entry. const fake = makeFakeRedis(); const rot = buildRotateHarness({ redisClient: fake.redisClient }); // Tamper with the registry snapshot AFTER the harness read it is not // possible — instead tamper the REDIS side: give the Redis-side old entry a // different lineage than the JS snapshot claims. fake.store.hash["adpanel:remember-logins:v1"] = { [rot.mintId]: JSON.stringify({ ...rot.registry[rot.mintId], lineage: "a-different-chain-root" }), }; const result = await rot.fn(rot.req, rot.res, USER, makeParsed(rot.mintId, HARNESS_NOW - 60000)); assert.strictEqual(result, 0, "the disagreed swap must be refused (drift signal)"); assert.strictEqual(Object.keys(rot.registry).length, 1, "no local commit"); assert.ok(rot.mintId in rot.registry, "the presented entry stays untouched"); assert.strictEqual(fake.store.hash["adpanel:remember-logins:v1"][rot.mintId] !== undefined, true, "the Redis-side entry stays untouched"); }); test("the local chain scan is owner-guarded: a uidHint veto keeps mismatched members out of the local deletes", async () => { const fake = makeFakeRedis(); const registry = { "root-uid": { uid: "1", email: USER.email, lineage: "root-uid" }, "member-uid": { uid: "1", email: USER.email, lineage: "root-uid" }, "impostor-uid": { uid: "999", email: "c@x.test", lineage: "root-uid" }, // cryptographically impossible; defense in depth }; const harness = buildLineageHarness({ registry, redisClient: fake.redisClient }); // Seed the Redis-side set to the same three members to observe both sides. fake.store.hash["adpanel:remember-logins:v1"] = { "root-uid": JSON.stringify(registry["root-uid"]), "member-uid": JSON.stringify(registry["member-uid"]), "impostor-uid": JSON.stringify(registry["impostor-uid"]), }; fake.store.sets["adpanel:remember-lineage:root-uid"] = new Set(["root-uid", "member-uid", "impostor-uid"]); await harness.fn("root-uid", { uidHint: "1", lineageHint: "root-uid" }); assert.ok(!("member-uid" in registry), "the same-owner member is deleted locally"); assert.ok("impostor-uid" in registry, "the uid-mismatched member is NOT deleted from the local snapshot (veto)"); assert.strictEqual(fake.store.hash["adpanel:remember-logins:v1"]["impostor-uid"], undefined, "the Redis-side set is the revocation authority: the set member is deleted cluster-wide, and the version INCR forces this worker to reload"); assert.strictEqual(fake.store.version >= 1, true, "the registry version was bumped so every worker reloads"); }); test("logout before a delayed first mint prevents the signed cookie from becoming live again", async () => { const fake = makeFakeRedis(); fake.store.hash["adpanel:remember-logins:v1"] = {}; const rememberId = "a".repeat(36); const entry = { uid: "1", email: USER.email, lineage: rememberId, issuedAt: HARNESS_NOW, expiresAt: ANCHOR }; const registry = { [rememberId]: entry }; const mintedIds = new Set([rememberId]); const revoke = buildLineageHarness({ registry: {}, redisClient: fake.redisClient }); await revoke.fn(rememberId, { uidHint: "1", lineageHint: rememberId }); assert.strictEqual(fake.store.ttls[getRevokedRememberLoginRedisKey(rememberId)], REVOKED_REMEMBER_LOGIN_TTL_SECONDS); const writerSandbox = { redisClient: fake.redisClient, REMEMBER_LOGIN_REGISTRY_GUARDED_WRITE_LUA: WRITE_LUA, REMEMBER_LOGIN_REGISTRY_VERSION_REDIS_KEY: "adpanel:remember-registry:ver", REMEMBER_LOGIN_REGISTRY_REDIS_KEY: "adpanel:remember-logins:v1", getRevokedRememberLoginRedisKey, rememberLoginRegistry: registry, locallyMintedRememberLoginIds: mintedIds, }; vm.createContext(writerSandbox); const write = vm.runInContext(`(${WRITE_SOURCE})`, writerSandbox); assert.strictEqual(await write(fake.store.version, rememberId, entry), false, "even a current snapshot cannot publish a revoked first mint"); assert.strictEqual(fake.store.hash["adpanel:remember-logins:v1"][rememberId], undefined); assert.strictEqual(registry[rememberId], undefined, "the minting worker must discard the revoked credential"); assert.strictEqual(mintedIds.has(rememberId), false, "drift-preservation must never retry the revoked mint"); const delayedReplacement = "b".repeat(36); assert.strictEqual(await write(fake.store.version, delayedReplacement, { ...entry, lineage: rememberId }), false, "a delayed replacement cannot rejoin a revoked lineage"); const freshId = "c".repeat(36); assert.strictEqual(await write(fake.store.version, freshId, { ...entry, lineage: freshId }), true, "an unrelated new login remains writable"); });