@chatpanel/gateway 0.86.0 → 0.88.0
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 +10 -0
- package/bin/chatpanel-gateway-bin.mjs +2 -2
- package/bin/chatpanel-gateway.js +6 -6
- package/package.json +3 -3
- package/src/apple-helper-fetch.js +1 -0
- package/src/apple-model.js +1 -1
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/egress.js +2 -2
- package/src/inference-engines.js +1 -1
- package/src/runtime.js +6 -6
- package/src/sandbox-cli.js +7 -0
- package/src/server.js +21 -21
- package/src/service.js +11 -11
- package/src/system-ca.js +1 -0
- package/src/update.js +3 -3
- package/src/version.js +1 -1
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 J}from"node:fs";import{spawnSync as Se,spawn 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 J}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 Q(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=J.native||J}={}){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 k({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 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`),Ae={MallocLargeCache:"0"};function ee({program:e,args:t,out:n,err:s,env:r={...Ae,...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 Ee(){const{program:e,args:t}=k(),{out:n,err:s}=
|
|
23
|
-
`,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=
|
|
22
|
+
`}function Ee(){const{program:e,args:t}=k(),{out:n,err:s}=P(),r=ee({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 ke(){const e=j();p("launchctl",["unload","-w",e]),g(e)&&$(e)}function je(){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 Ie({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||Q(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 Ne(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"),te=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 ne({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",te(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 Te(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 re(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 Re=`$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 Ce(e,{runImpl:t=p,env:n=process.env}={}){if(!e)return{added:!1,dir:e};const s=re(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",te(Re)],{timeout:15e3}),{added:!0,dir:e,onPath:!0})}function _e(e,{runImpl:t=p,env:n=process.env}={}){if(!e)return!0;const s=n.Path??n.PATH??"";return U(re(t).value,e,{delimiter:";",platform:"win32",env:n})===null||U(s,e,{delimiter:";",platform:"win32",env:n})===null}function Le({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 We({pid:e=process.pid}={}){return[["powershell.exe",["-NoProfile","-NonInteractive","-Command",Le({pid:e})]],["taskkill",["/F","/FI","IMAGENAME eq chatpanel-gateway.exe","/FI",`PID ne ${e}`]]]}function K(e=p){for(const[t,n]of We())e(t,n,{timeout:15e3})}function Oe(){return process.platform==="win32"?K():(process.platform==="darwin"?p("launchctl",["bootout",`gui/${process.getuid?.()??""}/${A}`]):p("systemctl",["--user","stop","chatpanel-gateway.service"]),ie())}function De(){const{program:e,args:t}=k(),{out:n,err:s}=P(),r=ne({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=Ce(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 Ue(){p("reg",["delete",S,"/v",m,"/f"]),$(F(),{force:!0}),K()}function se(){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 Be=["^[^ ]*chatpanel-gateway( |$)","^[^ ]*(node|bun)[^ ]*( +-[^ ]+)* +[^ ]*chatpanel-gateway\\.js( |$)"];function oe(e,t=p){const n=t("ps",["-o","ppid=","-p",String(e)]);return Number((n.stdout||"").trim())||0}function He({pid:e=process.pid,ppid:t=process.ppid,parentOf:n=oe,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 ie({runImpl:e=p,keep:t=null,kill:n=r=>process.kill(r,"SIGTERM"),patterns:s=Be}={}){const r=t||He({parentOf:a=>oe(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 ae=()=>ie(),ce=e=>({win:`${e.home}\\.chatpanel\\gateway-launch.vbs`,unix:f.posix.join(e.homeUnix,".chatpanel","gateway-launch.vbs")});function Ge(e,t){const[n,...s]=t.argv;return[n==="wscript.exe"?e.exe.wscript:e.exe.powershell,...s]}function Ve(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=ce(e),c=ne({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"]),ae(),Fe(800);const u=Ge(e,c);return p(u[0],u.slice(1),{timeout:2e4}),{launcher:c.kind,wsl:!0,path:{added:!1,dir:D()}}}function Me(e){p(e.exe.reg,["delete",S,"/v",m,"/f"]),$(ce(e).unix,{force:!0}),ae()}function le(e){return p(e.exe.reg,["query",S,"/v",m]).status===0}function Fe(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 ue({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 qe(){const e=v()?
|
|
39
|
+
`}function qe(){const e=v()?I():null;if(e)return Ve(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=ue({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 Ze(){const e=v()?I():null;e&&Me(e),p("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=H();g(t)&&$(t)}function pe(){const e=v()?I():null;return e&&le(e)?!0:(p("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function Ke({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 de="net.chatpanel.bridge",Y="ChatPanelBridge";function Ye({platform:e=process.platform,runImpl:t=p,paths:n=Ke(),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?.()??""}/${de}`]);const r=f.join(s,"Library","LaunchAgents",`${de}.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 Xe({env:e=process.env}={}){return{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0,env:e}}function ct({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&&le(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],Xe({env:r})).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function lt(){try{return N(()=>g(j()),se,pe)}catch{return!1}}function fe(){try{return`http://127.0.0.1:${ve().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function he(e=fe(),{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 ge(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{Ae as DARWIN_LAUNCH_ENV,Be as GATEWAY_ARGV_PATTERNS,D as commandDir,Q as compareVersions,ge as errLogTail,ut as installService,v as isWsl,
|
|
41
|
+
`):""}catch{return""}}function ze({platform:e=process.platform,text:t=we(),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"?ee({program:s,args:r,...P()}):ue({exec:[s,...r].map(o=>/\s/.test(o)?`"${o}"`:o).join(" ")});return!t||t!==i?!1:n===null?me():!!n}catch{return!1}}function Je({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 ut({waitMs:e=4e4,version:t="",probe:n=he,stop:s=Oe,install:r=()=>N(Ee,De,qe),retire:i=Ye,wait:o=d=>new Promise(u=>setTimeout(u,d)),now:a=()=>Date.now(),force:l=!1,current:c=ze}={}){const d=fe(),u=await n(d);if(!l&&u.ok&&t&&u.version&&Q(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=z=>z.ok&&(!y||z.version===y),ye=a()+e;let C=await n(d);for(;!b(C)&&a()<ye;)await o(500),C=await n(d);const X=b(C);return{...R,health:C,ok:X,replaced:w?u.version:"",deferredTo:T?h:"",shadow:B(),errLog:X?"":ge()}}function pt(){return N(ke,Ue,Ze)}function me(){return N(je,se,pe)}function Qe(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 et({text:e,loaded:t,exists:n=g,platform:s=process.platform}){if(!e)return{state:"none",missing:[]};const o=Qe(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 we(){try{return N(()=>W(j(),"utf8"),()=>"",()=>W(H(),"utf8"))}catch{return""}}async function dt({platform:e=process.platform}={}){const t=[];let n=!1;try{n=me()}catch(l){t.push(`auto-start: ${l.message}`)}const s=e==="win32"?{state:"none",missing:[]}:et({text:we(),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&&Te(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(_e(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 he();try{const l=a.ok?String((await(await fetch(`${a.url}/health`,{signal:AbortSignal.timeout(2e3)})).json())?.bridge?.version||""):"";t.push(...Ne(Ie({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(...Je({sandbox:c,appleHelper:a.appleHelper}))}else{t.push(`running: nothing answers at ${a.url}`);const l=ge();l&&t.push(` last of ${P().err}:`,...l.split(`
|
|
42
|
+
`).map(c=>` ${c}`))}return t.join(`
|
|
43
|
+
`)}export{Ae as DARWIN_LAUNCH_ENV,Be as GATEWAY_ARGV_PATTERNS,D as commandDir,Q as compareVersions,ge as errLogTail,ut as installService,v as isWsl,ue as linUnitText,ee as macPlistText,B as pathShadow,U as pathWithDir,he as probeHealth,te as psEncode,E as realPath,k as resolveLaunch,ct as restartService,Ye as retireStandaloneBridge,Je as runningInstallLines,He as selfAndAncestors,lt as serviceRegistered,dt as serviceReport,me as serviceStatus,Pe as stableNodePath,Ie as staleBridgeCommands,Ne as staleBridgeLines,Ke as standaloneCandidates,ie as stopOtherGateways,Oe as stopService,pt as uninstallService,ze as unitCurrent,et as unitHealth,Qe as unitLaunch,q as vbscriptAvailable,_e as winCommandOnPath,Ce as winEnsureOnPath,ne as winLauncher,Xe as winRelaunchOpts,Te as winStartupDisabled,We as winStopArgs,Le as winStopScript};
|
package/src/system-ca.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import i from"node:tls";import d from"node:os";import{existsSync as l,readFileSync as u}from"node:fs";import{join as h}from"node:path";const y=/^(off|0|false|no)$/i;function C(s=null,e=process.env){return y.test(String(e.CHATPANEL_SYSTEM_CA||""))?!1:s?.tls?.systemCa!==!1}function w(s=process.env,e=d.homedir()){let t=null;try{const a=s.CHATPANEL_GATEWAY_CONFIG||h(e,".chatpanel","gateway.config.json");l(a)&&(t=JSON.parse(u(a,"utf8")))}catch{t=null}return C(t,s)}let r={on:!1,added:0,why:"not applied yet"};function x(){return{...r}}function p(s,e){const t=(a,n)=>s(a,n?.tls?.ca?n:{...n,tls:{...n?.tls,ca:e}});for(const a of Object.keys(s))t[a]=s[a];return t.chatpanelSystemCa=!0,t}function T({enabled:s=!0,tlsImpl:e=i,scope:t=globalThis,bun:a=!!process.versions.bun}={}){if(!s)return r={on:!1,added:0,why:"switched off (tls.systemCa: false, or CHATPANEL_SYSTEM_CA=off)"};if(typeof e.getCACertificates!="function"||typeof e.setDefaultCACertificates!="function")return r={on:!1,added:0,why:"this runtime cannot change its certificate list — Node 22.19 or newer can"};try{const n=e.getCACertificates("default"),c=new Set(n),f=e.getCACertificates("system").filter(o=>!c.has(o));if(f.length){const o=[...n,...f];e.setDefaultCACertificates(o),a&&typeof t.fetch=="function"&&!t.fetch.chatpanelSystemCa&&(t.fetch=p(t.fetch,o))}return r={on:!0,added:f.length+(r.on?r.added:0)}}catch(n){return r={on:!1,added:0,why:`the system's certificates could not be read (${String(n?.message||n).slice(0,120)})`}}}function _(){r={on:!1,added:0,why:"not applied yet"}}export{_ as _resetSystemCaState,x as systemCaState,C as systemCaWanted,w as systemCaWantedOnDisk,T 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";const A="@chatpanel/gateway",Oe="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(/\/$/,""),se=`${_}/${A}/latest`,re=e=>`https://dl.chatpanel.net/gateway/${e.replace(/^chatpanel-gateway-/,"")}`,F=360*60*1e3,M=600*1e3,oe=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),ie=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"},le=new Set(["dl.chatpanel.net","github.com","api.github.com","objects.githubusercontent.com","release-assets.githubusercontent.com"]);function ce(e){try{const t=new URL(e);return t.protocol==="https:"&&le.has(t.hostname)}catch{return!1}}let f={at:0,error:""};function Ue(){f={at:0,error:""}}function P(){const e=l.basename(process.execPath).toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}function de(){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 G(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 pe(){try{return JSON.parse(await Q(T,"utf8"))}catch{return null}}async function ue(e){try{await z(l.dirname(T),{recursive:!0}),await I(T,JSON.stringify(e))}catch{}}async function N(e,t=oe){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 me(){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 fe(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 he(){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 we(){return["install","-g",`${A}@latest`,"--ignore-scripts"]}function ge(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 ye(e=process.allowedNodeEnvironmentFlags){try{return!process.versions.bun&&e.has("--use-system-ca")}catch{return!1}}function be({cli:e=E(),systemCa:t=!1,env:n=fe(),execPath:s=process.execPath}={}){const a=we();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 Ae({systemCa:e=!1}={}){const t=E(),{cmd:n,args:s,env:a}=be({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")}):(he(),r({ok:!0,out:i}))})})}async function Ee({run:e=Ae,canSystemCa:t=ye()}={}){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 ve(e,t=process.versions.node,n=process.platform){return!e||process.versions.bun?null:y("",{node:t,needsNode:e,platform:n})}async function W(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=de();let a=null,r=null,c=!1,u="",o=0,i="";const d=await pe(),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(se),a=h(m.version),i=String(m.engines?.node||"")}catch(Y){const D=await N(H);if(a=h(D?.npm?.version)||h(D?.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)?re(s):null}o=Date.now(),await ue({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 j=!!a&&G(a,e)>0,$=n==="npm"&&j?ve(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:j,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 je(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=W(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 De(){w=null,v=null}async function $e(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(),ie);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(!ce(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 Se(e){if(C)throw new Error("Self-update is switched off on this gateway (CHATPANEL_SELF_UPDATE=off).");const t=await W(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 $e(t),mode:"binary"}}catch(a){const r=y(a.message,{platform:process.platform,channel:"binary"});throw r?O(`${x(r)}
|
|
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)}
|
|
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}" "${E()}" install -g ${A}@latest --registry=${_} --no-fund --no-audit`};const n=await
|
|
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}" "${E()}" install -g ${A}@latest --registry=${_} --no-fund --no-audit`};const n=await ve();if(!n.ok){const a=ye(n.out),r=a?null:y(n.out,{platform:process.platform,node:process.versions.node,needsNode:t.needsNode}),c=n.out.slice(0,600);throw O(a?`${a}
|
|
4
4
|
|
|
5
5
|
npm said: ${c}`:r?`${x(r)}
|
|
6
6
|
|
|
7
|
-
npm said: ${c}`:`npm install failed: ${n.out.slice(0,800)}`,r,c)}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=
|
|
7
|
+
npm said: ${c}`:`npm install failed: ${n.out.slice(0,800)}`,r,c)}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=fe();if(!s||W(s,e)<=0)throw new Error(`npm ran, but the install at ${k()} is still ${s||"unreadable"} — the service launches a copy npm did not update. Run: ${t.npmCommand}`);return{from:e,to:s,mode:"npm"}}const p={state:"idle",mode:"",from:"",to:"",detail:"",advice:null,raw:"",startedAt:0,endedAt:0};function Ie(){return{...p}}function He(e,{restart:t=ae,apply:n=xe}={}){return p.state==="installing"||p.state==="restarting"?{...p,already:!0}:(Object.assign(p,{state:"installing",mode:P()?"binary":"npm",from:e,to:"",detail:"",advice:null,raw:"",startedAt:Date.now(),endedAt:0}),n(e).then(s=>{Object.assign(p,{state:"restarting",to:s.to,mode:s.mode,detail:s.deferred?`stopping to install v${s.to}, then relaunching`:`v${s.to} is installed; restarting the gateway into it`}),setTimeout(()=>{t({winInstall:s.deferred||""})||Object.assign(p,{state:"done",endedAt:Date.now(),detail:`v${s.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(s=>{const a=String(s?.message||s);Object.assign(p,{state:"failed",endedAt:Date.now(),detail:a.slice(0,2400),advice:s?.advice||y(a,{platform:process.platform,channel:p.mode==="binary"?"binary":"npm"}),raw:String(s?.raw||"").slice(0,800)})}),{...p})}function Fe(){Object.assign(p,{state:"idle",mode:"",from:"",to:"",detail:"",advice:null,raw:"",startedAt:0,endedAt:0})}export{Fe as _resetUpdateJob,Le as _resetUpdateStatus,G as checkForUpdate,W as cmpVersions,de as downloadHostAllowed,ve as installWithRetry,P as isCompiledBinary,$e as nodeGate,ge as npmInstallArgs,he as npmInstallEnv,k as npmPackageRoot,ye as npmPermissionHint,Ae as npmSpawn,je as resetUpdateBackoff,xe as selfUpdate,He as startUpdate,be as systemCaAvailable,Ie as updateJob,Re as updateStatus};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.88.0";export{o as VERSION};
|