Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+278
View File
@@ -0,0 +1,278 @@
"use strict";
// adpanel:remember-iat-stamp-guard — source pins + behavior pins for the loud
// issuedAt guard in upsertRememberLoginRegistryEntry.
//
// entry.issuedAt and the minted token's iat must be stamped from the SAME
// instant: the mint chain feeds one `now` to both writers
// (issueRememberLoginToken → upsertRememberLoginRegistryEntry AND
// buildRememberLoginToken), and the iat-vs-entry binding in
// isManagedRememberLoginToken (tests/remember-iat-binding.test.js) fails closed
// whenever they differ. The old `issuedAt: Number(issuedAt) || Date.now()`
// fallback was a silent desync trap: a future caller passing 0/NaN/null would
// stamp a DIFFERENT instant than the token's iat and permanently fail-close
// legitimate tokens. The guard throws LOUD before any registry write instead;
// the fallback is dead today (the only caller is the mint chain, which always
// passes a real `now`), so the throw is a pure dev-guard with no behavior
// change for valid inputs.
//
// Pins held here:
// 1. Source: the upsert signature is byte-identical (it anchors body slices
// in tests/remember-rotation-action-token.test.js); no
// `Number(issuedAt) || Date.now()` fallback remains on the issuedAt field;
// the guard precedes EVERY side effect (session id mint, registry write,
// persist); the only caller is the mint chain passing one `now` to both
// the entry and the token builder.
// 2. Behavior (vm-extracted upsert): issuedAt 0/NaN/null/""/-5 throw the
// guard message before any mutation; an explicit undefined is masked by
// the (byte-identical) signature's default parameter, which stamps a real
// positive instant — the raw guard's response to a reaching-undefined is
// pinned through a default-stripped harness variant; a valid now mints
// identically (entry.issuedAt === the passed value, never Date.now()).
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");
const UPSERT_SIGNATURE = "function upsertRememberLoginRegistryEntry(req, user, expiresAt, issuedAt = Date.now()) {";
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 tests/remember-iat-binding.test.js):
// skips // and /* */ comments so the adpanel: comment convention cannot desync
// the brace tracker.
function extractBlock(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker not found: ${startMarker}`);
let i = start + startMarker.length;
let depth;
if (startMarker.endsWith("{")) {
depth = 1;
} else {
while (i < source.length && /\s/.test(source[i])) i += 1;
assert.ok(i < source.length && source[i] === "{", `no opening brace after: ${startMarker}`);
depth = 1;
}
let inString = null;
while (i < source.length && depth > 0) {
i += 1;
const ch = source[i];
if (inString) {
if (ch === "\\") { i += 1; continue; }
if (ch === inString) inString = null;
continue;
}
if (ch === "/" && source[i + 1] === "/") {
while (i < source.length && source[i] !== "\n") i += 1;
continue;
}
if (ch === "/" && source[i + 1] === "*") {
i += 2;
while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i += 1;
i += 1;
continue;
}
if (ch === '"' || ch === "'" || ch === "`") inString = ch;
else if (ch === "{") depth += 1;
else if (ch === "}") depth -= 1;
}
assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`);
return source.slice(start, i + 1);
}
const UPSERT_SOURCE = extractBlock(indexSource, UPSERT_SIGNATURE);
const UPSERT_SLICE = sliceBetween(indexSource, UPSERT_SIGNATURE, "function revokeRememberLoginRegistryEntry(rememberId) {");
const ISSUE_SOURCE = extractBlock(indexSource, "function issueRememberLoginToken(req, user, now = Date.now()) {");
// ---------------------------------------------------------------------------
// Source pins — signature, guard placement, no silent fallback, one caller
// ---------------------------------------------------------------------------
test("the upsert signature stays byte-identical (it anchors body slices in other tests)", () => {
assert.ok(
indexSource.includes(UPSERT_SIGNATURE),
"the signature (including the issuedAt = Date.now() default) must stay byte-identical — tests/remember-fresh-reissue.test.js and tests/remember-rotation-action-token.test.js slice the body anchored on it"
);
});
test("no silent issuedAt fallback remains; the loud guard precedes every side effect", () => {
assert.doesNotMatch(
UPSERT_SLICE,
/issuedAt:\s*Number\(issuedAt\)\s*\|\|\s*Date\.now\(\)/,
"the silent `Number(issuedAt) || Date.now()` stamp must stay removed — it desyncs entry.issuedAt from token.iat"
);
assert.ok(
UPSERT_SLICE.includes("issuedAt: stampedIssuedAt,"),
"the entry must be stamped from the guarded stampedIssuedAt value"
);
assert.ok(
UPSERT_SLICE.includes('throw new Error("upsertRememberLoginRegistryEntry: issuedAt must be a positive epoch-ms timestamp matching the token iat")'),
"the guard must throw the loud dev-guard message"
);
assert.match(
UPSERT_SLICE,
/const stampedIssuedAt = Number\(issuedAt\);\s*\n\s*if \(!\(stampedIssuedAt > 0\)\) \{/,
"the guard shape must be the specified Number() + !(> 0) check"
);
const guardIdx = UPSERT_SLICE.indexOf("const stampedIssuedAt = Number(issuedAt);");
const ensureIdIdx = UPSERT_SLICE.indexOf("ensureRememberLoginSessionId(req)");
const registryWriteIdx = UPSERT_SLICE.indexOf("rememberLoginRegistry[rememberId] = {");
const persistIdx = UPSERT_SLICE.indexOf("persistRememberLoginRegistry();");
assert.ok(guardIdx >= 0 && ensureIdIdx > guardIdx, "the guard must run before the session id mint (no session side effect on a junk call)");
assert.ok(registryWriteIdx > guardIdx, "the guard must throw before any registry write");
assert.ok(persistIdx > guardIdx && persistIdx > registryWriteIdx, "the persist must follow the registry write");
});
test("the only caller is the mint chain, stamping entry and token from the same `now`", () => {
const callCount = indexSource.split("upsertRememberLoginRegistryEntry(").length - 1;
assert.strictEqual(callCount, 2,
"exactly one call site (+1 for the declaration) — no second caller can bypass the mint chain");
assert.ok(
ISSUE_SOURCE.includes("const expiresAt = now + REMEMBER_LOGIN_MAX_AGE_MS;") &&
ISSUE_SOURCE.includes("upsertRememberLoginRegistryEntry(req, user, expiresAt, now);") &&
ISSUE_SOURCE.includes("buildRememberLoginToken(user, rememberId, now, expiresAt);"),
"issueRememberLoginToken must feed the SAME `now` to the entry writer and the token builder (the guard's throw is therefore unreachable today — a pure dev-guard)"
);
// The mint chain's only caller stamps its `now` from Date.now() (positive).
const setCookieSource = extractBlock(indexSource, "function setRememberLoginCookie(req, res, user, options = {}) {");
const nowIdx = setCookieSource.indexOf("const now = Date.now();");
const callIdx = setCookieSource.indexOf("issueRememberLoginToken(req, user, now);");
assert.ok(nowIdx >= 0 && callIdx > nowIdx,
"setRememberLoginCookie stamps now = Date.now() before calling the mint chain — the guard can never fire on the live path");
});
// ---------------------------------------------------------------------------
// Behavior pins — vm-extracted upsert against stubbed plumbing
// ---------------------------------------------------------------------------
const GUARD_MESSAGE = "upsertRememberLoginRegistryEntry: issuedAt must be a positive epoch-ms timestamp matching the token iat";
const VALID_NOW = 1700000000000;
const EXPIRES_AT = VALID_NOW + 365 * 24 * 60 * 60 * 1000;
const USER = { id: 42, email: "user@example.test" };
function buildUpsertHarness() {
const calls = { ensureId: 0, persist: 0 };
const registry = {};
const sandbox = {
console: { log: () => {}, warn: () => {} },
ensureRememberLoginSessionId: (req) => {
calls.ensureId += 1;
const current = String(req.session.rememberLoginId || "").trim();
if (current) return current;
const minted = "minted-remember-id-0001";
req.session.rememberLoginId = minted;
return minted;
},
getRequestIp: () => "203.0.113.9",
normalizeBrowserSessionAudit: (existing, seed) => ({
createdAt: seed.createdAt,
lastSeenAt: seed.lastSeenAt,
userAgent: seed.userAgent,
firstIp: seed.firstIp,
lastIp: seed.lastIp,
rememberLoginId: seed.rememberLoginId,
}),
REMEMBER_LOGIN_MAX_AGE_MS: 365 * 24 * 60 * 60 * 1000,
rememberLoginRegistry: registry,
locallyMintedRememberLoginIds: new Set(),
persistRememberLoginRegistry: () => { calls.persist += 1; },
};
vm.createContext(sandbox);
const fn = vm.runInContext(`(${UPSERT_SOURCE})`, sandbox, { filename: "upsert-sandbox.js" });
return { fn, registry, calls, minted: sandbox.locallyMintedRememberLoginIds, sandbox };
}
function freshReq() {
return { sessionID: "sess-1", session: {}, get: () => "test-agent" };
}
test("issuedAt 0/NaN/null/''/-5 throw the guard message before ANY registry mutation", () => {
for (const junk of [0, NaN, null, "", -5]) {
const { fn, registry, calls, minted } = buildUpsertHarness();
const req = freshReq();
// Object matcher (not instanceof): the throw crosses the vm realm.
assert.throws(
() => fn(req, USER, EXPIRES_AT, junk),
{ message: GUARD_MESSAGE },
`issuedAt=${String(junk)} must throw the loud dev-guard message`
);
assert.deepStrictEqual(registry, {}, `issuedAt=${String(junk)}: no registry entry may be written`);
assert.strictEqual(calls.persist, 0, `issuedAt=${String(junk)}: no persist may run`);
assert.strictEqual(calls.ensureId, 0, `issuedAt=${String(junk)}: not even the session id mint may run (throw precedes every side effect)`);
assert.strictEqual(minted.size, 0, `issuedAt=${String(junk)}: no mint provenance may be recorded`);
assert.strictEqual(req.session.rememberLoginId, undefined, `issuedAt=${String(junk)}: the session must stay untouched`);
}
});
test("an explicit undefined is masked by the byte-identical signature's default parameter (real positive stamp)", () => {
// JS semantics: the `issuedAt = Date.now()` default fires for an explicit
// undefined BEFORE the body runs, so the shipped function cannot observe a
// raw undefined — the guard can only reject values that REACH it. Pin the
// shipped behavior: the default-parameter path stamps a real positive
// instant (never junk), which is why the signature cannot be changed.
const { fn, registry, calls } = buildUpsertHarness();
const req = freshReq();
const before = Date.now();
const rememberId = fn(req, USER, EXPIRES_AT, undefined);
assert.strictEqual(rememberId, "minted-remember-id-0001", "the shipped default-parameter path mints normally");
const entry = registry[rememberId];
assert.ok(Number(entry.issuedAt) >= before, "the masked-undefined call stamps a real (>= call time) instant, never 0/NaN");
assert.strictEqual(calls.persist, 1, "the mint completed");
// The raw guard's response to a REACHING undefined (i.e. what a caller
// without the default would hit) is still fail-loud: pin it through a
// default-stripped harness variant of the SAME shipped body.
const stripped = UPSERT_SOURCE.replace("issuedAt = Date.now()", "issuedAt");
assert.strictEqual(
UPSERT_SOURCE.split("issuedAt = Date.now()").length - 1,
1,
"the default appears exactly once (the signature) — the harness transform is exact"
);
const strippedHarness = buildUpsertHarness();
const fnStripped = vm.runInContext(`(${stripped})`, strippedHarness.sandbox, { filename: "upsert-stripped-sandbox.js" });
// Object matcher (not instanceof): the throw crosses the vm realm.
assert.throws(
() => fnStripped(freshReq(), USER, EXPIRES_AT, undefined),
{ message: GUARD_MESSAGE },
"a raw undefined reaching the guard must throw the loud dev-guard message"
);
assert.deepStrictEqual(strippedHarness.registry, {}, "the stripped-variant throw precedes any registry mutation too");
});
test("a valid now mints identically: entry.issuedAt is the PASSED value (never a Date.now() fallback)", () => {
const { fn, registry, calls, minted } = buildUpsertHarness();
const req = freshReq();
const rememberId = fn(req, USER, EXPIRES_AT, VALID_NOW);
assert.strictEqual(rememberId, "minted-remember-id-0001", "the mint returns the session's remember id");
const entry = registry[rememberId];
assert.strictEqual(entry.issuedAt, VALID_NOW, "entry.issuedAt must be EXACTLY the passed instant — the same `now` the token's iat gets");
assert.strictEqual(entry.expiresAt, EXPIRES_AT, "the hard expiry is the passed expiresAt");
assert.strictEqual(entry.absoluteExpiresAt, EXPIRES_AT, "interactive issuance anchors the absolute expiry at its own expiry");
assert.strictEqual(entry.uid, "42", "the owner binding is preserved");
assert.strictEqual(entry.email, "user@example.test", "the email binding is preserved");
assert.ok(entry.lastSeenAt > 0, "the audit-derived lastSeenAt is stamped");
assert.strictEqual(calls.persist, 1, "the registry persist ran once");
assert.ok(minted.has(rememberId), "a fresh mint is recorded in the provenance set");
assert.strictEqual(calls.ensureId, 1, "the session id mint ran once");
// Update path (same id): still returns the id, no duplicate entries.
const rememberId2 = fn(req, USER, EXPIRES_AT + 1000, VALID_NOW + 1000);
assert.strictEqual(rememberId2, rememberId, "an existing session id is reused");
assert.strictEqual(Object.keys(registry).length, 1, "no duplicate registry entries");
assert.strictEqual(registry[rememberId].issuedAt, VALID_NOW + 1000, "the update stamps the new passed instant verbatim");
assert.strictEqual(calls.persist, 2, "the update persisted again");
});