1581 lines
92 KiB
JavaScript
1581 lines
92 KiB
JavaScript
"use strict";
|
|
|
|
// adpanel:restore-store-bounds + adpanel:confirmed-revoke-read-bounds —
|
|
// source pins + behavior pins for the two bounded-store spots on the remember
|
|
// request paths:
|
|
//
|
|
// 1. The remember-RESTORE completion path (restoreRememberedLogin) wraps its
|
|
// session.regenerate and session.save in the SAME 5s bound (and the SAME
|
|
// labels) the shared login binder uses (utils/login-session-bind.js:
|
|
// REGENERATE_TIMEOUT_MS/SAVE_TIMEOUT_MS and their labels). A stalled
|
|
// session store must not wedge the request past the bound; the rejection
|
|
// propagates to the remember middleware's catch around the restore's
|
|
// single call site, which clears the remember cookie and the session
|
|
// state — fail closed to a full password re-auth. The restore stays
|
|
// deliberately OUTSIDE the shared binder (separate body; the
|
|
// tests/remember-rotation-action-token.test.js negative pins keep it
|
|
// that way).
|
|
// 2. revokeRememberLoginRegistryEntryConfirmed bounds ALL THREE of its
|
|
// Redis reads with REMEMBER_REVOKE_WRITE_TIMEOUT_MS (the delete already
|
|
// carried the bound): read (a) — the owner-source hGet — is the one read
|
|
// that may degrade on timeout (null → the function's existing
|
|
// local-registry fallback, so the sweep still runs from a valid owner),
|
|
// while the sweep read (b) and the final verification read (c) let ANY
|
|
// rejection — timeout included — reach the outer catch
|
|
// ({ok:false,"redis-error"} → the route's 503 + retry token): success is
|
|
// never reported without sweep+verify completing.
|
|
//
|
|
// Pins held here:
|
|
// 1. Source: restore's regenerate AND save are wrapped with the 5s labels
|
|
// (regenerate → rotate → save ordering kept); the remember middleware's
|
|
// catch around the single restore call site clears cookie + state and
|
|
// continues (fail closed, request not wedged into a 500).
|
|
// 2. Source: all three Confirmed reads wrapped with the shared constant +
|
|
// label; read (a) converts ONLY the timeout to null and rethrows every
|
|
// other error; reads (b)/(c) have no local catch that could swallow a
|
|
// timeout; the delete call is not double-wrapped (it bounds its own
|
|
// MULTI exec inside deleteRememberLoginRegistryFields).
|
|
// 3. Behavior (vm-extracted): a never-settling regenerate / save rejects
|
|
// with the label within the bound and nothing after the wrap runs; a
|
|
// timed-out owner-source read falls back to the local entry and the
|
|
// race sweep still completes; a timed-out sweep or verify read fails
|
|
// the revoke closed with redis-error; a non-timeout owner-source read
|
|
// error keeps failing closed without reaching the delete.
|
|
// 4. Source + behavior (adpanel:restore-lookup-bound): the restore's FIRST
|
|
// DB read — findUserById(parsed.uid) — is wrapped at the call site with
|
|
// the login path's 8s user-lookup bound and the shared <what>-timeout
|
|
// label vocabulary ("remember-restore-user-lookup-timeout"; the sibling
|
|
// findUserByEmail bounds its own reads at 8s "find-user-timeout"). A
|
|
// stalled DB must not wedge every request presenting a remember cookie.
|
|
// The definition itself stays unbounded — the scheduler resolver and the
|
|
// agent job worker call it off the request path and own their contracts.
|
|
// 5. Source + behavior (adpanel:restore-save-failure-tombstone): the
|
|
// remember middleware's catch tombstones the CURRENT (regenerated) sid
|
|
// after the clear-state/clear-cookie hygiene and before next() — a
|
|
// failed bounded save must not leave the bound (authenticated) live
|
|
// session object committable by express-session's late end-handler save
|
|
// (the same late-write resurrection the login binder's
|
|
// adpanel:login-bind-save-failure-tombstone closes). Behavior: a
|
|
// never-settling save → the catch tombstones the regenerated sid (never
|
|
// the pre-restore sid) while keeping clear-state / clear-cookie / next()
|
|
// unchanged; a failed tombstone write warns in the binder's style and
|
|
// still continues (the original error is not rethrown).
|
|
// 6. Source + behavior (adpanel:restore-revoke-rotated-credential): the
|
|
// catch ALSO revokes the registry id the session references at catch
|
|
// time — post-rotate that IS the rotated id, whose token crossed the
|
|
// wire in the failing response's headers (commitRotation queues
|
|
// Set-Cookie before the save; the clearCookie only expires it), and
|
|
// replay is not IP/UA-bound — so a failed restore must leave NOTHING
|
|
// live (the binder's save-failure hygiene, mirrored). Behavior: a
|
|
// never-settling save → the catch revokes the rotated id BETWEEN the
|
|
// cookie clear and the sid tombstone, before next(); a pre-rotate
|
|
// failure (lookup throw) → the referenced PRE-EXISTING id is revoked
|
|
// too — the coherent-hygiene semantics: the cookie was just cleared in
|
|
// the same response, so no live registry entry may survive for a
|
|
// credential the client no longer holds; a failure on a session that
|
|
// references NO registry id must NOT fire the revoke (no over-firing).
|
|
// WAVE-3 (adpanel:remember-logout-lineage): the revoke is now the
|
|
// lineage-scoped helper with the session's own hints (uid/email from
|
|
// the live binding, lineage stamp when present) — a rotation committing
|
|
// between the capture and the revoke dies with the chain; absent hints
|
|
// degrade to single-id reach, and the never-rejects contract is
|
|
// unchanged, so the catch's posture below is byte-identical.
|
|
// 7. Source + behavior (adpanel:restore-attempt-observability): every
|
|
// cookie-presenting restore attempt logs securityLog("remember-restore
|
|
// attempt", req) at the top of the attempt (after the cookieless
|
|
// early-return — cookieless requests are not restore attempts), and a
|
|
// SUCCESSFUL restore fires the durable audit row
|
|
// loginAuditRecorder.recordSuccessfulLoginAudit({ user, req, method:
|
|
// "remember-restore" }) fire-and-forget, after the bounded save and
|
|
// immediately before its success return (the two login paths'
|
|
// call-site position).
|
|
// 8. Source + behavior (adpanel:credential-generation): the staleness
|
|
// re-verify gains the comparable-only epoch leg — the ONE shared
|
|
// predicate credentialGenerationMismatch(user.session_epoch,
|
|
// freshRestoreRow.session_epoch), chained into the SAME fail-closed
|
|
// clear condition as the fingerprint leg — because the credential
|
|
// writers bump session_epoch in the same statement as the credential,
|
|
// so a password/2FA change committing inside the restore's read→bind
|
|
// gap is visible as an epoch difference between the two bounded row
|
|
// reads and must never promote the pre-change proof onto the new
|
|
// generation. The bind then sources identity/epoch/currentUser from
|
|
// the FRESH row (the authoritative object; the two rows are
|
|
// fingerprint-equal and generation-equal by construction), and a legacy
|
|
// row without the epoch column stays UNCOMPARABLE — fingerprint leg
|
|
// only, restore still succeeds (documented degraded posture).
|
|
|
|
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 indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
|
|
// adpanel:credential-generation — the ONE shared credential-generation
|
|
// predicate (utils/session-account-binding.js), injected into BOTH vm
|
|
// sandboxes below so the REAL restore body runs against the REAL contract —
|
|
// never a test-local copy (the session-account-binding pins forbid those).
|
|
const { credentialGenerationMismatch } = require("../utils/session-account-binding");
|
|
|
|
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);
|
|
}
|
|
|
|
const RESTORE_SOURCE = extractBlock(indexSource, "async function restoreRememberedLogin(req, res) {");
|
|
const COMPLETION_SOURCE = fs.readFileSync(path.join(ROOT, "utils", "remember-login-completion.js"), "utf8");
|
|
const CONFIRMED_SOURCE = extractBlock(
|
|
indexSource,
|
|
"async function revokeRememberLoginRegistryEntryConfirmed(rememberId, ownerHint = null) {"
|
|
);
|
|
|
|
// Marker→marker region extraction (the tombstone machinery spans several
|
|
// functions and constants — extractBlock's balanced-brace shape cannot span
|
|
// it). Same markers the tombstone-skip-signal harness uses.
|
|
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);
|
|
}
|
|
|
|
// The REAL downstream authorization primitives (read-only reference region of
|
|
// index.js): the deauthorization pins below prove the failed-restore request
|
|
// is treated as ANONYMOUS by exactly the fast path every auth gate uses.
|
|
const GET_LOGGED_IN_USER_SOURCE = extractBlock(indexSource, "async function getLoggedInUser(req) {");
|
|
const IS_AUTHENTICATED_SOURCE = extractBlock(indexSource, "async function isAuthenticated(req) {");
|
|
const IS_ADMIN_SOURCE = extractBlock(indexSource, "async function isAdmin(req) {");
|
|
const AUTH_SOURCE = `${GET_LOGGED_IN_USER_SOURCE}\n${IS_AUTHENTICATED_SOURCE}\n${IS_ADMIN_SOURCE}`;
|
|
|
|
// The REAL tombstone machinery + checker + store wrapper (same extraction the
|
|
// tombstone-skip-signal harness uses): the late-save pin runs the REAL guard
|
|
// against the sid the failed restore's teardown tombstoned. The machinery
|
|
// region is interval-free (the sweep's setInterval sits outside it), and in
|
|
// file-store mode (redisClient null) the local map IS the durable tombstone.
|
|
const MACHINERY_SOURCE = extractRegion(
|
|
indexSource,
|
|
"// ---- Revoked-sid tombstones (anti-resurrection) ----",
|
|
"// Consult BOTH layers before trusting a sid:"
|
|
);
|
|
const CHECKER_SOURCE = extractRegion(
|
|
indexSource,
|
|
"// Consult BOTH layers before trusting a sid:",
|
|
"const wrapSessionStoreWithTombstoneGuard"
|
|
);
|
|
const WRAPPER_SOURCE = extractRegion(
|
|
indexSource,
|
|
"const wrapSessionStoreWithTombstoneGuard",
|
|
"wrapSessionStoreWithTombstoneGuard(sessionStore);"
|
|
);
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source pins — the restore completion path's 5s store bounds
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("restore's regenerate and save are wrapped with the binder's 5s bounds and labels", () => {
|
|
assert.match(
|
|
RESTORE_SOURCE,
|
|
/await withTimeout\(\s*new Promise\(\(resolve, reject\) => req\.session\.regenerate\(\(err\) => \(err \? reject\(err\) : resolve\(\)\)\)\),\s*5000,\s*"session-regenerate-timeout"\s*\);/,
|
|
"the restore regenerate must carry the same 5s bound and label as the shared binder"
|
|
);
|
|
assert.match(
|
|
COMPLETION_SOURCE,
|
|
/await deps\.withTimeout\(\s*new Promise\(\(resolve, reject\) => req\.session\.save\(\(error\) => error \? reject\(error\) : resolve\(\)\)\),\s*5000,\s*"session-save-timeout"\s*\);/,
|
|
"the restore save must carry the same 5s bound and label as the shared binder"
|
|
);
|
|
assert.match(RESTORE_SOURCE, /return completeRememberLoginSession\(req, \{\s*withTimeout, findUserById, isSessionSidRevoked, safeCompare, getRememberLoginFingerprint, loginAuditRecorder,\s*\}, freshRestoreRow, parsed\.fp\);/,
|
|
"the real restore must delegate completion with its proved row, fingerprint and real dependencies");
|
|
|
|
// Order is load-bearing (rotation must stay between the two wraps): the
|
|
// regenerate runs first, the rotate-and-bind core next, the bounded save
|
|
// last.
|
|
const regenIdx = RESTORE_SOURCE.indexOf('"session-regenerate-timeout"');
|
|
const rotateIdx = RESTORE_SOURCE.indexOf("await rotateRememberLoginCookie(req, res, user, parsed);");
|
|
const saveIdx = RESTORE_SOURCE.indexOf("return completeRememberLoginSession(req, {");
|
|
assert.ok(regenIdx >= 0 && rotateIdx > regenIdx && saveIdx > rotateIdx,
|
|
"regenerate → rotate/bind → bounded save ordering must survive");
|
|
|
|
// The wraps are documented and the restore stays OUT of the shared binder
|
|
// (deliberately separate body; folding it would break the rotation test's
|
|
// negative pins).
|
|
assert.strictEqual(
|
|
((RESTORE_SOURCE + COMPLETION_SOURCE).match(/adpanel:restore-store-bounds/g) || []).length,
|
|
2,
|
|
"both wraps must carry the adpanel:restore-store-bounds comment"
|
|
);
|
|
assert.ok(
|
|
!RESTORE_SOURCE.includes("loginSessionBinder") && !RESTORE_SOURCE.includes("bindLoginSession"),
|
|
"the restore must not be folded into the shared login binder"
|
|
);
|
|
|
|
// The labels mirror the binder module's own constants — one vocabulary for
|
|
// the same constraint on every login completion path.
|
|
const binderSource = fs.readFileSync(path.join(ROOT, "utils", "login-session-bind.js"), "utf8");
|
|
assert.ok(
|
|
binderSource.includes('const REGENERATE_TIMEOUT_MS = 5000;') &&
|
|
binderSource.includes('const SAVE_TIMEOUT_MS = 5000;') &&
|
|
binderSource.includes('const REGENERATE_TIMEOUT_LABEL = "session-regenerate-timeout";') &&
|
|
binderSource.includes('const SAVE_TIMEOUT_LABEL = "session-save-timeout";'),
|
|
"the binder module defines the 5s constants and labels the restore mirrors"
|
|
);
|
|
});
|
|
|
|
test("the remember middleware's catch around the restore call site fails closed", () => {
|
|
const callIdx = indexSource.indexOf("await restoreRememberedLogin(req, res);");
|
|
assert.ok(callIdx >= 0, "the restore must have exactly one middleware call site");
|
|
assert.strictEqual(
|
|
indexSource.split("await restoreRememberedLogin(req, res);").length - 1,
|
|
1,
|
|
"exactly one call site — the catch evidence must be the middleware's own"
|
|
);
|
|
const middlewareStart = indexSource.lastIndexOf("app.use(async (req, res, next) => {", callIdx);
|
|
assert.ok(middlewareStart >= 0 && middlewareStart < callIdx, "the call site sits inside a middleware");
|
|
// Conscious pin update (adpanel:restore-failure-deauthorization): the catch
|
|
// no longer holds the hygiene inline — it warns the original error,
|
|
// DELEGATES to the ONE teardown helper and continues unauthenticated. The
|
|
// state/cookie/revoke/tombstone assertions moved with the code, into the
|
|
// teardown pins below. The window is sized to the (now short) delegated
|
|
// catch.
|
|
const window = indexSource.slice(middlewareStart, callIdx + 1200);
|
|
const tryIdx = window.indexOf("try {");
|
|
const catchIdx = window.indexOf("} catch (err) {", window.indexOf("await restoreRememberedLogin(req, res);"));
|
|
assert.ok(tryIdx >= 0 && tryIdx < window.indexOf("await restoreRememberedLogin(req, res);"),
|
|
"the restore call must sit inside the middleware's try");
|
|
assert.ok(catchIdx > tryIdx, "the try must have a catch");
|
|
const catchBody = window.slice(catchIdx);
|
|
const warnIdx = catchBody.indexOf('console.warn("[auth] Persistent login restore failed:", err?.message || err);');
|
|
const delegateIdx = catchBody.indexOf("await teardownFailedRememberRestore(req, res);");
|
|
const nextIdx = catchBody.indexOf("return next();");
|
|
assert.ok(warnIdx >= 0, "the catch still warns the original labeled error");
|
|
assert.ok(delegateIdx > warnIdx, "the catch delegates the teardown to the ONE helper");
|
|
assert.ok(nextIdx > delegateIdx, "the catch must continue unauthenticated (fail closed to a full password re-auth, not a wedged/500 request)");
|
|
assert.strictEqual(
|
|
indexSource.split("async function teardownFailedRememberRestore(req, res) {").length - 1,
|
|
1,
|
|
"exactly ONE failure-teardown helper — no parallel copies"
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source + behavior pins — the catch's post-failure tombstone
|
|
// (adpanel:restore-save-failure-tombstone)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("the failure teardown captures targeting, clears authority, revokes, tombstones, then destroys", () => {
|
|
const callIdx = indexSource.indexOf("await restoreRememberedLogin(req, res);");
|
|
const middlewareStart = indexSource.lastIndexOf("app.use(async (req, res, next) => {", callIdx);
|
|
assert.ok(middlewareStart >= 0 && middlewareStart < callIdx, "the call site sits inside a middleware");
|
|
// The enclosing handler is async — the tombstone/destroy awaits inside its
|
|
// catch are legal (and scanner-clean: the catch sits inside the try/catch
|
|
// guarded region the unguarded-awaited-route scanner recognizes).
|
|
assert.ok(indexSource.startsWith("app.use(async (req, res, next) => {", middlewareStart),
|
|
"the remember middleware handler is async");
|
|
|
|
// Conscious pin update (adpanel:restore-failure-deauthorization): the
|
|
// catch's hygiene moved into the ONE teardown helper — the assertions
|
|
// track it there, at the same strength, plus the new steps: the sync
|
|
// authority clear and the destroy-after-tombstone.
|
|
assert.ok(TEARDOWN_SOURCE.includes("adpanel:restore-save-failure-tombstone"),
|
|
"the post-failure tombstone carries its adpanel tag");
|
|
|
|
// Ordering is load-bearing: capture → sync authority clear → state →
|
|
// cookie → revoke → tombstone → destroy → cache. The revoke
|
|
// (adpanel:restore-revoke-rotated-credential) sits between the cookie
|
|
// clear and the tombstone — the rotated credential crossed the wire in
|
|
// this response's headers, so its registry entry must die before the
|
|
// teardown continues; the tombstone lands after both; the bounded destroy
|
|
// runs ONLY after the tombstone is durable (tombstone-before-destroy, the
|
|
// teardownStaleAccountSession ordering).
|
|
const captureIdx = TEARDOWN_SOURCE.indexOf('const postFailureSid = String(req.sessionID || "").trim();');
|
|
const clearUserIdx = TEARDOWN_SOURCE.indexOf("delete req.session.user;");
|
|
const stateIdx = TEARDOWN_SOURCE.indexOf("clearRememberLoginSessionState(req);");
|
|
const cookieIdx = TEARDOWN_SOURCE.indexOf("clearRememberLoginCookie(req, res);");
|
|
// Conscious pin update (adpanel:remember-logout-lineage, WAVE-3, carried
|
|
// into the helper): the revoke stays lineage-scoped — and since the
|
|
// authority clear now empties the live binding BEFORE the revoke runs,
|
|
// the hints MUST come from the capture, not the session.
|
|
const revokeIdx = TEARDOWN_SOURCE.indexOf("await revokeRememberLoginLineage(failedRestoreRememberId");
|
|
const tombstoneIdx = TEARDOWN_SOURCE.indexOf("await writeRevokedSidTombstone(postFailureSid)");
|
|
const warnIdx = TEARDOWN_SOURCE.indexOf("console.warn(`[security] Could not tombstone post-regeneration session");
|
|
const destroyIdx = TEARDOWN_SOURCE.indexOf("req.session.destroy((destroyErr) => {");
|
|
const cacheIdx = TEARDOWN_SOURCE.indexOf("removeActiveBrowserSessionCacheEntry(postFailureSid);");
|
|
assert.ok(captureIdx >= 0, "the sid targeting is captured before anything is cleared");
|
|
assert.ok(clearUserIdx > captureIdx, "the authority clear follows the capture");
|
|
assert.ok(stateIdx > clearUserIdx, "clear state follows the authority clear");
|
|
assert.ok(cookieIdx > stateIdx, "clear state → clear cookie unchanged");
|
|
assert.ok(revokeIdx > cookieIdx, "the registry-id revoke follows the cookie clear");
|
|
assert.ok(tombstoneIdx > revokeIdx, "the post-failure tombstone follows the registry-id revoke");
|
|
assert.ok(warnIdx > tombstoneIdx, "the binder-style warn sits in the tombstone's false branch");
|
|
assert.ok(destroyIdx > warnIdx, "the bounded destroy follows the tombstone (tombstone-before-destroy)");
|
|
assert.ok(cacheIdx > destroyIdx, "the active-session cache cleanup follows the destroy");
|
|
|
|
// ALL targeting (sid, remember id, lineage, email, account id) is captured
|
|
// BEFORE the authority clear — the awaited cleanup aims at what the
|
|
// request held, not at an already-emptied object.
|
|
const captureBlock = TEARDOWN_SOURCE.slice(0, clearUserIdx);
|
|
assert.ok(
|
|
captureBlock.includes('const failedRestoreRememberId = String(req.session?.rememberLoginId || "").trim();') &&
|
|
captureBlock.includes('const failedRestoreLineage = String(req.session?.rememberLoginLineage || "");') &&
|
|
captureBlock.includes('const failedRestoreEmail = String(req.session?.user || "").trim().toLowerCase();') &&
|
|
captureBlock.includes('const failedRestoreAccountId = req.session?.accountId != null ? String(req.session.accountId) : "";'),
|
|
"sid, remember id, lineage, email and account id are all captured BEFORE the authority clear"
|
|
);
|
|
|
|
// The synchronous authority clear removes every binding downstream gates
|
|
// resolve through (getLoggedInUser's req.currentUser fast path, the
|
|
// account-binding middleware, the req.isAdmin middleware), plus the
|
|
// protected pending-captcha state.
|
|
const authorityWindow = TEARDOWN_SOURCE.slice(clearUserIdx, stateIdx);
|
|
for (const key of ["user", "accountId", "accountEpoch", "browserSessionAudit", "rememberLoginId", "rememberLoginLineage"]) {
|
|
assert.ok(authorityWindow.includes(`delete req.session.${key};`), `the authority clear removes req.session.${key}`);
|
|
}
|
|
assert.ok(authorityWindow.includes("clearPendingCaptchaLogin(req);"), "the protected pending-captcha record is cleared (the ONE home for that key)");
|
|
assert.ok(authorityWindow.includes("req.session.captchaSolved = false;") && authorityWindow.includes("req.session.captchaRequired = false;"),
|
|
"the solved/required captcha flags are reset");
|
|
assert.ok(authorityWindow.includes("req.currentUser = null;"), "the req.currentUser fast path is nulled");
|
|
assert.ok(authorityWindow.includes("delete req.isAdmin;"), "a cached req.isAdmin flag is deleted");
|
|
|
|
// The revoke reads the id the SESSION referenced at failure time (post-rotate
|
|
// the rotated id, pre-rotate the pre-existing one — the coherent-hygiene
|
|
// semantics), guarded so a session referencing nothing does not fire it,
|
|
// and carries its adpanel tag.
|
|
assert.ok(TEARDOWN_SOURCE.includes("adpanel:restore-revoke-rotated-credential"),
|
|
"the registry-id revoke carries its adpanel tag");
|
|
assert.match(
|
|
TEARDOWN_SOURCE,
|
|
/const failedRestoreRememberId = String\(req\.session\?\.rememberLoginId \|\| ""\)\.trim\(\);[\s\S]*?if \(failedRestoreRememberId\) \{\s*\n\s*try \{\s*\n\s*await revokeRememberLoginLineage\(failedRestoreRememberId, \{\s*\n\s*uidHint: failedRestoreAccountId,\s*\n\s*emailHint: failedRestoreEmail,\s*\n\s*lineageHint: failedRestoreLineage,\s*\n\s*\}\);\s*\n\s*\} catch/,
|
|
"the revoked id is exactly the CAPTURED registry id — through the lineage-scoped revoke with the CAPTURED hints (the live binding is already cleared when the revoke runs), guarded, and rejection-isolated"
|
|
);
|
|
|
|
// The bounded destroy: the restore's own 5s store-bound vocabulary, in the
|
|
// file's callback style, warn-not-reject on the destroy error.
|
|
assert.match(
|
|
TEARDOWN_SOURCE,
|
|
/await withTimeout\(\s*new Promise\(\(resolve\) => req\.session\.destroy\(\(destroyErr\) => \{[\s\S]*?\}\)\),\s*5000,\s*"session-destroy-timeout"/,
|
|
"the session destroy is bounded with the 5s store-bound vocabulary, callback-style"
|
|
);
|
|
assert.ok(TEARDOWN_SOURCE.includes("[security] Failed to destroy failed-restore session:"),
|
|
"a destroy error warns (never rejects the teardown)");
|
|
|
|
assert.match(
|
|
TEARDOWN_SOURCE,
|
|
/const postFailureSid = String\(req\.sessionID \|\| ""\)\.trim\(\);/,
|
|
"the CURRENT (regenerated) sid is captured at tombstone time"
|
|
);
|
|
assert.match(
|
|
TEARDOWN_SOURCE,
|
|
/a late store write may still commit the failed restore's record/,
|
|
"the warn names this surface's subject (restore), keeping the binder's sentence style"
|
|
);
|
|
|
|
// One vocabulary with the shared binder: the capture line and the warn
|
|
// prefix are byte-identical to utils/login-session-bind.js's post-failure
|
|
// tombstone (adpanel:login-bind-save-failure-tombstone).
|
|
const binderSource = fs.readFileSync(path.join(ROOT, "utils", "login-session-bind.js"), "utf8");
|
|
assert.ok(
|
|
binderSource.includes('const postFailureSid = String(req.sessionID || "").trim();'),
|
|
"the binder defines the same postFailureSid capture"
|
|
);
|
|
assert.ok(
|
|
binderSource.includes("Could not tombstone post-regeneration session"),
|
|
"the warn prefix is shared with the binder"
|
|
);
|
|
});
|
|
|
|
// The middleware block is extracted whole (marker → balanced handler brace) so
|
|
// the behavior pins below run the REAL catch: restore is the real extracted
|
|
// body from above, wired through the same sandbox — the middleware under test
|
|
// calls the real single call site, not a shortcut stub. The anchor is the
|
|
// restore call site itself — the source pin above already proved it is unique.
|
|
const MW_MARKER = "app.use(async (req, res, next) => {";
|
|
const MW_ANCHOR = "await restoreRememberedLogin(req, res);";
|
|
const mwAnchorIdx = indexSource.indexOf(MW_ANCHOR);
|
|
const mwStartIdx = mwAnchorIdx >= 0 ? indexSource.lastIndexOf(MW_MARKER, mwAnchorIdx) : -1;
|
|
const MIDDLEWARE_SOURCE = mwStartIdx >= 0
|
|
? extractBlock(indexSource.slice(mwStartIdx), MW_MARKER) + ");"
|
|
: "";
|
|
// Conscious pin update (adpanel:restore-failure-deauthorization): the catch's
|
|
// failure teardown moved into its own helper — the middleware's catch
|
|
// DELEGATES to it, and the tombstone/revoke/clear hygiene (and its tags)
|
|
// lives there now.
|
|
const TEARDOWN_SOURCE = extractBlock(indexSource, "async function teardownFailedRememberRestore(req, res) {");
|
|
// The deauthorization tag lives in the header comment ABOVE the declaration
|
|
// (extractBlock starts at the marker), so it is asserted against the
|
|
// preceding window.
|
|
const teardownFnIdx = indexSource.indexOf("async function teardownFailedRememberRestore(req, res) {");
|
|
const TEARDOWN_HEADER = teardownFnIdx >= 0 ? indexSource.slice(Math.max(0, teardownFnIdx - 3000), teardownFnIdx) : "";
|
|
assert.ok(
|
|
MIDDLEWARE_SOURCE.includes(MW_ANCHOR) &&
|
|
MIDDLEWARE_SOURCE.includes("await ensureRememberLoginStoreReady();") &&
|
|
MIDDLEWARE_SOURCE.includes("await teardownFailedRememberRestore(req, res);") &&
|
|
MIDDLEWARE_SOURCE.includes("return next();"),
|
|
"the extracted middleware is the remember middleware delegating its catch to the teardown helper"
|
|
);
|
|
assert.ok(
|
|
TEARDOWN_HEADER.includes("adpanel:restore-failure-deauthorization") &&
|
|
TEARDOWN_SOURCE.includes("adpanel:restore-save-failure-tombstone") &&
|
|
TEARDOWN_SOURCE.includes("adpanel:restore-revoke-rotated-credential"),
|
|
"the extracted teardown helper carries the failure-deauthorization contract and the moved step tags"
|
|
);
|
|
|
|
function buildRestoreMiddlewareHarness({ session, tombstoneImpl, revokeImpl, findUserById } = {}) {
|
|
const calls = {
|
|
clearState: 0,
|
|
clearCookie: 0,
|
|
next: 0,
|
|
nextArgs: [],
|
|
tombstoneSids: [],
|
|
revokedIds: [],
|
|
revokedHints: [],
|
|
auditMethods: [],
|
|
securityLogs: [],
|
|
warnings: [],
|
|
events: [],
|
|
};
|
|
const req = { cookies: { "adpanel.remember": "tok" }, session, sessionID: "pre-restore-sid-1" };
|
|
// Default destroy stub (mirrors express-session 1.19's
|
|
// Session.prototype.destroy: req.session is deleted BEFORE the store
|
|
// destroy) so every failure-direction test exercises the real teardown's
|
|
// destroy step unless a test overrides it.
|
|
if (session && typeof session.destroy !== "function") {
|
|
session.destroy = (cb) => {
|
|
calls.events.push("destroy");
|
|
delete req.session;
|
|
cb(null);
|
|
};
|
|
}
|
|
const sandbox = {
|
|
console: { log: () => {}, warn: (...a) => calls.warnings.push(a.map(String).join(" ")) },
|
|
app: { use: (fn) => { sandbox.__capturedMw = fn; } },
|
|
REMEMBER_LOGIN_COOKIE_NAME: "adpanel.remember",
|
|
readRememberLoginToken: () => LIVE_PARSED,
|
|
// adpanel:restore-attempt-observability — the restore body logs every
|
|
// cookie-presenting attempt; the collector proves the attempt fires.
|
|
securityLog: (msg) => { calls.securityLogs.push(String(msg)); },
|
|
findUserById: findUserById || (async () => LIVE_USER),
|
|
// adpanel:credential-generation — the REAL shared predicate: the restore
|
|
// body's staleness re-verify calls it on (snapshot epoch, fresh row epoch).
|
|
credentialGenerationMismatch,
|
|
...require("../utils/remember-login-completion"),
|
|
isSessionSidRevoked: async () => false,
|
|
safeCompare: () => true,
|
|
getRememberLoginFingerprint: () => "fp",
|
|
getRememberLoginLegacyCutoff: () => 0,
|
|
isManagedRememberLoginToken: () => true,
|
|
revokeRememberLoginsForUser: async () => {},
|
|
// Same predicate copy as buildRestoreHarness — the restore's pre-regenerate
|
|
// tombstone condition calls it; the pins rely on a bare pre-auth session
|
|
// staying SKIPPED there so the post-failure tombstone's sid is unambiguous.
|
|
sessionCarriesProtectedPendingAuthState: (sess) =>
|
|
!!sess && (sess.captchaSolved === true || !!(sess.pendingCaptchaLogin && typeof sess.pendingCaptchaLogin === "object")),
|
|
getSessionDisplayId: (id) => `sid:${id}`,
|
|
writeRevokedSidTombstone:
|
|
tombstoneImpl ||
|
|
(async (sid) => { calls.tombstoneSids.push(sid); calls.events.push(`tombstone:${sid}`); return true; }),
|
|
// adpanel:restore-revoke-rotated-credential — the catch's registry-id
|
|
// revoke. Conscious mock update (adpanel:remember-logout-lineage, WAVE-3):
|
|
// the catch now revokes through the lineage-scoped helper; the collector
|
|
// proves WHICH id died, WHICH hints scoped it and WHEN (relative to the
|
|
// cookie clear, the sid tombstone and next()), delegating the outcome to
|
|
// revokeImpl when given (the DLQ-failure direction pin below).
|
|
revokeRememberLoginLineage: async (id, hints) => {
|
|
calls.revokedIds.push(String(id));
|
|
calls.revokedHints.push({ ...(hints || {}) });
|
|
calls.events.push(`revoke:${id}`);
|
|
return revokeImpl ? revokeImpl(id) : true;
|
|
},
|
|
// adpanel:restore-attempt-observability — the recorder's success-row call;
|
|
// the collector proves the method string and its position (post-save,
|
|
// pre-next). Fire-and-forget in the body, so recording is synchronous.
|
|
loginAuditRecorder: {
|
|
recordSuccessfulLoginAudit: ({ method }) => {
|
|
calls.auditMethods.push(String(method));
|
|
calls.events.push(`audit:${method}`);
|
|
},
|
|
},
|
|
// adpanel:remote-proxy-trust-gate — the restore body's issuance-gate
|
|
// check; the default-off/no-violation posture (false) is exactly what
|
|
// every pre-existing pin here exercises. The opt-in + violation refusal
|
|
// behavior is pinned in tests/remote-proxy-trust-gate.test.js with the
|
|
// REAL extracted helper.
|
|
remoteProxyTrustBlocksRememberIssuance: () => false,
|
|
// Mirrors index.js's real semantics (unchanged contract): only the
|
|
// freshness timestamps go. The identity keys are cleared by the REAL
|
|
// teardown helper (adpanel:restore-failure-deauthorization), which runs
|
|
// in this sandbox too — the deauthorization pins prove that separation.
|
|
clearRememberLoginSessionState: (r) => {
|
|
if (!r?.session) return;
|
|
delete r.session.rememberLoginCheckedAt;
|
|
delete r.session.rememberLoginExpiresAt;
|
|
calls.clearState += 1;
|
|
calls.events.push("clearState");
|
|
},
|
|
clearRememberLoginCookie: () => { calls.clearCookie += 1; calls.events.push("clearCookie"); },
|
|
clearPendingCaptchaLogin: (r) => { if (r?.session) delete r.session.pendingCaptchaLogin; },
|
|
removeActiveBrowserSessionCacheEntry: (sid) => { calls.events.push(`cacheRemove:${sid}`); },
|
|
invalidateActiveBrowserSessionCache: () => { calls.events.push("cacheInvalidate"); },
|
|
ensureRememberLoginStoreReady: async () => {},
|
|
ensureRememberLoginRegistryFresh: async () => {},
|
|
ensureRememberLoginCookie: async () => {},
|
|
// Mirrors commitRotation's session binding (index.js): a successful
|
|
// rotation ALWAYS re-points req.session.rememberLoginId at the new id —
|
|
// which is exactly the id the catch's revoke must see on a later failure.
|
|
rotateRememberLoginCookie: async (r) => {
|
|
if (r?.session) r.session.rememberLoginId = "rotated-remember-id-3";
|
|
return 4102444800000;
|
|
},
|
|
buildBrowserSessionAuditFromRequest: () => ({ rememberLoginId: LIVE_PARSED.jti }),
|
|
// Real mark-fresh semantics: the freshness markers go back on the live
|
|
// object between the bind and the stalled save, exactly like production.
|
|
markRememberLoginSessionFresh: (r, expiresAt) => {
|
|
if (!r?.session) return;
|
|
r.session.rememberLoginCheckedAt = Date.now();
|
|
r.session.rememberLoginExpiresAt = Number(expiresAt) || 0;
|
|
},
|
|
// File-store posture for the REAL tombstone machinery below: with no
|
|
// redisClient the local map IS the durable tombstone, so the late-save
|
|
// pin exercises the REAL store guard without Redis.
|
|
redisClient: null,
|
|
fileSessionRevocations: { write: () => true, has: () => false },
|
|
require: (id) => {
|
|
assert.strictEqual(id, "./utils/session-store-guard");
|
|
return require("../utils/session-store-guard");
|
|
},
|
|
process: { env: {} },
|
|
scaleForMemory: (base) => base,
|
|
findUserByEmail: async () => LIVE_USER,
|
|
withTimeout: sandboxWithTimeout,
|
|
req,
|
|
};
|
|
// A recording fake store for the REAL wrapper: a response-end style set
|
|
// against it must be REFUSED for any sid the teardown tombstoned (and the
|
|
// refusal re-destroys, the wrapper's documented contract).
|
|
const lateStoreWrites = [];
|
|
const lateStoreDestroys = [];
|
|
sandbox.__lateStore = {
|
|
set: (sid, sess, cb) => { lateStoreWrites.push(String(sid)); cb(null); },
|
|
touch: (sid, sess, cb) => { cb(null); },
|
|
destroy: (sid, cb) => { lateStoreDestroys.push(String(sid)); cb(null); },
|
|
};
|
|
vm.createContext(sandbox);
|
|
// The REAL tombstone machinery + checker + wrapper, applied to the fake
|
|
// store in ONE script (top-level const bindings live in the script scope,
|
|
// so the wrapper's closure needs them in the same run). Auth primitives
|
|
// are function declarations — they land on the context as globals.
|
|
vm.runInContext(
|
|
`${MACHINERY_SOURCE}\n${CHECKER_SOURCE}\n${WRAPPER_SOURCE}\nwrapSessionStoreWithTombstoneGuard(__lateStore);`,
|
|
sandbox,
|
|
{ filename: "tombstone-machinery-sandbox.js" }
|
|
);
|
|
vm.runInContext(AUTH_SOURCE, sandbox, { filename: "auth-sandbox.js" });
|
|
// The REAL failure teardown (adpanel:restore-failure-deauthorization) — the
|
|
// extracted middleware's catch calls it, so the behavior pins below run the
|
|
// real implementation against these sandbox stubs.
|
|
sandbox.teardownFailedRememberRestore = vm.runInContext(`(${TEARDOWN_SOURCE})`, sandbox, { filename: "teardown-sandbox.js" });
|
|
const realWriteRevokedSidTombstone = sandbox.writeRevokedSidTombstone;
|
|
// Recorded REAL write: the collectors keep the pre-existing pin shape
|
|
// (WHICH sid died, and when relative to the other steps), while the REAL
|
|
// machinery populates the local tombstone cache the guard consults.
|
|
sandbox.writeRevokedSidTombstone = tombstoneImpl || (async (sid) => {
|
|
const ok = await realWriteRevokedSidTombstone(sid);
|
|
calls.tombstoneSids.push(sid);
|
|
calls.events.push(`tombstone:${sid}`);
|
|
return ok;
|
|
});
|
|
sandbox.restoreRememberedLogin = vm.runInContext(`(${RESTORE_SOURCE})`, sandbox, { filename: "restore-sandbox.js" });
|
|
vm.runInContext(MIDDLEWARE_SOURCE, sandbox, { filename: "remember-middleware-sandbox.js" });
|
|
const next = (...a) => { calls.next += 1; calls.nextArgs.push(a); calls.events.push("next"); };
|
|
return {
|
|
mw: sandbox.__capturedMw,
|
|
calls,
|
|
req,
|
|
next,
|
|
isAuthenticated: sandbox.isAuthenticated,
|
|
isAdmin: sandbox.isAdmin,
|
|
lateStore: sandbox.__lateStore,
|
|
lateStoreWrites,
|
|
lateStoreDestroys,
|
|
};
|
|
}
|
|
|
|
test("a save that times out after the bind makes the catch tombstone the REGENERATED sid", async () => {
|
|
// adpanel:restore-save-failure-tombstone — the exact finding: the bounded
|
|
// save (never-settling store stub) rejects with the shared label; the
|
|
// middleware's catch must tombstone the CURRENT (regenerated) sid — never
|
|
// the pre-restore sid — while keeping its other duties (clear state, clear
|
|
// cookie, continue unauthenticated). Real-semantics withTimeout arms the
|
|
// full 5s bound, same discipline as the stall pins above.
|
|
const session = {
|
|
// express-session's regenerate mints the fresh sid; the stub models that
|
|
// swap (the bind lands on the live object — exactly what a late save
|
|
// would commit under the fresh sid).
|
|
regenerate: (cb) => { req.sessionID = "regenerated-sid-2"; cb(null); },
|
|
save: () => { /* never settles — the timeout direction the tombstone covers */ },
|
|
};
|
|
const { mw, calls, req, next, isAuthenticated } = buildRestoreMiddlewareHarness({ session });
|
|
await mw(req, {}, next);
|
|
assert.deepStrictEqual(
|
|
calls.events,
|
|
["clearState", "clearState", "clearCookie", "revoke:rotated-remember-id-3", "tombstone:regenerated-sid-2", "destroy", "cacheRemove:regenerated-sid-2", "cacheInvalidate", "next"],
|
|
"restore's own pre-save hygiene, then the teardown's clear-state → clear-cookie → revoke(rotated id) → tombstone(regenerated sid) → destroy → cache cleanup, then next"
|
|
);
|
|
assert.deepStrictEqual(
|
|
calls.tombstoneSids,
|
|
["regenerated-sid-2"],
|
|
"the catch must tombstone the CURRENT (regenerated) sid, never the pre-restore sid"
|
|
);
|
|
// adpanel:restore-revoke-rotated-credential — F-1: the rotated credential
|
|
// crossed the wire in this failing response's headers (commitRotation
|
|
// queued Set-Cookie BEFORE the save; the clearCookie only expires it), so
|
|
// the ROTATED registry id must be revoked BEFORE next() — the captured
|
|
// cookie must not stay replayable (replay is not IP/UA-bound).
|
|
assert.deepStrictEqual(
|
|
calls.revokedIds,
|
|
["rotated-remember-id-3"],
|
|
"the catch must revoke the ROTATED registry id — the id commitRotation re-pointed the session at and whose token crossed the wire"
|
|
);
|
|
// Conscious assertion update (adpanel:remember-logout-lineage, WAVE-3 +
|
|
// adpanel:restore-failure-deauthorization): the lineage revoke is scoped by
|
|
// the CAPTURED hints — and since the teardown's authority clear deletes
|
|
// user/accountId BEFORE the revoke runs, a correct capture is now PROVEN by
|
|
// these assertions: hints read from the (already-emptied) live session
|
|
// would be "". The lineage hint is "" only because this harness's rotate
|
|
// stub does not stamp rememberLoginLineage (real commitRotation does,
|
|
// index.js).
|
|
assert.strictEqual(calls.revokedHints.length, 1, "exactly one lineage revoke fired");
|
|
assert.strictEqual(calls.revokedHints[0].emailHint, LIVE_USER.email, "the lineage revoke carries the CAPTURED email hint (the live binding is already cleared)");
|
|
assert.strictEqual(calls.revokedHints[0].uidHint, "1", "the lineage revoke carries the CAPTURED account-id hint");
|
|
assert.strictEqual(calls.revokedHints[0].lineageHint, "", "no lineage stamp on this harness session — the helper degrades to the live entry/-id chain resolution");
|
|
assert.deepStrictEqual(
|
|
calls.auditMethods,
|
|
[],
|
|
"a failed restore records NO durable audit row (success-only audit)"
|
|
);
|
|
assert.strictEqual(calls.clearCookie, 1, "the remember hygiene is unchanged: the catch clears the cookie once");
|
|
assert.strictEqual(calls.next, 1, "the catch continues unauthenticated exactly once");
|
|
assert.deepStrictEqual(calls.nextArgs, [[]], "next() takes no error argument (fail closed, not a 500)");
|
|
// THE FIX (restore-failure-deauthorization): the live object is NO LONGER
|
|
// bound after the teardown — the tombstone protects the STORE, and the
|
|
// request-local authority is cleared so downstream sees an ANONYMOUS
|
|
// request instead of the authenticated residue the old catch left behind.
|
|
assert.strictEqual(req.session?.user, undefined, "the failed restore leaves NO identity binding on the live request");
|
|
assert.strictEqual(req.session?.accountId, undefined, "the account binding is cleared with the rest of the authority");
|
|
assert.strictEqual(req.currentUser, null, "the currentUser fast path is nulled");
|
|
assert.strictEqual(await isAuthenticated(req), false, "downstream authorization is denied after the failed restore");
|
|
assert.ok(!("rememberLoginCheckedAt" in (req.session || {})) && !("rememberLoginExpiresAt" in (req.session || {})),
|
|
"the freshness timestamps are gone too (clearRememberLoginSessionState ran; the destroy then removed the object)");
|
|
assert.ok(
|
|
calls.warnings.some((w) => w.includes("Persistent login restore failed") && w.includes("session-save-timeout")),
|
|
"the original labeled error still surfaces in the catch's warn"
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavior pins — failed-restore DEAUTHORIZATION of the current request
|
|
// (restore-failure-deauthorization): the tombstone protects the STORE, not
|
|
// the live request — the failure teardown must also clear the request-local
|
|
// authority, or the SAME request continues authenticated downstream
|
|
// (getLoggedInUser's req.currentUser fast path, the account-binding
|
|
// middleware, the req.isAdmin middleware).
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("a save that FAILS must deauthorize the current request, not just the store", async () => {
|
|
// THE FINDING: restore binds req.session.user/accountId/accountEpoch/
|
|
// browserSessionAudit and req.currentUser, THEN the bounded save fails.
|
|
// The catch's tombstone + revoke cover the store and the registry, but the
|
|
// live request object kept every binding — downstream in the SAME request
|
|
// authorized off exactly that. After a failed restore, downstream must see
|
|
// an ANONYMOUS request (the gates' 401/redirect — today's response shape).
|
|
const session = {
|
|
regenerate: (cb) => { req.sessionID = "regenerated-sid-2"; cb(null); },
|
|
save: (cb) => cb(new Error("synthetic store failure")),
|
|
// express-session 1.19 Session.prototype.destroy (deletes req.session
|
|
// BEFORE the store destroy) is injected by the harness — see its default
|
|
// destroy stub.
|
|
};
|
|
const { mw, calls, req, next, isAuthenticated, isAdmin } = buildRestoreMiddlewareHarness({ session });
|
|
req.isAdmin = true; // the teardown must remove even a pre-set authority flag
|
|
await mw(req, {}, next);
|
|
|
|
// Request-local authority: GONE.
|
|
assert.strictEqual(req.session?.user, undefined, "the failed restore must not leave req.session.user on the live request");
|
|
assert.strictEqual(req.session?.accountId, undefined, "the failed restore must not leave req.session.accountId on the live request");
|
|
assert.strictEqual(req.session?.accountEpoch, undefined, "the failed restore must not leave req.session.accountEpoch on the live request");
|
|
assert.strictEqual(req.session?.browserSessionAudit, undefined, "the failed restore must not leave req.session.browserSessionAudit on the live request");
|
|
assert.strictEqual(req.session?.rememberLoginId, undefined, "the failed restore must not leave the registry binding on the live request");
|
|
assert.strictEqual(req.currentUser, null, "getLoggedInUser's req.currentUser fast path must resolve to null after the failure");
|
|
assert.ok(!req.isAdmin, "the request must not carry an admin flag after the failure");
|
|
// Downstream authorization: DENIED — the exact primitives every gate uses.
|
|
assert.strictEqual(await isAuthenticated(req), false, "await isAuthenticated(req) must be false after a failed restore");
|
|
assert.strictEqual(await isAdmin(req), false, "await isAdmin(req) must be false after a failed restore");
|
|
// Store/registry/cookie hygiene: RETAINED (never weakened).
|
|
assert.deepStrictEqual(calls.revokedIds, ["rotated-remember-id-3"], "the rotated registry id is still revoked");
|
|
assert.deepStrictEqual(calls.tombstoneSids, ["regenerated-sid-2"], "the regenerated sid is still tombstoned");
|
|
assert.strictEqual(calls.clearCookie, 1, "the remember cookie is still cleared");
|
|
assert.strictEqual(calls.next, 1, "the catch still continues (now anonymous) exactly once");
|
|
assert.deepStrictEqual(calls.nextArgs, [[]], "next() takes no error argument (fail closed, not a 500)");
|
|
});
|
|
|
|
test("a save that TIMES OUT must deauthorize the current request too", async () => {
|
|
// Same denial for the timeout direction: the never-settling store stub
|
|
// rejects with the label at the 5s bound, and the teardown must treat the
|
|
// request exactly like the instant-rejection direction.
|
|
const session = {
|
|
regenerate: (cb) => { req.sessionID = "regenerated-sid-2"; cb(null); },
|
|
save: () => { /* never settles — the timeout direction */ },
|
|
};
|
|
const { mw, calls, req, next, isAuthenticated, isAdmin } = buildRestoreMiddlewareHarness({ session });
|
|
req.isAdmin = true;
|
|
await mw(req, {}, next);
|
|
assert.strictEqual(req.session?.user, undefined, "the timeout direction must deauthorize the live request too");
|
|
assert.strictEqual(req.session?.accountId, undefined, "the account binding must not survive the timeout");
|
|
assert.strictEqual(req.currentUser, null, "the currentUser fast path must be null after the timeout");
|
|
assert.strictEqual(await isAuthenticated(req), false, "await isAuthenticated(req) must be false after the timeout");
|
|
assert.strictEqual(await isAdmin(req), false, "await isAdmin(req) must be false after the timeout");
|
|
assert.deepStrictEqual(calls.tombstoneSids, ["regenerated-sid-2"], "the regenerated sid is still tombstoned (store surface)");
|
|
assert.deepStrictEqual(calls.revokedIds, ["rotated-remember-id-3"], "the rotated registry id is still revoked (credential surface)");
|
|
assert.strictEqual(calls.next, 1, "the catch still continues (now anonymous) exactly once");
|
|
});
|
|
|
|
test("a cleanup-step rejection must NOT skip the tombstone nor authorize the request", async () => {
|
|
// Each awaited cleanup step is individually guarded: a lineage-revoke
|
|
// rejection must not (a) escape the catch (the non-rethrow posture),
|
|
// (b) skip the sid tombstone, nor (c) leave the request authorized — the
|
|
// authority clear happens synchronously BEFORE the awaited cleanup, so a
|
|
// late rejection cannot re-authorize anything.
|
|
const session = {
|
|
regenerate: (cb) => { req.sessionID = "regenerated-sid-2"; cb(null); },
|
|
save: (cb) => cb(new Error("synthetic store failure")),
|
|
};
|
|
const { mw, calls, req, next, isAuthenticated } = buildRestoreMiddlewareHarness({
|
|
session,
|
|
revokeImpl: async () => { throw new Error("synthetic lineage revoke failure"); },
|
|
});
|
|
let mwError = null;
|
|
try {
|
|
await mw(req, {}, next);
|
|
} catch (err) {
|
|
mwError = err;
|
|
}
|
|
assert.strictEqual(mwError, null, "the catch keeps its non-rethrow posture — a cleanup rejection must not escape the middleware");
|
|
assert.deepStrictEqual(calls.tombstoneSids, ["regenerated-sid-2"], "the tombstone is still attempted after the revoke rejected");
|
|
assert.strictEqual(await isAuthenticated(req), false, "downstream authorization stays denied after a cleanup failure");
|
|
assert.strictEqual(req.currentUser, null, "the authority clear precedes the awaited cleanup and must survive its failure");
|
|
assert.strictEqual(calls.next, 1, "the catch still continues (now anonymous) exactly once");
|
|
});
|
|
|
|
test("a response-end style store set for the tombstoned sid is refused after the teardown", async () => {
|
|
// The store-surface contract (adpanel:restore-save-failure-tombstone),
|
|
// proven through the REAL machinery: after the failed restore's teardown
|
|
// tombstoned the regenerated sid, a late express-session end-handler style
|
|
// set() for that sid — carrying the authenticated record — must be refused
|
|
// (and re-destroyed) by the REAL store guard.
|
|
const session = {
|
|
regenerate: (cb) => { req.sessionID = "regenerated-sid-2"; cb(null); },
|
|
save: () => { /* never settles — the timeout direction */ },
|
|
};
|
|
const { mw, calls, req, next, lateStore, lateStoreWrites, lateStoreDestroys } = buildRestoreMiddlewareHarness({ session });
|
|
await mw(req, {}, next);
|
|
assert.deepStrictEqual(calls.tombstoneSids, ["regenerated-sid-2"], "the teardown tombstoned the regenerated sid");
|
|
await new Promise((resolve) => lateStore.set("regenerated-sid-2", { user: LIVE_USER.email, accountId: 1, rememberLoginId: "rotated-remember-id-3" }, resolve));
|
|
assert.deepStrictEqual(lateStoreWrites, [], "the store guard refused the late authenticated record for the tombstoned sid");
|
|
assert.deepStrictEqual(lateStoreDestroys, ["regenerated-sid-2"], "the refused write re-destroyed the record (wrapper contract)");
|
|
});
|
|
|
|
test("a successful restore keeps the request AUTHORIZED (deauthorization is failure-only)", async () => {
|
|
// The deauthorization must be failure-only: a successful restore binds the
|
|
// identity, marks freshness, and downstream authorizes exactly as before.
|
|
const session = {
|
|
regenerate: (cb) => { req.sessionID = "regenerated-sid-2"; cb(null); },
|
|
save: (cb) => cb(null),
|
|
};
|
|
const { mw, calls, req, next, isAuthenticated, isAdmin } = buildRestoreMiddlewareHarness({ session });
|
|
await mw(req, {}, next);
|
|
assert.strictEqual(req.session.user, LIVE_USER.email, "the identity stays bound on success");
|
|
assert.strictEqual(req.session.accountId, 1, "the account binding stays on success");
|
|
assert.ok("rememberLoginCheckedAt" in req.session && "rememberLoginExpiresAt" in req.session, "freshness is marked on success");
|
|
assert.strictEqual(req.currentUser?.id, LIVE_USER.id, "req.currentUser is bound on success");
|
|
assert.strictEqual(await isAuthenticated(req), true, "downstream authorizes the restored session");
|
|
assert.strictEqual(await isAdmin(req), false, "isAdmin resolves (false for this non-admin row) — the gate itself works");
|
|
assert.deepStrictEqual(calls.revokedIds, [], "no revocation on success");
|
|
assert.deepStrictEqual(calls.tombstoneSids, [], "no tombstone on success");
|
|
});
|
|
|
|
test("a successful restore records the durable audit row and the attempt log, revoking nothing", async () => {
|
|
// adpanel:restore-attempt-observability — I-1: restore is an authentication
|
|
// event; on success it must land the same durable forensic row the two
|
|
// login completion paths land (method "remember-restore", fire-and-forget),
|
|
// and every cookie-presenting attempt must be visible via securityLog. The
|
|
// harness's save resolves, so the REAL restore success path runs end to end
|
|
// through the middleware.
|
|
const session = {
|
|
regenerate: (cb) => { req.sessionID = "regenerated-sid-2"; cb(null); },
|
|
save: (cb) => cb(null),
|
|
};
|
|
const { mw, calls, req, next } = buildRestoreMiddlewareHarness({ session });
|
|
await mw(req, {}, next);
|
|
assert.deepStrictEqual(
|
|
calls.auditMethods,
|
|
["remember-restore"],
|
|
"the restore's success exit must record the durable audit row with method remember-restore"
|
|
);
|
|
assert.deepStrictEqual(
|
|
calls.events,
|
|
["clearState", "audit:remember-restore", "next"],
|
|
"the audit call sits after the bounded save (the restore body's last hygiene) and immediately before next() — the login paths' call-site position"
|
|
);
|
|
assert.deepStrictEqual(
|
|
calls.securityLogs,
|
|
["remember-restore attempt"],
|
|
"every cookie-presenting restore attempt logs the securityLog line (attempt observability)"
|
|
);
|
|
assert.deepStrictEqual(calls.revokedIds, [], "a successful restore must NOT revoke the just-rotated credential");
|
|
assert.deepStrictEqual(calls.tombstoneSids, [], "a bare pre-auth sid takes the normal untombstoned path");
|
|
assert.strictEqual(calls.next, 1, "the middleware continues authenticated exactly once");
|
|
assert.deepStrictEqual(calls.nextArgs, [[]], "next() takes no error argument");
|
|
assert.strictEqual(req.session.user, LIVE_USER.email, "the session is bound (the audit row's subject)");
|
|
});
|
|
|
|
test("a pre-rotate failure revokes the referenced PRE-EXISTING registry id (coherent hygiene)", async () => {
|
|
// The catch's chosen semantics pinned: on a PRE-rotate failure (the lookup
|
|
// throws before regenerate/rotate ever ran) the session still references
|
|
// its PRE-EXISTING registry id, and the catch revokes THAT. This is
|
|
// coherent, not collateral damage: the clearCookie in the same response
|
|
// already took that credential's cookie from the client, so a live
|
|
// registry entry for a credential the client no longer holds must not
|
|
// survive — never leave a live entry for a cookie this response cleared.
|
|
const session = { rememberLoginId: "pre-existing-remember-id" };
|
|
const { mw, calls, req, next } = buildRestoreMiddlewareHarness({
|
|
session,
|
|
// A genuine (non-timeout) lookup error rejects instantly through the
|
|
// withTimeout race — the pre-rotate direction that reaches the catch.
|
|
findUserById: async () => { throw new Error("synthetic db failure"); },
|
|
});
|
|
await mw(req, {}, next);
|
|
assert.deepStrictEqual(
|
|
calls.revokedIds,
|
|
["pre-existing-remember-id"],
|
|
"the catch revokes whatever registry id the session references at catch time — here the pre-existing one"
|
|
);
|
|
assert.deepStrictEqual(
|
|
calls.events,
|
|
["clearState", "clearCookie", "revoke:pre-existing-remember-id", "tombstone:pre-restore-sid-1", "destroy", "cacheRemove:pre-restore-sid-1", "cacheInvalidate", "next"],
|
|
"the coherent-hygiene ordering: clear state → clear cookie → revoke(referenced id) → tombstone → destroy → cache → next"
|
|
);
|
|
assert.deepStrictEqual(
|
|
calls.tombstoneSids,
|
|
["pre-restore-sid-1"],
|
|
"a pre-bind failure tombstones the unauthenticated pre-auth sid (regenerate never ran — documented posture)"
|
|
);
|
|
assert.deepStrictEqual(calls.auditMethods, [], "a failed restore records NO durable audit row");
|
|
assert.strictEqual(calls.next, 1, "the catch continues unauthenticated exactly once");
|
|
});
|
|
|
|
test("a failure on a session referencing NO registry id must NOT fire the revoke", async () => {
|
|
// No over-firing: the revoke is guarded on the referenced id — a bare
|
|
// pre-auth session (no rememberLoginId residue) has nothing to revoke, and
|
|
// the rest of the catch hygiene is unchanged.
|
|
const session = {};
|
|
const { mw, calls, req, next } = buildRestoreMiddlewareHarness({
|
|
session,
|
|
findUserById: async () => { throw new Error("synthetic db failure"); },
|
|
});
|
|
await mw(req, {}, next);
|
|
assert.deepStrictEqual(calls.revokedIds, [], "no referenced registry id — the revoke must not fire");
|
|
assert.deepStrictEqual(
|
|
calls.events,
|
|
["clearState", "clearCookie", "tombstone:pre-restore-sid-1", "destroy", "cacheRemove:pre-restore-sid-1", "cacheInvalidate", "next"],
|
|
"clear state → clear cookie → tombstone → destroy → cache → next, with no revoke step"
|
|
);
|
|
});
|
|
|
|
test("a FAILED revocation still tombstones and continues to next() (DLQ-covered, catch never wedges)", async () => {
|
|
// The revoke's own failure direction: revokeRememberLoginLineage (the
|
|
// WAVE-3 upgrade of the single-id twin) never rejects — on a Redis failure
|
|
// it dead-letters the id and chain members and returns — so the catch must
|
|
// keep its contract: the sid tombstone still runs and the request still
|
|
// continues unauthenticated, regardless of the revoke's outcome.
|
|
const session = {
|
|
regenerate: (cb) => { req.sessionID = "regenerated-sid-2"; cb(null); },
|
|
// An instant store rejection reaches the same catch (the error direction
|
|
// the tombstone covers) without the 5s stall.
|
|
save: (cb) => cb(new Error("synthetic store failure")),
|
|
};
|
|
const { mw, calls, req, next } = buildRestoreMiddlewareHarness({
|
|
session,
|
|
revokeImpl: async () => false, // the revocation FAILED (dead-lettered upstream)
|
|
});
|
|
await mw(req, {}, next);
|
|
assert.deepStrictEqual(
|
|
calls.revokedIds,
|
|
["rotated-remember-id-3"],
|
|
"the revoke was still attempted with the rotated id"
|
|
);
|
|
assert.deepStrictEqual(
|
|
calls.tombstoneSids,
|
|
["regenerated-sid-2"],
|
|
"the sid tombstone still runs after a failed revocation"
|
|
);
|
|
assert.strictEqual(calls.next, 1, "the catch continues unauthenticated regardless of the revoke's outcome");
|
|
assert.deepStrictEqual(calls.nextArgs, [[]], "next() takes no error argument");
|
|
});
|
|
|
|
test("a failed tombstone write still warns and continues (the original error is not rethrown)", async () => {
|
|
// The false-branch contract: the durable write failing must not convert the
|
|
// restore failure into a wedged/500 request — warn in the binder's style and
|
|
// continue unauthenticated (the dead-letter queue retries the write).
|
|
const session = {
|
|
regenerate: (cb) => { req.sessionID = "regenerated-sid-2"; cb(null); },
|
|
save: () => { /* never settles — the timeout direction the tombstone covers */ },
|
|
};
|
|
const { mw, calls, req, next } = buildRestoreMiddlewareHarness({
|
|
session,
|
|
tombstoneImpl: async () => false, // the durable write failed
|
|
});
|
|
await mw(req, {}, next); // must RESOLVE — no rethrow of the original error
|
|
assert.strictEqual(calls.next, 1, "the catch still ends in next() — the request proceeds unauthenticated");
|
|
assert.deepStrictEqual(calls.nextArgs, [[]], "next() takes no error argument");
|
|
assert.ok(
|
|
calls.warnings.some((w) => w.includes("Could not tombstone post-regeneration session") && w.includes("sid:regenerated-sid-2")),
|
|
"the binder-style warn fires on the false write, naming the sid"
|
|
);
|
|
assert.ok(
|
|
calls.warnings.some((w) => w.includes("Persistent login restore failed") && w.includes("session-save-timeout")),
|
|
"the original error's warn is unchanged"
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source pin — the restore path's first DB read is bounded at the call site
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("restore's user lookup is wrapped with the login path's 8s bound and label", () => {
|
|
// adpanel:restore-lookup-bound — findUserById is a bare db.query; only the
|
|
// RESTORE call site wraps it (the login path's sibling findUserByEmail
|
|
// bounds its own reads at 8s "find-user-timeout" — same bound, same
|
|
// <what>-timeout label vocabulary).
|
|
assert.match(
|
|
RESTORE_SOURCE,
|
|
/const user = await withTimeout\(\s*findUserById\(parsed\.uid\),\s*8000,\s*"remember-restore-user-lookup-timeout"\s*\);/,
|
|
"the restore user lookup must carry the login path's 8s bound and the shared label vocabulary"
|
|
);
|
|
|
|
// The lookup is the first bounded step: it precedes the regenerate wrap.
|
|
const lookupIdx = RESTORE_SOURCE.indexOf('"remember-restore-user-lookup-timeout"');
|
|
const regenIdx = RESTORE_SOURCE.indexOf('"session-regenerate-timeout"');
|
|
assert.ok(lookupIdx >= 0 && regenIdx > lookupIdx,
|
|
"the bounded lookup must run before the bounded regenerate (lookup → regenerate → rotate → save)");
|
|
|
|
// Call-site-only: the definition stays a bare db.query. The scheduler
|
|
// resolver (resolveSchedulerAgentUser) and the agent job worker call it off
|
|
// the request path and own their own error contracts — a definition-level
|
|
// wrap would change what those callers must handle.
|
|
const findByIdBlock = extractBlock(indexSource, "async function findUserById(id) {");
|
|
assert.ok(!findByIdBlock.includes("withTimeout"),
|
|
"findUserById's definition must stay unbounded — only the restore call site owns the bound");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source pins — the confirmed revoke's three bounded reads
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("all three Confirmed reads are bounded with the shared revoke-write constant", () => {
|
|
// The shared constant + label exist near the tombstone constants.
|
|
assert.match(indexSource, /const REMEMBER_REVOKE_WRITE_TIMEOUT_MS = Math\.max\(/,
|
|
"the shared 1s bound must stay a named constant");
|
|
assert.match(indexSource, /const REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL = "remember-revoke-write-timeout";/,
|
|
"the shared label must stay a named constant");
|
|
|
|
// Exactly three withTimeout sites in the function: read (a) hGet, read (b)
|
|
// sweep hGetAll, read (c) verify hGetAll. The delete is NOT among them — it
|
|
// bounds its own MULTI exec inside deleteRememberLoginRegistryFields.
|
|
const wrapCount = (CONFIRMED_SOURCE.match(/await withTimeout\(/g) || []).length;
|
|
assert.strictEqual(wrapCount, 3, "exactly the three reads may be wrapped — no more, no less");
|
|
assert.doesNotMatch(
|
|
CONFIRMED_SOURCE,
|
|
/await withTimeout\(\s*deleteRememberLoginRegistryFields/,
|
|
"the delete must not be double-wrapped"
|
|
);
|
|
|
|
// Read (a): owner-source hGet — timeout degrades to null (the local-registry
|
|
// fallback below is built for a missing remote entry); every OTHER error
|
|
// rethrows to the outer catch.
|
|
assert.match(
|
|
CONFIRMED_SOURCE,
|
|
/let rawEntry = null;\s*try \{\s*rawEntry = await withTimeout\(\s*redisClient\.hGet\(REMEMBER_LOGIN_REGISTRY_REDIS_KEY, id\),\s*REMEMBER_REVOKE_WRITE_TIMEOUT_MS,\s*REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL\s*\);\s*\} catch \(err\) \{\s*if \(err\?\.message !== REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL\) throw err;\s*rawEntry = null;\s*\}/,
|
|
"read (a) must convert ONLY the labeled timeout to null; non-timeout errors must keep propagating"
|
|
);
|
|
|
|
// Read (b): sweep hGetAll — wrapped, NO local catch: any rejection (timeout
|
|
// included) must reach the outer catch → redis-error → route 503 + retry.
|
|
assert.match(
|
|
CONFIRMED_SOURCE,
|
|
/const hash = await withTimeout\(\s*redisClient\.hGetAll\(REMEMBER_LOGIN_REGISTRY_REDIS_KEY\),\s*REMEMBER_REVOKE_WRITE_TIMEOUT_MS,\s*REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL\s*\);/,
|
|
"the sweep read must be bounded with the shared constant"
|
|
);
|
|
const sweepReadIdx = CONFIRMED_SOURCE.indexOf("const hash = await withTimeout(");
|
|
const sweepReadWindow = CONFIRMED_SOURCE.slice(sweepReadIdx, CONFIRMED_SOURCE.indexOf("const raceCutoff", sweepReadIdx));
|
|
assert.ok(!sweepReadWindow.includes("catch"),
|
|
"the sweep read must have no local catch swallowing its timeout (fail closed via the outer catch)");
|
|
|
|
// Read (c): final verification hGetAll — same posture: wrapped, no local
|
|
// catch; success is never reported without the verify completing.
|
|
assert.match(
|
|
CONFIRMED_SOURCE,
|
|
/const verifyHash = await withTimeout\(\s*redisClient\.hGetAll\(REMEMBER_LOGIN_REGISTRY_REDIS_KEY\),\s*REMEMBER_REVOKE_WRITE_TIMEOUT_MS,\s*REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL\s*\);/,
|
|
"the verification read must be bounded with the shared constant"
|
|
);
|
|
const verifyReadIdx = CONFIRMED_SOURCE.indexOf("const verifyHash = await withTimeout(");
|
|
const verifyReadWindow = CONFIRMED_SOURCE.slice(verifyReadIdx, CONFIRMED_SOURCE.indexOf("if (verifyHash &&", verifyReadIdx));
|
|
assert.ok(!verifyReadWindow.includes("catch"),
|
|
"the verification read must have no local catch swallowing its timeout (never a partial-sweep success)");
|
|
|
|
assert.strictEqual(
|
|
(CONFIRMED_SOURCE.match(/adpanel:confirmed-revoke-read-bounds/g) || []).length,
|
|
3,
|
|
"each bounded read must carry the adpanel:confirmed-revoke-read-bounds comment"
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavior pins — vm-extracted regions against real-semantics withTimeout
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// Same real race the index.js helper implements (verbatim from
|
|
// tests/remember-revoke-durable.test.js): the extracted regions call
|
|
// withTimeout, so the sandbox must provide the REAL semantics — a passthrough
|
|
// would make every stall pin below prove nothing.
|
|
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));
|
|
}
|
|
|
|
const LIVE_PARSED = { v: 2, uid: "1", iat: 1700000000000, exp: 4102444800000, fp: "fp", jti: "remember-id-restore" };
|
|
const LIVE_USER = { id: 1, email: "user@example.test", password: "x", suspended: false, session_epoch: 3 };
|
|
|
|
function buildRestoreHarness({ session, findUserById, parsedToken = LIVE_PARSED, fingerprint = () => "fp", compare = () => true }) {
|
|
const calls = { rotate: 0, clearState: 0, clearCookie: 0, markFresh: 0, tombstone: 0 };
|
|
const events = [];
|
|
const req = { cookies: { "adpanel.remember": "tok" }, session, sessionID: "restore-sid-1" };
|
|
const sandbox = {
|
|
console: { log: () => {}, warn: () => {} },
|
|
REMEMBER_LOGIN_COOKIE_NAME: "adpanel.remember",
|
|
readRememberLoginToken: () => parsedToken,
|
|
// adpanel:restore-attempt-observability — the restore body now calls
|
|
// securityLog on every cookie-presenting attempt and the ONE audit
|
|
// recorder on its success exit; the middleware harness pins that
|
|
// behavior end to end, these no-ops just keep the real restore body
|
|
// runnable in this sandbox.
|
|
securityLog: () => {},
|
|
loginAuditRecorder: { recordSuccessfulLoginAudit: () => {} },
|
|
// adpanel:remote-proxy-trust-gate — the restore body's issuance-gate
|
|
// check; default-off/no-violation (false) keeps every pin here on the
|
|
// pre-existing path (the refusal behavior lives in
|
|
// tests/remote-proxy-trust-gate.test.js with the REAL helper).
|
|
remoteProxyTrustBlocksRememberIssuance: () => false,
|
|
findUserById: findUserById || (async () => LIVE_USER),
|
|
// adpanel:credential-generation — the REAL shared predicate: the restore
|
|
// body's staleness re-verify calls it on (snapshot epoch, fresh row epoch).
|
|
credentialGenerationMismatch,
|
|
...require("../utils/remember-login-completion"),
|
|
isSessionSidRevoked: async () => false,
|
|
safeCompare: compare,
|
|
getRememberLoginFingerprint: fingerprint,
|
|
getRememberLoginLegacyCutoff: () => 0,
|
|
isManagedRememberLoginToken: () => true,
|
|
revokeRememberLoginsForUser: async () => {},
|
|
writeRevokedSidTombstone: async () => { calls.tombstone += 1; events.push("tombstone"); return true; },
|
|
// adpanel:login-bind-preauth-pending-tombstone — the restore's tombstone
|
|
// condition calls this predicate; the sandbox copy mirrors index.js's
|
|
// definition (the solved-captcha flag + the pending-captcha-login record)
|
|
// so the behavior pins below exercise the REAL condition branch.
|
|
sessionCarriesProtectedPendingAuthState: (sess) =>
|
|
!!sess && (sess.captchaSolved === true || !!(sess.pendingCaptchaLogin && typeof sess.pendingCaptchaLogin === "object")),
|
|
getSessionDisplayId: (id) => `sid:${id}`,
|
|
clearRememberLoginSessionState: () => { calls.clearState += 1; },
|
|
clearRememberLoginCookie: () => { calls.clearCookie += 1; },
|
|
rotateRememberLoginCookie: async () => { calls.rotate += 1; return 4102444800000; },
|
|
buildBrowserSessionAuditFromRequest: () => ({ rememberLoginId: LIVE_PARSED.jti }),
|
|
markRememberLoginSessionFresh: () => { calls.markFresh += 1; },
|
|
withTimeout: sandboxWithTimeout,
|
|
req,
|
|
};
|
|
vm.createContext(sandbox);
|
|
const fn = vm.runInContext(`(${RESTORE_SOURCE})`, sandbox, { filename: "restore-sandbox.js" });
|
|
return { fn, calls, events, req, session };
|
|
}
|
|
|
|
test("saved-login fingerprints bind the account generation without changing email-independent matching", () => {
|
|
const crypto = require("node:crypto");
|
|
const { getRememberLoginFingerprint } = require("../utils/remember-login-fingerprint");
|
|
const user = { ...LIVE_USER, secret: null };
|
|
const before = getRememberLoginFingerprint(user);
|
|
assert.notStrictEqual(before, getRememberLoginFingerprint({ ...user, session_epoch: 4 }));
|
|
assert.notStrictEqual(before, getRememberLoginFingerprint({ ...user, password: "new hash" }));
|
|
assert.notStrictEqual(before, getRememberLoginFingerprint({ ...user, secret: "new secret" }));
|
|
assert.strictEqual(before, getRememberLoginFingerprint({ ...user, email: "renamed@example.test", suspended: false }));
|
|
assert.strictEqual(before, getRememberLoginFingerprint({ ...user, session_epoch: "3" }));
|
|
assert.strictEqual(getRememberLoginFingerprint(null), "");
|
|
const oldFingerprint = crypto.createHash("sha256").update(user.password).update("\n").update("").digest("hex");
|
|
assert.notStrictEqual(before, oldFingerprint, "a compatibility fallback must not accept pre-generation saved-login proofs");
|
|
assert.strictEqual(indexSource.split('require("./utils/remember-login-fingerprint")').length - 1, 1);
|
|
assert.ok(!indexSource.includes("function getRememberLoginFingerprint(user) {"), "the utility must be the only implementation");
|
|
});
|
|
|
|
test("a saved login missed by suspension revocation cannot restore after unsuspension", async () => {
|
|
const { getRememberLoginFingerprint } = require("../utils/remember-login-fingerprint");
|
|
const crypto = require("node:crypto");
|
|
const compareSource = extractBlock(indexSource, "function safeCompare(a, b) {");
|
|
const compare = vm.runInNewContext(`(${compareSource})`, { Buffer, crypto });
|
|
const before = { ...LIVE_USER, secret: null };
|
|
const unsuspended = { ...before, session_epoch: 4, suspended: false };
|
|
const parsedToken = { ...LIVE_PARSED, fp: getRememberLoginFingerprint(before) };
|
|
const makeSession = () => ({ regenerate: (callback) => callback(null), save: (callback) => callback(null) });
|
|
const stale = buildRestoreHarness({ session: makeSession(), findUserById: async () => unsuspended, parsedToken, fingerprint: getRememberLoginFingerprint, compare });
|
|
assert.strictEqual(await stale.fn(stale.req, {}), false);
|
|
assert.strictEqual(stale.calls.rotate, 0, "a stale saved login is rejected before identifier rotation");
|
|
assert.strictEqual(stale.calls.markFresh, 0);
|
|
assert.strictEqual(stale.calls.clearCookie, 1);
|
|
assert.strictEqual(stale.req.session.user, undefined);
|
|
assert.strictEqual(stale.req.currentUser, undefined);
|
|
|
|
const current = buildRestoreHarness({ session: makeSession(), findUserById: async () => unsuspended,
|
|
parsedToken: { ...parsedToken, fp: getRememberLoginFingerprint(unsuspended) }, fingerprint: getRememberLoginFingerprint, compare });
|
|
assert.strictEqual(await current.fn(current.req, {}), true, "a newly authenticated post-suspension saved login still works");
|
|
assert.strictEqual(current.req.session.accountEpoch, unsuspended.session_epoch);
|
|
});
|
|
|
|
test("a never-settling store regenerate rejects with the label within the 5s bound", async () => {
|
|
const { fn, calls, req } = buildRestoreHarness({
|
|
// express-session reports through the callback; a wedged store never
|
|
// calls it — exactly the stall this bound exists for.
|
|
session: { regenerate: () => { /* never settles */ } },
|
|
});
|
|
const started = Date.now();
|
|
await assert.rejects(
|
|
fn(req, {}),
|
|
{ message: "session-regenerate-timeout" },
|
|
"the bounded regenerate must reject with the shared label, not hang"
|
|
);
|
|
const elapsed = Date.now() - started;
|
|
assert.ok(elapsed >= 4900, `the bound must actually arm 5000ms (elapsed ${elapsed}ms)`);
|
|
assert.ok(elapsed < 9000, `the rejection must arrive within the bound (elapsed ${elapsed}ms)`);
|
|
// The rejection escapes the restore body untouched: nothing after the wrap
|
|
// runs, and the restore does not swallow it — the middleware's catch owns
|
|
// the fail-closed teardown.
|
|
assert.strictEqual(calls.rotate, 0, "the rotate must not run after a timed-out regenerate");
|
|
assert.strictEqual(calls.clearState, 0, "the restore itself must not clear state (the middleware catch owns that)");
|
|
assert.strictEqual(calls.clearCookie, 0, "the restore itself must not clear the cookie (the middleware catch owns that)");
|
|
});
|
|
|
|
test("a never-settling store save rejects with the label within the 5s bound", async () => {
|
|
let boundUser = null;
|
|
const session = {
|
|
regenerate: (cb) => cb(null),
|
|
save: () => { /* never settles */ },
|
|
};
|
|
const { fn, calls, req } = buildRestoreHarness({ session });
|
|
const started = Date.now();
|
|
await assert.rejects(
|
|
fn(req, {}),
|
|
{ message: "session-save-timeout" },
|
|
"the bounded save must reject with the shared label, not hang"
|
|
);
|
|
const elapsed = Date.now() - started;
|
|
assert.ok(elapsed >= 4900, `the bound must actually arm 5000ms (elapsed ${elapsed}ms)`);
|
|
assert.ok(elapsed < 9000, `the rejection must arrive within the bound (elapsed ${elapsed}ms)`);
|
|
// The bind completed before the bounded save (rotation → bind → save order).
|
|
assert.strictEqual(calls.rotate, 1, "the rotate must have succeeded before the save");
|
|
assert.strictEqual(calls.markFresh, 1, "the remember-freshness mark must have run before the save");
|
|
assert.strictEqual(session.user, LIVE_USER.email, "the session must already be bound when the save stalls");
|
|
assert.strictEqual(session.accountId, 1, "the account binding precedes the bounded save");
|
|
});
|
|
|
|
test("a never-settling restore user lookup rejects with the label within the 8s bound", async () => {
|
|
// adpanel:restore-lookup-bound — the wedge this bound exists for: a stalled
|
|
// DB never settles the lookup promise. The real-semantics withTimeout in the
|
|
// sandbox must reject with the label inside the 8s bound.
|
|
const { fn, calls, req } = buildRestoreHarness({
|
|
session: { regenerate: (cb) => cb(null) },
|
|
findUserById: () => new Promise(() => {}), // the stalled DB read wedges
|
|
});
|
|
const started = Date.now();
|
|
await assert.rejects(
|
|
fn(req, {}),
|
|
{ message: "remember-restore-user-lookup-timeout" },
|
|
"the bounded lookup must reject with the shared label, not hang"
|
|
);
|
|
const elapsed = Date.now() - started;
|
|
assert.ok(elapsed >= 7900, `the bound must actually arm 8000ms (elapsed ${elapsed}ms)`);
|
|
assert.ok(elapsed < 12000, `the rejection must arrive within the bound (elapsed ${elapsed}ms)`);
|
|
// The rejection escapes the restore body untouched — the middleware's catch
|
|
// owns the fail-closed teardown (its clear-cookie + clear-state + continue
|
|
// shape is source-pinned above). Nothing after the lookup wrap runs.
|
|
assert.strictEqual(calls.rotate, 0, "the rotate must not run after a timed-out lookup");
|
|
assert.strictEqual(calls.clearState, 0, "the restore itself must not clear state (the middleware catch owns that)");
|
|
assert.strictEqual(calls.clearCookie, 0, "the restore itself must not clear the cookie (the middleware catch owns that)");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source + behavior pins — the staleness re-verify's credential-generation
|
|
// epoch leg and the fresh-row bind (adpanel:credential-generation)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("an epoch bump between the snapshot row and the staleness re-read fails the restore closed (no bind, no marks)", async () => {
|
|
// adpanel:credential-generation — the write-side contract: the credential
|
|
// writers bump session_epoch IN THE SAME STATEMENT as the credential they
|
|
// change, so a password/2FA change committing inside the restore's
|
|
// read→bind gap (the bounded rotation CAS sat in between) shows up as an
|
|
// epoch difference between the two bounded row reads. The re-verify's
|
|
// epoch leg must convert that into the SAME fail-closed clear shape as the
|
|
// fingerprint leg — a proof minted against generation 3 is never promoted
|
|
// onto generation 4, and the just-rotated identifier dies with the cleared
|
|
// cookie (its replay fails the next restore's own re-verify).
|
|
let lookupCalls = 0;
|
|
const { fn, calls, req, session } = buildRestoreHarness({
|
|
session: { regenerate: (cb) => cb(null) },
|
|
findUserById: async () => {
|
|
lookupCalls += 1;
|
|
return lookupCalls === 1
|
|
? LIVE_USER
|
|
: { ...LIVE_USER, session_epoch: LIVE_USER.session_epoch + 1 };
|
|
},
|
|
});
|
|
const ok = await fn(req, {});
|
|
assert.strictEqual(ok, false, "the epoch leg fails the restore closed — a pre-bump proof never reaches the bind");
|
|
assert.strictEqual(lookupCalls, 2, "both bounded row reads ran (the bump sat in the read→bind gap)");
|
|
assert.strictEqual(calls.rotate, 1, "the rotation CAS had already re-pointed the identifier — exactly the window the epoch leg closes");
|
|
assert.strictEqual(calls.clearState, 1, "the fail-closed clear ran (the same shape as the fingerprint leg)");
|
|
assert.strictEqual(calls.clearCookie, 1, "the stale remember cookie is cleared");
|
|
assert.strictEqual(calls.markFresh, 0, "NO freshness marks on the failed restore");
|
|
assert.strictEqual(session.user, undefined, "NO identity bound from the stale snapshot row");
|
|
assert.strictEqual(session.accountId, undefined, "no account binding on the failed restore");
|
|
assert.strictEqual(session.accountEpoch, undefined, "the stale generation is never written into the session");
|
|
assert.strictEqual(session.browserSessionAudit, undefined, "no browser-session audit binding");
|
|
assert.strictEqual(req.currentUser, undefined, "the currentUser fast path is never bound");
|
|
});
|
|
|
|
test("the restore binds identity, epoch and currentUser from the FRESH re-read row, not the snapshot", async () => {
|
|
// The two rows are fingerprint-equal and generation-equal by construction
|
|
// (the epoch leg guarantees the latter — this row's epoch matches), so the
|
|
// re-read row is the authoritative identity object: a non-credential row
|
|
// change that lands mid-restore (email rename — not a credential write, no
|
|
// epoch bump) must bind the CURRENT row's identity, never the stale
|
|
// snapshot's.
|
|
const snapshotRow = { ...LIVE_USER };
|
|
const freshRow = { ...LIVE_USER, email: "renamed@example.test" };
|
|
let lookupCalls = 0;
|
|
const { fn, calls, req, session } = buildRestoreHarness({
|
|
session: { regenerate: (cb) => cb(null), save: (cb) => cb(null) },
|
|
findUserById: async () => {
|
|
lookupCalls += 1;
|
|
return lookupCalls === 1 ? snapshotRow : freshRow;
|
|
},
|
|
});
|
|
const ok = await fn(req, {});
|
|
assert.strictEqual(ok, true, "an epoch-equal, fingerprint-equal restore completes");
|
|
assert.strictEqual(req.currentUser, freshRow, "req.currentUser is the FRESH row object (reference identity)");
|
|
assert.strictEqual(session.user, "renamed@example.test", "the session identity binds the fresh row's email");
|
|
assert.strictEqual(session.accountId, freshRow.id, "the account id comes from the fresh row");
|
|
assert.strictEqual(session.accountEpoch, freshRow.session_epoch, "the epoch binding comes from the fresh row");
|
|
assert.strictEqual(calls.markFresh, 1, "the success path still marks freshness");
|
|
});
|
|
|
|
test("a legacy row without the epoch column stays uncomparable — the fingerprint leg alone admits the restore", async () => {
|
|
// credentialGenerationMismatch is comparable-only: an absent epoch on
|
|
// either side is UNCOMPARABLE, never a mismatch and never a coercion to 0.
|
|
// The restore's UNCONDITIONAL fingerprint re-check stays authoritative on
|
|
// legacy reads, so a row that predates the epoch column still restores
|
|
// (the shared contract's documented degraded posture) instead of failing
|
|
// closed on a schema artifact.
|
|
let lookupCalls = 0;
|
|
let freshLegacyRow = null;
|
|
const { fn, calls, req, session } = buildRestoreHarness({
|
|
session: { regenerate: (cb) => cb(null), save: (cb) => cb(null) },
|
|
findUserById: async () => {
|
|
lookupCalls += 1;
|
|
if (lookupCalls === 1) return { id: 1, email: "user@example.test", password: "x", suspended: false };
|
|
freshLegacyRow = { id: 1, email: "user@example.test", password: "x", suspended: false };
|
|
return freshLegacyRow;
|
|
},
|
|
});
|
|
const ok = await fn(req, {});
|
|
assert.strictEqual(ok, true, "the fingerprint leg alone admits a legacy read (epoch absent on both sides — uncomparable, not mismatched)");
|
|
assert.strictEqual(req.currentUser, freshLegacyRow, "the fresh row object is still the authoritative bind");
|
|
assert.strictEqual(session.user, "user@example.test", "the identity binds normally");
|
|
assert.strictEqual(session.accountEpoch, 0, "the epoch binding degrades to 0 for a row without the column (bind expression unchanged)");
|
|
assert.strictEqual(calls.markFresh, 1, "the success path is unchanged for legacy rows");
|
|
});
|
|
|
|
test("source pin: the epoch leg sits in the staleness re-verify's condition and the bind sources the fresh row", () => {
|
|
// The epoch leg is the ONE shared predicate (never an inline copy — the
|
|
// session-account-binding pins forbid that), applied to the SNAPSHOT row's
|
|
// epoch vs the re-read row's epoch, chained into the SAME fail-closed
|
|
// condition as the fingerprint leg; and every identity bind line sources
|
|
// the fresh row.
|
|
assert.match(
|
|
RESTORE_SOURCE,
|
|
/!safeCompare\(parsed\.fp, getRememberLoginFingerprint\(freshRestoreRow\)\) \|\|\s*\n\s*credentialGenerationMismatch\(user\.session_epoch, freshRestoreRow\.session_epoch\)/,
|
|
"the epoch leg is the shared predicate on (snapshot epoch, fresh row epoch), chained into the same fail-closed condition as the fingerprint leg"
|
|
);
|
|
for (const line of [
|
|
"req.session.user = freshRestoreRow.email;",
|
|
"req.session.accountId = Number(freshRestoreRow.id);",
|
|
"req.session.accountEpoch = Number(freshRestoreRow.session_epoch || 0);",
|
|
"req.session.browserSessionAudit = buildBrowserSessionAuditFromRequest(req, freshRestoreRow.email, req.session.rememberLoginId);",
|
|
"req.currentUser = freshRestoreRow;",
|
|
]) {
|
|
assert.ok(RESTORE_SOURCE.includes(line), `the bind sources the fresh row: ${line}`);
|
|
}
|
|
const reReadIdx = RESTORE_SOURCE.indexOf('const freshRestoreRow = await withTimeout(findUserById(parsed.uid), 8000, "remember-restore-staleness-lookup-timeout");');
|
|
const mismatchIdx = RESTORE_SOURCE.indexOf("credentialGenerationMismatch(user.session_epoch, freshRestoreRow.session_epoch)");
|
|
const bindIdx = RESTORE_SOURCE.indexOf("req.session.user = freshRestoreRow.email;");
|
|
assert.ok(reReadIdx >= 0 && mismatchIdx > reReadIdx && bindIdx > mismatchIdx,
|
|
"ordering is load-bearing: staleness re-read → epoch+fingerprint re-verify → fresh-row bind");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source + behavior pins — the restore's pre-regenerate tombstone adopts the
|
|
// binder's pending-state predicate (adpanel:login-bind-preauth-pending-tombstone)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("the restore's pre-regenerate tombstone condition adopts the binder's pending-state predicate", () => {
|
|
// The restore backstop used to tombstone only `req.session?.user`; the
|
|
// shared binder's condition additionally adopts pre-auth sids carrying
|
|
// protected pending auth state (solved captcha / pending captcha login).
|
|
// The restore now calls the SAME predicate (defined in index.js next to the
|
|
// pending-captcha machinery whose key names it owns), so a pre-auth sid
|
|
// carrying pending state is tombstoned before the regenerate too — an
|
|
// in-flight re-save could otherwise resurrect that pending login under the
|
|
// old sid. Reachability is narrow (the presenter holds a VALID remember
|
|
// cookie that passed every restore check) but the protection is free.
|
|
assert.match(
|
|
RESTORE_SOURCE,
|
|
/adpanel:login-bind-preauth-pending-tombstone[\s\S]*?if \(req\.session\?\.user \|\| sessionCarriesProtectedPendingAuthState\(req\.session\)\) \{[\s\S]*?await writeRevokedSidTombstone\(preRegenerateSid\)/,
|
|
"the restore must tombstone a pre-regeneration sid that is authenticated OR carries protected pending auth state (same predicate as the shared binder)"
|
|
);
|
|
|
|
// Ordering stays load-bearing: the tombstone precedes the bounded regenerate.
|
|
const condIdx = RESTORE_SOURCE.indexOf("sessionCarriesProtectedPendingAuthState(req.session)");
|
|
const regenIdx = RESTORE_SOURCE.indexOf('"session-regenerate-timeout"');
|
|
assert.ok(condIdx >= 0 && regenIdx > condIdx, "the predicate-gated tombstone must precede the bounded regenerate");
|
|
|
|
// Symmetry with the shared binder: the condition expression is identical.
|
|
const CONDITION = "if (req.session?.user || sessionCarriesProtectedPendingAuthState(req.session)) {";
|
|
const binderSource = fs.readFileSync(path.join(ROOT, "utils", "login-session-bind.js"), "utf8");
|
|
assert.ok(RESTORE_SOURCE.includes(CONDITION), "the restore condition must be byte-identical to the binder's");
|
|
assert.ok(binderSource.includes(CONDITION), "the binder condition must be byte-identical to the restore's");
|
|
});
|
|
|
|
test("a pre-auth sid carrying protected pending auth state is tombstoned before the regenerate", async () => {
|
|
// Behavior pin through the vm harness: the session carries the
|
|
// pending-captcha-login record (shaped like beginPendingCaptchaLogin's
|
|
// write — enough for the predicate), restore completes, and the sid's
|
|
// tombstone is durable BEFORE the regenerate (binder ordering).
|
|
const session = {
|
|
pendingCaptchaLogin: { email: LIVE_USER.email, createdAt: Date.now(), expiresAt: Date.now() + 60000 },
|
|
regenerate: (cb) => { events.push("regenerate"); cb(null); },
|
|
save: (cb) => cb(null),
|
|
};
|
|
const { fn, calls, events, req } = buildRestoreHarness({ session });
|
|
const ok = await fn(req, {});
|
|
assert.strictEqual(ok, true, "the restore completes (the pending-state tombstone must not fail the restore)");
|
|
assert.strictEqual(calls.tombstone, 1, "the pending-state sid must be tombstoned before the regenerate");
|
|
assert.deepStrictEqual(events, ["tombstone", "regenerate"], "the tombstone must be durable BEFORE the regenerate (binder ordering)");
|
|
});
|
|
|
|
test("a bare pre-auth sid stays skipped (no tombstone on a plain restore)", async () => {
|
|
// The predicate-gated condition must not over-fire: a plain pre-auth
|
|
// session (no user, no protected pending state) takes the restore's normal
|
|
// untombstoned path — exactly the binder's skip rule.
|
|
const session = {
|
|
regenerate: (cb) => { events.push("regenerate"); cb(null); },
|
|
save: (cb) => cb(null),
|
|
};
|
|
const { fn, calls, events, req } = buildRestoreHarness({ session });
|
|
const ok = await fn(req, {});
|
|
assert.strictEqual(ok, true, "the restore completes for a plain pre-auth session");
|
|
assert.strictEqual(calls.tombstone, 0, "a bare pre-auth sid must NOT be tombstoned (same skip as the binder)");
|
|
assert.deepStrictEqual(events, ["regenerate"], "no tombstone event before the regenerate");
|
|
});
|
|
|
|
// Shallow-copy into the host realm: the object returned by the vm-realm
|
|
// function carries that realm's Object prototype, which breaks deepStrictEqual
|
|
// (same realm-mismatch note as the deletes copy in
|
|
// tests/remember-revoke-durable.test.js). All copied fields are primitives.
|
|
function toHost(obj) {
|
|
return { ...obj };
|
|
}
|
|
|
|
function buildConfirmedHarness({ registry = {}, hGetImpl, hGetAllImpl, ownerHint = null, timeoutMs = 40 }) {
|
|
const deletes = [];
|
|
const warnings = [];
|
|
const sandbox = {
|
|
console: { log: () => {}, warn: (...a) => warnings.push(a.map(String).join(" ")) },
|
|
rememberLoginRegistry: registry,
|
|
locallyMintedRememberLoginIds: new Set(),
|
|
ensureRememberLoginRedisReady: async () => true,
|
|
redisClient: { isOpen: true, hGet: hGetImpl, hGetAll: hGetAllImpl },
|
|
deleteRememberLoginRegistryFields: async (ids) => {
|
|
deletes.push(Array.from(ids));
|
|
return true;
|
|
},
|
|
REMEMBER_LOGIN_REGISTRY_REDIS_KEY: "adpanel:remember-logins",
|
|
REMEMBER_LOGIN_REVOKE_RACE_SWEEP_WINDOW_MS: 60 * 1000,
|
|
REMEMBER_LOGIN_REVOKE_RACE_SWEEP_MAX_ROUNDS: 3,
|
|
REMEMBER_REVOKE_WRITE_TIMEOUT_MS: timeoutMs,
|
|
REMEMBER_REVOKE_WRITE_TIMEOUT_LABEL: "remember-revoke-write-timeout",
|
|
getRememberLoginDisplayId: (id) => `saved:${id}`,
|
|
withTimeout: sandboxWithTimeout,
|
|
};
|
|
vm.createContext(sandbox);
|
|
const fn = vm.runInContext(`(${CONFIRMED_SOURCE})`, sandbox, { filename: "confirmed-sandbox.js" });
|
|
return { fn, deletes, warnings, registry, minted: sandbox.locallyMintedRememberLoginIds };
|
|
}
|
|
|
|
test("read (a) timeout degrades to the local-registry fallback and the sweep still completes", async () => {
|
|
const now = Date.now();
|
|
const registry = {
|
|
j1: { uid: "u1", email: "a@x", issuedAt: now },
|
|
j2: { uid: "u1", email: "a@x", issuedAt: now },
|
|
};
|
|
let hGetAllCalls = 0;
|
|
const hashStages = [
|
|
{ j2: JSON.stringify(registry.j2) }, // sweep round 0: the raced id is visible
|
|
{}, // sweep round 1: swept clean → stop
|
|
{}, // final verification: gone
|
|
];
|
|
const { fn, deletes } = buildConfirmedHarness({
|
|
registry,
|
|
// The owner-source read wedges: ONLY this read may degrade, to null.
|
|
hGetImpl: () => new Promise(() => {}),
|
|
hGetAllImpl: async () => hashStages[Math.min(hGetAllCalls++, hashStages.length - 1)],
|
|
// No owner hint: the sweep owner MUST come from the localEntry fallback,
|
|
// or the sweep silently skips and the raced identifier survives.
|
|
ownerHint: null,
|
|
});
|
|
const result = toHost(await fn("j1", null));
|
|
assert.deepStrictEqual(
|
|
result,
|
|
{ ok: true, existed: false, swept: 1 },
|
|
"the timed-out owner read must not fail the revoke; existed stays false (rawEntry null) and the fallback still powers the sweep"
|
|
);
|
|
assert.deepStrictEqual(
|
|
deletes,
|
|
[["j1"], ["j2"]],
|
|
"the presented id and the raced same-owner id (matched via the fallback uid) must both be deleted"
|
|
);
|
|
assert.ok(!("j1" in registry), "the local snapshot entry must be deleted once the revoke is confirmed");
|
|
assert.ok(!("j2" in registry), "the swept id must be deleted from the local snapshot too");
|
|
});
|
|
|
|
test("read (a) non-timeout errors keep propagating to the outer catch (fail closed)", async () => {
|
|
const { fn, deletes } = buildConfirmedHarness({
|
|
registry: { j1: { uid: "u1", email: "a@x", issuedAt: Date.now() } },
|
|
hGetImpl: async () => { throw new Error("boom"); },
|
|
ownerHint: { email: "a@x" },
|
|
});
|
|
const result = toHost(await fn("j1", { email: "a@x" }));
|
|
assert.deepStrictEqual(
|
|
result,
|
|
{ ok: false, reason: "redis-error" },
|
|
"a genuine read error must NOT be converted to the null fallback — it fails the revoke closed"
|
|
);
|
|
assert.deepStrictEqual(deletes, [], "the delete must not run when the owner-source read fails with a genuine error");
|
|
});
|
|
|
|
test("read (b) sweep hGetAll timeout fails the revoke closed (never a partial-sweep success)", async () => {
|
|
const { fn, deletes, warnings } = buildConfirmedHarness({
|
|
registry: { j1: { uid: "u1", email: "a@x", issuedAt: Date.now() } },
|
|
hGetImpl: async () => JSON.stringify({ uid: "u1", email: "a@x", issuedAt: Date.now() }),
|
|
hGetAllImpl: () => new Promise(() => {}), // the sweep read wedges
|
|
ownerHint: { uid: "u1", email: "a@x" },
|
|
});
|
|
const result = toHost(await fn("j1", { uid: "u1", email: "a@x" }));
|
|
assert.deepStrictEqual(
|
|
result,
|
|
{ ok: false, reason: "redis-error" },
|
|
"the sweep read's timeout must reach the outer catch — success without a completed sweep is forbidden"
|
|
);
|
|
assert.deepStrictEqual(deletes, [["j1"]], "the presented id's delete ran, but the outcome is still fail-closed");
|
|
assert.ok(
|
|
warnings.some((w) => w.includes("Confirmed remember-login revocation failed") && w.includes("saved:j1")),
|
|
"the outer catch must log the loud failure warning"
|
|
);
|
|
});
|
|
|
|
test("read (c) verification hGetAll timeout fails the revoke closed (never an unverified success)", async () => {
|
|
let hGetAllCalls = 0;
|
|
const { fn, deletes } = buildConfirmedHarness({
|
|
registry: { j1: { uid: "u1", email: "a@x", issuedAt: Date.now() } },
|
|
hGetImpl: async () => JSON.stringify({ uid: "u1", email: "a@x", issuedAt: Date.now() }),
|
|
hGetAllImpl: async () => (++hGetAllCalls === 1 ? {} : new Promise(() => {})),
|
|
ownerHint: { uid: "u1", email: "a@x" },
|
|
});
|
|
const result = toHost(await fn("j1", { uid: "u1", email: "a@x" }));
|
|
assert.deepStrictEqual(
|
|
result,
|
|
{ ok: false, reason: "redis-error" },
|
|
"the verification read's timeout must reach the outer catch — success requires the verify to complete"
|
|
);
|
|
assert.deepStrictEqual(deletes, [["j1"]], "the delete ran but the unverified outcome must stay fail-closed");
|
|
});
|
|
|
|
test("all three reads settle: the confirmed revoke still reports ok with the existed contract", async () => {
|
|
const registry = { j1: { uid: "u1", email: "a@x", issuedAt: Date.now() } };
|
|
const { fn, deletes } = buildConfirmedHarness({
|
|
registry,
|
|
hGetImpl: async () => JSON.stringify({ uid: "u1", email: "a@x", issuedAt: Date.now() }),
|
|
hGetAllImpl: async () => ({}),
|
|
ownerHint: { uid: "u1", email: "a@x" },
|
|
});
|
|
const result = toHost(await fn("j1", { uid: "u1", email: "a@x" }));
|
|
assert.deepStrictEqual(result, { ok: true, existed: true, swept: 0 }, "the success contract (ok/existed/swept) must survive the read bounds");
|
|
assert.deepStrictEqual(deletes, [["j1"]], "exactly the targeted HDEL");
|
|
assert.ok(!("j1" in registry), "the local snapshot converges on success");
|
|
});
|