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

+1 -1
View File
@@ -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;
+2 -2
View File
@@ -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);}
+50
View File
@@ -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};
+24 -46
View File
@@ -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 => {
+1 -1
View File
@@ -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';
+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{
+44
View File
@@ -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<source.length;start++){
if(!['{','[','"'].includes(source[start]))continue;
const stack=[],quoted=source[start]==='"';let inString=false,escaped=false,end=-1;
for(let at=start;at<source.length;at++){
const char=source[at];
if(inString){if(escaped)escaped=false;else if(char==='\\')escaped=true;else if(char==='"'){inString=false;if(quoted){end=at+1;break;}}continue;}
if(char==='"'){inString=true;continue;}
if(char==='{'||char==='[')stack.push(char);
else if(char==='}'||char===']'){if(stack.pop()!==(char==='}'?'{':'['))break;if(!stack.length){end=at+1;break;}}
}
if(end<0)continue;
const fragment=source.slice(start,end);let parsed;
try{parsed=JSON.parse(fragment);}catch{continue;}
const clean=sanitize(parsed),replacement=JSON.stringify(clean);
output+=source.slice(cursor,start)+(JSON.stringify(parsed)===replacement?fragment:replacement);cursor=end;start=end-1;
}
return output+source.slice(cursor);
}
function redact(value,maxLength=2000){
return redactText(jsonSegments(String(value??''))).slice(0,maxLength);
}
function redactText(value){
return value
.replace(/("(?:password|passwd|api[_-]?key|(?:access|refresh)[_-]?token|client[_-]?secret|secret|session[_-]?cookie|token|cookie|authorization|密码)"\s*:\s*)("(?:\\.|[^"\\])*"|[^,}\]\r\n]+)/gi,'$1"[已隐藏]"')
.replace(/\b(Cookie|Authorization)\s*:\s*[^\r\n]+/gi,'$1: [已隐藏]')
.replace(/\bBearer\s+[^\s,;]+/gi,'Bearer [已隐藏]')
.replace(/((?:password|passwd|api[_-]?key|(?:access|refresh)[_-]?token|client[_-]?secret|secret|session[_-]?cookie|token|cookie|authorization|密码)\s*[=:]\s*)([^\r\n,]+)/gi,'$1[已隐藏]')
.replace(/((?:password|passwd|api[_-]?key|(?:access|refresh)[_-]?token|client[_-]?secret|secret|session[_-]?cookie|token|密码)\s*:\s*)([^\s,;]+)/gi,'$1[已隐藏]')
.replace(/\b[A-Za-z]:[\\/][^\r\n"'<>]*/g,'[本机路径已隐藏]')
.replace(/\\\\[^\r\n"'<>]*/g,'[共享路径已隐藏]');
}
module.exports={redact};