fix: recover BPM browsers and harden redaction and Windows supervision

This commit is contained in:
abaishu0730 committed 2026-10-19 08:56:10 +08:00
1 parent acba28c879
commit db98d78f6b
14 files changed
+223 -59

No files matched your search

+9 -4
View File
@@ -5,7 +5,7 @@ const execFileAsync=promisify(execFile),DEFAULTS={intervalMs:10000,pingTimeoutMs
function restartPlan({failures=0,recent=0,...options}={}){const t={...DEFAULTS,...options},cooldown=recent>=t.maxRestarts;return {cooldown,delayMs:cooldown?t.cooldownMs:t.backoffMs[Math.min(failures,t.backoffMs.length-1)]};}
async function portsAvailable(ports){for(const port of ports){const server=net.createServer();await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',resolve);});await new Promise(r=>server.close(r));}}
class ServiceSupervisor {
constructor({stateDir,entry=path.join(require('../../shared/paths.cjs').PROJECT_ROOT,'src/server.cjs'),ports=[18765,18766],env={},timing={}}){Object.assign(this,{stateDir:path.resolve(stateDir),entry:path.resolve(entry),ports,env});this.timing={...DEFAULTS,...timing};this.state={};this.restarts=[];this.failures=0;this.stopping=false;this.started=false;}
constructor({stateDir,entry=path.join(require('../../shared/paths.cjs').PROJECT_ROOT,'src/server.cjs'),ports=[18765,18766],portsProvider,env={},timing={}}){Object.assign(this,{stateDir:path.resolve(stateDir),entry:path.resolve(entry),ports,portsProvider,env});this.timing={...DEFAULTS,...timing};this.state={};this.restarts=[];this.failures=0;this.stopping=false;this.started=false;}
snapshot(){return {...this.state};}
update(patch){Object.assign(this.state,patch,{updatedAt:new Date().toISOString()});this.store.set('state',this.state);}
async start(){
@@ -17,7 +17,7 @@ class ServiceSupervisor {
}
await new Promise((resolve,reject)=>{this.server.once('error',reject);this.server.listen(address,resolve);});this.started=true;
const previous=this.store.get('state');this.state={supervisorPid:process.pid,startedAt:new Date().toISOString(),status:'starting',restartCount:previous?.restartCount||0,childPid:null,heartbeatAt:null,reason:'initial_start'};
this.store.event('guard_started');this.update({});await portsAvailable(this.ports);await this.launch();
this.store.event('guard_started');this.update({});await this.launch();
this.timer=setInterval(()=>this.tick().catch(()=>{this.store?.event('monitor_error');}),this.timing.intervalMs);
this.logTimer=setInterval(()=>{try{this.rotateLog();}catch{}},30000);
return this;
@@ -35,7 +35,10 @@ class ServiceSupervisor {
});
}
async launch(){
if(this.stopping)return;this.misses=0;this.spawnedAt=Date.now();const instanceId=crypto.randomUUID(),heartbeatToken=crypto.randomBytes(32).toString('hex'),logFile=path.join(this.store.dir,'service.log');this.rotateLog();
if(this.stopping)return;
let ports;try{ports=await (this.portsProvider?this.portsProvider():this.ports);}catch(cause){throw Object.assign(Error('服务端口配置无效。',{cause}),{code:'EINVALIDPORTS'});}
if(!Array.isArray(ports)||!ports.length||ports.some(port=>!Number.isInteger(port)||port<1024||port>65535)||new Set(ports).size!==ports.length)throw Object.assign(Error('服务端口配置无效。'),{code:'EINVALIDPORTS'});
await portsAvailable(ports);if(this.stopping)return;this.ports=[...ports];this.misses=0;this.spawnedAt=Date.now();const instanceId=crypto.randomUUID(),heartbeatToken=crypto.randomBytes(32).toString('hex'),logFile=path.join(this.store.dir,'service.log');this.rotateLog();
const fd=fs.openSync(logFile,'a',0o600);let child;
try{child=spawn(process.execPath,[this.entry],{cwd:require('../../shared/paths.cjs').PROJECT_ROOT,env:{...process.env,...this.env,ORDER_SUPERVISOR_TOKEN:heartbeatToken,ORDER_SUPERVISOR_INSTANCE:instanceId},windowsHide:true,shell:false,stdio:['ignore',fd,fd,'ipc']});}finally{fs.closeSync(fd);}
this.child=child;this.instanceId=instanceId;this.heartbeatToken=heartbeatToken;this.childClosed=new Promise(resolve=>{this.resolveClosed=resolve;});
@@ -74,7 +77,9 @@ class ServiceSupervisor {
}
async restart(){
if(this.stopping||this.manualRestart)return;this.manualRestart=true;clearTimeout(this.restartTimer);this.store.event('manual_restart');
try{await this.endChild();this.child=null;this.update({restartCount:this.state.restartCount+1,reason:'manual_restart'});this.failures=0;this.restarts=[];await this.launch();}finally{this.manualRestart=false;}
try{await this.endChild();this.child=null;this.update({restartCount:this.state.restartCount+1,reason:'manual_restart'});this.failures=0;this.restarts=[];await this.launch();}
catch(cause){this.update({status:'failed',childPid:this.child?.pid||null,nextRestartAt:null,reason:cause.code==='EADDRINUSE'?'port_conflict':cause.code==='EINVALIDPORTS'?'config_invalid':'restart_failed'});this.store.event('restart_failed',{reason:this.state.reason});throw cause;}
finally{this.manualRestart=false;}
}
stop(){return this.stopPromise||=(async()=>{
this.stopping=true;clearInterval(this.timer);clearInterval(this.logTimer);clearTimeout(this.restartTimer);if(!this.started)return;
+39 -2
View File
@@ -6,10 +6,47 @@ function locations({stateDir,startupDir}){
const root=path.resolve(startupDir||path.join(process.env.APPDATA,'Microsoft','Windows','Start Menu','Programs','Startup'));
return {linkPath:path.join(root,'OrderNotificationAutomation.lnk'),launcherPath:path.join(path.resolve(stateDir),'supervisor','logon-launch.vbs'),wscript:path.join(process.env.SystemRoot,'System32','wscript.exe')};
}
function readShortcut(file){const raw=powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=(New-Object -ComObject WScript.Shell).CreateShortcut($d.file); @{target=$s.TargetPath;args=$s.Arguments}|ConvertTo-Json -Compress',{file});return JSON.parse(raw);}
// IShellLinkW and IPersistFile use UTF-16 even on an ANSI codepage such as 1252.
const SHELL_LINK_SOURCE=String.raw`
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
[ComImport, Guid("00021401-0000-0000-C000-000000000046")] class ShellLink {}
[ComImport, Guid("000214F9-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IShellLinkW {
void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder path,int count,IntPtr data,uint flags);
void GetIDList(out IntPtr list); void SetIDList(IntPtr list);
void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder text,int count);
void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string text);
void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder path,int count);
void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string path);
void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder args,int count);
void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string args);
void GetHotkey(out short key); void SetHotkey(short key);
void GetShowCmd(out int command); void SetShowCmd(int command);
void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder path,int count,out int index);
void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string path,int index);
void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string path,uint reserved);
void Resolve(IntPtr window,uint flags);
void SetPath([MarshalAs(UnmanagedType.LPWStr)] string path);
}
public static class UnicodeShortcut {
public static void Write(string file,string target,string args,string cwd) {
object value=new ShellLink();
try { var link=(IShellLinkW)value;link.SetPath(target);link.SetArguments(args);link.SetWorkingDirectory(cwd);link.SetDescription("Order workspace service supervisor");link.SetShowCmd(0);((IPersistFile)value).Save(file,true); }
finally { Marshal.FinalReleaseComObject(value); }
}
public static string[] Read(string file) {
object value=new ShellLink();
try { ((IPersistFile)value).Load(file,0);var link=(IShellLinkW)value;var target=new StringBuilder(32768);var args=new StringBuilder(32768);var cwd=new StringBuilder(32768);link.GetPath(target,target.Capacity,IntPtr.Zero,4);link.GetArguments(args,args.Capacity);link.GetWorkingDirectory(cwd,cwd.Capacity);return new [] {target.ToString(),args.ToString(),cwd.ToString()}; }
finally { Marshal.FinalReleaseComObject(value); }
}
}`;
function readShortcut(file){const raw=powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; Add-Type -TypeDefinition $d.source; $s=[UnicodeShortcut]::Read($d.file); @{target=$s[0];args=$s[1];cwd=$s[2]}|ConvertTo-Json -Compress',{file,source:SHELL_LINK_SOURCE});return JSON.parse(raw);}
function ownedShortcut(paths){if(!fs.existsSync(paths.linkPath))return true;const old=readShortcut(paths.linkPath);return path.resolve(old.target).toLowerCase()===path.resolve(paths.wscript).toLowerCase()&&old.args==='//B "'+paths.launcherPath+'"';}
function removeFile(file){try{fs.unlinkSync(file);}catch(e){if(e.code!=='ENOENT')throw e;}if(fs.existsSync(file))throw Error('无法确认自启动文件已移除。');}
function writeShortcut({paths,projectRoot}){powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=(New-Object -ComObject WScript.Shell).CreateShortcut($d.link); $s.TargetPath=$d.target; $s.Arguments=$d.args; $s.WorkingDirectory=$d.cwd; $s.Description="Order workspace service supervisor"; $s.Save()',{link:paths.linkPath,target:paths.wscript,args:'//B "'+paths.launcherPath+'"',cwd:path.resolve(projectRoot)});}
function writeShortcut({paths,projectRoot}){powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; Add-Type -TypeDefinition $d.source; [UnicodeShortcut]::Write($d.link,$d.target,$d.args,$d.cwd)',{link:paths.linkPath,target:paths.wscript,args:'//B "'+paths.launcherPath+'"',cwd:path.resolve(projectRoot),source:SHELL_LINK_SOURCE});}
function installAutostart({stateDir,projectRoot=require('../../shared/paths.cjs').PROJECT_ROOT,nodePath=process.execPath,startupDir,shortcutWriter=writeShortcut}={}){
const paths=locations({stateDir,startupDir}),store=new SupervisorStore(stateDir);
try{