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

+17
View File
@@ -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);
+18
View File
@@ -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('<!doctype html><title>Local BPM fixture</title>'));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);
});
+5
View File
@@ -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));}});
+10
View File
@@ -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()<end){if(await fn())return;await new Promise(r=>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;
+1 -1
View File
@@ -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()<deadline){try{if(await fs.readFile(marker,'utf8')==='run')break;}catch{}await new Promise(r=>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);