openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
770 lines (769 loc) • 29.5 kB
JavaScript
import { R as resolveTimerTimeoutMs, a as addTimerTimeoutGraceMs, g as clampTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs";
import { m as toStringifiedError } from "./error-coercion-hDrHOSGy.mjs";
import { u as redactToolPayloadText } from "./redact-Mj7pppxC.mjs";
import { d as sleepWithAbort } from "./src-BPmQBLJp.mjs";
import { s as isLoopbackHost } from "./net-BgRayX-P.mjs";
import { h as readProviderJsonResponse } from "./provider-http-errors-Dtgw3x-5.mjs";
import { p as resolvePinnedHostnameWithPolicy, t as SsrFBlockedError } from "./ssrf-DHBNJw0c.mjs";
import { i as hasProxyEnvConfigured } from "./proxy-env-CZP0dXDG.mjs";
import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs";
import { n as registerManagedProxyBrowserCdpBypass } from "./proxy-lifecycle-78PDzQG7.mjs";
import "./logging-core-DxpUImpb.mjs";
import "./security-runtime-C-zE_Zy_.mjs";
import { n as redactCdpUrl } from "./browser-cdp-DYGt86Rj.mjs";
import "./ssrf-runtime-B6q6NM4E.mjs";
import { i as BrowserCdpEndpointBlockedError } from "./errors-C9QQGqVs.mjs";
import "./webhook-ingress-pvI5xLbj.mjs";
import { n as rawDataToString } from "./ws-DFZcrj1T.mjs";
import { t as WebSocket } from "./websocket-runtime-jKgLhX3s.mjs";
import "./number-runtime-W4chuk8B.mjs";
import { t as normalizeBrowserTimerDelayMs } from "./timer-delay-vTpJN_mI.mjs";
import "./error-runtime-BM740gJj.mjs";
import "./runtime-env-D-Pa5lD6.mjs";
import "./ssrf-runtime-internal-Cl4t2EgL.mjs";
import "./provider-http-LcawLneq.mjs";
import { i as withExactHostnamePolicy, r as isCdpHostnameTrustedByPolicy, t as allowsDiscoveredCdpAuthorityChange } from "./ssrf-policy-helpers-CgdC_wgF.mjs";
import { createRequire } from "node:module";
import { createHash } from "node:crypto";
import net from "node:net";
import http from "node:http";
import https from "node:https";
//#region extensions/browser/src/browser/cdp-timeouts.ts
/**
* Centralizes timing so local loopback probes stay fast while remote/browser
* node probes retain enough handshake slack for real networks.
*/
const CDP_HTTP_REQUEST_TIMEOUT_MS = 1500;
const CDP_WS_HANDSHAKE_TIMEOUT_MS = 5e3;
const CDP_JSON_NEW_TIMEOUT_MS = 1500;
const PLAYWRIGHT_TARGET_INFO_TIMEOUT_MS = 2e3;
const MANAGED_CDP_READY_HTTP_TIMEOUT_MS = 1500;
const CHROME_BOOTSTRAP_PREFS_TIMEOUT_MS = 1e4;
const CHROME_BOOTSTRAP_EXIT_TIMEOUT_MS = 5e3;
const CHROME_STOP_TIMEOUT_MS = 2500;
const CHROME_STDERR_HINT_MAX_CHARS = 2e3;
const PROFILE_HTTP_REACHABILITY_TIMEOUT_MS = 300;
const PROFILE_WS_REACHABILITY_MIN_TIMEOUT_MS = 200;
const PROFILE_WS_REACHABILITY_MAX_TIMEOUT_MS = 2e3;
const PROFILE_ATTACH_RETRY_TIMEOUT_MS = 1200;
const CHROME_MCP_ATTACH_READY_WINDOW_MS = 8e3;
function usesFastLoopbackCdpProbeClass(e) {
return e.profileIsLoopback && e.attachOnly !== true;
}
function resolveCdpReachabilityTimeouts(e) {
const t = clampTimerTimeoutMs(e.timeoutMs);
const n = resolveTimerTimeoutMs(e.remoteHttpTimeoutMs, CDP_HTTP_REQUEST_TIMEOUT_MS);
const r = resolveTimerTimeoutMs(e.remoteHandshakeTimeoutMs, CDP_WS_HANDSHAKE_TIMEOUT_MS);
if (usesFastLoopbackCdpProbeClass({
profileIsLoopback: e.profileIsLoopback,
attachOnly: e.attachOnly
})) {
const e = t ?? PROFILE_HTTP_REACHABILITY_TIMEOUT_MS;
return {
httpTimeoutMs: e,
wsTimeoutMs: Math.max(PROFILE_WS_REACHABILITY_MIN_TIMEOUT_MS, Math.min(PROFILE_WS_REACHABILITY_MAX_TIMEOUT_MS, e * 2))
};
}
if (t !== void 0) {
const e = addTimerTimeoutGraceMs(t, t) ?? t;
return {
httpTimeoutMs: Math.max(t, n),
wsTimeoutMs: Math.max(e, r)
};
}
return {
httpTimeoutMs: n,
wsTimeoutMs: r
};
}
//#endregion
//#region extensions/browser/src/browser/cdp-auth.ts
function decodeUrlUserInfo(e) {
try {
return decodeURIComponent(e);
} catch {
return e;
}
}
/** Merge URL basic-auth credentials into headers without overriding explicit auth. */
function getHeadersWithAuth(e, t = {}) {
const n = { ...t };
const r = URL.parse(e);
if (!r || !r.username && !r.password || Object.keys(n).some((e) => e.trim().toLowerCase() === "authorization")) return n;
const i = decodeUrlUserInfo(r.username);
const a = decodeUrlUserInfo(r.password);
const o = Buffer.from(`${i}:${a}`).toString("base64");
return {
...n,
Authorization: `Basic ${o}`
};
}
/** Remove URL userinfo after callers have converted it to an Authorization header. */
function stripCdpUrlCredentials(e) {
const t = URL.parse(e);
if (!t || !t.username && !t.password) return e;
t.username = "";
t.password = "";
return t.toString();
}
//#endregion
//#region extensions/browser/src/browser/cdp-proxy-bypass.ts
/**
* Proxy bypass for CDP (Chrome DevTools Protocol) localhost connections.
*
* When HTTP_PROXY / HTTPS_PROXY / ALL_PROXY environment variables are set,
* CDP connections to localhost/127.0.0.1 can be incorrectly routed through
* the proxy, causing browser control to fail.
*
* @see https://github.com/nicepkg/openclaw/issues/31219
*/
/** HTTP agent that never uses a proxy — for localhost CDP connections. */
const directHttpAgent = new http.Agent();
const directHttpsAgent = new https.Agent();
/**
* Returns a plain (non-proxy) agent for WebSocket or HTTP connections
* when the target is a loopback address. Returns `undefined` otherwise
* so callers fall through to their default behaviour.
*/
function getDirectAgentForCdp(e) {
const t = URL.parse(e);
if (t && isLoopbackHost(t.hostname)) return t.protocol === "https:" || t.protocol === "wss:" ? directHttpsAgent : directHttpAgent;
}
const LOOPBACK_ENTRIES = "localhost,127.0.0.1,[::1]";
function noProxyValueCoversLocalhost(e) {
const t = new Set((e ?? "").split(",").map((e) => e.trim().toLowerCase()).filter(Boolean));
return t.has("localhost") && t.has("127.0.0.1") && t.has("[::1]");
}
function appendLoopbackEntries(e) {
return e ? `${e},${LOOPBACK_ENTRIES}` : LOOPBACK_ENTRIES;
}
let noProxyLeaseCount = 0;
let noProxySnapshot = null;
/**
* Scoped NO_PROXY bypass for loopback CDP URLs.
*
* Only loopback destinations mutate env vars. The final caller restores the
* initial values; third-party env edits during a CDP call are best effort.
*/
async function withNoProxyForCdpUrl(e, t) {
if (!isLoopbackHost(URL.parse(e)?.hostname ?? "") || !hasProxyEnvConfigured()) return await t();
if (noProxyLeaseCount === 0 && !(noProxyValueCoversLocalhost(process.env.NO_PROXY) && noProxyValueCoversLocalhost(process.env.no_proxy))) {
const e = {
NO_PROXY: process.env.NO_PROXY,
no_proxy: process.env.no_proxy
};
Object.assign(process.env, {
NO_PROXY: appendLoopbackEntries(e.NO_PROXY || e.no_proxy),
no_proxy: appendLoopbackEntries(e.no_proxy || e.NO_PROXY)
});
noProxySnapshot = e;
}
noProxyLeaseCount += 1;
try {
return await t();
} finally {
noProxyLeaseCount -= 1;
if (noProxyLeaseCount === 0 && noProxySnapshot) {
for (const e of ["NO_PROXY", "no_proxy"]) if (noProxySnapshot[e] !== void 0) process.env[e] = noProxySnapshot[e];
else delete process.env[e];
noProxySnapshot = null;
}
}
}
/**
* Scoped managed-proxy bypass for the exact CDP URL about to be used.
*
* Proxyline dynamic bypass registrations are exact URL matches, so callers
* must register the concrete `/json/version` or `ws://.../devtools/...` URL
* rather than a CDP base URL.
*/
function withManagedProxyForCdpUrl(e, t) {
const n = registerManagedProxyBrowserCdpBypass(e);
let r;
try {
r = t();
} catch (e) {
n?.();
throw e;
}
const i = r;
if (typeof i === "object" && i !== null && "finally" in i && typeof i.finally === "function") return i.finally(() => n?.());
n?.();
return r;
}
/**
* Validate managed-proxy loopback policy without keeping a long-lived bypass.
* Exact CDP request sites install their own scoped bypasses.
*/
function assertManagedProxyAllowsCdpUrl(e) {
withManagedProxyForCdpUrl(e, () => void 0);
}
//#endregion
//#region extensions/browser/src/browser/playwright-core.runtime.ts
/**
* Playwright runtime loader.
*
* Loads playwright-core only when browser behavior needs it. The worker deploy
* build declares its static dependency closure in worker-deploy-build-plugin.mts.
*/
const require = createRequire(import.meta.url);
function getPlaywrightCore() {
return require("playwright-core");
}
/** Dependency-owned User-Agent used by Playwright's native CDP WebSocket transport. */
function getPlaywrightUserAgent() {
return require("playwright-core/lib/coreBundle").getUserAgent();
}
//#endregion
//#region extensions/browser/src/browser/cdp-websocket.ts
const PLAYWRIGHT_CDP_MAX_PAYLOAD_BYTES = 268435456;
const PLAYWRIGHT_CDP_PER_MESSAGE_DEFLATE = {
clientNoContextTakeover: true,
zlibDeflateOptions: { level: 3 },
zlibInflateOptions: { chunkSize: 10240 },
threshold: 10240
};
const PLAYWRIGHT_CDP_MAX_REDIRECTS = 10;
var CdpSocketError = class extends Error {
constructor(e, t) {
super(t);
this.kind = e;
}
};
function withDefaultPlaywrightUserAgent(e) {
if (Object.keys(e).some((e) => e.trim().toLowerCase() === "user-agent")) return e;
return {
...e,
"User-Agent": getPlaywrightUserAgent()
};
}
function cdpWebSocketAuthority(e) {
const t = new URL(e);
return `${t.protocol}//${t.host}`;
}
function assertSameAuthorityWebSocketRedirect(e, t, n) {
if (cdpWebSocketAuthority(e) === cdpWebSocketAuthority(t)) return;
n.destroy(/* @__PURE__ */ new Error("CDP WebSocket redirect changed authority"));
}
function defaultPortForWebSocketProtocol(e) {
return e === "wss:" || e === "https:" ? "443" : "80";
}
function normalizeAuthorityHostname(e) {
return e.replace(/^\[(.*)\]$/, "$1").toLowerCase();
}
function hostnameFromAgentOptions(e) {
if (e instanceof URL) return e.hostname;
if (!e || typeof e !== "object") return;
if ("hostname" in e && typeof e.hostname === "string") return e.hostname;
const t = "host" in e && typeof e.host === "string" ? e.host : void 0;
if (!t) return;
if (t.startsWith("[")) {
const e = t.indexOf("]");
return e > 0 ? t.slice(1, e) : t;
}
if ((t.match(/:/g) ?? []).length > 1) return t;
return t.includes(":") ? t.split(":")[0] : t;
}
function portFromAgentOptions(e, t) {
if (e instanceof URL) return e.port || defaultPortForWebSocketProtocol(e.protocol);
if (!e || typeof e !== "object") return defaultPortForWebSocketProtocol(t);
if ("port" in e) {
const t = e.port;
if (typeof t === "string" || typeof t === "number") return String(t);
}
return defaultPortForWebSocketProtocol(t);
}
function assertPinnedAgentAuthority(e, t) {
const n = new URL(e);
const r = normalizeAuthorityHostname(n.hostname);
const i = n.port || defaultPortForWebSocketProtocol(n.protocol);
const a = hostnameFromAgentOptions(t);
const o = portFromAgentOptions(t, n.protocol);
if (!a || normalizeAuthorityHostname(a) !== r || o !== i) throw new Error("CDP WebSocket redirect changed authority");
}
function createPinnedAgentForCdpUrl(e, t) {
const n = new URL(e);
const r = {
keepAlive: false,
lookup: t
};
const i = n.protocol === "https:" || n.protocol === "wss:" ? new https.Agent(r) : new http.Agent(r);
const a = i.createConnection.bind(i);
i.createConnection = ((t, n) => {
try {
assertPinnedAgentAuthority(e, t);
} catch (e) {
const t = new net.Socket();
const r = toStringifiedError(e);
process.nextTick(() => {
n?.(r, t);
t.destroy(r);
});
return t;
}
return a(t, n);
});
return i;
}
function createCdpSender(e, t) {
let n = 1;
const r = /* @__PURE__ */ new Map();
const i = typeof t?.commandTimeoutMs === "number" && Number.isFinite(t.commandTimeoutMs) ? normalizeBrowserTimerDelayMs(t.commandTimeoutMs) : void 0;
const send = (t, a, o) => {
const s = n++;
const c = {
id: s,
method: t,
params: a,
sessionId: o
};
return new Promise((n, a) => {
if (e.readyState !== WebSocket.OPEN) {
a(new CdpSocketError("closed", "CDP socket closed"));
return;
}
const o = {
resolve: n,
reject: a
};
if (i !== void 0) o.timer = setTimeout(() => {
closeWithError(new CdpSocketError("timeout", `CDP command ${t} timed out after ${i}ms`));
}, i);
r.set(s, o);
try {
e.send(JSON.stringify(c));
} catch (e) {
r.delete(s);
clearTimeout(o.timer);
a(toStringifiedError(e));
}
});
};
const closeWithError = (n) => {
for (const [, e] of r) {
clearTimeout(e.timer);
e.reject(n);
}
r.clear();
if (t?.abortScope === "operation" && n instanceof CdpSocketError && n.kind === "timeout") e.terminate();
else e.close();
};
e.on("error", (e) => {
closeWithError(toStringifiedError(e));
});
e.on("message", (e) => {
try {
const t = JSON.parse(rawDataToString(e));
if (typeof t.id !== "number") return;
const n = r.get(t.id);
if (!n) return;
r.delete(t.id);
clearTimeout(n.timer);
if (t.error?.message) {
n.reject(new CdpSocketError("protocol", t.error.message));
return;
}
n.resolve(t.result);
} catch {}
});
e.on("close", () => {
closeWithError(new CdpSocketError("closed", "CDP socket closed"));
});
return {
send,
closeWithError
};
}
/** Open a CDP WebSocket with URL basic-auth and proxy bypass handling. */
function openCdpWebSocket(e, t) {
const n = getHeadersWithAuth(e, t?.headers ?? {});
const r = t?.playwrightTransportDefaults ? withDefaultPlaywrightUserAgent(n) : n;
const i = typeof t?.handshakeTimeoutMs === "number" && Number.isFinite(t.handshakeTimeoutMs) ? Math.max(1, Math.floor(t.handshakeTimeoutMs)) : CDP_WS_HANDSHAKE_TIMEOUT_MS;
const a = stripCdpUrlCredentials(e);
const o = t?.lookup ? createPinnedAgentForCdpUrl(a, t.lookup) : getDirectAgentForCdp(a);
return withManagedProxyForCdpUrl(a, () => {
const e = new WebSocket(a, {
handshakeTimeout: i,
...t?.playwrightTransportDefaults ? {
followRedirects: true,
maxRedirects: PLAYWRIGHT_CDP_MAX_REDIRECTS,
maxPayload: PLAYWRIGHT_CDP_MAX_PAYLOAD_BYTES,
perMessageDeflate: PLAYWRIGHT_CDP_PER_MESSAGE_DEFLATE
} : {},
...Object.keys(r).length ? { headers: r } : {},
...o ? { agent: o } : {}
});
if (t?.playwrightTransportDefaults) e.on("redirect", (e, t) => {
assertSameAuthorityWebSocketRedirect(a, e, t);
});
return e;
});
}
function shouldRetryCdpHandshakeError(e) {
if (!(e instanceof Error)) return false;
const t = e.message.toLowerCase();
if (!t) return false;
if (t.includes("rate limit")) return false;
const n = t.match(/(?:unexpected server response|response):\s*(\d{3})/);
if (n?.[1]) return Number(n[1]) >= 500;
return t.includes("cdp socket closed") || t.includes("econnreset") || t.includes("econnrefused") || t.includes("econnaborted") || t.includes("ehostunreach") || t.includes("enetunreach") || t.includes("etimedout") || t.includes("socket hang up") || t.includes("websocket error") || t.includes("closed before");
}
async function withCdpSocket(e, t, n) {
const r = n?.handshakeRetries ?? 2;
for (let i = 0;; i += 1) {
n?.signal?.throwIfAborted();
const a = openCdpWebSocket(e, n);
const { send: o, closeWithError: s } = createCdpSender(a, n);
const c = new Promise((e, t) => {
a.once("open", () => e());
a.once("error", (e) => t(e));
a.once("close", () => t(new CdpSocketError("closed", "CDP socket closed")));
});
const abortSocket = () => {
s(toStringifiedError(n?.signal?.reason));
a.terminate();
};
n?.signal?.addEventListener("abort", abortSocket, { once: true });
if (n?.signal?.aborted) abortSocket();
try {
try {
await c;
} catch (e) {
s(toStringifiedError(e));
n?.signal?.throwIfAborted();
if (i >= r || !shouldRetryCdpHandshakeError(e)) throw e;
await sleepWithAbort(200 * 2 ** i, n?.signal).catch((e) => {
n?.signal?.throwIfAborted();
throw e;
});
continue;
}
if (n?.abortScope !== "operation") n?.signal?.removeEventListener("abort", abortSocket);
else n.signal?.throwIfAborted();
const e = await t(o);
if (n?.abortScope === "operation") n.signal?.throwIfAborted();
return e;
} catch (e) {
s(toStringifiedError(e));
throw e;
} finally {
n?.signal?.removeEventListener("abort", abortSocket);
a.close();
}
}
}
//#endregion
//#region extensions/browser/src/browser/rate-limit-message.ts
const BROWSER_SERVICE_RATE_LIMIT_MESSAGE = "Browser service rate limit reached. Wait for the current session to complete, or retry later.";
const BROWSERBASE_RATE_LIMIT_MESSAGE = "Browserbase rate limit reached (max concurrent sessions). Wait for the current session to complete, or upgrade your plan.";
function isBrowserbaseUrl(e) {
if (!/^https?:\/\//i.test(e.trim())) return false;
const t = URL.parse(e)?.hostname.trim().toLowerCase() ?? "";
return t === "browserbase.com" || t.endsWith(".browserbase.com");
}
function resolveBrowserRateLimitMessage(e) {
return isBrowserbaseUrl(e) ? BROWSERBASE_RATE_LIMIT_MESSAGE : BROWSER_SERVICE_RATE_LIMIT_MESSAGE;
}
//#endregion
//#region extensions/browser/src/browser/cdp.helpers.ts
const CDP_URL_IN_TEXT_RE = /\b(?:https?|wss?):\/\/[^\s"'<>`]+/gi;
function isWebSocketUrl(e) {
const t = URL.parse(e);
return t?.protocol === "ws:" || t?.protocol === "wss:";
}
/**
* Returns true when `url` is a ws/wss URL with a `/devtools/<kind>/<id>`
* path segment — i.e. a handshake-ready per-browser or per-target CDP
* endpoint that can be opened directly without HTTP discovery.
*
* Bare ws roots (`ws://host:port`, `ws://host:port/`) and any other
* non-`/devtools/...` paths are NOT direct endpoints: Chrome's debug
* port only accepts WebSocket upgrades on the specific path returned
* by `GET /json/version`. Callers with a bare ws root must normalise
* it to http for discovery instead of attempting a root handshake that
* Chrome will reject with HTTP 400.
*/
function isDirectCdpWebSocketEndpoint(e) {
const t = URL.parse(e);
return (t?.protocol === "ws:" || t?.protocol === "wss:") && /\/devtools\/(?:browser|page|worker|shared_worker|service_worker)\/[^/]/i.test(t.pathname);
}
async function resolveCdpWebSocketDiscovery(e, t) {
if (isDirectCdpWebSocketEndpoint(e)) return {
url: e,
discovered: false
};
const n = isWebSocketUrl(e) ? normalizeCdpHttpBaseForJsonEndpoints(e) : e;
const r = await t(n);
if (r) return {
url: normalizeCdpWsUrl(r, n),
discovered: true
};
return isWebSocketUrl(e) ? {
url: e,
discovered: false
} : null;
}
/** Restrict a trusted CDP endpoint to its configured control-plane host. */
function scopeCdpPolicyToConfiguredEndpoint(e, t) {
if (!t) return;
const n = new URL(e).hostname;
if (!isLoopbackHost(n) && !isCdpHostnameTrustedByPolicy(t, n)) return t;
return withExactHostnamePolicy(t, n);
}
function cdpEndpointAuthority(e) {
const t = new URL(e);
const n = t.protocol === "https:" || t.protocol === "wss:";
const r = t.port || (n ? "443" : "80");
return `${n ? "tls" : "plain"}://${t.hostname}:${r}`;
}
function assertDiscoveredCdpEndpointMatchesConfigured(e, t, n) {
if (cdpEndpointAuthority(e) === cdpEndpointAuthority(t) || allowsDiscoveredCdpAuthorityChange(n)) return;
throw new BrowserCdpEndpointBlockedError({ cause: new SsrFBlockedError("discovered CDP endpoint changed configured authority") });
}
async function assertCdpEndpointAllowed(e, t, n) {
if (n?.source === "discovered") assertDiscoveredCdpEndpointMatchesConfigured(e, n.configuredUrl, t);
if (!t) return;
const r = new URL(e);
if (![
"http:",
"https:",
"ws:",
"wss:"
].includes(r.protocol)) throw new Error(`Invalid CDP URL protocol: ${r.protocol.replace(":", "")}`);
try {
const e = isLoopbackHost(r.hostname) && n?.source !== "discovered" ? withExactHostnamePolicy(t, r.hostname) : t;
return await resolvePinnedHostnameWithPolicy(r.hostname, { policy: e });
} catch (e) {
throw new BrowserCdpEndpointBlockedError({ cause: e });
}
}
/** Redact CDP URLs and credential-shaped text before dependency errors leave Browser. */
function redactCdpErrorText(e) {
const t = e.replace(CDP_URL_IN_TEXT_RE, (e) => redactCdpUrl(e) ?? e);
return redactToolPayloadText(t);
}
function appendCdpPath(e, t) {
const n = new URL(e);
n.pathname = `${n.pathname.replace(/\/$/, "")}${t.startsWith("/") ? t : `/${t}`}`;
return n.toString();
}
function normalizeCdpWsUrl(e, t) {
const n = new URL(e);
const r = new URL(t);
const i = n.hostname === "0.0.0.0" || n.hostname === "[::]";
if ((isLoopbackHost(n.hostname) || i) && !isLoopbackHost(r.hostname)) {
n.hostname = r.hostname;
n.port = r.port || (r.protocol === "https:" ? "443" : "80");
n.protocol = r.protocol === "https:" ? "wss:" : "ws:";
} else if (isLoopbackHost(n.hostname) && isLoopbackHost(r.hostname)) {
n.hostname = r.hostname;
if (!n.port && r.port) n.port = r.port;
}
if (r.protocol === "https:" && n.protocol === "ws:") n.protocol = "wss:";
if (!n.username && !n.password && (r.username || r.password)) {
n.username = r.username;
n.password = r.password;
}
for (const [e, t] of r.searchParams.entries()) if (!n.searchParams.has(e)) n.searchParams.append(e, t);
return n.toString();
}
/** Normalize ws/wss and direct devtools URLs back to the HTTP JSON endpoint base. */
function normalizeCdpHttpBaseForJsonEndpoints(e) {
const t = URL.parse(e);
if (t) {
if (t.protocol === "ws:") t.protocol = "http:";
else if (t.protocol === "wss:") t.protocol = "https:";
t.pathname = t.pathname.replace(/\/devtools\/browser\/.*$/, "");
t.pathname = t.pathname.replace(/\/cdp$/, "");
return t.toString().replace(/\/$/, "");
}
return e.replace(/^ws:/, "http:").replace(/^wss:/, "https:").replace(/\/devtools\/browser\/.*$/, "").replace(/\/cdp$/, "").replace(/\/$/, "");
}
function fingerprintCdpIdentity(e) {
return `sha256:${createHash("sha256").update(e).digest("hex")}`;
}
function canonicalCdpAuthority(e, t) {
return `${t}//${e.hostname.toLowerCase().replace(/\.$/, "")}:${e.port || (t === "https:" || t === "wss:" ? "443" : "80")}`;
}
function canonicalCdpProfileIdentity(e) {
const t = new URL(e);
const n = t.protocol === "ws:" ? "http:" : t.protocol === "wss:" ? "https:" : t.protocol;
if (n !== "http:" && n !== "https:") throw new Error("CDP profile identity requires an HTTP(S) or WebSocket endpoint");
if (!/^\/devtools\/browser\/[A-Za-z0-9._-]+$/.test(t.pathname) && t.pathname.split("/").some((e) => e.length >= 24)) throw new Error("CDP profile endpoint path may contain credentials");
return canonicalCdpAuthority(t, n);
}
function canonicalBrowserWebSocketIdentity(e) {
const t = new URL(e);
if (t.protocol !== "ws:" && t.protocol !== "wss:") throw new Error("Browser websocket identity requires a WebSocket endpoint");
const n = t.pathname.match(/^\/devtools\/browser\/([A-Za-z0-9._-]+)$/);
if (!n?.[1]) throw new Error("Browser websocket identity path is not credential-free");
return `${canonicalCdpAuthority(t, t.protocol)}/devtools/browser/${n[1]}`;
}
async function resolveCdpTabOwnershipContext(e) {
e.signal?.throwIfAborted();
const t = normalizeCdpHttpBaseForJsonEndpoints(e.cdpUrl);
let n;
try {
n = await fetchJson(appendCdpPath(t, "/json/version"), e.timeoutMs, { signal: e.signal }, e.ssrfPolicy);
} catch (t) {
if (e.signal?.aborted) throw e.signal.reason ?? t;
if (t instanceof BrowserCdpEndpointBlockedError) throw t;
return { ownership: {
status: "non-durable",
reason: "browser-identity-lookup-failed"
} };
}
e.signal?.throwIfAborted();
const r = typeof n.webSocketDebuggerUrl === "string" ? n.webSocketDebuggerUrl.trim() : "";
if (!r) return { ownership: {
status: "non-durable",
reason: "browser-identity-unavailable"
} };
try {
const n = normalizeCdpWsUrl(r, t);
const i = await assertCdpEndpointAllowed(n, e.ssrfPolicy, {
source: "discovered",
configuredUrl: e.cdpUrl
});
return {
ownership: {
status: "durable",
nativeTargetId: e.nativeTargetId,
/** Build restart-stable hashes without retaining endpoint credentials. */
profileFingerprint: fingerprintCdpIdentity(JSON.stringify([e.profileName, canonicalCdpProfileIdentity(e.cdpUrl)])),
browserInstanceFingerprint: fingerprintCdpIdentity(canonicalBrowserWebSocketIdentity(r))
},
browserWebSocketUrl: n,
browserWebSocketLookup: i?.lookup
};
} catch (e) {
if (e instanceof BrowserCdpEndpointBlockedError) throw e;
return { ownership: {
status: "non-durable",
reason: "browser-identity-unavailable"
} };
}
}
/** Resolve durable ownership for a native target from the browser-level CDP identity. */
async function resolveCdpTabOwnership(e) {
return (await resolveCdpTabOwnershipContext(e)).ownership;
}
/** Verify ownership and close a tracked target on the same browser-level CDP connection. */
async function closeTrackedCdpTarget(e) {
const t = await resolveCdpTabOwnershipContext(e);
if (t.ownership.status !== "durable" || !t.browserWebSocketUrl) return {
status: "unavailable",
reason: t.ownership.status === "non-durable" ? t.ownership.reason : "browser-identity-unavailable"
};
if (t.ownership.profileFingerprint !== e.expectedProfileFingerprint || t.ownership.browserInstanceFingerprint !== e.expectedBrowserInstanceFingerprint) return { status: "ownership-mismatch" };
e.signal?.throwIfAborted();
try {
return await withCdpSocket(t.browserWebSocketUrl, async (t) => {
e.signal?.throwIfAborted();
const n = await t("Target.getTargets");
e.signal?.throwIfAborted();
const r = n && typeof n === "object" ? n.targetInfos : void 0;
if (!Array.isArray(r)) return {
status: "unavailable",
reason: "target-lookup-failed"
};
if (!r.some((t) => t && typeof t === "object" && t.targetId === e.nativeTargetId)) return { status: "missing" };
const dispatch = async () => {
try {
e.signal?.throwIfAborted();
const n = await t("Target.closeTarget", { targetId: e.nativeTargetId });
e.signal?.throwIfAborted();
return n && typeof n === "object" && n.success === true ? { status: "closed" } : {
status: "unavailable",
reason: "target-close-failed"
};
} catch (e) {
if (String(e).includes("No target with given id found")) return { status: "missing" };
throw e;
}
};
return e.closeIfCurrent ? await e.closeIfCurrent(dispatch) : await dispatch();
}, {
commandTimeoutMs: e.timeoutMs,
handshakeTimeoutMs: e.timeoutMs,
handshakeRetries: 0,
lookup: t.browserWebSocketLookup
});
} catch (t) {
if (e.signal?.aborted) throw e.signal.reason ?? t;
if (t instanceof BrowserCdpEndpointBlockedError) throw t;
return {
status: "unavailable",
reason: "target-lookup-failed"
};
}
}
/** Fetch and parse a CDP JSON endpoint through the configured SSRF guard. */
async function fetchJson(e, t = CDP_HTTP_REQUEST_TIMEOUT_MS, n, r) {
const { response: i, release: a } = await fetchCdpChecked(e, t, n, r);
try {
return await readProviderJsonResponse(i, "cdp-json");
} finally {
await a();
}
}
/** Fetch a CDP endpoint and return the response with an idempotent release hook. */
async function fetchCdpChecked(e, t = CDP_HTTP_REQUEST_TIMEOUT_MS, n, r) {
const i = new AbortController();
const a = setTimeout(i.abort.bind(i), normalizeBrowserTimerDelayMs(t));
const o = n?.signal ? AbortSignal.any([i.signal, n.signal]) : i.signal;
let s;
let c;
let l = false;
const release = async () => {
if (l) return;
l = true;
clearTimeout(a);
i.abort();
try {
if (s && !s.bodyUsed) await s.body?.cancel();
} catch {} finally {
await c?.();
}
};
try {
const t = n?.headers;
const i = getHeadersWithAuth(e, t instanceof Headers || Array.isArray(t) ? Object.fromEntries(new Headers(t)) : t);
const a = stripCdpUrlCredentials(e);
const l = await withManagedProxyForCdpUrl(a, () => withNoProxyForCdpUrl(a, async () => {
const e = new URL(a);
const t = isLoopbackHost(e.hostname) ? withExactHostnamePolicy(r, e.hostname) : r ?? { allowPrivateNetwork: true };
const l = await fetchWithSsrFGuard({
url: a,
init: {
...n,
headers: i
},
signal: o,
policy: t,
auditContext: "browser-cdp"
});
c = l.release;
s = l.response;
return s;
}));
if (!l.ok) {
if (l.status === 429) throw new Error(`${resolveBrowserRateLimitMessage(e)} Do NOT retry the browser tool.`);
throw new Error(`HTTP ${l.status}`);
}
return {
response: l,
release
};
} catch (e) {
await release();
if (e instanceof SsrFBlockedError) throw new BrowserCdpEndpointBlockedError({ cause: e });
throw e;
}
}
async function fetchOk(e, t = CDP_HTTP_REQUEST_TIMEOUT_MS, n, r) {
const { release: i } = await fetchCdpChecked(e, t, n, r);
await i();
}
//#endregion
export { CHROME_STOP_TIMEOUT_MS as A, getHeadersWithAuth as C, CHROME_BOOTSTRAP_PREFS_TIMEOUT_MS as D, CHROME_BOOTSTRAP_EXIT_TIMEOUT_MS as E, usesFastLoopbackCdpProbeClass as F, PLAYWRIGHT_TARGET_INFO_TIMEOUT_MS as M, PROFILE_ATTACH_RETRY_TIMEOUT_MS as N, CHROME_MCP_ATTACH_READY_WINDOW_MS as O, resolveCdpReachabilityTimeouts as P, withNoProxyForCdpUrl as S, CDP_JSON_NEW_TIMEOUT_MS as T, openCdpWebSocket as _, fetchJson as a, assertManagedProxyAllowsCdpUrl as b, isWebSocketUrl as c, redactCdpErrorText as d, resolveCdpTabOwnership as f, CdpSocketError as g, resolveBrowserRateLimitMessage as h, fetchCdpChecked as i, MANAGED_CDP_READY_HTTP_TIMEOUT_MS as j, CHROME_STDERR_HINT_MAX_CHARS as k, normalizeCdpHttpBaseForJsonEndpoints as l, scopeCdpPolicyToConfiguredEndpoint as m, assertCdpEndpointAllowed as n, fetchOk as o, resolveCdpWebSocketDiscovery as p, closeTrackedCdpTarget as r, isDirectCdpWebSocketEndpoint as s, appendCdpPath as t, normalizeCdpWsUrl as u, withCdpSocket as v, stripCdpUrlCredentials as w, withManagedProxyForCdpUrl as x, getPlaywrightCore as y };