103 lines
11 KiB
JavaScript
103 lines
11 KiB
JavaScript
#!/usr/bin/env node
|
|
'use strict';
|
|
// Offline admin preparation only. This module never loads the application,
|
|
// network providers, scheduler, or mail sending service.
|
|
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto');
|
|
const {DatabaseSync}=require('node:sqlite');
|
|
const {execFileSync}=require('node:child_process');
|
|
const {BpmVault}=require('../src/platform/security/vault.cjs');
|
|
const {RuleStore}=require('../src/modules/order-rules/store.cjs');
|
|
const {MailStore}=require('../src/modules/mail/store.cjs');
|
|
const {readSourceWorkbook}=require('../src/modules/order-rules/source-workbook.cjs');
|
|
const {buildPreparationPlan,applyPreparationPlan,publicPlan}=require('../src/modules/order-rules/test-preparation.cjs');
|
|
const fail=code=>{throw Object.assign(Error(code),{code});};
|
|
const databases=[['order-rules','rules.sqlite'],['mail','mail.sqlite']];
|
|
function temporaryDirectory(){return fs.mkdtempSync(path.join(require('node:os').tmpdir(),'order-preparation-'));}
|
|
function removeTemporaryDirectory(directory){if(path.dirname(path.resolve(directory))!==path.resolve(require('node:os').tmpdir())||!path.basename(directory).startsWith('order-preparation-'))fail('PREPARATION_TEMP_PATH');fs.rmSync(directory,{recursive:true,force:true});}
|
|
function snapshotDatabases(stateDir){
|
|
const read=()=>databases.flatMap(([directory,name])=>[name,name+'-wal'].map(filename=>{
|
|
const relative=path.join(directory,filename),file=path.join(stateDir,relative);let before;
|
|
try{before=fs.statSync(file,{bigint:true});}catch(error){if(error.code==='ENOENT'&&filename.endsWith('-wal'))return {relative,bytes:null,identity:null};throw error;}
|
|
const bytes=fs.readFileSync(file),after=fs.statSync(file,{bigint:true}),identity=s=>[s.dev,s.ino,s.size,s.mtimeNs,s.ctimeNs].join(':');
|
|
if(identity(before)!==identity(after))fail('PREPARATION_SOURCE_CHANGED');return {relative,bytes,identity:identity(after)};
|
|
}));
|
|
// Never open the source with SQLite: readOnly WAL connections can create or
|
|
// update SHM. Only an unchanged double capture is eligible for local replay.
|
|
let captured;
|
|
for(let attempt=0;attempt<3;attempt++){
|
|
try{const before=read(),after=read();if(before.every((value,index)=>value.identity===after[index].identity&&(value.bytes===null?after[index].bytes===null:value.bytes.equals(after[index].bytes)))){captured=after;break;}}catch(error){if(error.code!=='PREPARATION_SOURCE_CHANGED'&&error.code!=='ENOENT')throw error;}
|
|
}
|
|
if(!captured)fail('PREPARATION_SOURCE_CHANGED');
|
|
const root=temporaryDirectory();try{for(const {relative,bytes} of captured)if(bytes!==null){const file=path.join(root,relative);fs.mkdirSync(path.dirname(file),{recursive:true});fs.writeFileSync(file,bytes,{flag:'wx',mode:0o600});}return root;}catch(error){removeTemporaryDirectory(root);throw error;}
|
|
}
|
|
function parseArgs(args){const options={apply:false};while(args.length){const arg=args.shift();if(arg==='--apply'){if(options.apply)throw Error('PREPARATION_USAGE');options.apply=true;continue;}const key={'--source-file':'sourceFile','--state-dir':'stateDir','--backup':'backup'}[arg];if(!key||options[key]||!args.length||args[0].startsWith('--'))throw Error('PREPARATION_USAGE');options[key]=args.shift();}if(!options.sourceFile)throw Error('PREPARATION_SOURCE_REQUIRED');if(options.apply&&!options.backup)throw Error('PREPARATION_BACKUP_REQUIRED');return options;}
|
|
function existingVault(directory){
|
|
const vault=Object.create(BpmVault.prototype);vault.stateDir=path.resolve(directory);
|
|
// Bypass the constructor and ensureKey's directory/key creation: preview may
|
|
// only read an existing vault, including when the key is missing or invalid.
|
|
vault.ensureKey=function(){if(this.key)return this.key;const keyFile=process.platform==='win32'?require('../src/platform/backup/keys.cjs').keyPath(this.stateDir):path.join(this.stateDir,'.keys',crypto.createHash('sha256').update(this.stateDir.toLowerCase()).digest('hex')+'.key');const bytes=fs.readFileSync(keyFile);this.key=process.platform==='win32'?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'):bytes;if(this.key.length!==32){this.key.fill(0);this.key=null;throw Error('PREPARATION_KEY_INVALID');}return this.key;};return vault;
|
|
}
|
|
function openStores(stateDir,{readOnly=true}={}){
|
|
const opened=[];let snapshotRoot;
|
|
try{
|
|
const databaseRoot=readOnly?(snapshotRoot=snapshotDatabases(stateDir)):stateDir;
|
|
const store=Object.create(RuleStore.prototype);store.db=new DatabaseSync(path.join(databaseRoot,'order-rules','rules.sqlite'),{readOnly});opened.push(store);store.vault=existingVault(path.join(stateDir,'order-rules','secrets'));store.clock=()=>new Date();store.desktopRoot=path.join(require('node:os').homedir(),'Desktop');store.schedule=()=>({times:['11:00','17:00'],weekends:false});store.calendar=()=>[];store.capabilities={liveTodo:false,pdfExport:false,automaticArchive:false};
|
|
const mailStore=Object.create(MailStore.prototype);mailStore.db=new DatabaseSync(path.join(databaseRoot,'mail','mail.sqlite'),{readOnly});opened.push(mailStore);mailStore.vault=existingVault(path.join(stateDir,'mail','secrets'));
|
|
if(readOnly)for(const value of opened)if(value.db.prepare('PRAGMA quick_check').all().some(row=>Object.values(row)[0]!=='ok'))fail('PREPARATION_SOURCE_SNAPSHOT_INVALID');
|
|
// Read an existing schema directly. Opening constructors here would run
|
|
// recovery/migrations and could rewrite old sending records during preview.
|
|
return {store,mailStore,close(){for(const value of opened.reverse()){value.db.close();value.vault?.destroy();}if(snapshotRoot){removeTemporaryDirectory(snapshotRoot);snapshotRoot=null;}}};
|
|
}catch(error){for(const value of opened.reverse()){try{value.db.close();}catch{}value.vault?.destroy();}if(snapshotRoot)removeTemporaryDirectory(snapshotRoot);throw error;}
|
|
}
|
|
function assertBackupCurrent(manifest,stateDir,backupDir){
|
|
const {inventory,fileHash,inside,verifyBackup}=require('../src/platform/backup/manifest.cjs');
|
|
if(!backupDir)fail('PREPARATION_BACKUP_INCOMPLETE');
|
|
const verified=verifyBackup(backupDir);if(JSON.stringify(verified)!==JSON.stringify(manifest))fail('PREPARATION_BACKUP_MANIFEST_CHANGED');
|
|
const canonical=file=>fs.realpathSync(file).toLowerCase();if(canonical(manifest.source.stateDir)!==canonical(stateDir))throw Error('PREPARATION_BACKUP_STATE_MISMATCH');
|
|
const outputDir=require('../src/platform/backup/snapshot.cjs').defaults(stateDir).outputDir;
|
|
if(path.resolve(outputDir).toLowerCase()!==path.resolve(manifest.source.outputDir).toLowerCase())fail('PREPARATION_BACKUP_OUTPUT_MISMATCH');
|
|
const current=inventory(stateDir),entries=new Map(manifest.files.map(file=>[file.path,file])),directories=new Set(manifest.directories),runtime=new Set(['supervisor/control.key','supervisor/control.sock']);
|
|
const excluded=relative=>runtime.has(relative)||inside(outputDir,path.join(stateDir,relative))||/\.sqlite-shm$/.test(relative);
|
|
const databaseFiles=current.files.filter(file=>file.path.endsWith('.sqlite')&&!excluded(file.path));
|
|
for(const [directory,name] of databases)if(!databaseFiles.some(file=>file.path===directory+'/'+name)||!entries.has('state/'+directory+'/'+name))fail('PREPARATION_BACKUP_INCOMPLETE');
|
|
for(const directory of current.directories)if(!excluded(directory)&&!directories.has('state/'+directory))fail('PREPARATION_BACKUP_INCOMPLETE');
|
|
for(const file of current.files){
|
|
if(excluded(file.path)||file.path.endsWith('.sqlite-wal'))continue;
|
|
const entry=entries.get('state/'+file.path);if(!entry)fail('PREPARATION_BACKUP_INCOMPLETE');
|
|
// Official backup validation replays committed WAL pages into its copy.
|
|
// Compare database contents after the same normalization on both copies.
|
|
if(!file.path.endsWith('.sqlite')&&(file.sha256!==entry.sha256||file.size!==entry.size))fail('PREPARATION_BACKUP_STALE');
|
|
}
|
|
// A full state listing alone is insufficient: Windows vault keys live outside
|
|
// state. Every existing key must be present, identical and DPAPI-readable.
|
|
if(process.platform==='win32'){
|
|
const {keyPath,unprotect}=require('../src/platform/backup/keys.cjs');
|
|
for(const directory of current.directories){
|
|
if(excluded(directory))continue;const key=keyPath(path.join(stateDir,directory));if(!fs.existsSync(key))continue;
|
|
const binding=manifest.vaults.find(vault=>vault.path===directory);
|
|
if(!binding||binding.keyFile!=='keys/'+path.basename(key)||!entries.has(binding.keyFile))fail('PREPARATION_BACKUP_KEY_MISSING');
|
|
const bytes=fs.readFileSync(path.join(backupDir,binding.keyFile));if(!bytes.equals(fs.readFileSync(key)))fail('PREPARATION_BACKUP_KEY_MISMATCH');unprotect(bytes);
|
|
}
|
|
}
|
|
// Both source and bundle remain untouched. The caller holds the exclusive
|
|
// offline instance lock while these current-state copies are compared.
|
|
const validationRoot=temporaryDirectory();try{
|
|
const sourceCopy=path.join(validationRoot,'current'),backupCopy=path.join(validationRoot,'backup'),validate=require('../src/platform/backup/restore.cjs').validateDatabases;
|
|
fs.cpSync(stateDir,sourceCopy,{recursive:true,filter:file=>!excluded(path.relative(stateDir,file).split(path.sep).join('/'))});
|
|
fs.cpSync(path.join(backupDir,'state'),backupCopy,{recursive:true,filter:file=>!file.endsWith('.sqlite-shm')});
|
|
validate(sourceCopy,manifest.vaults);validate(backupCopy,manifest.vaults);
|
|
for(const file of databaseFiles)if(fileHash(path.join(sourceCopy,file.path))!==fileHash(path.join(backupCopy,file.path)))fail('PREPARATION_BACKUP_STALE');
|
|
}finally{removeTemporaryDirectory(validationRoot);}
|
|
}
|
|
async function main(args){
|
|
const options=parseArgs([...args]),stateDir=path.resolve(options.stateDir||require('../src/platform/backup/snapshot.cjs').defaults().stateDir),source=readSourceWorkbook(options.sourceFile);let lock,opened;
|
|
try{
|
|
if(options.apply){const manifest=require('../src/platform/backup/manifest.cjs').verifyBackup(options.backup);lock=await require('../src/platform/backup/snapshot.cjs').lockOffline(stateDir);assertBackupCurrent(manifest,stateDir,options.backup);}
|
|
opened=openStores(stateDir,{readOnly:!options.apply});const plan=buildPreparationPlan({...opened,source});
|
|
if(!options.apply)return {mode:'dry-run',...publicPlan(plan)};
|
|
const result=applyPreparationPlan({...opened,plan,actor:{username:'offline-admin',role:'admin'}});return {mode:'applied',run:result.run,automaticProcessing:false,automaticSending:false,source:plan.source};
|
|
}finally{opened?.close();await lock?.release();}
|
|
}
|
|
if(require.main===module)main(process.argv.slice(2)).then(result=>process.stdout.write(JSON.stringify(result,null,2)+'\n')).catch(error=>{process.stderr.write(JSON.stringify({ok:false,code:/^(?:PREPARATION_|ORDER_|BACKUP_)/.test(error.code||error.message)?error.code||error.message:'PREPARATION_FAILED',message:'Preparation stopped; no automatic processing or sending was enabled.'})+'\n');process.exitCode=1;});
|
|
module.exports={parseArgs,existingVault,openStores,assertBackupCurrent,main};
|