{if(script.tagName==='script')queueMicrotask(()=>script.onerror(new Error('missing')));};
+ await assert.rejects(bad.context.window.AppModules.load('assistant'),/无法加载页面资源/);
+});
+
+test('failed modules can be retried without executing successful dependencies twice',async()=>{
+ const f=fixture();let fail=true;
+ f.context.document.head.appendChild=script=>{if(script.tagName!=='script')return;f.appended.push(script.src.split('?')[0]);queueMicrotask(()=>fail&&script.src.startsWith('/assistant.js')?script.onerror():script.onload());};
+ await assert.rejects(f.context.window.AppModules.load('assistant'),/无法加载页面资源/);fail=false;
+ await f.context.window.AppModules.load('assistant');
+ assert.equal(f.appended.filter(src=>src==='/assistant.js').length,2);assert.equal(f.appended.filter(src=>src==='/assistant-operations.js').length,1);
+});
diff --git a/tests/bpm/windows-directory.test.cjs b/tests/bpm/windows-directory.test.cjs
new file mode 100644
index 0000000..bd99108
--- /dev/null
+++ b/tests/bpm/windows-directory.test.cjs
@@ -0,0 +1,43 @@
+'use strict';
+const test=require('node:test'),assert=require('node:assert/strict'),cp=require('node:child_process');
+const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
+
+test('native ACL policy accepts only the current owner and one protected inheritable full-control allow rule',{skip:process.platform!=='win32'},()=>{
+ const {privateDirectoryAcl}=require('../../src/platform/security/windows-directory.cjs');
+ const cases=`
+ $sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User
+ function Make-Acl($protected,$owner,$rights,$inherit,$propagation,$type,$identity) {
+ $acl=New-Object System.Security.AccessControl.DirectorySecurity
+ $acl.SetOwner($owner);$acl.SetAccessRuleProtection($protected,$false)
+ $rule=New-Object System.Security.AccessControl.FileSystemAccessRule($identity,$rights,$inherit,$propagation,$type)
+ $acl.AddAccessRule($rule);return $acl
+ }
+ $other=New-Object System.Security.Principal.SecurityIdentifier('S-1-1-0')
+ $rows=@(
+ (Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid) $sid),
+ (Test-PrivateDirectoryAcl (Make-Acl $false $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid) $sid),
+ (Test-PrivateDirectoryAcl (Make-Acl $true $other 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid) $sid),
+ (Test-PrivateDirectoryAcl (Make-Acl $true $sid 'Read' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid) $sid),
+ (Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'None' 'None' 'Allow' $sid) $sid),
+ (Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'InheritOnly' 'Allow' $sid) $sid),
+ (Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Deny' $sid) $sid),
+ (Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $other) $sid)
+ )
+ $extra=Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid
+ $extra.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($other,'Read','ContainerInherit,ObjectInherit','None','Allow')))
+ $rows+=(Test-PrivateDirectoryAcl $extra $sid)
+ ConvertTo-Json -Compress -InputObject $rows
+ `;
+ const output=cp.execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop";'+privateDirectoryAcl+cases],{encoding:'utf8',windowsHide:true,timeout:15000});
+ assert.deepEqual(JSON.parse(output),[true,false,false,false,false,false,false,false,false]);
+});
+
+test('a compliant real directory is not rewritten and an unprotected directory is repaired',{skip:process.platform!=='win32'},t=>{
+ const {privateDirectoryAcl,secureDirectoryScript}=require('../../src/platform/security/windows-directory.cjs'),parent=path.resolve(os.tmpdir()),dir=fs.mkdtempSync(path.join(parent,'acl-policy-'));
+ assert.equal(path.dirname(dir),parent);t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
+ const run=script=>cp.execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop";'+script],{input:dir,encoding:'utf8',windowsHide:true,timeout:15000}).trim();
+ run(secureDirectoryScript);const protectedAt=fs.statSync(dir,{bigint:true}).ctimeNs;run(secureDirectoryScript);assert.equal(fs.statSync(dir,{bigint:true}).ctimeNs,protectedAt,'read verification must not rewrite the DACL');
+ run('$p=[Console]::In.ReadToEnd();$acl=[IO.Directory]::GetAccessControl($p);$acl.SetAccessRuleProtection($false,$true);[IO.Directory]::SetAccessControl($p,$acl)');
+ run(secureDirectoryScript);
+ const verified=run(privateDirectoryAcl+';$p=[Console]::In.ReadToEnd();Test-PrivateDirectoryAcl ([IO.Directory]::GetAccessControl($p)) ([System.Security.Principal.WindowsIdentity]::GetCurrent().User)');assert.equal(verified,'True');
+});
diff --git a/tests/fixtures/startup-failure-service.cjs b/tests/fixtures/startup-failure-service.cjs
new file mode 100644
index 0000000..d9c75e4
--- /dev/null
+++ b/tests/fixtures/startup-failure-service.cjs
@@ -0,0 +1,13 @@
+'use strict';
+const fs=require('node:fs'),http=require('node:http');
+const {respondToPing}=require('../../src/platform/service/ping.cjs');
+const file=process.env.ORDER_FIXTURE_COUNT;
+fs.writeFileSync(file,String((fs.existsSync(file)?Number(fs.readFileSync(file,'utf8')):0)+1));
+if(!fs.existsSync(file+'.ready')){
+ process.send({type:'order:startup-failed',diagnostic:{type:'Error',stage:'key_directory',code:'STORAGE_UNAVAILABLE',causeCode:'ETIMEDOUT',durationMs:30000,message:'SECRET_FIXTURE_NOT_FOR_STATE'}});
+ process.exitCode=1;
+}else{
+ const server=http.createServer((request,response)=>respondToPing(request,response,{token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt:new Date().toISOString()}));
+ server.listen(Number(process.env.ORDER_FIXTURE_PORT),'127.0.0.1');
+ process.on('message',message=>{if(message==='order:shutdown'){server.closeAllConnections();server.close(()=>process.exit(0));}});
+}
diff --git a/tests/service/service-supervisor.test.cjs b/tests/service/service-supervisor.test.cjs
index 04f989d..db34159 100644
--- a/tests/service/service-supervisor.test.cjs
+++ b/tests/service/service-supervisor.test.cjs
@@ -53,5 +53,16 @@ test('unknown port owners remain running, and repeated real exits enter cooldown
guard=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/managed-service.cjs'),ports:[listenPort],env:{ORDER_FIXTURE_PORT:String(listenPort),ORDER_FIXTURE_COUNT:path.join(stateDir,'count'),ORDER_FIXTURE_ALWAYS_CRASH:'1'},timing:{intervalMs:40,pingTimeoutMs:50,startupGraceMs:1000,backoffMs:[30],maxRestarts:1,cooldownMs:1000,windowMs:30000,stopGraceMs:500}});await guard.start();await until(()=>guard.snapshot().status==='cooldown');assert.ok(guard.snapshot().nextRestartAt);await guard.stop();
});
test('restart backoff is bounded and repeated failures enter a cooldown',()=>{
- const {restartPlan}=require('../../src/platform/service/supervisor.cjs');assert.deepEqual([0,1,2,20].map(failures=>restartPlan({failures,recent:0}).delayMs),[2000,5000,10000,60000]);assert.equal(restartPlan({failures:9,recent:8}).cooldown,true);assert.equal(restartPlan({failures:9,recent:8}).delayMs,300000);
+ const {restartPlan}=require('../../src/platform/service/supervisor.cjs');assert.deepEqual([0,1,2,20].map(failures=>restartPlan({failures,recent:0}).delayMs),[2000,5000,10000,60000]);assert.equal(restartPlan({failures:9,recent:8}).cooldown,true);assert.equal(restartPlan({failures:9,recent:8}).delayMs,300000);assert.equal(restartPlan({failures:0,recent:0,startupFailures:3}).cooldown,true);
+});
+
+test('three failed startups retain safe diagnostics and enter cooldown, then explicit retry can recover',{timeout:30000},async t=>{
+ const {ServiceSupervisor}=require('../../src/platform/service/supervisor.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'startup-cooldown-')),listenPort=await port(),count=path.join(stateDir,'count');let guard;
+ t.after(async()=>{await guard?.stop();await fs.rm(stateDir,{recursive:true,force:true});});
+ guard=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/startup-failure-service.cjs'),ports:[listenPort],env:{ORDER_FIXTURE_PORT:String(listenPort),ORDER_FIXTURE_COUNT:count},timing:{intervalMs:30,pingTimeoutMs:60,startupGraceMs:500,stopGraceMs:1000,backoffMs:[20],cooldownMs:5000,maxRestarts:99}});
+ await guard.start();await until(()=>guard.snapshot().status==='cooldown');
+ assert.equal(await fs.readFile(count,'utf8'),'3');assert.equal(guard.snapshot().consecutiveStartupFailures,3);
+ assert.equal(guard.snapshot().reason,'startup_failed');assert.equal(guard.snapshot().startupError.stage,'key_directory');assert.equal(guard.snapshot().startupError.causeCode,'ETIMEDOUT');assert.doesNotMatch(JSON.stringify(guard.snapshot()),/SECRET/);
+ await fs.writeFile(count+'.ready','ready');await guard.restart();await until(()=>guard.snapshot().status==='running');
+ assert.equal(guard.snapshot().consecutiveStartupFailures,0);assert.equal(guard.snapshot().startupError,null);
});
diff --git a/web/app.js b/web/app.js
index c3be195..22579dc 100644
--- a/web/app.js
+++ b/web/app.js
@@ -174,6 +174,7 @@ async function renderView() {
document.querySelector('#view-title').textContent=views[currentView][0];document.querySelector('#view-description').textContent=views[currentView][1];
const container=document.querySelector('#content');if(!(wasRecord&&['records','records-pdf'].includes(currentView)))container.innerHTML='';
+ try{await window.AppModules.load(currentView);if(!isActive())return;configureLoadedViews();}catch(error){if(isActive()){container.innerHTML=`${esc(error.message)}
`;container.querySelector('[data-module-retry]').onclick=()=>renderView();container.querySelector('[data-module-reload]').onclick=()=>location.reload();}return;}
const notificationSections={'order-notifications':'workbench','notification-execution':'execution','notification-orders':'orders','notification-batches':'pending','notification-history':'history','notification-settings':'settings'};
const fn={'rule-fields':(host,active)=>window.OrderRuleViews.render(host,active,'fields'),...Object.fromEntries(Object.entries(notificationSections).map(([route,section])=>[route,(host,active)=>window.OrderNotificationViews.render(host,active,section)])),'assistant-settings':window.AssistantViews?.settings,account:window.AccountViews?.account,'order-rules':window.OrderRuleViews?.render,health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,records:viewRecords,'records-pdf':viewPdfRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,users:window.AccountViews?.users,audit:viewAudit,rules:viewRules}[currentView];
void refreshTimer?.run().catch(()=>{});
@@ -186,7 +187,8 @@ async function authScreen() {
}
async function passwordChanged(actorId){if(currentUser&¤tUser.id!==actorId)return false;currentUser=null;++viewGeneration;refreshTimer?.dispose();await window.PageLifecycle?.dispose();await window.BpmLogin?.dispose().catch(()=>{});await boot();return true;}
-function enter(){window.PageLifecycle.configureRegions({read:(signal,region)=>api('/refresh/revisions?regions='+encodeURIComponent(region),undefined,{signal}),user:()=>currentUser});window.RecordState.configure(currentUser,({hash,push})=>{if(push&&location.hash!==hash)history.pushState({appIndex:++historyIndex},'',hash);else history.replaceState({...history.state,appIndex:historyIndex},'',hash);});window.PdfRecordViews?.configure({api,esc,formatDate,notify,user:currentUser});window.AccountViews?.configure({api,esc,formatDate,notify,user:currentUser,onPasswordChanged:passwordChanged});window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderNotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate,user:currentUser});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();refreshTimer?.dispose();const statusUser=currentUser;refreshTimer=window.PageLifecycle.regionPoll('orderRules',{refresh:signal=>updateAutomationStatus(()=>currentUser===statusUser,{signal}),onError:error=>{const node=document.querySelector('#automation-status');if(node&¤tUser===statusUser){node.textContent='通知状态待确认';node.className='badge bg-yellow-lt text-decoration-none';node.title=error.message+';请刷新重试。';}}},15000,{isActive:()=>!!currentUser&¤tUser===statusUser,owned:false});renderView();void checkSystemUpdate(()=>!!currentUser);}
+function configureLoadedViews(){window.PdfRecordViews?.configure({api,esc,formatDate,notify,user:currentUser});window.AccountViews?.configure({api,esc,formatDate,notify,user:currentUser,onPasswordChanged:passwordChanged});window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderNotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate,user:currentUser});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});}
+function enter(){window.PageLifecycle.configureRegions({read:(signal,region)=>api('/refresh/revisions?regions='+encodeURIComponent(region),undefined,{signal}),user:()=>currentUser});window.RecordState.configure(currentUser,({hash,push})=>{if(push&&location.hash!==hash)history.pushState({appIndex:++historyIndex},'',hash);else history.replaceState({...history.state,appIndex:historyIndex},'',hash);});configureLoadedViews();shell();refreshTimer?.dispose();const statusUser=currentUser;refreshTimer=window.PageLifecycle.regionPoll('orderRules',{refresh:signal=>updateAutomationStatus(()=>currentUser===statusUser,{signal}),onError:error=>{const node=document.querySelector('#automation-status');if(node&¤tUser===statusUser){node.textContent='通知状态待确认';node.className='badge bg-yellow-lt text-decoration-none';node.title=error.message+';请刷新重试。';}}},15000,{isActive:()=>!!currentUser&¤tUser===statusUser,owned:false});renderView();void checkSystemUpdate(()=>!!currentUser);}
async function boot(){try{currentUser=(await api('/me')).user;enter();}catch{await authScreen();}}
window.addEventListener('page-operation-error',event=>notify(event.detail.message,'danger'));
window.addEventListener('pagehide',()=>{window.BpmLogin?.dispose({unload:true});});
diff --git a/web/index.html b/web/index.html
index 71c0580..3f5ffc9 100644
--- a/web/index.html
+++ b/web/index.html
@@ -1,3 +1,3 @@
-订单通知中心
-
+订单通知中心
+
diff --git a/web/modules/navigation/module-loader.js b/web/modules/navigation/module-loader.js
new file mode 100644
index 0000000..74d08ea
--- /dev/null
+++ b/web/modules/navigation/module-loader.js
@@ -0,0 +1,40 @@
+'use strict';
+window.AppModules=(()=>{
+ const manifest=JSON.parse(document.querySelector('meta[name="app-modules"]')?.content||'{}');
+ const groups=manifest.groups||{},urls=manifest.urls||{},loaded=new Map(),preloads=new Map();
+ function assetFor(route){
+ const src=urls['/'+route];
+ if(typeof src!=='string'||!/^\/(?!\/)[\w./-]+\.js\?v=[a-f0-9]{64}$/.test(src))throw Error('页面资源版本无效,请重新加载工作台。');
+ const hash=src.slice(src.lastIndexOf('=')+1),integrity='sha256-'+btoa(String.fromCharCode(...hash.match(/../g).map(byte=>parseInt(byte,16))));
+ return {src,integrity};
+ }
+ function preload(asset){
+ if(loaded.has(asset.src)||preloads.has(asset.src))return;
+ const link=document.createElement('link');link.rel='preload';link.as='script';link.href=asset.src;link.integrity=asset.integrity;link.crossOrigin='anonymous';preloads.set(asset.src,link);document.head.appendChild(link);
+ }
+ function loadOne(route,asset){
+ const {src,integrity}=asset;
+ if(loaded.has(src))return loaded.get(src);
+ const script=document.createElement('script');script.async=true;script.src=src;script.integrity=integrity;script.crossOrigin='anonymous';
+ const promise=new Promise((resolve,reject)=>{script.onload=resolve;script.onerror=()=>reject(Error('无法加载页面资源:/'+route));});
+ loaded.set(src,promise);
+ document.head.appendChild(script);
+ promise.catch(()=>{if(loaded.get(src)===promise){loaded.delete(src);script.remove();}});
+ const cleanup=()=>{preloads.get(src)?.remove();preloads.delete(src);};promise.then(cleanup,cleanup);
+ return promise;
+ }
+ function filesFor(route,parents=new Set()){
+ if(parents.has(route)||!Object.hasOwn(groups,route))throw Error('页面模块配置无效,请重新加载工作台。');
+ const next=new Set(parents).add(route);
+ return groups[route].flatMap(item=>item.startsWith('$')?filesFor(item,next):[item]);
+ }
+ async function load(route){
+ const files=[...new Set(filesFor(route))].map(file=>({file,asset:assetFor(file)}));
+ // Download dependencies together, but execute only this route's sequence.
+ // A stalled script from an abandoned route cannot block another route.
+ for(const {asset} of files)preload(asset);
+ try{for(const {file,asset} of files)await loadOne(file,asset);}
+ finally{for(const {asset} of files){preloads.get(asset.src)?.remove();preloads.delete(asset.src);}}
+ }
+ return {load};
+})();
diff --git a/web/modules/navigation/module-manifest.json b/web/modules/navigation/module-manifest.json
new file mode 100644
index 0000000..ccb6f54
--- /dev/null
+++ b/web/modules/navigation/module-manifest.json
@@ -0,0 +1,27 @@
+{
+ "$records": ["record-ui.js", "record-table.js"],
+ "$business": ["$records", "order-notifications-shared.js", "mail-template-editor.js", "modules/order-notifications/batch-editor.js", "modules/order-notifications/detail.js", "modules/order-notifications/records.js", "order-notifications.js"],
+ "$mail": ["mail-history.js", "mail-template-editor.js", "mail.js"],
+ "$rules": ["vendor/tom-select.js", "order-notifications-shared.js", "field-sample-picker.js", "field-recognition-panel.js", "order-rules-scopes.js", "order-rules-resources.js", "order-rules-import.js", "order-rules-editor.js", "order-rules-preview.js", "field-mappings.js", "order-execution.js", "order-rules.js"],
+ "overview": ["business-home.js", "order-notifications.js"],
+ "notification-orders": ["$business"],
+ "notification-batches": ["$business"],
+ "notification-settings": ["order-notifications.js"],
+ "assistant": ["assistant-operations.js", "assistant.js"],
+ "assistant-settings": ["assistant-operations.js", "assistant.js"],
+ "bpm": ["workspace.js", "bpm-sync-settings.js", "bpm.js"],
+ "mail": ["$mail"],
+ "storage": ["storage-preview-host.js", "storage.js"],
+ "records": ["$records", "orders.js", "notifications.js"],
+ "records-pdf": ["$records", "pdf-records.js", "notifications.js"],
+ "rule-fields": ["$rules"],
+ "order-rules": ["$rules"],
+ "schedule": [],
+ "templates": ["$mail"],
+ "calendar": ["workspace.js"],
+ "exceptions": ["workspace.js"],
+ "audit": ["workspace.js"],
+ "users": ["account.js"],
+ "account": ["account.js"],
+ "health": ["health.js"]
+}