@typhons/sandbox-tools 0.6.0 → 0.6.3
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 +9 -9
- package/typhons-share-mount.js +4 -4
package/package.json
CHANGED
package/relay-client.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import A from"ws";import
|
|
3
|
-
`);o.length>0&&o[o.length-1]===""&&o.pop();let l=o.filter(
|
|
2
|
+
import A from"ws";import Ne from"http";import a from"fs";import N from"path";import be from"crypto";import{spawn as ae,execSync as $,execFileSync as Re}from"child_process";import{dirname as le}from"path";import{fileURLToPath as ue}from"url";import Se from"net";var Y=process.env.SESSION_PROXY_SOCK||"/tmp/session-proxy.sock",Ge=2*1024*1024;var J=1,j=2;function K(e,n){if(!e||e.destroyed)return!1;let t=Buffer.alloc(5);return t[0]=J,t.writeUInt32LE(n.length,1),e.write(t),e.write(n),!0}function W(e,n){if(!e||e.destroyed)return!1;let t=Buffer.from(JSON.stringify(n)),r=Buffer.alloc(5);return r[0]=j,r.writeUInt32LE(t.length,1),e.write(r),e.write(t),!0}var v=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],r=this.buf.readUInt32LE(1);if(this.buf.length<5+r)break;let s=this.buf.slice(5,5+r);if(this.buf=this.buf.slice(5+r),t===J)this.onBinary(s);else if(t===j)try{this.onJSON(JSON.parse(s.toString()))}catch(o){console.error(`[ipc] bad JSON: ${o.message}`)}}}};function G(e,{onConnect:n,onClose:t,onError:r,retryMs:s=500}={}){let o=null,l=!1,i=null;function u(){l||(o=Se.createConnection(e),o.on("connect",()=>{n&&n(o)}),o.on("close",()=>{o=null,t&&t(),l||(i=setTimeout(u,s))}),o.on("error",_=>{r&&r(_)}))}return u(),{getSocket(){return o},close(){l=!0,i&&clearTimeout(i),o&&o.destroy()}}}import E from"fs";import x from"path";var V="# typhons-managed-hostname";function Ee(e){let n=e.replace(/\.local$/,"");return`127.0.1.1 ${n===e?e:`${e} ${n}`} ${V}`}function ge(e,n,t){let r=x.dirname(e),s=x.basename(e),o=x.join(r,`.${s}.tmp.${process.pid}.${Date.now()}`);try{E.writeFileSync(o,n,{mode:t})}catch{try{E.unlinkSync(o)}catch{}return!1}try{return E.renameSync(o,e),!0}catch{try{E.unlinkSync(o)}catch{}return!1}}function X(e,n="/etc/hosts"){let t=Ee(e),r="",s=420;try{r=E.readFileSync(n,"utf8"),s=E.statSync(n).mode&511}catch{}let o=r.split(`
|
|
3
|
+
`);o.length>0&&o[o.length-1]===""&&o.pop();let l=o.filter(u=>!u.includes(V));l.push(t);let i=l.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`;return i===r?!1:(
|
|
6
|
-
`)}function
|
|
5
|
+
`;return i===r?!1:(ge(n,i,s)||E.writeFileSync(n,i,{mode:s}),!0)}import p from"node:fs";import z from"node:path";var Z="<!-- typhons-public-url -->",Q="<!-- /typhons-public-url -->",q="d.typhons.dev",_e=[{dir:".claude",file:"CLAUDE.md"},{dir:".codex",file:"AGENTS.md"}];function Te(e,n=q){let t=`https://${e}.${n}`;return[Z,`This server is publicly reachable at ${t}:<PORT>`,"(where <PORT> is whatever local port your dev server binds to \u2014 e.g.",`${t}:3000 for a server bound to :3000). When you stand something up`,"or want the user to test, hand them that URL \u2014 they can't reach","localhost inside this sandbox, but they can reach the public URL.","","After making changes, link the user to the dev server when applicable so they can test.",Q].join(`
|
|
6
|
+
`)}function $e(e,n){let t=new RegExp(`${Z}[\\s\\S]*?${Q}`,"m");if(t.test(e))return e.replace(t,n);let r=e?e.endsWith(`
|
|
7
7
|
|
|
8
8
|
`)?"":e.endsWith(`
|
|
9
9
|
`)?`
|
|
10
10
|
`:`
|
|
11
11
|
|
|
12
12
|
`:"";return e+r+n+`
|
|
13
|
-
`}function
|
|
14
|
-
`)){let r=
|
|
15
|
-
`)){let t=n.match(/^([A-Z_]+)=(.*)$/);t&&(e[t[1]]=t[2])}}catch{}return e}function
|
|
16
|
-
`)}catch{}try{
|
|
13
|
+
`}function Ae(){let e=[];try{p.existsSync("/root")&&e.push("/root")}catch{}try{for(let n of p.readdirSync("/home")){let t=`/home/${n}`;try{p.statSync(t).isDirectory()&&e.push(t)}catch{}}}catch{}return e}function ee(e,n=q,t=r=>process.stderr.write(r+`
|
|
14
|
+
`)){let r=Te(e,n),s=typeof process.getuid=="function"?process.getuid():0;for(let o of Ae()){let l=0,i=0;try{let u=p.statSync(o);l=u.uid,i=u.gid}catch{continue}if(!(s!==0&&l!==s))for(let{dir:u,file:_}of _e){let d=z.join(o,u),h=z.join(d,_);try{let m=p.existsSync(d);m||p.mkdirSync(d,{recursive:!0});let F=p.existsSync(h)?p.readFileSync(h,"utf8"):"",M=$e(F,r);M!==F&&p.writeFileSync(h,M);try{m||p.chownSync(d,l,i)}catch{}try{p.chownSync(h,l,i)}catch{}}catch(m){try{t(`[agent-md] ${h}: ${m.message}`)}catch{}}}}}var pt=le(ue(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 ve=process.env.RELAY_HOST||"ssh.typhons.dev",we=process.env.RELAY_SCHEME||"wss",b=process.env.E2B_RUN_DIR||"/run/e2b",Ie=`${b}/.RELAY_TOKEN`,Oe=`${b}/.E2B_SANDBOX_ID`,te=`${b}/.SAVED_SANDBOX_ID`,xe=`${b}/.DEVBOX_NAME`,De=parseInt(process.env.RELAY_CLIENT_RECONNECT_DELAY_MS||"1500",10),He=3e3,ne=15e3,ke=6e4,re=parseInt(process.env.RELAY_CLIENT_VERIFY_REJECT_RETRY_MS||"10000",10),oe="@typhons/sandbox-tools",Ce=process.env.RELAY_CLIENT_DISABLE_UPDATE==="1",w=parseInt(process.env.KEEPALIVE_PORT||"49999");function I(){try{return a.readFileSync(Ie,"utf8").trim()}catch{}return""}function Pe(e){return"tt1_"+be.createHmac("sha256",e).update("typhons:tunnel").digest("hex")}var D=!1,Be=`${b}/.TYPHONS_SHARED_MOUNT`;function L(){let e={};try{for(let n of a.readFileSync(Be,"utf8").split(`
|
|
15
|
+
`)){let t=n.match(/^([A-Z_]+)=(.*)$/);t&&(e[t[1]]=t[2])}}catch{}return e}function R(){return(process.env.TYPHONS_SHARE_CREDENTIALS??L().TYPHONS_SHARE_CREDENTIALS)!=="0"}function Le(){try{return a.readFileSync("/proc/mounts","utf8").includes(`/${fe} fuse.rclone`)}catch{return!1}}function O(){if(R())try{let e=N.join(le(ue(import.meta.url)),"typhons-share-mount.js"),[n,t]=a.existsSync(e)?[process.execPath,[e]]:["/opt/sandbox/bin/typhons-share-mount",[]],r=ae(n,t,{stdio:["ignore","inherit","inherit"],detached:!0,env:{...L(),...process.env}});r.on("error",s=>c(`typhons-share-mount spawn failed: ${s.message}`)),r.unref()}catch(e){c(`typhons-share-mount failed to start: ${e.message}`)}}var de=[".claude/.credentials.json",".config/gh/hosts.yml",".codex/auth.json"],fe=".typhons-shared-mount";function P(e,n){try{let t=a.realpathSync(N.join(e,fe)),r=a.realpathSync(N.dirname(n));return r===t||r.startsWith(t+"/")}catch{return!1}}function he(){let e=["/root"];try{e.push(...a.readdirSync("/home").map(n=>`/home/${n}`))}catch{}return e.filter(n=>{try{return a.existsSync(`${n}/.config/typhons-share/rclone.conf`)}catch{return!1}})}var H=null;function pe(e){H||(c(`${e} replaced by a regular file (login?) \u2014 folding into the share`),H=setTimeout(()=>{H=null,O()},300))}var k=new Set;function Ue(){if(R())for(let e of he())for(let n of de){let t=`${e}/${n}`,r=N.dirname(t),s=N.basename(t);if(!(k.has(r)||!a.existsSync(r))&&!P(e,t))try{let o=a.watch(r,(l,i)=>{if(i===s)try{a.lstatSync(t).isFile()&&!P(e,t)&&pe(t)}catch{}});o.on("error",()=>{k.delete(r);try{o.close()}catch{}}),k.add(r)}catch{}}}function Fe(){if(Ue(),!!R())try{for(let e of he())for(let n of de)try{if(a.lstatSync(`${e}/${n}`).isFile()&&!P(e,`${e}/${n}`)){pe(`${e}/${n}`);return}}catch{}}catch{}}setInterval(Fe,1e4);function Me(){!R()||!I()||Le()||O()}setInterval(Me,18e4);function ye(e=0){if((process.env.TYPHONS_SHARE_CREDENTIALS??L().TYPHONS_SHARE_CREDENTIALS)!=="0"){if(!R()||!I()){e<120?setTimeout(()=>ye(e+1),500):c("share mount boot kick: gave up waiting for token/config");return}c("share mount boot kick: starting typhons-share-mount"),O()}}function U(){try{return a.readFileSync(Oe,"utf8").trim()}catch{}return"unknown"}function c(e){console.log(`[relay-client ${new Date().toISOString().slice(11,19)}] ${e}`)}var ce=process.env.AGENT_MD_HTTP_DOMAIN||"d.typhons.dev",g="unknown";function Ye(){if(process.env.RELAY_URL)return process.env.RELAY_URL;g=U();try{let e=a.readFileSync(te,"utf8").trim();if(e&&e!==g){c(`Clone detected (${e} -> ${g}), interrupting agents...`);try{$("/opt/sandbox/bin/stop-agents",{timeout:1e4,stdio:"inherit"})}catch{}try{a.writeFileSync(te,g)}catch{}}}catch{}return`${we}://${ve}/tunnel/${g}`}var S=null,C=null;function Je(){return G(Y,{onConnect(n){c("Connected to session-proxy via IPC"),S=n,C=new v(t=>{f&&f.readyState===A.OPEN&&f.send(t)},t=>{f&&f.readyState===A.OPEN&&f.send(JSON.stringify(t))}),n.on("data",t=>C.feed(t))},onClose(){c("IPC connection to session-proxy lost, will retry..."),S=null,C=null},onError(n){n.code!=="ENOENT"&&n.code!=="ECONNREFUSED"&&c(`IPC error: ${n.message}`)}})}var f=null,B=null,y=0,T=null;function se(e=De){if(f){try{f.terminate()}catch{}f=null}T&&(clearTimeout(T),T=null),T=setTimeout(()=>{T=null,me()},e)}function me(){let e=++y,n=Ye();c(`Connecting to ${n}... (gen=${e}, sandbox=${g})`);let t={},r=I();if(r){let d=D?r:Pe(r);t.Authorization=`Bearer ${d}`}if(f){try{f.terminate()}catch{}f=null}let s=new A(n,{headers:t});f=s;let o=null,l=!0,i=setTimeout(()=>{if(e===y){c(`Handshake timeout after ${ne}ms \u2014 aborting and reconnecting`);try{s.terminate()}catch{}u()}},ne);function u(){i&&(clearTimeout(i),i=null),o&&(clearInterval(o),o=null),e===y&&se()}function _(){l=!0,o=setInterval(()=>{if(e!==y){clearInterval(o);return}if(!l){c("No pong received \u2014 connection dead, reconnecting"),u();return}l=!1;try{s.ping()}catch{u()}},He)}s.on("open",()=>{if(e!==y){s.terminate();return}i&&(clearTimeout(i),i=null),c(`Connected${B?` (reconnect, port ${B})`:""} (gen=${e})`),_()}),s.on("pong",()=>{e===y&&(l=!0)}),s.on("message",(d,h)=>{if(e===y){if(!h){try{je(JSON.parse(d.toString()))}catch(m){c(`Bad control msg: ${m.message}`)}return}S&&!S.destroyed&&K(S,Buffer.from(d))}}),s.on("close",(d,h)=>{if(e!==y)return;let m=h?h.toString():"";if(d===4100&&(c(`Replaced by newer connection (code 4100, reason=${m}) \u2014 exiting`),process.exit(42)),d===4101){c(`Identity verification rejected (code 4101, reason=${m}) \u2014 retrying in ${re}ms (likely waiting for envd to update /run/e2b/.E2B_SANDBOX_ID)`),i&&(clearTimeout(i),i=null),o&&(clearInterval(o),o=null),e===y&&se(re);return}if(d===4001&&!D&&I()){c("Derived tunnel token rejected (4001) \u2014 falling back to raw relay token"),D=!0,u();return}c(`Data WS closed: code=${d}, reason=${m}`),u()}),s.on("error",d=>{e===y&&(c(`Data WS error: ${d.message} (code=${d.code||"none"})`),u())}),s.on("unexpected-response",(d,h)=>{e===y&&(c(`Data WS unexpected response: status=${h.statusCode}`),u())})}function je(e){if(e.type==="port"){B=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{Re("hostname",[n],{timeout:5e3,stdio:"ignore"}),a.writeFileSync("/etc/hostname",n+`
|
|
16
|
+
`)}catch{}try{X(n)&&c(`Updated /etc/hosts entry for ${n}`)}catch(t){c(`Failed to update /etc/hosts: ${t.message}`)}try{a.writeFileSync(xe,e.name)}catch{}try{ee(e.name,ce,c)}catch(t){c(`updateAgentMd failed: ${t.message}`)}try{let t=`${e.name}.${ce}`,r=`https://${t}`;a.writeFileSync("/etc/profile.d/typhons.sh",`export TYPHONS_HOST=${JSON.stringify(t)}
|
|
17
17
|
export TYPHONS_URL=${JSON.stringify(r)}
|
|
18
|
-
`,{mode:420})}catch(t){
|
|
18
|
+
`,{mode:420})}catch(t){c(`Failed to write /etc/profile.d/typhons.sh: ${t.message}`)}O()}return}S&&!S.destroyed&&W(S,e)}function ie(){try{let e=$(`npm view ${oe} version 2>/dev/null`,{timeout:15e3}).toString().trim();if(!e)return;let n="";try{n=JSON.parse(a.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 ${oe}@latest`,{timeout:12e4,stdio:"inherit"});try{$('pkill -f "check-claude-active.*--daemon" 2>/dev/null',{shell:!0,timeout:5e3})}catch{}try{let t=a.openSync("/tmp/claude-keepalive.log","a");ae("/opt/sandbox/bin/check-claude-active",["--daemon"],{detached:!0,stdio:["ignore",t,t]}).unref(),a.closeSync(t)}catch{}c("Update installed, exiting for restart..."),process.exit(0)}}catch{}}function Ke(){let e=Ne.createServer((t,r)=>{if(r.setHeader("Content-Type","application/json"),t.method==="GET"&&t.url==="/health"){r.end(JSON.stringify({ok:!0,sandboxId:U(),wsConnected:!!(f&&f.readyState===A.OPEN)}));return}if(t.method==="POST"&&t.url==="/_relay/verify"){let s="";t.on("data",o=>{s+=o,s.length>4096&&t.destroy()}),t.on("end",()=>{let o;try{o=JSON.parse(s).nonce}catch{r.writeHead(400),r.end('{"error":"bad json"}');return}if(typeof o!="string"||!o.length||o.length>256){r.writeHead(400),r.end('{"error":"missing or invalid nonce"}');return}if(!f||f.readyState!==A.OPEN){r.writeHead(503),r.end('{"error":"WS not connected"}');return}try{f.send(JSON.stringify({type:"verify-ack",nonce:o}))}catch(l){r.writeHead(500),r.end(`{"error":"${l.message}"}`);return}r.writeHead(200),r.end('{"ok":true}')}),t.on("error",()=>{try{r.writeHead(400),r.end('{"error":"req error"}')}catch{}});return}r.writeHead(404),r.end('{"error":"not found"}')}),n=!1;return e.on("error",t=>{if(t.code==="EADDRINUSE"&&!n){n=!0,c(`Port ${w} 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(w,"0.0.0.0")}catch{}},1500);return}c(`Keepalive HTTP server error: ${t.message}`)}),e.listen(w,"0.0.0.0",()=>{c(`Keepalive HTTP server on :${w}`)}),e}var yt=Je();Ke();me();Ce||(setTimeout(ie,1e4),setInterval(ie,ke));c(`Relay client started (sandbox=${U()})`);ye();
|
package/typhons-share-mount.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import r from"fs";import
|
|
2
|
+
import r from"fs";import S from"os";import i from"path";import E from"crypto";import{execFileSync as w,spawn as j,spawnSync as h}from"child_process";var _=".typhons-shared-mount",v=`${process.env.E2B_RUN_DIR||"/run/e2b"}/.RELAY_TOKEN`,F="/run/e2b/.TYPHONS_SHARED_MOUNT",O=2e4;function P(e){if(process.env[e]!==void 0)return process.env[e];try{let t=r.readFileSync(F,"utf8").match(new RegExp(`^${e}=(.*)$`,"m"));if(t)return t[1]}catch{}}var L=()=>P("TYPHONS_SERVER_URL")||"https://www.typhons.dev",Y=[{from:".claude/.credentials.json",to:"claude/credentials.json"},{from:".config/gh/hosts.yml",to:"gh/hosts.yml"},{from:".codex/auth.json",to:"codex/auth.json"}];function s(e){console.error(`[typhons-share ${new Date().toISOString().slice(11,19)}] ${e}`)}var C=Buffer.from([156,147,91,72,115,10,85,77,107,253,124,99,200,134,169,43,211,144,25,142,184,18,138,251,244,222,22,43,139,149,246,56]);function q(e){let t=E.randomBytes(16),n=E.createCipheriv("aes-256-ctr",C,t),o=Buffer.concat([n.update(e,"utf8"),n.final()]);return Buffer.concat([t,o]).toString("base64url")}function B(e){return`# Managed by typhons-share-mount \u2014 do not edit.
|
|
3
3
|
[b2]
|
|
4
4
|
type = b2
|
|
5
5
|
account = ${e.key_id}
|
|
@@ -9,6 +9,6 @@ hard_delete = true
|
|
|
9
9
|
[share]
|
|
10
10
|
type = crypt
|
|
11
11
|
remote = b2:${e.bucket}/${e.prefix}
|
|
12
|
-
password = ${
|
|
13
|
-
`}function
|
|
14
|
-
`);for(let n of t){let o=n.split(/\s+/);if(o[1]===e)return{type:o[2],options:o[3]||""}}}catch{}return null}function
|
|
12
|
+
password = ${q(e.crypt_password)}
|
|
13
|
+
`}function I(e,t,n=384){r.mkdirSync(i.dirname(e),{recursive:!0,mode:448});let o=`${e}.tmp.${process.pid}`;r.writeFileSync(o,t,{mode:n}),r.renameSync(o,e)}function y(e){try{let t=r.readFileSync("/proc/mounts","utf8").split(`
|
|
14
|
+
`);for(let n of t){let o=n.split(/\s+/);if(o[1]===e)return{type:o[2],options:o[3]||""}}}catch{}return null}function b(e){return h("stat",["-f",e],{timeout:5e3,stdio:"ignore"}).status===0}function M(e){for(let[t,n]of[["fusermount3",["-uz",e]],["fusermount",["-uz",e]],["umount",["-l",e]]])try{return w(t,n,{stdio:"ignore",timeout:5e3}),!0}catch{}return!1}function U(e,t){try{return r.readFileSync(e).equals(r.readFileSync(t))}catch{return!1}}function N(e,t){if(r.copyFileSync(e,t),!U(e,t))throw new Error("readback mismatch after copy")}function R(e,t){let n=`${t}.tmp-link.${process.pid}`;try{r.unlinkSync(n)}catch{}return r.symlinkSync(e,n),n}function T(e,t,n=Y){let o=[],u=t;try{u=r.realpathSync(t)}catch{}for(let{from:c,to:f}of n){let a=i.join(e,c),l=i.join(t,f),d="none";try{let m=null;try{m=r.realpathSync(i.dirname(a))}catch{}if(m&&(m===u||m.startsWith(u+i.sep))){o.push({from:c,action:"already-in-mount"});continue}r.mkdirSync(i.dirname(l),{recursive:!0,mode:448}),r.mkdirSync(i.dirname(a),{recursive:!0,mode:448});let p=null;try{p=r.lstatSync(a)}catch{}if(p?.isSymbolicLink())r.readlinkSync(a)!==l&&(r.renameSync(R(l,a),a),d="relinked");else if(p){let x=null;try{x=r.statSync(l)}catch{}x?U(a,l)?d="already-synced":p.mtimeMs>x.mtimeMs?(N(a,l),d="migrated-newer-local"):d="kept-newer-remote":(N(a,l),d="migrated");let D=R(l,a),k=`${a}.pre-share.bak`;r.existsSync(k)&&(k=`${a}.pre-share.${Date.now()}.bak`),r.renameSync(a,k),r.renameSync(D,a)}else r.symlinkSync(l,a),d="linked";d!=="none"&&d!=="already-synced"&&s(`${c}: ${d}`),o.push({from:c,action:d})}catch(m){try{r.unlinkSync(`${a}.tmp-link.${process.pid}`)}catch{}s(`${c}: migration failed, leaving local file in place: ${m.message}`),o.push({from:c,action:"failed",error:m.message})}}return o}function A(e,t){try{if(!JSON.parse(r.readFileSync(i.join(t,"claude","credentials.json"),"utf8"))?.claudeAiOauth?.accessToken)return!1}catch{return!1}try{let n=i.join(e,".claude.json"),o={};try{o=JSON.parse(r.readFileSync(n,"utf8"))}catch{}return o.hasCompletedOnboarding?!1:(o.theme=o.theme||"dark",o.hasCompletedOnboarding=!0,o.lastOnboardingVersion=o.lastOnboardingVersion||"2.1.0",I(n,JSON.stringify(o,null,2)),s("marked claude onboarding complete (shared login present)"),!0)}catch(n){return s(`onboarding skip failed: ${n.message}`),!1}}function J(e){return"mt1_"+E.createHmac("sha256",e).update("typhons:mount").digest("hex")}function H(e){return fetch(`${L()}/api/typhons-share/token`,{method:"POST",headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(2e4)})}async function K(){if(process.env.TYPHONS_SHARE_TOKEN_JSON){let n=JSON.parse(process.env.TYPHONS_SHARE_TOKEN_JSON);return s(n?`using pre-fetched credentials (prefix=${n.prefix})`:"running credential-less (healing with the existing config)"),n}let e;try{e=r.readFileSync(v,"utf8").trim()}catch{}if(!e)throw new Error(`no tunnel token at ${v}`);let t=await H(J(e));if(t.status===401&&(t=await H(e),t.ok&&s("authenticated via raw-token fallback (pre-derivation server)")),!t.ok){let n=await t.text().catch(()=>"");throw new Error(`credential fetch failed: HTTP ${t.status} ${n.slice(0,200)}`)}return await t.json()}function z(e){let t=w("getent",["passwd",e],{timeout:5e3}).toString().trim().split(":");return{uid:Number(t[2]),gid:Number(t[3]),home:t[5]}}function V(){let e=[];for(let[o,u]of[["rclone","rclone"],["fusermount3","fuse3"]])h("sh",["-c",`command -v ${o}`],{stdio:"ignore"}).status===0||e.push(u);try{r.existsSync("/dev/fuse")||w("mknod",["/dev/fuse","c","10","229"],{timeout:5e3}),(r.statSync("/dev/fuse").mode&438)!==438&&r.chmodSync("/dev/fuse",438)}catch(o){s(`could not prepare /dev/fuse: ${o.message}`)}if(r.existsSync("/etc/ssl/certs/ca-certificates.crt")||e.push("ca-certificates"),!e.length)return;s(`installing missing packages: ${e.join(" ")}`);let t={...process.env,DEBIAN_FRONTEND:"noninteractive"};h("apt-get",["update","-qq"],{stdio:"ignore",timeout:12e4,env:t});let n=h("apt-get",["install","-y","-qq","--no-install-recommends",...e],{stdio:"ignore",timeout:18e4,env:t});n.status!==0&&s(`apt-get install failed (status ${n.status}) \u2014 mount will likely fail`)}function W(e){let t=y(e);if(!t)return;Number(t.options.match(/user_id=(\d+)/)?.[1]??0)===0&&(s(`unmounting legacy root-owned mount at ${e}`),M(e))}async function $(e,{home:t}={}){t=t||S.homedir();let n=i.join(t,_),o=i.join(t,".config","typhons-share","rclone.conf"),u=i.join(t,".cache","typhons-share");if(e)I(o,B(e));else if(!r.existsSync(o))return s("no credentials and no existing rclone config \u2014 nothing to do"),{mounted:!1,reason:"no-config"};if(r.mkdirSync(n,{recursive:!0,mode:493}),r.mkdirSync(u,{recursive:!0,mode:448}),y(n)&&b(n))return T(t,n),A(t,n),s(`mount healthy at ${n}`),{mounted:!0,reason:"already-healthy"};y(n)&&(s(`dead mount at ${n}; lazy-unmounting`),M(n));let c=["mount","share:",n,"--config",o,"--vfs-cache-mode","full","--vfs-cache-max-size","512M","--cache-dir",u,"--vfs-write-back","1s","--dir-cache-time","5s","--file-perms","0600","--dir-perms","0700","--low-level-retries","7","--contimeout","15s","--timeout","30s","--log-level","INFO","--log-file",i.join(u,"rclone.log")];s(`mounting: rclone ${c.join(" ")}`);let f=j("rclone",c,{stdio:"ignore",detached:!0});f.on("error",l=>s(`rclone spawn failed: ${l.message}`)),f.unref();let a=Date.now()+O;for(;Date.now()<a;){if(y(n)&&b(n))return T(t,n),A(t,n),s(`mount live at ${n}`),{mounted:!0,reason:"fresh-mount"};await new Promise(l=>setTimeout(l,100))}return s(`mount did not come up within ${O/1e3}s (see ${u}/rclone.log)`),{mounted:!1,reason:"mount-timeout"}}var g="/tmp/typhons-share-mount.lock";function G(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function X(){for(let e=0;e<2;e++)try{let t=r.openSync(g,"wx");return r.writeSync(t,String(process.pid)),r.closeSync(t),!0}catch(t){if(t.code!=="EEXIST")return!0;let n=0;try{n=parseInt(r.readFileSync(g,"utf8"),10)}catch{}if(n&&G(n))return!1;try{r.unlinkSync(g)}catch{}}return!1}function Q(){try{r.unlinkSync(g)}catch{}}async function Z(){if(P("TYPHONS_SHARE_CREDENTIALS")==="0")return s("TYPHONS_SHARE_CREDENTIALS=0 \u2014 skipping"),{mounted:!1,reason:"opted-out"};if(S.userInfo().uid===0&&!X())return s("another typhons-share-mount is already running \u2014 skipping"),{mounted:!1,reason:"locked"};try{return await te()}finally{S.userInfo().uid===0&&Q()}}function ee(){let e=["/root"];try{e.push(...r.readdirSync("/home").map(t=>`/home/${t}`))}catch{}for(let t of e)try{if(r.existsSync(i.join(t,".config","typhons-share","rclone.conf")))return t==="/root"?"root":i.basename(t)}catch{}return null}async function te(){let e=null;try{e=await K()}catch(u){s(`credential fetch failed: ${u.message}`)}if(S.userInfo().uid!==0)return $(e);let n=process.env.TYPHONS_SHARE_MOUNT_USER||e?.remote_user||ee()||(e?"user":null);if(!n)return{mounted:!1,reason:"fetch-failed"};if(n==="root")return $(e,{home:"/root"});let o;try{o=z(n)}catch{return s(`user "${n}" not found \u2014 falling back to root home mount`),$(e,{home:"/root"})}V(),W(i.join(o.home,_));for(let u of[".config",".cache",i.join(".config","typhons-share"),i.join(".cache","typhons-share"),_]){let c=i.join(o.home,u);try{r.mkdirSync(c,{recursive:!0}),r.statSync(c).uid===0&&r.chownSync(c,o.uid,o.gid)}catch(f){s(`could not prepare ${c}: ${f.message}`)}}return new Promise(u=>{let c=j(process.execPath,[process.argv[1]],{uid:o.uid,gid:o.gid,env:{PATH:process.env.PATH,HOME:o.home,USER:n,LOGNAME:n,TYPHONS_SHARE_TOKEN_JSON:JSON.stringify(e),TYPHONS_SHARE_MOUNT_USER:n},stdio:["ignore","inherit","inherit"]});c.on("error",f=>{s(`user-phase spawn failed: ${f.message}`),u({mounted:!1,reason:"spawn-failed"})}),c.on("exit",f=>u({mounted:f===0,reason:`user-phase-exit-${f}`}))})}import.meta.url===`file://${process.argv[1]}`&&Z().then(e=>{process.exit(e.mounted?0:1)}).catch(e=>{s(`fatal: ${e.stack||e.message}`),process.exit(2)});export{Y as CREDENTIAL_SYMLINKS,J as deriveMountToken,T as ensureSymlinks,K as fetchCredentials,y as mountEntry,q as obscure,b as probeMount,B as renderRcloneConfig,Z as runOnce,$ as runUserPhase,A as skipOnboardingIfLoggedIn,I as writeFileAtomic};
|