UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

755 lines (754 loc) • 29.9 kB
import { o as normalizeLowercaseStringOrEmpty, t as hasNonEmptyString } from "../../string-coerce-CCIiB4H7.mjs"; import { r as asNullableRecord } from "../../record-coerce-CVPuDqcc.mjs"; import { f as normalizeStringEntries } from "../../string-normalization-DLmfYZXI.mjs"; import { o as hasConfiguredSecretInput } from "../../types.secrets-BmNLLnHp.mjs"; import { t as formatCliCommand } from "../../command-format-CqdwUgPk.mjs"; import { Et as _enum, Jn as string, Lt as boolean, Pn as number, Un as record, qn as strictObject, sr as unknown } from "../../schemas-Cy6abvsu.mjs"; import { n as enqueueKeyedTask } from "../../keyed-async-queue-DewLnYvW.mjs"; import { t as ErrorCodes } from "../../gateway-error-details-B69XiHdh.mjs"; import { p as errorShape } from "../../error-codes-BzF7aRQ0.mjs"; import { n as detectMime } from "../../mime-D2wVBzpa.mjs"; import { s as isPrivateIpAddress } from "../../ssrf-DHBNJw0c.mjs"; import "../../string-coerce-runtime-BwAZZDf5.mjs"; import { n as redactCdpUrl } from "../../browser-cdp-DYGt86Rj.mjs"; import { i as isPrivateNetworkOptInEnabled } from "../../ssrf-policy-CVsxdUWo.mjs"; import { i as resolveBrowserConfig, r as isLocalManagedProfile, s as resolveProfile } from "../../config-ccOD-Wrr.mjs"; import "../../secret-input-CpgOwFAi.mjs"; import "../../setup-tools-NrA1nFHA.mjs"; import "../../media-mime-8fD2xhws.mjs"; import "../../gateway-runtime-Du0olVch.mjs"; import { a as BROWSER_PROXY_COMMAND, i as applyBrowserTabToolBinding, o as BROWSER_PROXY_UPLOAD_COMMAND } from "../../browser-tool-description-CxoyjbON.mjs"; import { J as getOptionalBrowserStateRuntime, q as getBrowserStateRuntime } from "../../session-tab-store-B94ME8MA.mjs"; import { n as resolveCdpControlPolicy } from "../../cdp-reachability-policy-DB0QjzXP.mjs"; import { r as closeTrackedCdpTarget } from "../../cdp.helpers-Bxe-G5Kr.mjs"; import { c as loadBrowserConfigForRuntimeRefresh } from "../../server-context-oqjYXXZE.mjs"; import { n as withTimeout } from "../../sdk-node-runtime-BnZEBbeE.mjs"; import { c as isProfileOperationCurrent, o as getProfileLifecycle } from "../../server-context.lifecycle-ZeQVAKUI.mjs"; import { n as getPwAiModule } from "../../pw-ai-module-BjUpv3YO.mjs"; import { a as normalizeBrowserRequestPath, i as isPersistentBrowserProfileMutation, n as browserNavigationPolicyForProfile, o as resolveRequestedBrowserProfile, r as isBrowserHostLocalRoute } from "../../routes-BC1rdkyd.mjs"; import { t as createBrowserRouteDispatcher } from "../../dispatcher-CpOB7hDZ.mjs"; import { n as resolveBrowserControlAuth } from "../../control-auth-CROFT0Gj.mjs"; import { n as handleBrowserGatewayRequest, r as createBrowserTool } from "../../browser-request-DayigK53.mjs"; import { d as assertBrowserProxyFileCountWithinLimit, f as createBrowserProxyFailure, h as visitBrowserProxyFilePaths, l as BROWSER_PROXY_OWNED_TAB_CLOSE_PATH, n as ensureBrowserProxyUploadCleanup, o as stageBrowserProxyUploadRequest, r as hasBrowserProxyUploadWork, s as BROWSER_PROXY_ERROR_ENVELOPE, t as discardStagedBrowserProxyUpload, u as assertBrowserProxyFileBytesWithinLimits } from "../../browser-proxy-upload-CKV5WP9y.mjs"; import { t as resolveBrowserProxyTimeoutMs } from "../../browser-proxy-timeouts-mqURld-y.mjs"; import { i as hasBrowserControlWork, r as getBrowserControlState, t as createBrowserControlContext } from "../../browser-control-state-DGe-q2t-.mjs"; import { t as describeBrowserControlUnavailable } from "../../plugin-enabled-Bu-dbx9E.mjs"; import { n as stopBrowserControlService, t as startBrowserControlServiceFromConfig } from "../../control-service-jRv8Hwcy.mjs"; import { n as sameBrowserDashboardDefinition, t as readBrowserDashboardDefinition } from "../../browser-dashboard-definition-C69ubA6g.mjs"; import fs from "node:fs/promises"; //#region extensions/browser/src/session-browser-dashboard.ts const MAX_SESSION_DASHBOARDS = 64; function keyFor(e) { return JSON.stringify([ e.agentId, e.sessionKey, e.instanceId ]); } function response(e) { const t = e.definition; return { sessionKey: t.sessionKey, name: t.name, instanceId: t.instanceId, revision: t.revision, url: t.url, title: t.title, paused: e.paused, stopping: false, ...e.page ? { browserTab: { target: "host", profile: t.profile, targetId: e.page.targetId } } : {} }; } async function createResource(e, t, n, r) { const i = getBrowserStateRuntime(); const a = i.sessionDashboards ??= /* @__PURE__ */ new Map(); if (a.size >= MAX_SESSION_DASHBOARDS) throw new Error("The Gateway has reached its isolated dashboard limit. Remove an unused browser widget and retry."); const o = t.retainSession(); const s = new AbortController(); const c = keyFor(e); let assertProfileCurrent; let removeProfileAbort; let l; const close = () => { s.abort(/* @__PURE__ */ new Error("The isolated browser dashboard was retired.")); o.signal.removeEventListener("abort", onAbort); o.release(); removeProfileAbort?.(); removeProfileAbort = void 0; if (!l) l = (async () => { await u.page?.close(); if (a.get(c) === u) a.delete(c); })().catch((e) => { l = void 0; throw e; }); return l; }; const assertCurrent = () => { o.assertCurrent(); if (s.signal.aborted || getOptionalBrowserStateRuntime() !== i || u.page && !u.page.isCurrent()) throw new Error("The isolated browser context is no longer available. Reopen the dashboard."); assertProfileCurrent?.(); }; const u = { definition: e, session: t.target, paused: r === "stop", signal: s.signal, assertCurrent, assertDefinitionCurrent: async () => { o.assertCurrent(); const t = await readBrowserDashboardDefinition(e, getBrowserControlState()?.resolved.defaultProfile); o.assertCurrent(); if (!sameBrowserDashboardDefinition(e, t)) { await close(); throw new Error("The dashboard was removed or replaced. Open its current definition."); } assertCurrent(); }, close }; const onAbort = () => { close().catch(() => {}); }; o.signal.addEventListener("abort", onAbort, { once: true }); a.set(c, u); try { t.assertCurrent(); n?.throwIfAborted(); if (r === "open") { if (!await startBrowserControlServiceFromConfig()) throw new Error("Browser control is unavailable on this Gateway."); t.assertCurrent(); n?.throwIfAborted(); const r = createBrowserControlContext(); if (e.profile !== r.state().resolved.defaultProfile) throw new Error("Isolated session dashboards use the configured default managed profile. Remove the widget's custom profile before reopening it."); const i = r.forProfile(e.profile); if (!isLocalManagedProfile(i.profile)) throw new Error("Isolated session dashboards require a local managed browser profile. Attached, extension and remote profiles are unsupported."); await i.ensureBrowserAvailable({ signal: n }); t.assertCurrent(); n?.throwIfAborted(); const a = getBrowserControlState(); const c = a?.profiles.get(e.profile); if (!a || !c) throw new Error("Browser profile is unavailable."); const l = getProfileLifecycle(c).controller.signal; assertProfileCurrent = () => { if (getBrowserControlState() !== a || a.profiles.get(e.profile) !== c || !isProfileOperationCurrent({ state: a, runtime: c, signal: l })) throw new Error("The browser profile changed. Reopen the dashboard."); }; l.addEventListener("abort", onAbort, { once: true }); removeProfileAbort = () => l.removeEventListener("abort", onAbort); const d = await getPwAiModule({ mode: "strict" }); t.assertCurrent(); assertProfileCurrent(); if (!d) throw new Error("Isolated session dashboards require Playwright in this Gateway build."); u.page = await d.createPageViaPlaywright({ cdpUrl: i.profile.cdpUrl, url: e.url, isolatedContext: true, assertCurrent: () => { t.assertCurrent(); assertCurrent(); }, ...browserNavigationPolicyForProfile(r, i), cdpPolicy: resolveCdpControlPolicy(i.profile, a.resolved.ssrfPolicy), signal: n ? AbortSignal.any([ n, o.signal, s.signal ]) : AbortSignal.any([o.signal, s.signal]) }); if (s.signal.aborted) { await u.page.close(); throw new Error("The session browser was retired during startup."); } t.assertCurrent(); n?.throwIfAborted(); await u.assertDefinitionCurrent(); t.assertCurrent(); } assertCurrent(); return u; } catch (e) { await close(); throw e; } } /** Same-widget requests serialize before allocation, so competing viewers never create shared-profile tabs. */ async function accessSessionBrowserDashboard(e, t, n) { if (t.sandboxRequired) throw new Error("This session requires a sandbox. The Gateway's isolated browser context does not provide a sandbox backend; ask an operator for a supported sandbox browser."); t.assertCurrent(); n.signal?.throwIfAborted(); if (!await startBrowserControlServiceFromConfig()) throw new Error("Browser control is unavailable on this Gateway."); t.assertCurrent(); const r = await readBrowserDashboardDefinition(e, getBrowserControlState()?.resolved.defaultProfile); t.assertCurrent(); n.signal?.throwIfAborted(); if (!r || r.sessionKey !== t.target.sessionKey || r.agentId !== t.target.agentId) throw new Error("The browser dashboard is missing, invalid or belongs to a different session."); const i = getBrowserStateRuntime(); const a = keyFor(r); const o = `session:${a}`; const assertOperationCurrent = () => { t.assertCurrent(); n.signal?.throwIfAborted(); if (getOptionalBrowserStateRuntime() !== i) throw new Error("Browser runtime changed."); }; return await enqueueKeyedTask({ tails: i.dashboardOperations, key: o, task: async () => { assertOperationCurrent(); const o = await readBrowserDashboardDefinition({ ...e, instanceId: r.instanceId }, getBrowserControlState()?.resolved.defaultProfile); assertOperationCurrent(); if (!sameBrowserDashboardDefinition(r, o)) throw new Error("The dashboard changed before this operation. Open its current definition."); let s = i.sessionDashboards?.get(a); if (s && (!sameBrowserDashboardDefinition(s.definition, r) || s.session.sessionId !== t.target.sessionId || s.session.lifecycleRevision !== t.target.lifecycleRevision)) { await s.close(); s = void 0; } if (s) { try { await s.assertDefinitionCurrent(); } catch (e) { if (s.page && !s.page.isCurrent()) await s.close(); throw e; } t.assertCurrent(); } if (s && (n.operation === "stop" || n.operation === "open" && (n.resume && s.paused || !s.page && !s.paused))) { await s.close(); s = void 0; t.assertCurrent(); } if (!s) s = await createResource(r, t, n.signal, n.operation); t.assertCurrent(); s.assertCurrent(); return { response: response(s), resource: s }; } }); } //#endregion //#region extensions/browser/src/gateway/session-browser-request.ts const identitySchema = strictObject({ name: string().regex(/^[a-z0-9][a-z0-9._-]{0,63}$/), instanceId: string().min(1).optional(), sessionKey: string().optional(), agentId: string().optional(), resume: boolean().optional() }); const requestSchema = strictObject({ sessionKey: string().min(1), agentId: string().min(1).optional(), method: _enum([ "GET", "POST", "DELETE" ]), path: string(), timeoutMs: number().finite().positive().optional(), dashboard: identitySchema.optional(), query: record(string(), unknown()).optional(), body: record(string(), unknown()).optional() }); const routes = /* @__PURE__ */ new Set([ "GET /tabs", "GET /snapshot", "POST /screenshot", "POST /navigate", "POST /tabs/focus", "POST /act", "POST /screencast" ]); const actions = /* @__PURE__ */ new Set([ "click", "clickCoords", "type", "press", "hover", "scrollIntoView", "drag", "select", "fill", "resize", "wait", "evaluate", "insertText" ]); const selectors = [ "targetId", "profile", "target", "node" ]; /** Closed session route: it never forwards profile, tab, file, cookie or host administration. */ const handleSessionBrowserGatewayRequest = async (e) => { const { respond: t, sessionAccessAuthority: n, signal: r, client: i } = e; try { if (!n) throw new Error("Session browser access requires Gateway session admission."); const a = requestSchema.parse(e.params); await withTimeout(async (e) => { const o = e && r ? AbortSignal.any([e, r]) : e ?? r; const s = identitySchema.parse(a.dashboard ?? (a.method === "GET" ? a.query : a.body)); if (s.sessionKey !== void 0 && s.sessionKey !== a.sessionKey || s.agentId !== void 0 && s.agentId !== n.target.agentId) throw new Error("Dashboard identity must match the admitted session."); const assertInvocation = () => { o?.throwIfAborted(); n.assertCurrent(); }; assertInvocation(); const c = a.path === "/dashboard"; if (!c && !routes.has(`${a.method} ${a.path}`)) throw new Error("This operation is unavailable in an isolated session browser."); if (!c && [a.query, a.body].some((e) => e && selectors.some((t) => Object.hasOwn(e, t)))) throw new Error("Session browser requests cannot select a browser profile or target."); if (a.path === "/act" && (typeof a.body?.kind !== "string" || !actions.has(a.body.kind))) throw new Error("This action is unavailable in an isolated session browser."); const { response: l, resource: u } = await accessSessionBrowserDashboard({ sessionKey: a.sessionKey, agentId: n.target.agentId, name: s.name, instanceId: s.instanceId }, n, { operation: c ? a.method === "POST" ? "open" : a.method === "DELETE" ? "stop" : "inspect" : "inspect", resume: s.resume ?? a.body?.resume === true, signal: o }); assertInvocation(); if (c) { t(true, l); return; } const d = l.browserTab; if (!d || l.paused) throw new Error("The session browser is paused or unavailable. Resume the dashboard first."); const f = createBrowserControlContext(); const assertCurrent = () => { assertInvocation(); u.assertCurrent(); }; assertCurrent(); if (a.path === "/tabs") { const e = await f.forProfile(d.profile).listTabs({ signal: o }); assertCurrent(); t(true, { running: true, tabs: e.filter((e) => e.targetId === d.targetId) }); return; } const p = { kind: "tab", tabId: 0, ...d }; const m = { ...applyBrowserTabToolBinding(a.query ?? {}, p), managedOnly: true }; const h = applyBrowserTabToolBinding(a.body ?? {}, p); const g = await createBrowserRouteDispatcher(f).dispatch({ method: a.method, path: a.path, query: m, body: h, signal: o, assertCurrent, screencastAuthority: { signal: u.signal, assertCurrent: u.assertCurrent, retainRequester: () => { assertInvocation(); u.assertCurrent(); const e = n.retain(); const t = AbortSignal.any([ e.signal, u.signal, ...i?.connectionSignal ? [i.connectionSignal] : [] ]); return { signal: t, release: e.release, isCurrent: () => { try { t.throwIfAborted(); e.assertCurrent(); u.assertCurrent(); return i?.invalidated !== true; } catch { return false; } } }; } } }); assertCurrent(); if (g.status >= 400) { const e = asNullableRecord(g.body); t(false, void 0, errorShape(g.status >= 500 ? ErrorCodes.UNAVAILABLE : ErrorCodes.INVALID_REQUEST, typeof e?.error === "string" ? e.error : "Session browser request failed.", { details: g.body })); return; } t(true, g.body); }, a.timeoutMs, "session browser request"); } catch (e) { t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, e instanceof Error ? e.message : String(e))); } }; //#endregion //#region extensions/browser/src/node-host/invoke-browser.ts function readOwnedTabCloseRequest(e) { const t = asNullableRecord(e); const n = asNullableRecord(t?.ownership); if (n?.status !== "durable" || typeof n.nativeTargetId !== "string" || !n.nativeTargetId.trim() || typeof n.profileFingerprint !== "string" || !n.profileFingerprint.trim() || typeof n.browserInstanceFingerprint !== "string" || !n.browserInstanceFingerprint.trim()) throw new Error("INVALID_REQUEST: valid durable tab ownership required"); return { ownership: { status: "durable", nativeTargetId: n.nativeTargetId.trim(), profileFingerprint: n.profileFingerprint.trim(), browserInstanceFingerprint: n.browserInstanceFingerprint.trim() } }; } const BROWSER_PROXY_STATUS_TIMEOUT_MS = 750; const BROWSER_PROXY_MAX_ENCODED_PAYLOAD_BYTES = 25165824; function countBrowserProxyEncodedPayloadBytes(e) { let t = Buffer.byteLength(e, "utf8") + 2; for (const n of "\"\\") { const r = n.charCodeAt(0); let i = e.indexOf(n); while (i !== -1) { const a = Math.min(i + 128, e.length); for (; i < a; i++) if (e.charCodeAt(i) === r) t++; i = e.indexOf(n, i); } } return t; } function resolveBrowserProxyConfig(e = loadBrowserConfigForRuntimeRefresh()) { const t = e.nodeHost?.browserProxy; if (t?.enabled === false) throw new Error("UNAVAILABLE: node browser proxy disabled"); return { allowProfiles: Array.isArray(t?.allowProfiles) ? normalizeStringEntries(t.allowProfiles) : [] }; } function hasBrowserNodeHostWork() { return hasBrowserControlWork() || hasBrowserProxyUploadWork(); } function collectBrowserProxyPaths(e) { const t = /* @__PURE__ */ new Set(); visitBrowserProxyFilePaths(e, (e) => { t.add(e); assertBrowserProxyFileCountWithinLimit(t.size); }); return [...t]; } async function readBrowserProxyFiles(e) { const t = []; let n = 0; for (const r of e) try { const e = await fs.stat(r).catch(() => null); if (!e || !e.isFile()) throw new Error("file not found"); assertBrowserProxyFileBytesWithinLimits(e.size, n + e.size); const i = await fs.readFile(r); assertBrowserProxyFileBytesWithinLimits(i.byteLength, n + i.byteLength); n += i.byteLength; const a = await detectMime({ buffer: i, filePath: r }); t.push({ path: r, base64: i.toString("base64"), mimeType: a }); } catch (e) { throw new Error(`browser proxy file read failed for ${r}: ${String(e)}`, { cause: e }); } return t; } function isBrowserProxyTimeoutError(e) { return String(e).includes("browser proxy request timed out"); } function combineBrowserProxySignals(e, t) { if (e && t) return AbortSignal.any([e, t]); return e ?? t; } function isWsBackedBrowserProxyPath(e) { return e === "/act" || e === "/download" || e === "/navigate" || e === "/pdf" || e === "/screenshot" || e === "/snapshot" || e === "/wait/download"; } async function readBrowserProxyStatus(e) { const t = e.profile ? { profile: e.profile } : {}; try { const n = await withTimeout((n) => e.dispatcher.dispatch({ method: "GET", path: "/", query: t, signal: n }), BROWSER_PROXY_STATUS_TIMEOUT_MS, "browser proxy status"); if (n.status >= 400 || !n.body || typeof n.body !== "object") return null; const r = n.body; return { running: r.running, transport: r.transport, cdpHttp: r.cdpHttp, cdpReady: r.cdpReady, cdpUrl: r.cdpUrl }; } catch { return null; } } function formatBrowserProxyTimeoutMessage(e) { const t = [`browser proxy timed out for ${e.method} ${e.path} after ${e.timeoutMs}ms`, e.wsBacked ? "ws-backed browser action" : "browser action"]; if (e.profile) t.push(`profile=${e.profile}`); if (e.status) { const n = [ `running=${String(e.status.running)}`, `cdpHttp=${String(e.status.cdpHttp)}`, `cdpReady=${String(e.status.cdpReady)}` ]; if (typeof e.status.transport === "string" && e.status.transport.trim()) n.push(`transport=${e.status.transport}`); if (typeof e.status.cdpUrl === "string" && e.status.cdpUrl.trim()) n.push(`cdpUrl=${redactCdpUrl(e.status.cdpUrl)}`); t.push(`status(${n.join(", ")})`); } return t.join("; "); } async function runBrowserProxyCommand(e, t = BROWSER_PROXY_COMMAND, n) { n?.throwIfAborted(); ensureBrowserProxyUploadCleanup(); if (!e) throw new Error("INVALID_REQUEST: paramsJSON required"); const r = JSON.parse(e); if (t === "browser.proxy" && r.upload !== void 0) throw new Error("INVALID_REQUEST: browser.proxy does not accept upload envelopes"); if (t === "browser.proxy.upload.v1" && !r.upload) throw new Error("INVALID_REQUEST: browser.proxy.upload.v1 requires an upload envelope"); if (t !== "browser.proxy" && t !== "browser.proxy.upload.v1") throw new Error(`INVALID_REQUEST: unsupported browser proxy command: ${t}`); const i = typeof r.path === "string" ? r.path.trim() : ""; if (!i) throw new Error("INVALID_REQUEST: path required"); resolveBrowserProxyConfig(); const a = typeof r.method === "string" ? r.method.trim().toUpperCase() : "GET"; const o = normalizeBrowserRequestPath(i); if (a !== "GET" && a !== "POST" && a !== "DELETE") throw new Error("INVALID_REQUEST: method must be GET, POST, or DELETE"); if (o === "/__openclaw/session-tab/close-owned" && a !== "POST") throw new Error("INVALID_REQUEST: owned tab close requires POST"); if (!await startBrowserControlServiceFromConfig()) throw new Error(await describeBrowserControlUnavailable()); n?.throwIfAborted(); const s = loadBrowserConfigForRuntimeRefresh(); const c = resolveBrowserConfig(s.browser, s); let l = r.body; const u = resolveRequestedBrowserProfile({ query: r.query, body: l, profile: r.profile }) ?? ""; const d = o === "/profiles" ? "" : u || c.defaultProfile; const f = d ? resolveProfile(c, d) : null; const p = f ? { status: "resolved", profile: d, driver: f.driver } : { status: "unavailable" }; const m = r.errorEnvelope === BROWSER_PROXY_ERROR_ENVELOPE; const h = resolveBrowserProxyConfig(s).allowProfiles; if (isPersistentBrowserProfileMutation(a, o)) throw new Error("INVALID_REQUEST: browser.proxy cannot mutate persistent browser profiles"); if (isBrowserHostLocalRoute(a, o)) throw new Error("INVALID_REQUEST: browser.proxy cannot run host-local browser routes"); const assertCurrent = (e) => { n?.throwIfAborted(); const t = resolveBrowserProxyConfig(); const r = e?.name || d || u; if ((o !== "/profiles" || r) && t.allowProfiles.length > 0 && (!r || !t.allowProfiles.includes(r.trim()))) throw new Error("INVALID_REQUEST: browser profile not allowed"); }; assertCurrent(); const g = resolveBrowserProxyTimeoutMs(r.timeoutMs); const _ = performance.now() + g; const v = { method: a, path: o, profile: u || c.defaultProfile || void 0, timeoutMs: g, wsBacked: isWsBackedBrowserProxyPath(o) }; const y = {}; const b = r.query ?? {}; for (const [e, t] of Object.entries(b)) { if (t === void 0 || t === null) continue; y[e] = typeof t === "string" ? t : String(t); } if (d || u) y.profile = d || u; if (o === "/__openclaw/session-tab/close-owned") { const e = readOwnedTabCloseRequest(l); const t = getBrowserControlState()?.resolved ?? c; const r = resolveProfile(t, d); assertCurrent(r ?? void 0); const i = r?.cdpUrl && d ? await closeTrackedCdpTarget({ profileName: d, cdpUrl: r.cdpUrl, nativeTargetId: e.ownership.nativeTargetId, expectedProfileFingerprint: e.ownership.profileFingerprint, expectedBrowserInstanceFingerprint: e.ownership.browserInstanceFingerprint, timeoutMs: t.remoteCdpTimeoutMs, ssrfPolicy: resolveCdpControlPolicy(r, t.ssrfPolicy), signal: n, closeIfCurrent: async (e) => { assertCurrent(r); return await e(); } }) : { status: "ownership-mismatch" }; return JSON.stringify({ result: i, ...m ? { route: p } : {} }); } const x = createBrowserRouteDispatcher(createBrowserControlContext()); let S; try { S = await withTimeout((e) => stageBrowserProxyUploadRequest({ method: a, path: o, body: l, upload: r.upload, signal: combineBrowserProxySignals(e, n) }), g, "browser proxy request"); } catch (e) { if (!isBrowserProxyTimeoutError(e)) throw e; throw new Error(formatBrowserProxyTimeoutMessage({ ...v, status: null }), { cause: e }); } l = S.body; try { assertCurrent(); } catch (e) { await discardStagedBrowserProxyUpload(S); throw e; } const C = _ - performance.now(); if (C <= 0) { await discardStagedBrowserProxyUpload(S); throw new Error(formatBrowserProxyTimeoutMessage({ ...v, status: null })); } let w; try { w = await withTimeout((e) => x.dispatch({ method: a, path: o, query: y, body: l, signal: combineBrowserProxySignals(e, n), assertCurrent: async (e) => { assertCurrent(e); } }), C, "browser proxy request"); } catch (e) { if (!isBrowserProxyTimeoutError(e)) throw e; const t = u || c.defaultProfile; const n = await readBrowserProxyStatus({ dispatcher: x, profile: o === "/profiles" ? void 0 : t }); throw new Error(formatBrowserProxyTimeoutMessage({ ...v, profile: o === "/profiles" ? void 0 : t || void 0, status: n }), { cause: e }); } if (w.status >= 400) { await discardStagedBrowserProxyUpload(S); if (r.errorEnvelope === "browser-v1") return JSON.stringify(createBrowserProxyFailure(w.status, w.body, p)); const e = w.body && typeof w.body === "object" && "error" in w.body ? String(w.body.error).trim() : ""; throw new Error(e ? `${w.status}: ${e}` : `HTTP ${w.status}`); } const T = w.body; if (h.length > 0 && o === "/profiles") { const e = typeof T === "object" && T !== null ? T : {}; e.profiles = (Array.isArray(e.profiles) ? e.profiles : []).filter((e) => { if (!e || typeof e !== "object") return false; const t = e.name; return typeof t === "string" && h.includes(t); }); } const E = collectBrowserProxyPaths(T); const D = E.length > 0 ? await readBrowserProxyFiles(E) : void 0; const O = { result: T, ...D ? { files: D } : {}, ...m ? { route: p } : {} }; const k = JSON.stringify(O); if (countBrowserProxyEncodedPayloadBytes(k) > BROWSER_PROXY_MAX_ENCODED_PAYLOAD_BYTES) throw new Error("browser proxy payload exceeds 24 MiB encoded limit"); return k; } //#endregion //#region extensions/browser/src/security-audit.ts const BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set([ "localhost", "localhost.localdomain", "metadata.google.internal" ]); function isTrustedPrivateHostname(e) { const t = normalizeLowercaseStringOrEmpty(e); return t.length > 0 && BLOCKED_HOSTNAMES.has(t); } function collectBrowserSecurityAuditFindings(e) { const t = []; let n; try { n = resolveBrowserConfig(e.config.browser, e.config); } catch (n) { t.push({ checkId: "browser.control_invalid_config", severity: "warn", title: "Browser control config looks invalid", detail: String(n), remediation: `Fix browser.cdpUrl in ${e.configPath} and re-run "${formatCliCommand("openclaw security audit --deep")}".` }); return t; } if (!n.enabled) return t; if (n.extensionRelay.allowLegacyAuth) t.push({ checkId: "browser.extension_relay_legacy_auth", severity: "warn", title: "Legacy browser extension relay authentication is enabled", detail: "browser.extensionRelay.allowLegacyAuth defaults to true for one migration window, so old relay Bearer, Basic, and token-subprotocol clients can still authenticate.", remediation: "Update paired Chrome extensions and external CDP clients to Browser Relay Authentication v2, then set browser.extensionRelay.allowLegacyAuth=false." }); const r = resolveBrowserControlAuth(e.config, e.env); const i = e.config.gateway?.auth?.mode; const a = Boolean(r.token) || hasNonEmptyString(e.env.OPENCLAW_GATEWAY_TOKEN) || hasConfiguredSecretInput(e.config.gateway?.auth?.token, e.config.secrets?.defaults); const o = i === "password" || i !== "token" && i !== "none" && i !== "trusted-proxy" && !a; const s = Boolean(r.password) || o && (hasNonEmptyString(e.env.OPENCLAW_GATEWAY_PASSWORD) || hasConfiguredSecretInput(e.config.gateway?.auth?.password, e.config.secrets?.defaults)); if (!a && !s) t.push({ checkId: "browser.control_no_auth", severity: "critical", title: "Browser control has no auth", detail: "Browser control HTTP routes are enabled but no gateway.auth token/password is configured. Any local process (or SSRF to loopback) can call browser control endpoints.", remediation: "Set gateway.auth.token (recommended) or gateway.auth.password so browser control HTTP routes require authentication. Restarting the gateway will auto-generate gateway.auth.token when browser control is enabled." }); for (const e of Object.keys(n.profiles)) { const r = resolveProfile(n, e); if (!r || r.cdpIsLoopback) continue; const i = URL.parse(r.cdpUrl); if (!i) continue; const a = redactCdpUrl(r.cdpUrl) ?? r.cdpUrl; if (i.protocol === "http:") t.push({ checkId: "browser.remote_cdp_http", severity: "warn", title: "Remote CDP uses HTTP", detail: `browser profile "${e}" uses http CDP (${a}); this is OK only if it's tailnet-only or behind an encrypted tunnel.`, remediation: "Prefer HTTPS/TLS or a tailnet-only endpoint for remote CDP." }); if (isPrivateNetworkOptInEnabled(n.ssrfPolicy) && (isTrustedPrivateHostname(i.hostname) || isPrivateIpAddress(i.hostname))) t.push({ checkId: "browser.remote_cdp_private_host", severity: "warn", title: "Remote CDP targets a private/internal host", detail: `browser profile "${e}" points at a private/internal CDP host (${a}). This is expected for LAN/tailnet/WSL-style setups, but treat it as a trusted-network endpoint.`, remediation: "Prefer a tailnet or tunnel for remote CDP. If you want strict blocking, set browser.ssrfPolicy.dangerouslyAllowPrivateNetwork=false and allow only explicit hosts." }); } return t; } //#endregion export { collectBrowserSecurityAuditFindings, createBrowserTool, handleBrowserGatewayRequest, handleSessionBrowserGatewayRequest, hasBrowserNodeHostWork, runBrowserProxyCommand, stopBrowserControlService };