UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

735 lines (734 loc) • 25.3 kB
import { t as isPromiseLike } from "./promise-like-aMoWEh5w.mjs"; import { t as runBestEffortCleanup } from "./non-fatal-cleanup-CRJjL6BT.mjs"; import { f as isLoopbackIpAddress } from "./ip-BUyyYvdK.mjs"; import { i as logWarn } from "./logger-CIwfuhOU.mjs"; import "./http-body-B9w7rzPz.mjs"; import { t as cancelUnreadResponseBody } from "./http-response-body-B-i_0116.mjs"; import { t as captureEffectAuthority } from "./effect-authority-nglmRKHz.mjs"; import { n as buildTimeoutAbortSignal } from "./fetch-timeout-D62KciOm.mjs"; import { n as normalizeHeadersInitForFetch, r as normalizeRequestInitHeadersForFetch } from "./fetch-headers-r34WWC5V.mjs"; import { n as normalizeHostname } from "./hostname-DQVb2xzD.mjs"; import { t as getActiveManagedProxyLoopbackMode } from "./active-proxy-state-LRlZWsqe.mjs"; import { i as createPinnedDispatcher, m as resolveSsrFPolicyForUrl, n as assertHostnameAllowedWithPolicy, p as resolvePinnedHostnameWithPolicy, r as closeDispatcher, t as SsrFBlockedError, u as matchesHostnameAllowlist, v as hasTrustedHostPodmanGatewayLinkLocalExemption, y as withTrustedHostPodmanGatewayLinkLocalExemption } from "./ssrf-DHBNJw0c.mjs"; import { c as shouldUseEnvHttpProxyForUrl } from "./proxy-env-CZP0dXDG.mjs"; import { n as createHttp1EnvHttpProxyAgent, o as globalUndiciStreamTimeoutMs, r as createHttp1ProxyAgent, t as createHttp1Agent, u as resolveUndiciAutoSelectFamilyConnectOptions } from "./undici-runtime-ByR6iuTV.mjs"; import { t as captureGuardedFetchRequestAuthority } from "./fetch-request-authority-nK0cxa_-.mjs"; import { i as isMockedFetch, n as fetchWithRuntimeDispatcher } from "./runtime-fetch-CQQovyS7.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; //#region 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); } /** Return whether proving a configured local-origin bypass requires target DNS. */ 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(); } /** Return whether a configured local provider origin may bypass the managed proxy. */ 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)); } /** Derive the host-only grant independently for each exact-origin hop. */ 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); } //#endregion //#region src/infra/net/fetch-redirect.ts 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; } }; function getRedirectVisitKey(e, t) { return `${t?.method?.toUpperCase() ?? "GET"} ${e}`; } function isRedirectStatus(e) { return e === 301 || e === 302 || e === 303 || e === 307 || e === 308; } //#endregion //#region src/infra/net/guarded-body-stream.ts /** * Shared body-stream cleanup for guarded fetch consumers (`fetchWithSsrFGuard` * callers that re-wrap streaming responses). */ 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; } /** Wraps a guarded body with best-effort cleanup and explicit cancellation errors. */ function wrapGuardedBodyStream(e) { return wrapBodyStream(e, "cancellation"); } /** Preserves post-header request cancellation around runtime fetch body streams. */ function responseWithAbortSignal(e, t) { if (!e.body || !t) return e; const n = new Response(wrapBodyStream({ body: e.body, cleanup: () => {}, signal: t }, "cancellation"), { status: e.status, statusText: e.statusText, headers: e.headers }); const applyMetadata = (t) => { Object.defineProperties(t, { headers: { value: e.headers }, url: { value: e.url }, redirected: { value: e.redirected }, type: { value: e.type }, clone: { configurable: true, value: () => applyMetadata(Response.prototype.clone.call(t)), writable: true } }); return t; }; return applyMetadata(n); } const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([ 101, 103, 204, 205, 304 ]); /** Keeps request ownership through body completion, failure, or cancellation. */ function responseWithRelease(e, t) { if (!e.body || NULL_BODY_STATUSES.has(e.status)) { runBestEffortCleanup({ cleanup: t, onError(e) { process.emitWarning(e instanceof Error ? e : String(e)); } }); return e; } return new Response(wrapBodyStream({ body: e.body, cleanup: t }, "release"), { status: e.status, statusText: e.statusText, headers: e.headers }); } //#endregion //#region src/infra/net/pinned-dispatcher-pool.ts const PROVIDER_DISPATCHER_POOL_MAX_ENTRIES = 16; const PROVIDER_DISPATCHER_POOL_IDLE_TTL_MS = 6e4; const runInDispatcherPoolContext = AsyncLocalStorage.snapshot(); /** * Bounded cache of reusable DNS-pinned dispatchers. * * Callers must perform fresh DNS and SSRF validation before every acquisition * and include the resulting origin, address set, and connection policy in the key. */ var PinnedDispatcherPool = class { constructor() { this.entries = /* @__PURE__ */ new Map(); this.closed = false; } acquire(e) { if (this.closed) return; const t = this.entries.get(e.key); if (t) { clearTimeout(t.idleTimer); t.idleTimer = void 0; t.activeLeases += 1; this.entries.delete(t.key); this.entries.set(t.key, t); return this.createLease(t, true); } if (this.entries.size >= PROVIDER_DISPATCHER_POOL_MAX_ENTRIES) { const e = [...this.entries.values()].find((e) => e.activeLeases === 0); if (e) this.retireEntry(e); } if (this.entries.size >= PROVIDER_DISPATCHER_POOL_MAX_ENTRIES) return; const n = { key: e.key, dispatcher: e.createDispatcher(), activeLeases: 1 }; this.entries.set(n.key, n); return this.createLease(n, false); } async closeAll() { this.closed = true; const e = [...this.entries.values()]; this.entries.clear(); await Promise.all(e.map((e) => { clearTimeout(e.idleTimer); e.idleTimer = void 0; return this.startClose(e); })); } createLease(e, t) { let n = false; return { dispatcher: e.dispatcher, reused: t, release: async () => { if (n) return; n = true; e.activeLeases -= 1; if (e.activeLeases > 0) return; if (this.closed || this.entries.get(e.key) !== e) { await this.startClose(e); return; } e.idleTimer = runInDispatcherPoolContext(() => setTimeout(() => this.retireEntry(e), PROVIDER_DISPATCHER_POOL_IDLE_TTL_MS)).unref(); } }; } retireEntry(e) { if (this.entries.get(e.key) === e) this.entries.delete(e.key); clearTimeout(e.idleTimer); e.idleTimer = void 0; if (e.activeLeases === 0) this.startClose(e); } startClose(e) { e.closePromise ??= runInDispatcherPoolContext(() => closeDispatcher(e.dispatcher)); return e.closePromise; } }; //#endregion //#region 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" ]); /** * Keeps only headers that are safe to replay after a redirect crosses origins. * Authorization/cookie-like metadata must be dropped before the follow-up fetch. */ 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; } //#endregion //#region src/infra/net/fetch-guard.ts const GUARDED_FETCH_MODE = { STRICT: "strict", TRUSTED_ENV_PROXY: "trusted_env_proxy", TRUSTED_EXPLICIT_PROXY: "trusted_explicit_proxy" }; const DEFAULT_MAX_REDIRECTS = 3; const OPENCLAW_DEBUG_PROXY_ENABLED = "OPENCLAW_DEBUG_PROXY_ENABLED"; function isTruthyEnvValue(e) { return e === "1" || e === "true" || e === "yes" || e === "on"; } function withStrictGuardedFetchMode(e) { return { ...e, mode: GUARDED_FETCH_MODE.STRICT }; } function withTrustedEnvProxyGuardedFetchMode(e) { return { ...e, mode: GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY }; } function withTrustedExplicitProxyGuardedFetchMode(e) { return { ...e, mode: GUARDED_FETCH_MODE.TRUSTED_EXPLICIT_PROXY }; } 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 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-B5ujXFJ2.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 fetchConfiguredLocalOriginWithSsrFGuard({ configuredLocalOriginBaseUrl: e, allowPodmanHostGatewayLinkLocal: t, ...n }) { return await fetchWithSsrFGuardInternal({ ...n, managedProxyBypass: { kind: "configured-local-origin", baseUrl: e, ...t === true ? { allowPodmanHostGatewayLinkLocal: t } : {} } }); } 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; } } } //#endregion export { withStrictGuardedFetchMode as a, retainSafeHeadersForCrossOriginRedirect$1 as c, wrapGuardedBodyStream as d, GuardedFetchRedirectError as f, isManagedProxyActive as i, PinnedDispatcherPool as l, fetchConfiguredLocalOriginWithSsrFGuard as n, withTrustedEnvProxyGuardedFetchMode as o, fetchWithSsrFGuard as r, withTrustedExplicitProxyGuardedFetchMode as s, GUARDED_FETCH_MODE as t, responseWithRelease as u };