Files
Kelx/tests/stealth-classification-normalize.test.js
T
2026-11-30 16:32:37 +00:00

691 lines
35 KiB
JavaScript

"use strict";
// adpanel:stealth-asset-normalized-match / adpanel:stealth-login-trailing-slash
// — behavior + source pins for the two stealth classification-vs-serving
// divergences the gate's helpers had against the installed express 4.22.2 /
// send 0.19.0 stack:
//
// F1 (assets): send 0.19.0 normalizes the DECODED path AFTER decoding —
// exactly normalize('.' + sep + path) with sep '/', at
// node_modules/send/index.js SendStream.prototype.pipe — while the gate
// classified the decoded-but-NOT-normalized spelling. Duplicate-slash and
// dot-segment spellings therefore normalize onto covered paths and were
// served to pre-gate probes while the raw spelling missed the exact-match
// set: /js//cdn-fallback.js, //login.css, /js/./cdn-fallback.js,
// /js/%2e/cdn-fallback.js, /js/%2e%2e/images/adpanel-dark.webp and
// /%2Fjs/cdn-fallback.js all reached the real file (200) through the
// gate → express.static chain. The helper now composes send's very
// expression. It deliberately does NOT use path.posix.normalize(decoded)
// alone: posix.normalize clamps '..' at root while send's './'-anchored
// form keeps a leading '..' (normalize('/../favicon.ico') is
// '/favicon.ico' but send computes '../favicon.ico' and 403s it via
// UP_PATH_REGEXP before joining root) — clamping alone would classify
// root-escaping spellings that clamp back onto a covered path as
// PROTECTED and turn the decoy 404 into an oracle beside send's
// swallowed-403 fallthrough (express.static fallthrough surfaces the 403
// as a plain downstream 404 — no content either way).
//
// F2 (login): express mounts routes with strict:false, which makes exactly
// ONE trailing '/' optional — GET /login/ reaches the real /login route
// while GET /login// does not (pinned behaviorally below against the
// installed express). The exact-string set missed the one-slash spelling,
// so the trailing slash bypassed the stealth bootstrap. The helper strips
// exactly one trailing '/' — not all of them, or /login// would classify
// protected while the router 404s it.
//
// F3 (login): express matches routes CASE-INSENSITIVELY (caseSensitive:
// false is the default) — /LOGIN, /Login and /LOGIN/ reach the real /login
// route exactly like /login (pinned behaviorally below against the
// installed express 4.22.2), while the exact-string set only held the
// lowercase spellings, so a case-variant spelling bypassed the stealth
// bootstrap. The helper folds case AFTER the one-slash strip; the set
// entries are lowercase and none ends in '/', so strip-then-fold is exactly
// router-equivalent. No case-variant route of the three stealth paths is
// defined anywhere (pinned below against index.js + routes/*.js), so
// folding cannot over-match a different route.
//
// 2026-11-13 (adpanel:stealth-asset-spelling-parity): the asset helper's
// old no-fold posture is consciously REVERSED. The original rationale
// ("express.static serving is filesystem case-sensitive on Linux, so
// classification(UNPROTECTED) and serving(404) already agree") held only
// for STATIC files — but the covered surface also includes ROUTE-BACKED
// assets (/branding-media/:kind, the /auth-assets/* branding routes),
// which the router serves case-insensitively with REAL operator-config-
// derived bytes: /BRANDING-MEDIA/logo and /AUTH-ASSETS/logo reached their
// remote assets pre-gate while the canonical spellings decoyed. The asset
// helper now case-folds too (and strips the one strict:false-optional
// trailing slash, and covers single-segment allowlisted-extension root
// files via the shared PRE_AUTH_STATIC_EXT): for static files the fs
// lookup stays case-sensitive, so a case-variant spelling was already an
// ENOENT 404 and the fold only makes that 404 uniform — the fold can only
// WIDEN decoy coverage, never narrow legit serving (gated callers pass the
// gate before any decoy; every view references canonical spellings).
//
// The sets themselves, the gate's branch structure and the serving stack are
// untouched: only the helpers' matching changed, so classification
// mirrors the serving/matching stage's exact normalize/slash/case semantics.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const http = require("node:http");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
function indexOfOrThrow(needle, from = 0) {
const idx = indexSource.indexOf(needle, from);
assert.ok(idx >= 0, `expected source pin not found: ${needle}`);
return idx;
}
// Extraction pattern (same technique as stealth-asset-decoded-match.test.js):
// stitch the set(s), the helper(s), and safeDecodePath into one evaluatable
// scope. index.js binds require("path") at module top (the asset helper
// composes send's normalize); new Function bodies see no module scope, so the
// same module object is handed in as a parameter — the identical binding.
function loadAssetClassifier() {
const setStart = indexOfOrThrow("const STEALTH_ASSET_PATHS = new Set([");
const setEnd = indexSource.indexOf("]);", setStart);
const fnStart = indexOfOrThrow("function isStealthProtectedAssetPath(");
const fnEnd = indexOfOrThrow("function isStealthProtectedLoginPath(", fnStart);
const decodeStart = indexOfOrThrow("function safeDecodePath(p)");
const decodeEnd = indexOfOrThrow("function servePublicStatic(", decodeStart);
assert.ok(setEnd > setStart && fnEnd > fnStart && decodeEnd > decodeStart, "slices must be bounded");
// The prefix-cover leg (adpanel:stealth-prefix-cover) and the root-level
// leg (adpanel:stealth-asset-spelling-parity) reference the shared
// PRE_AUTH_STATIC_PREFIXES / PRE_AUTH_STATIC_EXT consts — defined later in
// index.js, evaluated at request time. The stitched scope must carry the
// same bindings.
const prefixStart = indexOfOrThrow("const PRE_AUTH_STATIC_PREFIXES = [");
const prefixEnd = indexSource.indexOf("];", prefixStart);
assert.ok(prefixEnd > prefixStart, "PRE_AUTH_STATIC_PREFIXES slice must be bounded");
const extStart = indexOfOrThrow("const PRE_AUTH_STATIC_EXT = ");
const extEnd = indexSource.indexOf("\n", extStart);
assert.ok(extEnd > extStart, "PRE_AUTH_STATIC_EXT slice must be bounded");
const src =
indexSource.slice(setStart, setEnd + 3) + "\n" +
indexSource.slice(prefixStart, prefixEnd + 2) + "\n" +
indexSource.slice(extStart, extEnd) + "\n" +
indexSource.slice(fnStart, fnEnd) + "\n" +
indexSource.slice(decodeStart, decodeEnd);
return new Function("path", `${src}\nreturn { isStealthProtectedAssetPath, STEALTH_ASSET_PATHS, PRE_AUTH_STATIC_PREFIXES, PRE_AUTH_STATIC_EXT };`)(path);
}
function loadLoginClassifier() {
const setStart = indexOfOrThrow("const STEALTH_LOGIN_PATHS = new Set([");
const setEnd = indexSource.indexOf("]);", setStart);
const fnStart = indexOfOrThrow("function isStealthProtectedLoginPath(");
const fnEnd = indexOfOrThrow("function sanitizeStealthReturnTo(", fnStart);
assert.ok(setEnd > setStart && fnEnd > fnStart, "slices must be bounded");
const src = indexSource.slice(setStart, setEnd + 3) + "\n" + indexSource.slice(fnStart, fnEnd);
return new Function(`${src}\nreturn { isStealthProtectedLoginPath, STEALTH_LOGIN_PATHS };`)();
}
test("source: the asset helper composes send's exact normalize and mirrors its 403", () => {
const fnStart = indexOfOrThrow("function isStealthProtectedAssetPath(");
const fnEnd = indexOfOrThrow("function isStealthProtectedLoginPath(", fnStart);
const fnSrc = indexSource.slice(fnStart, fnEnd);
assert.ok(
fnSrc.includes('const sendNormalized = path.posix.normalize("." + "/" + decoded);'),
"must compose send's normalize('.' + sep + path) byte-for-byte (posix.normalize " +
"on the posix deployment; '/' is the URL separator)"
);
assert.ok(
fnSrc.includes('const p = "/" + sendNormalized;'),
"send's normalized intermediate is RELATIVE ('favicon.ico'); '/' + it is the " +
"absolute path send joins onto root"
);
assert.ok(
fnSrc.includes("/(?:^|[\\\\/])\\.\\.(?:[\\\\/]|$)/.test(sendNormalized)"),
"the UP_PATH_REGEXP mirror must run BEFORE the set/prefix legs (send 403s " +
"surviving '..' before joining root)"
);
assert.ok(fnSrc.includes("adpanel:stealth-asset-normalized-match"));
assert.ok(fnSrc.includes("adpanel:stealth-asset-decoded-match"));
// the decoded input must still be the shared single decode
assert.ok(fnSrc.includes('safeDecodePath(String(pathname || "").trim())'));
});
test("source: the login helper strips exactly ONE trailing slash and the set is untouched", () => {
const fnStart = indexOfOrThrow("function isStealthProtectedLoginPath(");
const fnEnd = indexOfOrThrow("function sanitizeStealthReturnTo(", fnStart);
const fnSrc = indexSource.slice(fnStart, fnEnd);
assert.ok(
fnSrc.includes('String(pathname || "").trim().replace(/\\/$/, "")'),
"must strip exactly one trailing '/' — express strict:false makes exactly one " +
"optional, so stripping all of them would classify /login// protected while " +
"the router 404s it"
);
assert.ok(fnSrc.includes("adpanel:stealth-login-trailing-slash"));
// set contents and consumers unchanged
const setStart = indexOfOrThrow("const STEALTH_LOGIN_PATHS = new Set([");
const setEnd = indexSource.indexOf("]);", setStart);
assert.strictEqual(
indexSource.slice(setStart, setEnd + 3),
'const STEALTH_LOGIN_PATHS = new Set(["/login", "/forgot-password", "/register"]);',
"STEALTH_LOGIN_PATHS contents must stay the exact-string set"
);
assert.strictEqual(
indexSource.match(/STEALTH_LOGIN_PATHS/g).length, 2,
"the set must keep exactly its definition + the helper consumer"
);
});
test("source: the login helper folds case AFTER the one-slash strip (F3, router-equivalent order)", () => {
const fnStart = indexOfOrThrow("function isStealthProtectedLoginPath(");
const fnEnd = indexOfOrThrow("function sanitizeStealthReturnTo(", fnStart);
const fnSrc = indexSource.slice(fnStart, fnEnd);
assert.ok(
fnSrc.includes('String(pathname || "").trim().replace(/\\/$/, "").toLowerCase()'),
"must fold case COMPOSED after the exact-one-slash strip — strip-then-fold; the " +
"set entries are lowercase and none ends in '/', so the order is exactly " +
"router-equivalent (express caseSensitive:false + strict:false on the raw pathname)"
);
assert.ok(fnSrc.includes("adpanel:stealth-login-case-fold"));
// the fold is the ONLY addition: the helper must not decode (router matches
// the raw pathname) and must not gain prefix/startsWith legs
assert.ok(!fnSrc.includes("toLowerCase() +"), "fold must be terminal in the has() chain");
assert.ok(!/startsWith\(/.test(fnSrc), "no prefix legs — the set is exact-string");
assert.ok(!fnSrc.includes("decodeURI"), "no decode — the router never decodes req.path");
});
test("source: no case-variant route of the three stealth paths exists (fold cannot over-match a different route)", () => {
// Every literal path that case-folds onto a set entry must BE that exact
// lowercase entry — otherwise the fold would make the classifier claim a
// spelling the router serves as a DIFFERENT route.
const routePattern = /\b(?:app|router)\.(?:get|post|put|delete|patch|all|use)\(\s*(["'])([^"']*)\1/g;
const sources = [indexSource];
const routesDir = path.join(ROOT, "routes");
if (fs.existsSync(routesDir)) {
for (const f of fs.readdirSync(routesDir)) {
if (f.endsWith(".js")) sources.push(fs.readFileSync(path.join(routesDir, f), "utf8"));
}
}
const entries = ["/login", "/forgot-password", "/register"];
const hits = [];
for (const src of sources) {
for (const m of src.matchAll(routePattern)) {
const p = m[2];
if (!p.startsWith("/")) continue;
const folded = p.replace(/\/$/, "").toLowerCase();
if (entries.includes(folded)) hits.push(p);
}
}
assert.ok(hits.length >= 1, "the three stealth routes must be defined somewhere");
for (const p of hits) {
assert.strictEqual(
p, entries.find((e) => p.toLowerCase() === e),
`route definition ${JSON.stringify(p)} must be the exact lowercase spelling — ` +
"a case-variant definition would make the case fold over-match a different route"
);
}
});
test("behavior F1: duplicate-slash/dot-segment spellings of covered assets classify PROTECTED", () => {
const { isStealthProtectedAssetPath } = loadAssetClassifier();
// The verified serving-vs-classification divergences: each spelling is
// normalized by send ONTO a covered path and was served (200) pre-fix.
const leakSpellings = [
"/js//cdn-fallback.js",
"//login.css",
"/js/./cdn-fallback.js",
"/js/%2e/cdn-fallback.js",
"/js/%2e%2e/images/adpanel-dark.webp",
"/%2Fjs/cdn-fallback.js",
// adpanel:stealth-asset-spelling-parity (2026-11-13) — root-level
// spellings that normalize onto an uncovered root file the static layer
// served pre-gate (200 REAL bytes): the double slash normalizes onto the
// root file and the encoded extension decodes onto it.
"//dashboard.css",
"/dashboard%2Ecss",
];
for (const spelling of leakSpellings) {
assert.strictEqual(isStealthProtectedAssetPath(spelling), true, spelling);
}
});
test("behavior F1: root-escaping traversals classify UNPROTECTED (send 403s them before joining root)", () => {
const { isStealthProtectedAssetPath } = loadAssetClassifier();
// send 403s any surviving '..' segment BEFORE joining root; express.static's
// fallthrough surfaces that as a plain downstream 404 — no content either
// way. Note posix.normalize('/js/../../etc/passwd') clamps to
// '/etc/passwd' (not in set → also unprotected), but the send composition
// yields '../etc/passwd' — the UP_PATH mirror, not the clamp, is what keeps
// '/../favicon.ico' (clamp → '/favicon.ico' → would be covered) UNPROTECTED
// beside send's 403.
for (const escape of [
"/js/%2e%2e/%2e%2e/etc/passwd",
"/js/../../etc/passwd",
"/%2e%2e/%2e%2e/etc/passwd",
"/../favicon.ico",
"/../auth-assets/x.js",
"/..\\x",
]) {
assert.strictEqual(isStealthProtectedAssetPath(escape), false, escape);
}
});
test("behavior F1: the remaining exact paths and the prefix/exclusion legs keep their cover", () => {
const { isStealthProtectedAssetPath, STEALTH_ASSET_PATHS } = loadAssetClassifier();
assert.strictEqual(STEALTH_ASSET_PATHS.size, 19);
assert.ok(!STEALTH_ASSET_PATHS.has("/js/cdn-fallback.js"), "retired script needs no exact entry");
assert.strictEqual(isStealthProtectedAssetPath("/js/cdn-fallback.js"), true, "the static prefix still covers the old path");
for (const p of STEALTH_ASSET_PATHS) {
assert.strictEqual(isStealthProtectedAssetPath(p), true, p);
}
assert.strictEqual(isStealthProtectedAssetPath("/auth-assets/logo"), true, "prefix leg unchanged");
assert.strictEqual(isStealthProtectedAssetPath("/auth-assets/favicon"), false, "favicon exclusion unchanged");
// req.path never carries a raw '?', but '%3F' survives into it and
// safeDecodePath turns it into '?' — the encoded-'?' exclusion branch stays
// reachable and unchanged on the normalized form (identity here).
assert.strictEqual(isStealthProtectedAssetPath("/auth-assets/favicon?x"), false);
// unchanged non-matching classes
assert.strictEqual(isStealthProtectedAssetPath("/dashboard"), false);
// 2026-11-13 (adpanel:stealth-asset-spelling-parity) — consciously
// re-pinned from UNPROTECTED to PROTECTED: strict:false serves the
// one-slash spelling of the set entry, so the strip-then-match fold covers
// it (the serving layer answers a bare fallthrough 404 for the static
// spelling — the decoy only makes that 404 uniform).
assert.strictEqual(isStealthProtectedAssetPath("/login.css/"), true, "trailing-slash spelling strips onto the set entry — uniform decoy");
// adpanel:stealth-prefix-cover — everything under the static prefix dirs now
// classifies PROTECTED, including spellings send itself 404s (trailing-slash
// directory lookup, double-encoded literal '%63...' name, malformed '%zz'
// sequence): the decoy 404 is uniform across the whole prefix with no
// content either way, so the old "unprotected beside send's 404" pins are
// consciously re-pinned as covered — the no-leak intent of the original
// assertions is preserved (nothing serveable diverges from the decoy).
assert.strictEqual(isStealthProtectedAssetPath("/js/cdn-fallback.js/"), true, "under the /js/ prefix leg — uniform decoy");
assert.strictEqual(isStealthProtectedAssetPath("/js/%2563dn-fallback.js"), true, "decodes once onto the /js/ prefix — uniform decoy (send 404s the literal name; no content either way)");
assert.strictEqual(isStealthProtectedAssetPath("/js/%zzdn-fallback.js"), true, "malformed sequence passes through onto the /js/ prefix — uniform decoy");
// 2026-11-13 (adpanel:stealth-asset-spelling-parity) — consciously
// re-pinned from UNPROTECTED to PROTECTED: the root-level cover classifies
// any single-segment allowlisted-extension spelling, including literal
// %-names send 404s (the double-decoded form never reaches a real file) —
// uniform decoy, same no-leak contract as the prefix pins above.
assert.strictEqual(isStealthProtectedAssetPath("/%2566avicon.ico"), true, "double-encoded root favicon: literal-name 404 mirror under the root-level cover — uniform decoy");
assert.strictEqual(isStealthProtectedAssetPath(""), false);
assert.strictEqual(isStealthProtectedAssetPath("/"), false);
assert.strictEqual(isStealthProtectedAssetPath(null), false);
});
test("behavior F2: exactly one trailing slash classifies protected; two do not (router mirror)", () => {
const { isStealthProtectedLoginPath } = loadLoginClassifier();
assert.strictEqual(isStealthProtectedLoginPath("/login"), true, "plain spelling unchanged");
assert.strictEqual(isStealthProtectedLoginPath("/forgot-password"), true);
assert.strictEqual(isStealthProtectedLoginPath("/register"), true);
// the fix: the one-slash spelling the router actually serves
assert.strictEqual(isStealthProtectedLoginPath("/login/"), true);
assert.strictEqual(isStealthProtectedLoginPath("/forgot-password/"), true);
assert.strictEqual(isStealthProtectedLoginPath("/register/"), true);
// the router does NOT serve these (verified below) — must stay unprotected
assert.strictEqual(isStealthProtectedLoginPath("/login//"), false);
assert.strictEqual(isStealthProtectedLoginPath("/login///"), false);
// untouched inputs
assert.strictEqual(isStealthProtectedLoginPath("/"), false, "root strips to '' and still misses the set");
assert.strictEqual(isStealthProtectedLoginPath("/log/"), false);
assert.strictEqual(isStealthProtectedLoginPath("//login"), false, "no leading-slash semantics — router 404s it too");
assert.strictEqual(isStealthProtectedLoginPath("/login%2F"), false, "raw pathname matching, no decode");
assert.strictEqual(isStealthProtectedLoginPath(""), false);
assert.strictEqual(isStealthProtectedLoginPath(null), false);
});
test("behavior F3: case-variant spellings classify PROTECTED (express matches routes case-insensitively)", () => {
const { isStealthProtectedLoginPath } = loadLoginClassifier();
// every spelling the router serves to the real route (pinned behaviorally
// below) must classify protected, slash or no slash, any case mix
for (const spelling of [
"/LOGIN",
"/Login",
"/lOGIN",
"/lOgIn/",
"/LOGIN/",
"/FORGOT-PASSWORD",
"/Forgot-Password/",
"/forgot-PASSWORD",
"/REGISTER",
"/Register/",
"/ReGiStEr",
]) {
assert.strictEqual(isStealthProtectedLoginPath(spelling), true, spelling);
}
// canonical spellings unchanged by the fold (fold is a no-op there)
assert.strictEqual(isStealthProtectedLoginPath("/login"), true);
assert.strictEqual(isStealthProtectedLoginPath("/login/"), true);
assert.strictEqual(isStealthProtectedLoginPath("/forgot-password"), true);
assert.strictEqual(isStealthProtectedLoginPath("/register"), true);
});
test("behavior F3: the fold creates NO prefix matches — near-miss spellings stay UNPROTECTED", () => {
const { isStealthProtectedLoginPath } = loadLoginClassifier();
// the key negative: /LOGISTICS folds to /logistics which is NOT /login — a
// prefix-style bug would claim it. The router 404s every spelling below
// (pinned behaviorally below), so classification(false) and routing(404)
// agree on each.
for (const spelling of [
"/",
"/log",
"/LOGISTICS",
"/logistics",
"/LOGINX",
"/loginx",
"/register-now",
"/REGISTER-NOW",
"/forgot-password-x",
"/register2",
"/login//",
"//LOGIN",
"/LOGIN%2F",
"",
]) {
assert.strictEqual(isStealthProtectedLoginPath(spelling), false, spelling);
}
assert.strictEqual(isStealthProtectedLoginPath(null), false);
});
test("behavioral: express strict:false serves /login/ but NOT /login// — the contract F2 mirrors", async () => {
const express = require("express");
const app = express();
app.get("/login", (req, res) => res.status(200).send("LOGIN-ROUTE"));
app.get("/forgot-password", (req, res) => res.status(200).send("FORGOT-ROUTE"));
app.use((req, res) => res.status(404).send("NO-ROUTE"));
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
try {
const port = server.address().port;
const rawGet = (requestPath) => new Promise((resolve, reject) => {
const req = http.get({ host: "127.0.0.1", port, path: requestPath }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => resolve({ status: res.statusCode, body }));
});
req.on("error", reject);
});
const oneSlash = await rawGet("/login/");
assert.strictEqual(oneSlash.status, 200);
assert.strictEqual(oneSlash.body, "LOGIN-ROUTE");
const forgot = await rawGet("/forgot-password/");
assert.strictEqual(forgot.status, 200);
assert.strictEqual(forgot.body, "FORGOT-ROUTE");
for (const two of ["/login//", "/login///", "//login", "/login%2F"]) {
const r = await rawGet(two);
assert.strictEqual(r.status, 404, `${two} must not reach the route`);
assert.strictEqual(r.body, "NO-ROUTE");
}
} finally {
server.close();
}
});
test("behavioral: the real gate chain (extracted classifier -> express.static) intercepts the leak spellings and never serves escapes", async () => {
// Mirrors index.js's stealth gate -> express.static order with the REAL
// extracted isStealthProtectedAssetPath and the installed send stack, raw
// request lines (no client-side URL normalization).
const express = require("express");
const { isStealthProtectedAssetPath } = loadAssetClassifier();
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-stealth-normalize-"));
try {
fs.mkdirSync(path.join(dir, "js"), { recursive: true });
fs.mkdirSync(path.join(dir, "images"), { recursive: true });
fs.writeFileSync(path.join(dir, "js", "cdn-fallback.js"), "FALLBACK-CONTENT");
fs.writeFileSync(path.join(dir, "login.css"), "LOGINCSS");
fs.writeFileSync(path.join(dir, "dashboard.css"), "DASHCSS-CONTENT");
fs.writeFileSync(path.join(dir, "images", "adpanel-dark.webp"), "WEBP-CONTENT");
fs.writeFileSync(path.join(dir, "dashboard.html"), "DASHBOARD-CONTENT");
const app = express();
app.use((req, res, next) => {
const pathName = String(req.path || "").trim();
if (!isStealthProtectedAssetPath(pathName)) return next();
// mirror sendStealthNotFound: 404, empty body
res.setHeader("X-Stealth-Gate", "decoy");
return res.status(404).type("text/plain").send("");
});
app.use(express.static(dir));
app.use((req, res) => res.status(404).send("FALLTHROUGH-404"));
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
try {
const port = server.address().port;
const rawGet = (requestPath) => new Promise((resolve, reject) => {
const req = http.get({ host: "127.0.0.1", port, path: requestPath }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => resolve({ status: res.statusCode, body, headers: res.headers }));
});
req.on("error", reject);
});
// every spelling send would normalize onto a covered file is intercepted
// by the gate (decoy 404) — the pre-fix leak served the real content.
// The root-level entries are adpanel:stealth-asset-spelling-parity
// spellings: /dashboard.css and its double-slash + encoded-extension
// + case-variant forms were served (200 REAL bytes) pre-fix while no
// leg covered them.
for (const spelling of [
"/js//cdn-fallback.js",
"//login.css",
"/js/./cdn-fallback.js",
"/js/%2e/cdn-fallback.js",
"/js/%2e%2e/images/adpanel-dark.webp",
"/%2Fjs/cdn-fallback.js",
"/js/cdn-fallback.js",
"/login.css",
"/dashboard.css",
"//dashboard.css",
"/dashboard%2Ecss",
"/DASHBOARD.css",
"/dashboard.css/",
]) {
const r = await rawGet(spelling);
assert.strictEqual(r.status, 404, spelling);
assert.strictEqual(r.headers["x-stealth-gate"], "decoy", spelling);
assert.strictEqual(r.body, "", spelling);
}
// escapes are NOT intercepted (send 403s them before joining root;
// express.static fallthrough surfaces a plain downstream 404) and NO
// content crosses — /etc/passwd never leaves the host.
for (const escape of [
"/js/%2e%2e/%2e%2e/etc/passwd",
"/js/../../etc/passwd",
"/../favicon.ico",
]) {
const r = await rawGet(escape);
assert.strictEqual(r.status, 404, escape);
assert.strictEqual(r.headers["x-stealth-gate"], undefined, escape);
assert.strictEqual(r.body, "FALLTHROUGH-404", escape);
}
// unprotected paths still serve normally through the chain
const dash = await rawGet("/dashboard.html");
assert.strictEqual(dash.status, 200);
assert.strictEqual(dash.body, "DASHBOARD-CONTENT");
assert.strictEqual(dash.headers["x-stealth-gate"], undefined);
// adpanel:stealth-prefix-cover — paths under the static prefix dirs are
// covered by the prefix leg now, so a missing /js/ file takes the uniform
// decoy rather than falling through; the fallthrough contract itself is
// re-pinned on a path under no static prefix.
const missing = await rawGet("/js/does-not-exist.js");
assert.strictEqual(missing.status, 404);
assert.strictEqual(missing.headers["x-stealth-gate"], "decoy", "/js/* decoys pre-gate (prefix cover)");
assert.strictEqual(missing.body, "");
const nonPrefixMiss = await rawGet("/no-such-dir/x.html");
assert.strictEqual(nonPrefixMiss.status, 404);
assert.strictEqual(nonPrefixMiss.headers["x-stealth-gate"], undefined);
assert.strictEqual(nonPrefixMiss.body, "FALLTHROUGH-404");
} finally {
server.close();
}
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("behavioral: express 4.22.2 serves case-variant spellings of the login routes but NOT near-misses (the contract F3 mirrors)", async () => {
const express = require("express");
const app = express();
app.get("/login", (req, res) => res.status(200).send("LOGIN-ROUTE"));
app.get("/forgot-password", (req, res) => res.status(200).send("FORGOT-ROUTE"));
app.get("/register", (req, res) => res.status(200).send("REGISTER-ROUTE"));
app.use((req, res) => res.status(404).send("NO-ROUTE"));
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
try {
const port = server.address().port;
const rawGet = (requestPath) => new Promise((resolve, reject) => {
const req = http.get({ host: "127.0.0.1", port, path: requestPath }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => resolve({ status: res.statusCode, body }));
});
req.on("error", reject);
});
// caseSensitive:false (the default) — case variants reach the real routes
// exactly like the lowercase spelling, so the decoy classification must
// fold case or they bypass the stealth bootstrap
const served = [
["/LOGIN", "LOGIN-ROUTE"],
["/Login", "LOGIN-ROUTE"],
["/lOGIN", "LOGIN-ROUTE"],
["/LOGIN/", "LOGIN-ROUTE"],
["/Forgot-Password", "FORGOT-ROUTE"],
["/Forgot-Password/", "FORGOT-ROUTE"],
["/FORGOT-PASSWORD", "FORGOT-ROUTE"],
["/Register", "REGISTER-ROUTE"],
["/Register/", "REGISTER-ROUTE"],
];
for (const [spelling, body] of served) {
const r = await rawGet(spelling);
assert.strictEqual(r.status, 200, spelling);
assert.strictEqual(r.body, body, spelling);
}
// near-misses: the router 404s each — folding must not create prefix
// matches, and classification(false) below agrees with 404 on each
for (const near of ["/LOGISTICS", "/logistics", "/register-now", "/log", "/LOGINX", "/login//", "//LOGIN"]) {
const r = await rawGet(near);
assert.strictEqual(r.status, 404, `${near} must not reach a route`);
assert.strictEqual(r.body, "NO-ROUTE");
}
} finally {
server.close();
}
});
test("behavioral: the real gate chain (extracted login classifier -> routes) decoys the case-variant spellings post-fix", async () => {
// Mirrors index.js's stealth gate -> routes order with the REAL extracted
// isStealthProtectedLoginPath: a pre-gate probe without stealth access gets
// the bootstrap decoy on every spelling the router would serve, and only
// spellings the router 404s fall through.
const express = require("express");
const { isStealthProtectedLoginPath } = loadLoginClassifier();
const app = express();
app.use((req, res, next) => {
const pathName = String(req.path || "").trim();
if (!isStealthProtectedLoginPath(pathName)) return next();
res.setHeader("X-Stealth-Gate", "bootstrap");
return res.status(404).type("text/plain").send("");
});
app.get("/login", (req, res) => res.status(200).send("LOGIN-ROUTE"));
app.get("/forgot-password", (req, res) => res.status(200).send("FORGOT-ROUTE"));
app.get("/register", (req, res) => res.status(200).send("REGISTER-ROUTE"));
app.use((req, res) => res.status(404).send("NO-ROUTE"));
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
try {
const port = server.address().port;
const rawGet = (requestPath) => new Promise((resolve, reject) => {
const req = http.get({ host: "127.0.0.1", port, path: requestPath }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => resolve({ status: res.statusCode, body, headers: res.headers }));
});
req.on("error", reject);
});
for (const spelling of [
"/LOGIN", "/Login", "/lOgIn/", "/LOGIN/",
"/FORGOT-PASSWORD", "/Forgot-Password/", "/Register/",
]) {
const r = await rawGet(spelling);
assert.strictEqual(r.status, 404, spelling);
assert.strictEqual(r.headers["x-stealth-gate"], "bootstrap", spelling);
assert.strictEqual(r.body, "", spelling);
}
for (const near of ["/LOGISTICS", "/register-now", "/log", "/"]) {
const r = await rawGet(near);
assert.strictEqual(r.status, 404, near);
assert.strictEqual(r.headers["x-stealth-gate"], undefined, near);
assert.strictEqual(r.body, "NO-ROUTE", near);
}
} finally {
server.close();
}
});
test("behavioral: case-variant asset spellings classify PROTECTED (spelling-parity fold) — static ENOENT spellings take the uniform decoy, canonical spellings still serve", async () => {
// 2026-11-13 (adpanel:stealth-asset-spelling-parity): the old no-fold pins
// ("/JS/CDN-FALLBACK.JS", "/LOGIN.CSS" … classify UNPROTECTED because the
// fs lookup is case-sensitive) are consciously REVERSED. The covered
// surface includes ROUTE-BACKED assets the router serves case-insensitively
// with real bytes (/branding-media/:kind, /auth-assets/* — pinned in
// stealth-branding-media-cover.test.js), so the classifier must fold case
// to match the matching layer. For static files the fs lookup stays
// case-sensitive on Linux: a case-variant spelling is an ENOENT 404 either
// way, so the fold only makes that bare 404 uniform (the decoy is no
// longer distinguishable from the fallthrough 404). This harness pins the
// serving layer's side of that contract: NO content crosses for any
// case-variant spelling, canonical spellings still serve.
const express = require("express");
const { isStealthProtectedAssetPath } = loadAssetClassifier();
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-stealth-case-fold-"));
try {
fs.mkdirSync(path.join(dir, "js"), { recursive: true });
fs.writeFileSync(path.join(dir, "js", "cdn-fallback.js"), "FALLBACK-CONTENT");
fs.writeFileSync(path.join(dir, "login.css"), "LOGINCSS");
const app = express();
app.use(express.static(dir));
app.use((req, res) => res.status(404).send("STATIC-FALLTHROUGH-404"));
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
try {
const port = server.address().port;
const rawGet = (requestPath) => new Promise((resolve, reject) => {
const req = http.get({ host: "127.0.0.1", port, path: requestPath }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => resolve({ status: res.statusCode, body, headers: res.headers }));
});
req.on("error", reject);
});
// every case-variant spelling classifies PROTECTED now (prefix leg on
// the folded form / root-level cover on the folded form) and the
// serving layer answers 404 with NO content for each — the gate decoy
// and this bare 404 are indistinguishable to a prober (no bytes either
// way), so no legit flow breaks and no oracle appears.
for (const spelling of ["/JS/CDN-FALLBACK.JS", "/JS/cdn-fallback.js", "/js/CDN-FALLBACK.JS", "/LOGIN.CSS", "/Login.css"]) {
assert.strictEqual(isStealthProtectedAssetPath(spelling), true, `${spelling} classifies PROTECTED (folded classification — spelling-parity)`);
const r = await rawGet(spelling);
assert.strictEqual(r.status, 404, `${spelling} is ENOENT — no content served`);
assert.notStrictEqual(r.body, "FALLBACK-CONTENT", spelling);
assert.notStrictEqual(r.body, "LOGINCSS", spelling);
}
// the canonical lowercase spellings still serve/satisfy the set
assert.strictEqual(isStealthProtectedAssetPath("/js/cdn-fallback.js"), true);
const ok = await rawGet("/js/cdn-fallback.js");
assert.strictEqual(ok.status, 200);
assert.strictEqual(ok.body, "FALLBACK-CONTENT");
assert.strictEqual(isStealthProtectedAssetPath("/login.css"), true);
const okRoot = await rawGet("/login.css");
assert.strictEqual(okRoot.status, 200);
assert.strictEqual(okRoot.body, "LOGINCSS");
} finally {
server.close();
}
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});