Files
Kelx/scripts/verify-user-lifecycle-session-revocation.js
T
2026-11-30 16:32:37 +00:00

1126 lines
60 KiB
JavaScript

// Standalone verification harness for the user-lifecycle session-revocation
// fix (the session-invalidation hole where CLI account mutations and the
// panel's account lifecycle endpoints left stale browser sessions and live
// sockets authenticated after a delete / password change / re-provision).
//
// Five layers (premise restated 2026-11: the CLI is no longer the only epoch
// bumper — every interactive credential writer now bumps in-statement, and
// generation lives in ONE shared module):
// A. mysql-schema.sql (static) — users.session_epoch and the idempotent
// pending_session_revocations queue table (PRIMARY KEY email, VARCHAR(64)
// reason covering every CLI reason literal).
// B. scripts/create-user.js (static) — every CLI mutation path must enqueue
// a pending revocation ('cli-delete' inside the --delete transaction,
// 'cli-password' on --update-password, 'cli-create' vs
// 'cli-create-existing' on the create upsert), mint its session epoch
// through the ONE shared generator (utils/session-epoch.js —
// adpanel:credential-generation: CSPRNG crypto.randomInt in
// [1, 2147483647], never 0, never a constant or a +1 increment, the
// ≠current retry for --update-password) and never print the epoch value.
// C. index.js (static) — the timer-driven sweep: setInterval(~5000ms) +
// .unref(), atomic claim via DELETE … WHERE email = ? AND requested_at = ?
// gated on affectedRows === 1, destroyBrowserSessionsForUser +
// disconnectSocketsForUser, retries with attempts+1 and a loud give-up at
// 5 attempts; plus the DELETE /api/settings/accounts/:email endpoint
// clearing the pending row after the delete commits and the
// POST /api/admin/user/create endpoint evicting the provisioned email.
// D. behavioral — only when the sweep's claim logic was factored into a
// requireable module. This harness never boots the panel, never connects
// to a database and never runs npm install, so an inlined sweep is SKIPped.
// E. credential writers everywhere (panel routes + the admin-2fa-reset
// service + the CLI) bump session_epoch IN THE SAME SQL statement as the
// credential they rotate (adpanel:credential-generation: a generation
// committed separately from its credential leaves a window where the
// stale credential authenticates against the new generation), and
// non-credential writers (login bcrypt rehash, recovery-code burn, TOTP
// counter claim, recovery-set replacements) stay epoch-free.
//
// Concurrent-edit awareness: the fix was landing while this harness was
// written. When a check fails and its feature is entirely absent from the
// target file, the failure is annotated "not yet implemented (concurrent
// agent still in flight)" so it can be told apart from a wrong implementation.
// This harness only ever READS the sources — requiring index.js would boot
// the panel and requiring create-user.js would open the DB pool.
//
// Run: node scripts/verify-user-lifecycle-session-revocation.js
"use strict";
const fs = require("fs");
const path = require("path");
const ROOT = path.join(__dirname, "..");
const TARGETS = {
schema: path.join(ROOT, "mysql-schema.sql"),
cli: path.join(ROOT, "scripts", "create-user.js"),
panel: path.join(ROOT, "index.js"),
shared: path.join(ROOT, "utils", "session-epoch.js"),
service: path.join(ROOT, "services", "admin-2fa-reset.js"),
credentials: path.join(ROOT, "services", "account-credentials.js"),
actions: path.join(ROOT, "services", "account-actions.js"),
};
const CLI_REASONS = ["cli-delete", "cli-password", "cli-create", "cli-create-existing"];
const LONGEST_REASON = CLI_REASONS.reduce((a, b) => (b.length > a.length ? b : a), "");
const SWEEP_INTERVAL_MS = 5000;
const GIVE_UP_ATTEMPTS = 5;
// ---- reporting -----------------------------------------------------------------
const results = [];
function record(id, label, status, detail) {
results.push({ id, label, status, detail });
const head = ` [${id}] ${status.padEnd(4)} ${label}`;
if (detail) console.log(`${head}\n ${String(detail).split("\n").join("\n ")}`);
else console.log(head);
}
function check(id, label, fn) {
try {
const note = fn();
record(id, label, "PASS", typeof note === "string" ? note : "");
} catch (err) {
if (err && err.__warn) record(id, label, "WARN", err.message);
else if (err && err.__skip) record(id, label, "SKIP", err.message);
else record(id, label, "FAIL", err && err.message ? err.message : String(err));
}
}
function fail(msg) { throw new Error(msg); }
function warn(msg) { throw Object.assign(new Error(msg), { __warn: true }); }
function skip(msg) { throw Object.assign(new Error(msg), { __skip: true }); }
// gatePresent: does the target file already reference this feature at all?
// If not, the failure is the concurrent agent's missing piece, not a bug.
function notYetImplemented(gatePresent, msg) {
return gatePresent ? msg : `${msg} — not yet implemented (concurrent agent still in flight)`;
}
function banner(t) { console.log(`\n${t}`); }
// ---- source loading and shared static-analysis helpers -------------------------
function readSource(p) { try { return fs.readFileSync(p, "utf8"); } catch { return null; } }
// Same convention as verify-db-user-privileges.js (drop comments before
// asserting, because the sources deliberately NAME these features in
// explanatory prose), but implemented as a string-aware scanner: a naive
// regex stripper treats the "/* … */" inside index.js's template-literal CSS
// as a real comment and silently swallows half the file (which hides route
// handlers). Comment text is blanked and every other character — including
// newlines — is kept, so offsets and line numbers in the result are IDENTICAL
// to the input. sqlLines additionally blanks SQL "--" full-line comments
// (mysql-schema.sql).
function stripComments(src, sqlLines) {
const out = src.split("");
const n = src.length;
const stack = []; // one entry per open ${ … } interpolation: { depth }
let mode = "code"; // code | " | ' | tpl | regex
let prevSig = "";
let regexClass = false;
let i = 0;
while (i < n) {
const c = src[i];
const d = i + 1 < n ? src[i + 1] : "";
if (mode === "code") {
if (c === "/" && d === "/") {
while (i < n && src[i] !== "\n") { out[i] = " "; i++; }
continue;
}
if (c === "/" && d === "*") {
out[i] = " "; out[i + 1] = " "; i += 2;
while (i < n) {
if (src[i] === "*" && src[i + 1] === "/") { out[i] = " "; out[i + 1] = " "; i += 2; break; }
if (src[i] !== "\n") out[i] = " ";
i++;
}
continue;
}
if (c === '"' || c === "'") { mode = c; i++; continue; }
if (c === "`") { mode = "tpl"; i++; continue; }
if (c === "}" && stack.length) {
const top = stack[stack.length - 1];
if (top.depth > 0) top.depth--;
else { stack.pop(); mode = "tpl"; }
i++;
continue;
}
if (c === "{" && stack.length) { stack[stack.length - 1].depth++; i++; continue; }
if (c === "/" && /^[=(,:[!&|?{};+\-*%<>~^]$/.test(prevSig)) { mode = "regex"; regexClass = false; i++; continue; }
if (!/\s/.test(c)) prevSig = c;
i++;
continue;
}
if (mode === '"' || mode === "'") {
if (c === "\\") { i += 2; continue; }
if (c === mode) { mode = "code"; prevSig = c; }
i++;
continue;
}
if (mode === "tpl") {
if (c === "\\") { i += 2; continue; }
if (c === "`") { mode = "code"; prevSig = c; i++; continue; }
if (c === "$" && d === "{") { stack.push({ depth: 0 }); mode = "code"; prevSig = "{"; i += 2; continue; }
i++;
continue;
}
if (mode === "regex") {
if (c === "\\") { i += 2; continue; }
if (c === "\n") { mode = "code"; continue; } // heuristics misfired; reset
if (regexClass) { if (c === "]") regexClass = false; i++; continue; }
if (c === "[") { regexClass = true; i++; continue; }
if (c === "/") { mode = "code"; prevSig = "/"; i++; continue; }
i++;
continue;
}
}
let result = out.join("");
if (sqlLines) result = result.replace(/^[ \t]*--.*$/gm, (m) => m.replace(/[^\n]/g, ""));
return result;
}
function esc(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }
function lineOf(src, idx) {
let line = 1;
for (let i = 0; i < idx && i < src.length; i++) if (src[i] === "\n") line++;
return line;
}
function at(src, idx) { return `line ${lineOf(src, idx)}`; }
// Top-level declaration boundaries. Function bodies and route handlers are
// sliced between consecutive starts — deliberately NOT brace-matched, so
// regex literals like /\d{1,3}/ inside 48k-line index.js cannot desynchronize
// region extraction.
const REGION_START_RE = new RegExp(
"\\n(?:" +
"(?:async\\s+)?function\\s+[A-Za-z0-9_$]+\\s*\\(" +
"|(?:const|let|var)\\s+[A-Za-z0-9_$]+\\s*=\\s*(?:async\\s*)?(?:function\\b|\\([^)]*\\)\\s*=>|[A-Za-z0-9_$]+\\s*=>)" +
"|app\\s*\\.\\s*(?:get|post|put|delete|patch|use|all)\\s*\\(" +
")"
);
function buildRegions(src) {
const starts = [];
const re = new RegExp(REGION_START_RE.source, "g");
let m;
while ((m = re.exec(src)) !== null) starts.push(m.index + 1);
return starts;
}
function regionAround(src, starts, idx) {
let lo = 0, hi = starts.length - 1, pos = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (starts[mid] <= idx) { pos = mid; lo = mid + 1; } else { hi = mid - 1; }
}
const start = pos === -1 ? 0 : starts[pos];
const end = pos + 1 < starts.length ? starts[pos + 1] : src.length;
return { start, end, header: src.slice(start, start + 160).split("\n")[0].trim() };
}
function regionName(header) {
const m = /(?:function|const|let|var)\s+([A-Za-z0-9_$]+)/.exec(header);
return m ? m[1] : null;
}
function functionRegionByName(src, starts, name) {
const re = new RegExp(
`\\n(?:async\\s+)?function\\s+${esc(name)}\\s*\\(|\\n(?:const|let|var)\\s+${esc(name)}\\s*=`
);
const m = re.exec(src);
if (!m) return null;
const r = regionAround(src, starts, m.index + 1);
return { ...r, name, body: src.slice(r.start, r.end) };
}
// A check region plus the bodies of any revocation-named helpers it calls, so
// a factored-out upsert still counts as belonging to the calling path.
function regionPlusRevocationHelpers(src, starts, regionBody) {
let out = regionBody;
const callRe = /([A-Za-z0-9_$]*[Rr]evocation[A-Za-z0-9_$]*)\s*\(/g;
let m;
while ((m = callRe.exec(regionBody)) !== null) {
const fn = functionRegionByName(src, starts, m[1]);
if (fn && fn.start !== 0) out += `\n${fn.body}`;
}
return out;
}
// Naive paren matcher for mysql-schema.sql (no regex/bracket traps there).
function sqlTableBlock(src, name) {
const re = new RegExp(`CREATE\\s+TABLE\\s+(IF\\s+NOT\\s+EXISTS\\s+)?\`?${esc(name)}\`?\\s*\\(`, "i");
const m = re.exec(src);
if (!m) return null;
const open = m.index + m[0].length - 1;
let depth = 0;
let close = -1;
for (let i = open; i < src.length; i++) {
if (src[i] === "(") depth++;
else if (src[i] === ")") { depth--; if (depth === 0) { close = i; break; } }
}
if (close === -1) return null;
return { start: m.index, ifNotExists: !!m[1], body: src.slice(m.index, close + 1) };
}
// Naive brace matcher for the small CLI file's if-blocks (create-user.js has
// no regex literals with braces and no unbalanced braces inside strings).
// ALL matches are returned: create-user.js carries more than one `if
// (args.delete)` block (the pre-delete ALTER widen runs before the delete
// transaction), so a first-match-only helper would slice the wrong block and
// false-fail the transaction pin.
function ifBlocksAt(src, condRe) {
const out = [];
const re = new RegExp(condRe.source, condRe.flags.includes("g") ? condRe.flags : condRe.flags + "g");
let m;
while ((m = re.exec(src)) !== null) {
const open = src.indexOf("{", m.index);
if (open === -1) break;
let depth = 0;
let closed = -1;
for (let i = open; i < src.length && i < open + 20000; i++) {
if (src[i] === "{") depth++;
else if (src[i] === "}") {
depth--;
if (depth === 0) { closed = i; break; }
}
}
out.push({ start: m.index, end: closed === -1 ? src.length - 1 : closed, body: closed === -1 ? src.slice(m.index) : src.slice(m.index, closed + 1) });
re.lastIndex = closed === -1 ? src.length : closed;
}
return out;
}
function ifBlockAt(src, condRe) {
return ifBlocksAt(src, condRe)[0] || null;
}
// Split a call's argument list on top-level commas (quote-aware).
function splitTopLevel(s) {
const parts = [];
let depth = 0;
let inStr = null;
let escNext = false;
let cur = "";
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (inStr) {
cur += c;
if (escNext) { escNext = false; continue; }
if (c === "\\") { escNext = true; continue; }
if (c === inStr) inStr = null;
continue;
}
if (c === "'" || c === '"' || c === "`") { inStr = c; cur += c; continue; }
if (c === "(" || c === "{" || c === "[") { depth++; cur += c; continue; }
if (c === ")" || c === "}" || c === "]") { depth--; cur += c; continue; }
if (c === "," && depth === 0) { parts.push(cur); cur = ""; continue; }
cur += c;
}
parts.push(cur);
return parts;
}
// Every top-level setInterval call, with its args split and the text that
// follows it (for chained/adjacent .unref() detection).
function setIntervalCalls(src) {
const out = [];
const re = /setInterval\s*\(/g;
let m;
while ((m = re.exec(src)) !== null) {
const open = m.index + m[0].length - 1;
let depth = 0;
let close = -1;
const limit = Math.min(src.length, open + 6000);
for (let i = open; i < limit; i++) {
if (src[i] === "(") depth++;
else if (src[i] === ")") { depth--; if (depth === 0) { close = i; break; } }
}
const argsText = close === -1 ? src.slice(open + 1, limit) : src.slice(open + 1, close);
let headStart = m.index - 1;
while (headStart >= 0 && src[headStart] !== ";" && src[headStart] !== "\n" && src[headStart] !== "}") headStart--;
out.push({
idx: m.index,
args: splitTopLevel(argsText),
tail: close === -1 ? "" : src.slice(close, Math.min(close + 400, src.length)),
stmtHead: src.slice(headStart + 1, m.index),
});
}
return out;
}
// ---- load targets (read-only) ---------------------------------------------------
const schemaRaw = readSource(TARGETS.schema);
const cliRaw = readSource(TARGETS.cli);
const panelRaw = readSource(TARGETS.panel);
const sharedRaw = readSource(TARGETS.shared);
const serviceRaw = readSource(TARGETS.service);
const credentialsRaw = readSource(TARGETS.credentials);
const actionsRaw = readSource(TARGETS.actions);
const schema = schemaRaw === null ? null : stripComments(schemaRaw, true);
const cli = cliRaw === null ? null : stripComments(cliRaw, false);
const panel = panelRaw === null ? null : stripComments(panelRaw, false);
const shared = sharedRaw === null ? null : stripComments(sharedRaw, false);
const service = serviceRaw === null ? null : stripComments(serviceRaw, false);
const credentials = credentialsRaw === null ? null : stripComments(credentialsRaw, false);
const actions = actionsRaw === null ? null : stripComments(actionsRaw, false);
const panelStarts = panel ? buildRegions(panel) : [];
const cliStarts = cli ? buildRegions(cli) : [];
const revIdxs = [];
if (panel) {
const re = /pending_session_revocations/g;
let m;
while ((m = re.exec(panel)) !== null) revIdxs.push(m.index);
}
const panelHasRevocations = revIdxs.length > 0;
// Regions referencing the queue: the sweep candidates (route handlers are
// excluded later where a *function* is required).
const sweepRegions = [];
if (panelHasRevocations) {
const seen = new Set();
for (const idx of revIdxs) {
const r = regionAround(panel, panelStarts, idx);
if (!seen.has(r.start)) {
seen.add(r.start);
sweepRegions.push({ ...r, name: regionName(r.header), body: panel.slice(r.start, r.end) });
}
}
}
// The atomic claim DELETE (shared by C2/C3/C4). There may be several — e.g. a
// cleanup delete for unusable rows plus the real claim — so keep them all.
const CLAIM_RE = /DELETE\s+FROM\s+`?pending_session_revocations`?\s+WHERE\s+`?email`?\s*=\s*\?\s+AND\s+`?requested_at`?\s*=\s*\?/gi;
const claimMatches = [];
if (panel) {
let m;
while ((m = CLAIM_RE.exec(panel)) !== null) claimMatches.push(m);
}
// The gate may be written directly (affectedRows === 1 → proceed) or inverted
// (affectedRows !== 1 → skip); both are the same atomic claim. A gate belongs
// to the claim it follows — search up to the NEXT claim DELETE, so one claim's
// window cannot be satisfied by a later claim's gate. Direction check: the
// first control-flow keyword or eviction call after the comparison tells
// which branch the gate guards — a gate that BAILS on === 1 (the winning
// worker would skip and eviction would run unconditionally below) or EVICTS
// on !== 1 (evicting exactly when the claim was lost) is the broken inversion
// of the atomic claim and must not satisfy this check.
function claimIsGated(src, mt, nextIdx) {
const limit = nextIdx !== -1 ? Math.min(nextIdx, mt.index + 800) : mt.index + 800;
const win = src.slice(mt.index, limit);
const direct = /affectedRows\s*===?\s*1\b/.exec(win);
const inverted = /affectedRows[^;\n]{0,40}!==?\s*1\b/.exec(win);
if (!direct && !inverted) return false;
const firstOf = (text) => {
const bail = /\b(?:return|continue|break|throw)\b/.exec(text);
const evict = /\b(?:destroyBrowserSessionsForUser|disconnectSocketsForUser)\s*\(/.exec(text);
return {
bailIdx: bail ? bail.index : Infinity,
evictIdx: evict ? evict.index : Infinity,
};
};
if (direct && (!inverted || direct.index <= inverted.index)) {
const { bailIdx, evictIdx } = firstOf(win.slice(direct.index + direct[0].length));
if (bailIdx !== Infinity && bailIdx < evictIdx) return false; // bails on success — inverted logic
return true;
}
const { bailIdx, evictIdx } = firstOf(win.slice(inverted.index + inverted[0].length));
if (evictIdx !== Infinity && evictIdx < bailIdx) return false; // evicts on failure — inverted logic
return true;
}
let gatedClaimIdx = -1;
for (let k = 0; k < claimMatches.length; k++) {
const nextIdx = k + 1 < claimMatches.length ? claimMatches[k + 1].index : -1;
if (claimIsGated(panel, claimMatches[k], nextIdx)) { gatedClaimIdx = k; break; }
}
// Prefer the claim that is actually gated (C2 reports this); fall back to the first.
let claimMatch = gatedClaimIdx !== -1 ? claimMatches[gatedClaimIdx] : (claimMatches[0] || null);
const sweepFunctionRegions = [];
if (panel) {
const seen = new Set();
const push = (r) => {
if (r && !seen.has(r.start)) {
seen.add(r.start);
sweepFunctionRegions.push({ ...r, name: regionName(r.header), body: panel.slice(r.start, r.end) });
}
};
if (claimMatch) push(regionAround(panel, panelStarts, claimMatch.index));
for (const r of sweepRegions) {
if (r.header && !/^app\s*\./.test(r.header)) push(r);
}
}
// ---- harness header --------------------------------------------------------------
console.log("user-lifecycle session-revocation verification harness");
console.log("statuses: PASS / FAIL / WARN / SKIP (FAIL fails the run)");
for (const [k, p] of Object.entries(TARGETS)) {
const raw = { schema: schemaRaw, cli: cliRaw, panel: panelRaw, shared: sharedRaw, service: serviceRaw, credentials: credentialsRaw, actions: actionsRaw }[k];
console.log(` ${k.padEnd(7)}: ${p}${raw === null ? " (NOT FOUND)" : ` (${raw.split("\n").length} lines)`}`);
}
// == A. schema contract (mysql-schema.sql) =========================================
banner("A. schema contract (mysql-schema.sql)");
check("A1", "users.session_epoch declared BIGINT UNSIGNED NOT NULL DEFAULT 0", () => {
if (schema === null) fail(`target file not found: ${TARGETS.schema}`);
const users = sqlTableBlock(schema, "users");
if (!users) fail("CREATE TABLE users not found in mysql-schema.sql");
const m = /session_epoch\s+BIGINT\s+UNSIGNED\s+NOT\s+NULL\s+DEFAULT\s+'?0'?\b/i.exec(users.body);
if (!m) {
const colIdx = users.body.search(/session_epoch/i);
const present = colIdx !== -1;
fail(notYetImplemented(present, present
? `users.session_epoch is declared at ${at(schema, users.start + colIdx)} but not as BIGINT UNSIGNED NOT NULL DEFAULT 0`
: "users.session_epoch column missing from the users CREATE TABLE"));
}
return `users table at ${at(schema, users.start)} declares session_epoch BIGINT UNSIGNED NOT NULL DEFAULT 0`;
});
check("A2", "pending_session_revocations: CREATE TABLE IF NOT EXISTS with PRIMARY KEY (email)", () => {
if (schema === null) fail(`target file not found: ${TARGETS.schema}`);
const gate = /pending_session_revocations/i.test(schema);
const t = sqlTableBlock(schema, "pending_session_revocations");
if (!t) fail(notYetImplemented(gate, "pending_session_revocations table is missing from mysql-schema.sql"));
if (!t.ifNotExists) fail(`pending_session_revocations at ${at(schema, t.start)} is not CREATE TABLE IF NOT EXISTS — re-runs would fail`);
const problems = [];
if (!/PRIMARY\s+KEY\s*\(\s*`?email`?\s*\)/i.test(t.body)) problems.push("no PRIMARY KEY (email)");
if (!/requested_at\s+BIGINT\s+UNSIGNED\s+NOT\s+NULL/i.test(t.body)) problems.push("requested_at BIGINT UNSIGNED NOT NULL missing");
if (!/attempts\s+INT\s+UNSIGNED\s+NOT\s+NULL/i.test(t.body)) problems.push("attempts INT UNSIGNED NOT NULL missing");
if (problems.length) fail(`${at(schema, t.start)}: ${problems.join("; ")}`);
return `idempotent queue table at ${at(schema, t.start)}; PRIMARY KEY (email), requested_at and attempts present`;
});
check("A3", "reason column fits every CLI reason (VARCHAR(64) per contract)", () => {
if (schema === null) fail(`target file not found: ${TARGETS.schema}`);
const gate = /pending_session_revocations/i.test(schema);
const t = sqlTableBlock(schema, "pending_session_revocations");
if (!t) fail(notYetImplemented(gate, "pending_session_revocations table is missing — nothing to size"));
const m = /reason\s+VARCHAR\s*\(\s*(\d+)\s*\)/i.exec(t.body);
if (!m) fail(`reason column at ${at(schema, t.start)} is not VARCHAR(n); contract requires VARCHAR(64)`);
const n = parseInt(m[1], 10);
const tooLong = CLI_REASONS.filter((r) => r.length > n);
if (tooLong.length) fail(`reason VARCHAR(${n}) cannot store: ${tooLong.join(", ")} (longest '${LONGEST_REASON}' is ${LONGEST_REASON.length} chars)`);
const notes = [];
if (n < 64) notes.push(`VARCHAR(${n}) holds every CLI reason but deviates from the contract's VARCHAR(64)`);
if (!/reason\s+VARCHAR\s*\(\s*\d+\s*\)\s+NOT\s+NULL\s+DEFAULT\s+''/i.test(t.body)) notes.push("reason lacks NOT NULL DEFAULT ''");
if (notes.length) warn(`${at(schema, t.start)}: ${notes.join("; ")}`);
return `reason VARCHAR(${n}) covers '${LONGEST_REASON}' (${LONGEST_REASON.length} chars)`;
});
// == B. cli lifecycle writes (scripts/create-user.js) ==============================
banner("B. cli lifecycle writes (scripts/create-user.js)");
const deleteIf = cli
? (ifBlocksAt(cli, /if\s*\(\s*args\.delete\s*\)/).find((b) => /beginTransaction\s*\(/.test(b.body)) || ifBlockAt(cli, /if\s*\(\s*args\.delete\s*\)/))
: null;
const updateIf = cli ? ifBlockAt(cli, /if\s*\(\s*args\.updatePassword\s*\)/) : null;
check("B1", "--delete path enqueues the pending revocation inside its transaction", () => {
if (cli === null) fail(`target file not found: ${TARGETS.cli}`);
if (!deleteIf) fail("the --delete path (if (args.delete) {…}) was not found in scripts/create-user.js");
const gate = /pending_session_revocations|cli-delete/.test(cli);
const beginIdx = deleteIf.body.search(/beginTransaction\s*\(/);
let txn = null;
if (beginIdx !== -1) {
const commitIdx = deleteIf.body.indexOf("commit(", beginIdx);
if (commitIdx !== -1) txn = deleteIf.body.slice(beginIdx, commitIdx + 7);
} else {
// tolerate a factored transaction helper (withTransaction/…)
const helper = /(?:withTransaction|\.transaction)\s*\(/.exec(deleteIf.body);
if (helper) txn = deleteIf.body.slice(helper.index, helper.index + 4000);
}
if (!txn) fail("the --delete path no longer runs inside a transaction (beginTransaction…commit not found)");
let ok = /(?:INSERT|REPLACE)\s+INTO\s+`?pending_session_revocations`?/i.test(txn);
let helperBodies = "";
let helperNote = "";
if (!ok) {
const callRe = /([A-Za-z0-9_$]*[Rr]evocation[A-Za-z0-9_$]*)\s*\(/g;
let cm;
while ((cm = callRe.exec(txn)) !== null) {
const fn = functionRegionByName(cli, cliStarts, cm[1]);
if (fn && /(?:INSERT|REPLACE)\s+INTO\s+`?pending_session_revocations`?/i.test(fn.body)) {
ok = true;
helperNote = ` (via ${cm[1]}())`;
helperBodies += `\n${fn.body}`;
break;
}
}
}
if (!ok) {
fail(notYetImplemented(gate, "no pending_session_revocations write (direct or via a revocation helper) between beginTransaction() and commit() in the --delete path"));
}
// Executor check (direct-transaction shape only): the queue write must run
// on the transaction connection. A requestSessionRevocation(db, …) call or
// a db./pool.-executed queue INSERT would place the row OUTSIDE the delete's
// atomicity — a rolled-back delete would still queue a revocation, and a
// crash between the delete's commit and the pooled write would delete
// without ever queueing one.
if (beginIdx !== -1) {
const stray = /(?:db|pool)\s*\.\s*(?:query|execute)\s*\([^)]*pending_session_revocations|(?:requestSessionRevocation|[A-Za-z0-9_$]*[Rr]evocation[A-Za-z0-9_$]*)\s*\(\s*(?:db|pool)\b/.exec(txn);
if (stray) {
fail(`the --delete path performs the pending_session_revocations write on the pooled handle instead of the transaction connection ("${stray[0].replace(/\s+/g, " ").slice(0, 80)}") — a rolled-back delete would still queue a revocation and a crash could delete without one`);
}
}
if (!/['"`]cli-delete['"`]/.test(`${txn}\n${helperBodies}`)) {
fail("the --delete transaction writes a pending revocation but never with the 'cli-delete' reason");
}
return `queued inside the --delete transaction${helperNote}`;
});
check("B2", "--update-password randomizes session_epoch and enqueues 'cli-password'", () => {
if (cli === null) fail(`target file not found: ${TARGETS.cli}`);
if (!updateIf) fail("the --update-password path (if (args.updatePassword) {…}) was not found");
const gate = /session_epoch|cli-password/.test(cli);
// the epoch may be generated just above the if-block; include a small look-behind
const region = cli.slice(Math.max(0, updateIf.start - 1200), updateIf.end + 1);
const effective = regionPlusRevocationHelpers(cli, cliStarts, region);
const missing = [];
if (!/session_epoch/i.test(effective)) missing.push("a users.session_epoch randomization/write");
if (!/['"`]cli-password['"`]/.test(effective)) missing.push("a pending_session_revocations upsert with reason 'cli-password'");
if (missing.length) fail(notYetImplemented(gate, `--update-password path is missing: ${missing.join("; ")}`));
return `--update-password path writes session_epoch and queues 'cli-password' (code around ${at(cli, updateIf.start)})`;
});
check("B3", "create path: INSERT…ON DUPLICATE KEY UPDATE carries session_epoch and queues 'cli-create'/'cli-create-existing'", () => {
if (cli === null) fail(`target file not found: ${TARGETS.cli}`);
const gate = /session_epoch|cli-create/.test(cli);
let stmt = null;
let stmtIdx = -1;
const insRe = /INSERT\s+INTO\s+`?users`?\s*\(/gi;
let im;
while ((im = insRe.exec(cli)) !== null) {
const window = cli.slice(im.index, im.index + 1600);
if (/ON\s+DUPLICATE\s+KEY\s+UPDATE/i.test(window)) { stmt = window; stmtIdx = im.index; break; }
}
if (!stmt) fail(notYetImplemented(gate, "no INSERT INTO users … ON DUPLICATE KEY UPDATE statement found (create path changed shape?)"));
const insMatch = /INSERT\s+INTO\s+`?users`?\s*\(/i.exec(stmt);
const colOpen = insMatch.index + insMatch[0].length - 1;
let colList = "";
let depth = 0;
for (let i = colOpen; i < stmt.length; i++) {
if (stmt[i] === "(") depth++;
else if (stmt[i] === ")") { depth--; if (depth === 0) { colList = stmt.slice(colOpen, i + 1); break; } }
}
const missing = [];
if (!colList || !/session_epoch/i.test(colList)) missing.push("session_epoch in the INSERT column list");
if (!/session_epoch\s*=\s*(?:VALUES\s*\(\s*`?session_epoch`?\s*\)|[A-Za-z0-9_$]+\.`?session_epoch`?)/i.test(stmt)) {
missing.push("ON DUPLICATE KEY UPDATE session_epoch = VALUES(session_epoch)");
}
const createRegion = cli.slice(updateIf ? updateIf.end + 1 : 0);
const hasExisting = /['"`]cli-create-existing['"`]/.test(createRegion);
const hasNew = /['"`]cli-create['"`]/.test(createRegion);
if (!hasExisting || !hasNew) {
missing.push(`both 'cli-create-existing' and 'cli-create' reasons in the create path (found existing=${hasExisting}, new=${hasNew})`);
}
const queued = /pending_session_revocations/i.test(createRegion) || /[A-Za-z0-9_$]*[Rr]evocation[A-Za-z0-9_$]*\s*\(/.test(createRegion);
if (!queued) missing.push("a pending_session_revocations upsert in the create path");
if (missing.length) fail(notYetImplemented(gate, `create path is missing: ${missing.join("; ")}`));
return `upsert statement at ${at(cli, stmtIdx)} carries session_epoch; both create reasons and the queue write present`;
});
// The ONE shared epoch generator (adpanel:credential-generation). The CLI's
// premise "the CLI is the only bumper" is retired: the panel's provisioning
// INSERT and every interactive credential writer mint through this module
// too, so CSPRNG proof follows the require — the module itself must carry the
// crypto.randomInt generation over the established range (never 0, never a
// predictable increment), and the CLI must NOT keep a local generator.
function sharedEpochModuleProof() {
if (shared === null) return { ok: false, why: `target file not found: ${TARGETS.shared}` };
if (!/crypto\.randomInt\s*\(\s*SESSION_EPOCH_MIN\s*,\s*SESSION_EPOCH_MAX\s*\)/.test(shared)) {
return { ok: false, why: "utils/session-epoch.js does not draw from crypto.randomInt(SESSION_EPOCH_MIN, SESSION_EPOCH_MAX)" };
}
if (!/SESSION_EPOCH_MIN\s*=\s*1\b/.test(shared) || !/SESSION_EPOCH_MAX\s*=\s*2147483647\b/.test(shared)) {
return { ok: false, why: "utils/session-epoch.js does not pin the established [1, 2147483647] range" };
}
if (/Math\.random|Date\.now/.test(shared)) {
return { ok: false, why: "utils/session-epoch.js reaches for a predictable PRNG" };
}
if (!/function\s+newSessionEpochDifferentFrom\s*\(/.test(shared)) {
return { ok: false, why: "utils/session-epoch.js no longer exports the ≠current generator (the CLI's --update-password needs it)" };
}
return { ok: true };
}
const sharedProof = sharedEpochModuleProof();
const sharedHelperCallRe = /\b(?:newSessionEpoch|newSessionEpochDifferentFrom)\s*\(/;
check("B4", "session_epoch generation is CSPRNG in the established range everywhere (via the ONE shared module), never a constant or +1 increment; the CLI keeps no local generator", () => {
if (cli === null) fail(`target file not found: ${TARGETS.cli}`);
const gate = /session_epoch/i.test(cli);
if (!gate) fail(notYetImplemented(false, "scripts/create-user.js does not reference session_epoch yet"));
if (!sharedProof.ok) fail(`the shared epoch generator is unusable — ${sharedProof.why}`);
// The require must actually reach the helper names the CLI calls.
if (!/require\s*\(\s*["']\.\.\/utils\/session-epoch["']\s*\)/.test(cli)) {
fail("scripts/create-user.js no longer requires the ONE shared epoch generator (utils/session-epoch.js)");
}
if (!/\{\s*[^}]*newSessionEpochDifferentFrom[^}]*\}\s*=\s*require\s*\(\s*["']\.\.\/utils\/session-epoch["']/.test(cli)) {
fail("the --update-password ≠current generator is not imported from utils/session-epoch.js");
}
const problems = [];
let csprng = false;
// verdict for an expression that produces the epoch: "csprng" (direct, via
// a traced local helper two levels deep, or via the SHARED module's
// generator), "predictable", or null (unknown)
function epochVerdict(expr, depth) {
if (/crypto\.randomInt|crypto\.randomBytes|crypto\.randomFill/.test(expr)) return "csprng";
if (/Math\.random|Date\.now/.test(expr)) return "predictable";
if (sharedHelperCallRe.test(expr)) return "csprng"; // proven by sharedEpochModuleProof above
if (depth > 0) {
const calleeRe = /\b([A-Za-z0-9_$]+)\s*\(/g;
let m;
while ((m = calleeRe.exec(expr)) !== null) {
if (/^(?:if|for|while|switch|catch|return|typeof|new)$/.test(m[1])) continue;
const fn = functionRegionByName(cli, cliStarts, m[1]);
if (fn) {
const verdict = epochVerdict(fn.body, depth - 1);
if (verdict) return verdict;
}
}
}
return null;
}
const assignRe = /(?:const|let|var)\s+([A-Za-z0-9_$]*[eE]poch[A-Za-z0-9_$]*)\s*=\s*([^;\n]+)/g;
let m;
while ((m = assignRe.exec(cli)) !== null) {
const rhs = m[2].trim();
const verdict = epochVerdict(rhs, 2);
if (verdict === "csprng") { csprng = true; continue; }
if (verdict === "predictable") { problems.push(`${at(cli, m.index)}: ${m[1]} = ${rhs.slice(0, 60)} (predictable, not a CSPRNG)`); continue; }
if (/\b[A-Za-z0-9_$]*[eE]poch[A-Za-z0-9_$]*\b/.test(rhs)) {
// Transferring/re-rolling an already-generated epoch value — unless the
// rhs invokes an epoch-named HELPER whose body shows no CSPRNG: a
// constant-producing helper must not hide behind the transfer rule
// while another site's direct crypto.randomInt sets csprng=true.
const helperCallRe = /\b([A-Za-z0-9_$]*[eE]poch[A-Za-z0-9_$]*)\s*\(/g;
let helperUnsafe = false;
let hmatch;
while ((hmatch = helperCallRe.exec(rhs)) !== null) {
const hfn = functionRegionByName(cli, cliStarts, hmatch[1]);
if (hfn && epochVerdict(hfn.body, 2) !== "csprng") { helperUnsafe = true; break; }
}
if (!helperUnsafe) continue;
problems.push(`${at(cli, m.index)}: ${m[1]} = ${rhs.slice(0, 60)} (epoch-named helper does not produce a CSPRNG value)`);
continue;
}
if (/^\d+$/.test(rhs)) { problems.push(`${at(cli, m.index)}: ${m[1]} = ${rhs} (constant)`); continue; }
problems.push(`${at(cli, m.index)}: ${m[1]} = ${rhs.slice(0, 60)} (no CSPRNG found)`);
}
// inline generation inside the SQL/params of a session_epoch statement
const seRe = /session_epoch/g;
while ((m = seRe.exec(cli)) !== null) {
const stmt = cli.slice(m.index, m.index + 500);
if (/crypto\.randomInt\s*\(/.test(stmt)) csprng = true;
}
const incRe = /\b[A-Za-z0-9_$]*[eE]poch[A-Za-z0-9_$]*\s*(?:\+\+|\+=\s*1\b|=\s*[A-Za-z0-9_$.]+\s*\+\s*1\b)/g;
const incs = [];
while ((m = incRe.exec(cli)) !== null) incs.push(`${at(cli, m.index)}: ${m[0].trim().slice(0, 60)}`);
if (incs.length) fail(`session_epoch must never be a predictable increment — ${incs.join("; ")}`);
if (problems.length) fail(`epoch generation is not CSPRNG-backed — ${problems.join("; ")}`);
if (!csprng) fail("no CSPRNG-backed epoch generation found (direct crypto.randomInt or the shared utils/session-epoch.js generator)");
// One true home: the CLI must not re-grow a local generator next to the
// shared module it now requires.
if (/function\s+newSessionEpoch\b/.test(cli)) {
fail("scripts/create-user.js re-defines a local newSessionEpoch — generation lives ONLY in utils/session-epoch.js");
}
return "epoch values come from the shared utils/session-epoch.js CSPRNG (crypto.randomInt in [1, 2147483647]); no local generator, no constant/increment epoch assignments";
});
check("B5", "no console.* call prints the session_epoch value", () => {
if (cli === null) fail(`target file not found: ${TARGETS.cli}`);
const gate = /session_epoch/i.test(cli);
if (!gate) fail(notYetImplemented(false, "scripts/create-user.js does not reference session_epoch yet; nothing to leak-check"));
const epochVars = new Set();
const avRe = /(?:const|let|var)\s+([A-Za-z0-9_$]*[eE]poch[A-Za-z0-9_$]*)\s*=/g;
let m;
while ((m = avRe.exec(cli)) !== null) epochVars.add(m[1]);
const consoleCalls = [];
const ccRe = /console\s*\.\s*(?:log|error|warn|info)\s*\(/g;
while ((m = ccRe.exec(cli)) !== null) {
const open = m.index + m[0].length - 1;
let depth = 0;
let close = -1;
for (let i = open; i < cli.length && i < open + 4000; i++) {
if (cli[i] === "(") depth++;
else if (cli[i] === ")") { depth--; if (depth === 0) { close = i; break; } }
}
consoleCalls.push({
line: lineOf(cli, m.index),
args: close === -1 ? cli.slice(open, open + 400) : cli.slice(open + 1, close),
});
}
const leaks = [];
for (const c of consoleCalls) {
if (!/epoch/i.test(c.args)) continue;
for (const v of epochVars) {
if (new RegExp(`\\b${esc(v)}\\b`).test(c.args)) { leaks.push(`line ${c.line}: console call interpolates '${v}'`); break; }
}
}
if (leaks.length) fail(`the epoch value reaches console output — ${leaks.join("; ")}`);
return `${consoleCalls.length} console.* calls scanned; epoch-named vars: ${epochVars.size ? [...epochVars].join(", ") : "none found"}; no epoch interpolation`;
});
// == E. credential writers bump in-statement (adpanel:credential-generation) ========
banner("E. credential writers bump session_epoch IN the credential's statement");
// Every interactive credential writer's exact UPDATE shape, with the epoch
// folded into the SET clause. Needles are QUOTED SQL literals and counts are
// exact, so the id-keyed shape cannot be satisfied by the CAS statements'
// longer strings (and a copy cannot drift in or out unnoticed).
const WRITER_SQL = {
panelPasswordCas: {
sql: '"UPDATE users SET password = ?, session_epoch = ? WHERE id = ? AND password = ? AND session_epoch = ?"',
expectedIn: [["credentials", 1, "the shared password-and-generation CAS used by both self-service routes"]],
},
panelEmailCas: {
sql: '"UPDATE users SET email = ?, session_epoch = ? WHERE id = ? AND password = ? AND LOWER(email) = LOWER(?) AND session_epoch = ?"',
expectedIn: [["credentials", 1, "the shared email-and-generation CAS"]],
},
panelSecretCas: {
sql: '"UPDATE users SET secret = ?, recovery_codes = ?, session_epoch = ?, totp_last_counter = GREATEST(COALESCE(totp_last_counter, 0), ?) WHERE id = ? AND secret <=> ? AND session_epoch = ?"',
expectedIn: [["credentials", 1, "the shared 2FA confirm CAS (MFA credentials, epoch and replay counter in ONE statement)"]],
},
panelAdminReset: {
sql: '"UPDATE users SET password = ?, session_epoch = ? WHERE id = ?"',
expectedIn: [["credentials", 1, "the actor-guarded admin password reset (id-keyed)"]],
},
serviceAdminMfaReset: {
sql: '"UPDATE users SET secret = NULL, recovery_codes = NULL, session_epoch = ? WHERE id = ?"',
expectedIn: [["credentials", 1, "the admin 2FA reset clear (id-keyed with atomic recovery-code revocation and epoch bump)"]],
},
cliPassword: {
sql: '"UPDATE users SET password = ?, session_epoch = ? WHERE id = ?"',
expectedIn: [["cli", 1, "the CLI --update-password write"]],
},
};
const SOURCE_BY_NAME = { panel, cli, service, credentials, actions };
check("E1", "every interactive credential writer folds session_epoch = ? into its EXISTING statement", () => {
if (sharedProof && !sharedProof.ok) fail(`the shared epoch generator is unusable — ${sharedProof.why}`);
const problems = [];
for (const [key, spec] of Object.entries(WRITER_SQL)) {
for (const [target, expected, label] of spec.expectedIn) {
const src = SOURCE_BY_NAME[target];
if (src === null) { problems.push(`${target}: file not found`); continue; }
const n = src.split(spec.sql).length - 1;
if (n !== expected) problems.push(`${label}: expected ${expected} occurrence(s) of the epoch-carrying statement in ${target}, found ${n}`);
}
for (const target of ["panel", "service"]) {
if (SOURCE_BY_NAME[target]?.includes(spec.sql)) problems.push(`${target}: duplicate credential SQL must stay in its shared owner`);
}
}
for (const [call, expected] of [["credentialCommitService.commitPassword(", 2], ["credentialCommitService.commitEmail(", 1], ["credentialCommitService.commitTwoFactor(", 1], ["resetAccountPassword(db,", 1]]) {
if (!panel || panel.split(call).length - 1 !== expected) problems.push(`panel: expected ${expected} delegation(s) through ${call}`);
}
if (!service?.includes("resetAccountTwoFactor(db, targetUser, actingAdmin)")) problems.push("admin 2FA reset: the shared actor-guarded commit is not called");
// The bump must never be its own statement anywhere.
for (const [target, src] of Object.entries(SOURCE_BY_NAME)) {
if (src === null) continue;
if (/UPDATE\s+users\s+SET\s+(`?`)?session_epoch/.test(src)) {
problems.push(`${target}: an epoch-only UPDATE exists — the bump must ride the credential's statement`);
}
}
if (problems.length) fail(`credential writers are missing their in-statement epoch bump — ${problems.join("; ")}`);
return `${Object.keys(WRITER_SQL).length} epoch-carrying writer contracts and their live delegations verified; no epoch-only UPDATE or inline credential SQL copies`;
});
check("E2", "housekeeping writes stay epoch-free; suspension atomically revokes sessions", () => {
const epochFree = [
["panel", 'db.query("UPDATE users SET password = ? WHERE id = ? AND password = ?", [upgraded, user.id, user.password])', "the login bcrypt rehash CAS (pinned byte-exact by tests/bcrypt-cost-parity.test.js)"],
["panel", '"UPDATE users SET recovery_codes = ? WHERE id = ? AND recovery_codes = ?"', "claimRecoveryCode's burn"],
["credentials", '"UPDATE users SET recovery_codes = ? WHERE id = ? AND password = ? AND session_epoch = ? AND recovery_codes <=> ?"', "the generation-pinned recovery-set replacement"],
["credentials", '"UPDATE users SET recovery_codes = ? WHERE id = ? AND admin = 0"', "the actor-guarded admin recovery reset's replacement"],
["panel", '"UPDATE users SET username = ?, username_changed_at = ? WHERE LOWER(email) = LOWER(?) AND username_changed_at <=> ?"', "the username change"],
["panel", '"UPDATE users SET avatar_url = ? WHERE LOWER(email) = LOWER(?)"', "the avatar change"],
["actions", '"UPDATE users SET agent_access = ? WHERE id = ? AND admin = 0"', "the actor-guarded agent_access write"],
["panel", '"UPDATE users SET preferences = ? WHERE id = ?"', "the preferences write"],
];
const problems = [];
for (const [target, needle, label] of epochFree) {
const src = SOURCE_BY_NAME[target];
if (src === null) { problems.push(`${target}: file not found`); continue; }
const idx = src.indexOf(needle);
if (idx === -1) { problems.push(`${label}: statement not found (${needle.slice(0, 60)}…) — the shape moved or drifted`); continue; }
const setClause = /UPDATE\s+users\s+SET\s+([\s\S]*?)\s+WHERE\b/i.exec(needle)?.[1];
if (!setClause || /session_epoch/i.test(setClause)) problems.push(`${label}: changes the epoch but must stay epoch-free`);
}
const suspension = actions ? functionRegionByName(actions, buildRegions(actions), "setAccountSuspension") : null;
if (!suspension?.body.includes("UPDATE users SET suspended = ?, suspended_at = ?, suspended_by = ?, session_epoch = ? WHERE id = ? AND admin = 0") ||
!suspension.body.includes("suspended ? newSessionEpochDifferentFrom(Number(live.session_epoch || 0)) : live.session_epoch")) {
problems.push("suspension must atomically advance the live epoch; unsuspension must preserve it");
}
if (!panel?.includes("credentialCommitService.commitRecoveryCodes(") || !panel?.includes("resetAccountRecoveryCodes(db,")) problems.push("recovery replacement routes must call their shared credential owner");
const claimUtil = readSource(path.join(ROOT, "utils", "totp-claim.js"));
if (claimUtil !== null && claimUtil.includes("session_epoch")) {
problems.push("utils/totp-claim.js (the TOTP counter claim) references session_epoch — the claim must stay epoch-free");
}
if (problems.length) fail(`non-credential writers must not bump the epoch — ${problems.join("; ")}`);
return `${epochFree.length} housekeeping statements + the TOTP claim module verified epoch-free; suspension generation revocation verified`;
});
check("E3", "provisioning and credential services use the shared epoch generator one-way", () => {
if (panel === null) fail(`target file not found: ${TARGETS.panel}`);
if (service === null) fail(`target file not found: ${TARGETS.service}`);
if (credentials === null) fail(`target file not found: ${TARGETS.credentials}`);
const problems = [];
// The INSERT carries the epoch column with the shared helper in its params.
const insNeedle = "INSERT INTO users (email, password, secret, admin, recovery_codes, avatar_url, session_epoch)";
const insIdx = credentials.indexOf(insNeedle);
if (insIdx === -1) problems.push("the panel provisioning INSERT no longer carries session_epoch in its column list");
else {
const params = credentials.slice(insIdx, insIdx + 400);
if (!params.includes("newSessionEpoch()")) problems.push("the panel provisioning INSERT mints its epoch inline (crypto.randomInt) instead of through the shared generator");
}
if (!/require\s*\(\s*["']\.\/utils\/session-epoch["']\s*\)/.test(panel)) problems.push("index.js does not require ./utils/session-epoch");
if (!/require\s*\(\s*["']\.\.\/utils\/session-epoch["']\s*\)/.test(credentials)) problems.push("services/account-credentials.js does not require ../utils/session-epoch");
if (!/require\s*\(\s*["']\.\/account-credentials["']\s*\)/.test(service)) problems.push("the admin 2FA reset service does not require its credential owner");
if (!panel.includes('require("./services/account-credentials").createCredentialCommitService({ db })') || !panel.includes("createProvisionedAccount(db,")) problems.push("the panel does not bind and call the shared credential service");
for (const [target, src] of Object.entries(SOURCE_BY_NAME)) {
if (src && /function\s+newSessionEpoch(?:DifferentFrom)?\b/.test(src)) problems.push(`${target} re-defines a local epoch generator — generation lives ONLY in utils/session-epoch.js`);
}
if (problems.length) fail(`shared-generator wiring is broken — ${problems.join("; ")}`);
return "the shared provisioning INSERT and live credential delegations mint through utils/session-epoch.js; no local generator re-grown";
});
// == C. panel sweep + endpoints (index.js) =========================================
banner("C. panel sweep + endpoints (index.js)");
check("C1", "pending-revocation sweep is scheduled via setInterval(…, 5000) with .unref()", () => {
if (panel === null) fail(`target file not found: ${TARGETS.panel}`);
if (!panelHasRevocations) fail(notYetImplemented(false, "index.js does not reference pending_session_revocations yet — no sweep exists to schedule"));
const sweepNames = [...new Set(sweepRegions.map((r) => r.name).filter(Boolean))];
const scheduled = [];
for (const c of setIntervalCalls(panel)) {
const cb = (c.args[0] || "").trim();
const refers = /pending_session_revocations/.test(cb) || sweepNames.some((n) => new RegExp(`\\b${esc(n)}\\b`).test(cb));
if (!refers) continue;
const msArg = (c.args[c.args.length - 1] || "").trim();
let ms = null;
const num = /^(\d[\d_]*)$/.exec(msArg);
if (num) ms = parseInt(num[1].replace(/_/g, ""), 10);
else if (/^[A-Za-z0-9_$]+$/.test(msArg)) {
const cm = new RegExp(`(?:const|let|var)\\s+${esc(msArg)}\\s*=\\s*(\\d[\\d_]*)`).exec(panel);
if (cm) ms = parseInt(cm[1].replace(/_/g, ""), 10);
}
const varDecl = /(?:const|let|var)\s+([A-Za-z0-9_$]+)\s*=\s*$/.exec(c.stmtHead);
const varName = varDecl ? varDecl[1] : null;
const unref = /\.unref\s*\(/.test(c.tail) ||
(varName !== null && new RegExp(`\\b${esc(varName)}\\s*\\.\\s*unref\\s*\\(`).test(panel));
scheduled.push({ ms, unref, cbHead: cb.replace(/\s+/g, " ").slice(0, 60) });
}
if (scheduled.length === 0) fail(notYetImplemented(true, "pending_session_revocations is referenced but no setInterval schedules a sweep for it"));
const chosen = scheduled.find((s) => s.ms === SWEEP_INTERVAL_MS) ||
scheduled.find((s) => s.ms !== null && Math.abs(s.ms - SWEEP_INTERVAL_MS) <= 100);
if (!chosen) {
const seen = scheduled.map((s) => (s.ms === null ? `callback ${s.cbHead}` : `${s.ms}ms`)).join(", ");
fail(`sweep scheduling found but none at ~${SWEEP_INTERVAL_MS}ms (observed: ${seen})`);
}
if (!chosen.unref) fail(`setInterval(…, ${chosen.ms}) schedules the sweep but .unref() is missing (the timer would hold the process open and keep sweeping during shutdown)`);
return `interval ${chosen.ms}ms${chosen.ms !== SWEEP_INTERVAL_MS ? ` (~${SWEEP_INTERVAL_MS}ms contract)` : ""}, unref'd, callback: ${chosen.cbHead}…`;
});
check("C2", "sweep claims atomically: DELETE … WHERE email = ? AND requested_at = ? gated on affectedRows === 1", () => {
if (panel === null) fail(`target file not found: ${TARGETS.panel}`);
const gate = panelHasRevocations;
if (claimMatches.length === 0) {
const loose = /DELETE\s+FROM\s+`?pending_session_revocations`?[\s\S]{0,300}?WHERE/i.exec(panel);
fail(notYetImplemented(gate, loose
? `a DELETE on pending_session_revocations exists (${at(panel, loose.index)}) but not the atomic claim form 'WHERE email = ? AND requested_at = ?'`
: "no claim DELETE on pending_session_revocations found in index.js"));
}
// The gate may be written directly (affectedRows === 1 → proceed) or
// inverted (affectedRows !== 1 → skip); both are the same atomic claim.
if (gatedClaimIdx === -1) {
fail(`${claimMatches.length} claim DELETE(s) on pending_session_revocations found (first at ${at(panel, claimMatches[0].index)}) but none is gated on affectedRows vs 1 (a lost race would re-run eviction for a row another worker already claimed)`);
}
const gated = claimMatches[gatedClaimIdx];
return `claim at ${at(panel, gated.index)} gated on affectedRows (=== 1 proceeds, !== 1 skips)`;
});
check("C3", "the sweep destroys browser sessions and disconnects sockets for the claimed email", () => {
if (panel === null) fail(`target file not found: ${TARGETS.panel}`);
const gate = panelHasRevocations;
if (sweepFunctionRegions.length === 0) {
fail(notYetImplemented(gate, "no pending_session_revocations sweep function identified in index.js"));
}
for (const r of sweepFunctionRegions) {
const effective = regionPlusRevocationHelpers(panel, panelStarts, r.body);
const hasDestroy = /destroyBrowserSessionsForUser\s*\(/.test(effective);
const hasSockets = /disconnectSocketsForUser\s*\(/.test(effective);
if (hasDestroy && hasSockets) return `in ${r.name || r.header}() at ${at(panel, r.start)}`;
}
fail(notYetImplemented(gate, "no pending_session_revocations-referencing function calls both destroyBrowserSessionsForUser and disconnectSocketsForUser (sweep eviction missing)"));
});
check("C4", "sweep retries with attempts+1 and gives up at 5 attempts", () => {
if (panel === null) fail(`target file not found: ${TARGETS.panel}`);
const gate = panelHasRevocations;
const sweepText = sweepFunctionRegions.map((r) => r.body).join("\n");
if (!sweepText) fail(notYetImplemented(gate, "no sweep function region identified (nothing tracks attempts)"));
if (!/\battempts\b/i.test(sweepText)) fail(notYetImplemented(gate, "the sweep does not track 'attempts' — failures are neither retried nor capped"));
const incr = /\battempts\s*(?:\+\+|\+=\s*1\b|\+\s*1\b)/i.test(sweepText) ||
/attempts\s*=\s*attempts\s*\+\s*1/i.test(sweepText);
if (!incr) fail("no attempts+1 increment found in the sweep (failed revocations are dropped, not retried)");
let cap = null;
let capWhere = null;
for (const m of sweepText.matchAll(/\battempts\b\s*(?:>=|<=|>|<|===?)\s*([A-Za-z0-9_$]+)/gi)) {
const raw = m[1];
if (/^\d+$/.test(raw)) { cap = parseInt(raw, 10); capWhere = "literal comparison"; break; }
const cm = new RegExp(`(?:const|let|var)\\s+${esc(raw)}\\s*=\\s*(\\d+)`).exec(panel);
if (cm) { cap = parseInt(cm[1], 10); capWhere = `${raw} constant`; break; }
}
if (cap === null) {
const dm = /(?:const|let|var)\s+([A-Z0-9_]*ATTEMPT[A-Z0-9_]*)\s*=\s*(\d+)/.exec(panel);
if (dm && sweepText.includes(dm[1])) { cap = parseInt(dm[2], 10); capWhere = `${dm[1]} constant`; }
}
if (cap === null) fail("attempts are incremented but no give-up cap was found");
if (cap !== GIVE_UP_ATTEMPTS) fail(`give-up cap is ${cap}, contract requires ${GIVE_UP_ATTEMPTS} (${capWhere})`);
// CRITICAL: the requeue upsert must carry the BUMPED attempt count into its
// ON DUPLICATE KEY UPDATE clause. A CLI-shaped upsert that resets
// `attempts = 0` on conflict would re-arm a fresh budget on every retry,
// making the give-up cap unreachable (the queue would retry forever).
const sweepTextPlusHelpers = sweepFunctionRegions
.map((r) => regionPlusRevocationHelpers(panel, panelStarts, r.body))
.join("\n");
const requeueRe = /INSERT\s+INTO\s+`?pending_session_revocations`?[\s\S]{0,400}?ON\s+DUPLICATE\s+KEY\s+UPDATE[^;`]{0,300}/gi;
const requeues = sweepTextPlusHelpers.match(requeueRe) || [];
if (requeues.length === 0) {
fail("the sweep never requeues a failed revocation (no INSERT … ON DUPLICATE KEY UPDATE on pending_session_revocations in the sweep) — failed revocations are dropped, not retried");
}
for (const u of requeues) {
if (!/attempts\s*=\s*VALUES\s*\(\s*`?attempts`?\s*\)/i.test(u)) {
fail(`the sweep's requeue upsert does not carry attempts = VALUES(attempts) into ON DUPLICATE KEY UPDATE — a conflict-time reset would make the give-up cap unreachable: ${u.replace(/\s+/g, " ").slice(0, 140)}…`);
}
if (/attempts\s*=\s*0\b/i.test(u)) {
fail(`the sweep's requeue upsert resets attempts to 0 on conflict — the give-up cap becomes unreachable: ${u.replace(/\s+/g, " ").slice(0, 140)}…`);
}
}
const loud = /console\.error|securityLog|logSecurity/.test(sweepText);
return `attempts+1 retry present; give-up at ${cap} (${capWhere})${loud ? "; give-up is loud" : ""}`;
});
check("C5", "DELETE /api/settings/accounts/:email clears the pending row after the delete commits", () => {
if (panel === null) fail(`target file not found: ${TARGETS.panel}`);
const gate = panelHasRevocations;
const hm = /\napp\s*\.\s*delete\s*\(\s*["'`]\/api\/settings\/accounts\/:email["'`]/.exec(panel);
if (!hm) fail("the DELETE /api/settings/accounts/:email handler was not found in index.js (route moved?)");
const r = regionAround(panel, panelStarts, hm.index + 1);
const body = panel.slice(r.start, r.end);
const outcome = /deleteOutcome|deleteUserAccountAtomically/.exec(body);
if (!outcome) fail("cannot find the atomic-delete commit anchor (deleteOutcome) in the delete endpoint");
let clearIdx = body.search(/DELETE\s+FROM\s+`?pending_session_revocations`?|pending_session_revocations/i);
let how = "direct pending_session_revocations delete";
if (clearIdx === -1) {
const callRe = /([A-Za-z0-9_$]*[Rr]evocation[A-Za-z0-9_$]*)\s*\(/g;
let cm;
while ((cm = callRe.exec(body)) !== null) {
const fn = functionRegionByName(panel, panelStarts, cm[1]);
if (fn && /pending_session_revocations/i.test(fn.body)) { clearIdx = cm.index; how = `via ${cm[1]}()`; break; }
}
}
// acceptable alternative: the clearing lives inside deleteUserAccountAtomically (same commit)
let inAtomic = false;
if (clearIdx === -1) {
const atomic = functionRegionByName(panel, panelStarts, "deleteUserAccountAtomically");
if (atomic && /pending_session_revocations/i.test(atomic.body)) { inAtomic = true; how = "inside deleteUserAccountAtomically()"; }
}
if (clearIdx === -1 && !inAtomic) {
fail(notYetImplemented(gate, "the delete endpoint never clears the pending_session_revocations row for the deleted email"));
}
if (!inAtomic && clearIdx <= outcome.index) {
fail(`pending-row clearing happens BEFORE the delete commits (${how}); a failed delete would drop a still-needed revocation`);
}
return `pending row cleared ${how}`;
});
check("C6", "POST /api/admin/user/create evicts sessions for the provisioned email after the INSERT", () => {
if (panel === null) fail(`target file not found: ${TARGETS.panel}`);
const gate = panelHasRevocations;
const hm = /\napp\s*\.\s*post\s*\(\s*["'`]\/api\/admin\/user\/create["'`]/.exec(panel);
if (!hm) fail("the POST /api/admin/user/create handler was not found in index.js (route moved?)");
const r = regionAround(panel, panelStarts, hm.index + 1);
const body = panel.slice(r.start, r.end);
const ins = /await\s+createProvisionedAccount\s*\(\s*db\s*,\s*currentAdmin\b/.exec(body);
if (!ins) fail("the create endpoint does not await its shared actor-guarded INSERT");
const successGate = body.indexOf("if (!created.ok) return res.status(409)", ins.index);
if (successGate === -1) fail("the create endpoint does not reject a refused INSERT before eviction");
const evictRe = /(destroyBrowserSessionsForUser|disconnectSocketsForUser)\s*\(/g;
let found = null;
let em;
while ((em = evictRe.exec(body)) !== null) {
if (em.index > successGate) { found = em[0].replace(/\s+\(/, "(").trim(); break; }
}
if (!found) {
// eviction may be delegated to an evict-named helper
const helperRe = /(evict[A-Za-z0-9_$]*)\s*\(/gi;
let hm2;
while ((hm2 = helperRe.exec(body)) !== null) {
if (hm2.index <= successGate) continue;
const fn = functionRegionByName(panel, panelStarts, hm2[1]);
if (fn && /destroyBrowserSessionsForUser|disconnectSocketsForUser/.test(fn.body)) { found = `${hm2[1]}() (delegated)`; break; }
}
}
if (!found) fail(notYetImplemented(gate, "the create endpoint never evicts the provisioned email's sessions after the INSERT"));
return `${found} invoked after the shared INSERT commits and its success gate (${at(panel, r.start + ins.index)})`;
});
// == D. behavioral probe (only if the claim logic is requireable) ===================
banner("D. behavioral probe (only if the claim logic is requireable in isolation)");
check("D1", "sweep claim decision logic exercised in isolation", () => {
const candidates = [];
const utilsDir = path.join(ROOT, "utils");
try {
for (const f of fs.readdirSync(utilsDir)) {
if (/\.js$/.test(f) && /revocat|pending|session.?epoch/i.test(f)) candidates.push(path.join(utilsDir, f));
}
} catch { }
for (const rel of [
"utils/pending-session-revocations.js",
"utils/session-revocation.js",
"utils/session-revocation-queue.js",
"utils/session-epoch.js",
]) {
const p = path.join(ROOT, rel);
if (!candidates.includes(p) && fs.existsSync(p)) candidates.push(p);
}
// only modules that really carry the claim logic and cannot boot the panel
const loadable = [];
for (const p of candidates) {
try {
const text = fs.readFileSync(p, "utf8");
if (!/pending_session_revocations|session_epoch/i.test(text)) continue;
if (/require\s*\(\s*["']\.\.\/index["']\s*\)/.test(text)) continue; // would boot the panel
loadable.push({ path: p, name: path.basename(p) });
} catch { }
}
if (loadable.length === 0) {
skip("the sweep's claim logic is inlined in index.js (requiring it would boot the panel) and no requireable utils module carries it — behavioral check skipped per harness contract (no panel boot, no DB, no npm install)");
}
const notes = [];
let usable = 0;
for (const mod of loadable) {
let exp;
try { exp = require(mod.path); } catch (err) {
notes.push(`${mod.name}: present but not loadable outside the panel env (${err && err.message ? err.message : err})`);
continue;
}
const fnName = Object.keys(exp || {}).find((k) => /claim|sweep|revocat|pending|epoch/i.test(k) && typeof exp[k] === "function");
if (!fnName) {
notes.push(`${mod.name}: loaded, exports [${Object.keys(exp || {}).join(", ")}] — no claim function recognized`);
continue;
}
usable += 1;
notes.push(`${mod.name}: loaded and exposes ${fnName}()`);
}
if (usable === 0) warn(`claim module(s) found but none usable in isolation — ${notes.join("; ")}`);
return notes.join("; ");
});
// ---- summary ----------------------------------------------------------------------
const counts = { PASS: 0, FAIL: 0, WARN: 0, SKIP: 0 };
for (const r of results) counts[r.status] += 1;
console.log(`\n${"-".repeat(72)}`);
console.log(`${counts.PASS} checks passed, ${counts.FAIL} failed, ${counts.WARN} warned, ${counts.SKIP} skipped`);
if (counts.FAIL > 0) {
console.log("user-lifecycle session-revocation verification: FAILED");
process.exit(1);
}
console.log("user-lifecycle session-revocation verification: OK");
process.exit(0);