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

+278
View File
@@ -0,0 +1,278 @@
"use strict";
// Header-host primitives shared by every cross-origin trust decision in the
// panel: the CSRF middleware (index.js sameOriginProtection), the shared
// cross-site read guard (utils/cross-site-read-guard.js), the Socket.IO
// handshake origin check (index.js isSocketOriginAllowed) and the nodes.js
// relay's CORS responder. The first five functions moved here VERBATIM from
// index.js so the read guard can reuse the exact same Origin/Referer parsing
// and host matching the state-changing CSRF check uses — a second copy of any
// of them would drift exactly like every other duplicated validator in this
// codebase (see the header note on utils/upload-filename.js for the
// convention). index.js requires these back; behavior is unchanged. The
// port-preserving primitives and the shared csrfPortMismatch decision were
// added later for adpanel:csrf-port-awareness (see below) and live here for
// the same reason.
//
// Matching semantics (deliberate, mirrored from the CSRF middleware): hosts
// are compared WITHOUT scheme, port or path, lowercased, IPv6 brackets
// stripped. Origin "https://panel.example.com:8443" therefore matches request
// host "panel.example.com" for allowlist/alias purposes. Scheme/port
// enforcement, where it matters (CORS response readability), happens in the
// CORS layer, not here.
//
// adpanel:csrf-port-awareness — host matching being port-blind is exactly why
// the CSRF middleware, the read guard and the Socket.IO handshake origin
// check ADDITIONALLY enforce explicit-port equality through csrfPortMismatch()
// below: an Origin from the SAME host on a DIFFERENT port (another service on
// this machine, a sibling loopback process) matches the serving host
// host-blind and would ride the victim's SameSite=Lax session cookie
// (SameSite ignores ports). The parse primitives below keep the explicit port
// (default-normalized) so the trust surfaces can compare it; the host
// matchers above still discard it on purpose — allowlist and alias semantics
// stay port-blind, and the explicit-port rule is the one instruction-side
// control that closes same-host-different-port rides.
// "host" / "host:port" / "a, b" / "[v6]" / "[v6]:port" → bare hostname, or
// null for falsy input. Takes the first comma-separated entry (X-Forwarded-
// Host can be a list), strips IPv6 brackets and the port.
function extractHostnameFromHeader(hostHeader) {
if (!hostHeader) return null;
const first = String(hostHeader).split(",")[0].trim();
if (first.startsWith("[")) {
const end = first.indexOf("]");
if (end !== -1) return first.slice(1, end);
}
return first.split(":")[0];
}
// URL-like header value (Origin, Referer, a configured public URL) → bare
// hostname. Values that do not parse as URLs fall back to hostname-style
// extraction; "null", opaque and non-http(s) values yield whatever the
// fallback extractor sees (callers re-normalize and treat "" as no evidence).
function parseOriginHost(value) {
if (!value) return "";
try {
const u = new URL(value);
return extractHostnameFromHeader(u.host || u.hostname || "");
} catch {
return extractHostnameFromHeader(value);
}
}
// Header host → normalized bare hostname ("" for null/undefined/"null"/
// "undefined" placeholders). This is the canonical form every allowlist entry
// is matched against.
function normalizeHostLower(value) {
const raw = String(value || "").trim().toLowerCase();
if (!raw || raw === "null" || raw === "undefined") return "";
const h = extractHostnameFromHeader(raw);
if (!h) return "";
return h.toLowerCase().replace(/\.+$/, "");
}
function isLocalHost(name) {
const h = String(name || "").toLowerCase();
return h === "localhost" || h === "127.0.0.1" || h === "::1" || h === "[::1]";
}
// Port part of a header-style "host[:port]" value → canonical decimal string,
// or null when absent/malformed. Header-style values carry no scheme, so BOTH
// well-known defaults (80, 443) count as explicit-port-absent: browsers omit
// default ports on both sides of a request, and a proxy that writes ":80" or
// ":443" onto Host/X-Forwarded-Host must not manufacture a port mismatch
// against a default-port Origin.
function normalizeHeaderPort(raw) {
const s = String(raw || "").trim();
if (!/^\d{1,5}$/.test(s)) return null;
const n = Number(s);
if (n < 1 || n > 65535) return null;
if (n === 80 || n === 443) return null;
return String(n);
}
// Same normalization for URL-parsed values (Origin, Referer, PANEL_PUBLIC_URL)
// where the scheme IS known: only the scheme's own default is treated as
// explicit-port-absent (that is the port a browser never sends explicitly).
function normalizeUrlPort(raw, protocol) {
const s = String(raw || "").trim();
if (!/^\d{1,5}$/.test(s)) return null;
const n = Number(s);
if (n < 1 || n > 65535) return null;
if ((protocol === "http:" && n === 80) || (protocol === "https:" && n === 443)) return null;
return String(n);
}
// Header host value (Host header, one X-Forwarded-Host entry) →
// { host, port } | null. Takes the first comma-separated entry (Host is
// single-valued; this keeps standalone lists from crashing), is IPv6-bracket
// aware, and KEEPS the explicit port (defaults normalized away — see
// normalizeHeaderPort). Callers deriving the SERVING port from
// X-Forwarded-Host must pass an ALREADY-trusted single entry
// (getTrustedForwardedHost returns the last comma entry of a trusted proxy's
// header) — trust selection stays with the caller, never here.
function extractHeaderHostPort(hostHeader) {
if (!hostHeader) return null;
const first = String(hostHeader).split(",")[0].trim();
if (!first) return null;
if (first.startsWith("[")) {
const end = first.indexOf("]");
if (end === -1) return { host: first, port: null };
const rest = first.slice(end + 1);
const port = rest.startsWith(":") ? normalizeHeaderPort(rest.slice(1)) : null;
return { host: first.slice(1, end), port };
}
const colonCount = (first.match(/:/g) || []).length;
if (colonCount === 1) {
const idx = first.indexOf(":");
return { host: first.slice(0, idx), port: normalizeHeaderPort(first.slice(idx + 1)) };
}
// Zero colons (plain hostname) or multiple colons (bare unbracketed IPv6
// literal): no usable port evidence either way.
return { host: first, port: null };
}
// URL-like header value (Origin, Referer, a configured public URL) →
// { host, port } | null — the port-evidence twin of parseOriginHost, whose
// callers strip the port. Returns null for everything that carries no usable
// evidence: empty input, the "null"/"undefined" placeholders, non-http(s)
// schemes (opaque origins), and values that are neither an absolute URL nor
// hostname-shaped. Callers must derive the host and the port from the SAME
// raw header value (gate on the host parseOriginHost produced) so host
// evidence and port evidence can never disagree about which header they came
// from.
function parseOriginHostPort(value) {
const raw = String(value || "").trim();
if (!raw || raw === "null" || raw === "undefined") return null;
try {
const u = new URL(raw);
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
return { host: normalizeHostLower(u.hostname), port: normalizeUrlPort(u.port, u.protocol) };
} catch {
// Not an absolute URL: mirror parseOriginHost's hostname-style fallback so
// port evidence exists exactly when the host evidence does. A value whose
// host parseOriginHost would NOT see (e.g. a bare unbracketed IPv6
// literal, which extractHostnameFromHeader reduces to "") yields no pair.
const pair = extractHeaderHostPort(raw);
if (!pair || !pair.host) return null;
const host = normalizeHostLower(pair.host);
if (!host || normalizeHostLower(parseOriginHost(raw)) !== host) return null;
return { host, port: pair.port };
}
}
// The both-explicit vocabulary of the port rule: a mismatch exists when BOTH
// sides carry an explicit, non-default port and the values differ. null on
// either side means "no reliable explicit-port evidence" (default port,
// NAT/port-forward, header rewriting) and returns false here. This helper is
// deliberately NOT the shared decision by itself: treating one-sided evidence
// as port-blind is exactly the gap adpanel:csrf-port-awareness closes — the
// stricter decision lives in csrfPortMismatch below, which also rejects a
// one-sided explicit port. Kept exported because its both-explicit semantics
// remain the right vocabulary for reasoning (and testing) about the
// both-explicit arm of that decision.
function explicitPortsDiffer(a, b) {
if (a === null || b === null) return false;
return a !== b;
}
// adpanel:csrf-port-awareness — the ONE rejection decision every cross-origin
// trust surface shares: sameOriginProtection (index.js, state-changing
// routes), rejectCrossSiteRead (utils/cross-site-read-guard.js, cookie-bearing
// reads) and isSocketOriginAllowed (index.js, the Socket.IO handshake)
// host-match port-blind via hostAllowed or bare-host equality, so the rule
// and its escapes live here, not in any caller. The port comparison: the two
// sides MISMATCH unless their explicit non-default ports are EQUAL, with "no
// explicit-port evidence" (null) equal only to itself —
// - both portless → pass (default-port and NAT/port-forward deployments;
// portless on both sides is exactly what a legitimate default-port
// browser request produces);
// - both explicit and equal → pass;
// - both explicit and different → reject (the original both-explicit rule;
// explicitPortsDiffer above keeps that vocabulary);
// - exactly ONE side explicit, the other portless → reject. Browsers always
// send an explicit port in BOTH Origin and Host when the port is
// non-default, so a one-sided explicit port is either (a) a same-host
// sibling service on another port — the ride this rule closes — or (b) a
// port-stripping/rewriting proxy, which is what the escapes below are
// for. Deliberate boundaries, each mirroring an existing convention of
// the surfaces:
// - Cookie-less requests pass: no ambient authority, so there is nothing to
// ride — the same posture the no-evidence paths already take; an
// anonymous port-mismatched request is not newly bricked.
// - A browser-attested same-origin fetch passes: that attestation includes
// the port (fetch spec) and the HTTP surfaces already let it win over a
// contradictory Origin header. The socket handshake carries no such
// signal and simply never sets the flag.
// - portBlindTrust passes: operator-owned trust that is deliberately
// port-blind. The CSRF allowlist parser (utils/csrf-allowed-hosts.js)
// normalizes entries to bare hostnames, so an operator's CSRF_ALLOWED_
// HOSTS endorsement cannot express a port; the read guard folds its exact
// NODES_CORS_ORIGINS origin match into the same input. Operator trust is
// the operator's own knob — it does not silently become port-aware.
// - The PANEL_PUBLIC_URL escape: an evidence host+port exactly equal to the
// configured public URL's host+port passes even when the Host header
// disagrees — one of the TWO documented remedies for Host-rewriting
// proxies (the case-(b) arm of the one-sided rule), extended (not
// invented) for ports. The other remedy is a trusted X-Forwarded-Host
// entry carrying the port, which the HTTP middleware and (adpanel:socket-
// forwarded-host) the socket handshake prefer for serving-port evidence.
// Where neither remedy is configurable, adpanel:port-mismatch-advisor
// makes the rejection loud instead of silent. Inert when no public host
// is configured.
// - Accepted edge (documented, deliberately not fixed): a deployment
// serving plain HTTP on port 443 or HTTPS on port 80 behind a rewriting
// proxy with neither remedy configured is now rejected where it passed
// before — the browser sends the non-default-for-scheme port explicitly
// in Origin while the scheme-less header side normalizes ":443"/":80" to
// absent, which the one-sided rule reads as a sibling port. That shape is
// a misconfiguration; the escape is either remedy — set PANEL_PUBLIC_URL
// to the public scheme+host+port, or make the proxy forward
// X-Forwarded-Host WITH the port.
function csrfPortMismatch(opts = {}) {
const originPair = opts.originPair || null;
if (!originPair || !originPair.host) return false;
if (!opts.hasCookie || opts.sameOriginFetch) return false;
if (opts.portBlindTrust) return false;
const publicHost = typeof opts.publicHost === "string" ? opts.publicHost : "";
if (publicHost && originPair.host === publicHost &&
originPair.port === (opts.publicPort == null ? null : opts.publicPort)) return false;
const originPort = originPair.port == null ? null : originPair.port;
const servingPort = opts.servingPort == null ? null : opts.servingPort;
// Mismatch ⇔ not equal, with null equal only to itself: both-portless and
// both-explicit-equal pass; differing explicit ports AND the one-sided
// shapes (explicit vs no evidence, either direction) reject.
return originPort !== servingPort;
}
// Match a header-derived host against an allowlist Set of normalized hosts.
// "*.domain" / ".domain" entries match the bare base and any subdomain;
// wildcard reachability is the CSRF allowlist parser's job
// (utils/csrf-allowed-hosts.js), not this matcher's.
function hostAllowed(headerHost, allowedHosts) {
if (!headerHost) return false;
if (!allowedHosts || allowedHosts.size === 0) return false;
if (allowedHosts.has(headerHost)) return true;
for (const allowed of allowedHosts) {
if (!allowed) continue;
if (headerHost === allowed) return true;
if (allowed.startsWith("*.") || allowed.startsWith(".")) {
const base = allowed.replace(/^\*\./, "").replace(/^\./, "");
if (!base) continue;
if (headerHost === base || headerHost.endsWith(`.${base}`)) return true;
}
}
return false;
}
module.exports = {
extractHostnameFromHeader,
parseOriginHost,
normalizeHostLower,
isLocalHost,
hostAllowed,
parseOriginHostPort,
extractHeaderHostPort,
explicitPortsDiffer,
csrfPortMismatch,
};