415 lines
21 KiB
JavaScript
415 lines
21 KiB
JavaScript
"use strict";
|
|
|
|
// adpanel:remember-rotation-cadence — Finding 3 (P2): activity indefinitely
|
|
// postponed the intended six-hour remember-token rotation.
|
|
//
|
|
// THE BUG: both skip branches of ensureRememberLoginCookie called
|
|
// markRememberLoginSessionFresh, which resets req.session.rememberLoginCheckedAt
|
|
// on EVERY request — and rememberLoginValidationIntervalFresh measured the 6h
|
|
// rotation interval from that LAST-ACTIVITY timestamp. An active browser
|
|
// therefore reset its own rotation timer on every request and NEVER reached
|
|
// it: 48 simulated hours of hourly activity produced ZERO rotations, while 7
|
|
// idle hours produced one. Rotation only fired after ≥6h of IDLE.
|
|
//
|
|
// THE FIX: the 6h validation/rotation cadence is anchored to the CREDENTIAL's
|
|
// OWN AGE — the presented token's iat (for v2 tokens
|
|
// isManagedRememberLoginToken binds iat to the registry entry's issuedAt —
|
|
// and restore's rotation mints a fresh iat, so a restored credential restarts
|
|
// its cadence correctly). markRememberLoginSessionFresh keeps stamping
|
|
// checkedAt for observability/expiry bookkeeping, but it is no longer the
|
|
// rotation gate. Constraints preserved and pinned here:
|
|
// (i) inside the anchor's refresh window rotation is impossible (absolute
|
|
// expiry anchored at original issuance), so the skip must STILL honor
|
|
// the validation interval — requests inside the window must not try to
|
|
// rotate on every request;
|
|
// (ii) the remote-proxy-trust-gate withholding (the first statement of
|
|
// ensureRememberLoginCookie) is untouched;
|
|
// (iii) v1 legacy tokens carry no jti, so they never reach the skip
|
|
// branches (the fail-closed clear is unchanged).
|
|
// Edge cases pinned: 48h of hourly activity rotates roughly every 6h of
|
|
// CREDENTIAL AGE; 7 idle hours then one request rotate exactly once; two-tab
|
|
// adoption neither double-rotates per request nor resets the adopted token's
|
|
// own cadence.
|
|
|
|
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");
|
|
|
|
// Brace-balanced extraction (same shape as tests/remember-rotation-bounded.test.js).
|
|
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 ENSURE_SOURCE = extractBlock(indexSource, "async function ensureRememberLoginCookie(req, res, user = null) {");
|
|
const MARK_FRESH_SOURCE = extractBlock(indexSource, "function markRememberLoginSessionFresh(req, expiresAt) {");
|
|
const CLEAR_STATE_SOURCE = extractBlock(indexSource, "function clearRememberLoginSessionState(req) {");
|
|
const INTERVAL_SOURCE = extractBlock(indexSource, "function rememberLoginValidationIntervalFresh(credentialIssuedAt) {");
|
|
const CAN_SKIP_SOURCE = extractBlock(indexSource, "function canSkipRememberLoginValidation(req, credentialIssuedAt) {");
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source pins
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("the 6h interval is anchored to the credential's own age, not to last activity", () => {
|
|
// The signature takes the credential age; the body measures from it.
|
|
assert.match(
|
|
INTERVAL_SOURCE,
|
|
/^function rememberLoginValidationIntervalFresh\(credentialIssuedAt\) \{/,
|
|
"the interval half must take the CREDENTIAL's age, not the session"
|
|
);
|
|
assert.match(
|
|
INTERVAL_SOURCE,
|
|
/Date\.now\(\) - issuedAt < REMEMBER_LOGIN_VALIDATE_INTERVAL_MS/,
|
|
"the interval must measure the credential's AGE against the 6h constant"
|
|
);
|
|
assert.ok(
|
|
!INTERVAL_SOURCE.includes("rememberLoginCheckedAt"),
|
|
"the last-activity stamp must no longer gate the rotation interval (it resets on every request)"
|
|
);
|
|
assert.match(
|
|
INTERVAL_SOURCE,
|
|
/if \(!issuedAt \|\| issuedAt <= 0\) return false;/,
|
|
"a non-positive iat fails closed (no skip)"
|
|
);
|
|
// Every caller passes the presented token's iat; canSkip threads it through.
|
|
assert.match(CAN_SKIP_SOURCE, /return rememberLoginValidationIntervalFresh\(credentialIssuedAt\);/, "canSkip composes the credential-age interval");
|
|
assert.match(ENSURE_SOURCE, /canSkipRememberLoginValidation\(req, parsed\.iat\)/, "the skip-validation branch passes the presented token's iat");
|
|
assert.match(ENSURE_SOURCE, /rememberLoginValidationIntervalFresh\(parsed\.iat\)/, "the refresh-window branch passes the presented token's iat");
|
|
// Constraint (iii): markRememberLoginSessionFresh keeps its bookkeeping role
|
|
// (checkedAt/expiry stamping) unchanged.
|
|
assert.match(MARK_FRESH_SOURCE, /req\.session\.rememberLoginCheckedAt = Date\(\)\.now\(\) — |req\.session\.rememberLoginCheckedAt = Date\.now\(\);/, "the freshness stamp keeps stamping checkedAt");
|
|
assert.match(MARK_FRESH_SOURCE, /req\.session\.rememberLoginExpiresAt = Number\(expiresAt\) \|\| 0;/, "the anchored-expiry stamp is unchanged");
|
|
});
|
|
|
|
test("the skip branches still honor the validation interval inside the refresh window, and the gate withholding is untouched", () => {
|
|
// Constraint (i): the refresh-window branch must keep the interval check so
|
|
// requests inside the window do not rotate on every request.
|
|
const windowBranch = extractBlock(indexSource, " if (\n parsed &&\n parsed.jti &&\n parsed.jti === sessionRememberId &&\n isManagedRememberLoginToken(parsed) &&\n rememberLoginValidationIntervalFresh(parsed.iat)\n ) {");
|
|
assert.ok(windowBranch.includes("markRememberLoginSessionFresh(req, parsed.exp);"), "the window branch skips WITHOUT rotating");
|
|
assert.ok(!windowBranch.includes("rotateRememberLoginCookie"), "the window branch must not rotate");
|
|
// Constraint (ii): the remote-proxy-trust-gate withholding is the first
|
|
// statement (tests/remote-proxy-trust-gate.test.js pins the behavior).
|
|
const gateIdx = ENSURE_SOURCE.indexOf("if (remoteProxyTrustBlocksRememberIssuance(req)) return;");
|
|
assert.ok(gateIdx >= 0 && gateIdx < ENSURE_SOURCE.indexOf("const parsed = readRememberLoginToken"), "the gate withholding precedes the token parse");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavior pins — vm-extracted chain with injectable time
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const REMEMBER_LOGIN_MAX_AGE_MS = 365 * 24 * 60 * 60 * 1000;
|
|
const REMEMBER_LOGIN_REFRESH_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
|
|
const REMEMBER_LOGIN_VALIDATE_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
|
|
|
function buildHarness({ initialIssuedAt, anchorAt, expiresAt }) {
|
|
// Simulated clock: every function under test reads Date.now() from the
|
|
// sandbox, so the whole 48h scenario runs in milliseconds.
|
|
let simNow = initialIssuedAt;
|
|
const registry = {};
|
|
const calls = { rotate: 0, markFresh: 0, clearState: 0, clearCookie: 0, findUser: 0, adopt: 0 };
|
|
const warnings = [];
|
|
|
|
// The presented credential: this is "the browser's cookie jar" — the silent
|
|
// refresh rewrites it on rotation, exactly like the real flow's Set-Cookie.
|
|
const currentToken = {
|
|
v: 2,
|
|
uid: "1",
|
|
iat: initialIssuedAt,
|
|
exp: expiresAt,
|
|
fp: "fp",
|
|
jti: "chain-root-token",
|
|
};
|
|
registry[currentToken.jti] = { uid: "1", issuedAt: initialIssuedAt, expiresAt, absoluteExpiresAt: anchorAt };
|
|
|
|
const req = {
|
|
session: {
|
|
user: "user@example.test",
|
|
rememberLoginId: currentToken.jti,
|
|
rememberLoginCheckedAt: 0,
|
|
rememberLoginExpiresAt: expiresAt,
|
|
},
|
|
cookies: { "adpanel.remember": "tok" },
|
|
get: () => "test-agent",
|
|
};
|
|
const res = { cookie: () => {}, clearCookie: () => {} };
|
|
|
|
const sandbox = {
|
|
console: { log: () => {}, warn: (...a) => warnings.push(a.map(String).join(" ")) },
|
|
REMEMBER_LOGIN_COOKIE_NAME: "adpanel.remember",
|
|
REMEMBER_LOGIN_VALIDATE_INTERVAL_MS,
|
|
REMEMBER_LOGIN_REFRESH_WINDOW_MS,
|
|
Date: { now: () => simNow },
|
|
remoteProxyTrustBlocksRememberIssuance: () => false,
|
|
readRememberLoginToken: () => ({ ...currentToken }),
|
|
ensureRememberLoginSessionId: (r) => {
|
|
const current = String(r.session.rememberLoginId || "").trim();
|
|
if (current) return current;
|
|
return (r.session.rememberLoginId = "minted-" + Math.random().toString(16).slice(2));
|
|
},
|
|
isManagedRememberLoginToken: (parsed, user) => {
|
|
const entry = registry[parsed?.jti];
|
|
if (!entry) return false;
|
|
if (user?.id && String(entry.uid) !== String(user.id)) return false;
|
|
if (Number(parsed?.v) === 2 && Number(entry.issuedAt) > 0 && Number(parsed.iat) !== Number(entry.issuedAt)) return false;
|
|
return true;
|
|
},
|
|
rememberLoginNeedsRefresh: (parsed) => parsed.exp - simNow <= REMEMBER_LOGIN_REFRESH_WINDOW_MS,
|
|
markRememberLoginSessionFresh: (r, exp) => {
|
|
calls.markFresh += 1;
|
|
r.session.rememberLoginCheckedAt = simNow;
|
|
r.session.rememberLoginExpiresAt = Number(exp) || 0;
|
|
},
|
|
clearRememberLoginSessionState: (r) => {
|
|
calls.clearState += 1;
|
|
delete r.session.rememberLoginCheckedAt;
|
|
delete r.session.rememberLoginExpiresAt;
|
|
},
|
|
clearRememberLoginCookie: () => { calls.clearCookie += 1; },
|
|
findUserByEmail: async () => {
|
|
calls.findUser += 1;
|
|
return { id: 1, email: "user@example.test", password: "x" };
|
|
},
|
|
// Mirrors the real rotateRememberLoginCookie's observable effects: a new
|
|
// jti, iat = NOW (the credential's age restarts), capped expiry, session
|
|
// rebind, registry swap.
|
|
rotateRememberLoginCookie: async (r, rs, user, parsed) => {
|
|
calls.rotate += 1;
|
|
const expiresAtNow = Math.min(simNow + REMEMBER_LOGIN_MAX_AGE_MS, anchorAt);
|
|
if (expiresAtNow <= simNow) return 0;
|
|
delete registry[parsed.jti];
|
|
currentToken.jti = `rotated-${calls.rotate}`;
|
|
currentToken.iat = simNow;
|
|
currentToken.exp = expiresAtNow;
|
|
registry[currentToken.jti] = { uid: "1", issuedAt: simNow, expiresAt: expiresAtNow, absoluteExpiresAt: anchorAt };
|
|
r.session.rememberLoginId = currentToken.jti;
|
|
r.session.rememberLoginLineage = "chain-root-token";
|
|
return expiresAtNow;
|
|
},
|
|
rememberLoginRegistry: registry,
|
|
req,
|
|
res,
|
|
currentToken,
|
|
calls,
|
|
setSimNow: (t) => { simNow = t; },
|
|
getSimNow: () => simNow,
|
|
warnings,
|
|
};
|
|
vm.createContext(sandbox);
|
|
for (const [name, src] of [
|
|
["ensureRememberLoginCookie", ENSURE_SOURCE],
|
|
["markRememberLoginSessionFresh", MARK_FRESH_SOURCE],
|
|
["clearRememberLoginSessionState", CLEAR_STATE_SOURCE],
|
|
["rememberLoginValidationIntervalFresh", INTERVAL_SOURCE],
|
|
["canSkipRememberLoginValidation", CAN_SKIP_SOURCE],
|
|
]) {
|
|
sandbox[name] = vm.runInContext(`(${src})`, sandbox, { filename: `${name}-sandbox.js` });
|
|
}
|
|
return { sandbox, req, res, calls, registry, currentToken };
|
|
}
|
|
|
|
const HOUR = 60 * 60 * 1000;
|
|
const START = 1_700_000_000_000;
|
|
|
|
test("48 simulated hours of hourly activity rotate roughly every 6h of CREDENTIAL age (the old activity-anchored interval never would)", async () => {
|
|
const harness = buildHarness({
|
|
initialIssuedAt: START,
|
|
anchorAt: START + REMEMBER_LOGIN_MAX_AGE_MS,
|
|
expiresAt: START + REMEMBER_LOGIN_MAX_AGE_MS,
|
|
});
|
|
const { sandbox, req, calls } = harness;
|
|
// The pre-fix behavior for contrast: checkedAt reset per request would have
|
|
// kept the interval forever fresh → zero rotations. The credential-age
|
|
// anchor must rotate on schedule instead.
|
|
for (let hour = 1; hour <= 48; hour += 1) {
|
|
sandbox.setSimNow(START + hour * HOUR);
|
|
await sandbox.ensureRememberLoginCookie(req, harness.res, null); // user resolved via session
|
|
// The presented token after each round IS the current (possibly rotated)
|
|
// one — the next hour presents it again, exactly like a real browser.
|
|
assert.strictEqual(req.session.user, "user@example.test", `hour ${hour}: the session stays bound`);
|
|
}
|
|
assert.ok(
|
|
calls.rotate >= 7,
|
|
`48 hourly requests must rotate at least 7 times (credential-age cadence: every 6h of age); got ${calls.rotate}`
|
|
);
|
|
assert.strictEqual(calls.clearCookie, 0, "a healthy active browser must never be failed closed");
|
|
assert.strictEqual(calls.findUser, calls.rotate, "only the rotation path pays the user lookup — the 40 skip paths never do");
|
|
// Rotation boundaries: the rotation count matches the age crossings
|
|
// (hours 6, 12, ..., 48 → 8 rotations, each restarting the 6h age clock).
|
|
assert.strictEqual(calls.rotate, 8, `exactly the 6h-age crossings rotate; got ${calls.rotate}`);
|
|
});
|
|
|
|
test("7 idle hours then one request rotate exactly once", async () => {
|
|
const harness = buildHarness({
|
|
initialIssuedAt: START,
|
|
anchorAt: START + REMEMBER_LOGIN_MAX_AGE_MS,
|
|
expiresAt: START + REMEMBER_LOGIN_MAX_AGE_MS,
|
|
});
|
|
const { sandbox, req, calls } = harness;
|
|
// First request at mint + 0: fresh credential, skip.
|
|
await sandbox.ensureRememberLoginCookie(req, harness.res, null);
|
|
assert.strictEqual(calls.rotate, 0, "a fresh credential skips");
|
|
// 7 hours of IDLE (no requests — checkedAt stays at the mint), then one
|
|
// request: exactly one rotation (the old code needed 6h of IDLE before it
|
|
// would ever rotate, then reset on activity — here the cadence is the
|
|
// credential's age, which the idle gap also satisfies).
|
|
sandbox.setSimNow(START + 7 * HOUR);
|
|
await sandbox.ensureRememberLoginCookie(req, harness.res, null);
|
|
assert.strictEqual(calls.rotate, 1, "the idle gap crossed the 6h credential age → one rotation");
|
|
// An immediate follow-up request does not rotate again (fresh iat).
|
|
await sandbox.ensureRememberLoginCookie(req, harness.res, null);
|
|
assert.strictEqual(calls.rotate, 1, "the freshly rotated credential skips");
|
|
});
|
|
|
|
test("two-tab adoption does not double-rotate per request, and the adopted token's own age drives its next rotation", async () => {
|
|
const harness = buildHarness({
|
|
initialIssuedAt: START,
|
|
anchorAt: START + REMEMBER_LOGIN_MAX_AGE_MS,
|
|
expiresAt: START + REMEMBER_LOGIN_MAX_AGE_MS,
|
|
});
|
|
const { sandbox, req, calls, currentToken } = harness;
|
|
// Tab A rotates at the 6h boundary.
|
|
sandbox.setSimNow(START + 6 * HOUR);
|
|
await sandbox.ensureRememberLoginCookie(req, harness.res, null);
|
|
assert.strictEqual(calls.rotate, 1, "the 6h boundary rotates");
|
|
const adoptedId = currentToken.jti;
|
|
const adoptedIat = currentToken.iat;
|
|
// Tab B: the same browser cookie jar presents the NEW identifier, but its
|
|
// (server-side) session snapshot still binds the PRE-rotation id — the
|
|
// adoption branch must converge WITHOUT re-issuing.
|
|
const tabB = buildHarness({
|
|
initialIssuedAt: START,
|
|
anchorAt: START + REMEMBER_LOGIN_MAX_AGE_MS,
|
|
expiresAt: START + REMEMBER_LOGIN_MAX_AGE_MS,
|
|
});
|
|
tabB.sandbox.setSimNow(START + 6 * HOUR);
|
|
tabB.req.session.rememberLoginId = "chain-root-token"; // stale snapshot
|
|
tabB.currentToken.jti = adoptedId; // the jar carries the rotated cookie
|
|
tabB.currentToken.iat = adoptedIat;
|
|
tabB.registry[adoptedId] = { uid: "1", issuedAt: adoptedIat, expiresAt: START + REMEMBER_LOGIN_MAX_AGE_MS, absoluteExpiresAt: START + REMEMBER_LOGIN_MAX_AGE_MS };
|
|
delete tabB.registry["chain-root-token"];
|
|
await tabB.sandbox.ensureRememberLoginCookie(tabB.req, tabB.res, null);
|
|
assert.strictEqual(tabB.calls.rotate, 0, "adoption converges without rotating");
|
|
assert.strictEqual(tabB.req.session.rememberLoginId, adoptedId, "the session adopted the presented identifier");
|
|
// The next request (same hour) is a plain skip — no per-request rotation.
|
|
await tabB.sandbox.ensureRememberLoginCookie(tabB.req, tabB.res, null);
|
|
assert.strictEqual(tabB.calls.rotate, 0, "the adopted credential's own age (<6h) keeps it in the skip path");
|
|
// 6h later, the ADOPTED token's own age drives the next rotation.
|
|
tabB.sandbox.setSimNow(adoptedIat + 6 * HOUR);
|
|
await tabB.sandbox.ensureRememberLoginCookie(tabB.req, tabB.res, null);
|
|
assert.strictEqual(tabB.calls.rotate, 1, "the adopted token's own age reached the 6h boundary → one rotation");
|
|
});
|
|
|
|
test("refresh-window behavior is unchanged: inside the window the 6h interval still gates rotation", async () => {
|
|
const anchor = START + REMEMBER_LOGIN_MAX_AGE_MS;
|
|
const harness = buildHarness({
|
|
initialIssuedAt: START,
|
|
anchorAt: anchor,
|
|
expiresAt: anchor,
|
|
});
|
|
const { sandbox, req, calls } = harness;
|
|
// Push the credential into the anchor's refresh window (10 days remaining):
|
|
// rotation is still POSSIBLE (the anchor is in the future) but the skip
|
|
// branches must keep honoring the 6h interval so requests inside the window
|
|
// do not mint an identifier per request.
|
|
const insideWindow = anchor - 10 * 24 * 60 * 60 * 1000;
|
|
sandbox.setSimNow(insideWindow);
|
|
req.session.rememberLoginExpiresAt = anchor;
|
|
harness.currentToken.exp = anchor;
|
|
// Re-baseline to a fresh-in-window token (the scenario's credential was
|
|
// minted as the window opened).
|
|
harness.currentToken.iat = insideWindow;
|
|
harness.registry[harness.currentToken.jti].issuedAt = insideWindow;
|
|
await sandbox.ensureRememberLoginCookie(req, harness.res, null);
|
|
assert.strictEqual(calls.rotate, 0, "a fresh-in-window credential skips without rotating (the interval still gates inside the window)");
|
|
// The anchored-expiry clause in canSkip still reads rememberLoginExpiresAt:
|
|
// a credential inside the window CANNOT take branch 1 (its remaining
|
|
// lifetime ≤ 30d), so the window branch is what skipped above.
|
|
assert.ok(req.session.rememberLoginExpiresAt - sandbox.getSimNow() <= REMEMBER_LOGIN_REFRESH_WINDOW_MS, "the scenario is genuinely inside the refresh window");
|
|
// Aging past 6h inside the window rotates (capped at the anchor) — the
|
|
// intended cadence continues until the anchor.
|
|
sandbox.setSimNow(insideWindow + 7 * HOUR);
|
|
await sandbox.ensureRememberLoginCookie(req, harness.res, null);
|
|
assert.strictEqual(calls.rotate, 1, "6h of credential age inside the window still rotates (never per request)");
|
|
});
|
|
|
|
test("v1 legacy tokens never reach the cadence (no jti → fail-closed clear, unchanged)", async () => {
|
|
const harness = buildHarness({
|
|
initialIssuedAt: START,
|
|
anchorAt: START + REMEMBER_LOGIN_MAX_AGE_MS,
|
|
expiresAt: START + REMEMBER_LOGIN_MAX_AGE_MS,
|
|
});
|
|
const { sandbox, req, calls } = harness;
|
|
sandbox.currentToken.v = 1;
|
|
sandbox.currentToken.jti = ""; // v1 predates jti
|
|
await sandbox.ensureRememberLoginCookie(req, harness.res, null);
|
|
assert.strictEqual(calls.rotate, 0, "a v1 cookie cannot rotate (no managed identifier)");
|
|
assert.strictEqual(calls.clearCookie, 1, "the fail-closed clear for a jti-less cookie is unchanged");
|
|
});
|
|
|
|
test("a token minted long ago but presenting after a restore starts a fresh cadence (restore mints iat=now)", async () => {
|
|
// restoreRememberedLogin rotates BEFORE binding (its mint path stamps
|
|
// iat = now), so a restored credential's cadence restarts — pin the source
|
|
// ordering: the restore's rotation precedes the session bind.
|
|
const restoreSource = extractBlock(indexSource, "async function restoreRememberedLogin(req, res) {");
|
|
const rotateIdx = restoreSource.indexOf("await rotateRememberLoginCookie(req, res, user, parsed);");
|
|
// Conscious pin update (adpanel:credential-generation): the restore's bind
|
|
// line now sources the fresh re-read row — the marker tracks it. Same
|
|
// assertion strength: rotation precedes the session bind.
|
|
const bindIdx = restoreSource.indexOf("req.session.user = freshRestoreRow.email;");
|
|
const markFreshIdx = restoreSource.indexOf("markRememberLoginSessionFresh(req, expiresAt);");
|
|
assert.ok(rotateIdx >= 0 && bindIdx > rotateIdx, "restore rotates before authenticating the regenerated session");
|
|
assert.ok(markFreshIdx > rotateIdx, "the restored credential's freshness stamp follows its fresh mint");
|
|
// And behaviorally: the interval half itself is purely age-based — a
|
|
// recently minted (iat = now) credential is fresh regardless of any
|
|
// long-ago session state.
|
|
const intervalSandbox = { REMEMBER_LOGIN_VALIDATE_INTERVAL_MS, Date: { now: () => START + 5 * HOUR } };
|
|
vm.createContext(intervalSandbox);
|
|
const intervalFn = vm.runInContext(`(${INTERVAL_SOURCE})`, intervalSandbox, { filename: "interval-sandbox.js" });
|
|
assert.strictEqual(intervalFn(START + 1 * HOUR), true, "a 4h-old credential is fresh");
|
|
assert.strictEqual(intervalFn(START - 1 * HOUR), false, "a 6h+ old credential is due for rotation");
|
|
assert.strictEqual(intervalFn(0), false, "a missing iat fails closed");
|
|
assert.strictEqual(intervalFn(undefined), false, "an absent argument fails closed");
|
|
});
|