UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

545 lines (544 loc) • 22.8 kB
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { m as resolveConfigPath } from "./paths-DAcAg5aV.mjs"; import { v as readSecureFile } from "./fs-safe-BbWvmdVn.mjs"; import { Et as _enum, Jn as string, Lt as boolean, Nt as array, qn as strictObject, xn as literal } from "./schemas-Cy6abvsu.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import { t as runCommandBuffered } from "./exec-aRIvS9s4.mjs"; import { a as inspectPathPermissions, t as assertNoSymlinkParents } from "./file-access-runtime-BD2Fjfbw.mjs"; import "./state-paths-qdCZ9HDY.mjs"; import { n as parseStrictJsonObject } from "./strict-json-Uas9w6qB.mjs"; import { n as BROWSER_NATIVE_HOST_NAME, t as BROWSER_NATIVE_HOST_DESCRIPTION } from "./extension-native-host.constants-Vrf4p7mK.mjs"; import "./process-runtime-DcBPEA8Y.mjs"; import { r as isValidProfileName } from "./profiles-DzbsR8ma.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import { promisify } from "node:util"; import { execFile } from "node:child_process"; //#region extensions/browser/src/browser/extension-windows-contract.ts const WINDOWS_MANAGEMENT_LIMIT = 32768; const WINDOWS_NATIVE_EXE = "OpenClaw.BrowserBootstrap.exe"; const WINDOWS_BINDING = "OpenClaw.BrowserBootstrap.binding.json"; const WINDOWS_RECEIPT = "OpenClaw.BrowserBootstrap.owned.json"; const WINDOWS_MANIFEST = BROWSER_NATIVE_HOST_NAME + ".json"; const WINDOWS_OFFICIAL_ORIGIN = "chrome-extension://kcdjddhmeafeomebliikmbpblkmkfoig/"; const windowsPathKey = (e) => e.replace(/[A-Z]/g, (e) => e.toLowerCase()); const sameWindowsPath = (e, t) => windowsPathKey(e) === windowsPathKey(t); const wellFormed = (e) => !/[\uD800-\uDFFF]/u.test(e); function isWindowsNativePath(e) { if (!e || e.length > 4096 || !wellFormed(e) || !/^[a-z]:\\/i.test(e) || e !== path.win32.normalize(e) || e.includes("/") || e.slice(2).includes(":")) return false; if (e.length > 3 && e.endsWith("\\")) return false; return e.slice(3).split("\\").filter(Boolean).every((e) => Array.from(e).every((e) => e.charCodeAt(0) >= 32) && !/[<>:"|?*]/u.test(e) && e.trim() === e && !e.endsWith(".") && !/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]|conin\$|conout\$)(?:\.|$)/i.test(e)); } const windowsPathSchema = string().refine(isWindowsNativePath); const generationSchema = string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/).refine((e) => e !== "00000000-0000-0000-0000-000000000000"); const sidSchema = string().max(184).refine((e) => { if (!/^S-1-(?:0|[1-9][0-9]*)(?:-(?:0|[1-9][0-9]*)){1,15}$/.test(e)) return false; const t = e.split("-").slice(2).map(BigInt); return t[0] <= 281474976710655n && t.slice(1).every((e) => e <= 4294967295n) && ![ "S-1-5-18", "S-1-5-19", "S-1-5-20" ].includes(e); }); const originsSchema = array(string().regex(/^chrome-extension:\/\/[a-p]{32}\/$/)).min(1).max(32).refine((e) => e.includes("chrome-extension://kcdjddhmeafeomebliikmbpblkmkfoig/") && e.every((t, n) => n === 0 || e[n - 1] < t)); const nativeWindowsContextSchema = strictObject({ nodePath: windowsPathSchema.refine((e) => windowsPathKey(path.win32.basename(e)) === "node.exe"), cliPath: windowsPathSchema.refine((e) => windowsPathKey(path.win32.basename(e)) === "openclaw.mjs"), stateDir: windowsPathSchema, configPath: windowsPathSchema, browserProfile: string().refine(isValidProfileName) }); const modeSchema = _enum(["companion-managed-wsl", "native-windows-cli"]); const actionSchema = _enum([ "inspect", "install", "uninstall" ]); const storeActionSchema = _enum([ "preserve", "request", "remove" ]); const modeContext = (e) => e.mode === "native-windows-cli" ? e.context !== null : e.context === null && e.expectedOrigins.length === 1 && e.expectedOrigins[0] === "chrome-extension://kcdjddhmeafeomebliikmbpblkmkfoig/"; const managementRequestSchema = strictObject({ v: literal(1), action: actionSchema, mode: modeSchema, context: nativeWindowsContextSchema.nullable(), expectedOrigins: originsSchema, store: storeActionSchema }).refine(modeContext).refine((e) => e.action === "inspect" ? e.store === "preserve" : e.action === "install" ? e.store !== "remove" : e.store !== "request"); const installationSchema = strictObject({ generation: generationSchema, manifestPath: windowsPathSchema, launcherPath: windowsPathSchema, bindingPath: windowsPathSchema, receiptPath: windowsPathSchema }).refine((e) => { const t = path.win32.dirname(e.manifestPath); return path.win32.basename(t) === e.generation && e.manifestPath === path.win32.join(t, WINDOWS_MANIFEST) && e.launcherPath === path.win32.join(t, "OpenClaw.BrowserBootstrap.exe") && e.bindingPath === path.win32.join(t, "OpenClaw.BrowserBootstrap.binding.json") && e.receiptPath === path.win32.join(t, "OpenClaw.BrowserBootstrap.owned.json"); }); const managementResponseSchema = strictObject({ v: literal(1), ok: boolean(), code: _enum([ "ok", "invalid_request", "context_conflict", "foreign_registration", "unsafe_path", "unsafe_acl", "binding_invalid", "browser_control_disabled", "transport_failed", "busy", "cancelled", "io_error", "platform_unsupported" ]), registration: _enum([ "missing", "owned", "foreign", "invalid" ]).nullable(), mode: modeSchema.nullable(), store: _enum([ "missing", "requested", "foreign", "invalid" ]).nullable(), installation: installationSchema.nullable() }).refine((e) => e.ok === (e.code === "ok")).refine((e) => e.registration === "owned" ? e.mode !== null : e.mode === null && e.installation === null).refine((e) => ![ "invalid_request", "platform_unsupported", "busy" ].includes(e.code) || [ e.registration, e.mode, e.store, e.installation ].every((e) => e === null)); const bindingSchema = strictObject({ version: literal(1), mode: modeSchema, manifestPath: windowsPathSchema, expectedOrigins: originsSchema, nativeWindows: nativeWindowsContextSchema.nullable() }).refine((e) => modeContext({ ...e, context: e.nativeWindows })); const receiptSchema = strictObject({ owner: literal("openclaw-browser-native-host"), version: literal(1), generation: generationSchema, ownerSid: sidSchema, transportVerified: literal(true), executableSha256: string().regex(/^[a-f0-9]{64}$/), bindingSha256: string().regex(/^[a-f0-9]{64}$/), manifestSha256: string().regex(/^[a-f0-9]{64}$/) }); const windowsManifestSchema = strictObject({ name: literal(BROWSER_NATIVE_HOST_NAME), description: literal(BROWSER_NATIVE_HOST_DESCRIPTION), path: windowsPathSchema, type: literal("stdio"), allowed_origins: originsSchema }); /** Reuse the browser's duplicate-key owner; version tokens and UTF-8 are ABI-specific. */ function parseWindowsJson(e, t = false) { if (!e.length || e.length > 32768 || e.subarray(0, 3).equals(Buffer.from([ 239, 187, 191 ]))) throw new Error("Invalid Windows management JSON"); const n = new TextDecoder("utf-8", { fatal: true }).decode(e); const r = /"(?:\\.|[^"\\])*"/g; let i = false; const a = n.replace(r, (e) => { const t = JSON.parse(e); if (typeof t !== "string" || !wellFormed(t)) i = true; return "\"\""; }); if (i || t && /\s/u.test(a) || [...a.matchAll(/-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/g)].some((e) => e[0] !== "1")) throw new Error("Invalid Windows management JSON"); const o = parseStrictJsonObject(n); if (!o) throw new Error("Invalid Windows management JSON"); return o; } function parseWindowsManagementResponse(e, t, n) { if (e.length > 32768 || e.at(-1) !== 10) throw new Error("Invalid management frame"); const r = managementResponseSchema.parse(parseWindowsJson(e.subarray(0, -1), true)); if (t !== (r.ok ? 0 : 1) || r.installation && r.mode !== n.mode || r.code === "context_conflict" && r.installation) throw new Error("Invalid management receipt"); if (r.ok) { const e = r.registration === "owned" && r.mode === n.mode && r.installation !== null; if (n.action === "install" && (!e || n.store === "request" && r.store !== "requested")) throw new Error("Incomplete install"); if (n.action === "uninstall" && (r.registration !== "missing" || n.store === "remove" && r.store !== "missing")) throw new Error("Incomplete uninstall"); if (n.action === "inspect" && (!e && r.registration !== "missing" || !["missing", "requested"].includes(r.store ?? ""))) throw new Error("Incomplete inspection"); } return r; } //#endregion //#region extensions/browser/src/browser/extension-windows-management.ts /** No unverified transport output is ever projected as registration state. */ var WindowsManagementTransportError = class extends Error { constructor(e) { super(e ? "Windows setup outcome is unknown. Inspect the same local context before retrying; no fallback was attempted." : "Windows bootstrap management is unavailable. Install a compatible helper; no fallback was attempted."); } }; async function runWindowsManagement(e, t, n = {}) { const r = JSON.stringify(t); if (Buffer.byteLength(r) > 32768) throw new WindowsManagementTransportError(false); n.signal?.throwIfAborted(); const i = Object.fromEntries(Object.entries(process.env).filter(([e]) => !/^(NODE_|OPENCLAW_)/i.test(e))); const a = await runCommandBuffered([e, "--manage"], { baseEnv: i, input: r, timeoutMs: 6e4, signal: n.signal, maxOutputBytes: { stdout: WINDOWS_MANAGEMENT_LIMIT, stderr: 1 }, maxCombinedOutputBytes: WINDOWS_MANAGEMENT_LIMIT, killProcessTree: true, terminateOnOutputError: true }).catch(() => { throw new WindowsManagementTransportError(true); }); if (a.termination !== "exit" || a.signal || a.stderr.length || n.signal?.aborted) throw new WindowsManagementTransportError(true); try { return parseWindowsManagementResponse(a.stdout, a.code, t); } catch { throw new WindowsManagementTransportError(true); } } //#endregion //#region extensions/browser/src/browser/extension-windows-platform.ts const IDENTITY_SCRIPT = String.raw`$ErrorActionPreference = "Stop" [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) [Console]::Out.Write((ConvertTo-Json -Compress -InputObject ([ordered]@{ localAppData = [Environment]::GetFolderPath([Environment+SpecialFolder]::LocalApplicationData) sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value })))`; const identitySchema = strictObject({ localAppData: windowsPathSchema, sid: sidSchema }); const inspect$1 = async (e) => { const t = path.win32.join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"); if (process.platform !== "win32" || !isWindowsNativePath(t)) throw new Error("Windows OS inspection unavailable"); await assertNoSymlinkParents({ rootDir: path.win32.parse(t).root, targetPath: t }); if (!(await fs.lstat(t)).isFile()) throw new Error("Windows OS inspection unavailable"); const { stdout: n } = await promisify(execFile)(t, [ "-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(e, "utf16le").toString("base64") ], { env: process.env, windowsHide: true, timeout: 5e3, maxBuffer: 32768 }); return n; }; const assertParents = async (e) => { const t = Buffer.from(path.win32.dirname(e)).toString("base64"); await inspect$1(String.raw`$ErrorActionPreference='Stop' $p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('` + t + String.raw`')) $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User.Value $trusted=@($sid,'S-1-5-18','S-1-5-32-544','S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464') while($p){ $acl=[IO.Directory]::GetAccessControl($p) if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin $trusted){throw 'Unsafe ancestor'} $raw=[Security.AccessControl.RawSecurityDescriptor]::new($acl.GetSecurityDescriptorBinaryForm(),0) if($null -eq $raw.DiscretionaryAcl){throw 'Unverified ancestor'} foreach($ace in $raw.DiscretionaryAcl){ if($ace -isnot [Security.AccessControl.CommonAce] -or $ace.IsCallback -or [int]$ace.AceType -notin @(0,1)){throw 'Unverified ancestor'} if([int]$ace.AceType -eq 0 -and ([int]$ace.AceFlags -band 8) -eq 0 -and $ace.SecurityIdentifier.Value -notin $trusted -and (([long]$ace.AccessMask -band 0x500d0150) -ne 0)){throw 'Unsafe ancestor writer'} } $parent=[IO.Directory]::GetParent($p) $p=if($null -eq $parent){$null}else{$parent.FullName} } `); }; const assertPath = async (e, t) => { if (process.platform !== "win32" || !isWindowsNativePath(e)) throw new Error("Windows path unavailable"); await assertNoSymlinkParents({ rootDir: path.win32.parse(e).root, targetPath: e, allowMissing: t.allowMissing }); const n = await fs.lstat(e).catch((e) => { if (t.allowMissing && e instanceof Error && "code" in e && e.code === "ENOENT") return null; throw e; }); if (!n) { const t = path.win32.dirname(e); if (t === e) throw new Error("Windows path unavailable"); await assertPath(t, { kind: "directory", private: false, allowMissing: true }); return; } if (n.isSymbolicLink() || (t.kind === "file" ? !n.isFile() : !n.isDirectory()) || !sameWindowsPath(await fs.realpath(e), e)) throw new Error("Windows path redirected"); const r = await inspectPathPermissions(e, { platform: "win32", env: process.env }); if (!r.ok || r.source !== "windows-acl" || r.ownerTrusted !== true || r.groupWritable || r.worldWritable || t.private && (r.groupReadable || r.worldReadable)) throw new Error("Windows path ownership unavailable"); if (path.win32.dirname(e) !== e) await assertParents(e); }; const windowsNativePlatform = { assertPath, async identity() { if (process.platform !== "win32") throw new Error("Windows identity unavailable"); const e = await inspect$1(IDENTITY_SCRIPT); const t = JSON.parse(e); return identitySchema.parse(t); }, async readFile(e, t, n = true) { await assertPath(e, { kind: "file", private: n }); const { buffer: r } = await readSecureFile({ filePath: e, permissions: { allowReadableByOthers: !n }, io: { maxBytes: t } }); return r; }, listFiles: (e) => fs.readdir(e), realpath: (e) => fs.realpath(e) }; //#endregion //#region extensions/browser/src/browser/extension-windows-host.ts function matchesWindowsContext(e, t) { return e.browserProfile === t.browserProfile && [ "nodePath", "cliPath", "stateDir", "configPath" ].every((n) => sameWindowsPath(e[n], t[n])); } /** Descriptor/receipt are evidence, never permission to skip current OS admission. */ async function readWindowsNativeGeneration(e) { const t = await windowsNativePlatform.identity(); const n = path.win32.join(t.localAppData, "OpenClawTray", "browser-native", "generations"); const r = path.win32.dirname(e); const i = installationSchema.parse({ generation: path.win32.basename(r), manifestPath: e, launcherPath: path.win32.join(r, WINDOWS_NATIVE_EXE), bindingPath: path.win32.join(r, WINDOWS_BINDING), receiptPath: path.win32.join(r, WINDOWS_RECEIPT) }); if (!sameWindowsPath(path.win32.dirname(r), n)) throw new Error("Windows generation is outside the fixed root"); for (const e of [n, r]) await windowsNativePlatform.assertPath(e, { kind: "directory", private: true }); const a = await windowsNativePlatform.listFiles(r); if (a.length !== 4 || a.some((e) => ![ "OpenClaw.BrowserBootstrap.exe", "OpenClaw.BrowserBootstrap.binding.json", "OpenClaw.BrowserBootstrap.owned.json", WINDOWS_MANIFEST ].includes(e))) throw new Error("Windows generation contains foreign files"); const [o, s, c, l] = await Promise.all([ windowsNativePlatform.readFile(i.receiptPath, 32768), windowsNativePlatform.readFile(i.bindingPath, 32768), windowsNativePlatform.readFile(i.manifestPath, 32768), windowsNativePlatform.readFile(i.launcherPath, 268435456) ]); const u = receiptSchema.parse(parseWindowsJson(o)); const d = bindingSchema.parse(parseWindowsJson(s)); const f = windowsManifestSchema.parse(parseWindowsJson(c)); if (u.ownerSid !== t.sid || u.generation !== i.generation || u.bindingSha256 !== sha256Hex(s) || u.manifestSha256 !== sha256Hex(c) || u.executableSha256 !== sha256Hex(l) || d.manifestPath !== i.manifestPath || f.path !== i.launcherPath || JSON.stringify(d.expectedOrigins) !== JSON.stringify(f.allowed_origins)) throw new Error("Windows generation integrity mismatch"); return { installation: i, binding: d }; } async function admitWindowsNativeRuntime(e, t) { const n = await readWindowsNativeGeneration(e.manifestPath); if (n.binding.mode !== "native-windows-cli" || !n.binding.nativeWindows || !matchesWindowsContext(n.binding.nativeWindows, t) || !sameWindowsPath(n.installation.launcherPath, e.launcherPath) || JSON.stringify(n.binding.expectedOrigins) !== JSON.stringify(e.expectedOrigins)) throw new Error("Windows native execution context mismatch"); await windowsNativePlatform.assertPath(t.nodePath, { kind: "file", private: false }); await windowsNativePlatform.assertPath(t.cliPath, { kind: "file", private: false }); await windowsNativePlatform.assertPath(t.stateDir, { kind: "directory", private: true, allowMissing: true }); await windowsNativePlatform.assertPath(t.configPath, { kind: "file", private: true, allowMissing: true }); return t.browserProfile; } const products = [ ["chrome", "Google Chrome"], ["chromium", "Chromium"], ["chrome-for-testing", "Google Chrome for Testing"] ]; async function resolveCliPath(e) { if (!e) return await fs.realpath(process.argv[1]); for (let t = path.resolve(e);;) { const e = path.join(t, "openclaw.mjs"); try { return await fs.realpath(e); } catch (e) { if (!(e instanceof Error) || !("code" in e) || e.code !== "ENOENT") throw e; } const n = path.dirname(t); if (n === t) throw new Error("Local Windows CLI unavailable"); t = n; } } async function selectedContext(e, t, n) { const r = process.env; const i = n ?? resolveStateDir(r); return nativeWindowsContextSchema.parse({ nodePath: await windowsNativePlatform.realpath(process.execPath), cliPath: await windowsNativePlatform.realpath(await resolveCliPath(t)), stateDir: i, configPath: resolveConfigPath(r, i), browserProfile: e }); } async function executableFor(e, t) { const n = await windowsNativePlatform.identity(); const r = t ? [t] : [...e ? [path.win32.join(e, "native-host", "win32-" + process.arch, WINDOWS_NATIVE_EXE)] : [], path.win32.join(n.localAppData, "OpenClawTray", "tools", "browser-bootstrap", WINDOWS_NATIVE_EXE)]; for (const e of r) try { const t = await windowsNativePlatform.realpath(e); await windowsNativePlatform.readFile(t, 268435456, false); return t; } catch (e) { if (t || !(e instanceof Error) || !("code" in e) || e.code !== "ENOENT") throw e; } throw new WindowsManagementTransportError(false); } const managementObservations = /* @__PURE__ */ new WeakMap(); function windowsManagementObservation(e) { return managementObservations.get(e); } function projection(e, t, n, r) { const i = n ?? "Windows management reported " + (e?.code ?? "an unknown outcome"); const a = n ?? (!e?.ok && e?.code !== "browser_control_disabled" && !(e?.registration === "owned" && e.code === "foreign_registration" && e.store === "foreign") ? i : void 0); const o = { registrations: products.map(([n, i]) => ({ product: n, browser: i, manifestPath: "Windows current-user native registration", state: e?.registration ?? null, extensionIds: e?.installation ? t.map((e) => e.slice(19, -1)) : [], issue: a, browserProfile: r })), storeInstallRequests: [{ browser: "Google Chrome", path: "Windows current-user Chrome Store request", state: e?.store ?? null, ...!e?.ok ? { issue: i } : {} }], issues: n ? [n] : e && !e.ok ? ["Windows management reported " + e.code] : [] }; managementObservations.set(o.registrations, { response: e, browserProfile: r }); return o; } async function operate(e) { let t = false; try { e.signal?.throwIfAborted(); const n = await selectedContext(e.browserProfile ?? "chrome", e.pluginRoot); const r = [.../* @__PURE__ */ new Set([WINDOWS_OFFICIAL_ORIGIN, ...(e.extensionIds ?? []).map((e) => "chrome-extension://" + e + "/")])].toSorted(); const i = managementRequestSchema.parse({ v: 1, mode: "native-windows-cli", context: n, action: e.action, store: e.store, expectedOrigins: r }); const a = await executableFor(e.pluginRoot, e.executable); e.signal?.throwIfAborted(); t = true; const o = await runWindowsManagement(a, i, { signal: e.signal }); e.signal?.throwIfAborted(); let s; if (o.installation) { const e = await readWindowsNativeGeneration(o.installation.manifestPath); if (JSON.stringify(e.installation) !== JSON.stringify(o.installation) || e.binding.mode !== "native-windows-cli" || !e.binding.nativeWindows || !matchesWindowsContext(e.binding.nativeWindows, n) || JSON.stringify(e.binding.expectedOrigins) !== JSON.stringify(r)) throw new WindowsManagementTransportError(true); s = e.binding.nativeWindows.browserProfile; } e.signal?.throwIfAborted(); return { response: o, origins: r, browserProfile: s }; } catch (e) { if (e instanceof WindowsManagementTransportError) throw e; throw new WindowsManagementTransportError(t); } } async function installWindowsNativeHost(e) { const { response: t, origins: n, browserProfile: r } = await operate({ ...e, action: "install", store: e.requestStoreInstall === true ? "request" : "preserve" }); return projection(t, n, void 0, r); } async function inspectWindowsNativeHosts(e = {}) { try { const { response: t, origins: n, browserProfile: r } = await operate({ ...e, action: "inspect", store: "preserve" }); return projection(t, n, void 0, r); } catch { return projection(null, [], "Windows management observation is unavailable. Inspect the same local context with a compatible helper."); } } async function uninstallWindowsNativeHosts(e = {}) { const { response: t } = await operate({ ...e, action: "uninstall", store: e.removeStore ? "remove" : "preserve" }); return { removed: t.ok ? ["Windows current-user native registration"] : [], refused: t.ok ? [] : ["Windows management reported " + t.code], manualRequired: false }; } /** Used only by the native CLI, behind frame validation and before config or keys. */ async function validateWindowsNativeContext(e) { const t = process.argv.indexOf("--browser-profile"); const n = t < 0 ? "chrome" : process.argv[t + 1]; if (!n) throw new Error("Missing bound browser profile"); return await admitWindowsNativeRuntime(e, await selectedContext(n, void 0, e.stateDir)); } //#endregion export { inspectWindowsNativeHosts, installWindowsNativeHost, uninstallWindowsNativeHosts, validateWindowsNativeContext, windowsManagementObservation };