diff --git a/scripts/service.cjs b/scripts/service.cjs index 8df6fd1..4a1e3d9 100644 --- a/scripts/service.cjs +++ b/scripts/service.cjs @@ -3,12 +3,12 @@ const fs=require('node:fs'),path=require('node:path'),{spawn}=require('node:chil const root=path.resolve(__dirname,'..'),pause=ms=>new Promise(r=>setTimeout(r,ms)); function ports(){let config={};try{config=JSON.parse(fs.readFileSync(path.join(root,'config.json'),'utf8'));}catch(e){if(e.code!=='ENOENT')throw e;}const result=[config.port||18765,config.dashboard?.port??18766];if(result.some(p=>!Number.isInteger(p)||p<1024||p>65535)||result[0]===result[1])throw Error('服务端口配置无效。');return result;} async function waitRunning(stateDir,previousInstance){const end=Date.now()+130000;let last; - while(Date.now()guard.stop().then(()=>process.exit(0),()=>process.exit(1));process.once('SIGINT',stop);process.once('SIGTERM',stop);return; + const guard=new ServiceSupervisor({stateDir,portsProvider:ports});await guard.start();const stop=()=>guard.stop().then(()=>process.exit(0),()=>process.exit(1));process.once('SIGINT',stop);process.once('SIGTERM',stop);return; } if(action==='install'||action==='uninstall'){const startup=require('../src/platform/service/windows-startup.cjs');const result=action==='install'?startup.installAutostart({stateDir}):startup.uninstallAutostart({stateDir});console.log(result.enabled?'Windows 登录自启动已启用(当前用户,后台运行)。':'Windows 登录自启动已移除。');return;} if(action==='status'){let live;try{live=await requestControl({stateDir});}catch{}const saved=readSupervisor(stateDir);console.log(JSON.stringify({supervisorResponding:!!live,state:live?.state||saved.state,autostartEnabled:!!(saved.autostart?.enabled&&fs.existsSync(saved.autostart.linkPath)),events:saved.events},null,2));return;} diff --git a/src/modules/assistant/policy.cjs b/src/modules/assistant/policy.cjs index 4dba080..a68278e 100644 --- a/src/modules/assistant/policy.cjs +++ b/src/modules/assistant/policy.cjs @@ -1,6 +1,6 @@ 'use strict'; const crypto=require('node:crypto'),{fail}=require('./store.cjs'); -function redact(value,maxLength=2000){return String(value??'').replace(/\b(?:Bearer\s+)[^\s,;]+/gi,'Bearer [已隐藏]').replace(/((?:password|passwd|api[_-]?key|token|cookie|authorization|密码)\s*[=::]\s*)([^\s,;]+)/gi,'$1[已隐藏]').replace(/\b[A-Za-z]:[\\/][^\r\n"'<>]*/g,'[本机路径已隐藏]').replace(/\\\\[^\r\n"'<>]*/g,'[共享路径已隐藏]').slice(0,maxLength);} +const {redact}=require('../../shared/redact.cjs'); const cleanMessage=(value,key)=>String(value??'').split(key||'\u0000').join('[已隐藏]'); function snapshot({workspace,scanner,storage,dashboard},user){ const w=workspace?.snapshot()||{connections:[],exceptions:[]},authorized=c=>user.role==='admin'||c.owner===user.username; diff --git a/src/modules/assistant/service.cjs b/src/modules/assistant/service.cjs index 3b9ddd6..2562dee 100644 --- a/src/modules/assistant/service.cjs +++ b/src/modules/assistant/service.cjs @@ -1,5 +1,5 @@ 'use strict'; -const {fail}=require('./store.cjs'),{redact,cleanMessage,snapshot,checkAction,parseResponse}=require('./policy.cjs'); +const {fail}=require('./store.cjs'),{cleanMessage,snapshot,checkAction,parseResponse}=require('./policy.cjs'),{redact}=require('../../shared/redact.cjs'); class AssistantService{ constructor({store,runtime,...deps}){this.store=store;this.runtime=runtime;this.deps=deps;this.running=new Map();this.actions=new Set();this.stopped=false;} context(user){return snapshot(this.deps,user);} @@ -17,7 +17,7 @@ class AssistantService{ const task=Promise.resolve().then(async()=>{ try{if(controller.signal.aborted)throw controller.signal.reason; const raw=await this.runtime.chat({config,text:cleanMessage(redact(text,4000),config.apiKey),context,history,signal:controller.signal});if(controller.signal.aborted)throw controller.signal.reason; - const response=parseResponse(raw,this.deps,principal.user);response.reply=cleanMessage(response.reply,config.apiKey);if(!config.allowActions)response.actions=[]; + const response=parseResponse(raw,this.deps,principal.user);response.reply=cleanMessage(redact(response.reply,20000),config.apiKey);if(!config.allowActions)response.actions=[]; this.store.updateTurn(turn.id,'success',{...response,evidence:[{label:'诊断快照时间',value:context.at},{label:'范围',value:`${context.connections.length} 个授权 BPM 连接,${context.servers.length} 个存储配置,${context.jobs.length} 条导出记录`}],finishedAt:new Date().toISOString()}); }catch(e){const cancelled=e.status===499&&!e.stopUnconfirmed&&controller.signal.aborted&&controller.signal.reason?.status===499;this.store.updateTurn(turn.id,cancelled?'cancelled':'error',{error:cleanMessage(redact(e.status?e.message:'ZCode 调用未完成,请检查运行包和模型配置。'),config.apiKey),finishedAt:new Date().toISOString()});} finally{clearTimeout(timer);this.running.delete(turn.id);} diff --git a/src/modules/bpm/login-form.cjs b/src/modules/bpm/login-form.cjs new file mode 100644 index 0000000..7a6821a --- /dev/null +++ b/src/modules/bpm/login-form.cjs @@ -0,0 +1,50 @@ +'use strict'; +const LOGIN_FORMS = { + 'https://sso.skyworthdigital.com': { username:'#username', password:'#password', submit:'#kc-form-login button[type="submit"]', form:'#kc-form-login', actionPath:'/realms/skyworthdigital/login-actions/authenticate' } +}; +async function fillSavedForm(lease,stored,loginForms) { + const origin=new URL(lease.page.url()).origin, form=loginForms[origin]; + if (!form || lease.blocked) return {filled:false,message:'请打开支持的 BPM 登录页面。'}; + try { + await Promise.all([lease.page.locator(form.username).waitFor({state:'visible',timeout:1500}),lease.page.locator(form.password).waitFor({state:'visible',timeout:1500})]); + // Validate and set both values in one browser task: a navigation or DOM replacement + // between separate locator.fill calls must never redirect a secret to another field. + const filled=await lease.page.evaluate(({origin,form,username,password})=>{ + if (location.origin!==origin || window!==window.top) return false; + const user=document.querySelector(form.username), secret=document.querySelector(form.password); + const usable=(node,type)=>node instanceof HTMLInputElement && node.type===type && !node.disabled && !node.readOnly && node.getClientRects().length>0 && getComputedStyle(node).visibility==='visible' && getComputedStyle(node).display!=='none'; + if (!usable(user,'text') || !usable(secret,'password') || user===secret) return false; + const set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set; + set.call(user,username);set.call(secret,password); + for (const node of [user,secret]) { node.dispatchEvent(new Event('input',{bubbles:true})); node.dispatchEvent(new Event('change',{bubbles:true})); } + return true; + },{origin,form,username:stored.username,password:stored.password}); + return {filled,message:filled?'已填入托管账号,请完成登录。':'请打开支持的 BPM 登录表单。'}; + } catch { return {filled:false,message:'请等待登录表单显示后重试。'}; } + } +async function automaticSubmitForm(lease,stored,submit,loginForms) { + const origin=new URL(lease.page.url()).origin, form=loginForms[origin]; + if (!form?.submit || lease.blocked) return false; + return lease.page.evaluate(({origin,form,stored,submit})=>{ + if (location.origin!==origin || window!==window.top) return false; + const visible=node=>!!node && node.getClientRects().length>0 && getComputedStyle(node).visibility==='visible' && getComputedStyle(node).display!=='none'; + const user=document.querySelector(form.username),secret=document.querySelector(form.password),button=document.querySelector(form.submit); + if (!(user instanceof HTMLInputElement) || user.type!=='text' || !visible(user) || user.disabled || user.readOnly || !(secret instanceof HTMLInputElement) || secret.type!=='password' || !visible(secret) || secret.disabled || secret.readOnly || !visible(button) || button.disabled || button.type!=='submit') return false; + const login=user.form; + if (!login || secret.form!==login || button.form!==login || login.method.toLowerCase()!=='post' || (form.form && !login.matches(form.form))) return false; + if ((button.getAttribute('formmethod') || login.method).toLowerCase()!=='post' || !['','_self'].includes(button.getAttribute('formtarget') || login.target)) return false; + const action=new URL(button.getAttribute('formaction') || login.action,location.href); + if (action.origin!==origin || (form.actionPath && action.pathname!==form.actionPath)) return false; + // Any additional visible field or challenge requires the user's intervention. + const challenge=/captcha|recaptcha|hcaptcha|turnstile|otp|one.?time|totp|verification|verify.?code/i; + if (Array.from(document.querySelectorAll('input,iframe,img,[id],[class]')).some(node=>visible(node) && challenge.test([node.id,node.className,node.getAttribute('name'),node.getAttribute('autocomplete'),node.getAttribute('src'),node.getAttribute('title')].join(' ')))) return false; + if (Array.from(login.elements).some(node=>visible(node) && node!==user && node!==secret && !['submit','button','hidden','reset'].includes(node.type))) return false; + if (submit) { + const set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set; + set.call(user,stored.username);set.call(secret,stored.password); + button.click(); + } + return true; + },{origin,form,stored:{username:stored.username,password:stored.password},submit}).catch(()=>false); + } +module.exports={LOGIN_FORMS,fillSavedForm,automaticSubmitForm}; diff --git a/src/modules/bpm/session-manager.cjs b/src/modules/bpm/session-manager.cjs index 8da479c..c377add 100644 --- a/src/modules/bpm/session-manager.cjs +++ b/src/modules/bpm/session-manager.cjs @@ -5,9 +5,7 @@ const { BpmVault } = require('../../platform/security/vault.cjs'); const { loadPlaywright, browserOptions } = require('../../platform/browser.cjs'); const { BpmListClient } = require('./list-client.cjs'); const DEFAULT_URLS = { main: 'https://bpmn.skyworthdigital.com/' }; -const LOGIN_FORMS = { - 'https://sso.skyworthdigital.com': { username:'#username', password:'#password', submit:'#kc-form-login button[type="submit"]', form:'#kc-form-login', actionPath:'/realms/skyworthdigital/login-actions/authenticate' } -}; +const { LOGIN_FORMS, fillSavedForm, automaticSubmitForm } = require('./login-form.cjs'); const TTL = 10 * 60 * 1000; const KEYS = new Set(['Tab','Enter','Backspace','Delete','ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Home','End','Escape','Control+A']); const error = (message, status = 400) => Object.assign(new Error(message), { status }); @@ -75,53 +73,16 @@ class BpmSessionManager { async fillSavedAccount(lease) { const stored=await this.vault().read('account:'+lease.id); if (!stored) return {filled:false,message:'请先保存托管账号。'}; - const origin=new URL(lease.page.url()).origin, form=this.loginForms[origin]; - if (!form || lease.blocked) return {filled:false,message:'请打开支持的 BPM 登录页面。'}; - try { - await Promise.all([lease.page.locator(form.username).waitFor({state:'visible',timeout:1500}),lease.page.locator(form.password).waitFor({state:'visible',timeout:1500})]); - // Validate and set both values in one browser task: a navigation or DOM replacement - // between separate locator.fill calls must never redirect a secret to another field. - const filled=await lease.page.evaluate(({origin,form,username,password})=>{ - if (location.origin!==origin || window!==window.top) return false; - const user=document.querySelector(form.username), secret=document.querySelector(form.password); - const usable=(node,type)=>node instanceof HTMLInputElement && node.type===type && !node.disabled && !node.readOnly && node.getClientRects().length>0 && getComputedStyle(node).visibility==='visible' && getComputedStyle(node).display!=='none'; - if (!usable(user,'text') || !usable(secret,'password') || user===secret) return false; - const set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set; - set.call(user,username);set.call(secret,password); - for (const node of [user,secret]) { node.dispatchEvent(new Event('input',{bubbles:true})); node.dispatchEvent(new Event('change',{bubbles:true})); } - return true; - },{origin,form,username:stored.username,password:stored.password}); - return {filled,message:filled?'已填入托管账号,请完成登录。':'请打开支持的 BPM 登录表单。'}; - } catch { return {filled:false,message:'请等待登录表单显示后重试。'}; } + return fillSavedForm(lease,stored,this.loginForms); } + async fillAccount(connection,principal) { return this.run(connection?.id,async()=>{ this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true); await this.settleNavigation(lease); return this.fillSavedAccount(lease); }); } async automaticSubmit(lease,stored,submit=false) { - const origin=new URL(lease.page.url()).origin, form=this.loginForms[origin]; - if (!form?.submit || lease.blocked) return false; - return lease.page.evaluate(({origin,form,stored,submit})=>{ - if (location.origin!==origin || window!==window.top) return false; - const visible=node=>!!node && node.getClientRects().length>0 && getComputedStyle(node).visibility==='visible' && getComputedStyle(node).display!=='none'; - const user=document.querySelector(form.username),secret=document.querySelector(form.password),button=document.querySelector(form.submit); - if (!(user instanceof HTMLInputElement) || user.type!=='text' || !visible(user) || user.disabled || user.readOnly || !(secret instanceof HTMLInputElement) || secret.type!=='password' || !visible(secret) || secret.disabled || secret.readOnly || !visible(button) || button.disabled || button.type!=='submit') return false; - const login=user.form; - if (!login || secret.form!==login || button.form!==login || login.method.toLowerCase()!=='post' || (form.form && !login.matches(form.form))) return false; - if ((button.getAttribute('formmethod') || login.method).toLowerCase()!=='post' || !['','_self'].includes(button.getAttribute('formtarget') || login.target)) return false; - const action=new URL(button.getAttribute('formaction') || login.action,location.href); - if (action.origin!==origin || (form.actionPath && action.pathname!==form.actionPath)) return false; - // Any additional visible field or challenge requires the user's intervention. - const challenge=/captcha|recaptcha|hcaptcha|turnstile|otp|one.?time|totp|verification|verify.?code/i; - if (Array.from(document.querySelectorAll('input,iframe,img,[id],[class]')).some(node=>visible(node) && challenge.test([node.id,node.className,node.getAttribute('name'),node.getAttribute('autocomplete'),node.getAttribute('src'),node.getAttribute('title')].join(' ')))) return false; - if (Array.from(login.elements).some(node=>visible(node) && node!==user && node!==secret && !['submit','button','hidden','reset'].includes(node.type))) return false; - if (submit) { - const set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set; - set.call(user,stored.username);set.call(secret,stored.password); - button.click(); - } - return true; - },{origin,form,stored:{username:stored.username,password:stored.password},submit}).catch(()=>false); + return automaticSubmitForm(lease,stored,submit,this.loginForms); } + async persistLease(lease) { await this.captureSessions(lease); const storageState=await lease.context.storageState({indexedDB:true}); @@ -205,8 +166,24 @@ class BpmSessionManager { } async browser() { if (this.stopped) throw error('BPM 服务正在关闭。',503); - if (!this.browserPromise) this.browserPromise = Promise.resolve().then(()=>this.browserFactory()).catch(cause=>{ this.browserPromise=null; throw cause; }); - return this.browserPromise; + const cached=this.browserPromise; + if (cached) { + const browser=await cached; + if (browser.isConnected?.()!==false) return browser; + this.invalidateBrowser(browser,cached); + return this.browser(); + } + const pending=Promise.resolve().then(()=>this.browserFactory()).then(browser=>{ + browser.on?.('disconnected',()=>this.invalidateBrowser(browser,pending)); + if (browser.isConnected?.()===false) { this.invalidateBrowser(browser,pending);throw error('BPM 浏览器暂不可用,请重试。',503); } + return browser; + }).catch(cause=>{if(this.browserPromise===pending)this.browserPromise=null;throw cause;}); + this.browserPromise=pending; + return pending; + } + invalidateBrowser(browser,pending) { + if(this.browserPromise===pending)this.browserPromise=null; + for(const [id,lease] of this.sessions)if(lease.browser===browser){clearTimeout(lease.timer);this.sessions.delete(id);lease.context?.close().catch(()=>{});} } async create(connection, principal) { this.authorize(connection,principal); @@ -217,6 +194,7 @@ class BpmSessionManager { const stored = await this.vault().read(connection.id); lease.sessionStorage = stored?.sessionStorage || {}; const browser = await this.browser(); + lease.browser=browser; this.authorize(connection,principal); lease.context = await browser.newContext({ viewport:{width:1280,height:800}, acceptDownloads:false, serviceWorkers:'block', permissions:[], storageState:stored?.storageState }); await lease.context.route('**/*', async route => { diff --git a/src/modules/health/runtime-health.cjs b/src/modules/health/runtime-health.cjs index ae865ba..b2e6394 100644 --- a/src/modules/health/runtime-health.cjs +++ b/src/modules/health/runtime-health.cjs @@ -1,5 +1,5 @@ 'use strict'; -const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'),{readSupervisor}=require('../../platform/service/control.cjs'),{redact}=require('../assistant/policy.cjs'); +const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'),{readSupervisor}=require('../../platform/service/control.cjs'),{redact}=require('../../shared/redact.cjs'); function timestamp(value){if(typeof value!=='string')return null;const normalized=/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/.test(value)?value.replace(' ','T')+'Z':value;const n=Date.parse(normalized);return Number.isFinite(n)?new Date(n).toISOString():null;} const latest=(...values)=>values.map(timestamp).filter(Boolean).sort().at(-1)||null; const groupStatus=items=>!items.length?'unconfigured':['error','unknown','running','pending','healthy','paused','disabled'].find(s=>items.some(i=>i.status===s))||'pending'; diff --git a/src/platform/service/supervisor.cjs b/src/platform/service/supervisor.cjs index 9f40489..0ab003d 100644 --- a/src/platform/service/supervisor.cjs +++ b/src/platform/service/supervisor.cjs @@ -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; diff --git a/src/platform/service/windows-startup.cjs b/src/platform/service/windows-startup.cjs index 40befb5..1627e65 100644 --- a/src/platform/service/windows-startup.cjs +++ b/src/platform/service/windows-startup.cjs @@ -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{ diff --git a/src/shared/redact.cjs b/src/shared/redact.cjs new file mode 100644 index 0000000..0033acb --- /dev/null +++ b/src/shared/redact.cjs @@ -0,0 +1,44 @@ +'use strict'; +const sensitive=/^(?:password|passwd|apikey|accesstoken|refreshtoken|clientsecret|secret|sessioncookie|token|cookie|authorization|密码)$/i; +const isSensitive=key=>sensitive.test(key.replace(/[_\s-]/g,'')); +function sanitize(value){ + if(Array.isArray(value))return value.map(sanitize); + if(value&&typeof value==='object')return Object.fromEntries(Object.entries(value).map(([key,item])=>[key,isSensitive(key)?'[已隐藏]':sanitize(item)])); + return typeof value==='string'?redactText(jsonSegments(value)):value; +} +// Parse balanced JSON fragments as well as complete documents. Quoted log payloads +// are decoded before traversal, so escaped JSON has the same policy as plain JSON. +function jsonSegments(source){ + let output='',cursor=0; + for(let start=0;start]*/g,'[本机路径已隐藏]') + .replace(/\\\\[^\r\n"'<>]*/g,'[共享路径已隐藏]'); +} +module.exports={redact}; diff --git a/tests/assistant/assistant.test.cjs b/tests/assistant/assistant.test.cjs index 81a0dfd..df6ad84 100644 --- a/tests/assistant/assistant.test.cjs +++ b/tests/assistant/assistant.test.cjs @@ -13,6 +13,23 @@ async function fixture(t,runtime){ store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/v1',model:'test-model',apiKey:'PRIVATE_API_KEY',allowActions:true}); return {dir,store,service,workspace,counters:()=>({checks,scans,archives})}; } + +test('nested JSON and complete credential headers are absent from runtime inputs and persisted history',async t=>{ + const calls=[],payload='{"nested":{"password":"dummy p a s s","cookie":"dummy=a; dummy2=b","authorization":"Basic dummy credential"}}\nCookie: dummySession=x; dummyCsrf=y\nAuthorization: Custom dummy auth value\nC:/local/private.txt'; + const {store,service}=await fixture(t,{chat:async input=>{calls.push(input);return JSON.stringify({reply:payload,actions:[]});}}),conversation=store.create(admin.user.id); + for(const text of [payload,'follow up']){const turn=service.send(conversation.id,admin,text);await service.running.get(turn.id).task;} + const actual=JSON.stringify({inputs:calls.map(({config,signal,...input})=>input),persisted:store.conversation(conversation.id,admin.user.id)}); + for(const secret of ['dummy p a s s','dummy=a','dummy2=b','dummy credential','dummySession=x','dummyCsrf=y','dummy auth value','local/private.txt'])assert.equal(actual.includes(secret),false,secret); +}); + +test('structured credential values at arbitrary depth and escaped JSON logs are removed before runtime and store',async t=>{ + const calls=[],deep={password:{a:{b:{c:'FAKE_DEEP_SECRET'}}},nested:[{cookie:[{a:[{b:'FAKE_ARRAY_SECRET'}]}]}],variants:{access_token:'FAKE_ACCESS_SECRET',refreshToken:'FAKE_REFRESH_SECRET','CLIENT-SECRET':'FAKE_CLIENT_SECRET',secret:'FAKE_BARE_SECRET','session_cookie':'FAKE_SESSION_SECRET'}},escaped={payload:{token:{a:{b:{c:'FAKE_ESCAPED_SECRET'}}}}}; + const payloads=[JSON.stringify(deep,null,2),'debug '+JSON.stringify(JSON.stringify(escaped))]; + const {store,service}=await fixture(t,{chat:async input=>{calls.push(input);return JSON.stringify({reply:payloads.join('\n'),actions:[]});}}),conversation=store.create(admin.user.id); + for(const text of payloads){const turn=service.send(conversation.id,admin,text);await service.running.get(turn.id).task;} + const actual=JSON.stringify({inputs:calls.map(({config,signal,...input})=>input),persisted:store.conversation(conversation.id,admin.user.id)}); + assert.doesNotMatch(actual,/FAKE_(?:DEEP|ARRAY|ESCAPED|ACCESS|REFRESH|CLIENT|BARE|SESSION)_SECRET/); +}); test('assistant conversations are private, encrypted and survive restart without exposing the API key',async t=>{ const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),{dir,store,service}=await fixture(t),c=store.create(admin.user.id);const turn=service.send(c.id,admin,'PRIVATE_CHAT_MESSAGE');await service.running.get(turn.id).task; assert.throws(()=>store.conversation(c.id,operator.user.id),e=>e.status===404);assert.deepEqual(store.conversations(operator.user.id),[]);assert.equal(store.settings().hasApiKey,true);assert.equal(store.settings().apiKey,undefined); diff --git a/tests/bpm/browser-recovery.test.cjs b/tests/bpm/browser-recovery.test.cjs new file mode 100644 index 0000000..0b1e086 --- /dev/null +++ b/tests/bpm/browser-recovery.test.cjs @@ -0,0 +1,18 @@ +'use strict'; +const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),http=require('node:http'); +const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'); +for(const deliverDisconnect of [true,false])test(`closed real Chrome is rebuilt once concurrently and late disconnect cannot remove new leases (event=${deliverDisconnect})`,async t=>{ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-recovery-'));let launches=0;const browsers=[]; + const server=http.createServer((_req,res)=>res.end('Local BPM fixture'));await new Promise(r=>server.listen(0,'127.0.0.1',r));const origin=`http://127.0.0.1:${server.address().port}`; + const manager=new BpmSessionManager({stateDir:dir,urls:{main:origin},allowedOrigins:[origin],browserFactory:async()=>{launches++;const browser=await loadPlaywright().chromium.launch(browserOptions());browsers.push(browser);return browser;}}); + t.after(async()=>{await manager.shutdown();for(const browser of browsers)await browser.close();await new Promise(r=>server.close(r));await fs.rm(dir,{recursive:true,force:true});}); + const principal={user:{username:'owner',role:'operator'},sessionId:'session'},connection={id:'dead',owner:'owner'};await manager.open(connection,principal);const first=await manager.browser(); + // Leave Playwright's own close-completion listener intact when simulating a + // missed manager event; removing all listeners would deadlock browser.close(). + const managerListener=first.listeners('disconnected').at(-1);if(!deliverDisconnect)first.off('disconnected',managerListener); + await first.close();const replacements=await Promise.all(Array.from({length:8},()=>manager.browser())); + assert.equal(replacements[0].isConnected(),true);assert.equal(launches,2);assert.ok(replacements.every(browser=>browser===replacements[0]));assert.equal(manager.sessions.has('dead'),false); + const current=replacements[0];await manager.open({...connection,id:'live'},principal);if(!deliverDisconnect)managerListener();else first.emit('disconnected'); + assert.equal(await manager.browser(),current);assert.equal(manager.sessions.has('live'),true); + assert.equal((await manager.frame('live',principal)).readUInt16BE(0),0xffd8); +}); diff --git a/tests/fixtures/reload-ports-service.cjs b/tests/fixtures/reload-ports-service.cjs new file mode 100644 index 0000000..8893e8c --- /dev/null +++ b/tests/fixtures/reload-ports-service.cjs @@ -0,0 +1,5 @@ +'use strict'; +const fs=require('node:fs'),http=require('node:http'),{respondToPing}=require('../../src/platform/service/ping.cjs'); +const port=JSON.parse(fs.readFileSync(process.env.ORDER_FIXTURE_CONFIG,'utf8')).port; +const server=http.createServer((req,res)=>respondToPing(req,res,{token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt:new Date().toISOString()})); +server.listen(port,'127.0.0.1');process.on('message',message=>{if(message==='order:shutdown'){server.closeAllConnections();server.close(()=>process.exit(0));}}); diff --git a/tests/service/service-supervisor.test.cjs b/tests/service/service-supervisor.test.cjs index 6b61930..95bbce8 100644 --- a/tests/service/service-supervisor.test.cjs +++ b/tests/service/service-supervisor.test.cjs @@ -2,6 +2,16 @@ const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),net=require('node:net'); async function port(){const s=net.createServer();await new Promise(r=>s.listen(0,'127.0.0.1',r));const p=s.address().port;await new Promise(r=>s.close(r));return p;} async function until(fn,timeout=15000){const end=Date.now()+timeout;while(Date.now()setTimeout(r,30));}assert.fail('condition did not become true');} +test('each real child launch reloads ports and refuses an unknown occupant before spawning', {timeout:30000},async t=>{ + const {ServiceSupervisor}=require('../../src/platform/service/supervisor.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'guard-reload-')),config=path.join(stateDir,'ports.json'),a=await port(),b=await port();let guard,owner; + t.after(async()=>{await guard?.stop();if(owner?.listening)await new Promise(r=>owner.close(r));await fs.rm(stateDir,{recursive:true,force:true});}); + await fs.writeFile(config,JSON.stringify({port:a}));let reads=0; + guard=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/reload-ports-service.cjs'),ports:[a],portsProvider:async()=>{reads++;return [JSON.parse(await fs.readFile(config,'utf8')).port];},env:{ORDER_FIXTURE_CONFIG:config},timing:{intervalMs:50,pingTimeoutMs:100,startupGraceMs:2000,stopGraceMs:1000}}); + await guard.start();await until(()=>guard.snapshot().status==='running');await fs.writeFile(config,JSON.stringify({port:b}));await guard.restart();await until(()=>guard.snapshot().status==='running');assert.deepEqual(guard.ports,[b]);assert.equal(reads,2); + owner=net.createServer();await new Promise(r=>owner.listen(a,'127.0.0.1',r));await fs.writeFile(config,JSON.stringify({port:a}));await assert.rejects(guard.restart(),e=>e.code==='EADDRINUSE');assert.equal(guard.child,null);assert.equal(owner.listening,true);assert.equal(guard.snapshot().status,'failed');assert.equal(guard.snapshot().reason,'port_conflict'); + await fs.writeFile(config,JSON.stringify({port:'invalid'}));await assert.rejects(guard.restart(),/端口/);assert.equal(guard.child,null);assert.equal(guard.snapshot().status,'failed');assert.equal(guard.snapshot().reason,'config_invalid'); + await fs.writeFile(config,JSON.stringify({port:b}));await guard.restart();await until(()=>guard.snapshot().status==='running');assert.deepEqual(guard.ports,[b]);assert.equal(owner.listening,true); +}); test('external guard recovers a crashed child and a live but unresponsive child, then stops without respawning',{timeout:60000},async t=>{ const {ServiceSupervisor}=require('../../src/platform/service/supervisor.cjs'),{requestControl,readSupervisor}=require('../../src/platform/service/control.cjs'); const stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-guard-')),listenPort=await port(),countFile=path.join(stateDir,'count');let guard; diff --git a/tests/service/windows-startup.test.cjs b/tests/service/windows-startup.test.cjs index f28e625..1d3afef 100644 --- a/tests/service/windows-startup.test.cjs +++ b/tests/service/windows-startup.test.cjs @@ -4,7 +4,7 @@ test('Windows login shortcut uses the current account, supports spaces and can b const {installAutostart,uninstallAutostart,readShortcut}=require('../../src/platform/service/windows-startup.cjs'),root=await fs.mkdtemp(path.join(os.tmpdir(),'order startup ')),startupDir=path.join(root,'登录启动'),stateDir=path.join(root,'状态库');t.after(()=>fs.rm(root,{recursive:true,force:true})); const projectRoot=path.join(root,'项目 带空格'),marker=path.join(root,'started.txt');await fs.mkdir(path.join(projectRoot,'scripts'),{recursive:true});await fs.writeFile(path.join(projectRoot,'scripts','service.cjs'),'require("node:fs").writeFileSync('+JSON.stringify(marker)+',process.argv[2]);'); const installed=installAutostart({stateDir,startupDir,projectRoot,nodePath:process.execPath});const shortcut=readShortcut(installed.linkPath); - assert.match(shortcut.target,/wscript\.exe$/i);assert.ok(shortcut.args.includes(installed.launcherPath));assert.equal(installed.enabled,true); + assert.match(shortcut.target,/wscript\.exe$/i);assert.equal(shortcut.args,'//B "'+installed.launcherPath+'"');assert.equal(shortcut.cwd,projectRoot);assert.equal(installed.enabled,true); require('node:child_process').execFileSync('cscript.exe',['//Nologo','//B',installed.launcherPath],{windowsHide:true,timeout:5000}); const deadline=Date.now()+5000;while(Date.now()setTimeout(r,100));}assert.equal(await fs.readFile(marker,'utf8'),'run'); const twice=installAutostart({stateDir,startupDir,projectRoot,nodePath:process.execPath});assert.equal(twice.linkPath,installed.linkPath);