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
@@ -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