UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,104 lines (1,103 loc) • 45.3 kB
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs"; import { a as lstatIfExists } from "./path-existence-Co7-GyVr.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { t as escapeRegExp } from "./regexp-dj3rRPbj.mjs"; import { m as resolveConfigPath } from "./paths-DAcAg5aV.mjs"; import { t as shellEscape } from "./shell-quote-DeRN90_2.mjs"; import "./path-existence-runtime-LOpU--Vt.mjs"; import { a as inspectPathPermissions } from "./file-access-runtime-BD2Fjfbw.mjs"; import "./state-paths-qdCZ9HDY.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import { t as hasExactKeys } from "./strict-json-Uas9w6qB.mjs"; import { t as readPrivateNativeHostFile } from "./extension-native-host-file-gSPVznV7.mjs"; import { n as BROWSER_NATIVE_HOST_NAME, r as NATIVE_HOST_MANIFEST_KEYS, t as BROWSER_NATIVE_HOST_DESCRIPTION } from "./extension-native-host.constants-Vrf4p7mK.mjs"; import { r as replaceFileAtomic } from "./security-runtime-C-zE_Zy_.mjs"; import "./text-utility-runtime-Ds8jsG0J.mjs"; import { a as resolveFirstExtensionProfileName, i as resolveBrowserConfig, s as resolveProfile } from "./config-ccOD-Wrr.mjs"; import { r as isValidProfileName } from "./profiles-DzbsR8ma.mjs"; import { constants } from "node:fs"; import path from "node:path"; import crypto from "node:crypto"; import fs$1 from "node:fs/promises"; import os from "node:os"; import { setTimeout } from "node:timers/promises"; //#region extensions/browser/src/browser/extension-install-context.ts function resolveInstallStateDir() { return path.resolve(resolveStateDir()); } function resolveInstallConfigPath() { const e = process.env; const t = e.OPENCLAW_CONFIG_PATH?.trim(); return t ? resolveStateDir({ ...e, OPENCLAW_STATE_DIR: t }) : void 0; } var NativeHostSetupContextError = class extends Error {}; function assertExpectedNativeHostProfile(e, t) { if (!t) return; const n = t.find((t) => t.manifestPath === e.manifestPath); if (!n || e.state !== n.state || e.browserProfile !== n.browserProfile) throw new NativeHostSetupContextError("Chrome's native host browser selection changed during setup. Inspect setup again before retrying."); } function assertCurrentNativeHostLaunchContext(e) { if (e.state !== "owned") return; const t = e.launchContext; const n = { stateDir: resolveInstallStateDir(), configPath: resolveInstallConfigPath() }; const configPath = (e) => resolveConfigPath({ ...process.env, OPENCLAW_STATE_DIR: e.stateDir, OPENCLAW_CONFIG_PATH: e.configPath }, e.stateDir); if (!t || path.resolve(t.stateDir) !== n.stateDir || configPath(t) !== configPath(n)) throw new NativeHostSetupContextError("Chrome's native host uses a different OpenClaw configuration. Rerun setup with its matching OPENCLAW_STATE_DIR and OPENCLAW_CONFIG_PATH."); } //#endregion //#region extensions/browser/src/browser/extension-install-layout.ts const EXTENSION_ID_PATTERN = /^[a-p]{32}$/; const UNPACKED_MANIFEST_LOCATION = 4; const OWNED_COPY_MARKER = ".openclaw-owned.json"; const PREFERENCES_MAX_BYTES = 33554432; async function approvedInstallRealpaths(e, t) { const n = await fs$1.realpath(e); const r = await fs$1.realpath(t); await assertOwnedPath(n, "directory"); await assertOwnedPath(r, "directory", { allowRootOwner: true }); return [.../* @__PURE__ */ new Set([n, r])]; } /** Chromium crx_file::id_util::GenerateIdForPath for a canonical absolute path. */ function generateChromeExtensionIdForPath(e, t = process.platform) { if (!(t === "win32" ? path.win32.isAbsolute(e) : path.isAbsolute(e))) throw new Error("Chrome extension ID paths must be resolved absolute paths"); let n = e; if (t === "win32" && /^[a-z]:/u.test(n)) n = `${n[0]?.toUpperCase()}${n.slice(1)}`; const r = Buffer.from(n, t === "win32" ? "utf16le" : "utf8"); return crypto.createHash("sha256").update(r).digest("hex").slice(0, 32).replace(/[0-9a-f]/gu, (e) => String.fromCharCode("a".charCodeAt(0) + Number.parseInt(e, 16))); } function homeDirectory() { const e = process.env.HOME ?? process.env.USERPROFILE ?? os.homedir(); if (!e.trim()) throw new Error("Could not resolve the user home directory."); return path.resolve(e); } /** Chromium-derived default user-data and user native-host roots. */ function chromeProductRoots() { const e = process.platform; const t = process.env; const n = homeDirectory(); const root = (e, t, n, r = path.join(n, "NativeMessagingHosts")) => ({ product: e, label: t, userDataDir: n, nativeManifestDir: r }); if (e === "darwin") { const e = path.join(n, "Library", "Application Support"); const t = path.join(e, "Google", "Chrome for Testing"); return [ root("chrome", "Google Chrome", path.join(e, "Google", "Chrome")), root("chrome-for-testing", "Google Chrome for Testing", t), root("chrome-for-testing", "Google Chrome for Testing (documented host root)", t, path.join(e, "Google", "ChromeForTesting", "NativeMessagingHosts")), root("chromium", "Chromium", path.join(e, "Chromium")) ]; } if (e === "linux") { const e = path.resolve(t.CHROME_CONFIG_HOME?.trim() || t.XDG_CONFIG_HOME?.trim() || path.join(n, ".config")); return [ root("chrome", "Google Chrome", path.join(e, "google-chrome")), root("chrome-for-testing", "Google Chrome for Testing", path.join(e, "google-chrome-for-testing")), root("chromium", "Chromium", path.join(e, "chromium")) ]; } if (e === "win32") { const e = t.LOCALAPPDATA?.trim(); if (!e) return []; return [ root("chrome", "Google Chrome", path.join(e, "Google", "Chrome", "User Data"), ""), root("chrome-for-testing", "Google Chrome for Testing", path.join(e, "Google", "Chrome for Testing", "User Data"), ""), root("chromium", "Chromium", path.join(e, "Chromium", "User Data"), "") ]; } return []; } function stableChromeExtensionDir() { return path.join(path.resolve(resolveStateDir()), "browser", "chrome-extension"); } async function assertOwnedPath(e, t, n = {}) { const r = await fs$1.lstat(e); if (r.isSymbolicLink() || (t === "file" ? !r.isFile() : !r.isDirectory())) throw new Error(`Unsafe ${t} at ${e}`); if (process.platform === "win32") { const t = await inspectPathPermissions(e); if (!t.ok || t.source !== "windows-acl" || t.ownerTrusted !== true || t.groupWritable || t.worldWritable) throw new Error(`Refusing unsafe Windows owner or ACL at ${e}`); } else { const t = process.getuid?.(); if (!(t === void 0 || r.uid === t || n.allowRootOwner === true && r.uid === 0)) throw new Error(`Refusing foreign owner at ${e}`); if ((r.mode & 18) !== 0) throw new Error(`Refusing group/world-writable path at ${e}`); } const i = await fs$1.realpath(e); const a = path.resolve(e); if (process.platform === "win32" ? i.toLowerCase() !== a.toLowerCase() : i !== a) throw new Error(`Refusing unresolved path at ${e}`); } async function ensurePrivateDirectory(e) { await fs$1.mkdir(e, { recursive: true, mode: 448 }); await assertOwnedPath(e, "directory"); if (process.platform !== "win32") await fs$1.chmod(e, 448); } async function inspectInstalledCopy(e) { if (!await lstatIfExists(e, "ENOENT")) return { present: false, owned: false }; await assertOwnedPath(e, "directory"); const t = path.join(e, OWNED_COPY_MARKER); try { await assertOwnedPath(t, "file"); const e = JSON.parse(await fs$1.readFile(t, "utf8")); return { present: true, owned: Boolean(e) && typeof e === "object" && !Array.isArray(e) && e.v === 1 }; } catch { return { present: true, owned: false }; } } async function copyRuntimeTree(e, t) { await ensurePrivateDirectory(t); for (const n of await fs$1.readdir(e, { withFileTypes: true })) { if (/(?:sidepanel|copilot|page-share)/iu.test(n.name) || n.name.endsWith(".test.ts") || n.name.endsWith(".test-support.ts") || n.name.endsWith(".test-harness.ts") || n.name.endsWith(".d.ts")) continue; const r = path.join(e, n.name); const i = path.join(t, n.name); if (n.isSymbolicLink()) throw new Error(`Refusing symlink in bundled Chrome extension: ${r}`); if (n.isDirectory()) await copyRuntimeTree(r, i); else if (n.isFile()) { await fs$1.copyFile(r, i, constants.COPYFILE_EXCL); if (process.platform !== "win32") await fs$1.chmod(i, 384); } } } /** Copy/update the bundled extension with rollback-safe same-directory renames. */ async function installStableChromeExtension(e) { const t = await fs$1.realpath(path.resolve(e)); await assertOwnedPath(t, "directory", { allowRootOwner: true }); const n = stableChromeExtensionDir(); await ensurePrivateDirectory(path.resolve(resolveStateDir())); await ensurePrivateDirectory(path.dirname(n)); const r = await inspectInstalledCopy(n); if (r.present && !r.owned) throw new Error(`Refusing to overwrite foreign Chrome extension directory: ${n}`); const i = `${process.pid}-${crypto.randomBytes(6).toString("hex")}`; const a = `${n}.tmp-${i}`; const o = `${n}.previous-${i}`; try { await copyRuntimeTree(t, a); await fs$1.writeFile(path.join(a, OWNED_COPY_MARKER), `${JSON.stringify({ v: 1, owner: "openclaw" })}\n`, { mode: 384, flag: "wx" }); if (r.present) await fs$1.rename(n, o); try { await fs$1.rename(a, n); } catch (e) { if (r.present) await fs$1.rename(o, n).catch(() => void 0); throw e; } if (r.present) await fs$1.rm(o, { recursive: true, force: true }); return await fs$1.realpath(n); } finally { await fs$1.rm(a, { recursive: true, force: true }).catch(() => void 0); } } function comparablePath(e, t) { const n = path.resolve(e); return t === "win32" ? n.toLowerCase() : n; } async function approvedRealpaths(e) { const t = await Promise.all(e.map(async (e) => await fs$1.realpath(e).catch(() => null))); return [...new Set(t.filter((e) => e !== null))]; } /** Discover exact Store identity separately from approved unpacked path records. */ async function discoverChromeExtensionIds(e) { const t = process.platform; const n = new Set((await approvedRealpaths(e.approvedDirs)).map((e) => comparablePath(e, t))); const r = []; const i = []; const a = []; const o = []; for (const s of chromeProductRoots()) { if (!await lstatIfExists(s.userDataDir, "ENOENT")) continue; try { await assertOwnedPath(s.userDataDir, "directory"); } catch (e) { a.push(`${s.label}: ${e instanceof Error ? e.message : String(e)}`); continue; } let c; try { c = await fs$1.readdir(s.userDataDir, { withFileTypes: true }); } catch (e) { a.push(`${s.label}: could not list profiles (${String(e)})`); continue; } for (const l of c) { if (!l.isDirectory() || l.isSymbolicLink()) continue; const c = path.join(s.userDataDir, l.name); for (const u of ["Preferences", "Secure Preferences"]) { const d = path.join(c, u); const f = await lstatIfExists(d, "ENOENT"); if (!f) continue; try { await assertOwnedPath(c, "directory"); await assertOwnedPath(d, "file"); if (f.size > PREFERENCES_MAX_BYTES) throw new Error(`${u} exceeds the 32 MiB inspection limit`); const p = JSON.parse(await fs$1.readFile(d, "utf8"))?.extensions?.settings; if (!p || typeof p !== "object" || Array.isArray(p)) continue; for (const [u, f] of Object.entries(p)) { if (!EXTENSION_ID_PATTERN.test(u) || !f || typeof f !== "object") continue; const p = f; const m = { product: s.product, browser: s.label, userDataDir: s.userDataDir, profile: l.name, securePreferencesPath: d, extensionId: u }; if (u === e.storeExtensionId && p.from_webstore === true && p.location !== UNPACKED_MANIFEST_LOCATION) { const e = p.disable_reasons; const t = (p.state === void 0 || p.state === 1) && (e === void 0 || e === 0 || Array.isArray(e) && e.length === 0); const n = Array.isArray(e) ? e.includes(8192) : typeof e === "number" && (e & 8192) !== 0; i.push({ ...m, enabled: t, awaitingApproval: n }); continue; } if (p.location !== UNPACKED_MANIFEST_LOCATION || typeof p.path !== "string") continue; const h = path.isAbsolute(p.path) ? p.path : path.join(c, "Extensions", p.path); const g = await fs$1.realpath(h).catch(() => null); if (!g || !n.has(comparablePath(g, t))) continue; const _ = generateChromeExtensionIdForPath(g, t); if (u !== _) { const e = `${s.label} profile ${l.name}: unpacked extension ID ${u} does not match predicted ID ${_} for ${g}`; a.push(e); o.push(e); continue; } r.push({ ...m, extensionPath: g }); } } catch (e) { a.push(`${s.label} profile ${l.name} (${u}): ${e instanceof Error ? e.message : String(e)}`); } } } } const uniqueSorted = (e, t) => { return [...new Map(e.map((e) => [`${e.product}\0${e.profile}\0${e.extensionId}${t(e)}`, e])).values()].toSorted((e, t) => `${e.product}/${e.profile}/${e.extensionId}`.localeCompare(`${t.product}/${t.profile}/${t.extensionId}`)); }; return { discovered: uniqueSorted(r, (e) => `\0${e.extensionPath}`), storeDiscovered: uniqueSorted(i, () => ""), issues: a, identityMismatches: o }; } //#endregion //#region extensions/browser/src/browser/extension-install-external.ts const FOUNDATION_CHROME_WEB_STORE_EXTENSION_ID = "kcdjddhmeafeomebliikmbpblkmkfoig"; const FOUNDATION_CHROME_WEB_STORE_URL = `https://chromewebstore.google.com/detail/openclaw/${FOUNDATION_CHROME_WEB_STORE_EXTENSION_ID}`; const OWNED_REQUEST = { external_update_url: "https://clients2.google.com/service/update2/crx", openclawOwnership: "browser-store-install-v1" }; function requestPath(e) { return path.join(e.userDataDir, "External Extensions", `${FOUNDATION_CHROME_WEB_STORE_EXTENSION_ID}.json`); } async function inspectRequest(e) { const t = requestPath(e); const n = { browser: e.label, path: t }; try { if (!await lstatIfExists(t, "ENOENT")) return { ...n, state: "missing" }; await assertOwnedPath(e.userDataDir, "directory"); await assertOwnedPath(path.dirname(t), "directory"); await assertOwnedPath(t, "file"); if ((await fs$1.stat(t)).size > 4096) throw new Error("Store install registration exceeds 4 KiB"); const r = JSON.parse(await fs$1.readFile(t, "utf8")); if (!hasExactKeys(r, ["external_update_url", "openclawOwnership"]) || r.external_update_url !== OWNED_REQUEST.external_update_url || r.openclawOwnership !== OWNED_REQUEST.openclawOwnership) return { ...n, state: "foreign", issue: "Store install registration is not OpenClaw-owned" }; return { ...n, state: "requested" }; } catch (e) { return { ...n, state: "invalid", issue: e instanceof Error ? e.message : String(e) }; } } function supportedRoots() { return process.platform === "darwin" ? chromeProductRoots().filter((e) => e.product === "chrome") : []; } /** Registration requests installation; only Chrome can install and approve it. */ async function chromeStoreInstallRequests() { return await Promise.all(supportedRoots().map(inspectRequest)); } /** The caller must register the native host successfully before requesting installation. */ async function requestChromeStoreInstall(e) { if (!supportedRoots().some((t) => t.userDataDir === e.userDataDir)) return; const t = await inspectRequest(e); if (t.state === "requested") return t; if (t.state !== "missing") throw new Error(t.issue); await assertOwnedPath(e.userDataDir, "directory"); await ensurePrivateDirectory(path.dirname(t.path)); await fs$1.writeFile(t.path, `${JSON.stringify(OWNED_REQUEST, null, 2)}\n`, { mode: 384, flag: "wx" }); return await inspectRequest(e); } /** Chrome may remove an externally installed extension after this request is removed. */ async function removeChromeStoreInstallRequests() { const e = []; const t = []; for (const n of supportedRoots()) { const r = await inspectRequest(n); if (r.state === "requested") { await fs$1.unlink(r.path); e.push(r.path); } else if (r.state !== "missing") t.push(r.path); } return { removed: e, refused: t }; } //#endregion //#region extensions/browser/src/browser/extension-install-registration.ts const OWNED_LAUNCHER_MARKER = "# OpenClaw native messaging bootstrap v1"; function nativeMessagingRoot() { return path.join(resolveInstallStateDir(), "browser", "native-messaging"); } async function resolveNativeHostPath(e) { const t = path.resolve(e); const n = [path.join(t, "native-host-entry.js")]; let r = t; for (;;) { n.push(path.join(r, "dist", "extensions", "browser", "native-host-entry.js")); const e = path.dirname(r); if (e === r) break; r = e; } for (const e of n) if (await lstatIfExists(e, "ENOENT")) return await fs$1.realpath(e); throw new Error("Could not resolve the built browser native-host entrypoint; run pnpm build."); } function launcherPathForManifest(e) { const t = crypto.createHash("sha256").update(e).digest("hex").slice(0, 16); return path.join(nativeMessagingRoot(), `${BROWSER_NATIVE_HOST_NAME}.${t}.sh`); } function versionedLauncherPath(e, t) { return `${e.slice(0, -3)}.${crypto.createHash("sha256").update(t).digest("hex")}.sh`; } function expectedExtensionIds(e) { return [.../* @__PURE__ */ new Set([...e, FOUNDATION_CHROME_WEB_STORE_EXTENSION_ID])].toSorted(); } function expectedOriginsForExtensionIds(e) { return expectedExtensionIds(e).map((e) => `chrome-extension://${e}/`); } function isSafeOriginMigration(e, t) { const n = e.filter((e) => e !== FOUNDATION_CHROME_WEB_STORE_EXTENSION_ID).toSorted(); const r = [...new Set(t)].toSorted(); if (JSON.stringify(n) === JSON.stringify(r)) return true; const i = n.filter((e) => !r.includes(e)); const a = r.filter((e) => !n.includes(e)); const o = n.some((e) => r.includes(e)); return n.length === r.length && i.length === 1 && a.length === 1 && o; } function parseOwnedLauncher(e) { const t = String.raw`'(?:[^'\r\n]|'"'"')*'`; const n = [ `(${t})`, `(${t})`, escapeRegExp(shellEscape("--manifest")), escapeRegExp(shellEscape(e.manifestPath)), escapeRegExp(shellEscape("--launcher")), escapeRegExp(shellEscape(e.launcherPath)), ...e.origins.flatMap((e) => [escapeRegExp(shellEscape("--expected-origin")), escapeRegExp(shellEscape(e))]) ].join(" "); const r = `(?: ${escapeRegExp(shellEscape("--browser-profile"))} (${t}))?`; const [i, a, o, s, c] = new RegExp(`^#!/bin/sh\\n${escapeRegExp(OWNED_LAUNCHER_MARKER)}\\nexport OPENCLAW_STATE_DIR=(${t})\\n(?:export OPENCLAW_CONFIG_PATH=(${t})\\n)?exec ${n}${r} "\\$@"\\n$`, "u").exec(e.content)?.slice(1) ?? []; if (i === void 0 || o === void 0 || s === void 0) return; const decode = (e) => e.slice(1, -1).replaceAll(`'"'"'`, "'"); const l = c === void 0 ? void 0 : decode(c); if (l !== void 0 && !isValidProfileName(l)) return; return { targets: [decode(o), decode(s)], context: { stateDir: decode(i), configPath: a === void 0 ? void 0 : decode(a) }, ...l === void 0 ? {} : { browserProfile: l } }; } async function assertNativeHostTarget(e, t) { if (!path.isAbsolute(e)) throw new Error("native host target must be an absolute path"); await assertOwnedPath(e, "file", { allowRootOwner: true }); await fs$1.access(e, t); } async function resolveLauncherInstall(e) { const t = launcherPathForManifest(e.manifestPath); const n = await fs$1.realpath(process.execPath); const r = await resolveNativeHostPath(e.pluginRoot); await assertNativeHostTarget(n, fs$1.constants.X_OK); await assertNativeHostTarget(r, fs$1.constants.R_OK); const i = [ n, r, "--manifest", e.manifestPath, "--launcher", t, ...expectedOriginsForExtensionIds(e.extensionIds).flatMap((e) => ["--expected-origin", e]) ]; if (e.browserProfile) i.push("--browser-profile", e.browserProfile); const a = e.launchContext ?? { stateDir: resolveInstallStateDir(), configPath: resolveInstallConfigPath() }; const o = [ "#!/bin/sh", OWNED_LAUNCHER_MARKER, `export OPENCLAW_STATE_DIR=${shellEscape(a.stateDir)}`, ...a.configPath !== void 0 ? [`export OPENCLAW_CONFIG_PATH=${shellEscape(a.configPath)}`] : [], `exec ${i.map(shellEscape).join(" ")} "$@"`, "" ].join("\n"); const s = versionedLauncherPath(t, o); return { path: s, content: o.replace(` '--launcher' ${shellEscape(t)}`, () => ` '--launcher' ${shellEscape(s)}`) }; } async function inspectRegistration(e, t) { const n = path.join(e.nativeManifestDir, `${BROWSER_NATIVE_HOST_NAME}.json`); const r = { product: e.product, browser: e.label, manifestPath: n }; if (!await lstatIfExists(n, "ENOENT")) return { ...r, extensionIds: [], state: "missing" }; try { const e = await readPrivateNativeHostFile(n, false); const i = asNullableRecord(JSON.parse(e.buffer.toString("utf8"))); if (!i) throw new Error("manifest is not an object"); const a = launcherPathForManifest(n); const o = typeof i.path === "string" ? i.path : ""; const s = new RegExp(`^${escapeRegExp(a.slice(0, -3))}\\.[a-f0-9]{64}\\.sh$`, "u"); const c = Array.isArray(i.allowed_origins) ? i.allowed_origins : []; const l = c.flatMap((e) => { const t = /^chrome-extension:\/\/([a-p]{32})\/$/.exec(String(e)); return t?.[1] ? [t[1]] : []; }); if (i.name !== "ai.openclaw.browser_bootstrap" || o !== a && !s.test(o)) return { ...r, extensionIds: l, state: "foreign", issue: "same host name is registered to a foreign manifest or launcher" }; const u = c.filter((e) => typeof e === "string"); const d = c.length > 0 && c.length === u.length && u.every((e) => /^chrome-extension:\/\/[a-p]{32}\/$/u.test(e)) && new Set(c).size === c.length; const f = [...u].toSorted(); const p = t ? expectedOriginsForExtensionIds(t) : null; if (!hasExactKeys(i, NATIVE_HOST_MANIFEST_KEYS) || i.description !== "OpenClaw browser extension bootstrap" || i.type !== "stdio" || !d || JSON.stringify(c) !== JSON.stringify(f)) throw new Error("native host manifest does not contain exact allowed origins"); const m = (await readPrivateNativeHostFile(o, true)).buffer.toString("utf8"); const h = m.replace(` '--launcher' ${shellEscape(o)}`, () => ` '--launcher' ${shellEscape(a)}`); if (o !== a && versionedLauncherPath(a, h) !== o) throw new Error("native host launcher content does not match its immutable identity"); const g = parseOwnedLauncher({ content: m, manifestPath: n, launcherPath: o, origins: u }); if (!g) throw new Error("native host launcher and manifest origins do not match"); let _; if (t !== void 0 && JSON.stringify(c) !== JSON.stringify(p)) { if (!isSafeOriginMigration(l, t)) throw new Error("native host manifest does not contain exact allowed origins"); _ = "registered native host origins require a supported path migration; run openclaw browser extension install"; } try { for (const [e, t] of g.targets.entries()) await assertNativeHostTarget(t, e === 0 ? fs$1.constants.X_OK : fs$1.constants.R_OK); } catch { _ ??= "registered native host runtime or entry is unavailable or unsafe; run openclaw browser extension install"; } return { ...r, extensionIds: l.toSorted(), state: "owned", nativeHostPath: g.targets[1], launcherPath: o, launchContext: g.context, issue: _, ...g.browserProfile === void 0 ? {} : { browserProfile: g.browserProfile } }; } catch (e) { return { ...r, extensionIds: [], state: "invalid", issue: e instanceof Error ? e.message : String(e) }; } } async function installRegistration(e) { const { root: t, extensionIds: n } = e; const r = path.join(t.nativeManifestDir, `${BROWSER_NATIVE_HOST_NAME}.json`); const i = await inspectRegistration(t); assertExpectedNativeHostProfile(i, e.expectedRegistrations); if (i.state === "foreign" || i.state === "invalid") throw new Error(`Refusing to overwrite ${i.state} native host: ${r}`); if (e.requireCurrentLaunchContext) assertCurrentNativeHostLaunchContext(i); if (e.expectedNativeHostPath !== void 0 && i.nativeHostPath !== e.expectedNativeHostPath) throw new Error("Native host target changed before repair; inspect it again."); const a = expectedOriginsForExtensionIds(n); if (i.state === "owned" && JSON.stringify(i.extensionIds.map((e) => `chrome-extension://${e}/`)) !== JSON.stringify(a) && !isSafeOriginMigration(i.extensionIds, n)) throw new Error(`Refusing to overwrite owned native host with unexpected allowed origins`); e.signal?.throwIfAborted(); await ensurePrivateDirectory(nativeMessagingRoot()); e.signal?.throwIfAborted(); await ensurePrivateDirectory(t.nativeManifestDir); const o = await resolveLauncherInstall({ manifestPath: r, pluginRoot: e.pluginRoot, extensionIds: n, launchContext: e.requireCurrentLaunchContext || e.expectedNativeHostPath !== void 0 ? i.launchContext : void 0, browserProfile: e.browserProfile ?? i.browserProfile }); const s = o.path; const c = i.state === "owned" ? await fs$1.readFile(r, "utf8") : void 0; const l = i.launcherPath ? { path: i.launcherPath, content: await fs$1.readFile(i.launcherPath, "utf8") } : null; let u = false; if (await lstatIfExists(s, "ENOENT")) { await assertOwnedPath(s, "file"); if (await fs$1.readFile(s, "utf8") !== o.content) throw new Error(`Refusing to overwrite changed immutable native host launcher: ${s}`); } else { e.signal?.throwIfAborted(); await replaceFileAtomic({ filePath: s, content: o.content, mode: 448 }); u = true; } const d = `${JSON.stringify({ name: BROWSER_NATIVE_HOST_NAME, description: BROWSER_NATIVE_HOST_DESCRIPTION, path: s, type: "stdio", allowed_origins: a }, null, 2)}\n`; try { e.signal?.throwIfAborted(); if (process.platform !== "win32") await fs$1.chmod(s, 448); e.signal?.throwIfAborted(); await replaceFileAtomic({ filePath: r, content: d, mode: 384, beforeRename: e.requireCurrentLaunchContext || e.expectedRegistrations ? async () => { e.signal?.throwIfAborted(); const n = await inspectRegistration(t); if (e.requireCurrentLaunchContext) assertCurrentNativeHostLaunchContext(n); assertExpectedNativeHostProfile(n, e.expectedRegistrations); const a = n.state === "missing" ? void 0 : await fs$1.readFile(r, "utf8"); if (n.state !== i.state || a !== c) throw new NativeHostSetupContextError("Chrome's native host selection changed during setup. Inspect the registered OPENCLAW_CONFIG_PATH before trying again."); e.signal?.throwIfAborted(); } : void 0 }); } catch (e) { const t = await fs$1.readFile(r, "utf8").catch((e) => asNullableRecord(e)?.code === "ENOENT" ? void 0 : null); if (u && t === c) { await readPrivateNativeHostFile(s, true); await fs$1.unlink(s); } throw e; } if (l && l.path !== s && await fs$1.readFile(r, "utf8") === d && await fs$1.readFile(l.path, "utf8") === l.content) { await readPrivateNativeHostFile(l.path, true); await fs$1.unlink(l.path); } return await inspectRegistration(t, n); } /** Inspect or refresh existing registrations without reading personal browser profiles. */ async function repairChromeExtensionNativeHosts(e) { if (!e.dryRun && (!e.fromNativeHostPath || !path.isAbsolute(e.fromNativeHostPath))) throw new Error("Native host repair requires --from with the exact absolute registered entrypoint; use --dry-run to inspect targets."); const t = e.fromNativeHostPath; const n = []; const r = []; const i = []; const a = /* @__PURE__ */ new Set(); const o = process.platform === "win32"; let s = !o; for (const c of o ? [] : chromeProductRoots()) { let o = await inspectRegistration(c); if (!e.dryRun && t && o.state === "owned" && o.nativeHostPath === t) try { const r = stableChromeExtensionDir(); if (!(await inspectInstalledCopy(r)).owned) throw new Error("stable extension copy is not OpenClaw-owned; run browser extension install explicitly"); const i = (await approvedInstallRealpaths(r, e.bundledDir)).map((e) => generateChromeExtensionIdForPath(e)); const a = await resolveLauncherInstall({ manifestPath: o.manifestPath, pluginRoot: e.pluginRoot, extensionIds: i, launchContext: o.launchContext, browserProfile: o.browserProfile }); if (JSON.stringify(o.extensionIds) !== JSON.stringify(expectedExtensionIds(i)) || o.launcherPath !== a.path) { o = await installRegistration({ root: c, extensionIds: i, pluginRoot: e.pluginRoot, expectedNativeHostPath: t }); n.push(`Repaired ${c.label} OpenClaw native messaging registration.`); } } catch (e) { r.push(`${c.label} native host repair failed: ${String(e)}`); a.add(t); o = await inspectRegistration(c); } i.push(o); if (o.state === "owned" && o.nativeHostPath && path.isAbsolute(o.nativeHostPath)) a.add(o.nativeHostPath); else if (o.state !== "missing") { s = false; r.push(`${c.label} native host target cannot be established: ${o.issue ?? o.state}`); } } return { changes: n, warnings: r, registrations: i.map(({ launchContext: e, ...t }) => t), retainedNativeHostPaths: [...a].toSorted(), retentionSafe: s, manualRequired: o }; } /** Remove only registrations and launchers that carry OpenClaw ownership. */ async function uninstallChromeExtensionNativeHosts(e = {}) { if (process.platform === "win32") return (await import("./extension-windows-host-BQ-X73Wt.mjs")).uninstallWindowsNativeHosts({ ...e, executable: e.nativeHostExecutable }); if (e.removeStore) throw new Error("Use uninstall-store for macOS Store requests."); const t = []; const n = []; for (const e of chromeProductRoots()) { const r = await inspectRegistration(e); if (r.state === "missing") continue; const i = r.launcherPath; if (r.state !== "owned" || !i) { n.push(r.manifestPath); continue; } const a = await lstatIfExists(i, "ENOENT"); if (a) { await assertOwnedPath(i, "file"); if (!(await fs$1.readFile(i, "utf8")).includes(OWNED_LAUNCHER_MARKER)) { n.push(i); continue; } } await fs$1.unlink(r.manifestPath); t.push(r.manifestPath); if (a) { await fs$1.unlink(i); t.push(i); } } return { removed: t, refused: n, manualRequired: false }; } //#endregion //#region extensions/browser/src/browser/extension-install.ts const BROWSER_EXTENSION_INSTALL_WAIT_DEFAULT_MS = 3e4; const BROWSER_EXTENSION_INSTALL_WAIT_MIN_MS = 1e3; const BROWSER_EXTENSION_INSTALL_WAIT_MAX_MS = 12e4; function normalizeExtensionInstallWaitMs(e) { if (e === void 0) return BROWSER_EXTENSION_INSTALL_WAIT_DEFAULT_MS; const t = typeof e === "number" || typeof e === "string" && /^\d+$/u.test(e) ? Number(e) : NaN; if (!Number.isInteger(t) || t < BROWSER_EXTENSION_INSTALL_WAIT_MIN_MS || t > BROWSER_EXTENSION_INSTALL_WAIT_MAX_MS) throw new Error(`--wait-ms must be an integer from ${BROWSER_EXTENSION_INSTALL_WAIT_MIN_MS} to ${BROWSER_EXTENSION_INSTALL_WAIT_MAX_MS}`); return t; } /** Copy, pre-register Store plus deterministic IDs, then verify Chrome's recorded identity. */ async function installChromeExtensionBootstrap(e) { const t = process.platform; if (e.browserProfile !== void 0 && !isValidProfileName(e.browserProfile)) throw new Error("Invalid native browser profile"); e.signal?.throwIfAborted(); if ((e.requireCurrentLaunchContext || e.expectedRegistrations) && t !== "win32") { for (const t of chromeProductRoots()) { const n = await inspectRegistration(t); if (e.requireCurrentLaunchContext) assertCurrentNativeHostLaunchContext(n); assertExpectedNativeHostProfile(n, e.expectedRegistrations); } e.signal?.throwIfAborted(); } const n = await installStableChromeExtension(e.bundledDir); const r = await approvedInstallRealpaths(n, e.bundledDir); const i = [...new Set(r.map((e) => generateChromeExtensionIdForPath(e, t)))].toSorted(); if (t === "win32") { const { installWindowsNativeHost: t } = await import("./extension-windows-host-BQ-X73Wt.mjs"); const n = await t({ ...e, executable: e.nativeHostExecutable, extensionIds: i }); return await browserExtensionStatus({ ...e, windowsObservation: n }); } const a = []; let o = 0; for (const n of chromeProductRoots()) { e.signal?.throwIfAborted(); try { if (!await lstatIfExists(n.userDataDir, "ENOENT")) { if (t !== "darwin" || n.product !== "chrome") continue; await ensurePrivateDirectory(n.userDataDir); } await assertOwnedPath(n.userDataDir, "directory"); e.signal?.throwIfAborted(); await installRegistration({ root: n, extensionIds: i, pluginRoot: e.pluginRoot, browserProfile: e.browserProfile, signal: e.signal, requireCurrentLaunchContext: e.requireCurrentLaunchContext, expectedRegistrations: e.expectedRegistrations }); o += 1; e.onProgress?.(`Pre-registered the native host for ${n.label}.`); } catch (t) { e.signal?.throwIfAborted(); if (t instanceof NativeHostSetupContextError) throw t; a.push(`${n.label}: native host pre-registration refused (${t instanceof Error ? t.message : String(t)})`); continue; } try { e.signal?.throwIfAborted(); if (e.requestStoreInstall === false ? void 0 : await requestChromeStoreInstall(n)) e.onProgress?.(`Requested the OpenClaw Store extension for ${n.label}. Restart Chrome if needed, then approve OpenClaw in chrome://extensions.`); } catch (t) { e.signal?.throwIfAborted(); a.push(`${n.label}: Store installation request refused (${t instanceof Error ? t.message : String(t)}). Add OpenClaw directly: ${FOUNDATION_CHROME_WEB_STORE_URL}`); } } if (o > 0) e.onProgress?.(`Native bootstrap is ready. Add OpenClaw from the Chrome Web Store: ${FOUNDATION_CHROME_WEB_STORE_URL}. For development, load unpacked from ${n}.`); else a.push("No native host was pre-registered. Resolve any pre-registration refusals above; if Chrome has not been launched yet, launch it first. Then run install again before loading the extension."); const s = normalizeExtensionInstallWaitMs(e.waitMs); const c = performance.now() + s; let l = await discoverChromeExtensionIds({ approvedDirs: r, storeExtensionId: FOUNDATION_CHROME_WEB_STORE_EXTENSION_ID }); let u = false; while (l.discovered.length === 0 && l.storeDiscovered.length === 0 && performance.now() < c) { if (!u) { e.onProgress?.("Waiting for Chrome to verify the OpenClaw extension…"); u = true; } e.signal?.throwIfAborted(); await setTimeout(Math.min(500, Math.max(1, c - performance.now()))); e.signal?.throwIfAborted(); l = await discoverChromeExtensionIds({ approvedDirs: r, storeExtensionId: FOUNDATION_CHROME_WEB_STORE_EXTENSION_ID }); } const d = await browserExtensionStatus({ bundledDir: e.bundledDir, requireCurrentLaunchContext: e.requireCurrentLaunchContext }); return { ...d, issues: [.../* @__PURE__ */ new Set([...a, ...d.issues])] }; } /** Read-only extension copy, profile discovery, and native registration report. */ async function browserExtensionStatus(e) { const t = process.platform; const n = stableChromeExtensionDir(); const r = await inspectInstalledCopy(n); const i = await fs$1.realpath(e.bundledDir); await assertOwnedPath(i, "directory", { allowRootOwner: true }); const a = r.owned ? await approvedInstallRealpaths(n, i) : [i]; const o = await discoverChromeExtensionIds({ approvedDirs: a, storeExtensionId: FOUNDATION_CHROME_WEB_STORE_EXTENSION_ID }); const s = [...new Set(a.map((e) => generateChromeExtensionIdForPath(e, t)))].toSorted(); const c = t === "win32" ? e.windowsObservation ?? await (await import("./extension-windows-host-BQ-X73Wt.mjs")).inspectWindowsNativeHosts({ pluginRoot: e.pluginRoot, executable: e.nativeHostExecutable, extensionIds: s, browserProfile: e.browserProfile, signal: e.signal }) : void 0; const l = t === "win32" ? c?.registrations ?? [] : await Promise.all(chromeProductRoots().map((e) => inspectRegistration(e, s))).then((t) => t.map((t) => { if (e.requireCurrentLaunchContext) assertCurrentNativeHostLaunchContext(t); const { nativeHostPath: n, launcherPath: r, launchContext: i, ...a } = t; return a; })); const u = l.some((e) => { return (o.discovered.some((t) => t.product === e.product) || o.storeDiscovered.some((t) => t.product === e.product)) && (e.state !== "owned" || Boolean(e.issue)); }); const d = c?.storeInstallRequests ?? await chromeStoreInstallRequests(); return { platform: t, platformSupport: t === "win32" && !l.length ? "manual_required" : "automatic", installedCopy: { path: n, ...r }, bundledPath: path.resolve(e.bundledDir), approvedPaths: a, discovered: o.discovered, storeDiscovered: o.storeDiscovered, storeInstallRequests: d, registrations: l, manualSetupRequired: t === "win32" && !l.length || r.present && !r.owned || o.discovered.length === 0 && !o.storeDiscovered.some((e) => e.enabled) || o.identityMismatches.length > 0 || u, issues: [ ...r.present && !r.owned ? [`Chrome extension copy is not OpenClaw-owned: ${n}`] : [], ...o.issues, ...c?.issues ?? [], ...[...d, ...l].flatMap((e) => e.issue ? [`${e.browser}: ${e.issue}`] : []) ] }; } /** Resolve the installed stable copy when present, bundled source otherwise. */ async function resolveChromeExtensionLoadPath(e) { const t = stableChromeExtensionDir(); const n = await inspectInstalledCopy(t); if (n.present) { if (!n.owned) throw new Error(`Refusing foreign Chrome extension directory: ${t}`); return await fs$1.realpath(t); } const r = await fs$1.realpath(path.resolve(e)); await assertOwnedPath(r, "directory", { allowRootOwner: true }); return r; } //#endregion //#region extensions/browser/src/browser/extension-setup.ts /** Filesystem setup has one owner; callers retain their documented output projections. */ async function observeBrowserExtensionSetup(e) { e.signal?.throwIfAborted(); return e.action === "install" ? installChromeExtensionBootstrap({ ...e, browserProfile: e.profile }) : browserExtensionStatus({ ...e, browserProfile: e.profile }); } async function resolveWindowsSetupSelection(e, t, n) { const { windowsManagementObservation: r } = await import("./extension-windows-host-BQ-X73Wt.mjs"); const blocked = () => /* @__PURE__ */ new Error("Windows saved profile is unverified. Repair the intended existing profile with an explicit --browser-profile; no automatic change was made."); const inspect = async (t) => { e.signal?.throwIfAborted(); const n = await observeBrowserExtensionSetup({ ...e, action: "inspect", profile: t }); e.signal?.throwIfAborted(); return n; }; function classify(e) { if (e.platform !== "win32") return "blocked"; const t = r(e.registrations); const n = t?.response; if (!n || n.store !== "missing" && n.store !== "requested") return "blocked"; if (n.ok && n.registration === "owned" && n.mode === "native-windows-cli" && n.installation && t.browserProfile) return "matching"; if (n.ok && n.registration === "missing" && n.mode === null && !n.installation && n.store === "missing") return "missing"; if (!n.ok && n.code === "context_conflict" && n.registration === "owned" && n.mode === "native-windows-cli" && !n.installation) return "conflict"; return "blocked"; } let i = t; let a = classify(i); if (a === "conflict") for (const t of Object.keys(n.profiles)) { e.signal?.throwIfAborted(); if (t === "chrome" || !isValidProfileName(t) || resolveProfile(n, t)?.driver !== "extension") continue; i = await inspect(t); a = classify(i); if (a === "matching") break; if (a !== "conflict") throw blocked(); } if (a !== "matching" && a !== "missing") throw blocked(); const o = r(i.registrations); const s = a === "missing" ? "chrome" : o?.browserProfile; if (!s || !isValidProfileName(s) || resolveProfile(n, s)?.driver !== "extension") throw blocked(); const c = await inspect(s); const l = r(c.registrations); if (classify(c) !== a || a === "matching" && (l?.browserProfile !== s || l.response?.installation?.generation !== o?.response?.installation?.generation)) throw blocked(); return { observed: c, profile: s }; } /** Native bootstrap, not the UI, transfers the host-local key to the origin-locked extension. */ async function runBrowserExtensionSetup(e) { let t = { ...e, requireCurrentLaunchContext: true }; t.signal?.throwIfAborted(); const n = AbortSignal.timeout(6e4); const r = t.signal ? AbortSignal.any([t.signal, n]) : n; if (process.platform === "win32") t = { ...t, signal: r }; const i = resolveBrowserConfig(t.cfg.browser, t.cfg); let a = t.profile === void 0 || t.action !== "install" ? await observeBrowserExtensionSetup({ ...t, action: "inspect" }) : void 0; let o; if (a?.platform === "win32" && t.profile === void 0) { t = { ...t, signal: r }; t.signal?.throwIfAborted(); const e = await resolveWindowsSetupSelection(t, a, i); a = e.observed; o = e.profile; } if (a && a.platform !== "win32" && a.registrations.some((e) => e.state !== "owned" && e.state !== "missing")) throw new Error("Chrome setup cannot recover the saved profile from an unverified native host"); const s = resolveFirstExtensionProfileName(i); const c = new Set(a?.registrations.filter((e) => e.state === "owned").map((e) => e.browserProfile ?? s)); if (t.action !== "install" && a?.platform !== "win32" && t.profile !== void 0 && [...c].some((e) => e !== t.profile)) throw new Error("Chrome setup profile does not match the registered native host; use an explicit install to change it"); if (c.size > 1) throw new Error("Chrome setup requires an explicit profile when owned registrations disagree"); const l = t.profile ?? o ?? c.values().next().value ?? "chrome"; const u = resolveProfile(i, l); if (!u || u.driver !== "extension") throw new Error("Chrome setup requires an existing extension browser profile"); const d = t.action !== "install" && a ? a : await observeBrowserExtensionSetup({ ...t, profile: l, expectedRegistrations: t.profile === void 0 && a?.platform !== "win32" ? a?.registrations : void 0 }); t.signal?.throwIfAborted(); const f = d.registrations.filter((e) => e.product === "chrome"); const p = d.discovered.filter((e) => e.product === "chrome"); const m = d.storeDiscovered.filter((e) => e.product === "chrome"); const h = f.some((e) => e.state === "owned" && !e.issue); const g = f.some((e) => e.state === "foreign" || e.state === "invalid" || Boolean(e.issue)); const _ = { nativeHostRegistered: h, installRequested: d.storeInstallRequests.some((e) => e.state === "requested"), installedProfiles: p.length + m.length, discoveredProfiles: p.length + m.filter((e) => e.enabled).length, awaitingApproval: m.some((e) => e.awaitingApproval), automaticBootstrapSupported: d.platformSupport === "automatic" }; const v = { action: t.action, target: { kind: "local-host", platform: d.platform, hostname: os.hostname(), profile: l, relayPort: u.cdpPort }, phase: "waiting_for_connection", reason: "connection_unchecked", installation: _, connection: { state: "not_checked" }, nextAction: "check_connection" }; if (!_.automaticBootstrapSupported) Object.assign(v, { phase: "blocked", reason: "platform_unsupported", nextAction: "unsupported" }); else if (!h) Object.assign(v, { phase: g ? "blocked" : "inspection_required", reason: g ? "native_host_unavailable" : "native_host_missing", nextAction: g ? "repair_native_host" : "install" }); else if (!_.discoveredProfiles) Object.assign(v, { phase: "needs_browser_action", reason: _.awaitingApproval ? "chrome_approval_required" : "extension_missing", nextAction: _.awaitingApproval ? "approve_extension" : _.installRequested ? "open_chrome" : "install_from_store" }); return t.action === "verify" && (d.platform !== "win32" || v.phase !== "blocked") ? verifyBrowserExtensionSetup(v, t.signal) : v; } async function verifyBrowserExtensionSetup(e, t) { try { const { readExtensionRelayToken: n } = await import("./relay-auth-CPMTuBxl.mjs"); const r = n(); if (!r) e.connection = { state: "unavailable" }; else { const { RelayOwnerClient: n } = await import("./owner-client-B3CWBPhr.mjs"); const i = await n.connect({ port: e.target.relayPort, profile: e.target.profile, token: r, signal: t ? AbortSignal.any([t, AbortSignal.timeout(5e3)]) : AbortSignal.timeout(5e3) }); try { const t = await i.status(); e.connection = t.ready && t.identity ? { state: "connected", extensionVersion: t.identity.extensionVersion } : { state: "waiting_for_extension" }; } finally { await i.close(); } } } catch { t?.throwIfAborted(); e.connection = { state: "unavailable" }; } if (e.connection.state === "connected") Object.assign(e, { phase: "ready", reason: "connected", nextAction: "none" }); else if (e.phase === "waiting_for_connection") e.reason = e.connection.state === "waiting_for_extension" ? "extension_disconnected" : "relay_unavailable"; return e; } //#endregion export { repairChromeExtensionNativeHosts as a, FOUNDATION_CHROME_WEB_STORE_URL as c, resolveChromeExtensionLoadPath as i, removeChromeStoreInstallRequests as l, runBrowserExtensionSetup as n, resolveNativeHostPath as o, normalizeExtensionInstallWaitMs as r, uninstallChromeExtensionNativeHosts as s, observeBrowserExtensionSetup as t, NativeHostSetupContextError as u };