Initial upload to Gitea

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

No files matched your search

+841
View File
@@ -0,0 +1,841 @@
"use strict";
// adpanel:remote-proxy-trust-gate — pins for the OPT-IN
// (REMOTE_PROXY_REQUIRE_TRUST=1) enforcement of the remote-proxy misconfig
// signature on the credential surfaces.
//
// The ledger-chosen default (adpanel:remote-proxy-misconfig-warning) stays
// WARN-ONLY and byte-identical; this knob is additive and default-off. What
// is locked here:
// 1. The predicate isRemoteProxyTrustViolationRequest (index.js) is the ONE
// home of the signature condition — the exact condition the runtime warn
// applies — and warnRemoteProxyMisconfigOnce DELEGATES to it: no second
// copy of the condition may exist in the warn or in the gate module.
// Deliberately NO req.secure leg: the warn never tested it, and the gate
// inherits that exact condition (a direct-TLS client forging XFP: https
// presents the same observable; opt-in refusal hits the forging client
// only).
// 2. The gate: disabled → pass-through for EVERYTHING (one read + next());
// enabled + violation → refuses ONLY POST /login and
// POST /api/captcha/verify, matched router-equivalently (case-fold +
// exactly one optional trailing "/", raw pathname); GET /login and every
// other route pass through even on violation. Refusal: 503 with a
// path-free generic body — NO proxy/XFP/trust detail
// (adpanel:preauth-500-no-proxy-detail discipline).
// 3. Wiring: the knob resolves through parseBoolean with default false (no
// raw parseInt), and the gate is mounted between the Secure-sync/warn
// middleware and the preauth TTL middleware, never touching the warn's
// one-time latch.
// 4. The SECOND CONSUMER of the same predicate (remember-credential
// ISSUANCE): under opt-in + violation no remember credential is minted
// or refreshed on any path the credential-POST gate cannot cover —
// restore fails CLOSED (stale cookie cleared, no session bind, silent
// false — the shape of its existing failure paths, before ALL
// choreography), the authenticated silent refresh and the mint helper
// SKIP entirely (nothing mutated). Default OFF stays byte-identical on
// every one of those paths (the ledger's warn-only posture), and opt-in
// + no-violation stays byte-identical too. The credential POSTs' own
// mint paths are deliberately NOT double-gated: the routes register
// after the gate mount, so they never execute under the signature.
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 http = require("node:http");
const express = require("express");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const GATE_JS = path.join(ROOT, "utils", "remote-proxy-trust-gate.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const gateSource = fs.readFileSync(GATE_JS, "utf8");
const { createRemoteProxyTrustGate } = require(GATE_JS);
function endIndexOfBlock(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker ${startMarker} not found`);
const bodyStart = source.indexOf("{", start);
let depth = 0;
for (let i = bodyStart; i < source.length; i += 1) {
if (source[i] === "{") depth += 1;
else if (source[i] === "}") {
depth -= 1;
if (depth === 0) return i + 1;
}
}
assert.fail(`unbalanced braces after marker ${startMarker}`);
}
function sliceBlock(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker ${startMarker} not found`);
return source.slice(start, endIndexOfBlock(source, startMarker));
}
// ---------- (a) the REAL predicate, vm-extracted from index.js ----------
function buildRealViolationOf({ trustedProxyIpsEnv = "" } = {}) {
const helpers = indexSource.slice(
indexSource.indexOf("const TRUSTED_PROXY_IPS = new Set("),
endIndexOfBlock(indexSource, "function getLastForwardedValue(value, normalizer")
);
const predicate = sliceBlock(indexSource, "function isRemoteProxyTrustViolationRequest(req)");
const context = vm.createContext({
net: require("node:net"),
console: { log: () => {}, warn: () => {}, error: () => {} },
process: { env: { TRUSTED_PROXY_IPS: trustedProxyIpsEnv } },
});
vm.runInContext([helpers, predicate].join("\n"), context, { filename: "index.js#isRemoteProxyTrustViolationRequest" });
const fn = context.isRemoteProxyTrustViolationRequest;
assert.strictEqual(typeof fn, "function", "predicate extraction failed");
return fn;
}
// Raw request shape, mirroring what the panel sees: direct socket peer +
// headers. secure defaults false (plain HTTP at the node — the misconfig's
// cookie half is live in exactly that posture).
function probeReq({ peer = "203.0.113.7", xfp, secure = false } = {}) {
return {
secure,
connection: { remoteAddress: peer },
socket: { remoteAddress: peer },
headers: xfp === undefined ? {} : { "x-forwarded-proto": xfp },
};
}
test("predicate: untrusted peer + XFP claims https — violation (the warn's exact observable)", () => {
const fn = buildRealViolationOf();
assert.strictEqual(fn(probeReq({ xfp: "https", secure: false })), true);
assert.strictEqual(fn(probeReq({ xfp: "HTTPS" })), true, "the last-hop compare is case-insensitive");
assert.strictEqual(fn(probeReq({ xfp: "http,https" })), true, "the LAST hop wins, matching getTrustedForwardedProto");
});
test("predicate: plain HTTP without an https claim — no violation", () => {
const fn = buildRealViolationOf();
assert.strictEqual(fn(probeReq({ xfp: undefined })), false);
assert.strictEqual(fn(probeReq({ xfp: "http" })), false);
assert.strictEqual(fn(probeReq({ xfp: "https,http" })), false, "a last hop of http is no https claim");
});
test("predicate: trusted proxy appending XFP — no violation", () => {
const loopback = buildRealViolationOf();
assert.strictEqual(loopback(probeReq({ peer: "127.0.0.1", xfp: "https" })), false, "a loopback TLS proxy is trusted");
assert.strictEqual(loopback(probeReq({ peer: "::1", xfp: "https" })), false, "IPv6 loopback too");
const listed = buildRealViolationOf({ trustedProxyIpsEnv: "10.8.0.5, 192.0.2.9" });
assert.strictEqual(listed(probeReq({ peer: "10.8.0.5", xfp: "https" })), false, "an operator-trusted proxy is never a violation");
assert.strictEqual(listed(probeReq({ peer: "::ffff:192.0.2.9", xfp: "https" })), false, "IPv6-mapped peers are normalized first");
});
test("predicate: no socket address (UNIX socket) — no violation; direct-TLS forged XFP IS a violation", () => {
const fn = buildRealViolationOf();
assert.strictEqual(fn({ connection: {}, socket: {}, headers: { "x-forwarded-proto": "https" } }), false);
// Deliberate: the warn never tested req.secure, so a direct-TLS client
// forging XFP: https presents the same observable (see the predicate's
// adpanel comment). The gate inherits this exact condition; under opt-in
// only the forging client's credential posts are refused.
assert.strictEqual(fn(probeReq({ xfp: "https", secure: true })), true, "the exact warn condition has NO req.secure leg");
});
// ---------- (b) the gate middleware: real express + real predicate ----------
const UNTRUSTED_PEER = "203.0.113.7"; // TEST-NET-3, loopback is always trusted
function buildGateApp({ enabled, peer = UNTRUSTED_PEER, spy } = {}) {
const app = express();
// Harness: present the misconfig's signature surface to the panel — a
// REMOTE (non-loopback) direct peer — before the gate resolves anything.
app.use((req, _res, next) => {
req.connection = { remoteAddress: peer, encrypted: false };
req.socket = { remoteAddress: peer };
next();
});
app.use(createRemoteProxyTrustGate({ enabled, violationOf: spy || buildRealViolationOf() }));
const hits = [];
app.post("/login", (req, res) => { hits.push("post-login"); res.status(200).json({ ok: true }); });
app.get("/login", (req, res) => { hits.push("get-login"); res.status(200).json({ ok: true }); });
app.post("/api/captcha/verify", (req, res) => { hits.push("captcha-verify"); res.status(200).json({ ok: true }); });
app.post("/other", (req, res) => { hits.push("other"); res.status(200).json({ ok: true }); });
app.use((req, res) => { hits.push("fallthrough"); res.status(200).json({ ok: true, path: req.path }); });
return { app, hits };
}
function requestOnce(app, method, reqPath, headers = {}) {
return new Promise((resolve, reject) => {
const server = app.listen(0, "127.0.0.1", () => {
const port = server.address().port;
const req = http.request({ host: "127.0.0.1", port, path: reqPath, method, headers }, (res) => {
let body = "";
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
server.close(() => resolve({ status: res.statusCode, headers: res.headers, body }));
};
res.on("data", (c) => { body += c; });
res.on("error", finish);
res.on("aborted", finish);
res.on("end", finish);
});
req.on("error", (err) => server.close(() => reject(err)));
req.end();
});
server.on("error", (err) => reject(err));
});
}
const VIOLATING_HEADERS = { "x-forwarded-proto": "https" };
test("gate disabled: a violating request passes through untouched (byte-identical default posture)", async () => {
const { app, hits } = buildGateApp({ enabled: false });
const res = await requestOnce(app, "POST", "/login", VIOLATING_HEADERS);
assert.strictEqual(res.status, 200, "the gate must not respond when disabled");
assert.deepStrictEqual(hits, ["post-login"], "next() ran — the route handled the request");
assert.ok(!res.headers["cache-control"], "the disabled gate adds nothing to the response");
});
test("gate disabled: needs no predicate at all — the default-off wiring is inert", async () => {
const app = express();
app.use((req, _res, next) => {
req.connection = { remoteAddress: UNTRUSTED_PEER };
req.socket = { remoteAddress: UNTRUSTED_PEER };
next();
});
app.use(createRemoteProxyTrustGate({ enabled: false }));
app.post("/login", (req, res) => res.status(200).json({ ok: true }));
const res = await requestOnce(app, "POST", "/login", VIOLATING_HEADERS);
assert.strictEqual(res.status, 200);
});
test("hot path: disabled never calls the predicate; enabled + clean calls it exactly once", async () => {
let calls = 0;
const spy = () => { calls += 1; return false; };
const disabled = buildGateApp({ enabled: false, spy });
await requestOnce(disabled.app, "POST", "/login", VIOLATING_HEADERS);
assert.strictEqual(calls, 0, "disabled: one closure read + next(), no predicate call");
calls = 0;
const enabled = buildGateApp({ enabled: true, spy });
await requestOnce(enabled.app, "POST", "/login", VIOLATING_HEADERS);
assert.strictEqual(calls, 1, "enabled + clean: exactly one predicate call per request");
});
test("gate enabled + violation: POST /login refused — 503, generic body, NO proxy/trust detail", async () => {
const { app, hits } = buildGateApp({ enabled: true });
const res = await requestOnce(app, "POST", "/login", VIOLATING_HEADERS);
assert.strictEqual(res.status, 503, "house pre-auth refusal status (maintenance-gate precedent)");
assert.strictEqual(res.headers["cache-control"], "no-store");
assert.ok(res.body.includes("Service temporarily unavailable. Try again later."), "path-free generic body");
for (const forbidden of ["proxy", "forwarded", "xfp", "trust", "secure", "cookie"]) {
assert.ok(!new RegExp(forbidden, "i").test(res.body), `the body must not leak "${forbidden}" detail to an unauthenticated caller`);
}
assert.deepStrictEqual(hits, [], "the credential handler never ran");
});
test("gate enabled + violation: JSON-negotiating client gets the JSON refusal shape", async () => {
const { app } = buildGateApp({ enabled: true });
const res = await requestOnce(app, "POST", "/login", { ...VIOLATING_HEADERS, Accept: "application/json" });
assert.strictEqual(res.status, 503);
assert.match(String(res.headers["content-type"] || ""), /json/);
const parsed = JSON.parse(res.body);
assert.deepStrictEqual(parsed, { ok: false, error: "Service temporarily unavailable. Try again later." });
});
test("gate enabled + violation: GET /login passes (only credential POSTs are refused)", async () => {
const { app, hits } = buildGateApp({ enabled: true });
const res = await requestOnce(app, "GET", "/login", VIOLATING_HEADERS);
assert.strictEqual(res.status, 200);
assert.deepStrictEqual(hits, ["get-login"]);
});
test("gate enabled + violation: POST /api/captcha/verify refused", async () => {
const { app, hits } = buildGateApp({ enabled: true });
const res = await requestOnce(app, "POST", "/api/captcha/verify", VIOLATING_HEADERS);
assert.strictEqual(res.status, 503);
assert.ok(res.body.includes("Service temporarily unavailable. Try again later."));
assert.deepStrictEqual(hits, [], "the captcha-verify handler never ran");
});
test("gate enabled + violation: non-credential surfaces pass (POST /other)", async () => {
const { app, hits } = buildGateApp({ enabled: true });
const res = await requestOnce(app, "POST", "/other", VIOLATING_HEADERS);
assert.strictEqual(res.status, 200);
assert.deepStrictEqual(hits, ["other"]);
});
test("gate enabled + violation: router-equivalent path parity (trailing slash, case-fold)", async () => {
const { app, hits } = buildGateApp({ enabled: true });
// Express mounts strict:false + caseSensitive:false: ONE trailing slash and
// case variants reach the real route, so the gate must guard them too.
const slashed = await requestOnce(app, "POST", "/login/", VIOLATING_HEADERS);
assert.strictEqual(slashed.status, 503, "/login/ reaches the real POST /login route — the gate refuses it too");
const folded = await requestOnce(app, "POST", "/LOGIN", VIOLATING_HEADERS);
assert.strictEqual(folded.status, 503, "/LOGIN reaches the real POST /login route — the gate refuses it too");
const captchaSlashed = await requestOnce(app, "POST", "/api/captcha/verify/", VIOLATING_HEADERS);
assert.strictEqual(captchaSlashed.status, 503, "/api/captcha/verify/ likewise");
// Two slashes: the ROUTER 404s this spelling (verified against express in
// adpanel:stealth-login-trailing-slash), so guarding it would diverge from
// the route set — it must pass the gate (and fall through here).
const doubleSlashed = await requestOnce(app, "POST", "/login//", VIOLATING_HEADERS);
assert.strictEqual(doubleSlashed.status, 200);
assert.deepStrictEqual(hits, ["fallthrough"]);
});
test("gate enabled + NO violation: everything passes (plain HTTP client, trusted proxy)", async () => {
const plain = buildGateApp({ enabled: true }); // no XFP header
const plainRes = await requestOnce(plain.app, "POST", "/login", {});
assert.strictEqual(plainRes.status, 200);
assert.deepStrictEqual(plain.hits, ["post-login"]);
const trusted = buildGateApp({ enabled: true, peer: "127.0.0.1" }); // loopback proxy appending XFP
const trustedRes = await requestOnce(trusted.app, "POST", "/login", VIOLATING_HEADERS);
assert.strictEqual(trustedRes.status, 200, "a trusted TLS proxy appending XFP is the correct deployment");
assert.deepStrictEqual(trusted.hits, ["post-login"]);
});
test("factory: enabled without a violationOf predicate fails fast at creation (boot, not per request)", () => {
assert.throws(() => createRemoteProxyTrustGate({ enabled: true }), /violationOf/);
const inert = createRemoteProxyTrustGate({ enabled: false });
assert.strictEqual(typeof inert, "function", "default-off needs no predicate — wiring stays inert");
});
// ---------- (c) source pins: one condition, one mount, knob default ----------
test("source pin: the warn DELEGATES to the shared predicate — the old inline condition no longer exists in warnRemoteProxyMisconfigOnce", () => {
const warnFn = sliceBlock(indexSource, "function warnRemoteProxyMisconfigOnce(req)");
assert.ok(warnFn.includes("if (!isRemoteProxyTrustViolationRequest(req)) return;"),
"the warn must call the shared predicate");
for (const token of [
'req.headers && req.headers["x-forwarded-proto"]',
'claimedProto !== "https"',
"getDirectRemoteIp(req)",
"isTrustedProxyIp(directPeer)",
]) {
assert.strictEqual(warnFn.includes(token), false,
`the old inline condition token must NOT remain in the warn helper: ${token}`);
}
// The warn's one-time latch is untouched: guard first, flag before the warn.
assert.ok(warnFn.startsWith("function warnRemoteProxyMisconfigOnce(req) {\n if (remoteProxyMisconfigWarningPrinted) return;"),
"the flag guard is still the FIRST statement");
const latchAt = warnFn.indexOf("remoteProxyMisconfigWarningPrinted = true;");
const warnAt = warnFn.indexOf("console.warn(");
assert.ok(latchAt > -1 && warnAt > latchAt, "the flag is still set BEFORE the console.warn");
assert.strictEqual(warnFn.includes("console.warn(", warnAt + 1), false, "exactly ONE console.warn in the helper");
});
test("source pin: the predicate is the ONE home of the condition — no second copy anywhere", () => {
const marker = "function isRemoteProxyTrustViolationRequest(req)";
assert.strictEqual(indexSource.indexOf(marker), indexSource.lastIndexOf(marker),
"the predicate must be defined exactly once in index.js");
const predicateFn = sliceBlock(indexSource, marker);
assert.ok(predicateFn.includes('claimedProto !== "https"') && predicateFn.includes("getDirectRemoteIp(req)") && predicateFn.includes("isTrustedProxyIp(directPeer)"),
"the predicate carries the exact warn condition");
assert.strictEqual(indexSource.split('claimedProto !== "https"').length - 1, 1,
"exactly ONE copy of the condition in index.js (the predicate)");
assert.ok(!gateSource.includes("x-forwarded-proto") && !gateSource.includes("claimedProto") && !gateSource.includes("isTrustedProxyIp"),
"the gate module must not carry a second copy of the condition");
assert.ok(!gateSource.includes("remoteProxyMisconfigWarningPrinted"),
"the gate never shares or resets the warn's one-time latch");
});
test("source pin: the gate is mounted between the Secure-sync/warn middleware and the preauth TTL middleware", () => {
const secureSyncAt = indexSource.indexOf("// Upgrade-only Secure sync:");
const gateAt = indexSource.indexOf("app.use(createRemoteProxyTrustGate(");
const preauthAt = indexSource.indexOf("app.use(createPreauthSessionTtlMiddleware(");
for (const [name, at] of [["secure-sync middleware", secureSyncAt], ["gate mount", gateAt], ["preauth TTL mount", preauthAt]]) {
assert.ok(at > -1, `${name} must exist`);
}
assert.ok(secureSyncAt < gateAt && gateAt < preauthAt,
"the gate must sit immediately after the Secure-sync/warn middleware and before the preauth TTL");
assert.strictEqual(indexSource.indexOf("app.use(createRemoteProxyTrustGate("), indexSource.lastIndexOf("app.use(createRemoteProxyTrustGate("),
"exactly ONE mount");
});
test("source pin: the env knob defaults false through parseBoolean — booleans only, no raw parseInt", () => {
assert.ok(indexSource.includes("const REMOTE_PROXY_REQUIRE_TRUST = parseBoolean(process.env.REMOTE_PROXY_REQUIRE_TRUST, false);"),
"the knob must default false via the shared parseBoolean");
assert.strictEqual(indexSource.includes("parseInt(process.env.REMOTE_PROXY_REQUIRE_TRUST"), false,
"no raw parseInt for the boolean knob (adpanel:env-int-clamp discipline)");
assert.ok(indexSource.includes("if (REMOTE_PROXY_REQUIRE_TRUST) {"), "the enforcement boot advisory is gated on the knob");
assert.ok(indexSource.includes("violationOf: isRemoteProxyTrustViolationRequest"),
"the mount hands the gate the ONE shared predicate");
});
test("source pin: the gate module carries the constraint comment and a generic refusal message", () => {
assert.ok(gateSource.includes("// adpanel:remote-proxy-trust-gate — OPT-IN (REMOTE_PROXY_REQUIRE_TRUST=1) enforcement"),
"the constraint comment must be present");
const messageMatch = gateSource.match(/const REFUSAL_MESSAGE = "([^"]+)";/);
assert.ok(messageMatch, "the refusal message is one named constant");
const message = messageMatch[1];
for (const forbidden of ["proxy", "forwarded", "trust", "secure", "cookie", "sid"]) {
assert.ok(!new RegExp(forbidden, "i").test(message), `the refusal message must not leak "${forbidden}" detail`);
}
});
// ---------- (d) the second consumer: remember-credential ISSUANCE ----------
//
// The gate refuses credential PROCESSING (the two POSTs); the remember
// machinery also MINTS/REFRESHES a 365-day 2FA-skipping credential on paths
// those POSTs never reach. Under the same knob, those paths withhold the
// credential while the misconfig signature is present. Locked here:
// - remoteProxyTrustBlocksRememberIssuance (index.js) is the ONE
// composition of the knob + the predicate; no site re-derives it.
// - restoreRememberedLogin fails CLOSED (stale cookie cleared, no session
// bind, silent false — the exact shape of its existing failure paths)
// BEFORE any tombstone/regenerate/rotate/bind/save choreography.
// - ensureRememberLoginCookie (authenticated silent refresh) and
// setRememberLoginCookie (the mint choke point: the four interactive
// re-issues) SKIP with NOTHING mutated.
// - Default OFF is byte-identical on every path (the ledger's warn-only
// default pin), and opt-in + no-violation is byte-identical too.
// - The credential POSTs' mint paths are NOT double-gated: the routes
// register after the gate mount, so they never execute under the
// signature.
// String-aware brace-balanced extraction (the remember tests' extractBlock
// shape): the restore body embeds template literals, so a naive counter is
// not safe here.
function extractBalancedBlock(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker not found: ${startMarker}`);
let i = start + startMarker.length;
let depth;
if (startMarker.endsWith("{")) {
depth = 1;
} else {
while (i < source.length && /\s/.test(source[i])) i += 1;
assert.ok(i < source.length && source[i] === "{", `no opening brace after: ${startMarker}`);
depth = 1;
}
let inString = null;
while (i < source.length && depth > 0) {
i += 1;
const ch = source[i];
if (inString) {
if (ch === "\\") { i += 1; continue; }
if (ch === inString) inString = null;
continue;
}
if (ch === "/" && source[i + 1] === "/") {
while (i < source.length && source[i] !== "\n") i += 1;
continue;
}
if (ch === "/" && source[i + 1] === "*") {
i += 2;
while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i += 1;
i += 1;
continue;
}
if (ch === '"' || ch === "'" || ch === "`") inString = ch;
else if (ch === "{") depth += 1;
else if (ch === "}") depth -= 1;
}
assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`);
return source.slice(start, i + 1);
}
const RESTORE_SOURCE = extractBalancedBlock(indexSource, "async function restoreRememberedLogin(req, res) {");
const ENSURE_SOURCE = extractBalancedBlock(indexSource, "async function ensureRememberLoginCookie(req, res, user = null) {");
const SETCOOKIE_SOURCE = extractBalancedBlock(indexSource, "function setRememberLoginCookie(req, res, user, options = {}) {");
// The REAL second consumer: the extracted blocker composed in one vm context
// with the REAL extracted predicate and the peer-trust helpers — the same
// extraction discipline as buildRealViolationOf above.
function buildRealIssuanceBlocker({ requireTrust } = {}) {
const helpers = indexSource.slice(
indexSource.indexOf("const TRUSTED_PROXY_IPS = new Set("),
endIndexOfBlock(indexSource, "function getLastForwardedValue(value, normalizer")
);
const predicate = sliceBlock(indexSource, "function isRemoteProxyTrustViolationRequest(req)");
const blocker = sliceBlock(indexSource, "function remoteProxyTrustBlocksRememberIssuance(req)");
const context = vm.createContext({
net: require("node:net"),
console: { log: () => {}, warn: () => {}, error: () => {} },
process: { env: {} },
REMOTE_PROXY_REQUIRE_TRUST: requireTrust === true,
});
vm.runInContext([helpers, predicate, blocker].join("\n"), context, { filename: "index.js#remoteProxyTrustBlocksRememberIssuance" });
const fn = context.remoteProxyTrustBlocksRememberIssuance;
assert.strictEqual(typeof fn, "function", "issuance-blocker extraction failed");
return fn;
}
test("source pin: the issuance blocker is the ONE composition of the knob and the predicate", () => {
const marker = "function remoteProxyTrustBlocksRememberIssuance(req)";
assert.strictEqual(indexSource.indexOf(marker), indexSource.lastIndexOf(marker),
"the blocker must be defined exactly once in index.js");
const blockerFn = sliceBlock(indexSource, marker);
assert.ok(blockerFn.includes("isRemoteProxyTrustViolationRequest(req)"),
"the blocker delegates to the ONE predicate — never a second copy of the condition");
assert.ok(blockerFn.includes("REMOTE_PROXY_REQUIRE_TRUST"),
"the blocker respects the same knob const");
const conjunction = "REMOTE_PROXY_REQUIRE_TRUST === true && isRemoteProxyTrustViolationRequest(req)";
assert.strictEqual(indexSource.split(conjunction).length - 1, 1,
"exactly ONE copy of the composition in index.js — no issuance site re-derives the condition");
});
test("source pin: the gate module documents the second consumer without implementing it", () => {
assert.ok(gateSource.includes("SECOND CONSUMER"),
"the module comment must document the issuance consumer");
assert.ok(gateSource.includes("remoteProxyTrustBlocksRememberIssuance"),
"the module comment must name the ONE helper");
assert.strictEqual(gateSource.includes("function remoteProxyTrustBlocksRememberIssuance"), false,
"the helper lives in index.js — the module only documents the consumer");
});
test("the REAL blocker composes BOTH legs: opt-in AND violation (default OFF never blocks)", () => {
const on = buildRealIssuanceBlocker({ requireTrust: true });
const off = buildRealIssuanceBlocker({ requireTrust: false });
assert.strictEqual(on(probeReq({ xfp: "https" })), true, "opt-in + violation → blocked");
assert.strictEqual(on(probeReq({})), false, "opt-in + no violation → not blocked");
assert.strictEqual(on(probeReq({ peer: "127.0.0.1", xfp: "https" })), false, "opt-in + trusted TLS proxy → not blocked (the correct deployment)");
assert.strictEqual(off(probeReq({ xfp: "https" })), false,
"knob OFF — the ledger's default posture is NEVER blocked, even on the violation signature");
});
// Restore-harness constants (modeled on the sibling remember-restore test's
// sandbox discipline; the blocker here is the REAL extracted helper).
const LIVE_RESTORE_PARSED = { v: 2, uid: "1", iat: 1700000000000, exp: 4102444800000, fp: "fp", jti: "remember-id-restore" };
const LIVE_RESTORE_USER = { id: 1, email: "user@example.test", password: "x", suspended: false, session_epoch: 3 };
function buildIssuanceRestoreHarness({ requireTrust, peer = UNTRUSTED_PEER, xfp = "https", authenticated = false } = {}) {
const calls = { rotate: 0, clearState: 0, clearCookie: 0, markFresh: 0, tombstone: 0, regen: 0, saves: 0 };
const events = [];
const session = {
regenerate: (cb) => { calls.regen += 1; events.push("regenerate"); cb(null); },
save: (cb) => { calls.saves += 1; events.push("save"); cb(null); },
};
if (authenticated) session.user = LIVE_RESTORE_USER.email;
const req = {
cookies: { "adpanel.remember": "tok" },
session,
sessionID: "restore-sid-1",
headers: xfp === undefined ? {} : { "x-forwarded-proto": xfp },
connection: { remoteAddress: peer, encrypted: false },
socket: { remoteAddress: peer },
secure: false,
};
const res = { cookies: [] }; // records MINTS only — a clearCookie is not an issuance
res.cookie = (name) => { events.push(`setCookie:${name}`); res.cookies.push(name); };
const sandbox = {
console: { log: () => {}, warn: () => {} },
REMEMBER_LOGIN_COOKIE_NAME: "adpanel.remember",
remoteProxyTrustBlocksRememberIssuance: buildRealIssuanceBlocker({ requireTrust }),
readRememberLoginToken: () => LIVE_RESTORE_PARSED,
securityLog: (msg) => events.push(`log:${String(msg)}`),
loginAuditRecorder: { recordSuccessfulLoginAudit: ({ method }) => events.push(`audit:${String(method)}`) },
findUserById: async () => LIVE_RESTORE_USER,
// adpanel:credential-generation — the REAL shared predicate: the restore
// body's staleness re-verify calls it on (snapshot epoch, fresh row
// epoch); both harness reads return the same row, so every byte-identity
// pin below stays on the pre-existing success path.
credentialGenerationMismatch: require("../utils/session-account-binding").credentialGenerationMismatch,
...require("../utils/remember-login-completion"),
isSessionSidRevoked: async () => false,
safeCompare: () => true,
getRememberLoginFingerprint: () => "fp",
getRememberLoginLegacyCutoff: () => 0,
isManagedRememberLoginToken: () => true,
revokeRememberLoginsForUser: async () => { events.push("revokeUser"); },
sessionCarriesProtectedPendingAuthState: () => false,
getSessionDisplayId: (id) => `sid:${id}`,
writeRevokedSidTombstone: async (sid) => { calls.tombstone += 1; events.push(`tombstone:${sid}`); return true; },
clearRememberLoginSessionState: () => { calls.clearState += 1; events.push("clearState"); },
clearRememberLoginCookie: () => { calls.clearCookie += 1; events.push("clearCookie"); },
rotateRememberLoginCookie: async () => { calls.rotate += 1; events.push("rotate"); return 4102444800000; },
buildBrowserSessionAuditFromRequest: () => ({ rememberLoginId: LIVE_RESTORE_PARSED.jti }),
markRememberLoginSessionFresh: () => { calls.markFresh += 1; events.push("markFresh"); },
withTimeout: (p) => Promise.resolve(p),
req,
};
vm.createContext(sandbox);
const fn = vm.runInContext(`(${RESTORE_SOURCE})`, sandbox, { filename: "restore-issuance-sandbox.js" });
return { fn, calls, events, req, res, session };
}
// The pre-existing success path's exact event shape (regenerate → rotate →
// hygiene → markFresh → save → audit): every byte-identity pin below asserts
// against THIS list, so "unchanged" is not a judgement call.
const RESTORE_SUCCESS_EVENTS = ["log:remember-restore attempt", "regenerate", "rotate", "clearState", "markFresh", "save", "audit:remember-restore"];
test("issuance: opt-in + violation + valid remember cookie — restore refused FAIL-CLOSED, no cookie, no session", async () => {
const { fn, calls, events, req, res, session } = buildIssuanceRestoreHarness({ requireTrust: true });
const ok = await fn(req, res);
assert.strictEqual(ok, false, "the restore is refused (silent false — the middleware's unauthenticated fall-through shape)");
assert.deepStrictEqual(events, ["log:remember-restore attempt", "clearState", "clearCookie"],
"the attempt stays observable (restore-attempt-observability unchanged), then the EXACT failure-path shape: state cleared, stale cookie cleared — and NOTHING else");
assert.strictEqual(res.cookies.length, 0, "NO remember cookie is set — the only Set-Cookie path (the rotation) never ran");
assert.strictEqual(calls.rotate, 0, "no rotation — no registry mint, no fresh 365d credential");
assert.strictEqual(calls.tombstone, 0, "the tombstone choreography never started");
assert.strictEqual(calls.regen, 0, "the regenerate never started");
assert.strictEqual(calls.markFresh, 0, "no freshness markers written");
assert.ok(!events.some((e) => e.startsWith("audit:")), "a refused restore records NO durable login row (success-only audit, unchanged)");
assert.strictEqual(session.user, undefined, "NO session established — the 2FA-skipping bind never happened");
});
test("issuance: opt-in + NO violation — restore works byte-identically to the pre-existing success path", async () => {
const { fn, calls, events, req, res, session } = buildIssuanceRestoreHarness({ requireTrust: true, xfp: "" });
const ok = await fn(req, res);
assert.strictEqual(ok, true, "without the signature the restore completes");
assert.deepStrictEqual(events, RESTORE_SUCCESS_EVENTS,
"the success choreography is byte-identical (regenerate → rotate → hygiene → markFresh → save → audit)");
assert.strictEqual(res.cookies.length, 0, "the harness stubs the rotation's Set-Cookie (pinned by the rotation suites) — the restore itself still completed");
assert.strictEqual(session.user, LIVE_RESTORE_USER.email, "the session is bound");
assert.strictEqual(calls.clearCookie, 0, "no hygiene clears on success");
});
test("issuance: opt-in + violation from a TRUSTED TLS proxy — restore works (the correct deployment)", async () => {
const { fn, events, req, res, session } = buildIssuanceRestoreHarness({ requireTrust: true, peer: "127.0.0.1" });
const ok = await fn(req, res);
assert.strictEqual(ok, true, "a loopback TLS proxy appending XFP: https is exactly the deployment the advisory asks for");
assert.deepStrictEqual(events, RESTORE_SUCCESS_EVENTS, "byte-identical success path");
assert.strictEqual(session.user, LIVE_RESTORE_USER.email, "the session is bound");
});
test("issuance: DEFAULT OFF + violation — byte-identical default posture (the ledger's warn-only pin)", async () => {
// The misconfig signature is present, but the knob is unset: the refusal
// must not fire anywhere. This is the byte-identity proof that the opt-in
// ledger default (remote-proxy-misconfig-warning, warn-only) is untouched.
const { fn, calls, events, req, res, session } = buildIssuanceRestoreHarness({ requireTrust: false });
const ok = await fn(req, res);
assert.strictEqual(ok, true, "default OFF: the violating request restores exactly as before");
assert.deepStrictEqual(events, RESTORE_SUCCESS_EVENTS, "byte-identical success path under the default");
assert.strictEqual(calls.clearCookie, 0, "no hygiene clears under the default");
assert.strictEqual(session.user, LIVE_RESTORE_USER.email, "the session is bound under the default");
});
test("issuance: middleware level — the refused restore continues UNAUTHENTICATED via next(), no error", async () => {
// The "same response shape" pin end to end: the remember middleware's
// normal fall-through for a false restore is next() with no error, so the
// route serves its unauthenticated response — identical to every existing
// restore failure. Extracted with the sibling test's anchor discipline.
const MW_ANCHOR = "await restoreRememberedLogin(req, res);";
const mwAnchorIdx = indexSource.indexOf(MW_ANCHOR);
const mwStartIdx = indexSource.lastIndexOf("app.use(async (req, res, next) => {", mwAnchorIdx);
const MIDDLEWARE_SRC = extractBalancedBlock(indexSource.slice(mwStartIdx), "app.use(async (req, res, next) => {") + ");";
const { fn, events, req, res } = buildIssuanceRestoreHarness({ requireTrust: true });
const sandbox = {
console: { log: () => {}, warn: () => {} },
app: { use: (mw) => { sandbox.__mw = mw; } },
req,
ensureRememberLoginStoreReady: async () => {},
ensureRememberLoginRegistryFresh: async () => {},
ensureRememberLoginCookie: async () => { events.push("ensure"); },
restoreRememberedLogin: fn,
clearRememberLoginSessionState: () => { events.push("catch-clearState"); },
clearRememberLoginCookie: () => { events.push("catch-clearCookie"); },
revokeRememberLoginRegistryEntry: async () => { events.push("catch-revoke"); },
writeRevokedSidTombstone: async () => { events.push("catch-tombstone"); },
consoleWarnCollector: [],
};
vm.createContext(sandbox);
vm.runInContext(MIDDLEWARE_SRC, sandbox, { filename: "remember-mw-issuance-sandbox.js" });
const nextCalls = [];
await sandbox.__mw(req, res, (...a) => nextCalls.push(a));
assert.strictEqual(nextCalls.length, 1, "the middleware continues exactly once");
assert.deepStrictEqual(nextCalls[0], [], "next() takes NO error argument — the refusal is a normal unauthenticated fall-through, not a 500");
assert.deepStrictEqual(events, ["log:remember-restore attempt", "clearState", "clearCookie"],
"the middleware's catch hygiene (clear/revoke/tombstone) does NOT fire — the refusal is a plain false return, not an exception path");
});
// ---------- (d.2) the authenticated silent refresh skips entirely ----------
const LIVE_ENSURE_PARSED = { v: 2, uid: "1", iat: 1700000000000, exp: 4102444800000, fp: "fp", jti: "remember-id-restore" };
const LIVE_ENSURE_USER = { id: 1, email: "user@example.test", password: "x", suspended: false, session_epoch: 3 };
function buildEnsureHarness({ requireTrust, peer = UNTRUSTED_PEER, xfp = "https" } = {}) {
const calls = { parse: 0, rotate: 0, clearState: 0, clearCookie: 0, markFresh: 0, findUser: 0 };
const req = {
cookies: { "adpanel.remember": "tok" },
session: {
user: LIVE_ENSURE_USER.email,
rememberLoginId: LIVE_ENSURE_PARSED.jti,
rememberLoginCheckedAt: 0,
rememberLoginExpiresAt: 0,
},
sessionID: "sess-1",
headers: xfp === undefined ? {} : { "x-forwarded-proto": xfp },
connection: { remoteAddress: peer, encrypted: false },
socket: { remoteAddress: peer },
secure: false,
};
const sandbox = {
REMEMBER_LOGIN_COOKIE_NAME: "adpanel.remember",
remoteProxyTrustBlocksRememberIssuance: buildRealIssuanceBlocker({ requireTrust }),
readRememberLoginToken: () => { calls.parse += 1; return LIVE_ENSURE_PARSED; },
ensureRememberLoginSessionId: (r) => r.session.rememberLoginId,
isManagedRememberLoginToken: () => true,
rememberLoginNeedsRefresh: () => true,
canSkipRememberLoginValidation: () => false,
rememberLoginValidationIntervalFresh: () => false,
markRememberLoginSessionFresh: () => { calls.markFresh += 1; },
findUserByEmail: async () => { calls.findUser += 1; return LIVE_ENSURE_USER; },
clearRememberLoginSessionState: () => { calls.clearState += 1; },
clearRememberLoginCookie: () => { calls.clearCookie += 1; },
rotateRememberLoginCookie: async () => { calls.rotate += 1; return 4102444800000; },
req,
};
vm.createContext(sandbox);
const fn = vm.runInContext(`(${ENSURE_SOURCE})`, sandbox, { filename: "ensure-issuance-sandbox.js" });
return { fn, calls, req };
}
test("issuance: opt-in + violation — the authenticated silent refresh SKIPS with nothing mutated", async () => {
const { fn, calls, req } = buildEnsureHarness({ requireTrust: true });
await fn(req, {}, LIVE_ENSURE_USER);
assert.strictEqual(calls.parse, 0, "the skip is the first statement — not even a cookie parse runs");
assert.strictEqual(calls.rotate, 0, "no rotation — no registry mint, no Set-Cookie for a refreshed 365d credential");
assert.strictEqual(calls.clearCookie, 0, "a WITHHOLD is not a clear — the presented credential keeps its anchored lifetime");
assert.strictEqual(calls.clearState, 0, "no session-state writes");
assert.strictEqual(calls.markFresh, 0, "no freshness markers written");
assert.strictEqual(calls.findUser, 0, "no user lookup either");
assert.strictEqual(req.session.user, LIVE_ENSURE_USER.email, "the PRE-EXISTING session continues (the documented residual)");
});
test("issuance: opt-in + NO violation — the silent refresh runs exactly as before", async () => {
const { fn, calls, req } = buildEnsureHarness({ requireTrust: true, xfp: "" });
await fn(req, {}, LIVE_ENSURE_USER);
assert.strictEqual(calls.rotate, 1, "the refresh rotates as always");
assert.strictEqual(calls.markFresh, 1, "the freshness markers are written as always");
assert.strictEqual(calls.clearCookie, 0, "no hygiene clears on a clean refresh");
});
test("issuance: DEFAULT OFF + violation — the silent refresh runs exactly as before (the ledger default pin)", async () => {
const { fn, calls, req } = buildEnsureHarness({ requireTrust: false });
await fn(req, {}, LIVE_ENSURE_USER);
assert.strictEqual(calls.rotate, 1, "default OFF: the violating request refreshes exactly as before");
assert.strictEqual(calls.markFresh, 1, "the freshness markers are written as always");
});
// ---------- (d.3) the mint choke point skips with NOTHING mutated ----------
function buildMintHarness({ requireTrust, peer = UNTRUSTED_PEER, xfp = "https" } = {}) {
const events = [];
const req = {
// The interactive re-issues run AFTER a user-wide revocation, so the
// session's rememberLoginId is a just-revoked identifier — exactly the
// state the real callers present.
session: { rememberLoginId: "stale-revoked-id", browserSessionAudit: { rememberLoginId: "stale-revoked-id" } },
headers: xfp === undefined ? {} : { "x-forwarded-proto": xfp },
connection: { remoteAddress: peer, encrypted: false },
socket: { remoteAddress: peer },
secure: false,
};
const res = { cookies: [] };
res.cookie = (name) => { events.push(`setCookie:${name}`); res.cookies.push(name); };
const sandbox = {
REMEMBER_LOGIN_COOKIE_NAME: "adpanel.remember",
REMEMBER_LOGIN_MAX_AGE_MS: 31536000000,
remoteProxyTrustBlocksRememberIssuance: buildRealIssuanceBlocker({ requireTrust }),
issueRememberLoginToken: (r) => {
if (!r?.session?.rememberLoginId) r.session.rememberLoginId = "minted-1";
events.push(`issue:${r.session.rememberLoginId}`);
return `token:${r.session.rememberLoginId}`;
},
getRememberLoginCookieOptions: () => ({ httpOnly: true, path: "/" }),
events,
req,
res,
};
vm.createContext(sandbox);
const fn = vm.runInContext(`(${SETCOOKIE_SOURCE})`, sandbox, { filename: "mint-issuance-sandbox.js" });
return { fn, events, req, res };
}
const MINT_USER = { id: 42, email: "user@example.test", password: "hashed" };
test("issuance: opt-in + violation — the interactive re-issue mint is withheld, mutating NOTHING", async () => {
const { fn, events, req, res } = buildMintHarness({ requireTrust: true });
const out = fn(req, res, MINT_USER, { forceFreshId: true });
assert.strictEqual(out, undefined, "nothing was issued");
assert.deepStrictEqual(events, [], "no issue, no Set-Cookie — the credential is withheld");
assert.strictEqual(res.cookies.length, 0, "NO remember cookie set");
assert.strictEqual(req.session.rememberLoginId, "stale-revoked-id",
"the skip deletes NOTHING — the just-revoked id stays exactly as the caller's own revocation left it (no forceFreshId deletion before the skip)");
assert.strictEqual(req.session.browserSessionAudit.rememberLoginId, "stale-revoked-id", "the audit copy is untouched too");
});
test("issuance: opt-in + NO violation — the mint runs exactly as before", async () => {
const { fn, events, req, res } = buildMintHarness({ requireTrust: true, xfp: "" });
const out = fn(req, res, MINT_USER);
assert.strictEqual(typeof out, "number", "the expiry contract is unchanged");
assert.deepStrictEqual(events, ["issue:stale-revoked-id", "setCookie:adpanel.remember"], "issue then Set-Cookie, byte-identical order");
assert.strictEqual(res.cookies.length, 1, "the cookie is issued");
});
test("issuance: DEFAULT OFF + violation — the mint runs exactly as before (the ledger default pin)", async () => {
const { fn, events, req, res } = buildMintHarness({ requireTrust: false });
const out = fn(req, res, MINT_USER);
assert.strictEqual(typeof out, "number", "default OFF: the violating request mints exactly as before");
assert.deepStrictEqual(events, ["issue:stale-revoked-id", "setCookie:adpanel.remember"], "byte-identical mint under the default");
assert.strictEqual(res.cookies.length, 1, "the cookie is issued under the default");
});
// ---------- (d.4) source pins: placement + the no-double-gate rule ----------
test("source pin: restore's refusal is fail-closed and precedes ALL of its choreography", () => {
const refusalAt = RESTORE_SOURCE.indexOf("if (remoteProxyTrustBlocksRememberIssuance(req)) {");
assert.ok(refusalAt > -1, "the restore carries the issuance refusal");
const parsedAt = RESTORE_SOURCE.indexOf("const parsed = readRememberLoginToken(rawToken);", refusalAt);
assert.ok(parsedAt > refusalAt, "the refusal precedes even the token parse");
const refusalBody = RESTORE_SOURCE.slice(refusalAt, parsedAt);
assert.ok(refusalBody.includes("clearRememberLoginSessionState(req);"), "the stale state is cleared — the failure-path shape");
assert.ok(refusalBody.includes("clearRememberLoginCookie(req, res);"), "the stale cookie is cleared — the failure-path shape");
assert.ok(refusalBody.includes("return false;"), "silent false — the middleware continues unauthenticated (the failure paths' response shape)");
assert.ok(!/revoke/i.test(refusalBody), "the refusal is a WITHHOLD of issuance, not a revocation — no registry deletion beyond the failure-path shape");
// Order is load-bearing: after the attempt log (a refused restore stays
// observable), before every mutating step of the choreography.
const cookielessAt = RESTORE_SOURCE.indexOf("if (!rawToken) return false;");
const attemptAt = RESTORE_SOURCE.indexOf('securityLog("remember-restore attempt", req);');
const pendingAt = RESTORE_SOURCE.indexOf("sessionCarriesProtectedPendingAuthState(req.session)");
const regenAt = RESTORE_SOURCE.indexOf('"session-regenerate-timeout"');
const rotateAt = RESTORE_SOURCE.indexOf("await rotateRememberLoginCookie(req, res, user, parsed);");
for (const [name, at] of [["cookieless early-return", cookielessAt], ["attempt log", attemptAt]]) {
assert.ok(at > -1 && at < refusalAt, `the refusal must sit after the ${name}`);
}
for (const [name, at] of [["pending-state tombstone condition", pendingAt], ["bounded regenerate", regenAt], ["rotation", rotateAt]]) {
assert.ok(at > refusalAt, `the refusal must precede the ${name} — fail fast, nothing mutated`);
}
});
test("source pin: the authenticated refresh skip is the function's FIRST statement", () => {
const SIGNATURE = "async function ensureRememberLoginCookie(req, res, user = null) {";
const skipAt = ENSURE_SOURCE.indexOf("if (remoteProxyTrustBlocksRememberIssuance(req)) return;");
assert.ok(skipAt > -1, "the refresh carries the issuance skip");
const preSkip = ENSURE_SOURCE.slice(SIGNATURE.length, skipAt).replace(/\/\/[^\n]*/g, "").trim();
assert.strictEqual(preSkip, "", "only the constraint comment precedes the skip — no statement runs before it under the signature");
assert.ok(skipAt < ENSURE_SOURCE.indexOf("readRememberLoginToken("), "no parse before the skip");
assert.ok(skipAt < ENSURE_SOURCE.indexOf("rotateRememberLoginCookie("), "no rotation before the skip");
});
test("source pin: the mint choke point skips before the flag/mint machinery", () => {
const SIGNATURE = "function setRememberLoginCookie(req, res, user, options = {}) {";
const skipAt = SETCOOKIE_SOURCE.indexOf("if (remoteProxyTrustBlocksRememberIssuance(req)) return;");
assert.ok(skipAt > -1, "the mint carries the issuance skip");
// The slice starts after the FULL signature — the parameter default `= {}`
// contains the first brace, so a naive indexOf("{") would land inside it.
const preSkip = SETCOOKIE_SOURCE.slice(SIGNATURE.length, skipAt).replace(/\/\/[^\n]*/g, "").replace(/\s+/g, " ").trim();
assert.strictEqual(preSkip, 'if (!req?.session || !res) return;',
"only the existing guard precedes the skip — the ONE issuance choke point starts with its refusal");
assert.ok(skipAt < SETCOOKIE_SOURCE.indexOf("// adpanel:remember-fresh-reissue"), "the skip precedes the forceFreshId machinery");
assert.ok(skipAt < SETCOOKIE_SOURCE.indexOf("delete req.session.rememberLoginId;"), "nothing is deleted before the skip (the skip mutates nothing)");
assert.ok(skipAt < SETCOOKIE_SOURCE.indexOf("issueRememberLoginToken("), "no registry mint before the skip");
assert.ok(skipAt < SETCOOKIE_SOURCE.indexOf("res.cookie("), "no Set-Cookie before the skip");
});
test("source pin: NO route-level double gate — the credential POSTs register AFTER the gate mount", () => {
// Their binder mint paths never execute under the signature (the gate
// refuses the POSTs upstream), so gating them again would be dead code;
// the mint helper's skip covers only the paths the gate cannot reach.
const gateAt = indexSource.indexOf("app.use(createRemoteProxyTrustGate(");
const captchaAt = indexSource.indexOf('app.post("/api/captcha/verify"');
const loginAt = indexSource.indexOf('app.post("/login"');
for (const [name, at] of [["gate mount", gateAt], ["captcha-verify route", captchaAt], ["login route", loginAt]]) {
assert.ok(at > -1, `${name} must exist`);
}
assert.ok(gateAt < captchaAt && gateAt < loginAt,
"the gate middleware is registered before both credential routes — their mint paths never execute under the signature");
});