openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
511 lines (510 loc) • 19.4 kB
JavaScript
import { y as toErrorObject } from "./paths-0xDagtub.mjs";
import { p as isRecord } from "./utils-BclMknzT.mjs";
import { B as normalizeOptionalString, D as floorPositiveFiniteNumber, L as normalizeLowercaseStringOrEmpty } from "./path-guards-quCEQx1i.mjs";
import { Z as expectDefined } from "./redact-BRF0hr6G.mjs";
import { t as formatErrorMessage } from "./errors-hqLS1E8Y.mjs";
import { t as logDebug } from "./logger-DlJKXoGM.mjs";
import { createRequire } from "node:module";
import { readFileSync } from "node:fs";
import fsPromises, { readFile } from "node:fs/promises";
import * as net$1 from "node:net";
import net from "node:net";
import { EventEmitter } from "node:events";
//#region src/infra/net/proxy-env.ts
function readProxyEnvValue(e, t) {
const n = t[e];
return normalizeOptionalString(typeof n === "string" ? n : t[e.toUpperCase()]);
}
/**
* Match undici EnvHttpProxyAgent semantics for env-based HTTP/S proxy selection:
* - lower-case vars take precedence over upper-case
* - HTTPS requests prefer https_proxy/HTTPS_PROXY, then fall back to http_proxy/HTTP_PROXY
* - ALL_PROXY is ignored by EnvHttpProxyAgent
*/
function resolveEnvHttpProxyUrl(e, t = process.env) {
const n = readProxyEnvValue("http_proxy", t);
const r = readProxyEnvValue("https_proxy", t);
return e === "https" ? r ?? n : n;
}
/** Return whether EnvHttpProxyAgent-style HTTP/S proxy resolution finds a proxy URL. */
function hasEnvHttpProxyConfigured(e = "https", t = process.env) {
return resolveEnvHttpProxyUrl(e, t) !== void 0;
}
/**
* Build explicit options for undici's EnvHttpProxyAgent.
*
* EnvHttpProxyAgent does not read ALL_PROXY itself, but it accepts explicit
* HTTP/HTTPS proxy overrides. Keep this helper separate from the
* HTTP(S)-only URL helpers so SSRF trusted-env proxy gates do not widen.
*/
function resolveEnvHttpProxyAgentOptions(e = process.env) {
const t = readProxyEnvValue("all_proxy", e);
const n = resolveEnvHttpProxyUrl("http", e) ?? t;
const r = resolveEnvHttpProxyUrl("https", e) ?? n;
const i = {
...n ? { httpProxy: n } : {},
...r ? { httpsProxy: r } : {}
};
return i.httpProxy || i.httpsProxy ? i : void 0;
}
/** Return whether a target URL should use configured HTTP/S env proxy variables. */
function shouldUseEnvHttpProxyForUrl(e, t = process.env) {
const n = URL.parse(e);
if (!n || n.protocol !== "http:" && n.protocol !== "https:") return false;
return hasEnvHttpProxyConfigured(n.protocol === "https:" ? "https" : "http", t) && !matchesNoProxy(n, t);
}
/**
* Check whether a target URL should bypass the HTTP proxy per NO_PROXY env var.
*
* Mirrors undici EnvHttpProxyAgent semantics
* (`undici/lib/dispatcher/env-http-proxy-agent.js`):
* - Entries separated by commas OR whitespace (undici splits on `/[,\s]/`)
* - Case-insensitive
* - A single trailing DNS dot is ignored in both hosts and entries
* - Lower-case `no_proxy` shadows upper-case `NO_PROXY`, including blank values
* - Empty or missing → no bypass
* - Bare `*` value → bypass everything
* - Exact hostname match
* - Leading-dot match (`.example.com` matches `foo.example.com`)
* - Leading `*.` wildcard match (`*.example.com` matches `foo.example.com`);
* undici normalizes via `.replace(/^\*?\./, '')`, so the bare domain also
* matches (kept in sync with that behavior)
* - Subdomain suffix match (`openai.com` matches `api.openai.com`)
* - Optional `:port` suffix; when present, must match target port
* - IPv6 literals in bracketed (`[::1]`) or bare (`::1`) form
* - OpenClaw extension: IPv4 CIDR and octet-wildcard entries
* (`100.64.0.0/10`, `100.64.*`) bypass the trusted env proxy mode before
* undici's EnvHttpProxyAgent is selected.
*
* Undici does not export its matcher, so this is a targeted reimplementation
* kept in sync with the upstream file above. Paired with
* `hasEnvHttpProxyConfigured` this gates the trusted-env-proxy auto-upgrade
* in provider HTTP helpers; see openclaw#64974 review thread on NO_PROXY
* SSRF bypass.
*/
function matchesNoProxy(e, t = process.env) {
const n = t.no_proxy ?? t.NO_PROXY ?? "";
if (!n) return false;
const r = e instanceof URL ? e : URL.parse(e);
if (!r) return false;
const i = r.hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/^(.+)\.$/, "$1");
if (!i) return false;
if (n === "*") return true;
const a = parseIpv4Address(i);
const o = r.port !== "" ? r.port : r.protocol === "https:" ? "443" : r.protocol === "http:" ? "80" : "";
for (const e of n.split(/[,\s]/)) {
const t = e.trim().toLowerCase();
if (!t) continue;
let n;
let r;
if (t.startsWith("[")) {
const e = t.match(/^\[([^\]]+)\](?::(\d+))?$/);
if (!e) continue;
n = expectDefined(e[1], "m capture group 1");
r = e[2];
} else {
const e = t.indexOf(":");
const i = t.lastIndexOf(":");
if (e > -1 && e === i && /^\d+$/.test(t.slice(i + 1))) {
n = t.slice(0, i);
r = t.slice(i + 1);
} else n = t;
}
if (r && r !== o) continue;
const s = n.replace(/^\*?\./, "").replace(/^(.+)\.$/, "$1");
if (!s || s === "*") continue;
if (matchesIpv4NoProxyPattern(a, s)) return true;
if (i === s) return true;
if (i.endsWith("." + s)) return true;
}
return false;
}
function parseIpv4Address(e) {
const t = e.split(".");
if (t.length !== 4) return;
let n = 0;
for (const e of t) {
if (!/^\d{1,3}$/.test(e)) return;
const t = Number(e);
if (t > 255) return;
n = n << 8 | t;
}
return n >>> 0;
}
function matchesIpv4NoProxyPattern(e, t) {
if (e === void 0) return false;
const n = t.match(/^(\d{1,3}(?:\.\d{1,3}){3})\/(\d{1,2})$/);
if (n) {
const t = parseIpv4Address(expectDefined(n[1], "cidr match capture group 1"));
const r = Number(n[2]);
if (t === void 0 || r > 32) return false;
const i = r === 0 ? 0 : 4294967295 << 32 - r >>> 0;
return (e & i) === (t & i);
}
if (!t.includes("*")) return false;
const r = t.split(".");
if (r.length > 4) return false;
for (const [t, n] of r.entries()) {
if (n === "*") {
if (t === r.length - 1) return true;
continue;
}
if (!/^\d{1,3}$/.test(n) || Number(n) !== (e >>> (3 - t) * 8 & 255)) return false;
}
return r.length === 4;
}
//#endregion
//#region src/infra/net/proxy/active-proxy-state.ts
let activeProxyUrl;
let activeProxyLoopbackMode;
let activeProxyTlsOptions;
function parseActiveManagedProxyLoopbackMode(e) {
if (e === "gateway-only" || e === "proxy" || e === "block") return e;
}
function readInheritedActiveManagedProxyLoopbackMode() {
if (process.env["OPENCLAW_PROXY_ACTIVE"] !== "1") return;
return parseActiveManagedProxyLoopbackMode(process.env["OPENCLAW_PROXY_LOOPBACK_MODE"]) ?? "gateway-only";
}
/** Returns local loopback policy from in-process state or inherited proxy env. */
function getActiveManagedProxyLoopbackMode() {
return activeProxyLoopbackMode ?? readInheritedActiveManagedProxyLoopbackMode();
}
/** Returns the in-process managed proxy URL, if this process owns the proxy. */
function getActiveManagedProxyUrl() {
return activeProxyUrl;
}
/** Returns the active managed proxy TLS options used by undici/proxyline dispatchers. */
function getActiveManagedProxyTlsOptions() {
return activeProxyTlsOptions;
}
//#endregion
//#region src/infra/net/proxy/proxy-tls.ts
/** Returns a CA file only for HTTPS proxy URLs; HTTP proxies do not need TLS trust. */
function resolveManagedProxyCaFileForUrl(e) {
if (!e.proxyUrl || URL.parse(e.proxyUrl)?.protocol !== "https:") return;
return normalizeOptionalString(e.caFileOverride) ?? normalizeOptionalString(e.config?.tls?.caFile);
}
/** Loads managed proxy TLS options synchronously for inherited child-process routing. */
function loadManagedProxyTlsOptionsSync(e) {
if (!e) return;
try {
return { ca: readFileSync(e, "utf8") };
} catch (t) {
throw new Error(`proxy CA file could not be read (${e}): ${formatErrorMessage(t)}`, { cause: t });
}
}
//#endregion
//#region src/infra/net/proxy/active-managed-proxy-tls.ts
function normalizeProxyUrl(e) {
return e ? URL.parse(e)?.href : void 0;
}
function resolveManagedProxyUrl(e = process.env) {
const t = getActiveManagedProxyUrl();
if (t) return t.href;
if (e.OPENCLAW_PROXY_ACTIVE !== "1") return;
return normalizeProxyUrl(resolveEnvHttpProxyUrl("https", e));
}
/** Resolves managed proxy TLS trust only when the target proxy is OpenClaw's active proxy. */
function resolveActiveManagedProxyTlsOptions(e) {
const t = e?.env ?? process.env;
const n = resolveManagedProxyUrl(t);
const r = normalizeProxyUrl(e?.proxyUrl ?? resolveEnvHttpProxyUrl("https", t));
if (!n || r !== n) return;
const i = getActiveManagedProxyTlsOptions();
if (i) return i;
const a = resolveManagedProxyCaFileForUrl({
proxyUrl: n,
caFileOverride: t.OPENCLAW_PROXY_CA_FILE
});
try {
return loadManagedProxyTlsOptionsSync(a);
} catch {
return;
}
}
//#endregion
//#region src/infra/net/proxy/managed-proxy-undici.ts
function readProxyTlsRecord(e) {
if (!e || !("proxyTls" in e)) return;
return isRecord(e.proxyTls) ? e.proxyTls : void 0;
}
function readProxyUrlFromOptions(e) {
if (!e) return;
if ("uri" in e) {
const t = e.uri;
return t instanceof URL ? t.href : typeof t === "string" ? t : void 0;
}
if ("httpsProxy" in e || "httpProxy" in e) {
const t = Reflect.get(e, "httpsProxy");
const n = Reflect.get(e, "httpProxy");
return typeof t === "string" ? t : typeof n === "string" ? n : void 0;
}
}
function addActiveManagedProxyTlsOptions(e, t) {
const n = resolveActiveManagedProxyTlsOptions({
proxyUrl: readProxyUrlFromOptions(e),
env: t?.env
});
if (!n) return e;
const r = readProxyTlsRecord(e);
return {
...e,
proxyTls: {
...n,
...r
}
};
}
//#endregion
//#region src/infra/net/undici-error-diagnostics.ts
const observedDispatcherValues = /* @__PURE__ */ new WeakSet();
function logUndiciDispatcherError(e) {
logDebug(`undici: internal dispatcher error: ${formatErrorMessage(e)}`);
}
function observeDispatcherValue(e) {
if (typeof e !== "object" && typeof e !== "function" || e === null) return;
if (observedDispatcherValues.has(e)) return;
observedDispatcherValues.add(e);
if (e instanceof EventEmitter) {
EventEmitter.prototype.on.call(e, "error", logUndiciDispatcherError);
EventEmitter.prototype.on.call(e, "connect", (e, t) => {
observeDispatcherValue(t);
});
for (const t of Reflect.ownKeys(e)) {
const n = Object.getOwnPropertyDescriptor(e, t);
if (n && "value" in n) observeDispatcherValue(n.value);
}
return;
}
if (Array.isArray(e) || e instanceof Set || e instanceof Map) for (const t of e instanceof Map ? e.values() : e) observeDispatcherValue(t);
}
function withUndiciErrorDiagnostics(e) {
observeDispatcherValue(e);
return e;
}
//#endregion
//#region src/infra/wsl.ts
/** Detects WSL2 from kernel-version markers, which also establish WSL itself. */
function isWSL2Sync() {
if (process.platform !== "linux") return false;
try {
const e = normalizeLowercaseStringOrEmpty(readFileSync("/proc/version", "utf8"));
return e.includes("wsl2") || e.includes("microsoft-standard");
} catch {
return false;
}
}
//#endregion
//#region src/infra/net/undici-family-policy.ts
const AUTO_SELECT_FAMILY_ATTEMPT_TIMEOUT_MS = 300;
/** Resolves the process default autoSelectFamily policy, with WSL2 forced to IPv4. */
function resolveUndiciAutoSelectFamily() {
const e = net$1.getDefaultAutoSelectFamily();
if (e && isWSL2Sync()) return false;
return e;
}
function createUndiciAutoSelectFamilyConnectOptions(e) {
if (e === void 0) return;
return {
autoSelectFamily: e,
autoSelectFamilyAttemptTimeout: AUTO_SELECT_FAMILY_ATTEMPT_TIMEOUT_MS
};
}
/** Returns shared undici connect options for dispatchers that do not override them. */
function resolveUndiciAutoSelectFamilyConnectOptions() {
return createUndiciAutoSelectFamilyConnectOptions(resolveUndiciAutoSelectFamily());
}
//#endregion
//#region src/infra/net/undici-dispatcher-options.ts
const TEST_UNDICI_RUNTIME_DEPS_KEY = "__OPENCLAW_TEST_UNDICI_RUNTIME_DEPS__";
const requireUndici = createRequire(import.meta.url);
let undiciModule;
let globalUndiciStreamTimeoutMs;
function loadUndiciModule(e) {
const t = globalThis[TEST_UNDICI_RUNTIME_DEPS_KEY];
if (isRecord(t) && e.every((e) => typeof t[e] === "function")) return t;
return undiciModule ??= requireUndici("undici/index.js");
}
function createHttp1ProxyClient(e, t) {
const n = isRecord(t) ? t.connect : void 0;
return createUndiciPool(e, {
...t,
...typeof n === "function" ? { connect: (e, t) => {
const { servername: r, ...i } = e;
return n(r && net.isIP(r.replace(/^\[|\]$/g, "")) ? i : e, t);
} } : {}
});
}
/** Prepare proxy transport without transferring direct-origin TLS or DNS policy. */
function buildProxyConnectOptions(e, t) {
const n = {
...resolveUndiciAutoSelectFamilyConnectOptions(),
...typeof e.connect === "object" ? e.connect : {}
};
const r = floorPositiveFiniteNumber(t);
return {
autoSelectFamily: n.autoSelectFamily,
autoSelectFamilyAttemptTimeout: n.autoSelectFamilyAttemptTimeout,
family: "family" in n ? n.family : void 0,
keepAlive: n.keepAlive,
keepAliveInitialDelay: n.keepAliveInitialDelay,
timeout: e.connectTimeout,
...e.proxyTls,
...r !== void 0 ? { timeout: r } : {},
allowH2: false
};
}
function createUndiciClient(e, t) {
const { Client: n } = loadUndiciModule(["Client"]);
return withUndiciErrorDiagnostics(new n(e, t));
}
function createUndiciPool(e, t) {
const { Pool: n } = loadUndiciModule(["Pool"]);
return withUndiciErrorDiagnostics(new n(e, {
...t,
factory: createUndiciClient
}));
}
function createUndiciOriginDispatcher(e, t) {
return t.connections === 1 ? createUndiciClient(e, t) : createUndiciPool(e, t);
}
function buildHttp1AgentOptions(e = {}, t) {
const n = floorPositiveFiniteNumber(t);
return {
factory: createUndiciOriginDispatcher,
...e,
allowH2: false,
connect: typeof e.connect === "function" ? e.connect : {
...resolveUndiciAutoSelectFamilyConnectOptions(),
...e.connect,
...n !== void 0 ? { timeout: n } : {}
},
bodyTimeout: n ?? e.bodyTimeout ?? globalUndiciStreamTimeoutMs,
headersTimeout: n ?? e.headersTimeout ?? globalUndiciStreamTimeoutMs
};
}
function buildHttp1ProxyAgentOptions(e, t, n) {
const r = typeof e === "string" || e instanceof URL ? { uri: e.toString() } : e;
const { clientFactory: i = createHttp1ProxyClient } = r;
const a = addActiveManagedProxyTlsOptions(r, { env: n });
return {
proxyTunnel: true,
...a,
...buildHttp1AgentOptions(a, t),
clientFactory: i
};
}
//#endregion
//#region src/infra/net/undici-runtime.ts
/** Loads undici lazily, allowing tests to inject constructors without global side effects. */
function loadUndiciRuntimeDeps() {
return loadUndiciModule([
"Agent",
"EnvHttpProxyAgent",
"ProxyAgent",
"fetch"
]);
}
/** Loads only the undici global-dispatcher API used by startup proxy setup. */
function loadUndiciGlobalDispatcherDeps() {
return loadUndiciModule(["getGlobalDispatcher", "setGlobalDispatcher"]);
}
/** Creates a direct undici Agent with OpenClaw's HTTP/1-only dispatcher policy. */
function createHttp1Agent(e, t) {
const { Agent: n } = loadUndiciRuntimeDeps();
return withUndiciErrorDiagnostics(new n(buildHttp1AgentOptions(e, t)));
}
function isSocksProxy(e) {
return e !== void 0 && ["socks:", "socks5:"].includes(URL.parse(e)?.protocol ?? "");
}
function createSocksProxyAgent(e, t) {
const { Agent: n, Socks5ProxyAgent: r, buildConnector: i, errors: a } = loadUndiciModule([
"Agent",
"Socks5ProxyAgent",
"buildConnector"
]);
if (typeof e.clientFactory !== "function") throw new a.InvalidArgumentError("Proxy opts.clientFactory must be a function.");
if (e.auth && e.token) throw new a.InvalidArgumentError("opts.auth cannot be used in combination with opts.token");
const o = i(buildProxyConnectOptions(e, t));
class SocksProxyAgent extends n {}
const s = withUndiciErrorDiagnostics(new SocksProxyAgent({
...e,
factory: () => withUndiciErrorDiagnostics(new r(e.uri, {
...e,
connect: o
}))
}));
const c = {
connections: e.connections,
pipelining: e.pipelining,
bodyTimeout: e.bodyTimeout,
headersTimeout: e.headersTimeout
};
return s.compose((e) => (t, n) => {
const r = t.headers;
const i = Array.isArray(r) ? r.filter((e, t) => t % 2 === 0) : [];
if (!Array.isArray(r)) for (const e in r) i.push(e);
if (i.some((e) => typeof e === "string" && e.toLowerCase() === "proxy-authorization")) throw new a.InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
return e({
...c,
...t
}, n);
});
}
function completeProxyLifecycle(e, t) {
if (t !== void 0 && typeof t !== "function") {
const { errors: e } = loadUndiciModule([]);
throw new e.InvalidArgumentError("invalid callback");
}
const n = e().then(() => void 0);
if (t) n.then(() => t(null, null), (e) => t(toErrorObject(e, "Proxy shutdown failed"), null));
else return n;
}
/** Creates an env dispatcher with per-hop connectors and the existing dynamic bypass policy. */
function createHttp1EnvHttpProxyAgent(e, t, n) {
const { EnvHttpProxyAgent: r } = loadUndiciRuntimeDeps();
const i = e?.httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY;
const a = (e?.httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY) || i;
const o = /* @__PURE__ */ new Map();
for (const r of [i, a]) if (r && !o.has(r)) o.set(r, createHttp1ProxyAgent({
...e,
uri: r
}, t, n));
const s = withUndiciErrorDiagnostics(new r({
...buildHttp1AgentOptions(e, t),
httpProxy: "",
httpsProxy: "",
noProxy: "*"
}));
if (o.size === 0) return s;
const c = [s, ...o.values()];
const isDestroyed = () => c.every((e) => Reflect.get(e, "destroyed") === true);
let l;
return new Proxy(s, { get(t, n, r) {
if (n === "destroyed") return isDestroyed();
if (n === "dispatch") return (n, r) => {
const s = n?.origin ? URL.parse(String(n.origin)) : null;
const c = s?.protocol === "https:" ? a : i;
const l = c && o.get(c);
const u = e?.noProxy === void 0 ? process.env : { no_proxy: e.noProxy };
return l && s && !matchesNoProxy(s, u) ? l.dispatch(n, r) : t.dispatch(n, r);
};
if (n === "close") return (e) => completeProxyLifecycle(() => isDestroyed() ? t.close() : l ??= Promise.all(c.map((e) => e.close())).finally(() => {
l = void 0;
}), e);
if (n === "destroy") return (e, t) => completeProxyLifecycle(() => Promise.all(c.map((t) => t.destroy(typeof e === "function" ? null : e ?? null))), typeof e === "function" ? e : t);
return Reflect.get(t, n, r);
} });
}
/** Creates a fixed proxy dispatcher without using TLS options for plain TCP policy. */
function createHttp1ProxyAgent(e, t, n) {
const r = buildHttp1ProxyAgentOptions(e, t, n);
if (isSocksProxy(r.uri)) return createSocksProxyAgent(r, t);
const { ProxyAgent: i } = loadUndiciRuntimeDeps();
return withUndiciErrorDiagnostics(new i({
...r,
proxyTls: buildProxyConnectOptions(r, t)
}));
}
//#endregion
export { loadUndiciRuntimeDeps as a, resolveActiveManagedProxyTlsOptions as c, getActiveManagedProxyLoopbackMode as d, resolveEnvHttpProxyAgentOptions as f, loadUndiciGlobalDispatcherDeps as i, loadManagedProxyTlsOptionsSync as l, createHttp1EnvHttpProxyAgent as n, globalUndiciStreamTimeoutMs as o, shouldUseEnvHttpProxyForUrl as p, createHttp1ProxyAgent as r, resolveUndiciAutoSelectFamilyConnectOptions as s, createHttp1Agent as t, resolveManagedProxyCaFileForUrl as u };