Files
Kelx/tests/stealth-favicon-decoy.test.js
2026-11-30 16:32:37 +00:00

604 lines
30 KiB
JavaScript

"use strict";
// adpanel:stealth-favicon-decoy — behavior + source pins for the stealth-mode
// favicon fingerprint oracle the audit found:
//
// The finding: /auth-assets/favicon is deliberately EXCLUDED from the
// stealth gate's decoy classification (isStealthProtectedAssetPath returns
// false for it — a test-pinned decision), but the route behind the
// exclusion had NO stealth re-check. Under STEALTH_ACTIVE an
// unauthenticated prober therefore got, for the one path every sibling
// asset 404s on:
// - the REAL ADPanel favicon bytes (admin-uploaded logo, built-in
// adpanel-dark.webp chrome, or the pinned CDN fallback asset), or
// - a 302 whose Location header leaked the operator's configured remote
// logo URL,
// while /favicon.ico (a 20-entry set member) served the empty 204 decoy —
// a distinguishable pair that fingerprinted the panel.
//
// The fix (cover, not reclassify — mirrors the established /favicon.ico
// design): the /auth-assets/favicon handler runs /favicon.ico's exact
// in-handler pre-flight (STEALTH_ACTIVE && !(await hasStealthAccess(req)))
// FIRST and serves the SAME sendStealthEmptyFavicon decoy (204-empty,
// no-store, stealth response floor) to probes without access — so every
// favicon spelling serves the identical empty decoy and neither the panel
// identity nor the remote-logo URL can leak. With stealth access (gate
// cookie or session) or stealth off, every serving branch below behaves
// exactly as before the check existed. The classifier exclusion stays
// byte-identical; its new comment documents the rationale: the exclusion
// is "covered at the route layer", not "no cover" — and the route-layer
// check is spelling-agnostic, covering the case-variant, trailing-slash
// and query-string spellings the router serves to the handler. 2026-11-13
// (adpanel:stealth-asset-spelling-parity): the gate-side exclusion now
// runs on the classifier's case-folded form so case-variant spellings stay
// excluded exactly like the canonical spelling (the fold can only widen
// what reaches the route's own decoy), but it deliberately does NOT strip
// the trailing slash — the one-slash spelling still rides the /auth-assets/
// prefix leg and takes the gate's 404 decoy, the pre-existing pinned
// classification, unchanged.
//
// Spelling surface note (pinned against the installed express 4.22.2 and
// the REAL extracted classifier): express matches routes on the RAW path,
// so /auth-%61ssets/favicon and /auth-assets/fav%69con do NOT route to the
// handler at all (they fall through to the auth gate, unchanged by this
// fix). Of the spellings that DO route, the plain/case-variant/query forms
// are unprotected at the gate (the exact-spelling exclusion) and reach the
// route cover → empty-favicon decoy; the trailing-slash form normalizes
// (send-style, which KEEPS the trailing slash) onto the /auth-assets/
// prefix leg → classified PROTECTED → the gate's 404 decoy answers it
// before the route is reached (pre-existing classification, no content
// either way — the route cover is a second layer behind it, reachable if
// the classification ever drifts).
process.env.STEALTH_RESPONSE_FLOOR_MS = "1"; // fastest real floor value (0 falls back to 90 — parseInt(...) || 90)
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;
}
// Route windows: each slice is the complete app.get(...) statement, bounded
// by its own catch marker + the first "});" after it (both catches are the
// last statements of their handlers).
function routeWindow(regPrefix, catchMarker) {
const start = indexOfOrThrow(regPrefix);
const catchAt = indexOfOrThrow(catchMarker, start);
const end = indexSource.indexOf("});", catchAt);
assert.ok(end > catchAt, `route window must be bounded: ${regPrefix}`);
return indexSource.slice(start, end + 3);
}
const FAVICON_ROUTE_SRC = routeWindow(
'app.get("/auth-assets/favicon"',
'console.error("[auth-assets] Failed to serve favicon:"'
);
const FAVICO_ROUTE_SRC = routeWindow(
'app.get("/favicon.ico"',
'console.error("[/favicon.ico] pre-flight failed:"'
);
// Extraction (same technique as stealth-classification-normalize.test.js /
// static-prefix-hardening.test.js): stitch the REAL classifier (set +
// prefixes + helper + safeDecodePath), the REAL decoy senders
// (sendStealthNotFound / sendStealthEmptyFavicon / applyStealthResponseFloor
// / delay / the floor const) and the REAL favicon sender chain
// (enhanceSvgForFavicon + applySvgContentSecurityHeaders +
// sendPrivateAssetFile) into evaluatable scopes. index.js binds
// require("path") at module top; new Function bodies see no module scope, so
// the module object is handed in as a parameter — the identical binding.
function loadStealthScope() {
const floorStart = indexOfOrThrow("const STEALTH_RESPONSE_FLOOR_MS = ");
const floorEnd = indexSource.indexOf("\n", floorStart);
assert.ok(floorEnd > floorStart, "floor const slice must be bounded");
const delayStart = indexOfOrThrow("function delay(ms) {");
const delayEnd = indexOfOrThrow("function getStealthBootstrapState(req) {", delayStart);
assert.ok(delayEnd > delayStart, "delay + floor slice must be bounded");
const notFoundStart = indexOfOrThrow("async function sendStealthNotFound(res) {");
const notFoundEnd = indexOfOrThrow("async function hasStealthAccess(req) {", notFoundStart);
assert.ok(notFoundEnd > notFoundStart, "decoy sender slice must be bounded");
const setStart = indexOfOrThrow("const STEALTH_ASSET_PATHS = new Set([");
const setEnd = indexSource.indexOf("]);", setStart);
assert.ok(setEnd > setStart, "STEALTH_ASSET_PATHS slice must be bounded");
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");
// adpanel:stealth-asset-spelling-parity — the classifier's root-level leg
// references the shared PRE_AUTH_STATIC_EXT const (defined later in
// index.js, request-time evaluation); the stitched scope must carry it.
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 clsStart = indexOfOrThrow("function isStealthProtectedAssetPath(");
const clsEnd = indexOfOrThrow("function isStealthProtectedLoginPath(", clsStart);
assert.ok(clsEnd > clsStart, "classifier slice must be bounded");
const decodeStart = indexOfOrThrow("function safeDecodePath(p)");
const decodeEnd = indexOfOrThrow("function servePublicStatic(", decodeStart);
assert.ok(decodeEnd > decodeStart, "safeDecodePath slice must be bounded");
const src =
indexSource.slice(floorStart, floorEnd) + "\n" +
indexSource.slice(delayStart, delayEnd) + "\n" +
indexSource.slice(notFoundStart, notFoundEnd) + "\n" +
indexSource.slice(setStart, setEnd + 3) + "\n" +
indexSource.slice(prefixStart, prefixEnd + 2) + "\n" +
indexSource.slice(extStart, extEnd) + "\n" +
indexSource.slice(clsStart, clsEnd) + "\n" +
indexSource.slice(decodeStart, decodeEnd);
// adpanel:stealth-mint-cap — the delay → getStealthBootstrapState window
// now spans the mint-cap block, whose module-scope bindings (redisClient /
// STEALTH_ACTIVE / buildSharedRateLimitRedisStore) are handed in per the
// identical-binding rule above. A null client keeps this decoy-scoped
// harness counter-free: the cap builds no stores and the decoy senders
// under test are untouched.
return new Function("path", "redisClient", "STEALTH_ACTIVE", "buildSharedRateLimitRedisStore",
`${src}\nreturn { isStealthProtectedAssetPath, STEALTH_ASSET_PATHS, PRE_AUTH_STATIC_PREFIXES, sendStealthNotFound, sendStealthEmptyFavicon, STEALTH_RESPONSE_FLOOR_MS };`
)(path, null, false, () => null);
}
function loadSenderScope(brandingUtils) {
const start = indexOfOrThrow("function enhanceSvgForFavicon(svgContent) {");
const end = indexOfOrThrow("async function sendPrivateRemoteAsset(", start);
assert.ok(end > start, "sender chain slice must be bounded");
const src = indexSource.slice(start, end);
return new Function("path", "fs", "getMimeTypeForExtension", `${src}\nreturn { sendPrivateAssetFile };`)(path, fs, brandingUtils.getMimeTypeForExtension);
}
// The two route slices ARE the production app.get(...) statements. Evaluating
// them registers the REAL handler source on the harness app, with every
// closed-over dependency injected as a parameter. This is the same
// evaluate-the-extracted-source technique the other route tests use — the
// handler under test is index.js's own text, not a mirror.
function registerRealRoutes(app, deps) {
const src = FAVICON_ROUTE_SRC + "\n" + FAVICO_ROUTE_SRC;
new Function(
"app",
"brandingAssetRateLimiter",
"STEALTH_ACTIVE",
"hasStealthAccess",
"sendStealthEmptyFavicon",
"loadBrandingConfig",
"resolvePublicImagePath",
"sanitizeLogoUrl",
"sendPrivateAssetFile",
"getBuiltInFaviconPath",
"getExtensionFromUrl",
"FIXED_FAVICON_REMOTE_URL",
"sendPrivateRemoteAsset",
src
)(
app,
deps.brandingAssetRateLimiter,
deps.STEALTH_ACTIVE,
deps.hasStealthAccess,
deps.sendStealthEmptyFavicon,
deps.loadBrandingConfig,
deps.resolvePublicImagePath,
deps.sanitizeLogoUrl,
deps.sendPrivateAssetFile,
deps.getBuiltInFaviconPath,
deps.getExtensionFromUrl,
deps.FIXED_FAVICON_REMOTE_URL,
deps.sendPrivateRemoteAsset
);
}
// ---------------------------------------------------------------------------
// Source pins
// ---------------------------------------------------------------------------
test("source: the classifier exclusion matches the case-folded form and documents its route-layer cover", () => {
const clsStart = indexOfOrThrow("function isStealthProtectedAssetPath(");
const clsEnd = indexOfOrThrow("function isStealthProtectedLoginPath(", clsStart);
const fnSrc = indexSource.slice(clsStart, clsEnd);
// 2026-11-13 (adpanel:stealth-asset-spelling-parity): the exclusion line
// moved from the raw `p` form to the case-folded form — consciously
// updated, semantics preserved: the exclusion must still carve the favicon
// spellings out of the gate decoys so the ROUTE's own empty-favicon decoy
// answers them, and the case fold extends that carve-out to the
// case-variant spellings the router serves to the same handler.
assert.ok(
fnSrc.includes('if (caseFolded === "/auth-assets/favicon" || caseFolded.startsWith("/auth-assets/favicon?")) return false;'),
"the exclusion must run on the case-folded form (case-variant spellings keep reaching the route's own decoy)"
);
// the rationale comment sits immediately above it (between the spelling-
// parity fold and the exclusion) and documents the ROUTE-layer cover
const foldIdx = fnSrc.indexOf("const caseFolded = p.toLowerCase();");
const exclIdx = fnSrc.indexOf('caseFolded === "/auth-assets/favicon"');
const tagIdx = fnSrc.indexOf("adpanel:stealth-favicon-decoy");
assert.ok(foldIdx >= 0 && exclIdx > foldIdx, "classifier shape pins must hold");
assert.ok(
tagIdx > foldIdx && tagIdx < exclIdx,
"the exclusion must carry its adpanel:stealth-favicon-decoy rationale comment immediately above the line"
);
const comment = fnSrc.slice(tagIdx, exclIdx);
assert.ok(comment.includes("ROUTE"), "the comment must state the cover lives at the ROUTE layer");
assert.ok(comment.includes("sendStealthEmptyFavicon"), "the comment must name the shared decoy the route serves");
assert.ok(comment.includes("hasStealthAccess"), "the comment must name the in-handler pre-flight");
// the exclusion deliberately does NOT strip the trailing slash: the
// one-slash spelling keeps riding the /auth-assets/ prefix leg → gate 404
// decoy (pinned behaviorally below), so the strip must appear only on the
// exact-match legs' `resolved` form
assert.ok(
fnSrc.includes('const resolved = caseFolded.replace(/\\/$/, "");'),
"the one-trailing-slash strip composes on the folded form for the exact-match legs"
);
// the legs the fix must not touch stay structurally identical (folded forms)
assert.ok(
/return caseFolded\.startsWith\("\/auth-assets\/"\) \|\| STEALTH_ASSET_PATHS\.has\(resolved\) \|\|\n\s*PRE_AUTH_STATIC_PREFIXES\.some\(\(prefix\) => caseFolded\.startsWith\(prefix\)\) \|\|\n\s*\(resolved\.indexOf\("\/", 1\) === -1 && PRE_AUTH_STATIC_EXT\.test\(resolved\)\);/.test(fnSrc),
"the return must still compose the /auth-assets/ leg, the STEALTH_ASSET_PATHS exact-match set (folded + stripped), the PRE_AUTH_STATIC_PREFIXES legs and the root-level cover"
);
});
test("source: both favicon routes check legacy stealth access before serving branded output", () => {
const aaCheck = FAVICON_ROUTE_SRC.indexOf("if (STEALTH_ACTIVE && !(await hasStealthAccess(req))) {");
const favCheck = FAVICO_ROUTE_SRC.indexOf("if (!STEALTH_ACTIVE || !(await hasStealthAccess(req))) {");
assert.ok(aaCheck >= 0, "the /auth-assets/favicon handler must contain the exact /favicon.ico pre-flight expression");
assert.ok(favCheck >= 0, "/favicon.ico keeps its pre-flight (mirror source unchanged)");
const aaDecoy = FAVICON_ROUTE_SRC.indexOf("return sendStealthEmptyFavicon(res);");
const favDecoy = FAVICO_ROUTE_SRC.indexOf("return sendStealthEmptyFavicon(res, STEALTH_ACTIVE);");
assert.ok(aaDecoy > aaCheck, "the decoy call must follow the check");
assert.ok(favDecoy > favCheck, "/favicon.ico's decoy call must follow its check");
// the check must precede EVERY serving branch: config load, the 302-to-remote
// redirect (the Location leak), the built-in send and the CDN fallback
for (const branch of [
"const branding = loadBrandingConfig();",
"res.redirect(302, remoteLogoUrl)",
"sendPrivateAssetFile(res, localLogoPath",
"getBuiltInFaviconPath()",
"sendPrivateRemoteAsset(res, {",
'res.status(404).end("not found")',
]) {
const at = FAVICON_ROUTE_SRC.indexOf(branch);
assert.ok(at > aaCheck, `${branch} must come after the stealth pre-flight`);
}
// the decoy is the SHARED helper — no fork inside the route, and index.js
// still defines the sender exactly once
assert.ok(!FAVICON_ROUTE_SRC.includes("async function sendStealthEmptyFavicon"), "the route must not fork its own decoy sender");
assert.ok(!FAVICON_ROUTE_SRC.includes("status(204)"), "the route must not inline a decoy response beside the shared helper");
const senderDefCount = indexSource.split("async function sendStealthEmptyFavicon(").length - 1;
assert.strictEqual(senderDefCount, 1, "sendStealthEmptyFavicon must have exactly one definition (one-true-home)");
// Express-4 async-rejection class: the await sits inside the guard try
const tryAt = FAVICON_ROUTE_SRC.indexOf("try {");
const awaitAt = FAVICON_ROUTE_SRC.indexOf("await hasStealthAccess(req)");
assert.ok(tryAt >= 0 && tryAt < awaitAt, "the guard try must precede the pre-flight await (preflight-guard-sweep class)");
// the handler carries the comment tag documenting the constraint
assert.ok(FAVICON_ROUTE_SRC.includes("adpanel:stealth-favicon-decoy"), "the handler must carry the adpanel:stealth-favicon-decoy comment");
});
test("source: the shared decoy keeps its no-store/204 posture", () => {
const { sendStealthEmptyFavicon, STEALTH_RESPONSE_FLOOR_MS } = loadStealthScope();
const defStart = indexOfOrThrow("async function sendStealthEmptyFavicon(res, withFloor = true) {");
const defEnd = indexOfOrThrow("async function hasStealthAccess(req) {", defStart);
const src = indexSource.slice(defStart, defEnd);
assert.ok(src.includes('"no-store, private"'), "the decoy must stay no-store");
assert.ok(src.includes('"nosniff"'), "the decoy must stay nosniff");
assert.ok(src.includes("status(204)"), "the decoy must stay a 204-empty");
assert.ok(src.includes("if (withFloor) await applyStealthResponseFloor(startedAt);"));
assert.strictEqual(typeof sendStealthEmptyFavicon, "function");
assert.strictEqual(STEALTH_RESPONSE_FLOOR_MS, 1, "the env knob must gate the floor in this test process");
});
// ---------------------------------------------------------------------------
// Behavioral harness: production order — stealth gate (REAL classifier, REAL
// decoy senders) → the REAL extracted route handlers → fallthrough.
// hasStealthAccess is reduced to a boolean (cookie/session semantics are the
// gate's own tests' concern); the login-path/bootstrap legs are not under
// test and collapse to fallthrough. sendPrivateRemoteAsset throws — branch 4
// (stripped-images CDN fallback) is out of scope and must stay unreachable
// with the fixture branding used here.
// ---------------------------------------------------------------------------
function buildFixtureDir() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-favicon-decoy-"));
fs.writeFileSync(path.join(dir, "admin-logo.webp"), "ADMIN-LOGO-BYTES");
fs.writeFileSync(path.join(dir, "built-in.webp"), "BUILT-IN-BYTES");
return dir;
}
function buildHarness(dir, { stealthActive, hasAccess, branding, builtInAvailable = true }) {
const express = require("express");
const brandingUtils = require("../utils/branding");
const { isStealthProtectedAssetPath, sendStealthNotFound, sendStealthEmptyFavicon } = loadStealthScope();
const { sendPrivateAssetFile } = loadSenderScope(brandingUtils);
const app = express();
const hasStealthAccess = async () => (stealthActive ? !!hasAccess : true);
if (stealthActive) {
// mirror of index.js's stealth gate middleware (asset leg): classify on
// req.path with the REAL classifier, pass on access, else favicon
// special-case → empty decoy, other protected assets → 404 decoy
app.use(async (req, res, next) => {
const pathName = String(req.path || "").trim();
const isProtectedAssetPath = isStealthProtectedAssetPath(pathName);
if (!isProtectedAssetPath) return next();
try {
if (await hasStealthAccess(req)) return next();
} catch (err) {
return next(err);
}
if (pathName === "/favicon.ico") {
return sendStealthEmptyFavicon(res).catch(next);
}
if (isProtectedAssetPath) {
return sendStealthNotFound(res).catch(next);
}
return next();
});
}
const resolveFixture = (filename) => {
if (!filename) return null;
const p = path.join(dir, path.basename(String(filename)));
return fs.existsSync(p) ? p : null;
};
registerRealRoutes(app, {
brandingAssetRateLimiter: (req, res, next) => next(),
STEALTH_ACTIVE: stealthActive,
hasStealthAccess,
sendStealthEmptyFavicon,
loadBrandingConfig: () => branding,
resolvePublicImagePath: resolveFixture,
sanitizeLogoUrl: brandingUtils.sanitizeLogoUrl,
sendPrivateAssetFile,
getBuiltInFaviconPath: () => (builtInAvailable ? path.join(dir, "built-in.webp") : null),
getExtensionFromUrl: brandingUtils.getExtensionFromUrl,
FIXED_FAVICON_REMOTE_URL: "https://cdn.example.invalid/favicon.webp",
sendPrivateRemoteAsset: async () => {
throw new Error("branch 4 (CDN fallback) must not be reached by these fixtures");
},
});
app.use((req, res) => res.status(404).send("FALLTHROUGH"));
return app;
}
function startServer(app) {
const server = app.listen(0, "127.0.0.1");
return new Promise((resolve) => server.once("listening", () => resolve(server)));
}
function rawRequest(server, method, requestPath) {
const port = server.address().port;
return new Promise((resolve, reject) => {
const req = http.request({ host: "127.0.0.1", port, path: requestPath, method }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("error", reject);
res.on("end", () => resolve({ status: res.statusCode, body, headers: res.headers }));
});
req.on("error", reject);
req.end();
});
}
// The decoy fingerprint: what an unauthenticated prober must see for every
// favicon spelling under stealth. The /auth-assets/favicon decoy and the
// /favicon.ico decoy must be INDISTINGUISHABLE (same status, empty body, same
// cache posture) — that parity is the fix's whole point.
function assertDecoyShape(r, label) {
assert.strictEqual(r.status, 204, label);
assert.strictEqual(r.body, "", label);
assert.strictEqual(r.headers.location, undefined, `${label}: no Location header`);
assert.strictEqual(r.headers["cache-control"], "no-store, private", label);
assert.strictEqual(r.headers["x-content-type-options"], "nosniff", label);
assert.strictEqual(
r.headers["content-security-policy"],
"default-src 'none'; base-uri 'none'; frame-ancestors 'none'; object-src 'none';",
label
);
}
function assertSameDecoy(a, b, label) {
for (const key of ["status", "body", "cache-control", "x-content-type-options", "content-security-policy"]) {
const av = key === "status" ? a.status : key === "body" ? a.body : a.headers[key];
const bv = key === "status" ? b.status : key === "body" ? b.body : b.headers[key];
assert.strictEqual(av, bv, `${label}: ${key}`);
}
}
test("behavior: stealth ON no-access — every routing spelling of /auth-assets/favicon serves the empty-favicon decoy", async () => {
const dir = buildFixtureDir();
const app = buildHarness(dir, {
stealthActive: true,
hasAccess: false,
branding: { localLogoPath: "admin-logo.webp", logoUrl: null },
});
let server;
try {
server = await startServer(app);
// spellings the router serves to the handler (pinned against express
// 4.22.2: case-insensitive routes, raw query) — all unprotected at the
// gate (exact-spelling exclusion), so the ROUTE cover answers them
for (const spelling of [
"/auth-assets/favicon",
"/AUTH-ASSETS/favicon",
"/Auth-Assets/Favicon",
"/auth-assets/favicon?ref=login",
]) {
const r = await rawRequest(server, "GET", spelling);
assertDecoyShape(r, spelling);
assert.notStrictEqual(r.body, "ADMIN-LOGO-BYTES", `${spelling}: real bytes must not leak`);
}
// the trailing-slash spelling normalizes (send-style, slash kept) onto
// the /auth-assets/ prefix leg → classified PROTECTED → the GATE's 404
// decoy answers it before the route is reached (pre-existing, no content)
const slash = await rawRequest(server, "GET", "/auth-assets/favicon/");
assert.strictEqual(slash.status, 404, "trailing-slash spelling rides the prefix leg → gate decoy");
assert.strictEqual(slash.body, "", "trailing-slash decoy body empty");
assert.strictEqual(slash.headers["cache-control"], "no-store, private", "trailing-slash decoy posture");
assert.strictEqual(slash.headers.location, undefined, "trailing-slash spelling: no Location leak either");
const head = await rawRequest(server, "HEAD", "/auth-assets/favicon");
assert.strictEqual(head.status, 204, "HEAD no-access → decoy");
assert.strictEqual(head.body, "", "HEAD decoy body empty");
// parity: the two favicon spellings are indistinguishable to the prober
const ico = await rawRequest(server, "GET", "/favicon.ico");
const aa = await rawRequest(server, "GET", "/auth-assets/favicon");
assertSameDecoy(aa, ico, "favicon decoy parity");
} finally {
if (server) server.close();
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("behavior: stealth ON no-access + remote-logo branding — the 302 Location leak is closed", async () => {
const dir = buildFixtureDir();
const app = buildHarness(dir, {
stealthActive: true,
hasAccess: false,
branding: { localLogoPath: null, logoUrl: "https://brand.example.com/logo.webp" },
});
let server;
try {
server = await startServer(app);
const r = await rawRequest(server, "GET", "/auth-assets/favicon");
assertDecoyShape(r, "/auth-assets/favicon (remote-logo branding)");
const ico = await rawRequest(server, "GET", "/favicon.ico");
assertSameDecoy(r, ico, "remote-logo branding decoy parity");
} finally {
if (server) server.close();
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("behavior: stealth ON no-access — the decoy wins even with no servable branding (check precedes every branch)", async () => {
const dir = buildFixtureDir();
const app = buildHarness(dir, {
stealthActive: true,
hasAccess: false,
branding: { localLogoPath: null, logoUrl: null },
builtInAvailable: false, // nothing to serve: without the check this fell to 502/404
});
let server;
try {
server = await startServer(app);
const r = await rawRequest(server, "GET", "/auth-assets/favicon");
assertDecoyShape(r, "/auth-assets/favicon (nothing to serve)");
} finally {
if (server) server.close();
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("behavior: stealth ON gated — real bytes / 302-to-remote / favicon.ico chain unchanged", async () => {
const dir = buildFixtureDir();
const app = buildHarness(dir, {
stealthActive: true,
hasAccess: true,
branding: { localLogoPath: "admin-logo.webp", logoUrl: null },
});
let server;
try {
server = await startServer(app);
const r = await rawRequest(server, "GET", "/auth-assets/favicon");
assert.strictEqual(r.status, 200, "gated → real bytes");
assert.strictEqual(r.body, "ADMIN-LOGO-BYTES", "gated → admin logo bytes");
assert.strictEqual(r.headers["cache-control"], "public, max-age=86400, must-revalidate", "gated favicon cache posture unchanged");
assert.ok((r.headers["content-type"] || "").startsWith("image/webp"), "gated favicon content-type unchanged");
const ico = await rawRequest(server, "GET", "/favicon.ico");
assert.strictEqual(ico.status, 302, "/favicon.ico keeps its redirect");
assert.strictEqual(ico.headers.location, "/auth-assets/favicon", "/favicon.ico → /auth-assets/favicon chain unchanged");
} finally {
if (server) server.close();
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("behavior: stealth ON gated + remote-logo branding — the legit 302 keeps its Location", async () => {
const dir = buildFixtureDir();
const app = buildHarness(dir, {
stealthActive: true,
hasAccess: true,
branding: { localLogoPath: null, logoUrl: "https://brand.example.com/logo.webp" },
});
let server;
try {
server = await startServer(app);
const r = await rawRequest(server, "GET", "/auth-assets/favicon");
assert.strictEqual(r.status, 302, "gated → the configured redirect is preserved");
assert.strictEqual(r.headers.location, "https://brand.example.com/logo.webp", "gated Location unchanged");
} finally {
if (server) server.close();
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("behavior: stealth OFF — explicit icon remains branded and the implicit favicon is empty", async () => {
const dir = buildFixtureDir();
const app = buildHarness(dir, {
stealthActive: false,
hasAccess: false,
branding: { localLogoPath: "admin-logo.webp", logoUrl: null },
});
let server;
try {
server = await startServer(app);
const r = await rawRequest(server, "GET", "/auth-assets/favicon");
assert.strictEqual(r.status, 200);
assert.strictEqual(r.body, "ADMIN-LOGO-BYTES");
assert.strictEqual(r.headers["cache-control"], "public, max-age=86400, must-revalidate");
const ico = await rawRequest(server, "GET", "/favicon.ico");
assertDecoyShape(ico, "implicit favicon");
assertDecoyShape(await rawRequest(server, "HEAD", "/FAVICON.ICO/"), "implicit favicon HEAD alias");
} finally {
if (server) server.close();
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("behavior: stealth OFF + remote-logo branding — 302 unchanged", async () => {
const dir = buildFixtureDir();
const app = buildHarness(dir, {
stealthActive: false,
hasAccess: false,
branding: { localLogoPath: null, logoUrl: "https://brand.example.com/logo.webp" },
});
let server;
try {
server = await startServer(app);
const r = await rawRequest(server, "GET", "/auth-assets/favicon");
assert.strictEqual(r.status, 302);
assert.strictEqual(r.headers.location, "https://brand.example.com/logo.webp");
} finally {
if (server) server.close();
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("behavior: the exclusion stays scoped — sibling /auth-assets paths still decoy 404 at the gate", async () => {
const dir = buildFixtureDir();
const app = buildHarness(dir, {
stealthActive: true,
hasAccess: false,
branding: { localLogoPath: "admin-logo.webp", logoUrl: null },
});
let server;
try {
server = await startServer(app);
// /auth-assets/logo rides the /auth-assets/ prefix leg — gate 404 decoy
const r = await rawRequest(server, "GET", "/auth-assets/logo");
assert.strictEqual(r.status, 404, "sibling stays gated");
assert.strictEqual(r.body, "", "sibling decoy body empty");
assert.strictEqual(r.headers["cache-control"], "no-store, private", "sibling decoy posture");
// the classifier scope check: favicon excluded, sibling + set entries not
const { isStealthProtectedAssetPath, STEALTH_ASSET_PATHS } = loadStealthScope();
assert.strictEqual(isStealthProtectedAssetPath("/auth-assets/favicon"), false, "favicon exclusion unchanged");
assert.strictEqual(isStealthProtectedAssetPath("/auth-assets/favicon?x"), false, "encoded-'?' branch unchanged");
assert.strictEqual(isStealthProtectedAssetPath("/auth-assets/logo"), true, "prefix leg unchanged");
assert.strictEqual(STEALTH_ASSET_PATHS.size, 19, "only the retired CDN script is removed from the pinned set");
assert.ok(STEALTH_ASSET_PATHS.has("/favicon.ico"), "/favicon.ico stays a set member");
assert.ok(STEALTH_ASSET_PATHS.has("/branding-media/login-background"), "login-background keeps its set cover");
assert.ok(STEALTH_ASSET_PATHS.has("/branding-media/logo"), "logo carries its set cover (adpanel:branding-media-stealth-cover)");
} finally {
if (server) server.close();
fs.rmSync(dir, { recursive: true, force: true });
}
});