UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

224 lines (223 loc) • 6.89 kB
import { s as parseTcpPort, u as isErrno } from "./paths-0xDagtub.mjs"; import { c as isAbortError } from "./utils-BclMknzT.mjs"; import { n as createAbortError, o as sleepWithAbort, r as racePromiseWithAbortSignal } from "./src-DIZdnDBl.mjs"; import { o as normalizeStringEntries, t as containsAsciiControlCharacter } from "./string-normalization-BMFMScZY.mjs"; import "./subsystem-CeOCPr4l.mjs"; import { t as formatErrorMessage } from "./errors-hqLS1E8Y.mjs"; import { n as probeTcpListener, r as tryListenOnPort } from "./ports-probe-BXzZ4if-.mjs"; import { n as getWindowsInstallRoots } from "./windows-install-roots-CNvr-0dO.mjs"; import { i as theme } from "./logger-DlJKXoGM.mjs"; import { t as resolveSystemBin } from "./resolve-system-bin-C-lukYOk.mjs"; import { spawn } from "node:child_process"; import path from "node:path"; //#region src/globals.ts const success = theme.success; const warn = theme.warn; const info = theme.info; const danger = theme.error; //#endregion //#region src/infra/ports.ts var PortInUseError = class extends Error { constructor(e, t) { super(`Port ${e} is already in use.`); this.name = "PortInUseError"; this.port = e; this.details = t; } }; /** Probes Node's wildcard bind by default; callers may scope checks to their owned interface. */ async function ensurePortAvailable(e, t, n) { try { const r = { port: e, ...t ? { host: t } : {}, ...n ? { signal: n } : {} }; await tryListenOnPort(r); } catch (t) { if (isErrno(t) && t.code === "EADDRINUSE") throw new PortInUseError(e); throw t; } } //#endregion //#region src/infra/ssh-client.ts function resolveSshClient() { if (process.platform !== "win32") return resolveSystemBin("ssh", { trust: "strict" }); const { systemRoot: e } = getWindowsInstallRoots(); const t = path.win32.join(e, "System32", "OpenSSH"); return resolveSystemBin("ssh", { trust: "strict", extraDirs: [t] }); } //#endregion //#region src/infra/ssh-tunnel.ts function hasControlOrWhitespace(e) { return containsAsciiControlCharacter(e) || /\s/.test(e); } function isSafeSshTargetUser(e) { return !hasControlOrWhitespace(e) && !e.startsWith("-"); } function isSafeSshTargetHost(e) { return !hasControlOrWhitespace(e) && !e.startsWith("-") && !e.startsWith(":") && !e.endsWith(":") && !e.includes("@"); } function parseSshTarget(e) { const t = e.trim().replace(/^ssh\s+/, ""); if (!t) return null; const n = t.indexOf("@"); const r = n === -1 ? void 0 : t.slice(0, n).trim() || void 0; let i = n === -1 ? t : t.slice(n + 1).trim(); let a = 22; const o = i.lastIndexOf(":"); if (o > 0 && o < i.length - 1) { a = parseTcpPort(i.slice(o + 1).trim()); i = i.slice(0, o).trim(); } if (!i || a === null || !isSafeSshTargetHost(i) || r !== void 0 && !isSafeSshTargetUser(r)) return null; return { user: r, host: i, port: a }; } async function waitForLocalListener(e, t, n, r, i) { const a = performance.now(); while (performance.now() - a < t) { if (await probeTcpListener(e, "127.0.0.1", n) === "busy") { const { inspectPortUsage: t } = await import("./ports-inspect-DnPR-j41.mjs"); const a = await t(e, { probeHosts: ["127.0.0.1"], signal: n }); if (!i()) throw new Error("ssh exited before tunnel listener ownership was verified"); if (r === void 0 || a.listeners.length === 0 || a.listeners.some((e) => e.pid !== r)) throw new Error(`cannot verify SSH tunnel listener ownership on 127.0.0.1:${e} for SSH process ${r ?? "unknown"}; stop any conflicting listener or enable process inspection, then retry`); return; } await sleepWithAbort(50, n); } throw new Error(`ssh tunnel did not start listening on localhost:${e}`); } async function startSshPortForward(e) { const t = parseSshTarget(e.target); if (!t) throw new Error(`invalid SSH target: ${e.target}`); const n = resolveSshClient(); if (!n) throw new Error("trusted SSH client not found in system directories"); let r = e.localPortPreferred; try { await ensurePortAvailable(r, "127.0.0.1"); } catch (e) { if (e instanceof PortInUseError || isErrno(e) && (e.code === "EADDRINUSE" || e.code === "EACCES" || e.code === "EPERM")) r = await tryListenOnPort({ port: 0, host: "127.0.0.1" }); else throw e; } const i = t.user ? `${t.user}@${t.host}` : t.host; const a = [ "-N", "-L", `127.0.0.1:${r}:127.0.0.1:${e.remotePort}`, .../:\d+$/.test(e.target.trim()) ? ["-p", String(t.port)] : [], "-o", "ExitOnForwardFailure=yes", "-o", "BatchMode=yes", "-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ControlPersist=no", "-o", "ForkAfterAuthentication=no", ...e.hostKeyPolicy === "openssh" ? [] : ["-o", "StrictHostKeyChecking=yes"], "-o", "UpdateHostKeys=yes", "-o", "ConnectTimeout=5", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3" ]; if (e.identity?.trim()) a.push("-i", e.identity.trim()); a.push("--", i); if (e.signal?.aborted) throw createAbortError("SSH tunnel start aborted", { cause: e.signal.reason }); const o = []; const s = spawn(n, a, { stdio: [ "ignore", "ignore", "pipe" ] }); const c = s.stderr; c?.on("error", () => {}); c?.setEncoding("utf8"); c?.on("data", (e) => o.push(e)); let l = true; const u = new Promise((e) => { const onExit = () => { l = false; e(); }; s.once("exit", onExit); s.once("close", onExit); }); let onAbort; const detachAbort = () => { if (onAbort) { e.signal?.removeEventListener("abort", onAbort); onAbort = void 0; } }; let d; const stop = () => d ??= (async () => { detachAbort(); const e = setTimeout(() => s.kill("SIGKILL"), 1500); try { s.kill("SIGTERM"); await u; } finally { clearTimeout(e); } })(); const f = new AbortController(); const p = waitForLocalListener(r, Math.max(250, e.timeoutMs), f.signal, s.pid, () => l && !d); try { try { await racePromiseWithAbortSignal(Promise.race([p, new Promise((e, t) => { s.once("error", (e) => t(e)); s.once("exit", (e, n) => { t(/* @__PURE__ */ new Error(`ssh exited (${e ?? "null"}${n ? `/${n}` : ""})`)); }); })]), e.signal); } finally { f.abort(); await p.catch(() => {}); } } catch (e) { await stop(); if (isAbortError(e)) throw e; const t = normalizeStringEntries(o.join("").split("\n")); const n = t.length > 0 ? `\n${t.join("\n")}` : ""; throw new Error(`${formatErrorMessage(e)}${n}`, { cause: e }); } if (e.signal) { onAbort = () => void stop().catch(() => {}); e.signal.addEventListener("abort", onAbort, { once: true }); if (e.signal.aborted) { onAbort(); await stop(); throw createAbortError("SSH tunnel start aborted", { cause: e.signal.reason }); } } u.then(detachAbort); return { localPort: r, pid: typeof s.pid === "number" ? s.pid : null, closed: u, isActive: () => l && !d, stop }; } //#endregion export { startSshPortForward };