"use strict"; // adpanel:relay-helper-consolidation — ONE shared implementation of the // panel→node HTTP plumbing (Wave 2 Step A of the relay consolidation // campaign, see .campaign/spec-relay.md §6). index.js and nodes.js carried // drifting twins of every helper below; the twins are deleted from both // monoliths and re-bound here under the SAME identifier names, so no call // site changed. This module requires ONLY utils/* and node builtins — it // must NEVER require index.js or nodes.js (dependency direction is one-way: // the monoliths require this module). Boot-time capabilities that still live // in index.js (the mTLS agent, the SSRF-pinned request agent builders used // by the non-node branch) arrive through configureNodeHttp() and are read at // CALL time, never at require time. // // TWO FLAGGED SAFETY HARDENINGS land with this extraction (both fail-closed // on malformed node configurations, neither can reject a legitimate one): // 1. Credential-in-URL rejection in buildNodeBaseUrl // (`u.username || u.password → null`) — previously index.js-only; the // nodes.js twin silently forwarded node addresses like // `https://user:pass@host` and leaked the credentials into every relayed // upstream URL. Now enforced on BOTH surfaces. // 2. The stricter safeJoinUnix union lives in services/node-fs-relay.js // (documented there). // // Every other behavioral delta between the former twins (port clamping, // trailing-slash/origin URL form, the // X-Node-Token-Id header shape, the local-daemon token branch) is preserved // EXACTLY per caller behind factory parameters — byte-identical outputs on // both surfaces for every input either surface can receive today. const http = require("http"); const https = require("https"); const { isIP } = require("node:net"); const nodeSsrfGuard = require("../utils/node-ssrf-guard"); const remoteUrlGuard = require("../utils/remote-url-guard"); const { destroyStreams } = require("../utils/stream-lifecycle"); // --------------------------------------------------------------------------- // Injectable boot-time capabilities (set once by index.js at startup; read at // call time so module-load ordering can never observe a half-built agent). // --------------------------------------------------------------------------- const deps = { // index.js builds an https.Agent for node mTLS at boot (let nodeMtlsAgent, // lazily assigned); httpRequestJson attaches it to https dials that carry // node credentials. Getter, not value: the agent is assigned after modules // load. getNodeMtlsAgent: () => null, // SSRF-pinned agent builders shared with index.js's ssrfPipedHttpGet — // they stay defined in index.js (their only other consumer) and are // injected here so the non-node branch of httpRequestJson keeps its exact // dial posture (IP-pinned agent + SNI servername). createSsrfSafeAgent: null, tlsServernameForHost: null, }; function configureNodeHttp(patch) { Object.assign(deps, patch || {}); } // adpanel:node-mtls-parity - every TLS transport must use the configured node identity and CA. function nodeTlsAgent(url) { if (typeof url !== "string" || !/^(?:https|wss):/.test(url)) return undefined; return deps.getNodeMtlsAgent() || undefined; } function hasVerifiedNodeHttps(fullUrl) { if (typeof fullUrl !== "string" || !fullUrl.startsWith("https://") || process.env.NODE_TLS_REJECT_UNAUTHORIZED === "0") return false; const { options } = nodeTlsAgent(fullUrl) || https.globalAgent; return options?.rejectUnauthorized !== false && !options?.checkServerIdentity; } // --------------------------------------------------------------------------- // httpRequestJson — moved verbatim from index.js (its previous and only // definition site). Since the Wave 3 HTTP-helper convergence, the nodes.js // helpers of the same family (httpJson, the GET-probe httpRequestJson) are // thin wrappers over THIS implementation via the `opts` param below — the // crash-class hardening (response error AND aborted listeners, hard // total-duration timer + inactivity timeout + request error listener, // single-settle finish, Content-Length pre-check + streaming 16 MiB cap) is // enforced exactly once, here. Everything the panel call sites closed over // in index.js is either required directly above or injected via // configureNodeHttp. // --------------------------------------------------------------------------- // opts (Wave 3 HTTP-helper convergence, all flags default off so the panel's // 54 existing call sites dial exactly as before): // opts.includeText — the nodes.js httpJson contract: the result carries the // raw body as `text` (on the end path) and `text: null` on the guard / // response-error / too-large paths, exactly as that helper always // resolved them. Deliberately NOT added to the timeout / request-error / // setup-failure paths — the former httpJson resolved those WITHOUT the // text key, and the shape is preserved verbatim. // opts.nodeDial — force the node branch of the SSRF guard regardless of // headers. The branch condition below ("headers carry the node's bearer // credential") fits every panel caller, but the nodes.js surface's // helpers historically applied the node guard chain UNCONDITIONALLY — // including the unauthenticated /health probe, which dials the node's // custom api_port with no auth headers and would otherwise fall into the // external-URL branch, whose 80/443 port allowlist rejects every real // node address. The nodes.js wrappers pass this so their guard posture // stays byte-identical. function httpRequestJson(fullUrl, method = "GET", headers = {}, body = null, timeoutMs = 15000, maxBytes = null, opts = null) { const includeText = !!(opts && opts.includeText); const nodeDial = !!(opts && opts.nodeDial); // The failure shapes without a body. includeText adds `text: null` on // exactly the paths the former nodes.js httpJson resolved it on (guard // error, response error, aborted, too large) and leaves the timeout / // request-error / setup-failure shapes without the key. const noBodyResult = () => (includeText ? { status: 0, json: null, text: null } : { status: 0, json: null }); return new Promise(async (resolve) => { let settled = false; const finish = (out) => { if (settled) return; settled = true; try { clearTimeout(hardTimer); } catch { } resolve(out); }; let hardTimer = null; let req = null; let response = null; const deadline = Date.now() + timeoutMs; const fail = (out) => { if (settled) return; finish(out); destroyStreams(response, req); }; // adpanel:node-http-total-deadline - external DNS validation belongs to // the same budget as the dial and body; expiry must forbid a late dial. hardTimer = setTimeout(() => fail({ status: 0, json: null }), timeoutMs); try { const isInternalNodeRequest = nodeDial || !!(headers && (headers["X-Node-Token"] || headers["Authorization"])); let requestOptions; let lib; if (isInternalNodeRequest) { // SSRF guard (finding 3.3): pre-flight for literal-IP hosts (Node skips // custom lookup for them); the guarded lookup below re-validates // resolved IPs at connect time. Every dial to a node goes through this // guard: the request headers carry the node's bearer credential. const guardError = nodeSsrfGuard.assertNodeUrlHostAllowed(fullUrl); if (guardError) return finish(noBodyResult()); const isHttps = fullUrl.startsWith("https:"); lib = isHttps ? https : http; requestOptions = { method, headers, lookup: nodeSsrfGuard.guardedNodeLookup, agent: nodeTlsAgent(fullUrl) }; } else { let validated; try { validated = await remoteUrlGuard.assertSafeRemoteUrlWithResolvedIp(fullUrl); } catch (e) { return finish({ status: 0, json: null }); } if (settled || Date.now() >= deadline) return fail({ status: 0, json: null }); const { url: u, resolvedIp, originalHostname } = validated; lib = u.protocol === "https:" ? https : http; const agent = deps.createSsrfSafeAgent(resolvedIp, u.protocol, originalHostname); requestOptions = { method, hostname: resolvedIp, port: u.port || (u.protocol === "https:" ? 443 : 80), path: u.pathname + u.search, headers: { ...headers, "Host": originalHostname, }, agent: agent, ...(u.protocol === "https:" ? { servername: deps.tlsServernameForHost(originalHostname) } : {}), }; fullUrl = null; } if (settled || Date.now() >= deadline) return fail({ status: 0, json: null }); req = fullUrl ? lib.request(fullUrl, requestOptions, handleResponse) : lib.request(requestOptions, handleResponse); // Panel-side cap for buffered node responses. The daemon serves file // reads up to 10 MiB (maxEditorRead = 10 << 20, handleFSRead in main.go) // and puts no size cap on /v1/fs/list output, so a legal payload can // reach ~10 MiB before JSON encoding; base64 encoding inflates it 4/3 // (~13.7 MiB) and JSON string escaping adds more for escape-heavy text. // 16 MiB fits every daemon-legal read/list response with headroom; a // body beyond it fails as { error: "response too large", tooLarge: true } // so routes can answer node_response_too_large instead of node_offline. const MAX_RESPONSE_BYTES = 16 * 1024 * 1024; const tooLargeResult = () => (includeText ? { status: 0, json: null, text: null, error: "response too large", tooLarge: true } : { status: 0, json: null, error: "response too large", tooLarge: true }); function handleResponse(res) { response = res; // adpanel:node-http-cap-error-listeners - even a header-only refusal // destroys a response that can emit a late error or aborted event. res.on("error", () => fail(noBodyResult())); res.on("aborted", () => fail(noBodyResult())); res.on("close", () => { if (!settled) fail(noBodyResult()); }); if (settled) { destroyStreams(res, req); return; } if (Date.now() >= deadline) { fail({ status: 0, json: null }); return; } const statusCode = res.statusCode || 0; const chunks = []; let totalBytes = 0; // maxBytes is an optional per-call cap for callers that must not // buffer large bodies. Callers that omit it get MAX_RESPONSE_BYTES. const byteCap = Number.isFinite(maxBytes) && maxBytes > 0 ? maxBytes : MAX_RESPONSE_BYTES; { const contentLength = parseInt(res.headers["content-length"], 10); // Compare against byteCap (not raw maxBytes) so a non-finite or // non-positive maxBytes falls back to the MAX_RESPONSE_BYTES guard // here exactly as the streaming check below does. if (Number.isFinite(contentLength) && contentLength > byteCap) { // Settle BEFORE destroying: destroy() on a mid-message // IncomingMessage emits 'aborted' synchronously, and finish() is // single-settle — destroying first let the aborted handler's // tooLarge-less shape win the race, misreporting an over-cap // dial as a generic transport failure instead of // node_response_too_large (surfaced by the Wave 3 behavioral // convergence tests; the old inline helpers never hit it because // they registered no aborted listener at all). fail(tooLargeResult()); return; } } res.on("data", (d) => { if (settled) return; totalBytes += d.length; if (totalBytes > byteCap) { // Settle-then-destroy, for the same aborted-listener race as the // Content-Length pre-check above. Destroying still stops the // drain (the over-cap remainder is never buffered); the promise // is already settled, so the destroy's own error/aborted events // are no-ops. fail(tooLargeResult()); return; } chunks.push(d); }); res.on("end", () => { if (settled) return; const bodyStr = Buffer.concat(chunks).toString("utf8"); try { const json = bodyStr ? JSON.parse(bodyStr) : null; finish(includeText ? { status: statusCode, json, text: bodyStr } : { status: statusCode, json }); } catch { finish(includeText ? { status: statusCode, json: null, text: bodyStr } : { status: statusCode, json: null }); } }); } req.on("timeout", () => { fail({ status: 0, json: null }); }); req.on("error", () => fail({ status: 0, json: null })); req.setTimeout(Math.max(1, deadline - Date.now())); // Bodies go out chunked (no explicit Content-Length): the Go daemon's // net/http server decodes both identically. The former nodes.js httpJson // set Content-Length explicitly — the relay consolidation accepted the // chunked form as the one request-wire delta of the hardened core // (Wave 2 review note). if (body != null) req.write(typeof body === "string" ? body : JSON.stringify(body)); req.end(); } catch { fail({ status: 0, json: null }); } }); } function httpStreamRequest(fullUrl, { method = "GET", headers = {}, bodyStream = null, timeoutMs = 120000, onRequest = null, nodeDial = false, idleTimeoutMs = 0 } = {}) { return new Promise((resolve, reject) => { let settled = false; let finished = false; let responseEnded = false; let req = null; let response = null; let hardTimer = null; const deadline = Date.now() + timeoutMs; const complete = () => { if (finished) return; finished = true; clearTimeout(hardTimer); }; const fail = (error) => { if (finished) return; complete(); if (bodyStream && req) bodyStream.unpipe(req); // adpanel:node-stream-lifetime - response headers transfer ownership, // not completion; late dial failures must still reach the body reader. if (response && !response.destroyed) response.destroy(error); destroyStreams(req, bodyStream); if (!settled) { settled = true; reject(error); } }; const active = () => { if (finished) return false; if (Date.now() >= deadline) { fail(new Error("timeout")); return false; } return true; }; hardTimer = setTimeout(() => fail(new Error("timeout")), timeoutMs); if (bodyStream) { bodyStream.on("error", fail); bodyStream.on("close", () => { if (!bodyStream.readableEnded) fail(new Error("Request body closed before end")); }); if (bodyStream.destroyed && !bodyStream.readableEnded) { fail(bodyStream.errored || new Error("Request body closed before end")); return; } } try { const isNodeAuthenticated = nodeDial || (headers && (headers["X-Node-Token"] || headers["Authorization"])); if (isNodeAuthenticated) { const guardError = nodeSsrfGuard.assertNodeUrlHostAllowed(fullUrl); if (guardError) return fail(guardError); } if (!active()) return; const isHttps = fullUrl.startsWith("https:"); const lib = isHttps ? https : http; const requestOptions = { method, headers }; if (isNodeAuthenticated) requestOptions.lookup = nodeSsrfGuard.guardedNodeLookup; const agent = nodeTlsAgent(fullUrl); if (agent) requestOptions.agent = agent; req = lib.request(fullUrl, requestOptions, (res) => { response = res; res.on("error", fail); res.on("aborted", () => fail(new Error("Node response aborted"))); res.on("close", () => { if (!responseEnded) fail(new Error("Node response closed before end")); }); res.once("end", () => { responseEnded = true; complete(); }); if (!active()) { destroyStreams(res, req); return; } if (idleTimeoutMs > 0 && res.statusCode === 200) { clearTimeout(hardTimer); req.setTimeout(idleTimeoutMs); } settled = true; resolve({ req, res }); }); req.on("error", fail); req.on("timeout", () => fail(new Error("timeout"))); req.on("close", () => { if (!response) fail(new Error("Node request closed before headers")); }); if (typeof onRequest === "function") { try { onRequest(req); } catch { } } if (!active()) { destroyStreams(req, bodyStream); return; } req.setTimeout(Math.max(1, deadline - Date.now())); if (bodyStream) bodyStream.pipe(req); else req.end(); } catch (error) { fail(error); } }); } // --------------------------------------------------------------------------- // Node base-URL plumbing — the byte-identical micro-helpers both former // buildNodeBaseUrl twins closed over. They were duplicated verbatim in // index.js and nodes.js; the monoliths now import THESE copies (same // identifiers) so the set cannot drift again. // --------------------------------------------------------------------------- function truthyFlag(value) { if (typeof value === "boolean") return value; if (typeof value === "number") return value === 1; if (typeof value === "string") { const normalized = value.trim().toLowerCase(); return normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on"; } return false; } const CLOUDFLARE_HTTPS_EDGE_PORTS = new Set([443, 2053, 2083, 2087, 2096, 8443]); // Formerly a twin pair: index.js clamped with clampApiPort, nodes.js with its // clampPort. The clamp is now a parameter; each caller's factory binds its own // so outputs stay byte-identical. Module-private: only the shared // buildNodeBaseUrl below calls it. function cloudflareHttpsEdgePort(port, clamp) { const p = clamp(port || 443); return CLOUDFLARE_HTTPS_EDGE_PORTS.has(p) ? p : 443; } function hasExplicitHostPort(host) { const value = String(host || "").trim(); if (value.startsWith("[")) return /\]:\d+$/.test(value); return /^[^:]+:\d+$/.test(value); } function explicitHostPort(host) { const value = String(host || "").trim(); const match = value.startsWith("[") ? value.match(/\]:(\d+)$/) : value.match(/^[^:]+:(\d+)$/); return match ? Number(match[1]) : null; } function stripExplicitHostPort(host) { const value = String(host || "").trim(); if (!hasExplicitHostPort(value)) return value; if (value.startsWith("[")) return value.replace(/\]:\d+$/, "]"); return value.replace(/:\d+$/, ""); } // --------------------------------------------------------------------------- // buildNodeBaseUrl — index.js's version is the shared one, with every // nodes.js delta parameterized so BOTH callers keep byte-identical outputs: // clampEdgePort index.js: clampApiPort nodes.js: clampPort // clampUrlPathPort index.js: clampApiPort nodes.js: identity (the // nodes.js twin did NOT clamp an explicit-URL branch port) // clampBareHostPort index.js: clampApiPort nodes.js: clampPort // returnOrigin index.js: true (u.origin) nodes.js: false // (u.toString().replace(/\/$/, "")) // THE ONE UNCONDITIONAL HARDENING (both surfaces): credential-in-URL // rejection. A node address embedding user:pass is a malformed configuration; // the former nodes.js twin forwarded it verbatim (credentials leaking into // every upstream URL), index.js already refused. Fail-closed on both now. // --------------------------------------------------------------------------- function createBuildNodeBaseUrl(opts = {}) { const clampEdgePort = opts.clampEdgePort; const clampUrlPathPort = opts.clampUrlPathPort; const clampBareHostPort = opts.clampBareHostPort; const returnOrigin = opts.returnOrigin === true; if (typeof clampEdgePort !== "function" || typeof clampUrlPathPort !== "function" || typeof clampBareHostPort !== "function") { throw new Error("createBuildNodeBaseUrl requires clampEdgePort, clampUrlPathPort and clampBareHostPort functions"); } return function buildNodeBaseUrl(address, port, sslEnabled, underCloudflare = false) { let base = String(address || "").trim(); if (!base) return null; const cloudflareProxy = truthyFlag(underCloudflare); if (/^https?:\/\//i.test(base)) { try { const u = new URL(base); // adpanel:relay-helper-consolidation — HARDENING (both surfaces): a // node address embedding credentials is malformed config; refuse it // instead of dialing with the credentials in every upstream URL. if (u.username || u.password) return null; u.hash = ""; u.search = ""; u.pathname = ""; const authority = base.match(/^https?:\/\/([^/?#\\]*)/i)?.[1]; const addressPort = u.port || explicitHostPort(authority); if (cloudflareProxy) { u.protocol = "https:"; const edgePort = cloudflareHttpsEdgePort(addressPort || port, clampEdgePort); u.port = edgePort === 443 ? "" : String(edgePort); return returnOrigin ? u.origin : u.toString().replace(/\/$/, ""); } // adpanel:node-tls — an explicit HTTP address cannot override enabled TLS. if (sslEnabled) u.protocol = "https:"; u.port = String(addressPort || clampUrlPathPort(port || 8080)); return returnOrigin ? u.origin : u.toString().replace(/\/$/, ""); } catch { } } if (cloudflareProxy) { base = base.split(/[/?#]/)[0]; const edgePort = cloudflareHttpsEdgePort(explicitHostPort(base) || port, clampEdgePort); base = stripExplicitHostPort(base); if (edgePort !== 443) base += `:${edgePort}`; return `https://${base}`; } // adpanel:node-tls-default - node routes must not downgrade the panel's configured default. const configuredScheme = String(process.env.NODE_DEFAULT_SCHEME || "http").trim().toLowerCase(); const defaultScheme = sslEnabled ? "https" : configuredScheme; if (defaultScheme !== "http" && defaultScheme !== "https") return null; base = base.split(/[/?#]/)[0]; if (hasExplicitHostPort(base)) return `${defaultScheme}://${base}`; if (isIP(base) === 6) base = `[${base}]`; return `${defaultScheme}://${base}:${clampBareHostPort(port || 8080)}`; }; } // --------------------------------------------------------------------------- // Node auth headers — one core, two former twins behind parameters: // index.js nodeAuthHeadersFor(node, isRemote): Content-Type on EVERY header // set; remote token resolved as node.token || node.secret || node.api_key; // X-Node-Token-Id only when token_id is truthy; non-remote (local daemon) // dials authenticate with index.js's LOCAL_NODE_TOKEN (injected by the // caller — it is index.js module state). // nodes.js nodeHeaders(node): no Content-Type; token from node.token only; // X-Node-Token-Id ALWAYS present, possibly "" (alwaysSendTokenId). // Each caller keeps its exact current header shape and key set. // --------------------------------------------------------------------------- function buildNodeAuthHeaders(node, opts = {}) { const isRemote = opts.isRemote !== false; const includeContentType = opts.includeContentType !== false; const alwaysSendTokenId = opts.alwaysSendTokenId === true; const tokenFields = opts.tokenFields || ["token", "secret", "api_key"]; const localNodeToken = opts.localNodeToken || null; const h = includeContentType ? { "Content-Type": "application/json" } : {}; const remoteToken = node && tokenFields.map((f) => node[f]).find((v) => v); if (isRemote && (remoteToken || alwaysSendTokenId)) { const token = remoteToken || ""; h.Authorization = `Bearer ${token}`; h["X-Node-Token"] = token; if (alwaysSendTokenId) h["X-Node-Token-Id"] = node.token_id || ""; else if (node.token_id) h["X-Node-Token-Id"] = node.token_id; return h; } if (!isRemote && localNodeToken) { h.Authorization = `Bearer ${localNodeToken}`; h["X-Node-Token"] = localNodeToken; } return h; } // The nodes.js relay shape, verbatim (the twin nodes.js carried): every dial // identifies the token slot even when the token/token_id fields are empty. function nodeHeaders(node) { return buildNodeAuthHeaders(node, { isRemote: true, includeContentType: false, alwaysSendTokenId: true, tokenFields: ["token"], }); } function nodeUnderCloudflare(node) { const bc = node?.buildConfig; // adpanel:node-proxy-state — a saved disable must override the row's stale derived flag. if (typeof bc?.under_cloudflare !== "undefined") return truthyFlag(bc.under_cloudflare); return truthyFlag(node?.under_cloudflare) || truthyFlag(node?.cloudflare_proxy) || truthyFlag(bc?.cloudflare_proxy); } function nodeConnectionState(node, patch = {}, build = false) { const currentTls = !!node.buildConfig?.ssl_enabled; const ssl = patch.ssl_enabled === undefined ? currentTls : truthyFlag(patch.ssl_enabled); const rawProxy = build ? patch.under_cloudflare ?? patch.cloudflare_proxy : patch.under_cloudflare === undefined ? patch.cloudflare_proxy : patch.under_cloudflare; const currentProxy = nodeUnderCloudflare(node); const hasProxyFlag = patch.under_cloudflare !== undefined || patch.cloudflare_proxy !== undefined; const proxy = hasProxyFlag ? ssl && truthyFlag(rawProxy) : patch.ssl_enabled !== undefined && !ssl ? false : currentProxy; const rawPort = !build && patch.api_port !== undefined ? patch.api_port : node.api_port; const port = Math.round(Number(rawPort)); const address = !build && patch.address !== undefined ? patch.address : node.address; return JSON.stringify([String(address || "").trim(), port >= 1 && port <= 65535 ? port : 8080, ssl, proxy]); } // adpanel:console-stream-deadline - wait for headers, then allow for the // daemon's 15-second heartbeats without keeping a stalled tail registered. function openNodeConsoleLogStream(url, headers, onRequest) { const streamHeaders = { ...headers, Accept: "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" }; delete streamHeaders["Content-Type"]; return httpStreamRequest(url, { headers: streamHeaders, onRequest, nodeDial: true, timeoutMs: 15_000, idleTimeoutMs: 45_000 }); } module.exports = { httpStreamRequest, openNodeConsoleLogStream, configureNodeHttp, httpRequestJson, hasVerifiedNodeHttps, nodeTlsAgent, truthyFlag, CLOUDFLARE_HTTPS_EDGE_PORTS, hasExplicitHostPort, explicitHostPort, stripExplicitHostPort, createBuildNodeBaseUrl, buildNodeAuthHeaders, nodeHeaders, nodeUnderCloudflare, nodeConnectionState, };