feat: integrate native BPM task processing and strict Excel test rules

This commit is contained in:
abaishu0730 committed 2026-10-23 12:01:55 +08:00
commit 8cb6a32876
444 files changed
+17045 -3182

No files matched your search

+94
View File
@@ -0,0 +1,94 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),{SessionStore}=require('../../src/modules/dashboard/sessions.cjs'),{createAuth}=require('../../src/modules/dashboard/auth.cjs'),{BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs'),{BpmConnectionLifecycle}=require('../../src/modules/bpm/connection-lifecycle.cjs'),{workspaceApi}=require('../../src/modules/workspace/api.cjs');
function fixture(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'cleanup-retry-')),store=new Store(path.join(dir,'dashboard')),workspace=new WorkspaceStore(path.join(dir,'workspace')),admin=store.bootstrap('admin','Synthetic-password-123'),worker=store.addUser({username:'worker',role:'operator',password:'Synthetic-password-123'},'admin'),next=store.addUser({username:'nextuser',role:'operator',password:'Synthetic-password-123'},'admin'),sessions=new SessionStore(path.dirname(store.file)),manager=new BpmSessionManager({stateDir:path.join(dir,'bpm'),browserFactory:()=>{throw Error('No browser allowed');}}),monitor={stopConnection:async()=>{}},lifecycle=new BpmConnectionLifecycle({workspace,manager,monitor});
let auth=createAuth({store,workspace,bpmSessions:manager,bpmMonitor:monitor,bpmLifecycle:lifecycle});
const adminToken=sessions.issue(admin.id).token,workerToken=sessions.issue(worker.id).token;
const call=async(route,body,token=adminToken)=>{let result;await auth.authenticate({request:{method:body===undefined?'GET':'POST',headers:{host:'localhost',cookie:'order_session='+token},socket:{remoteAddress:'127.0.0.1'}},response:{setHeader(){}},route,body,reply:(status,data)=>{result={status,...data};},fail:(status,message)=>{throw Object.assign(Error(message),{status});}});return result;};
const lease=(id,token=adminToken)=>{const value={id,sessionId:token,context:{close:async()=>{value.closed=true;}}};manager.sessions.set(id,value);return value;};
t.after(async()=>{auth.close();sessions.close();await manager.shutdown();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
return {store,workspace,admin,worker,next,sessions,manager,monitor,lifecycle,call,lease,workerToken,reopen(){auth.close();auth=createAuth({store,workspace,bpmSessions:manager,bpmMonitor:monitor,bpmLifecycle:lifecycle});},owner:async(id,body)=>{let result;await workspaceApi({store,workspace,user:admin,route:'/api/connections/'+id+'/owner',method:'POST',body,bpmSessions:manager,bpmMonitor:monitor,bpmLifecycle:lifecycle,reply:(_,data)=>{result=data;}});return result;}};
}
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};};
test('unfinished account retry revokes a newly issued session and its real manager lease',async t=>{
const f=fixture(t),id=f.workspace.createConnection({name:'Synthetic',owner:'worker'},f.admin,f.store.users()).id,oldLease=f.lease(id,f.workerToken),update=f.store.updateUser.bind(f.store);
f.store.updateUser=()=>{throw Error('synthetic save failure');};
const first=await f.call('/api/users/'+f.worker.id+'/revoke-sessions',{version:1});
assert.equal(first.status,503);assert.equal(oldLease.closed,true);assert.equal(first.cleanup.stages.account,false);
const fresh=f.sessions.issue(f.worker.id,Date.now(),f.store.passwordVersion(f.worker.id)).token,newLease=f.lease(id,fresh);
f.store.updateUser=update;
const second=await f.call('/api/users/'+f.worker.id+'/revoke-sessions',{version:1});
assert.equal(second.cleanupPending,false);assert.equal(newLease.closed,true);assert.equal(f.sessions.userSessionHashes(f.worker.id).length,0);
for(const token of [f.workerToken,fresh])assert.throws(()=>f.manager.authorize(f.workspace.getConnection(id),{user:f.worker,sessionId:token}),{status:401});
});
test('unfinished retry captures fresh hashes before retrying failed session row pruning',async t=>{
const f=fixture(t),id=f.workspace.createConnection({name:'Synthetic',owner:'worker'},f.admin,f.store.users()).id,update=f.store.updateUser.bind(f.store),revoke=SessionStore.prototype.revokeUser;
t.after(()=>{SessionStore.prototype.revokeUser=revoke;});f.store.updateUser=()=>{throw Error('synthetic save failure');};SessionStore.prototype.revokeUser=()=>{throw Error('synthetic session row failure');};
const first=await f.call('/api/users/'+f.worker.id+'/revoke-sessions',{version:1});assert.equal(first.cleanup.stages.sessionRows,false);assert.equal(first.cleanup.stages.sessionHashes,true);
const fresh=f.sessions.issue(f.worker.id,Date.now(),f.store.passwordVersion(f.worker.id)).token,lease=f.lease(id,fresh);
f.store.updateUser=update;SessionStore.prototype.revokeUser=revoke;
const second=await f.call('/api/users/'+f.worker.id+'/revoke-sessions',{version:1});
assert.equal(second.cleanupPending,false);assert.equal(lease.closed,true);assert.throws(()=>f.manager.authorize(f.workspace.getConnection(id),{user:f.worker,sessionId:fresh}),{status:401});
});
for(const transfer of [false,true])test(`account commit revalidates assignments added during cleanup wait (transfer=${transfer})`,async t=>{
const f=fixture(t);
const operation=f.call('/api/users/'+f.worker.id+'/lifecycle',{version:1,enabled:false,role:'operator',...(transfer?{transferTo:'nextuser'}:{})});
const id=f.workspace.createConnection({name:'New assignment',owner:'worker'},f.admin,f.store.users()).id,lease=f.lease(id);
if(!transfer){await assert.rejects(operation,{status:409});assert.equal(f.store.user(f.worker.id).enabled,true);return;}
const result=await operation;
assert.equal(result.cleanupPending,false);assert.deepEqual(result.transfer.connections,[id]);assert.equal(f.workspace.getConnection(id).owner,'nextuser');assert.equal(lease.closed,true);assert.equal(f.manager.disabled.has(id),true);
assert.throws(()=>f.workspace.createConnection({name:'Too late',owner:'worker'},f.admin,f.store.users()));
});
for(const transfer of [false,true])test(`account commit revalidates unresolved exceptions added during cleanup wait (transfer=${transfer})`,async t=>{
const f=fixture(t),operation=f.call('/api/users/'+f.worker.id+'/lifecycle',{version:1,enabled:false,role:'operator',...(transfer?{transferTo:'nextuser'}:{})});
const issue=f.workspace.createException({title:'Synthetic late issue',description:'Synthetic',component:'system',priority:'normal',owner:'worker'},f.admin,f.store.users());
if(!transfer){await assert.rejects(operation,{status:409});assert.equal(f.store.user(f.worker.id).enabled,true);return;}
const result=await operation;assert.deepEqual(result.transfer.exceptions,[issue.id]);assert.deepEqual(f.workspace.ownedWork('worker'),{connections:[],exceptions:[]});
});
test('unfinished account handoff includes new assignments and re-drains previously transferred connections',async t=>{
const f=fixture(t),firstId=f.workspace.createConnection({name:'First',owner:'worker'},f.admin,f.store.users()).id,update=f.store.updateUser.bind(f.store);
f.store.updateUser=()=>{throw Error('synthetic save failure');};
const first=await f.call('/api/users/'+f.worker.id+'/lifecycle',{version:1,enabled:false,role:'operator',transferTo:'nextuser'});assert.equal(first.status,503);
f.workspace.transferConnection(firstId,{version:1,owner:'worker'},f.admin,f.store.users());
const secondId=f.workspace.createConnection({name:'Second',owner:'worker'},f.admin,f.store.users()).id,leases=[f.lease(firstId),f.lease(secondId)];
f.store.updateUser=update;
const result=await f.call('/api/users/'+f.worker.id+'/lifecycle',{version:1,enabled:false,role:'operator',transferTo:'nextuser'});
assert.equal(result.cleanupPending,false);assert.deepEqual(new Set(result.transfer.connections),new Set([firstId,secondId]));assert.deepEqual(f.workspace.ownedWork('worker'),{connections:[],exceptions:[]});assert.equal(leases.every(lease=>lease.closed),true);
});
test('account handoff rejects ownership set drift while acquiring connection locks',async t=>{
const f=fixture(t),id=f.workspace.createConnection({name:'First',owner:'worker'},f.admin,f.store.users()).id,gate=deferred(),started=deferred();t.after(()=>gate.resolve());
const holding=f.lifecycle.run(id,async()=>{started.resolve();await gate.promise;});await started.promise;
const operation=f.call('/api/users/'+f.worker.id+'/lifecycle',{version:1,enabled:false,role:'operator',transferTo:'nextuser'});
await new Promise(r=>setImmediate(r));
const added=f.workspace.createConnection({name:'During lock wait',owner:'worker'},f.admin,f.store.users()).id;
const rejection=assert.rejects(operation,{status:409});gate.resolve();await holding;await rejection;
assert.equal(f.store.user(f.worker.id).enabled,true);assert.equal(f.workspace.getConnection(added).owner,'worker');assert.equal(f.workspace.getConnection(id).owner,'worker');
});
test('retained hash cleanup survives session pruning and auth restart',async t=>{
const f=fixture(t),id=f.workspace.createConnection({name:'Synthetic',owner:'worker'},f.admin,f.store.users()).id,lease=f.lease(id,f.workerToken),original=f.manager.releaseSessionHashes.bind(f.manager);let fail=true;
f.manager.releaseSessionHashes=async hashes=>{if(fail)throw Error('synthetic failure');return original(hashes);};
const first=await f.call('/api/users/'+f.worker.id+'/revoke-sessions',{version:1});assert.equal(first.cleanupPending,true);assert.equal(f.sessions.userSessionHashes(f.worker.id).length,0);assert.equal(lease.closed,undefined);
const pending=await f.call('/api/users');assert.equal(pending.cleanupPending,true);assert.equal(pending.cleanup.stages.sessionHashes,false);assert.doesNotMatch(JSON.stringify(pending),new RegExp(crypto.createHash('sha256').update(f.workerToken).digest('hex')));
f.reopen();fail=false;const second=await f.call('/api/users/'+f.worker.id+'/revoke-sessions',{version:2});assert.equal(second.cleanupPending,false);assert.equal(lease.closed,true);assert.equal(f.manager.revokedSessionHashes.has(crypto.createHash('sha256').update(f.workerToken).digest('hex')),true);
assert.equal(second.cleanup.stages.sessionHashes,true);
});
test('owner transfer drains a real manager lease and serializes concurrent enable',async t=>{
const f=fixture(t),id=f.workspace.createConnection({name:'Synthetic',owner:'worker'},f.admin,f.store.users()).id,lease=f.lease(id),gate=deferred(),started=deferred();t.after(()=>gate.resolve());f.monitor.stopConnection=async()=>{started.resolve();await gate.promise;};
const transfer=f.owner(id,{version:0,owner:'nextuser'});await started.promise;assert.equal(f.manager.disabled.has(id),true);let enabled=false;const enable=f.lifecycle.change(id,true,{version:1},f.admin).then(()=>{enabled=true;});await new Promise(r=>setImmediate(r));assert.equal(enabled,false);gate.resolve();const result=await transfer;await enable;assert.equal(result.cleanupPending,false);assert.equal(lease.closed,true);assert.equal(f.manager.sessions.has(id),false);assert.equal(f.workspace.getConnection(id).status,'unchecked');assert.equal(f.manager.disabled.has(id),false);
});
test('account handoff suspends another administrator lease before waiting for monitor',async t=>{
const f=fixture(t),id=f.workspace.createConnection({name:'Synthetic',owner:'worker'},f.admin,f.store.users()).id,lease=f.lease(id),gate=deferred(),started=deferred();t.after(()=>gate.resolve());f.monitor.stopConnection=async()=>{started.resolve();await gate.promise;};
const operation=f.call('/api/users/'+f.worker.id+'/lifecycle',{version:1,enabled:false,role:'operator',transferTo:'nextuser'});await started.promise;assert.equal(f.manager.disabled.has(id),true);gate.resolve();const result=await operation;assert.equal(result.cleanupPending,false);assert.equal(lease.closed,true);assert.equal(f.manager.sessions.has(id),false);
});
test('failed handoff drain retains connection IDs and protects disabled connections until retry',async t=>{
const f=fixture(t),id=f.workspace.createConnection({name:'Synthetic',owner:'worker'},f.admin,f.store.users()).id,lease=f.lease(id),original=f.manager.suspend.bind(f.manager);let fail=true;
f.manager.suspend=async id=>{f.manager.disabled.add(id);if(fail)throw Error('synthetic drain failure');return original(id);};
const first=await f.call('/api/users/'+f.worker.id+'/lifecycle',{version:1,enabled:false,role:'operator',transferTo:'nextuser'});assert.equal(first.cleanupPending,true);await assert.rejects(f.lifecycle.change(id,true,{version:1},f.admin),{status:503});f.reopen();fail=false;
const second=await f.call('/api/users/'+f.worker.id+'/lifecycle',{version:2,enabled:false,role:'operator'});assert.equal(second.cleanupPending,false);assert.equal(lease.closed,true);assert.equal(f.workspace.getConnection(id).version,1);assert.equal(f.workspace.getConnection(id).owner,'nextuser');assert.equal(f.manager.disabled.has(id),true);
});
test('account save failure after handoff invalidates sessions and retains resumable stages',async t=>{
const f=fixture(t),id=f.workspace.createConnection({name:'Synthetic',owner:'worker'},f.admin,f.store.users()).id,lease=f.lease(id),original=f.store.updateUser.bind(f.store);f.store.updateUser=()=>{throw Error('synthetic account persistence failure');};
const first=await f.call('/api/users/'+f.worker.id+'/lifecycle',{version:1,enabled:false,role:'operator',transferTo:'nextuser'});assert.equal(first.status,503);assert.equal(first.cleanupPending,true);assert.equal(first.cleanup.stages.account,false);assert.equal(lease.closed,true);await assert.rejects(f.call('/api/me',undefined,f.workerToken),{status:401});assert.equal(f.workspace.getConnection(id).owner,'nextuser');
f.store.updateUser=original;f.reopen();const second=await f.call('/api/users/'+f.worker.id+'/lifecycle',{version:1,enabled:false,role:'operator',transferTo:'nextuser'});assert.equal(second.cleanupPending,false);assert.equal(second.user.enabled,false);assert.equal(f.workspace.getConnection(id).version,1);
});
+56
View File
@@ -0,0 +1,56 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs');
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');
const {createDashboard}=require('../../src/app/dashboard.cjs');
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'account-lifecycle-')),store=new Store(path.join(dir,'dashboard')),workspace=new WorkspaceStore(path.join(dir,'workspace')),admin=store.bootstrap('admin','Synthetic-password-123'),f={dir,store,workspace,admin};t.after(async()=>{if(f.server){f.server.closeAllConnections();await new Promise(resolve=>f.server.close(resolve));}workspace.close();fs.rmSync(dir,{recursive:true,force:true});});return f;}
test('account changes protect the last enabled admin and invalidate old authorization versions',t=>{
const f=fixture(t),worker=f.store.addUser({username:'worker',password:'Synthetic-password-123',role:'operator'},'admin');
assert.equal(typeof f.store.updateUser,'function');
assert.throws(()=>f.store.updateUser(f.admin.id,{version:1,enabled:false,role:'admin'},f.admin),{status:409});
const old=f.store.passwordVersion(worker.id),saved=f.store.updateUser(worker.id,{version:1,enabled:false,role:'operator'},f.admin);
assert.equal(saved.enabled,false);assert.equal(saved.version,2);assert.equal(f.store.authenticate('worker','Synthetic-password-123'),null);assert.equal(f.store.passwordVersion(worker.id),old+1);
assert.throws(()=>f.store.updateUser(worker.id,{version:1,enabled:true,role:'operator'},f.admin),{status:409});
assert.throws(()=>f.store.updateUser(worker.id,{version:2,enabled:true,role:'admin'},{...worker,role:'operator'}),{status:403});
});
test('owner handoff pauses connections and transfers only unfinished exceptions',t=>{
const f=fixture(t),worker=f.store.addUser({username:'worker',password:'Synthetic-password-123',role:'operator'},'admin'),next=f.store.addUser({username:'nextuser',password:'Synthetic-password-123',role:'operator'},'admin'),members=f.store.users();
const connection=f.workspace.createConnection({name:'合成交接来源',owner:worker.username},f.admin,members),exception=f.workspace.createException({title:'合成异常',component:'bpm',priority:'normal',description:'fixture',owner:worker.username},f.admin,members);
assert.equal(typeof f.workspace.handoffOwner,'function');const result=f.workspace.handoffOwner(worker.username,next.username,f.admin,members);
assert.equal(result.connections.length,1);assert.equal(result.exceptions.length,1);assert.equal(f.workspace.getConnection(connection.id).owner,next.username);assert.equal(f.workspace.getConnection(connection.id).status,'disabled');
assert.equal(f.workspace.getConnection(connection.id).version,1);
assert.equal(f.workspace.snapshot().exceptions.find(item=>item.id===exception.id).owner,next.username);
assert.throws(()=>f.workspace.handoffOwner(next.username,'missing',f.admin,members),{status:400});
});
test('connection owner changes share the enable-state version and reject stale transfer forms',t=>{
const f=fixture(t),next=f.store.addUser({username:'nextuser',password:'Synthetic-password-123',role:'operator'},'admin'),connection=f.workspace.createConnection({name:'版本来源',owner:'admin'},f.admin,f.store.users());
f.workspace.setConnectionEnabled(connection.id,false,{version:0},f.admin);
assert.throws(()=>f.workspace.transferConnection(connection.id,{version:0,owner:next.username},f.admin,f.store.users()),{status:409});
const moved=f.workspace.transferConnection(connection.id,{version:1,owner:next.username},f.admin,f.store.users());assert.equal(moved.version,2);assert.equal(moved.status,'disabled');
});
test('HTTP lifecycle revokes existing sessions, drains old connection access and keeps the account disabled',async t=>{
const f=fixture(t),worker=f.store.addUser({username:'worker',password:'Synthetic-password-123',role:'operator'},'admin'),next=f.store.addUser({username:'nextuser',password:'Synthetic-password-123',role:'operator'},'admin'),connection=f.workspace.createConnection({name:'合成来源',owner:worker.username},f.admin,f.store.users()),released=[],paused=[];
assert.equal(typeof require('../../src/modules/bpm/session-manager.cjs').BpmSessionManager.prototype.suspend,'function');const server=f.server=createDashboard({store:f.store,workspace:f.workspace,outputDir:f.dir,bpmSessions:{releaseSessionHashes:async hashes=>released.push(...hashes),suspend:async id=>paused.push(id)}});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const base='http://127.0.0.1:'+server.address().port,call=(route,cookie,body)=>fetch(base+'/api'+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{Origin:base,'Content-Type':'application/json'}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});
const login=async username=>(await call('/login',null,{username,password:'Synthetic-password-123'})).headers.get('set-cookie').split(';')[0],adminCookie=await login('admin'),workerCookie=await login('worker');
assert.equal((await call('/me',workerCookie)).status,200);
const response=await call('/users/'+worker.id+'/lifecycle',adminCookie,{version:1,enabled:false,role:'operator',transferTo:next.username});assert.equal(response.status,200);const result=await response.json();assert.equal(result.user.enabled,false);assert.equal(result.cleanupPending,false);
assert.equal((await call('/me',workerCookie)).status,401);assert.equal(released.length,1);assert.deepEqual(paused,[connection.id]);assert.equal(f.workspace.getConnection(connection.id).owner,next.username);
assert.equal((await call('/users/'+next.id+'/lifecycle',workerCookie,{version:1,enabled:true,role:'admin'})).status,401);
});
test('connection recovery requests verification and deletion retires outstanding source exceptions',t=>{
const f=fixture(t),connection=f.workspace.createConnection({name:'合成来源',owner:'admin'},f.admin,f.store.users()),update=(status,at)=>f.workspace.updateConnectionSession(connection.id,{status,identity:'synthetic',checkedAt:at,checks:{portal:{ok:status==='connected',message:'synthetic'}}},f.admin);
update('connected','2026-10-21T01:00:00Z');update('error','2026-10-21T01:01:00Z');let exception=f.workspace.snapshot().exceptions.find(item=>item.connectionId===connection.id);assert.equal(exception.status,'in_progress');
update('connected','2026-10-21T01:02:00Z');exception=f.workspace.snapshot().exceptions.find(item=>item.id===exception.id);assert.equal(exception.status,'verifying');
f.workspace.disableConnection(connection.id,f.admin);f.workspace.deleteConnection(connection.id,f.admin);exception=f.workspace.snapshot().exceptions.find(item=>item.id===exception.id);assert.equal(exception.status,'retired');assert.ok(exception.retiredAt);assert.throws(()=>f.workspace.actOnException(exception.id,{version:exception.version,action:'resolve',note:'synthetic'},f.admin,f.store.users()),{status:409});
});
for(const status of ['error','login_required'])test('connection recurrence '+status+' invalidates old verification and records safe evidence',t=>{
const f=fixture(t),connection=f.workspace.createConnection({name:'合成来源',owner:'admin'},f.admin,f.store.users()),update=(value,minute)=>f.workspace.updateConnectionSession(connection.id,{status:value,identity:'synthetic',checkedAt:'2026-10-21T01:0'+minute+':00Z',checks:{portal:{ok:value==='connected',message:'synthetic'}}},f.admin);
update('connected',0);update('error',1);update('connected',2);const before=f.workspace.snapshot().exceptions.find(item=>item.connectionId===connection.id);update(status,3);const after=f.workspace.snapshot().exceptions.find(item=>item.id===before.id);
assert.equal(after.status,'in_progress');assert.equal(after.version,before.version+1);assert.equal(after.history.at(-1).evidence.status,status);assert.equal(after.history.at(-1).evidence.checkedAt,'2026-10-21T01:03:00Z');assert.equal(after.history.length,before.history.length+1);
assert.throws(()=>f.workspace.actOnException(after.id,{version:before.version,action:'resolve',note:'stale verification'},f.admin,f.store.users()),{status:409});
});
test('obsolete exception archive has a named global audit event and preserves history',t=>{
const f=fixture(t),issue=f.workspace.createException({title:'Synthetic obsolete issue',component:'system',priority:'normal',description:'fixture',owner:'admin'},f.admin,f.store.users()),saved=f.workspace.actOnException(issue.id,{version:issue.version,action:'archive',note:'Synthetic retirement evidence'},f.admin,f.store.users());
assert.equal(saved.status,'retired');assert.equal(saved.history.at(-1).action,'archive');assert.ok(f.workspace.snapshot().audit.some(item=>item.action==='归档旧异常'&&item.detail.includes(issue.title)));
});
+83
View File
@@ -0,0 +1,83 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
const {SessionStore}=require('../../src/modules/dashboard/sessions.cjs');
const OLD='Test-password-123',NEW='Changed-password-456';
async function fixture(t,options={}){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'account-password-')),store=new Store(dir);const admin=store.bootstrap('admin',OLD);
const viewer=store.addUser({username:'viewer',password:OLD,role:'viewer'},'admin'),operator=store.addUser({username:'operator',password:OLD,role:'operator'},'admin');
let server,base;async function start(){server=createDashboard({store,outputDir:dir,...options});await new Promise(r=>server.listen(0,'127.0.0.1',r));base='http://127.0.0.1:'+server.address().port;}
async function stop(){server.closeAllConnections();await new Promise(r=>server.close(r));}await start();t.after(async()=>{await stop();fs.rmSync(dir,{recursive:true,force:true});});
const call=(route,body,cookie,origin)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{Origin:origin||base,'Content-Type':'application/json'}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});
const login=async(username='admin',password=OLD)=>{const r=await call('/api/login',{username,password});assert.equal(r.status,200);return r.headers.get('set-cookie').split(';')[0];};
return {dir,store,admin,viewer,operator,call,login,restart:async()=>{await stop();await start();}};
}
const input=(currentPassword=OLD,newPassword=NEW)=>({currentPassword,newPassword,confirmPassword:newPassword});
test('every role can change own password; all old sessions expire and new credentials persist after restart',async t=>{
const f=await fixture(t);for(const username of ['admin','viewer','operator']){
const first=await f.login(username),second=await f.login(username);const result=await f.call('/api/account/password',input(),first);assert.equal(result.status,200);assert.equal((await result.json()).requiresLogin,true);assert.equal(result.headers.get('set-cookie'),null);
assert.equal((await f.call('/api/me',undefined,first)).status,401);assert.equal((await f.call('/api/me',undefined,second)).status,401);assert.equal((await f.call('/api/login',{username,password:OLD})).status,401);
assert.ok(new Store(f.dir).authenticate(username,NEW));await f.restart();assert.equal((await f.call('/api/me',undefined,second)).status,401);assert.equal((await f.call('/api/me',undefined,await f.login(username,NEW))).status,200);
}
const serialized=JSON.stringify(f.store.audit());assert.match(serialized,/修改密码/);assert.equal(serialized.includes(NEW),false);assert.equal(serialized.includes(OLD),false);
assert.equal(fs.readFileSync(path.join(f.dir,'state.sqlite')).includes(Buffer.from(NEW)),false);
});
test('invalid password edits, wrong current password, and cross-origin requests preserve existing credentials and sessions',async t=>{
const f=await fixture(t),cookie=await f.login();const original=JSON.stringify(f.store.data);
const invalid=[input('incorrect'),input(OLD,'short'),input(OLD,'x'.repeat(129)),input(OLD,OLD),{...input(),confirmPassword:'Mismatch-password-123'},{...input(),userId:f.viewer.id}];
for(const body of invalid)assert.equal((await f.call('/api/account/password',body,cookie)).status,400);
assert.equal((await f.call('/api/account/password',input(),cookie,'https://evil.test')).status,403);assert.equal((await f.call('/api/account/password',input())).status,401);
assert.equal(JSON.stringify(f.store.data),original);assert.equal((await f.call('/api/me',undefined,cookie)).status,200);
});
test('admin reset requires admin current password, revokes target sessions, preserves other accounts, and rejects self reset',async t=>{
const f=await fixture(t),admin=await f.login(),target=await f.login('viewer');const route='/api/users/'+f.viewer.id+'/password';
assert.equal((await f.call(route,input(),target)).status,403);assert.equal((await f.call(route,input('incorrect'),admin)).status,400);
assert.equal((await f.call('/api/users/'+f.admin.id+'/password',input(),admin)).status,400);assert.equal((await f.call('/api/users/missing/password',input(),admin)).status,404);
const r=await f.call(route,input(),admin);assert.equal(r.status,200);assert.equal((await r.json()).requiresLogin,false);
assert.equal((await f.call('/api/me',undefined,target)).status,401);assert.equal((await f.call('/api/me',undefined,admin)).status,200);assert.ok(f.store.authenticate('viewer',NEW));assert.ok(f.store.authenticate('admin',OLD));
assert.match(JSON.stringify(f.store.audit()),/重置密码/);
});
test('incorrect current passwords are rate limited without invalidating a valid session',async t=>{
const f=await fixture(t),cookie=await f.login();for(let i=0;i<10;i++)assert.equal((await f.call('/api/account/password',input('incorrect'),cookie)).status,400);
assert.equal((await f.call('/api/account/password',input(),cookie)).status,429);assert.equal((await f.call('/api/me',undefined,cookie)).status,200);
});
test('password version rejects old sessions even if eager session cleanup fails',async t=>{
const f=await fixture(t),cookie=await f.login();const original=SessionStore.prototype.revokeUser;SessionStore.prototype.revokeUser=()=>{throw Error('injected cleanup failure');};
try{assert.equal((await f.call('/api/account/password',input(),cookie)).status,200);}finally{SessionStore.prototype.revokeUser=original;}
assert.equal((await f.call('/api/me',undefined,cookie)).status,401);await f.restart();assert.equal((await f.call('/api/me',undefined,cookie)).status,401);await f.login('admin',NEW);
});
test('password change closes only the target account BPM login windows',async t=>{
const crypto=require('node:crypto'),{BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
const f=await fixture(t),first=await f.login('viewer'),second=await f.login('viewer'),admin=await f.login();
const cookies=[first,second,admin],manager={revokedSessionHashes:new Set(),sessions:new Map(cookies.map((cookie,i)=>[String(i),{id:String(i),sessionId:cookie.split('=')[1]}])),run:async(id,work)=>work(),async closeLease(id){this.sessions.delete(id);}};
const hashes=new SessionStore(f.dir);const targetHashes=hashes.userSessionHashes(f.viewer.id);hashes.close();
assert.equal(targetHashes.length,2);await BpmSessionManager.prototype.releaseSessionHashes.call(manager,targetHashes);assert.deepEqual([...manager.sessions.keys()],['2']);
assert.equal(targetHashes.includes(crypto.createHash('sha256').update(admin.split('=')[1]).digest('hex')),false);
});
test('existing database sessions survive schema migration until their account password changes',async t=>{
const {DatabaseSync}=require('node:sqlite'),crypto=require('node:crypto');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'account-legacy-session-')),store=new Store(dir),user=store.bootstrap('admin',OLD),token=crypto.randomBytes(32).toString('hex');
const db=new DatabaseSync(path.join(dir,'auth.sqlite'));db.exec('CREATE TABLE sessions(hash TEXT PRIMARY KEY,userId TEXT NOT NULL,expires INTEGER NOT NULL,renewedAt INTEGER NOT NULL)');db.prepare('INSERT INTO sessions VALUES(?,?,?,?)').run(crypto.createHash('sha256').update(token).digest('hex'),user.id,Date.now()+86400000,Date.now());db.close();
const server=createDashboard({store,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});
const base='http://127.0.0.1:'+server.address().port,cookie='order_session='+token;
assert.equal((await fetch(base+'/api/me',{headers:{Cookie:cookie}})).status,200);
const updated=await fetch(base+'/api/account/password',{method:'POST',headers:{Origin:base,'Content-Type':'application/json',Cookie:cookie},body:JSON.stringify(input())});assert.equal(updated.status,200);assert.equal((await fetch(base+'/api/me',{headers:{Cookie:cookie}})).status,401);
});
test('a delayed password response never clears or renews over a later login cookie',async t=>{
let arrived,release;const entered=new Promise(r=>arrived=r),gate=new Promise(r=>release=r);
const f=await fixture(t,{bpmSessions:{async releaseSessionHashes(){arrived();await gate;}}}),cookie=await f.login();
const {DatabaseSync}=require('node:sqlite');const db=new DatabaseSync(path.join(f.dir,'auth.sqlite'));db.prepare('UPDATE sessions SET renewedAt=?').run(Date.now()-2*86400000);db.close();
const pending=f.call('/api/account/password',input(),cookie);await entered;
try{const fresh=await f.login('viewer');release();const result=await pending;assert.equal(result.status,200);assert.equal(result.headers.get('set-cookie'),null,'late credential response must not overwrite a newer browser login');assert.equal((await f.call('/api/me',undefined,fresh)).status,200);}finally{release();}
});
test('revoked BPM principals queued before lease creation cannot open a new login window',async()=>{
const crypto=require('node:crypto'),{BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
const manager=new BpmSessionManager({stateDir:os.tmpdir()}),principal={sessionId:'revoked-token',user:{id:'a',username:'admin',role:'admin'}},connection={id:'queued',status:'disconnected'};
let release;const gate=new Promise(r=>release=r);const blocker=manager.run(connection.id,()=>gate);
manager.create=async(connection,principal)=>{manager.authorize(connection,principal);const lease={id:connection.id,sessionId:principal.sessionId,expiresAt:Date.now()+10000,page:{url:()=> 'https://bpmn.skyworthdigital.com/'}};manager.sessions.set(connection.id,lease);return lease;};
const opening=assert.rejects(manager.open(connection,principal),e=>e.status===401);
try{await manager.releaseSessionHashes([crypto.createHash('sha256').update(principal.sessionId).digest('hex')]);}finally{release();}
await blocker;await opening;assert.equal(manager.sessions.size,0);assert.throws(()=>manager.authorize(connection,principal),e=>e.status===401);
});
+46
View File
@@ -0,0 +1,46 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
const OLD='Test-password-123',NEW='Changed-password-456';
test('team account page retains failed cleanup warning and offers a working refresh retry',{timeout:30000},async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'account-cleanup-ui-')),store=new Store(dir);store.bootstrap('admin',OLD);const worker=store.addUser({username:'worker',role:'operator',password:OLD},'admin');let fail=true;
const {SessionStore}=require('../../src/modules/dashboard/sessions.cjs'),sessions=new SessionStore(dir);sessions.issue(worker.id);sessions.close();
const server=createDashboard({store,outputDir:dir,bpmSessions:{releaseSessionHashes:async()=>{if(fail)throw Error('Synthetic cleanup failure');}}});await new Promise(r=>server.listen(0,'127.0.0.1',r));const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});
const page=await browser.newPage();page.setDefaultTimeout(5000);await page.goto('http://127.0.0.1:'+server.address().port+'/#users');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill(OLD);await page.getByRole('button',{name:'登录',exact:true}).click();await page.locator('[data-revoke-sessions="'+worker.id+'"]').click();await page.locator('#account-cleanup-warning').waitFor();await page.reload();await page.locator('#account-cleanup-warning').waitFor();fail=false;await page.getByRole('button',{name:'重试会话清理',exact:true}).click();await page.locator('#account-cleanup-warning').waitFor({state:'detached'});assert.equal(store.user(worker.id).version,2);
});
test('team UI hands off and disables an account while preserving last-admin protection',{timeout:45000},async t=>{
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),dir=fs.mkdtempSync(path.join(os.tmpdir(),'account-lifecycle-ui-')),store=new Store(path.join(dir,'dashboard')),workspace=new WorkspaceStore(path.join(dir,'workspace')),admin=store.bootstrap('admin',OLD),worker=store.addUser({username:'worker',role:'operator',password:OLD},'admin'),next=store.addUser({username:'nextuser',role:'operator',password:OLD},'admin');
const connection=workspace.createConnection({name:'UI合成来源',owner:worker.username},admin,store.users()),server=createDashboard({store,workspace,outputDir:dir});let browser;
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const base='http://127.0.0.1:'+server.address().port;
t.after(async()=>{await browser?.close();server.closeAllConnections();await new Promise(resolve=>server.close(resolve));workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:390,height:844}}),errors=[];page.on('pageerror',error=>errors.push(error.message));
await page.goto(base+'/#users');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill(OLD);await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByText('worker',{exact:true}).waitFor();
assert.equal(await page.locator('[data-manage-user="'+worker.id+'"]').count(),1,'team account settings must be actionable');await page.locator('[data-manage-user="'+worker.id+'"]').click();let form=page.locator('#user-lifecycle-form');
await form.getByLabel('账号状态',{exact:true}).selectOption('disabled');await form.getByLabel('交接负责人',{exact:true}).selectOption(next.username);await form.getByRole('button',{name:'保存账号设置',exact:true}).click();await page.getByText('账号设置已保存,原登录已撤销;转交连接保持暂停。',{exact:true}).waitFor();
assert.equal(store.user(worker.id).enabled,false);assert.equal(workspace.getConnection(connection.id).owner,next.username);assert.equal(workspace.getConnection(connection.id).status,'disabled');
await page.locator('[data-manage-user="'+admin.id+'"]').click();form=page.locator('#user-lifecycle-form');await form.getByLabel('账号状态',{exact:true}).selectOption('disabled');await form.getByRole('button',{name:'保存账号设置',exact:true}).click();await form.getByText('必须保留至少一个启用的管理员。',{exact:true}).waitFor();assert.equal(store.user(admin.id).enabled,true);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
});
test('account UI lets every role change passwords, validates confirmation, and gives admins a member reset form',{timeout:90000},async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'account-ui-')),store=new Store(dir);const admin=store.bootstrap('admin',OLD),viewer=store.addUser({username:'viewer',password:OLD,role:'viewer'},'admin');store.addUser({username:'operator',password:OLD,role:'operator'},'admin');
const server=createDashboard({store,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;let browser;
t.after(async()=>{await browser?.close();server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const errors=[];
const login=async(page,username,password=OLD)=>{await page.getByLabel('账号',{exact:true}).fill(username);await page.getByLabel('密码',{exact:true}).fill(password);await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('link',{name:'修改密码',exact:true}).waitFor({timeout:5000});};
const page=await browser.newPage({viewport:{width:1440,height:1000}});page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/#users');await login(page,'admin');
assert.equal(await page.locator('[data-reset-user="'+admin.id+'"]').count(),0);await page.locator('[data-reset-user="'+viewer.id+'"]').click();
await page.getByLabel('管理员当前密码',{exact:true}).fill(OLD);await page.getByLabel('成员新密码',{exact:true}).fill(NEW);await page.getByLabel('确认成员新密码',{exact:true}).fill(NEW);await page.getByRole('button',{name:'确认重置密码',exact:true}).click();await page.getByText('成员密码已重置,该账号需要重新登录。',{exact:true}).waitFor();assert.ok(store.authenticate('viewer',NEW));assert.equal(await page.locator('#password-reset-form').count(),0);
// The separate create-user flow remains usable after introducing reset controls.
await page.getByLabel('登录账号',{exact:true}).fill('new-member');await page.getByLabel('初始密码',{exact:true}).fill(OLD);await page.getByRole('button',{name:'创建账号',exact:true}).click();await page.getByText('new-member',{exact:true}).waitFor();
for(const [username,password]of [['admin',OLD],['operator',OLD],['viewer',NEW]]){
const account=username==='admin'?page:await browser.newPage();if(account!==page){account.on('pageerror',e=>errors.push(e.message));await account.goto(base+'/#account');await login(account,username,password);}
await account.getByRole('link',{name:'修改密码',exact:true}).click();await account.getByLabel('当前密码',{exact:true}).fill('incorrect');await account.getByLabel('新密码',{exact:true}).fill('Final-password-789');await account.getByLabel('确认新密码',{exact:true}).fill('different-password-789');await account.getByRole('button',{name:'保存新密码',exact:true}).click();await account.getByText('两次输入的新密码不一致。',{exact:true}).waitFor();
await account.getByLabel('确认新密码',{exact:true}).fill('Final-password-789');await account.getByRole('button',{name:'保存新密码',exact:true}).click();await account.getByText('当前密码不正确。',{exact:true}).waitFor();assert.equal(await account.getByLabel('新密码',{exact:true}).inputValue(),'Final-password-789');
await account.getByLabel('当前密码',{exact:true}).fill(password);
if(username==='admin'){await account.setViewportSize({width:390,height:844});assert.equal(await account.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await fs.promises.mkdir(path.resolve('output/verification'),{recursive:true});await account.screenshot({path:path.resolve('output/verification/account-password-mobile.png'),fullPage:true});await account.setViewportSize({width:1440,height:1000});}
let release,arrived;const pending=new Promise(r=>arrived=r);
if(username==='operator')await account.route('**/api/account/password',async route=>{arrived();await new Promise(r=>release=r);await route.continue();},{times:1});
await account.getByRole('button',{name:'保存新密码',exact:true}).click();
if(username==='operator'){await pending;await account.getByRole('link',{name:'系统设置',exact:true}).click();release();}
await account.getByRole('heading',{name:'登录工作台',exact:true}).waitFor({timeout:5000});await account.getByText('密码已修改,请使用新密码重新登录。',{exact:true}).waitFor();await login(account,username,'Final-password-789');assert.ok(store.authenticate(username,'Final-password-789'));
}
assert.deepEqual(errors,[]);
});
+45
View File
@@ -0,0 +1,45 @@
'use strict';
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');const net=require('node:net');
const {main}=require('../../src/server.cjs');const {NotificationStore}=require('../../src/modules/notifications/store.cjs');
const {NotificationService}=require('../../src/modules/notifications/service.cjs');
async function freePort(){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 fixture(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-application-'));return {stateDir:dir,quiet:true,config:{port:await freePort(),outputDir:path.join(dir,'output'),dashboard:{port:await freePort(),host:'127.0.0.1'}}};}
test('formal application never starts the retired generic notification scheduler',async t=>{
const options=await fixture(t),start=NotificationService.prototype.start;let starts=0;NotificationService.prototype.start=function(){starts++;};let app;
try{app=await main(options);assert.equal(starts,0);}finally{NotificationService.prototype.start=start;await app?.stop();await fs.rm(options.stateDir,{recursive:true,force:true});}
});
test('second main rejects before recovering or mutating current frozen business evidence',async t=>{
const options=await fixture(t),app=await main(options);t.after(async()=>{await app.stop();await fs.rm(options.stateDir,{recursive:true,force:true});});
const batch={id:'owned-frozen',status:'prepared',cutoff:new Date(Date.now()+300000).toISOString(),orderIds:[],text:'synthetic frozen evidence'};app.orderRules.put('batches',batch);
let recoveries=0;const original=NotificationStore.prototype.recover;NotificationStore.prototype.recover=function(){recoveries++;return original.call(this);};
try{await assert.rejects(main(options),e=>e.code==='ORDER_INSTANCE_OWNED');assert.equal(recoveries,0);assert.deepEqual(app.orderRules.get('batches',batch.id),batch);assert.equal(app.notifications.historyOnly,true);assert.equal(app.notifications.tick,undefined);}finally{NotificationStore.prototype.recover=original;}
});
test('validation failure and occupied dashboard port both release state ownership',async t=>{
const options=await fixture(t);t.after(()=>fs.rm(options.stateDir,{recursive:true,force:true}));await assert.rejects(main({...options,config:{...options.config,dashboard:{port:1}}}),/端口/);
const occupied=net.createServer();await new Promise(r=>occupied.listen(options.config.dashboard.port,'127.0.0.1',r));
try{await assert.rejects(main(options),e=>e.code==='EADDRINUSE');}finally{await new Promise(r=>occupied.close(r));}
const app=await main(options);await app.stop();const again=await main(options);await again.stop();
});
test('partial construction failure closes earlier databases and releases ownership',async t=>{
const options=await fixture(t);t.after(()=>fs.rm(options.stateDir,{recursive:true,force:true}));await fs.writeFile(path.join(options.stateDir,'mail'),'blocks directory initialization');
await assert.rejects(main(options));await fs.rm(path.join(options.stateDir,'mail'));
// Windows refuses this rename if the workspace database remains open.
const db=path.join(options.stateDir,'workspace','workspace.sqlite');const moved=db+'.closed';await fs.rename(db,moved);await fs.rename(moved,db);
const app=await main(options);await app.stop();
});
test('shutdown attempts every resource and releases ownership despite teardown errors',async t=>{
const options=await fixture(t);t.after(()=>fs.rm(options.stateDir,{recursive:true,force:true}));const app=await main(options);
const close=app.health.close.bind(app.health);app.health.close=()=>{close();throw new Error('health teardown fixture');};const stop=app.assistant.stop.bind(app.assistant);app.assistant.stop=async()=>{await stop();throw new Error('assistant teardown fixture');};
await assert.rejects(app.stop(),e=>e instanceof AggregateError&&e.errors.length===2);
assert.equal(app.workspace.db,null);assert.equal(app.mail.store.db,null);assert.equal(app.notifications.store.db,null);assert.equal(app.server.listening,false);assert.equal(app.dashboard.listening,false);
const next=await main(options);await next.stop();
});
test('dashboard asset initialization failure closes the already-created session store',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-assets-fail-'));t.after(()=>fs.rm(dir,{recursive:true,force:true}));
const {Store}=require('../../src/modules/dashboard/store.cjs');const {SessionStore}=require('../../src/modules/dashboard/sessions.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const Module=require('node:module');
const originalResolve=Module._resolveFilename,originalClose=SessionStore.prototype.close;let closed=0;
Module._resolveFilename=function(id,...rest){if(id==='@tabler/core/dist/css/tabler.min.css')throw new Error('fixture missing asset');return originalResolve.call(this,id,...rest);};SessionStore.prototype.close=function(){closed++;return originalClose.call(this);};
try{assert.throws(()=>createDashboard({store:new Store(path.join(dir,'dashboard')),outputDir:dir}),/fixture missing asset/);assert.equal(closed,1);}finally{Module._resolveFilename=originalResolve;SessionStore.prototype.close=originalClose;}
});
@@ -4,7 +4,7 @@ const fs = require('node:fs/promises');
const vm = require('node:vm');
test('asset collection keeps source CSS order even when network completion order differs', async () => {
const worker = await fs.readFile(require.resolve('../extension/worker.js'),'utf8');
const worker = await fs.readFile(require.resolve('../../extension/worker.js'),'utf8');
const responses = {
'https://bpm.skyworthdigital.com/first.css': {delay:30,text:'body{color:red}'},
'https://bpm.skyworthdigital.com/second.css': {delay:0,text:'body{color:blue}'}
+15
View File
@@ -0,0 +1,15 @@
const test=require('node:test'),assert=require('node:assert/strict'),vm=require('node:vm'),fs=require('node:fs');
test('business list state preserves whitelisted filters and account separation',()=>{
const saved=new Map(),context={window:{},document:{querySelectorAll:()=>[]},URLSearchParams,location:{hash:''},history:{replaceState(){}},sessionStorage:{getItem:k=>saved.get(k),setItem:(k,v)=>saved.set(k,v),get length(){return saved.size},key:i=>[...saved.keys()][i],removeItem:k=>saved.delete(k)}};vm.runInNewContext(fs.readFileSync('web/modules/records/state.js','utf8'),context);const s=context.window.RecordState;
assert.equal(s.isRecord('#notification-orders?page=3'),true);s.configure({id:'alice'},()=>{});s.commit('notification-orders',{q:'order',page:3,pageSize:50,categoryId:'cat',secret:'no'});assert.match(s.href('notification-orders'),/page=3/);assert.equal(s.normalize('notification-orders',{secret:'no'}).secret,undefined);s.configure({id:'bob'},()=>{});assert.equal(s.href('notification-orders'),'#notification-orders');assert.equal(s.defaults('notification-batches').scope,'active');
});
test('retired supervisor entry delegates to health without a write form',async()=>{
let renders=0;const context={window:{HealthViews:{render:async()=>renders++}}};vm.runInNewContext(fs.readFileSync('web/modules/workspace/view.js','utf8'),context);await context.window.WorkspaceViews.supervisor({},()=>true);assert.equal(renders,1);
});
test('primary order routes stay outside settings groups and configuration belongs to business settings',()=>{
const context={window:{addEventListener(){}}};vm.runInNewContext(fs.readFileSync('web/modules/navigation/view.js','utf8'),context);const nav=context.window.AppNavigation;
for(const route of ['notification-orders','notification-batches','notification-execution','notification-history'])assert.equal(nav.sectionFor(route),null,route);
for(const route of ['schedule','calendar','templates','notification-settings'])assert.equal(nav.sectionFor(route),'business-settings',route);
assert.deepEqual(Array.from(nav.groups['business-settings']),['order-rules','rule-fields','schedule']);assert.equal(nav.groups['order-notifications'],undefined);
});
+31
View File
@@ -0,0 +1,31 @@
'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');
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function fixture(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'business-query-ui-')),runtime=await startTestDashboard({stateDir:dir,mailHistory:true}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});
for(let i=0;i<83;i++)runtime.orderRules.put('orders',{id:'order-'+String(i).padStart(3,'0'),categoryId:'cat',status:'pending',sample:{connectionId:'c',fields:{private:'DO NOT EXPOSE'}},event:{connectionId:'c',orderNo:'ORDER '+i,receivedAt:'2026-10-20T10:00:00Z'},createdAt:'2026-10-20T10:00:00Z'});
runtime.orderRules.put('batches',{id:'old-prepared',status:'prepared',subject:'旧窗口待发批次',categoryId:'cat',orderIds:['order-000'],windowStart:'2020-01-01T00:00:00Z',text:'冻结正文',to:['test@example.invalid'],cc:[]});
const page=await browser.newPage({viewport:{width:1280,height:900}});page.setDefaultTimeout(6000);const base='http://127.0.0.1:'+runtime.server.address().port;return {page,runtime,base};}
test('business lists paginate, query on enter, retain detail during background updates, and keep mobile width',{timeout:90000},async t=>{
const {page,runtime,base}=await fixture(t);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.clock.install();await page.goto(base+'/#notification-orders?page=999');await login(page);await page.waitForFunction(()=>document.querySelector('[data-record-count]')?.textContent.includes('第 4 / 4'));
assert.equal(await page.locator('[data-business-detail]').count(),8);await page.getByLabel('每页条数',{exact:true}).selectOption('50');await page.waitForFunction(()=>document.querySelectorAll('[data-business-detail]').length===50);
await page.getByRole('button',{name:'查看详情',exact:true}).first().click();await page.getByRole('dialog',{name:'业务详情'}).getByRole('heading',{name:'处理进度'}).waitFor();
runtime.orderRules.put('orders',{id:'new',status:'blocked',event:{orderNo:'NEW',connectionId:'c',receivedAt:'2026-10-21T00:00:00Z'}});await page.clock.fastForward(11000);await page.getByText('记录有更新。',{exact:true}).waitFor();assert.equal(await page.locator('[data-business-detail]').count(),50);await page.getByRole('dialog').getByRole('heading',{name:'处理进度'}).waitFor();
await page.getByRole('button',{name:'关闭详情',exact:true}).click();await page.clock.fastForward(500);await page.locator('[name=q]').fill('ORDER 8');await page.locator('[name=q]').press('Enter');await page.waitForFunction(()=>document.querySelectorAll('[data-business-detail]').length===4);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
await page.goto(base+'/#notification-history');await page.getByText('旧窗口待发批次',{exact:true}).waitFor();assert.equal(new URL(page.url()).hash,'#notification-batches?scope=all');assert.deepEqual(errors,[]);
});
test('failed pagination retains successful rows and slow request cannot replace destination',{timeout:90000},async t=>{
const {page,base}=await fixture(t);await page.goto(base+'/#notification-orders');await login(page);await page.locator('[data-business-detail]').first().waitFor();let held;await page.route('**/api/order-rules/orders?*',route=>{if(new URL(route.request().url()).searchParams.get('page')==='2')held=route;else route.continue();});await page.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-next]').disabled);while(!held)await new Promise(r=>setTimeout(r,20));await held.fulfill({status:503,json:{error:'隔离分页失败'}});await page.getByRole('button',{name:'重试加载',exact:true}).waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 1 /);assert.equal(await page.locator('[data-business-detail]').count(),25);
held=null;await page.getByRole('button',{name:'重试加载',exact:true}).click();while(!held)await new Promise(r=>setTimeout(r,20));await page.goto(base+'/#notification-batches');await page.getByText('旧窗口待发批次',{exact:true}).waitFor();await held.fulfill({json:{items:[],total:0,page:1,pageSize:25}}).catch(()=>{});await page.getByText('旧窗口待发批次',{exact:true}).waitFor();
});
test('business list links retain independent applied pages through tab return, reload and account logout',{timeout:90000},async t=>{
const {page,base}=await fixture(t);await page.goto(base+'/#notification-orders');await login(page);await page.locator('[data-record-count]').waitFor();await page.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 2 /'));await page.locator('#sidebar-menu a[data-view=notification-batches]').click();await page.getByText('旧窗口待发批次',{exact:true}).waitFor();await page.locator('#sidebar-menu a[data-view=notification-orders]').click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 2 /'),null,{timeout:2500});await page.reload();await page.waitForFunction(()=>document.querySelector('[data-record-count]')?.textContent.includes('第 2 /'));await page.getByRole('button',{name:'退出',exact:true}).click();await page.locator('#login-form').waitFor();assert.equal(await page.evaluate(()=>Object.keys(sessionStorage).filter(k=>k.startsWith('ona-record-navigation:')).length),0);
});
test('dismissal cancels late details, guards Escape drafts, and sent batch links include history',{timeout:90000},async t=>{
const {page,runtime,base}=await fixture(t);runtime.orderRules.put('batches',{id:'sent-reference',status:'sent',subject:'已发送关联批次',orderIds:['order-000'],text:'历史正文',attachments:[]});
await page.goto(base+'/#notification-orders?q=order-000');await login(page);await page.locator('[data-business-detail]').waitFor();let release,started;const ready=new Promise(r=>started=r),gate=new Promise(r=>release=r);t.after(()=>release());
await page.route('**/api/order-rules/orders/order-000',async route=>{started();await gate;await route.continue().catch(()=>{});});await page.getByRole('button',{name:'查看详情',exact:true}).click();await ready;await page.getByRole('button',{name:'关闭详情',exact:true}).click();await page.getByRole('dialog',{name:'业务详情'}).waitFor({state:'hidden'});release();await page.unroute('**/api/order-rules/orders/order-000');await page.waitForTimeout(600);assert.equal(await page.locator('.record-detail.show,.record-detail.showing').count(),0);
await page.getByRole('button',{name:'查看详情',exact:true}).click();const link=page.getByRole('link',{name:'已发送关联批次',exact:true});await link.waitFor();assert.match(await link.getAttribute('href'),/scope=all/);await link.click();await page.getByText('已发送关联批次',{exact:true}).waitFor();
runtime.orderRules.put('batches',{id:'failed-draft',status:'failed',subject:'失败批次草稿',orderIds:['order-000'],text:'冻结正文',attachments:[],version:1});await page.goto(base+'/#notification-batches?q=failed-draft');await page.getByRole('button',{name:'查看详情',exact:true}).click();await page.locator('.record-detail.show:not(.showing)').waitFor();await page.locator('[data-business-action] textarea').fill('未提交的人工补发依据');assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),true);await page.keyboard.press('Escape');await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('.record-detail.show').count(),1);await page.keyboard.press('Escape');await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('dialog',{name:'业务详情'}).waitFor({state:'hidden'});assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);
});
+129
View File
@@ -0,0 +1,129 @@
'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 {BpmTodoClient}=require('../../src/modules/bpm/todo-client.cjs');
const {BpmOrderProvider,detailURL}=require('../../src/modules/bpm/order-provider.cjs');
const {OrderArchiveProvider,targetFor}=require('../../src/modules/storage/order-archive.cjs');
const {FileArea}=require('../../src/modules/storage/files.cjs');
const {MailStore}=require('../../src/modules/mail/store.cjs');
const {loadData,loadForm}=require('../../src/modules/bpm/order-form.cjs');
test('historical fields use a distinct readonly chain and method; pending-task boundaries stay strict',async()=>{
const {historyURL}=require('../../src/modules/bpm/order-form.cjs'),target='https://bpm.skyworthdigital.com/YZSoft/Forms/Read.aspx?tid=21',entry='https://bpm.skyworthdigital.com/sso/ssologin.aspx?ReturnUrl='+encodeURIComponent(target)+'&todo_token=fixture-secret&todo_account=fixture',final='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21';
const calls=[],request={get:async url=>({status:()=>url===final?200:302,headers:()=>({location:url===entry?target:final}),body:async()=>Buffer.from('form')}),post:async(url,options)=>{calls.push(options.data);return {status:()=>200,body:async()=>Buffer.from('{"success":true,"Tables":[]}')};}};
assert.equal((await loadForm(request,entry,historyURL,{history:true})).url.href,final);
await loadData(request,new URL(final),{history:true});assert.match(calls[0],/<Method>GetFormReadData<\/Method><TID>21<\/TID>/);
assert.throws(()=>detailURL(final));assert.throws(()=>historyURL(final+'&pid=99'));assert.throws(()=>historyURL(final+'&action=submit'));
await assert.rejects(loadForm({...request,get:async()=>({status:()=>302,headers:()=>({location:final.replace('tid=21','tid=22')})})},entry,historyURL,{history:true}),/标识/);
});
test('transient todo SSO entry follows only matching process and form and never persists its token',async()=>{
const target='https://bpm.skyworthdigital.com/YZSoft/Forms/Process.aspx?tid=21&pid=11',entry='https://bpm.skyworthdigital.com/sso/ssologin.aspx?ReturnUrl='+encodeURIComponent(target)+'&todo_token=fixture-secret&todo_account=fixture';
const final='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11',calls=[];
const request={get:async(url)=>{calls.push(url);return url===entry?{status:()=>302,headers:()=>({location:target})}:url===target?{status:()=>302,headers:()=>({location:final})}:{status:()=>200,body:async()=>Buffer.from('<p>form</p>')};}};
assert.equal((await loadForm(request,entry,detailURL)).url.href,final);assert.equal(calls.length,3);
const manager={run:(_,fn)=>fn(),authorize(){},sessions:new Map(),vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})})};
const provider=new BpmOrderProvider({manager,client:{scan:async()=>[{taskId:'11',detailUrl:entry}]}});const rows=await provider.scan({id:'c'},{});assert.equal(rows[0].detailUrl,target);assert.doesNotMatch(JSON.stringify(rows),/fixture-secret|todo_token/);
await assert.rejects(loadForm({get:async()=>({status:()=>302,headers:()=>({location:final.replace('tid=21','tid=22')})})},entry,detailURL),/标识/);
await assert.rejects(loadForm({get:async()=>({status:()=>302,headers:()=>({location:'https://evil.test/login'})})},entry,detailURL),/范围/);
});
test('form data loader sends only the observed readonly process method and rejects login or invalid data',async()=>{
const requests=[],request={post:async(url,options)=>{requests.push({url,options});return {status:()=>200,body:async()=>Buffer.from(JSON.stringify({success:true,Tables:[{TableName:'Order',FormTable:true,Rows:[{Number:'123'}]}]}))};}};
const tables=await loadData(request,new URL('https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11'));
assert.equal(tables[0].Rows[0].Number,'123');assert.equal(requests[0].url,'https://bpm.skyworthdigital.com/YZSoft/BPM/XMLService/DataProvider.ashx');assert.match(requests[0].options.data,/<Method>GetFormProcessData<\/Method><PID>11<\/PID>/);assert.equal(requests[0].options.maxRedirects,0);
await assert.rejects(loadData({post:async()=>({status:()=>302,headers:()=>({})})},new URL('https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11')),cause=>cause.status===502);
await assert.rejects(loadData({post:async()=>({status:()=>200,body:async()=>Buffer.from('{"success":false}')})},new URL('https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11')),/数据/);
});
test('capture rejects mismatched cached task metadata before requesting the form',async()=>{
const manager={run:(_,fn)=>fn(),authorize(){},sessions:new Map(),vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})})};
const row={source:'todo',portalSource:'portal-v4',taskId:'11',instanceId:'21',processName:'测试订单',nodeName:'通知书',processVersion:'1.4',revision:'r1',receivedAt:'2026-10-23T00:00:00Z',title:'订单号:000123',serialNum:'FIXTURE',detailUrl:'https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11'};
const provider=new BpmOrderProvider({manager,client:{scan:async()=>[row]}});await provider.scan({id:'c'},{});
for(const change of [{instanceId:'22'},{nodeName:'已办理'},{processVersion:'1.5'},{revision:'r2'}])await assert.rejects(provider.capture({id:'c'},{},{...row,...change}),/任务.*变化|任务.*原节点/);
});
test('real todo routes retain instance, node, received time, version and V4 detail, excluding inform endpoints',async t=>{
const calls=[],server=http.createServer((req,res)=>{calls.push(req.url);if(req.url==='/')return res.end('<script>Yiez.clientId="fixture";</script>');const v4=req.url.includes('work_v4');res.setHeader('Content-Type','application/json');res.end(JSON.stringify({total:v4?1:0,children:v4?[{taskId:'11',processInstanceId:21,processVersion:'1.4',processName:'备损订单更改评审',activityName:'订单专员(订单通知书)',startTime:'2026-10-19T09:01:00',serialNum:'SN11',processInstanceSubject:'订单号:123机芯号:ABC',executionPointerId:'https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11'}]:[]}));});
await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));
const client=new BpmTodoClient({baseURL:`http://127.0.0.1:${server.address().port}/`,allowLocal:true}),rows=await client.scan({cookies:[],origins:[]});assert.equal(rows.length,1);assert.equal(rows[0].source,'todo');assert.equal(rows[0].nodeName,'订单专员(订单通知书)');assert.equal(rows[0].processVersion,'1.4');assert.equal(rows[0].receivedAt,'2026-10-19T01:01:00.000Z');assert.equal(rows[0].instanceId,'21');assert.ok(calls.every(u=>!u.includes('inform')));
});
test('form URL boundaries reject credentials, redirects, arbitrary endpoints and mutation query fields',()=>{
const base='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11';assert.equal(detailURL(base).href,base);
for(const value of [base+'&action=submit',base.replace('bpm.skyworthdigital.com','evil.test'),base.replace('https://','https://u:p@'),base.replace('/YZSoft/Forms/XForm/','/Redirect/'),'file:///tmp/x.aspx?tid=21&pid=11'])assert.throws(()=>detailURL(value));
});
test('readonly capture blocks page scripts, external requests and form submission, freezes actual field values',async t=>{
let mutations=0;const server=http.createServer((req,res)=>{if(req.url==='/YZSoft/BPM/XMLService/DataProvider.ashx'){res.setHeader('Content-Type','application/json');return res.end(JSON.stringify({success:true,Tables:[{TableName:'Order',FormTable:true,Rows:[{Number:'123',Change:'actual'}]},{TableName:'Lines',FormTable:true,Rows:[{Value:'line-one'}]}]}));}if(req.method==='POST'||req.url.includes('mutate'))mutations++;res.setHeader('Content-Type','text/html');res.end('<input id="o" xdatabind="Order.Number"><textarea id="c" xdatabind="Order.Change"></textarea><input xdatabind="Lines.Value"><input id="repeat" value="first-row"><input id="repeat" value="second-row"><script>fetch("/mutate",{method:"POST"})</script><button>提交</button>');});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));
const manager={run:(_,fn)=>fn(),authorize(){},sessions:new Map(),vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})})},provider=new BpmOrderProvider({manager,allowLocal:true});
const result=await provider.capture({id:'c'},{},{detailUrl:`http://127.0.0.1:${server.address().port}/form.aspx?tid=1&pid=2`,processVersion:'1.4',title:'订单号:123'});assert.equal(result.sample.fields['Order.Number'],'123');assert.equal(mutations,0);assert.doesNotMatch(result.snapshot.html,/<script|<input|提交/);assert.match(result.snapshot.html,/actual/);assert.match(result.snapshot.html,/second-row/);assert.match(result.snapshot.html,/line-one/);assert.equal(result.sample.fields['Lines.Value'],'line-one');
});
async function captureFixture(t,html,tables){
const calls=[],server=http.createServer((req,res)=>{calls.push([req.method,req.url]);res.setHeader('Content-Type',req.method==='POST'?'application/json':'text/html');res.end(req.method==='POST'?JSON.stringify({success:true,Tables:tables}):html);});
await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));
const manager={run:(_,fn)=>fn(),authorize(){},sessions:new Map(),vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})})};
const provider=new BpmOrderProvider({manager,allowLocal:true}),capture=(fieldsOnly=false)=>provider[fieldsOnly?'captureFields':'capture']({id:'c'},{},{detailUrl:`http://127.0.0.1:${server.address().port}/form.aspx?tid=1&pid=2`,processVersion:'1.4',title:'订单号:123'});
return {provider,capture,calls};
}
test('detail snapshot preserves exact DOM row correspondence and indexed catalog without joining columns',async t=>{
const fixture=await captureFixture(t,'<input xdatabind="Order.Number"><table><thead><tr><th>Item</th><th>Qty</th></tr></thead><tbody><tr data-row="first"><td><span xdatabind="ERP:Lines.Item"></span></td><td><input xdatabind="ERP:Lines.Qty"></td></tr><tr data-row="second"><td><span xdatabind="ERP:Lines.Item"></span></td><td><input xdatabind="ERP:Lines.Qty"></td></tr></tbody></table>',[{TableName:'Order',FormTable:true,Rows:[{Number:'123'}]},{DataSource:'ERP',TableName:'Lines',FormTable:true,Rows:[{Item:'A',Qty:1},{Item:'B',Qty:9}]}]);
const {sample,snapshot}=await fixture.capture();
const cells=name=>[...snapshot.html.match(new RegExp('<tr data-row="'+name+'">([\\s\\S]*?)</tr>'))[1].matchAll(/<td>([\s\S]*?)<\/td>/g)].map(m=>m[1].replace(/<[^>]*>/g,''));
assert.deepEqual(cells('first'),['A','1']);assert.deepEqual(cells('second'),['B','9']);
assert.deepEqual(sample.fields,{'Order.Number':'123','ERP:Lines[0].Item':'A','ERP:Lines[1].Item':'B','ERP:Lines[0].Qty':'1','ERP:Lines[1].Qty':'9'});
assert.equal(fixture.provider.capabilities().pdfExport,true);
assert.deepEqual(fixture.calls,[['GET','/form.aspx?tid=1&pid=2'],['POST','/YZSoft/BPM/XMLService/DataProvider.ashx']]);
});
test('field-only evidence expands server data rows without claiming PDF layout readiness',async t=>{
const f=await captureFixture(t,'<table><tr><td>订单号</td><td><input xdatabind="Order.Number"></td></tr><tr><td><input xdatabind="Lines.Qty"></td></tr></table>',[{TableName:'Order',FormTable:true,Rows:[{Number:'123'}]},{TableName:'Lines',FormTable:true,Rows:[{Qty:0},{Qty:9}]}]);
const result=await f.capture(true);
assert.equal(result.snapshot.purpose,'field-mapping');assert.equal(result.snapshot.html,undefined);
assert.equal(result.sample.fields['Order.Number'],'123');assert.equal(result.sample.fields['Lines[0].Qty'],'0');
assert.equal(result.sample.fields['Lines[1].Qty'],'9');assert.equal(f.provider.capabilities().pdfExport,false);
await assert.rejects(f.capture(),/明细|多行/);
});
test('capture blocks unsupported or ambiguous detail layouts instead of returning an archivable snapshot',async t=>{
const input=key=>'<input xdatabind="Lines.'+key+'">',row=content=>'<tr><td>'+content+'</td></tr>',both=input('Item')+input('Qty');
for(const [name,html,rows]of [
['one template for multiple data rows','<table>'+row(both)+'</table>',[{Item:'A',Qty:1},{Item:'B',Qty:9}]],
['repeated controls outside rows',both+both,[{Item:'A',Qty:1},{Item:'B',Qty:9}]],
['inconsistent row schema','<table>'+row(both)+row(input('Item'))+'</table>',[{Item:'A',Qty:1},{Item:'B',Qty:9}]],
['duplicate same-column controls','<table>'+row(both+input('Item'))+row(both)+'</table>',[{Item:'A',Qty:1},{Item:'B',Qty:9}]],
['split table containers','<table>'+row(both)+'</table><table>'+row(both)+'</table>',[{Item:'A',Qty:1},{Item:'B',Qty:9}]],
['missing source row column','<table>'+row(both)+row(both)+'</table>',[{Item:'A',Qty:1},{Item:'B'}]],
['non-scalar source column','<table>'+row(both)+row(both)+'</table>',[{Item:'A',Qty:1},{Item:'B',Qty:{value:9}}]]
])await t.test(name,async sub=>{
const fixture=await captureFixture(sub,'<input xdatabind="Order.Number">'+html,[{TableName:'Order',FormTable:true,Rows:[{Number:'123'}]},{TableName:'Lines',FormTable:true,Rows:rows}]);
await assert.rejects(fixture.capture(),error=>error.status===409&&/明细|多行/.test(error.message));
assert.equal(fixture.provider.capabilities().pdfExport,false);assert.match(fixture.provider.capabilities().message,/明细|多行/);
});
});
test('archive produces evidence only after remote readback; directory must map inside configured server',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-archive-'));t.after(()=>fs.rm(dir,{recursive:true,force:true}));const share=path.join(dir,'share');await fs.mkdir(share);const area=new FileArea(share),server={id:'s',host:'nas',share:'orders',directory:'',enabled:true,state:{readable:true,writable:true}};let corrupt=false;
const storage={store:{servers:()=>[server]},run:(_,fn)=>fn(server,new AbortController().signal),operation:async(_,method,args)=>{const result=await area[method](...args);if(corrupt&&method==='readFile')result.bytes=Buffer.from('%PDF-wrong');return result;},readFile:(_,relative)=>area.readFile(relative)};
const renderer=async(_,options)=>{await fs.mkdir(options.outputDir,{recursive:true});const file=path.join(options.outputDir,'test.pdf');await fs.writeFile(file,'%PDF-fixture');return {path:file};},provider=new OrderArchiveProvider({storage,outputDir:dir,renderer});
const input={order:{event:{orderNo:'123',serialNum:'SN',receivedAt:'2026-10-19T01:00:00Z'}},rule:{archiveDirectory:'\\\\nas\\orders\\category',filenameDate:'receivedAt'},snapshot:{html:'<p>order</p>'},taskId:'task'};
const result=await provider.archive(input);assert.match(result.files[0].path,/123_2026-10-19_SN\.pdf$/);assert.equal(result.files[0].size,12);assert.equal((await provider.read(result.files[0])).toString(),'%PDF-fixture');
assert.throws(()=>targetFor(storage,'\\\\nas\\other\\category'));assert.throws(()=>targetFor(storage,'\\\\nas\\orders\\..\\outside'));
corrupt=true;await assert.rejects(provider.archive(input),/读回/);assert.equal(provider.capabilities().automaticArchive,false);
});
test('category bindings require an explicit active template and optimistic version, persist tombstones',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-mail-')),store=new MailStore(dir);t.after(async()=>{store.close();await fs.rm(dir,{recursive:true,force:true});});store.migrateLegacy({subject:'test',body:'body'});const pending=store.templates()[0];assert.throws(()=>store.bindCategory({categoryId:'bs-change',templateId:pending.id,version:0}),e=>e.status===409);assert.equal(store.categoryBindings().length,0);
const parsed={subject:'test',scope:'',text:'body',html:'',sender:'source@company.test',attachments:[]};const channel=store.saveChannel({name:'test',email:'test@company.test',smtp:{host:'mail.test',port:465,security:'tls',user:'u',password:'test'},imap:{host:'mail.test',port:993,security:'tls',user:'u',password:'test'},senders:['source@company.test'],enabled:false});const p=store.ingest(channel.id,'1',1,parsed,Buffer.from('fixture'),1);store.confirm(p.id,{version:1,subject:'test',scope:'',useText:false},'admin');
const bound=store.bindCategory({categoryId:'bs-change',templateId:p.id,version:0});assert.equal(bound.version,1);assert.equal(store.categoryTemplate('bs-change').id,p.id);assert.throws(()=>store.bindCategory({categoryId:'bs-change',templateId:'',version:0}),e=>e.status===409);store.bindCategory({categoryId:'bs-change',templateId:'',version:1});assert.equal(store.categoryTemplate('bs-change'),null);assert.equal(store.categoryBindings()[0].version,2);
});
test('real Chromium PDF generation archives through temporary storage and returns verified readable evidence',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-real-pdf-'));t.after(()=>fs.rm(dir,{recursive:true,force:true}));const share=path.join(dir,'share');await fs.mkdir(share);const area=new FileArea(share),server={id:'s',host:'fixture-nas',share:'orders',directory:'',enabled:true,state:{readable:true,writable:true}};
const storage={store:{servers:()=>[server]},check:()=>area.check(),run:(_,fn)=>fn(server,new AbortController().signal),operation:(_,method,args)=>area[method](...args),readFile:(_,relative)=>area.readFile(relative)};
const provider=new OrderArchiveProvider({storage,outputDir:dir});assert.equal(provider.capabilities().automaticArchive,false);assert.equal((await provider.probe({archiveDirectory:'\\\\fixture-nas\\orders'})).pdfExport,true);
const evidence=await provider.archive({order:{event:{orderNo:'000123',serialNum:'SN-1',receivedAt:'2026-10-19T01:00:00Z'}},rule:{archiveDirectory:'\\\\fixture-nas\\orders\\通知书',filenameDate:'receivedAt'},snapshot:{html:'<h1>隔离订单归档</h1><table><tr><td>000123</td><td>5000</td></tr></table>',styles:[],images:[]}});
const bytes=await provider.read(evidence.files[0]);assert.equal(bytes.subarray(0,5).toString(),'%PDF-');assert.ok(bytes.length>1000);assert.equal(bytes.length,evidence.files[0].size);assert.equal(require('node:crypto').createHash('sha256').update(bytes).digest('hex'),evidence.files[0].sha256);
});
test('interrupted archive retries reuse durable PDF bytes and fixed destination across provider restart',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-archive-recovery-'));t.after(()=>fs.rm(dir,{recursive:true,force:true}));const share=path.join(dir,'share');await fs.mkdir(share);const area=new FileArea(share),server={id:'s',host:'nas',share:'orders',directory:'',enabled:true,state:{readable:true,writable:true}},records=new Map(),journal={get:(kind,id)=>structuredClone(records.get(kind+id)||null),put:(kind,value)=>records.set(kind+value.id,structuredClone(value))};let corrupt=true,renders=0;
const storage={store:{servers:()=>[server]},run:(_,fn)=>fn(server,new AbortController().signal),operation:async(_,method,args)=>{const result=await area[method](...args);if(corrupt&&method==='readFile')throw Error('read interrupted');return result;},readFile:(_,relative)=>area.readFile(relative)},renderer=async(_,options)=>{renders++;await fs.mkdir(options.outputDir,{recursive:true});const file=path.join(options.outputDir,'durable.pdf');await fs.writeFile(file,'%PDF-durable'+renders);return {path:file};};
const input={order:{id:'o',sourceHash:'source',event:{orderNo:'123',serialNum:'SN',receivedAt:'2026-10-19T01:00:00Z'}},rule:{archiveDirectory:'\\\\nas\\orders',filenameDate:'receivedAt'},snapshot:{html:'<p>order</p>'},taskId:'task'};
let provider=new OrderArchiveProvider({storage,outputDir:dir,renderer,journal});assert.equal(provider.supportsRecovery,true);await assert.rejects(provider.archive(input),/interrupted/);assert.equal(renders,1);
corrupt=false;provider=new OrderArchiveProvider({storage,outputDir:dir,renderer,journal});const evidence=await provider.archive(input);assert.equal(renders,1);assert.equal((await fs.readdir(share)).length,1);assert.equal((await provider.read(evidence.files[0])).toString(),'%PDF-durable1');assert.deepEqual(await provider.archive(input),evidence);assert.equal(renders,1);
});
@@ -1,8 +1,8 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
let createDashboard;try{({createDashboard}=require('../src/dashboard.cjs'));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
let createDashboard;try{({createDashboard}=require('../../src/app/dashboard.cjs'));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
test('dashboard requires login, persists settings and enforces viewer and same-origin restrictions',async t=>{
assert.equal(typeof createDashboard,'function','web dashboard server not implemented');
const {Store}=require('../src/dashboard-store.cjs');
const {Store}=require('../../src/modules/dashboard/store.cjs');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'dashboard-http-'));const store=new Store(path.join(dir,'data'));
const outputDir=path.join(dir,'pdf');fs.mkdirSync(outputDir);fs.writeFileSync(path.join(outputDir,'ok.pdf'),'%PDF-test');fs.writeFileSync(path.join(dir,'secret.pdf'),'%PDF-private');
const server=createDashboard({store,outputDir});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
@@ -13,6 +13,7 @@ test('dashboard requires login, persists settings and enforces viewer and same-o
assert.equal((await call('/api/bootstrap',{username:'admin',password:'Test-password-123'},null,'https://evil.example')).status,403);
const setup=await call('/api/bootstrap',{username:'admin',password:'Test-password-123'});assert.equal(setup.status,201);const cookie=setup.headers.get('set-cookie').split(';')[0];
const overview=await (await call('/api/overview',null,cookie)).json();assert.equal(overview.automation.enabled,false);assert.equal(overview.stats.total,0);
assert.ok(!overview.connections.some(c=>c.name==='产品线群组'));assert.ok(!JSON.stringify(overview).includes('等待提供表格'));assert.ok(overview.connections.some(c=>c.name==='Excel 分类规则'));
const original=await (await call('/api/settings',null,cookie)).json();
assert.equal((await call('/api/settings',{version:original.version,schedule:{...original.schedule,times:['10:00','16:00']}},cookie)).status,200);
assert.deepEqual(new Store(path.join(dir,'data')).settings().schedule.times,['10:00','16:00']);
@@ -5,8 +5,8 @@ const vm=require('node:vm');
test('late overview response cannot overwrite a newly opened settings form',async()=>{
let resolve;
const container={innerHTML:'unsaved template draft'};
const context=vm.createContext({document:{querySelector:()=>({})},Intl,setTimeout,window:{addEventListener(){}},fetch(){throw Error('unexpected fetch');}});
const source=fs.readFileSync(require.resolve('../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
const context=vm.createContext({document:{querySelector:()=>({}),addEventListener(){}},Intl,setTimeout,window:{addEventListener(){}},fetch(){throw Error('unexpected fetch');}});
const source=fs.readFileSync(require.resolve('../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
vm.runInContext(source,context);
context.pending=new Promise(r=>{resolve=r;});context.container=container;
vm.runInContext("api=()=>pending;currentUser={role:'admin'};",context);
+10
View File
@@ -0,0 +1,10 @@
'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');
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
test('real captured sample uses server evidence id and uncertain batch verification carries version and idempotency',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'execution-contract-ui-')),runtime=await startTestDashboard({stateDir:dir}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});const page=await browser.newPage();page.setDefaultTimeout(5000);const writes=[];
let captured=false;await page.route('**/api/order-rules/fields*',route=>route.fulfill({json:{samples:captured?[{id:'capture-1',provenance:'server-provider',processName:'备损订单更改评审',processVersion:'1.4',sample:{demo:false,receivedAt:'2026-10-19T09:00:00+08:00',processName:'备损订单更改评审',processVersion:'1.4',fields:{'OFR_BS_Applicant.OrderNum':'REAL-1'},title:'订单号:REAL-1'},fields:[{path:'OFR_BS_Applicant.OrderNum',label:'订单号',value:'REAL-1'}]}]:[],adapters:[]}}));
await page.route('**/api/order-rules/rules/bs-change/trial',route=>{writes.push(route.request().postDataJSON());return route.fulfill({json:{valid:true,issues:[]}});});
await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');await login(page);await page.locator('#order-rule-refresh').waitFor();captured=true;await page.locator('#order-rule-refresh').click();await page.locator('[data-rule-id="bs-change"]').click();await page.getByLabel('已采集的 BPM 订单',{exact:true}).selectOption('capture:capture-1');assert.equal(await page.locator('#order-rule-sample').count(),0);await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#order-rule-preview-result .bg-green-lt').waitFor();assert.equal(writes[0].sampleId,'capture-1');assert.equal(writes[0].version,1);assert.equal(Object.hasOwn(writes[0],'sample'),false);assert.deepEqual(writes[0].draft.scopes,[{processName:'备损订单更改评审',nodeName:'订单专员(订单通知书)'}]);
runtime.orderRules.put('batches',{id:'unknown-1',version:7,status:'unknown',subject:'待核验批次',to:['orders@example.test'],orderIds:[],text:'冻结内容'});await page.route('**/api/order-rules/batches/unknown-1/resolve',route=>{writes.push(route.request().postDataJSON());return route.fulfill({json:{status:'failed'}});});await page.locator('#sidebar-menu a[data-view=notification-batches]').click();await page.getByText('待核验批次',{exact:true}).waitFor();await page.getByRole('button',{name:'查看详情',exact:true}).click();const form=page.locator('[data-business-action=resolve]');await form.locator('textarea[name=note]').fill('已核实SMTP服务器未接受');await form.locator('select[name=resolution]').selectOption('retry');await page.getByRole('button',{name:'保存核验结论',exact:true}).click();await page.getByText('操作已提交,请关闭详情并刷新列表核对实际结果。',{exact:true}).waitFor();assert.equal(writes[1].version,7);assert.ok(writes[1].idempotencyKey);assert.equal(writes[1].note,'已核实SMTP服务器未接受');assert.equal(writes[1].resolution,'retry');
});
+7
View File
@@ -0,0 +1,7 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
const source=fs.readFileSync('web/app.js','utf8');
function fixture(){let resolve,requests=0,disposed=0,booted=0;const context={AbortController,AbortSignal,setTimeout:(fn,ms)=>{const timer=setTimeout(fn,ms);timer.unref();return timer;},clearTimeout,fetch:()=>{requests++;return new Promise(r=>resolve=r);},window:{PageLifecycle:{revision:1,dispose:async()=>{disposed++;},succeeded(){},failed(){}},BpmLogin:{dispose(){}}}};vm.createContext(context);vm.runInContext("let currentUser={username:'old'},viewGeneration=1;const pendingWrites=new Map();async function boot(){booted++;}",context);context.booted=0;vm.runInContext(source.slice(source.indexOf('async function api('),source.indexOf('async function verifyUncertainWrite(')),context);return {context,run:s=>vm.runInContext(s,context),resolve:r=>resolve(r),requests:()=>requests,disposed:()=>disposed};}
for(const change of ['viewGeneration++;window.PageLifecycle.revision++;','currentUser={username:"new"};viewGeneration++;window.PageLifecycle.revision++;'])test('obsolete 401 has no auth effects after '+change,async()=>{const f=fixture(),request=f.run("api('/old')");f.run(change);f.resolve({ok:false,status:401,json:async()=>({error:'expired'})});await assert.rejects(request,/expired/);assert.equal(f.run('currentUser!==null'),true);assert.equal(f.disposed(),0);assert.equal(f.context.booted,0);});
test('owned session 401 still disposes expired session',async()=>{const f=fixture(),request=f.run("api('/current')");f.resolve({ok:false,status:401,json:async()=>({error:'expired'})});await assert.rejects(request,/expired/);assert.equal(f.run('currentUser'),null);assert.equal(f.disposed(),1);assert.equal(f.context.booted,1);});
test('identical writes from a newer session never join old pending work',async()=>{const f=fixture();f.run("api('/write',{a:1})");f.run('currentUser={username:"new"};viewGeneration++;');const current=f.run("api('/write',{a:1})");assert.equal(f.requests(),2);f.resolve({ok:true,json:async()=>({version:2})});await current;});
+61
View File
@@ -0,0 +1,61 @@
'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'),net=require('node:net'),http=require('node:http');
const {DatabaseSync}=require('node:sqlite');
const {main,createServer}=require('../../src/server.cjs');let render;
const {acquireInstanceLock}=require('../../src/platform/service/instance-lock.cjs');
const turn=()=>new Promise(r=>setImmediate(r));
const gate=()=>{let release;const promise=new Promise(r=>release=r);return {promise,release};};
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 fixture(){const stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-final-lifecycle-'));return {stateDir,quiet:true,config:{port:await port(),outputDir:path.join(stateDir,'output'),dashboard:{port:await port(),host:'127.0.0.1'}}};}
const snapshot={html:'<p>fixture</p>',metadata:{order:'order',project:'project',model:'model',serial:'serial'}};
function post(port,token,{partial=false}={}){let finish;const response=new Promise((resolve,reject)=>{const req=http.request({host:'127.0.0.1',port,path:'/export',method:'POST',headers:{Origin:'chrome-extension://'+'a'.repeat(32),'X-Order-Token':token,'Content-Type':'application/json',Connection:'close'}},res=>{let body='';res.on('data',c=>body+=c);res.on('end',()=>resolve({status:res.statusCode,body:JSON.parse(body)}));});req.on('error',reject);const raw=JSON.stringify(snapshot);if(partial){req.write(raw.slice(0,5));finish=()=>req.end(raw.slice(5));}else req.end(raw);});return {response,finish:()=>finish()};}
test('application stop retains ownership and storage until accepted rendering and automatic archive settle',async t=>{
const options=await fixture(),renderGate=gate(),archiveGate=gate(),archiveStarted=gate();let app,stopping,writes=0;
render=async()=>{await renderGate.promise;return {filename:'fixture.pdf',bytes:1};};
t.after(async()=>{renderGate.release();archiveGate.release();await stopping?.catch(()=>{});await app?.stop();await fs.rm(options.stateDir,{recursive:true,force:true});});
app=await main({...options,renderSnapshot:(...args)=>render(...args)});const token=(await fs.readFile(path.join(options.stateDir,'pairing.key'),'utf8')).trim();
let storageStopped=false;const originalStop=app.storage.stop.bind(app.storage);app.storage.stop=async()=>{storageStopped=true;await originalStop();};
app.storage.automatic=async job=>{assert.equal(storageStopped,false);archiveStarted.release();await archiveGate.promise;app.storage.jobs.recordJob({...job,archiveFixture:true});writes++;};
const accepted=await post(options.config.port,token).response;assert.equal(accepted.status,202);
let done=false;stopping=app.stop().then(()=>{done=true;});await new Promise(r=>setTimeout(r,40));
assert.equal(done,false,'stop must wait for accepted renderer');assert.equal(storageStopped,false);await assert.rejects(acquireInstanceLock(options.stateDir),e=>e.code==='ORDER_INSTANCE_OWNED');
renderGate.release();await archiveStarted.promise;await turn();assert.equal(done,false,'stop must wait for automatic archive');await assert.rejects(acquireInstanceLock(options.stateDir),e=>e.code==='ORDER_INSTANCE_OWNED');
archiveGate.release();await stopping;assert.equal(writes,1);assert.equal(storageStopped,true);
const replacement=await main(options);await replacement.stop();await turn();assert.equal(writes,1);
});
test('request whose body completes after shutdown begins cannot start a new export',async t=>{
let rendered=0;render=async()=>{rendered++;return {filename:'fixture.pdf',bytes:1};};const server=createServer({token:'fixture',renderSnapshot:(...args)=>render(...args)});await new Promise(r=>server.listen(0,'127.0.0.1',r));
const received=new Promise(r=>server.once('request',r));const pending=post(server.address().port,'fixture',{partial:true});await received;
const closing=new Promise((resolve,reject)=>server.close(e=>e?reject(e):resolve()));pending.finish();const response=await pending.response;await closing;
assert.equal(response.status,503);assert.equal(rendered,0);
});
test('malformed workspace migration closes its allocated database before ownership release and permits repaired retry',async t=>{
const options=await fixture();t.after(()=>fs.rm(options.stateDir,{recursive:true,force:true}));await fs.mkdir(path.join(options.stateDir,'workspace'));const file=path.join(options.stateDir,'workspace','workspace.sqlite');const db=new DatabaseSync(file);db.exec("CREATE TABLE connections(id TEXT PRIMARY KEY,value TEXT NOT NULL); INSERT INTO connections VALUES('legacy','{broken');");db.close();
const original=DatabaseSync.prototype.exec;let allocated;
DatabaseSync.prototype.exec=function(sql){if(sql.includes('PRAGMA foreign_keys=ON'))allocated=this;return original.call(this,sql);};
try{await assert.rejects(main(options),SyntaxError);}finally{DatabaseSync.prototype.exec=original;}
try{assert.throws(()=>allocated.prepare('SELECT 1'),/not open|closed/i);}finally{try{allocated.close();}catch{}}
const repair=new DatabaseSync(file);repair.exec('DELETE FROM connections');repair.close();const app=await main(options);await app.stop();
});
test('all allocating store constructors close the database and destroy the vault when initialization fails',async t=>{
const cases=[['workspace','WorkspaceStore'],['mail','MailStore'],['notifications','NotificationStore'],['storage','StorageStore'],['assistant','AssistantStore'],['bpm/scan-store','BpmScanStore'],['dashboard/sessions','SessionStore'],['health/runtime-health','RuntimeHealth'],['../platform/service/store','SupervisorStore']];
const {BpmVault}=require('../../src/platform/security/vault.cjs');
for(const [name,exportName] of cases)await t.test(name,async()=>{const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-constructor-'));let allocated,destroyed=0;const exec=DatabaseSync.prototype.exec,destroy=BpmVault.prototype.destroy;DatabaseSync.prototype.exec=function(){allocated=this;throw new Error('initialization fixture');};BpmVault.prototype.destroy=function(){destroyed++;return destroy.call(this);};
try{const file=name.includes('/')?name:name+'/store';const Type=require('../../src/modules/'+file+'.cjs')[exportName];assert.throws(()=>new Type(exportName==='RuntimeHealth'?{stateDir:dir}:dir),/initialization fixture/);assert.throws(()=>allocated.prepare('SELECT 1'),/not open|closed/i,name);if(['mail','notifications','storage','assistant'].includes(name))assert.equal(destroyed,1,name);}
finally{DatabaseSync.prototype.exec=exec;BpmVault.prototype.destroy=destroy;try{allocated?.close();}catch{}await fs.rm(dir,{recursive:true,force:true});}
});
});
test('automatic archive remains background work and finishing it cannot clear a newer renderer busy state',async t=>{
const archive=gate(),archiveStarted=gate(),secondRender=gate();let calls=0;const records=[];
const server=createServer({token:'fixture',store:{recordJob(job){records.push(job);return job;}},storage:{automatic:async()=>{archiveStarted.release();await archive.promise;}},renderSnapshot:async()=>{if(++calls===2)await secondRender.promise;return {filename:'fixture.pdf',bytes:1};}});
await new Promise(r=>server.listen(0,'127.0.0.1',r));const p=server.address().port;
t.after(async()=>{archive.release();secondRender.release();if(server.listening)await new Promise(r=>server.close(r));});
assert.equal((await post(p,'fixture').response).status,202);await archiveStarted.promise;
assert.equal((await post(p,'fixture').response).status,202);archive.release();await turn();
assert.equal((await post(p,'fixture').response).status,409);
let done=false;const closing=new Promise(r=>server.close(r)).then(()=>{done=true;});await turn();assert.equal(done,false);secondRender.release();await closing;assert.equal(records.filter(r=>r.status==='success').length,2);
});
test('shutdown drains a synchronous renderer failure and preserves the accepted job error',async()=>{
const records=[];const server=createServer({token:'fixture',store:{recordJob:job=>{records.push(job);return job;}},renderSnapshot(){throw new Error('renderer fixture');}});await new Promise(r=>server.listen(0,'127.0.0.1',r));
const response=await post(server.address().port,'fixture').response;assert.equal(response.status,202);await new Promise(r=>server.close(r));assert.deepEqual(records.map(j=>j.status),['running','error']);assert.equal(records[1].jobId,response.body.jobId);assert.equal(records[1].error,'renderer fixture');
});
@@ -1,7 +1,7 @@
'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');
async function fixture(t){
const {Store}=require('../src/dashboard-store.cjs'),{RuntimeHealth}=require('../src/runtime-health.cjs'),{createDashboard}=require('../src/dashboard.cjs');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{RuntimeHealth}=require('../../src/modules/health/runtime-health.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'health-http-')),store=new Store(path.join(dir,'dashboard'));store.bootstrap('admin','Health-test-password-123');
const health=new RuntimeHealth({stateDir:dir,workspace:{snapshot:()=>({connections:[{id:'c',owner:'admin',name:'<img src=x onerror=alert(1)>',status:'connected',checkedAt:new Date().toISOString(),lastConnectedAt:new Date().toISOString()}]})}}),watchdog={token:'a'.repeat(64),instanceId:'health-fixture',startedAt:new Date().toISOString()};
const server=createDashboard({store,health,watchdog,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));health.close();await fs.rm(dir,{recursive:true,force:true});});
@@ -14,7 +14,7 @@ test('health API is authenticated and watchdog requires a secret token and exact
const response=await fetch(base+'/api/health',{headers:{Cookie:cookie}});assert.equal(response.status,200);assert.doesNotMatch(await response.text(),/a{64}|password|health-fixture/);
});
test('health page shows historical checks, escapes labels, and recovers from an offline refresh',{timeout:60000},async t=>{
const {base}=await fixture(t),{loadPlaywright,browserOptions}=require('../src/runtime.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1280,height:900}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
const {base}=await fixture(t),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1280,height:900}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.goto(base+'/#health');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Health-test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();
await page.getByRole('heading',{name:'系统健康',exact:true}).waitFor();await page.getByText('上次检查结果,非实时连通性检测',{exact:true}).waitFor();assert.equal(await page.locator('#health-groups img').count(),0);
await page.route('**/api/health',route=>route.abort());await page.getByRole('button',{name:'刷新健康状态',exact:true}).click();await page.getByText('暂时无法连接服务,保留上次状态;恢复后会自动更新。',{exact:true}).waitFor();
+32
View File
@@ -0,0 +1,32 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {RuntimeHealth}=require('../../src/modules/health/runtime-health.cjs');
test('health separates successful todo from failed inform and reports listener separately',t=>{
const stateDir=fs.mkdtempSync(path.join(os.tmpdir(),'health-source-')),now=new Date().toISOString();
const health=new RuntimeHealth({stateDir,workspace:{snapshot:()=>({connections:[{id:'c',name:'合成连接',owner:'worker',status:'connected'}]})},scanner:{store:{status:()=>({config:{enabled:true,intervalMinutes:1},runs:[{connectionId:'c',kind:'todo',status:'success',finishedAt:now,seen:1},{connectionId:'c',kind:'inform',status:'error',finishedAt:now,message:'合成读取失败'}]})}},monitor:{snapshot:()=>({status:'listening',lastSyncAt:now,sources:{}})}});
t.after(()=>{health.close();fs.rmSync(stateDir,{recursive:true,force:true});});
const data=health.snapshot({username:'worker',role:'operator'}),scan=data.groups.find(group=>group.key==='scan');
assert.equal(scan.status,'error');assert.equal(scan.items.find(item=>item.kind==='todo').status,'healthy');assert.equal(scan.items.find(item=>item.kind==='inform').status,'error');
assert.equal(data.groups.find(group=>group.key==='listener').status,'healthy');
});
test('an old successful source becomes stale without making external requests',t=>{
const stateDir=fs.mkdtempSync(path.join(os.tmpdir(),'health-stale-')),old=new Date(Date.now()-10*60000).toISOString();
const health=new RuntimeHealth({stateDir,workspace:{snapshot:()=>({connections:[{id:'c',owner:'worker'}]})},scanner:{scan:()=>assert.fail('no external scan'),store:{status:()=>({config:{enabled:true,intervalMinutes:1},runs:[{connectionId:'c',kind:'todo',status:'success',finishedAt:old}]})}}});
t.after(()=>{health.close();fs.rmSync(stateDir,{recursive:true,force:true});});
const item=health.snapshot({role:'admin'}).groups.find(group=>group.key==='scan').items.find(item=>item.kind==='todo');
assert.ok(item,'todo source must have its own health item');assert.equal(item.status,'pending');assert.equal(item.stale,true);assert.equal(item.lastSuccessAt,old);
});
test('health reports process event loop observations without exposing host data',async t=>{
const stateDir=fs.mkdtempSync(path.join(os.tmpdir(),'health-loop-')),health=new RuntimeHealth({stateDir});
t.after(()=>{health.close();fs.rmSync(stateDir,{recursive:true,force:true});});
health.start();await new Promise(resolve=>setTimeout(resolve,35));
const observed=health.snapshot({role:'admin'}).runtime.eventLoop;
assert.ok(observed,'process event loop observations must be available');assert.equal(observed.observed,true);assert.ok(Number.isFinite(observed.maxMs));assert.ok(observed.maxMs>=0);
});
test('paused connections retain their source and listener failure evidence',t=>{
const stateDir=fs.mkdtempSync(path.join(os.tmpdir(),'health-paused-')),at=new Date().toISOString(),connection={id:'c',owner:'worker',status:'connected'};
const health=new RuntimeHealth({stateDir,workspace:{snapshot:()=>({connections:[connection]})},scanner:{store:{status:()=>({config:{enabled:true},runs:[{connectionId:'c',kind:'inform',status:'error',finishedAt:at,message:'合成失败'}]})}},monitor:{snapshot:()=>({status:'error',lastFailureAt:at,sources:{}})}});
t.after(()=>{health.close();fs.rmSync(stateDir,{recursive:true,force:true});});health.snapshot({role:'admin'});connection.status='disabled';const data=health.snapshot({role:'admin'}),scan=data.groups.find(group=>group.key==='scan');
assert.equal(scan.items.length,2);assert.equal(scan.items.find(item=>item.kind==='inform').status,'paused');assert.equal(scan.items.find(item=>item.kind==='inform').lastFailureAt,at);
const listener=data.groups.find(group=>group.key==='listener').items[0];assert.equal(listener.status,'paused');assert.equal(listener.lastFailureAt,at);
});
+8
View File
@@ -0,0 +1,8 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
let queryJobs;try{({queryJobs}=require('../../src/modules/dashboard/job-records.cjs'));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'job-records-')),outputDir=path.join(dir,'pdf');fs.mkdirSync(outputDir);const result={dir,outputDir};t.after(()=>{result.close?.();fs.rmSync(dir,{recursive:true,force:true});});return result;}
test('PDF ledger retains export success but only offers existing in-root PDFs for download',async t=>{assert.equal(typeof queryJobs,'function');const f=fixture(t);fs.writeFileSync(path.join(f.outputDir,'ok.pdf'),'%PDF-1.4\nfixture');fs.writeFileSync(path.join(f.dir,'outside.pdf'),'%PDF-1.4\nprivate');fs.writeFileSync(path.join(f.outputDir,'bad.pdf'),'not a PDF');const jobs=['ok','missing','outside','bad'].map(id=>({jobId:id,status:'success',path:path.join(id==='outside'?f.dir:f.outputDir,id+'.pdf'),metadata:{order:id},updatedAt:'2026-10-20T01:00:00Z'}));const result=await queryJobs({jobs,outputDir:f.outputDir});assert.equal(result.total,4);assert.equal(result.jobs.find(j=>j.jobId==='ok').downloadable,true);for(const id of ['missing','outside','bad'])assert.equal(result.jobs.find(j=>j.jobId===id).downloadable,false);assert.equal(result.jobs.every(j=>j.status==='success'),true);assert.equal(JSON.stringify(result).includes(f.dir.replace(/\\/g,'\\\\')),false);assert.equal(result.jobs.some(j=>'path'in j),false);});
test('PDF ledger pages filtered records independently from connection lifecycle and has an honest empty page',async t=>{assert.equal(typeof queryJobs,'function');const f=fixture(t),jobs=Array.from({length:27},(_,i)=>({jobId:'job-'+i,status:'error',metadata:{order:'ORD-'+i},error:'fixture',updatedAt:'2026-10-20T01:00:00Z'}));assert.equal((await queryJobs({jobs,outputDir:f.outputDir},{page:2})).jobs.length,2);assert.equal((await queryJobs({jobs,outputDir:f.outputDir},{q:'ORD-26'})).total,1);assert.equal((await queryJobs({jobs,outputDir:f.outputDir},{status:'success'})).total,0);const empty=await queryJobs({jobs:[],outputDir:f.outputDir});assert.equal(empty.total,0);assert.deepEqual(empty.jobs,[]);for(const filters of [{page:0},{pageSize:101},{status:'unknown'}])await assert.rejects(queryJobs({jobs,outputDir:f.outputDir},filters),e=>e.status===400);});
test('archive history lookup returns older job receipts beyond the latest one hundred entries',async t=>{const {StorageStore}=require('../../src/modules/storage/store.cjs');const f=fixture(t),store=new StorageStore(path.join(f.dir,'storage'));f.close=()=>store.close();assert.equal(typeof store.archivesForJobs,'function');for(let i=0;i<105;i++)store.db.prepare('INSERT INTO archives VALUES(?,?,?,?,?)').run('receipt-'+i,'server','job-'+i,'success',JSON.stringify({relativePath:i+'/file.pdf',finishedAt:'2026-10-20T01:00:00Z'}));const receipt=store.archivesForJobs(['job-0']);assert.equal(receipt.length,1);assert.equal(receipt[0].jobId,'job-0');assert.equal(receipt[0].relativePath,'0/file.pdf');});
test('PDF ledger clamps to the actual last page including an empty filtered dataset',async t=>{const f=fixture(t),jobs=Array.from({length:101},(_,i)=>({jobId:'job-'+i,status:'error'}));const last=await queryJobs({jobs,outputDir:f.outputDir},{page:99});assert.equal(last.page,5);assert.equal(last.jobs.length,1);const empty=await queryJobs({jobs,outputDir:f.outputDir},{status:'success',page:99});assert.equal(empty.page,1);assert.equal(empty.total,0);});
+25
View File
@@ -0,0 +1,25 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
test('compact navigation groups settings, retains deep links and role boundaries, and works on mobile',{timeout:60000},async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'navigation-ui-')),store=new Store(dir),password='Navigation-test-123';store.bootstrap('admin',password);store.addUser({username:'viewer',password,role:'viewer'},'admin');
const server=createDashboard({store,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser;const base='http://127.0.0.1:'+server.address().port;
t.after(async()=>{await browser?.close();server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());
const errors=[];
for(const role of ['admin','viewer']){
const context=await browser.newContext({viewport:{width:1440,height:1000}}),page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));
await page.goto(base+'/#system-settings');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill(password);await page.getByRole('button',{name:'登录',exact:true}).click();
await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.equal(await page.locator('#sidebar-menu [data-view]').count(),7);
assert.equal(await page.locator('#settings-tabs a[href="#users"]').count(),role==='admin'?1:0);
await page.getByRole('link',{name:'业务设置',exact:true}).click();await page.getByRole('link',{name:'通知配置',exact:true}).click();await page.locator('#schedule-form').waitFor();
assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#business-settings');
await page.getByRole('link',{name:'业务设置',exact:true}).click();await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor();
await page.goto(base+'/#users');await page.getByRole('heading',{name:role==='admin'?'团队账号':'业务首页',exact:true}).first().waitFor();
await page.goto(base+'/#calendar');await page.getByRole('heading',{name:'业务日历',exact:true}).waitFor();assert.equal(await page.locator('#sidebar-menu [aria-current="page"]').getAttribute('href'),'#business-settings');
await page.goto(base+'/#system-settings');await page.setViewportSize({width:390,height:844});await page.getByRole('button',{name:'展开菜单',exact:true}).click();
await page.locator('#sidebar-menu').getByRole('link',{name:'业务设置',exact:true}).click();await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor();
await page.waitForFunction(()=>!document.querySelector('#sidebar-menu').classList.contains('collapsing'));assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.equal(await page.locator('#sidebar-menu').evaluate(el=>el.classList.contains('show')),false);assert.equal(await page.getByRole('button',{name:'展开菜单',exact:true}).getAttribute('aria-expanded'),'false');
await context.close();
}
assert.deepEqual(errors,[]);
});
+14
View File
@@ -0,0 +1,14 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');
test('retired demo options cannot enable passwordless access or accept an old demo cookie',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'no-demo-')),store=new Store(dir);const admin=store.bootstrap('admin','Test-password-123');
const server=createDashboard({store,outputDir:dir,previewUserId:admin.id});await new Promise(r=>server.listen(0,'127.0.0.1',r));
t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});
const base='http://127.0.0.1:'+server.address().port;const call=(route,body,cookie)=>fetch(base+route,{method:body?'POST':'GET',headers:{...(body?{Origin:base,'Content-Type':'application/json'}:{}),...(cookie?{Cookie:cookie}:{})},body:body?JSON.stringify(body):undefined});
assert.notEqual((await(await call('/api/bootstrap/status')).json()).preview,true);
assert.ok([401,404].includes((await call('/api/preview-login',{})).status));
const login=await call('/api/login',{username:'admin',password:'Test-password-123'});assert.equal(login.status,200);const cookie=login.headers.get('set-cookie').split(';')[0];assert.match(cookie,/^order_session=/);
assert.equal((await call('/api/me',undefined,cookie)).status,200);
assert.equal((await call('/api/me',undefined,cookie.replace('order_session=','order_preview_session='))).status,401);
});
@@ -0,0 +1,34 @@
'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');
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function fixture(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notification-navigation-')),runtime=await startTestDashboard({stateDir:dir,mailHistory:true}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});return {runtime,browser,base:'http://127.0.0.1:'+runtime.server.address().port};}
test('independent sidebar order entries have no duplicate top tabs and configuration stays in business settings',{timeout:90000},async t=>{
const {runtime,browser,base}=await fixture(t);runtime.store.addUser({username:'viewer',password:'Test-password-123',role:'viewer'},'admin');
for(const role of ['admin','viewer']){const page=await browser.newPage({viewport:{width:1280,height:900}});page.setDefaultTimeout(6000);await page.goto(base+'/#overview');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();
for(const [route,title]of [['notification-orders','订单中心'],['notification-batches','邮件批次'],['notification-orders','订单中心']]){await page.locator('#sidebar-menu a[data-view='+route+']').click();await page.locator('[data-record-count]').waitFor();assert.equal(await page.locator('#view-title').innerText(),title);assert.equal(await page.locator('#settings-tabs').isVisible(),false);assert.equal(await page.locator('#settings-tabs a').count(),0);assert.equal(await page.locator('#view-breadcrumb').isVisible(),false);assert.equal(await page.locator('#sidebar-menu [aria-current=page]').count(),1);assert.equal(await page.locator('#sidebar-menu a[data-view='+route+']').getAttribute('aria-current'),'page');await page.locator('#sidebar-menu a[data-view='+route+']').click();assert.equal(new URL(page.url()).hash,'#'+route);}
await page.setViewportSize({width:390,height:844});await page.getByRole('button',{name:'展开菜单',exact:true}).click();await page.locator('#sidebar-menu a[data-view=business-settings]').click();await page.locator('#order-rules-panel').waitFor();await page.locator('#settings-tabs').getByRole('link',{name:'通知配置',exact:true}).click();await page.locator('#schedule-form').waitFor();assert.equal(await page.locator('#sidebar-menu a[data-view=business-settings]').getAttribute('aria-current'),'page');assert.deepEqual(await page.locator('#settings-tabs a').allTextContents(),['分类通知规则','字段映射','通知配置']);assert.equal(await page.locator('#settings-tabs a[aria-current=page]').innerText(),'通知配置');assert.equal(await page.locator('#notification-config-tabs a').count(),4);await page.locator('#notification-config-tabs').getByRole('link',{name:'业务日历',exact:true}).click();await page.getByRole('heading',{name:'业务日历',exact:true}).waitFor();await page.goBack();await page.locator('#schedule-form').waitFor();await page.reload();await page.locator('#schedule-form').waitFor();assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.close();
}
});
test('one business homepage and canonical order/batch routes preserve old deep links and configuration navigation',{timeout:90000},async t=>{
const {runtime,browser,base}=await fixture(t),page=await browser.newPage();page.setDefaultTimeout(6000);const errors=[],writes=[],full=[];page.on('pageerror',e=>errors.push(e.message));page.on('request',r=>{if(r.method()==='POST'&&!r.url().endsWith('/login'))writes.push(r.url());if(r.url()===base+'/api/order-rules')full.push(r.url());});await page.goto(base+'/#order-notifications');await login(page);await page.getByRole('heading',{name:'业务首页',exact:true}).waitFor();assert.equal(new URL(page.url()).hash,'#overview');assert.equal(await page.locator('#sidebar-menu [data-view]').count(),7);
for(const [route,title,canonical]of [['notification-execution','订单中心','notification-orders'],['notification-orders','订单中心','notification-orders'],['notification-history','邮件批次','notification-batches'],['notification-batches','邮件批次','notification-batches'],['schedule','发送计划','schedule'],['calendar','业务日历','calendar'],['templates','邮件模板','templates'],['notification-settings','发送设置','notification-settings']]){await page.goto(base+'/#'+route);await page.locator('#view-title').getByText(title,{exact:true}).waitFor();assert.equal(new URL(page.url()).hash,'#'+canonical+(route==='notification-history'?'?scope=all':''));if(['schedule','calendar','templates','notification-settings'].includes(route))await page.locator('#notification-config-tabs [aria-current=page]').waitFor();}
await page.goto(base+'/#templates');await page.getByRole('heading',{name:'有效使用情况(只读)',exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'保存关联',exact:true}).count(),0);
assert.equal(runtime.orderRules.settings().enabled,false);assert.deepEqual(writes,[]);assert.deepEqual(full,[]);assert.deepEqual(errors,[]);
});
test('notification settings retain dirty guards and role controls on mobile',{timeout:90000},async t=>{
const {runtime,browser,base}=await fixture(t);for(const role of ['operator','viewer'])runtime.store.addUser({username:role,password:'Test-password-123',role},'admin');
for(const role of ['admin','operator','viewer']){const context=await browser.newContext({viewport:{width:390,height:844}}),page=await context.newPage();page.setDefaultTimeout(6000);await page.goto(base+'/#notification-settings');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.locator('#order-rule-max-size').waitFor();assert.equal(await page.locator('#order-rule-max-size').isDisabled(),role!=='admin');assert.equal(await page.locator('[name=processingEnabled]').isDisabled(),role!=='admin');assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
if(role==='admin'){await page.locator('#order-rule-max-size').fill('19');await page.locator('#notification-config-tabs a[href="#calendar"]').click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('#order-rule-max-size').inputValue(),'19');await page.locator('#notification-config-tabs a[href="#calendar"]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('heading',{name:'业务日历',exact:true}).waitFor();}
await context.close();
}
});
test('summary status failures and old responses cannot overwrite a later page status',{timeout:60000},async t=>{
const {browser,base}=await fixture(t),page=await browser.newPage();page.setDefaultTimeout(6000);await page.goto(base+'/#notification-orders');await login(page);await page.getByText('自动通知已暂停',{exact:true}).waitFor();const original=await(await page.request.get(base+'/api/order-rules?view=summary')).json();
await page.route('**/api/order-rules?view=summary',route=>route.fulfill({json:{...original,settings:{...original.settings,enabled:true},capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}}));await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByText('自动通知已启用',{exact:true}).waitFor();
let held,receive;const received=new Promise(r=>receive=r);await page.route('**/api/order-rules?view=summary',route=>{held=route;receive();});await page.getByRole('button',{name:'刷新数据',exact:true}).click();await received;await page.route('**/api/order-rules?view=summary',route=>route.fulfill({status:503,json:{error:'最新状态读取失败'}}));await page.goto(base+'/#bpm');await page.waitForFunction(()=>document.querySelector('#automation-status')?.title.includes('最新状态读取失败'));await held.fulfill({json:original}).catch(()=>{});await page.waitForTimeout(100);assert.equal(await page.locator('#automation-status').innerText(),'通知状态待确认');
});
test('homepage background polling only announces updates and ignores responses after departure',{timeout:60000},async t=>{
const {browser,base}=await fixture(t),page=await browser.newPage();page.setDefaultTimeout(6000);await page.clock.install();await page.goto(base+'/#overview');await login(page);await page.getByRole('heading',{name:'连续业务窗口',exact:true}).waitFor();const original=await(await page.request.get(base+'/api/order-rules?view=summary')).json();let held;await page.route('**/api/order-rules?view=summary',route=>{held=route;return route.fulfill({json:{...original,counts:{...original.counts,orders:42}}});});await page.clock.fastForward(15001);await page.locator('[data-business-updates]').waitFor();assert.equal(await page.locator('.metric-number').first().innerText(),'0项');await page.goto(base+'/#notification-orders');await page.locator('[data-record-count]').waitFor();assert.equal(await page.locator('[data-business-updates]').count(),0);
});
@@ -0,0 +1,50 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),path=require('node:path'),os=require('node:os'),http=require('node:http'),crypto=require('node:crypto');
const {SMTPServer}=require('smtp-server'),nodemailer=require('nodemailer'),{simpleParser}=require('mailparser');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),{RuleStore}=require('../../src/modules/order-rules/store.cjs');
const {MailStore}=require('../../src/modules/mail/store.cjs'),{MailService}=require('../../src/modules/mail/service.cjs');
const {BpmTodoClient}=require('../../src/modules/bpm/todo-client.cjs'),{BpmOrderProvider}=require('../../src/modules/bpm/order-provider.cjs');
const {FileArea}=require('../../src/modules/storage/files.cjs'),{OrderArchiveProvider}=require('../../src/modules/storage/order-archive.cjs');
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs'),{OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
test('HTTP todo, captured field binding, real PDF, verified share and loopback SMTP form one persistent chain',async t=>{
let now=new Date('2026-10-19T02:00:00Z'),web,bpm,smtp,execution,dispatcher,mail,mutations=0,messages=[],orderNo='000123';
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-complete-')),dashboard=new Store(path.join(dir,'dashboard')),workspace=new WorkspaceStore(path.join(dir,'workspace')),rules=new RuleStore(path.join(dir,'rules'),{clock:()=>now,schedule:()=>dashboard.settings().schedule}),mailStore=new MailStore(path.join(dir,'mail'));
t.after(async()=>{await dispatcher?.stop();await execution?.stop();await mail?.stop();for(const server of [web,bpm])if(server?.listening)await new Promise(r=>server.close(r));if(smtp)await new Promise(r=>smtp.close(r));rules.close();workspace.close();mailStore.close();await fs.rm(dir,{recursive:true,force:true});});
bpm=http.createServer((req,res)=>{
if(req.url==='/')return res.end('<script>Yiez.clientId="fixture";</script>');
if(req.url.startsWith('/bpm/worklist')||req.url.startsWith('/skyworth/todo/')){res.setHeader('Content-Type','application/json');const v4=req.url.startsWith('/skyworth/');return res.end(JSON.stringify({total:v4?1:0,children:v4?[{taskId:11,processInstanceId:21,processVersion:'fixture-1',processName:'备损订单更改评审',activityName:'订单专员(订单通知书)',startTime:'2026-10-19T09:00:00',serialNum:'S11',processInstanceSubject:'订单号:'+orderNo+'机芯号:TEST客户简称:隔离客户总数量:0订单号:HA'+orderNo+'机芯号:SECOND客户简称:隔离客户总数量:5',executionPointerId:'http://127.0.0.1:'+bpm.address().port+'/form.aspx?tid=21&pid=11'}]:[]}));}
if(req.url==='/YZSoft/BPM/XMLService/DataProvider.ashx'&&req.method==='POST'){res.setHeader('Content-Type','application/json');return res.end(JSON.stringify({success:true,Tables:[{TableName:'Order',FormTable:true,Rows:[{Number:orderNo,Quantity:0,Summary:'隔离更改摘要'}]}]}));}
if(req.url.startsWith('/form.aspx'))return res.end('<html><body><h1>隔离更改订单</h1><input xdatabind="Order.Number" aria-label="订单号"><input xdatabind="Order.Quantity" aria-label="订单数量"><textarea xdatabind="Order.Summary"></textarea><script>fetch("/submit",{method:"POST"})</script></body></html>');
mutations++;res.writeHead(403);res.end();
});await new Promise(r=>bpm.listen(0,'127.0.0.1',r));
const manager={run:(_,fn)=>fn(),authorize(){},sessions:new Map(),vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})})},provider=new BpmOrderProvider({manager,allowLocal:true,client:new BpmTodoClient({baseURL:'http://127.0.0.1:'+bpm.address().port+'/',allowLocal:true})});
const share=path.join(dir,'share');await fs.mkdir(share);const area=new FileArea(share),server={id:'s',host:'fixture-nas',share:'orders',directory:'',enabled:true,state:{readable:true,writable:true}},storage={store:{servers:()=>[server]},check:()=>area.check(),run:(_,fn)=>fn(server,new AbortController().signal),operation:(_,method,args)=>area[method](...args),readFile:(_,relative)=>area.readFile(relative)};
const archive=new OrderArchiveProvider({storage,outputDir:path.join(dir,'output'),journal:rules,clock:()=>now});
smtp=new SMTPServer({secure:false,hideSTARTTLS:true,authOptional:true,disabledCommands:['AUTH'],onData(stream,session,cb){const chunks=[];stream.on('data',c=>chunks.push(c));stream.on('end',()=>{messages.push(Buffer.concat(chunks));cb();});}});await new Promise(r=>smtp.listen(0,'127.0.0.1',r));
mail=new MailService({store:mailStore,smtpFactory:()=>nodemailer.createTransport({host:'127.0.0.1',port:smtp.server.address().port,secure:false,ignoreTLS:true})});
execution=new OrderExecutionCoordinator({store:rules,workspace,provider,archive,mail,dashboard,clock:()=>now,settings:()=>dashboard.settings(),calendar:()=>[]});
dispatcher=new OrderRuleDispatcher({store:rules,mail,clock:()=>now,settings:()=>dashboard.settings(),providersReady:()=>Object.values(execution.snapshot().capabilities).every(v=>v===true),attachmentReader:f=>archive.read(f),templateResolver:id=>mailStore.categoryTemplate(id)});
web=createDashboard({store:dashboard,workspace,orderRules:rules,orderExecution:execution,orderDispatcher:dispatcher,mail,outputDir:dir});await new Promise(r=>web.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+web.address().port;let cookie;
const call=async(route,body)=>{const response=await fetch(base+route,{method:body?'POST':'GET',headers:{...(cookie?{Cookie:cookie}:{}),...(body?{'Content-Type':'application/json',Origin:base}:{})},body:body?JSON.stringify(body):undefined});const data=await response.json();assert.ok(response.ok,route+': '+JSON.stringify(data));return {response,data};};
const setup=await call('/api/bootstrap',{username:'admin',password:'Fixture-password-123'});cookie=setup.response.headers.get('set-cookie').split(';')[0];const admin=dashboard.users()[0],connection=workspace.createConnection({name:'隔离连接',owner:'admin'},admin,[admin]);
const listing=(await call('/api/order-rules/field-samples/list',{connectionId:connection.id,scope:'configuration',idempotencyKey:'config-list'})).data;
const captured=(await call('/api/order-rules/field-samples/capture',{connectionId:connection.id,listId:listing.id,rowId:listing.rows[0].id,idempotencyKey:'config-capture'})).data;
const before=rules.all('rules'),catalog=(await call('/api/order-rules/field-samples/catalog')).data;assert.equal(catalog.items[0].id,captured.id);assert.equal(catalog.items[0].fields,undefined);
const proposal=(await call('/api/order-rules/field-mappings/propose',{sampleId:captured.id,ruleId:'bs-change',ruleVersion:1})).data;assert.equal(proposal.recognition.valid,true);assert.equal(proposal.recognition.event.quantity,0);assert.match(proposal.recognition.event.brief,/HA000123/);assert.deepEqual(rules.all('rules'),before);assert.deepEqual(rules.all('orders'),[]);assert.deepEqual(rules.all('execution-tasks'),[]);assert.equal(proposal.recognition.publishEvidence,false);
const adapter=(await call('/api/order-rules/field-mappings/draft',{sampleId:captured.id,processName:captured.processName,processVersion:captured.processVersion,sources:proposal.mapping.sources,version:0,idempotencyKey:'config-draft'})).data;
const mappingCheck=(await call('/api/order-rules/field-mappings/check',{id:adapter.id,version:adapter.version,sampleId:captured.id,idempotencyKey:'mapping-check'})).data;assert.equal(mappingCheck.valid,true);await call('/api/order-rules/field-mappings/activate',{id:adapter.id,version:adapter.version,checkId:mappingCheck.id,idempotencyKey:'mapping-confirm'});
const current=(await call('/api/order-rules')).data.rules.find(r=>r.id==='bs-change');const saved=(await call('/api/order-rules/rules',{...current,adapterIds:[adapter.id],to:['2639266652@qq.com'],cc:[],attachPdf:false,archiveDirectory:'\\\\fixture-nas\\orders',filenameDate:'receivedAt'})).data;
assert.equal((await call('/api/order-rules/rules/bs-change/trial',{version:saved.version,sampleId:captured.id})).data.valid,true);await call('/api/order-rules/rules/bs-change/publish',{version:saved.version});
orderNo='000456';
await call('/api/order-execution/scan',{connectionId:connection.id,idempotencyKey:'archive'});await call('/api/order-execution/scan',{connectionId:connection.id,idempotencyKey:'duplicate'});assert.equal((await fs.readdir(share)).length,1);assert.equal(mutations,0);
const order=rules.all('orders')[0],evidence=order.archive.files[0],bytes=await archive.read(evidence);assert.equal(bytes.subarray(0,5).toString(),'%PDF-');assert.equal(bytes.length,evidence.size);assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'),evidence.sha256);
const channel=mailStore.saveChannel({name:'隔离邮箱',email:'sender@example.test',enabled:false,senders:['source@example.test'],smtp:{host:'fixture.test',port:465,security:'tls',user:'fixture',password:'fixture'},imap:{host:'fixture.test',port:993,security:'tls',user:'fixture',password:'fixture'}});mailStore.setState(channel.id,channel.version,{smtp:true});
await call('/api/order-rules/settings',{...rules.settings(),enabled:true,channelId:channel.id});
now=new Date('2026-10-19T08:59:00+08:00');await dispatcher.tick();now=new Date('2026-10-19T09:00:00+08:00');await dispatcher.tick();
// The dashboard's configured morning cutoff is 09:00, but this received-at is
// exactly 09:00 and belongs to the later half-open window. It must not leak.
assert.equal(messages.length,0);now=new Date('2026-10-19T16:59:00+08:00');await dispatcher.tick();now=new Date('2026-10-19T17:00:00+08:00');await call('/api/order-execution/scan',{connectionId:connection.id,idempotencyKey:'cutoff-complete'});await dispatcher.tick();
assert.equal(messages.length,1);const message=await simpleParser(messages[0]);assert.deepEqual(message.to.value.map(v=>v.address),['2639266652@qq.com']);assert.equal(message.attachments.length,0);assert.equal(message.cc,undefined);assert.match(message.text,/000456/);assert.doesNotMatch(message.text,/(?<!HA)000123/);
assert.equal((await call('/api/order-execution')).data.tasks[0].status,'sent');assert.equal(rules.all('batches').filter(b=>b.status==='sent').length,1);const frozen=rules.all('batches');const updated=rules.saveMapping({processName:captured.processName,processVersion:captured.processVersion,sampleId:captured.id,sources:proposal.mapping.sources,version:1,idempotencyKey:'updated-mapping'},admin),checked=rules.checkMapping({id:updated.id,version:updated.version,sampleId:captured.id,idempotencyKey:'updated-check'},admin);rules.activateMapping({id:updated.id,version:updated.version,checkId:checked.id,idempotencyKey:'updated-confirm'},admin);assert.equal(rules.get('rules','bs-change').published.status,'paused');assert.equal(rules.get('rules','bs-change').trialVersion,null);assert.deepEqual(rules.all('batches'),frozen);assert.equal(mutations,0);
});
+13
View File
@@ -0,0 +1,13 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),{setup}=require('../fixtures/records-app.cjs');
test('global sync settings live only in BPM, keep stored values and expose read-only roles',async t=>{const f=await setup(t),page=await f.page('#bpm');await page.getByRole('heading',{name:'全局同步设置',exact:true}).waitFor({timeout:3000});assert.equal(await page.getByLabel('自动到达同步',{exact:true}).isChecked(),false);assert.equal(await page.getByLabel('完整对账间隔(分钟)',{exact:true}).inputValue(),'9');await page.goto(f.base+'/#records');await page.locator('[data-arrival-row]').first().waitFor();assert.equal(await page.locator('#scan-config').count(),0);await page.close();const reader=await f.page('#bpm','viewer');await reader.getByRole('heading',{name:'全局同步设置',exact:true}).waitFor();assert.equal(await reader.locator('#scan-config').count(),0);await reader.getByText('9 分钟',{exact:true}).waitFor();assert.deepEqual(f.scan.config(),{enabled:false,intervalMinutes:9});});
test('record pages retain independent applied queries across tabs, reload and history',async t=>{const f=await setup(t),page=await f.page('#records?page=3');await page.locator('[data-arrival-row]').first().waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 3/);let calls=0;page.on('request',r=>{if(new URL(r.url()).pathname==='/api/arrivals')calls++;});await page.getByRole('link',{name:'流程到达记录',exact:true}).click();await page.waitForTimeout(100);assert.equal(calls,0);await page.getByLabel('搜索流程记录',{exact:true}).fill('未应用条件');await page.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 4'));assert.equal(new URLSearchParams(page.url().split('?')[1]).has('q'),false);assert.equal(await page.locator('[data-arrival-row]').count(),25);await page.getByRole('button',{name:'上一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 3'));await page.getByRole('link',{name:'PDF 导出记录',exact:true}).click();await page.locator('[data-pdf-row]').first().waitFor();await page.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 2'));await page.getByRole('link',{name:'流程到达记录',exact:true}).click();await page.locator('[data-arrival-row]').first().waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 3/);await page.reload();await page.locator('[data-arrival-row]').first().waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 3/);await page.goBack();await page.locator('[data-pdf-row]').first().waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 2/);});
test('pagination keeps the successful page on a failed request, supports retry and clamps a shrinking last page',async t=>{const f=await setup(t),page=await f.page('#records');await page.locator('[data-arrival-row]').first().waitFor();let held,requests=0,fail=true;await page.route('**/api/arrivals?*',async route=>{if(new URL(route.request().url()).searchParams.get('page')==='2'){requests++;if(fail){held=route;return;}}await route.continue();});await page.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-next]').disabled);assert.equal(await page.getByRole('button',{name:'下一页',exact:true}).isDisabled(),true);await page.waitForTimeout(50);await held.fulfill({status:503,json:{error:'隔离分页失败'}});await page.getByRole('button',{name:'重试加载',exact:true}).waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 1/);assert.equal(page.url().includes('page=2'),false);fail=false;await page.getByRole('button',{name:'重试加载',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 2'));assert.equal(requests,2);await page.getByRole('button',{name:'第 5 页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 5'));f.scan.db.exec("DELETE FROM arrivals WHERE task_id>'030'");await page.getByRole('button',{name:'刷新记录',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 2'));assert.equal(await page.locator('[data-arrival-row]').count(),6);});
test('browser back to a bare record URL restores page one rather than the most recently cached page',async t=>{const f=await setup(t),page=await f.page('#records');await page.locator('[data-arrival-row]').first().waitFor();await page.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 2'));await page.goBack();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 1'),null,{timeout:2500});assert.equal(new URL(page.url()).hash,'#records');});
test('logout clears saved record filters and the next account starts with its own defaults',async t=>{const f=await setup(t),page=await f.page('#records?page=3');await page.locator('[data-arrival-row]').first().waitFor();await page.getByRole('button',{name:'退出',exact:true}).click();await page.locator('#login-form').waitFor();assert.equal(await page.evaluate(()=>Object.keys(sessionStorage).filter(k=>k.startsWith('ona-record-navigation:')).length),0);await page.locator('#username').fill('viewer');await page.locator('#password').fill(f.password);await page.locator('#login-form button').click();await page.locator('[data-arrival-row]').first().waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 1/);});
test('background updates preserve open details and drafts until explicit refresh, and page size uses applied filters',async t=>{const f=await setup(t),page=await f.page('#records','admin',true);await page.locator('[data-arrival-row]').first().waitFor();await page.getByLabel('搜索流程记录',{exact:true}).fill('未应用的关键字');await page.getByRole('button',{name:'查看详情',exact:true}).first().click();await page.getByRole('dialog',{name:'流程到达详情'}).waitFor();f.scan.complete(f.scan.begin(f.connection.id,'admin'),f.connection.id,[{taskId:'NEW',serialNum:'NEW',source:'portal-v4',processName:'海外运营订单评审',activityName:'通知节点',subject:'后台新增记录',arrivalDay:'2026-10-21',arrivedAt:'2026-10-21T01:00:00Z'}]);await page.clock.fastForward(11000);await page.getByText('记录有更新。',{exact:true}).waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/105/);assert.equal(await page.locator('[data-arrival-row]').filter({hasText:'后台新增记录'}).count(),0);await page.getByRole('dialog').getByText('订单样例 000',{exact:true}).waitFor();await page.getByRole('button',{name:'关闭详情',exact:true}).click();await page.clock.fastForward(400);await page.locator('.card-header').getByRole('button',{name:'刷新记录',exact:true}).click();await page.locator('[data-arrival-row]').filter({hasText:'后台新增记录'}).waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/106/);assert.equal(await page.getByLabel('搜索流程记录',{exact:true}).inputValue(),'未应用的关键字');await page.getByLabel('每页条数',{exact:true}).selectOption('50');await page.waitForFunction(()=>document.querySelectorAll('[data-arrival-row]').length===50);assert.equal(new URLSearchParams(page.url().split('?')[1]).has('q'),false);assert.equal(await page.evaluate(()=>JSON.stringify(sessionStorage).includes('后台新增记录')),false);});
test('record scroll positions survive page changes, tab return and reload without widening the mobile viewport',async t=>{const f=await setup(t),page=await f.page('#records?page=2');await page.locator('[data-arrival-row]').first().waitFor();await page.evaluate(()=>window.scrollTo(0,850));await page.waitForTimeout(250);await page.goto(f.base+'/#records-pdf');await page.locator('[data-pdf-row]').first().waitFor();await page.evaluate(()=>window.scrollTo(0,600));await page.waitForTimeout(250);await page.goto(f.base+'/#records?page=2');await page.locator('[data-arrival-row]').first().waitFor();await page.waitForFunction(()=>Math.abs(window.scrollY-850)<80);await page.reload();await page.locator('[data-arrival-row]').first().waitFor();await page.waitForFunction(()=>Math.abs(window.scrollY-850)<80);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);});
test('sync configuration failures retain input and use the shared save-and-leave guard',async t=>{const f=await setup(t),page=await f.page('#bpm');await page.locator('#scan-config').waitFor();let reject=true;await page.route('**/api/bpm-scan/config',route=>reject?route.fulfill({status:503,json:{error:'隔离保存失败'}}):route.continue());await page.getByLabel('完整对账间隔(分钟)',{exact:true}).fill('11');await page.getByRole('button',{name:'保存同步设置',exact:true}).click();await page.locator('#scan-config').getByText('隔离保存失败',{exact:true}).waitFor();assert.equal(await page.getByLabel('完整对账间隔(分钟)',{exact:true}).inputValue(),'11');assert.equal(f.scan.config().intervalMinutes,9);await page.getByRole('link',{name:'工具',exact:true}).click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();reject=false;await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('[data-arrival-row]').first().waitFor();assert.equal(f.scan.config().intervalMinutes,11);});
test('missing sync configuration shows an error and retry without replacing the connection page or inventing defaults',async t=>{const f=await setup(t),page=await f.page('#records');await page.locator('[data-arrival-row]').first().waitFor();let fail=true;await page.route('**/api/bpm-scan',route=>fail?route.fulfill({status:503,json:{error:'配置暂不可用'}}):route.continue());await page.goto(f.base+'/#bpm');await page.getByRole('button',{name:'重试读取同步设置',exact:true}).waitFor();assert.equal(await page.locator('#scan-config').count(),0);await page.getByRole('heading',{name:'隔离测试来源',exact:true}).waitFor();fail=false;await page.getByRole('button',{name:'重试读取同步设置',exact:true}).click();await page.locator('#scan-config').waitFor();assert.equal(await page.getByLabel('完整对账间隔(分钟)',{exact:true}).inputValue(),'9');});
test('leaving a slow record page cancels its request and late data cannot replace the PDF tab',async t=>{const f=await setup(t),page=await f.page('#records');await page.locator('[data-arrival-row]').first().waitFor();let release;const received=new Promise(resolve=>release=resolve);await page.route('**/api/arrivals?*',route=>{if(new URL(route.request().url()).searchParams.get('page')==='2')release(route);else void route.continue();});await page.getByRole('button',{name:'下一页',exact:true}).click();const held=await received;await page.getByRole('link',{name:'PDF 导出记录',exact:true}).click();await page.locator('[data-pdf-row]').first().waitFor();await held.fulfill({json:{items:[],total:0,page:2,pageSize:25,sources:[]}}).catch(()=>{});assert.equal(await page.locator('[data-arrival-row]').count(),0);assert.equal(await page.locator('[data-pdf-row]').count(),25);assert.equal(new URL(page.url()).hash,'#records-pdf');});
test('the record same-tab shortcut does not suppress the existing refresh behavior of other pages',async t=>{const f=await setup(t),page=await f.page('#bpm');await page.locator('#scan-config').waitFor();const read=page.waitForRequest(r=>new URL(r.url()).pathname==='/api/workspace',{timeout:2000});await page.locator('#settings-tabs').getByRole('link',{name:'BPM 连接',exact:true}).click();await read;});
+5
View File
@@ -0,0 +1,5 @@
'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');const {resolveOutputDir}=require('../../src/app/application.cjs');
test('restored state selects its own output without overwriting an explicit deployment choice',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'restored-output-'));t.after(()=>fs.rm(dir,{recursive:true,force:true}));await fs.mkdir(path.join(dir,'restored-pdf'));await fs.writeFile(path.join(dir,'restore-config.json'),JSON.stringify({outputDir:'restored-pdf'}));assert.equal(await resolveOutputDir('C:/example',dir,{}),path.join(dir,'restored-pdf'));assert.equal(await resolveOutputDir('C:/example',dir,{outputDir:'explicit'}),path.resolve('C:/example','explicit'));await fs.writeFile(path.join(dir,'restore-config.json'),JSON.stringify({outputDir:'../original'}));await assert.rejects(resolveOutputDir('C:/example',dir,{}),/恢复输出目录/);
});
@@ -1,7 +1,7 @@
'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');
test('health keeps success/failure history across restart, filters BPM ownership, and never checks external systems',async t=>{
const {RuntimeHealth}=require('../src/runtime-health.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-health-'));let health;
const {RuntimeHealth}=require('../../src/modules/health/runtime-health.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-health-'));let health;
t.after(async()=>{health?.close();await fs.rm(stateDir,{recursive:true,force:true});});
const connections=[{id:'mine',name:'我的连接',owner:'worker',status:'connected',checkedAt:'2026-10-18T01:00:00Z',lastConnectedAt:'2026-10-18T01:00:00Z',password:'PRIVATE'},{id:'other',name:'PRIVATE_OTHER',owner:'other',status:'connected'}];
const deps={stateDir,workspace:{snapshot:()=>({connections})},scanner:{store:{status:()=>({config:{enabled:false},runs:[{connectionId:'mine',status:'error',finishedAt:'2026-10-18T02:00:00Z'}]})},scan:()=>assert.fail('must not scan')},storage:{store:{servers:()=>[{id:'s',name:'共享',enabled:true,state:{checkedAt:'2026-10-18T01:00:00Z',readable:true,writable:true,message:'password=PRIVATE C:/PRIVATE/file'}}]},check:()=>assert.fail('must not write/check')},mail:{store:{channels:()=>[]},verify:()=>assert.fail('must not verify/send')}};
@@ -11,6 +11,12 @@ test('health keeps success/failure history across restart, filters BPM ownership
assert.equal(health.snapshot({username:'admin',role:'admin'}).groups.find(g=>g.key==='bpm').items.length,2);
});
test('a damaged module is reported unknown without hiding other modules or claiming real-time connectivity',async t=>{
const {RuntimeHealth}=require('../src/runtime-health.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-health-errors-'));const health=new RuntimeHealth({stateDir,workspace:{snapshot:()=>({connections:[]})},storage:{store:{servers:()=>{throw Error('PRIVATE failure');}}},mail:{store:{channels:()=>[{id:'m',name:'邮箱',enabled:false,state:{checkedAt:null,smtp:false,imap:false}}]}}});t.after(async()=>{health.close();await fs.rm(stateDir,{recursive:true,force:true});});
const {RuntimeHealth}=require('../../src/modules/health/runtime-health.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-health-errors-'));const health=new RuntimeHealth({stateDir,workspace:{snapshot:()=>({connections:[]})},storage:{store:{servers:()=>{throw Error('PRIVATE failure');}}},mail:{store:{channels:()=>[{id:'m',name:'邮箱',enabled:false,state:{checkedAt:null,smtp:false,imap:false}}]}}});t.after(async()=>{health.close();await fs.rm(stateDir,{recursive:true,force:true});});
const data=health.snapshot({role:'admin'});assert.equal(data.groups.find(g=>g.key==='storage').status,'unknown');assert.equal(data.groups.find(g=>g.key==='mail').items[0].status,'pending');assert.equal(data.runtime.managed,false);assert.doesNotMatch(JSON.stringify(data),/PRIVATE/);
});
test('execution health reports saved blockers and filters task ownership without probing providers',async t=>{
const {RuntimeHealth}=require('../../src/modules/health/runtime-health.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-health-execution-'));
const health=new RuntimeHealth({stateDir,workspace:{snapshot:()=>({connections:[{id:'mine',owner:'worker'},{id:'other',owner:'other'}]})},execution:{snapshot:()=>({capabilities:{liveTodo:true,pdfExport:false,automaticArchive:false},tasks:[{id:'a',connectionId:'mine',processName:'目标流程',status:'blocked',error:'缺少订单字段',updatedAt:'2026-10-19T01:00:00Z'},{id:'b',connectionId:'other',processName:'PRIVATE_OTHER',status:'failed'}]}),refreshCapabilities:()=>assert.fail('health must not probe')}});t.after(async()=>{health.close();await fs.rm(stateDir,{recursive:true,force:true});});
const group=health.snapshot({username:'worker',role:'operator'}).groups.find(g=>g.key==='execution');assert.ok(group);assert.equal(group.status,'error');assert.doesNotMatch(JSON.stringify(group),/PRIVATE_OTHER/);assert.ok(group.items.some(i=>i.detail.includes('缺少订单字段')));
});
@@ -4,10 +4,10 @@ const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const net = require('node:net');
const serverModule = (() => { try { return require('../src/server.cjs'); } catch(e) { if(e.code === 'MODULE_NOT_FOUND') return {}; throw e; } })();
const serverModule = (() => { try { return require('../../src/server.cjs'); } catch(e) { if(e.code === 'MODULE_NOT_FOUND') return {}; throw e; } })();
const origin = 'chrome-extension://' + 'a'.repeat(32);
test('BPM field evidence must match the current order binding and captured value',()=>{
const {validateSnapshot}=require('../src/exporter.cjs');
const {validateSnapshot}=require('../../src/modules/pdf/exporter.cjs');
const snapshot={html:'<form>订单</form>',metadata:{order:'001234',project:'project',model:'model',serial:'notice'}};
assert.doesNotThrow(()=>validateSnapshot(snapshot));
for(const field of ['OFR_LSCP_Applicant.OrderNum','OFR_BS_Applicant.OrderNum','OFR_KD_Applicant.OrderNum','OFR_WY_Applicant.OrderNum'])assert.doesNotThrow(()=>validateSnapshot({...snapshot,bpmOrder:{field,value:'001234'}}));
@@ -33,7 +33,7 @@ test('loopback API rejects web origins, unpaired callers and oversized bodies',
test('paired HTTP export returns a readable PDF saved to the configured directory', async () => {
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-http-test-'));
const {Store}=require('../src/dashboard-store.cjs');
const {Store}=require('../../src/modules/dashboard/store.cjs');
const store=new Store(path.join(dir,'state'));
const bpmOrder={field:'OFR_WY_Applicant.OrderNum',value:'900001'};
const server=serverModule.createServer({token:'test-pairing-key',outputDir:dir,store});
@@ -70,7 +70,7 @@ test('extension setup failure leaves no listening service behind', async () => {
try {
const invalid=path.join(dir,'extension');
await fs.writeFile(invalid,'not a directory');
await assert.rejects(serverModule.startService({port,token:'test-key',outputDir:dir,extensionSourceDir:path.resolve(__dirname,'../extension'),installedExtension:invalid}));
await assert.rejects(serverModule.startService({port,token:'test-key',outputDir:dir,extensionSourceDir:path.resolve(__dirname,'../../extension'),installedExtension:invalid}));
const free=net.createServer();
await new Promise((resolve,reject)=>{free.once('error',reject);free.listen(port,'127.0.0.1',resolve);});
await new Promise(resolve=>free.close(resolve));
+47
View File
@@ -0,0 +1,47 @@
'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');
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function fixture(t,hash='schedule'){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-review-')),runtime=await startTestDashboard({stateDir:dir,mailHistory:true}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(6000);await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#'+hash);await login(page);return {page,runtime};}
test('a successful delayed save commits only submitted inputs and later edits remain dirty',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();let release,arrive;const arrived=new Promise(r=>arrive=r),gate=new Promise(r=>release=r);await page.route('**/api/settings',async route=>{if(route.request().method()==='GET')return route.continue();const response=await route.fetch();arrive();await gate;return route.fulfill({response});});await page.locator('#time-first').fill('09:11');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await arrived;await page.locator('#time-first').fill('09:12');release();await page.getByText('发送计划已保存。',{exact:true}).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),true);await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();assert.equal(await page.locator('#time-first').inputValue(),'09:12');});
for(const destination of ['internal','route'])test('Save and Continue preserves currentTarget for rule settings: '+destination,{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await openRuleRoute(page,'notification-settings');await page.locator('#order-rule-settings').waitFor();const input=page.locator('#order-rule-settings [name=maxSize]');await input.fill('12');const posts=[];await page.route('**/api/order-rules/settings',async route=>{posts.push(route.request().postDataJSON());return route.continue();});if(destination==='internal')await openRuleRoute(page,'order-notifications');else await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();if(destination==='internal')await page.getByRole('heading',{name:'连续业务窗口',exact:true}).waitFor();else await page.locator('#schedule-form').waitFor();assert.equal(posts.length,1);assert.equal(posts[0].maxMessageBytes,12582912);});
async function mailFixture(page){const drafts=['t1','t2'].map((id,i)=>({id,version:1,status:'pending',subject:'模板'+(i+1),scope:'',channelId:'mail1',sender:'fixture@example.test',attachmentCount:0,attachments:[],text:'正文'}));await page.route('**/api/mail',route=>route.fulfill({json:{channels:[],templates:drafts,receipts:[],sends:[]}}));await page.route('**/api/mail/templates/categories',route=>route.fulfill({json:{categories:[],bindings:[]}}));await page.route(/\/api\/mail\/templates\/t[12]$/,route=>route.fulfill({json:drafts.find(d=>route.request().url().endsWith('/'+d.id))}));await page.route('**/api/mail/templates/*/preview',route=>route.fulfill({contentType:'text/html',body:'<p>正文</p>'}));return drafts;}
test('switching a template immediately retires its old editable form while the next detail loads',{timeout:45000},async t=>{
const {page}=await fixture(t),drafts=await mailFixture(page);await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('[data-template=t1]').click();await page.waitForFunction(()=>document.querySelector('#template-subject')?.value==='模板1');
let release,arrive;const gate=new Promise(r=>release=r),arrived=new Promise(r=>arrive=r);await page.route('**/api/mail/templates/t2',async route=>{arrive();await gate;await route.fulfill({json:drafts[1]});});
await page.locator('[data-template=t2]').click();await arrived;const staleInputs=await page.locator('#template-subject').count();release();await page.waitForFunction(()=>document.querySelector('#template-subject')?.value==='模板2');assert.equal(staleInputs,0);
await page.route('**/api/mail/templates/t1',route=>route.fulfill({status:503,json:{error:'模板读取中断'}}));await page.locator('[data-template=t1]').click();await page.locator('#mail-template-detail').getByText(/模板读取中断/).waitFor();assert.equal(await page.locator('#template-subject').count(),0);
});
test('switching a dirty template supports stay discard and save before selecting another',{timeout:45000},async t=>{const {page}=await fixture(t);const drafts=await mailFixture(page);let saved;await page.route('**/api/mail/templates/t1/confirm',route=>{saved=route.request().postDataJSON();drafts[0].status='active';drafts[0].subject=saved.subject;return route.fulfill({json:{ok:true}});});await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('[data-template=t1]').click();await page.locator('#template-subject').fill('未保存模板一');await page.locator('[data-template=t2]').click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('#template-subject').inputValue(),'未保存模板一');await page.locator('[data-template=t2]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#template-subject')?.value==='模板2');await page.locator('[data-template=t1]').click();await page.locator('#template-subject').fill('保存模板一');await page.locator('[data-template=t2]').click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#template-subject')?.value==='模板2');assert.equal(saved.subject,'保存模板一');});
test('failed uncertain-result readback stays uncertain and never claims state was queried',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();let posts=0,reads=0;await page.route('**/api/settings',route=>{if(route.request().method()==='POST'){posts++;return route.abort('timedout');}reads++;return route.fulfill({status:503,json:{error:'State unavailable'}});});await page.locator('#time-first').fill('10:01');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#operation-uncertain')?.textContent.includes('查询失败'));const text=await page.locator('#operation-uncertain').innerText();assert.match(text,/结果待核实/);assert.doesNotMatch(text,/已查询最新状态/);assert.equal(posts,1);assert.equal(reads,1);});
test('delayed readback cannot notify after leaving its originating page',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();let release,arrive;const gate=new Promise(r=>release=r),arrived=new Promise(r=>arrive=r);await page.route('**/api/settings',async route=>{if(route.request().method()==='POST')return route.abort('timedout');arrive();await gate;return route.fulfill({json:{version:2,schedule:{times:['09:00','17:00']}}});});await page.locator('#time-first').fill('10:02');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await arrived;await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();await page.evaluate(()=>document.querySelector('#flash')?.remove());release();await page.waitForTimeout(250);assert.equal(await page.locator('#flash').count(),0);assert.equal(await page.locator('#operation-uncertain').count(),0);});
test('execution detail retains recovery notes during explicit list refresh and reopens with current version',{timeout:45000},async t=>{
const {page,runtime}=await fixture(t,'order-rules');runtime.orderRules.put('execution-tasks',{id:'t1',connectionId:'c1',status:'failed',version:1,error:'失败一',row:{orderNo:'ONE'}});const retried=[];
await page.route('**/api/order-execution/tasks/t1/retry',route=>{retried.push(route.request().postDataJSON());return route.fulfill({json:{ok:true}});});await openRuleRoute(page,'notification-execution');await page.getByRole('button',{name:'查看详情'}).click();await page.getByLabel('操作依据').fill('保留任务的处理依据');runtime.orderRules.put('execution-tasks',{id:'t1',connectionId:'c1',status:'failed',version:2,error:'再次失败',row:{orderNo:'ONE'}});await page.evaluate(()=>window.RecordTable.active.refresh());assert.equal(await page.getByLabel('操作依据').inputValue(),'保留任务的处理依据');await page.getByRole('button',{name:'重试失败任务',exact:true}).click();await page.getByText('操作已提交,请关闭详情并刷新列表核对实际结果。',{exact:true}).waitFor();assert.equal(retried[0].version,1);await page.getByRole('button',{name:'关闭详情'}).click();await page.waitForTimeout(400);await page.getByRole('button',{name:'查看详情'}).click();await page.getByLabel('操作依据').fill('读取最新版本再尝试');await page.getByRole('button',{name:'重试失败任务',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-business-action] [role=alert]')?.textContent.includes('操作已提交'));assert.deepEqual(retried.map(r=>r.version),[1,2]);
});
test('rerendering rule saves lock editable fields until the saved response has replaced the form',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await openRuleRoute(page,'order-rules');let release,arrive;const gate=new Promise(r=>release=r),arrived=new Promise(r=>arrive=r);await page.route('**/api/order-rules/rules',async route=>{const response=await route.fetch();arrive();await gate;return route.fulfill({response});});await page.getByLabel('规则名称',{exact:true}).fill('提交中的草稿');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await arrived;assert.equal(await page.getByLabel('规则名称',{exact:true}).isDisabled(),true);release();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();assert.equal(await page.getByLabel('规则名称',{exact:true}).isDisabled(),false);assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'提交中的草稿');assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);});
test('invalid readback payload is rejected even when HTTP succeeds',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();await page.route('**/api/settings',route=>route.request().method()==='POST'?route.abort('timedout'):route.fulfill({json:{schedule:'not a schedule'}}));await page.locator('#time-first').fill('10:03');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#operation-uncertain')?.textContent.includes('查询失败'));assert.doesNotMatch(await page.locator('#operation-uncertain').innerText(),/已查询最新状态/);});
test('uncertain calendar write reads its workspace calendar rather than overview',{timeout:45000},async t=>{const {page}=await fixture(t,'calendar');await page.locator('#day-note').waitFor();let reads=0;await page.route('**/api/calendar',route=>route.abort('timedout'));await page.route('**/api/workspace',route=>{reads++;return route.fulfill({json:{calendar:{version:8,overrides:[]}}});});await page.locator('#day-note').fill('隔离测试日历安排');await page.getByRole('button',{name:'应用到此日期',exact:true}).click();await page.getByRole('button',{name:'保存日历',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#operation-uncertain')?.textContent.includes('配置版本 8'));assert.equal(reads,1);});
test('rule durable save survives refresh failure, retains version and permits Save and Continue',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await openRuleRoute(page,'order-rules');let failRead=false;const versions=[];await page.route('**/api/order-rules?view=summary',route=>failRead?route.fulfill({status:503,json:{error:'refresh unavailable'}}):route.continue());await page.route('**/api/order-rules/rules',async route=>{versions.push(route.request().postDataJSON().version);const response=await route.fetch();failRead=true;return route.fulfill({response});});await page.getByLabel('规则名称',{exact:true}).fill('首次持久保存');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/已保存.*刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);await page.getByLabel('规则名称',{exact:true}).fill('再次持久保存');await page.locator('a[href="#system-settings"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.deepEqual(versions,[1,2]);});
test('field mapping save retains returned version after followup GET fails',{timeout:45000},async t=>{
const {page}=await fixture(t,'order-rules');let saved=false;const versions=[];
await page.route('**/api/order-rules/fields*',route=>saved?route.fulfill({status:503,json:{error:'fields unavailable'}}):route.fulfill({json:{samples:[{id:'s1',processName:'测试流程',processVersion:'1',sample:{title:'订单号:A1'},fields:[{path:'order',label:'订单号',value:'A1'},{path:'brief',label:'摘要',value:'摘要'}]}],adapters:[]}}));
await page.route('**/api/order-rules/field-mappings/draft',route=>{const input=route.request().postDataJSON();versions.push(input.version);saved=true;return route.fulfill({json:{...input,id:'a1',version:versions.length,sources:{...input.sources,receivedAt:{type:'metadata',key:'receivedAt'}}}});});
await openRuleRoute(page,'rule-fields');await page.locator('#fm-manual').evaluate(e=>e.open=true);await page.locator('#fm-orderNo').selectOption('order');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/已保存.*刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);
await page.getByText(/可选业务信息 ·/).evaluate(e=>e.parentElement.open=true);await page.locator('#fm-customer').selectOption('brief');await page.locator('a[href="#overview"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByRole('heading',{name:'连续业务窗口',exact:true}).waitFor();assert.deepEqual(versions,[0,1]);
});
test('template usage read failure never enables an alternate binding writer',{timeout:45000},async t=>{const {page}=await fixture(t);await mailFixture(page);await page.route('**/api/order-rules?view=summary',route=>route.fulfill({status:503,json:{error:'使用情况读取失败'}}));await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('#content').getByText('使用情况读取失败',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'保存关联'}).count(),0);assert.equal(await page.getByRole('button',{name:'预览并确认',exact:true}).count(),2);await page.locator('[data-template=t1]').click();await page.getByLabel('发信标题',{exact:true}).waitFor();assert.equal(await page.getByLabel('发信标题',{exact:true}).inputValue(),'模板1');});
test('unknown and conflicted task details cannot offer ordinary retry',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'order-rules');runtime.orderRules.put('execution-tasks',{id:'unknown',connectionId:'c1',status:'unknown',version:1,row:{orderNo:'UNKNOWN'}});await openRuleRoute(page,'notification-execution');await page.getByRole('button',{name:'查看详情'}).click();await page.getByRole('heading',{name:'处理进度'}).waitFor();assert.equal(await page.getByRole('button',{name:'重试失败任务',exact:true}).count(),0);});
test('confirmed template and created user stay committed when list refresh fails',{timeout:45000},async t=>{const {page}=await fixture(t);await mailFixture(page);await page.route('**/api/mail/templates/t1/confirm',route=>route.fulfill({json:{id:'t1',status:'active',version:2}}));await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('[data-template=t1]').click();await page.route('**/api/mail',route=>route.fulfill({status:503,json:{error:'mail list unavailable'}}));await page.getByRole('button',{name:'确认生效',exact:true}).click();await page.getByText(/模板已确认生效.*刷新失败/).waitFor();assert.equal(await page.getByRole('button',{name:'确认生效',exact:true}).count(),0);await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('link',{name:'团队账号',exact:true}).click();await page.locator('#new-username').fill('isolated-new');await page.locator('#new-password').fill('Fixture-password-123');await page.route('**/api/users',route=>route.request().method()==='POST'?route.fulfill({json:{id:'new-user'}}):route.fulfill({status:503,json:{error:'users unavailable'}}));await page.getByRole('button',{name:'创建账号',exact:true}).click();await page.getByText(/账号已创建.*刷新失败/).waitFor();assert.equal(await page.locator('#new-password').inputValue(),'');});
test('assistant settings retain persisted version after refresh failure',{timeout:45000},async t=>{const {page}=await fixture(t);await page.route('**/api/assistant',route=>route.fulfill({json:{settings:{version:1,runtimePath:'',apiBase:'',model:'',timeoutSeconds:30,dailyLimit:10}}}));await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('link',{name:'助手设置',exact:true}).click();await page.locator('#assistant-model').waitFor();const versions=[];await page.route('**/api/assistant/settings',async route=>{versions.push(route.request().postDataJSON().version);return route.fulfill({json:{version:versions.at(-1)+1}});});await page.route('**/api/assistant',route=>route.fulfill({status:503,json:{error:'assistant refresh unavailable'}}));await page.locator('#assistant-model').fill('fixture-model-one');await page.getByRole('button',{name:'保存助手设置',exact:true}).click();await page.getByText(/助手设置已保存.*刷新失败/).waitFor();await page.locator('#assistant-model').fill('fixture-model-two');await page.getByRole('button',{name:'保存助手设置',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('#assistant-settings-form')?.hasAttribute('aria-busy'));assert.equal(versions[1],versions[0]+1);});
async function openRuleRoute(page,hash){
await page.evaluate(hash=>{const link=document.createElement('a');link.href='#'+hash;document.body.append(link);link.click();link.remove();},hash);
}
+39
View File
@@ -0,0 +1,39 @@
'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');
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function fixture(t,hash='schedule') {const dir=await fs.mkdtemp(path.join(os.tmpdir(),'web-closure-'));const runtime=await startTestDashboard({stateDir:dir,mailHistory:true});const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(5000);await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#'+hash);await login(page);return {page,runtime};}
test('settings open directly with horizontal tabs, retired hashes redirect, and mobile stays inside viewport',{timeout:45000},async t=>{const {page}=await fixture(t,'business-settings');await page.locator('#order-rules-panel').waitFor();assert.equal(await page.locator('#settings-tabs a').count(),3);await page.getByRole('link',{name:'业务设置',exact:true}).click();await page.getByRole('link',{name:'通知配置',exact:true}).first().click();await page.locator('#schedule-form').waitFor();assert.equal(await page.locator('#send-mode').count(),0);await page.goBack();await page.goBack();await page.locator('#order-rules-panel').waitFor();for(const [hash,title] of [['supervisor','系统健康'],['connections','系统健康'],['notifications','分类通知规则']]){await page.evaluate(h=>location.hash=h,hash);await page.getByRole('heading',{name:title,exact:true}).first().waitFor();}await page.evaluate(()=>location.hash='system-settings');await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.equal(await page.locator('#settings-tabs a').count(),6);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.equal(await page.locator('#settings-tabs').evaluate(e=>getComputedStyle(e).overflowX),'auto');});
test('dirty navigation offers stay discard save, suppresses duplicate saves and preserves failed inputs',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();await page.locator('#time-first').fill('09:11');await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.locator('#time-first').inputValue(),'09:11');await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.locator('#day-form').waitFor();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.locator('#time-first').fill('09:12');let requests=0;await page.route('**/api/settings',async route=>{if(route.request().method()==='GET')return route.continue();requests++;await new Promise(r=>setTimeout(r,100));await route.fulfill({status:409,json:{error:'版本已更新,请核对'}});});await page.getByRole('button',{name:'保存发送计划',exact:true}).dblclick();await page.getByRole('alert').getByText('版本已更新,请核对',{exact:true}).waitFor();assert.equal(requests,1);assert.equal(await page.locator('#time-first').inputValue(),'09:12');await page.unroute('**/api/settings');await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('#day-form').waitFor();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();assert.equal(await page.locator('#time-first').inputValue(),'09:12');});
test('password creation is discard-only and assistant settings have a distinct route',{timeout:45000},async t=>{const {page}=await fixture(t,'account');await page.route('**/api/assistant',route=>route.fulfill({json:{settings:{version:1,runtimePath:'',apiBase:'',model:'',timeoutSeconds:60,dailyLimit:30,enabled:false,allowActions:false},conversations:[],usage:{calls:0,limit:30}}}));await page.locator('#account-current').fill('unsaved-test-secret');await page.getByRole('link',{name:'系统设置',exact:true}).click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();assert.equal(await page.getByRole('button',{name:'保存并继续',exact:true}).count(),0);await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByRole('link',{name:'助手设置',exact:true}).click();await page.locator('#assistant-settings-form').waitFor();await page.getByRole('link',{name:'工具',exact:true}).click();await page.getByRole('link',{name:'ZCode 助手',exact:true}).click();await page.locator('#assistant-compose').waitFor();assert.equal(await page.locator('#assistant-settings-form').count(),0);});
test('execution scan, evidence-only field draft and check emit versioned contracts',{timeout:45000},async t=>{
const {page,runtime}=await fixture(t,'order-rules'),writes=[];runtime.orderRules.put('execution-tasks',{id:'task1',version:4,status:'failed',error:'归档失败',connectionId:'connection1',row:{orderNo:'TASK1'}});await page.route('**/api/workspace',route=>route.fulfill({json:{connections:[{id:'connection1',name:'隔离连接',owner:'admin'}]}}));
await page.route('**/api/order-execution**',async route=>{if(route.request().method()==='POST'){writes.push({url:route.request().url(),body:route.request().postDataJSON()});return route.fulfill({json:{ok:true}});}return route.fulfill({json:{tasks:[{id:'task1',version:4,status:'failed',error:'归档失败',connectionId:'connection1'}],capabilities:{liveTodo:false,pdfExport:false,automaticArchive:false}}});});
const sample={id:'sample1',processName:'订单流程',processVersion:'v7',sample:{title:'订单号:TITLE-1',serialNum:'SER1'},fields:[{path:'Order.Number',label:'订单编号',value:'A123'},{path:'Order.Text',label:'正文',value:'通知'}]};
await page.route('**/api/order-rules/fields*',route=>route.fulfill({json:{samples:[sample],adapters:[]}}));
await page.route('**/api/order-rules/field-mappings/draft',route=>{const body=route.request().postDataJSON();writes.push({url:route.request().url(),body});return route.fulfill({json:{...body,id:'mapping1',version:1,sources:{...body.sources,processName:{type:'metadata',key:'processName'}}}});});
await page.route('**/api/order-rules/field-mappings/check',route=>{const body=route.request().postDataJSON();writes.push({url:route.request().url(),body});return route.fulfill({json:{id:'check1',version:1,sampleId:'sample1',valid:true,result:{event:{orderNo:'A123',brief:'订单号:TITLE-1',titleOrders:[{orderNo:'TITLE-1'}]},filenames:[],affectedCategories:[],issues:[]}}});});
await openRuleRoute(page,'notification-execution');await page.getByText('归档失败',{exact:true}).waitFor();await page.getByLabel('扫描连接',{exact:true}).selectOption('connection1');await page.evaluate(()=>{crypto.randomUUID=undefined;});await page.getByRole('button',{name:'扫描并处理订单',exact:true}).click();await page.getByText('扫描已完成,请核对订单中心。',{exact:true}).waitFor();assert.equal(writes[0].body.connectionId,'connection1');assert.match(writes[0].body.idempotencyKey,/^[a-z0-9-]+$/i);
await page.getByRole('button',{name:'查看详情',exact:true}).first().click();await page.getByLabel('操作依据',{exact:true}).fill('已恢复隔离归档目录');await page.getByRole('button',{name:'重试失败任务',exact:true}).click();await page.getByText('操作已提交,请关闭详情并刷新列表核对实际结果。',{exact:true}).waitFor();assert.equal(writes[1].body.version,4);await page.getByRole('button',{name:'关闭详情',exact:true}).click();await page.waitForTimeout(400);
await openRuleRoute(page,'rule-fields');await page.locator('#fm-manual').evaluate(e=>e.open=true);await page.locator('#fm-orderNo').selectOption('Order.Number');assert.equal(await page.locator('[data-fm-binding] input[type=text]').count(),0);await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('字段对应草稿已保存。',{exact:true}).waitFor();const draft=writes[2].body;assert.deepEqual({...draft,idempotencyKey:undefined},{sampleId:'sample1',processName:'订单流程',processVersion:'v7',sources:{orderNo:{type:'form',path:'Order.Number'},brief:{type:'title'}},version:0,idempotencyKey:undefined});assert.equal(typeof draft.idempotencyKey,'string');assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);
await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#fm-result .fm-title-order').getByText('订单号:TITLE-1',{exact:true}).waitFor();assert.deepEqual({...writes[3].body,idempotencyKey:undefined},{id:'mapping1',version:1,sampleId:'sample1',idempotencyKey:undefined});assert.equal(await page.locator('#fm-activate').isDisabled(),true);
});
test('calendar staged changes save through navigation and rule tab changes use the same guard',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'calendar');await page.route('**/api/order-rules/fields*',route=>route.fulfill({json:{samples:[],adapters:[]}}));await page.getByLabel('安排说明',{exact:true}).fill('隔离测试调休日');await page.getByRole('button',{name:'应用到此日期',exact:true}).click();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('#schedule-form').waitFor();assert.equal(runtime.workspace.snapshot().calendar.overrides[0].note,'隔离测试调休日');await openRuleRoute(page,'order-rules');await page.getByLabel('规则名称',{exact:true}).fill('尚未保存规则');await openRuleRoute(page,'rule-fields');await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'尚未保存规则');assert.equal(await page.evaluate(()=>{const e=new Event('beforeunload',{cancelable:true});window.dispatchEvent(e);return e.defaultPrevented;}),true);await openRuleRoute(page,'rule-fields');await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.waitForFunction(()=>location.hash==='#rule-fields');await page.locator('#fm-editor').waitFor();});
test('manual resend uses frozen batch identity and unknown offers verification only',{timeout:45000},async t=>{
const {page,runtime}=await fixture(t,'order-rules');for(const [id,status]of [['failed1','failed'],['unknown1','unknown']])runtime.orderRules.put('batches',{id,version:8,status,subject:id,orderIds:[],to:['frozen@example.test'],cc:[]});let body;
await page.route('**/api/order-rules/batches/failed1/resend',route=>{body=route.request().postDataJSON();return route.fulfill({json:{ok:true}});});await openRuleRoute(page,'notification-history');await page.getByRole('button',{name:'查看详情'}).first().click();await page.locator('[data-business-action=resend]').waitFor();await page.getByLabel('操作依据').fill('已确认原发送明确失败');await page.getByRole('button',{name:'人工补发原冻结批次',exact:true}).click();await page.getByText('操作已提交,请关闭详情并刷新列表核对实际结果。',{exact:true}).waitFor();assert.equal(body.version,8);assert.equal(body.note,'已确认原发送明确失败');assert.equal(typeof body.idempotencyKey,'string');assert.equal(Object.hasOwn(body,'to'),false);await page.getByRole('button',{name:'关闭详情'}).click();await page.waitForTimeout(400);await page.getByRole('button',{name:'查看详情'}).nth(1).click();await page.locator('[data-business-action=resolve]').waitFor();assert.equal(await page.locator('[data-business-action=resend]').count(),0);
});
test('late page responses cannot overwrite new form and dirty browser history keeps current inputs',{timeout:45000},async t=>{const {page}=await fixture(t,'calendar');await page.locator('#day-form').waitFor();let release;const gate=new Promise(r=>release=r);await page.route('**/api/settings',async route=>{if(route.request().method()!=='GET')return route.continue();await gate;return route.continue();});await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('link',{name:'业务日历',exact:true}).first().click();release();await page.locator('#day-form').waitFor();assert.equal(await page.locator('#schedule-form').count(),0);await page.unroute('**/api/settings');await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.locator('#time-first').fill('10:13');await page.goBack();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.match(page.url(),/#schedule$/);assert.equal(await page.locator('#time-first').inputValue(),'10:13');});
test('write timeout queries state without resubmission and retains uncertain inputs',{timeout:45000},async t=>{const {page}=await fixture(t,'schedule');await page.locator('#schedule-form').waitFor();await page.clock.install();let posts=0,gets=0;await page.route('**/api/settings',async route=>{if(route.request().method()==='GET'){gets++;return route.continue();}posts++;await route.abort('timedout');});await page.locator('#time-first').fill('10:14');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await page.locator('#operation-uncertain').waitFor();assert.equal(posts,1);await page.waitForFunction(()=>document.querySelector('#flash')?.textContent.includes('已查询最新状态'));assert.equal(gets,1);assert.equal(await page.locator('#time-first').inputValue(),'10:14');});
test('record history opens legacy notifications read-only after retired address redirects',{timeout:45000},async t=>{const {page}=await fixture(t,'notifications');await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor();assert.equal(await page.locator('#notification-settings').count(),0);await page.route('**/api/notifications',route=>route.fulfill({json:{items:[{sourceId:'OLD1',industry:'原分类',subject:'历史通知',brief:'原正文',status:'sent'}],batches:[{id:'old-batch',industry:'原分类',subject:'历史批次',status:'sent',to:['old@example.test']}]}}));await page.getByRole('link',{name:'工具',exact:true}).click();await page.getByRole('button',{name:'查看旧通知历史(只读)',exact:true}).click();await page.getByText('历史通知',{exact:true}).waitFor();assert.equal(await page.locator('#legacy-notification-history form').count(),0);});
test('a delayed execution response cannot replace the selected field directory',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');let release;const gate=new Promise(r=>release=r);await page.route('**/api/order-execution',async route=>{await gate;return route.fulfill({json:{tasks:[],capabilities:{},fields:{samples:[],adapters:[]}}});});await page.route('**/api/order-rules/fields*',route=>route.fulfill({json:{samples:[],adapters:[]}}));await openRuleRoute(page,'notification-execution');await openRuleRoute(page,'rule-fields');await page.locator('#fm-editor').waitFor();release();await page.waitForTimeout(300);assert.equal(await page.locator('#fm-editor').count(),1);assert.equal(await page.locator('#execution-scan').count(),0);});
test('operator scans but cannot configure fields or resend, viewer has no scan action',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'order-rules');const base=new URL(page.url()).origin;for(const role of ['operator','viewer'])runtime.store.addUser({username:role,password:'Test-password-123',role},'admin');for(const role of ['operator','viewer']){const context=await page.context().browser().newContext(),member=await context.newPage();member.setDefaultTimeout(5000);await member.route('**/api/order-execution',route=>route.fulfill({json:{tasks:[{id:'x',version:1,status:'failed'}],capabilities:{},fields:{samples:[],adapters:[]}}}));await member.route('**/api/order-rules/fields*',route=>route.fulfill({json:{samples:[],adapters:[]}}));await member.goto(base+'/#order-rules');await member.getByLabel('账号',{exact:true}).fill(role);await member.getByLabel('密码',{exact:true}).fill('Test-password-123');await member.getByRole('button',{name:'登录',exact:true}).click();await openRuleRoute(member,'notification-execution');await member.getByRole('heading',{name:'订单中心',exact:true}).first().waitFor();assert.equal(await member.getByRole('button',{name:'扫描并处理订单',exact:true}).count(),role==='operator'?1:0);assert.equal(await member.getByRole('button',{name:'重试失败任务',exact:true}).count(),0);await openRuleRoute(member,'rule-fields');await member.locator('#fm-editor').waitFor();assert.equal(await member.getByRole('button',{name:'保存草稿',exact:true}).count(),0);await context.close();}});
test('staying after browser Back preserves history so a second Back can discard to its original page',{timeout:45000},async t=>{const {page}=await fixture(t,'calendar');await page.locator('#day-form').waitFor();await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.locator('#time-first').fill('11:17');await page.goBack();await page.getByRole('button',{name:'留在此页',exact:true}).click();await page.goBack();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.locator('#day-form').waitFor();await page.goForward();await page.locator('#schedule-form').waitFor();});
test('template categories show effective published usage without a second binding writer',{timeout:45000},async t=>{
const {page}=await fixture(t,'schedule');let writes=0;await page.route('**/api/mail',route=>route.fulfill({json:{channels:[],templates:[],receipts:[],sends:[]}}));await page.route('**/api/mail/templates/categories',route=>{writes++;return route.fulfill({json:{}});});await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.getByRole('heading',{name:'有效使用情况(只读)'}).waitFor();assert.equal(await page.locator('[data-category] form').count(),0);assert.equal(await page.getByRole('button',{name:'保存关联'}).count(),0);assert.equal(writes,0);
});
async function openRuleRoute(page,hash){
await page.evaluate(hash=>{const link=document.createElement('a');link.href='#'+hash;document.body.append(link);link.click();link.remove();},hash);
}
@@ -10,7 +10,7 @@ async function workerContext(saved) {
chrome:{runtime:{onMessage:{addListener:()=>{}}},storage:{session:{get:async()=>storage,set:async value=>Object.assign(storage,value)}}},
fetch:async()=>({ok:true,json:async()=>({status:'success',filename:'saved.pdf',path:'output/saved.pdf',bytes:1000})})
});
vm.runInContext(await fs.readFile(require.resolve('../extension/worker.js'),'utf8'),context);
vm.runInContext(await fs.readFile(require.resolve('../../extension/worker.js'),'utf8'),context);
return context;
}
test('reopening popup after worker restart recovers a completed local job',async()=>{
@@ -1,6 +1,6 @@
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
async function fixture(t){
const {Store}=require('../src/dashboard-store.cjs'),{AssistantStore}=require('../src/assistant-store.cjs'),{AssistantService}=require('../src/assistant-service.cjs'),{createDashboard}=require('../src/dashboard.cjs');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'assistant-http-')),users=new Store(path.join(dir,'users'));users.bootstrap('admin','Test-password-123');users.addUser({username:'viewer',role:'viewer',password:'Test-password-123'},'admin');const store=new AssistantStore(path.join(dir,'assistant'));let checks=0;
const storage={store:{servers:()=>[{id:'server',name:'测试存储',enabled:true,state:{readable:true,writable:true,message:'正常'}}],archives:()=>[]},check:async()=>{checks++;return {state:{readable:true,writable:true}};}};
const runtime={probe:async()=>({available:true,version:'3.14.3',message:'运行包已就绪'}),chat:async({text,signal,config})=>{if(text.includes('挂起'))return new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(signal.reason),{once:true}));return JSON.stringify({reply:'已读取运行状态。<img src=x onerror=alert(1)>',actions:config.allowActions?[{kind:'check_storage',targetId:'server'}]:[]});}};
@@ -20,10 +20,32 @@ test('assistant HTTP enforces authentication, ownership, body validation and rol
});
test('chat UI persists conversations, shows escaped messages and explicit fixed action results, and cancels a running reply',{timeout:120000},async t=>{
const {base,store,checks}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/v1',model:'fixture',apiKey:'PRIVATE_UI_KEY',allowActions:true});
const {loadPlaywright,browserOptions}=require('../src/runtime.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1440,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));page.setDefaultTimeout(15000);
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1440,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));page.setDefaultTimeout(15000);
await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();
await page.getByLabel('发送给 ZCode',{exact:true}).fill('分析订单运行状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.locator('.assistant-reply').getByText('已读取运行状态。<img src=x onerror=alert(1)>',{exact:true}).waitFor();assert.equal(await page.locator('.assistant-reply img').count(),0);assert.equal(checks(),0);
await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).click();await page.getByText('操作已完成',{exact:true}).waitFor();assert.equal(checks(),1);await page.reload();await page.locator('.assistant-reply').getByText('已读取运行状态。<img src=x onerror=alert(1)>',{exact:true}).waitFor();
await page.getByLabel('发送给 ZCode',{exact:true}).fill('挂起诊断');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'停止回复',exact:true}).click();await page.getByText('已停止本轮回复。',{exact:true}).waitFor();
await fs.mkdir('output/verification',{recursive:true});await page.screenshot({path:'output/verification/zcode-chat-desktop.png',fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
});
test('a long action displays persisted sampling progress before its POST completes',{timeout:60000},async t=>{
const {base,store}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/v1',model:'fixture',apiKey:'PRIVATE_PROGRESS_KEY',allowActions:true});
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();page.setDefaultTimeout(8000);
await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();await page.getByLabel('发送给 ZCode',{exact:true}).fill('读取状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).waitFor();
let started=false,finished=false,release;const gate=new Promise(resolve=>release=resolve);t.after(()=>release());
await page.route('**/api/assistant/conversations/*',async route=>{const response=await route.fetch(),data=await response.json();if(started)for(const turn of data.turns)for(const action of turn.actions||[])Object.assign(action,{status:finished?'success':'running',progress:{completed:1,total:3,captured:1,failed:0}});await route.fulfill({json:data});});
await page.route('**/api/assistant/conversations/*/actions/*/execute',async route=>{started=true;await gate;finished=true;await route.fulfill({json:{status:'success'}});});
await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).click();
await page.getByText('采样进度 1 / 3,成功 1,受阻 0',{exact:true}).waitFor({timeout:4500});assert.equal(finished,false);
release();await page.getByText('操作已完成',{exact:true}).waitFor();
});
test('personal conversation UI archives, pages and restores evidence without sending a model request',{timeout:60000},async t=>{
const {base,store}=await fixture(t);const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:390,height:844}});page.setDefaultTimeout(10000);
await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();
await page.getByRole('button',{name:'归档会话',exact:true}).click();await page.getByRole('button',{name:'归档会话',exact:true}).waitFor({state:'hidden'});
await page.getByLabel('会话范围',{exact:true}).selectOption('archived');await page.locator('[data-assistant-conversation]').first().click();
await page.getByRole('button',{name:'恢复会话',exact:true}).click();await page.getByRole('button',{name:'恢复会话',exact:true}).waitFor({state:'hidden'});
await page.getByLabel('会话范围',{exact:true}).selectOption('active');await page.locator('[data-assistant-conversation]').first().waitFor();
assert.equal(store.listConversations(store.db.prepare('SELECT owner FROM conversations').get().owner,{scope:'archived'}).total,0);assert.equal(store.usage().calls,0);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
});
@@ -1,7 +1,7 @@
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
const admin={user:{id:'admin',username:'admin',role:'admin'},sessionId:'admin-session'},operator={user:{id:'operator',username:'operator',role:'operator'},sessionId:'operator-session'},viewer={user:{id:'viewer',username:'viewer',role:'viewer'},sessionId:'viewer-session'};
async function fixture(t,runtime){
const {AssistantStore}=require('../src/assistant-store.cjs'),{AssistantService}=require('../src/assistant-service.cjs');
const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-assistant-')),store=new AssistantStore(dir);let checks=0,scans=0,archives=0;
const connections=[{id:'own',owner:'operator',name:'Own BPM',status:'connected',identity:'PRIVATE_IDENTITY'},{id:'other',owner:'other',name:'Other BPM',status:'connected'}];
const workspace={snapshot:()=>({connections,exceptions:[{id:'e1',owner:'operator',title:'扫描失败',status:'open',description:'password=PRIVATE_PASSWORD Cookie=PRIVATE_COOKIE'}]}),getConnection:id=>connections.find(c=>c.id===id),record(){}};
@@ -13,8 +13,25 @@ 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/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;
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);
const restart=new AssistantStore(dir);try{assert.equal(restart.conversation(c.id,admin.user.id).turns[0].text,'PRIVATE_CHAT_MESSAGE');assert.equal(restart.secretSettings().apiKey,'PRIVATE_API_KEY');}finally{restart.close();}
for(const name of await fs.readdir(dir))if(name.includes('.sqlite')){const bytes=await fs.readFile(path.join(dir,name));assert.equal(bytes.includes(Buffer.from('PRIVATE_CHAT_MESSAGE')),false);assert.equal(bytes.includes(Buffer.from('PRIVATE_API_KEY')),false);}
@@ -54,7 +71,7 @@ test('a cancellation signal alone cannot label an unconfirmed runtime failure as
assert.equal(store.conversation(c.id,admin.user.id).turns[0].status,'error');
});
test('only a matching installed runtime is discovered, without enabling the model',async t=>{
const {AssistantStore}=require('../src/assistant-store.cjs'),crypto=require('node:crypto'),root=await fs.mkdtemp(path.join(os.tmpdir(),'order-zcode-discovery-')),dir=path.join(root,'assistant'),install=path.join(root,'zcode-runtime'),runtimePath=path.join(install,'3.14.3/package/resources/glm/zcode.cjs');t.after(()=>fs.rm(root,{recursive:true,force:true}));
const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),crypto=require('node:crypto'),root=await fs.mkdtemp(path.join(os.tmpdir(),'order-zcode-discovery-')),dir=path.join(root,'assistant'),install=path.join(root,'zcode-runtime'),runtimePath=path.join(install,'3.14.3/package/resources/glm/zcode.cjs');t.after(()=>fs.rm(root,{recursive:true,force:true}));
await fs.mkdir(path.dirname(runtimePath),{recursive:true});await fs.writeFile(runtimePath,'fixture');await fs.writeFile(path.join(install,'manifest.json'),JSON.stringify({releaseVersion:'3.14.3',cliVersion:'0.16.9',runtimePath,runtimeSha256:'sha256:'+crypto.createHash('sha256').update('fixture').digest('hex')}));
const store=new AssistantStore(dir);assert.equal(store.settings().runtimePath,runtimePath);assert.equal(store.settings().enabled,false);assert.equal(store.settings().hasApiKey,false);store.close();
await fs.writeFile(runtimePath,'modified');const changed=new AssistantStore(dir);try{assert.equal(changed.settings().runtimePath,'');}finally{changed.close();}
@@ -0,0 +1,22 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto');
const {AssistantStore}=require('../../src/modules/assistant/store.cjs');
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'conversation-lifecycle-')),store=new AssistantStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return store;}
test('archiving releases active conversation quota, preserves history and remains owner scoped',t=>{
const store=fixture(t),items=Array.from({length:50},()=>store.create('owner'));
assert.equal(typeof store.archive,'function');assert.throws(()=>store.create('owner'),{status:409});assert.throws(()=>store.archive(items[0].id,'other',{version:1}),{status:404});
const archived=store.archive(items[0].id,'owner',{version:1});assert.equal(archived.archived,true);store.create('owner');assert.equal(store.conversations('owner').length,50);assert.equal(store.listConversations('owner',{scope:'archived'}).total,1);
assert.throws(()=>store.restore(items[0].id,'owner',{version:archived.version}),{status:409});store.archive(items[1].id,'owner',{version:1});assert.equal(store.restore(items[0].id,'owner',{version:archived.version}).archived,false);
});
test('running turns cannot be archived and archived conversations cannot execute or accept messages',t=>{
const store=fixture(t),conversation=store.create('owner');assert.equal(typeof store.archive,'function');const turn=store.beginTurn(conversation.id,'owner','synthetic message');
assert.throws(()=>store.archive(conversation.id,'owner',{version:store.conversation(conversation.id,'owner').version}),{status:409});store.updateTurn(turn.id,'success',{reply:'synthetic answer'});
const saved=store.archive(conversation.id,'owner',{version:store.conversation(conversation.id,'owner').version});assert.throws(()=>store.beginTurn(conversation.id,'owner','new'),{status:409});assert.throws(()=>store.action(conversation.id,'owner','none',()=>{}),{status:409});assert.equal(store.conversation(conversation.id,'owner').turns[0].reply,'synthetic answer');assert.equal(saved.archived,true);
});
test('a full conversation continues once with a bounded private history and retains action evidence',t=>{
const store=fixture(t),parent=store.create('owner');assert.equal(typeof store.continueConversation,'function');
for(let i=0;i<100;i++){const id=crypto.randomUUID();store.db.prepare('INSERT INTO turns VALUES(?,?,?,?,?,?)').run(id,parent.id,'success',store.encode(id,{text:'line-'+i,reply:'answer-'+i,actions:i===0?[{id:'evidence',status:'success',result:{verified:true}}]:[],evidence:[]}), '2020-01-01','2020-01-01T00:00:00Z');}
const next=store.continueConversation(parent.id,'owner',{version:1});assert.equal(next.continuationOf,parent.id);assert.equal(next.turns.length,0);assert.equal(store.conversation(parent.id,'owner').archived,true);assert.equal(store.conversation(parent.id,'owner').turns[0].actions[0].result.verified,true);
assert.equal(store.continueConversation(parent.id,'owner',{version:1}).id,next.id);const history=store.history(next.id,'owner');assert.equal(history.length,3);assert.equal(history[0].text,'line-97');
store.beginTurn(next.id,'owner','follow up');assert.equal(store.conversation(next.id,'owner').continuationOf,parent.id);assert.throws(()=>store.history(next.id,'other'),{status:404});
});
+57
View File
@@ -0,0 +1,57 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
const principal={user:{id:'admin',username:'admin',role:'admin'},sessionId:'test-session'};
function fixture(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'field-skill-')),store=new RuleStore(dir,{clock:()=>new Date('2026-10-20T02:00:00Z')});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
const connection={id:'c1',owner:'admin',status:'connected'},workspace={getConnection:()=>connection,snapshot:()=>({connections:[connection]})};
const row={source:'todo',instanceId:'1',taskId:'1',revision:'1',processName:'备损订单评审',processVersion:'2.0',nodeName:'订单专员(订单通知书)',receivedAt:'2026-10-01T02:00:00Z',title:'订单号:123机芯号:ABC客户简称:PRIVATE_CUSTOMER总数量:0',serialNum:'TEST'};
let captures=0;const provider={scan:async()=>[row,{...row,taskId:'2',instanceId:'2'}],captureFields:async(c,p,r)=>{captures++;return {sample:{...r,connectionId:c.id,fields:{'Order.Number':'123','Order.Quantity':'0','Order.Amount':'999'}},snapshot:{purpose:'field-mapping',processVersion:r.processVersion,fields:[{path:'Order.Number',label:'订单号',value:'123'},{path:'Order.Quantity',label:'数量',value:'0'},{path:'Order.Amount',label:'总金额',value:'999'}]}};}};
const execution=new OrderExecutionCoordinator({store,workspace,provider,archive:{},mail:{},clock:()=>new Date('2026-10-20T02:00:00Z')});
return {deps:{workspace,orderRules:store,orderExecution:execution},store,connection,captures:()=>captures};
}
test('ZCode project skill collects one sample per missing version and only prepares checked drafts',async t=>{
const skill=require('../../src/modules/assistant/field-skill.cjs'),f=fixture(t),progress=[];
const report=await skill.collect(f.deps,'c1',principal,'action1',p=>progress.push(p));
assert.equal(report.captured,1);assert.equal(f.captures(),1);assert.equal(progress.at(-1).completed,1);
const sample=f.store.all('capture-samples')[0],guard=skill.guardMapping(f.deps,sample.id,principal.user);
const result=await skill.prepare(f.deps,sample.id,principal,'prepare1',guard);
assert.equal(result.status,'checked');assert.equal(f.store.all('field-mapping-drafts').length,1);
assert.equal(f.store.all('field-adapters').length,0);assert.deepEqual(f.store.all('orders'),[]);assert.deepEqual(f.store.all('batches'),[]);
const context=skill.coverage(f.deps,principal.user);assert.deepEqual(context.samples,[{id:sample.id,connectionId:'c1',processName:sample.processName,version:sample.processVersion}]);
// Opaque sample hashes may contain "999"; inspect the permitted metadata,
// whose exact sample shape above also excludes raw fields and evidence.
assert.doesNotMatch(JSON.stringify(context,(key,value)=>key==='id'?undefined:value),/PRIVATE_CUSTOMER|Order\.Number|999|订单号:123/);
assert.equal((await skill.collect(f.deps,'c1',principal,'action2',()=>{})).captured,0);assert.equal(f.captures(),1);
await assert.rejects(skill.prepare(f.deps,sample.id,principal,'stale',guard),e=>e.status===409);
f.connection.status='disabled';assert.throws(()=>skill.guardMapping(f.deps,sample.id,principal.user),e=>e.status===403);
});
test('mapping recommendations keep ambiguous fields unresolved and never mix amount and quantity',()=>{
const {recommend}=require('../../src/modules/assistant/field-skill.cjs');
const r=recommend([{path:'A.Order',label:'订单号',value:'123'},{path:'B.Order',label:'订单号',value:'123'},{path:'Amount',label:'总金额',value:'10'},{path:'Qty',label:'数量',value:'0'}]);
assert.equal(r.sources.orderNo,undefined);assert.equal(r.sources.quantity.path,'Qty');assert.equal(r.sources.totalAmount.path,'Amount');assert.ok(r.issues.length);
assert.equal(recommend([{path:'ProductRequirement.Antennanum',label:'数量',value:'2'}]).sources.quantity,undefined);
});
test('application skill is versioned, injected into prompt and cannot enable native tools',()=>{
const {projectSkills}=require('../../src/modules/assistant/skills.cjs'),{prompt,runtimeConfig}=require('../../src/modules/assistant/zcode-runtime.cjs');
const skills=projectSkills();assert.equal(skills[0].id,'bpm-field-mapping');assert.match(skills[0].sha256,/^[a-f0-9]{64}$/);
const input=prompt({text:'采集字段样本',history:[],context:{},config:{allowActions:true}});
assert.match(input,/BPM 信息识别技能/);assert.match(input,/collect_field_samples/);assert.match(input,/HA/);
const config=runtimeConfig({timeoutSeconds:30},'test');assert.equal(config.features.skill,false);assert.ok(config.permission.disallowedTools.includes('Skill'));
});
test('historical evidence can check a mapping while real notification matching still rejects history',async t=>{
const f=fixture(t),{recommend}=require('../../src/modules/assistant/field-skill.cjs'),row={source:'history',configurationOnly:true,instanceId:'1',taskId:'1',revision:0,connectionId:'c1',processName:'备损订单评审',processVersion:'2.0',nodeName:'历史查看(未提供办理节点)',receivedAt:'2026-10-01T00:00:00Z',timestampType:'process-start',serialNum:'TEST',title:'订单号:123机芯号:ABC',fields:{order:'123'}},snapshot={purpose:'field-mapping',processVersion:'2.0',fields:[{path:'order',label:'订单号',value:'123'}]};
const sample=f.store.recordCapture({sample:row,snapshot,taskId:'h1'}),draft=f.store.saveMapping({processName:row.processName,processVersion:row.processVersion,sampleId:sample.id,sources:recommend(snapshot.fields).sources,version:0,idempotencyKey:'draft'},principal.user);
const result=f.store.checkMapping({id:draft.id,version:draft.version,sampleId:sample.id,idempotencyKey:'check'},principal.user);
assert.equal(result.valid,true);assert.equal(result.result.configurationOnly,true);assert.ok(result.result.warnings.length);
assert.equal(f.store.capturedPreview(sample.id).valid,false);
});
test('assistant prepares the same active-only selection as page preview and never activates or publishes it',async t=>{
const f=fixture(t),skill=require('../../src/modules/assistant/field-skill.cjs');await skill.collect(f.deps,'c1',principal,'collect-consistent',()=>{});const sample=f.store.all('capture-samples')[0];
f.store.put('field-adapters',{id:'legacy-selected',processName:sample.processName,processVersion:sample.processVersion,verified:true,version:2,sources:{orderNo:{type:'form',path:'Order.Number'},brief:{type:'title'}}});
const proposal=f.store.proposeMapping({sampleId:sample.id}),before=f.store.all('rules');assert.equal(proposal.mapping.basis,'active');assert.equal(proposal.mapping.sources.quantity,undefined);
const result=await skill.prepare(f.deps,sample.id,principal,'prepare-consistent',skill.guardMapping(f.deps,sample.id,principal.user));assert.equal(result.status,'checked');const draft=f.store.all('field-mapping-drafts')[0];assert.equal(draft.sources.quantity,undefined);assert.deepEqual(f.store.all('rules'),before);assert.equal(f.store.all('field-adapters').length,1);assert.equal(f.store.settings().enabled,false);
});
+12
View File
@@ -0,0 +1,12 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {BpmHistoryClient,normalizeHistory,HISTORY_ROUTES}=require('../../src/modules/bpm/history-client.cjs');
const raw=(version='1.4',id='21')=>({processName:'备损订单更改评审',processInstanceId:id,processVersion:version,startTime:'2026-10-20T10:00:00',serialNum:'TEST',subject:'订单号:123',businessKey:'https://bpm.skyworthdigital.com/sso/ssologin.aspx?ReturnUrl='+encodeURIComponent('https://bpm.skyworthdigital.com/YZSoft/Forms/Read.aspx?tid='+id)+'&todo_token=FIXTURE&todo_account=test'});
test('history client queries only observed readonly sources and keeps latest version alternatives',async()=>{
const calls=[];let disposed=false;
const client=new BpmHistoryClient({requestFactory:async()=>({get:async(route,options)=>{calls.push({route,options});return {status:()=>200,body:async()=>Buffer.from(route==='/'?"Yiez.clientId='fixture';":JSON.stringify({total:4,children:[raw(),raw('1.3','22'),raw('1.4','23'),{...raw('1.5','24'),processName:'其他流程'}]}))};},dispose:async()=>{disposed=true;}})});
const rows=await client.scan({},['备损订单更改评审']);assert.equal(rows.length,2);assert.equal(rows[0].source,'history');assert.equal(rows[0].configurationOnly,true);assert.equal(rows[0].timestampType,'process-start');assert.match(rows[0].nodeName,/未提供/);assert.equal(rows[0].receivedAt,'2026-10-20T02:00:00.000Z');
assert.deepEqual(calls.map(c=>c.route),['/',HISTORY_ROUTES[0]]);assert.equal(calls[1].options.params.year,-1);assert.equal(calls[1].options.params.limit,100);assert.equal(disposed,true);
assert.throws(()=>normalizeHistory({...raw(),processInstanceId:'22'}),e=>e.status===403);
assert.throws(()=>normalizeHistory({...raw(),processVersion:''}),e=>e.status===502);
});
+22
View File
@@ -0,0 +1,22 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),path=require('node:path');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function fixture(t){
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.route('https://synthetic.invalid/**',route=>route.fulfill({body:'<div id="fixture"></div>',contentType:'text/html'}));await page.goto('https://synthetic.invalid/');await page.addScriptTag({path:path.resolve('web/modules/assistant/view.js')});
await page.evaluate(async()=>{
window.requests=[];window.failNext=false;window.hold=false;window.release=null;
const items=Array.from({length:26},(_,i)=>({id:'active-'+i,title:'Active '+i,updatedAt:'2026-10-21',version:1}));
const api=async route=>{
if(route==='/assistant')return {settings:{enabled:false},usage:{calls:0,limit:100},conversations:items};
if(route.includes('?')){const url=new URL(route,location.origin),scope=url.searchParams.get('scope'),page=Number(url.searchParams.get('page'));window.requests.push(scope+':'+page);if(window.hold&&scope==='active'&&page===2)await new Promise((resolve,reject)=>{window.release=()=>reject(Error('Stale failure'));});if(window.failNext){window.failNext=false;throw Error('Synthetic page failure');}const list=scope==='active'?items:[{id:'archived',title:'Archived only',updatedAt:'2026-10-21'}];return {items:list.slice((page-1)*25,page*25),page,total:list.length};}
return {id:route.split('/').at(-1),title:'Synthetic',version:1,turns:[],archived:route.endsWith('archived')};
};
window.AssistantViews.configure({api,esc:String,formatDate:String,notify:()=>{},user:{username:'synthetic',role:'admin'}});await window.AssistantViews.render(document.querySelector('#fixture'));
});return page;
}
test('failed assistant page restores navigation and retries the same page',{timeout:30000},async t=>{
const page=await fixture(t);await page.evaluate(()=>{window.failNext=true;});await page.locator('#assistant-next').click();await page.getByText('Synthetic page failure',{exact:true}).waitFor();assert.equal(await page.locator('#assistant-next').isDisabled(),false);assert.equal(await page.locator('#assistant-prev').isDisabled(),true);await page.locator('#assistant-next').click();await page.locator('#assistant-page').filter({hasText:'2 / 2'}).waitFor();assert.deepEqual(await page.evaluate(()=>requests),['active:1','active:2','active:2']);assert.equal(await page.locator('[data-assistant-conversation]').count(),1);
});
test('stale failed page cannot roll back the new scope or disable its navigation',{timeout:30000},async t=>{
const page=await fixture(t);await page.evaluate(()=>{window.hold=true;});await page.locator('#assistant-next').click();await page.waitForFunction(()=>!!window.release);await page.locator('#assistant-scope').selectOption('archived');await page.getByText('Archived only',{exact:true}).waitFor();await page.evaluate(()=>window.release());await page.evaluate(()=>new Promise(r=>setTimeout(r,0)));assert.equal(await page.locator('#assistant-error').textContent(),'');assert.equal(await page.locator('#assistant-page').textContent(),'1 / 1');assert.equal(await page.locator('#assistant-next').isDisabled(),true);assert.equal(await page.locator('#assistant-prev').isDisabled(),true);
});
@@ -1,6 +1,6 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),http=require('node:http'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
const {ZcodeRuntime}=require('../src/zcode-runtime.cjs');
const {ZcodeRuntime}=require('../../src/modules/assistant/zcode-runtime.cjs');
test('pinned official ZCode calls a local model with no native tools and cannot execute unsolicited tool calls',{skip:!process.env.ORDER_TEST_ZCODE_CLI,timeout:180000},async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-official-zcode-')),runtime=new ZcodeRuntime({stateDir:dir}),requests=[];let attack=false,attackSent=0,attackRequests=0;
t.after(()=>fs.rm(dir,{recursive:true,force:true}));
@@ -1,15 +1,15 @@
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
test('ZCode bridge uses fixed permissions, isolated profile and filtered environment; secrets are not command arguments',async t=>{
const {ZcodeRuntime}=require('../src/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-driver-')),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));process.env.PRIVATE_TEST_KEY='must-not-reach-zcode';t.after(()=>delete process.env.PRIVATE_TEST_KEY);
const {ZcodeRuntime}=require('../../src/modules/assistant/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-driver-')),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));process.env.PRIVATE_TEST_KEY='must-not-reach-zcode';t.after(()=>delete process.env.PRIVATE_TEST_KEY);
const config={runtimePath:path.resolve('tests/fixtures/zcode-fixture.cjs'),model:'fixture',apiBase:'https://models.example/v1',apiKey:'NEVER-IN-ARGV',timeoutSeconds:15,allowActions:false};
assert.equal((await runtime.probe(config.runtimePath)).available,true);
const result=JSON.parse(await runtime.chat({config,text:'hello $() `shell`',history:[],context:{servers:[]},signal:new AbortController().signal}));assert.equal(result.observed.privateEnv,undefined);assert.equal(result.observed.args[result.observed.args.indexOf('--mode')+1],'plan');assert.ok(result.observed.args.includes('--disallowed-tools'));assert.doesNotMatch(JSON.stringify(result.observed.args),/NEVER-IN-ARGV/);assert.equal(result.observed.config.plugins.enabled,false);assert.equal(result.observed.config.features.mcp,false);assert.equal(result.observed.config.features.subagent,false);assert.match(result.observed.cwd,/zcode-driver/);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
});
test('ZCode cancellation and excessive output terminate the invocation and clean private profiles',async t=>{
const {ZcodeRuntime}=require('../src/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-abort-')),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));const config={runtimePath:path.resolve('tests/fixtures/zcode-fixture.cjs'),model:'fixture',apiBase:'https://models.example/v1',apiKey:'secret',timeoutSeconds:15};
const {ZcodeRuntime}=require('../../src/modules/assistant/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-abort-')),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));const config={runtimePath:path.resolve('tests/fixtures/zcode-fixture.cjs'),model:'fixture',apiBase:'https://models.example/v1',apiKey:'secret',timeoutSeconds:15};
const controller=new AbortController(),pending=runtime.chat({config,text:'FIXTURE_HANG',history:[],context:{},signal:controller.signal});setTimeout(()=>controller.abort(Object.assign(new Error('cancelled'),{status:499})),350);await assert.rejects(pending,e=>e.status===499);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
await assert.rejects(runtime.chat({config,text:'FIXTURE_OVERFLOW',history:[],context:{},signal:new AbortController().signal}),e=>e.status===502);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
});
test('cancelling during runtime discovery interrupts the probe and cleans its profile',async t=>{
const {ZcodeRuntime}=require('../src/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-probe-abort-')),entry=path.join(dir,'slow-probe.cjs'),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));await fs.writeFile(entry,"setInterval(()=>{},1000);");const controller=new AbortController();const pending=runtime.chat({config:{runtimePath:entry,timeoutSeconds:15},text:'hello',history:[],context:{},signal:controller.signal});setTimeout(()=>controller.abort(Object.assign(new Error('cancelled'),{status:499})),500);await assert.rejects(pending,e=>e.status===499);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
const {ZcodeRuntime}=require('../../src/modules/assistant/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-probe-abort-')),entry=path.join(dir,'slow-probe.cjs'),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));await fs.writeFile(entry,"setInterval(()=>{},1000);");const controller=new AbortController();const pending=runtime.chat({config:{runtimePath:entry,timeoutSeconds:15},text:'hello',history:[],context:{},signal:controller.signal});setTimeout(()=>controller.abort(Object.assign(new Error('cancelled'),{status:499})),500);await assert.rejects(pending,e=>e.status===499);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
});
+48
View File
@@ -0,0 +1,48 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),crypto=require('node:crypto');
const {spawnSync}=require('node:child_process'),{DatabaseSync}=require('node:sqlite');
const {acquireInstanceLock}=require('../../src/platform/service/instance-lock.cjs');
const {BpmVault}=require('../../src/platform/security/vault.cjs');
const cli=path.resolve(__dirname,'../../scripts/backup.cjs');
function fixture(t){const root=fs.mkdtempSync(path.join(os.tmpdir(),'order-backup-test-'));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));const state=path.join(root,'state'),output=path.join(root,'pdf'),backup=path.join(root,'backup'),restored=path.join(root,'restored'),local=path.join(root,'local');for(const p of [state,output,local])fs.mkdirSync(p);fs.writeFileSync(path.join(state,'ordinary.json'),'{"retained":true}');fs.writeFileSync(path.join(output,'order.pdf'),'%PDF-1.4 synthetic');return {root,state,output,backup,restored,local};}
function run(f,...args){return spawnSync(process.execPath,[cli,...args],{encoding:'utf8',env:{...process.env,LOCALAPPDATA:f.local,NODE_NO_WARNINGS:'1'},windowsHide:true,timeout:60000});}
function create(f){const r=run(f,'create','--state',f.state,'--output',f.output,'--destination',f.backup);assert.equal(r.status,0,r.stderr);return JSON.parse(fs.readFileSync(path.join(f.backup,'manifest.json'),'utf8'));}
function hashes(root){const out={};function visit(dir){for(const name of fs.readdirSync(dir)){const p=path.join(dir,name),s=fs.lstatSync(p);if(s.isDirectory())visit(p);else out[path.relative(root,p)]=crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');}}visit(root);return out;}
function changeManifest(f,change){const p=path.join(f.backup,'manifest.json'),m=JSON.parse(fs.readFileSync(p));change(m);const bytes=Buffer.from(JSON.stringify(m,null,2)+'\n');fs.writeFileSync(p,bytes);fs.writeFileSync(path.join(f.backup,'manifest.sha256'),crypto.createHash('sha256').update(bytes).digest('hex')+'\n');}
test('create, verify and restore preserve complete offline state and relocate PDF history',t=>{
const f=fixture(t);fs.mkdirSync(path.join(f.state,'dashboard'));fs.mkdirSync(path.join(f.state,'empty-vault'));fs.mkdirSync(path.join(f.state,'supervisor'));
fs.writeFileSync(path.join(f.state,'supervisor','control.key'),'stale-control-token');
const db=new DatabaseSync(path.join(f.state,'dashboard','state.sqlite'));db.exec('CREATE TABLE pdf_jobs(job_id TEXT PRIMARY KEY,value TEXT NOT NULL)');db.prepare('INSERT INTO pdf_jobs VALUES(?,?)').run('j',JSON.stringify({jobId:'j',status:'success',path:path.join(f.output,'order.pdf')}));db.close();const before=hashes(f.state);
const manifest=create(f);assert.equal(manifest.appVersion,require('../../package.json').version);assert.equal(manifest.source.stateDir,f.state);assert.ok(manifest.files.every(v=>Number.isSafeInteger(v.size)&&/^[a-f0-9]{64}$/.test(v.sha256)));
assert.equal(run(f,'verify','--source',f.backup).status,0);
const restored=run(f,'restore','--source',f.backup,'--destination',f.restored);assert.equal(restored.status,0,restored.stderr);
assert.ok(fs.statSync(path.join(f.restored,'empty-vault')).isDirectory());assert.ok(!fs.existsSync(path.join(f.restored,'supervisor','control.key')));
assert.equal(fs.readFileSync(path.join(f.restored,'restored-pdf','order.pdf'),'utf8'),'%PDF-1.4 synthetic');assert.equal(JSON.parse(fs.readFileSync(path.join(f.restored,'restore-config.json'))).outputDir,'restored-pdf');
const target=new DatabaseSync(path.join(f.restored,'dashboard','state.sqlite'),{readOnly:true});assert.equal(JSON.parse(target.prepare('SELECT value FROM pdf_jobs').get().value).path,path.join(f.restored,'restored-pdf','order.pdf'));target.close();assert.deepEqual(hashes(f.state),before);
});
for(const attack of ['tamper','missing','unexpected','traversal','absolute','case-collision','link'])test('verify and restore reject '+attack+' without publishing state',t=>{
const f=fixture(t);create(f);const file=path.join(f.backup,'state','ordinary.json');
if(attack==='tamper')fs.appendFileSync(file,'bad');if(attack==='missing')fs.unlinkSync(file);if(attack==='unexpected')fs.writeFileSync(path.join(f.backup,'extra'),'bad');
if(attack==='traversal')changeManifest(f,m=>m.files[0].path='../outside');if(attack==='absolute')changeManifest(f,m=>m.files[0].path='C:/outside');if(attack==='case-collision')changeManifest(f,m=>m.files.push({...m.files[0],path:m.files[0].path.toUpperCase()}));
if(attack==='link'){fs.mkdirSync(path.join(f.root,'outside'));fs.symlinkSync(path.join(f.root,'outside'),path.join(f.backup,'linked'),'junction');}
assert.notEqual(run(f,'verify','--source',f.backup).status,0);assert.notEqual(run(f,'restore','--source',f.backup,'--destination',f.restored).status,0);assert.ok(!fs.existsSync(f.restored));
});
test('source links and overlapping backup destinations are refused',t=>{const f=fixture(t);fs.symlinkSync(f.output,path.join(f.state,'linked'),'junction');const r=run(f,'create','--state',f.state,'--output',f.output,'--destination',f.backup);assert.notEqual(r.status,0);assert.ok(!fs.existsSync(path.join(f.backup,'manifest.json')));fs.unlinkSync(path.join(f.state,'linked'));assert.notEqual(run(f,'create','--state',f.state,'--output',f.output,'--destination',path.join(f.state,'backup')).status,0);});
test('existing backup and occupied restore destinations remain untouched',t=>{const f=fixture(t);create(f);const before=hashes(f.backup);assert.notEqual(run(f,'create','--state',f.state,'--output',f.output,'--destination',f.backup).status,0);assert.deepEqual(hashes(f.backup),before);fs.mkdirSync(f.restored);fs.writeFileSync(path.join(f.restored,'keep'),'untouched');assert.notEqual(run(f,'restore','--source',f.backup,'--destination',f.restored).status,0);assert.equal(fs.readFileSync(path.join(f.restored,'keep'),'utf8'),'untouched');});
test('active source writer blocks backup',async t=>{const f=fixture(t),lock=await acquireInstanceLock(f.state);try{const r=run(f,'create','--state',f.state,'--output',f.output,'--destination',f.backup);assert.notEqual(r.status,0);assert.match(r.stderr,/ORDER_INSTANCE_OWNED/);assert.ok(!fs.existsSync(f.backup));}finally{await lock.release();}});
test('a restored state can be backed up and restored again with its contained PDF output',t=>{const f=fixture(t);create(f);let r=run(f,'restore','--source',f.backup,'--destination',f.restored);assert.equal(r.status,0,r.stderr);const second=path.join(f.root,'backup2'),third=path.join(f.root,'restored2');r=run(f,'create','--state',f.restored,'--output',path.join(f.restored,'restored-pdf'),'--destination',second);assert.equal(r.status,0,r.stderr);r=run(f,'restore','--source',second,'--destination',third);assert.equal(r.status,0,r.stderr);assert.equal(fs.readFileSync(path.join(third,'restored-pdf/order.pdf'),'utf8'),'%PDF-1.4 synthetic');});
test('live supervisor alone blocks offline backup',async t=>{const f=fixture(t),net=require('node:net'),{controlAddress}=require('../../src/platform/service/control.cjs');if(process.platform!=='win32')return;const server=net.createServer();await new Promise(r=>server.listen(controlAddress(f.state),r));try{const r=run(f,'create','--state',f.state,'--output',f.output,'--destination',f.backup);assert.notEqual(r.status,0);assert.match(r.stderr,/ORDER_INSTANCE_OWNED/);assert.ok(!fs.existsSync(f.backup));}finally{await new Promise(r=>server.close(r));}});
test('empty notification and scan vault directories retain external keys and readable encrypted history',{skip:process.platform!=='win32'},t=>{const f=fixture(t),old=process.env.LOCALAPPDATA;process.env.LOCALAPPDATA=f.local;t.after(()=>{if(old===undefined)delete process.env.LOCALAPPDATA;else process.env.LOCALAPPDATA=old;});for(const [folder,vaultDir,file,table,idColumn,aad]of [['notifications','secrets','notifications.sqlite','items','id','historic'],['bpm-scan','delivery-secrets','scan.sqlite','execution_deliveries','run_id','execution-delivery:historic']]){const v=new BpmVault({stateDir:path.join(f.state,folder,vaultDir)}),db=new DatabaseSync(path.join(f.state,folder,file));db.exec('CREATE TABLE '+table+'('+idColumn+' TEXT,payload BLOB)');db.prepare('INSERT INTO '+table+' VALUES(?,?)').run('historic',v.encode(aad,{localPath:path.join(f.output,'order.pdf'),evidence:'synthetic-history'}));db.close();v.destroy();assert.deepEqual(fs.readdirSync(path.join(f.state,folder,vaultDir)),[]);}create(f);const r=run(f,'restore','--source',f.backup,'--destination',f.restored);assert.equal(r.status,0,r.stderr);for(const [folder,vaultDir,file,table,aad]of [['notifications','secrets','notifications.sqlite','items','historic'],['bpm-scan','delivery-secrets','scan.sqlite','execution_deliveries','execution-delivery:historic']]){const v=new BpmVault({stateDir:path.join(f.restored,folder,vaultDir)}),db=new DatabaseSync(path.join(f.restored,folder,file));assert.deepEqual(v.decode(aad,db.prepare('SELECT payload FROM '+table).get().payload),{localPath:path.join(f.restored,'restored-pdf/order.pdf'),evidence:'synthetic-history'});db.close();v.destroy();}});
test('invalid DPAPI key and existing differing target key never publish restored state',{skip:process.platform!=='win32'},async t=>{const f=fixture(t),old=process.env.LOCALAPPDATA;process.env.LOCALAPPDATA=f.local;t.after(()=>{if(old===undefined)delete process.env.LOCALAPPDATA;else process.env.LOCALAPPDATA=old;});const v=new BpmVault({stateDir:path.join(f.state,'bpm-sessions')});await v.write('fixture',{password:'synthetic-only'});v.destroy();const m=create(f),keyRoot=path.join(f.local,'OrderNotificationAutomation/bpm-keys'),target=path.join(keyRoot,crypto.createHash('sha256').update(path.join(f.restored,'bpm-sessions').toLowerCase()).digest('hex')+'.key');fs.writeFileSync(target,'do not overwrite');let r=run(f,'restore','--source',f.backup,'--destination',f.restored);assert.notEqual(r.status,0);assert.match(r.stderr,/BACKUP_KEY_COLLISION/);assert.equal(fs.readFileSync(target,'utf8'),'do not overwrite');assert.ok(!fs.existsSync(f.restored));fs.unlinkSync(target);const key=m.vaults[0].keyFile;fs.writeFileSync(path.join(f.backup,key),'invalid DPAPI blob');changeManifest(f,m=>{const item=m.files.find(f=>f.path===key);item.size=18;item.sha256=crypto.createHash('sha256').update('invalid DPAPI blob').digest('hex');});r=run(f,'restore','--source',f.backup,'--destination',f.restored);assert.notEqual(r.status,0);assert.match(r.stderr,/BACKUP_KEY_IDENTITY/);assert.ok(!fs.existsSync(f.restored));fs.unlinkSync(path.join(keyRoot,path.basename(key)));const b2=path.join(f.root,'no-key');r=run(f,'create','--state',f.state,'--output',f.output,'--destination',b2);assert.notEqual(r.status,0);assert.match(r.stderr,/BACKUP_KEY_MISSING/);assert.ok(!fs.existsSync(b2));});
test('relocated DPAPI vaults decrypt synthetic records while source and key bytes remain identical',{skip:process.platform!=='win32'},async t=>{
const f=fixture(t),old=process.env.LOCALAPPDATA;process.env.LOCALAPPDATA=f.local;t.after(()=>{if(old===undefined)delete process.env.LOCALAPPDATA;else process.env.LOCALAPPDATA=old;});
for(const rel of ['bpm-sessions','mail/secrets','storage/secrets','order-rules/secrets','assistant','bpm-scan/delivery-secrets']){const v=new BpmVault({stateDir:path.join(f.state,rel)});await v.write('fixture',{secret:'synthetic-only-'+rel});v.destroy();}
const ruleVault=new BpmVault({stateDir:path.join(f.state,'order-rules/secrets')}),ruleDb=new DatabaseSync(path.join(f.state,'order-rules/rules.sqlite'));ruleDb.exec('CREATE TABLE records(kind TEXT,id TEXT,payload BLOB,PRIMARY KEY(kind,id))');ruleDb.prepare('INSERT INTO records VALUES(?,?,?)').run('archive-intents','intent',ruleVault.encode('archive-intents:intent',{id:'intent',localPath:path.join(f.output,'order.pdf')}));ruleDb.close();ruleVault.destroy();
const original=hashes(f.state),keyRoot=path.join(f.local,'OrderNotificationAutomation','bpm-keys'),keys=hashes(keyRoot);create(f);const backupHashes=hashes(f.backup);const r=run(f,'restore','--source',f.backup,'--destination',f.restored);assert.equal(r.status,0,r.stderr);
for(const rel of ['bpm-sessions','mail/secrets','storage/secrets','order-rules/secrets','assistant','bpm-scan/delivery-secrets']){const v=new BpmVault({stateDir:path.join(f.restored,rel)});assert.deepEqual(await v.read('fixture'),{secret:'synthetic-only-'+rel});v.destroy();}
const rv=new BpmVault({stateDir:path.join(f.restored,'order-rules/secrets')}),rd=new DatabaseSync(path.join(f.restored,'order-rules/rules.sqlite'));assert.equal(rv.decode('archive-intents:intent',rd.prepare('SELECT payload FROM records').get().payload).localPath,path.join(f.restored,'restored-pdf/order.pdf'));rd.close();rv.destroy();
assert.deepEqual(hashes(f.state),original);for(const [name,hash]of Object.entries(keys))assert.equal(hashes(keyRoot)[name],hash);assert.deepEqual(hashes(f.backup),backupHashes);
assert.ok(!fs.readFileSync(path.join(f.backup,'manifest.json'),'utf8').includes('synthetic-only'));
});
+1 -1
View File
@@ -33,7 +33,7 @@ test('DataProvider generates only GetFormProcessData PID XML with redirects disa
const calls=[];const tables=await loadData({post:async(url,options)=>{calls.push({url,options});return reply(200,{success:true,Tables:formTables});}},new URL(finalURL));
assert.equal(tables.length,2);assert.equal(calls[0].url,origin+'/YZSoft/BPM/XMLService/DataProvider.ashx');assert.equal(calls[0].options.data,'<?xml version="1.0"?><Requests><Params><Method>GetFormProcessData</Method><PID>2001</PID></Params></Requests>');assert.equal(calls[0].options.maxRedirects,0);
await assert.rejects(()=>loadData({post:async()=>{throw Error('must not call');}},new URL(finalURL.replace('pid=2001','pid=bad'))));
await assert.rejects(()=>loadData({post:async()=>reply(302,'','https://evil.example/')},new URL(finalURL)),error=>error.status===401);
await assert.rejects(()=>loadData({post:async()=>reply(302,'','https://evil.example/')},new URL(finalURL)),error=>error.status===502);
await assert.rejects(()=>loadData({post:async()=>reply(200,{success:true,Tables:[{TableName:'X',FormTable:true,Rows:[null]}]})},new URL(finalURL)));
await assert.rejects(()=>loadData({post:async()=>{throw Error('must not call');}},new URL(finalURL+'&method=Approve')));
await assert.rejects(()=>loadData({post:async()=>reply(200,{success:true,Tables:[]})},new URL(processURL)));
-37
View File
@@ -1,37 +0,0 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const os=require('node:os');
const path=require('node:path');
const net=require('node:net');
async function freePort(){const server=net.createServer();await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const port=server.address().port;await new Promise(resolve=>server.close(resolve));return port;}
test('formal runtime wires BPM sessions and preserves users across restart',async t=>{
const {main}=require('../src/server.cjs');
assert.equal(typeof main,'function','formal runtime must support isolated startup and shutdown');
const stateDir=fs.mkdtempSync(path.join(os.tmpdir(),'order-runtime-'));
let app;
t.after(async()=>{if(app)await app.stop();fs.rmSync(stateDir,{recursive:true,force:true});});
const config={port:await freePort(),dashboard:{host:'127.0.0.1',port:await freePort()}};
app=await main({stateDir,config,quiet:true});
assert.ok(app.pipeline,'runtime must wire the guarded order pipeline');
assert.equal(app.pipeline.config().enabled,false);
assert.equal(app.pipeline.config().sendEnabled,false);
const base=`http://127.0.0.1:${config.dashboard.port}`;
const post=(route,body,cookie)=>fetch(base+route,{method:'POST',headers:{Origin:base,'Content-Type':'application/json',...(cookie?{Cookie:cookie}:{})},body:JSON.stringify(body)});
const bootstrap=await post('/api/bootstrap',{username:'runtime-admin',password:'Runtime-test-password-123'});
assert.equal(bootstrap.status,201);
let cookie=bootstrap.headers.get('set-cookie').split(';')[0];
const snapshot=await (await fetch(base+'/api/workspace',{headers:{Cookie:cookie}})).json();
assert.equal(snapshot.capabilities.remoteLogin,true);
assert.equal(snapshot.members[0].username,'runtime-admin');
await app.stop();app=null;
app=await main({stateDir,config,quiet:true});
assert.equal((await (await fetch(base+'/api/bootstrap/status')).json()).required,false);
assert.equal((await fetch(base+'/api/me',{headers:{Cookie:cookie}})).status,200);
const login=await post('/api/login',{username:'runtime-admin',password:'Runtime-test-password-123'});
assert.equal(login.status,200);cookie=login.headers.get('set-cookie').split(';')[0];
assert.equal((await fetch(base+'/api/workspace',{headers:{Cookie:cookie}})).status,200);
assert.equal(fs.existsSync(path.join(stateDir,'bpm-sessions')),true);
});
-34
View File
@@ -1,34 +0,0 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {Store}=require('../src/dashboard-store.cjs');const {WorkspaceStore}=require('../src/workspace-store.cjs');const {BpmScanStore}=require('../src/bpm-scan-store.cjs');const {BpmScanner}=require('../src/bpm-scanner.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {normalizeArrival}=require('../src/bpm-list-client.cjs');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
async function setup(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'scan-http-')),store=new Store(path.join(dir,'users')),workspace=new WorkspaceStore(path.join(dir,'workspace')),scanStore=new BpmScanStore(path.join(dir,'scan'));
store.bootstrap('admin','Test-password-123');store.addUser({username:'reader',password:'Test-password-123',role:'viewer'},'admin');store.addUser({username:'other',password:'Test-password-123',role:'operator'},'admin');
const connection={id:'fixture',name:'测试连接',owner:'admin',status:'connected',lastConnectedAt:new Date().toISOString()};workspace.db.prepare('INSERT INTO connections VALUES(?,?)').run(connection.id,JSON.stringify(connection));
const rows=['2026-10-15T16:33:58','2026-10-14T10:00:00'].map((date,i)=>normalizeArrival({taskId:String(i),serialNum:'TEST-'+i,processName:'测试流程',startTime:date,processInstanceSubject:i?'昨天的流程':'<script>bad()</script>订单号:123'},'portal-v8'));
const scanner=new BpmScanner({store:scanStore,workspace,manager:{scanArrivals:async()=>rows},settings:()=>store.settings()});
const server=createDashboard({store,workspace,scanner,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));
t.after(async()=>{await scanner.stop();await new Promise(r=>server.close(r));scanStore.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
const base='http://127.0.0.1:'+server.address().port,call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});
const login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {base,call,login,scanner,scanStore};
}
test('scan API enforces owner, role and origin; scan results and overview reflect database',async t=>{
const {call,login,scanner}=await setup(t);assert.equal((await call('/api/arrivals')).status,401);const admin=await login('admin'),reader=await login('reader'),other=await login('other');
for(const cookie of [reader,other])assert.equal((await call('/api/bpm-scan/run',{connectionId:'fixture'},cookie)).status,403);
assert.equal((await call('/api/bpm-scan/config',{enabled:false,intervalMinutes:5},reader)).status,403);
assert.equal((await call('/api/bpm-scan/run',{connectionId:'fixture'},admin,'http://evil.test')).status,403);
assert.equal((await call('/api/bpm-scan/run',{connectionId:'fixture'},admin)).status,202);await Promise.all([...scanner.pending.values()]);
const page=await (await call('/api/arrivals',undefined,reader)).json();assert.equal(page.groups.length,2);assert.equal(page.groups[0].day,'2026-10-15');assert.equal(page.groups[0].items[0].subject,'订单号:123');
const overview=await (await call('/api/overview',undefined,reader)).json();assert.equal(overview.scan.total,2);assert.equal(overview.connections.find(c=>c.name==='BPM 自动扫描').ready,true);
});
test('browser displays separate arrival days, searches, scans and preserves PDF entry',async t=>{
const {base,scanner,scanStore}=await setup(t);await scanner.scan('fixture',{user:{username:'admin',role:'admin'},sessionId:'fixture'});
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.goto(base+'/#records');await page.locator('#username').fill('admin');await page.locator('#password').fill('Test-password-123');await page.locator('#login-form button').click();
await page.locator('[data-arrival-day="2026-10-15"]').waitFor();assert.equal(await page.locator('[data-arrival-day]').count(),2);
const background=normalizeArrival({taskId:'background',serialNum:'BG-1',processName:'新增流程',startTime:'2026-10-16T12:00:00',processInstanceSubject:'后台扫描新增'},'portal-v8');scanStore.complete(scanStore.begin('fixture','系统扫描'),'fixture',[background]);
await page.getByText('后台扫描新增',{exact:true}).waitFor({timeout:20000});
await page.getByLabel('搜索流程记录',{exact:true}).fill('昨天');await page.getByRole('button',{name:'查询',exact:true}).click();await page.getByText('昨天的流程',{exact:true}).waitFor();assert.equal(await page.locator('[data-arrival-day]').count(),1);
await page.getByRole('button',{name:'立即扫描',exact:true}).click();await page.getByText(/扫描完成/).waitFor();
await page.getByRole('button',{name:'PDF 导出记录',exact:true}).click();await page.locator('#record-search').waitFor();assert.equal(await page.locator('#record-search').isVisible(),true);
await page.route('**/api/bpm-scan',route=>route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:'扫描暂不可用'})}));
await page.getByRole('link',{name:'工作总览',exact:true}).click();await page.getByRole('link',{name:'订单与导出记录',exact:true}).click();await page.locator('#pdf-fallback').waitFor();await page.locator('#pdf-fallback').click();await page.locator('#record-search').waitFor();
});
+23
View File
@@ -0,0 +1,23 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),{BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs'),{BpmScanner}=require('../../src/modules/bpm/scanner.cjs');
let Monitor;try{Monitor=require('../../src/modules/bpm/arrival-monitor.cjs').BpmArrivalMonitor;}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
async function until(predicate){const end=Date.now()+2500;while(!predicate()){if(Date.now()>end)throw Error('Monitor condition was not reached');await new Promise(r=>setTimeout(r,10));}}
function fixture(t){assert.equal(typeof Monitor,'function');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-monitor-')),workspace=new WorkspaceStore(path.join(dir,'workspace')),store=new BpmScanStore(path.join(dir,'scan')),actor={username:'admin',role:'admin'},connection=workspace.createConnection({name:'监听连接',owner:'admin'},actor,[actor]);let now=Date.parse('2026-10-20T01:00:00Z'),todo=[{source:'todo',portalSource:'portal-v4',taskId:'T1',instanceId:'I1',revision:0,processName:'测试订单评审',nodeName:'通知节点',processVersion:'1',serialNum:'S1',title:'订单号:TEST-1',receivedAt:'2026-10-20T00:00:00Z'}],hold=null,connects=0,todoCalls=0,failed=false,epoch=0,hubFailure=0;let callbacks;
workspace.updateConnectionSession(connection.id,{status:'connected',identity:'fixture',checkedAt:new Date(now).toISOString(),checks:{portal:{ok:true,message:'ok'}}},actor);
const manager={epoch:()=>epoch,sessions:new Map(),ensure:async()=>({status:'connected'}),run:async(_,fn)=>fn(),authorize(){},vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})}),scanArrivals:async()=>[{source:'portal-v4',taskId:'INFORM',arrivalDay:'2026-10-20',arrivedAt:'2026-10-20T00:00:00Z',subject:'只读待阅'}]};
const provider={scan:async()=>{todoCalls++;if(hold)await hold;if(failed)throw Object.assign(Error('temporary query failure'),{status:502});return structuredClone(todo);}},scanner=new BpmScanner({workspace,store,manager,settings:()=>({schedule:{weekends:true}}),clock:()=>new Date(now)});
const hubClient={connect:async(_,options)=>{connects++;callbacks=options;if(hubFailure)throw Object.assign(Error('hub denied'),{status:hubFailure});return {stop:async()=>{}};}};
const monitor=new Monitor({workspace,manager,scanner,provider,hubClient,settings:()=>({schedule:{weekends:true}}),clock:()=>now,debounceMs:15,pollMs:10,retryMs:[20,40]});
t.after(async()=>{await monitor.stop();await scanner.stop();store.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
return {workspace,store,monitor,connection,actor,get todoCalls(){return todoCalls;},get connects(){return connects;},hint(name){callbacks.onEvent(name);},disconnect(){callbacks.onClose({reason:'disconnected'});},bumpEpoch:()=>epoch++,setHubFailure:value=>hubFailure=value,setTodo:value=>todo=value,setFailure:value=>failed=value,setHold:value=>hold=value,advance:ms=>now+=ms,until};
}
test('initial and reconnected subscriptions reconcile real todo and inform sources separately, including equal-count replacement',async t=>{const f=fixture(t);f.monitor.start();await until(()=>f.store.list({kind:'todo'}).total===1&&f.store.list().total===1);assert.equal(f.monitor.snapshot(f.connection.id).status,'listening');f.setTodo([{source:'todo',portalSource:'portal-v4',taskId:'T2',instanceId:'I2',revision:1,processName:'测试订单评审',nodeName:'通知节点',serialNum:'S2',title:'订单号:TEST-2',receivedAt:'2026-10-20T00:10:00Z'}]);f.disconnect();f.advance(100);await until(()=>f.connects>=2&&f.store.list({kind:'todo'}).total===2);assert.equal(f.store.list().total,1);assert.equal(f.store.list({kind:'todo'}).groups[0].items.some(r=>r.taskId==='T2'),true);});
test('hint bursts coalesce and a hint during synchronization schedules exactly one followup',async t=>{const f=fixture(t);f.monitor.start();await until(()=>f.todoCalls===1&&f.monitor.snapshot(f.connection.id).lastSyncAt);let release;f.setHold(new Promise(r=>release=r));for(let i=0;i<20;i++)f.hint('worklistChanged');await until(()=>f.todoCalls===2);for(let i=0;i<20;i++)f.hint('worklistChanged');release();f.setHold(null);await until(()=>f.todoCalls===3);await new Promise(r=>setTimeout(r,60));assert.equal(f.todoCalls,3);});
test('failed reconciliation retains prior rows and fallback polling recovers without a pushed event',async t=>{const f=fixture(t);f.monitor.start();await until(()=>f.store.list({kind:'todo'}).total===1);f.setFailure(true);f.hint('worklistChanged');await until(()=>f.store.status().runs.some(r=>r.kind==='todo'&&r.status==='error'));assert.equal(f.store.list({kind:'todo'}).total,1);f.setFailure(false);f.advance(5*60*1000+1);await until(()=>f.monitor.snapshot(f.connection.id).lastSyncAt===new Date(Date.parse('2026-10-20T01:00:00Z')+5*60*1000+1).toISOString());assert.equal(f.store.list({kind:'todo'}).total,1);});
test('pause removes listener and late callbacks cannot reconnect or commit new arrivals',async t=>{const f=fixture(t);f.monitor.start();await until(()=>f.store.list({kind:'todo'}).total===1);f.workspace.disableConnection(f.connection.id,f.actor);await f.monitor.stopConnection(f.connection.id);f.hint('worklistChanged');f.disconnect();f.advance(1000000);await f.monitor.tick();await new Promise(r=>setTimeout(r,40));assert.equal(f.connects,1);assert.equal(f.todoCalls,1);assert.equal(f.monitor.snapshot(f.connection.id).status,'paused');});
test('manual todo reconciliation enforces ownership and only commits after every row is valid',async t=>{const f=fixture(t);assert.equal(typeof f.monitor.startTodoScan,'function');assert.throws(()=>f.monitor.startTodoScan(f.connection.id,{user:{username:'other',role:'operator'},sessionId:'x'}),e=>e.status===403);await f.monitor.startTodoScan(f.connection.id,{user:f.actor,sessionId:'manual'}).promise;assert.equal(f.store.list({kind:'todo'}).total,1);f.setTodo([{source:'todo',portalSource:'portal-v4',taskId:'bad',instanceId:'bad',revision:1,title:'订单号:BAD',receivedAt:'not-a-date'}]);await assert.rejects(f.monitor.startTodoScan(f.connection.id,{user:f.actor,sessionId:'manual'}).promise);assert.equal(f.store.list({kind:'todo'}).total,1);});
test('company calendar pauses automatic synchronization while retaining the listener and queued change',async t=>{const f=fixture(t);f.workspace.saveCalendar({version:1,overrides:[{date:'2026-10-20',kind:'pause',scan:false,send:false,note:'隔离验证'}]},f.actor);f.monitor.start();await until(()=>f.monitor.snapshot(f.connection.id).status==='listening');f.hint('worklistChanged');await new Promise(r=>setTimeout(r,45));assert.equal(f.todoCalls,0);f.advance(86400000);await f.monitor.tick();await until(()=>f.store.list({kind:'todo'}).total===1);});
test('identity changes retire old hints and establish a fresh subscription before reconciliation',async t=>{const f=fixture(t);await f.monitor.tick();await until(()=>f.todoCalls===1&&f.monitor.snapshot(f.connection.id).lastSyncAt);f.bumpEpoch();f.hint('worklistChanged');await new Promise(r=>setTimeout(r,45));assert.equal(f.todoCalls,1);await f.monitor.tick();await f.monitor.tick();await until(()=>f.connects===2&&f.todoCalls===2);});
test('a denied push channel falls back immediately to authorized readonly lists',async t=>{const f=fixture(t);f.setHubFailure(403);f.monitor.start();await until(()=>f.store.list({kind:'todo'}).total===1);assert.equal(f.monitor.snapshot(f.connection.id).status,'polling');});
+56
View File
@@ -0,0 +1,56 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');
const {BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs');
const {BpmScanner}=require('../../src/modules/bpm/scanner.cjs');
const {BpmArrivalMonitor}=require('../../src/modules/bpm/arrival-monitor.cjs');
async function until(predicate){const end=Date.now()+1500;while(!predicate()){if(Date.now()>end)assert.fail('expected monitor transition');await new Promise(resolve=>setTimeout(resolve,5));}}
function fixture(t,{interval=1440,onTodoReconciled}={}){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'arrival-recovery-')),workspace=new WorkspaceStore(path.join(dir,'workspace')),scanStore=new BpmScanStore(path.join(dir,'scan'));
let scanner,monitor;t.after(async()=>{await monitor?.stop();await scanner?.stop();scanStore.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
const admin={username:'admin',role:'admin'},connection=workspace.createConnection({name:'合成连接',owner:'admin'},admin,[admin]);
let now=Date.parse('2026-10-21T01:00:00Z'),todoCalls=0,informCalls=0,failed=false,callbacks,hold,informHold;
workspace.updateConnectionSession(connection.id,{status:'connected',identity:'synthetic',checkedAt:new Date(now).toISOString(),checks:{portal:{ok:true,message:'synthetic'}}},admin);
scanStore.saveConfig({enabled:true,intervalMinutes:interval});
const row={source:'todo',portalSource:'portal-v4',taskId:'T',instanceId:'I',revision:1,processName:'合成订单',nodeName:'通知',processVersion:'1',serialNum:'S',title:'订单号:TEST',receivedAt:'2026-10-21T00:30:00Z'};
const manager={sessions:new Map(),epoch:()=>0,ensure:async()=>({status:'connected'}),run:async(_,fn)=>fn(),authorize(){},vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})}),scanArrivals:async()=>{informCalls++;if(informHold)await informHold;return [];}};
const provider={scan:async()=>{todoCalls++;if(hold)await hold;if(failed)throw Object.assign(Error('synthetic network failure'),{code:'ETIMEDOUT'});return [structuredClone(row)];}};
scanner=new BpmScanner({workspace,store:scanStore,manager,settings:()=>({schedule:{weekends:true}})});
monitor=new BpmArrivalMonitor({workspace,manager,scanner,provider,onTodoReconciled,clock:()=>now,settings:()=>({schedule:{weekends:true}}),hubClient:{connect:async(_,options)=>{callbacks=options;return {stop:async()=>{}};}},debounceMs:1,sourceRetryMs:[100,200,1000]});
return {workspace,scanStore,connection,admin,monitor,row,get now(){return now;},get calls(){return todoCalls;},get informCalls(){return informCalls;},advance:ms=>now+=ms,fail:value=>failed=value,hint:()=>callbacks.onEvent('worklistChanged'),hintInform:()=>callbacks.onEvent('informlistChanged'),hold:value=>hold=value,holdInform:value=>informHold=value};
}
test('reducing a live reconciliation interval applies from the last completed reconciliation',async t=>{
const f=fixture(t);await f.monitor.tick();await until(()=>f.monitor.snapshot(f.connection.id).lastSyncAt);
f.advance(10*60000);f.scanStore.saveConfig({enabled:true,intervalMinutes:1});await f.monitor.tick();
await until(()=>f.calls===2);assert.ok(Date.parse(f.monitor.snapshot(f.connection.id).nextReconcileAt)<=f.now+60000);
});
test('failed todo sources keep an independent retry with backoff despite hint bursts',async t=>{
const f=fixture(t);await f.monitor.tick();await until(()=>f.monitor.snapshot(f.connection.id).lastSyncAt);
f.fail(true);f.hint();await until(()=>f.scanStore.status().runs.some(run=>run.kind==='todo'&&run.status==='error'));
let state=f.monitor.snapshot(f.connection.id);assert.equal(state.sources.todo.status,'error');assert.equal(state.sources.inform.status,'healthy');
const calls=f.calls;f.fail(false);for(let i=0;i<20;i++)f.hint();f.advance(50);await f.monitor.tick();await new Promise(resolve=>setTimeout(resolve,15));assert.equal(f.calls,calls);
f.advance(51);await f.monitor.tick();await until(()=>f.calls===calls+1&&f.monitor.snapshot(f.connection.id).sources.todo.status==='healthy');
});
test('only fully committed authorized todo reads publish trusted execution hints',async t=>{
const hints=[],f=fixture(t,{onTodoReconciled:payload=>hints.push(payload)});await f.monitor.tick();await until(()=>f.monitor.snapshot(f.connection.id).lastSyncAt);
assert.equal(hints.length,1);assert.equal(hints[0].connectionId,f.connection.id);assert.deepEqual(hints[0].rows,[f.row]);assert.ok(hints[0].runId);assert.ok(Date.parse(hints[0].startedAt)<=Date.parse(hints[0].finishedAt));
let release;f.hold(new Promise(resolve=>release=resolve));f.hint();await until(()=>f.calls===2);f.workspace.disableConnection(f.connection.id,f.admin);
const stopping=f.monitor.stopConnection(f.connection.id);release();await stopping;assert.equal(hints.length,1);
});
test('global automatic pause revokes the in-flight todo ticket without blocking later manual sync',async t=>{
const hints=[],f=fixture(t,{onTodoReconciled:payload=>hints.push(payload)});await f.monitor.tick();await until(()=>f.monitor.snapshot(f.connection.id).lastSyncAt);
let release;f.hold(new Promise(resolve=>release=resolve));f.hint();await until(()=>f.calls===2);f.scanStore.saveConfig({enabled:false,intervalMinutes:1440});const stopping=f.monitor.reconfigure();release();await stopping;
assert.equal(hints.length,1);assert.equal(f.scanStore.status().runs.filter(run=>run.kind==='todo'&&run.status==='success').length,1);
f.hold(null);await f.monitor.startTodoScan(f.connection.id,{user:f.admin,sessionId:'manual'}).promise;assert.equal(hints.length,2);
});
test('retiring the listener revokes an in-flight inform commit ticket',async t=>{
const f=fixture(t);await f.monitor.tick();await until(()=>f.monitor.snapshot(f.connection.id).lastSyncAt);
let release;f.holdInform(new Promise(resolve=>release=resolve));f.hintInform();await until(()=>f.informCalls===2);const stopping=f.monitor.stopConnection(f.connection.id);release();await stopping;
assert.equal(f.scanStore.status().runs.filter(run=>run.kind==='inform'&&run.status==='success').length,1);
});
test('local hint delivery retries its encrypted committed payload without re-reading BPM or changing read success',async t=>{
let attempts=0;const f=fixture(t,{onTodoReconciled:()=>{attempts++;if(attempts===1)throw Error('synthetic queue failure');}});await f.monitor.tick();await until(()=>attempts===1&&!f.monitor.entries.get(f.connection.id).sync);
const run=f.scanStore.status().runs.find(item=>item.kind==='todo');assert.equal(run.status,'success');assert.equal(f.monitor.snapshot(f.connection.id).delivery.status,'error');
const stored=f.scanStore.db.prepare('SELECT payload FROM execution_deliveries WHERE run_id=?').get(run.id);assert.ok(stored);assert.equal(Buffer.from(stored.payload).includes(Buffer.from(f.row.title)),false);
f.advance(101);await f.monitor.tick();await until(()=>attempts===2&&f.monitor.snapshot(f.connection.id).delivery.pending===0);assert.equal(f.calls,1);assert.equal(f.scanStore.status().runs.find(item=>item.id===run.id).status,'success');
});
@@ -5,8 +5,8 @@ const fs=require('node:fs/promises');
const os=require('node:os');
const path=require('node:path');
const http=require('node:http');
const {BpmSessionManager}=require('../src/bpm-session-manager.cjs');
const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
const principal={user:{username:'owner',role:'operator'},sessionId:'session-one'};
const connection={id:'account-test',owner:'owner',status:'disconnected'};
const credentials={username:'Fixture User',password:' Fixture-password-123 '};
@@ -1,8 +1,8 @@
const {test}=require('node:test');const assert=require('node:assert/strict');
const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {WorkspaceStore}=require('../src/workspace-store.cjs');
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');
test('custodian restores managed or saved sessions, skips busy/disabled connections and never overlaps',async t=>{
let BpmCustodian;try{({BpmCustodian}=require('../src/bpm-custodian.cjs'));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
let BpmCustodian;try{({BpmCustodian}=require('../../src/modules/bpm/custodian.cjs'));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
assert.equal(typeof BpmCustodian,'function');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'custodian-'));const workspace=new WorkspaceStore(dir);
t.after(()=>{workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
@@ -22,7 +22,7 @@ test('custodian restores managed or saved sessions, skips busy/disabled connecti
const stopped=custodian.stop();await stopped;await custodian.tick();assert.equal(calls.length,2);
});
test('custodian start restores saved state without managed credentials and stop waits for running check',async()=>{
const {BpmCustodian}=require('../src/bpm-custodian.cjs');let finish,started;const active=new Promise(r=>started=r),gate=new Promise(r=>finish=r);let updates=0;
const {BpmCustodian}=require('../../src/modules/bpm/custodian.cjs');let finish,started;const active=new Promise(r=>started=r),gate=new Promise(r=>finish=r);let updates=0;
const connection={id:'saved',status:'unchecked',lastConnectedAt:'2026-10-16T00:00:00Z'};
const workspace={snapshot:()=>({connections:[connection]}),getConnection:()=>connection,updateConnectionSession:()=>updates++};
const manager={account:async()=>({configured:false}),ensure:async()=>{started();await gate;return {};}};
@@ -1,13 +1,13 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const http=require('node:http');
const {Store}=require('../src/dashboard-store.cjs');const {WorkspaceStore}=require('../src/workspace-store.cjs');const {createDashboard}=require('../src/dashboard.cjs');
const {Store}=require('../../src/modules/dashboard/store.cjs');const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');
const result=(status='connected')=>({status,identity:'alice@bpm',checkedAt:'2026-10-16T01:00:00.000Z',checks:{portal:{ok:status==='connected',message:'门户检查'}}});
async function setup(t,options={}){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-http-'));const store=new Store(path.join(dir,'users'));const admin=store.bootstrap('admin','Test-password-123');for(const [username,role] of [['alice','operator'],['bob','operator'],['reader','viewer']])store.addUser({username,password:'Test-password-123',role},'admin');const workspace=new WorkspaceStore(path.join(dir,'workspace'));let lease;let next=result();let disabled=0,released=0;const jpg=Buffer.from([255,216,255,217]);
const manager={open:async(connection,principal)=>{if(lease && lease!==principal.sessionId)throw Object.assign(new Error('占用'),{status:409});lease=principal.sessionId;return {active:true,viewport:{width:1280,height:800},expiresAt:'2026-10-16T02:00:00.000Z',host:'bpmn.skyworthdigital.com'};},frame:async(id,p)=>{assert.ok(id);if(lease!==p.sessionId)throw Object.assign(new Error('占用'),{status:409});return jpg;},input:async(id,p,action)=>{assert.equal(action.type,'text');return {ok:true};},navigate:async(id,p,action)=>({target:action.target}),save:async()=>next,check:async()=>next,close:async(id,p)=>{if(lease && lease!==p.sessionId)throw Object.assign(new Error('占用'),{status:409});lease=null;return {ok:true};},releaseSession:async(token)=>{if(lease===token)lease=null;released++;},disable:async()=>{disabled++;lease=null;}};
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-http-'));const store=new Store(path.join(dir,'users'));const admin=store.bootstrap('admin','Test-password-123');for(const [username,role] of [['alice','operator'],['bob','operator'],['reader','viewer']])store.addUser({username,password:'Test-password-123',role},'admin');const workspace=new WorkspaceStore(path.join(dir,'workspace'));let lease;let next=result();let disabled=0,released=0,suspended=0;const jpg=Buffer.from([255,216,255,217]);
const manager={open:async(connection,principal)=>{if(lease && lease!==principal.sessionId)throw Object.assign(new Error('占用'),{status:409});lease=principal.sessionId;return {active:true,viewport:{width:1280,height:800},expiresAt:'2026-10-16T02:00:00.000Z',host:'bpmn.skyworthdigital.com'};},frame:async(id,p)=>{assert.ok(id);if(lease!==p.sessionId)throw Object.assign(new Error('占用'),{status:409});return jpg;},input:async(id,p,action)=>{assert.equal(action.type,'text');return {ok:true};},navigate:async(id,p,action)=>({target:action.target}),save:async()=>next,check:async()=>next,close:async(id,p)=>{if(lease && lease!==p.sessionId)throw Object.assign(new Error('占用'),{status:409});lease=null;return {ok:true};},releaseSession:async(token)=>{if(lease===token)lease=null;released++;},suspend:async()=>{suspended++;lease=null;},resume:async()=>{},disable:async()=>{disabled++;lease=null;}};
const server=createDashboard({store,workspace,outputDir:dir,...(options.noManager?{}:{bpmSessions:manager}),trustedProxy:options.trustedProxy});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));t.after(async()=>{await new Promise(resolve=>server.close(resolve));workspace.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;
function call(route,body,cookie,extra={}){return new Promise((resolve,reject)=>{const host=extra.host||'127.0.0.1:'+server.address().port;const request=http.request(base+route,{method:body===undefined?'GET':'POST',headers:{Host:host,...(body===undefined?{}:{Origin:extra.origin||'http://'+host,'Content-Type':'application/json'}),...(cookie?{Cookie:cookie}:{}),...(extra.headers||{})}},response=>{const chunks=[];response.on('data',x=>chunks.push(x));response.on('end',()=>{const bytes=Buffer.concat(chunks);resolve({status:response.statusCode,headers:response.headers,bytes,json:()=>JSON.parse(bytes.toString())});});});request.on('error',reject);request.end(body===undefined?undefined:JSON.stringify(body));});}
const login=async(username)=>(await call('/api/login',{username,password:'Test-password-123'})).headers['set-cookie'][0].split(';')[0];const cookie=await login('admin');const connection=(await call('/api/connections',{name:'BPM',owner:'alice'},cookie)).json();const route='/api/connections/'+connection.id;
return {call,login,cookie,workspace,store,manager,connection,route,setResult:value=>{next=value;},counts:()=>({disabled,released}),jpg};
return {call,login,cookie,workspace,store,manager,connection,route,setResult:value=>{next=value;},counts:()=>({disabled,released,suspended}),jpg};
}
test('deleting a disabled connection enforces admin, cleans custody first, and preserves the entry on cleanup failure',async t=>{
const s=await setup(t);const endpoint=s.route+'/delete';
@@ -50,7 +50,7 @@ test('remote credentials require local host or explicit local HTTPS proxy and re
const trusted=await setup(t,{trustedProxy:true});const proxy={host:'workspace.example',origin:'https://workspace.example',headers:{'X-Forwarded-Proto':'https'}};const proxyLogin=await trusted.call('/api/login',{username:'alice',password:'Test-password-123'},undefined,proxy);assert.match(proxyLogin.headers['set-cookie'][0],/; Secure(?:;|$)/);const owner=proxyLogin.headers['set-cookie'][0].split(';')[0];assert.equal((await trusted.call(trusted.route+'/login/open',{},owner,proxy)).status,200);
});
test('transport never trusts remote LAN address with local Host or forwarded HTTPS, but accepts TLS and configured loopback proxy',()=>{
const {secureBpmTransport}=require('../src/bpm-api.cjs');
const {secureBpmTransport}=require('../../src/modules/bpm/api.cjs');
const request=(host,remoteAddress,encrypted=false,proto)=>({socket:{remoteAddress,encrypted},headers:{host,'x-forwarded-proto':proto}});
for(const trusted of [false,true]){
assert.equal(secureBpmTransport(request('localhost','192.168.1.10',false,'https'),trusted),false);
@@ -62,10 +62,10 @@ test('transport never trusts remote LAN address with local Host or forwarded HTT
assert.equal(secureBpmTransport(request('workspace.example','127.0.0.1',false,'https,http'),true),false);
assert.equal(secureBpmTransport(request('workspace.example','127.0.0.1',false,'https'),true),true);
});
test('manager errors do not leak browser secrets and failed disable leaves persisted connection enabled',async t=>{
test('manager errors do not leak browser secrets and failed pause remains disabled without exposing manager errors',async t=>{
const s=await setup(t);s.manager.open=async()=>{throw new Error('password=NEVER-EXPOSE cookie=PRIVATE');};
const failed=await s.call(s.route+'/login/open',{},s.cookie);assert.equal(failed.status,502);assert.ok(!failed.bytes.toString().includes('NEVER-EXPOSE'));
s.manager.disable=async()=>{throw new Error('cookie=PRIVATE');};const disabled=await s.call(s.route+'/disable',{},s.cookie);assert.equal(disabled.status,502);assert.equal(s.workspace.getConnection(s.connection.id).status,'disconnected');
s.manager.suspend=async()=>{throw new Error('cookie=PRIVATE');};const disabled=await s.call(s.route+'/disable',{},s.cookie);assert.equal(disabled.status,502);assert.equal(s.workspace.getConnection(s.connection.id).status,'disabled');
});
test('portal metadata persists safely, unavailable and login tasks deduplicate, and restart clears readiness',async t=>{
const s=await setup(t);const alice=await s.login('alice');assert.equal((await s.call('/api/workspace',undefined,alice)).json().capabilities.remoteLogin,true);
@@ -77,7 +77,7 @@ test('portal metadata persists safely, unavailable and login tasks deduplicate,
s.setResult(result('login_required'));for(let n=0;n<2;n++)assert.equal((await s.call(s.route+'/check',{},alice)).status,200);assert.equal(s.workspace.snapshot().exceptions.length,1);assert.equal(s.workspace.snapshot().exceptions[0].component,'bpm');assert.equal(s.workspace.snapshot().exceptions[0].id,attentionId);
s.setResult({...result(),cookies:[{value:'PRIVATE_COOKIE'}],password:'PRIVATE_PASSWORD'});assert.equal((await s.call(s.route+'/check',{},alice)).status,400);assert.ok(!JSON.stringify(s.workspace.snapshot()).includes('PRIVATE_'));
s.setResult(result());await s.call(s.route+'/check',{},alice);s.workspace.markSessionChecksPending();const after=s.workspace.getConnection(s.connection.id);assert.equal(after.status,'unchecked');assert.equal(after.identity,'alice@bpm');assert.equal(after.checkedAt,'2026-10-16T01:00:00.000Z');
assert.equal((await s.call(s.route+'/disable',{},alice)).status,403);assert.equal(s.counts().disabled,0);assert.equal((await s.call(s.route+'/disable',{},s.cookie)).status,200);assert.equal(s.counts().disabled,1);assert.equal((await s.call(s.route+'/login/open',{},alice)).status,409);
assert.equal((await s.call(s.route+'/disable',{},alice)).status,403);assert.equal(s.counts().disabled,0);assert.equal((await s.call(s.route+'/disable',{},s.cookie)).status,200);assert.equal(s.counts().suspended,1);assert.equal(s.counts().disabled,0);assert.equal((await s.call(s.route+'/login/open',{},alice)).status,409);
const noManager=await setup(t,{noManager:true});assert.equal((await noManager.call('/api/workspace',undefined,noManager.cookie)).json().capabilities.remoteLogin,false);assert.equal((await noManager.call(noManager.route+'/login/open',{},noManager.cookie)).status,503);
});
@@ -123,3 +123,5 @@ test('account availability is authenticated, owner scoped, strict and duplicate
const failed=await s.call(s.route+'/account',{username:'existing',password:'SECRET'},owner);
assert.equal(failed.status,409);assert.match(failed.json().error,/账号.*已/);assert.equal(failed.bytes.includes(Buffer.from('PRIVATE')),false);
});
test('BPM lifecycle endpoints resume with the current version and reject stale or unauthorized enables',async t=>{const s=await setup(t);const paused=await s.call(s.route+'/disable',{version:0},s.cookie);assert.equal(paused.status,200);assert.equal(paused.json().version,1);assert.equal(s.counts().disabled,0);assert.equal(s.counts().suspended,1);assert.equal((await s.call(s.route+'/enable',{version:0},s.cookie)).status,409);assert.equal((await s.call(s.route+'/enable',{version:1},await s.login('alice'))).status,403);const enabled=await s.call(s.route+'/enable',{version:1},s.cookie);assert.equal(enabled.status,200);assert.equal(enabled.json().status,'unchecked');assert.equal(enabled.json().version,2);});
@@ -4,13 +4,13 @@ const fs=require('node:fs/promises');
const os=require('node:os');
const path=require('node:path');
const http=require('node:http');
const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
test('formal dashboard remote screen signs into an isolated BPM fixture under production CSP',async t=>{
const {Store}=require('../src/dashboard-store.cjs');
const {WorkspaceStore}=require('../src/workspace-store.cjs');
const {BpmSessionManager}=require('../src/bpm-session-manager.cjs');
const {createDashboard}=require('../src/dashboard.cjs');
const {Store}=require('../../src/modules/dashboard/store.cjs');
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');
const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
const {createDashboard}=require('../../src/app/dashboard.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-full-ui-'));
const site=http.createServer((req,res)=>{
res.setHeader('Content-Type','text/html; charset=utf-8');
@@ -1,5 +1,5 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {WorkspaceStore}=require('../src/workspace-store.cjs');
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');
test('new BPM portal alone marks connected and legacy connection metadata migrates without losing ownership',t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-portal-'));let store=new WorkspaceStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
const actor={username:'owner',role:'admin'},c=store.createConnection({name:'BPM',owner:'owner'},actor,[actor]);
@@ -1,6 +1,6 @@
'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');
const {BpmSessionManager}=require('../src/bpm-session-manager.cjs');
const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
test('disposed BPM responses and rejected navigation aborts are contained in the route handler',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-route-errors-'));let handler;
const origin='http://127.0.0.1:18888',page={url:()=>origin+'/',goto:async()=>{},on(){}},network={on(){},send:async method=>method==='Page.getFrameTree'?{frameTree:{frame:{id:'main'}}}:{}};
+70
View File
@@ -0,0 +1,70 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const os=require('node:os');
const path=require('node:path');
const net=require('node:net');
async function freePort(){const server=net.createServer();await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const port=server.address().port;await new Promise(resolve=>server.close(resolve));return port;}
test('formal runtime wires BPM sessions and preserves users across restart',async t=>{
const {main}=require('../../src/server.cjs');
assert.equal(typeof main,'function','formal runtime must support isolated startup and shutdown');
const stateDir=fs.mkdtempSync(path.join(os.tmpdir(),'order-runtime-'));
let app;
t.after(async()=>{if(app)await app.stop();fs.rmSync(stateDir,{recursive:true,force:true});});
const config={port:await freePort(),dashboard:{host:'127.0.0.1',port:await freePort()}};
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
const coordinatorStart=t.mock.method(OrderExecutionCoordinator.prototype,'start');
const dispatcherStart=t.mock.method(OrderRuleDispatcher.prototype,'start');
const {NotificationService}=require('../../src/modules/notifications/service.cjs');
const genericStart=t.mock.method(NotificationService.prototype,'start');
const {OrderPipeline}=require('../../src/order-pipeline.cjs');
const legacyStart=t.mock.method(OrderPipeline.prototype,'start');
app=await main({stateDir,config,quiet:true});
let startups=0;
const assertRuntime=()=>{
startups++;
assert.ok(app.orderExecution instanceof OrderExecutionCoordinator,'runtime must wire the native guarded coordinator');
assert.ok(app.orderDispatcher instanceof OrderRuleDispatcher,'runtime must wire the native guarded dispatcher');
assert.equal(coordinatorStart.mock.callCount(),startups,'exactly one coordinator starts per runtime');
assert.equal(dispatcherStart.mock.callCount(),startups,'exactly one dispatcher starts per runtime');
assert.equal(coordinatorStart.mock.calls.at(-1).this,app.orderExecution);
assert.equal(dispatcherStart.mock.calls.at(-1).this,app.orderDispatcher);
assert.equal(genericStart.mock.callCount(),0,'generic notification sender must not start');
assert.equal(legacyStart.mock.callCount(),0,'legacy order pipeline must not start');
assert.equal(app.orderExecution.store,app.orderRules);
assert.equal(app.orderDispatcher.store,app.orderRules);
assert.equal(app.orderExecution.provider.manager,app.bpmSessions);
assert.equal(app.bpmMonitor.provider,app.orderExecution.provider);
assert.equal(app.assistant.deps.orderExecution,app.orderExecution);
assert.equal(app.health.sources.execution,app.orderExecution);
assert.equal(app.orderExecution.mail,app.mail);
assert.equal(app.orderDispatcher.mail,app.mail);
assert.deepEqual(Object.keys(app.notifications).sort(),['historyOnly','store']);
assert.equal(app.notifications.historyOnly,true);
assert.equal(app.orderRules.settings().processingEnabled,false);
assert.equal(app.orderRules.settings().enabled,false);
assert.equal(app.orderDispatcher.ready(),false);
assert.equal(app.pipeline,undefined,'runtime must not start a second legacy pipeline');
};
assertRuntime();
const base=`http://127.0.0.1:${config.dashboard.port}`;
const post=(route,body,cookie)=>fetch(base+route,{method:'POST',headers:{Origin:base,'Content-Type':'application/json',...(cookie?{Cookie:cookie}:{})},body:JSON.stringify(body)});
const bootstrap=await post('/api/bootstrap',{username:'runtime-admin',password:'Runtime-test-password-123'});
assert.equal(bootstrap.status,201);
let cookie=bootstrap.headers.get('set-cookie').split(';')[0];
const snapshot=await (await fetch(base+'/api/workspace',{headers:{Cookie:cookie}})).json();
assert.equal(snapshot.capabilities.remoteLogin,true);
assert.equal(snapshot.members[0].username,'runtime-admin');
await app.stop();app=null;
app=await main({stateDir,config,quiet:true});
assertRuntime();
assert.equal((await (await fetch(base+'/api/bootstrap/status')).json()).required,false);
assert.equal((await fetch(base+'/api/me',{headers:{Cookie:cookie}})).status,200);
const login=await post('/api/login',{username:'runtime-admin',password:'Runtime-test-password-123'});
assert.equal(login.status,200);cookie=login.headers.get('set-cookie').split(';')[0];
assert.equal((await fetch(base+'/api/workspace',{headers:{Cookie:cookie}})).status,200);
assert.equal(fs.existsSync(path.join(stateDir,'bpm-sessions')),true);
});
+52
View File
@@ -0,0 +1,52 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs');const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');const {BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs');const {BpmScanner}=require('../../src/modules/bpm/scanner.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {normalizeArrival}=require('../../src/modules/bpm/list-client.cjs');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function setup(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'scan-http-')),store=new Store(path.join(dir,'users')),workspace=new WorkspaceStore(path.join(dir,'workspace')),scanStore=new BpmScanStore(path.join(dir,'scan'));
store.bootstrap('admin','Test-password-123');store.addUser({username:'reader',password:'Test-password-123',role:'viewer'},'admin');store.addUser({username:'other',password:'Test-password-123',role:'operator'},'admin');
const connection={id:'fixture',name:'测试连接',owner:'admin',status:'connected',lastConnectedAt:new Date().toISOString()};workspace.db.prepare('INSERT INTO connections VALUES(?,?)').run(connection.id,JSON.stringify(connection));
const rows=['2026-10-15T16:33:58','2026-10-14T10:00:00'].map((date,i)=>normalizeArrival({taskId:String(i),serialNum:'TEST-'+i,processName:'海外运营订单评审',startTime:date,processInstanceSubject:i?'昨天的流程':'<script>bad()</script>订单号:123'},'portal-v8'));
const scanner=new BpmScanner({store:scanStore,workspace,manager:{scanArrivals:async()=>rows},settings:()=>store.settings()});
const server=createDashboard({store,workspace,scanner,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));
t.after(async()=>{await scanner.stop();await new Promise(r=>server.close(r));scanStore.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
const base='http://127.0.0.1:'+server.address().port,call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});
const login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {base,call,login,scanner,scanStore,workspace,store,dir};
}
test('scan API enforces owner, role and origin; scan results and overview reflect database',async t=>{
const {call,login,scanner}=await setup(t);assert.equal((await call('/api/arrivals')).status,401);const admin=await login('admin'),reader=await login('reader'),other=await login('other');
for(const cookie of [reader,other])assert.equal((await call('/api/bpm-scan/run',{connectionId:'fixture'},cookie)).status,403);
assert.equal((await call('/api/bpm-scan/config',{enabled:false,intervalMinutes:5},reader)).status,403);
assert.equal((await call('/api/bpm-scan/run',{connectionId:'fixture'},admin,'http://evil.test')).status,403);
assert.equal((await call('/api/bpm-scan/run',{connectionId:'fixture'},admin)).status,202);await Promise.all([...scanner.pending.values()]);
const page=await (await call('/api/arrivals',undefined,reader)).json();assert.equal(page.groups.length,2);assert.equal(page.groups[0].day,'2026-10-15');assert.equal(page.groups[0].items[0].subject,'订单号:123');
const overview=await (await call('/api/overview',undefined,reader)).json();assert.equal(overview.scan.total,2);assert.equal(overview.connections.find(c=>c.name==='到达历史扫描').ready,true);assert.equal(overview.connections.find(c=>c.name==='BPM 待办执行').ready,false);assert.equal(overview.connections.some(c=>c.name==='BPM 自动扫描'),false);
});
test('ledger browser keeps filtering, details and addressable PDF navigation independent from scanner failures',async t=>{
const {base,scanner,scanStore}=await setup(t);await scanner.scan('fixture',{user:{username:'admin',role:'admin'},sessionId:'fixture'});
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.goto(base+'/#records');await page.locator('#username').fill('admin');await page.locator('#password').fill('Test-password-123');await page.locator('#login-form button').click();
await page.locator('[data-arrival-row]').first().waitFor();assert.equal(await page.locator('[data-arrival-row]').count(),2);assert.equal(await page.getByRole('navigation',{name:'工具导航'}).getByRole('link',{name:'流程到达记录',exact:true}).getAttribute('aria-current'),'page');
await page.getByRole('button',{name:'查看详情',exact:true}).first().click();await page.getByRole('dialog',{name:'流程到达详情'}).waitFor();await page.getByRole('dialog').getByText('订单号:123',{exact:true}).waitFor();await page.getByRole('button',{name:'关闭详情',exact:true}).click();
const background=normalizeArrival({taskId:'background',serialNum:'BG-1',processName:'海外运营订单评审',startTime:'2026-10-16T12:00:00',processInstanceSubject:'后台扫描新增'},'portal-v8');scanStore.complete(scanStore.begin('fixture','系统扫描'),'fixture',[background]);
await page.getByText('记录有更新。',{exact:true}).waitFor({timeout:20000});await page.locator('.card-header').getByRole('button',{name:'刷新记录',exact:true}).click();await page.getByText('后台扫描新增',{exact:true}).filter({visible:true}).waitFor();await page.getByLabel('搜索流程记录',{exact:true}).fill('昨天');await page.getByRole('button',{name:'查询',exact:true}).click();await page.waitForFunction(()=>document.querySelectorAll('[data-arrival-row]').length===1);await page.getByText('昨天的流程',{exact:true}).filter({visible:true}).waitFor();
await page.setViewportSize({width:661,height:900});assert.equal(await page.getByRole('button',{name:'查看详情',exact:true}).first().evaluate(node=>node.getBoundingClientRect().right<=innerWidth),true);await page.setViewportSize({width:1280,height:900});await page.getByLabel('到达类型',{exact:true}).selectOption('inform');await page.getByRole('button',{name:'查询',exact:true}).click();await page.waitForFunction(()=>!document.querySelector('[data-record-query]').disabled);await page.getByRole('button',{name:'立即同步',exact:true}).click();await page.getByText(/同步完成/).waitFor();
await page.getByRole('link',{name:'PDF 导出记录',exact:true}).click();await page.locator('#record-search').waitFor();assert.equal(new URL(page.url()).hash,'#records-pdf');await page.reload();await page.locator('#record-search').waitFor();
await page.route('**/api/bpm-scan',route=>route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:'扫描暂不可用'})}));await page.getByRole('link',{name:'流程到达记录',exact:true}).click();await page.getByText(/扫描暂不可用/).waitFor();await page.getByRole('link',{name:'PDF 导出记录',exact:true}).click();await page.locator('#record-search').waitFor();assert.equal(await page.locator('.offcanvas-backdrop').count(),0);
});
test('deleted sources enter read-only history while other BPM processes remain available through explicit filters',async t=>{
const {base,workspace,scanner,scanStore,call,login}=await setup(t);await scanner.scan('fixture',{user:{username:'admin',role:'admin'},sessionId:'fixture'});scanStore.complete(scanStore.begin('orphan','old'),'orphan',[normalizeArrival({taskId:'OLD',processName:'采购审批',startTime:'2026-10-15T12:00:00',processInstanceSubject:'非订单历史'},'portal-v4')]);workspace.disableConnection('fixture',{username:'admin',role:'admin'});workspace.deleteConnection('fixture',{username:'admin',role:'admin'});const cookie=await login('reader');const data=await(await call('/api/arrivals?view=ledger&scope=archived',undefined,cookie)).json();assert.equal(data.total,2);assert.equal(data.items[0].origin.name,'测试连接');assert.equal((await(await call('/api/arrivals?view=ledger',undefined,cookie)).json()).total,0);
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.goto(base+'/#records');await page.locator('#username').fill('reader');await page.locator('#password').fill('Test-password-123');await page.locator('#login-form button').click();await page.getByText('暂无匹配的到达记录',{exact:true}).waitFor();await page.getByLabel('记录范围',{exact:true}).selectOption('archived');await page.getByRole('button',{name:'查询',exact:true}).click();await page.locator('[data-arrival-row]').first().waitFor();assert.equal(await page.locator('[data-arrival-row]').count(),2);assert.equal(await page.getByRole('button',{name:'立即同步',exact:true}).count(),0);await page.getByLabel('业务范围',{exact:true}).selectOption('all');await page.getByRole('button',{name:'查询',exact:true}).click();await page.getByText('非订单历史',{exact:true}).filter({visible:true}).waitFor();await page.locator('[data-arrival-row]').filter({hasText:'非订单历史'}).getByRole('button',{name:'查看详情',exact:true}).click();await page.getByRole('dialog',{name:'流程到达详情'}).getByText(/来源信息缺失/).waitFor();await page.goto(base+'/#records-pdf');await page.locator('#record-search').waitFor();await page.waitForFunction(()=>!document.querySelector('.offcanvas-backdrop'));
});
test('todo arrival queries stay separate from inform history and cannot invoke an unavailable todo listener',async t=>{
const {call,login,scanner,scanStore}=await setup(t),cookie=await login('admin');await scanner.scan('fixture',{user:{username:'admin',role:'admin'},sessionId:'fixture'});
const row=require('../../src/modules/bpm/arrival-monitor.cjs').todoArrival({source:'todo',portalSource:'portal-v4',taskId:'TODO-1',instanceId:'INSTANCE',revision:1,processName:'订单流程',nodeName:'通知节点',title:'待办样例',receivedAt:'2026-10-20T01:00:00Z'});scanStore.complete(scanStore.begin('fixture','系统监听','todo'),'fixture',[row]);
const todo=await (await call('/api/arrivals?kind=todo',undefined,cookie)).json();assert.equal(todo.total,1);assert.equal(todo.groups[0].items[0].kind,'todo');assert.equal((await (await call('/api/arrivals',undefined,cookie)).json()).total,2);assert.equal((await call('/api/arrivals?kind=unknown',undefined,cookie)).status,400);assert.equal((await call('/api/bpm-scan/run',{connectionId:'fixture',kind:'todo'},cookie)).status,503);
});
test('a successful todo observation does not claim that the independent inform-history source was verified',async t=>{const {call,login,scanStore}=await setup(t),cookie=await login('admin'),row=require('../../src/modules/bpm/arrival-monitor.cjs').todoArrival({source:'todo',portalSource:'portal-v4',taskId:'TODO',instanceId:'I',revision:1,processName:'订单流程',nodeName:'通知节点',title:'待办样例',receivedAt:'2026-10-20T01:00:00Z'});scanStore.complete(scanStore.begin('fixture','系统监听','todo'),'fixture',[row]);const overview=await (await call('/api/overview',undefined,cookie)).json();assert.equal(overview.connections.find(c=>c.name==='到达历史扫描').ready,false);});
test('a delayed initial PDF response cannot discard a search typed while loading',async t=>{const {base}=await setup(t);const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();let release;const captured=new Promise(resolve=>release=resolve);let first=true;await page.route('**/api/jobs?*',async route=>{if(first){first=false;release(route);return;}await route.continue();});await page.goto(base+'/#records-pdf');await page.locator('#username').fill('admin');await page.locator('#password').fill('Test-password-123');await page.locator('#login-form button').click();await page.locator('#record-search').waitFor();const held=await captured;await page.locator('#record-search').fill('UNMATCHED');await held.continue();await page.waitForFunction(()=>!document.querySelector('[data-record-query]').disabled);assert.equal(await page.locator('#record-search').inputValue(),'UNMATCHED');const searched=page.waitForRequest(request=>new URL(request.url()).pathname==='/api/jobs'&&new URL(request.url()).searchParams.get('q')==='UNMATCHED',{timeout:3000});await page.getByRole('button',{name:'查询',exact:true}).click();await searched;await page.getByText('暂无匹配的导出记录',{exact:true}).waitFor();});
test('PDF HTTP and browser separate missing files from completed exports and clean a closing detail on route change',async t=>{
const {base,store,dir,call,login}=await setup(t);fs.writeFileSync(path.join(dir,'available.pdf'),'%PDF-1.4\nfixture');store.recordJob({jobId:'live-pdf',status:'success',path:path.join(dir,'available.pdf'),filename:'available.pdf',metadata:{order:'LIVE-1',project:'项目',model:'型号',serial:'通知-1'}});store.recordJob({jobId:'lost-pdf',status:'success',path:path.join(dir,'lost.pdf'),filename:'lost.pdf',metadata:{order:'LOST-1'}});const cookie=await login('reader');const data=await(await call('/api/jobs?view=ledger',undefined,cookie)).json();assert.equal(data.total,2);assert.equal(data.jobs.find(j=>j.jobId==='lost-pdf').status,'success');assert.equal(data.jobs.find(j=>j.jobId==='lost-pdf').downloadable,false);assert.equal((await call('/api/jobs/live-pdf/file',undefined,cookie)).status,200);assert.equal((await call('/api/jobs/lost-pdf/file',undefined,cookie)).status,404);assert.equal((await call('/api/jobs?view=ledger&page=0',undefined,cookie)).status,400);
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:390,height:844}}),errors=[];page.on('pageerror',error=>errors.push(error.message));await page.goto(base+'/#records-pdf');await page.locator('#username').fill('reader');await page.locator('#password').fill('Test-password-123');await page.locator('#login-form button').click();const lost=page.locator('[data-pdf-row]').filter({hasText:'LOST-1'});await lost.waitFor();assert.match(await lost.innerText(),/已完成/);assert.match(await lost.innerText(),/文件缺失/);assert.equal(await lost.getByRole('link',{name:'下载 PDF',exact:true}).count(),0);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await lost.getByRole('button',{name:'查看详情',exact:true}).click();await page.getByRole('dialog',{name:'PDF 导出详情'}).waitFor();await page.getByRole('button',{name:'关闭详情',exact:true}).click();await page.goto(base+'/#records');await page.locator('#arrival-query').waitFor();await page.waitForTimeout(450);assert.equal(await page.locator('.offcanvas-backdrop').count(),0);assert.equal(await page.evaluate(()=>document.body.style.overflow),'');assert.deepEqual(errors,[]);
});
@@ -1,8 +1,8 @@
const test=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const http=require('node:http');
const {BpmListClient,normalizeArrival}=require('../src/bpm-list-client.cjs');
const {BpmScanStore}=require('../src/bpm-scan-store.cjs');
const {BpmScanner}=require('../src/bpm-scanner.cjs');
const {BpmSessionManager}=require('../src/bpm-session-manager.cjs');
const {BpmListClient,normalizeArrival}=require('../../src/modules/bpm/list-client.cjs');
const {BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs');
const {BpmScanner}=require('../../src/modules/bpm/scanner.cjs');
const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
const row=(id,date='2026-10-15T16:33:58')=>({taskId:id,serialNum:'SN-'+id,processName:'订单评审',activityName:'知会',startTime:date,processInstanceSubject:'<b>订单号:</b>123 &amp; 456',processInstanceInitiatorShortName:'甲'});
test('list summary preserves raw line breaks and explicit detail references only',()=>{
const value=normalizeArrival({...row('line'),processInstanceSubject:' 第一行\r\n第二行<br>第三行 ',detailUrl:'https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/PV1.aspx?tid=1&pid=2'},'portal-v4');
@@ -54,3 +54,6 @@ test('SQLite keeps history across rescan and restart, daily pagination and searc
const bad=store.begin('c','甲');assert.throws(()=>store.complete(bad,'c',[rows[0],{...rows[1],arrivalDay:null}]));assert.equal(store.list().total,2);store.fail(bad,'扫描失败');assert.equal(store.status().runs[0].status,'error');
store.saveConfig({enabled:false,intervalMinutes:10},'甲');assert.equal(store.status().config.enabled,false);
});
test('a forbidden list response is a permission failure and must not request credential renewal',async t=>{
const server=http.createServer((req,res)=>{if(req.url==='/')return res.end('<script>Yiez.clientId="fixture-token";</script>');res.writeHead(403);res.end();});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));const client=new BpmListClient({baseURL:'http://127.0.0.1:'+server.address().port+'/',allowLocal:true});await assert.rejects(client.scan({cookies:[],origins:[]}),e=>e.status===403);
});
@@ -4,7 +4,7 @@ const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const http = require('node:http');
const { loadPlaywright, browserOptions } = require('../src/runtime.cjs');
const { loadPlaywright, browserOptions } = require('../../src/platform/browser.cjs');
const principal = { user: { id: '1', username: 'owner', role: 'operator' }, sessionId: 'dashboard-session' };
const connection = { id: 'a', owner: 'owner', status: 'disconnected' };
const other = { user: { id: '2', username: 'intruder', role: 'operator' }, sessionId: 'other-session' };
@@ -15,7 +15,7 @@ async function login(){const db=await dbp;await new Promise(r=>{const t=db.trans
</script>`;
async function fixture(t) {
const { BpmSessionManager } = require('../src/bpm-session-manager.cjs');
const { BpmSessionManager } = require('../../src/modules/bpm/session-manager.cjs');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'bpm-browser-'));
let blockedHits = 0;const requests=[];
const forbidden = http.createServer((req,res) => { blockedHits++; res.end('forbidden'); });
@@ -109,7 +109,7 @@ test('legacy detail navigation is rejected before any request',async t=>{
});
test('production origin policy permits verified company SSO but rejects lookalikes and arbitrary injections', async t => {
const { BpmSessionManager } = require('../src/bpm-session-manager.cjs');
const { BpmSessionManager } = require('../../src/modules/bpm/session-manager.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-origin-'));
t.after(()=>fs.rm(dir,{recursive:true,force:true}));
const manager=new BpmSessionManager({stateDir:dir}); t.after(()=>manager.shutdown());
@@ -3,11 +3,11 @@ const assert=require('node:assert/strict');
const fs=require('node:fs');
const http=require('node:http');
const path=require('node:path');
const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
const {setTimeout:delay}=require('node:timers/promises');
async function waitUntil(predicate){const deadline=Date.now()+10000;while(!predicate()){assert.ok(Date.now()<deadline,'expected browser request did not arrive');await delay(25);}}
let browser,server,base,jpeg;
const source=path.join(__dirname,'../web/bpm.js');
const source=path.join(__dirname,'../../web/modules/bpm/view.js');
before(async()=>{
browser=await loadPlaywright().chromium.launch(browserOptions());
const page=await browser.newPage({viewport:{width:1280,height:800}});jpeg=await page.screenshot({type:'jpeg'});await page.close();
@@ -39,10 +39,11 @@ async function fixture(t,{user={username:'alice',role:'operator'},connections,ac
if(url.pathname.endsWith('/save'))await saveGate;
if(url.pathname.endsWith('/save')||url.pathname.endsWith('/check'))result={connection:{id:'one',name:'业务连接',owner:'alice',status:'connected',identity:'Alice',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'已登录'}}}};
if(url.pathname.endsWith('/account/check'))result={available:body?.username!=='already-used'};
if(url.pathname.endsWith('/enable')||url.pathname.endsWith('/disable')){const id=url.pathname.split('/').at(-2),item=connections.find(c=>c.id===id);item.status=url.pathname.endsWith('/enable')?'unchecked':'disabled';item.version=(item.version||0)+1;result={...item};}
await route.fulfill({json:result});
});
await page.goto(base);
await page.addStyleTag({path:path.join(__dirname,'../web/app.css')});
await page.addStyleTag({path:path.join(__dirname,'../../web/app.css')});
if(fs.existsSync(source))await page.addScriptTag({path:source});
assert.equal(await page.evaluate(()=>typeof window.BpmLogin?.mount),'function','BPM page exposes a working mount function');
await page.evaluate(async user=>{
@@ -80,11 +81,11 @@ test('auto-renew setup rejects a duplicate username before sending credentials a
assert.equal(await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).count(),1);
});
test('portal login displays one portal check and saves connected without legacy controls',async t=>{
test('portal login displays session, business and monitoring checks without legacy controls',async t=>{
const f=await fixture(t,{connections:[{id:'one',name:'新版 BPM',owner:'alice',status:'connected',checks:{portal:{ok:true,message:'新版已登录'}}}]});
assert.equal(await f.page.getByText('旧版入口',{exact:true}).count(),0);
assert.equal(await f.page.getByText('bpm.skyworthdigital.com',{exact:true}).count(),0);
assert.equal(await f.page.locator('.bpm-checks>div').count(),1);
assert.match(await f.page.locator('.bpm-checks').innerText(),/登录会话.*新版已登录/);
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
assert.equal(await f.page.getByRole('button',{name:'旧版入口',exact:true}).count(),0);
await f.page.getByRole('button',{name:'新版门户',exact:true}).click();
@@ -92,7 +93,7 @@ test('portal login displays one portal check and saves connected without legacy
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();
await f.page.getByText('连接已检查并保存。',{exact:true}).waitFor();
assert.equal(await f.page.getByText('已连接',{exact:true}).count(),1);
assert.equal(await f.page.locator('.bpm-checks>div').count(),1);
assert.match(await f.page.locator('.bpm-checks').innerText(),/登录会话.*已登录/);
assert.deepEqual(f.calls.filter(c=>c.path.endsWith('/navigate')).map(c=>c.body),[{target:'main'},{target:'reload'}]);
});
test('account management loads metadata only for enabled owner or admin connections',async t=>{
@@ -258,8 +259,9 @@ test('narrow screens keep the frame inside the page and native typing forwards t
test('refresh and logout release BPM control before rendering or dropping authentication',async()=>{
const vm=require('node:vm'),events=[],elements=new Map();
const element=id=>{if(!elements.has(id))elements.set(id,{innerHTML:'',textContent:'',classList:{remove(){}},querySelector(){return {disabled:false};}});return elements.get(id);};
const context=vm.createContext({Intl,setTimeout,clearInterval,location:{hash:'#overview'},document:{querySelector:element,querySelectorAll:()=>[]},window:{addEventListener(){},BpmLogin:{dispose:async()=>events.push('release')},WorkspaceViews:{overview:async()=>events.push('render')}}});
const source=fs.readFileSync(path.join(__dirname,'../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
const context=vm.createContext({Intl,setTimeout,clearInterval,location:{hash:'#overview'},history:{replaceState(){}},document:{querySelector:element,querySelectorAll:()=>[],addEventListener(){}},window:{addEventListener(){},PageLifecycle:{guard:fn=>fn(),dispose:async()=>{},attach(){},bind(){}},AppNavigation:{primary:[],resolve:id=>id,sectionFor:()=>null,renderTabs(){},isConfiguration:()=>false},BpmLogin:{dispose:async()=>events.push('release')},OrderNotificationViews:{render:async()=>events.push('render')}}});
const source=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
vm.runInContext(fs.readFileSync(path.join(__dirname,'../../web/modules/records/state.js'),'utf8'),context);
vm.runInContext(source,context);
await vm.runInContext("currentUser={username:'alice',role:'admin'};renderView()",context);
assert.deepEqual(events,['release','render']);events.length=0;
@@ -268,15 +270,15 @@ test('refresh and logout release BPM control before rendering or dropping authen
});
test('an expired login request rejects without waiting on its own remote cleanup',async()=>{
const vm=require('node:vm'),events=[];
const context=vm.createContext({Intl,setTimeout,fetch:async()=>({status:401,ok:false,json:async()=>({error:'请重新登录。'})}),document:{querySelector:()=>({})},window:{addEventListener(){},BpmLogin:{dispose:()=>new Promise(()=>{})}},events});
const source=fs.readFileSync(path.join(__dirname,'../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');vm.runInContext(source,context);
const context=vm.createContext({Intl,setTimeout,clearTimeout,AbortController,AbortSignal,fetch:async()=>({status:401,ok:false,json:async()=>({error:'请重新登录。'})}),document:{querySelector:()=>({}),addEventListener(){}},window:{addEventListener(){},BpmLogin:{dispose:()=>new Promise(()=>{})}},events});
const source=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');vm.runInContext(source,context);
const pending=vm.runInContext("currentUser={username:'alice',role:'operator'};boot=async()=>events.push('login');api('/connections/one/login/open',{}).then(()=> 'resolved',()=> 'rejected')",context);
assert.equal(await Promise.race([pending,new Promise(resolve=>setTimeout(()=>resolve('pending'),100))]),'rejected');assert.deepEqual(events,['login']);
});
for(const pendingAction of ['open','save'])test(`document unload sends authenticated close while ${pendingAction} is pending`,async t=>{
const calls=[];let finishPending=()=>{},pendingStarted;
const started=new Promise(resolve=>pendingStarted=resolve);
const appSource=fs.readFileSync(path.join(__dirname,'../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
const appSource=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
const fixtureServer=http.createServer(async(req,res)=>{
const requestPath=new URL(req.url,'http://localhost').pathname;
if(requestPath==='/bpm.js'||requestPath==='/app.js'){res.setHeader('Content-Type','application/javascript; charset=utf-8');return res.end(requestPath==='/bpm.js'?fs.readFileSync(source):appSource);}
@@ -302,3 +304,17 @@ for(const pendingAction of ['open','save'])test(`document unload sends authentic
const close=calls.find(c=>c.path.endsWith('/close'));assert.ok(close,'unload must dispatch close before the held request completes');
assert.equal(close.body,'{}');assert.match(close.cookie,/session=fixture-session/);assert.equal(close.origin,fixtureBase);
});
test('admin pauses and resumes using explicit buttons and the current version',async t=>{const f=await fixture(t,{user:{username:'admin',role:'admin'},connections:[{id:'toggle',name:'可恢复连接',owner:'alice',status:'connected',version:4,identity:'fixture'}]});await f.page.getByRole('button',{name:'停用连接',exact:true}).click();await f.page.getByRole('button',{name:'启用连接',exact:true}).waitFor();assert.equal(await f.page.getByRole('button',{name:'检查连接',exact:true}).count(),0);assert.deepEqual(f.calls.find(c=>c.path.endsWith('/disable')).body,{version:4});await f.page.getByRole('button',{name:'启用连接',exact:true}).click();await f.page.getByRole('button',{name:'停用连接',exact:true}).waitFor();assert.deepEqual(f.calls.find(c=>c.path.endsWith('/enable')).body,{version:5});assert.equal(await f.page.getByRole('switch').count(),0);});
test('connection cards distinguish authenticated session, todo permission and passive-listener status',async t=>{const f=await fixture(t,{connections:[{id:'one',name:'分层检测',owner:'alice',status:'connected',health:{portal:{status:'healthy',checkedAt:new Date().toISOString()},todo:{status:'forbidden',checkedAt:new Date().toISOString()}},monitoring:{status:'listening',lastSyncAt:new Date().toISOString()}}]});await f.page.getByText('订单接口 · 无读取权限',{exact:false}).waitFor();await f.page.getByText('到达监听 · 推送已连接',{exact:false}).waitFor();await f.page.getByRole('button',{name:'开启自动续登',exact:true}).click();await f.page.getByLabel('BPM 账号',{exact:true}).fill('not-yet-saved');await new Promise(r=>setTimeout(r,5200));assert.equal(await f.page.getByLabel('BPM 账号',{exact:true}).inputValue(),'not-yet-saved');});
test('a delayed background snapshot cannot resurrect a connection after deletion',async t=>{
const connection={id:'off',name:'旧连接',owner:'alice',status:'disabled',version:1},f=await fixture(t,{user:{username:'admin',role:'admin'},connections:[connection]});let arrive,release;const arrived=new Promise(r=>arrive=r),gate=new Promise(r=>release=r);
await f.page.route('**/api/workspace',async route=>{arrive();await gate;await route.fulfill({json:{connections:[connection],capabilities:{remoteLogin:true}}});});await arrived;f.page.once('dialog',dialog=>dialog.accept());await f.page.getByRole('button',{name:'删除',exact:true}).click();await f.page.getByText('连接已删除。',{exact:true}).waitFor();const response=f.page.waitForResponse(r=>r.url().endsWith('/api/workspace'));release();await response;await f.page.waitForTimeout(100);assert.equal(await f.page.getByRole('heading',{name:'旧连接',exact:true}).count(),0);
});
test('source read state and local delivery are separate and handover uses connection version',async t=>{
const connection={id:'one',name:'隔离监听连接',owner:'boss',version:7,status:'connected',monitoring:{status:'listening',nextReconcileAt:'2026-10-21T10:00:00Z',sources:{todo:{status:'healthy',lastSuccessAt:'2026-10-21T09:00:00Z'},inform:{status:'failed',lastFailureAt:'2026-10-21T09:01:00Z',retryAt:'2026-10-21T09:02:00Z'}},delivery:{status:'retrying',pending:2,message:'隔离本地投递失败'}}};
const f=await fixture(t,{user:{username:'boss',role:'admin'},connections:[connection]});await f.page.getByText(/待办源读取 · healthy/).waitFor();await f.page.getByText(/通知源读取 · failed/).waitFor();await f.page.getByText(/本地执行器投递 · retrying · 待交付 2/).waitFor();let submitted;
await f.page.route('**/api/connections/one/owner',route=>{submitted=route.request().postDataJSON();return route.fulfill({json:{connection:{...connection,owner:'alice',status:'disabled',version:8},cleanupPending:false}});});
await f.page.locator('[data-owner-transfer] select').selectOption('alice');await f.page.getByRole('button',{name:'确认转交',exact:true}).click();await f.page.getByRole('button',{name:'启用连接',exact:true}).waitFor();assert.deepEqual(submitted,{version:7,owner:'alice'});assert.match(await f.page.locator('[data-bpm-feedback]').innerText(),/连接已暂停/);
});
@@ -5,7 +5,7 @@ const os = require('node:os');
const path = require('node:path');
test('session updates remain atomic when the state directory rejects file renames',async t=>{
const {BpmVault}=require('../src/bpm-vault.cjs');
const {BpmVault}=require('../../src/platform/security/vault.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-session-rename-'));
const vault=new BpmVault({stateDir:dir});
t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
@@ -18,7 +18,7 @@ test('session updates remain atomic when the state directory rejects file rename
});
test('managed accounts use an encrypted SQLite registry with uniqueness across connections and restarts',async t=>{
const {BpmVault}=require('../src/bpm-vault.cjs');
const {BpmVault}=require('../../src/platform/security/vault.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-accounts-db-'));
const vault=new BpmVault({stateDir:dir}),second=new BpmVault({stateDir:dir});
t.after(async()=>{vault.destroy();second.destroy();await fs.rm(dir,{recursive:true,force:true});});
@@ -38,7 +38,7 @@ test('managed accounts use an encrypted SQLite registry with uniqueness across c
});
test('simultaneous account saves admit only one normalized username and preserve other records',async t=>{
const {BpmVault}=require('../src/bpm-vault.cjs');const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-unique-'));
const {BpmVault}=require('../../src/platform/security/vault.cjs');const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-unique-'));
const vault=new BpmVault({stateDir:dir}),other=new BpmVault({stateDir:dir});
t.after(async()=>{vault.destroy();other.destroy();await fs.rm(dir,{recursive:true,force:true});});
await vault.write('account:existing',{username:'different',password:'keep-this'});
@@ -49,7 +49,7 @@ test('simultaneous account saves admit only one normalized username and preserve
});
test('legacy encrypted account files migrate atomically and conflicting legacy files are retained',async t=>{
const {BpmVault}=require('../src/bpm-vault.cjs'),crypto=require('node:crypto');const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-legacy-'));
const {BpmVault}=require('../../src/platform/security/vault.cjs'),crypto=require('node:crypto');const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-legacy-'));
const vault=new BpmVault({stateDir:dir});t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
const legacy=async(id,username)=>{const key='account:'+id,iv=crypto.randomBytes(12),cipher=crypto.createCipheriv('aes-256-gcm',vault.ensureKey(),iv);cipher.setAAD(Buffer.from(key));const data=Buffer.concat([cipher.update(JSON.stringify({username,password:'legacy-secret',nextAttemptAt:'2030-01-01T00:00:00Z'})),cipher.final()]);await fs.writeFile(vault.filename(key),Buffer.concat([Buffer.from('BPM1'),iv,cipher.getAuthTag(),data]));};
await legacy('one','First.User');await legacy('two','first.user');
@@ -63,7 +63,7 @@ test('legacy encrypted account files migrate atomically and conflicting legacy f
});
test('vault encrypts state, survives restart, rejects corruption and keeps connection isolation', async t => {
const { BpmVault } = require('../src/bpm-vault.cjs');
const { BpmVault } = require('../../src/platform/security/vault.cjs');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'bpm-vault-'));
const vault = new BpmVault({ stateDir: dir });
t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
@@ -82,7 +82,7 @@ test('vault encrypts state, survives restart, rejects corruption and keeps conne
});
test('vault binds ciphertext to connection identity and never leaves plaintext temporary files', async t => {
const { BpmVault } = require('../src/bpm-vault.cjs');
const { BpmVault } = require('../../src/platform/security/vault.cjs');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'bpm-vault-'));
const vault = new BpmVault({ stateDir: dir });
t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
@@ -95,7 +95,7 @@ test('vault binds ciphertext to connection identity and never leaves plaintext t
});
test('legacy session ciphertext migrates, database state wins, and removal cannot restore a stale file',async t=>{
const {BpmVault}=require('../src/bpm-vault.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-legacy-session-')),vault=new BpmVault({stateDir:dir});
const {BpmVault}=require('../../src/platform/security/vault.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-legacy-session-')),vault=new BpmVault({stateDir:dir});
t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
const old={storageState:{cookies:[]},sessionStorage:{portal:{token:'legacy-private-token'}}};
await fs.writeFile(vault.filename('legacy'),vault.encode('legacy',old));
+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);
});
+22
View File
@@ -0,0 +1,22 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),http=require('node:http');
const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
test('concurrent manual and background checks share one authenticated request',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-shared-check-'));let release,started,probes=0;const gate=new Promise(r=>release=r),begun=new Promise(r=>started=r),manager=new BpmSessionManager({stateDir:dir,accessClient:{check:async()=>{probes++;started();await gate;return {status:'connected',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'ok'}},todo:'healthy'};}}});manager._vault={read:async()=>({storageState:{cookies:[],origins:[]}}),destroy(){}};t.after(async()=>{await manager.shutdown();fs.rmSync(dir,{recursive:true,force:true});});const c={id:'c',owner:'admin',status:'connected'},p={user:{username:'admin',role:'admin'},sessionId:'same'};const a=manager.ensure(c,p);await begun;const b=manager.check(c,p);release();await Promise.all([a,b]);assert.equal(probes,1);
});
test('recent authenticated traffic avoids browser checks but expiry or identity invalidation requires fresh evidence',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-health-'));let probes=0,browsers=0;const manager=new BpmSessionManager({stateDir:dir,accessClient:{check:async()=>{probes++;return {status:'connected',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'已验证'}},todo:'healthy'};}},browserFactory:()=>{browsers++;throw Error('Unexpected browser');}});
manager._vault={read:async()=>({storageState:{cookies:[],origins:[]}}),write:async()=>{},destroy(){}};const c={id:'c',owner:'admin',status:'connected',identity:'fixture'},p={user:{username:'admin',role:'admin'},sessionId:'health'};t.after(async()=>{await manager.shutdown();fs.rmSync(dir,{recursive:true,force:true});});
manager.observe('c','inform');const result=await manager.ensure(c,p);assert.equal(result.status,'connected');assert.equal(probes,0);assert.equal(browsers,0);await manager.check(c,p);assert.equal(probes,1);await manager.suspend('c');await manager.resume('c');await manager.ensure(c,p);assert.equal(probes,2);
});
test('an upstream network failure never triggers browser credential submission',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-probe-'));let browsers=0;const manager=new BpmSessionManager({stateDir:dir,accessClient:{check:async()=>({status:'error',checkedAt:new Date().toISOString(),checks:{portal:{ok:false,message:'网络暂不可用'}},todo:'error'})},browserFactory:()=>{browsers++;throw Error('must not login');}});manager._vault={read:async()=>({storageState:{cookies:[],origins:[]}}),destroy(){}};t.after(async()=>{await manager.shutdown();fs.rmSync(dir,{recursive:true,force:true});});const result=await manager.ensure({id:'c',owner:'admin',status:'connected'},{user:{username:'admin',role:'admin'},sessionId:'network'});assert.equal(result.status,'error');assert.equal(browsers,0);
});
let Access;try{Access=require('../../src/modules/bpm/access-client.cjs').BpmAccessClient;}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
test('lightweight probes distinguish permission failure from expired authentication without loading order details',async t=>{
assert.equal(typeof Access,'function');let mode='ok',urls=[];const server=http.createServer((req,res)=>{urls.push(req.url);if(req.url==='/'){res.end('<script>Yiez.clientId="fixture-token";</script>');return;}if(mode==='auth'){res.writeHead(401);return res.end();}if(mode==='forbidden'){res.writeHead(403);return res.end();}res.setHeader('Content-Type','application/json');res.end(JSON.stringify({total:4,children:[{taskId:1}]}));});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));const client=new Access({baseURL:'http://127.0.0.1:'+server.address().port+'/',allowLocal:true});
const state={cookies:[],origins:[]},ok=await client.check(state);assert.equal(ok.status,'connected');assert.equal(ok.todo,'healthy');assert.equal(urls.filter(u=>u!=='/').every(u=>u.includes('limit=1')),true);assert.equal(JSON.stringify(ok).includes('fixture-token'),false);mode='forbidden';const forbidden=await client.check(state);assert.equal(forbidden.status,'connected');assert.equal(forbidden.todo,'forbidden');mode='auth';assert.equal((await client.check(state)).status,'login_required');
});
test('an unrecognized external redirect is a transport failure rather than proof that credentials expired',async t=>{
const server=http.createServer((req,res)=>{res.writeHead(302,{Location:'https://untrusted.invalid/login'});res.end();});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));const client=new Access({baseURL:'http://127.0.0.1:'+server.address().port+'/',allowLocal:true});assert.equal((await client.check({cookies:[],origins:[]})).status,'error');
});
+13
View File
@@ -0,0 +1,13 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');
const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
let Lifecycle;try{Lifecycle=require('../../src/modules/bpm/connection-lifecycle.cjs').BpmConnectionLifecycle;}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
function fixture(t){assert.equal(typeof Lifecycle,'function');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-lifecycle-')),workspace=new WorkspaceStore(path.join(dir,'workspace')),manager=new BpmSessionManager({stateDir:path.join(dir,'sessions'),browserFactory:()=>{throw Error('A toggle must not launch a browser');}}),admin={username:'admin',role:'admin'},connection=workspace.createConnection({name:'测试连接',owner:'admin'},admin,[admin]);
const secrets=new Map([[connection.id,{storageState:{cookies:[{name:'fixture',value:'private'}]}}],['account:'+connection.id,{username:'fixture',password:'private'}]]);manager._vault={read:async key=>secrets.get(key)||null,remove:async key=>secrets.delete(key),destroy(){}};
t.after(async()=>{await manager.shutdown();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});return {dir,workspace,manager,admin,connection,secrets,service:new Lifecycle({workspace,manager})};}
test('pause and resume retain account and cookies, increment versions, and survive workspace reopen',async t=>{const f=fixture(t),id=f.connection.id;const paused=await f.service.change(id,false,{version:0},f.admin);assert.equal(paused.status,'disabled');assert.equal(paused.version,1);assert.equal(f.secrets.size,2);const again=await f.service.change(id,false,{version:0},f.admin);assert.equal(again.version,1);const enabled=await f.service.change(id,true,{version:1},f.admin);assert.equal(enabled.status,'unchecked');assert.equal(enabled.version,2);assert.equal(f.secrets.size,2);assert.equal(f.manager.disabled.has(id),false);const reopened=new WorkspaceStore(path.join(f.dir,'workspace'));assert.equal(reopened.getConnection(id).status,'unchecked');assert.equal(reopened.getConnection(id).version,2);reopened.close();});
test('stale enable cannot undo a newer pause, and only admins change lifecycle',async t=>{const f=fixture(t),id=f.connection.id;await f.service.change(id,false,{version:0},f.admin);await assert.rejects(f.service.change(id,true,{version:0},f.admin),e=>e.status===409);await assert.rejects(f.service.change(id,true,{version:1},{username:'admin',role:'operator'}),e=>e.status===403);assert.equal(f.workspace.getConnection(id).status,'disabled');});
test('pause publishes disabled before draining in-flight work and a late check cannot revive it',async t=>{const f=fixture(t),id=f.connection.id;let release,arrive;const started=new Promise(r=>arrive=r),gate=new Promise(r=>release=r);const active=f.manager.run(id,async()=>{arrive();await gate;assert.throws(()=>f.workspace.updateConnectionSession(id,{status:'connected',identity:'fixture',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'ok'}}},f.admin),e=>e.status===409);});await started;const stopping=f.service.change(id,false,{version:0},f.admin);await new Promise(r=>setImmediate(r));assert.equal(f.workspace.getConnection(id).status,'disabled');release();await active;await stopping;assert.equal(f.secrets.size,2);});
test('deletion alone clears account and session and requires a disabled connection',async t=>{const f=fixture(t),id=f.connection.id;await assert.rejects(f.service.remove(id,f.admin),e=>e.status===409);await f.service.change(id,false,{version:0},f.admin);await f.service.remove(id,f.admin);assert.equal(f.secrets.size,0);assert.throws(()=>f.workspace.getConnection(id),e=>e.status===404);});
test('pause closes an active browser context before waiting for its queued operation to drain',async t=>{const f=fixture(t),id=f.connection.id;let release,closed=false;const gate=new Promise(r=>release=r);f.manager.sessions.set(id,{context:{close:async()=>{closed=true;release();}}});const work=f.manager.run(id,()=>gate);const stopping=f.service.change(id,false,{version:0},f.admin);try{await new Promise(r=>setImmediate(r));await new Promise(r=>setImmediate(r));assert.equal(closed,true);}finally{release();await work;await stopping;}assert.equal(f.secrets.size,2);});
@@ -0,0 +1,22 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {loadForm,loadData}=require('../../src/bpm-readonly-form.cjs');
const {captureDetail}=require('../../src/bpm-order-detail.cjs');
const url='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/海外运营订单评审V13.aspx?tid=100&pid=200';
const reply=(status,location)=>({status:()=>status,headers:()=>location?{location}:{},body:async()=>Buffer.from('fixture')});
test('readonly form permission and network errors never masquerade as an expired login',async()=>{
for(const status of [401,403,502]){await assert.rejects(()=>loadForm({get:async()=>reply(status)},url),e=>e.status===status);await assert.rejects(()=>loadData({post:async()=>reply(status)},new URL(url)),e=>e.status===status);}
});
test('only a proven login redirect is eligible for renewal after a detail read',async()=>{
for(const location of ['https://evil.example/','/maintenance',undefined])await assert.rejects(()=>loadData({post:async()=>reply(302,location)},new URL(url)),e=>e.status===502);
const login='https://sso.skyworthdigital.com/realms/skyworthdigital/protocol/openid-connect/auth';
await assert.rejects(()=>loadData({post:async()=>reply(302,login)},new URL(url)),e=>e.status===401);
await assert.rejects(()=>loadForm({get:async()=>reply(302,login)},url),e=>e.status===401);
});
test('legacy strict DOM detail capture preserves non-200 status classification',async()=>{
for(const status of [401,403,502]){
const page={on(){},goto:async()=>reply(status),url:()=>new URL(url).href},context={route:async()=>{},routeWebSocket:async()=>{},addInitScript:async()=>{},newPage:async()=>page,close:async()=>{}},browser={newContext:async()=>context,close:async()=>{}};
await assert.rejects(()=>captureDetail({storageState:{cookies:[],origins:[]},detailUrl:url,processName:'海外运营订单评审',nodeName:'订单专员(生效)',browserFactory:async()=>browser}),e=>e.status===status);
}
});
@@ -0,0 +1,53 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {loadForm,loadData,historyURL}=require('../../src/modules/bpm/order-form.cjs');
const {BpmHistoryClient}=require('../../src/modules/bpm/history-client.cjs');
const formURL='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/FixtureV1.aspx?tid=21';
const response=({status,location,body=''})=>({status:()=>status,headers:()=>location?{location}:{},body:async()=>Buffer.from(body)});
const failures=[
{name:'HTTP401',status:401,want:401},
{name:'HTTP403',status:403,want:403},
{name:'HTTP502',status:502,want:502},
{name:'known same-origin gateway',status:302,location:'/skyworth/sso/open_sso_url',want:401},
{name:'known company SSO',status:302,location:'https://sso.skyworthdigital.com/realms/skyworthdigital/protocol/openid-connect/auth',want:401},
{name:'unknown same-origin redirect',status:302,location:'/maintenance',want:502},
{name:'unrelated login host',status:302,location:'https://sso.skyworthdigital.com.evil.invalid/realms/login',want:502},
{name:'redirect without location',status:302,want:502}
];
for(const fixture of failures){
test('native form HTML preserves '+fixture.name+' classification without following rejected redirects',async()=>{
const calls=[],request={get:async(url,options)=>{calls.push({url,options});return response(fixture);}};
await assert.rejects(loadForm(request,formURL,historyURL,{history:true}),cause=>cause.status===fixture.want);
assert.deepEqual(calls,[{url:formURL,options:{maxRedirects:0,timeout:20000}}]);
});
test('native readonly data preserves '+fixture.name+' classification and its request policy',async()=>{
const calls=[],request={post:async(url,options)=>{calls.push({url,options});return response(fixture);}};
await assert.rejects(loadData(request,new URL(formURL),{history:true}),cause=>cause.status===fixture.want);
assert.deepEqual(calls,[{url:'https://bpm.skyworthdigital.com/YZSoft/BPM/XMLService/DataProvider.ashx',options:{data:'<?xml version="1.0"?><Requests><Params><Method>GetFormReadData</Method><TID>21</TID></Params></Requests>',headers:{'Content-Type':'text/xml'},maxRedirects:0,timeout:20000}}]);
});
for(const phase of ['portal','business'])test('native history '+phase+' preserves '+fixture.name+' classification without a second request',async()=>{
const calls=[];let disposed=false;
const client=new BpmHistoryClient({requestFactory:async()=>({get:async(route,options)=>{calls.push({route,options});return response(phase==='business'&&route==='/'?{status:200,body:'Yiez.clientId="fixture-token";'}:fixture);},dispose:async()=>{disposed=true;}})});
await assert.rejects(client.scan({cookies:[],origins:[]},['Fixture']),cause=>cause.status===fixture.want);
assert.equal(calls.length,phase==='portal'?1:2);assert.equal(calls.every(call=>call.options.maxRedirects===0),true);assert.equal(disposed,true);
});
}
test('native history treats only an explicit login form as expired when a 200 portal has no token',async()=>{
for(const [body,want]of [['<form id="kc-form-login"></form>',401],['<h1>Maintenance</h1>',502]]){
let calls=0,disposed=false;const client=new BpmHistoryClient({requestFactory:async()=>({get:async()=>{calls++;return response({status:200,body});},dispose:async()=>{disposed=true;}})});
await assert.rejects(client.scan({},['Fixture']),cause=>cause.status===want);assert.equal(calls,1);assert.equal(disposed,true);
}
});
test('native history resolves relative redirects against the actual business request path',async()=>{
const client=new BpmHistoryClient({requestFactory:async()=>({get:async route=>response(route==='/'?{status:200,body:'Yiez.clientId="fixture-token";'}:{status:302,location:'login'}),dispose:async()=>{}})});
await assert.rejects(client.scan({},['Fixture']),cause=>cause.status===502);
});
test('native form follows only its already validated temporary SSO to history form chain',async()=>{
const entry='https://bpm.skyworthdigital.com/sso/ssologin.aspx?'+new URLSearchParams({ReturnUrl:'/YZSoft/Forms/Read.aspx?tid=21',todo_token:'FIXTURE',todo_account:'fixture'}),calls=[];
const request={get:async(url,options)=>{calls.push(url);assert.equal(options.maxRedirects,0);return response(url===entry?{status:302,location:'/YZSoft/Forms/Read.aspx?tid=21'}:url.endsWith('/Read.aspx?tid=21')?{status:302,location:formURL}:{status:200,body:'<form>fixture</form>'});}};
const loaded=await loadForm(request,entry,historyURL,{history:true});assert.equal(loaded.url.href,formURL);assert.equal(loaded.bytes.toString(),'<form>fixture</form>');assert.deepEqual(calls,[entry,'https://bpm.skyworthdigital.com/YZSoft/Forms/Read.aspx?tid=21',formURL]);
});
+28
View File
@@ -0,0 +1,28 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {BpmOrderProvider}=require('../../src/modules/bpm/order-provider.cjs');
test.beforeEach(t=>{t.mock.method(require('../../src/platform/browser.cjs').loadPlaywright().request,'newContext',async()=>{throw Error('Fixture forbids real network requests');});});
const entry='https://bpm.skyworthdigital.com/sso/ssologin.aspx?'+new URLSearchParams({ReturnUrl:'/YZSoft/Forms/Process.aspx?tid=100&pid=200',todo_token:'EPHEMERAL-FIXTURE',todo_account:'fixture'});
const row={source:'todo',portalSource:'portal-v4',instanceId:'100',taskId:'200',processName:'海外运营订单评审',processVersion:'3.2',nodeName:'订单专员(生效)',title:'流程标题 订单号:000123 客户:示例',serialNum:'FIXTURE-SERIAL',receivedAt:'2026-10-23T00:00:00Z',detailUrl:entry};
const connection={id:'c',owner:'owner',status:'connected'},principal={user:{username:'owner',role:'admin'},sessionId:'s'};
test('native todo normalization preserves missing revision rather than inventing zero',()=>{
const {normalizeTodo}=require('../../src/modules/bpm/todo-client.cjs'),raw={taskId:'200',processInstanceId:'100',processName:row.processName,activityName:row.nodeName,processVersion:'3.2',startTime:row.receivedAt,processInstanceSubject:'前缀\n订单号:000123',serialNum:row.serialNum,executionPointerId:entry};
const absent=normalizeTodo(raw,'portal-v4');assert.equal(Object.hasOwn(absent,'revision'),false);assert.equal(absent.title,'前缀\n订单号:000123');
const zero=normalizeTodo({...raw,revision:0},'portal-v4');assert.equal(zero.revision,0);assert.equal(zero.revisionSource,'bpm.revision');
});
function manager(){let locked=false;const calls={ensure:0,observe:[]};return {calls,sessions:new Map(),authorize(){},vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})}),async run(id,work){assert.equal(locked,false);locked=true;try{return await work();}finally{locked=false;}},observe(id,source,cause){calls.observe.push(cause?.status||200);},async ensure(){assert.equal(locked,false);calls.ensure++;return {status:'connected'};}};}
test('provider releases its read lock before one standard renewal and never renews forbidden or network errors',async()=>{
for(const status of [401,403,502]){const m=manager();let reads=0;const p=new BpmOrderProvider({manager:m,client:{scan:async()=>{reads++;if(reads===1)throw Object.assign(Error('fixture'),{status});return [row];}}});if(status===401){assert.equal((await p.scan(connection,principal)).length,1);assert.equal(reads,2);assert.equal(m.calls.ensure,1);}else{await assert.rejects(()=>p.scan(connection,principal),e=>e.status===status);assert.equal(reads,1);assert.equal(m.calls.ensure,0);}}
});
test('native provider uses proven readonly form hydration and retains list and form versions independently',async()=>{
const m=manager();let reads=0,captures=0;const p=new BpmOrderProvider({manager:m,client:{scan:async()=>{reads++;return [row];}},readonlyReader:async input=>{captures++;assert.equal(input.nodeName,'订单专员(生效)');assert.equal(input.listProcessVersion,'3.2');assert.equal(input.detailUrl,entry);return {detailUrl:'https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/海外运营订单评审V13.aspx?tid=100&pid=200',detail:{tid:'100',pid:'200',processVersion:'V13',formVersion:'V13',formPath:'/YZSoft/Forms/XForm/海外运营订单评审V13.aspx',fields:{'OFR_WY_Applicant.OrderNum':'000123'},fieldSources:{'OFR_WY_Applicant.OrderNum':{source:'DataProvider.GetFormProcessData'}}},snapshot:input.fieldsOnly?null:{html:'<form>000123</form>',styles:[]},capturedAt:'2026-10-23T00:01:00Z',evidenceHash:'fixture-hash'};}});
const scanned=(await p.scan(connection,principal))[0],captured=await p.capture(connection,principal,scanned);
assert.equal(reads,2);assert.equal(captures,1);assert.equal(captured.sample.processVersion,'3.2');assert.equal(captured.sample.formVersion,'V13');assert.equal(Object.hasOwn(captured.sample,'revision'),false);assert.equal(captured.sample.brief,row.title);assert.equal(captured.snapshot.processVersion,'3.2');assert.equal(captured.snapshot.formVersion,'V13');assert.deepEqual(captured.snapshot.fields,[{path:'OFR_WY_Applicant.OrderNum',label:'OFR_WY_Applicant.OrderNum',value:'000123'}]);assert.equal(JSON.stringify(captured).includes('EPHEMERAL-FIXTURE'),false);
});
test('changed current task summary or node blocks native capture before any form request',async()=>{
let current=row,captures=0;const p=new BpmOrderProvider({manager:manager(),client:{scan:async()=>[current]},readonlyReader:async()=>{captures++;throw Error('must not capture');}});const scanned=(await p.scan(connection,principal))[0];
for(const changed of [{...row,title:'changed'},{...row,nodeName:'BOM确认'}]){current=changed;await assert.rejects(()=>p.capture(connection,principal,scanned),/变化|不一致/);}assert.equal(captures,0);
});
+12
View File
@@ -0,0 +1,12 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),{BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs');
const actor={username:'admin',role:'admin'};
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'records-ledger-'));let workspace=new WorkspaceStore(path.join(dir,'workspace'));const scan=new BpmScanStore(path.join(dir,'scan'));t.after(()=>{scan.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});const c=workspace.createConnection({name:'原业务连接',owner:'admin'},actor,[actor]);workspace.updateConnectionSession(c.id,{status:'connected',identity:'原账号',checkedAt:'2026-10-20T01:00:00Z',checks:{portal:{ok:true,message:'ok'}}},actor);return {dir,scan,c,get workspace(){return workspace;},restart(){workspace.close();workspace=new WorkspaceStore(path.join(dir,'workspace'));}};}
const row=(taskId,processName='海外运营订单评审',day='2026-10-20')=>({source:'portal-v4',taskId,processName,subject:'订单号:TEST-'+taskId,arrivalDay:day,arrivedAt:day+'T01:00:00.000Z',activityName:'通知节点'});
function query(f,filters={}){const modulePath='../../src/modules/bpm/records-query.cjs';let queryLedger;try{({queryLedger}=require(modulePath));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}assert.equal(typeof queryLedger,'function','ledger query must be implemented');return queryLedger({store:f.scan,workspace:f.workspace,processNames:['海外运营订单评审']},filters);}
test('deletion preserves a safe source archive across restart, while pause stays current',t=>{const f=fixture(t);f.scan.complete(f.scan.begin(f.c.id,'admin'),f.c.id,[row('one')]);f.workspace.disableConnection(f.c.id,actor);assert.equal(query(f).total,1);f.workspace.deleteConnection(f.c.id,actor);f.restart();assert.equal(query(f).total,0);const old=query(f,{scope:'archived'});assert.equal(old.total,1);assert.equal(old.items[0].origin.name,'原业务连接');assert.equal(old.items[0].origin.identity,'原账号');assert.equal(old.items[0].origin.status,'archived');assert.ok(old.items[0].origin.archivedAt);assert.equal(/cookie|password|token/i.test(JSON.stringify(old)),false);});
test('legacy orphans remain searchable without inventing a source identity or deletion date',t=>{const f=fixture(t);f.scan.complete(f.scan.begin('old-source','old'),'old-source',[row('old')]);const old=query(f,{scope:'archived'});assert.equal(old.total,1);assert.equal(old.items[0].origin.id,'old-source');assert.equal(old.items[0].origin.identity,'');assert.equal(old.items[0].origin.archivedAt,null);assert.equal(old.items[0].origin.missing,true);assert.equal(query(f,{scope:'archived',connectionId:'old-source',q:'TEST-old'}).total,1);});
test('ledger filters exact configured processes, both arrival types, dates and stable pages',t=>{const f=fixture(t);const rows=[row('a'),row('b'),row('c','采购审批'),{...row('d'),source:'todo:portal-v4',kind:'todo',recordKey:'instance-d'}];f.scan.complete(f.scan.begin(f.c.id,'admin'),f.c.id,rows);const first=query(f,{pageSize:1});assert.equal(first.total,3);assert.equal(first.items.length,1);const second=query(f,{pageSize:1,page:2});assert.notEqual(first.items[0].taskId,second.items[0].taskId);assert.equal(query(f,{business:'all'}).total,4);assert.equal(query(f,{kind:'todo'}).total,1);assert.equal(query(f,{from:'2026-10-20',to:'2026-10-20'}).total,3);assert.equal(query(f,{from:'2026-10-21'}).total,0);for(const filters of [{scope:'bad'},{business:'bad'},{kind:'bad'},{page:0},{pageSize:101},{from:'2026-02-30'},{from:'2026-10-21',to:'2026-10-20'}])assert.throws(()=>query(f,filters),e=>e.status===400);assert.equal(f.scan.list().total,3);});
test('rescan retains the first observed source snapshot and preserves arrival identity',t=>{const f=fixture(t);const original=f.workspace.getConnection(f.c.id);f.scan.complete(f.scan.begin(f.c.id,'admin'),f.c.id,[row('a')],original);f.workspace.updateConnectionSession(f.c.id,{status:'connected',identity:'新账号',checkedAt:'2026-10-20T02:00:00Z',checks:{portal:{ok:true,message:'ok'}}},actor);f.scan.complete(f.scan.begin(f.c.id,'admin'),f.c.id,[row('a')],f.workspace.getConnection(f.c.id));const records=query(f);assert.equal(records.total,1);assert.equal(records.items[0].origin.identity,'原账号');});
test('ledger clamps a valid page beyond the last page and reports page one for empty results',t=>{const f=fixture(t);f.scan.complete(f.scan.begin(f.c.id,'admin'),f.c.id,Array.from({length:101},(_,i)=>row(String(i))));const last=query(f,{page:99});assert.equal(last.page,5);assert.equal(last.items.length,1);const empty=query(f,{q:'absent',page:99});assert.equal(empty.page,1);assert.equal(empty.total,0);assert.deepEqual(empty.items,[]);});
+93
View File
@@ -0,0 +1,93 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const fs=require('node:fs'),os=require('node:os'),path=require('node:path'),http=require('node:http');
const {isLoginRedirect}=require('../../src/modules/bpm/auth-redirect.cjs');
const {BpmAccessClient}=require('../../src/modules/bpm/access-client.cjs');
const {BpmListClient,normalizeArrival}=require('../../src/modules/bpm/list-client.cjs');
const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
const connection={id:'c',owner:'owner',status:'connected'},principal={user:{username:'owner',role:'operator'},sessionId:'fixture-session'};
const state={cookies:[],origins:[]};
async function serverFixture(t,handler){
const server=http.createServer(handler);await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
t.after(async()=>{server.closeAllConnections();await new Promise(resolve=>server.close(resolve));});
return 'http://127.0.0.1:'+server.address().port+'/';
}
function managerFixture(t,options={}){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-runtime-renew-'));
const manager=new BpmSessionManager({stateDir:dir,...options});
manager._vault={read:async()=>({storageState:state}),destroy(){}};
t.after(async()=>{await manager.shutdown();fs.rmSync(dir,{recursive:true,force:true});});return manager;
}
test('only the exact known same-origin SSO gateway is login evidence',()=>{
const base='https://bpmn.skyworthdigital.com/';
for(const location of ['/skyworth/sso/open_sso_url','/skyworth/sso/open_sso_url?returnUrl=%2F','https://bpmn.skyworthdigital.com/skyworth/sso/open_sso_url'])assert.equal(isLoginRedirect(location,base),true,location);
for(const location of ['/skyworth/sso/open_sso_url/','/skyworth/sso/open_sso_url.extra','/other/skyworth/sso/open_sso_url','/SKYWORTH/sso/open_sso_url','https://bpmn.skyworthdigital.com.evil.invalid/skyworth/sso/open_sso_url','https://evil.invalid/skyworth/sso/open_sso_url','http://bpmn.skyworthdigital.com/skyworth/sso/open_sso_url','https://user@bpmn.skyworthdigital.com/skyworth/sso/open_sso_url','/maintenance'])assert.equal(isLoginRedirect(location,base),false,location);
});
test('saved-session access and business reads classify the same gateway as expired without following it',async t=>{
let mode='login',gatewayHits=0;
const baseURL=await serverFixture(t,(req,res)=>{if(req.url!=='/'){gatewayHits++;res.writeHead(500);return res.end();}if(mode==='login')res.writeHead(302,{Location:'/skyworth/sso/open_sso_url'});else if(mode==='other')res.writeHead(302,{Location:'/maintenance'});else res.writeHead(+mode);res.end();});
const access=new BpmAccessClient({baseURL,allowLocal:true}),list=new BpmListClient({baseURL,allowLocal:true});
assert.equal((await access.check(state)).status,'login_required');await assert.rejects(list.scan(state),cause=>cause.status===401);
for(const [value,status,todo]of [['403',403,'forbidden'],['502',502,'error'],['other',502,'error']]){mode=value;const result=await access.check(state);assert.equal(result.status,'error');assert.equal(result.todo,todo);await assert.rejects(list.scan(state),cause=>cause.status===status);}
assert.equal(gatewayHits,0);
});
test('notification task 401 invalidates recent authentication before standard ensure',async t=>{
let probes=0;
const manager=managerFixture(t,{accessClient:{check:async()=>{probes++;return {status:'error',checkedAt:new Date().toISOString(),checks:{portal:{ok:false,message:'offline'}},todo:'error'};}}});
manager.notificationClientFactory=()=>({scan:async()=>{throw Object.assign(Error('expired'),{status:401});}});
manager.observe('c','inform');assert.equal(manager.health.recent('c'),true);
await assert.rejects(manager.scanOrderTasks(connection,principal),cause=>cause.status===401);
assert.equal(manager.health.recent('c'),false);assert.equal((await manager.ensure(connection,principal)).status,'error');assert.equal(probes,1);
});
test('detail read 401 invalidates recent authentication and preserves failure classification',async t=>{
const manager=managerFixture(t);manager.detailReader=async()=>{throw Object.assign(Error('expired'),{status:401});};manager.observe('c','inform');
await assert.rejects(manager.captureOrderDetail(connection,principal,{detailUrl:'unused'}),cause=>cause.status===401);
assert.equal(manager.health.recent('c'),false);assert.equal(manager.health.snapshot('c').inform.status,'login_required');
});
test('business 401 releases its connection lock before real saved-account renewal and one re-read',async t=>{
let submissions=0,authenticated=false,mode='normal',businessReads=0;
const baseURL=await serverFixture(t,(req,res)=>{
res.setHeader('Content-Type','text/html; charset=utf-8');
if(req.url==='/authenticate'&&req.method==='POST'){
let body='';req.on('data',chunk=>body+=chunk);req.on('end',()=>{submissions++;const fields=new URLSearchParams(body);if(fields.get('username')==='Fixture User'&&fields.get('password')==='fixture-password'){authenticated=true;res.setHeader('Set-Cookie','auth=valid; HttpOnly; Path=/');}res.writeHead(302,{Location:'/'});res.end();});return;
}
if(req.url==='/skyworth/sso/open_sso_url'||req.url==='/login')return res.end('<form method="POST" action="/authenticate"><input id="username" name="username" type="text"><input id="password" name="password" type="password"><button id="submit" type="submit">Login</button></form>');
const logged=authenticated&&(req.headers.cookie||'').includes('auth=valid');
if(req.url==='/'){
if(mode==='403'||mode==='502'){res.writeHead(+mode);return res.end();}
if(!logged){res.writeHead(302,{Location:'/skyworth/sso/open_sso_url'});return res.end();}
return res.end('<script>Yiez.clientId="fixture-token";</script><a class="yz-btn-signinuser"><span class="x-btn-inner">Fixture User</span></a>');
}
businessReads++;res.setHeader('Content-Type','application/json');res.end(JSON.stringify({children:[],total:0}));
});
const origin=new URL(baseURL).origin,dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-real-renew-'));
const manager=new BpmSessionManager({stateDir:dir,urls:{main:baseURL},allowedOrigins:[origin],loginForms:{[origin]:{username:'#username',password:'#password',submit:'#submit'}},accessClient:new BpmAccessClient({baseURL,allowLocal:true}),browserFactory:()=>loadPlaywright().chromium.launch(browserOptions()),probe:async page=>{const marker=page.locator('a.yz-btn-signinuser .x-btn-inner'),identity=await marker.count()?await marker.innerText():'';return {ok:!!identity,identity};}});
t.after(async()=>{await manager.shutdown();fs.rmSync(dir,{recursive:true,force:true});});
manager.listClient=new BpmListClient({baseURL,allowLocal:true});await manager.saveAccount(connection,principal,{username:'Fixture User',password:'fixture-password'});await manager.vault().write(connection.id,{storageState:state});
manager.observe('c','inform');assert.deepEqual(await manager.scanArrivals(connection,principal),[]);assert.equal(submissions,1);assert.equal(businessReads,2);assert.equal(manager.sessions.size,0);
for(const status of ['403','502']){mode=status;await assert.rejects(manager.scanArrivals(connection,principal),cause=>cause.status===+status);assert.equal(submissions,1);}
});
test('native notification clients keep per-connection ephemeral entry maps',t=>{
const manager=managerFixture(t),a=manager.notificationClientFor('a'),b=manager.notificationClientFor('b');
assert.equal(manager.notificationClientFor('a'),a);assert.notEqual(a,b);assert.notEqual(a.entries,b.entries);
a.entries.set('fixture',{entry:'ephemeral-a'});assert.equal(b.entries.size,0);
});
test('normalization retains validated explicit detail references through the native loader',()=>{
const detailUrl='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/PV1.aspx?tid=1&pid=2';
assert.equal(normalizeArrival({taskId:'1',startTime:'2026-10-23T01:00:00Z',detailUrl},'portal-v4').detailUrl,detailUrl);
});
test('native detail loader reaches the canonical capture authentication guard',async t=>{
const detailUrl='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/PV1.aspx?tid=1&pid=2';
const manager=managerFixture(t);manager._vault={read:async()=>null,destroy(){}};
await assert.rejects(manager.captureOrderDetail(connection,principal,{detailUrl,processName:'P',activityName:'node'}),cause=>cause.status===401);
});
+16
View File
@@ -0,0 +1,16 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs');
test('committed delivery survives restart encrypted and acknowledgement releases only transport payload',t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'scan-delivery-'));let store=new BpmScanStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
const runId=store.begin('c','synthetic','todo'),payload={runId,connectionId:'c',rows:[{title:'synthetic-private-title'}],startedAt:'2026-10-21T01:00:00Z',finishedAt:'2026-10-21T01:00:01Z'};
store.complete(runId,'c',[{arrivalDay:'2026-10-21',taskId:'t',source:'todo:fixture'}],{id:'c',owner:'synthetic'},{delivery:payload});
const bytes=store.db.prepare('SELECT payload FROM execution_deliveries WHERE run_id=?').get(runId).payload;assert.equal(Buffer.from(bytes).includes(Buffer.from('synthetic-private-title')),false);
store.close();store=new BpmScanStore(dir);assert.deepEqual(store.deliveries.pending('c',Date.now())[0].payload,payload);store.deliveries.acknowledge(runId);assert.equal(store.deliveries.summary('c').pending,0);
assert.equal(store.db.prepare('SELECT payload FROM execution_deliveries WHERE run_id=?').get(runId).payload,null);assert.equal(store.status().runs.find(run=>run.id===runId).status,'success');assert.equal(store.list({kind:'todo'}).total,1);
});
test('a damaged transport payload remains visible as delivery failure without falsifying its successful read',t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'scan-delivery-damaged-')),store=new BpmScanStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
const id=store.begin('c','synthetic','todo');store.complete(id,'c',[],{id:'c'},{delivery:{runId:id,connectionId:'c',rows:[],startedAt:'2026-10-21T01:00:00Z',finishedAt:'2026-10-21T01:00:01Z'}});
store.db.prepare('UPDATE execution_deliveries SET payload=? WHERE run_id=?').run(Buffer.from('damaged'),id);assert.deepEqual(store.deliveries.pending('c',Date.now()),[]);assert.equal(store.deliveries.summary('c').status,'error');assert.equal(store.deliveries.summary('c').pending,1);assert.equal(store.status().runs.find(run=>run.id===id).status,'success');
});
+8
View File
@@ -0,0 +1,8 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');const {signalrHub}=require('../fixtures/signalr-hub.cjs');
let Client;try{Client=require('../../src/modules/bpm/signalr-client.cjs').BpmSignalRClient;}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
const state={cookies:[],origins:[]};
test('real hub handshake accepts only known change hints and sends no business invocation',async t=>{assert.equal(typeof Client,'function');const hub=await signalrHub(t),events=[];let notify;const received=new Promise(r=>notify=r);const client=new Client({baseURL:hub.baseURL,allowLocal:true}),handle=await client.connect(state,{onEvent:name=>{events.push(name);if(events.length===2)notify();}});hub.emit({type:1,target:'worklistChanged',arguments:[{private:'not passed'}]});hub.emit({type:1,target:'executeApproval',arguments:[]});hub.emit({type:1,target:'informlistChanged',arguments:[]});await received;await handle.stop();assert.deepEqual(events,['worklistChanged','informlistChanged']);assert.deepEqual(hub.messages[0],{protocol:'json',version:1});assert.equal(hub.messages.some(m=>m.type===1),false);});
test('missing handshake and heartbeat fail with bounded safe reasons and release the connection',async t=>{assert.equal(typeof Client,'function');const missing=await signalrHub(t,{handshake:false});await assert.rejects(new Client({baseURL:missing.baseURL,allowLocal:true,handshakeMs:70}).connect(state),e=>e.code==='BPM_HUB_HANDSHAKE');const quiet=await signalrHub(t,{pings:false});let close;const closed=new Promise(r=>close=r);const handle=await new Client({baseURL:quiet.baseURL,allowLocal:true,heartbeatMs:80,pingMs:30}).connect(state,{onClose:close});assert.equal((await closed).reason,'heartbeat_timeout');await handle.stop();});
test('abort and unauthorized negotiation never expose credentials or leave retry work running',async t=>{assert.equal(typeof Client,'function');const denied=await signalrHub(t,{authStatus:401});await assert.rejects(new Client({baseURL:denied.baseURL,allowLocal:true}).connect(state),e=>e.status===401&&!e.message.includes('fixture-token'));const controller=new AbortController();controller.abort();await assert.rejects(new Client({baseURL:denied.baseURL,allowLocal:true}).connect(state,{signal:controller.signal}),e=>e.name==='AbortError');});
test('oversized or malformed hub frames close safely instead of delivering a forged event',async t=>{assert.equal(typeof Client,'function');const hub=await signalrHub(t),events=[];let close;const closed=new Promise(r=>close=r);const handle=await new Client({baseURL:hub.baseURL,allowLocal:true,maxFrameBytes:256}).connect(state,{onEvent:n=>events.push(n),onClose:close});hub.raw('x'.repeat(300));assert.equal((await closed).reason,'invalid_frame');assert.deepEqual(events,[]);await handle.stop();});
+28
View File
@@ -0,0 +1,28 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),cp=require('node:child_process');
let safeDiagnostic;try{safeDiagnostic=require('../../src/shared/diagnostics.cjs').safeDiagnostic;}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
test('storage diagnostics preserve useful stages and codes without messages, paths or secrets',()=>{
assert.equal(typeof safeDiagnostic,'function');
const cause=Object.assign(Error('synthetic-secret password=value C:/private/form'),{code:'EACCES',path:'C:/private/form'}),error=Object.assign(Error('public message',{cause}),{stage:'key_read',code:'STORAGE_UNAVAILABLE',status:503});
const data=safeDiagnostic(error);assert.equal(data.stage,'key_read');assert.equal(data.causeCode,'EACCES');assert.doesNotMatch(JSON.stringify(data),/synthetic-secret|password|private|form|public message/);
});
test('a secured directory can be reused but replacement must be secured again',{skip:process.platform!=='win32'},t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'vault-acl-reuse-'));let unavailable=false,calls=0;
t.mock.method(cp,'execFileSync',()=>{calls++;if(unavailable)throw Object.assign(Error('synthetic shell failure'),{code:'ETIMEDOUT'});return '';});
delete require.cache[require.resolve('../../src/platform/security/vault.cjs')];const {BpmVault}=require('../../src/platform/security/vault.cjs');
t.after(()=>{fs.rmSync(dir,{recursive:true,force:true});fs.rmSync(dir+'-old',{recursive:true,force:true});});
const first=new BpmVault({stateDir:dir});first.destroy();unavailable=true;
const second=new BpmVault({stateDir:dir});second.destroy();assert.equal(calls,1);
fs.renameSync(dir,dir+'-old');fs.mkdirSync(dir);
assert.throws(()=>new BpmVault({stateDir:dir}),error=>error.status===503&&error.stage==='directory_permissions'&&error.cause.code==='ETIMEDOUT');
});
test('key read failures retain the original cause behind a safe public 503',{skip:process.platform!=='win32'},t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'vault-cause-'));
t.mock.method(cp,'execFileSync',()=> '');
const originalExists=fs.existsSync,originalRead=fs.readFileSync;
t.mock.method(fs,'existsSync',file=>/[\\/]bpm-keys[\\/].+\.key$/.test(String(file))?true:originalExists(file));
t.mock.method(fs,'readFileSync',(file,...args)=>{if(/[\\/]bpm-keys[\\/].+\.key$/.test(String(file)))throw Object.assign(Error('synthetic-secret'),{code:'EACCES'});return originalRead(file,...args);});
delete require.cache[require.resolve('../../src/platform/security/vault.cjs')];const {BpmVault}=require('../../src/platform/security/vault.cjs'),vault=new BpmVault({stateDir:dir});
t.after(()=>{vault.destroy();fs.rmSync(dir,{recursive:true,force:true});});
assert.throws(()=>vault.encode('synthetic',{value:'synthetic'}),error=>error.status===503&&error.stage==='key_read'&&error.cause.code==='EACCES'&&!error.message.includes('synthetic-secret'));
});
+7
View File
@@ -0,0 +1,7 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),cp=require('node:child_process');
function fixture(t,protection){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'vault-retry-')),previous=process.env.LOCALAPPDATA;process.env.LOCALAPPDATA=dir;const logs=[];t.mock.method(console,'error',(...args)=>logs.push(args.join(' ')));t.mock.method(cp,'execFileSync',(_,args,options)=>{const script=args.at(-1);if(script.includes('::Protect('))return protection(options);if(script.includes('::Unprotect('))return options.input;return '';});delete require.cache[require.resolve('../../src/platform/security/vault.cjs')];const {BpmVault}=require('../../src/platform/security/vault.cjs');let vault;t.after(()=>{vault?.destroy();if(previous===undefined)delete process.env.LOCALAPPDATA;else process.env.LOCALAPPDATA=previous;fs.rmSync(dir,{recursive:true,force:true});});return {dir,logs,create:()=>vault=new BpmVault({stateDir:path.join(dir,'state')}),keys:()=>fs.readdirSync(path.join(dir,'OrderNotificationAutomation','bpm-keys'))};}
test('one timed-out protection attempt retries the same key and commits one readable encrypted identity',{skip:process.platform!=='win32'},t=>{
const inputs=[];const f=fixture(t,options=>{inputs.push(options.input);if(inputs.length===1)throw Object.assign(Error('synthetic-secret timeout'),{code:'ETIMEDOUT'});return options.input;});const vault=f.create(),value={fixture:'private synthetic data'},bytes=vault.encode('sample',value);assert.deepEqual(vault.decode('sample',bytes),value);assert.equal(inputs.length,2);assert.equal(inputs[0],inputs[1]);assert.equal(f.keys().length,1);assert.equal(f.logs.length,1);assert.doesNotMatch(f.logs.join(''),/synthetic-secret|private|ProtectedData|base64/i);assert.equal(bytes.includes(Buffer.from(value.fixture)),false);
});
for(const code of ['ETIMEDOUT','EACCES'])test('protection '+code+' stays bounded and never publishes a partial key',{skip:process.platform!=='win32'},t=>{let calls=0;const f=fixture(t,()=>{calls++;throw Object.assign(Error('synthetic-secret '+code),{code});}),vault=f.create();assert.throws(()=>vault.encode('sample',{fixture:'private'}),e=>e.status===503&&e.stage==='key_protect'&&e.cause.code===code);assert.equal(calls,code==='ETIMEDOUT'?2:1);assert.equal(f.keys().length,0);assert.equal(f.logs.length,code==='ETIMEDOUT'?1:0);assert.doesNotMatch(f.logs.join(''),/synthetic-secret|private/);});
@@ -4,7 +4,7 @@ const fs=require('node:fs');
const os=require('node:os');
const path=require('node:path');
test('workbench sessions persist for thirty days, renew with activity and revoke without storing raw tokens',t=>{
let SessionStore;try{({SessionStore}=require('../src/dashboard-sessions.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
let SessionStore;try{({SessionStore}=require('../../src/modules/dashboard/sessions.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
assert.equal(typeof SessionStore,'function','persistent workbench sessions missing');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'workbench-auth-'));let store;
t.after(()=>{store?.close();fs.rmSync(dir,{recursive:true,force:true});});
@@ -4,7 +4,7 @@ const fs=require('node:fs');
const os=require('node:os');
const path=require('node:path');
let Store, nextSlots;
try { ({Store}=require('../src/dashboard-store.cjs')); ({nextSlots}=require('../src/schedule.cjs')); } catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
try { ({Store}=require('../../src/modules/dashboard/store.cjs')); ({nextSlots}=require('../../src/shared/schedule.cjs')); } catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
function fixture(t){assert.equal(typeof Store,'function','dashboard store not implemented');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'dashboard-store-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));return {dir,store:new Store(dir)};}
test('configuration is persisted and stale edits cannot overwrite another colleague',t=>{
const {dir,store}=fixture(t);
+21
View File
@@ -0,0 +1,21 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs');
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'job-retention-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));return {dir,store:new Store(dir)};}
test('legacy 5001 PDF jobs migrate intact and an additional export never evicts their evidence',t=>{
const f=fixture(t),legacy={...f.store.data,jobs:Array.from({length:5001},(_,i)=>({jobId:'job-'+String(i).padStart(5,'0'),status:'success',filename:'record-'+i+'.pdf',metadata:{order:'ORDER-'+i},updatedAt:'2026-10-21T00:00:00Z'}))};
f.store.database(db=>db.prepare('UPDATE dashboard_state SET value=? WHERE id=1').run(JSON.stringify(legacy)));
const store=new Store(f.dir);store.recordJob({jobId:'latest',status:'success',filename:'new.pdf'});assert.equal(store.jobs().length,5002);assert.ok(store.jobs().some(job=>job.jobId==='job-00000'));
const restarted=new Store(f.dir);assert.equal(restarted.jobs().length,5002);assert.equal(typeof restarted.job,'function');assert.equal(restarted.job('job-00000').filename,'record-0.pdf');
const state=restarted.database(db=>JSON.parse(db.prepare('SELECT value FROM dashboard_state WHERE id=1').get().value));assert.ok(!state.jobs,'job rows must not remain in the growing settings JSON');
});
test('SQL job pagination clamps, searches literal wildcards and retains a stable empty first page',t=>{
const f=fixture(t);assert.equal(typeof f.store.jobPage,'function');for(let i=0;i<76;i++)f.store.recordJob({jobId:'j-'+i,status:'running',metadata:{order:i===0?'LITERAL_%':'ORDER-'+i}});
const last=f.store.jobPage({page:99,pageSize:25});assert.equal(last.page,4);assert.equal(last.jobs.length,1);assert.equal(last.total,76);
assert.equal(f.store.jobPage({q:'_%'}).total,1);const empty=f.store.jobPage({status:'interrupted',page:99});assert.equal(empty.page,1);assert.equal(empty.total,0);assert.deepEqual(empty.jobs,[]);
});
test('job and audit updates roll back together when SQLite rejects the new evidence row',t=>{
const f=fixture(t),exists=f.store.database(db=>db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='pdf_jobs'").get());assert.ok(exists,'jobs require their own durable table');
f.store.database(db=>db.exec("CREATE TRIGGER reject_job BEFORE INSERT ON pdf_jobs BEGIN SELECT RAISE(ABORT,'synthetic database failure'); END"));const before=f.store.audit();
assert.throws(()=>f.store.recordJob({jobId:'rejected',status:'error',error:'synthetic'}),/synthetic/);assert.deepEqual(f.store.audit(),before);assert.equal(f.store.jobs().length,0);
});
+10
View File
@@ -0,0 +1,10 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
test('capacity and history export preserve all rows and expose only authorized safe fields',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maintenance-')),store=new Store(path.join(dir,'dashboard'));store.bootstrap('admin','Synthetic-password-123');store.addUser({username:'viewer',password:'Synthetic-password-123',role:'viewer'},'admin');store.recordJob({jobId:'oldest',status:'success',path:'PRIVATE_PATH',metadata:{order:'ORDER-1',form:'PRIVATE_FORM',password:'PRIVATE_PASSWORD'},error:'PRIVATE_ERROR'});fs.mkdirSync(path.join(dir,'pdf'));fs.writeFileSync(path.join(dir,'pdf','one.pdf'),'%PDF-fixture');const server=createDashboard({store,outputDir:path.join(dir,'pdf')});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;
const login=async username=>(await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({username,password:'Synthetic-password-123'})})).headers.get('set-cookie').split(';')[0];
assert.equal((await fetch(base+'/api/maintenance')).status,401);const viewer=await login('viewer');assert.equal((await fetch(base+'/api/maintenance',{headers:{Cookie:viewer}})).status,403);const admin=await login('admin'),headers={Cookie:admin};
const capacity=await fetch(base+'/api/maintenance',{headers});assert.equal(capacity.status,200);const data=await capacity.json();assert.equal(data.retention,'permanent');assert.equal(data.jobs.total,1);assert.equal(data.pdf.files,1);assert.equal(data.pdf.bytes,12);
const exported=await fetch(base+'/api/jobs/export',{headers});assert.equal(exported.status,200);const body=await exported.text();assert.match(body,/ORDER-1/);assert.doesNotMatch(body,/PRIVATE_/);assert.equal(JSON.parse(body.trim()).jobId,'oldest');assert.equal(store.jobs().length,1);
});
+25
View File
@@ -0,0 +1,25 @@
'use strict';
// Fixtures must follow the same explicit draft/check/confirmation lifecycle as the UI.
function activateFieldMapping(store,input,actor={username:'admin',role:'admin'}){
const draft=store.saveAdapter(input,actor),key=draft.id+':'+draft.version;
const check=store.checkMapping({id:draft.id,version:draft.version,sampleId:input.sampleId,idempotencyKey:'check:'+key},actor);
if(!check.valid)throw Error('Fixture mapping check failed: '+check.result.issues.join(';'));
return store.activateMapping({id:draft.id,version:draft.version,checkId:check.id,idempotencyKey:'activate:'+key},actor).active;
}
function activateReferenceMapping(store,referenceId='bs-change',overrides={},actor={username:'admin',role:'admin'}){
const reference=require('../../src/modules/order-rules/catalog.cjs').adapters.find(adapter=>adapter.id===referenceId);
if(!reference)throw Error('Unknown fixture reference mapping: '+referenceId);
const sample={...structuredClone(reference.sample),...structuredClone(overrides),demo:false};
sample.fields={...structuredClone(reference.sample.fields),...structuredClone(overrides.fields||{})};
if(!Object.hasOwn(overrides,'title'))sample.title='订单号:'+sample.fields[reference.fields.orderNo];
const captured=store.recordCapture({sample,taskId:'fixture:'+referenceId+':'+sample.taskId,snapshot:{processVersion:sample.processVersion,fields:Object.entries(sample.fields).map(([path,value])=>({path,value}))}});
const previous=store.all('field-mapping-drafts').find(draft=>draft.processName===sample.processName&&draft.processVersion===sample.processVersion);
const sources={...Object.fromEntries(Object.entries(reference.fields).filter(([key])=>key!=='brief').map(([key,path])=>[key,{type:'form',path}])),brief:{type:'title'}};
const key='reference:'+referenceId+':'+(previous?.version||0)+':'+captured.id;
const draft=store.saveMapping({processName:sample.processName,processVersion:sample.processVersion,sampleId:captured.id,sources,version:previous?.version||0,idempotencyKey:'save:'+key},actor);
const check=store.checkMapping({id:draft.id,version:draft.version,sampleId:captured.id,idempotencyKey:'check:'+key},actor);
if(!check.valid)throw Error('Fixture reference mapping check failed: '+check.result.issues.join(';'));
const active=store.activateMapping({id:draft.id,version:draft.version,checkId:check.id,idempotencyKey:'activate:'+key},actor).active;
return {sample,captured,active};
}
module.exports={activateFieldMapping,activateReferenceMapping};
+22
View File
@@ -0,0 +1,22 @@
'use strict';
// Test-only runtime. Exercises ordinary password authentication without background jobs.
const path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs');
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
const {MailStore}=require('../../src/modules/mail/store.cjs');
const {MailService}=require('../../src/modules/mail/service.cjs');
const {createDashboard}=require('../../src/app/dashboard.cjs');
async function startTestDashboard({stateDir,mailHistory=false,executionFactory}){
const store=new Store(path.join(stateDir,'accounts'));store.bootstrap('admin','Test-password-123');
const workspace=new WorkspaceStore(path.join(stateDir,'workspace'));
const orderRules=new RuleStore(path.join(stateDir,'order-rules'));
const mailStore=mailHistory?new MailStore(path.join(stateDir,'mail')):null;
const mail=mailStore?new MailService({store:mailStore}):null;
const orderExecution=executionFactory?.({orderRules,workspace});
const server=createDashboard({store,workspace,orderRules,orderExecution,mail,outputDir:stateDir});
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);});
return {server,store,workspace,orderRules,mail,orderExecution,async close(){await orderExecution?.stop();await mail?.stop();server.closeAllConnections();await new Promise(r=>server.close(r));workspace.close();orderRules.close();mailStore?.close();}};
}
async function login(page){await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();}
module.exports={startTestDashboard,login};
+1 -1
View File
@@ -1,5 +1,5 @@
'use strict';
const fs=require('node:fs'),http=require('node:http'),{respondToPing}=require('../../src/service-ping.cjs');
const fs=require('node:fs'),http=require('node:http'),{respondToPing}=require('../../src/platform/service/ping.cjs');
const file=process.env.ORDER_FIXTURE_COUNT,generation=(fs.existsSync(file)?Number(fs.readFileSync(file,'utf8')):0)+1;fs.writeFileSync(file,String(generation));
const startedAt=new Date().toISOString();let hang=false;
const server=http.createServer((req,res)=>{fs.writeFileSync(file+'.heartbeat',String(req.headers['x-order-watchdog']||''));if(hang)return;respondToPing(req,res,{token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt});});
+14
View File
@@ -0,0 +1,14 @@
'use strict';
const fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
const {startTestDashboard,login}=require('./dashboard-runtime.cjs');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function orderDrivenUI(t,route='#rule-fields'){
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-driven-ui-')),runtime=await startTestDashboard({stateDir:dir,executionFactory:({orderRules,workspace})=>new (require('../../src/modules/order-execution/coordinator.cjs').OrderExecutionCoordinator)({store:orderRules,workspace,provider:{},archive:{},mail:{}})}),browser=await loadPlaywright().chromium.launch(browserOptions());
t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});
const admin=runtime.store.users()[0],connection=runtime.workspace.createConnection({name:'隔离连接',owner:'admin'},admin,[admin]);
const sample={connectionId:connection.id,source:'todo',instanceId:'1',taskId:'1',revision:1,processName:'备损订单更改评审',processVersion:'1.4',nodeName:'订单专员(订单通知书)',receivedAt:'2026-10-20T01:00:00Z',serialNum:'S-1',title:'订单号:148396机芯号:X客户简称:甲总数量:0订单号:HA148396机芯号:Y客户简称:乙总数量:5',fields:{order:'148396',qty:0,date:'2026-10-20'}};
const capture=(overrides={},labels={})=>{const s={...sample,...overrides};return runtime.orderRules.recordCapture({sample:s,taskId:s.taskId,snapshot:{processVersion:s.processVersion,fields:Object.entries(s.fields).map(([path,value])=>({path,value,label:labels[path]||({order:'订单号',qty:'订单数量',date:'申请日期'})[path]||path}))}});};
const captured=capture(),page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(7000);
const base='http://127.0.0.1:'+runtime.server.address().port;await page.goto(base+'/'+route);await login(page);return {page,runtime,capture,captured,sample,browser,base};
}
module.exports={orderDrivenUI};
+12
View File
@@ -0,0 +1,12 @@
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><body>
<!-- Isolated compatibility-component harness. The production app uses the native Coordinator/Dispatcher UI. -->
<aside><a href="#rules">分类规则</a><a href="#order-center">订单中心</a><a href="#mail-batches">邮件批次</a></aside>
<main id="content"></main><script src="/order-workflow.js"></script><script>
(async()=>{
const api=async(route,body,{signal}={})=>{const response=await fetch('/api'+route,{signal,method:body===undefined?'GET':'POST',headers:body===undefined?{}:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});const data=await response.json();if(!response.ok)throw Error(data.error||'request failed');return data;};
const esc=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const {user}=await api('/me');window.OrderWorkflowViews.configure({api,esc,formatDate:value=>String(value||'—'),notify(){},user});
let generation=0,current='';async function route(){const hash=location.hash.slice(1)||'rules',name=['rules','order-rules'].includes(hash)?'rules':hash==='mail-batches'?'batches':'orders';if(current===hash)return;current=hash;const revision=++generation;await window.OrderWorkflowViews[name](document.querySelector('#content'),()=>revision===generation);}
window.addEventListener('hashchange',()=>route().catch(error=>{document.querySelector('#content').textContent=error.message;}));await route();
})();
</script></body></html>
+6
View File
@@ -0,0 +1,6 @@
'use strict';
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),{BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs'),{BpmScanner}=require('../../src/modules/bpm/scanner.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function setup(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'record-nav-')),store=new Store(path.join(dir,'dashboard')),workspace=new WorkspaceStore(path.join(dir,'workspace')),scan=new BpmScanStore(path.join(dir,'scan')),password='Record-nav-test-123',actor={username:'admin',role:'admin'};store.bootstrap('admin',password);for(const role of ['viewer','operator'])store.addUser({username:role,password,role},'admin');const connection=workspace.createConnection({name:'隔离测试来源',owner:'admin'},actor,store.users());scan.saveConfig({enabled:false,intervalMinutes:9});scan.complete(scan.begin(connection.id,'admin'),connection.id,Array.from({length:105},(_,i)=>({taskId:String(i).padStart(3,'0'),serialNum:'TEST-'+String(i).padStart(3,'0'),source:'portal-v4',processName:'海外运营订单评审',activityName:'通知节点',subject:'订单样例 '+String(i).padStart(3,'0'),arrivalDay:'2026-10-20',arrivedAt:'2026-10-20T01:00:00Z'})),connection);for(let i=0;i<105;i++)store.recordJob({jobId:'job-'+String(i).padStart(3,'0'),status:'error',metadata:{order:'PDF-'+String(i).padStart(3,'0')},error:'隔离导出失败'});const scanner=new BpmScanner({store:scan,workspace,manager:{scanArrivals:async()=>[]},settings:()=>store.settings()}),server=createDashboard({store,workspace,scanner,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));const browser=await loadPlaywright().chromium.launch(browserOptions()),base='http://127.0.0.1:'+server.address().port;
t.after(async()=>{await browser.close();await scanner.stop();server.closeAllConnections();await new Promise(r=>server.close(r));scan.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});return {store,workspace,scan,connection,browser,base,password,async page(route='#records',username='admin',clock=false){const page=await browser.newPage({viewport:{width:1280,height:900}});if(clock)await page.clock.install();await page.goto(base+'/'+route);await page.locator('#username').fill(username);await page.locator('#password').fill(password);await page.locator('#login-form button').click();return page;}};}
module.exports={setup};
+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));}});
+15
View File
@@ -0,0 +1,15 @@
'use strict';
const http=require('node:http'),crypto=require('node:crypto');
function frame(text){const bytes=Buffer.from(text);if(bytes.length<126)return Buffer.concat([Buffer.from([0x81,bytes.length]),bytes]);const header=Buffer.alloc(4);header[0]=0x81;header[1]=126;header.writeUInt16BE(bytes.length,2);return Buffer.concat([header,bytes]);}
async function signalrHub(t,{handshake=true,pings=true,authStatus=200}={}){
const sockets=new Set(),messages=[];let pingsSent=0;
const server=http.createServer((req,res)=>{if(req.url==='/'){res.end('<script>Yiez.clientId="fixture-token";</script>');return;}if(req.url==='/hubs/system/negotiate?negotiateVersion=1'){if(req.method!=='POST'||req.headers.authorization!=='Bearer fixture-token'){res.writeHead(401);return res.end();}res.writeHead(authStatus,{'Content-Type':'application/json'});return res.end(JSON.stringify({connectionToken:'fixture-connection',availableTransports:[{transport:'WebSockets'}]}));}res.writeHead(404);res.end();});
server.on('upgrade',(req,socket)=>{const url=new URL(req.url,'http://fixture');if(url.pathname!=='/hubs/system'||url.searchParams.get('access_token')!=='fixture-token'||url.searchParams.get('id')!=='fixture-connection'){socket.end('HTTP/1.1 401 Unauthorized\r\n\r\n');return;}
const accept=crypto.createHash('sha1').update(req.headers['sec-websocket-key']+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64');socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: '+accept+'\r\n\r\n');sockets.add(socket);let pending=Buffer.alloc(0);
socket.on('data',chunk=>{pending=Buffer.concat([pending,chunk]);while(pending.length>=2){let length=pending[1]&127,at=2;if(length===126){if(pending.length<4)return;length=pending.readUInt16BE(2);at=4;}if(length===127){socket.destroy();return;}const masked=!!(pending[1]&128);if(pending.length<at+(masked?4:0)+length)return;const opcode=pending[0]&15,mask=masked?pending.subarray(at,at+4):null;at+=masked?4:0;const data=Buffer.from(pending.subarray(at,at+length));if(mask)for(let i=0;i<data.length;i++)data[i]^=mask[i%4];pending=pending.subarray(at+length);if(opcode===8){socket.end(Buffer.from([0x88,0]));return;}if(opcode!==1)continue;for(const part of data.toString().split('\x1e').filter(Boolean)){const value=JSON.parse(part);messages.push(value);if(value.protocol&&handshake){socket.write(frame('{}\x1e'));if(pings){pingsSent++;socket.write(frame('{"type":6}\x1e'));}}}}});
socket.on('close',()=>sockets.delete(socket));socket.on('error',()=>{});
});
await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{for(const socket of sockets)socket.destroy();await new Promise(r=>server.close(r));});
return {baseURL:'http://127.0.0.1:'+server.address().port+'/',messages,sockets,get pingsSent(){return pingsSent;},emit(value){for(const socket of sockets)socket.write(frame(JSON.stringify(value)+'\x1e'));},raw(text){for(const socket of sockets)socket.write(frame(text));},disconnect(){for(const socket of sockets)socket.destroy();}};
}
module.exports={signalrHub};
+1 -1
View File
@@ -1,6 +1,6 @@
// Local test fixture, never used by the production launcher. No BPM/mail access.
const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {Store}=require('../../src/dashboard-store.cjs');const {createDashboard}=require('../../src/dashboard.cjs');
const {Store}=require('../../src/modules/dashboard/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-dashboard-ui-'));const store=new Store(dir);
store.bootstrap('preview','Preview-only-test-2026');
const server=createDashboard({store,outputDir:dir});
+21
View File
@@ -0,0 +1,21 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
test('history UI saves IMAP-only credentials locally, explicitly queries sent mail and displays escaped evidence',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'history-ui-'));const runtime=await startTestDashboard({stateDir:dir,mailHistory:true});let browser;
t.after(async()=>{await browser?.close();await runtime.close();fs.rmSync(dir,{recursive:true,force:true});});
let connects=0;
const raw=Buffer.from('From: sender@example.test\r\nTo: orders@example.test\r\nSubject: Test notice\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n<img src="https://tracker.example.test/pixel"> Huizhou evidence');
runtime.mail.imapFactory=()=>({mailbox:{uidValidity:1n},on(){},async connect(){connects++;},async list(){return [{path:'Sent',specialUse:'\\Sent'}];},async getMailboxLock(_path,opts){assert.equal(opts.readOnly,true);return {release(){}};},async search(){return [1];},async fetchOne(uid,q){return q.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Test notice'}};},async logout(){},close(){}});
browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage();const requests=[];page.on('request',r=>requests.push(r.url()));
await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#mail');await login(page);await page.getByRole('button',{name:'只读查阅已发送邮件',exact:true}).click();
await page.getByRole('button',{name:'添加只读邮箱',exact:true}).click({timeout:5000});
for(const [label,value]of [['邮箱名称','历史核对'],['邮箱地址','orders@example.test'],['IMAP 服务器','imap.example.test'],['IMAP 登录账号','orders@example.test'],['IMAP 授权码','History-123']])await page.getByLabel(label,{exact:true}).fill(value);
await page.getByRole('button',{name:'保存只读邮箱',exact:true}).click();await page.getByText('只读邮箱已保存。',{exact:true}).waitFor();assert.equal(connects,0);
await page.getByRole('button',{name:'连接并列出已发送文件夹',exact:true}).click();await page.getByLabel('已发送文件夹',{exact:true}).selectOption('Sent');
await page.getByRole('button',{name:'查询已发送邮件',exact:true}).click();await page.getByRole('button',{name:'查看邮件',exact:true}).click();
await page.getByText('<img src="https://tracker.example.test/pixel"> Huizhou evidence',{exact:true}).waitFor();
assert.equal(requests.some(r=>r.startsWith('https://tracker.example.test')),false);assert.equal(await page.getByRole('button',{name:/发送测试/}).count(),0);
assert.equal(runtime.mail.store.channels()[0].smtp.hasPassword,false);await page.getByRole('button',{name:'返回邮箱管理',exact:true}).click();await page.getByRole('button',{name:'只读查阅已发送邮件',exact:true}).waitFor();await page.getByRole('button',{name:'只读查阅已发送邮件',exact:true}).click();
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
});
+41
View File
@@ -0,0 +1,41 @@
'use strict';
const {test}=require('node:test');const assert=require('node:assert/strict');
const {MailService}=require('../../src/modules/mail/service.cjs');
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {MailStore}=require('../../src/modules/mail/store.cjs');
const raw=Buffer.from('From: sender@example.test\r\nTo: orders@example.test\r\nCc: factory@example.test\r\nSubject: Order notice\r\nDate: Sun, 18 Oct 2026 10:00:00 +0800\r\nMessage-ID: <notice@example.test>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nOrder body');
function fixture(){
const calls=[],store={channelSecret:()=>({version:1,imap:{}}),guard(){}};
const client={mailbox:{uidValidity:9n},on(){},async connect(){},async logout(){},close(){},async list(){return [{path:'Sent',specialUse:'\\Sent',flags:new Set()},{path:'INBOX',flags:new Set()}];},async getMailboxLock(folder,options){calls.push({folder,...options});return {release(){}};},async search(query,options){calls.push({query,...options});return [1,2,3];},async fetchOne(uid,query,options){calls.push({uid,query,...options});return query.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Order notice',date:new Date('2026-10-18T02:00:00Z'),to:[{address:'orders@example.test'}]}};}};
const service=new MailService({store,imapFactory:()=>client,smtpFactory:()=>{throw Error('SMTP must not be used');}});
return {service,calls,client};
}
test('an IMAP-only history account stores no SMTP credential and rejects all sending or template polling',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'history-account-')),store=new MailStore(dir);
const service=new MailService({store,smtpFactory:()=>{throw Error('SMTP should be unreachable');}});
t.after(async()=>{await service.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});});
const account=store.saveChannel({readOnly:true,name:'历史格式核对',email:'orders@example.test',imap:{host:'imap.example.test',port:993,security:'tls',user:'orders@example.test',password:'History-only-123'}});
assert.equal(account.readOnly,true);assert.equal(account.enabled,false);assert.equal(account.smtp.hasPassword,false);
assert.doesNotMatch(JSON.stringify(store.channels()),/History-only-123/);
for(const work of [()=>service.verify(account.id),()=>service.poll(account.id),()=>service.sendTest(account.id,'any')])await assert.rejects(work(),e=>e.status===409&&e.message.includes('只读'));
});
test('sent history is bounded, read-only, does not download bodies during search, and keeps mailbox cursor untouched',async()=>{
const {service,calls}=fixture();
const result=await service.history('channel',{action:'search',folder:'Sent',since:'2026-10-01',before:'2026-10-20',subject:'订单',limit:2});
assert.equal(result.messages.length,2);assert.equal(result.truncated,true);assert.deepEqual(result.messages.map(m=>m.uid),[3,2]);
assert.ok(calls.some(c=>c.folder==='Sent'&&c.readOnly===true));
assert.ok(calls.some(c=>c.query?.sentSince instanceof Date&&c.query.subject==='订单'));
assert.ok(!calls.some(c=>c.query?.source));
const detail=await service.history('channel',{action:'message',folder:'Sent',uid:3,uidValidity:result.uidValidity});
assert.equal(detail.text,'Order body');assert.equal(detail.to[0].address,'orders@example.test');assert.equal(detail.cc[0].address,'factory@example.test');
assert.deepEqual(detail.attachments,[]);
});
test('history rejects wrong folder, stale UID epoch, oversized messages and unbounded dates without leaking provider errors',async()=>{
const {service,client}=fixture();
for(const input of [{action:'search',folder:'INBOX',since:'2026-10-01',before:'2026-10-20'},{action:'search',folder:'Sent',since:'2020-01-01',before:'2026-10-20'},{action:'search',folder:'Sent',since:'2026-02-31',before:'2026-03-05'}])await assert.rejects(service.history('c',input),e=>e.status===400);
await assert.rejects(service.history('c',{action:'message',folder:'Sent',uid:3,uidValidity:'8'}),e=>e.status===409);
client.fetchOne=async()=>({size:20*1024*1024});
await assert.rejects(service.history('c',{action:'message',folder:'Sent',uid:3,uidValidity:'9'}),e=>e.status===413);
client.connect=async()=>{throw Error('secret password');};
await assert.rejects(service.history('c',{action:'folders'}),e=>!e.message.includes('secret password'));
});
+39
View File
@@ -0,0 +1,39 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {parseTemplate,cleanHtml,renderTemplate}=require('../../src/modules/mail/parser.cjs');
const {extractTitle}=require('../../src/modules/order-rules/title.cjs');
const {ordersForMode}=require('../../src/modules/order-rules/huizhou.cjs');
const {buildBatch}=require('../../src/modules/order-rules/batch.cjs');
const {applyBodyTemplate}=require('../../src/modules/order-rules/template.cjs');
const channel={email:'orders@example.test',senders:['author@example.test']};
const raw=html=>Buffer.from('From: author@example.test\r\nTo: orders@example.test\r\nSubject: [模板]惠州 {{订单号}}\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=utf-8\r\n\r\n'+html);
test('imported business anchor survives real parsing and Hui rendering as a usable HTTPS link',async()=>{
const parsed=await parseTemplate(raw('<p><a href="https://example.test/business">业务访问入口</a></p><p>{{订单明细}}</p><img src="https://tracker.example.test/pixel">'),channel);
const rule={id:'notice',version:1,categoryId:'notice',name:'通知',to:['recipient@example.test'],cc:[],attachPdf:false,huizhouEnabled:true,huizhouTemplateId:'hui-link'};
const title=extractTitle('订单号:O-100客户简称:普通客户业务模式:惠州数字毛利:绿标订单号:H-200客户简称:终端客户');
const order={id:'event',status:'pending',ruleSnapshot:rule,event:{orderNo:'O-100',receivedAt:'2026-10-19T01:00:00Z',brief:title.brief,titleOrders:title.orders},archive:{archivedAt:'2026-10-19T02:00:00Z',files:[{name:'event.pdf',path:'C:\\archive\\event.pdf',kind:'pdf',size:100,sha256:'a'.repeat(64)}]}};
const selected=ordersForMode([order],'huizhou'),snapshot=buildBatch(rule,selected,'2026-10-19T03:00:00Z',{notificationMode:'huizhou'});
const mail=applyBodyTemplate(snapshot,{...parsed,id:'hui-link',version:1,status:'active',notificationMode:'huizhou'},selected,20971520);
assert.match(mail.html,/<a href="https:\/\/example\.test\/business">业务访问入口<\/a>/);assert.match(mail.text,/https:\/\/example\.test\/business/);assert.match(mail.html,/H-200/);assert.doesNotMatch(mail.html,/O-100|tracker|<img/i);
});
test('sanitizer preserves absolute HTTP and HTTPS links but removes navigation side effects',()=>{
const html=cleanHtml('<a href="http://example.test/business" onclick="attack()" ping="https://tracker.test/ping" target="_blank" download>HTTP</a><a href="https://example.test/business?q=one&amp;mode=hui" onmouseover="attack()">HTTPS</a>');
assert.match(html,/href="http:\/\/example\.test\/business"/);assert.match(html,/href="https:\/\/example\.test\/business\?q=one&amp;mode=hui"/);assert.doesNotMatch(html,/onclick|onmouseover|ping=|target=|download|tracker|attack/i);
});
for(const href of ['javascript:alert(1)','jav&#x61;script:alert(1)','data:text/html,hello','file:///C:/private','mailto:user@example.test','//example.test/business','/business','https://user:secret@example.test/business','https://user@example.test/business','https://@example.test/business','https://example.test/\nredirect',' https://example.test/business','https://example.test/%0aheader','https://example.test/%00','https:\\\\example.test\\business','https:///example.test/business'])test('sanitizer strips unsafe link target '+JSON.stringify(href),async()=>{
const parsed=await parseTemplate(raw('<a href="'+href+'" onfocus="attack()">业务访问入口</a>'),channel);assert.match(parsed.html,/业务访问入口/);assert.doesNotMatch(parsed.html,/href=|onfocus|attack/i);
});
for(const [href,value] of [
['{{产品线}}://example.test/business','javascript'],
['https://{{产品线}}','user:secret@example.test'],
['https://example.test/{{产品线}}','\\\\untrusted.test'],
['https://example.test/business?next={{产品线}}','x\nheader'],
['https://&#123;&#123;产品线&#125;&#125;','user:secret@example.test']
])test('import removes dynamic href before template substitution '+JSON.stringify(href),async()=>{
const parsed=await parseTemplate(raw('<a href="'+href+'">业务访问入口</a><p>产品线:{{产品线}}</p><p>订单:{{订单号}}</p>'),channel);
const rendered=renderTemplate(parsed,{'产品线':value,'订单号':'H-200'});assert.doesNotMatch(rendered.html,/href=/i);assert.match(rendered.html,/业务访问入口/);assert.match(rendered.html,/订单:H-200/);assert.doesNotMatch(rendered.html,/{{产品线}}/);assert.ok(rendered.text.includes(value));
});
test('literal percent-encoded business path stays clickable and body variables still render',async()=>{
const parsed=await parseTemplate(raw('<a href="https://example.test/business/%E6%83%A0%E5%B7%9E?label=one%20two">业务访问入口</a><p>{{产品线}} {{订单号}}</p>'),channel),rendered=renderTemplate(parsed,{'产品线':'机顶盒','订单号':'H-200'});
assert.match(rendered.html,/href="https:\/\/example\.test\/business\/%E6%83%A0%E5%B7%9E\?label=one%20two"/);assert.match(rendered.html,/机顶盒 H-200/);
});
+35
View File
@@ -0,0 +1,35 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {DatabaseSync}=require('node:sqlite');
const {BpmVault}=require('../../src/platform/security/vault.cjs');
const {MailStore}=require('../../src/modules/mail/store.cjs');
const {ruleTemplate}=require('../../src/modules/mail/rule-template.cjs');
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'hui-template-'));let store=new MailStore(dir);const channel=store.saveChannel({readOnly:true,name:'test',email:'orders@example.test',imap:{host:'imap.example.test',port:993,security:'tls',user:'orders',password:'isolated-test'}});let uid=0;t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return {dir,get store(){return store;},channel,draft(){const n=++uid;return store.ingest(channel.id,'test',n,{scope:'scope',subject:'Notice',text:'Body {{订单号}}',html:'',sender:'author@example.test',attachments:[]},Buffer.from('isolated '+n),channel.version);},confirm(d,mode){return store.confirm(d.id,{version:d.version,scope:d.scope,subject:d.subject,useText:false,...(mode===undefined?{}:{notificationMode:mode})},'admin');},reopen(){store.close();store=new MailStore(dir);return store;}};}
test('legacy template migration defaults to normal without rewriting payloads or versions',t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'hui-legacy-')),vault=new BpmVault({stateDir:path.join(dir,'secrets')}),db=new DatabaseSync(path.join(dir,'mail.sqlite'));
db.exec("CREATE TABLE templates(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,source_key TEXT NOT NULL,scope TEXT NOT NULL,status TEXT NOT NULL,version INTEGER NOT NULL,base_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL,summary TEXT NOT NULL DEFAULT '{}',UNIQUE(channel_id,source_key)); CREATE UNIQUE INDEX active_template ON templates(channel_id,scope) WHERE status='active'");
const payload={subject:'Legacy',text:'original body',html:'',sender:'author@example.test',attachments:[]},encrypted=vault.encode('old',payload);
db.prepare('INSERT INTO templates VALUES(?,?,?,?,?,?,?,?,?,?)').run('old','legacy','source','scope','active',7,null,encrypted,'2026-10-01T00:00:00Z',JSON.stringify({subject:'Legacy',attachmentCount:0}));db.close();vault.destroy();
const store=new MailStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
assert.equal(store.template('old').notificationMode,'normal');assert.equal(store.templates()[0].notificationMode,'normal');assert.equal(store.template('old').version,7);assert.equal(store.template('old').text,'original body');assert.deepEqual(Buffer.from(store.db.prepare('SELECT payload FROM templates WHERE id=?').get('old').payload),Buffer.from(encrypted));
});
test('confirming and replacing templates archives only the same notification mode and survives reopen',t=>{
const f=fixture(t),normal=f.confirm(f.draft()),hui=f.confirm(f.draft(),'huizhou');
assert.equal(f.store.template(normal.id).status,'active');assert.equal(hui.notificationMode,'huizhou');assert.equal(f.store.active(f.channel.id,'scope').id,normal.id);assert.equal(f.store.active(f.channel.id,'scope','huizhou').id,hui.id);
const hui2=f.confirm(f.draft(),'huizhou');assert.equal(f.store.template(hui.id).status,'archived');assert.equal(f.store.template(normal.id).status,'active');
f.reopen();assert.equal(f.store.templates().find(t=>t.id===hui2.id).notificationMode,'huizhou');assert.equal(f.store.active(f.channel.id,'scope').id,normal.id);
});
test('mode confirmation rejects invalid values and concurrent replacements within the selected mode',t=>{
const f=fixture(t),d=f.draft();for(const mode of ['',null,false,'HUIZHOU','other'])assert.throws(()=>f.confirm(d,mode),e=>e.status===400);
f.confirm(d,'huizhou');const a=f.draft(),b=f.draft();f.confirm(a,'huizhou');assert.throws(()=>f.confirm(b,'huizhou'),e=>e.status===409);
});
test('resolver isolates modes, requires explicit Hui selection and rejects inactive selections',t=>{
const f=fixture(t),normal=f.confirm(f.draft()),hui=f.confirm(f.draft(),'huizhou'),rule={bodyTemplateId:normal.id,huizhouEnabled:true,huizhouTemplateId:hui.id,to:['owner@example.test'],cc:['copy@example.test']};
assert.equal(ruleTemplate(f.store,'bs-change',rule).id,normal.id);assert.equal(ruleTemplate(f.store,'bs-change',rule,'huizhou').id,hui.id);
assert.equal(ruleTemplate(f.store,'bs-change',{...rule,huizhouEnabled:false},'huizhou'),null);
assert.throws(()=>ruleTemplate(f.store,'bs-change',{...rule,huizhouTemplateId:''},'huizhou'),e=>e.status===409);
assert.throws(()=>ruleTemplate(f.store,'bs-change',{...rule,bodyTemplateId:hui.id}),e=>e.status===409);
assert.throws(()=>ruleTemplate(f.store,'bs-change',{...rule,huizhouTemplateId:normal.id},'huizhou'),e=>e.status===409);
assert.throws(()=>f.store.bindCategory({categoryId:'bs-change',templateId:hui.id,version:0}),e=>e.status===409);
f.confirm(f.draft(),'huizhou');assert.throws(()=>ruleTemplate(f.store,'bs-change',rule,'huizhou'),e=>e.status===409);assert.equal(ruleTemplate(f.store,'bs-change',rule).id,normal.id);
});
@@ -1,5 +1,5 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {Store}=require('../src/dashboard-store.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {MailStore}=require('../src/mail-store.cjs');const {MailService}=require('../src/mail-service.cjs');const {parseTemplate}=require('../src/mail-parser.cjs');
const {Store}=require('../../src/modules/dashboard/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');const {parseTemplate}=require('../../src/modules/mail/parser.cjs');
const config={name:'邮箱',email:'orders@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'orders',password:'Secret-mail-123'},imap:{host:'imap.company.test',port:993,security:'tls',user:'orders',password:'Secret-mail-123'},senders:['author@company.test'],enabled:true};
async function setup(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-http-'));const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');store.addUser({username:'reader',password:'Test-password-123',role:'viewer'},'admin');const mailStore=new MailStore(path.join(dir,'mail'));const mail=new MailService({store:mailStore});const server=createDashboard({store,mail,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{await mail.stop();await new Promise(r=>server.close(r));mailStore.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;const call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});const login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {mail,mailStore,call,login};}
test('mail API uses authentication, roles, same origin, redacted config and actual overview status',async t=>{
@@ -13,3 +13,18 @@ test('template preview is isolated, source attachments downloadable and confirma
assert.equal((await call('/api/mail/templates/'+d.id+'/confirm',{version:1,subject:d.subject,scope:'',useText:false},reader)).status,403);assert.equal((await call('/api/mail/templates/'+d.id+'/confirm',{version:1,subject:d.subject,scope:'',useText:false},admin)).status,200);assert.equal(mailStore.active(c.id,'').id,d.id);
assert.equal((await call('/api/mail/templates/'+d.id+'/source',undefined,reader)).status,403);const source=await call('/api/mail/templates/'+d.id+'/source',undefined,admin);assert.equal(await source.text(),raw.toString());
});
test('history access requires administrator and same origin; isolated history mode rejects SMTP and polling routes',async t=>{
const {mail,mailStore,call,login}=await setup(t);mail.historyOnly=true;
const admin=await login('admin'),reader=await login('reader');
const saved=await call('/api/mail/channels',{readOnly:true,name:'历史核对',email:'orders@example.test',imap:config.imap},admin);
assert.equal(saved.status,201);const account=await saved.json();
const url='/api/mail/channels/'+account.id;
assert.equal((await call(url+'/history',{action:'folders'},reader)).status,403);
assert.equal((await call(url+'/history',{action:'folders'},admin,'https://evil.test')).status,403);
for(const action of ['verify','poll','test'])assert.equal((await call(url+'/'+action,{},admin)).status,409);
assert.equal((await call('/api/mail/channels',config,admin)).status,409);
assert.equal(mailStore.channels().length,1);
mail.imapFactory=()=>({on(){},async connect(){},async list(){return [{path:'Sent',specialUse:'\\Sent'}];},async logout(){},close(){}});
const folders=await call(url+'/history',{action:'folders'},admin);assert.equal(folders.status,200);assert.deepEqual((await folders.json()).folders,[{path:'Sent',name:'Sent'}]);
});
@@ -1,8 +1,15 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const path=require('node:path');const os=require('node:os');const {SMTPServer}=require('smtp-server');const {simpleParser}=require('mailparser');
const {MailStore}=require('../src/mail-store.cjs');const {MailService}=require('../src/mail-service.cjs');
const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');
const config={name:'邮箱',email:'orders@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'orders',password:'Secret-mail-123'},imap:{host:'imap.company.test',port:993,security:'tls',user:'orders',password:'Secret-mail-123'},senders:['author@company.test'],enabled:true};
const raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMessage-ID: <a@company.test>\r\n\r\nHello {{订单号}}');
async function fixture(t,options={}){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-service-'));const store=new MailStore(dir);const service=new MailService({store,...options});t.after(async()=>{await service.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});});return {store,service};}
test('self-test renders business template variables with synthetic data and the configured self recipient',async t=>{
let sent;const {store,service}=await fixture(t,{smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{sent=message;return {accepted:[config.email]};},close(){}})});
const c=store.saveChannel(config),p=require('../../src/modules/mail/parser.cjs'),body='{{类别名称}}\n{{订单明细}}\n存放地址:{{存放地址}}',mail=Buffer.from(raw.toString().replace('Hello {{订单号}}',body));
const draft=store.ingest(c.id,'1',1,await p.parseTemplate(mail,config),mail,c.version);store.confirm(draft.id,{version:1,subject:'测试摘要',scope:'',text:body,useText:true},'admin');
await service.sendTest(c.id,draft.id);assert.equal(sent.to.address,config.email);assert.match(sent.text,/订单号:TEST/);assert.match(sent.text,/示例归档目录/);assert.doesNotMatch(sent.text,/{{/);assert.equal(store.sends()[0].status,'sent');
});
test('read-only poll uses UID epoch, ignores ordinary messages, does not double ingest, and records source denials',async t=>{
let downloads=0,locks=0;const client={mailbox:{uidValidity:10n},on(){},async connect(){},async getMailboxLock(box,options){assert.equal(box,'INBOX');assert.equal(options.readOnly,true);locks++;return {release(){locks--;}};},async search(query,options){assert.equal(options.uid,true);return [1,2,3];},async fetchOne(uid,query,options){assert.equal(options.uid,true);if(query.source){downloads++;return {source:uid===3?Buffer.from(raw.toString().replace('author@','unknown@')):raw};}return {size:raw.length,envelope:{subject:uid===1?'Ordinary':'[模板]Notice'}};},async logout(){},close(){}};
const {store,service}=await fixture(t,{imapFactory:()=>client});const c=store.saveChannel(config);await service.poll(c.id);await service.poll(c.id);assert.equal(downloads,2);assert.equal(locks,0);assert.equal(store.templates().length,1);assert.equal(store.cursor(c.id).uid,3);assert.equal(store.receipts()[0].status,'rejected');
@@ -15,5 +22,5 @@ test('initial empty seven-day scan retains date boundary on future polls',async
test('SMTP verification never sends; explicit self-test uses confirmed template and durable send record',async t=>{
let messages=[];const smtp=new SMTPServer({secure:false,hideSTARTTLS:true,authOptional:true,disabledCommands:['AUTH'],onData(stream,session,cb){const chunks=[];stream.on('data',c=>chunks.push(c));stream.on('end',()=>{messages.push(Buffer.concat(chunks));cb();});}});await new Promise(r=>smtp.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>smtp.close(r)));
const nodemailer=require('nodemailer');const {store,service}=await fixture(t,{smtpFactory:()=>nodemailer.createTransport({host:'127.0.0.1',port:smtp.server.address().port,secure:false,ignoreTLS:true}),imapFactory:()=>({on(){},async connect(){},async getMailboxLock(){return {release(){}};},async logout(){},close(){}})});
const c=store.saveChannel(config);await service.verify(c.id);assert.equal(messages.length,0);const p=require('../src/mail-parser.cjs');const draft=store.ingest(c.id,'1',1,await p.parseTemplate(raw,config),raw,c.version);assert.equal(store.active(c.id,''),null);await assert.rejects(service.sendTest(c.id,draft.id),e=>e.status===409);store.confirm(draft.id,{version:1,subject:'Notice {{订单号}}',scope:'',text:'Hello {{订单号}}',useText:false},'admin');await service.sendTest(c.id,draft.id);assert.equal(messages.length,1);const sent=await simpleParser(messages[0]);assert.equal(sent.to.value[0].address,config.email);assert.match(sent.text,/Hello TEST/);assert.equal(store.sends()[0].status,'sent');
const c=store.saveChannel(config);await service.verify(c.id);assert.equal(messages.length,0);const p=require('../../src/modules/mail/parser.cjs');const draft=store.ingest(c.id,'1',1,await p.parseTemplate(raw,config),raw,c.version);assert.equal(store.active(c.id,''),null);await assert.rejects(service.sendTest(c.id,draft.id),e=>e.status===409);store.confirm(draft.id,{version:1,subject:'Notice {{订单号}}',scope:'',text:'Hello {{订单号}}',useText:false},'admin');await service.sendTest(c.id,draft.id);assert.equal(messages.length,1);const sent=await simpleParser(messages[0]);assert.equal(sent.to.value[0].address,config.email);assert.match(sent.text,/Hello TEST/);assert.equal(store.sends()[0].status,'sent');
});
@@ -1,8 +1,8 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');const {Store}=require('../src/dashboard-store.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {MailStore}=require('../src/mail-store.cjs');const {MailService}=require('../src/mail-service.cjs');const {parseTemplate}=require('../src/mail-parser.cjs');
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');const {Store}=require('../../src/modules/dashboard/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');const {parseTemplate}=require('../../src/modules/mail/parser.cjs');
test('mail management saves a real config, previews template under CSP and confirms after review; narrow layout stays inside viewport',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-ui-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const mailStore=new MailStore(path.join(dir,'mail')),mail=new MailService({store:mailStore});const server=createDashboard({store,mail,outputDir:dir});let browser;
t.after(async()=>{await browser?.close();await mail.stop();await new Promise(r=>server.close(r));mailStore.close();fs.rmSync(dir,{recursive:true,force:true});});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1360,height:950}});const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/#mail');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'添加邮箱',exact:true}).click({timeout:5000});
await page.getByLabel('邮箱名称',{exact:true}).fill('通知邮箱');await page.getByLabel('邮箱地址',{exact:true}).fill('orders@company.test');for(const type of ['SMTP','IMAP']){await page.getByLabel(type+' 服务器',{exact:true}).fill(type.toLowerCase()+'.company.test');await page.getByLabel(type+' 登录账号',{exact:true}).fill('orders');await page.getByLabel(type+' 密码 / 授权码',{exact:true}).fill('Secret-mail-123');}await page.getByLabel('允许提交模板的发件人',{exact:true}).fill('author@company.test');await page.getByRole('button',{name:'保存邮箱',exact:true}).click();await page.getByText('通知邮箱',{exact:true}).waitFor();assert.equal(mailStore.channels().length,1);
const c=mailStore.channels()[0],raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMIME-Version: 1.0\r\nContent-Type: text/html\r\n\r\n<table><tr><td>Template body</td></tr></table><img src="https://tracker.test/1">');const draft=mailStore.ingest(c.id,'1',1,await parseTemplate(raw,c),raw,1);await page.getByRole('link',{name:'模板与收件群组',exact:true}).click();await page.getByRole('button',{name:'预览并确认',exact:true}).click();await page.frameLocator('iframe[title="邮件正文预览"]').getByText('Template body',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'pending');await page.getByLabel('发信标题',{exact:true}).fill('Confirmed notice');await page.getByRole('button',{name:'确认生效',exact:true}).click();await page.getByText('模板已确认生效。',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'active');
const c=mailStore.channels()[0],raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMIME-Version: 1.0\r\nContent-Type: text/html\r\n\r\n<table><tr><td>Template body</td></tr></table><img src="https://tracker.test/1">');const draft=mailStore.ingest(c.id,'1',1,await parseTemplate(raw,c),raw,1);await page.locator('#sidebar-menu a[data-view=business-settings]').click();await page.getByRole('link',{name:'通知配置',exact:true}).click();await page.locator('#notification-config-tabs').getByRole('link',{name:'邮件模板',exact:true}).click();await page.getByRole('button',{name:'预览并确认',exact:true}).click();await page.frameLocator('iframe[title="邮件正文预览"]').getByText('Template body',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'pending');await page.getByLabel('发信标题',{exact:true}).fill('Confirmed notice');await page.getByRole('button',{name:'确认生效',exact:true}).click();await page.getByText('模板已确认生效。',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'active');
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
});
@@ -1,6 +1,6 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {parseTemplate,renderTemplate}=require('../src/mail-parser.cjs');
const {MailStore}=require('../src/mail-store.cjs');
const {parseTemplate,renderTemplate}=require('../../src/modules/mail/parser.cjs');
const {MailStore}=require('../../src/modules/mail/store.cjs');
const config={name:'通知邮箱',email:'Orders@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'orders',password:'Secret-mail-123'},imap:{host:'imap.company.test',port:993,security:'tls',user:'orders',password:'Secret-mail-123'},senders:['author@company.test'],enabled:true};
const eml=(subject='[模板][海外运营]订单 {{订单号}}',body='你好,{{产品线}}\r\n{{订单列表}}',from='author@company.test')=>Buffer.from(`From: ${from}\r\nTo: orders@company.test\r\nSubject: =?UTF-8?B?${Buffer.from(subject).toString('base64')}?=\r\nMessage-ID: <test1@company.test>\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n${body}`);
async function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-'));const store=new MailStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return {dir,store};}
@@ -41,6 +41,6 @@ test('source message duplicates under new UID and epoch never generate new versi
store.saveChannel({...config,id:c.id,version:1,enabled:false});assert.throws(()=>store.ingest(c.id,'2',100,p,eml(),1),e=>e.status===409);assert.equal(store.cursor(c.id).uid,99);
});
module.exports={config,eml};
test('repeated CID references are rejected before expanding to unbounded HTML',()=>{const {cleanHtml}=require('../src/mail-parser.cjs');assert.throws(()=>cleanHtml('<img src="cid:logo">'.repeat(200),[{cid:'logo',contentType:'image/png',content:Buffer.alloc(100000).toString('base64')}]),e=>e.status===400&&/内嵌图片/.test(e.message));});
test('repeated CID references are rejected before expanding to unbounded HTML',()=>{const {cleanHtml}=require('../../src/modules/mail/parser.cjs');assert.throws(()=>cleanHtml('<img src="cid:logo">'.repeat(200),[{cid:'logo',contentType:'image/png',content:Buffer.alloc(100000).toString('base64')}]),e=>e.status===400&&/内嵌图片/.test(e.message));});
test('outgoing embedded images use MIME content IDs and template lists never decode raw messages',async t=>{const {store}=await fixture(t);const c=store.saveChannel(config);const parsed={subject:'Notice',scope:'',text:'Image',html:'<img src="data:image/png;base64,aGVsbG8=">',sender:'author@company.test',attachments:[{filename:'a.png',cid:'logo',contentType:'image/png',content:'aGVsbG8=',inline:true,size:5}]};const d=store.ingest(c.id,'1',1,parsed,Buffer.from('raw'),1);assert.match(renderTemplate(parsed,{}).html,/src="cid:logo"/);const decode=store.decode;store.decode=()=>{throw new Error('must not decode payload');};try{assert.equal(store.templates()[0].id,d.id);}finally{store.decode=decode;}});
test('legacy draft can be assigned once to a real mailbox without losing body',async t=>{const {store}=await fixture(t);const c=store.saveChannel(config);store.migrateLegacy({subject:'旧草稿',body:'保留正文'});const d=store.templates()[0];const saved=store.confirm(d.id,{version:1,channelId:c.id,subject:'正式标题',scope:'',useText:false},'admin');assert.equal(saved.channelId,c.id);assert.equal(saved.text,'保留正文');assert.equal(store.active(c.id,'').id,d.id);store.migrateLegacy({subject:'旧草稿',body:'保留正文'});assert.equal(store.templates().length,1);});
+3
View File
@@ -0,0 +1,3 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),{mailApi}=require('../../src/modules/mail/api.cjs');
test('legacy category template binding is readable but cannot compete with classification writes',async()=>{let writes=0,output;const args={mail:{store:{categoryBindings:()=>[{categoryId:'old',templateId:'legacy'}],bindCategory:()=>writes++}},user:{role:'admin'},route:'/api/mail/templates/categories',reply:(status,data)=>output={status,data}};await mailApi({...args,method:'GET'});assert.equal(output.status,200);assert.equal(output.data.bindings[0].templateId,'legacy');await assert.rejects(mailApi({...args,method:'POST',body:{categoryId:'old',templateId:'new'}}),{status:410});assert.equal(writes,0);});
-9
View File
@@ -1,9 +0,0 @@
'use strict';
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');const {Store}=require('../src/dashboard-store.cjs');const {NotificationStore,NotificationService}=require('../src/notifications.cjs');const {createDashboard}=require('../src/dashboard.cjs');
test('notification HTTP exposes configurable mapping and preview without sending, with role and origin checks',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notice-http-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');const notificationStore=new NotificationStore(path.join(dir,'notifications')),notifications=new NotificationService({store:notificationStore,mail:{},settings:()=>store.settings()}),server=createDashboard({store,notifications,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{await notifications.stop();server.closeAllConnections();await new Promise(r=>server.close(r));notificationStore.close();await fs.rm(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port,call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)}),login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];
assert.equal((await call('/api/notifications')).status,401);const admin=await login('admin'),operator=await login('operator'),viewer=await login('viewer');const config=notificationStore.settings();assert.equal((await call('/api/notifications/settings',config,operator)).status,403);assert.equal((await call('/api/notifications/settings',config,admin,'https://evil.test')).status,403);assert.equal((await call('/api/notifications/settings',config,admin)).status,200);
const data={id:'external-1',industry:'待配置产业',brief:'简要说明原文\n保持换行'};const preview=await(await call('/api/notifications/preview',{data},operator)).json();assert.equal(preview.event.brief,data.brief);assert.equal(notificationStore.items().length,0);
assert.equal((await call('/api/notifications/events',{data},viewer)).status,403);assert.equal((await call('/api/notifications/events',{data},operator)).status,201);assert.equal(notificationStore.items().length,1);
assert.equal((await call('/api/notifications',undefined,viewer)).status,200);
});
-5
View File
@@ -1,5 +0,0 @@
'use strict';
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');const {Store}=require('../src/dashboard-store.cjs');const {NotificationStore,NotificationService}=require('../src/notifications.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
test('notification page saves field maps and previews original text without queuing or sending',{timeout:90000},async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notice-ui-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const notificationStore=new NotificationStore(path.join(dir,'notifications')),notifications=new NotificationService({store:notificationStore,mail:{},settings:()=>store.settings()}),server=createDashboard({store,notifications,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser;t.after(async()=>{await browser?.close();await notifications.stop();server.closeAllConnections();await new Promise(r=>server.close(r));notificationStore.close();await fs.rm(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(6000);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('http://127.0.0.1:'+server.address().port+'/#notifications');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByLabel('来源名称',{exact:true}).fill('团队业务');await page.getByRole('button',{name:'保存通知配置',exact:true}).click();await page.getByText('业务通知配置已保存。',{exact:true}).waitFor();assert.equal(notificationStore.settings().sourceName,'团队业务');await page.getByLabel('来源 JSON 样本',{exact:true}).fill(JSON.stringify({id:'SAMPLE-001',industry:'同事后续配置',brief:'原始简要说明\n第二行'}));await page.getByRole('button',{name:'预览字段映射',exact:true}).click();await page.locator('#notification-preview pre').getByText('原始简要说明\n第二行',{exact:true}).waitFor();assert.equal(notificationStore.items().length,0);assert.equal(await page.locator('#notification-preview pre').evaluate(el=>{const node=el.firstChild,index=node.textContent.indexOf('\n'),range=document.createRange();range.setStart(node,0);range.setEnd(node,1);const first=range.getBoundingClientRect().top;range.setStart(node,index+1);range.setEnd(node,index+2);return range.getBoundingClientRect().top>first;}),true);await fs.mkdir(path.resolve('output/verification'),{recursive:true});await page.evaluate(()=>window.scrollTo(0,0));await page.screenshot({path:path.resolve('output/verification/notifications-desktop.png'),fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
});
@@ -0,0 +1,8 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto');const {NotificationHistory}=require('../../src/modules/notifications/history.cjs'),{NotificationStore}=require('../../src/modules/notifications/store.cjs');
test('retired engine reads old encrypted evidence without recovery or database writes',t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'readonly-notifications-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));const writer=new NotificationStore(dir);writer.ingest({sourceKey:'fixture-source',sourceId:'old',sourceVersion:'1',industry:'历史类别',brief:'合成历史',subject:'合成主题'});const expected=writer.items();writer.close();const file=path.join(dir,'notifications.sqlite'),hash=()=>crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'),before=hash();const history=new NotificationHistory(dir);assert.deepEqual(history.items(),expected);assert.deepEqual(history.batches(),[]);assert.equal(history.settings().historyOnly,true);assert.equal(history.settings().enabled,false);assert.equal(history.settings().sourceKey,undefined);assert.equal(history.recover,undefined);assert.equal(history.ingest,undefined);history.close();assert.equal(hash(),before);
});
test('older uncertain legacy batches remain visible beyond the recent history cap',t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'readonly-unknown-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));const writer=new NotificationStore(dir);for(let i=0;i<102;i++)writer.db.prepare('INSERT INTO batches VALUES(?,?,?,?,?)').run('batch-'+i,i===0?'unknown':'sent',writer.encode('batch-'+i,{text:'合成历史'}),null,'2020-01-01');writer.close();const history=new NotificationHistory(dir);try{assert.equal(history.batches()[0].id,'batch-0');assert.equal(history.batches().length,100);}finally{history.close();}
});
@@ -0,0 +1,10 @@
'use strict';
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');const {Store}=require('../../src/modules/dashboard/store.cjs');const {NotificationStore}=require('../../src/modules/notifications/store.cjs');const {NotificationService}=require('../../src/modules/notifications/service.cjs');const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');
test('retired notification HTTP preserves history and rejects all writes with clear reason',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notice-http-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');const notificationStore=new NotificationStore(path.join(dir,'notifications')),notifications=new NotificationService({store:notificationStore,mail:{},settings:()=>store.settings()}),workspace=new WorkspaceStore(path.join(dir,'workspace')),server=createDashboard({store,notifications,workspace,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{await notifications.stop();server.closeAllConnections();await new Promise(r=>server.close(r));notificationStore.close();workspace.close();await fs.rm(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port,call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)}),login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];
assert.equal((await call('/api/notifications')).status,401);const admin=await login('admin'),operator=await login('operator'),viewer=await login('viewer');
const data={id:'historical-1',industry:'历史类别',brief:'历史内容'};notifications.ingest(data);const before=notificationStore.items();
for(const cookie of [admin,operator,viewer])for(const route of ['/api/notifications/settings','/api/notifications/preview','/api/notifications/events','/api/notifications/items/old/retry','/api/notifications/batches/old/resolve']){const response=await call(route,{data},cookie);assert.equal(response.status,410);assert.match((await response.json()).error,/停用|分类规则/);}
assert.equal((await call('/api/notifications/settings',{},admin,'https://evil.test')).status,403);
const history=await (await call('/api/notifications',undefined,viewer)).json();assert.deepEqual(history.items,before);assert.deepEqual(notificationStore.items(),before);
});
@@ -0,0 +1,6 @@
'use strict';
const retryHistory=(store,id)=>store.db.prepare('SELECT id,payload FROM retry_audit WHERE item_id=? ORDER BY rowid').all(id).map(row=>store.decode(row.id,row.payload));
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');const {Store}=require('../../src/modules/dashboard/store.cjs');const {NotificationStore}=require('../../src/modules/notifications/store.cjs');const {NotificationService}=require('../../src/modules/notifications/service.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
test('retired notification route redirects while real historical items remain read-only',{timeout:60000},async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notice-ui-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const notificationStore=new NotificationStore(path.join(dir,'notifications')),notifications=new NotificationService({store:notificationStore,mail:{},settings:()=>store.settings()}),server=createDashboard({store,notifications,outputDir:dir});const item=notifications.ingest({id:'OLD1',industry:'宽带',brief:'原始简要说明\n第二行',subject:'隔离历史通知'});await new Promise(r=>server.listen(0,'127.0.0.1',r));const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await notifications.stop();server.closeAllConnections();await new Promise(r=>server.close(r));notificationStore.close();await fs.rm(dir,{recursive:true,force:true});});const page=await browser.newPage({viewport:{width:390,height:844}});page.setDefaultTimeout(6000);const writes=[];page.on('request',r=>{if(r.method()==='POST'&&r.url().includes('/notifications'))writes.push(r.url());});await page.goto('http://127.0.0.1:'+server.address().port+'/#notifications');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('heading',{name:'分类通知规则',exact:true}).waitFor();assert.equal(await page.locator('#notification-settings').count(),0);await page.evaluate(()=>location.hash='records');await page.getByRole('button',{name:'查看旧通知历史(只读)',exact:true}).click();await page.locator('#legacy-notification-history pre').getByText('原始简要说明\n第二行',{exact:true}).waitFor();assert.equal(await page.locator('#legacy-notification-history form').count(),0);assert.equal(notificationStore.items().length,1);assert.deepEqual(writes,[]);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
});
@@ -1,6 +1,7 @@
'use strict';
const retryHistory=(store,id)=>store.db.prepare('SELECT id,payload FROM retry_audit WHERE item_id=? ORDER BY rowid').all(id).map(row=>store.decode(row.id,row.payload));
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
const {NotificationStore,NotificationService}=require('../src/notifications.cjs');const {MailStore}=require('../src/mail-store.cjs');const {MailService}=require('../src/mail-service.cjs');
const {NotificationStore}=require('../../src/modules/notifications/store.cjs');const {NotificationService}=require('../../src/modules/notifications/service.cjs');const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');
const fields={id:'flow.id',version:'flow.version',industry:'flow.industry',brief:'flow.brief',subject:'flow.subject',occurredAt:'flow.at'};
const event={flow:{id:'FLOW-001',version:'v1',industry:'宽带',brief:'第一行原文\n第二行 <原文> & 保留',subject:'业务提醒',at:'2026-10-17T08:00:00+08:00'}};
async function fixture(t,{uncertain=false}={}){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-notice-'));const store=new NotificationStore(path.join(dir,'notifications'));const mailStore=new MailStore(path.join(dir,'mail'));const channel=mailStore.saveChannel({name:'工作邮箱',email:'notice@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'notice',password:'Fixture-only-password'},imap:{host:'imap.company.test',port:993,security:'tls',user:'notice',password:'Fixture-only-password'},senders:['author@company.test'],enabled:false});mailStore.setState(channel.id,1,{smtp:true});const sent=[];const mail=new MailService({store:mailStore,smtpFactory:()=>({verify:async()=>{},sendMail:async payload=>{sent.push(payload);if(uncertain)throw new Error('socket disconnected');return {accepted:['interface@company.test'],rejected:[]};},close(){}})});const service=new NotificationService({store,mail,settings:()=>({schedule:{times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:true,mode:'product_line',missed:'next_window'},groups:[{productLine:'宽带',to:['interface@company.test'],cc:[]}]}),calendar:()=>[],clock:()=>new Date('2026-10-17T08:59:00+08:00')});service.saveSettings({version:1,enabled:false,sourceName:'业务流程',channelId:channel.id,fieldMap:fields,maxAttempts:3});t.after(async()=>{await service.stop();await mail.stop();store.close();mailStore.close();await fs.rm(dir,{recursive:true,force:true});});return {dir,store,service,sent,channel};}
@@ -50,3 +51,43 @@ test('field mapping supports Chinese object keys and rejects control characters
const sample={来源:{编号:'FLOW-CN',产业:'宽带',简要说明:'中文字段原文'}};assert.equal(service.preview(sample).event.brief,'中文字段原文');
assert.throws(()=>service.ingest({来源:{...sample.来源,编号:'bad\u0000identity'}}),e=>e.status===400);
});
test('opening another store never recovers the active owner reservation',async t=>{
const {dir,store,service}=await fixture(t);const item=service.ingest(event),batch=store.prepare([item],{to:[],sourceIds:[item.sourceId]});
const other=new NotificationStore(path.join(dir,'notifications'));try{
assert.equal(other.items()[0].status,'reserved');assert.equal(other.batches()[0].status,'prepared');assert.equal(store.items()[0].batch_id,batch);
}finally{other.close();}
});
test('cancelled or stolen reservations cannot cross the SMTP send boundary',async t=>{
const {store,service,sent}=await fixture(t);service.ingest(event);service.saveSettings({...store.settings(),enabled:true});
service.mail.smtpFactory=()=>({verify:async()=>{store.db.prepare("UPDATE batches SET status='cancelled' WHERE status='prepared'").run();},sendMail:async payload=>{sent.push(payload);return {accepted:['interface@company.test']};},close(){}});
await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(sent.length,0);assert.equal(store.batches()[0].status,'cancelled');
const item=service.ingest({flow:{...event.flow,id:'stolen'}}),batch=store.prepare([item],{to:[]});store.db.prepare("UPDATE items SET batch_id='another-owner' WHERE id=?").run(item.id);
assert.throws(()=>store.beginSending(batch),e=>e.status===409);assert.equal(store.batches().find(b=>b.id===batch).status,'prepared');
});
test('last SMTP verification failure exhausts one item until evidence-based CAS manual retry',async t=>{
const {store,service,sent}=await fixture(t);const item=service.ingest(event);service.saveSettings({...store.settings(),enabled:true,maxAttempts:1});
service.mail.smtpFactory=()=>({verify:async()=>{throw new Error('fixture verification failure');},close(){}});
await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(store.items()[0].status,'exhausted');assert.doesNotMatch(store.items()[0].error,/等待下个时段/);assert.doesNotMatch(store.batches()[0].error,/等待下个时段/);
await service.tick(new Date('2026-10-17T17:00:00+08:00'));assert.equal(store.items()[0].attempts,1);assert.equal(sent.length,0);
const batchId=store.items()[0].batch_id;assert.throws(()=>service.retryItem(item.id,{batchId,note:''},'admin'),e=>e.status===400);
service.retryItem(item.id,{batchId,note:'已修复 SMTP 并完成连接检查'},'admin');assert.equal(store.items()[0].status,'pending');assert.equal(store.items()[0].attempts,0);
assert.throws(()=>service.retryItem(item.id,{batchId,note:'重复提交同一核验依据'},'admin'),e=>e.status===409);
const audit=retryHistory(store,item.id);assert.equal(audit.length,1);assert.equal(audit[0].actor,'admin');assert.match(audit[0].note,/SMTP/);
service.mail.smtpFactory=()=>({verify:async()=>{},sendMail:async payload=>{sent.push(payload);return {accepted:['interface@company.test'],rejected:[]};},close(){}});await service.tick(new Date('2026-10-18T09:00:00+08:00'));assert.equal(sent.length,1);assert.equal(store.items()[0].status,'sent');
});
test('explicit recovery and lowering attempts normalize eligible work but never revive unknown or exhausted',async t=>{
const {store,service}=await fixture(t);const item=service.ingest(event),batch=store.prepare([item],{to:[]});
store.saveSettings({...store.settings(),maxAttempts:1});store.recover();assert.equal(store.items()[0].status,'exhausted');
store.saveSettings({...store.settings(),maxAttempts:3});assert.equal(store.items()[0].status,'exhausted');
service.retryItem(item.id,{batchId:batch,note:'已核实未发送且完成连接修复'},'admin');const second=store.prepare(store.items(),{to:[]});store.beginSending(second);store.recover();assert.equal(store.items()[0].status,'unknown');
assert.throws(()=>service.retryItem(item.id,{batchId:second,note:'不能绕过未知发送结果核验'},'admin'),e=>e.status===409);
store.recover();assert.equal(store.items()[0].status,'unknown');
const next=service.ingest({flow:{...event.flow,id:'lower-limit'}});store.db.prepare('UPDATE items SET attempts=2 WHERE id=?').run(next.id);store.saveSettings({...store.settings(),maxAttempts:2});assert.equal(store.items().find(i=>i.id===next.id).status,'exhausted');
});
test('manual retry resets only one exhausted item and stale evidence cannot reset its next failure',async t=>{
const {store,service}=await fixture(t);const first=service.ingest(event),second=service.ingest({flow:{...event.flow,id:'SECOND'}});store.saveSettings({...store.settings(),maxAttempts:1});const batchId=store.prepare([first,second],{to:[]});store.mark(batchId,'failed','fixture verify failure');
const input={batchId,note:'已修复 SMTP 并核实第一项未发送'};service.retryItem(first.id,input,'admin');assert.equal(store.items().find(i=>i.id===first.id).attempts,0);assert.equal(store.items().find(i=>i.id===second.id).status,'exhausted');assert.equal(store.items().find(i=>i.id===second.id).attempts,1);
const nextBatch=store.prepare([store.items().find(i=>i.id===first.id)],{to:[]});store.mark(nextBatch,'failed','fixture verify failure again');assert.throws(()=>service.retryItem(first.id,input,'admin'),e=>e.status===409);assert.equal(store.items().find(i=>i.id===first.id).attempts,1);assert.equal(retryHistory(store,first.id).length,1);
});
+39 -79
View File
@@ -1,83 +1,43 @@
'use strict';
const test=require('node:test');
const assert=require('node:assert/strict');
const crypto=require('node:crypto');
const fs=require('node:fs/promises');
const net=require('node:net');
const os=require('node:os');
const path=require('node:path');
const {main}=require('../src/server.cjs');
const {FileArea}=require('../src/storage-files.cjs');
const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),path=require('node:path'),os=require('node:os'),net=require('node:net'),crypto=require('node:crypto');
const {main}=require('../src/server.cjs'),{FileArea}=require('../src/storage-files.cjs');
const {activateReferenceMapping}=require('./fixtures/activate-field-mapping.cjs');
async function port(){const server=net.createServer();await new Promise(r=>server.listen(0,'127.0.0.1',r));const result=server.address().port;await new Promise(r=>server.close(r));return result;}
async function unusedPort(){
const server=net.createServer();await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);});
const port=server.address().port;await new Promise((resolve,reject)=>server.close(error=>error?reject(error):resolve()));return port;
}
test('isolated main integrates authenticated rule publication, real PDF/local archive and order browser evidence',{timeout:120000},async t=>{
const temporary=await fs.mkdtemp(path.join(os.tmpdir(),'order-pipeline-http-'));
let app,browser;const smtp={verified:0,sent:0},captured=[];
t.after(async()=>{
await browser?.close();
app?.dashboard.closeAllConnections();app?.server.closeAllConnections();
await app?.stop();
await fs.rm(temporary,{recursive:true,force:true});
});
const bridgePort=await unusedPort();let dashboardPort=await unusedPort();while(dashboardPort===bridgePort)dashboardPort=await unusedPort();
test('the canonical native app exposes one authenticated execution chain with real PDF archive and visible candidates',{timeout:120000},async t=>{
const temporary=await fs.mkdtemp(path.join(os.tmpdir(),'native-category-http-'));let app;
t.after(async()=>{app?.dashboard.closeAllConnections();app?.server.closeAllConnections();await app?.stop();await fs.rm(temporary,{recursive:true,force:true});});
const bridgePort=await port();let dashboardPort=await port();while(dashboardPort===bridgePort)dashboardPort=await port();
app=await main({stateDir:path.join(temporary,'state'),quiet:true,config:{port:bridgePort,outputDir:path.join(temporary,'pdf'),dashboard:{port:dashboardPort,host:'127.0.0.1'}}});
const base='http://127.0.0.1:'+dashboardPort,password='Isolated-http-password-123';
const call=async(route,body,cookie)=>{
const response=await fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{Origin:base,'Content-Type':'application/json'}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});
const text=await response.text();let data;try{data=JSON.parse(text);}catch{data={text};}return {status:response.status,data,cookie:response.headers.get('set-cookie')?.split(';')[0]};
};
const expect=async(route,body,cookie,status=200)=>{const result=await call(route,body,cookie);assert.equal(result.status,status,route+': '+JSON.stringify(result.data));return result;};
assert.equal((await call('/api/order-workflow')).status,401);
const bootstrap=await expect('/api/bootstrap',{username:'admin',password},undefined,201),adminCookie=bootstrap.cookie;
await expect('/api/users',{username:'operator',password,role:'operator'},adminCookie,201);
await expect('/api/users',{username:'viewer',password,role:'viewer'},adminCookie,201);
const operatorCookie=(await expect('/api/login',{username:'operator',password})).cookie;
const viewerCookie=(await expect('/api/login',{username:'viewer',password})).cookie;
app.scanner.store.saveConfig({enabled:false,intervalMinutes:5});
const connection=(await expect('/api/connections',{name:'HTTP 隔离 BPM 来源',owner:'operator'},adminCookie,201)).data;
const arrival={source:'portal-v4',taskId:'http-test-task-1',processName:'隔离海外订单评审',activityName:'订单专员(生效)',subject:'隔离订单简要说明第一行\n第二行保留原文',arrivedAt:'2026-10-22T01:00:00.000Z',arrivalDay:'2026-10-22',detailUrl:'https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/HttpFixtureV13.aspx?tid=900100&pid=900200'};
app.scanner.store.complete(app.scanner.store.begin(connection.id,'隔离测试'),connection.id,[arrival]);
const storedArrival=app.scanner.store.getArrival(connection.id,arrival.source,arrival.taskId);
assert.equal(storedArrival.detailUrl,arrival.detailUrl);
const fields={'OFR_WY_Applicant.OrderNum':'000321','OFR_WY_Applicant.SN':'HTTP-SERIAL-1','OFR_WY_Applicant.Revision':'HTTP-BV-1','OFR_WY_BInfo.ProductNum':'HTTP-PRODUCT','OFR_WY_BInfo.ProductModel':'HTTP-MODEL-FULL','OFR_WY_BInfo.ProductModelNEW':'HTTP-MODEL','OFR_WY_BInfo.CustomerName':'HTTP 客户'};
app.bpmSessions.captureOrderDetail=async(actualConnection,principal,actualArrival)=>{
assert.equal(actualConnection.id,connection.id);assert.equal(actualArrival.taskId,arrival.taskId);assert.equal(actualArrival.detailUrl,arrival.detailUrl);assert.ok(principal.sessionId);captured.push(actualArrival.taskId);
return {detail:{readOnly:true,tid:'900100',pid:'900200',processName:arrival.processName,nodeName:arrival.activityName,processVersion:'V13',fields:structuredClone(fields),processSteps:[{name:arrival.activityName,status:'处理中'}]},capturedAt:'2026-10-22T01:01:00.000Z',evidenceHash:crypto.createHash('sha256').update(JSON.stringify(fields)).digest('hex'),snapshot:{html:'<!doctype html><html><body><form><h1>隔离测试订单</h1><table><tr><td>订单号</td><td>000321</td></tr><tr><td>产品</td><td>HTTP-PRODUCT</td></tr></table></form></body></html>',styles:[]}};
};
const localArchive=path.join(temporary,'archive');await fs.mkdir(localArchive);const area=new FileArea(localArchive);
app.storage.client.area=async()=>area;
const server=app.storage.store.saveServer({name:'HTTP 隔离本地归档',host:'archive.example.test',share:'fixture',directory:'',authMode:'windows',enabled:true});
await app.storage.check(server.id);
const channel=app.mail.store.saveChannel({name:'HTTP 隔离发件箱',email:'sender@example.test',enabled:false,senders:['author@example.test'],smtp:{host:'smtp.example.test',port:465,security:'tls',user:'sender@example.test',password:'Synthetic-smtp-password'},imap:{host:'imap.example.test',port:993,security:'tls',user:'sender@example.test',password:'Synthetic-imap-password'}});
app.mail.smtpFactory=()=>({async verify(){smtp.verified++;},async sendMail(){smtp.sent++;return {accepted:['2639266652@qq.com'],rejected:[]};},close(){}});
const draft=app.mail.store.ingest(channel.id,'fixture',1,{subject:'{{产品线}} {{订单号}}',scope:'HTTP 隔离产品线',text:'{{日期}}\n{{订单列表}}',html:'<p>{{订单列表}}</p>',sender:'author@example.test',messageId:'<http-isolated-template@example.test>',attachments:[],notes:[]},Buffer.alloc(0),channel.version);
const template=app.mail.store.confirm(draft.id,{version:draft.version,subject:'{{产品线}} {{订单号}}',scope:'HTTP 隔离产品线',useText:false},'admin');
assert.equal(template.status,'active');assert.equal(app.mail.store.source(template.id).length,0);
const settings=(await expect('/api/settings',undefined,adminCookie)).data;
await expect('/api/settings',{version:settings.version,groups:[{productLine:'HTTP 隔离产品线',to:['2639266652@qq.com'],cc:[]}]},adminCookie);
const runtimeConfig=app.pipeline.config();await expect('/api/order-workflow/settings',{...runtimeConfig,serverId:server.id,channelId:channel.id,enabled:false,sendEnabled:false},adminCookie);
const rule={id:'http-category-rule',enabled:true,processName:arrival.processName,nodeName:arrival.activityName,productLine:'HTTP 隔离产品线',templateId:template.id,pdfTemplateId:'bpm-snapshot-v1',recipientGroupId:'HTTP 隔离产品线',notificationType:'order',batchMode:'category_template',adapters:{V13:{orderNo:'OFR_WY_Applicant.OrderNum',serialNo:'OFR_WY_Applicant.SN',businessVersion:'OFR_WY_Applicant.Revision',productCode:'OFR_WY_BInfo.ProductNum',modelFull:'OFR_WY_BInfo.ProductModel',modelShort:'OFR_WY_BInfo.ProductModelNEW',customer:'OFR_WY_BInfo.CustomerName',brief:{source:'arrival',path:'subject'}}}};
await expect('/api/order-workflow/rules',rule,viewerCookie,403);
const saved=(await expect('/api/order-workflow/rules',rule,adminCookie)).data;assert.equal(saved.status,'draft');
const checked=(await expect('/api/order-workflow/rules/'+rule.id+'/check',{connectionId:connection.id,source:arrival.source,taskId:arrival.taskId},adminCookie)).data;assert.equal(checked.valid,true,JSON.stringify(checked.issues));assert.equal(checked.sample.fields['OFR_WY_Applicant.OrderNum'],'000321');
await expect('/api/order-workflow/rules/'+rule.id+'/publish',{version:saved.version,checkId:checked.checkId},operatorCookie,403);
const published=(await expect('/api/order-workflow/rules/'+rule.id+'/publish',{version:saved.version,checkId:checked.checkId},adminCookie)).data;assert.equal(published.status,'published');
assert.equal(app.workflow.listOrders().length,0);assert.equal(app.pipeline.config().enabled,false);assert.equal(app.pipeline.config().sendEnabled,false);assert.equal(smtp.sent,0);
const order=await app.pipeline.process(storedArrival,{user:bootstrap.data.user,sessionId:'explicit-isolated-pipeline-test'});
assert.equal(order.status,'notification_pending',JSON.stringify(order));assert.equal(order.businessVersion,'HTTP-BV-1');assert.equal(order.steps.pdf.status,'success');assert.equal(order.steps.archive.status,'success');assert.equal(order.brief,arrival.subject);
const receipt=app.storage.store.archives().find(record=>record.id===order.archive.archiveId);assert.equal(receipt.status,'success');assert.match(receipt.relativePath,/^000321\//);
const archivedBytes=await fs.readFile(path.join(localArchive,...receipt.relativePath.split('/')));assert.equal(archivedBytes.subarray(0,5).toString(),'%PDF-');assert.equal(archivedBytes.length,receipt.bytes);assert.equal(crypto.createHash('sha256').update(archivedBytes).digest('hex'),receipt.sha256);assert.equal(order.archive.sha256,receipt.sha256);
const mirror=app.notifications.store.items().find(item=>item.orderVersionKey===order.versionKey);assert.ok(mirror);assert.equal(mirror.status,'pending');assert.equal(mirror.owner,'order-workflow');assert.equal(mirror.brief,arrival.subject);assert.equal(mirror.templateId,template.id);
const before=await fs.readdir(path.join(localArchive,'000321'));await app.pipeline.process(storedArrival,{user:bootstrap.data.user,sessionId:'duplicate-isolated-test'});assert.deepEqual(await fs.readdir(path.join(localArchive,'000321')),before);assert.equal(app.workflow.listOrders().length,1);assert.equal(app.notifications.store.items().filter(item=>item.owner==='order-workflow').length,1);
assert.equal(captured.length,3);assert.equal(smtp.sent,0);assert.equal(smtp.verified,0);
browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1280,height:900}}),pageErrors=[];page.on('pageerror',error=>pageErrors.push(error.message));
await page.goto(base+'/#order-center');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill(password);await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('heading',{name:'订单任务',exact:true}).waitFor();await page.locator('#content tbody tr').filter({hasText:'000321'}).first().waitFor();await page.getByRole('button',{name:'查看详情',exact:true}).click();await page.getByText('detail.OFR_WY_Applicant.OrderNum',{exact:true}).waitFor();await page.getByText('list.receivedAt',{exact:false}).waitFor();assert.deepEqual(pageErrors,[]);
const viewerPage=await browser.newPage();await viewerPage.goto(base+'/#order-rules');await viewerPage.getByLabel('账号',{exact:true}).fill('viewer');await viewerPage.getByLabel('密码',{exact:true}).fill(password);await viewerPage.getByRole('button',{name:'登录',exact:true}).click();await viewerPage.getByRole('heading',{name:'分类规则',exact:true}).waitFor();assert.equal(await viewerPage.getByRole('button',{name:'新增分类规则',exact:true}).count(),0);assert.equal(await viewerPage.getByRole('button',{name:'编辑规则',exact:true}).count(),0);
const summary=(await expect('/api/order-workflow',undefined,viewerCookie)).data;assert.equal(summary.orders[0].versionKey,order.versionKey);assert.equal(summary.settings.sendEnabled,false);assert.equal(summary.batches.length,0);
assert.equal(smtp.sent,0);assert.equal(app.scanner.store.config().enabled,false);
await app.bpmMonitor.stop();await app.scanner.stop();
assert.equal(app.pipeline,undefined);assert.ok(app.orderExecution);assert.ok(app.orderDispatcher);
const base='http://127.0.0.1:'+dashboardPort,password='Isolated-fixture-password-123';
async function call(route,body,cookie,status=200){const response=await fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{Origin:base,'Content-Type':'application/json'}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});const data=await response.json();assert.equal(response.status,status,route+': '+JSON.stringify(data));return {data,cookie:response.headers.get('set-cookie')?.split(';')[0]};}
await call('/api/order-execution',undefined,undefined,401);
const admin=(await call('/api/bootstrap',{username:'admin',password},undefined,201)).cookie;
await call('/api/users',{username:'operator',password,role:'operator'},admin,201);await call('/api/users',{username:'viewer',password,role:'viewer'},admin,201);
const operator=(await call('/api/login',{username:'operator',password})).cookie,viewer=(await call('/api/login',{username:'viewer',password})).cookie;
const connection=(await call('/api/connections',{name:'隔离通知来源',owner:'operator'},admin,201)).data;
const fields={'OFR_BS_Applicant.OrderNum':'000321','OFR_BS_Applicant.AppDate':'2026-10-23','OFR_BS_BInfo.CustomerName':'隔离客户','OFR_BS_Applicant.ProductLine':'来源产品线','OFR_BS_Applicant.ChangeReason':'隔离原因','OFR_BS_Applicant.OrderChangeContent':'隔离内容'};
const activated=activateReferenceMapping(app.orderRules,'bs-change',{connectionId:connection.id,instanceId:'900100',taskId:'900200',revision:undefined,receivedAt:new Date().toISOString(),serialNum:'HTTP-FIXTURE',title:'前置说明 订单号:000321 客户:隔离客户',fields});
const row={source:'todo',portalSource:'portal-v4',instanceId:'900100',taskId:'900200',processName:activated.sample.processName,processVersion:activated.sample.processVersion,nodeName:activated.sample.nodeName,receivedAt:activated.sample.receivedAt,serialNum:'HTTP-FIXTURE',title:activated.sample.title,detailUrl:'https://bpm.skyworthdigital.com/sso/ssologin.aspx?'+new URLSearchParams({ReturnUrl:'/YZSoft/Forms/Process.aspx?tid=900100&pid=900200',todo_token:'EPHEMERAL-FIXTURE',todo_account:'fixture'})};
app.bpmSessions.vault=()=>({read:async()=>({storageState:{cookies:[],origins:[]}}),destroy(){}});
app.orderExecution.provider.client={scan:async()=>[row]};
app.orderExecution.provider.readonlyReader=async()=>({detailUrl:'https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/备损更改订单评审V2.aspx?tid=900100&pid=900200',capturedAt:new Date().toISOString(),evidenceHash:'fixture-evidence',detail:{tid:'900100',pid:'900200',formVersion:'V2',formPath:'/YZSoft/Forms/XForm/备损更改订单评审V2.aspx',fields,fieldSources:{}},snapshot:{html:'<form><table><tr><td>订单号</td><td>000321</td></tr></table></form>',styles:[],images:[]}});
const archiveRoot=path.join(temporary,'archive');await fs.mkdir(archiveRoot);const area=new FileArea(archiveRoot);app.storage.client={area:async()=>area};
const server=app.storage.store.saveServer({name:'隔离存储',host:'archive.example.test',share:'fixture',directory:'',authMode:'windows',enabled:true});await app.storage.check(server.id);
const draft=app.orderRules.get('rules','bs-change').draft;
const configured={...draft,productLine:'分类指定产品线',adapterIds:[activated.active.id],filenameDate:'receivedAt',archiveDirectory:'\\\\archive.example.test\\fixture\\orders',attachPdf:false,to:['2639266652@qq.com'],cc:[]};
await call('/api/order-rules/rules',configured,viewer,403);await call('/api/order-rules/rules',configured,admin);
const checked=(await call('/api/order-rules/preview',{sampleId:activated.captured.id},admin)).data;assert.equal(checked.valid,true,JSON.stringify(checked));
const version=app.orderRules.get('rules','bs-change').draft.version;
await call('/api/order-rules/rules/bs-change/publish',{version},operator,403);await call('/api/order-rules/rules/bs-change/publish',{version},admin);
let smtpCalls=0;app.mail.smtpFactory=()=>{smtpCalls++;throw Error('Fixture forbids external SMTP');};
await call('/api/order-execution/scan',{connectionId:connection.id,idempotencyKey:'native-first-scan'},viewer,403);await call('/api/order-execution/scan',{connectionId:connection.id,idempotencyKey:'native-first-scan'},operator);
const order=app.orderRules.all('orders')[0];assert.equal(order.status,'pending',JSON.stringify(order));assert.equal(Object.hasOwn(order.sample,'revision'),false);assert.equal(order.event.productLine,'分类指定产品线');assert.equal(order.sample.title,row.title);assert.equal(order.archive.files.length,1);
const bytes=await app.orderExecution.archive.read(order.archive.files[0]);assert.equal(bytes.subarray(0,5).toString(),'%PDF-');assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'),order.archive.files[0].sha256);
const before=await fs.readdir(path.join(archiveRoot,'orders'));await call('/api/order-execution/scan',{connectionId:connection.id,idempotencyKey:'native-second-scan'},operator);assert.equal(app.orderRules.all('orders').length,1);assert.deepEqual(await fs.readdir(path.join(archiveRoot,'orders')),before);
const list=(await call('/api/order-rules/orders',undefined,operator)).data;assert.equal(list.items[0].id,order.id);const details=(await call('/api/order-rules/orders/'+order.id,undefined,operator)).data;assert.equal(details.files.length,1);assert.equal(details.event.taskId,row.taskId);
row.taskId='900201';row.nodeName='小湃BOM创建';await call('/api/order-execution/scan',{connectionId:connection.id,idempotencyKey:'candidate-scan'},operator);
const candidates=(await call('/api/order-rules/orders?status=candidate',undefined,operator)).data;assert.equal(candidates.total,1);assert.equal(candidates.items[0].status,'candidate');assert.equal(smtpCalls,0);assert.equal(app.orderRules.all('batches').length,0);
});
@@ -0,0 +1,20 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),os=require('node:os');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
const {MailStore}=require('../../src/modules/mail/store.cjs');
test('an outer configuration migration rolls back all nested supported updates and can commit a complete retry',t=>{
const directory=fs.mkdtempSync(path.join(os.tmpdir(),'atomic-rule-migration-')),store=new RuleStore(directory);t.after(()=>{store.close();fs.rmSync(directory,{recursive:true,force:true});});
const rule=store.get('rules','bs-change').draft,settings=store.settings();
const change=()=>{store.saveRule({...store.get('rules','bs-change').draft,subjectPrefix:'隔离迁移主题',attachPdf:false},'admin');store.saveSettings({...store.settings(),maxMessageBytes:1048576},'admin');};
assert.throws(()=>store.transaction(()=>{change();throw Error('fixture-migration-rollback');}),/fixture-migration-rollback/);
assert.deepEqual(store.get('rules','bs-change').draft,rule);assert.deepEqual(store.settings(),settings);
store.transaction(change);assert.equal(store.get('rules','bs-change').draft.subjectPrefix,'隔离迁移主题');assert.equal(store.settings().maxMessageBytes,1048576);
});
test('nested mailbox template preparation can roll back every new object without sending',t=>{
const directory=fs.mkdtempSync(path.join(os.tmpdir(),'atomic-mail-migration-')),store=new MailStore(directory);t.after(()=>{store.close();fs.rmSync(directory,{recursive:true,force:true});});
const work=()=>{const c=store.saveChannel({name:'隔离邮箱',email:'sender@example.test',enabled:false,senders:['source@example.test'],smtp:{host:'smtp.example.test',port:465,security:'tls',user:'fixture',password:'fixture'},imap:{host:'imap.example.test',port:993,security:'tls',user:'fixture',password:'fixture'}});const draft=store.ingest(c.id,'fixture',1,{subject:'隔离 {{订单号}}',scope:'fixture-scope',text:'{{订单列表}}',html:'',attachments:[],notes:[],sender:'source@example.test'},Buffer.from('fixture-template'),c.version);store.confirm(draft.id,{version:draft.version,subject:draft.subject,scope:draft.scope,useText:false},'admin');};
assert.throws(()=>store.transaction(()=>{work();throw Error('fixture-template-rollback');}),/fixture-template-rollback/);
assert.equal(store.channels().length,0);assert.equal(store.templates().length,0);assert.equal(store.receipts().length,0);
store.transaction(work);assert.equal(store.templates()[0].status,'active');assert.equal(store.sends().length,0);
});
+200
View File
@@ -0,0 +1,200 @@
'use strict';
const test=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const crypto=require('node:crypto');
const {transition}=require('../../src/modules/order-rules/state.cjs');
const {buildBatch}=require('../../src/modules/order-rules/batch.cjs');
const cutoff='2026-10-19T01:00:00.000Z';
function rule(patch={}){return {id:'r1',version:1,categoryId:'notice',name:'订单通知',subjectPrefix:'订单通知',intro:'请处理以下订单。',signature:'业务部',to:['USER@example.com','user@example.com'],cc:['copy@example.com','USER@example.com'],attachPdf:false,archiveDirectory:'\\\\nas\\orders',...patch};}
function order(id='1',patch={}){return {id,event:{orderNo:`SO-${id}`,brief:'型号 <script>alert(1)</script>',receivedAt:'2026-10-19T00:00:00.000Z'},ruleSnapshot:rule(),archive:{archivedAt:'2026-10-19T00:30:00.000Z',files:[{name:`SO-${id}.pdf`,path:`\\\\nas\\orders\\SO-${id}.pdf`,sha256:'a'.repeat(64),size:100,kind:'pdf'}]},...patch};}
test('state actions enforce archive, pending and batch progression without skipping evidence stages',()=>{
assert.equal(transition('order','identified','prepare'),'preparing');
assert.equal(transition('order','preparing','archive'),'archived');
assert.equal(transition('order','archived','queue'),'pending');
assert.equal(transition('order','pending','batch'),'batched');
assert.equal(transition('order','batched','sent'),'sent');
assert.throws(()=>transition('order','identified','sent'),{status:409});
assert.throws(()=>transition('order','blocked','sent'),{status:409});
assert.throws(()=>transition('batch','failed','send'),{status:409});
assert.throws(()=>transition('batch','unknown','send'),{status:409});
assert.equal(transition('batch','prepared','send'),'sending');
assert.equal(transition('batch','sending','unknown'),'unknown');
assert.equal(transition('batch','unknown','resolve_sent'),'sent');
assert.equal(transition('batch','unknown','retry'),'cancelled');
});
test('batch includes every order above 200 with subject numbers and normalized independent recipients',()=>{
const orders=Array.from({length:205},(_,i)=>order(String(i+1)));
const batch=buildBatch(rule(),orders,cutoff);
assert.equal(batch.orderIds.length,205);
assert.deepEqual(batch.attachments,[]);
assert.match(batch.subject,/SO-1/);assert.match(batch.subject,/SO-205/);
assert.deepEqual(batch.to,['user@example.com']);assert.deepEqual(batch.cc,['copy@example.com']);
assert.equal(batch.cutoff,cutoff);
orders[0].archive.files[0].name='mutated';orders[0].event.orderNo='mutated';
assert.equal(batch.orderNos[0],'SO-1');assert.match(batch.text,/订单号:SO-1/);
});
test('mail keeps intro signature and escaped summaries with blue clickable UNC evidence',()=>{
const batch=buildBatch(rule({intro:'<团队>',signature:'研发 & 业务'}),[order()],cutoff);
assert.match(batch.text,/<团队>/);assert.match(batch.text,/研发 & 业务/);
assert.match(batch.html,/&lt;script&gt;/);assert.doesNotMatch(batch.html,/<script>/);
assert.match(batch.html,/href="file:\/\/nas\/orders\/?"/);
assert.match(batch.html,/color:\s*#(?:00f|0000ff)/i);
assert.match(batch.html,/&lt;团队&gt;/);
});
test('missing required PDF or archive evidence blocks the entire category',()=>{
assert.throws(()=>buildBatch(rule(),[order(),order('2',{archive:null})],cutoff),/归档/);
const onlyNotice=order('2');onlyNotice.archive.files[0].kind='notice';
assert.throws(()=>buildBatch(rule(),[order(),onlyNotice],cutoff),/PDF/);
const badEvidence=order('2');delete badEvidence.archive.files[0].sha256;
assert.throws(()=>buildBatch(rule(),[badEvidence],cutoff),/证据/);
});
test('mixed categories, rule versions, duplicate IDs and after-cutoff items are rejected instead of omitted',()=>{
const other=order('2');other.ruleSnapshot.categoryId='change';
assert.throws(()=>buildBatch(rule(),[order(),other],cutoff),/类别/);
const revised=order('2');revised.ruleSnapshot.version=2;
assert.throws(()=>buildBatch(rule(),[order(),revised],cutoff),/版本/);
assert.throws(()=>buildBatch(rule(),[order(),order()],cutoff),/重复/);
const later=order('2');later.event.receivedAt='2026-10-19T02:00:00.000Z';
assert.throws(()=>buildBatch(rule(),[later],cutoff),/截止/);
});
test('strict recipient parsing rejects header injections and malformed lists',()=>{
for(const address of ['a@example.com\r\nBcc: intruder@example.com','Name <a@example.com>','a@@example.com','a@example.com,other@example.com','a@localhost','a..b@example.com']){
assert.throws(()=>buildBatch(rule({to:[address]}),[order()],cutoff),/邮箱|收件/);
}
assert.throws(()=>buildBatch(rule({to:[]}),[order()],cutoff),/收件/);
});
test('message size estimate rejects oversize order content rather than truncating',()=>{
const large=order();large.event.brief='型号'.repeat(15000);
assert.throws(()=>buildBatch(rule(),[large],cutoff,{maxMessageBytes:20000}),/大小|容量/);
});
test('an explicit batch window rejects historical orders and excludes its upper boundary',()=>{
const window={start:'2026-10-19T00:00:00.000Z',end:cutoff,startInclusive:true,endInclusive:false};
const old=order('old');old.event.receivedAt='2026-10-18T23:59:59.999Z';
assert.throws(()=>buildBatch(rule(),[old,order()],cutoff,{window}),/时段|窗口/);
const boundary=order('boundary');boundary.event.receivedAt=cutoff;
assert.throws(()=>buildBatch(rule(),[boundary],cutoff,{window}),/时段|窗口/);
const batch=buildBatch(rule(),[order(),order('2')],cutoff,{window});
assert.deepEqual(batch.orderIds,['1','2']);assert.equal(batch.window.start,'2026-10-19T00:00:00.000Z');assert.equal(batch.window.end,cutoff);
});
test('batch refuses inverted windows and windows that do not end at its cutoff',()=>{
for(const window of [{start:cutoff,end:'2026-10-19T00:00:00.000Z'},{start:'2026-10-18T00:00:00.000Z',end:'2026-10-19T02:00:00.000Z'}]){
assert.throws(()=>buildBatch(rule(),[order()],cutoff,{window}),/时段|窗口/);
}
});
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
const dispatchCutoff='2026-10-20T01:00:00.000Z';
const dispatchWindow={start:'2026-10-19T09:00:00.000Z',end:dispatchCutoff,label:'当天首时段',startInclusive:true,endInclusive:false};
function dispatchFixture(t,{ready=true,capabilities=true,enabled=true,verify,send,result}={}){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'rule-batch-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
const content=Buffer.from('%PDF-1.7\ntrusted evidence');const file=path.join(dir,'order.pdf');fs.writeFileSync(file,content);
const batch={id:'batch1',status:'prepared',categoryId:'notice',subject:'已冻结 SO-1',text:'原正文',html:'<p>原正文</p>',to:['2639266652@qq.com'],cc:[],attachments:[],cutoff:dispatchCutoff,window:structuredClone(dispatchWindow)};
const record={prepared:0,begun:0,smtp:0,locked:0,status:'prepared',messages:[],sent:[]};
const config={version:1,enabled,channelId:'channel1'};
const caps={liveTodo:capabilities,pdfExport:capabilities,automaticArchive:capabilities};
const store={discoveryBlockers:()=>[],batchIncomplete:()=>false,settings:()=>({...config}),snapshot:()=>({capabilities:{...caps},batches:[structuredClone({...batch,status:record.status})]}),prepare:(date,actor,window)=>{record.prepared++;assert.equal(date,dispatchCutoff);assert.equal(actor,'系统调度');assert.equal(window.start,'2026-10-19T09:00:00.000Z');assert.equal(window.end,dispatchCutoff);assert.equal(window.startInclusive,true);assert.equal(window.endInclusive,false);return [batch];},beginSending:id=>{assert.equal(id,'batch1');record.begun++;record.status='sending';},finishSending:(id,status,message)=>{assert.equal(id,'batch1');record.status=status;record.messages.push(message);}};
const mail={exclusive:async(id,fn)=>{assert.equal(id,'channel1');record.locked++;return fn();},store:{channelSecret:id=>({id,version:2,email:'sender@example.com',name:'通知',smtp:{host:'unused.invalid'}}),guard:(id,version)=>{assert.equal(id,'channel1');assert.equal(version,2);}},smtpFactory:()=>{record.smtp++;return {verify:async()=>{if(verify)await verify({batch,config,caps,file});},sendMail:async message=>{record.sent.push(message);if(send)return send(message);return result||{accepted:['2639266652@qq.com'],rejected:[]};},close:()=>{}};}};
const schedule={times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:false,mode:'product_line',missed:'next_window'};
let now=new Date('2026-10-20T00:59:00.000Z');
const dispatcher=new OrderRuleDispatcher({store,mail,settings:()=>({schedule}),calendar:()=>[],clock:()=>now,providersReady:()=>ready});
return {dispatcher,store,mail,record,batch,config,caps,file,setNow:value=>{now=new Date(value);}};
}
async function due(f){await f.dispatcher.tick();f.setNow(dispatchCutoff);await f.dispatcher.tick();}
test('dispatcher never prepares or touches SMTP while disabled or any provider is unverified',async t=>{
for(const input of [{enabled:false},{ready:false},{capabilities:false}]){
const f=dispatchFixture(t,input);await due(f);assert.equal(f.record.prepared,0);assert.equal(f.record.smtp,0);assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
}
});
test('dispatcher sends the frozen recipients and attachment-free content once per schedule',async t=>{
const f=dispatchFixture(t,{verify:({batch})=>{batch.subject='changed';batch.to=['intruder@example.com'];}});
await due(f);await f.dispatcher.tick();
assert.equal(f.record.status,'sent');assert.equal(f.record.prepared,2);assert.equal(f.record.begun,1);assert.equal(f.record.locked,2);
const sent=f.record.sent[0];assert.equal(sent.subject,'已冻结 SO-1');assert.deepEqual(sent.to,['2639266652@qq.com']);assert.deepEqual(sent.cc,[]);
assert.deepEqual(sent.attachments,[]);assert.equal(sent.disableFileAccess,true);assert.equal(sent.disableUrlAccess,true);
await f.dispatcher.stop();
});
test('dispatcher blocks legacy frozen attachments before SMTP or sending transition',async t=>{
const f=dispatchFixture(t);f.batch.attachments=[{name:'old.pdf',path:f.file,size:1,sha256:'a'.repeat(64),kind:'pdf'}];await due(f);
assert.equal(f.record.status,'failed');assert.equal(f.record.begun,0);assert.equal(f.record.smtp,0);assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
});
test('dispatcher maps pre-send verify failure to failed and post-begin errors or partial acceptance to unknown',async t=>{
for(const [input,wanted,begun] of [[{verify:()=>{throw Error('verify failure');}},'failed',0],[{send:()=>{throw Error('socket dropped');}},'unknown',1],[{result:{accepted:[],rejected:['2639266652@qq.com']}},'unknown',1]]){
const f=dispatchFixture(t,input);await due(f);assert.equal(f.record.status,wanted);assert.equal(f.record.begun,begun);await f.dispatcher.stop();
}
});
test('dispatcher rechecks pause and provider gates after SMTP verification',async t=>{
for(const change of [({config})=>{config.enabled=false;},({caps})=>{caps.pdfExport=false;}]){
const f=dispatchFixture(t,{verify:change});await due(f);assert.equal(f.record.begun,0);assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
}
});
test('dispatcher uses business calendar to skip paused days and stop prevents further sends',async t=>{
const f=dispatchFixture(t);f.dispatcher.calendar=()=>[{date:'2026-10-20',kind:'pause'}];await due(f);assert.equal(f.record.prepared,0);
await f.dispatcher.stop();f.dispatcher.calendar=()=>[];await f.dispatcher.tick();assert.equal(f.record.sent.length,0);
});
test('dispatcher acquires mailbox before preparing and retries the same slot when busy',async t=>{
const f=dispatchFixture(t);const exclusive=f.mail.exclusive;let busy=true;
f.mail.exclusive=async(id,work)=>{if(busy)throw Object.assign(Error('busy'),{status:409});return exclusive(id,work);};
await due(f);assert.equal(f.record.prepared,0);assert.equal(f.record.sent.length,0);
busy=false;await f.dispatcher.tick();assert.equal(f.record.prepared,1);assert.equal(f.record.status,'sent');await f.dispatcher.stop();
});
test('dispatcher recovers a manually prepared batch even when no new orders can be prepared',async t=>{
const f=dispatchFixture(t);f.store.prepare=()=>[];
await due(f);assert.equal(f.record.sent.length,1);assert.equal(f.record.status,'sent');await f.dispatcher.stop();
});
test('dispatcher refuses a prepared snapshot frozen to a different mailbox before SMTP',async t=>{
const f=dispatchFixture(t);f.batch.channelId='old-channel';
await due(f);assert.equal(f.record.status,'failed');assert.equal(f.record.smtp,0);assert.equal(f.record.begun,0);assert.equal(f.record.sent.length,0);assert.match(f.record.messages[0],/邮箱|渠道/);await f.dispatcher.stop();
});
test('dispatcher never carries a prepared morning batch into the afternoon slot after a pause',async t=>{
const f=dispatchFixture(t);let prepareCount=0;
f.store.prepare=()=>{prepareCount++;if(prepareCount===1){f.config.enabled=false;return [f.batch];}return [];};
await due(f);assert.equal(f.record.begun,0);
f.config.enabled=true;f.setNow('2026-10-20T08:59:00.000Z');await f.dispatcher.tick();
f.setNow('2026-10-20T09:00:00.000Z');await f.dispatcher.tick();
assert.equal(f.record.status,'failed');assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
});
test('dispatcher ignores old, future and mismatched-window prepared batches at the current slot',async t=>{
for(const mutate of [b=>{b.cutoff='2026-10-19T09:00:00.000Z';},b=>{b.cutoff='2026-10-20T09:00:00.000Z';},b=>{b.window.start='2026-10-18T16:00:00.000Z';},b=>{delete b.window;}]){
const f=dispatchFixture(t);mutate(f.batch);f.store.prepare=()=>[];await due(f);assert.equal(f.record.sent.length,0);assert.equal(f.record.smtp,0);await f.dispatcher.stop();
}
});
test('dispatcher resumes a paused prepared batch only within the same slot grace',async t=>{
const f=dispatchFixture(t);let preparation=0;
f.store.prepare=()=>{preparation++;if(preparation===1){f.config.enabled=false;return [f.batch];}return [];};
await due(f);assert.equal(f.record.sent.length,0);f.setNow('2026-10-20T01:00:15.000Z');await f.dispatcher.tick();
f.config.enabled=true;f.setNow('2026-10-20T01:00:30.000Z');await f.dispatcher.tick();
assert.equal(f.record.sent.length,1);await f.dispatcher.stop();
});
test('dispatcher resumes a frozen batch after collection ends within queue allowance',async t=>{
const f=dispatchFixture(t);const exclusive=f.mail.exclusive;let busy=true;
f.mail.exclusive=async(id,work)=>{if(busy)throw Object.assign(Error('busy'),{status:409});return exclusive(id,work);};
await due(f);busy=false;f.setNow('2026-10-20T01:01:01.000Z');await f.dispatcher.tick();assert.equal(f.record.prepared,0);assert.equal(f.record.sent.length,1);await f.dispatcher.stop();
});
test('dispatcher rechecks thirty minute queue expiration after asynchronous SMTP verification',async t=>{
const f=dispatchFixture(t,{verify:()=>f.setNow('2026-10-20T01:30:01.000Z')});
await due(f);assert.equal(f.record.begun,0);assert.equal(f.record.sent.length,0);assert.equal(f.record.status,'failed');await f.dispatcher.stop();
});
@@ -0,0 +1,33 @@
'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');
const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function setup(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'business-config-ui-')),runtime=await startTestDashboard({stateDir:dir,mailHistory:true}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(6000);return {runtime,page};}
test('business editor selects configured template and server folder, preserves draft on browse failures and guards switching', {timeout:60000},async t=>{
const {page,runtime}=await setup(t),mail=runtime.mail.store;
const config={name:'测试邮箱',email:'orders@example.test',senders:['author@example.test'],enabled:false,smtp:{host:'smtp.example.test',port:465,security:'tls',user:'orders',password:'Test-only-password'},imap:{host:'imap.example.test',port:993,security:'tls',user:'orders',password:'Test-only-password'}},channel=mail.saveChannel(config);
const raw=Buffer.from('From: author@example.test\r\nTo: orders@example.test\r\nSubject: [模板]Configured notice\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nConfigured body {{订单列表}}');
const parsed=await require('../../src/modules/mail/parser.cjs').parseTemplate(raw,config),draft=mail.ingest(channel.id,'1',1,parsed,raw,channel.version),template=mail.confirm(draft.id,{version:1,subject:parsed.subject,scope:parsed.scope,useText:false,text:parsed.text},'admin');
activateReferenceMapping(runtime.orderRules);runtime.orderRules.templateResolver=(categoryId,rule)=>require('../../src/modules/mail/rule-template.cjs').ruleTemplate(mail,categoryId,rule);await page.route('**/api/order-rules/fields',r=>r.fulfill({json:runtime.orderRules.fields()}));
let browseFails=true;await page.route('**/api/storage',r=>r.fulfill({json:{servers:[{id:'fixture-server',name:'测试存储',host:'fixture',share:'orders',directory:'archive',enabled:true,state:{readable:true,writable:true}}]}}));
await page.route('**/api/storage/servers/fixture-server/files?**',route=>browseFails?route.fulfill({status:503,json:{error:'临时断线'}}):route.fulfill({json:{path:new URL(route.request().url()).searchParams.get('path')||'',entries:new URL(route.request().url()).searchParams.get('path')?[]:[{name:'分类文件夹',type:'directory'}],truncated:false}}));
await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');await login(page);await page.locator('[data-rule-id="bs-change"]').click();
assert.equal(await page.locator('.rule-validation-column').count(),0);assert.equal(await page.locator('[data-adapter-choice]').count(),0);assert.equal(await page.locator('#order-rule-advanced').count(),0);
await page.getByLabel('邮件模板',{exact:true}).selectOption(template.id);await page.getByLabel('存储服务器',{exact:true}).selectOption('fixture-server');await page.getByLabel('服务器内文件夹',{exact:true}).fill('changes');
await page.getByRole('button',{name:'浏览',exact:true}).click();await page.getByText(/文件夹读取失败:临时断线/).waitFor();assert.equal(await page.getByLabel('邮件模板',{exact:true}).inputValue(),template.id);assert.equal(await page.getByLabel('服务器内文件夹',{exact:true}).inputValue(),'changes');
browseFails=false;await page.getByLabel('服务器内文件夹',{exact:true}).fill('');await page.getByRole('button',{name:'浏览',exact:true}).click();await page.getByRole('button',{name:'▱ 分类文件夹',exact:true}).click();await page.getByRole('button',{name:'使用此文件夹',exact:true}).click();
await page.getByLabel('文件名日期依据',{exact:true}).selectOption('receivedAt');await page.getByLabel('收件人',{exact:true}).fill('orders@example.test');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();const saved=runtime.orderRules.get('rules','bs-change').draft;assert.equal(saved.bodyTemplateId,template.id);assert.equal(saved.archiveDirectory,'\\\\fixture\\orders\\archive\\分类文件夹');
await page.getByRole('button',{name:'检查识别结果',exact:true}).click();await page.locator('#order-rule-preview-result').getByText('已保存规则通过真实订单检查,可以继续核对并发布。',{exact:true}).waitFor();await page.getByRole('button',{name:'检查识别结果',exact:true}).waitFor();assert.match(await page.locator('#order-rule-preview-result').textContent(),/Configured body/);
await page.getByLabel('规则名称',{exact:true}).fill('尚未保存的分类');await page.locator('[data-rule-id="bs-notice"]').click();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'尚未保存的分类');
await page.locator('[data-rule-toggle="bs-change"]').click();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.getByText(/此分类尚未发布。/).waitFor();assert.equal(runtime.orderRules.get('rules','bs-change').published,null);assert.equal(runtime.orderRules.settings().enabled,false);await page.locator('[data-rule-id="bs-notice"]').click();assert.equal(await page.getByRole('dialog',{name:'未保存的修改'}).count(),0);
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
});
test('Excel import reads xls in a worker, previews rows, commits once, downloads xlsx and displays invalid rows', {timeout:60000},async t=>{
const {page,runtime}=await setup(t),XLSX=require('xlsx'),sheet=XLSX.utils.aoa_to_sheet([['类别编号','分类名称','订单评审流程','电子流状态','服务器存档地址','邮件命名','收件人','附带PDF'],['bs-change','备损订单更改通知书','备损订单更改评审','订单专员(订单通知书)','备损订单','【备损订单更改通知书】','orders@example.test','是']]),book=XLSX.utils.book_new();XLSX.utils.book_append_sheet(book,sheet,'分类规则');
await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');await login(page);await page.getByRole('button',{name:'导入 Excel',exact:true}).click();
const before=runtime.orderRules.get('rules','bs-change').draft.version;
await page.locator('#rule-import-file').setInputFiles({name:'分类.xls',mimeType:'application/vnd.ms-excel',buffer:XLSX.write(book,{type:'buffer',bookType:'biff8'})});await page.getByRole('button',{name:'确认导入 1 类草稿',exact:true}).waitFor();assert.equal(runtime.orderRules.get('rules','bs-change').draft.version,before);
await page.getByRole('button',{name:'确认导入 1 类草稿',exact:true}).click();await page.getByText('Excel 草稿已导入,启停状态未改变。',{exact:true}).waitFor();assert.equal(runtime.orderRules.get('rules','bs-change').draft.version,before+1);assert.equal(runtime.orderRules.get('rules','bs-change').published,null);assert.equal(runtime.orderRules.settings().enabled,false);
const download=await Promise.all([page.waitForEvent('download',{timeout:20000}),page.getByRole('link',{name:'下载当前规则 Excel',exact:true}).click({noWaitAfter:true})]);assert.equal(download[0].suggestedFilename(),'分类规则.xlsx');assert.equal(await download[0].failure(),null);const exported=XLSX.read(await fs.readFile(await download[0].path()),{type:'buffer'});assert.equal(XLSX.utils.sheet_to_json(exported.Sheets['分类规则']).length,15);
sheet.G2={t:'s',v:'invalid-address'};await page.locator('#rule-import-file').setInputFiles({name:'无效分类.xlsx',mimeType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',buffer:XLSX.write(book,{type:'buffer',bookType:'xlsx'})});await page.getByText('收件人未识别到有效邮箱',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'确认导入 1 类草稿',exact:true}).isDisabled(),true);assert.equal(runtime.orderRules.get('rules','bs-change').draft.version,before+1);
});
@@ -0,0 +1,40 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
function setup(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'rule-business-')),store=new RuleStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return store;}
const table=()=>({rows:[['类别编号','分类名称','订单评审流程','电子流状态','服务器存档地址','邮件命名','收件人','抄送人','附带PDF'],['bs-change','备损订单更改通知书','备损订单更改评审','订单专员(订单通知书)','备损订单通知书','【备损订单更改通知书】','A@example.test','','是']]});
test('Excel preview is read-only for business state; import commits drafts atomically and is idempotent',t=>{
const store=setup(t),{previewImport,commitImport}=require('../../src/modules/order-rules/import.cjs'),before=store.all('rules');
const preview=previewImport(store,table(),'admin');assert.equal(preview.rows.length,1);assert.deepEqual(store.all('rules'),before);
const saved=commitImport(store,{id:preview.id},'admin');assert.equal(saved.count,1);assert.deepEqual(store.get('rules','bs-change').draft.to,['a@example.test']);assert.equal(store.get('rules','bs-change').published,null);assert.equal(store.settings().enabled,false);
assert.deepEqual(commitImport(store,{id:preview.id},'admin'),saved);
});
test('Excel reports unknown and duplicate categories, invalid addresses and stale versions without partial writes',t=>{
const store=setup(t),{previewImport,commitImport}=require('../../src/modules/order-rules/import.cjs'),bad=table();bad.rows.push([...bad.rows[1]]);assert.equal(previewImport(store,bad,'admin').canCommit,false);
const unknown=table();unknown.rows[1][0]='unknown';assert.equal(previewImport(store,unknown,'admin').canCommit,false);
const invalid=table();invalid.rows[1][6]='not an address';assert.equal(previewImport(store,invalid,'admin').canCommit,false);
const partial=table();partial.rows[1][6]='Valid <valid@example.test>, bad@invalid';assert.equal(previewImport(store,partial,'admin').canCommit,false);
const plan=previewImport(store,table(),'admin'),old=store.get('rules','bs-change').draft;store.saveRule({...old,name:'另一个管理员已修改'},'admin');const before=store.all('rules');assert.throws(()=>commitImport(store,{id:plan.id},'admin'),e=>e.status===409);assert.deepEqual(store.all('rules'),before);
});
test('resume enables verified published snapshot without publishing a later draft and rejects stale switch actions',t=>{
const store=setup(t),{captured}=activateReferenceMapping(store),old=store.get('rules','bs-change').draft;
const saved=store.saveRule({...old,to:['a@example.test'],archiveDirectory:'\\\\server\\share',filenameDate:'receivedAt',bodyTemplateId:'template-1'},'admin');
store.trial(saved.id,{version:saved.version,sampleId:captured.id});store.publish(saved.id,{version:saved.version},'admin');store.pause(saved.id,{version:saved.version},'admin');
const edit=store.saveRule({...saved,intro:'尚未发布'},'admin'),snapshot=store.snapshot().rules.find(r=>r.id===saved.id);
const input={version:edit.version,publishedVersion:saved.version,activationVersion:snapshot.activationVersion};store.resume(saved.id,input,'admin');assert.equal(store.get('rules',saved.id).published.intro,saved.intro);assert.equal(store.get('rules',saved.id).draft.intro,'尚未发布');assert.throws(()=>store.resume(saved.id,input,'admin'),e=>e.status===409);
assert.equal(store.get('rules',saved.id).draft.bodyTemplateId,'template-1');
const active=store.snapshot().rules.find(r=>r.id===saved.id);store.pause(saved.id,{version:edit.version},'admin');const record=store.get('rules',saved.id);record.publicationAdaptersHash='stale-mapping';store.put('rules',record);assert.throws(()=>store.resume(saved.id,{version:edit.version,publishedVersion:saved.version,activationVersion:active.activationVersion+1},'admin'),/识别配置已变化/);
});
test('Excel merged cells inherit only their explicit span and formulas/oversized ranges are rejected',()=>{
const XLSX=require('xlsx'),{parse}=require('../../web/modules/order-rules/import-parser.js');
const sheet=XLSX.utils.aoa_to_sheet([['序号','服务器存档地址','订单评审流程','邮件命名','邮件正文','电子流状态','收件人'],[1,'共享类别','流程甲','【备损订单通知书】','摘要信息','订单节点','a@example.test'],[2,'','流程乙','【备损订单更改通知书】','附件:PDF','',''],['','','说明文字']]);
sheet['!merges']=[{s:{r:1,c:1},e:{r:2,c:1}},{s:{r:1,c:5},e:{r:2,c:5}},{s:{r:1,c:6},e:{r:2,c:6}}];const book=XLSX.utils.book_new();XLSX.utils.book_append_sheet(book,sheet,'分类规则');
for(const bookType of ['biff8','xlsx']){const result=parse(XLSX,XLSX.write(book,{type:'buffer',bookType}));assert.equal(result.rows.length,3);assert.equal(result.rows[2][1],'共享类别');assert.equal(result.rows[2][6],'a@example.test');}
sheet.C2={t:'s',v:'流程甲',f:'1+1'};assert.throws(()=>parse(XLSX,XLSX.write(book,{type:'buffer',bookType:'xlsx'})),/公式/);assert.throws(()=>parse(XLSX,new Uint8Array(2*1024*1024+1)),/2 MiB/);
});
test('chosen template is resolved from the rule snapshot and inactive templates are blocked',()=>{
const {ruleTemplate}=require('../../src/modules/mail/rule-template.cjs');let active=true;
const store={categoryTemplate:id=>({id:'legacy-'+id}),template:id=>({id,status:active?'active':'archived',text:'选定模板'})};
assert.equal(ruleTemplate(store,'cat',{}).id,'legacy-cat');assert.equal(ruleTemplate(store,'cat',{bodyTemplateId:''}),null);assert.equal(ruleTemplate(store,'cat',{bodyTemplateId:'chosen'}).id,'chosen');active=false;assert.throws(()=>ruleTemplate(store,'cat',{bodyTemplateId:'chosen'}),e=>e.status===409);
});
@@ -0,0 +1,47 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {extractTitle}=require('../../src/modules/order-rules/title.cjs');
const {buildBatch}=require('../../src/modules/order-rules/batch.cjs');
const {applyBodyTemplate}=require('../../src/modules/order-rules/template.cjs');
const rule={id:'overseas-notice',version:1,categoryId:'overseas-notice',name:'海外订单通知书',intro:'大家好:\n\n以下为海外订单通知书,请查收!',signature:'Best Regards!\n示例团队',to:['team@example.test'],cc:[],attachPdf:false};
const title='订单号:TEST-100机芯号:CORE-A产品型号:MODEL-A客户简称:示例甲出货方式:CBU总数量:0订单号:HA100机芯号:CORE-B产品型号:MODEL-B客户简称:示例乙出货方式:SKD总数量:200';
function order(id,brief=title,directory='\\\\example-nas\\orders\\overseas'){return {id,status:'pending',event:{orderNo:id,brief,receivedAt:'2026-10-20T01:00:00Z'},ruleSnapshot:rule,archive:{archivedAt:'2026-10-20T01:01:00Z',files:[{name:id+'.pdf',path:directory+'\\'+id+'.pdf',size:100,sha256:'a'.repeat(64),kind:'pdf'}]}};}
test('title output separates shipping and customer for every summary row and keeps zero and missing distinct',()=>{
const result=extractTitle(title);assert.equal(result.issues.length,0);
assert.deepEqual(result.orders.map(({orderNo,coreNo,productModel,customerShort,shippingMethod,totalQuantity})=>({orderNo,coreNo,productModel,customerShort,shippingMethod,totalQuantity})),[
{orderNo:'TEST-100',coreNo:'CORE-A',productModel:'MODEL-A',customerShort:'示例甲',shippingMethod:'CBU',totalQuantity:'0'},
{orderNo:'HA100',coreNo:'CORE-B',productModel:'MODEL-B',customerShort:'示例乙',shippingMethod:'SKD',totalQuantity:'200'}]);
assert.equal(extractTitle('订单号:TEST-2客户简称:示例丙总数量:5').orders[0].shippingMethod,undefined);assert.equal(result.brief.includes('出货方式:CBU'),true);
});
test('overseas mail has summary paragraphs and one actual directory after the list without per-file clutter',()=>{
const one=order('TEST-100'),two=order('TEST-200','订单号:TEST-200机芯号:C产品型号:M客户简称:示例丙出货方式:CBU总数量:5');
const batch=buildBatch(rule,[one,two],'2026-10-20T03:00:00Z');
assert.equal(batch.text,[rule.intro,title.replace('订单号:HA100','\n订单号:HA100')+'\n'+two.event.brief,'存放地址:\\\\example-nas\\orders\\overseas',rule.signature].join('\n\n'));
assert.equal((batch.text.match(/存放地址/g)||[]).length,1);assert.doesNotMatch(batch.text,/\.pdf/);assert.equal(batch.attachments.length,0);assert.deepEqual(batch.orderIds,['TEST-100','TEST-200']);
assert.match(batch.html,/file:\/\/example-nas\/orders\/overseas/);assert.doesNotMatch(batch.html,/TEST-100\.pdf/);
});
test('overseas directory comes from frozen evidence and all actual directories are retained and escaped',()=>{
const batch=buildBatch({...rule,archiveDirectory:'\\\\wrong\\configured'},[order('A','订单号:A客户简称:<script>','\\\\example-nas\\orders\\one'),order('B','订单号:B','\\\\example-nas\\orders\\two')],'2026-10-20T03:00:00Z');
assert.match(batch.text,/orders\\one/);assert.match(batch.text,/orders\\two/);assert.doesNotMatch(batch.text,/wrong/);assert.doesNotMatch(batch.html,/<script>/);assert.match(batch.html,/&lt;script&gt;/);
});
test('business templates receive separate summary directory and category variables without duplicating content',()=>{
const orders=[order('A','订单号:A机芯号:C出货方式:CBU总数量:5')],snapshot=buildBatch(rule,orders,'2026-10-20T03:00:00Z');
const template={id:'t',version:1,text:'以下为{{类别名称}}\n\n{{订单明细}}\n\n存放地址:{{存放地址}}\n\n团队签名',html:'<p>{{类别名称}}</p><div>{{订单明细}}</div><p>存放地址:{{存放地址}}</p>',subject:'{{类别名称}}',attachments:[]};
const batch=applyBodyTemplate(snapshot,template,orders,20971520);
assert.equal(batch.text,'以下为海外订单通知书\n\n订单号:A机芯号:C出货方式:CBU总数量:5\n\n存放地址:\\\\example-nas\\orders\\overseas\n\n团队签名');
assert.equal((batch.html.match(/订单号:A/g)||[]).length,1);assert.doesNotMatch(batch.text,/\.pdf/);assert.deepEqual(batch.to,['team@example.test']);
});
test('a template that omits business variables still retains the complete overseas summary and directory',()=>{
const orders=[order('A','订单号:A客户简称:<b>')],snapshot=buildBatch(rule,orders,'2026-10-20T03:00:00Z');
const batch=applyBodyTemplate(snapshot,{id:'t',version:1,text:'固定前言',html:'<p>固定前言</p>',attachments:[]},orders,20971520);
assert.match(batch.text,/订单号:A/);assert.match(batch.text,/存放地址:\\\\example-nas\\orders\\overseas/);assert.match(batch.html,/&lt;b&gt;/);assert.doesNotMatch(batch.html,/<b>/);
});
test('legacy summary objects without text never discard the recorded notification brief',()=>{
const item=order('A','订单号:A客户简称:保留旧摘要');item.event.titleOrders=[{orderNo:'A'}];
assert.match(buildBatch(rule,[item],'2026-10-20T03:00:00Z').text,/保留旧摘要/);
});
test('the order-list variable keeps order lines separate from clickable archive directories',()=>{
const orders=[order('A','订单号:A')],snapshot=buildBatch(rule,orders,'2026-10-20T03:00:00Z');
const batch=applyBodyTemplate(snapshot,{id:'legacy',version:1,text:'旧格式\n{{订单列表}}',html:'<p>旧格式</p>{{订单列表}}',attachments:[]},orders,20971520);
assert.equal(batch.text,'旧格式\n订单号:A\n\n存放地址:\\\\example-nas\\orders\\overseas');assert.match(batch.html,/href="file:\/\/example-nas\/orders\/overseas"/);assert.equal((batch.html.match(/订单号:A/g)||[]).length,1);
});
Loaded 100 of 444 files, more files were not shown because too many files have changed in this diff. Show more