UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

259 lines (258 loc) • 20.3 kB
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as safeEqualSecret } from "./secret-equal-BogABOFr.mjs"; import { a as classifyMcpAppStandalonePath, n as MCP_APP_STANDALONE_VIEW_PATH, t as MCP_APP_STANDALONE_PATH } from "./gateway-http-route-contracts-DIOh6f_o.mjs"; import { i as respondPlainText } from "./control-ui-http-utils-DH5C3tE0.mjs"; import { t as sendJson } from "./http-json-ddGJz5CA.mjs"; import { s as readJsonBodyOrError, v as watchClientDisconnect } from "./http-common-FfhIIwOW.mjs"; import { n as runWithSessionMcpRequestSignal } from "./agent-bundle-mcp-request-context-B-LzHCC-.mjs"; import { o as peekSessionMcpRuntime } from "./agent-bundle-mcp-manager-api-Um6GkoIv.mjs"; import { i as getMcpAppViewLease, l as buildMcpAppSandboxPath, u as resolveMcpAppSandboxPort } from "./mcp-ui-resource-3UHFH-eE.mjs"; import { d as withMcpAppActiveView, i as parseMcpAppOperation, r as executeMcpAppOperation, u as supportsMcpAppInteraction } from "./mcp-app-operations-Qv9yxlnB.mjs"; import { createHash, createHmac, randomBytes } from "node:crypto"; //#region src/gateway/mcp-app-standalone-host.generated.ts const MCP_APP_STANDALONE_HOST_SOURCE = "(() => {\nvar __openclawRuntimeScript=(()=>{var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from===\"object\"||typeof from===\"function\"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},\"__esModule\",{value:true}),mod);var runtime_script_exports={};__export(runtime_script_exports,{run:()=>runStandaloneMcpAppHost});function runStandaloneMcpAppHost(config){const browser=globalThis;const host=browser.document.getElementById(\"host\");const ticket=browser.location.hash.startsWith(\"#\")?browser.location.hash.slice(1):\"\";let frame;let payload;let initializeAccepted=false;let initialized=false;let displayMode=\"inline\";let availableDisplayModes=[\"inline\",\"fullscreen\"];let requestId=0;let sandboxOrigin;let teardownId;let phase=\"active\";const pending=new Map;const asStandaloneRecord=value=>value&&typeof value===\"object\"&&!Array.isArray(value)?value:void 0;const errorMessage=(error,timeoutMessage)=>asStandaloneRecord(error)?.name===\"TimeoutError\"?timeoutMessage:error instanceof Error?error.message:String(error);const fail=message=>{if(phase===\"suspended\"||phase===\"closed\"){return}removeFrame();host?.replaceChildren(Object.assign(browser.document.createElement(\"p\"),{className:\"error\",textContent:message}))};const post=message=>{if(sandboxOrigin){frame?.contentWindow?.postMessage(message,sandboxOrigin)}};const notify=(method,params={})=>post({jsonrpc:\"2.0\",method,params});const respond=(id,result)=>post({jsonrpc:\"2.0\",id,result});const reject=(id,code,message)=>post({jsonrpc:\"2.0\",id,error:{code,message}});const retireOperations=()=>{for(const[id,controller]of pending){pending.delete(id);controller.abort()}};const removeFrame=()=>{phase=\"closed\";retireOperations();frame?.remove();frame=void 0;sandboxOrigin=void 0;teardownId=void 0};const resolveSandboxUrl=view=>{const base=view.sandboxOrigin?new URL(view.sandboxOrigin):new URL(browser.location.origin);if(!view.sandboxOrigin){base.port=String(view.sandboxPort)}base.pathname=\"/\";base.search=\"\";base.hash=\"\";const resolved=new URL(view.sandboxUrl,base);if(![\"http:\",\"https:\"].includes(resolved.protocol)||resolved.origin!==base.origin||resolved.origin===browser.location.origin||resolved.pathname!==\"/mcp-app-sandbox\"){throw new Error(\"MCP App sandbox URL is invalid\")}return resolved};const request=async(method,params,signal)=>{const response=await fetch(config.viewPath,{method:\"POST\",headers:{Authorization:`MCP-App ${ticket}`,\"Content-Type\":\"application/json\"},body:JSON.stringify({method,params}),cache:\"no-store\",credentials:\"omit\",signal});const body=await response.json().catch(()=>void 0);signal.throwIfAborted();if(response.status===401){fail(\"MCP App ticket was rejected\");throw new Error(\"MCP App ticket was rejected\")}if(!response.ok||body?.ok!==true){throw new Error(body?.error||\"MCP App operation was rejected\")}return body.result};const operations=new Set;const installOperations=view=>{if(view.serverTools===true){operations.add(\"tools/call\");operations.add(\"tools/list\")}if(view.serverResources===true){operations.add(\"resources/list\");operations.add(\"resources/templates/list\");operations.add(\"resources/read\")}};const deliverInitialState=()=>{if(initialized||!payload){return}initialized=true;notify(\"ui/notifications/tool-input\",{arguments:asStandaloneRecord(payload.toolInput)??{}});notify(\"ui/notifications/tool-result\",payload.toolResult)};const isValidInitialize=params=>{const record=asStandaloneRecord(params);const appInfo=asStandaloneRecord(record?.appInfo);return typeof record?.protocolVersion===\"string\"&&typeof appInfo?.name===\"string\"&&typeof appInfo?.version===\"string\"&&asStandaloneRecord(record?.appCapabilities)!==void 0};browser.addEventListener(\"message\",event=>{const message=asStandaloneRecord(event.data);if(event.source!==frame?.contentWindow||event.origin!==sandboxOrigin||message?.jsonrpc!==\"2.0\"||message.id!==void 0&&typeof message.id!==\"string\"&&!(typeof message.id===\"number\"&&Number.isInteger(message.id))){return}if(message.method===\"notifications/cancelled\"){const id2=asStandaloneRecord(message.params)?.requestId;if(message.id===void 0&&(typeof id2===\"string\"||typeof id2===\"number\")){const controller2=pending.get(id2);pending.delete(id2);controller2?.abort()}return}if(typeof message.method===\"string\"&&message.id!==void 0&&pending.has(message.id)){return}if(message.method===\"ui/notifications/sandbox-proxy-ready\"){if(payload){notify(\"ui/notifications/sandbox-resource-ready\",{html:payload.html,csp:payload.csp})}return}if(message.method===\"ping\"&&message.id!==void 0){respond(message.id,{});return}if(message.method===\"ui/initialize\"&&message.id!==void 0){if(!payload||!isValidInitialize(message.params)){reject(message.id,-32602,\"Invalid MCP App initialization\");return}const capabilities=asStandaloneRecord(asStandaloneRecord(message.params)?.appCapabilities);const hints=payload.displayModes?.availableDisplayModes??(payload.displayModes?.preferredDisplayMode?[payload.displayModes.preferredDisplayMode]:capabilities?.availableDisplayModes);availableDisplayModes=[\"inline\",\"fullscreen\"].filter(mode=>!Array.isArray(hints)||hints.includes(mode));if(!availableDisplayModes.length){reject(message.id,-32602,\"No supported display mode\");return}const preferred=payload.displayModes?.preferredDisplayMode;displayMode=preferred&&availableDisplayModes.includes(preferred)?preferred:availableDisplayModes[0];if(frame){frame.style.height=displayMode===\"fullscreen\"?`${browser.innerHeight??600}px`:\"600px\"}initializeAccepted=true;respond(message.id,{protocolVersion:config.protocolVersion,hostInfo:{name:\"OpenClaw standalone host\",version:\"1.0.0\"},hostCapabilities:{sandbox:{csp:payload.csp??{}},...payload.serverTools===true?{serverTools:{}}:{},...payload.serverResources===true?{serverResources:{}}:{}},hostContext:{theme:browser.matchMedia(\"(prefers-color-scheme: dark)\").matches?\"dark\":\"light\",displayMode,availableDisplayModes,...payload.hostContext?.[\"openai/deepLink\"]?{\"openai/deepLink\":payload.hostContext[\"openai/deepLink\"]}:{},containerDimensions:{width:Math.max(1,browser.innerWidth),height:displayMode===\"fullscreen\"?browser.innerHeight??600:600},locale:browser.navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:\"web\"}});return}if(message.method===\"ui/notifications/initialized\"){if(!initializeAccepted){return}deliverInitialState();return}if(message.method===\"ui/request-display-mode\"&&message.id!==void 0){if(!initialized){reject(message.id,-32002,\"MCP App initialization is incomplete\");return}const mode=asStandaloneRecord(message.params)?.mode;if((mode===\"inline\"||mode===\"fullscreen\")&&availableDisplayModes.includes(mode)){displayMode=mode;if(frame){frame.style.height=mode===\"fullscreen\"?`${browser.innerHeight??600}px`:\"600px\"}notify(\"ui/notifications/host-context-changed\",{displayMode})}respond(message.id,{mode:displayMode});return}if(message.method===\"ui/notifications/size-changed\"){const height=asStandaloneRecord(message.params)?.height;if(frame&&displayMode===\"inline\"&&typeof height===\"number\"&&Number.isFinite(height)){frame.style.height=`${Math.min(1200,Math.max(160,Math.round(height)))}px`}return}if(message.method===\"ui/notifications/request-teardown\"){if(phase!==\"active\"){return}phase=\"tearing-down\";const id2=++requestId;teardownId=id2;post({jsonrpc:\"2.0\",id:id2,method:\"ui/resource-teardown\",params:{}});setTimeout(()=>{if(teardownId===id2){removeFrame()}},1e3);return}if(teardownId!==void 0&&message.id===teardownId&&message.method===void 0){removeFrame();return}if(phase===\"suspended\"||phase===\"closed\"||message.id===void 0||typeof message.method!==\"string\"){return}if(!operations.has(message.method)){reject(message.id,-32601,`Method not available in standalone host: ${message.method}`);return}if(!initialized){reject(message.id,-32002,\"MCP App initialization is incomplete\");return}const id=message.id;const controller=new AbortController;pending.set(id,controller);void request(message.method,message.params??{},controller.signal).then(result=>{if(pending.get(id)===controller){respond(id,result)}}).catch(error=>{if(pending.get(id)===controller){reject(id,-32e3,errorMessage(error,\"MCP App operation timed out; try again\"))}}).finally(()=>{if(pending.get(id)===controller){pending.delete(id)}})});browser.addEventListener(\"pagehide\",event=>{if(phase===\"tearing-down\"){phase=\"closed\"}else if(phase===\"active\"){phase=event.persisted?\"suspended\":\"closed\"}retireOperations();if(frame?.contentWindow){post({jsonrpc:\"2.0\",id:++requestId,method:\"ui/resource-teardown\",params:{}})}});browser.addEventListener(\"pageshow\",event=>{if(event.persisted&&phase===\"suspended\"){removeFrame();browser.location.reload()}});if(!ticket){fail(\"MCP App ticket is missing\");return}void fetch(config.viewPath,{headers:{Authorization:`MCP-App ${ticket}`},cache:\"no-store\",credentials:\"omit\",signal:AbortSignal.timeout(config.initialLoadTimeoutMs)}).then(async response=>{if(!response.ok){throw new Error(\"MCP App ticket was rejected\")}const view=await response.json();if(phase!==\"active\"){return}payload=view;installOperations(payload);const sandboxUrl=resolveSandboxUrl(payload);sandboxOrigin=sandboxUrl.origin;frame=browser.document.createElement(\"iframe\");frame.title=\"MCP App\";frame.referrerPolicy=\"origin\";frame.setAttribute(\"sandbox\",\"allow-scripts allow-same-origin allow-forms\");frame.src=sandboxUrl.href;host?.replaceChildren(frame)}).catch(error=>fail(errorMessage(error,\"MCP App view timed out; reload to try again\")))}return __toCommonJS(runtime_script_exports);})();\n\nreturn __openclawRuntimeScript.run;\n})()"; //#endregion //#region src/gateway/mcp-app-standalone.ts const MCP_APP_STANDALONE_TICKET_SCOPE = "mcp-app-standalone-view"; const MCP_APP_STANDALONE_INITIAL_LOAD_TIMEOUT_MS = 3e4; const MCP_APP_STANDALONE_TICKET_TTL_MS = 12e4; const MCP_APP_STANDALONE_TICKET_MIN_REMAINING_MS = 15e3; const MCP_APP_STANDALONE_TICKET_MAX_ENTRIES = 256; const MCP_APP_STABLE_PROTOCOL_VERSION = "2026-01-26"; const MCP_APP_OPERATION_MAX_BODY_BYTES = 262144; const ticketSecret = randomBytes(32); const ticketBindings = /* @__PURE__ */ new Map(); function pruneTicketBindings(e) { for (const [t, n] of ticketBindings) if (n.expiresAtMs <= e) ticketBindings.delete(t); } function signTicket(e, t) { return createHmac("sha256", ticketSecret).update(`${MCP_APP_STANDALONE_TICKET_SCOPE}\0${e}\0${t}`).digest("base64url"); } function formatTicket(e) { const t = `v1.${e.nonce}.${e.expiresAtMs}.${signTicket(e.nonce, e.expiresAtMs)}`; return { ticket: t, url: `${MCP_APP_STANDALONE_PATH}#${t}`, expiresAtMs: e.expiresAtMs }; } function createMcpAppStandaloneTicket(e) { if (e.view.requesterId) return; const t = e.nowMs ?? Date.now(); if (!Number.isSafeInteger(t) || e.view.expiresAtMs <= t) return; const n = Math.min(e.view.expiresAtMs, t + MCP_APP_STANDALONE_TICKET_TTL_MS); pruneTicketBindings(t); let r; for (const t of ticketBindings.values()) if (t.sessionKey === e.sessionKey && t.sessionId === e.view.sessionId && t.viewId === e.view.viewId && t.toolOperationsAuthorized === e.toolOperationsAuthorized) { if (t.expiresAtMs > e.view.expiresAtMs) { ticketBindings.delete(t.nonce); continue; } if (!r || t.expiresAtMs > r.expiresAtMs) r = t; } if (r && (r.expiresAtMs >= n || r.expiresAtMs - t >= MCP_APP_STANDALONE_TICKET_MIN_REMAINING_MS)) return formatTicket(r); if (ticketBindings.size >= MCP_APP_STANDALONE_TICKET_MAX_ENTRIES) return; const i = randomBytes(24).toString("base64url"); const a = { nonce: i, sessionKey: e.sessionKey, sessionId: e.view.sessionId, viewId: e.view.viewId, toolOperationsAuthorized: e.toolOperationsAuthorized, expiresAtMs: n }; ticketBindings.set(i, a); return formatTicket(a); } function verifyMcpAppStandaloneTicket(e, t) { const n = e.split("."); if (n.length !== 4 || n[0] !== "v1") return; const [, r, i, a] = n; if (!r || r.length !== 32 || !i || !a) return; const o = Number(i); if (!Number.isSafeInteger(o) || o <= t) return; const s = signTicket(r, o); if (!safeEqualSecret(a, s)) return; const c = ticketBindings.get(r); if (!c || c.expiresAtMs !== o) return; return c; } function resolveTicketActiveView(e, t) { const n = verifyMcpAppStandaloneTicket(e, t); if (!n) return; const r = peekSessionMcpRuntime({ sessionKey: n.sessionKey }); if (!r || r.mcpAppsEnabled !== true || r.sessionId !== n.sessionId) return; const i = getMcpAppViewLease(n.viewId, r); if (!i || i.requesterId !== void 0 || i.viewId !== n.viewId || i.sessionId !== n.sessionId || i.expiresAtMs <= t || n.expiresAtMs > i.expiresAtMs) return; return { runtime: r, view: i, toolOperationsAuthorized: n.toolOperationsAuthorized }; } function ticketFromRequest(e) { const t = e.headers.authorization; if (!t?.startsWith("MCP-App ")) return; return t.slice(8).trim() || void 0; } function supportsStandaloneToolOperations(e) { return e.toolOperationsAuthorized && e.view.allowedAppToolNames !== void 0 && e.view.readOnly !== true; } function sendJsonRepresentation(e, t, n, r) { const i = JSON.stringify(r); t.statusCode = n; t.setHeader("Content-Type", "application/json; charset=utf-8"); t.setHeader("Content-Length", String(Buffer.byteLength(i))); t.end(e.method === "HEAD" ? void 0 : i); } function standaloneHostHtml() { const e = JSON.stringify({ protocolVersion: MCP_APP_STABLE_PROTOCOL_VERSION, viewPath: MCP_APP_STANDALONE_VIEW_PATH, initialLoadTimeoutMs: MCP_APP_STANDALONE_INITIAL_LOAD_TIMEOUT_MS }); const t = `;(${MCP_APP_STANDALONE_HOST_SOURCE})(${e});`.replaceAll("<\/script", "<\\/script"); return { html: `<!doctype html> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1" /> <title>OpenClaw MCP App</title> <style>html,body{height:100%;margin:0;background:#fff;color:#111;font:14px system-ui,sans-serif}main{height:100%}iframe{display:block;width:100%;height:600px;border:0}.error{padding:16px;color:#b91c1c}</style> <main id="host" aria-live="polite"></main> <script>${t}<\/script>`, scriptHash: createHash("sha256").update(t).digest("base64") }; } function resolveShellSandboxOrigin(e) { if (e.sandboxOrigin) return new URL(e.sandboxOrigin).origin; const t = "encrypted" in e.req.socket && e.req.socket.encrypted ? "https:" : "http:"; const n = new URL(`${t}//${e.req.headers.host ?? "localhost"}`); n.port = String(e.sandboxPort); return n.origin; } async function handleMcpAppStandaloneHttpRequest(e, t, n = {}) { const r = URL.parse(e.url ?? "/", "http://localhost"); if (!r) return false; const i = classifyMcpAppStandalonePath(r.pathname); if (i === "namespace" || i === "outside") return false; if (e.method !== "GET" && e.method !== "HEAD" && !(r.pathname === "/__openclaw__/mcp-app/view" && e.method === "POST")) { respondPlainText(t, 404, "Not Found"); return true; } const a = n.gatewayPort ?? e.socket.localPort; if (!a) { respondPlainText(t, 503, "MCP App host unavailable"); return true; } let o; try { o = resolveMcpAppSandboxPort(a, n.sandboxPort); } catch { respondPlainText(t, 503, "MCP App host unavailable"); return true; } t.setHeader("Cache-Control", "no-store"); t.setHeader("Referrer-Policy", "no-referrer"); t.setHeader("X-Content-Type-Options", "nosniff"); if (i === "shell") { const r = resolveShellSandboxOrigin({ req: e, sandboxOrigin: n.sandboxOrigin, sandboxPort: o }); const i = standaloneHostHtml(); t.statusCode = 200; t.setHeader("Content-Type", "text/html; charset=utf-8"); t.setHeader("Content-Length", String(Buffer.byteLength(i.html))); t.setHeader("Content-Security-Policy", `default-src 'none'; script-src 'sha256-${i.scriptHash}'; style-src 'unsafe-inline'; connect-src 'self'; frame-src ${r}; base-uri 'none'; form-action 'none'; object-src 'none'`); t.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=()"); t.end(e.method === "HEAD" ? void 0 : i.html); return true; } t.setHeader("Vary", "Authorization"); const s = ticketFromRequest(e); const c = s ? resolveTicketActiveView(s, Date.now()) : void 0; if (!c) { t.setHeader("WWW-Authenticate", "MCP-App"); respondPlainText(t, 401, "Unauthorized"); return true; } if (e.method === "POST") { const n = new AbortController(); const r = watchClientDisconnect(e, t, n); try { await runWithSessionMcpRequestSignal(n.signal, async () => { n.signal.throwIfAborted(); const r = await readJsonBodyOrError(e, t, MCP_APP_OPERATION_MAX_BODY_BYTES); n.signal.throwIfAborted(); if (r === void 0) return; const i = parseMcpAppOperation(r); if (!i) { sendJson(t, 400, { ok: false, error: "Invalid MCP App operation" }); return; } const a = s ? resolveTicketActiveView(s, Date.now()) : void 0; if (!a) { t.setHeader("WWW-Authenticate", "MCP-App"); sendJson(t, 401, { ok: false, error: "Unauthorized" }); return; } if ((i.method === "tools/call" || i.method === "tools/list") && !supportsStandaloneToolOperations(a)) { sendJson(t, 403, { ok: false, error: "MCP App tool bridge is unavailable" }); return; } const o = await executeMcpAppOperation(a, i); n.signal.throwIfAborted(); sendJson(t, 200, { ok: true, result: o }); }); } catch (e) { if (!n.signal.aborted && !t.destroyed) sendJson(t, 403, { ok: false, error: formatErrorMessage(e) }); } finally { r(); } return true; } try { return await withMcpAppActiveView(c, "read", async () => { const { runtime: r, view: i } = c; const a = r.readResource !== void 0 && await supportsMcpAppInteraction(i); sendJsonRepresentation(e, t, 200, { sandboxUrl: buildMcpAppSandboxPath(i.csp), sandboxPort: o, ...n.sandboxOrigin ? { sandboxOrigin: new URL(n.sandboxOrigin).origin } : {}, html: i.html, ...i.csp ? { csp: i.csp } : {}, toolInput: i.toolInput, toolResult: i.toolResult, ...i.displayModes ? { displayModes: i.displayModes } : {}, ...i.deepLink ? { hostContext: { "openai/deepLink": i.deepLink } } : {}, serverTools: supportsStandaloneToolOperations(c), serverResources: a }); return true; }); } catch (n) { sendJsonRepresentation(e, t, 429, { ok: false, error: formatErrorMessage(n) }); return true; } } //#endregion export { handleMcpAppStandaloneHttpRequest as n, createMcpAppStandaloneTicket as t };