openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
15 lines • 12.4 kB
JavaScript
import{Dt as MAX_HEAD_FRAME_BYTES,Mt as STREAM_RESET,Ot as MAX_HTTP_DATA_FRAME_BYTES,Pt as TUNNEL_ALPN,St as HTTP_STREAM_IDLE_TIMEOUT_MS,_t as stripClientHeaders,bt as CONNECTION_CLOSE,ft as HOP_BY_HOP_HEADERS,jt as SHUTDOWN_GRACE_MS,pt as INGRESS_HEADERS,vt as syntheticPeerAddress,xt as HEAD_TIMEOUT_MS}from"../../../src-BTTzpNjb.mjs";import{a as TunnelProtocolError,c as encodeWsMessage,i as loadIrohBinding,l as parseRequestHead,n as writeDataFrames,o as decodeWsMessage,r as writeFrame,s as encodeHead,t as FrameReader}from"../../../frames-CVpY1Akq.mjs";import{t as TUNNEL_STAGE_ARG}from"../../../tunnel-ipc-D_tCqdSW.mjs";import{a as loadOrCreateEndpointKey,i as loadKeyFile,n as ed25519PublicKeyHex,o as logFingerprint,r as loadBoundKey,t as KeyFileRefusedError}from"../../../keyfile-mFhV59Tf.mjs";import fs from"node:fs/promises";import net from"node:net";import{once}from"node:events";import http from"node:http";import WebSocket$1 from"ws";
//!src/gateway/openclaw-id/tunnel-child/relay-state.ts
function nextRelayState(e,t){const n=t.some(e=>e.connected);const r=t.find(e=>e.authDeniedReason)?.authDeniedReason??null;return{online:n,denied:n?null:r??e.denied}}
//!src/gateway/openclaw-id/tunnel-child/headers.ts
function upstreamHeaders(e,t,n){const r=e.find(([e])=>e.toLowerCase()===`host`)?.[1];const i={};for(const[t,r]of stripClientHeaders(e,n)){const e=t.toLowerCase();const n=i[e];i[e]=n===void 0?r:[n,r].flat()}i[INGRESS_HEADERS.peerKey]=t.peerKey;i[INGRESS_HEADERS.proxyToken]=t.proxyToken;i[INGRESS_HEADERS.forwardedFor]=t.peerAddress;i[INGRESS_HEADERS.forwardedProto]=t.forwardedProto;if(r){i.host=r;i[INGRESS_HEADERS.forwardedHost]=r}return i}const HOP_BY_HOP=new Set(HOP_BY_HOP_HEADERS);function responseHeaders(e){const t=[];for(let n=0;n+1<e.length;n+=2){const r=e[n];if(!HOP_BY_HOP.has(r.toLowerCase()))t.push([r,e[n+1]])}return t}
//!src/gateway/openclaw-id/tunnel-child/http-proxy.ts
function proxyHttp(e){const{head:t,reader:n,send:r,headers:i,target:a}=e;return new Promise(o=>{let s=false;const fail=e=>{if(s)return;s=true;c.destroy();r.reset(e).catch(()=>{});o(`reset`)};const c=http.request({socketPath:a.socketPath,method:t.method,path:t.path,headers:{...i,"transfer-encoding":`chunked`}});c.setTimeout(e.idleMs??12e4,()=>fail(STREAM_RESET.gateway_unreachable));c.on(`error`,()=>fail(STREAM_RESET.gateway_unreachable));c.on(`response`,e=>{(async()=>{try{await writeFrame(r,encodeHead({status:e.statusCode??502,headers:responseHeaders(e.rawHeaders)}));for await(const t of e)await writeDataFrames(r,t);await r.finish();s=true;o(e.statusCode??502)}catch{fail(STREAM_RESET.gateway_unreachable)}})()});pumpBody(n,c).catch(e=>fail(e instanceof TunnelProtocolError?STREAM_RESET.bad_request:STREAM_RESET.gateway_unreachable))})}async function pumpBody(e,t){for(;;){const n=await e.next(MAX_HTTP_DATA_FRAME_BYTES);if(n===null){t.end();return}if(!t.write(n))await once(t,`drain`)}}
//!src/gateway/openclaw-id/tunnel-child/ws-proxy.ts
const HIGH_WATER=16;const LOW_WATER=4;function proxyWs(e){const{head:t,reader:n,send:r,headers:i,target:a}=e;return new Promise(e=>{const o=new WebSocket$1(`ws://localhost${t.path}`,t.protocols,{createConnection:()=>net.connect(a.socketPath),headers:i,perMessageDeflate:false,handshakeTimeout:1e4,followRedirects:false,maxPayload:33554432});const s=new FrameQueue(r,o);let c=false;o.on(`unexpected-response`,(t,n)=>{n.resume();s.push(encodeHead({status:n.statusCode??502,headers:responseHeaders(n.rawHeaders)}));s.finish().then(()=>e(n.statusCode??502))});o.on(`error`,()=>{if(c){o.terminate();return}r.reset(STREAM_RESET.gateway_unreachable).catch(()=>{});e(`reset`)});o.on(`open`,()=>{c=true;s.push(encodeHead({status:101,protocol:o.protocol||null}));pumpClient(n,o,r).catch(()=>o.terminate())});o.on(`message`,(e,t)=>{const n=Array.isArray(e)?Buffer.concat(e):Buffer.from(e);s.push(encodeWsMessage({op:t?`binary`:`text`,data:n}))});o.on(`close`,(t,n)=>{if(!c)return;s.push(encodeWsMessage({op:`close`,code:t||1005,reason:n.toString()}));s.finish().then(()=>e(101))})})}var FrameQueue=class{constructor(e,t){this.send=e;this.ws=t;this.tail=Promise.resolve();this.pending=0;this.failed=false}push(e){this.pending+=1;if(this.pending>HIGH_WATER)this.ws.pause();this.tail=this.tail.then(()=>this.failed?void 0:writeFrame(this.send,e)).catch(()=>{this.failed=true;this.ws.terminate()}).finally(()=>{this.pending-=1;if(this.pending<=LOW_WATER)this.ws.resume()})}finish(){return this.tail.then(()=>this.failed?void 0:this.send.finish()).catch(()=>{})}};async function pumpClient(e,t,n){for(;;){const r=await e.next();if(r===null){t.terminate();return}let i;try{i=decodeWsMessage(r)}catch{n.reset(STREAM_RESET.bad_request).catch(()=>{});t.terminate();return}if(i.op===`close`){if(isSendableCloseCode(i.code))t.close(i.code,i.reason);else t.close();return}await sendWs(t,i.op===`text`?Buffer.from(i.data).toString(`utf8`):i.data)}}function sendWs(e,t){if(e.readyState!==WebSocket$1.OPEN)return;if(e.bufferedAmount<1<<20){e.send(t);return}return new Promise(n=>{e.send(t,()=>n())})}function isSendableCloseCode(e){return e!==null&&(e>=1e3&&e<=1003||e>=1007&&e<=1014||e>=3e3&&e<=4999)}
//!src/gateway/openclaw-id/tunnel-child/server.ts
const TUNNEL_ALPN_BYTES=new TextEncoder().encode(TUNNEL_ALPN);var IngressServer=class{constructor(e){this.params=e;this.conns=/* @__PURE__ */ new Map;this.admitted=/* @__PURE__ */ new Set;this.stopping=false}setMembership(e){this.admitted=new Set(e);for(const[e,t]of this.conns)if(!this.admitted.has(e)){this.conns.delete(e);for(const e of t)e.close(CONNECTION_CLOSE.revoked,`revoked`);this.params.log(`peer removed: peer=${logFingerprint(hexOf(e))} closed_conns=${t.size}`);this.notifyConnections()}}connectionCount(){let e=0;for(const t of this.conns.values())e+=t.size;return e}async run(){for(;;){let e;try{e=await this.params.endpoint.accept()}catch{continue}if(!e)return;this.handleConnection(e).catch(e=>this.params.log(`connection error: ${short(e)}`))}}async shutdown(){this.stopping=true;for(const e of this.conns.values())for(const t of e)t.close(CONNECTION_CLOSE.shutdown,`shutdown`);this.conns.clear();await Promise.race([this.params.endpoint.close(),new Promise(e=>{setTimeout(e,SHUTDOWN_GRACE_MS).unref()})])}async handleConnection(e){const t=e.remoteId();const n=`iroh:${t}`;const r=logFingerprint(t);if(this.stopping||!this.admitted.has(n)){e.close(CONNECTION_CLOSE.not_a_member,`not a member`);this.params.log(`admission rejected: peer=${r}`);return}e.setMaxConcurrentBiStreams(64);this.track(n,e);this.params.log(`admission allowed: peer=${r} path=${e.pathKind()}`);const i=await syntheticPeerAddress(n);await this.serveStreams(e,n,i,r)}track(e,t){let n=this.conns.get(e);if(!n){n=/* @__PURE__ */ new Set;this.conns.set(e,n)}n.add(t);this.notifyConnections();t.closed().then(()=>{this.conns.get(e)?.delete(t);if(this.conns.get(e)?.size===0)this.conns.delete(e);this.notifyConnections()})}notifyConnections(){this.params.onConnectionsChanged?.(this.connectionCount())}async serveStreams(e,t,n,r){const i=new Slots(64);for(;;){await i.acquire();let a;try{a=await e.acceptBi()}catch{return}this.handleStream(e,a,t,n,r).catch(e=>this.params.log(`stream error peer=${r}: ${short(e)}`)).finally(()=>i.release())}}async handleStream(e,t,n,r,i){const a=new FrameReader(t.recv);const o=await readHead(a);if(!o){await t.send.reset(STREAM_RESET.bad_request).catch(()=>{});return}if(!this.admitted.has(n)){e.close(CONNECTION_CLOSE.revoked,`revoked`);return}const s=upstreamHeaders(o.headers,{peerKey:n,proxyToken:this.params.proxyToken,peerAddress:r,forwardedProto:this.params.forwardedProto},o.kind);const c=Date.now();const l=o.kind===`ws`?await proxyWs({head:o,reader:a,send:t.send,headers:s,target:this.params.target}):await proxyHttp({head:o,reader:a,send:t.send,headers:s,target:this.params.target,idleMs:this.params.idleMs});const u=o.kind===`http`?o.method:`GET`;this.params.log(`${o.kind} peer=${i} ${u} ${o.path.split(`?`)[0]} -> ${l} (${Date.now()-c}ms)`)}};async function readHead(e){let t;try{const n=await Promise.race([e.next(MAX_HEAD_FRAME_BYTES),new Promise((e,n)=>{t=setTimeout(()=>n(/* @__PURE__ */ new Error(`HEAD timeout`)),HEAD_TIMEOUT_MS)})]);if(!n)return null;const r=parseRequestHead(n);return r.path.startsWith(`//`)||hasControlOrSpace(r.path)?null:r}catch{return null}finally{clearTimeout(t)}}function hasControlOrSpace(e){for(let t=0;t<e.length;t+=1){const n=e.charCodeAt(t);if(n<=32||n===127)return true}return false}var Slots=class{constructor(e){this.free=e;this.waiters=[]}acquire(){if(this.free>0){this.free-=1;return Promise.resolve()}return new Promise(e=>{this.waiters.push(e)})}release(){const e=this.waiters.shift();if(e)e();else this.free+=1}};function hexOf(e){return e.startsWith(`iroh:`)?e.slice(5):e}function short(e){return(e instanceof Error?e.message:String(e)).split(`
`)[0].slice(0,160)}
//!src/gateway/openclaw-id/tunnel-child/entry.ts
function log(e){process.stdout.write(`${e}\n`)}function send(e){process.send?.(e)}const owned={stopping:false};async function stop(e){if(owned.stopping)return;owned.stopping=true;process.exitCode=e;try{await(owned.server?owned.server.shutdown():owned.endpoint?.close())}finally{process.removeAllListeners(`message`);process.removeAllListeners(`disconnect`);if(process.connected)process.disconnect?.()}}async function loadEndpointKey(e){if(!e.expectedEndpointKey)return loadOrCreateEndpointKey(e.keyPath);const t=await loadBoundKey(e.keyPath,e.expectedEndpointKey.replace(/^iroh:/,``));if(`refused`in t)return t;if(t.promoted)log(`promoted the staged endpoint key the binding names`);return{key:t.key,created:false}}async function serve(e,t,n){let r;try{r=await loadEndpointKey(t)}catch(e){log(`key refused: ${e.message}`);await stop(e instanceof KeyFileRefusedError?77:1);return}if(`refused`in r){log(`key refused: ${r.refused}`);await stop(r.refused===`keys_missing`?76:75);return}const{key:i,created:a}=r;let o;try{o=await e.bind({secretKey:i,relayUrl:t.relayUrl,alpns:[TUNNEL_ALPN_BYTES],...t.bindAddr?{bindAddr:t.bindAddr}:{}})}finally{i.fill(0)}owned.endpoint=o;if(owned.stopping){await o.close();return}const s=new IngressServer({endpoint:o,target:{socketPath:t.ingress.socketPath},proxyToken:t.ingress.proxyToken,forwardedProto:t.forwardedProto,log,onConnectionsChanged:e=>send({type:`state`,relayOnline:c,connections:e,relayDenied:l})});let c=false;let l=null;const report=()=>send({type:`state`,relayOnline:c,connections:s.connectionCount(),relayDenied:l});followHomeRelay(o,({online:e,denied:t})=>{if(t!==null&&l===null)log(`relay refused this endpoint: ${t}`);else if(e&&!c)log(`relay online`);c=e;l=t;report()});const handle=e=>{if(e.type===`membership`)s.setMembership(e.admitted);else if(e.type===`ping`)send({type:`pong`,id:e.id,rssBytes:process.memoryUsage.rss()})};n(handle);owned.server=s;process.on(`SIGTERM`,()=>void stop(0));process.on(`SIGINT`,()=>void stop(0));const u=o.id();log(`iroh tunnel up: server=${logFingerprint(u)} key=${a?`created`:`loaded`}`);send({type:`ready`,endpointKey:`iroh:${u}`,relayUrl:t.relayUrl,directAddrs:o.boundSockets(),keyCreated:a});await s.run()}function followHomeRelay(e,t){e.watchHomeRelay().then(async e=>{let n={online:false,denied:null};for(let r=await e.next();r;r=await e.next()){const e=nextRelayState(n,r);if(e.online!==n.online||e.denied!==n.denied){n=e;t(n)}}})}async function stage(e){try{if(e.type===`discard`){const t=await loadKeyFile(e.keyPath);const n=t?`iroh:${ed25519PublicKeyHex(t)}`:null;t?.fill(0);if(n&&n!==e.keep)await fs.rm(e.keyPath,{force:true});send({type:`staged`,endpointKey:n===e.keep?n:null})}else{const{key:t}=await loadOrCreateEndpointKey(e.keyPath);send({type:`staged`,endpointKey:`iroh:${ed25519PublicKeyHex(t)}`});t.fill(0)}}catch(e){log(`stage refused: ${e instanceof Error?e.message:String(e)}`);process.exitCode=e instanceof KeyFileRefusedError?77:1}process.disconnect?.()}function main(){if(process.argv.includes(`--stage`)){process.once(`message`,e=>{stage(e)});return}let e;try{e=loadIrohBinding()}catch(e){log(e instanceof Error?e.message:String(e));process.exitCode=78;return}process.on(`disconnect`,()=>void stop(0));const t=[];let n;let r=false;const takeOver=e=>{n=e;t.splice(0).forEach(e)};process.on(`message`,i=>{if(n){n(i);return}if(i.type!==`start`||r){t.push(i);return}r=true;serve(e,i,takeOver).catch(e=>{log(`fatal: ${(e instanceof Error?e.message:String(e)).split(`
`)[0]}`);stop(1)})})}main();export{};