UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

235 lines (234 loc) • 8.72 kB
import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs"; import "./utils-C8YECn2Q.mjs"; import { t as sleep } from "./sleep-CkI3nkiJ.mjs"; import { b as resolveGatewayPort } from "./paths-DAcAg5aV.mjs"; import { l as CONTROL_UI_OWNER_BOOTSTRAP_PROFILE_HINT, s as CONTROL_UI_BOOTSTRAP_PROFILE_FRAGMENT_PARAM } from "./zod-schema.gateway-BfjwVYdf.mjs"; import { r as normalizeTlsFingerprint } from "./client-address-utils-Clpzy8Fr.mjs"; import "./config-CMA-J084.mjs"; import { t as createGatewayCredentialPlan } from "./credential-planner-DCQbkiQO.mjs"; import { n as monotonicNow } from "./monotonic-time-Cc4T2fkU.mjs"; import "./http-body-B9w7rzPz.mjs"; import { r as readResponseTextSnippet } from "./http-response-body-B-i_0116.mjs"; import { n as fetchConfiguredLocalOriginWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs"; import "./control-ui-contract-DTmt_Jww.mjs"; import { r as CONTROL_UI_OWNER_BOOTSTRAP_PROFILE } from "./device-bootstrap-profile-COYynVlw.mjs"; import { t as inspectGatewayTlsCertificate } from "./gateway-XogH1jHE.mjs"; import { t as CONTROL_UI_ASSETS_BUILD_TIMEOUT_MS } from "./control-ui-assets-DgSDpYwf.mjs"; import { t as resolveGatewayInteractiveSurfaceAuth } from "./auth-surface-resolution-CJMC_AjZ.mjs"; import { o as isSameProcessSpecificIpv4WithLoopbackListeners } from "./ports-format-BBqs9qRU.mjs"; import { n as inspectPortUsage } from "./ports-inspect-DjJ_TGZf.mjs"; import { n as resolveControlUiLinks } from "./control-ui-links-tAtEMm92.mjs"; import { s as issueDeviceBootstrapToken } from "./device-bootstrap-5DbASnAD.mjs"; //#region src/commands/control-ui-handoff.ts const CONTROL_UI_DOCUMENT_REQUEST_TIMEOUT_MS = 2e3; const CONTROL_UI_DOCUMENT_ERROR_MAX_BYTES = 2048; const CONTROL_UI_DOCUMENT_TRANSIENT_RETRY_DELAY_MS = 500; /** One canonical target keeps advertised identity, local browser delivery, and document probes distinct. */ async function resolveControlUiHandoffTarget(e) { const { config: t, env: n } = e; const r = resolveGatewayPort(t, n); const i = t.gateway?.bind ?? "loopback"; const a = t.gateway?.controlUi?.basePath; const o = t.gateway?.customBindHost; const s = t.gateway?.tls; const c = s?.enabled === true; const l = createGatewayCredentialPlan({ config: t, env: n }); const u = await resolveGatewayInteractiveSurfaceAuth({ config: t, env: n, surface: "local" }); const d = t.gateway?.auth?.mode ?? (l.localPassword.value || l.envPassword ? "password" : "token"); const f = d === "password" && !l.localPassword.hasSecretRef ? u.password : void 0; const p = i === "custom" && o?.trim() === "0.0.0.0"; const m = i === "lan" || p || !c && (i === "tailnet" || i === "custom") ? "loopback" : i; const h = resolveControlUiLinks({ port: r, bind: i, customBindHost: o, basePath: a, tlsEnabled: c }); const g = m === i ? h : resolveControlUiLinks({ port: r, bind: m, customBindHost: o, basePath: a, tlsEnabled: c }); const _ = new URL(h.wsUrl).hostname; const v = m === "loopback" && (i === "tailnet" || i === "custom") && _ !== "127.0.0.1" && _ !== "0.0.0.0" ? _ : void 0; const y = new URL(g.httpUrl); y.hostname = "127.0.0.1"; y.username = ""; y.password = ""; y.search = ""; y.hash = ""; const b = l.localToken.value ?? l.envToken ?? ""; const x = Boolean(b) && !l.localToken.hasSecretRef; return { port: r, basePath: a, bind: i, links: g, authMode: d, gatewayAuthHandoff: f, includeTokenInUrl: x, dashboardUrl: x ? `${g.httpUrl}#token=${encodeURIComponent(b)}` : g.httpUrl, documentUrl: y.toString(), probeUrl: v ? h.wsUrl : g.wsUrl, loopbackAliasHost: v, tlsConfig: s }; } /** Keep shared browser credentials on the same process proven by the configured Gateway endpoint. */ async function hasVerifiedControlUiLoopbackAlias(e) { if (!e.loopbackAliasHost) return true; const t = await inspectPortUsage(e.port).catch(() => void 0); return Boolean(t && isSameProcessSpecificIpv4WithLoopbackListeners(t.listeners, e.port, e.loopbackAliasHost)); } /** Mint the Control-UI-scoped one-time device grant immediately before actual delivery. */ async function issueControlUiBrowserHandoff({ httpUrl: e, wsUrl: t }) { const n = await issueDeviceBootstrapToken({ profile: CONTROL_UI_OWNER_BOOTSTRAP_PROFILE }); return { browserUrl: `${e}#${new URLSearchParams({ bootstrapToken: n.token, [CONTROL_UI_BOOTSTRAP_PROFILE_FRAGMENT_PARAM]: CONTROL_UI_OWNER_BOOTSTRAP_PROFILE_HINT, gatewayUrl: t }).toString()}`, expiresAtMs: n.expiresAtMs }; } const CONTROL_UI_READINESS_INTERRUPTED = "Control UI readiness check was interrupted."; /** Wait for a preparing or temporarily slow dashboard; fail immediately for terminal errors. */ async function waitForControlUiDocument(e) { const t = monotonicNow() + (e.timeoutMs ?? 6e5); let n; let r; if (e.tlsConfig?.enabled === true) try { const t = await inspectGatewayTlsCertificate(e.tlsConfig); if (!t.ok) return { ready: false, reason: t.error }; n = t.value.fingerprintSha256; const i = n; r = { ca: t.value.cert, allowPartialTrustChain: true, checkServerIdentity: (e, t) => normalizeTlsFingerprint(t.fingerprint256 ?? "") === i ? void 0 : /* @__PURE__ */ new Error("Gateway TLS certificate fingerprint mismatch.") }; } catch (e) { return { ready: false, reason: e instanceof Error ? e.message : "Gateway TLS certificate is unavailable." }; } let i = false; let a; const o = new URL(e.url).origin; const requestDocument = async (t, n) => await fetchConfiguredLocalOriginWithSsrFGuard({ url: e.url, configuredLocalOriginBaseUrl: o, policy: { allowedOrigins: [o] }, maxRedirects: 0, timeoutMs: Math.min(CONTROL_UI_DOCUMENT_REQUEST_TIMEOUT_MS, n), capture: false, auditContext: "gateway-control-ui-readiness", ...r ? { dispatcherPolicy: { mode: "direct", connect: r } } : {}, init: { method: t, headers: { Accept: "text/html", "Accept-Encoding": "identity" }, ...e.signal ? { signal: e.signal } : {} } }); while (true) { if (e.signal?.aborted) return { ready: false, reason: CONTROL_UI_READINESS_INTERRUPTED }; const r = t - monotonicNow(); if (r <= 0) return a ? { ready: false, reason: `Control UI dashboard is unavailable: ${a.message}` } : { ready: false, reason: "Control UI assets did not finish preparing in time." }; let o = CONTROL_UI_DOCUMENT_TRANSIENT_RETRY_DELAY_MS; try { const i = await requestDocument("HEAD", r); a = void 0; try { const r = i.response.headers.get("content-type")?.split(";", 1)[0]?.trim(); if (i.response.status === 200 && r?.toLowerCase() === "text/html") return { ready: true, ...n ? { tlsFingerprint: n } : {} }; const a = i.response.headers.get("retry-after"); if (i.response.status !== 503 || !a || e.waitForPending === false) { let e; if (i.response.status === 503 && !a) { const n = await requestDocument("GET", Math.max(1, t - monotonicNow())).catch(() => void 0); if (n) try { const t = n.response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase(); if (n.response.status === 503 && t === "text/plain") { const t = await readResponseTextSnippet(n.response, { maxBytes: CONTROL_UI_DOCUMENT_ERROR_MAX_BYTES, maxChars: CONTROL_UI_DOCUMENT_ERROR_MAX_BYTES, timeoutMs: CONTROL_UI_DOCUMENT_REQUEST_TIMEOUT_MS }).catch(() => void 0); e = t ? sanitizeTerminalText(t) : void 0; } } finally { await n.release(); } } return { ready: false, reason: i.response.status === 503 && a ? "Control UI assets are still preparing." : e || `Control UI dashboard is unavailable (HTTP ${i.response.status}).`, status: i.response.status }; } const s = Number(a); o = Number.isFinite(s) && s > 0 ? s * 1e3 : 1e3; } finally { await i.release(); } } catch (t) { if (e.signal?.aborted) return { ready: false, reason: CONTROL_UI_READINESS_INTERRUPTED }; if (e.waitForPending === false || !(t instanceof Error) || t.name !== "TimeoutError") return { ready: false, reason: `Control UI dashboard is unavailable: ${t instanceof Error ? t.message : String(t)}` }; a = t; } if (!i) { i = true; e.onPending?.(); } try { await sleep(Math.min(o, Math.max(0, t - monotonicNow())), e.signal); } catch (t) { if (e.signal?.aborted) return { ready: false, reason: CONTROL_UI_READINESS_INTERRUPTED }; throw t; } } } //#endregion export { waitForControlUiDocument as i, issueControlUiBrowserHandoff as n, resolveControlUiHandoffTarget as r, hasVerifiedControlUiLoopbackAlias as t };