@chatpanel/gateway 0.87.0 → 0.97.2
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/README.md +33 -0
- package/bin/chatpanel-gateway-bin.mjs +3 -2
- package/bin/chatpanel-gateway.js +6 -6
- package/package.json +4 -5
- package/src/apple-helper-fetch.js +1 -0
- package/src/apple-model.js +1 -1
- package/src/bridge-supervisor.js +5 -5
- package/src/configstore.js +1 -1
- package/src/confine-start.js +1 -0
- package/src/confine.js +1 -0
- package/src/egress.js +2 -2
- package/src/inference-engines.js +1 -1
- package/src/link-approvals.js +1 -0
- package/src/link-cli.js +13 -0
- package/src/link-files.js +1 -0
- package/src/link-host.js +1 -1
- package/src/ort-native.js +1 -1
- package/src/release-trust.js +5 -0
- package/src/runtime.js +6 -6
- package/src/sandbox-cli.js +7 -0
- package/src/sandbox-runtime-unpack.js +1 -0
- package/src/server.js +34 -27
- package/src/service.js +11 -11
- package/src/system-ca.js +2 -1
- package/src/update.js +4 -4
- package/src/version.js +1 -1
- package/src/worker-sandbox.js +1 -1
- package/native/darwin-arm64/chatpanel-apple-model +0 -0
package/src/service.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import x from"node:os";import{SERVICE_ENV as xe}from"@chatpanel/events/service-standby.js";import f from"node:path";import{mkdirSync as _,writeFileSync as L,readFileSync as W,rmSync as $,existsSync as g,statSync as $e,realpathSync as
|
|
2
|
-
`),
|
|
1
|
+
import x from"node:os";import{SERVICE_ENV as xe}from"@chatpanel/events/service-standby.js";import f from"node:path";import{mkdirSync as _,writeFileSync as L,readFileSync as W,rmSync as $,existsSync as g,statSync as $e,realpathSync as Q}from"node:fs";import{spawnSync as Se,spawn as O}from"node:child_process";import{loadConfig as ve}from"./config.js";import{VERSION as G}from"./version.js";const A="net.chatpanel.gateway",be="ChatPanel Privacy Gateway";function ee(e,t){const n=String(e||"").split(".").map(r=>parseInt(r,10)),s=String(t||"").split(".").map(r=>parseInt(r,10));if(n.some(Number.isNaN)||s.some(Number.isNaN)||n.length<3||s.length<3)return 0;for(let r=0;r<3;r+=1)if(n[r]!==s[r])return n[r]>s[r]?1:-1;return 0}function E(e,{real:t=Q.native||Q}={}){if(!e)return e;try{return t(e)}catch{return e}}function Pe(e,{exists:t=g}={}){const n=/^(.*)\/Cellar\/(node(?:@[\w.]+)?)\/[^/]+\/bin\/(node|bun)$/.exec(String(e||""));if(!n)return e;const s=`${n[1]}/opt/${n[2]}/bin/${n[3]}`;return t(s)?s:e}function Ae({execPath:e=Pe(E(process.execPath)),argv1:t=E(process.argv[1]||"")}={}){const n=f.basename(e).toLowerCase();return(n.startsWith("node")||n.startsWith("bun"))&&t?{program:e,args:[f.resolve(t)]}:{program:e,args:[]}}function k({argv:e=process.argv,current:t=X}={}){const{program:n,args:s}=Ae(),r=e.includes("--confined")||!e.includes("--unconfined")&&/<string>--confined<\/string>|\s--confined(\s|$)/m.test(t()||"");return{program:n,args:r?[...s,"--confined"]:s}}function P(){const e=f.join(x.homedir(),".chatpanel");return _(e,{recursive:!0}),{out:f.join(e,"gateway.log"),err:f.join(e,"gateway.err.log")}}function p(e,t,n={}){return Se(e,t,{encoding:"utf8",...n})}const j=()=>f.join(x.homedir(),"Library","LaunchAgents",`${A}.plist`),Ee={MallocLargeCache:"0"};function te({program:e,args:t,out:n,err:s,env:r={...Ee,...xe},label:i=A}={}){const o=c=>String(c).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),a=[e,...t].map(c=>` <string>${o(c)}</string>`).join(`
|
|
2
|
+
`),l=Object.entries(r).map(([c,d])=>` <key>${o(c)}</key><string>${o(d)}</string>`).join(`
|
|
3
3
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
4
4
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
5
5
|
<plist version="1.0">
|
|
@@ -11,7 +11,7 @@ ${a}
|
|
|
11
11
|
</array>
|
|
12
12
|
<key>EnvironmentVariables</key>
|
|
13
13
|
<dict>
|
|
14
|
-
${
|
|
14
|
+
${l}
|
|
15
15
|
</dict>
|
|
16
16
|
<key>RunAtLoad</key><true/>
|
|
17
17
|
<key>KeepAlive</key><true/>
|
|
@@ -19,12 +19,12 @@ ${c}
|
|
|
19
19
|
<key>StandardErrorPath</key><string>${o(s)}</string>
|
|
20
20
|
</dict>
|
|
21
21
|
</plist>
|
|
22
|
-
`}function
|
|
23
|
-
`,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=
|
|
22
|
+
`}function ke(){const{program:e,args:t}=k(),{out:n,err:s}=P(),r=te({program:e,args:t,out:n,err:s}),i=j();_(f.dirname(i),{recursive:!0}),L(i,r),p("launchctl",["unload",i]);const o=p("launchctl",["load","-w",i]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"launchctl load failed")}function je(){const e=j();p("launchctl",["unload","-w",e]),g(e)&&$(e)}function Ie(){return(p("launchctl",["list"]).stdout||"").includes(A)}function D({execPath:e=E(process.execPath),argv1:t=E(process.argv[1]||""),platform:n=process.platform,isFile:s=V}={}){const r=n==="win32"?f.win32:f.posix,i=r.basename(e).toLowerCase();if(!(i.startsWith("node")||i.startsWith("bun")))return r.dirname(e);const o=n==="win32"?"chatpanel-gateway.cmd":"chatpanel-gateway";let a=r.dirname(r.resolve(t));for(let l=0;l<6;l++){const c=r.dirname(a);if(c===a)break;if(a=c,s(r.join(a,o)))return a;if(s(r.join(a,"bin",o)))return r.join(a,"bin")}return""}const V=e=>{try{return $e(e).isFile()}catch{return!1}};function U(e,t,{delimiter:n=f.delimiter,platform:s=process.platform,env:r=process.env}={}){const i=l=>s==="win32"?l.replace(/%([^%]+)%/g,(c,d)=>r[d]??r[d.toUpperCase()]??c):l,o=l=>{const c=i(l.trim()).replace(/[\\/]+$/,"");return s==="win32"?c.toLowerCase():c},a=String(e||"").split(n).filter(l=>l.trim());return a.some(l=>o(l)===o(t))?null:[...a,t].join(n)}function B({dir:e=D(),pathEnv:t=process.env.PATH||"",platform:n=process.platform,isFile:s=V}={}){if(!e)return"";const r=n==="win32"?f.win32:f.posix,i=n==="win32"?";":":",o=l=>{const c=String(l).trim().replace(/[\\/]+$/,"");return n==="win32"?c.toLowerCase():c},a=n==="win32"?["chatpanel-gateway.cmd","chatpanel-gateway.exe"]:["chatpanel-gateway"];for(const l of String(t).split(i)){const c=l.trim();if(c){if(o(c)===o(e))return"";if(a.some(d=>s(r.join(c,d))))return c}}return""}function Ne({embedded:e="",pathEnv:t=process.env.PATH||"",platform:n=process.platform,real:s=E,read:r=o=>W(o,"utf8"),isFile:i=V}={}){if(!e)return[];const o=n==="win32"?f.win32:f.posix,a=n==="win32"?["chatpanel-bridge.cmd"]:["chatpanel-bridge"],l=[],c=new Set;for(const d of String(t).split(n==="win32"?";":":")){const u=d.trim().replace(/[\\/]+$/,"");if(!u)continue;const h=a.map(y=>o.join(u,y)).find(y=>i(y));if(!h||c.has(h))continue;c.add(h);const T=n==="win32"?[o.join(u,"node_modules","@chatpanel","bridge")]:[o.dirname(o.dirname(s(h))),o.join(o.dirname(u),"lib","node_modules","@chatpanel","bridge")];let w="";for(const y of T)try{const b=JSON.parse(r(o.join(y,"package.json")));if(b?.name==="@chatpanel/bridge"&&b.version){w=String(b.version);break}}catch{}if(!w||ee(w,e)>=0)continue;const R=o.join(u,n==="win32"?"npm.cmd":"npm");l.push({path:h,version:w,remove:`${i(R)?R:"npm"} rm -g @chatpanel/bridge`})}return l}function Te(e,{embedded:t=""}={}){if(!e?.length)return[];const n=[` ⚠ An older ChatPanel bridge is still installed: ${e.map(s=>`${s.path} (v${s.version})`).join(", ")}.`,` The gateway carries its own bridge${t?` (v${t})`:""} and does not use ${e.length===1?"it":"them"}, but typing \`chatpanel-bridge\` runs the old copy — which starts a second bridge instead of doing what was asked.`];for(const s of e)n.push(` Remove it: ${s.remove}`);return n.push(" To pair a browser: chatpanel-gateway pair"),n}const S="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",M="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",m="ChatPanelGateway",F=()=>f.join(x.homedir(),".chatpanel","gateway-launch.vbs"),ne=e=>Buffer.from(e,"utf16le").toString("base64");function q({systemRoot:e=process.env.SystemRoot||"C:\\Windows",exists:t=g}={}){return t(f.join(e,"System32","vbscript.dll"))}function re({program:e,args:t=[],out:n,err:s,vbs:r,vbscript:i=!0}){const o=u=>`"${u}"`;if(i){const u=`cmd.exe /c "${[e,...t].map(o).join(" ")} >> ${o(n)} 2>> ${o(s)}"`;return{kind:"vbs",file:r,text:`CreateObject("WScript.Shell").Run "${u.replace(/"/g,'""')}", 0, False\r
|
|
23
|
+
`,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=u=>`'${String(u).replace(/'/g,"''")}'`,l=t.length?` -ArgumentList @(${t.map(u=>a(o(u))).join(", ")})`:"",c=`Start-Process -WindowStyle Hidden -FilePath ${a(e)}${l} -RedirectStandardOutput ${a(n)} -RedirectStandardError ${a(s)}`,d=["powershell.exe","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",ne(c)];return{kind:"powershell",file:"",text:c,runValue:d.join(" "),argv:d}}function Z(e=p){const t=e("reg",["query",S,"/v",m]);if(t.status!==0)return"";const n=new RegExp(`${m}\\s+REG_\\w+\\s+(.*)$`,"m").exec(t.stdout||"");return n?n[1].trim():""}function Re(e=p){const t=e("reg",["query",M,"/v",m]);if(t.status!==0)return!1;const n=/REG_BINARY\s+([0-9A-Fa-f]{2})/.exec(t.stdout||"");return!!n&&(parseInt(n[1],16)&1)===1}function se(e=p){const t=e("reg",["query","HKCU\\Environment","/v","Path"]),n=/\bPath\s+(REG_EXPAND_SZ|REG_SZ)\s+(.*)$/mi.exec(t.stdout||"");return n?{type:n[1],value:n[2].trim()}:{type:"REG_EXPAND_SZ",value:""}}const Ce=`$sig = '[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);'
|
|
24
24
|
$t = Add-Type -MemberDefinition $sig -Name 'Env' -Namespace 'ChatPanelWin32' -PassThru
|
|
25
25
|
$r = [UIntPtr]::Zero
|
|
26
|
-
[void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function
|
|
27
|
-
`)){const d=Number(
|
|
26
|
+
[void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function _e(e,{runImpl:t=p,env:n=process.env}={}){if(!e)return{added:!1,dir:e};const s=se(t),r=U(s.value,e,{delimiter:";",platform:"win32",env:n});if(r===null)return{added:!1,dir:e,onPath:!0};const i=t("reg",["add","HKCU\\Environment","/v","Path","/t",s.type,"/d",r,"/f"]);return i.status!==0?{added:!1,dir:e,error:(i.stderr||"").trim()||"reg add failed"}:(t("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",ne(Ce)],{timeout:15e3}),{added:!0,dir:e,onPath:!0})}function Le(e,{runImpl:t=p,env:n=process.env}={}){if(!e)return!0;const s=n.Path??n.PATH??"";return U(se(t).value,e,{delimiter:";",platform:"win32",env:n})===null||U(s,e,{delimiter:";",platform:"win32",env:n})===null}function We({pid:e=process.pid}={}){return`${`$keep = @(${e}, $PID); $p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${e}'; $n = 0; while ($p -and $n++ -lt 8) { $keep += $p.ParentProcessId; $p = Get-CimInstance Win32_Process -Filter "ProcessId = $($p.ParentProcessId)" }`}; Get-CimInstance Win32_Process | Where-Object { $keep -notcontains $_.ProcessId -and (($_.Name -ieq 'chatpanel-gateway.exe') -or ($_.CommandLine -match '[\\\\/]chatpanel-gateway\\.js(["'' ]|$)')) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`}function Oe({pid:e=process.pid}={}){return[["powershell.exe",["-NoProfile","-NonInteractive","-Command",We({pid:e})]],["taskkill",["/F","/FI","IMAGENAME eq chatpanel-gateway.exe","/FI",`PID ne ${e}`]]]}function K(e=p){for(const[t,n]of Oe())e(t,n,{timeout:15e3})}function De(){return process.platform==="win32"?K():(process.platform==="darwin"?p("launchctl",["bootout",`gui/${process.getuid?.()??""}/${A}`]):p("systemctl",["--user","stop","chatpanel-gateway.service"]),ae())}function Ue(){const{program:e,args:t}=k(),{out:n,err:s}=P(),r=re({program:e,args:t,out:n,err:s,vbs:F(),vbscript:q()});r.file?L(r.file,r.text):$(F(),{force:!0});const i=p("reg",["add",S,"/v",m,"/t","REG_SZ","/d",r.runValue,"/f"]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"reg add failed");p("reg",["delete",M,"/v",m,"/f"]);const o=_e(D());return K(),p("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),p(r.argv[0],r.argv.slice(1),{windowsHide:!0,timeout:2e4}),{launcher:r.kind,path:o}}function Be(){p("reg",["delete",S,"/v",m,"/f"]),$(F(),{force:!0}),K()}function oe(){return p("reg",["query",S,"/v",m]).status===0}function v({env:e=process.env,release:t=x.release(),platform:n=process.platform}={}){return n==="linux"&&(!!e.WSL_DISTRO_NAME||/microsoft/i.test(t))}function I(e=p){const t=["/mnt/c/Windows/System32/cmd.exe","cmd.exe"];let n=null;for(const c of t){if(n=e(c,["/c","echo %USERPROFILE%|%SystemRoot%"],{cwd:"/mnt/c",timeout:15e3}),n&&!n.error&&n.status===0)break;n=null}const[s,r]=(n?.stdout||"").trim().split("|");if(!/^[A-Za-z]:\\/.test(s||"")||!/^[A-Za-z]:\\/.test(r||""))return null;const i=c=>(e("wslpath",["-u",c]).stdout||"").trim(),o=i(r),a=i(s);if(!o||!a)return null;const l=f.posix.join(o,"System32");return{home:s,homeUnix:a,sysRoot:r,sysUnix:o,exe:{reg:f.posix.join(l,"reg.exe"),wscript:f.posix.join(l,"wscript.exe"),powershell:f.posix.join(l,"WindowsPowerShell","v1.0","powershell.exe")}}}const He=["^[^ ]*chatpanel-gateway( |$)","^[^ ]*(node|bun)[^ ]*( +-[^ ]+)* +[^ ]*chatpanel-gateway\\.js( |$)"];function ie(e,t=p){const n=t("ps",["-o","ppid=","-p",String(e)]);return Number((n.stdout||"").trim())||0}function Ge({pid:e=process.pid,ppid:t=process.ppid,parentOf:n=ie,depth:s=8}={}){const r=new Set([e]);let i=t;for(let o=0;o<s&&i>1&&!r.has(i);o+=1)r.add(i),i=n(i);return r}function ae({runImpl:e=p,keep:t=null,kill:n=r=>process.kill(r,"SIGTERM"),patterns:s=He}={}){const r=t||Ge({parentOf:a=>ie(a,e)}),i=[],o=new Set;for(const a of s){const l=e("pgrep",["-f",a]);for(const c of(l.stdout||"").split(`
|
|
27
|
+
`)){const d=Number(c.trim());if(!(!d||r.has(d)||o.has(d))){o.add(d);try{n(d),i.push(d)}catch{}}}}return i}const ce=()=>ae(),le=e=>({win:`${e.home}\\.chatpanel\\gateway-launch.vbs`,unix:f.posix.join(e.homeUnix,".chatpanel","gateway-launch.vbs")});function Ve(e,t){const[n,...s]=t.argv;return[n==="wscript.exe"?e.exe.wscript:e.exe.powershell,...s]}function Me(e){const{program:t,args:n}=k(),{out:s,err:r}=P(),i=h=>`'${String(h).replace(/'/g,"'\\''")}'`,o=`exec ${[t,...n].map(i).join(" ")} >> ${i(s)} 2>> ${i(r)}`,a=process.env.WSL_DISTRO_NAME?["-d",process.env.WSL_DISTRO_NAME]:[],l=le(e),c=re({program:"wsl.exe",args:[...a,"-u",x.userInfo().username,"--","bash","-lc",o],vbs:l.win,vbscript:q({systemRoot:e.sysUnix})});_(f.dirname(l.unix),{recursive:!0}),c.file?L(l.unix,c.text):$(l.unix,{force:!0});const d=p(e.exe.reg,["add",S,"/v",m,"/t","REG_SZ","/d",c.runValue,"/f"]);if(d.status!==0)throw new Error((d.stderr||"").trim()||"reg.exe add failed");p(e.exe.reg,["delete",M,"/v",m,"/f"]),ce(),qe(800);const u=Ve(e,c);return p(u[0],u.slice(1),{timeout:2e4}),{launcher:c.kind,wsl:!0,path:{added:!1,dir:D()}}}function Fe(e){p(e.exe.reg,["delete",S,"/v",m,"/f"]),$(le(e).unix,{force:!0}),ce()}function ue(e){return p(e.exe.reg,["query",S,"/v",m]).status===0}function qe(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}const H=()=>f.join(x.homedir(),".config","systemd","user","chatpanel-gateway.service");function pe({exec:e,display:t=be}={}){return`[Unit]
|
|
28
28
|
Description=${t}
|
|
29
29
|
After=network.target
|
|
30
30
|
|
|
@@ -36,8 +36,8 @@ RestartSec=2
|
|
|
36
36
|
|
|
37
37
|
[Install]
|
|
38
38
|
WantedBy=default.target
|
|
39
|
-
`}function
|
|
39
|
+
`}function Ze(){const e=v()?I():null;if(e)return Me(e);if(v()&&!g("/run/systemd/system"))throw new Error("WSL: Windows interop is off (cmd.exe cannot run from here) and systemd is not enabled in /etc/wsl.conf — nothing here can start the gateway at login. Enable one of them, or run `chatpanel-gateway` from a shell.");const{program:t,args:n}=k(),s=[t,...n].map(a=>/\s/.test(a)?`"${a}"`:a).join(" "),r=pe({exec:s}),i=H();_(f.dirname(i),{recursive:!0}),L(i,r),p("systemctl",["--user","daemon-reload"]);const o=p("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"systemctl enable failed")}function Ke(){const e=v()?I():null;e&&Fe(e),p("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=H();g(t)&&$(t)}function de(){const e=v()?I():null;return e&&ue(e)?!0:(p("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function Ye({home:e=x.homedir(),platform:t=process.platform,env:n=process.env}={}){const s=t==="win32"?f.win32:f.posix;return t==="win32"?[s.join(n.LOCALAPPDATA||s.join(e,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[s.join(e,".local","bin","chatpanel-bridge")]}const fe="net.chatpanel.bridge",Y="ChatPanelBridge";function Xe({platform:e=process.platform,runImpl:t=p,paths:n=Ye(),home:s=x.homedir()}={}){if(e==="win32"){t("reg",["delete",S,"/v",Y,"/f"]),t("schtasks",["/End","/TN",Y]),t("schtasks",["/Delete","/TN",Y,"/F"]);for(const r of n){const i=`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${r.replace(/'/g,"''")}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;t("powershell.exe",["-NoProfile","-NonInteractive","-Command",i],{timeout:15e3})}return}if(e==="darwin"){t("launchctl",["bootout",`gui/${process.getuid?.()??""}/${fe}`]);const r=f.join(s,"Library","LaunchAgents",`${fe}.plist`);g(r)&&$(r,{force:!0})}else{t("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=f.join(s,".config","systemd","user","chatpanel-bridge.service");g(r)&&$(r,{force:!0})}for(const r of n)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function N(e,t,n){if(process.platform==="darwin")return e();if(process.platform==="win32")return t();if(process.platform==="linux")return n();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function ze({env:e=process.env}={}){return{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0,env:e}}function lt({winInstall:e=""}={}){try{if(process.platform==="darwin")return g(j())?(O("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${A}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux"){const t=v()?I():null;if(t&&ue(t)){const n=Z((r,i,o)=>p(r==="reg"?t.exe.reg:r,i,o));return n?(O("sh",["-c",`sleep 3; cd /mnt/c 2>/dev/null; exec cmd.exe /c ${(r=>`'${String(r).replace(/'/g,"'\\''")}'`)(n)}`],{detached:!0,stdio:"ignore"}).unref(),setTimeout(()=>process.exit(0),300),!0):!1}return g(H())?(O("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1}if(process.platform==="win32"){const t=Z();if(!t)return!1;const n=f.dirname(process.execPath),s=`timeout /t 3 >nul & ${e?`${e} & `:""}${t} & del /q "${f.join(n,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`,r={...process.env},i=Object.keys(r).find(o=>o.toLowerCase()==="path")||"Path";return r[i]=[n,...(r[i]||"").split(";").filter(Boolean)].filter((o,a,l)=>l.indexOf(o)===a).join(";"),O("cmd",["/c",s],ze({env:r})).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function ut(){try{return N(()=>g(j()),oe,de)}catch{return!1}}function he(){try{return`http://127.0.0.1:${ve().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function ge(e=he(),{timeoutMs:t=2e3}={}){try{const n=await fetch(`${e}/health`,{signal:AbortSignal.timeout(t)});if(!n.ok)return{ok:!1,url:e};const s=await n.json();return{ok:!0,url:e,version:String(s.version||""),managedBy:s.managedBy?String(s.managedBy):"",install:s.install?String(s.install):"",...typeof s.appleHelper=="boolean"?{appleHelper:s.appleHelper}:{}}}catch{return{ok:!1,url:e}}}function me(e=8){try{const t=W(P().err,"utf8").trimEnd();return t?t.split(`
|
|
40
40
|
`).slice(-e).join(`
|
|
41
|
-
`):""}catch{return""}}function
|
|
42
|
-
`).map(
|
|
43
|
-
`)}export{
|
|
41
|
+
`):""}catch{return""}}function Je({platform:e=process.platform,text:t=X(),loaded:n=null}={}){if(e!=="darwin"&&e!=="linux")return!1;try{if(e==="linux"&&v())return!1;const{program:s,args:r}=k(),i=e==="darwin"?te({program:s,args:r,...P()}):pe({exec:[s,...r].map(o=>/\s/.test(o)?`"${o}"`:o).join(" ")});return!t||t!==i?!1:n===null?we():!!n}catch{return!1}}function Qe({sandbox:e=null,appleHelper:t}={}){const n=[];if(e){e.enabled?e.runtime?e.narrowed?n.push(`agents: sandboxed through the \`srt\` command — a fixed list of hosts, not "${e.mode}": each agent reaches its own service, the developer hosts and the ones you allow. The npm package (npm i -g @chatpanel/gateway) runs "open".`):n.push(`agents: sandboxed, network "${e.mode}"`):n.push(`agents: NOT sandboxed — ${e.reason||"no sandbox runtime was found"}`):n.push("agents: NOT sandboxed — the sandbox is switched off (sandbox.mode, or CHATPANEL_SANDBOX in the service's environment)");for(const[s,r]of Object.entries(e.agents||{})){const i=[r.signIn?.length?`may sign in with ${r.signIn.join(", ")}`:"",r.outside?"runs OUTSIDE the sandbox":"",r.hosts?.length?`may also reach ${r.hosts.join(", ")}`:"",r.write?.length?`may also write ${r.write.join(", ")}`:""].filter(Boolean);i.length&&n.push(` ${s}: ${i.join("; ")}`)}for(const s of e.warnings||[])n.push(` ⚠ ${s}`)}return t===!1&&n.push(" ✕ Apple on-device: its helper is not in the running install — `chatpanel-gateway --fetch-apple-helper` fetches it (then Start on its row)"),n}async function pt({waitMs:e=4e4,version:t="",probe:n=ge,stop:s=De,install:r=()=>N(ke,Ue,Ze),retire:i=Xe,wait:o=d=>new Promise(u=>setTimeout(u,d)),now:a=()=>Date.now(),force:l=!1,current:c=Je}={}){const d=he(),u=await n(d);if(!l&&u.ok&&t&&u.version&&ee(u.version,t)>0)return{ok:!1,newer:!0,health:u,shadow:B()};i();const h=u.ok&&u.managedBy&&u.managedBy!=="gateway"?u.managedBy:"";if(!l&&u.ok&&t&&u.version===t&&!h&&c())return{ok:!0,unchanged:!0,health:u,replaced:"",deferredTo:"",shadow:B(),errLog:""};const T=!!(u.ok&&t&&u.version&&u.version!==t),w=T&&!h;w&&(s(),await o(1200));const R=r()||{},y=w?t:"",b=J=>J.ok&&(!y||J.version===y),ye=a()+e;let C=await n(d);for(;!b(C)&&a()<ye;)await o(500),C=await n(d);const z=b(C);return{...R,health:C,ok:z,replaced:w?u.version:"",deferredTo:T?h:"",shadow:B(),errLog:z?"":me()}}function dt(){return N(je,Be,Ke)}function we(){return N(Ie,oe,de)}function et(e,t=process.platform){const n=String(e||"");if(t==="darwin"){const r=/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(n);if(!r)return[];const i=o=>o.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&");return[...r[1].matchAll(/<string>([\s\S]*?)<\/string>/g)].map(o=>i(o[1]))}const s=/^ExecStart=(.*)$/m.exec(n);return s?[...s[1].matchAll(/"([^"]*)"|(\S+)/g)].map(r=>r[1]??r[2]):[]}function tt({text:e,loaded:t,exists:n=g,platform:s=process.platform}){if(!e)return{state:"none",missing:[]};const o=et(e,s).slice(0,2).filter((a,l)=>l===0||/[\\/]/.test(a)&&!a.startsWith("-")).filter(a=>a.startsWith("/")&&!n(a));return o.length?{state:"gone",missing:o}:{state:t?"ok":"unloaded",missing:[]}}function X(){try{return N(()=>W(j(),"utf8"),()=>"",()=>W(H(),"utf8"))}catch{return""}}async function ft({platform:e=process.platform}={}){const t=[];let n=!1;try{n=we()}catch(l){t.push(`auto-start: ${l.message}`)}const s=e==="win32"?{state:"none",missing:[]}:tt({text:X(),loaded:n,platform:e});s.state==="gone"?t.push(`auto-start: ✕ registered, but it starts ${s.missing.join(" and ")}, which is gone (a Node upgrade or a version manager removed it) — \`chatpanel-gateway --install\` registers it again with this copy`):s.state==="unloaded"?t.push("auto-start: installed but switched off (the service manager is not running it) — `chatpanel-gateway --install` turns it back on"):t.push(n?"auto-start: registered":"auto-start: not registered — `chatpanel-gateway --install`");const r=e==="linux"&&v()?I():null;if(e==="win32"||r){const l=r?(d,u,h)=>p(d==="reg"?r.exe.reg:d,u,h):p,c=n?Z(l):"";c&&t.push(` launcher: ${c.length>120?`${c.slice(0,117)}…`:c}`),c.startsWith("wscript")&&!q(r?{systemRoot:r.sysUnix}:{})&&t.push(" ✕ VBScript is not installed on this Windows, so that launcher cannot run — `--install` again registers one that does not need it"),n&&Re(l)&&t.push(" ✕ switched off in Task Manager › Startup — `--install` again turns it back on"),r&&t.push(` WSL: starts at Windows login through wsl.exe (${process.env.WSL_DISTRO_NAME||"default distro"})`)}const i=D();i&&(e==="win32"?t.push(Le(i)?`command: ${i} (on PATH)`:`command: ${i} — NOT on your PATH; \`--install\` adds it`):t.push(U(process.env.PATH||"",i,{platform:e})===null?`command: ${i} (on PATH)`:`command: ${i} — not on your PATH: export PATH="${i}:$PATH"`));const o=B({platform:e});o&&t.push(` ✕ ${o}/chatpanel-gateway is EARLIER on your PATH — that copy is what the name runs, not this v${G}`);const a=await ge();try{const l=a.ok?String((await(await fetch(`${a.url}/health`,{signal:AbortSignal.timeout(2e3)})).json())?.bridge?.version||""):"";t.push(...Te(Ne({embedded:l,platform:e}),{embedded:l}).map(c=>c.replace(/^ {2}/,"")))}catch{}if(a.ok){const l=a.version===G?"":` — this command is v${G}; \`--install\` makes it the one that runs`;t.push(`running: v${a.version}${a.install==="binary"?" (the standalone binary)":a.install==="npm"?" (the npm package)":""} at ${a.url}${a.managedBy?` (run by ${a.managedBy})`:""}${a.managedBy?"":l}`);let c=null;try{c=(await(await fetch(`http://127.0.0.1:${process.env.CHATPANEL_BRIDGE_PORT||4319}/health`,{signal:AbortSignal.timeout(2e3)})).json())?.sandbox||null}catch{}t.push(...Qe({sandbox:c,appleHelper:a.appleHelper}))}else{t.push(`running: nothing answers at ${a.url}`);const l=me();l&&t.push(` last of ${P().err}:`,...l.split(`
|
|
42
|
+
`).map(c=>` ${c}`))}return t.join(`
|
|
43
|
+
`)}export{Ee as DARWIN_LAUNCH_ENV,He as GATEWAY_ARGV_PATTERNS,D as commandDir,ee as compareVersions,me as errLogTail,pt as installService,v as isWsl,pe as linUnitText,te as macPlistText,B as pathShadow,U as pathWithDir,ge as probeHealth,ne as psEncode,E as realPath,Ae as resolveLaunch,lt as restartService,Xe as retireStandaloneBridge,Qe as runningInstallLines,Ge as selfAndAncestors,k as serviceLaunch,ut as serviceRegistered,ft as serviceReport,we as serviceStatus,Pe as stableNodePath,Ne as staleBridgeCommands,Te as staleBridgeLines,Ye as standaloneCandidates,ae as stopOtherGateways,De as stopService,dt as uninstallService,Je as unitCurrent,tt as unitHealth,et as unitLaunch,q as vbscriptAvailable,Le as winCommandOnPath,_e as winEnsureOnPath,re as winLauncher,ze as winRelaunchOpts,Re as winStartupDisabled,Oe as winStopArgs,We as winStopScript};
|
package/src/system-ca.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import
|
|
1
|
+
import C from"node:tls";import d from"node:os";import{existsSync as l,readFileSync as i}from"node:fs";import{join as y}from"node:path";const h=/^(off|0|false|no)$/i;function m(e=null,t=process.env){return h.test(String(t.CHATPANEL_SYSTEM_CA||""))?!1:e?.tls?.systemCa!==!1}function w(e=process.env,t=d.homedir()){let s=null;try{const n=e.CHATPANEL_GATEWAY_CONFIG||y(t,".chatpanel","gateway.config.json");l(n)&&(s=JSON.parse(i(n,"utf8")))}catch{s=null}return m(s,e)}let a={on:!1,added:0,why:"not applied yet"};function N(){return{...a}}function p(e,t){const s=(n,r)=>e(n,r?.tls?.ca?r:{...r,tls:{...r?.tls,ca:t}});for(const n of Object.keys(e))s[n]=e[n];return s.chatpanelSystemCa=!0,s}function x({enabled:e=!0,tlsImpl:t=C,scope:s=globalThis,bun:n=!!process.versions.bun,env:r=process.env}={}){if(!e)return a={on:!1,added:0,why:"switched off (tls.systemCa: false, or CHATPANEL_SYSTEM_CA=off)"};if(typeof t.getCACertificates!="function"||typeof t.setDefaultCACertificates!="function")return a={on:!1,added:0,why:"this runtime cannot change its certificate list — Node 22.19 or newer can"};try{const o=t.getCACertificates("default"),u=new Set(o),c=(r.CHATPANEL_SYSTEM_CA_FILE?A(i(r.CHATPANEL_SYSTEM_CA_FILE,"utf8")):t.getCACertificates("system")).filter(f=>!u.has(f));if(c.length){const f=[...o,...c];t.setDefaultCACertificates(f),n&&typeof s.fetch=="function"&&!s.fetch.chatpanelSystemCa&&(s.fetch=p(s.fetch,f))}return a={on:!0,added:c.length+(a.on?a.added:0)}}catch(o){return a={on:!1,added:0,why:`the system's certificates could not be read (${String(o?.message||o).slice(0,120)})`}}}function A(e){return(String(e||"").match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g)||[]).map(t=>`${t}
|
|
2
|
+
`)}function F(){a={on:!1,added:0,why:"not applied yet"}}export{F as _resetSystemCaState,A as pemList,N as systemCaState,m as systemCaWanted,w as systemCaWantedOnDisk,x as trustSystemCertificates};
|
package/src/update.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import R from"node:os";import l from"node:path";import{execFile as S}from"node:child_process";import{chmod as q,rename as L,mkdir as z,readFile as Q,writeFile as I,rm as X}from"node:fs/promises";import{existsSync as Z,readFileSync as ee,realpathSync as te}from"node:fs";import{explainInstallFailure as y,adviceText as x,npmInstallCommand as ne}from"@chatpanel/events/install-advice.js";import{restartService as ae,serviceRegistered as b}from"./service.js";import{systemCaWantedOnDisk as se}from"./system-ca.js";const A="@chatpanel/gateway",De="chatpanel/chatpanel-gateway",H="https://dl.chatpanel.net/version/gateway",_=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),re=`${_}/${A}/latest`,oe=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,F=360*60*1e3,M=600*1e3,ie=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),le=15*6e4,B=20*6e4,T=process.env.CHATPANEL_UPDATE_CACHE||l.join(R.homedir(),".chatpanel","gateway-update-check.json"),C=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",J={"User-Agent":"chatpanel-gateway-updater"},ce=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function de(e){try{const t=new URL(e);return t.protocol==="https:"&&ce.has(t.hostname)}catch{return!1}}let f={at:0,error:""};function je(){f={at:0,error:""}}function P(){const e=l.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function pe(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function h(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function W(e,t){const n=String(e).split(".").map(Number),s=String(t).split(".").map(Number);for(let a=0;a<Math.max(n.length,s.length);a+=1){const r=(n[a]||0)-(s[a]||0);if(r)return r>0?1:-1}return 0}async function ue(){try{return JSON.parse(await Q(T,"utf8"))}catch{return null}}async function me(e){try{await z(l.dirname(T),{recursive:!0}),await I(T,JSON.stringify(e))}catch{}}async function N(e,t=ie){const n=new AbortController,s=setTimeout(()=>n.abort(),t);try{const a=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...J},signal:n.signal});if(!a.ok)throw new Error(a.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${a.status}`);return await a.json()}catch(a){const r=a?.cause?.code||a?.cause?.message||a?.message||String(a);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${r}`)}finally{clearTimeout(s)}}function k(e=process.argv[1]){let t=e?l.resolve(e):"";try{t=te(t)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return n?n[1]:""}function fe(){const e=k();if(!e)return"";try{return String(JSON.parse(ee(l.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function E(){const e=l.dirname(process.execPath);return[l.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"..","libexec","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"node_modules","npm","bin","npm-cli.js")].find(n=>Z(n))||""}function he(e=process.env,t=process.execPath){const n={...e,npm_config_registry:_,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const s=Object.keys(n).find(a=>a.toLowerCase()==="path")||"PATH";return n[s]=[l.dirname(t),...(n[s]||"").split(l.delimiter).filter(Boolean)].filter((a,r,c)=>c.indexOf(a)===r).join(l.delimiter),n}function we(){import("./prune-install.js").then(({pruneForeignPrebuilds:e,pruneLine:t})=>{const n=t(e({log:s=>console.log(s)}));n&&console.log(`[update]${n}`)}).catch(()=>{})}function ge(){return["install","-g",`${A}@latest`,"--ignore-scripts"]}function ye(e,{home:t=R.homedir(),platform:n=process.platform}={}){if(n==="win32"||!/\b(EACCES|EPERM)\b/.test(e||""))return"";const s=(e.match(/^npm (?:error|ERR!) path (.+)$/m)||[])[1]?.trim()||"",a=s.indexOf(`${l.sep}lib${l.sep}node_modules`),r=a>0?s.slice(0,a):"";return r?r===t||r.startsWith(t+l.sep)?`npm cannot write ${r} — part of it belongs to another user, usually from an earlier \`sudo npm i -g\` (npm's hint about ~/.npm is a different folder). Fix: sudo chown -R "$(whoami)" "${r}" — then update again.`:`npm cannot write ${r}, which belongs to another user. Install the standalone build instead — it needs no npm: curl -fsSL https://dl.chatpanel.net/install.sh | bash`:""}function be(e=process.allowedNodeEnvironmentFlags){try{return!process.versions.bun&&e.has("--use-system-ca")}catch{return!1}}function Ae({cli:e=E(),systemCa:t=!1,env:n=he(),execPath:s=process.execPath}={}){const a=ge();return e?{cmd:s,args:[...t?["--use-system-ca"]:[],e,...a],env:n}:{cmd:"npm",args:a,env:t?{...n,NODE_OPTIONS:`${n.NODE_OPTIONS?`${n.NODE_OPTIONS} `:""}--use-system-ca`}:n}}function Ee({systemCa:e=!1}={}){const t=E(),{cmd:n,args:s,env:a}=Ae({cli:t,systemCa:e});return new Promise(r=>{S(n,s,{env:a,timeout:B,maxBuffer:8<<20,windowsHide:!0},(c,u,o)=>{const i=`${u||""}${o||""}`.trim();return c?c.killed&&!i?r({ok:!1,out:`npm was still running after ${Math.round(B/6e4)} minutes and was stopped`}):r({ok:!1,out:i||(t?c.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):(we(),r({ok:!0,out:i}))})})}async function ve({run:e=Ee,canSystemCa:t=be()&&se()}={}){const n=await e({systemCa:!1});if(n.ok||!t||y(n.out)?.kind!=="certificate")return n;console.log("[update] npm refused the registry's certificate (a re-signing proxy) — trying once more with the system's certificates");const s=await e({systemCa:!0});return s.ok?{...s,via:"system-ca"}:s}function $e(e,t=process.versions.node,n=process.platform){return!e||process.versions.bun?null:y("",{node:t,needsNode:e,platform:n})}async function G(e,{force:t=!1}={}){const n=P()?"binary":"npm";if(C)return{current:e,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const s=pe();let a=null,r=null,c=!1,u="",o=0,i="";const d=await ue(),g=d&&d.mode===n,U=()=>{a=g&&d.latest||null,r=g&&d.assetUrl||null,o=g&&d.checkedAt||0,i=g&&d.needsNode||"",c=!0};if(!t&&g&&Date.now()-d.checkedAt<F)a=d.latest,r=d.assetUrl,o=d.checkedAt,i=d.needsNode||"";else if(!t&&f.at&&Date.now()-f.at<M)u=f.error,U();else try{if(n==="npm"){let m;try{m=await N(re),a=h(m.version),i=String(m.engines?.node||"")}catch(Y){const j=await N(H);if(a=h(j?.npm?.version)||h(j?.version),!a)throw Y}}else{const m=await N(H);a=h(m.version)||h(m.release?.tag),r=s&&(m.release?.assets||[]).includes(s)?oe(s):null}o=Date.now(),await me({checkedAt:o,mode:n,latest:a,assetUrl:r,needsNode:i}),f={at:0,error:""}}catch(m){u=m.message,f={at:Date.now(),error:u},U()}const D=!!a&&W(a,e)>0,$=n==="npm"&&D?$e(i):null,K=$?!1:n==="binary"?!!r&&(process.platform!=="win32"||b()):!!k()&&(process.platform!=="win32"||b()&&!!E()),V=n==="npm"?ne({pkg:A,platform:process.platform}):null;return{current:e,latest:a,updateAvailable:D,mode:n,canSelfUpdate:K,assetUrl:r,stale:c,error:u,npmCommand:V,channel:n==="npm"?"npm":"release",service:b(),checkedAt:o,...n==="npm"?{node:process.versions.node,...i?{needsNode:i}:{}}:{},...$?{blocked:$}:{}}}let w=null,v=null;function Re(e){const t=P()?"binary":"npm";return C?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!w||(w.stale?!(f.at&&Date.now()-f.at<M):Date.now()-w.seenAt>F))&&!v&&(v=G(e).then(s=>{w={...s,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{v=null})),w?{...w,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:b()})}function Le(){w=null,v=null}async function Se(e){const t=process.execPath,n=l.dirname(t),s=l.join(n,`.chatpanel-gateway.new-${Date.now()}`),a=new AbortController,r=setTimeout(()=>a.abort(),le);let c;try{let o;try{o=await fetch(e.assetUrl,{headers:J,redirect:"follow",signal:a.signal})}catch(i){throw new Error(`download failed: ${a.signal.aborted?"timed out":i?.cause?.code||i?.cause?.message||i?.message||i}`)}if(!o.ok)throw new Error(`download failed (HTTP ${o.status})`);if(!de(o.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${o.url}, which is not a ChatPanel release host`);c=Buffer.from(await o.arrayBuffer())}finally{clearTimeout(r)}if(c.length<5<<20)throw new Error(`the download was only ${(c.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);await I(s,c),process.platform!=="win32"&&await q(s,493),process.platform==="darwin"&&await new Promise(o=>S("xattr",["-c",s],()=>o()));const u=await new Promise(o=>S(s,["--version"],{timeout:6e4,windowsHide:!0},(i,d)=>o(i?"":String(d||"").trim())));if(!h(u))throw await X(s,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await L(t,l.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await L(s,t),h(u)}const O=(e,t=null,n="")=>Object.assign(new Error(e),{advice:t,raw:n});async function xe(e){if(C)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await G(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(t.blocked)throw O(`v${t.latest} was not installed. ${x(t.blocked)}`,t.blocked);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")try{return{from:e,to:await Se(t),mode:"binary"}}catch(a){const r=y(a.message,{platform:process.platform,channel:"binary"});throw r?O(`${x(r)}
|
|
1
|
+
import{checkReleaseFile as te}from"./release-trust.js";import{isCompiledBinary as I,hostFacts as F}from"@chatpanel/events/runtime-host.js";import $ from"node:os";import l from"node:path";import{execFile as x}from"node:child_process";import{chmod as ne,rename as M,mkdir as ae,readFile as se,writeFile as B,rm as re}from"node:fs/promises";import{existsSync as oe,readFileSync as ie,realpathSync as le}from"node:fs";import{explainInstallFailure as y,adviceText as T,npmInstallCommand as ce}from"@chatpanel/events/install-advice.js";import{restartService as de,serviceRegistered as A}from"./service.js";import{systemCaWantedOnDisk as ue}from"./system-ca.js";import{requestUpdate as pe,updateResult as me}from"./confine.js";const K=()=>l.dirname(process.env.CHATPANEL_GATEWAY_CONFIG||l.join($.homedir(),".chatpanel","gateway.config.json")),E="@chatpanel/gateway",We="chatpanel/chatpanel-gateway",G="https://dl.chatpanel.net/version/gateway",k=(process.env.CHATPANEL_NPM_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/$/,""),fe=`${k}/${E}/latest`,he=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,J=360*60*1e3,W=600*1e3,we=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),ge=15*6e4,Y=20*6e4,C=process.env.CHATPANEL_UPDATE_CACHE||l.join($.homedir(),".chatpanel","gateway-update-check.json"),N=String(process.env.CHATPANEL_SELF_UPDATE||"").toLowerCase()==="off",O={"User-Agent":"chatpanel-gateway-updater"},ye=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function V(e){try{const t=new URL(e);return t.protocol==="https:"&&ye.has(t.hostname)}catch{return!1}}let h={at:0,error:""};function Ye(){h={at:0,error:""}}function be(){return I(F())}function P(e=F()){return e.versions?.electron?"desktop":I(e)?"binary":"npm"}const U="updated with ChatPanel Desktop — update the app";function q(){return process.platform==="darwin"?`chatpanel-gateway-macos-${process.arch==="arm64"?"arm64":"x64"}`:process.platform==="linux"?process.arch==="x64"?"chatpanel-gateway-linux-x64":null:process.platform==="win32"?"chatpanel-gateway-windows-x64.exe":null}function w(e=""){const t=/(\d+(?:\.\d+){0,3})/.exec(e||"");return t?t[1]:null}function z(e,t){const n=String(e).split(".").map(Number),s=String(t).split(".").map(Number);for(let a=0;a<Math.max(n.length,s.length);a+=1){const r=(n[a]||0)-(s[a]||0);if(r)return r>0?1:-1}return 0}async function Ae(){try{return JSON.parse(await se(C,"utf8"))}catch{return null}}async function Ee(e){try{await ae(l.dirname(C),{recursive:!0}),await B(C,JSON.stringify(e))}catch{}}async function D(e,t=we){const n=new AbortController,s=setTimeout(()=>n.abort(),t);try{const a=await fetch(e,{headers:{Accept:"application/json, application/vnd.github+json",...O},signal:n.signal});if(!a.ok)throw new Error(a.status===403&&/github/.test(e)?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${a.status}`);return await a.json()}catch(a){const r=a?.cause?.code||a?.cause?.message||a?.message||String(a);throw new Error(n.signal.aborted?`the update server did not answer within ${Math.round(t/1e3)}s`:`${new URL(e).hostname}: ${r}`)}finally{clearTimeout(s)}}function j(e=process.argv[1]){let t=e?l.resolve(e):"";try{t=le(t)}catch{}const n=/^(.*[/\\]node_modules[/\\]@chatpanel[/\\]gateway)[/\\]/.exec(t);return n?n[1]:""}function ve(){const e=j();if(!e)return"";try{return String(JSON.parse(ie(l.join(e,"package.json"),"utf8")).version||"")}catch{return""}}function v(){const e=l.dirname(process.execPath);return[l.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"..","libexec","lib","node_modules","npm","bin","npm-cli.js"),l.join(e,"node_modules","npm","bin","npm-cli.js")].find(n=>oe(n))||""}function Se(e=process.env,t=process.execPath){const n={...e,npm_config_registry:k,npm_config_fund:"false",npm_config_audit:"false"};delete n.ELECTRON_RUN_AS_NODE;const s=Object.keys(n).find(a=>a.toLowerCase()==="path")||"PATH";return n[s]=[l.dirname(t),...(n[s]||"").split(l.delimiter).filter(Boolean)].filter((a,r,o)=>o.indexOf(a)===r).join(l.delimiter),n}function _e(){import("./prune-install.js").then(({pruneForeignPrebuilds:e,pruneLine:t})=>{const n=t(e({log:s=>console.log(s)}));n&&console.log(`[update]${n}`)}).catch(()=>{})}function $e(){return["install","-g",`${E}@latest`,"--ignore-scripts"]}function xe(e,{home:t=$.homedir(),platform:n=process.platform}={}){if(n==="win32"||!/\b(EACCES|EPERM)\b/.test(e||""))return"";const s=(e.match(/^npm (?:error|ERR!) path (.+)$/m)||[])[1]?.trim()||"",a=s.indexOf(`${l.sep}lib${l.sep}node_modules`),r=a>0?s.slice(0,a):"";return r?r===t||r.startsWith(t+l.sep)?`npm cannot write ${r} — part of it belongs to another user, usually from an earlier \`sudo npm i -g\` (npm's hint about ~/.npm is a different folder). Fix: sudo chown -R "$(whoami)" "${r}" — then update again.`:`npm cannot write ${r}, which belongs to another user. Install the standalone build instead — it needs no npm: curl -fsSL https://dl.chatpanel.net/install.sh | bash`:""}function Te(e=process.allowedNodeEnvironmentFlags){try{return!process.versions.bun&&e.has("--use-system-ca")}catch{return!1}}function ke({cli:e=v(),systemCa:t=!1,env:n=Se(),execPath:s=process.execPath}={}){const a=$e();return e?{cmd:s,args:[...t?["--use-system-ca"]:[],e,...a],env:n}:{cmd:"npm",args:a,env:t?{...n,NODE_OPTIONS:`${n.NODE_OPTIONS?`${n.NODE_OPTIONS} `:""}--use-system-ca`}:n}}function Ce({systemCa:e=!1}={}){const t=v(),{cmd:n,args:s,env:a}=ke({cli:t,systemCa:e});return new Promise(r=>{x(n,s,{env:a,timeout:Y,maxBuffer:8<<20,windowsHide:!0},(o,u,m)=>{const d=`${u||""}${m||""}`.trim();return o?o.killed&&!d?r({ok:!1,out:`npm was still running after ${Math.round(Y/6e4)} minutes and was stopped`}):r({ok:!1,out:d||(t?o.message:"could not run npm: it is not beside the node running this gateway and not on the service's PATH")}):(_e(),r({ok:!0,out:d}))})})}async function Ne({run:e=Ce,canSystemCa:t=Te()&&ue()}={}){const n=await e({systemCa:!1});if(n.ok||!t||y(n.out)?.kind!=="certificate")return n;console.log("[update] npm refused the registry's certificate (a re-signing proxy) — trying once more with the system's certificates");const s=await e({systemCa:!0});return s.ok?{...s,via:"system-ca"}:s}function Oe(e,t=process.versions.node,n=process.platform){return!e||process.versions.bun?null:y("",{node:t,needsNode:e,platform:n})}async function Q(e,{force:t=!1}={}){const n=P();if(n==="desktop")return{current:e,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:"desktop",service:!1,disabled:!0,note:U};if(N)return{current:e,latest:null,updateAvailable:!1,mode:n,canSelfUpdate:!1,assetUrl:null,stale:!1,error:"",npmCommand:null,channel:n==="npm"?"npm":"release",service:!1,disabled:!0};const s=q();let a=null,r=null,o=!1,u="",m=0,d="";const i=await Ae(),p=i&&i.mode===n,b=()=>{a=p&&i.latest||null,r=p&&i.assetUrl||null,m=p&&i.checkedAt||0,d=p&&i.needsNode||"",o=!0};if(!t&&p&&Date.now()-i.checkedAt<J)a=i.latest,r=i.assetUrl,m=i.checkedAt,d=i.needsNode||"";else if(!t&&h.at&&Date.now()-h.at<W)u=h.error,b();else try{if(n==="npm"){let f;try{f=await D(fe),a=w(f.version),d=String(f.engines?.node||"")}catch(ee){const H=await D(G);if(a=w(H?.npm?.version)||w(H?.version),!a)throw ee}}else{const f=await D(G);a=w(f.version)||w(f.release?.tag),r=s&&(f.release?.assets||[]).includes(s)?he(s):null}m=Date.now(),await Ee({checkedAt:m,mode:n,latest:a,assetUrl:r,needsNode:d}),h={at:0,error:""}}catch(f){u=f.message,h={at:Date.now(),error:u},b()}const L=!!a&&z(a,e)>0,_=n==="npm"&&L?Oe(d):null,X=_?!1:n==="binary"?!!r&&(process.platform!=="win32"||A()):!!j()&&(process.platform!=="win32"||A()&&!!v()),Z=n==="npm"?ce({pkg:E,platform:process.platform}):null;return{current:e,latest:a,updateAvailable:L,mode:n,canSelfUpdate:X,assetUrl:r,stale:o,error:u,npmCommand:Z,channel:n==="npm"?"npm":"release",service:A(),checkedAt:m,...n==="npm"?{node:process.versions.node,...d?{needsNode:d}:{}}:{},..._?{blocked:_}:{}}}let g=null,S=null;function Ve(e){const t=P();return t==="desktop"?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:"desktop",service:!1,disabled:!0,note:U}:N?{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!1,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:!1,disabled:!0}:((!g||(g.stale?!(h.at&&Date.now()-h.at<W):Date.now()-g.seenAt>J))&&!S&&(S=Q(e).then(s=>{g={...s,seenAt:Date.now()}}).catch(()=>{}).finally(()=>{S=null})),g?{...g,seenAt:void 0,current:e}:{current:e,latest:null,updateAvailable:!1,mode:t,canSelfUpdate:!1,stale:!0,checking:!0,error:"",npmCommand:null,channel:t==="npm"?"npm":"release",service:A()})}function qe(){g=null,S=null}async function Pe(){const e=async s=>{const a=await fetch(`https://dl.chatpanel.net/gateway/${s}`,{headers:O,redirect:"follow",signal:AbortSignal.timeout(3e4)});return!a.ok||!V(a.url||"https://dl.chatpanel.net/")?null:Buffer.from(await a.arrayBuffer())},[t,n]=await Promise.all([e("SHA256SUMS").catch(()=>null),e("SHA256SUMS.sig").catch(()=>null)]);return{sums:t?t.toString("utf8"):null,signature:n}}async function Ue(e){const t=process.execPath,n=l.dirname(t),s=l.join(n,`.chatpanel-gateway.new-${Date.now()}`),a=new AbortController,r=setTimeout(()=>a.abort(),ge);let o;try{let i;try{i=await fetch(e.assetUrl,{headers:O,redirect:"follow",signal:a.signal})}catch(p){throw new Error(`download failed: ${a.signal.aborted?"timed out":p?.cause?.code||p?.cause?.message||p?.message||p}`)}if(!i.ok)throw new Error(`download failed (HTTP ${i.status})`);if(!V(i.url||e.assetUrl))throw new Error(`refused: the download was redirected to ${i.url}, which is not a ChatPanel release host`);o=Buffer.from(await i.arrayBuffer())}finally{clearTimeout(r)}if(o.length<5<<20)throw new Error(`the download was only ${(o.length/1024).toFixed(0)} KB — that is not the gateway, so nothing was replaced`);const u=await(e.fetchManifest||Pe)(),m=te({bytes:o,name:e.assetName||q(),sums:u.sums,signature:u.signature,...e.releaseKeys?{keys:e.releaseKeys}:{}});if(!m.ok)throw new Error(`refused: ${m.reason} — nothing was replaced`);await B(s,o),process.platform!=="win32"&&await ne(s,493),process.platform==="darwin"&&await new Promise(i=>x("xattr",["-c",s],()=>i()));const d=await new Promise(i=>x(s,["--version"],{timeout:6e4,windowsHide:!0},(p,b)=>i(p?"":String(b||"").trim())));if(!w(d))throw await re(s,{force:!0}),new Error("the downloaded gateway would not run, so it was discarded");return process.platform==="win32"&&await M(t,l.join(n,`chatpanel-gateway.old-${Date.now()}.exe`)),await M(s,t),w(d)}const R=(e,t=null,n="")=>Object.assign(new Error(e),{advice:t,raw:n});async function De(e){if(N)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await Q(e,{force:!0});if(t.stale)throw new Error(`Could not reach the update server${t.error?` (${t.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!t.updateAvailable)throw new Error(`Already on the latest ${t.channel} version (v${e}).`);if(t.blocked)throw R(`v${t.latest} was not installed. ${T(t.blocked)}`,t.blocked);if(!t.canSelfUpdate)throw new Error(t.mode==="npm"?`This gateway cannot update itself here. Run: ${t.npmCommand}`:"No downloadable build for this platform — install it with npm instead.");if(t.mode==="binary")try{return{from:e,to:await Ue(t),mode:"binary"}}catch(a){const r=y(a.message,{platform:process.platform,channel:"binary"});throw r?R(`${T(r)}
|
|
2
2
|
|
|
3
|
-
The download said: ${a.message}`,r,a.message):a}if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${
|
|
3
|
+
The download said: ${a.message}`,r,a.message):a}if(process.platform==="win32")return{from:e,to:t.latest,mode:"npm",deferred:`"${process.execPath}" "${v()}" install -g ${E}@latest --registry=${k} --no-fund --no-audit`};const n=await Ne();if(!n.ok){const a=xe(n.out),r=a?null:y(n.out,{platform:process.platform,node:process.versions.node,needsNode:t.needsNode}),o=n.out.slice(0,600);throw R(a?`${a}
|
|
4
4
|
|
|
5
|
-
npm said: ${
|
|
5
|
+
npm said: ${o}`:r?`${T(r)}
|
|
6
6
|
|
|
7
|
-
npm said: ${
|
|
7
|
+
npm said: ${o}`:`npm install failed: ${n.out.slice(0,800)}`,r,o)}n.via==="system-ca"&&console.log("[update] installed through the system's certificates — a proxy on this network re-signs npm's traffic");const s=ve();if(!s||z(s,e)<=0)throw new Error(`npm ran, but the install at ${j()} is still ${s||"unreadable"} — the service launches a copy npm did not update. Run: ${t.npmCommand}`);return{from:e,to:s,mode:"npm"}}const c={state:"idle",mode:"",from:"",to:"",detail:"",advice:null,raw:"",startedAt:0,endedAt:0};function ze({result:e=()=>me(K())}={}){if(c.mode==="confined"&&c.state==="restarting"){const t=e();t&&t.at>=c.startedAt&&!t.ok&&Object.assign(c,{state:"failed",endedAt:t.at,detail:String(t.detail||"the launcher could not install it").slice(0,2400)})}return{...c}}function Qe(e,{restart:t=de,apply:n=De,kind:s=P(),confined:a=process.env.CHATPANEL_CONFINED==="1",ask:r=o=>pe({stateDir:K(),version:o})}={}){if(c.state==="installing"||c.state==="restarting")return{...c,already:!0};if(s==="desktop")return{...c,state:"failed",mode:"desktop",detail:U,refused:!0};if(a){try{r(e)}catch(o){return{...c,state:"failed",mode:"confined",detail:`could not ask the launcher: ${o?.message||o}`}}return Object.assign(c,{state:"restarting",mode:"confined",from:e,to:"",detail:"the launcher outside the sandbox is installing the signed release, then restarts the gateway",advice:null,raw:"",startedAt:Date.now(),endedAt:0}),{...c}}return Object.assign(c,{state:"installing",mode:be()?"binary":"npm",from:e,to:"",detail:"",advice:null,raw:"",startedAt:Date.now(),endedAt:0}),n(e).then(o=>{Object.assign(c,{state:"restarting",to:o.to,mode:o.mode,detail:o.deferred?`stopping to install v${o.to}, then relaunching`:`v${o.to} is installed; restarting the gateway into it`}),setTimeout(()=>{t({winInstall:o.deferred||""})||Object.assign(c,{state:"done",endedAt:Date.now(),detail:`v${o.to} is installed, but this gateway is not run by a service it can restart. Start it again yourself to run the new version.`})},400)}).catch(o=>{const u=String(o?.message||o);Object.assign(c,{state:"failed",endedAt:Date.now(),detail:u.slice(0,2400),advice:o?.advice||y(u,{platform:process.platform,channel:c.mode==="binary"?"binary":"npm"}),raw:String(o?.raw||"").slice(0,800)})}),{...c}}function Xe(){Object.assign(c,{state:"idle",mode:"",from:"",to:"",detail:"",advice:null,raw:"",startedAt:0,endedAt:0})}export{Xe as _resetUpdateJob,qe as _resetUpdateStatus,Q as checkForUpdate,z as cmpVersions,V as downloadHostAllowed,P as installKind,Ne as installWithRetry,be as isCompiledBinary,Oe as nodeGate,$e as npmInstallArgs,Se as npmInstallEnv,j as npmPackageRoot,xe as npmPermissionHint,ke as npmSpawn,Ye as resetUpdateBackoff,De as selfUpdate,Qe as startUpdate,Te as systemCaAvailable,ze as updateJob,Ve as updateStatus};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.97.2";export{o as VERSION};
|
package/src/worker-sandbox.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import{isCompiledBinary as c,hostFacts as l}from"@chatpanel/events/runtime-host.js";import"node:path";import{createSandbox as d}from"@chatpanel/bridge/src/sandbox.js";import{sandboxRecord as p}from"@chatpanel/bridge/src/events/sandbox-policy.js";function n(){if(process.env.CHATPANEL_SRT_MODULE)return process.env.CHATPANEL_SRT_MODULE;try{return import.meta.resolve("@anthropic-ai/sandbox-runtime")}catch{return""}}function u(){return c(l())}let e=null;function w({log:r=o=>console.warn(`[gateway] ${o}`),env:a=process.env}={}){if(!e&&a.CHATPANEL_CONFINED==="1"){const o=p({layer:"external",runtime:"gateway-confined",kitId:"gateway:open",mode:"open"});e={status:async()=>({enabled:!0,layer:"external",runtime:"gateway-confined",reason:null}),wrap:async(t,i,s)=>({bin:t,argv:i,opts:s,record:o})}}if(!e){const o=/^(off|0|false)$/i.test(String(process.env.CHATPANEL_SANDBOX||"")),t=n();e=d({config:{enabled:!o,mode:"none",extraHosts:[],extraWrite:[],extraDenyRead:[]},loadSrt:()=>t?import(t):Promise.reject(new Error("sandbox-runtime is not installed")),compiled:u(),loopback:[],log:r})}return e}function S(r){e=r}async function A(){e=null;const r=n();if(r)try{await(await import(r)).SandboxManager.reset()}catch{}}export{S as _setWorkerSandboxForTest,A as disposeWorkerSandbox,n as srtModuleUrl,w as workerSandbox};
|
|
Binary file
|