UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

524 lines (523 loc) • 16.7 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { i as resolveEnvironmentValue } from "./process-env-DVJdcOcM.mjs"; import { o as resolveExecutablePath, s as resolveExecutablePathCandidate } from "./executable-path-D8oWZRS5.mjs"; import { c as sha256File } from "./directory-durability-DlnWwNmv.mjs"; import { o as resolveCliBackendConfig } from "./cli-backends-B8PrIwPC.mjs"; import { a as readCodexCliCredentialsCached, o as readGeminiCliCredentialsCached } from "./cli-credentials-BaPg7qWx.mjs"; import { f as loadAuthProfileStoreForRuntimeAsync, i as ensureAuthProfileStoreAsync } from "./store-runtime-dW0pXLJI.mjs"; import { i as resolveWindowsExecutablePath, o as resolveWindowsSpawnProgramCandidate } from "./windows-spawn-BcHMKZuG.mjs"; import { a as fingerprintResolvedAuthProfileCredential, i as fingerprintOpaqueRuntimeOwner, n as fingerprintAuthProfileOwnerShape, t as fingerprintAuthProfileCredential } from "./execution-auth-binding-DfJE1iEP.mjs"; import path from "node:path"; import crypto from "node:crypto"; import fs from "node:fs/promises"; import { readFileWindowFully } from "@openclaw/fs-safe/advanced"; //#region src/agents/cli-executable-identity.ts const MAX_PACKAGE_ARTIFACT_FILES = 8192; const MAX_PACKAGE_ARTIFACT_ENTRIES = MAX_PACKAGE_ARTIFACT_FILES * 4; const MAX_PACKAGE_ARTIFACT_BYTES = 1024n * 1024n * 1024n; function sameOpenedFile(e, t) { return e.dev === t.dev && e.ino === t.ino && e.mode === t.mode && e.size === t.size && e.mtimeNs === t.mtimeNs && e.ctimeNs === t.ctimeNs; } async function readExecutableFileIdentity(e, t = false) { let n; try { const r = await fs.realpath(e); n = await fs.open(r, "r"); const i = await n.stat({ bigint: true }); if (!i.isFile()) return null; const a = await sha256File(n); const o = Buffer.allocUnsafe(t ? Math.min(4096, a.bytes) : 0); const s = t ? await readFileWindowFully(n, o, 0) : 0; const c = await n.stat({ bigint: true }); const l = await fs.stat(r, { bigint: true }); if (!sameOpenedFile(i, c) || !sameOpenedFile(c, l)) return null; return { identity: { path: r, device: String(c.dev), inode: String(c.ino), mode: String(c.mode), size: String(c.size), modifiedNs: String(c.mtimeNs), changedNs: String(c.ctimeNs), contentSha256: a.digest }, prefix: o.subarray(0, s) }; } catch { return null; } finally { await n?.close().catch(() => {}); } } function hasPathSeparator(e) { return e.includes("/") || e.includes("\\"); } function isDurableRootedCommand(e) { return path.isAbsolute(e) || /^~[\\/]/u.test(e); } function pathEntriesAreAbsolute(e) { const t = resolveEnvironmentValue(e, "PATH") ?? ""; const n = process.platform === "win32" ? ";" : path.delimiter; return t.split(n).filter(Boolean).every((e) => path.isAbsolute(e)); } function resolveCommandPath(e) { if (!hasPathSeparator(e.command) && !pathEntriesAreAbsolute(e.env)) return; if (hasPathSeparator(e.command) && !isDurableRootedCommand(e.command)) return; const t = process.platform === "win32" ? resolveWindowsExecutablePath(e.command, e.env) : e.command; if (process.platform === "win32" && !isDurableRootedCommand(t)) return; const n = { ...e.cwd ? { cwd: e.cwd } : {}, env: e.env }; return process.platform === "win32" && isDurableRootedCommand(e.command) ? resolveExecutablePathCandidate(t, n) : resolveExecutablePath(t, n); } function hasShebang(e) { return e.subarray(0, 2).toString("utf8") === "#!"; } function parseShebangInterpreter(e) { const t = e.toString("utf8").split(/\r?\n/u, 1)[0] ?? ""; if (!t.startsWith("#!")) return null; const n = t.slice(2).trim().split(/\s+/u).filter(Boolean); const r = n[0]; if (!r) return null; if (path.basename(r) !== "env") return { executable: r, args: n.slice(1) }; const i = n.slice(1); const a = i[0] === "-S" ? 1 : 0; const o = i[a]; if (!o || o.startsWith("-")) return null; return { executable: r, viaEnv: o, args: i.slice(a + 1) }; } async function resolvePackageTreeArtifact(e) { if (!e.policy || e.policy.kind !== "bundled-package-tree") return; const t = e.policy; let n = path.dirname(e.entrypointPath); let r; for (;;) { const e = path.join(n, "package.json"); try { if (JSON.parse(await fs.readFile(e, "utf8")).name === t.packageName) { r = await fs.realpath(n); break; } } catch {} const i = path.dirname(n); if (i === n) return; n = i; } try { const e = JSON.parse(await fs.readFile(path.join(r, "package.json"), "utf8")); if ([e.dependencies, e.peerDependencies].some((e) => e !== void 0 && (e === null || typeof e !== "object" || Array.isArray(e) || Object.keys(e).length > 0))) return; } catch { return; } const i = crypto.createHash("sha256"); let a = 0; let o = 0; let s = 0n; let c; const visit = async (e) => { let n; try { n = await fs.readdir(e, { withFileTypes: true, encoding: "utf8" }); } catch { return false; } for (const l of n.toSorted((e, t) => e.name < t.name ? -1 : e.name > t.name ? 1 : 0)) { a += 1; if (a > MAX_PACKAGE_ARTIFACT_ENTRIES) return false; const n = path.join(e, l.name); if (l.isDirectory()) { if (!await visit(n)) return false; continue; } if (!l.isFile()) return false; let u; try { const e = await fs.stat(n, { bigint: true }); if (!e.isFile()) return false; u = e.size; } catch { return false; } if (o + 1 > MAX_PACKAGE_ARTIFACT_FILES || s + u > MAX_PACKAGE_ARTIFACT_BYTES) return false; const d = await readExecutableFileIdentity(n); if (!d) return false; const f = path.relative(r, d.identity.path).split(path.sep).join("/"); if (f === "package.json") { let e; try { e = JSON.parse(await fs.readFile(n, "utf8")); } catch { return false; } const r = await readExecutableFileIdentity(n); if (!r || JSON.stringify(r.identity) !== JSON.stringify(d.identity) || e.name !== t.packageName || typeof e.version !== "string" || !e.version.trim()) return false; c = e.version.trim(); } o += 1; s += BigInt(d.identity.size); if (o > MAX_PACKAGE_ARTIFACT_FILES || s > MAX_PACKAGE_ARTIFACT_BYTES) return false; i.update(JSON.stringify([ f, d.identity.mode, d.identity.size, d.identity.contentSha256 ])); i.update("\n"); } return true; }; if (!await visit(r) || o === 0 || !c) return; return { kind: "package-tree", packageName: t.packageName, packageVersion: c, rootPath: r, fileCount: o, totalBytes: String(s), treeSha256: i.digest("hex") }; } function resolveSelfContainedArtifact(e, t, n) { if (!n) return; const r = new Set([e, t].map((e) => { const t = path.basename(e); return process.platform === "win32" ? t.toLowerCase() : t; })); return n.nativeExecutableNames?.some((e) => r.has(process.platform === "win32" ? e.toLowerCase() : e)) === true ? { kind: "self-contained-executable" } : void 0; } function dedupeFileIdentities(e) { return e.filter((t, n) => e.findIndex((e) => e.path === t.path) === n); } /** * Resolve and fingerprint the exact program a CLI child will execute. * * Call only while minting or revalidating verified setup authority: content * hashing is deliberate and must not enter the normal CLI request hot path. */ async function resolveCliExecutableIdentity(e) { const t = e.command.trim(); if (!t) return; const n = e.env ?? process.env; const r = resolveCommandPath({ command: t, ...e.cwd ? { cwd: e.cwd } : {}, env: n }); if (!r) return; const i = process.platform === "win32"; const a = !i && e.cwd ? e.cwd : void 0; const o = e.runtimeArtifact ? e.runtimeArtifact : void 0; if (i) { const e = resolveWindowsExecutablePath("node", n); const i = resolveWindowsSpawnProgramCandidate({ command: r, env: n, execPath: e }); if (i.resolution === "unresolved-wrapper") return; if (i.resolution !== "node-entrypoint" && !resolveExecutablePath(r, { env: n })) return; if (i.resolution === "node-entrypoint" && path.extname(i.command).toLowerCase() !== ".exe") return; const a = await readExecutableFileIdentity(r); const s = await readExecutableFileIdentity(i.command, i.resolution === "direct"); if (!a || !s) return; const c = [a.identity, s.identity]; const l = []; for (const e of i.leadingArgv) { const t = await readExecutableFileIdentity(e); if (!t) return; c.push(t.identity); l.push(t.identity.path); } const u = i.resolution === "node-entrypoint" ? c.find((e) => e.path === l[0]) : void 0; if (i.resolution === "direct" && hasShebang(s.prefix)) return; const d = u ? await resolvePackageTreeArtifact({ entrypointPath: u.path, policy: o }) : resolveSelfContainedArtifact(s.identity.path, r, o); if (!d) return; return { command: t, resolvedPath: a.identity.path, invocation: { command: s.identity.path, leadingArgv: l, resolution: i.resolution }, files: dedupeFileIdentities(c), runtimeArtifact: d }; } const s = await readExecutableFileIdentity(r, true); if (!s) return; const c = [s.identity]; const l = hasShebang(s.prefix); const u = parseShebangInterpreter(s.prefix); if (l && !u) return; if (u && u.args.length > 0) return; const d = u ? s.identity : void 0; const f = d ? await resolvePackageTreeArtifact({ entrypointPath: d.path, policy: o }) : resolveSelfContainedArtifact(s.identity.path, r, o); if (!f) return; const p = s.identity.path; let m; if (u) { for (const e of [u.executable, ...u.viaEnv ? [u.viaEnv] : []]) { const t = resolveCommandPath({ command: e, cwd: a, env: n }); if (!t) return; const r = await readExecutableFileIdentity(t, true); if (!r || hasShebang(r.prefix)) return; c.push(r.identity); } m = { command: c.at(-1).path, leadingArgv: [...u.args, p], resolution: "direct" }; } else m = { command: p, ...r !== p ? { argv0: r } : {}, leadingArgv: [], resolution: "direct" }; return { command: t, resolvedPath: p, invocation: m, files: dedupeFileIdentities(c), runtimeArtifact: f }; } //#endregion //#region src/agents/cli-auth-epoch.ts /** * Builds auth-state epochs for CLI-backed runtimes so reusable sessions reset * when the owning local credential identity changes. */ const GEMINI_CLI_PROVIDER_ID = "google-gemini-cli"; function hashCliAuthEpochPart(e) { return crypto.createHash("sha256").update(e).digest("hex"); } function encodeUnknown(e) { return JSON.stringify(e ?? null); } function encodeOAuthIdentity(e) { return JSON.stringify([ "oauth", e.provider, e.clientId ?? null, e.email ?? null, e.enterpriseUrl ?? null, e.projectId ?? null, e.accountId ?? null ]); } function encodeAuthProfileCredential(e) { switch (e.type) { case "api_key": return JSON.stringify([ "api_key", e.provider, e.key ?? null, encodeUnknown(e.keyRef), e.email ?? null, e.displayName ?? null, encodeUnknown(e.metadata) ]); case "token": if (e.tokenRef !== void 0) return JSON.stringify([ "token-identity", e.provider, encodeUnknown(e.tokenRef), e.email ?? null, e.displayName ?? null ]); return JSON.stringify([ "token", e.provider, e.token ?? null, encodeUnknown(e.tokenRef), e.email ?? null, e.displayName ?? null ]); case "oauth": return encodeOAuthIdentity(e); } throw new Error("Unsupported auth profile credential type"); } function hasOAuthAccountIdentity(e) { return e.type === "oauth" && (normalizeOptionalString(e.accountId) !== void 0 || normalizeOptionalString(e.email) !== void 0); } function encodeAuthProfileEpochPart(e, t) { const n = hashCliAuthEpochPart(encodeAuthProfileCredential(t)); if (hasOAuthAccountIdentity(t) && t.provider !== GEMINI_CLI_PROVIDER_ID) return `profile:oauth-identity:${n}`; return `profile:${e}:${n}`; } function getLocalCliCredential(e, t = 0) { switch (e) { case "codex-cli": return readCodexCliCredentialsCached({ ttlMs: t, allowKeychainPrompt: false }) ?? void 0; case "google-gemini-cli": return readGeminiCliCredentialsCached({ ttlMs: t }) ?? void 0; default: return; } } async function resolveCliAuthEpoch(e) { const t = e.provider.trim(); const n = normalizeOptionalString(e.authProfileId); const r = []; if (e.skipLocalCredential !== true) { const e = getLocalCliCredential(t, 5e3); if (e) r.push(`local:${t}:${hashCliAuthEpochPart(encodeOAuthIdentity(e))}`); } if (n) { const t = (await loadAuthProfileStoreForRuntimeAsync(e.agentDir, { readOnly: true, allowKeychainPrompt: false })).profiles[n]; if (t) r.push(encodeAuthProfileEpochPart(n, t)); } if (r.length === 0) return; return hashCliAuthEpochPart(r.join("\n")); } /** * Strict credential-owner proof for a verified inference turn. Unlike the * reusable-session epoch, identity-less OAuth tokens intentionally invalidate * on rotation because accepting an unknown replacement could cross accounts. */ async function resolveCliAuthBindingFingerprint(e) { const t = e.provider.trim(); const n = normalizeOptionalString(e.authProfileId); const r = n ? await ensureAuthProfileStoreAsync(e.agentDir, { config: e.config, readOnly: true, allowKeychainPrompt: false, externalCliProviderIds: [t] }) : void 0; const i = []; const a = e.skipLocalCredential ? void 0 : getLocalCliCredential(t); if (a) { const e = fingerprintAuthProfileCredential({ profileId: `local:${t}`, credential: a }); if (!e) return; i.push(`local:${e}`); } if (n) { const t = r?.profiles[n]; if (!t) return; const a = fingerprintResolvedAuthProfileCredential({ profileId: n, credential: t, resolvedAuth: e.resolvedAuth }); if (!a) return; i.push(`profile:${a}`); } return i.length > 0 ? hashCliAuthEpochPart(JSON.stringify([ "strict-execution-v1", t, i ])) : void 0; } /** Hash the exact executable plus backend-owned package implementation tree. */ function fingerprintCliRuntimeArtifact(e) { return hashCliAuthEpochPart(JSON.stringify([ "cli-runtime-artifact-v1", e.provider.trim(), e.backendId, e.executableIdentity ])); } /** Re-resolve a CLI backend's complete executable/package artifact boundary. */ async function resolveCliRuntimeArtifactFingerprint(e) { const t = e.provider.trim(); const n = resolveCliBackendConfig(t, e.config, e.agentId ? { agentId: e.agentId } : {}); if (!n) return; if (e.runtimeArtifactId && n.id !== e.runtimeArtifactId) return; const r = await resolveCliExecutableIdentity({ command: n.config.command, ...e.cwd ? { cwd: e.cwd } : {}, ...e.env ? { env: e.env } : {}, ...n.runtimeArtifact ? { runtimeArtifact: n.runtimeArtifact } : {} }); if (!r) return; return fingerprintCliRuntimeArtifact({ provider: t, backendId: n.id, executableIdentity: r }); } /** * Resolve a CLI runtime's non-secret owner shape. The trusted runner emits * this projection only after a real successful turn; callers must not treat * this pre-run value as proof by itself. */ async function resolveCliRuntimeOwnerFingerprint(e) { const t = e.provider.trim(); const n = normalizeOptionalString(e.authProfileId); const r = resolveCliBackendConfig(t, e.config, e.agentId ? { agentId: e.agentId } : {}); if (!r || e.runtimeOwnerId && r.id !== e.runtimeOwnerId) return; const i = e.runtimeArtifactFingerprint ?? await resolveCliRuntimeArtifactFingerprint({ provider: t, config: e.config, ...e.agentId ? { agentId: e.agentId } : {}, runtimeArtifactId: r.id, ...e.cwd ? { cwd: e.cwd } : {}, ...e.env ? { env: e.env } : {} }); if (!i) return; let a; if (n) { const r = await ensureAuthProfileStoreAsync(e.agentDir, { config: e.config, readOnly: true, allowKeychainPrompt: false, externalCliProviderIds: [t] }); a = fingerprintAuthProfileOwnerShape({ profileId: n, credential: r.profiles[n] }); if (!a) return; } return fingerprintOpaqueRuntimeOwner({ kind: "cli-runtime", runner: "cli", provider: t, backendId: r.id, backendConfig: { config: r.config, bundleMcp: r.bundleMcp, bundleMcpMode: r.bundleMcpMode, authEpochMode: r.authEpochMode, nativeToolMode: r.nativeToolMode, hostOwnedTools: r.hostOwnedTools, toolAvailabilityEnforcement: r.toolAvailabilityEnforcement, sideQuestionToolMode: r.sideQuestionToolMode }, ...n ? { authProfileId: n } : {}, ...a ? { authProfileOwnerFingerprint: a } : {}, ...e.skipLocalCredential ? { skipLocalCredential: true } : {}, runtimeArtifactFingerprint: i }); } //#endregion export { resolveCliRuntimeOwnerFingerprint as a, resolveCliRuntimeArtifactFingerprint as i, resolveCliAuthBindingFingerprint as n, resolveCliExecutableIdentity as o, resolveCliAuthEpoch as r, fingerprintCliRuntimeArtifact as t };