371 lines
20 KiB
JavaScript
371 lines
20 KiB
JavaScript
"use strict";
|
|
|
|
// Shared CSRF-read guard for file-read endpoints. The panel's own file routes
|
|
// (index.js /api/servers/:name/files/{list,read,stream,download}) and the
|
|
// remote-mode relays (nodes.js /api/nodes/server/:name/{entries,file,download})
|
|
// expose the same class of data, so both surfaces must apply the SAME
|
|
// cross-site rejection policy — a second copy here would drift exactly like
|
|
// every other duplicated validator in this codebase (see the header note on
|
|
// utils/upload-filename.js for the convention).
|
|
//
|
|
// Policy (mirrors index.js sameOriginProtection, the panel-wide CSRF check on
|
|
// state-changing routes, adapted for GET reads — same primitives from
|
|
// utils/origin-host.js, same allowlists, so an operator's trust decisions mean
|
|
// the same thing on both sides):
|
|
//
|
|
// 1. sec-fetch-site "cross-site" → 403, UNLESS the Origin/Referer host is
|
|
// one the operator already endorsed (hostAllowed against the allowlist
|
|
// built below) — parity with the CSRF middleware, which accepts
|
|
// cross-site WRITES from those same hosts, so reads cannot be stricter
|
|
// than writes. A browser-attested "same-origin" site value wins over a
|
|
// contradictory Origin header, exactly as in sameOriginProtection.
|
|
// 2. Origin/Referer literally "null" (sandboxed iframe, data:/file:
|
|
// context): cross-origin by definition → 403 when the request carries
|
|
// cookies (ambient authority an attacker page can drive); without
|
|
// cookies the request carries no authority and falls through to the
|
|
// ordinary auth gate (401).
|
|
// 3. NO evidence at all (no Sec-Fetch-Site, no Origin, no Referer) →
|
|
// cookieless requests PASS (the non-browser contract: curl, API
|
|
// scripts and monitor agents). Cookie-bearing requests are 403 — the
|
|
// same combination sameOriginProtection already rejects on
|
|
// state-changing routes, because it is exactly what a hostile page
|
|
// produces once it strips its own Referer (old browser: no metadata at
|
|
// all; modern sibling subdomain: site "same-site" with the SameSite=Lax
|
|
// cookie still attached). Browser attestation is still honored:
|
|
// "same-origin", and "none" (address bar / bookmark / reload — hostile
|
|
// JS cannot forge Sec-Fetch-*). Scripted session clients declare
|
|
// themselves with an Origin header instead, which branch 4 honors —
|
|
// the same declaration the CSRF middleware already requires of them
|
|
// for writes.
|
|
// 4. Origin/Referer evidence present while Sec-Fetch-Site is absent or
|
|
// indecisive (old browsers, "same-site"/"none"/malformed values): the
|
|
// evidence host must be same-host or allowlisted, else 403. This closes
|
|
// the old-browser hole: every browser, however old, sends Origin on
|
|
// cross-site fetch/XHR and Referer on cross-site subresources, so a
|
|
// hostile page can no longer ride the absent-header fail-open. "same-site"
|
|
// (sibling-subdomain) evidence is held to the same host standard as the
|
|
// CSRF middleware — SameSite=Lax cookies attach to same-site GETs, so a
|
|
// hostile sibling subdomain must be allowlisted too.
|
|
// 5. adpanel:csrf-port-awareness — host matching being port-blind, an
|
|
// evidence host on the SAME host at a DIFFERENT port (another service on
|
|
// this machine, a sibling loopback process) would match and ride the
|
|
// SameSite=Lax session cookie (SameSite ignores ports). Before the host
|
|
// branches, a cookie-bearing request whose evidence-origin port and
|
|
// serving-host port are not EQUAL is 403'd — differing explicit ports,
|
|
// and (the one-sided gap the rule closes) an explicit non-default port
|
|
// on exactly one side while the other carries no port evidence, since
|
|
// browsers always send the explicit port on BOTH sides when it is
|
|
// non-default (so one-sided is a sibling service or a rewriting proxy) —
|
|
// the SAME rule, escapes and trade-offs as index.js sameOriginProtection,
|
|
// decided by the ONE shared csrfPortMismatch in utils/origin-host.js
|
|
// (cookie-less requests pass; browser-attested same-origin wins;
|
|
// CSRF_ALLOWED_HOSTS trust and an exact NODES_CORS_ORIGINS origin stay
|
|
// port-blind; the PANEL_PUBLIC_URL host+port escape covers
|
|
// Host-rewriting proxies; both-portless — default-port and NAT
|
|
// deployments — and both-explicit-equal requests pass).
|
|
//
|
|
// Evidence hosts are matched WITHOUT scheme/port/path (hostAllowed semantics)
|
|
// — the explicit-port rule above is the only port-aware control, shared with
|
|
// the CSRF middleware so neither can drift — and responses readable
|
|
// cross-origin are still gated by CORS (index.js sends no ACAO at all; nodes.js
|
|
// echoes only operator-allowlisted origins), so this guard is read-side
|
|
// hardening layered on session auth — never a replacement for it — and must
|
|
// always run ahead of the auth check so the rejection does not depend on
|
|
// session state.
|
|
//
|
|
// Trust context injection: index.js injects the panel-wide pieces at startup
|
|
// (same pattern as nodesRouter.setPermissionCheckers/setUploadPolicyHooks —
|
|
// this module cannot require index.js back, circular import). Everything
|
|
// degrades to a NARROWER allowlist when not injected, never a wider one:
|
|
// standalone (nodes.js test harness, direct mounts) the panel's own host is
|
|
// just the request's Host header. The injection also carries the shared
|
|
// port-mismatch advisor (adpanel:port-mismatch-advisor, below) so the port-
|
|
// mismatch rejection here is as diagnosable as the same rule's rejection on
|
|
// the middleware and socket surfaces — reads must not be the one silent
|
|
// surface.
|
|
|
|
const {
|
|
parseOriginHost,
|
|
parseOriginHostPort,
|
|
extractHeaderHostPort,
|
|
normalizeHostLower,
|
|
isLocalHost,
|
|
hostAllowed,
|
|
csrfPortMismatch,
|
|
} = require("./origin-host");
|
|
|
|
// Operator-endorsed cross-origin READ clients for the nodes relay: exact
|
|
// origins (scheme+host+port as written) that nodes.js's CORS responder also
|
|
// echoes with credentials. The guard matches these at HOST level (like every
|
|
// other allowlist here) so Referer-only evidence from the endorsed app is
|
|
// honored too; actual cross-origin READABILITY stays exact-origin — the CORS
|
|
// layer echoes ACAO only for the origin as written — so a sibling origin on
|
|
// the same host may drive a request it cannot read. An EXACT origin match
|
|
// additionally counts as port-blind trust for the adpanel:csrf-port-awareness
|
|
// rule below: the operator endorsed the full scheme+host+port string, so a
|
|
// request carrying that exact Origin must keep working behind a
|
|
// Host-rewriting proxy exactly as it did before the port rule existed (and a
|
|
// forged Origin that merely shares the host does not exact-match, so it stays
|
|
// port-checked).
|
|
const CORS_READ_ALLOWED_ORIGINS = new Set(
|
|
(process.env.NODES_CORS_ORIGINS || "")
|
|
.split(",")
|
|
.map(s => s.trim())
|
|
.filter(Boolean)
|
|
);
|
|
|
|
// Injected by index.js after the CSRF allowlist is parsed (see
|
|
// setCrossOriginTrustContext below). Defaults keep the guard standalone-safe.
|
|
let _panelPublicHost = "";
|
|
// adpanel:csrf-port-awareness — the PANEL_PUBLIC_URL host's explicit port
|
|
// (null when the URL carries none): the escape-hatch comparison target for
|
|
// the shared csrfPortMismatch rule, mirroring index.js _CSRF_PANEL_PUBLIC_PORT.
|
|
let _panelPublicPort = null;
|
|
let _extraAllowedHosts = [];
|
|
// Same entries as _extraAllowedHosts, as a Set for the per-request port-blind
|
|
// trust lookup (CSRF_ALLOWED_HOSTS entries are normalized to bare hostnames,
|
|
// so this trust stays deliberately port-blind).
|
|
let _extraAllowedHostsSet = new Set();
|
|
let _resolveTrustedForwardedHost = null;
|
|
// adpanel:port-mismatch-advisor — the third shared-rule rejection point (this
|
|
// guard's) must get the same diagnosis the middleware's 403 branch and the
|
|
// socket handshake already emit: cookie-bearing READS (GET/HEAD) skip
|
|
// sameOriginProtection entirely, so the one-sided brick shape on reads
|
|
// reaches THIS branch — without the injected advisor an operator with a
|
|
// misconfigured Deployment-D proxy gets diagnosed on writes but stays silent
|
|
// on reads. index.js injects its ONE advisor instance plus a logAdvice sink
|
|
// alongside the trust context below; nodes.js binds the guard WITHOUT the
|
|
// dep, and when either piece is absent the rejection below is byte-identical
|
|
// to the pre-advisor behavior (null-safe, never a wider trust or a new
|
|
// verdict). The advisor owns the fire condition and the throttle
|
|
// (utils/origin-port-advisor.js); the guard only forwards the evidence the
|
|
// rejection actually saw.
|
|
let _portMismatchAdvisor = null;
|
|
let _logAdvice = null;
|
|
|
|
function setCrossOriginTrustContext(ctx = {}) {
|
|
_panelPublicHost = typeof ctx.panelPublicHost === "string" ? normalizeHostLower(ctx.panelPublicHost) : "";
|
|
_panelPublicPort = typeof ctx.panelPublicPort === "string" ? ctx.panelPublicPort : null;
|
|
_extraAllowedHosts = Array.isArray(ctx.extraAllowedHosts)
|
|
? ctx.extraAllowedHosts.filter(h => typeof h === "string" && h)
|
|
: [];
|
|
_extraAllowedHostsSet = new Set(_extraAllowedHosts);
|
|
_resolveTrustedForwardedHost = typeof ctx.resolveTrustedForwardedHost === "function"
|
|
? ctx.resolveTrustedForwardedHost
|
|
: null;
|
|
_portMismatchAdvisor = ctx.portMismatchAdvisor &&
|
|
typeof ctx.portMismatchAdvisor.advice === "function"
|
|
? ctx.portMismatchAdvisor
|
|
: null;
|
|
_logAdvice = typeof ctx.logAdvice === "function" ? ctx.logAdvice : null;
|
|
}
|
|
|
|
// The panel's own hosts + operator-endorsed cross-origin hosts, mirroring the
|
|
// allowedHosts set sameOriginProtection builds: the serving Host header, the
|
|
// trusted X-Forwarded-Host (injected resolver — empty without a trusted
|
|
// proxy), the configured PANEL_PUBLIC_URL host, the parsed CSRF_ALLOWED_HOSTS
|
|
// entries and the CORS read allowlist. Loopback evidence grants the localhost
|
|
// variants ONLY when the panel's own host is itself loopback — the
|
|
// adpanel:csrf-localhost-scoping gate below, mirrored in sameOriginProtection.
|
|
function buildAllowedHosts(req, originHost, refererHost) {
|
|
const headers = req.headers || {};
|
|
const hostHeader = normalizeHostLower(headers.host);
|
|
const forwardedHost = _resolveTrustedForwardedHost
|
|
? normalizeHostLower(_resolveTrustedForwardedHost(req))
|
|
: "";
|
|
const allowed = new Set([forwardedHost, hostHeader, _panelPublicHost].filter(Boolean));
|
|
for (const h of _extraAllowedHosts) allowed.add(h);
|
|
for (const origin of CORS_READ_ALLOWED_ORIGINS) {
|
|
const host = normalizeHostLower(parseOriginHost(origin));
|
|
if (host) allowed.add(host);
|
|
}
|
|
// adpanel:csrf-localhost-scoping — loopback origins earn the loopback
|
|
// aliases only when the panel itself is served from loopback (Host header,
|
|
// trusted X-Forwarded-Host or PANEL_PUBLIC_URL host). On a non-loopback
|
|
// deployment a page from another local process (Origin
|
|
// http://localhost:9999) is cross-site: hostAllowed ignores ports, so the
|
|
// blanket grant would let that page ride the victim's SameSite=Lax session
|
|
// cookie. There it must fall through to the normal allowlist like any
|
|
// other foreign host. adpanel:csrf-port-awareness closes the LOOPBACK
|
|
// variant of that ride (sibling process on a different port against a
|
|
// loopback-served panel) via the shared csrfPortMismatch check that runs
|
|
// ahead of the host branches — this host-level grant stays as is and cannot
|
|
// bypass it; a TRUE same-port loopback origin still passes.
|
|
if ((isLocalHost(originHost) || isLocalHost(refererHost)) &&
|
|
(isLocalHost(hostHeader) || isLocalHost(forwardedHost) || isLocalHost(_panelPublicHost))) {
|
|
allowed.add("localhost");
|
|
allowed.add("127.0.0.1");
|
|
allowed.add("::1");
|
|
}
|
|
return allowed;
|
|
}
|
|
|
|
function reject(res) {
|
|
return res.status(403).json({ error: "cross-site request blocked" });
|
|
}
|
|
|
|
function rejectCrossSiteRead(req, res, next) {
|
|
try {
|
|
const headers = req.headers || {};
|
|
const site = String(headers["sec-fetch-site"] || "").toLowerCase();
|
|
const rawOrigin = String(headers.origin || headers.Origin || "");
|
|
const rawReferer = String(headers.referer || headers.referrer || "");
|
|
const originHost = normalizeHostLower(parseOriginHost(rawOrigin));
|
|
const refererHost = normalizeHostLower(parseOriginHost(rawReferer));
|
|
const sameOriginFetch = site === "same-origin";
|
|
const hasCookie = Boolean(headers.cookie);
|
|
const headerHost = originHost || refererHost;
|
|
|
|
// adpanel:csrf-port-awareness — mirror of sameOriginProtection's
|
|
// explicit-port check (index.js), decided by the SAME shared rule
|
|
// (csrfPortMismatch in utils/origin-host.js) so reads and writes can never
|
|
// drift apart on what a sibling-port origin means. The evidence port comes
|
|
// from the SAME header that produced headerHost (Origin preferred, else
|
|
// Referer); the serving port from the same source that produced the
|
|
// guard's serving host (the trusted X-Forwarded-Host entry the injected
|
|
// resolver endorses — the resolver already returns that single trusted
|
|
// entry — else the Host header; buildAllowedHosts re-derives the host side
|
|
// itself and stays untouched). The check runs ahead of branches 1 and 4 so
|
|
// a host-allowed same-host-different-port origin cannot slip past on the
|
|
// host match; the loopback alias grant inside buildAllowedHosts is
|
|
// likewise host-level only and cannot bypass this. Rejections are
|
|
// cookie-bearing only — a cookie-less request carries no ambient authority
|
|
// and keeps today's posture (it falls through to the ordinary branches and
|
|
// the auth gate).
|
|
const originPortPair = originHost
|
|
? parseOriginHostPort(rawOrigin)
|
|
: (refererHost ? parseOriginHostPort(rawReferer) : null);
|
|
const forwardedRaw = _resolveTrustedForwardedHost
|
|
? String(_resolveTrustedForwardedHost(req) || "")
|
|
: "";
|
|
const servingPair = normalizeHostLower(forwardedRaw)
|
|
? extractHeaderHostPort(forwardedRaw)
|
|
: extractHeaderHostPort(headers.host || "");
|
|
if (csrfPortMismatch({
|
|
originPair: originPortPair,
|
|
servingPort: servingPair ? servingPair.port : null,
|
|
hasCookie,
|
|
sameOriginFetch,
|
|
// Port-blind trust on this surface: the operator's CSRF_ALLOWED_HOSTS
|
|
// entries (bare hostnames by parser contract) plus an exact
|
|
// NODES_CORS_ORIGINS origin match (the operator endorsed the full
|
|
// scheme+host+port string — see the CORS_READ_ALLOWED_ORIGINS note).
|
|
portBlindTrust: hostAllowed(headerHost, _extraAllowedHostsSet) ||
|
|
CORS_READ_ALLOWED_ORIGINS.has(rawOrigin),
|
|
publicHost: _panelPublicHost,
|
|
publicPort: _panelPublicPort,
|
|
})) {
|
|
// adpanel:port-mismatch-advisor — diagnose the one-sided brick shape
|
|
// with the values this rejection actually saw: the origin header that
|
|
// produced originPortPair, and the serving port the derivation above
|
|
// settled on — the SAME evidence the middleware's 403 branch and the
|
|
// socket handshake forward, so all three shared-rule rejection points
|
|
// speak with one voice. Reads get the same diagnosis because
|
|
// cookie-bearing GET/HEAD never pass through sameOriginProtection —
|
|
// this branch is their ONLY encounter with the explicit-port rule.
|
|
// Best-effort: the advisor + log pair is wrapped so a logging failure
|
|
// can never alter or break the rejection (same crash-class doctrine as
|
|
// every upstream-response listener); the verdict and 403 body below
|
|
// stay byte-identical, and without the injected dep (nodes.js) this
|
|
// block is inert.
|
|
if (_portMismatchAdvisor && _logAdvice) {
|
|
try {
|
|
const advice = _portMismatchAdvisor.advice({
|
|
originHeader: originHost ? rawOrigin : rawReferer,
|
|
servingPort: servingPair ? servingPair.port : null,
|
|
});
|
|
if (advice) _logAdvice(advice, req);
|
|
} catch (_err) {
|
|
// Best-effort logging only — never re-route the rejection to
|
|
// next(err): the 403 must stand regardless of advisor failures.
|
|
}
|
|
}
|
|
return reject(res);
|
|
}
|
|
|
|
// 1. Positive cross-site attestation from the browser.
|
|
if (site === "cross-site") {
|
|
if (headerHost && hostAllowed(headerHost, buildAllowedHosts(req, originHost, refererHost))) return next();
|
|
return reject(res);
|
|
}
|
|
|
|
// 2. Opaque "null" origin: a sandboxed frame has no origin to trust.
|
|
if (rawOrigin === "null" || rawReferer === "null") {
|
|
if (hasCookie && !sameOriginFetch) return reject(res);
|
|
// Cookieless: no ambient authority — the auth gate decides below.
|
|
}
|
|
|
|
// 3. No evidence at all (no Sec-Fetch-Site, no Origin, no Referer).
|
|
// Cookieless requests pass — the non-browser contract: curl, API
|
|
// scripts and monitor agents carry no ambient authority and the auth
|
|
// gate decides. Cookie-bearing requests with zero initiator evidence
|
|
// are the residual attack shape, not a client to serve: an old
|
|
// browser navigating with its Referer stripped (Referrer-Policy:
|
|
// no-referrer) and a same-site sibling that strips its Referer (site
|
|
// "same-site"; SameSite=Lax cookies still attach to same-site GETs)
|
|
// both arrive exactly like this. sameOriginProtection already
|
|
// rejects that combination on state-changing routes — reads are no
|
|
// looser than writes. Browser-attested trust is still honored:
|
|
// "same-origin" (sameOriginFetch) and "none" (top-level navigation —
|
|
// address bar, bookmark, reload; hostile JS cannot forge Sec-Fetch-*).
|
|
// Scripted session clients declare themselves with an Origin header,
|
|
// which branch 4 honors — the same declaration the CSRF middleware
|
|
// already requires of them for writes.
|
|
if (!originHost && !refererHost) {
|
|
if (hasCookie && !sameOriginFetch && site !== "none") return reject(res);
|
|
return next();
|
|
}
|
|
|
|
// 4. Evidence without a decisive Fetch Metadata value (old browsers, or
|
|
// same-site/none/malformed): hold the evidence host to the same standard
|
|
// as the CSRF middleware.
|
|
if (!sameOriginFetch &&
|
|
!hostAllowed(headerHost, buildAllowedHosts(req, originHost, refererHost))) {
|
|
return reject(res);
|
|
}
|
|
return next();
|
|
} catch (err) {
|
|
return next(err);
|
|
}
|
|
}
|
|
|
|
// App-wide default-secure read gate (mounted by index.js on /api): every
|
|
// cookie-bearing GET/HEAD under /api must be browser-attested or host-
|
|
// allowlisted, exactly per rejectCrossSiteRead — no per-route mounting
|
|
// required. The per-route mounts (the file/console/per-server family pinned
|
|
// in tests/node-relay-cross-site-guard-parity.test.js) stay: they are the
|
|
// documented family; this layer backstops EVERYTHING else, including routes
|
|
// added later, so a new data endpoint cannot silently ship unguarded.
|
|
//
|
|
// opts.exemptPaths / opts.exemptPatterns carve out the documented
|
|
// telemetry-polling family — the same surface RATE_LIMIT_EXEMPT_* in
|
|
// index.js treats as scripted-monitor territory: their responses carry
|
|
// nothing worth an existence/size oracle, and high-frequency polling with
|
|
// cookie jars is those endpoints' contract, so guarding them would break
|
|
// monitor agents for zero security gain. Paths are matched relative to the
|
|
// mount (under app.use("/api", …), "/api/me" arrives as "/me"). Writes are
|
|
// NOT this layer's concern — non-GET/HEAD methods pass through to the
|
|
// panel-wide sameOriginProtection CSRF middleware, which already rejects
|
|
// cookie-bearing evidence-less writes.
|
|
function createApiReadGate(opts = {}) {
|
|
const exemptPaths = new Set(
|
|
(Array.isArray(opts.exemptPaths) ? opts.exemptPaths : [])
|
|
.filter((p) => typeof p === "string" && p)
|
|
);
|
|
const exemptPatterns = (Array.isArray(opts.exemptPatterns) ? opts.exemptPatterns : [])
|
|
.filter((re) => re instanceof RegExp);
|
|
return function apiReadGate(req, res, next) {
|
|
try {
|
|
const method = (req.method || "").toUpperCase();
|
|
if (method !== "GET" && method !== "HEAD") return next();
|
|
const p = String(req.path || "");
|
|
if (exemptPaths.has(p) || exemptPatterns.some((re) => re.test(p))) return next();
|
|
return rejectCrossSiteRead(req, res, next);
|
|
} catch (err) {
|
|
return next(err);
|
|
}
|
|
};
|
|
}
|
|
|
|
module.exports = { rejectCrossSiteRead, setCrossOriginTrustContext, createApiReadGate };
|