openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
29 lines • 30.3 kB
JavaScript
import{a as isCloudMetadataIpAddress,c as isLinkLocalIpAddress,f as isUnspecifiedIpAddress,h as parseLooseIpAddress,i as isCanonicalDottedDecimalIPv4,l as isLoopbackIpAddress,m as parseCanonicalIpAddress,n as isBlockedSpecialUseIpv4Address,o as isIpv4Address,r as isBlockedSpecialUseIpv6Address,s as isLegacyIpv4Literal,t as extractEmbeddedIpv4FromIpv6}from"./ip-D5sFl_15.mjs";import{n as normalizeLowercaseStringOrEmpty}from"./string-coerce-BBqv4GXj.mjs";import{a as raceWithTimeout,i as racePromiseWithAbortSignal}from"./src-CY_qXgOR.mjs";import{o as resolveSafeTimeoutDelayMs}from"./timeouts-_PMLOAsc.mjs";import{L as truncateUtf16Safe,R as redactSensitiveUrlLikeString}from"./redact-LQdRaLFO.mjs";import{t as expectDefined}from"./expect-DkJCbmLj.mjs";import{t as cancelUnreadResponseBody}from"./http-body-BRjD2txO.mjs";import{l as normalizeUniqueStringEntries}from"./string-normalization-mfgVoo8i.mjs";import"./prototype-keys-DI_O-fr9.mjs";import{t as createSubsystemLogger}from"./subsystem-BMw5Czn-.mjs";import{t as isPromiseLike}from"./promise-like-OKzBwzLG.mjs";import{t as AsyncContext}from"./async-context-BikFC1Fp.mjs";import{r as logWarn}from"./logger-DmLqrh-9.mjs";import{a as loadUndiciRuntimeDeps,d as getActiveManagedProxyLoopbackMode,n as createHttp1EnvHttpProxyAgent,o as globalUndiciStreamTimeoutMs,p as shouldUseEnvHttpProxyForUrl,r as createHttp1ProxyAgent,s as resolveUndiciAutoSelectFamilyConnectOptions,t as createHttp1Agent}from"./undici-runtime-CiEGgc_q.mjs";import{n as normalizeHeadersInitForFetch,r as normalizeRequestInitHeadersForFetch}from"./fetch-headers-XNg_3XDQ.mjs";import{AsyncLocalStorage}from"node:async_hooks";import{lookup}from"node:dns";import dns from"node:dns/promises";
//!src/shared/monotonic-time.ts
function monotonicNow(){return performance.now()}
//!src/shared/effect-authority.ts
function captureEffectAuthority(){return{active:false,run(e){return e()},async initiate(e){return e()}}}
//!src/utils/fetch-timeout.ts
const log=createSubsystemLogger(`fetch-timeout`);const LOG_URL_MAX_CHARS=500;const URL_SECRET_SUFFIX_PATTERN=/[?#]/;function sanitizeTimeoutLogUrl(e){const t=e?.trim();if(!t)return;try{const e=new URL(t);e.username=``;e.password=``;e.search=``;e.hash=``;const n=redactSensitiveUrlLikeString(e.toString());return n.length>LOG_URL_MAX_CHARS?`${truncateUtf16Safe(n,LOG_URL_MAX_CHARS)}...`:n}catch{const e=t.split(URL_SECRET_SUFFIX_PATTERN,1)[0]??``;const n=redactSensitiveUrlLikeString(e.replace(/[\r\n\u2028\u2029]+/g,` `).replace(/\p{Cc}+/gu,` `).replace(/\s+/g,` `).trim());if(!n)return;return n.length>LOG_URL_MAX_CHARS?`${truncateUtf16Safe(n,LOG_URL_MAX_CHARS)}...`:n}}function abortDueToTimeout(e,t,n,r,i,a,o=true){if(a?.aborted??e.signal.aborted)return;const s=sanitizeTimeoutLogUrl(i);const c=Math.max(0,monotonicNow()-n);const l=Math.max(0,c-t);const u=l>=Math.max(1e3,t*.5)?`timer delayed ${l}ms, likely event-loop starvation`:null;const d=[`fetch timeout after ${t}ms`,`(elapsed ${c}ms)`,u,r?`operation=${r}`:null,s?`url=${s}`:null].filter(e=>Boolean(e)).join(` `);if(o)log.warn(`fetch timeout reached; aborting operation`,{timeoutMs:t,elapsedMs:c,...u?{timerDelayMs:l,eventLoopDelayHint:u}:{},consoleMessage:d,...r?{operation:r}:{},...s?{url:s}:{}});const f=/* @__PURE__ */ new Error(`request timed out`);f.name=`TimeoutError`;e.abort(f)}function buildTimeoutAbortSignal(e){const{timeoutMs:t,signal:n}=e;if(!t)return{signal:n,cleanup:()=>{},refresh:()=>{}};const r=new AbortController;const i=n?AbortSignal.any([n,r.signal]):r.signal;const a=resolveSafeTimeoutDelayMs(t);let o=true;let s;const scheduleTimeout=()=>{s=setTimeout(abortDueToTimeout,a,r,a,monotonicNow(),e.operation,e.url,i,e.logTimeout)};scheduleTimeout();return{signal:i,refresh:()=>{if(!o||i.aborted)return;clearTimeout(s);scheduleTimeout()},cleanup:()=>{o=false;clearTimeout(s)}}}
//!src/infra/net/hostname.ts
function normalizeHostname(e){const t=normalizeLowercaseStringOrEmpty(e).replace(/\.+$/,``);if(t.startsWith(`[`)&&t.endsWith(`]`))return t.slice(1,-1);return t}
//!src/infra/net/ssrf-trusted-host-linklocal-exemptions.ts
const podmanGatewayLinkLocalExemptPolicies=/* @__PURE__ */ new WeakSet;function withTrustedHostPodmanGatewayLinkLocalExemption(e){const t={...e};podmanGatewayLinkLocalExemptPolicies.add(t);return t}function hasTrustedHostPodmanGatewayLinkLocalExemption(e){return e!==void 0&&podmanGatewayLinkLocalExemptPolicies.has(e)}
//!src/infra/net/ssrf.ts
const DISPATCHER_CLOSE_TIMEOUT_MS=100;var SsrFBlockedError=class extends Error{constructor(e){super(e);this.name=`SsrFBlockedError`}};function normalizePolicyHostnames(e){return normalizeUniqueStringEntries(e?.map(e=>normalizeHostname(e)))}function parseHttpBaseUrl(e){const t=e.trim();if(!t)return;try{const e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)return;return e}catch{return}}function normalizeSsrFPolicyOrigin(e){const t=parseHttpBaseUrl(e);if(!t)return;t.hostname=t.hostname.replace(/\.+$/,``);return t.origin.toLowerCase()}function normalizeSsrFPolicyOrigins(e){if(!e||e.length===0)return[];return Array.from(new Set(e.map(e=>normalizeSsrFPolicyOrigin(e)).filter(e=>Boolean(e)))).toSorted()}const BLOCKED_HOSTNAMES=/* @__PURE__ */ new Set([`localhost`,`localhost.localdomain`,`metadata.google.internal`]);function normalizeHostnameAllowlist(e){return normalizePolicyHostnames(e).filter(e=>e!==`*`&&e!==`*.`)}function isPrivateNetworkAllowedByPolicy(e){return e?.dangerouslyAllowPrivateNetwork===true||e?.allowPrivateNetwork===true}function shouldSkipPrivateNetworkChecks(e,t){return isPrivateNetworkAllowedByPolicy(t)||normalizePolicyHostnames(t?.allowedHostnames).includes(e)}function resolveSsrFPolicyForUrl(e,t){if(!t?.allowedOrigins?.length)return t;const n=normalizeSsrFPolicyOrigin(e.toString());if(!n||!normalizeSsrFPolicyOrigins(t.allowedOrigins).includes(n))return t;return{...t,allowedHostnames:Array.from(/* @__PURE__ */ new Set([...t.allowedHostnames??[],normalizeHostname(e.hostname)]))}}function isHostnameAllowedByPattern(e,t){if(t.startsWith(`*.`)){const n=t.slice(2);if(!n||e===n)return false;return e.endsWith(`.${n}`)}return e===t}function matchesHostnameAllowlist(e,t){if(t.length===0)return true;return t.some(t=>isHostnameAllowedByPattern(e,t))}function looksLikeUnsupportedIpv4Literal(e){const t=e.split(`.`);if(t.length>4)return false;if(t.some(e=>e.length===0))return true;return t.every(e=>/^[0-9]+$/.test(e)||/^0x/i.test(e))}function isPrivateIpAddress(e,t){const n=normalizeHostname(e);if(!n)return false;const r={allowRfc2544BenchmarkRange:t?.allowRfc2544BenchmarkRange===true};const i={allowUniqueLocalRange:t?.allowIpv6UniqueLocalRange===true};const a=parseCanonicalIpAddress(n);if(a){if(isIpv4Address(a))return isBlockedSpecialUseIpv4Address(a,r);if(isBlockedSpecialUseIpv6Address(a,i))return true;const e=extractEmbeddedIpv4FromIpv6(a);return e?isBlockedSpecialUseIpv4Address(e,r):false}if(n.includes(`:`)&&!parseLooseIpAddress(n))return true;if(!isCanonicalDottedDecimalIPv4(n)&&isLegacyIpv4Literal(n))return true;return looksLikeUnsupportedIpv4Literal(n)}function isBlockedHostnameNormalized(e){return BLOCKED_HOSTNAMES.has(e)||e.endsWith(`.localhost`)||e.endsWith(`.local`)||e.endsWith(`.internal`)}function isBlockedHostnameOrIp(e,t){const n=normalizeHostname(e);if(!n)return false;return isBlockedHostnameNormalized(n)||isPrivateIpAddress(n,t)}const BLOCKED_HOST_OR_IP_MESSAGE=`Blocked hostname or private/internal/special-use IP address`;const BLOCKED_RESOLVED_IP_MESSAGE=`Blocked: resolves to private/internal/special-use IP address`;function resolveHostnamePolicyChecks(e,t){const n=normalizeHostname(e);if(!n)throw new Error(`Invalid hostname`);if(normalizeHostnameAllowlist(t?.blockedHostnames).some(e=>isHostnameAllowedByPattern(n,e)))throw new SsrFBlockedError(`Domain policy: Blocked hostname (configured blocklist): ${e}. Try a URL on a different domain or ask the operator to review blockedHostnames.`);const r=normalizeHostnameAllowlist(t?.hostnameAllowlist);if(!matchesHostnameAllowlist(n,r))throw new SsrFBlockedError(`Domain policy: Blocked hostname (not in allowlist): ${e}. Permitted hostname patterns: ${r.join(`, `)}. Try a URL on a permitted domain.`);const i=shouldSkipPrivateNetworkChecks(n,t);if(!i&&isBlockedHostnameOrIp(n,t))throw new SsrFBlockedError(BLOCKED_HOST_OR_IP_MESSAGE);return{normalized:n,skipPrivateNetworkChecks:i}}function assertAllowedResolvedAddressesOrThrow(e,t){for(const n of e)if(isBlockedHostnameOrIp(n.address,t))throw new SsrFBlockedError(BLOCKED_RESOLVED_IP_MESSAGE)}function isLoopbackIpAddressIncludingEmbeddedIpv4(e){if(isLoopbackIpAddress(e))return true;const t=parseCanonicalIpAddress(e);if(!t||isIpv4Address(t))return false;return extractEmbeddedIpv4FromIpv6(t)?.range()===`loopback`}function isBlockedTrustedResolvedIpv6Address(e){const t=parseCanonicalIpAddress(e);if(!t||isIpv4Address(t))return false;const n=t.range();if(n!==`unicast`&&n!==`rfc6052`)return false;return isBlockedSpecialUseIpv6Address(t)}function isExplicitLoopbackHostname(e){return e===`localhost`||e===`localhost.localdomain`||e.endsWith(`.localhost`)||isLoopbackIpAddressIncludingEmbeddedIpv4(e)}const PODMAN_GATEWAY_BLOCKED_LINK_LOCAL_ADDRESSES=/* @__PURE__ */ new Set([`169.254.0.23`,`169.254.42.42`,`169.254.169.254`,`169.254.170.2`,`169.254.170.23`]);function assertAllowedTrustedHostnameResolvedAddressesOrThrow(e,t,n){const r=isExplicitLoopbackHostname(t);const i=hasTrustedHostPodmanGatewayLinkLocalExemption(n);for(const t of e)if(isUnspecifiedIpAddress(t.address)||!r&&isLoopbackIpAddressIncludingEmbeddedIpv4(t.address)||isBlockedTrustedResolvedIpv6Address(t.address)||isLinkLocalIpAddress(t.address)&&(!i||!isCanonicalDottedDecimalIPv4(t.address)||PODMAN_GATEWAY_BLOCKED_LINK_LOCAL_ADDRESSES.has(t.address))||isCloudMetadataIpAddress(t.address))throw new SsrFBlockedError(BLOCKED_RESOLVED_IP_MESSAGE)}function normalizeLookupResults(e){if(Array.isArray(e))return e;return[e]}function createPinnedLookup(e){const t=normalizeHostname(e.hostname);if(e.addresses.length===0)throw new Error(`Pinned lookup requires at least one address for ${e.hostname}`);const n=e.fallback??lookup;const r=e.addresses.map(e=>({address:e,family:e.includes(`:`)?6:4}));const i=r.filter(e=>e.family===4);const a=i.length>0?i:r;let o=0;return((e,i,s)=>{const c=typeof i===`function`?i:s;if(!c)return;const l=normalizeHostname(e);if(!l||l!==t){if(typeof i===`function`||i===void 0)return n(e,c);if(typeof i===`number`)return n(e,i,c);return n(e,i,c)}const u=typeof i===`object`&&i!==null?i:{};const d=typeof i===`number`?i:typeof u.family===`number`?u.family:0;const f=d===4||d===6?r.filter(e=>e.family===d):u.all?r:a;const p=f.length>0?f:a;if(u.all){process.nextTick(()=>{c(null,p)});return}const m=expectDefined(p[o%p.length],`usable entry at index % usable.length`);o+=1;process.nextTick(()=>{c(null,m.address,m.family)})})}function dedupeAndPreferIpv4(e){const t=/* @__PURE__ */ new Set;const n=[];const r=[];for(const i of e){if(t.has(i.address))continue;t.add(i.address);if(i.family===4){n.push(i.address);continue}r.push(i.address)}return[...n,...r]}async function resolvePinnedHostnameWithPolicy(e,t={}){t.signal?.throwIfAborted();const{normalized:n,skipPrivateNetworkChecks:r}=resolveHostnamePolicyChecks(e,t.policy);const i=t.lookupFn??dns.lookup;const a=normalizeLookupResults(await racePromiseWithAbortSignal(()=>i(n,{all:true}),t.signal,e=>e.reason));t.signal?.throwIfAborted();if(a.length===0)throw new Error(`Unable to resolve hostname: ${e}`);if(!r)assertAllowedResolvedAddressesOrThrow(a,t.policy);else if(!isPrivateNetworkAllowedByPolicy(t.policy))assertAllowedTrustedHostnameResolvedAddressesOrThrow(a,n,t.policy);const o=dedupeAndPreferIpv4(a);return{hostname:n,addresses:o,lookup:createPinnedLookup({hostname:n,addresses:o})}}function assertHostnameAllowedWithPolicy(e,t){return resolveHostnamePolicyChecks(e,t).normalized}function withPinnedLookup(e,t){return{...t,lookup:e}}function resolvePinnedDispatcherLookup(e,t,n){if(!t)return e.lookup;const r=normalizeHostname(t.hostname);if(!r||r!==e.hostname)throw new Error(`Pinned dispatcher override hostname mismatch: expected ${e.hostname}, got ${t.hostname}`);const i=t.addresses.map(e=>({address:e,family:e.includes(`:`)?6:4}));if(!shouldSkipPrivateNetworkChecks(e.hostname,n))assertAllowedResolvedAddressesOrThrow(i,n);else if(!isPrivateNetworkAllowedByPolicy(n))assertAllowedTrustedHostnameResolvedAddressesOrThrow(i,e.hostname,n);return createPinnedLookup({hostname:e.hostname,addresses:[...t.addresses],fallback:e.lookup})}function createPinnedDispatcher(e,t,n,r,i){const a=resolvePinnedDispatcherLookup(e,t?.pinnedHostname,n);const o={bodyTimeout:i,headersTimeout:i};if(!t||t.mode===`direct`)return createHttp1Agent({...o,connect:withPinnedLookup(a,t?.connect)},r);if(t.mode===`env-proxy`)return createHttp1EnvHttpProxyAgent({...o,connect:withPinnedLookup(a,t.connect),...t.proxyTls?{proxyTls:{...t.proxyTls}}:{}},r);const s=t.proxyUrl.trim();const c=withPinnedLookup(a,t.proxyTls);return createHttp1ProxyAgent({...o,uri:s,requestTls:c},r)}function destroyDispatcher(e){try{e.destroy?.()}catch{}}async function waitForDispatcherClose(e){const t=e.close;if(typeof t!==`function`){destroyDispatcher(e);return}try{await raceWithTimeout(Promise.resolve(t.call(e)),DISPATCHER_CLOSE_TIMEOUT_MS,()=>destroyDispatcher(e),{ref:false})}catch(t){destroyDispatcher(e);throw t}}async function closeDispatcher(e){if(!e)return;const t=e;try{await waitForDispatcherClose(t)}catch{}}
//!src/infra/net/configured-local-origin-bypass.ts
function parseHttpUrl(e){const t=URL.parse(e.trim());if(!t||t.protocol!==`http:`&&t.protocol!==`https:`)return;t.hostname=t.hostname.replace(/\.+$/,``);return t}function isLoopbackManagedProxyBypassHost(e){const t=normalizeHostname(e);return t===`localhost`||isLoopbackIpAddress(t)}function shouldResolveConfiguredLocalOriginManagedProxyBypass(e){if(e.managedProxyBypass?.kind!==`configured-local-origin`)return false;const t=parseHttpUrl(e.managedProxyBypass.baseUrl);if(!t||!isLoopbackManagedProxyBypassHost(t.hostname))return false;return parseHttpUrl(e.url.toString())?.origin.toLowerCase()===t.origin.toLowerCase()}function shouldUseConfiguredLocalOriginManagedProxyBypass(e){if(!shouldResolveConfiguredLocalOriginManagedProxyBypass(e))return false;const t=getActiveManagedProxyLoopbackMode();if(t===`proxy`)return false;if(t===`block`&&isLoopbackManagedProxyBypassHost(e.url.hostname))throw new SsrFBlockedError(`proxy: configured local provider loopback connections are blocked by proxy.loopbackMode`);return e.resolvedAddresses.length>0&&e.resolvedAddresses.every(e=>isLoopbackIpAddress(e))}function resolveConfiguredLocalOriginLinkLocalHopPolicy(e){const{policy:t,managedProxyBypass:n}=e;if(!t||n?.allowPodmanHostGatewayLinkLocal!==true)return t;const r=parseHttpUrl(n.baseUrl);if(r?.hostname!==`host.containers.internal`||parseHttpUrl(e.url.href)?.origin!==r.origin)return t;return withTrustedHostPodmanGatewayLinkLocalExemption(t)}
//!src/infra/net/fetch-request-authority.ts
const requestAuthority=new AsyncContext(Symbol.for(`openclaw.guardedFetchRequestAuthority`));function captureGuardedFetchRequestAuthority(){const e=requestAuthority.getStore();return e?()=>{e.assertCurrent();e.beforeRequest?.()}:void 0}
//!src/infra/net/guarded-body-stream.ts
const guardedBodyCleanupRegistry=new FinalizationRegistry(e=>{e.finalize().catch(()=>void 0)});function attachBodyAbort(e,t,n){const abort=()=>{const r=t.deref();if(!r)return;const i=e.reason??new DOMException(`This operation was aborted`,`AbortError`);const a=n(i);r.error(i);a.catch(()=>void 0)};if(e.aborted)abort();else e.addEventListener(`abort`,abort,{once:true});return()=>e.removeEventListener(`abort`,abort)}function wrapBodyStream(e,t){const n=e.body.getReader();let r=false;let i=false;let detachAbort=()=>{};const a={};const finalize=async(i=async()=>{await n.cancel().catch(()=>void 0)})=>{if(r)return;r=true;detachAbort();guardedBodyCleanupRegistry.unregister(a);const[o,s,c]=await Promise.allSettled([i(),(async()=>n.releaseLock())(),(async()=>await e.cleanup())()]);if(c.status===`rejected`&&t===`release`)throw c.reason;if(s.status===`rejected`)throw s.reason;if(o.status===`rejected`&&t===`cancellation`)throw o.reason};const cancel=async e=>await finalize(async()=>await n.cancel(e));const o=new ReadableStream((()=>{let onError;let onChunk;return{start(n){onError=async e=>{if(r)return;if(t===`release`)await finalize();n.error(e);await finalize()};onChunk=t=>{try{if(t.done){n.close();return finalize().catch(onError)}e.refreshTimeout?.();n.enqueue(t.value);return}catch(e){return onError(e)}}},pull(t){const a=e.signal;if(a&&!i){i=true;detachAbort=attachBodyAbort(a,new WeakRef(t),cancel)}if(r)return;return n.read().then(onChunk,onError)},cancel}})(),e.signal?{highWaterMark:0}:void 0);guardedBodyCleanupRegistry.register(o,{finalize},a);return o}function responseWithAbortSignal(e,t,n=()=>{}){if(!e.body||!t){n();return e}return preserveResponseMetadata(e,new Response(wrapBodyStream({body:e.body,cleanup:n,signal:t},`cancellation`),{status:e.status,statusText:e.statusText,headers:e.headers}),e.headers)}function preserveResponseMetadata(e,t,n){if(n)Object.defineProperty(t,"headers",{value:n});Object.defineProperties(t,{url:{value:e.url},redirected:{value:e.redirected},type:{value:e.type},clone:{configurable:true,value:()=>preserveResponseMetadata(e,Response.prototype.clone.call(t),n),writable:true}});return t}
//!src/infra/net/pinned-dispatcher-pool.ts
const runInDispatcherPoolContext=AsyncLocalStorage.snapshot();
//!src/infra/net/redirect-headers.ts
const CROSS_ORIGIN_REDIRECT_SAFE_HEADERS=/* @__PURE__ */ new Set([`accept`,`accept-encoding`,`accept-language`,`cache-control`,`content-language`,`content-type`,`if-match`,`if-modified-since`,`if-none-match`,`if-unmodified-since`,`pragma`,`range`,`user-agent`]);function retainSafeHeadersForCrossOriginRedirect$1(e){if(!e)return e;const t=new Headers(normalizeHeadersInitForFetch(e));const n={};for(const[e,r]of t.entries())if(CROSS_ORIGIN_REDIRECT_SAFE_HEADERS.has(e))n[e]=r;return n}function restoreRedirectAuthorization(e){if(!e.authorization)return e.init;const t=new Headers(e.init?.headers);t.set(`Authorization`,e.authorization);return{...e.init,headers:t}}function dropBodyHeaders(e){if(!e)return e;const t=new Headers(normalizeHeadersInitForFetch(e));t.delete(`content-encoding`);t.delete(`content-language`);t.delete(`content-length`);t.delete(`content-location`);t.delete(`content-type`);t.delete(`transfer-encoding`);return t}
//!src/infra/net/form-data.ts
function isFormDataLike(e){return typeof e===`object`&&e!==null&&typeof e.entries===`function`&&e[Symbol.toStringTag]===`FormData`}
//!src/infra/net/runtime-fetch.ts
function isMockedFetch(e){if(typeof e!==`function`)return false;return typeof e.mock===`object`}async function fetchWithRuntimeDispatcher(e,t){return await fetchWithPreparedRuntimeDispatcher(loadUndiciRuntimeDeps(),e,t)}function fetchWithPreparedRuntimeDispatcher(e,t,n){const r=e.fetch;const i=normalizeRequestInitHeadersForFetch(n);const a=e.FormData;if(!n||!isFormDataLike(n.body)||typeof a!==`function`||n.body instanceof a)return r(t,i);const o=new a;for(const[e,t]of n.body.entries()){const n=t;const r=typeof n.name===`string`&&n.name.trim()?n.name:void 0;if(r)o.append(e,t,r);else o.append(e,t)}const s=new Headers(i?.headers);s.delete(`content-length`);s.delete(`content-type`);return r(t,{...i,headers:s,body:o})}
//!src/infra/net/fetch-guard.ts
const GUARDED_FETCH_MODE={STRICT:`strict`,TRUSTED_ENV_PROXY:`trusted_env_proxy`,TRUSTED_EXPLICIT_PROXY:`trusted_explicit_proxy`};var GuardedFetchRedirectError=class extends Error{constructor(e){super(`Too many redirects (limit: ${e.maxRedirects})`);this.name=`GuardedFetchRedirectError`;this.status=e.status;this.maxRedirects=e.maxRedirects}};const DEFAULT_MAX_REDIRECTS=3;const OPENCLAW_DEBUG_PROXY_ENABLED=`OPENCLAW_DEBUG_PROXY_ENABLED`;function getRedirectVisitKey(e,t){return`${t?.method?.toUpperCase()??`GET`} ${e}`}function isTruthyEnvValue(e){return e===`1`||e===`true`||e===`yes`||e===`on`}function resolveGuardedFetchMode(e){if(e.mode)return e.mode;if(e.proxy===`env`&&e.dangerouslyAllowEnvProxyWithoutPinnedDns===true)return GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY;return GUARDED_FETCH_MODE.STRICT}function isManagedProxyActive(){return process.env[`OPENCLAW_PROXY_ACTIVE`]===`1`}function assertExplicitProxySupportsPinnedDns(e,t,n){if(n!==false&&t?.mode===`explicit-proxy`&&e.protocol!==`https:`)throw new Error(`Explicit proxy SSRF pinning requires HTTPS targets; plain HTTP targets are not supported`)}function createPolicyDispatcherWithoutPinnedDns(e,t,n){if(!e&&n===void 0)return null;const r={bodyTimeout:n,headersTimeout:n};if(!e||e.mode===`direct`)return createHttp1Agent({...r,connect:e?.connect},t);if(e.mode===`env-proxy`)return createHttp1EnvHttpProxyAgent({...r,...e.connect?{connect:{...e.connect}}:{},...e.proxyTls?{proxyTls:{...e.proxyTls}}:{}},t);const i=e.proxyUrl.trim();const a=e.proxyTls;return createHttp1ProxyAgent({...r,uri:i,...a?{requestTls:{...a}}:{}},t)}async function assertExplicitProxyAllowed(e,t,n,r,i){if(!e||e.mode!==`explicit-proxy`)return;let a;try{a=new URL(e.proxyUrl)}catch{throw new Error(`Invalid explicit proxy URL`)}const o=i&&[`socks:`,`socks5:`].includes(a.protocol);if(![`http:`,`https:`].includes(a.protocol)&&!o)throw new Error(`Explicit proxy URL must use http or https`);const s=n||e.allowPrivateProxy===true?{...n,hostnameAllowlist:void 0,...e.allowPrivateProxy===true?{allowPrivateNetwork:true}:{}}:void 0;await resolvePinnedHostnameWithPolicy(a.hostname,{lookupFn:t,policy:s,signal:r})}function isRedirectStatus(e){return e===301||e===302||e===303||e===307||e===308}function isAmbientGlobalFetch(e){return typeof e.fetchImpl===`function`&&typeof e.globalFetch===`function`&&e.fetchImpl===e.globalFetch}async function prepareGuardedFetchCapture(e,t){if(e.capture===false||!isTruthyEnvValue(process.env[OPENCLAW_DEBUG_PROXY_ENABLED]))return{fetchImpl:t};const{prepareHttpCaptureForTransport:n,resolveDebugProxyFetchTransport:r}=await import(`./runtime-Cek02me7.mjs`);return{fetchImpl:r(t),capture:n()}}function retainSafeHeadersForCrossOriginRedirect(e){if(!e?.headers)return e;return{...e,headers:retainSafeHeadersForCrossOriginRedirect$1(e.headers)}}function resolveRetainedAuthorizationForRedirect(e){const t=e.init;if(!t?.headers||!e.hostnameAllowlist?.length)return;if(e.nextUrl.protocol!==`https:`)return;if(!e.hostnameAllowlist.includes(`*`)&&!matchesHostnameAllowlist(e.nextUrl.hostname,e.hostnameAllowlist))return;const n=normalizeRequestInitHeadersForFetch(t);if(!n?.headers)return;return new Headers(n.headers).get(`authorization`)??void 0}function rewriteRedirectInit(e){const{init:t,status:n}=e;if(!t)return t;const r=t.method?.toUpperCase()??`GET`;const i=n===303?r!==`GET`&&r!==`HEAD`:(n===301||n===302)&&r===`POST`;const a=e.crossOrigin&&!e.allowUnsafeReplay&&r!==`GET`&&r!==`HEAD`;if(!i&&!a)return t;return{...t,...i?{method:`GET`}:{},body:void 0,headers:dropBodyHeaders(t.headers)}}async function fetchWithSsrFGuard(e){const{managedProxyBypass:t,...n}=e;return await fetchWithSsrFGuardInternal(n)}async function fetchWithSsrFGuardInternal(e){const t=captureGuardedFetchRequestAuthority();const n=captureEffectAuthority();if(e.allowCrossOriginUnsafeRedirectReplay===true&&e.rejectCrossOriginUnsafeRedirectReplay===true)throw new TypeError(`Cross-origin unsafe redirect replay cannot be both allowed and rejected`);const r=globalThis.fetch;const i=e.fetchImpl??r;if(!i)throw new Error(`fetch is not available`);const a=isMockedFetch(i);const o=e.fetchImpl!==void 0&&!isAmbientGlobalFetch({fetchImpl:e.fetchImpl,globalFetch:r})||a;const s=await prepareGuardedFetchCapture(e,i);const c=typeof e.maxRedirects===`number`&&Number.isFinite(e.maxRedirects)?Math.max(0,Math.floor(e.maxRedirects)):DEFAULT_MAX_REDIRECTS;const l=resolveGuardedFetchMode(e);const{signal:u,cleanup:d,refresh:f}=buildTimeoutAbortSignal({timeoutMs:e.timeoutMs,signal:e.signal??e.init?.signal??void 0,operation:`fetchWithSsrFGuard`,url:e.url});let p=false;const finishRequest=async e=>{if(p)return;p=true;d();await e?.()};let m=e.url;let h=normalizeRequestInitHeadersForFetch(e.init?{...e.init}:void 0);const g=/* @__PURE__ */ new Set([getRedirectVisitKey(m,h)]);let _=0;while(true){let r;try{r=new URL(m)}catch{await finishRequest();throw new Error(`Invalid URL: must be http or https`)}if(![`http:`,`https:`].includes(r.protocol)){await finishRequest();throw new Error(`Invalid URL: must be http or https`)}if(e.requireHttps===true&&r.protocol!==`https:`){await finishRequest();throw new Error(`URL must use https`)}let i=null;let d;let p;const v=new AbortController;const releaseDispatcher=async()=>{v.abort();await cancelUnreadResponseBody(p);await(d?d.release():closeDispatcher(i))};const y=resolveConfiguredLocalOriginLinkLocalHopPolicy({url:r,policy:resolveSsrFPolicyForUrl(r,e.policy),managedProxyBypass:e.managedProxyBypass});const b=e.resolveDispatcherPolicy?.(r)??e.dispatcherPolicy;const resolvePinnedHostname=async()=>await resolvePinnedHostnameWithPolicy(r.hostname,{lookupFn:e.lookupFn,policy:y,signal:u});try{const x=l===GUARDED_FETCH_MODE.TRUSTED_EXPLICIT_PROXY&&b?.mode===`explicit-proxy`;assertExplicitProxySupportsPinnedDns(r,b,x?false:e.pinDns);await assertExplicitProxyAllowed(b,e.lookupFn,e.policy,u,x);const S=l===GUARDED_FETCH_MODE.STRICT&&isManagedProxyActive();const C=S&&shouldResolveConfiguredLocalOriginManagedProxyBypass({url:r,managedProxyBypass:e.managedProxyBypass});const w=S&&(shouldUseEnvHttpProxyForUrl(r.toString())||C);const T=(l===GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY||e.useEnvProxyForEligibleUrls===true&&!w)&&!b&&shouldUseEnvHttpProxyForUrl(r.toString());const E=a&&e.lookupFn===void 0&&!T&&!w&&!x&&e.pinDns!==false;const D=e.timeoutMs;const O=e.streamTimeoutMs;const k={bodyTimeout:O,headersTimeout:O};if(T||w||e.pinDns===false)assertHostnameAllowedWithPolicy(r.hostname,y);if(T)i=createHttp1EnvHttpProxyAgent(k,D);else if(w){if(C){const t=await resolvePinnedHostname();i=shouldUseConfiguredLocalOriginManagedProxyBypass({url:r,managedProxyBypass:e.managedProxyBypass,resolvedAddresses:t.addresses})?createPinnedDispatcher(t,b,y,D,O):createHttp1EnvHttpProxyAgent({...k,noProxy:``,...b?.mode===`direct`&&b.connect?{requestTls:{...b.connect}}:{}},D)}else i=createHttp1EnvHttpProxyAgent(k,D)}else if(x){assertHostnameAllowedWithPolicy(r.hostname,y);i=createPolicyDispatcherWithoutPinnedDns(b,D,O)}else if(E)assertHostnameAllowedWithPolicy(r.hostname,y);else if(e.pinDns===false){await resolvePinnedHostname();i=createPolicyDispatcherWithoutPinnedDns(b,D,O)}else{const t=await resolvePinnedHostname();if(e.dispatcherPool&&l===GUARDED_FETCH_MODE.STRICT&&b===void 0){const n=resolveUndiciAutoSelectFamilyConnectOptions();const a=JSON.stringify({origin:r.origin,addresses:[...t.addresses].toSorted(),timeoutMs:D??null,streamTimeoutMs:D??O??globalUndiciStreamTimeoutMs??null,familyConnect:n??null,policy:y??null,podmanGatewayLinkLocalExempt:hasTrustedHostPodmanGatewayLinkLocalExemption(y)});d=e.dispatcherPool.acquire({key:a,createDispatcher:()=>createPinnedDispatcher(t,n?{mode:`direct`,connect:n}:void 0,y,D,O)});i=d?d.dispatcher:createPinnedDispatcher(t,void 0,y,D,O)}else i=createPinnedDispatcher(t,b,y,D,O)}const A={...h?{...h}:{},redirect:`manual`,...i?{dispatcher:i}:{},signal:u?AbortSignal.any([u,v.signal]):v.signal};let j=h?.body??null;if(A.body instanceof Blob){const e=A.body;const t=new Headers(A.headers);if(!t.has(`content-length`))t.set(`content-length`,String(e.size));if(!t.has(`content-type`)&&e.type)t.set(`content-type`,e.type);A.headers=t;const n=new Uint8Array(await e.arrayBuffer());A.body=n;j=s.capture?Buffer.from(n):j}const M=Boolean(i)&&!o;const N={url:r.toString(),method:h?.method??`GET`,signal:process.versions.bun?A.signal??void 0:void 0,requestHeaders:h?.headers,requestBody:j,transport:`http`,flowId:e.capture===false?void 0:e.capture?.flowId,meta:{captureOrigin:`guarded-fetch`,...e.auditContext?{auditContext:e.auditContext}:{},...e.capture===false?{}:e.capture?.meta,...e.capture&&e.capture.sensitiveRequestHeaderNames?{sensitiveRequestHeaderNames:e.capture.sensitiveRequestHeaderNames}:{}}};let P=false;try{p=await n.initiate(()=>{const n=e.beforeRequest?.();if(isPromiseLike(n)){Promise.resolve(n).catch(()=>void 0);throw new TypeError(`beforeRequest must be synchronous.`)}t?.();P=true;return M?fetchWithRuntimeDispatcher(r.toString(),A):s.fetchImpl(r.toString(),A)})}catch(e){if(P)s.capture?.({...N,error:e});throw e}e.onResponse?.(p.status);s.capture?.({...N,response:p});if(isRedirectStatus(p.status)){_+=1;if(_>c)throw new GuardedFetchRedirectError({status:p.status,maxRedirects:c});const t=p.headers.get(`location`);if(!t)throw new Error(`Redirect missing location header (${p.status})`);const n=new URL(t,r);const i=n.toString();const a=resolveRetainedAuthorizationForRedirect({init:h,nextUrl:n,hostnameAllowlist:e.retainAuthorizationRedirectHostnameAllowlist});const o=n.origin!==r.origin;if(o&&hasTrustedHostPodmanGatewayLinkLocalExemption(y))throw new SsrFBlockedError(`Blocked cross-origin redirect from configured Podman host gateway`);const s=rewriteRedirectInit({init:h,status:p.status,crossOrigin:false,allowUnsafeReplay:true});if(o){const t=s?.method?.toUpperCase()??`GET`;const i=s?.body;if(e.rejectCrossOriginUnsafeRedirectReplay===true&&t!==`GET`&&t!==`HEAD`&&i!=null)throw new Error(`Refusing to follow cross-origin redirect for ${t} request body (${r.origin} -> ${n.origin})`)}h=rewriteRedirectInit({init:s,status:p.status,crossOrigin:o,allowUnsafeReplay:e.allowCrossOriginUnsafeRedirectReplay===true});if(o){h=retainSafeHeadersForCrossOriginRedirect(h);h=restoreRedirectAuthorization({init:h,authorization:a})}const l=getRedirectVisitKey(i,h);if(g.has(l))throw new Error(`Redirect loop detected`);g.add(l);await releaseDispatcher();m=i;continue}return{response:process.versions.bun&&!(p instanceof Response)?responseWithAbortSignal(p,A.signal??void 0):p,signal:u,finalUrl:m,release:async()=>finishRequest(releaseDispatcher),refreshTimeout:f,dispatcherReused:d?.reused}}catch(t){if(t instanceof SsrFBlockedError){const n=e.auditContext??`url-fetch`;logWarn(`security: blocked URL fetch (${n}) targetOrigin=${r.origin} reason=${t.message}`)}await finishRequest(releaseDispatcher);throw t}}}export{fetchWithSsrFGuard};