فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
fix(A03): validate anchored backups, preserve legacy replay, reject reordered and tampered history
davoodmehraban89 committed
Oct 20, 2026 at 08:50 UTC
293239951b6c15df766e891fd386b54c6f99ec51
6 files changed
+105
-7
src/controllers/SettingsController.js
+3
-3
@@ -78,7 +78,8 @@ class SettingsControllerImpl {
78
}
79
}
80
81
- const events = [...backup.data.audit_events].sort((a,b) => (a.chainIndex ?? 0) - (b.chainIndex ?? 0));
81
+ backup.data.audit_events.sort((a,b) => (a.chainIndex ?? 0) - (b.chainIndex ?? 0));
82
+ const events = backup.data.audit_events;
83
const result = verifyChain(events);
84
if (!result.valid) throw new Error('زنجیره ممیزی هنگام تهیه پشتیبان نامعتبر است');
85
backup.auditAnchor = { count: result.count, headHash: result.headHash };
@@ -188,8 +189,7 @@ class SettingsControllerImpl {
189
const history = backup.data.audit_events || [];
190
if (!Array.isArray(history)) throw new Error('سوابق ممیزی پشتیبان نامعتبر است');
191
if (backup.auditAnchor !== undefined || history.some(row => row.eventHash !== undefined)) {
191
- const ordered = [...history].sort((a,b) => (a.chainIndex ?? 0) - (b.chainIndex ?? 0));
192
- const result = verifyChain(ordered, backup.auditAnchor ?? null);
192
+ const result = verifyChain(history, backup.auditAnchor ?? null);
193
if (!result.valid) throw new Error('زنجیره ممیزی یا لنگر پشتیبان نامعتبر است');
194
}
195
src/core/AuditChain.js
+3
-2
@@ -31,12 +31,13 @@ export const auditHash = row => sha256(canonical(Object.fromEntries(Object.entri
31
export function verifyChain(rows, anchor = null) {
32
const ordered=[...rows];
33
let previous=null;
34
+ const companyId = ordered[0]?.companyId;
35
for(let i=0;i<ordered.length;i++){
36
const row=ordered[i];
36
- if(!row||row.chainIndex!==i||row.prevHash!==previous||row.eventHash!==auditHash(row))return {valid:false,index:i,reason:'chain mismatch'};
37
+ if(!row||row.companyId!==companyId||row.chainIndex!==i||row.prevHash!==previous||!(/^[0-9a-f]{64}$/).test(row.eventHash)||row.eventHash!==auditHash(row))return {valid:false,index:i,reason:'chain mismatch'};
38
previous=row.eventHash;
39
}
39
- if(anchor!==null&&(anchor.count!==ordered.length||anchor.headHash!==previous))
40
+ if(anchor!==null&&(!anchor||!Number.isSafeInteger(anchor.count)||anchor.count<0||anchor.count!==ordered.length||anchor.headHash!==previous))
41
return {valid:false,index:ordered.length,reason:'anchor mismatch'};
42
return {valid:true,count:ordered.length,headHash:previous,anchored:anchor!==null};
43
}
src/core/CompanyBackupService.js
+6
-1
@@ -3,6 +3,7 @@
3
import { StorageService } from './StorageService.js';
4
import { Auth } from './Auth.js';
5
import { AuditService } from './AuditService.js';
6
+import { normalizeLegacyAudit, verifyChain } from './AuditChain.js';
7
import { assertJalaliDate, validateAccount, validateFiscalPeriod, validateJournalLines, journalSourceKey } from './AccountingCore.mjs';
8
9
export const COMPANY_BACKUP_STORES = Object.freeze([
@@ -53,6 +54,8 @@ export async function restoreCompanyBackup(data, { companyId, userId, mode = 'me
54
}
55
}
56
57
+ if (Array.isArray(data.audit_events) && data.audit_events.some(row => row.eventHash !== undefined) &&
58
+ !verifyChain(data.audit_events).valid) throw new Error('زنجیره ممیزی پشتیبان نامعتبر است');
59
const counts = { added: 0, updated: 0, skipped: 0 };
60
// Reads, ownership validation, foreign-key validation and writes share one IndexedDB transaction.
61
return StorageService.transaction([...COMPANY_BACKUP_STORES, 'settings'], async tx => {
@@ -80,7 +83,9 @@ export async function restoreCompanyBackup(data, { companyId, userId, mode = 'me
83
throw new Error(`شناسه رکورد ${store}/${row.id} متعلق به شرکت دیگر است؛ بازیابی متوقف شد`);
84
}
85
if (existing && immutable) {
83
- if (!sameImmutableRecord(existing, row)) {
86
+ const comparable = store === 'audit_events' && row.eventHash === undefined
87
+ ? normalizeLegacyAudit(row, existing.chainIndex, existing.prevHash) : row;
88
+ if (!sameImmutableRecord(existing, comparable)) {
89
throw new Error('بازنویسی سابقه ممیزی یا اصلاح سند مجاز نیست');
90
}
91
counts.skipped++;
src/core/StorageService.js
+34
-1
@@ -1,4 +1,5 @@
1
import { isAuditServiceRow, AuditService } from './AuditService.js';
2
+import { verifyChain, normalizeLegacyAudit } from './AuditChain.js';
3
4
// ============================================================
5
// StorageService — IndexedDB wrapper
@@ -387,9 +388,20 @@ class StorageServiceImpl {
388
data.users = data.users.map(stripCredentials);
389
}
390
391
+ const auditAnchors = {};
392
+ const companies = [...new Set((data.audit_events || []).map(row => row.companyId))].sort();
393
+ data.audit_events = companies.flatMap(companyId =>
394
+ data.audit_events.filter(row => row.companyId === companyId)
395
+ .sort((a,b) => (a.chainIndex ?? 0) - (b.chainIndex ?? 0)));
396
+ for (const companyId of companies) {
397
+ const result = verifyChain(data.audit_events.filter(row => row.companyId === companyId));
398
+ if (!result.valid) throw new Error('زنجیره ممیزی در پشتیبان کامل نامعتبر است');
399
+ auditAnchors[companyId] = { count: result.count, headHash: result.headHash };
400
+ }
401
return {
402
app: 'Factor-easyPro',
403
version: DB_VERSION,
404
+ auditAnchors,
405
exportedAt: new Date().toISOString(),
406
data
407
};
@@ -434,6 +446,25 @@ class StorageServiceImpl {
446
}
447
}
448
449
+ const auditRowsForValidation = json.data.audit_events || [];
450
+ if (json.auditAnchors !== undefined) {
451
+ if (!json.auditAnchors || typeof json.auditAnchors !== 'object' || Array.isArray(json.auditAnchors))
452
+ throw new Error('لنگر پشتیبان نامعتبر است');
453
+ const companies = new Set(auditRowsForValidation.map(row => row.companyId));
454
+ if (Object.keys(json.auditAnchors).length !== companies.size ||
455
+ [...companies].some(companyId => !Object.hasOwn(json.auditAnchors, companyId)))
456
+ throw new Error('لنگر پشتیبان ناقص است');
457
+ for (const companyId of companies) {
458
+ const rows = auditRowsForValidation.filter(row => row.companyId === companyId);
459
+ if (!verifyChain(rows, json.auditAnchors[companyId]).valid)
460
+ throw new Error('زنجیره ممیزی یا لنگر پشتیبان نامعتبر است');
461
+ }
462
+ } else if (auditRowsForValidation.some(row => row.eventHash !== undefined)) {
463
+ for (const companyId of new Set(auditRowsForValidation.map(row => row.companyId))) {
464
+ if (!verifyChain(auditRowsForValidation.filter(row => row.companyId === companyId)).valid)
465
+ throw new Error('زنجیره ممیزی فایل پشتیبان نامعتبر است');
466
+ }
467
+ }
468
await this.transaction(STORES, async tx => {
469
const auditRows = (json.data.audit_events || []).filter(item => !!item);
470
for (const companyId of new Set(auditRows.map(row => row.companyId))) {
@@ -458,7 +489,9 @@ class StorageServiceImpl {
489
}
490
const old = await tx.get(store, item.id);
491
if (old) {
461
- if (!sameSnapshotRecord(old, item)) {
492
+ const comparable = store === 'audit_events' && item.eventHash === undefined
493
+ ? normalizeLegacyAudit(item, old.chainIndex, old.prevHash) : item;
494
+ if (!sameSnapshotRecord(old, comparable)) {
495
throw new Error('بازنویسی سابقه ممیزی یا اصلاح سند از پشتیبان مجاز نیست');
496
}
497
} else {
tests/a03-audit-chain.test.mjs
+10
@@ -51,3 +51,13 @@ test('A03 old backup audit metadata receives deterministic defaults', () => {
51
assert.equal(verifyChain([migrated]).valid, true);
52
assert.deepEqual(normalizeLegacyAudit(old, 0, null), migrated);
53
});
54
+
55
+test('A03: foreign-company event cannot join an otherwise valid hash chain', () => {
56
+ const rows = sample();
57
+ rows[1].companyId = 'other-company';
58
+ rows[1].eventHash = auditHash(rows[1]);
59
+ assert.equal(verifyChain(rows).valid, false);
60
+});
61
+test('A03: invalid anchor metadata is rejected', () => {
62
+ assert.equal(verifyChain(sample(), { count: -1, headHash: null }).valid, false);
63
+});
tests/a03-audit-integration.test.mjs
+49
@@ -272,3 +272,52 @@ test('A03: direct historical restore without authorization is rejected', async (
272
})), /بازیابی مستقیم ممیزی/);
273
assert.equal(await StorageService.get('audit_events', 'forged-restore'), undefined);
274
});
275
+
276
+
277
+test('A03: company backup detects payload change, middle deletion, reorder and tail deletion', async () => {
278
+ await setup();
279
+ for (let i = 0; i < 3; i++) {
280
+ await StorageService.transaction('audit_events', tx => AuditService.append(tx, {
281
+ companyId: company, eventType: 'journal_posted', sourceType: 'journal',
282
+ sourceId: 'tamper-' + i, commandKey: 'tamper-' + i, businessDate
283
+ }));
284
+ }
285
+ const original = await SettingsController.exportBackup();
286
+ assert.equal(original.auditAnchor.count, original.data.audit_events.length);
287
+ for (const mutation of ['payload', 'middle', 'reorder', 'tail']) {
288
+ const altered = structuredClone(original);
289
+ const rows = altered.data.audit_events;
290
+ if (mutation === 'payload') rows[1].sourceId = 'forged';
291
+ if (mutation === 'middle') rows.splice(1, 1);
292
+ if (mutation === 'reorder') [rows[0], rows[1]] = [rows[1], rows[0]];
293
+ if (mutation === 'tail') rows.pop();
294
+ await assert.rejects(SettingsController.importBackup(altered), /زنجیره ممیزی|لنگر پشتیبان/,
295
+ mutation);
296
+ }
297
+ const withoutAnchor = structuredClone(original);
298
+ withoutAnchor.data.audit_events.pop();
299
+ delete withoutAnchor.auditAnchor;
300
+ const { verifyChain } = await import('../src/core/AuditChain.js');
301
+ assert.equal(verifyChain(withoutAnchor.data.audit_events).valid, true,
302
+ 'Without an independently retained head, tail truncation is not detectable');
303
+});
304
+
305
+test('A03: legacy v6 backup imports audit rows without new metadata and exports a valid anchor', async () => {
306
+ await StorageService.clearAll();
307
+ Auth.currentUser = { id: 'audit-admin', role: 'admin', username: 'manager' };
308
+ CompanyService.activeCompanyId = company;
309
+ await StorageService.put('companies', { id: company, name: 'Synthetic C1' });
310
+ const old = { id: 'legacy-6', companyId: company, eventType: 'journal_posted',
311
+ sourceId: 'journal-6', commandKey: company + ':old' };
312
+ await StorageService.importAll({ app: 'Factor-easyPro', version: 6,
313
+ data: { audit_events: [old] } });
314
+ const migrated = await StorageService.get('audit_events', old.id);
315
+ assert.equal(migrated.actorId, 'legacy-unknown');
316
+ assert.equal(migrated.chainIndex, 0);
317
+ assert.match(migrated.eventHash, /^[0-9a-f]{64}$/);
318
+ const backup = await StorageService.exportAll();
319
+ assert.equal(backup.auditAnchors[company].headHash, migrated.eventHash);
320
+ await StorageService.importAll({ app: 'Factor-easyPro', version: 6,
321
+ data: { audit_events: [old] } });
322
+ assert.equal((await StorageService.getAll('audit_events')).length, 1);
323
+});