From 1148aa6f14d42ae8380361839c48cdf065615e72 Mon Sep 17 00:00:00 2001 From: abaishu0730 Date: Wed, 21 Oct 2026 11:12:18 +0800 Subject: [PATCH] feat: add verified offline recovery and retire legacy send assembly --- docs/backup-restore-guide.md | 25 ++++++++++ package.json | 1 + scripts/backup.cjs | 6 +++ src/app/application.cjs | 23 ++++++---- src/modules/bpm/scan-deliveries.cjs | 1 + src/modules/mail/api.cjs | 2 +- src/modules/notifications/history.cjs | 12 +++++ src/modules/order-rules/store.cjs | 13 +++--- src/platform/backup/keys.cjs | 9 ++++ src/platform/backup/manifest.cjs | 20 ++++++++ src/platform/backup/restore.cjs | 30 ++++++++++++ src/platform/backup/snapshot.cjs | 19 ++++++++ tests/app/application.test.cjs | 14 ++---- tests/app/restored-output.test.cjs | 5 ++ tests/backup/backup.test.cjs | 48 ++++++++++++++++++++ tests/mail/retired-binding.test.cjs | 3 ++ tests/notifications/history-adapter.test.cjs | 8 ++++ tests/order-rules/delivery-barrier.test.cjs | 10 ++++ tests/order-rules/summary.test.cjs | 10 ++++ 19 files changed, 235 insertions(+), 24 deletions(-) create mode 100644 docs/backup-restore-guide.md create mode 100644 scripts/backup.cjs create mode 100644 src/modules/notifications/history.cjs create mode 100644 src/platform/backup/keys.cjs create mode 100644 src/platform/backup/manifest.cjs create mode 100644 src/platform/backup/restore.cjs create mode 100644 src/platform/backup/snapshot.cjs create mode 100644 tests/app/restored-output.test.cjs create mode 100644 tests/backup/backup.test.cjs create mode 100644 tests/mail/retired-binding.test.cjs create mode 100644 tests/notifications/history-adapter.test.cjs create mode 100644 tests/order-rules/delivery-barrier.test.cjs create mode 100644 tests/order-rules/summary.test.cjs diff --git a/docs/backup-restore-guide.md b/docs/backup-restore-guide.md new file mode 100644 index 0000000..342e247 --- /dev/null +++ b/docs/backup-restore-guide.md @@ -0,0 +1,25 @@ +# 本机备份与恢复 + +备份包含应用状态、实际PDF、Windows当前用户保护的加密键及SHA256文件清单。历史默认永久保留;归档会话或退役异常不会删除原业务证据。备份含敏感信息,应保存在受控目录。 + +在项目目录运行以下命令。先停止本机测试服务;备份命令会拒绝仍被服务占用的状态目录。 + +```powershell +npm run service:stop +npm run backup -- create --destination C:\OrderBackups\snapshot-20261021 +npm run backup -- verify --source C:\OrderBackups\snapshot-20261021 +``` + +目标备份目录必须尚不存在。默认读取当前应用状态与项目输出目录;隔离测试可显式指定`--state --output `。校验会检查文件大小、SHA256、目录清单、链接和路径边界,缺失、增添或修改文件均拒绝。SHA256是完整性校验,不能代替可信来源确认。 + +恢复只允许新的空目录,不覆盖正在使用的状态: + +```powershell +npm run backup -- restore --source C:\OrderBackups\snapshot-20261021 --destination C:\OrderRecovery\isolated-state +``` + +恢复会实际验证DPAPI、为新目录注册对应的受保护键,并把本地PDF引用迁入新状态目录的`restored-pdf`;原目录和原键不改。`restore-config.json`记录迁移摘要,应用在未显式配置输出目录时使用此隔离输出。现有不同密钥、不可解密、路径越界及非空目标都拒绝。此版本按当前Windows用户设计,不保证跨用户或跨机器可解密。 + +恢复命令本身不启动服务、不启用处理或发信。隔离启动需要明确指定新状态目录,使用空闲端口,并确认原配置中的两个业务开关暂停。不要用服务控制命令误启动默认状态来代替恢复演练。恢复验证通过后,再单独安排实际切换。 + +系统设置的“系统健康”提供数据容量、永久保留说明和PDF历史导出。导出包含安全业务摘要,不含本地路径、密码或原始表单。它不能代替完整备份。 diff --git a/package.json b/package.json index 0e34d16..8343017 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,7 @@ "private": true, "description": "Team workspace for BPM connections, business calendars, exceptions and order PDF export", "scripts": { + "backup": "node scripts/backup.cjs", "start": "node scripts/service.cjs start", "start:foreground": "node src/server.cjs", "service:install": "node scripts/service.cjs install", diff --git a/scripts/backup.cjs b/scripts/backup.cjs new file mode 100644 index 0000000..126f44e --- /dev/null +++ b/scripts/backup.cjs @@ -0,0 +1,6 @@ +'use strict'; +const {createBackup}=require('../src/platform/backup/snapshot.cjs'); +const {verifyBackup}=require('../src/platform/backup/manifest.cjs'); +const {restoreBackup}=require('../src/platform/backup/restore.cjs'); +async function main(args){const command=args.shift(),allowed={create:['destination','state','output'],verify:['source'],restore:['source','destination']}[command];if(!allowed)throw Object.assign(Error('invalid command'),{code:'BACKUP_USAGE'});const options={};while(args.length){const key=args.shift();if(!key.startsWith('--')||!allowed.includes(key.slice(2))||Object.hasOwn(options,key.slice(2))||!args.length||args[0].startsWith('--'))throw Object.assign(Error('invalid option'),{code:'BACKUP_USAGE'});options[key.slice(2)]=args.shift();}if((command!=='create'&&!options.source)||(command!=='verify'&&!options.destination))throw Object.assign(Error('missing option'),{code:'BACKUP_USAGE'});if(command==='create')await createBackup({stateDir:options.state,outputDir:options.output,destination:options.destination});else if(command==='verify')verifyBackup(options.source);else await restoreBackup(options);process.stdout.write(JSON.stringify({ok:true,operation:command})+'\n');} +main(process.argv.slice(2)).catch(error=>{const code=/^(?:BACKUP_[A-Z_]+|ORDER_INSTANCE_OWNED)$/.test(error.code||'')?error.code:'BACKUP_FAILED';process.stderr.write(JSON.stringify({ok:false,code,message:'操作未完成。请检查服务已停止、备份完整性、目标为空及 Windows 身份兼容性。'})+'\n');process.exitCode=1;}); diff --git a/src/app/application.cjs b/src/app/application.cjs index 3317c0b..426dae5 100644 --- a/src/app/application.cjs +++ b/src/app/application.cjs @@ -21,8 +21,7 @@ const { ZcodeRuntime } = require('../modules/assistant/zcode-runtime.cjs'); const { RuntimeHealth } = require('../modules/health/runtime-health.cjs'); const { StorageStore } = require('../modules/storage/store.cjs'); const { StorageService } = require('../modules/storage/service.cjs'); -const { NotificationStore } = require('../modules/notifications/store.cjs'); -const { NotificationService } = require('../modules/notifications/service.cjs'); +const { NotificationHistory } = require('../modules/notifications/history.cjs'); const { RuleStore } = require('../modules/order-rules/store.cjs'); const { OrderRuleDispatcher } = require('../modules/order-rules/dispatcher.cjs'); const { BpmOrderProvider } = require('../modules/bpm/order-provider.cjs'); @@ -35,6 +34,13 @@ async function closeServer(server){ if(!server.listening){await server.drainExports?.();server.closeSessionStore?.();return;} await new Promise((resolve,reject)=>server.close(error=>error?reject(error):resolve())); } +async function resolveOutputDir(root,stateDir,config){ + if(Object.hasOwn(config,'outputDir'))return path.resolve(root,config.outputDir||'output/pdf'); + let restored;try{restored=JSON.parse(await fs.readFile(path.join(stateDir,'restore-config.json'),'utf8'));}catch(e){if(e.code==='ENOENT')return path.resolve(root,'output/pdf');throw e;} + if(restored.outputDir!=='restored-pdf')throw Error('恢复输出目录必须位于新状态目录内。'); + const resolved=path.resolve(stateDir,restored.outputDir),relative=path.relative(path.resolve(stateDir),resolved);if(!relative||relative.startsWith('..')||path.isAbsolute(relative))throw Error('恢复输出目录必须位于新状态目录内。'); + const [realState,realOutput]=await Promise.all([fs.realpath(stateDir),fs.realpath(resolved)]),realRelative=path.relative(realState,realOutput);if(!realRelative||path.isAbsolute(realRelative)||realRelative==='..'||realRelative.startsWith('..'+path.sep)||(await fs.lstat(resolved)).isSymbolicLink())throw Error('恢复输出目录不能是链接。');return resolved; +} async function main(options = {}) { const startedAt=new Date().toISOString(),watchdog={token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt}; const root = require('../shared/paths.cjs').PROJECT_ROOT; @@ -64,7 +70,7 @@ async function main(options = {}) { let token; try { token = (await fs.readFile(tokenPath,'utf8')).trim(); } catch(error) { if(error.code !== 'ENOENT') throw error; token=crypto.randomBytes(32).toString('hex'); await fs.writeFile(tokenPath,token,{mode:0o600}); } if (!/^[a-f0-9]{64}$/.test(token)) throw new Error('本地配对文件损坏,请删除 pairing.key 后重启。'); - const outputDir = path.resolve(root,config.outputDir || 'output/pdf'); + const outputDir = await resolveOutputDir(root,stateDir,config); const installedExtension = path.join(stateDir,'extension'); const dashboardConfig=config.dashboard || {}; const dashboardPort=dashboardConfig.port ?? 18766; @@ -76,7 +82,7 @@ async function main(options = {}) { workspace=new WorkspaceStore(path.join(stateDir,'workspace')); // Register conditional closures before constructing later resources; partial startup follows the same path. cleanup.push(()=>closeServer(server)); - cleanup.push(()=>bpmMonitor?.stop(),()=>health?.close(),()=>assistant?.stop(),()=>orderDispatcher?.stop(),()=>orderExecution?.stop(),()=>notifications?.stop(),()=>storage?.stop(),()=>scanner?.stop(),()=>mail?.stop(),()=>custodian?.stop(),()=>bpmSessions?.shutdown()); + cleanup.push(()=>bpmMonitor?.stop(),()=>health?.close(),()=>assistant?.stop(),()=>orderDispatcher?.stop(),()=>orderExecution?.stop(),()=>storage?.stop(),()=>scanner?.stop(),()=>mail?.stop(),()=>custodian?.stop(),()=>bpmSessions?.shutdown()); cleanup.push(()=>closeServer(dashboard),()=>workspace.close()); cleanup.push(()=>mailStore?.close(),()=>scanStore?.close(),()=>storageStore?.close(),()=>notificationStore?.close(),()=>orderRules?.close(),()=>assistantStore?.close()); bpmSessions=new BpmSessionManager({stateDir:path.join(stateDir,'bpm-sessions'),accessClient:new BpmAccessClient()}); @@ -85,14 +91,15 @@ async function main(options = {}) { mailStore.migrateLegacy(store.settings().templates); scanStore=new BpmScanStore(path.join(stateDir,'bpm-scan'));scanner=new BpmScanner({store:scanStore,workspace,manager:bpmSessions,settings:()=>store.settings()}); storageStore=new StorageStore(path.join(stateDir,'storage'));storage=new StorageService({store:storageStore,jobs:store,outputDir}); - notificationStore=new NotificationStore(path.join(stateDir,'notifications'));notificationStore.recover();notifications=new NotificationService({store:notificationStore,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides}); + notificationStore=new NotificationHistory(path.join(stateDir,'notifications'));notifications={store:notificationStore,historyOnly:true}; orderRules=new RuleStore(path.join(stateDir,'order-rules'),{schedule:()=>store.settings().schedule,calendar:()=>workspace.meta('calendar').overrides}); orderProvider=new BpmOrderProvider({manager:bpmSessions});orderArchive=new OrderArchiveProvider({storage,outputDir,journal:orderRules}); orderExecution=new OrderExecutionCoordinator({store:orderRules,workspace,provider:orderProvider,archive:orderArchive,mail,dashboard:store,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,systemPrincipal:custodian.principal}); orderDispatcher=new OrderRuleDispatcher({store:orderRules,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,providersReady:()=>{const cap=orderExecution.snapshot().capabilities;return ['liveTodo','pdfExport','automaticArchive'].every(key=>cap?.[key]===true);},templateResolver:(categoryId,rule)=>require('../modules/mail/rule-template.cjs').ruleTemplate(mailStore,categoryId,rule),attachmentReader:file=>orderArchive.read(file)}); - bpmMonitor=new BpmArrivalMonitor({workspace,manager:bpmSessions,scanner,provider:orderProvider,settings:()=>store.settings()}); + orderRules.deliveryBlockers=allowed=>scanStore.deliveries.pendingSources().filter(allowed); + bpmMonitor=new BpmArrivalMonitor({workspace,manager:bpmSessions,scanner,provider:orderProvider,settings:()=>store.settings(),onTodoReconciled:payload=>orderExecution.notifyDiscovery(payload)}); assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistant=new AssistantService({store:assistantStore,runtime:new ZcodeRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage,orderRules,orderExecution}); - health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail,execution:orderExecution}); + health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail,execution:orderExecution,monitor:bpmMonitor}); await bpmSessions.migrateAccounts(workspace.snapshot().connections); workspace.markSessionChecksPending(); server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog,renderSnapshot:options.renderSnapshot}); @@ -110,4 +117,4 @@ async function main(options = {}) { return {server,dashboard,workspace,bpmSessions,bpmMonitor,custodian,mail,scanner,storage,notifications,orderRules,orderDispatcher,orderExecution,assistant,health,stop}; }catch(error){try{await stop();}catch(cleanupError){error.cleanupError=cleanupError;}throw error;} } -module.exports={main}; +module.exports={main,resolveOutputDir}; diff --git a/src/modules/bpm/scan-deliveries.cjs b/src/modules/bpm/scan-deliveries.cjs index 075dfcf..eebbf1c 100644 --- a/src/modules/bpm/scan-deliveries.cjs +++ b/src/modules/bpm/scan-deliveries.cjs @@ -23,6 +23,7 @@ class ScanDeliveries{ return ready; } acknowledge(id){const at=new Date().toISOString();this.db.prepare("UPDATE execution_deliveries SET status='delivered',payload=NULL,next_at=0,updated_at=?,delivered_at=? WHERE run_id=?").run(at,at,id);} + pendingSources(){return this.db.prepare("SELECT DISTINCT connection_id AS id FROM execution_deliveries WHERE status IN ('pending','error')").all().map(row=>row.id);} failed(id,nextAt){const at=new Date().toISOString();this.db.prepare("UPDATE execution_deliveries SET status='error',attempts=attempts+1,next_at=?,updated_at=?,failed_at=? WHERE run_id=? AND status!='delivered'").run(nextAt,at,at,id);} summary(connectionId){ const pending=this.db.prepare("SELECT COUNT(*) AS n,MIN(next_at) AS due,SUM(CASE WHEN status='error' THEN 1 ELSE 0 END) AS errors FROM execution_deliveries WHERE connection_id=? AND status!='delivered'").get(connectionId),history=this.db.prepare('SELECT MAX(failed_at) AS failed,MAX(delivered_at) AS delivered FROM execution_deliveries WHERE connection_id=?').get(connectionId); diff --git a/src/modules/mail/api.cjs b/src/modules/mail/api.cjs index 56d772b..5dadc6c 100644 --- a/src/modules/mail/api.cjs +++ b/src/modules/mail/api.cjs @@ -8,7 +8,7 @@ async function mailApi({mail,workspace,user,route,method,body,request,response,r const audit=(action,detail)=>workspace?.record(user,action,detail); if(route==='/api/mail/templates/categories'){ if(method==='GET'){reply(200,{categories:require('../order-rules/catalog.cjs').seedRules().map(({id,name})=>({id,name})),bindings:store.categoryBindings()});return true;} - if(method==='POST'){if(mail.historyOnly)fail('只读邮件空间不能修改类别关联。',409);const saved=store.bindCategory(body);audit('mail.category.bind',saved.categoryId);reply(200,saved);return true;} + if(method==='POST')fail('旧类别模板关联已改为只读,请在分类通知规则选择模板。',410); } if(route==='/api/mail/channels'&&method==='POST'){ if(!secureBpmTransport(request,trustedProxy))fail('请在部署机本地或 HTTPS 页面维护邮箱账号。',403); diff --git a/src/modules/notifications/history.cjs b/src/modules/notifications/history.cjs new file mode 100644 index 0000000..9f9f669 --- /dev/null +++ b/src/modules/notifications/history.cjs @@ -0,0 +1,12 @@ +'use strict'; +const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'),{BpmVault}=require('../../platform/security/vault.cjs'); +// Legacy evidence is readable, but never recovered, scheduled, or mutated by the application. +class NotificationHistory{ + constructor(dir){this.dir=dir;const file=path.join(dir,'notifications.sqlite');if(fs.existsSync(file))this.db=new DatabaseSync(file,{readOnly:true});} + settings(){if(!this.db)return {enabled:false,historyOnly:true};const row=this.db.prepare('SELECT value FROM settings WHERE id=1').get();const {sourceKey,...settings}=row?JSON.parse(row.value):{};return {...settings,enabled:false,historyOnly:true};} + decode(row){const {payload,...metadata}=row;this.vault||=new BpmVault({stateDir:path.join(this.dir,'secrets')});return {...this.vault.decode(row.id,payload),...metadata};} + items(){return this.db?this.db.prepare('SELECT * FROM items ORDER BY rowid DESC LIMIT 100').all().map(row=>this.decode(row)):[];} + batches(){return this.db?this.db.prepare("SELECT * FROM batches ORDER BY CASE status WHEN 'unknown' THEN 0 ELSE 1 END,rowid DESC LIMIT 100").all().map(row=>this.decode(row)):[];} + close(){this.db?.close();this.db=null;this.vault?.destroy();this.vault=null;} +} +module.exports={NotificationHistory}; diff --git a/src/modules/order-rules/store.cjs b/src/modules/order-rules/store.cjs index 8bb22ba..19e26b2 100644 --- a/src/modules/order-rules/store.cjs +++ b/src/modules/order-rules/store.cjs @@ -69,9 +69,10 @@ class RuleStore{ const processingEnabled=input.processingEnabled??old.processingEnabled;const processingSince=processingEnabled&&!old.processingEnabled?this.now():old.processingSince; this.put('settings',{...input,processingEnabled,processingSince,id:'main',version:old.version+1});this.audit(actor,'保存分类通知设置',input.enabled?'已启用':'已暂停');return this.settings(); });} - snapshot(){ - const rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',activationVersion:record.activationVersion||0,hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,mappingIssue:record.mappingIssue||null,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,this.adapters())})); - return {rules,adapters:this.adapters(),orders:this.all('orders').reverse(),batches:this.all('batches').reverse(),settings:this.settings(),audit:this.all('audit').slice(-100).reverse(),capabilities:copy(this.capabilities),window:upcomingWindow(this.clock(),this.schedule(),this.calendar())}; + queryRevision(){return Number(this.db.prepare('SELECT total_changes() AS revision').get().revision);} + snapshot({includeRecords=true}={}){ + const adapters=this.adapters(),rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',activationVersion:record.activationVersion||0,hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,mappingIssue:record.mappingIssue||null,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,adapters)})); + return {rules,adapters,orders:includeRecords?this.all('orders').reverse():[],batches:includeRecords?this.all('batches').reverse():[],settings:this.settings(),audit:includeRecords?this.all('audit').slice(-100).reverse():[],capabilities:copy(this.capabilities),window:upcomingWindow(this.clock(),this.schedule(),this.calendar())}; } saveRule(input,actor){return this.transaction(()=>{ const record=this.get('rules',input?.id);if(!record)fail('规则不存在。',404); @@ -172,8 +173,8 @@ class RuleStore{ this.put('orders',order);this.audit(actor,'应用当前规则重新识别',id+':'+input.note.trim());return order; });} discoveryBlockers(cutoff,allowed=()=>true){ - if(!this.executionSources)return []; - const blockers=[]; + const blockers=(this.deliveryBlockers?.(allowed)||[]).map(id=>'连接 '+id+' 本地执行线索尚未交付。'); + if(!this.executionSources)return blockers; const pendingSources=new Set([...this.all('execution-discoveries'),...this.all('execution-discovery-runs')].filter(hint=>hint.status==='pending'&&allowed(hint.connectionId)).map(hint=>hint.connectionId)); for(const id of pendingSources)blockers.push('连接 '+id+' 完整对账线索尚未处理。'); if(this.activeDiscoveries>0)blockers.push('待办扫描尚未完成,不能冻结或发送不完整类别。'); @@ -207,7 +208,7 @@ class RuleStore{ recordIssue(id,input){ const old=this.get('business-issues',id); const owners=this.issueOwners(input); - const status=old?.status==='resolved'?'awaiting_verification':old?.status||'open'; + const status=['resolved','awaiting_verification'].includes(old?.status)?'open':old?.status||'open'; return this.put('business-issues',{ ...old,...input,id,status,owners, ownerStatus:owners.length?'assigned':'unassigned', diff --git a/src/platform/backup/keys.cjs b/src/platform/backup/keys.cjs new file mode 100644 index 0000000..b78efeb --- /dev/null +++ b/src/platform/backup/keys.cjs @@ -0,0 +1,9 @@ +'use strict'; +const fs=require('node:fs'),path=require('node:path'),{execFileSync}=require('node:child_process'); +const {fail,sha,noLinks}=require('./manifest.cjs'); +const {BpmVault}=require('../security/vault.cjs'); +function keyPath(vaultDir){if(process.platform!=='win32'||!process.env.LOCALAPPDATA)fail('BACKUP_KEY_PLATFORM');return path.join(process.env.LOCALAPPDATA,'OrderNotificationAutomation','bpm-keys',sha(path.resolve(vaultDir).toLowerCase())+'.key');} +function protectDirectory(dir){noLinks(dir,{missing:true});new BpmVault({stateDir:dir}).destroy();} +function unprotect(bytes){if(process.platform!=='win32')fail('BACKUP_KEY_PLATFORM');let raw;try{raw=Buffer.from(execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop"; Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd()); $r=[System.Security.Cryptography.ProtectedData]::Unprotect($b,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Out.Write([Convert]::ToBase64String($r))'],{input:bytes.toString('base64'),encoding:'utf8',windowsHide:true,timeout:15000,stdio:['pipe','pipe','pipe']}).trim(),'base64');if(raw.length!==32)fail('BACKUP_KEY_IDENTITY');}catch{fail('BACKUP_KEY_IDENTITY');}finally{raw?.fill(0);}} +function identity(){return {platform:process.platform,protection:process.platform==='win32'?'DPAPI-CurrentUser':'none',userMachineSha256:sha([process.env.USERDOMAIN||'',process.env.USERNAME||'',require('node:os').hostname()].join('\0')),compatibility:'Requires the original Windows DPAPI user profile and machine; restore verifies decryption.'};} +module.exports={keyPath,protectDirectory,unprotect,identity}; diff --git a/src/platform/backup/manifest.cjs b/src/platform/backup/manifest.cjs new file mode 100644 index 0000000..ee9030c --- /dev/null +++ b/src/platform/backup/manifest.cjs @@ -0,0 +1,20 @@ +'use strict'; +const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'); +function fail(code='BACKUP_INVALID'){throw Object.assign(Error('备份操作未完成;请检查完整性、目录和运行实例。'),{code});} +const sha=bytes=>crypto.createHash('sha256').update(bytes).digest('hex'); +function safeRelative(value){if(typeof value!=='string'||!value||value.length>2000||value.includes('\\')||value.split('/').some(p=>!p||p==='.'||p==='..'||/[<>:"|?*\x00-\x1f]/.test(p)||/[. ]$/.test(p)||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)))fail('BACKUP_PATH');return value;} +function noLinks(location,{missing=false}={}){let p=path.resolve(location),parts=[];while(true){parts.push(p);const parent=path.dirname(p);if(parent===p)break;p=parent;}for(const part of parts.reverse()){let s;try{s=fs.lstatSync(part);}catch(e){if(e.code==='ENOENT'&&missing)return path.resolve(location);if(e.code==='ENOENT')fail('BACKUP_MISSING');throw e;}if(s.isSymbolicLink()||(!s.isDirectory()&&!s.isFile())||(s.isFile()&&s.nlink!==1))fail('BACKUP_LINK');}return path.resolve(location);} +function inside(root,target){const r=path.relative(path.resolve(root),path.resolve(target));return !r||(!path.isAbsolute(r)&&r!=='..'&&!r.startsWith('..'+path.sep));} +function disjoint(...locations){for(let i=0;i32*1024*1024)fail();if(fs.readFileSync(path.join(root,'manifest.sha256'),'utf8').trim()!==sha(bytes))fail('BACKUP_MANIFEST_HASH');m=JSON.parse(bytes);}catch(e){if(e.code?.startsWith('BACKUP_'))throw e;fail('BACKUP_MANIFEST');} + if(m.format!==1||typeof m.appVersion!=='string'||!m.source||!path.isAbsolute(m.source.stateDir||'')||!path.isAbsolute(m.source.outputDir||'')||!Array.isArray(m.files)||!Array.isArray(m.directories)||!Array.isArray(m.vaults))fail(); + const seen=new Set();for(const p of [...m.directories,...m.files.map(f=>f.path)]){safeRelative(p);if(!['state','pdf','keys'].includes(p.split('/')[0])||seen.has(p.toLowerCase()))fail('BACKUP_PATH');seen.add(p.toLowerCase());} + for(const f of m.files)if(!Number.isSafeInteger(f.size)||f.size<0||!/^[a-f0-9]{64}$/.test(f.sha256))fail(); + if(!['state','pdf','keys'].every(p=>m.directories.includes(p)))fail(); + const expected=new Map(m.files.map(f=>[f.path,f]));for(const f of actual.files){if(['manifest.json','manifest.sha256'].includes(f.path))continue;const e=expected.get(f.path);if(!e||e.size!==f.size||e.sha256!==f.sha256)fail('BACKUP_INTEGRITY');expected.delete(f.path);}if(expected.size||actual.directories.length!==m.directories.length||actual.directories.some(p=>!m.directories.includes(p)))fail('BACKUP_INTEGRITY'); + const vaultPaths=new Set();for(const v of m.vaults){safeRelative(v.path);safeRelative(v.keyFile);if(vaultPaths.has(v.path.toLowerCase())||!m.directories.includes('state/'+v.path)||!/^keys\/[a-f0-9]{64}\.key$/.test(v.keyFile)||!m.files.some(f=>f.path===v.keyFile))fail('BACKUP_VAULT');vaultPaths.add(v.path.toLowerCase());} + return m; +} +module.exports={fail,sha,safeRelative,noLinks,inside,disjoint,fileHash,inventory,verifyBackup}; diff --git a/src/platform/backup/restore.cjs b/src/platform/backup/restore.cjs new file mode 100644 index 0000000..ae5ac2d --- /dev/null +++ b/src/platform/backup/restore.cjs @@ -0,0 +1,30 @@ +'use strict'; +const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'); +const {fail,noLinks,disjoint,inside,inventory,verifyBackup}=require('./manifest.cjs'); +const {keyPath,protectDirectory,unprotect}=require('./keys.cjs'); +const {BpmVault}=require('../security/vault.cjs'); +const quote=s=>'"'+s.replaceAll('"','""')+'"'; +function databaseVault(relative){if(relative.endsWith('/accounts.sqlite'))return path.posix.dirname(relative);return {'mail/mail.sqlite':'mail/secrets','storage/storage.sqlite':'storage/secrets','notifications/notifications.sqlite':'notifications/secrets','order-rules/rules.sqlite':'order-rules/secrets','assistant/assistant.sqlite':'assistant','bpm-scan/scan.sqlite':'bpm-scan/delivery-secrets'}[relative];} +function validateDatabases(stateDir,vaults){const known=new Set(vaults.map(v=>v.path));for(const file of inventory(stateDir).files){if(file.path.endsWith('.enc')&&!known.has(path.posix.dirname(file.path)))fail('BACKUP_KEY_MISSING');if(!file.path.endsWith('.sqlite'))continue;const db=new DatabaseSync(path.join(stateDir,file.path));try{if(db.prepare('PRAGMA quick_check').all().some(r=>Object.values(r)[0]!=='ok'))fail('BACKUP_DATABASE');const vault=databaseVault(file.path);if(!vault)continue;for(const {name} of db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all()){if(!db.prepare('PRAGMA table_info('+quote(name)+')').all().some(c=>c.name==='payload'))continue;if(db.prepare('SELECT 1 FROM '+quote(name)+' WHERE payload IS NOT NULL LIMIT 1').get()&&!known.has(vault))fail('BACKUP_KEY_MISSING');}}finally{db.close();}}} +function relocate(value,oldOutput,newOutput,key=''){if(Array.isArray(value))return value.map(v=>relocate(v,oldOutput,newOutput));if(value&&typeof value==='object')return Object.fromEntries(Object.entries(value).map(([k,v])=>[k,relocate(v,oldOutput,newOutput,k)]));if(typeof value==='string'&&['path','localPath','outputDir'].includes(key)&&path.isAbsolute(value)&&inside(oldOutput,value))return path.join(newOutput,path.relative(oldOutput,value));return value;} +function payloadId(relative,table,row){if(relative.endsWith('/accounts.sqlite'))return table==='accounts'?'account:'+row.connection_id:table==='sessions'?row.connection_id:null;if(relative==='order-rules/rules.sqlite'&&table==='records')return row.kind+':'+row.id;if(relative==='assistant/assistant.sqlite')return 'assistant:'+(table==='config'?'config':row.id);if(relative==='bpm-scan/scan.sqlite'&&table==='execution_deliveries')return 'execution-delivery:'+row.run_id;if(['mail/mail.sqlite','storage/storage.sqlite','notifications/notifications.sqlite'].includes(relative))return row.id;return null;} +function migrateDatabases(stateDir,manifest){const changed=[];for(const file of inventory(stateDir).files){if(!file.path.endsWith('.sqlite'))continue;let vault;const db=new DatabaseSync(path.join(stateDir,file.path));try{const tables=db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all().map(r=>r.name);db.exec('BEGIN IMMEDIATE');for(const name of tables){const columns=db.prepare('PRAGMA table_info('+quote(name)+')').all().map(c=>c.name);if(file.path==='supervisor/supervisor.sqlite'&&name==='metadata'){db.exec("DELETE FROM metadata WHERE key IN ('state','autostart')");changed.push({file:file.path,table:name,action:'clear-runtime-ownership'});continue;} + for(const row of db.prepare('SELECT rowid AS backup_rowid,* FROM '+quote(name)).iterate()){ + if(columns.includes('value')&&typeof row.value==='string'){let before;try{before=JSON.parse(row.value);}catch{continue;}const after=JSON.stringify(relocate(before,manifest.source.outputDir,path.join(stateDir,'restored-pdf')));if(JSON.stringify(before)!==after){db.prepare('UPDATE '+quote(name)+' SET value=? WHERE rowid=?').run(after,row.backup_rowid);changed.push({file:file.path,table:name,action:'relocate-output-path'});}} + if(columns.includes('payload')&&row.payload!==null){const rel=databaseVault(file.path),id=payloadId(file.path,name,row);if(!rel||!id)continue;vault||=new BpmVault({stateDir:path.join(stateDir,rel)});const before=vault.decode(id,row.payload),after=relocate(before,manifest.source.outputDir,path.join(stateDir,'restored-pdf'));if(JSON.stringify(before)!==JSON.stringify(after)){db.prepare('UPDATE '+quote(name)+' SET payload=? WHERE rowid=?').run(vault.encode(id,after),row.backup_rowid);changed.push({file:file.path,table:name,action:'relocate-encrypted-output-path'});}} + }}db.exec('COMMIT');}catch(e){try{db.exec('ROLLBACK');}catch{}throw e;}finally{db.close();vault?.destroy();}} + const legacy=path.join(stateDir,'dashboard','state.json');if(fs.existsSync(legacy)){const before=JSON.parse(fs.readFileSync(legacy,'utf8')),after=relocate(before,manifest.source.outputDir,path.join(stateDir,'restored-pdf'));if(JSON.stringify(before)!==JSON.stringify(after)){fs.writeFileSync(legacy,JSON.stringify(after));changed.push({file:'dashboard/state.json',action:'relocate-output-path'});}} + return changed; +} +async function restoreBackup({source,destination}={}){source=noLinks(source);const manifest=verifyBackup(source);destination=noLinks(destination,{missing:true});for(const p of [source,manifest.source.stateDir,manifest.source.outputDir])disjoint(destination,p);const existed=fs.existsSync(destination);if(existed&&(!fs.statSync(destination).isDirectory()||fs.readdirSync(destination).length))fail('BACKUP_DESTINATION'); + // Validate identity and pre-existing key collisions before creating any restored state. + const plans=manifest.vaults.map(v=>{const bytes=fs.readFileSync(path.join(source,v.keyFile));unprotect(bytes);const target=keyPath(path.join(destination,v.path));noLinks(target,{missing:true});if(fs.existsSync(target)&&!fs.readFileSync(target).equals(bytes))fail('BACKUP_KEY_COLLISION');return {target,bytes};}); + let lock,owned=false,created=false;const installed=[];try{if(!existed){fs.mkdirSync(destination);created=true;}lock=await require('./snapshot.cjs').lockOffline(destination);if(fs.readdirSync(destination).length)fail('BACKUP_DESTINATION');owned=true;protectDirectory(destination); + for(const p of plans){protectDirectory(path.dirname(p.target));try{fs.writeFileSync(p.target,p.bytes,{flag:'wx',mode:0o600});installed.push(p);}catch(e){if(e.code!=='EEXIST'||!fs.readFileSync(p.target).equals(p.bytes))fail('BACKUP_KEY_COLLISION');}} + require('./snapshot.cjs').copyTree(path.join(source,'state'),destination,{skipRuntime:true}); + // A restored backup may itself contain a previous PDF restore; the new bundle is authoritative. + if(fs.existsSync(path.join(destination,'restored-pdf')))fail('BACKUP_RESERVED_PATH');fs.mkdirSync(path.join(destination,'restored-pdf'));require('./snapshot.cjs').copyTree(path.join(source,'pdf'),path.join(destination,'restored-pdf')); + validateDatabases(destination,manifest.vaults);const migrations=migrateDatabases(destination,manifest);fs.writeFileSync(path.join(destination,'restore-config.json'),JSON.stringify({format:1,outputDir:'restored-pdf',restoredAt:new Date().toISOString(),sourceAppVersion:manifest.appVersion,migrations},null,2)+'\n',{mode:0o600});return {outputDir:path.join(destination,'restored-pdf'),migrations:migrations.length}; + }catch(error){for(const p of installed)if(fs.existsSync(p.target)&&fs.readFileSync(p.target).equals(p.bytes))fs.unlinkSync(p.target);if(owned){for(const name of fs.readdirSync(destination))fs.rmSync(path.join(destination,name),{recursive:true,force:true});}throw error;}finally{await lock?.release();if(created&&!fs.existsSync(path.join(destination,'restore-config.json'))&&fs.readdirSync(destination).length===0)fs.rmdirSync(destination);} +} +module.exports={restoreBackup,validateDatabases}; diff --git a/src/platform/backup/snapshot.cjs b/src/platform/backup/snapshot.cjs new file mode 100644 index 0000000..a7f4361 --- /dev/null +++ b/src/platform/backup/snapshot.cjs @@ -0,0 +1,19 @@ +'use strict'; +const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),net=require('node:net'); +const {acquireInstanceLock}=require('../service/instance-lock.cjs'); +const {controlAddress}=require('../service/control.cjs'); +const {fail,sha,noLinks,inside,disjoint,inventory,verifyBackup}=require('./manifest.cjs'); +const {keyPath,protectDirectory,unprotect,identity}=require('./keys.cjs'); +const runtime=new Set(['supervisor/control.key','supervisor/control.sock']); +function defaults(stateDir){const root=require('../../shared/paths.cjs').PROJECT_ROOT;let config={};try{config=JSON.parse(fs.readFileSync(path.join(root,'config.json'),'utf8'));}catch(e){if(e.code!=='ENOENT')throw e;}stateDir=path.resolve(stateDir||path.join(process.env.LOCALAPPDATA||os.homedir(),'OrderNotificationAutomation'));let outputDir=path.resolve(root,config.outputDir||'output/pdf');if(!config.outputDir){const restored=path.join(stateDir,'restore-config.json');if(fs.existsSync(restored)){noLinks(restored);const saved=JSON.parse(fs.readFileSync(restored,'utf8'));if(saved.outputDir!=='restored-pdf')fail('BACKUP_PATH');outputDir=path.join(stateDir,'restored-pdf');}}return {stateDir,outputDir};} +async function lockOffline(stateDir){const lock=await acquireInstanceLock(stateDir);let server;try{if(process.platform==='win32'){server=net.createServer(s=>s.destroy());await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(controlAddress(stateDir),resolve);});}return {async release(){if(server?.listening)await new Promise(r=>server.close(r));await lock.release();}};}catch{await lock.release();fail('ORDER_INSTANCE_OWNED');}} +function copyTree(source,target,{skipRuntime=false,exclude}={}){const inv=inventory(source),skip=p=>exclude&&inside(exclude,path.join(source,p));for(const rel of inv.directories)if(!skip(rel))fs.mkdirSync(path.join(target,rel),{recursive:true});for(const file of inv.files){if(skip(file.path)||(skipRuntime&&runtime.has(file.path)))continue;fs.copyFileSync(path.join(source,file.path),path.join(target,file.path),fs.constants.COPYFILE_EXCL);}return {directories:inv.directories.filter(p=>!skip(p)),files:inv.files.filter(f=>!skip(f.path))};} +async function createBackup({stateDir,outputDir,destination}={}){const d=stateDir&&outputDir?{}:defaults(stateDir);stateDir=noLinks(stateDir||d.stateDir);outputDir=noLinks(outputDir||d.outputDir,{missing:true});destination=noLinks(destination,{missing:true});disjoint(stateDir,destination);disjoint(outputDir,destination);if(inside(outputDir,stateDir))fail('BACKUP_OVERLAP');if(!fs.statSync(stateDir).isDirectory())fail('BACKUP_PATH');if(fs.existsSync(destination))fail('BACKUP_DESTINATION');const lock=await lockOffline(stateDir);let owned=false; + try{fs.mkdirSync(destination);owned=true;protectDirectory(destination);for(const p of ['state','pdf','keys'])fs.mkdirSync(path.join(destination,p));const copied=copyTree(stateDir,path.join(destination,'state'),{skipRuntime:true,exclude:outputDir});if(fs.existsSync(outputDir))copyTree(outputDir,path.join(destination,'pdf')); + const vaults=[];for(const rel of copied.directories){if(process.platform!=='win32')continue;const key=keyPath(path.join(stateDir,rel));if(!fs.existsSync(key))continue;noLinks(key);const bytes=fs.readFileSync(key);unprotect(bytes);const keyFile='keys/'+path.basename(key);fs.writeFileSync(path.join(destination,keyFile),bytes,{flag:'wx',mode:0o600});vaults.push({path:rel,keyFile});} + // DB validation runs only on the copy, never on source databases or their WAL files. + require('./restore.cjs').validateDatabases(path.join(destination,'state'),vaults); + const inv=inventory(destination),manifest={format:1,createdAt:new Date().toISOString(),appVersion:require('../../../package.json').version,source:{stateDir,outputDir},identity:identity(),excludedRuntime:[...runtime],vaults,...inv};const bytes=Buffer.from(JSON.stringify(manifest,null,2)+'\n');fs.writeFileSync(path.join(destination,'manifest.json'),bytes,{flag:'wx',mode:0o600});fs.writeFileSync(path.join(destination,'manifest.sha256'),sha(bytes)+'\n',{flag:'wx',mode:0o600});verifyBackup(destination);return manifest; + }catch(error){if(owned)fs.rmSync(destination,{recursive:true,force:true});throw error;}finally{await lock.release();} +} +module.exports={createBackup,defaults,lockOffline,copyTree}; diff --git a/tests/app/application.test.cjs b/tests/app/application.test.cjs index 8cfa134..8374b46 100644 --- a/tests/app/application.test.cjs +++ b/tests/app/application.test.cjs @@ -9,17 +9,13 @@ test('formal application never starts the retired generic notification scheduler 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 cannot recover a batch waiting at SMTP verification; owner sends exactly once',async t=>{ - const options=await fixture(t);const app=await main(options);let release;const gate=new Promise(r=>{release=r;});t.after(async()=>{release();await app.stop();await fs.rm(options.stateDir,{recursive:true,force:true});}); - const channel=app.mail.store.saveChannel({name:'fixture',email:'notice@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'notice',password:'fixture-only'},imap:{host:'imap.company.test',port:993,security:'tls',user:'notice',password:'fixture-only'},senders:['source@company.test'],enabled:false});app.mail.store.setState(channel.id,1,{smtp:true}); - const notifications=app.notifications,store=notifications.store;notifications.settings=()=>({schedule:{times:['09:00'],timezone:'Asia/Shanghai',weekends:true,mode:'product_line',missed:'next_window'},groups:[{productLine:'fixture',to:['receiver@company.test'],cc:[]}]});notifications.clock=()=>new Date('2026-10-17T08:59:00+08:00'); - notifications.saveSettings({...store.settings(),enabled:true,channelId:channel.id});store.ingest({sourceKey:store.settings().sourceKey,sourceId:'one',sourceVersion:'1',industry:'fixture',brief:'fixture',subject:'fixture',occurredAt:'2026-10-17T00:00:00Z'}); - let entered;const verifying=new Promise(r=>{entered=r;});let sends=0;app.mail.smtpFactory=()=>({verify:async()=>{entered();await gate;},sendMail:async()=>{sends++;return {accepted:['receiver@company.test'],rejected:[]};},close(){}}); - const sending=notifications.tick(new Date('2026-10-17T09:00:00+08:00'));await verifying;assert.equal(store.batches()[0].status,'prepared'); +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.equal(store.batches()[0].status,'prepared');assert.equal(store.items()[0].status,'reserved');}finally{NotificationStore.prototype.recover=original;release();await sending;} - assert.equal(sends,1);assert.equal(store.items()[0].status,'sent'); + 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)); diff --git a/tests/app/restored-output.test.cjs b/tests/app/restored-output.test.cjs new file mode 100644 index 0000000..11e45ed --- /dev/null +++ b/tests/app/restored-output.test.cjs @@ -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,{}),/恢复输出目录/); +}); diff --git a/tests/backup/backup.test.cjs b/tests/backup/backup.test.cjs new file mode 100644 index 0000000..9da3672 --- /dev/null +++ b/tests/backup/backup.test.cjs @@ -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')); +}); diff --git a/tests/mail/retired-binding.test.cjs b/tests/mail/retired-binding.test.cjs new file mode 100644 index 0000000..5b0e166 --- /dev/null +++ b/tests/mail/retired-binding.test.cjs @@ -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);}); diff --git a/tests/notifications/history-adapter.test.cjs b/tests/notifications/history-adapter.test.cjs new file mode 100644 index 0000000..24459d3 --- /dev/null +++ b/tests/notifications/history-adapter.test.cjs @@ -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();} +}); diff --git a/tests/order-rules/delivery-barrier.test.cjs b/tests/order-rules/delivery-barrier.test.cjs new file mode 100644 index 0000000..e17a9f3 --- /dev/null +++ b/tests/order-rules/delivery-barrier.test.cjs @@ -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 {RuleStore}=require('../../src/modules/order-rules/store.cjs'),{BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs'); +test('producer pending and corrupt deliveries block freezing despite a newer completed target scan',t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'delivery-barrier-')),rules=new RuleStore(path.join(dir,'rules')),scans=new BpmScanStore(path.join(dir,'scans'));t.after(()=>{rules.close();scans.close();fs.rmSync(dir,{recursive:true,force:true});}); + rules.executionSources=()=>['a'];rules.deliveryBlockers=allowed=>scans.deliveries.pendingSources().filter(id=>allowed(id));rules.put('execution-scans',{id:'a',status:'complete',startedAt:'2026-10-21T03:01:00Z'}); + const cutoff='2026-10-21T03:00:00Z';assert.deepEqual(rules.discoveryBlockers(cutoff),[]);scans.deliveries.enqueue({connectionId:'a',runId:'old-run',rows:[],startedAt:'2026-10-21T03:00:00Z'}); + assert.ok(rules.discoveryBlockers(cutoff).length);assert.deepEqual(rules.discoveryBlockers(cutoff,id=>id==='other'),[]); + scans.db.prepare("UPDATE execution_deliveries SET payload=x'00'").run();scans.deliveries.pending('a',Date.now());assert.ok(rules.discoveryBlockers(cutoff).length);scans.deliveries.acknowledge('old-run');assert.deepEqual(rules.discoveryBlockers(cutoff),[]); +}); diff --git a/tests/order-rules/summary.test.cjs b/tests/order-rules/summary.test.cjs new file mode 100644 index 0000000..f502f55 --- /dev/null +++ b/tests/order-rules/summary.test.cjs @@ -0,0 +1,10 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'),{DatabaseSync}=require('node:sqlite'); +const {RuleStore}=require('../../src/modules/order-rules/store.cjs'); +test('summary snapshot never decrypts full order batch or audit records',()=>{ + const calls=[],store={all:kind=>{calls.push(kind);assert.ok(!['orders','batches','audit','business-issues'].includes(kind),'summary must not load '+kind);return [];},adapters:()=>[],settings:()=>({enabled:false}),capabilities:{},clock:()=>new Date('2026-10-21T01:00:00Z'),schedule:()=>({times:['11:00','17:00'],weekends:false}),calendar:()=>[]}; + const summary=RuleStore.prototype.snapshot.call(store,{includeRecords:false});assert.deepEqual(summary.orders,[]);assert.deepEqual(summary.batches,[]);assert.deepEqual(summary.audit,[]);assert.deepEqual(calls,['rules']); +}); +test('query revision changes on updates to an existing SQLite row',()=>{ + const db=new DatabaseSync(':memory:');try{db.exec('CREATE TABLE sample(id INTEGER PRIMARY KEY,value TEXT); INSERT INTO sample VALUES(1,\'a\')');assert.equal(typeof RuleStore.prototype.queryRevision,'function');const first=RuleStore.prototype.queryRevision.call({db});db.exec("UPDATE sample SET value='b' WHERE id=1");assert.ok(RuleStore.prototype.queryRevision.call({db})>first);}finally{db.close();} +});