Files
Kelx/tests/pre-gate-mount-census.test.js
T
2026-11-30 16:32:37 +00:00

529 lines
30 KiB
JavaScript

"use strict";
// adpanel:preauth-gate-mount-census — census pins for everything registered
// BEFORE the generic pre-auth gate (the app.use middleware carrying the
// adpanel:preauth-gate-case-fold comment in index.js).
//
// The auth model: the generic gate is a FALLBACK, not the primary guard.
// Routers/routes that must serve unauthenticated callers are mounted BEFORE
// it (Express dispatches in source order, so the gate never sees them) and
// must carry their own auth internally; everything the gate does see is
// redirected/401'd unless an exemption matches. The hazard this census
// closes: nothing previously tested the pattern, so a future router mounted
// before the gate that forgets its internal auth would be silently anonymous
// (the gate never runs for it).
//
// Pinned here:
// 1. The full pre-gate registration census — every app.<verb> call site in
// index.js before the gate block, classified as:
// (a) router carrying its OWN auth (dashboard-assistant: injected
// deps.isAuthenticated/deps.isAdmin checkers; db-access proxy:
// internally scoped to /db-access/ with per-request live session
// re-validation) — the nodes router itself is mounted AFTER the
// gate (pinned) behind the /api/nodes admin gate + its own
// node-token HMAC gates;
// (b) deliberately-pre-auth route (stealth bootstrap/nginx-auth,
// branding/auth-assets/favicon assets, POST /api/captcha/verify,
// /healthz + /healtz, the static-serving middleware);
// (c) pass-through guard/limiter middleware (helmet, session stack,
// sameOriginProtection, cross-site read gate, rate limiters,
// parsers, the maintenance/suspension/stealth gates).
// The counts must match exactly: ANY new pre-gate registration — route,
// router mount, or middleware — fails CI with instructions to either
// give it internal auth and extend this census consciously, or keep it
// behind the gate.
// 2. Mechanism evidence for every entry that responds pre-gate (category a
// and b): the router's injected checkers, the proxy's session
// re-validation, each asset route's limiter, the stealth endpoints'
// token/state validation, the captcha limiter, the static allowlist +
// isAuthenticated branch.
// 3. Mount-order reliance vs gate-exemption reliance: entries that serve
// pre-gate callers ONLY because they are mounted first (stealth
// endpoints, dashboard-assistant, captcha/verify) must have NO matching
// exemption in the gate (the gate would 401/redirect them if the order
// regressed), while entries with a redundant ordering guarantee must
// have their exemption present.
// 4. The gate's exemption list is pinned EXACTLY (every startsWith prefix
// and every === path asserted, nothing else). WARNING documented here on
// purpose: the prefix exemptions keep startsWith semantics (the ledger
// decision in preauth-gate-case-fold — "startsWith stays startsWith",
// sub-path spellings under the auth-page prefixes stay exempt
// deliberately), so a future sibling path such as /login-2fa-verify IS
// silently exempt today. The exemption is inert (no route serves that
// path — the mount-set pin in preauth-gate-case-fold.test.js fails if
// one is added), but any NEW route under /login, /register,
// /forgot-password must mount pre-gate with its own auth and update that
// pin + this census consciously. The static/db-access/branding prefixes
// genuinely cover multi-segment surfaces (static directory trees, the
// /db-access/<service>/... proxy paths) and CANNOT become exact-match
// without breaking real routes — assessed 2026-11, pin-only hardening.
//
// Technique: index.js is read as text; registrations are extracted from the
// comment-stripped pre-gate slice (everything before the gate's app.use
// statement, located via the adpanel:preauth-gate-case-fold marker); the
// gate block itself is sliced brace-balanced and evaluated in a vm sandbox
// for the behavioral exemption pins — same window/marker techniques as
// tests/preauth-gate-case-fold.test.js and tests/force-https-coverage.test.js.
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 GATE_MARKER = "// adpanel:preauth-gate-case-fold —";
const GATE_REG_START = "app.use(";
function indexOfOrThrow(needle, from = 0) {
const idx = indexSource.indexOf(needle, from);
assert.ok(idx >= 0, `expected source pin not found: ${needle}`);
return idx;
}
// The generic pre-auth gate's app.use statement start (source position).
const gateMarkerIdx = indexOfOrThrow(GATE_MARKER);
const gateStart = indexSource.lastIndexOf(GATE_REG_START, gateMarkerIdx);
assert.ok(gateStart > 0, "gate app.use( statement not found before its marker");
// Everything registered before the gate statement, comment lines stripped so
// prose that mentions app.use(...) (e.g. the nodesRouter mount discussed in
// comments) cannot pollute the census.
const preGateSource = indexSource
.slice(0, gateStart)
.split("\n")
.filter((line) => !/^\s*(\/\/|\*|\/\*)/.test(line))
.join("\n");
// Extract every registration's first argument classification:
// { kind: "path", verb, paths: [...] } — string or array-of-strings path
// { kind: "named", verb, token } — identifier middleware factory
// { kind: "anonymous", verb } — inline (req, ...) middleware
function extractRegistrations(source) {
const out = [];
const re = /\bapp\.(use|get|post|put|delete|all|patch)\s*\(/g;
let m;
while ((m = re.exec(source)) !== null) {
const verb = m[1];
let i = m.index + m[0].length;
while (i < source.length && /\s/.test(source[i])) i += 1;
const ch = source[i];
if (ch === '"' || ch === "'") {
const endQ = source.indexOf(ch, i + 1);
assert.ok(endQ > i, `unterminated path literal near offset ${i}`);
out.push({ kind: "path", verb, paths: [source.slice(i + 1, endQ)] });
} else if (ch === "[") {
const endB = source.indexOf("]", i);
assert.ok(endB > i, `unterminated path array near offset ${i}`);
const paths = [...source.slice(i + 1, endB).matchAll(/"([^"]+)"/g)].map((x) => x[1]);
assert.ok(paths.length >= 1, `path array with no string entries near offset ${i}`);
out.push({ kind: "path", verb, paths });
} else if (ch === "(" || source.startsWith("async (", i) || source.startsWith("async(", i)) {
out.push({ kind: "anonymous", verb, token: "(req..." });
} else {
const tokenMatch = /^[\w$.]+/.exec(source.slice(i));
assert.ok(tokenMatch, `unclassified first argument near offset ${i}: ${source.slice(i, i + 40)}`);
out.push({ kind: "named", verb, token: tokenMatch[0] });
}
}
return out;
}
const registrations = extractRegistrations(preGateSource);
// ---------------------------------------------------------------------------
// Census 1: path-bearing mounts and routes, in source order
// ---------------------------------------------------------------------------
const EXPECTED_PATH_CENSUS = [
{ verb: "use", path: "/api/", tag: "guard", note: "conditional redis-backed globalLimiter (pass-through or 429)" },
{ verb: "get", path: "/_stealth/authorize", tag: "preauth-route", note: "stealth bootstrap: state+safeCompare validated, issues/clears the stealth gate cookie" },
{ verb: "all", path: "/_stealth/nginx-auth", tag: "preauth-route", note: "stealth auth_request upstream: hasStealthAccess (stealth cookie or live session) → 204/401" },
{ verb: "get", path: "/branding-media/:kind", tag: "preauth-route", note: "branding asset, brandingAssetRateLimiter" },
{ verb: "get", path: "/auth-assets/logo", tag: "preauth-route", note: "auth-page asset, brandingAssetRateLimiter" },
{ verb: "get", path: "/auth-assets/christmas-logo", tag: "preauth-route", note: "auth-page asset, brandingAssetRateLimiter" },
{ verb: "get", path: "/auth-assets/background", tag: "preauth-route", note: "auth-page asset, brandingAssetRateLimiter" },
{ verb: "get", path: "/auth-assets/favicon", tag: "preauth-route", note: "auth-page asset, brandingAssetRateLimiter" },
{ verb: "get", path: "/favicon.ico", tag: "preauth-route", note: "pre-auth favicon, brandingAssetRateLimiter" },
{ verb: "use", path: "/api", tag: "guard", note: "crossSiteReadGuard API read gate (pass-through or 403)" },
{ verb: "use", path: "/api/dashboard-assistant", tag: "own-auth-router", note: "dashboard-assistant router: requireAuth/requireAssistantAccess/requireAssistantAdmin on injected deps.isAuthenticated/deps.isAdmin" },
{ verb: "post", path: "/api/captcha/verify", tag: "preauth-route", note: "deliberate pre-auth captcha endpoint, captchaVerifyRateLimiter" },
{ verb: "get", path: "/healthz", tag: "preauth-route", note: "health endpoint, static ok:true body (no operational detail)" },
{ verb: "get", path: "/healtz", tag: "preauth-route", note: "documented stealth decoy twin of /healthz" }
];
test("census: every pre-gate path-bearing mount/route matches the known list in order", () => {
const pathEntries = [];
for (const reg of registrations) {
if (reg.kind !== "path") continue;
for (const p of reg.paths) pathEntries.push({ verb: reg.verb, path: p });
}
assert.equal(
pathEntries.length,
EXPECTED_PATH_CENSUS.length,
`pre-gate path census drift: got ${JSON.stringify(pathEntries.map((e) => `${e.verb} ${e.path}`))}` +
"\nA new mount/route was added BEFORE the generic pre-auth gate. It must either carry its own auth" +
"\ninternally (routers: inject the admin/session checkers like routes/dashboard-assistant.js) or be a" +
"\nconsciously-reviewed pre-auth route — then extend EXPECTED_PATH_CENSUS here with its protection" +
"\nmechanism. If it needs no pre-gate access, move it BELOW the gate so the gate guards it."
);
pathEntries.forEach((entry, i) => {
assert.equal(entry.verb, EXPECTED_PATH_CENSUS[i].verb, `census verb mismatch at #${i}`);
assert.equal(entry.path, EXPECTED_PATH_CENSUS[i].path, `census path mismatch at #${i}`);
});
});
// ---------------------------------------------------------------------------
// Census 2: named middleware factories (identifier first argument)
// ---------------------------------------------------------------------------
const EXPECTED_NAMED_MIDDLEWARE = [
{ verb: "use", token: "helmet", note: "global CSP/security headers" },
{ verb: "use", token: "cookieParser", note: "cookie parsing" },
{ verb: "use", token: "sessionMiddleware", note: "session store" },
{ verb: "use", token: "createRemoteProxyTrustGate", note: "remote-proxy trust gate" },
{ verb: "use", token: "createPreauthSessionTtlMiddleware", note: "anonymous short-TTL sessions" },
{ verb: "use", token: "dbProxy.createProxyMiddleware", note: "db-access proxy: internally scoped to /db-access/ (DB_ACCESS_PREFIX in utils/db-proxy.js), per-request live session re-validation (sessionMatchesToken) — category (a) own auth" },
{ verb: "use", token: "createAgentFeatureGate", note: "returns Agent OFF before body parsing on Agent-only URLs" },
{ verb: "use", token: "hpp", note: "HTTP parameter pollution guard" },
{ verb: "use", token: "createResponseCompression", note: "conditional response compression; owns disconnect cleanup and backpressure" },
{ verb: "use", token: "sameOriginProtection", note: "same-origin guard" },
{ verb: "use", token: "rateLimiterMiddleware", note: "global in-memory rate limiter" }
];
test("census: named middleware factories match the known list in order", () => {
const named = registrations.filter((r) => r.kind === "named");
assert.equal(
named.length,
EXPECTED_NAMED_MIDDLEWARE.length,
`pre-gate named-middleware census drift: got ${JSON.stringify(named.map((r) => `${r.verb} ${r.token}`))}` +
"\nA new middleware factory was registered BEFORE the generic pre-auth gate. It runs for every request," +
"\npre-auth included — extend EXPECTED_NAMED_MIDDLEWARE here consciously with what it does."
);
named.forEach((entry, i) => {
assert.equal(entry.verb, EXPECTED_NAMED_MIDDLEWARE[i].verb);
assert.equal(entry.token, EXPECTED_NAMED_MIDDLEWARE[i].token, `named middleware mismatch at #${i}`);
});
});
// ---------------------------------------------------------------------------
// Census 3: anonymous inline middleware — count pin (any new one breaks CI)
// ---------------------------------------------------------------------------
test("census: anonymous inline middleware count is stable (any new pre-gate app.use fails here)", () => {
const anonymous = registrations.filter((r) => r.kind === "anonymous");
assert.equal(
anonymous.length,
29,
`pre-gate anonymous-middleware count drift: ${anonymous.length} (expected 29)` +
"\nA new inline app.use((req,...)) middleware was registered BEFORE the generic pre-auth gate." +
"\nIt runs for every pre-auth request and may answer responses. Update this count consciously and" +
"\nconfirm the middleware either passes through (guard/limiter/parser) or is an intended pre-auth" +
"\nresponder covered by the exemption census below."
);
// Grand total: 14 path entries (13 registrations, /healthz+healtz share one)
// + 11 named + 29 anonymous = 53 app.<verb>( call sites before the gate.
assert.equal(
registrations.length,
53,
"total pre-gate registration count drift — recompute the census split (paths/named/anonymous)"
);
});
// ---------------------------------------------------------------------------
// Mechanism evidence: every responding pre-gate entry proves its protection
// ---------------------------------------------------------------------------
test("mechanism: dashboard-assistant router carries its own injected auth checkers", () => {
const mountIdx = indexOfOrThrow('app.use("/api/dashboard-assistant", createDashboardAssistantRouter({');
const depsRegion = indexSource.slice(mountIdx, indexOfOrThrow("recordActivity,", mountIdx));
assert.ok(depsRegion.includes("isAuthenticated,"), "the router mount must inject isAuthenticated");
assert.ok(depsRegion.includes("isAdmin,"), "the router mount must inject isAdmin");
const routerSource = fs.readFileSync(path.join(ROOT, "routes", "dashboard-assistant.js"), "utf8");
for (const marker of [
"if (!(await deps.isAuthenticated(req))) {",
"if (await deps.isAdmin(req)) return true;",
"if (!(await deps.isAdmin(req))) {"
]) {
assert.ok(routerSource.includes(marker), `dashboard-assistant router internal auth marker missing: ${marker}`);
}
// Every route in the router file must pass through one of the three checkers.
const checkerUses = (routerSource.match(/requireAuth|requireAssistantAccess|requireAssistantAdmin/g) || []).length;
assert.ok(checkerUses >= 6, "the router's auth checkers must be referenced per route");
});
test("mechanism: db-access proxy is internally scoped and re-validates the live session per request", () => {
const proxySource = fs.readFileSync(path.join(ROOT, "utils", "db-proxy.js"), "utf8");
assert.ok(proxySource.includes('const DB_ACCESS_PREFIX = "/db-access/";'), "db-proxy must scope itself to /db-access/");
const uses = (proxySource.match(/sessionMatchesToken/g) || []).length;
assert.ok(uses >= 3, "db-proxy must re-validate the token's session on requests (sessionMatchesToken)");
// The mount is pre-gate by design (streams before body parsers).
const mountIdx = indexOfOrThrow("app.use(dbProxy.createProxyMiddleware({");
assert.ok(mountIdx < gateStart, "db-access proxy must stay mounted before the gate (pre-body-parser streaming)");
});
test("mechanism: asset routes carry their rate limiter; stealth endpoints carry their validation", () => {
for (const marker of [
'app.get("/branding-media/:kind", brandingAssetRateLimiter,',
'app.get("/auth-assets/logo", brandingAssetRateLimiter,',
'app.get("/auth-assets/christmas-logo", brandingAssetRateLimiter,',
'app.get("/auth-assets/background", brandingAssetRateLimiter,',
'app.get("/auth-assets/favicon", brandingAssetRateLimiter,',
'app.get("/favicon.ico", brandingAssetRateLimiter,',
'app.post("/api/captcha/verify", captchaVerifyRateLimiter,'
]) {
indexOfOrThrow(marker);
}
const authorizeIdx = indexOfOrThrow('app.get("/_stealth/authorize", (req, res) => {');
const authorizeRegion = indexSource.slice(authorizeIdx, indexOfOrThrow("app.all(\"/_stealth/nginx-auth\"", authorizeIdx));
assert.ok(authorizeRegion.includes("getStealthBootstrapState"), "stealth authorize must validate the bootstrap state");
assert.ok(authorizeRegion.includes("safeCompare"), "stealth authorize must compare the state id with safeCompare");
const nginxAuthIdx = indexOfOrThrow('app.all("/_stealth/nginx-auth", async (req, res) => {');
const nginxAuthRegion = indexSource.slice(nginxAuthIdx, nginxAuthIdx + 1500);
assert.ok(nginxAuthRegion.includes("hasStealthAccess"), "nginx-auth must gate on hasStealthAccess (stealth cookie or live session)");
});
test("mechanism: /healthz + /healtz answer a static ok body with no session or user work", () => {
const start = indexOfOrThrow('app.get(["/healthz", "/healtz"], (req, res) => {');
const end = indexSource.indexOf(GATE_MARKER, start);
const body = indexSource.slice(start, end);
assert.ok(body.includes("ok: true"), "health handler must answer ok:true");
assert.ok(!body.includes("findUserByEmail"), "health handler must not touch user lookups");
assert.ok(!body.includes("isAuthenticated"), "health handler must not run session work");
});
test("mechanism: the static-serving middleware gates pre-auth serving on the extension allowlist", () => {
const start = indexOfOrThrow("const PRE_AUTH_STATIC_PREFIXES = [");
const end = indexOfOrThrow("const STATUS_CACHE_TTL_MS =", start);
const region = indexSource.slice(start, end);
assert.ok(region.includes("PRE_AUTH_UPLOADS_EXT.test(p)"), "pre-auth /uploads/ serving must stay on the narrow image allowlist");
assert.ok(region.includes("PRE_AUTH_STATIC_EXT.test(p)"), "pre-auth static serving must stay on the extension allowlist");
assert.ok(region.includes("if (await isAuthenticated(req)) return servePublicStatic(req, res, next);"), "full public/ serving must require an authenticated session");
});
test("mechanism: the /api/ global limiter mount is conditional and unique", () => {
// adpanel:rate-limit-policy-owner — the mount goes through the policy
// OWNER's swap-safe middleware wrapper (services/global-rate-limit-owner.js
// constructs/rebuilds the underlying express-rate-limit instance per
// generation); the census pin consciously tracks the new mount shape while
// preserving its intent: exactly ONE /api/ limiter mount, and the
// redisApiLimiterMounted marker stays truthful (false → the in-memory
// fallback owns /api/*; true → the owner does).
assert.equal(indexSource.split('app.use("/api/", globalRateLimitOwner.middleware);').length - 1, 1, "exactly one /api/ limiter mount (through the owner's middleware wrapper)");
assert.equal(indexSource.split('app.use("/api/", globalLimiter);').length - 1, 0, "no parallel globalLimiter mount may return");
indexOfOrThrow("redisApiLimiterMounted = true;");
});
// ---------------------------------------------------------------------------
// Census 4: mount-order reliance vs gate-exemption reliance
// ---------------------------------------------------------------------------
test("ordering: pre-gate responders sit before the gate; order-reliant ones have NO gate exemption", () => {
for (const marker of [
'app.get("/_stealth/authorize"',
'app.all("/_stealth/nginx-auth"',
'app.get("/branding-media/:kind"',
'app.get("/auth-assets/logo"',
'app.get("/favicon.ico"',
'app.use("/api/dashboard-assistant"',
'app.post("/api/captcha/verify"',
'app.get(["/healthz", "/healtz"]'
]) {
assert.ok(indexOfOrThrow(marker) < gateStart, `${marker} must stay registered before the generic gate`);
}
// Entries that serve pre-gate callers purely by mount order must NOT be
// exempted (the exemption would mask an ordering regression by letting the
// gate wave them through to post-gate handlers that may not exist yet).
const gateBlock = extractGateBlock(indexSource);
const orderReliant = ["/_stealth/", "/api/captcha/verify", "/api/dashboard-assistant"];
for (const p of orderReliant) {
assert.ok(!gateBlock.includes(`"${p}"`), `order-reliant pre-gate surface must not gain a gate exemption: ${p}`);
}
// Entries with a redundant ordering guarantee keep their exemption entry.
for (const exemption of ["/db-access/", "/branding-media/", "/auth-assets/", "/favicon.ico", "/healthz", "/healtz"]) {
assert.ok(gateBlock.includes(exemption), `gate must keep the ordering-guarantee exemption for ${exemption}`);
}
// The nodes router is the post-gate model: mounted AFTER the gate, guarded
// by the /api/nodes admin gate plus its own node-token HMAC checks.
const nodesMountIdx = indexOfOrThrow("app.use(nodesRouter);");
assert.ok(nodesMountIdx > gateStart, "app.use(nodesRouter) must stay mounted AFTER the generic gate");
});
// ---------------------------------------------------------------------------
// Census 5: the gate's exemption list pinned EXACTLY (pin-only hardening)
// ---------------------------------------------------------------------------
// adpanel:preauth-gate-mount-census — exemption-hardening assessment (2026-11,
// this campaign): an exact-match switch was considered and REJECTED as not
// provably safe. Of the eleven prefix exemptions, the three auth-page
// prefixes (/login, /register, /forgot-password) each cover exactly one route
// path, but /db-access/ and the five static prefixes cover genuinely
// multi-segment surfaces (the proxy's /db-access/<service>/... paths, static
// directory trees), /auth-assets/ covers four routes, and /branding-media/
// covers a parametric route — the task's all-prefixes condition for switching
// fails. The SOLVED preauth-gate-case-fold ledger also pins the shape
// deliberately ("startsWith stays startsWith", sub-path spellings stay
// exempt). So the semantics are retained and pinned here instead: the list is
// asserted exact, and the sibling-path hazard is documented behaviorally.
// WARNING FOR OPERATORS: prefix semantics silently exempt future sibling
// paths — /login-2fa-verify, /register-totp, /forgot-password-done and
// friends pass the gate unauthenticated TODAY. The exemption is inert (no
// handler serves them; preauth-gate-case-fold.test.js's mount-set pin fails
// if a route under those prefixes is added), but a new route there must
// mount pre-gate with its own auth and update both pins consciously.
const EXPECTED_FOLDED_PREFIXES = ["/login", "/register", "/forgot-password"];
const EXPECTED_RAW_PREFIXES = ["/db-access/", "/images/", "/css/", "/js/", "/vendor/", "/uploads/", "/auth-assets/", "/branding-media/"];
const EXPECTED_EXACT_PATHS = ["/favicon.ico", "/healthz", "/healtz", "/api/me", "/api/maintenance/status"];
// Same brace-balanced extraction as tests/preauth-gate-case-fold.test.js.
function extractGateBlock(source) {
const markerIdx = source.indexOf(GATE_MARKER);
assert.ok(markerIdx >= 0, "gate marker not found");
const start = source.lastIndexOf(GATE_REG_START, markerIdx);
assert.ok(start >= 0, "gate app.use( not found");
const bodyStart = source.indexOf("{", start);
let depth = 0;
let i = bodyStart;
for (; i < source.length; i += 1) {
if (source[i] === "{") depth += 1;
else if (source[i] === "}") {
depth -= 1;
if (depth === 0) { i += 1; break; }
}
}
assert.ok(depth === 0, "unbalanced braces in gate block");
while (i < source.length && (source[i] === ")" || source[i] === ";" || /\s/.test(source[i]))) {
i += 1;
if (source[i - 1] === ")") break;
}
return source.slice(start, i);
}
function loadGate() {
const block = extractGateBlock(indexSource);
let captured = null;
const sandbox = {
app: { use: (mw) => { captured = mw; } },
isOpenNodeRoute: async (req) => req._openRoute === true,
isAuthenticated: async (req) => req._authed === true
};
vm.createContext(sandbox);
vm.runInContext(block, sandbox);
assert.ok(captured, "preauth gate middleware was not registered");
return captured;
}
function makeRes() {
return {
statusCode: 0,
body: null,
redirectedTo: null,
headers: {},
status(c) { this.statusCode = c; return this; },
json(b) { this.body = b; return this; },
redirect(target) { this.redirectedTo = target; return this; },
setHeader(name, value) { this.headers[String(name).toLowerCase()] = value; }
};
}
async function runGate(gate, req) {
const res = makeRes();
let nexted = false;
await Promise.resolve(gate(req, res, () => { nexted = true; }));
return { res, nexted };
}
test("exemption list: folded prefix entries are exactly the three auth-page prefixes", () => {
const block = extractGateBlock(indexSource);
const code = block.split("\n").filter((l) => !l.trim().startsWith("//")).join("\n");
const found = [...code.matchAll(/pLowerPath\.startsWith\("([^"]+)"\)/g)].map((m) => m[1]);
assert.deepEqual(found.sort(), [...EXPECTED_FOLDED_PREFIXES].sort(),
"the folded prefix exemption set drifted — a new prefix exemption must be added to this census consciously");
for (const p of EXPECTED_FOLDED_PREFIXES) {
assert.equal(code.split(`pLowerPath.startsWith("${p}")`).length - 1, 1, `folded prefix exemption must appear exactly once: ${p}`);
}
});
test("exemption list: raw-path prefix entries are exactly the static/proxy/asset prefixes", () => {
const block = extractGateBlock(indexSource);
const found = [...block.matchAll(/req\.path\.startsWith\("([^"]+)"\)/g)].map((m) => m[1]);
assert.deepEqual(found.sort(), [...EXPECTED_RAW_PREFIXES].sort(),
"the raw-path prefix exemption set drifted — a new prefix exemption must be added to this census consciously");
for (const p of EXPECTED_RAW_PREFIXES) {
assert.equal(block.split(`req.path.startsWith("${p}")`).length - 1, 1, `raw prefix exemption must appear exactly once: ${p}`);
}
});
test("exemption list: exact entries are exactly the five pExact paths", () => {
const block = extractGateBlock(indexSource);
const code = block.split("\n").filter((l) => !l.trim().startsWith("//")).join("\n");
const found = [...code.matchAll(/pExact === "([^"]+)"/g)].map((m) => m[1]);
assert.deepEqual(found.sort(), [...EXPECTED_EXACT_PATHS].sort(),
"the exact exemption set drifted — a new exact exemption must be added to this census consciously");
// The only dynamic exemption stays isOpenNodeRoute; no other call-shaped
// exemption may appear in the exemption condition.
assert.ok(block.includes("await isOpenNodeRoute(req)"), "the isOpenNodeRoute dynamic exemption must remain");
});
test("exemption behavior: known-good paths are exempt; sibling paths stay exempt under retained prefix semantics (inert today)", async () => {
const gate = loadGate();
// Known-good: the surfaces each exemption was written for.
const knownGood = [
"/login", "/login/", "/register", "/forgot-password",
"/db-access/mysql/", "/images/ADPanel.webp", "/css/bot.css", "/js/bot.js",
"/vendor/monaco-editor/0.55.1/x.js", "/uploads/avatar.png",
"/auth-assets/logo", "/branding-media/login-background",
"/favicon.ico", "/healthz", "/healtz", "/api/me", "/api/maintenance/status"
];
for (const p of knownGood) {
const out = await runGate(gate, { path: p, method: "GET" });
assert.equal(out.nexted, true, `${p} must stay exempt`);
}
// Sibling-path hazard, pinned consciously: prefix semantics are retained
// (see the ledger decision in preauth-gate-case-fold), so these would-be
// future siblings ARE exempt. The exemption is inert — no route serves
// them (the mount-set pin in preauth-gate-case-fold.test.js fails if one
// is registered) — but a future route under these prefixes must mount
// pre-gate with its own auth and update both pins consciously.
const siblings = ["/login-2fa-verify", "/register-totp", "/forgot-password-done"];
for (const p of siblings) {
const out = await runGate(gate, { path: p, method: "GET" });
assert.equal(out.nexted, true, `${p} is exempt under retained prefix semantics (inert today — no route serves it); flipping this pin requires the exact-match assessment to be redone consciously`);
}
// Nothing outside the prefixes absorbs them (the exemption is a prefix of
// the auth pages, not of arbitrary content): near-miss spellings that do
// NOT start with the prefix strings stay gated.
for (const p of ["/logi", "/registr", "/forgot-passwor", "/ogin-2fa-verify"]) {
const out = await runGate(gate, { path: p, method: "GET" });
assert.equal(out.nexted, false, `${p} must not be exempt`);
if (p.toLowerCase().startsWith("/api/")) {
assert.equal(out.res.statusCode, 401);
} else {
assert.equal(out.res.redirectedTo, "/login");
}
}
// Order-reliant pre-gate surfaces get NO exemption: an unauthenticated
// request that somehow reaches the gate is refused (proving they serve
// pre-gate callers purely by mount position).
for (const p of ["/_stealth/authorize", "/_stealth/nginx-auth", "/api/captcha/verify", "/api/dashboard-assistant/bootstrap"]) {
const out = await runGate(gate, { path: p, method: "POST" });
assert.equal(out.nexted, false, `${p} must not be gate-exempt (order-reliant surface)`);
if (p.toLowerCase().startsWith("/api/")) {
assert.equal(out.res.statusCode, 401, `${p} falls into the gate's API-format 401`);
} else {
assert.equal(out.res.redirectedTo, "/login", `${p} falls into the gate's unauthenticated redirect`);
}
}
});