Treasury & Bank Transfer Management System — سامانه مدیریت خزانه‌داری و حواله‌های بانکی

Add atomic never-overwrite SQLite WAL-consistent backup, integrity verify, and safe restore to new path

davoodmehraban89 committed Oct 23, 2026 at 14:47 UTC 004493888078df4ed280d1c5ff29916a408fdf19
1 file changed +77
src/platform/local/verified-sqlite-backup.ts new
+77
@@ -0,0 +1,77 @@
1 +import {randomUUID} from 'node:crypto';
2 +import {DatabaseSync} from 'node:sqlite';
3 +import {COPYFILE_EXCL,copyFileSync,existsSync,mkdirSync,rmSync} from 'node:fs';
4 +import {dirname,join,resolve} from 'node:path';
5 +
6 +const expectedTables=['accounts','audit','beneficiaries','meta','payments'] as const;
7 +
8 +/** Verify the entire backup, not just that SQLite can open its header. */
9 +export function verifyTreasurySqliteBackup(file:string){
10 + const db=new DatabaseSync(file,{readOnly:true});
11 + try{
12 + const result=db.prepare('PRAGMA integrity_check').all() as Array<{integrity_check:string}>;
13 + if(result.length!==1||result[0].integrity_check!=='ok'){
14 + throw new Error('SQLITE_BACKUP_INTEGRITY_FAILED');
15 + }
16 + const tables=(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all() as Array<{name:string}>)
17 + .map(row=>row.name);
18 + for(const name of expectedTables)if(!tables.includes(name)){
19 + throw new Error('SQLITE_BACKUP_REQUIRED_TABLE_MISSING');
20 + }
21 + const row=db.prepare("SELECT value FROM meta WHERE key='schema_version'").get() as {value?:string}|undefined;
22 + if(row?.value!=='1')throw new Error('SQLITE_BACKUP_UNSUPPORTED_SCHEMA');
23 + return {
24 + schemaVersion:1,
25 + accounts:Number((db.prepare('SELECT COUNT(*) AS count FROM accounts').get() as {count:number}).count),
26 + beneficiaries:Number((db.prepare('SELECT COUNT(*) AS count FROM beneficiaries').get() as {count:number}).count),
27 + payments:Number((db.prepare('SELECT COUNT(*) AS count FROM payments').get() as {count:number}).count),
28 + audit:Number((db.prepare('SELECT COUNT(*) AS count FROM audit').get() as {count:number}).count)
29 + };
30 + }finally{db.close()}
31 +}
32 +
33 +/**
34 + * VACUUM INTO makes a consistent SQLite snapshot, including committed WAL data.
35 + * The temporary file is unique and only files created by this invocation are
36 + * removed. COPYFILE_EXCL ensures an existing backup is never overwritten.
37 + */
38 +export function createVerifiedSqliteBackup(db:DatabaseSync,destination:string){
39 + const dest=resolve(destination);
40 + if(existsSync(dest))throw new Error('SQLITE_BACKUP_DESTINATION_EXISTS');
41 + mkdirSync(dirname(dest),{recursive:true});
42 + const temporary=join(dirname(dest),'.treasuryflow-backup-'+randomUUID()+'.sqlite');
43 + let createdDestination=false;
44 + try{
45 + db.prepare('VACUUM main INTO ?').run(temporary);
46 + const summary=verifyTreasurySqliteBackup(temporary);
47 + copyFileSync(temporary,dest,COPYFILE_EXCL);
48 + createdDestination=true;
49 + const copied=verifyTreasurySqliteBackup(dest);
50 + if(JSON.stringify(summary)!==JSON.stringify(copied))throw new Error('SQLITE_BACKUP_VERIFICATION_MISMATCH');
51 + return copied;
52 + }catch(error){
53 + if(createdDestination)rmSync(dest,{force:true});
54 + throw error;
55 + }finally{
56 + rmSync(temporary,{force:true});
57 + }
58 +}
59 +
60 +/** Restore to a new location only. Never replace an existing operational DB. */
61 +export function restoreVerifiedSqliteBackupToNewPath(source:string,destination:string){
62 + const src=resolve(source),dest=resolve(destination);
63 + if(src===dest||existsSync(dest))throw new Error('SQLITE_RESTORE_WOULD_OVERWRITE_EXISTING_DATA');
64 + const expected=verifyTreasurySqliteBackup(src);
65 + mkdirSync(dirname(dest),{recursive:true});
66 + let created=false;
67 + try{
68 + copyFileSync(src,dest,COPYFILE_EXCL);
69 + created=true;
70 + const recovered=verifyTreasurySqliteBackup(dest);
71 + if(JSON.stringify(expected)!==JSON.stringify(recovered))throw new Error('SQLITE_RESTORE_VERIFICATION_MISMATCH');
72 + return recovered;
73 + }catch(error){
74 + if(created)rmSync(dest,{force:true});
75 + throw error;
76 + }
77 +}