@typhons/sandbox-tools 0.5.9 → 0.5.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/relay-client.js +4 -4
package/package.json
CHANGED
package/relay-client.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`);
|
|
2
|
+
import T from"ws";import G from"http";import p from"fs";import{spawn as W,execSync as _,execFileSync as z}from"child_process";import{dirname as Q}from"path";import{fileURLToPath as Z}from"url";import V from"net";var O=process.env.SESSION_PROXY_SOCK||"/tmp/session-proxy.sock",he=2*1024*1024;var b=1,B=2;function D(e,n){if(!e||e.destroyed)return!1;let t=Buffer.alloc(5);return t[0]=b,t.writeUInt32LE(n.length,1),e.write(t),e.write(n),!0}function C(e,n){if(!e||e.destroyed)return!1;let t=Buffer.from(JSON.stringify(n)),o=Buffer.alloc(5);return o[0]=B,o.writeUInt32LE(t.length,1),e.write(o),e.write(t),!0}var N=class{constructor(n,t){this.onBinary=n,this.onJSON=t,this.buf=Buffer.alloc(0)}feed(n){for(this.buf=this.buf.length?Buffer.concat([this.buf,n]):n;this.buf.length>=5;){let t=this.buf[0],o=this.buf.readUInt32LE(1);if(this.buf.length<5+o)break;let i=this.buf.slice(5,5+o);if(this.buf=this.buf.slice(5+o),t===b)this.onBinary(i);else if(t===B)try{this.onJSON(JSON.parse(i.toString()))}catch(r){console.error(`[ipc] bad JSON: ${r.message}`)}}}};function k(e,{onConnect:n,onClose:t,onError:o,retryMs:i=500}={}){let r=null,l=!1,a=null;function u(){l||(r=V.createConnection(e),r.on("connect",()=>{n&&n(r)}),r.on("close",()=>{r=null,t&&t(),l||(a=setTimeout(u,i))}),r.on("error",A=>{o&&o(A)}))}return u(),{getSocket(){return r},close(){l=!0,a&&clearTimeout(a),r&&r.destroy()}}}import y from"fs";import R from"path";var L="# typhons-managed-hostname";function X(e){let n=e.replace(/\.local$/,"");return`127.0.1.1 ${n===e?e:`${e} ${n}`} ${L}`}function j(e,n,t){let o=R.dirname(e),i=R.basename(e),r=R.join(o,`.${i}.tmp.${process.pid}.${Date.now()}`);try{y.writeFileSync(r,n,{mode:t})}catch{try{y.unlinkSync(r)}catch{}return!1}try{return y.renameSync(r,e),!0}catch{try{y.unlinkSync(r)}catch{}return!1}}function H(e,n="/etc/hosts"){let t=X(e),o="",i=420;try{o=y.readFileSync(n,"utf8"),i=y.statSync(n).mode&511}catch{}let r=o.split(`
|
|
3
|
+
`);r.length>0&&r[r.length-1]===""&&r.pop();let l=r.filter(u=>!u.includes(L));l.push(t);let a=l.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`;
|
|
6
|
-
`)}catch{}try{H(n)}catch(t){
|
|
5
|
+
`;return a===o?!1:(j(n,a,i)||y.writeFileSync(n,a,{mode:i}),!0)}var xe=Q(Z(import.meta.url));process.on("uncaughtException",e=>{console.error(`[relay-client] UNCAUGHT: ${e.message}`),console.error(e.stack)});process.on("unhandledRejection",e=>{console.error(`[relay-client] UNHANDLED REJECTION: ${e.message||e}`)});var q=process.env.RELAY_HOST||"ssh.typhons.dev",ee=process.env.RELAY_SCHEME||"wss",I=process.env.E2B_RUN_DIR||"/run/e2b",te=`${I}/.RELAY_TOKEN`,ne=`${I}/.E2B_SANDBOX_ID`,P=`${I}/.SAVED_SANDBOX_ID`,re=`${I}/.DEVBOX_NAME`,oe=parseInt(process.env.RELAY_CLIENT_RECONNECT_DELAY_MS||"1500",10),ie=3e3,U=15e3,ce=6e4,F=parseInt(process.env.RELAY_CLIENT_VERIFY_REJECT_RETRY_MS||"10000",10),Y="@typhons/sandbox-tools",se=process.env.RELAY_CLIENT_DISABLE_UPDATE==="1",$=parseInt(process.env.KEEPALIVE_PORT||"49999");function ae(){try{return p.readFileSync(te,"utf8").trim()}catch{}return""}function x(){try{return p.readFileSync(ne,"utf8").trim()}catch{}return"unknown"}function c(e){console.log(`[relay-client ${new Date().toISOString().slice(11,19)}] ${e}`)}var E="unknown";function le(){if(process.env.RELAY_URL)return process.env.RELAY_URL;E=x();try{let e=p.readFileSync(P,"utf8").trim();if(e&&e!==E){c(`Clone detected (${e} -> ${E}), interrupting agents...`);try{_("/opt/sandbox/bin/stop-agents",{timeout:1e4,stdio:"inherit"})}catch{}try{p.writeFileSync(P,E)}catch{}}}catch{}return`${ee}://${q}/tunnel/${E}`}var h=null,v=null;function ue(){return k(O,{onConnect(n){c("Connected to session-proxy via IPC"),h=n,v=new N(t=>{s&&s.readyState===T.OPEN&&s.send(t)},t=>{s&&s.readyState===T.OPEN&&s.send(JSON.stringify(t))}),n.on("data",t=>v.feed(t))},onClose(){c("IPC connection to session-proxy lost, will retry..."),h=null,v=null},onError(n){n.code!=="ENOENT"&&n.code!=="ECONNREFUSED"&&c(`IPC error: ${n.message}`)}})}var s=null,w=null,d=0,g=null;function J(e=oe){if(s){try{s.terminate()}catch{}s=null}g&&(clearTimeout(g),g=null),g=setTimeout(()=>{g=null,M()},e)}function M(){let e=++d,n=le();c(`Connecting to ${n}... (gen=${e}, sandbox=${E})`);let t={},o=ae();if(o&&(t.Authorization=`Bearer ${o}`),s){try{s.terminate()}catch{}s=null}let i=new T(n,{headers:t});s=i;let r=null,l=!0,a=setTimeout(()=>{if(e===d){c(`Handshake timeout after ${U}ms \u2014 aborting and reconnecting`);try{i.terminate()}catch{}u()}},U);function u(){a&&(clearTimeout(a),a=null),r&&(clearInterval(r),r=null),e===d&&J()}function A(){l=!0,r=setInterval(()=>{if(e!==d){clearInterval(r);return}if(!l){c("No pong received \u2014 connection dead, reconnecting"),u();return}l=!1;try{i.ping()}catch{u()}},ie)}i.on("open",()=>{if(e!==d){i.terminate();return}a&&(clearTimeout(a),a=null),c(`Connected${w?` (reconnect, port ${w})`:""} (gen=${e})`),A()}),i.on("pong",()=>{e===d&&(l=!0)}),i.on("message",(f,m)=>{if(e===d){if(!m){try{de(JSON.parse(f.toString()))}catch(S){c(`Bad control msg: ${S.message}`)}return}h&&!h.destroyed&&D(h,Buffer.from(f))}}),i.on("close",(f,m)=>{if(e!==d)return;let S=m?m.toString():"";if(f===4100&&(c(`Replaced by newer connection (code 4100, reason=${S}) \u2014 exiting`),process.exit(42)),f===4101){c(`Identity verification rejected (code 4101, reason=${S}) \u2014 retrying in ${F}ms (likely waiting for envd to update /run/e2b/.E2B_SANDBOX_ID)`),a&&(clearTimeout(a),a=null),r&&(clearInterval(r),r=null),e===d&&J(F);return}c(`Data WS closed: code=${f}, reason=${S}`),u()}),i.on("error",f=>{e===d&&(c(`Data WS error: ${f.message} (code=${f.code||"none"})`),u())}),i.on("unexpected-response",(f,m)=>{e===d&&(c(`Data WS unexpected response: status=${m.statusCode}`),u())})}function de(e){if(e.type==="port"){w=e.port,c(`Assigned port ${e.port}`);return}if(e.type==="name"){if(c(`Name assigned: ${e.name}`),e.name&&/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(e.name)){let n=`${e.name}.local`;try{z("hostname",[n],{timeout:5e3,stdio:"ignore"}),p.writeFileSync("/etc/hostname",n+`
|
|
6
|
+
`)}catch{}try{H(n)&&c(`Updated /etc/hosts entry for ${n}`)}catch(t){c(`Failed to update /etc/hosts: ${t.message}`)}try{p.writeFileSync(re,e.name)}catch{}}return}h&&!h.destroyed&&C(h,e)}function K(){try{let e=_(`npm view ${Y} version 2>/dev/null`,{timeout:15e3}).toString().trim();if(!e)return;let n="";try{n=JSON.parse(p.readFileSync("/opt/sandbox/lib/node_modules/@typhons/sandbox-tools/package.json","utf8")).version||""}catch{return}if(e!==n){c(`Update available: ${n} \u2192 ${e}, installing...`),_(`npm install -g --prefix /opt/sandbox ${Y}@latest`,{timeout:12e4,stdio:"inherit"});try{_('pkill -f "check-claude-active.*--daemon" 2>/dev/null',{shell:!0,timeout:5e3})}catch{}try{let t=p.openSync("/tmp/claude-keepalive.log","a");W("/opt/sandbox/bin/check-claude-active",["--daemon"],{detached:!0,stdio:["ignore",t,t]}).unref(),p.closeSync(t)}catch{}c("Update installed, exiting for restart..."),process.exit(0)}}catch{}}function fe(){let e=G.createServer((t,o)=>{if(o.setHeader("Content-Type","application/json"),t.method==="GET"&&t.url==="/health"){o.end(JSON.stringify({ok:!0,sandboxId:x(),wsConnected:!!(s&&s.readyState===T.OPEN)}));return}if(t.method==="POST"&&t.url==="/_relay/verify"){let i="";t.on("data",r=>{i+=r,i.length>4096&&t.destroy()}),t.on("end",()=>{let r;try{r=JSON.parse(i).nonce}catch{o.writeHead(400),o.end('{"error":"bad json"}');return}if(typeof r!="string"||!r.length||r.length>256){o.writeHead(400),o.end('{"error":"missing or invalid nonce"}');return}if(!s||s.readyState!==T.OPEN){o.writeHead(503),o.end('{"error":"WS not connected"}');return}try{s.send(JSON.stringify({type:"verify-ack",nonce:r}))}catch(l){o.writeHead(500),o.end(`{"error":"${l.message}"}`);return}o.writeHead(200),o.end('{"ok":true}')}),t.on("error",()=>{try{o.writeHead(400),o.end('{"error":"req error"}')}catch{}});return}o.writeHead(404),o.end('{"error":"not found"}')}),n=!1;return e.on("error",t=>{if(t.code==="EADDRINUSE"&&!n){n=!0,c(`Port ${$} held by another process \u2014 killing it (likely a pre-0.5.5 session-proxy that owned this port; watchdog will restart it under new code which no longer binds it)`);try{_("pkill -f /opt/sandbox/lib/node_modules/@typhons/sandbox-tools/session-proxy.js",{timeout:3e3})}catch{}setTimeout(()=>{try{e.listen($,"0.0.0.0")}catch{}},1500);return}c(`Keepalive HTTP server error: ${t.message}`)}),e.listen($,"0.0.0.0",()=>{c(`Keepalive HTTP server on :${$}`)}),e}var Oe=ue();fe();M();se||(setTimeout(K,1e4),setInterval(K,ce));c(`Relay client started (sandbox=${x()})`);
|