UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

345 lines (344 loc) • 9.91 kB
import { c as normalizeOptionalLowercaseString } from "./string-coerce-CCIiB4H7.mjs"; import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { b as uniqueStrings, f as normalizeStringEntries } from "./string-normalization-DLmfYZXI.mjs"; import { n as parseTcpPort, t as MAX_TCP_PORT } from "./tcp-port-CuNPxuH-.mjs"; import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs"; import "./exec-aRIvS9s4.mjs"; import { t as isTailnetIPv4 } from "./tailnet-Ec_4DLPQ.mjs"; import { a as resolveWideAreaDiscoveryDomain } from "./widearea-dns-Clgx1Bw3.mjs"; import pLimit from "p-limit"; //#region src/infra/bonjour-discovery.ts function resolveGatewayDiscoveryEndpoint(e) { const t = e.host?.trim(); const n = e.port; if (!t || typeof n !== "number" || !Number.isSafeInteger(n) || n <= 0 || n > 65535) return null; const r = e.gatewayTls === true ? "wss" : "ws"; return { host: t, port: n, gatewayTlsFingerprintSha256: e.gatewayTlsFingerprintSha256, wsUrl: `${r}://${t}:${n}` }; } function remainingDiscoveryMs(e, t) { return t.signal?.aborted ? 0 : Math.max(0, Math.min(e, Math.ceil((t.deadlineMs ?? Infinity) - performance.now()))); } const DEFAULT_TIMEOUT_MS = 2e3; const GATEWAY_SERVICE_TYPE = "_openclaw-gw._tcp"; function decodeDnsSdEscapes(e) { const t = []; let n = 0; for (const r of e.matchAll(/\\[0-9]{3}/g)) { const i = Number.parseInt(r[0].slice(1), 10); if (i > 255) continue; t.push(Buffer.from(e.slice(n, r.index), "utf8"), Buffer.from([i])); n = r.index + r[0].length; } if (n === 0) return e; t.push(Buffer.from(e.slice(n), "utf8")); return Buffer.concat(t).toString("utf8"); } function parseDigSrv(e) { const t = e.split("\n").map((e) => e.trim()).find(Boolean); if (!t) return null; const n = t.split(/\s+/).filter(Boolean); if (n.length < 4) return null; const r = parseTcpPort(n[2]); const i = n[3] ?? ""; if (r === null) return null; const a = i.replace(/\.$/, ""); if (!a) return null; return { host: a, port: r }; } function parseTailscaleStatusIPv4s(e) { const t = e ? JSON.parse(e) : {}; const n = []; const addIps = (e) => { if (!e || typeof e !== "object") return; const t = e.TailscaleIPs; if (!Array.isArray(t)) return; for (const e of t) { if (typeof e !== "string") continue; const t = e.trim(); if (t && isTailnetIPv4(t)) n.push(t); } }; addIps(t.Self); const r = t.Peer; if (r && typeof r === "object") for (const e of Object.values(r)) addIps(e); return uniqueStrings(n); } function parseTxtTokens(e) { const t = {}; for (const n of e) { const e = n.indexOf("="); if (e <= 0) continue; const r = n.slice(0, e).trim(); const i = decodeDnsSdEscapes(n.slice(e + 1).trim()); if (!r) continue; t[r] = i; } return t; } function applyBeaconTxt(e, t) { for (const n of [ "tailnetDns", "cliPath", "role", "transport" ]) if (t[n]) e[n] = t[n]; e.gatewayPort = parseTcpPort(t.gatewayPort) ?? void 0; e.sshPort = parseTcpPort(t.sshPort) ?? void 0; if (t.gatewayTls) { const n = normalizeOptionalLowercaseString(t.gatewayTls); e.gatewayTls = n === "1" || n === "true" || n === "yes"; } if (t.gatewayTlsSha256) e.gatewayTlsFingerprintSha256 = t.gatewayTlsSha256; } function parseDnsSdBrowse(e) { const t = /* @__PURE__ */ new Set(); for (const n of e.split("\n")) { const e = n.trim(); if (!e || !e.includes(GATEWAY_SERVICE_TYPE)) continue; if (!e.includes("Add")) continue; const r = e.match(/_openclaw-gw\._tcp\.?\s+(.+)$/); if (r?.[1]) t.add(decodeDnsSdEscapes(r[1].trim())); } return Array.from(t.values()); } function parseDnsSdResolve(e, t) { const n = decodeDnsSdEscapes(t); const r = { instanceName: n }; let i = {}; for (const t of e.split("\n")) { const e = t.trim(); if (!e) continue; if (e.includes("can be reached at")) { const t = e.match(/can be reached at\s+([^\s:]+):([^\s]+)/i); if (t?.[1]) r.host = t[1].replace(/\.$/, ""); if (t?.[2]) r.port = parseTcpPort(t[2]) ?? void 0; continue; } if (e.startsWith("txt") || e.includes("txtvers=")) i = parseTxtTokens(e.split(/\s+/).filter(Boolean)); } r.txt = Object.keys(i).length ? i : void 0; if (i.displayName) r.displayName = decodeDnsSdEscapes(i.displayName); if (i.lanHost) r.lanHost = i.lanHost; applyBeaconTxt(r, i); if (!r.displayName) r.displayName = n; return r; } async function discoverViaDnsSd(e, t, n) { const r = remainingDiscoveryMs(t, n); if (r <= 0) return []; const i = parseDnsSdBrowse((await runCommandWithTimeout([ "dns-sd", "-B", GATEWAY_SERVICE_TYPE, e ], { timeoutMs: r, signal: n.signal })).stdout); const a = []; for (const r of i) { const i = remainingDiscoveryMs(t, n); if (i <= 0) break; const o = await runCommandWithTimeout([ "dns-sd", "-L", r, GATEWAY_SERVICE_TYPE, e ], { timeoutMs: i, signal: n.signal }); a.push({ ...parseDnsSdResolve(o.stdout, r), domain: e }); } return a; } async function discoverWideAreaViaTailnetDns(e, t, n) { if (!e || e === "local.") return []; const r = Date.now(); const remainingMs = () => remainingDiscoveryMs(t - (Date.now() - r), n); const i = ["tailscale", "/Applications/Tailscale.app/Contents/MacOS/Tailscale"]; let a = []; for (const e of i) { if (remainingMs() <= 0) break; try { a = parseTailscaleStatusIPv4s((await runCommandWithTimeout([ e, "status", "--json" ], { timeoutMs: Math.max(1, Math.min(700, remainingMs())), signal: n.signal })).stdout); if (a.length > 0) break; } catch {} } if (a.length === 0) return []; if (remainingMs() <= 0) return []; a = a.slice(0, 40); const o = `${GATEWAY_SERVICE_TYPE}.${e.replace(/\.$/, "")}`; let s = null; let c = []; await pLimit(6).map(a, async (e) => { if (s !== null) return; const t = remainingMs(); if (t <= 0) return; try { const r = await runCommandWithTimeout([ "dig", "+short", "+time=1", "+tries=1", `@${e}`, o, "PTR" ], { timeoutMs: Math.max(1, Math.min(250, t)), signal: n.signal }); const i = normalizeStringEntries(r.stdout.split("\n")); if (i.length > 0) { s = e; c = i; } } catch {} }); if (!s || c.length === 0) return []; if (remainingMs() <= 0) return []; const l = `@${String(s)}`; const u = []; for (const t of c) { const r = remainingMs(); if (r <= 0) break; const i = t.trim().replace(/\.$/, ""); if (!i) continue; const a = i.replace(/\.?_openclaw-gw\._tcp\..*$/, ""); const o = await runCommandWithTimeout([ "dig", "+short", "+time=1", "+tries=1", l, i, "SRV" ], { timeoutMs: Math.max(1, Math.min(350, r)), signal: n.signal }).catch(() => null); const s = o ? parseDigSrv(o.stdout) : null; if (!s) continue; const c = { instanceName: a || i, displayName: a || i, domain: e, host: s.host, port: s.port }; u.push(c); const d = remainingMs(); if (d <= 0) continue; const f = ((await runCommandWithTimeout([ "dig", "+short", "+time=1", "+tries=1", l, i, "TXT" ], { timeoutMs: Math.max(1, Math.min(350, d)), signal: n.signal }).catch(() => null))?.stdout ?? "").split("\n").flatMap((e) => Array.from(e.matchAll(/"([^"]*)"/g), (e) => (e[1] ?? "").replaceAll("\\\\", "\\").replaceAll("\\\"", "\"").replaceAll("\\n", "\n"))); const p = f.length > 0 ? parseTxtTokens(f) : {}; c.displayName = p.displayName || c.displayName; c.txt = Object.keys(p).length ? p : void 0; c.tailnetDns = p.tailnetDns || void 0; c.cliPath = p.cliPath || void 0; applyBeaconTxt(c, p); } return u; } function parseAvahiBrowse(e) { const t = []; let n = null; for (const r of e.split("\n")) { const e = r.trimEnd(); if (!e) continue; if (e.startsWith("=") && e.includes(GATEWAY_SERVICE_TYPE)) { if (n) t.push(n); const r = ` ${GATEWAY_SERVICE_TYPE}`; const i = e.indexOf(r); const a = i >= 0 ? e.slice(0, i).trim() : e; const o = a.split(/\s+/); const s = o.length > 3 ? o.slice(3).join(" ") : a; n = { instanceName: s, displayName: s }; continue; } if (!n) continue; const i = e.trim(); if (i.startsWith("hostname =")) { const e = i.match(/hostname\s*=\s*\[([^\]]+)\]/); if (e?.[1]) n.host = e[1]; continue; } if (i.startsWith("port =")) { const e = i.match(/port\s*=\s*\[(\d+)\]/); if (e?.[1]) n.port = parseTcpPort(e[1]) ?? void 0; continue; } if (i.startsWith("txt =")) { const e = parseTxtTokens(Array.from(i.matchAll(/"([^"]*)"/g), (e) => expectDefined(e.at(1), "Bonjour TXT token"))); n.txt = Object.keys(e).length ? e : void 0; if (e.displayName) n.displayName = e.displayName; if (e.lanHost) n.lanHost = e.lanHost; applyBeaconTxt(n, e); } } if (n) t.push(n); return t; } async function discoverViaAvahi(e, t, n) { const r = [ "avahi-browse", "-rt", GATEWAY_SERVICE_TYPE ]; if (e && e !== "local.") r.push("-d", e.replace(/\.$/, "")); const i = remainingDiscoveryMs(t, n); if (i <= 0) return []; return parseAvahiBrowse((await runCommandWithTimeout(r, { timeoutMs: i, signal: n.signal })).stdout).map((t) => Object.assign({}, t, { domain: e })); } async function discoverGatewayBeacons(e = {}) { const t = e.timeoutMs ?? DEFAULT_TIMEOUT_MS; const n = process.platform; const r = resolveWideAreaDiscoveryDomain({ configDomain: e.wideAreaDomain }); const i = ["local.", ...r ? [r] : []]; const a = n === "darwin" ? discoverViaDnsSd : n === "linux" ? discoverViaAvahi : void 0; if (!a) return []; const o = (await Promise.allSettled(i.map((n) => a(n, t, e)))).flatMap((e) => e.status === "fulfilled" ? e.value : []); if (n === "darwin" && r && !o.some((e) => e.domain === r)) { const n = await discoverWideAreaViaTailnetDns(r, t, e).catch(() => []); return [...o, ...n]; } return o; } //#endregion export { resolveGatewayDiscoveryEndpoint as n, discoverGatewayBeacons as t };