UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

226 lines (225 loc) • 10.6 kB
import { m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { t as captureRuntimeConfigAsyncReader } from "./io.runtime-DsJ2dLCQ.mjs"; import { n as quotePowerShellArg, t as quoteCliArg } from "./quote-cli-arg-J7A9UE6m.mjs"; import { s as isLoopbackHost } from "./net-BgRayX-P.mjs"; import { d as normalizeMimeType } from "./mime-D2wVBzpa.mjs"; import { n as mutateConfigFileWithRetry } from "./mutate-DhAOi0-2.mjs"; import "./config-CMA-J084.mjs"; import { r as theme } from "./theme-BOI0xyRZ.mjs"; import "./http-body-B9w7rzPz.mjs"; import { i as readResponseWithLimit, t as cancelUnreadResponseBody } from "./http-response-body-B-i_0116.mjs"; import { n as CF_ACCESS_CLIENT_SECRET_HEADER, r as buildCloudflareAccessHeaders, t as CF_ACCESS_CLIENT_ID_HEADER } from "./cloudflare-access-D5ntQryq.mjs"; import { n as normalizeHostname } from "./hostname-DQVb2xzD.mjs"; import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs"; import { t as isDevicePairingJoinCode } from "./join-code-zMzzNXYS.mjs"; import { t as addNodeCommandOptions } from "./command-options-pF05i-p6.mjs"; import { a as nodeHostCloudflareAccessConfigFromEnv, l as resolveNodeHostCloudflareAccess, o as nodeHostGatewayMatchesUrl, s as nodeHostGatewaysShareOrigin } from "./node-worker-prepared-workspace-publication-BHZAZGva.mjs"; import { a as loadNodeHostConfig } from "./config-BmUu42pB.mjs"; import { n as formatHelpExamples, t as formatDocsHelp } from "./help-format-D2ytHW5E.mjs"; import { n as decodePairingSetupCode, r as encodePairingSetupCode } from "./setup-code-BZtNhry3.mjs"; import { r as formatGatewayCandidateUrl } from "./gateway-auth-DyMkGKMU.mjs"; import { n as runNodeHost, t as loadResumableNodeHostGateway } from "./runner-BSaLdg41.mjs"; import { t as runNodeDaemonInstall } from "./daemon-DvDhO3lG.mjs"; import { r as resolveNodePairGatewayPayload } from "./gateway-options-BJTgGucZ.mjs"; import fs from "node:fs/promises"; import { readRegularFile } from "@openclaw/fs-safe/advanced"; import { isUtf8 } from "node:buffer"; //#region src/cli/connect-cli.ts const MAX_JOIN_PAYLOAD_BYTES = 24576; const MAX_TARGET_FILE_BYTES = 65536; const JOIN_FETCH_TIMEOUT_MS = 15e3; function parseJoinTarget(e) { const t = URL.parse(e); if (!t || t.protocol !== "https:" && t.protocol !== "http:") return null; const n = /(?:^|\/)j\/([^/]+)$/u.exec(t.pathname)?.[1] ?? ""; if (t.username || t.password || t.search || t.hash || !isDevicePairingJoinCode(n)) throw new Error("Join URL must end with the exact /j/<shortcode> form."); if (t.protocol === "http:" && !isLoopbackHost(t.hostname)) throw new Error("Plain HTTP join URLs are allowed only for loopback gateways."); return t; } async function fetchJoinPayload(e, t, n) { const r = normalizeHostname(e.hostname); let release = async () => {}; try { n?.throwIfAborted(); const i = await fetchWithSsrFGuard({ url: e.toString(), auditContext: "openclaw-connect-join", maxRedirects: 0, requireHttps: e.protocol === "https:", timeoutMs: JOIN_FETCH_TIMEOUT_MS, signal: n, ...t ? { init: { headers: buildCloudflareAccessHeaders(t) }, capture: { sensitiveRequestHeaderNames: [CF_ACCESS_CLIENT_ID_HEADER, CF_ACCESS_CLIENT_SECRET_HEADER] } } : {}, policy: { allowPrivateNetwork: true, allowedHostnames: [r], hostnameAllowlist: [r] } }); release = i.release; n?.throwIfAborted(); const a = i.response; if (!a.ok || normalizeMimeType(a.headers.get("content-type")) !== "application/json") { await cancelUnreadResponseBody(a); throw new Error("Gateway join code was not found or has expired."); } const o = await readResponseWithLimit(a, MAX_JOIN_PAYLOAD_BYTES, { signal: n }); n?.throwIfAborted(); let s; try { s = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(o)); } catch { throw new Error("Gateway returned an invalid pairing payload."); } return decodePairingSetupCode(encodePairingSetupCode(s)); } catch (e) { if (n?.aborted) return; if (e instanceof Error && e.message.startsWith("Gateway ")) throw e; throw new Error("Could not fetch the Gateway join payload securely.", { cause: e }); } finally { await release(); } } /** Connect only redeems one-shot targets; a saved pairing resumes through `openclaw node`. */ function formatMissingTargetError(e, t) { const n = "Connect target is required."; if (e.ephemeral) return n; const command = (e, ...t) => [formatCliCommand(e), ...t].join(" "); const r = process.platform === "win32" ? quotePowerShellArg : quoteCliArg; const i = e.sessionHost ? ["--session-host"] : []; const a = [ ...e.displayName !== void 0 ? ["--display-name", r(e.displayName)] : [], ...e.commands ? ["--commands", r(e.commands.join(","))] : [], ...e.allCommands ? ["--all-commands"] : [] ]; const o = `mint a join URL on the Gateway host with ${command("openclaw devices join-code")}, then run: ${command("openclaw connect <join-url>", ...e.service ? ["--service"] : [], ...i, ...a)}`; if (!t) return `${n} To pair this machine, ${o}`; const s = e.service ? [...e.sessionHost ? [command("openclaw config set nodeHost.workerRuns.enabled true")] : [], command("openclaw node install --force", ...a)].join(", then ") : command("openclaw node run", ...i, ...a); return [ `${n} Join URLs and setup codes are single-use.`, `If this machine is still paired with ${formatGatewayCandidateUrl(t)}, reconnect with the saved pairing: ${s}`, `Otherwise, ${o}` ].join("\n"); } async function resolveConnectTarget(e, t) { if (e && t) throw new Error("Provide the connect target or --target-file, not both."); if (e) return e; const n = readNonBlankString(t); if (!n) return; let r; try { const e = await fs.realpath(n); ({buffer: r} = await readRegularFile({ filePath: e, maxBytes: MAX_TARGET_FILE_BYTES })); } catch (e) { const t = e instanceof Error ? e.message : String(e); throw new Error(`Could not read --target-file ${n} (max ${MAX_TARGET_FILE_BYTES} bytes): ${t}`, { cause: e }); } if (!isUtf8(r)) throw new Error("Connect target file must be valid UTF-8."); const i = r.toString("utf8").trim(); if (!i) throw new Error("Connect target file is empty."); await fs.rm(n, { force: true }); return i; } function registerConnectCli(e) { addNodeCommandOptions(e.command("connect").description("Connect this machine to an OpenClaw Gateway as a node")).argument("[target]", "oc-pair URL, setup code, or HTTPS Gateway join URL").option("--service", "Install and run the node host as an OS service", false).option("--ephemeral", "Run as an environment-managed disposable session host", false).option("--session-host", "Host worker sessions (process-scoped unless installed as a service)", false).option("--target-file <path>", "Read the connect target from a private file and remove it").option("--display-name <name>", "Override the node display name").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([ ["openclaw connect oc-pair://<setup-code>", "Connect in the foreground."], ["openclaw connect https://gateway.example/j/<code> --service", "Install the node host service."], ["openclaw connect https://gateway.example/j/<code> --service --session-host", "Install a worker-session host service."] ])}\n${formatDocsHelp("/cli/connect")}`).action(async (e, t) => { try { if (t.ephemeral && t.sessionHost) throw new Error("--ephemeral cannot be combined with --session-host."); if (t.ephemeral && t.service) throw new Error("--ephemeral cannot be combined with --service."); const n = await resolveConnectTarget(e, t.targetFile); if (!n) throw new Error(formatMissingTargetError(t, await loadResumableNodeHostGateway())); const r = parseJoinTarget(n); const i = r ? getAsyncWorkSignal() : void 0; const a = await loadNodeHostConfig(); let o; if (r) { const e = a?.gateway; const t = process.env; o = (e && nodeHostGatewayMatchesUrl(e, r) ? e.cloudflareAccess : void 0) ?? nodeHostCloudflareAccessConfigFromEnv(t); } if (o && r?.protocol !== "https:") throw new Error("Cloudflare Access credentials require an HTTPS join URL."); const s = await resolveNodeHostCloudflareAccess({ value: o, config: await captureRuntimeConfigAsyncReader()(), env: process.env }); const c = r ? await fetchJoinPayload(r, s, i) : decodePairingSetupCode(n, { allowExpired: t.ephemeral === true }); if (!c || i?.aborted) return; const l = resolveNodePairGatewayPayload(c); const u = o ?? (a?.gateway && nodeHostGatewaysShareOrigin(a.gateway, l.candidates[0]) ? a.gateway.cloudflareAccess : void 0) ?? nodeHostCloudflareAccessConfigFromEnv(process.env); const d = l.candidates.map((e, t) => { return (r ? nodeHostGatewayMatchesUrl(e, r) : t === 0) && u ? { ...e, cloudflareAccess: u } : e; }); const f = t.ephemeral === true || t.sessionHost === true && !t.service; const p = { gatewayHost: l.host, gatewayPort: l.port, gatewayTls: l.tls, gatewayTlsFingerprint: l.tlsFingerprint, gatewayContextPath: l.contextPath, ...d[0]?.cloudflareAccess ? { gatewayCloudflareAccess: d[0].cloudflareAccess } : {}, gatewayCandidates: d, gatewayBootstrapToken: l.bootstrapToken, ...t.ephemeral === true && l.expiresAtMs !== void 0 ? { gatewayBootstrapExpiresAtMs: l.expiresAtMs } : {}, preferGatewayBootstrapToken: t.ephemeral !== true, ...f ? { forceWorkerRuns: true } : {}, ...t.ephemeral === true ? { ephemeral: true } : {}, displayName: t.displayName, commands: t.commands, allCommands: t.allCommands }; if (!t.service) { await runNodeHost(p); return; } await runNodeHost({ ...p, stopAfterFirstConnect: true }); if (t.sessionHost) await mutateConfigFileWithRetry({ writeOptions: { auditOrigin: "cli", explicitSetPaths: [[ "nodeHost", "workerRuns", "enabled" ]] }, mutate: (e) => { e.nodeHost = { ...e.nodeHost, workerRuns: { ...e.nodeHost?.workerRuns, enabled: true } }; } }); await runNodeDaemonInstall({ displayName: t.displayName, commands: t.commands, allCommands: t.allCommands, force: true }); } catch (e) { defaultRuntime.error(e instanceof Error ? e.message : String(e)); defaultRuntime.exit(1); } }); } //#endregion export { registerConnectCli };