Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,275 @@
|
||||
"use strict";
|
||||
|
||||
// adpanel:remember-iat-binding — source pins + behavior pins for the
|
||||
// token↔entry-issuance binding in isManagedRememberLoginToken.
|
||||
//
|
||||
// Layer two of the resurrection defense (layer one is the { forceFreshId }
|
||||
// rule pinned by tests/remember-fresh-reissue.test.js): a remember identifier
|
||||
// has NO tombstone (unlike a revoked sid), so a jti whose registry entry was
|
||||
// revoked could in principle be resurrected by any future write that re-creates
|
||||
// an entry under the same id. This layer binds the presented token to its
|
||||
// entry's issuance generation: both entry.issuedAt writers (the mint path and
|
||||
// the rotation path) stamp the entry and the token's iat from the SAME
|
||||
// instant, so a live managed token always satisfies iat === entry.issuedAt.
|
||||
// A resurrected or re-minted identifier carries a different issuedAt, which
|
||||
// fails closed — the remember-id analogue of the sid tombstone.
|
||||
//
|
||||
// Guards that keep this from being a mass logout:
|
||||
// - v:2 tokens only (v:1 cookies predate the anchor fields);
|
||||
// - entry.issuedAt > 0 (normalizeRememberLoginRegistry backfills missing
|
||||
// issuedAt to 0 for legacy entries, which stay on the legacy-cutoff
|
||||
// mechanism instead).
|
||||
//
|
||||
// Pins held here:
|
||||
// 1. Source: the mint path stamps token iat and entry issuedAt from the same
|
||||
// `now`; the rotation path stamps the rotated token's iat and the rotated
|
||||
// entry's issuedAt from the same `now`.
|
||||
// 2. Source: the binding check sits AFTER the existing uid/email checks in
|
||||
// isManagedRememberLoginToken (existing failure precedence unchanged).
|
||||
// 3. Behavior (vm-extracted): v:2 + issuedAt>0 + iat mismatch -> false;
|
||||
// v:2 + matching iat -> true; issuedAt=0 -> check bypassed (legacy
|
||||
// passes); v:1 -> bypassed; missing entry / missing jti -> false as
|
||||
// before.
|
||||
|
||||
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");
|
||||
|
||||
function sliceBetween(source, startMarker, endMarker) {
|
||||
const start = source.indexOf(startMarker);
|
||||
assert.ok(start >= 0, `start marker not found: ${startMarker}`);
|
||||
const end = source.indexOf(endMarker, start + startMarker.length);
|
||||
assert.ok(end > start, `end marker not found after start: ${endMarker}`);
|
||||
return source.slice(start, end);
|
||||
}
|
||||
|
||||
// Brace-balanced extraction (same shape as the extractBlock helper in
|
||||
// tests/remember-fresh-reissue.test.js): skips // and /* */ comments so the
|
||||
// adpanel: comment convention cannot desync the string/brace tracker.
|
||||
function extractBlock(source, startMarker) {
|
||||
const start = source.indexOf(startMarker);
|
||||
assert.ok(start >= 0, `marker not found: ${startMarker}`);
|
||||
let i = start + startMarker.length;
|
||||
let depth;
|
||||
if (startMarker.endsWith("{")) {
|
||||
depth = 1;
|
||||
} else {
|
||||
while (i < source.length && /\s/.test(source[i])) i += 1;
|
||||
assert.ok(i < source.length && source[i] === "{", `no opening brace after: ${startMarker}`);
|
||||
depth = 1;
|
||||
}
|
||||
let inString = null;
|
||||
while (i < source.length && depth > 0) {
|
||||
i += 1;
|
||||
const ch = source[i];
|
||||
if (inString) {
|
||||
if (ch === "\\") { i += 1; continue; }
|
||||
if (ch === inString) inString = null;
|
||||
continue;
|
||||
}
|
||||
if (ch === "/" && source[i + 1] === "/") {
|
||||
while (i < source.length && source[i] !== "\n") i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "/" && source[i + 1] === "*") {
|
||||
i += 2;
|
||||
while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i += 1;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"' || ch === "'" || ch === "`") inString = ch;
|
||||
else if (ch === "{") depth += 1;
|
||||
else if (ch === "}") depth -= 1;
|
||||
}
|
||||
assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`);
|
||||
return source.slice(start, i + 1);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source pins — the iat === entry.issuedAt invariant
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("the mint path stamps token iat and entry issuedAt from the same instant", () => {
|
||||
const issue = extractBlock(indexSource, "function issueRememberLoginToken(req, user, now = Date.now()) {");
|
||||
assert.ok(
|
||||
issue.includes("const expiresAt = now + REMEMBER_LOGIN_MAX_AGE_MS;") &&
|
||||
issue.includes("upsertRememberLoginRegistryEntry(req, user, expiresAt, now);") &&
|
||||
issue.includes("buildRememberLoginToken(user, rememberId, now, expiresAt);"),
|
||||
"issueRememberLoginToken must feed the SAME `now` to the registry upsert and the token builder"
|
||||
);
|
||||
|
||||
// buildRememberLoginToken stamps the token payload's iat from its issuedAt
|
||||
// parameter (so token.iat === the `now` the caller passed).
|
||||
const builder = extractBlock(indexSource, "function buildRememberLoginToken(user, rememberId, issuedAt, expiresAt) {");
|
||||
assert.ok(builder.includes("iat: issuedAt,"), "the token payload's iat comes from the issuedAt argument");
|
||||
|
||||
// upsertRememberLoginRegistryEntry stamps the entry's issuedAt from its
|
||||
// issuedAt argument VERBATIM — adpanel:remember-iat-stamp-guard: the old
|
||||
// `Number(issuedAt) || Date.now()` fallback would silently stamp a DIFFERENT
|
||||
// instant than the token's iat (making the binding check below fail closed
|
||||
// on legitimate tokens), so it was replaced with a loud guard that throws on
|
||||
// any non-positive issuedAt before any registry write. Stronger pin, same
|
||||
// invariant (behavior pins live in tests/remember-iat-stamp-guard.test.js).
|
||||
const upsert = sliceBetween(
|
||||
indexSource,
|
||||
"function upsertRememberLoginRegistryEntry(req, user, expiresAt, issuedAt = Date.now()) {",
|
||||
"function revokeRememberLoginRegistryEntry(rememberId) {"
|
||||
);
|
||||
assert.ok(
|
||||
upsert.includes("const stampedIssuedAt = Number(issuedAt);") && upsert.includes("issuedAt: stampedIssuedAt,"),
|
||||
"the entry's issuedAt comes from the issuedAt argument verbatim (guarded stampedIssuedAt)"
|
||||
);
|
||||
assert.ok(
|
||||
!upsert.includes("issuedAt: Number(issuedAt) || Date.now(),"),
|
||||
"the silent issuedAt fallback must stay removed — a fallback would desync entry.issuedAt from token.iat"
|
||||
);
|
||||
const guardThrowIdx = upsert.indexOf('throw new Error("upsertRememberLoginRegistryEntry: issuedAt must be a positive epoch-ms timestamp matching the token iat")');
|
||||
const registryWriteIdx = upsert.indexOf("rememberLoginRegistry[rememberId] = {");
|
||||
assert.ok(guardThrowIdx >= 0 && registryWriteIdx > guardThrowIdx,
|
||||
"the issuedAt guard must throw before any registry write");
|
||||
});
|
||||
|
||||
test("the rotation path stamps the rotated token's iat and the rotated entry's issuedAt from the same `now`", () => {
|
||||
const rotate = extractBlock(indexSource, "async function rotateRememberLoginCookie(req, res, user, parsedToken) {");
|
||||
const nowIdx = rotate.indexOf("const now = Date.now();");
|
||||
const entryIssuedAtIdx = rotate.indexOf("issuedAt: now,");
|
||||
const tokenIdx = rotate.indexOf("const token = buildRememberLoginToken(user, rememberId, now, expiresAt);");
|
||||
assert.ok(nowIdx >= 0, "the rotation must capture one `now` instant");
|
||||
assert.ok(entryIssuedAtIdx > nowIdx, "the rotated entry's issuedAt must be that `now`");
|
||||
assert.ok(tokenIdx > entryIssuedAtIdx, "the rotated token must be built from the same `now` (iat === entry.issuedAt)");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source pins — placement and guards of the binding check
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("the iat-binding check sits AFTER the uid/email checks and gates the final return true", () => {
|
||||
const fn = extractBlock(indexSource, "function isManagedRememberLoginToken(parsedToken, user = null) {");
|
||||
const uidIdx = fn.indexOf('if (user?.id && String(entry.uid || "") !== String(user.id)) return false;');
|
||||
const emailIdx = fn.indexOf('if (user?.email && String(entry.email || "").toLowerCase() !== String(user.email || "").toLowerCase()) return false;');
|
||||
const markerIdx = fn.indexOf("// adpanel:remember-iat-binding");
|
||||
const checkIdx = fn.indexOf("Number(parsedToken?.v) === 2 && Number(entry.issuedAt) > 0 && Number(parsedToken.iat) !== Number(entry.issuedAt)");
|
||||
const returnTrueIdx = fn.indexOf("return true;");
|
||||
|
||||
assert.ok(uidIdx >= 0 && emailIdx > uidIdx, "the existing uid/email checks must remain first");
|
||||
assert.ok(markerIdx > emailIdx, "the binding check must be documented and follow the uid/email checks");
|
||||
assert.ok(checkIdx > markerIdx && checkIdx < returnTrueIdx, "the binding check must gate the final return true");
|
||||
assert.ok(
|
||||
fn.includes("Number(parsedToken?.v) === 2"),
|
||||
"the check must be scoped to v:2 tokens (v:1 predates the anchor fields)"
|
||||
);
|
||||
assert.ok(
|
||||
fn.includes("Number(entry.issuedAt) > 0"),
|
||||
"the check must be scoped to anchored entries (legacy backfill is issuedAt=0)"
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Behavior pins — vm-extracted isManagedRememberLoginToken
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildHarness(registry) {
|
||||
const fnSource = extractBlock(indexSource, "function isManagedRememberLoginToken(parsedToken, user = null) {");
|
||||
const sandbox = {
|
||||
getRememberLoginRegistryEntry: (jti) => (Object.prototype.hasOwnProperty.call(registry, jti) ? registry[jti] : null),
|
||||
};
|
||||
const context = vm.createContext(sandbox);
|
||||
return vm.runInContext(`(${fnSource})`, context);
|
||||
}
|
||||
|
||||
const USER = { id: 42, email: "user@example.test" };
|
||||
// A live managed entry: minted (or last rotated) at 1000, owned by USER.
|
||||
const LIVE_ENTRY = { uid: "42", email: "user@example.test", issuedAt: 1000, expiresAt: 9999999999999 };
|
||||
|
||||
test("v:2 token with a mismatched iat fails closed (resurrected/re-minted identifier)", () => {
|
||||
const fn = buildHarness({ "remember-id-a": LIVE_ENTRY });
|
||||
// A stolen pre-revocation token value presented after the identifier's entry
|
||||
// was re-created under the same jti at a different instant.
|
||||
assert.equal(
|
||||
fn({ v: 2, uid: "42", iat: 500, exp: 9999999999999, fp: "fp", jti: "remember-id-a" }, USER),
|
||||
false,
|
||||
"iat !== entry.issuedAt must fail closed"
|
||||
);
|
||||
// Also fails with NO user hint (the silent-validation callers pass none):
|
||||
// the binding is unconditional for anchored v:2 tokens.
|
||||
assert.equal(
|
||||
fn({ v: 2, uid: "42", iat: 500, exp: 9999999999999, fp: "fp", jti: "remember-id-a" }),
|
||||
false,
|
||||
"the binding must not be bypassable by omitting the user hint"
|
||||
);
|
||||
});
|
||||
|
||||
test("v:2 token with the matching iat is honored (uid/email checks satisfied)", () => {
|
||||
const fn = buildHarness({ "remember-id-a": LIVE_ENTRY });
|
||||
assert.equal(
|
||||
fn({ v: 2, uid: "42", iat: 1000, exp: 9999999999999, fp: "fp", jti: "remember-id-a" }, USER),
|
||||
true,
|
||||
"a live managed token (iat === entry.issuedAt) must validate"
|
||||
);
|
||||
assert.equal(
|
||||
fn({ v: 2, uid: "42", iat: 1000, exp: 9999999999999, fp: "fp", jti: "remember-id-a" }),
|
||||
true,
|
||||
"no-user-hint validation must keep working for matching tokens"
|
||||
);
|
||||
});
|
||||
|
||||
test("the existing uid/email failure modes keep their precedence over the binding check", () => {
|
||||
const fn = buildHarness({
|
||||
"remember-id-a": { ...LIVE_ENTRY, uid: "7", email: "other@example.test" },
|
||||
});
|
||||
// The iat MATCHES here; the uid/email checks must still reject.
|
||||
assert.equal(
|
||||
fn({ v: 2, uid: "42", iat: 1000, exp: 9999999999999, fp: "fp", jti: "remember-id-a" }, USER),
|
||||
false,
|
||||
"a matching iat must not rescue a token owned by a different user"
|
||||
);
|
||||
// And a mismatched iat on a foreign-owned entry fails the same way (false),
|
||||
// never an exception.
|
||||
assert.equal(
|
||||
fn({ v: 2, uid: "42", iat: 500, exp: 9999999999999, fp: "fp", jti: "remember-id-a" }, USER),
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test("issuedAt=0 entries bypass the binding check (legacy backfill stays on the legacy-cutoff mechanism)", () => {
|
||||
const fn = buildHarness({ "legacy-entry": { ...LIVE_ENTRY, issuedAt: 0 } });
|
||||
assert.equal(
|
||||
fn({ v: 2, uid: "42", iat: 123456, exp: 9999999999999, fp: "fp", jti: "legacy-entry" }, USER),
|
||||
true,
|
||||
"a legacy entry (issuedAt backfilled to 0) must keep validating regardless of iat"
|
||||
);
|
||||
// An entry whose issuedAt is missing entirely normalizes to 0 — same rule.
|
||||
const fnMissing = buildHarness({ "legacy-entry": { uid: "42", email: "user@example.test", expiresAt: 9999999999999 } });
|
||||
assert.equal(
|
||||
fnMissing({ v: 2, uid: "42", iat: 123456, exp: 9999999999999, fp: "fp", jti: "legacy-entry" }, USER),
|
||||
true,
|
||||
"an entry without an issuedAt field must behave like the 0-backfill"
|
||||
);
|
||||
});
|
||||
|
||||
test("v:1 tokens bypass the binding check (they predate the anchor fields)", () => {
|
||||
const fn = buildHarness({ "transition-entry": LIVE_ENTRY });
|
||||
assert.equal(
|
||||
fn({ v: 1, uid: "42", iat: 123456, exp: 9999999999999, fp: "fp", jti: "transition-entry" }, USER),
|
||||
true,
|
||||
"a transition-era v:1 token must keep validating under the pre-fix rules"
|
||||
);
|
||||
});
|
||||
|
||||
test("the pre-existing failure modes are unchanged (no jti, unknown entry)", () => {
|
||||
const fn = buildHarness({ "remember-id-a": LIVE_ENTRY });
|
||||
assert.equal(fn(null, USER), false, "no parsed token -> false");
|
||||
assert.equal(fn({ v: 2, uid: "42", iat: 1000, exp: 9999999999999, fp: "fp" }, USER), false, "no jti -> false");
|
||||
assert.equal(
|
||||
fn({ v: 2, uid: "42", iat: 1000, exp: 9999999999999, fp: "fp", jti: "unknown-id" }, USER),
|
||||
false,
|
||||
"entry not in the registry -> false (revoked/rotated-away identifier)"
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user