feat: add verified offline recovery and retire legacy send assembly
This commit is contained in:
1 parent
84e2f0d9ba
commit
1148aa6f14
19 files changed
+235
-24
No files matched your search
+15
-8
@@ -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};
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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};
|
||||
@@ -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',
|
||||
|
||||
@@ -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};
|
||||
@@ -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;i<locations.length;i++)for(let j=i+1;j<locations.length;j++)if(inside(locations[i],locations[j])||inside(locations[j],locations[i]))fail('BACKUP_OVERLAP');}
|
||||
function fileHash(file){const h=crypto.createHash('sha256'),fd=fs.openSync(file,'r'),buf=Buffer.allocUnsafe(1024*1024);try{let n;while((n=fs.readSync(fd,buf,0,buf.length,null)))h.update(buf.subarray(0,n));return h.digest('hex');}finally{fs.closeSync(fd);}}
|
||||
function inventory(root){noLinks(root);const files=[],directories=[];function visit(dir,prefix=''){for(const name of fs.readdirSync(dir).sort()){const rel=safeRelative(prefix+name),file=path.join(dir,name),s=fs.lstatSync(file);if(s.isSymbolicLink()||(!s.isDirectory()&&!s.isFile())||(s.isFile()&&s.nlink!==1))fail('BACKUP_LINK');if(s.isDirectory()){directories.push(rel);visit(file,rel+'/');}else files.push({path:rel,size:s.size,sha256:fileHash(file)});}}visit(root);return {files,directories};}
|
||||
function verifyBackup(source){const root=noLinks(source),actual=inventory(root);let m,bytes;try{bytes=fs.readFileSync(path.join(root,'manifest.json'));if(bytes.length>32*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};
|
||||
@@ -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};
|
||||
@@ -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};
|
||||
Reference in new issue
Block a user