UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

373 lines (372 loc) • 13.9 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { c as filterStringRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { s as raceWithTimeout } from "./src-BPmQBLJp.mjs"; import { o as registerSecretValueForRedaction } from "./secret-redaction-registry-Cy0acctn.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { o as getPluginRuntimeGatewayRequestScope } from "./gateway-request-scope-BvvDhs5D.mjs"; import { t as AuthProfileAuthorizationError } from "./authorization-contract-CQ0hvliU.mjs"; import { l as getActivePluginRegistry } from "./runtime-ezCEpumg.mjs"; import { i as logWarn } from "./logger-CIwfuhOU.mjs"; import { r as resolveConfiguredMcpTransport } from "./mcp-config-normalize-DxJwGDsa.mjs"; import { i as loadEnabledBundleMcpConfig } from "./bundle-mcp-DKz8uq8U.mjs"; import crypto from "node:crypto"; import fs from "node:fs/promises"; //#region src/agents/mcp-connection-resolver.ts /** * Plugin-registered MCP connection resolvers: lookup and per-requester resolve. * Resolved url/headers are credentials — never log, fingerprint, or persist them. */ function isLiveConnectionAuthority(e) { return isRecord(e) && typeof e.authorizationId === "string" && e.authorizationId.length > 0 && e.authorizationId.length <= 2048 && typeof e.assertCurrent === "function" && typeof e.revalidate === "function" && typeof e.dispose === "function"; } function retainResolverObservation(e, t) { const n = e.authorizationId; let r = false; const assertCurrent = () => { if (r || e.authorizationId !== n) throw new AuthProfileAuthorizationError("retired"); try { e.assertCurrent(); } catch (e) { throw new AuthProfileAuthorizationError(isRecord(e) && e.code === "MCP_AUTHORIZATION_RETIRED" ? "retired" : "unavailable"); } }; return { authorizationId: JSON.stringify([ t.pluginId, t.serverName, n ]), assertCurrent, revalidate: async () => { if (r || e.authorizationId !== n) throw new AuthProfileAuthorizationError("retired"); try { await raceWithTimeout(Promise.resolve(e.revalidate()), MCP_CONNECTION_RESOLVER_TIMEOUT_MS, () => { throw new McpResolverTimeoutError(); }, { ref: false }); assertCurrent(); } catch (e) { throw new AuthProfileAuthorizationError(isRecord(e) && e.code === "MCP_AUTHORIZATION_RETIRED" ? "retired" : "unavailable"); } }, dispose: () => { if (!r) { r = true; e.dispose(); } } }; } function releaseResolverObservation(e) { if (typeof e?.authority?.dispose === "function") e.authority.dispose(); } /** Per-server bound on plugin resolve(); stalled providers must not hang getOrCreate. */ const MCP_CONNECTION_RESOLVER_TIMEOUT_MS = 1e4; /** * How long a full-set requester runtime may skip re-resolve while active. * Revocation/rotation takes effect within this window even for continuously active requesters. */ const MCP_CONNECTION_REVALIDATE_MS = 3e5; /** * Ephemeral per-process HMAC key for connection digests. Never exported, logged, * or persisted — dies with the process so digests are not offline-guessable. */ let connectionDigestKey; /** * Ephemeral keyed digest of resolved connection material for rotation detection. * HMAC-SHA256 with a process-local random key — not a plain hash of credentials. * Never log or persist the preimage (urls/headers) or the key. */ function hashMcpResolvedConnections(e) { const t = [...e.entries()].toSorted(([e], [t]) => e.localeCompare(t)).map(([e, t]) => { const n = t.headers ? Object.entries(t.headers).toSorted(([e], [t]) => e.localeCompare(t)) : []; return [ e, t.url, n ]; }); return crypto.createHmac("sha256", connectionDigestKey ??= crypto.randomBytes(32)).update(JSON.stringify(t)).digest("hex"); } var McpResolverTimeoutError = class extends Error { constructor() { super("mcp connection resolver timed out"); this.name = "McpResolverTimeoutError"; } }; /** Returns registered connection resolvers keyed by server name (deterministic order). */ function listMcpServerConnectionResolversByServerName() { const e = /* @__PURE__ */ new Map(); const t = getPluginRuntimeGatewayRequestScope()?.pluginRegistry ?? getActivePluginRegistry(); for (const n of t?.mcpServerConnectionResolvers ?? []) { const t = normalizeOptionalString(n.resolver.serverName); if (!t || typeof n.resolver.resolve !== "function" || e.has(t)) continue; e.set(t, { pluginId: n.pluginId, serverName: t, resolve: n.resolver.resolve }); } return new Map([...e.entries()].toSorted(([e], [t]) => e.localeCompare(t))); } /** Partition loaded MCP servers into static vs requester-scoped connections. */ function partitionMcpServersByConnectionScope(e) { const t = listMcpServerConnectionResolversByServerName(); const n = []; const r = []; const i = []; const a = []; for (const [o, s] of Object.entries(e).toSorted(([e], [t]) => e.localeCompare(t))) { const e = isRecord(s) ? s : void 0; const c = e && isRecord(e.oauth) ? e.oauth : void 0; if (e?.auth === "oauth" && c?.identity === "per-requester") { r.push(o); i.push(o); continue; } if (t.has(o)) { r.push(o); a.push(o); continue; } n.push([o, s]); } return { staticServers: Object.fromEntries(n), requesterScopedServerNames: r, oauthRequesterServerNames: i, resolverRequesterServerNames: a }; } /** * Debug-proxy capture and log redaction match registered exact values, not * header names alone. Resolver output is credential material (auth headers, * signed-URL query tokens), so register it before it can reach any transport. */ function registerResolvedConnectionSecrets(e) { for (const t of Object.values(e.headers ?? {})) { registerSecretValueForRedaction(t); const e = t.trim().split(/\s+/).at(-1); if (e && e !== t) registerSecretValueForRedaction(e); } registerSecretValueForRedaction(e.url); try { const t = new URL(e.url); for (const e of t.searchParams.values()) registerSecretValueForRedaction(e); if (t.password) registerSecretValueForRedaction(t.password); } catch {} } /** * Resolve requester-scoped server connections. Fail closed without requesterSenderId: * returns an empty map (no shared-connection fallback). Per-server resolve errors and * timeouts are logged generically and omitted so one plugin cannot block static MCP. * Servers resolve concurrently (each individually bounded). */ async function resolveRequesterScopedMcpConnections(e) { if (e.retainAuthority && e.serverNames.length !== 1) throw new Error("Live MCP authority must resolve one exact server"); const t = normalizeOptionalString(e.requesterSenderId); const n = /* @__PURE__ */ new Map(); if (!t || e.serverNames.length === 0) return n; const r = listMcpServerConnectionResolversByServerName(); const i = normalizeOptionalString(e.agentAccountId); const a = normalizeOptionalString(e.messageChannel); const o = { requesterSenderId: t, ...i ? { agentAccountId: i } : {}, ...a ? { messageChannel: a } : {}, ...e.retainAuthority ? { requireLiveAuthority: true } : {} }; const s = MCP_CONNECTION_RESOLVER_TIMEOUT_MS; const c = [...e.serverNames].toSorted((e, t) => e.localeCompare(t)); const l = await Promise.all(c.map(async (t) => { const n = r.get(t); if (!n) { if (e.retainAuthority) throw new AuthProfileAuthorizationError("unavailable"); return null; } let i = null; let a = false; try { const r = Promise.resolve(n.resolve(o)); try { i = await raceWithTimeout(r, s, () => { throw new McpResolverTimeoutError(); }, { ref: false }); } catch (e) { if (e instanceof McpResolverTimeoutError) r.then(releaseResolverObservation).catch(() => { logWarn("bundle-mcp: late resolver authority cleanup failed"); }); throw e; } if (!i || typeof i.url !== "string" || i.url.trim().length === 0) { if (e.retainAuthority) throw new AuthProfileAuthorizationError(i === null ? "retired" : "unavailable"); return null; } const c = e.retainAuthority ? i.authority : void 0; if (e.retainAuthority && !isLiveConnectionAuthority(c)) throw new AuthProfileAuthorizationError("unavailable"); c?.assertCurrent(); const l = filterStringRecord(i.headers); const u = l ? Object.fromEntries(Object.entries(l).toSorted(([e], [t]) => e.localeCompare(t))) : void 0; const d = { url: i.url.trim(), ...u ? { headers: u } : {}, ...c ? { authority: retainResolverObservation(c, n) } : {} }; registerResolvedConnectionSecrets(d); a = Boolean(c); return { serverName: t, connection: d }; } catch (r) { if (e.retainAuthority) throw new AuthProfileAuthorizationError(isRecord(r) && r.code === "MCP_AUTHORIZATION_RETIRED" ? "retired" : "unavailable"); const i = r instanceof McpResolverTimeoutError ? "resolver timeout" : "resolver error"; logWarn(`bundle-mcp: connection resolver for server "${t}" (plugin "${n.pluginId}") failed with ${i}`); return null; } finally { if (!a) try { releaseResolverObservation(i); } catch { logWarn("bundle-mcp: resolver authority cleanup failed"); } } })); for (const e of l) if (e) n.set(e.serverName, e.connection); return n; } /** * Apply resolved connection fields for transport construction only. * Does not mutate the original static config object. */ function applyMcpConnectionOverride(e, t) { const n = isRecord(e) ? { ...e } : {}; n.url = t.url; if (t.headers) n.headers = { ...t.headers }; else delete n.headers; const r = resolveConfiguredMcpTransport(n); n.transport = !r || r === "stdio" ? "streamable-http" : r; delete n.auth; delete n.oauth; delete n.type; delete n.command; delete n.args; return n; } /** * Fingerprint shape for requester-scoped servers: identity + filters only. * Never includes resolved or static url/headers credentials. */ function redactMcpServersForFingerprint(e, t) { const n = {}; for (const [r, i] of Object.entries(e).toSorted(([e], [t]) => e.localeCompare(t))) { if (!t.has(r)) { n[r] = i; continue; } if (!isRecord(i)) { n[r] = { connection: "requester-scoped" }; continue; } const { url: e, headers: a, command: o, args: s, env: c, ...l } = i; n[r] = { ...l, connection: "requester-scoped" }; } return n; } function buildMcpRequesterRuntimeCacheKey(e) { return JSON.stringify({ sessionId: e.sessionId, messageChannel: normalizeOptionalString(e.messageChannel) ?? "", agentAccountId: normalizeOptionalString(e.agentAccountId) ?? "", requesterSenderId: e.requesterSenderId }); } //#endregion //#region src/agents/bundle-mcp-config.ts /** * Merges bundled plugin MCP servers with user-configured MCP servers for agent * runtimes. */ const OPENCLAW_TRANSPORT_TO_CLI_BUNDLE_TYPE = { "streamable-http": "http", http: "http", sse: "sse", stdio: "stdio" }; /** Session-shared harness connections must exclude requester-owned credentials. */ function loadStaticBundleMcpConfig(e) { const t = loadMergedBundleMcpConfig(e); const { staticServers: n, requesterScopedServerNames: r } = partitionMcpServersByConnectionScope(t.config.mcpServers); return { ...t, config: { mcpServers: n }, prepareDataDirsByServer: Object.fromEntries(Object.entries(t.prepareDataDirsByServer).filter(([e]) => Object.hasOwn(n, e))), requesterScopedServerNames: r }; } async function prepareOwnedBundleMcpDataDirs(e) { const t = { ...e.config.mcpServers }; const n = []; for (const [r, i] of Object.entries(e.prepareDataDirsByServer)) { if (!Object.hasOwn(t, r)) continue; try { await fs.mkdir(i.dataDir, { recursive: true }); } catch (e) { delete t[r]; n.push({ pluginId: i.pluginId, message: `unable to prepare PLUGIN_DATA directory "${i.dataDir}" for MCP server "${r}": ${formatErrorMessage(e)}` }); } } return { config: { mcpServers: t }, diagnostics: n }; } /** * User config stores OpenClaw MCP transport names, while CLI backends such as * Claude Code and Gemini expect a downstream `type` field. Keep this adapter * at the output boundary so OAuth and runtime policy keep canonical transport. */ function toCliBundleMcpServerConfig(e) { const t = { ...e }; const n = t.transport; delete t.transport; if (typeof n === "string") { const e = OPENCLAW_TRANSPORT_TO_CLI_BUNDLE_TYPE[n]; if (e) t.type = e; } return t; } /** Loads enabled bundled MCP servers and overlays user config by server name. */ function loadMergedBundleMcpConfig(e) { return mergeConfiguredBundleMcpServers(loadEnabledBundleMcpConfig({ workspaceDir: e.workspaceDir, cfg: e.cfg, manifestRegistry: e.manifestRegistry }), e); } /** Apply the same operator overrides to prepared runtime and account-setup declarations. */ function mergeConfiguredBundleMcpServers(e, t) { const n = t.cfg?.mcp?.servers ?? {}; const r = t.toolOverrides?.mcpServers; const i = Object.fromEntries(Object.entries({ ...e.config.mcpServers, ...n }).filter(([e]) => { const t = r && Object.hasOwn(r, e) ? r[e] : void 0; return t !== false && (t === true || n[e]?.enabled !== false); })); const isUnshadowedBundleServer = ([e]) => Object.hasOwn(i, e) && !Object.hasOwn(n, e); const a = Object.fromEntries(Object.entries(e.prepareDataDirsByServer ?? {}).filter(isUnshadowedBundleServer)); return { config: { mcpServers: i }, diagnostics: e.diagnostics, pluginIdsByServer: Object.fromEntries(Object.entries(e.pluginIdsByServer).filter(isUnshadowedBundleServer)), prepareDataDirsByServer: a }; } //#endregion export { toCliBundleMcpServerConfig as a, buildMcpRequesterRuntimeCacheKey as c, redactMcpServersForFingerprint as d, resolveRequesterScopedMcpConnections as f, prepareOwnedBundleMcpDataDirs as i, hashMcpResolvedConnections as l, loadStaticBundleMcpConfig as n, MCP_CONNECTION_REVALIDATE_MS as o, mergeConfiguredBundleMcpServers as r, applyMcpConnectionOverride as s, loadMergedBundleMcpConfig as t, partitionMcpServersByConnectionScope as u };