"use strict"; // adpanel:remote-proxy-trust-gate — OPT-IN (REMOTE_PROXY_REQUIRE_TRUST=1) enforcement for the remote-proxy misconfiguration signature that the DEFAULT posture only WARNS about (adpanel:remote-proxy-misconfig-warning: boot advisory + one-time runtime hint, warn-only). // Default OFF keeps the ledger's warn-only posture byte-identical; forged XFP // on a direct HTTP connection becomes a per-request refusal for the forging // client only (shared state unaffected; the accepted forged-XFP-warn trade-off // widens to refusal ONLY under explicit opt-in). // // Scope: on a violation (the ONE predicate in index.js, // isRemoteProxyTrustViolationRequest — XFP claims https while the DIRECT peer // is untrusted), refuse ONLY the credential-establishing pre-auth surfaces — // POST /login and POST /api/captcha/verify. GET /login, static assets and // every other route PASS THROUGH even on violation. The gate is per-request // and stateless: it never shares or resets the warn's one-time latch (the // warn stays observability-only). // // SECOND CONSUMER (adpanel:remote-proxy-trust-gate — remember-credential // ISSUANCE): this module deliberately does NOT implement it — index.js wires // the same knob + predicate into the remember issuance paths through its ONE // helper remoteProxyTrustBlocksRememberIssuance (one predicate, one home, two // consumers): restoreRememberedLogin fails closed (stale cookie cleared, no // session bind — the shape of its existing failure paths), the authenticated // silent refresh (ensureRememberLoginCookie) and the mint helper // (setRememberLoginCookie, covering the four interactive re-issues) SKIP // entirely, while the credential POSTs this gate refuses never reach their // mint at all. Under opt-in + violation no NEW session can be established and // no remember credential is minted/refreshed. // // Residual risks (documented, accepted under opt-in): // - The throttle-bucket collapse remains for NON-credential surfaces: a // misconfigured remote proxy is still one client IP for every limiter and // log that the gate does not refuse. // - Already-established SESSIONS remain out of scope: they require // possession of a valid cookie, not credential processing, and // express-session's own cookie issuance has no per-request gate hook — // pre-existing sessions continue (their cookies keep shipping without // Secure under the misconfig); the issuance consumer covers only the // remember credential's mint/refresh surfaces. // - The refusal is a backstop, not the fix: TRUSTED_PROXY_IPS (the complete // shared-throttle-bucket fix) + TRUST_PROXY (the Secure-cookie half) // remain the operator remedies named by the boot/warn advisories. // // Refusal shape (adpanel:preauth-500-no-proxy-detail discipline): 503 with a // path-free generic body — NO proxy/XFP/trust detail reaches the // unauthenticated caller; the diagnosis is the operator's boot/warn // advisories. 503 follows the house pre-auth refusal precedent (the // maintenance gate answers non-exempt traffic 503 with a generic // action-oriented message): it is truthful — the panel declines to process // credentials under the current trust posture — without impersonating an auth // verdict (401/403) or the throttles' Retry-After contract (429). Content // negotiation reuses the ONE login-surface JSON-wants predicate // (wantsJsonLoginResponse from utils/login-throttle.js), so this refusal // cannot negotiate differently from the rest of the login surface. const { wantsJsonLoginResponse } = require("./login-throttle"); const REFUSAL_MESSAGE = "Service temporarily unavailable. Try again later."; // Router-equivalent path anchor (adpanel:stealth-login-trailing-slash / // adpanel:stealth-login-case-fold): express matches the RAW pathname with // caseSensitive:false and strict:false — exactly ONE trailing "/" is // optional, nothing is decoded. Fold the same way, or a case-variant or // one-slash spelling of a guarded POST would slip past this gate into the // real route (while /login// — which the router 404s — must NOT be guarded). function normalizeRoutePath(raw) { return String(raw || "").trim().replace(/\/$/, "").toLowerCase(); } const GUARDED_CREDENTIAL_PATHS = new Set(["/login", "/api/captcha/verify"]); function isGuardedCredentialRequest(req) { if (String(req.method || "").toUpperCase() !== "POST") return false; return GUARDED_CREDENTIAL_PATHS.has(normalizeRoutePath(req.path)); } function sendTrustGateRefusal(req, res) { // One console.warn per refusal, mirroring the revoked-sid gate's per-hit // record — the operator explicitly opted in, so refusals are the feature // working and must be visible. Path only: no peer/proxy/XFP echo, matching // the body's no-detail discipline; control chars stripped as securityLog // does (the raw peer here would be the proxy/forger's address anyway — // never the real client under the misconfig). const safePath = String(req.path || "").replace(/[\x00-\x1f\x7f]/g, "").slice(0, 500); console.warn(`[security] Remote-proxy trust gate refused credential processing | Path: ${safePath}`); res.setHeader("Cache-Control", "no-store"); if (wantsJsonLoginResponse(req)) { return res.status(503).json({ ok: false, error: REFUSAL_MESSAGE }); } return res.status(503).type("text/plain").send(REFUSAL_MESSAGE); } function createRemoteProxyTrustGate({ enabled, violationOf }) { const gateEnabled = enabled === true; if (gateEnabled && typeof violationOf !== "function") { // Fail fast at BOOT, not per request: an opt-in gate without its // predicate is a wiring bug, and silently passing every request would // defeat the operator's explicit opt-in. throw new Error("createRemoteProxyTrustGate: enabled requires a violationOf(req) predicate"); } return function remoteProxyTrustGate(req, res, next) { // Hot path: ONE closure-variable read when disabled; ONE predicate call // when enabled and clean. No allocation, no I/O, no shared state. if (!gateEnabled) return next(); if (!violationOf(req)) return next(); if (!isGuardedCredentialRequest(req)) return next(); return sendTrustGateRefusal(req, res); }; } module.exports = { createRemoteProxyTrustGate };