openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
11 lines • 6 kB
JavaScript
import{r as isErrno}from"./errno-DUBt6SQQ.mjs";import{i as racePromiseWithAbortSignal,n as createAbortError,s as sleepWithAbort}from"./src-CY_qXgOR.mjs";import{n as isAbortError}from"./sleep-BeLUM6My.mjs";import{o as normalizeStringEntries,t as containsAsciiControlCharacter}from"./string-normalization-mfgVoo8i.mjs";import{s as parseTcpPort}from"./paths-BFN5qw21.mjs";import"./subsystem-BMw5Czn-.mjs";import{t as formatErrorMessage}from"./errors-BKYtsKt6.mjs";import"./backoff-CJvCP7wh.mjs";import{i as theme}from"./logger-DmLqrh-9.mjs";import{n as getWindowsInstallRoots}from"./windows-install-roots-BXU3EsrD.mjs";import{t as resolveSystemBin}from"./resolve-system-bin-CnoUykR_.mjs";import{n as probeTcpListener,r as tryListenOnPort}from"./ports-probe-D-ZgBEac.mjs";import{spawn}from"node:child_process";import path from"node:path";import{isIPv6}from"node:net";
//!src/globals.ts
const success=theme.success;const warn=theme.warn;const info=theme.info;const danger=theme.error;
//!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}};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}}
//!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]})}
//!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(`-`)&&(isIPv6(e)||!e.startsWith(`:`)&&!e.endsWith(`:`))&&!e.includes(`[`)&&!e.includes(`]`)&&!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;let o=false;if(i.startsWith(`[`)){const e=i.match(/^\[([^\]]+)\](?::(.*))?$/);if(!e?.[1]||!isIPv6(e[1]))return null;i=e[1];o=e[2]!==void 0;a=o?parseTcpPort(e[2]):22}else if(!isIPv6(i)){const e=i.lastIndexOf(`:`);if(e>0&&e<i.length-1){o=true;a=parseTcpPort(i.slice(e+1).trim());i=i.slice(0,e).trim()}}if(!i||a===null||!isSafeSshTargetHost(i)||r!==void 0&&!isSafeSshTargetUser(r))return null;return{user:r,host:i,port:a,explicitPort:o}}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-DdwH8M9w.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}`,...t.explicitPort?[`-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(`
`));const n=t.length>0?`\n${t.join(`
`)}`:``;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}}export{startSshPortForward};