UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

318 lines (317 loc) • 12 kB
import { s as formatErrorMessage } from "./error-coercion-hDrHOSGy.mjs"; import { i as getPluginRegistryForContext } from "./gateway-request-scope-BvvDhs5D.mjs"; import { i as createPluginCache, w as withPluginCache } from "./plugin-cache-B_eRuqTM.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { r as loadPluginManifest } from "./manifest-Y5vPZPOf.mjs"; import { t as shouldRejectHardlinkedPluginFiles } from "./hardlink-policy-Kq1Lxk7_.mjs"; import { a as getRuntimeConfigSnapshot } from "./runtime-snapshot-WbwbY5b7.mjs"; import { a as pluginControlUiRevision, o as readPluginControlUiAssets } from "./control-ui-assets-CzHZdjPy.mjs"; import { a as capturePluginLifecycleAuthority } from "./registry-lifecycle-CJjWnl-y.mjs"; import "./runtime-ezCEpumg.mjs"; import { a as hasCanonicalPluginDistribution } from "./plugin-runtime-artifact-binding-BHK81c8H.mjs"; import { a as READ_SCOPE } from "./operator-scopes-CULmYfyY.mjs"; import { r as authorizeOperatorScopesForRequiredScope } from "./method-scopes-Dpyb0Ck-.mjs"; import { l as controlUiPluginAssetPrefix, o as CUSTOM_PLUGIN_UI_DISABLED_MESSAGE, s as isControlUiPluginAllowed, u as controlUiPluginAssetRoot } from "./control-ui-plugin-tabs-C_6CJE64.mjs"; import { r as respondNotFound } from "./control-ui-http-utils-DH5C3tE0.mjs"; import { t as resolveSharedGatewaySessionGeneration } from "./ws-shared-generation-BWsSp-Zl.mjs"; import { d as sendMethodNotAllowed, l as sendGatewayAuthFailure } from "./http-common-FfhIIwOW.mjs"; import { i as captureHttpRequestAuthority } from "./http-request-authority-CYXIvBHo.mjs"; import { m as prepareControlUiPluginCookieRequest, p as authorizeControlUiPluginCookieRequest, t as authorizeControlUiReadRequestOrReply } from "./http-auth-utils-B0FI4CE4.mjs"; import { createHash } from "node:crypto"; //#region src/gateway/control-ui-plugin-assets.ts const log = createSubsystemLogger("gateway/control-ui"); const MAX_CONTROL_UI_PLUGINS = 64; const MAX_CONTROL_UI_CATALOG_BYTES = 67108864; const MAX_CONTROL_UI_CATALOG_REVISIONS = 256; const browserPluginStates = /* @__PURE__ */ new WeakMap(); let pendingCatalogOperation; function getActiveBrowserRegistry() { const e = getPluginRegistryForContext(); return e && capturePluginLifecycleAuthority(e)?.() ? e : null; } function pluginState(e) { let t = browserPluginStates.get(e); if (!t) { t = { revisions: /* @__PURE__ */ new Map(), activations: /* @__PURE__ */ new WeakMap(), initialized: false }; browserPluginStates.set(e, t); } return t; } function browserOwners(e) { return e.plugins.filter((e) => e.enabled && e.status === "loaded" && e.controlUi && e.controlUi.activation !== "settings-only").toSorted((e, t) => e.id.localeCompare(t.id)); } async function staticBrowserImports(e, t, n) { const { build: r } = await import("esbuild"); const i = new Map([...t].filter(([e]) => /\.m?js$/u.test(e)).map(([e, t]) => [new URL(n(e), "http://localhost").href, t])); const a = new URL(e, "http://localhost").href; const o = /* @__PURE__ */ new Set([a]); const s = [a]; for (const e of s) { const t = i.get(e); if (!t) continue; let n; try { const e = await r({ stdin: { contents: t.body.toString("utf8"), loader: "js" }, format: "esm", treeShaking: false, write: false, metafile: true, logLevel: "silent" }); n = Object.values(e.metafile.outputs).flatMap((e) => e.imports); } catch { continue; } for (const t of n) { const n = t.path; if (t.kind !== "import-statement" || !n.startsWith("./") && !n.startsWith("../")) continue; const r = new URL(n, e).href; if (i.has(r) && !o.has(r)) { o.add(r); s.push(r); } } } return s.slice(1).map((e) => new URL(e).pathname); } async function snapshotBrowserBuild(e, t = e.controlUi, n) { if (!t || !e.rootDir || !isControlUiPluginAllowed(e)) throw new Error("plugin is no longer active"); const { entryName: r, styles: i, assets: a, bytes: o } = await readPluginControlUiAssets(e.rootDir, t, { rejectHardlinks: shouldRejectHardlinkedPluginFiles({ origin: e.origin, rootDir: e.rootDir }) }); const s = pluginControlUiRevision(t, n, a); const c = getRuntimeConfigSnapshot()?.gateway?.controlUi?.basePath; const l = `${controlUiPluginAssetPrefix(e.id, c)}${s}/`; const assetUrl = (e) => `${l}${e.split("/").map(encodeURIComponent).join("/")}`; const u = await staticBrowserImports(assetUrl(r), a, assetUrl); return { assets: a, bytes: o, module: { pluginId: e.id, name: e.name, revision: s, entryUrl: assetUrl(r), imports: u, styles: i.map(assetUrl), ...n !== void 0 ? { uiCapabilities: n } : {}, ...hasCanonicalPluginDistribution(e) && e.packageName && e.packageVersion ? { bundledDistribution: { packageName: e.packageName, packageVersion: e.packageVersion } } : {} } }; } async function refreshBrowserCatalog(e, t, n = false) { const r = browserOwners(e); if (r.length > MAX_CONTROL_UI_PLUGINS) throw new Error(`Native Control UI supports at most ${MAX_CONTROL_UI_PLUGINS} active plugins`); if (t && !r.some((e) => e.id === t)) throw new Error("No active Control UI entrypoint for this plugin"); for (const e of r) { if (!isControlUiPluginAllowed(e)) { browserPluginStates.delete(e); continue; } const i = pluginState(e); if (i.initialized && (!n || t && e.id !== t)) continue; try { let t = e.controlUi; let a = e.uiCapabilities; if (n) { const n = e.rootDir; if (!n) throw new Error("plugin is no longer active"); const r = shouldRejectHardlinkedPluginFiles({ origin: e.origin, rootDir: n }); const i = withPluginCache(createPluginCache(), () => loadPluginManifest(n, r, n)); if (!i.ok) throw new Error(i.error); if (i.manifest.id !== e.id || !i.manifest.controlUi) throw new Error("active plugin browser declaration is missing or invalid"); t = i.manifest.controlUi; a = i.manifest.uiCapabilities; } const o = await snapshotBrowserBuild(e, t, a); const s = o.module.revision; if (!i.revisions.has(s)) { let t = o.bytes; let n = 0; for (const e of r) { const r = browserPluginStates.get(e); if (!isControlUiPluginAllowed(e) || !r) continue; n += r.revisions.size; for (const e of r.revisions.values()) t += e.bytes; } if (t > MAX_CONTROL_UI_CATALOG_BYTES || n >= MAX_CONTROL_UI_CATALOG_REVISIONS) { i.diagnostic = { pluginId: e.id, message: "Control UI revision cache is full. Reload this plugin's backend or restart the Gateway before loading another browser build." }; continue; } } i.revisions.set(s, o); i.build = o; delete i.diagnostic; } catch (t) { log.warn(`Browser assets unavailable for plugin ${e.id}: ${formatErrorMessage(t, { includeCode: true })}`); i.diagnostic = { pluginId: e.id, message: "Control UI assets could not be loaded. Build the plugin and reload its UI." }; } finally { i.initialized = true; } } } function projectBrowserCatalog(e) { const t = e ? browserOwners(e) : []; const n = t.flatMap((e) => { const t = browserPluginStates.get(e)?.build; return t && isControlUiPluginAllowed(e) ? [t.module] : []; }); const r = t.flatMap((e) => { if (!isControlUiPluginAllowed(e)) return [{ pluginId: e.id, code: "custom-plugin-ui-disabled", message: CUSTOM_PLUGIN_UI_DISABLED_MESSAGE }]; const t = browserPluginStates.get(e)?.diagnostic; return t ? [t] : []; }); return { revision: createHash("sha256").update(JSON.stringify({ plugins: n, diagnostics: r })).digest("hex"), plugins: n, diagnostics: r }; } async function loadControlUiPluginCatalog(e, t = false) { const n = getPluginRegistryForContext(); if (!n) { if (e) throw new Error("No active Control UI entrypoint for this plugin"); return projectBrowserCatalog(null); } if (!capturePluginLifecycleAuthority(n)?.()) throw new Error("plugin registry is no longer active"); const r = (pendingCatalogOperation ?? Promise.resolve()).then(async () => { await refreshBrowserCatalog(n, e, t); return projectBrowserCatalog(n); }); const i = r.then(() => void 0, () => void 0); pendingCatalogOperation = i; try { return await r; } finally { if (pendingCatalogOperation === i) pendingCatalogOperation = void 0; } } /** Explicit UI-only refresh; never imports or replaces backend plugin code. */ function reloadControlUiPluginCatalog(e) { return loadControlUiPluginCatalog(e, true); } function listControlUiPluginCatalog() { return loadControlUiPluginCatalog(); } /** A receipt is an observation by one live browser connection, never activation authority. */ function reportControlUiPluginActivation(e, t) { const n = getActiveBrowserRegistry(); const r = n && browserOwners(n).find((e) => e.id === t.pluginId); const i = r && browserPluginStates.get(r); const a = i?.build; if (!i || !a || !r || !isControlUiPluginAllowed(r) || a.module.revision !== t.revision) return false; i.activations.set(e, { ...t }); return true; } function listControlUiPluginActivations(e, t) { const n = getActiveBrowserRegistry(); return (n ? browserOwners(n) : []).flatMap((n) => { const r = browserPluginStates.get(n); const i = r?.activations.get(e); return i && (!t || t === n.id) && isControlUiPluginAllowed(n) && r?.build && r.build.module.revision === i.revision ? [i] : []; }); } /** Authorized content-addressed snapshots stay in the private browser cache across grant renewal. */ async function handleControlUiPluginAssetRequest(e, t, n) { const r = new URL(e.url ?? "/", "http://localhost").pathname; const i = controlUiPluginAssetRoot(n.basePath); if (!r.startsWith(i)) return false; t.setHeader("Cache-Control", "no-store"); if (e.method !== "GET" && e.method !== "HEAD") { sendMethodNotAllowed(t, "GET, HEAD"); return true; } let a; try { a = r.slice(i.length).split("/").map(decodeURIComponent); } catch { respondNotFound(t); return true; } const [o, s = "", ...c] = a; if (!o || !/^[a-f0-9]{64}$/u.test(s) || c.length === 0 || c.some((e) => !e || e === "." || e === ".." || /[\\/\0]/u.test(e))) { respondNotFound(t); return true; } const l = captureHttpRequestAuthority({ ...n, req: e }); await prepareControlUiPluginCookieRequest(e, { requestPath: r, authGeneration: resolveSharedGatewaySessionGeneration(n.auth, n.trustedProxies), res: t }); if (t.writableEnded || t.destroyed) return true; const u = authorizeControlUiPluginCookieRequest(e, { requestPath: r, authGeneration: resolveSharedGatewaySessionGeneration(n.auth, n.trustedProxies), res: t }); if (t.writableEnded || t.destroyed) return true; if (u) { if (!u.requestAuth.controlUiPluginGrants?.find((e) => e.pluginId === o && authorizeOperatorScopesForRequiredScope("operator.read", e.scopes).allowed)) { sendGatewayAuthFailure(t, { ok: false, reason: "unauthorized" }); return true; } } else if (!await authorizeControlUiReadRequestOrReply({ req: e, res: t, ...n })) return true; if (!l()) { sendGatewayAuthFailure(t, { ok: false, reason: "unauthorized" }); return true; } const d = getActiveBrowserRegistry(); const f = d && browserOwners(d).find((e) => e.id === o); const p = f && browserPluginStates.get(f)?.revisions.get(s); const m = p && f && isControlUiPluginAllowed(f) ? p.assets.get(c.join("/")) : void 0; if (!m) { respondNotFound(t); return true; } t.statusCode = 200; t.setHeader("Content-Type", m.contentType); t.setHeader("Content-Length", m.body.length); t.setHeader("Cache-Control", "private, max-age=31536000, immutable"); t.setHeader("X-Content-Type-Options", "nosniff"); t.end(e.method === "HEAD" ? void 0 : m.body); return true; } //#endregion export { reportControlUiPluginActivation as a, reloadControlUiPluginCatalog as i, listControlUiPluginActivations as n, listControlUiPluginCatalog as r, handleControlUiPluginAssetRequest as t };