فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

fix(A04): validate backup envelopes and test atomic restore

* fix(A04): validate company backup envelope and prevent implicit cross-company restore * fix(A04): reject malformed and duplicate company-backup records before writes * test(A04): exercise real IndexedDB backup roundtrip, isolation and atomic rollback

davoodmehraban89 committed Oct 14, 2026 at 22:32 UTC ca63e5bd9e5e817f4affaceb795b596dba0835d0
3 files changed +149 -4
src/controllers/SettingsController.js
+19 -3
@@ -142,11 +142,27 @@ class SettingsControllerImpl {
142 backup = JSON.parse(new TextDecoder().decode(clear));
143 } catch (_) { throw new Error('رمز نادرست است یا فایل پشتیبان آسیب دیده است'); }
144 }
145 - if (!backup || !backup.data) {
146 - throw new Error('ساختار فایل بکاپ نامعتبر است');
145 + // Never send an unauthenticated, foreign-app or future-schema envelope to
146 + // the financial restore transaction. The encrypted file is authenticated
147 + // by AES-GCM; legacy plaintext JSON still requires structural validation.
148 + if (!backup || typeof backup !== 'object' || Array.isArray(backup) ||
149 + !['Factor-easyPro', 'Finora Pro'].includes(backup.app) ||
150 + backup.scope !== 'company' ||
151 + !Number.isSafeInteger(backup.schemaVersion) ||
152 + backup.schemaVersion < 1 || backup.schemaVersion > 6 ||
153 + typeof backup.companyId !== 'string' || !backup.companyId.trim() ||
154 + !backup.data || typeof backup.data !== 'object' || Array.isArray(backup.data)) {
155 + throw new Error('ساختار یا نسخه فایل پشتیبان شرکت نامعتبر است');
156 }
157
149 - return restoreCompanyBackup(backup.data, { companyId: await DataScope.companyId(), userId: user.id, mode: options.mode || 'merge' });
158 + const companyId = await DataScope.companyId();
159 + // Prevent an accidental merge of one company's books into another.
160 + // Explicit cross-company migration is a separate, intentional operation.
161 + if (backup.companyId !== companyId && options.allowCrossCompany !== true) {
162 + throw new Error('پشتیبان متعلق به شرکت دیگری است؛ بازیابی در شرکت فعلی متوقف شد');
163 + }
164 +
165 + return restoreCompanyBackup(backup.data, { companyId, userId: user.id, mode: options.mode || 'merge' });
166 }
167
168 async readFileAsText(file) {
src/core/CompanyBackupService.js
+4 -1
@@ -17,16 +17,19 @@ const isId = id => typeof id === 'string' && id.trim().length > 0;
17 export async function restoreCompanyBackup(data, { companyId, userId, mode = 'merge' }) {
18 if (!Auth.isAdmin())throw Error('بازنشانی یا بازیابی اطلاعات حسابداری فقط با مدیر مجاز است');
19 if (!companyId || !userId || !['merge', 'replace'].includes(mode)) throw new Error('گزینه‌های بازیابی نامعتبر است');
20 - if (!data || typeof data !== 'object') throw new Error('داده فایل پشتیبان نامعتبر است');
20 + if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('داده فایل پشتیبان نامعتبر است');
21
22 for (const store of COMPANY_BACKUP_STORES) {
23 const items = data[store];
24 if (items === undefined) continue;
25 if (!Array.isArray(items)) throw new Error(`جدول ${store} در فایل پشتیبان نامعتبر است`);
26 + const seenIds = new Set();
27 for (const item of items) {
28 if (!item || typeof item !== 'object' || Array.isArray(item) || !isId(item.id)) {
29 throw new Error(`رکورد بدون شناسه معتبر در بخش ${store}`);
30 }
31 + if (seenIds.has(item.id)) throw new Error(`شناسه تکراری در بخش ${store}`);
32 + seenIds.add(item.id);
33 }
34 }
35
tests/backup-restore-integration.test.mjs new
+126
@@ -0,0 +1,126 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { StorageService } from '../src/core/StorageService.js';
5 +import { CompanyService } from '../src/core/CompanyService.js';
6 +import { Auth } from '../src/core/Auth.js';
7 +import { SettingsController } from '../src/controllers/SettingsController.js';
8 +
9 +async function setup() {
10 + await StorageService.clearAll();
11 + Auth.currentUser = { id: 'restore-admin', role: 'admin', username: 'restore-admin' };
12 + await StorageService.put('companies', { id: 'c1', name: 'Company 1' });
13 + await StorageService.put('companies', { id: 'c2', name: 'Company 2' });
14 + CompanyService.activeCompanyId = 'c1';
15 +}
16 +
17 +test('A04: an actual IndexedDB company backup round-trip restores records', async () => {
18 + await setup();
19 + await StorageService.put('contacts', { id: 'customer-1', companyId: 'c1', name: 'Before backup' });
20 + await StorageService.put('contacts', { id: 'customer-2', companyId: 'c2', name: 'Other company' });
21 + const backup = await SettingsController.exportBackup();
22 + assert.equal(backup.scope, 'company');
23 + assert.equal(backup.schemaVersion, 6);
24 + await StorageService.delete('contacts', 'customer-1');
25 + assert.equal(await StorageService.get('contacts', 'customer-1'), undefined);
26 + const result = await SettingsController.importBackup(JSON.stringify(backup));
27 + assert.equal(result.added, 1);
28 + assert.equal((await StorageService.get('contacts', 'customer-1')).name, 'Before backup');
29 + assert.equal((await StorageService.get('contacts', 'customer-2')).name, 'Other company');
30 +});
31 +
32 +test('A04: malformed or future company backup envelopes never modify IndexedDB', async () => {
33 + await setup();
34 + const example = await SettingsController.exportBackup();
35 + const invalid = [
36 + { ...example, app: 'unknown' },
37 + { ...example, app: undefined },
38 + { ...example, scope: 'global' },
39 + { ...example, schemaVersion: 7 },
40 + { ...example, schemaVersion: '6' },
41 + { ...example, schemaVersion: undefined },
42 + { ...example, companyId: '' },
43 + { ...example, data: [] }
44 + ];
45 + for (const backup of invalid) {
46 + backup.data = Array.isArray(backup.data) ? backup.data : {
47 + ...backup.data,
48 + contacts: [{ id: 'should-never-exist', companyId: 'c1' }]
49 + };
50 + await assert.rejects(SettingsController.importBackup(backup), /نامعتبر/);
51 + assert.equal(await StorageService.get('contacts', 'should-never-exist'), undefined);
52 + }
53 +});
54 +
55 +test('A04: cross-company restore requires explicit opt-in', async () => {
56 + await setup();
57 + const backup = await SettingsController.exportBackup();
58 + backup.companyId = 'c2';
59 + backup.data.contacts = [{ id: 'from-c2', companyId: 'c2', name: 'Imported only by permission' }];
60 + await assert.rejects(SettingsController.importBackup(backup), /شرکت دیگری/);
61 + assert.equal(await StorageService.get('contacts', 'from-c2'), undefined);
62 + const result = await SettingsController.importBackup(backup, { allowCrossCompany: true });
63 + assert.equal(result.added, 1);
64 + assert.equal((await StorageService.get('contacts', 'from-c2')).companyId, 'c1');
65 +});
66 +
67 +test('A04: company backup rejects duplicate IDs before any database writes', async () => {
68 + await setup();
69 + const backup = await SettingsController.exportBackup();
70 + backup.data.contacts = [
71 + { id: 'duplicate', companyId: 'c1', name: 'first' },
72 + { id: 'duplicate', companyId: 'c1', name: 'second' }
73 + ];
74 + await assert.rejects(SettingsController.importBackup(backup), /شناسه تکراری/);
75 + assert.equal(await StorageService.get('contacts', 'duplicate'), undefined);
76 +});
77 +
78 +test('A04: a collision with another company rolls back earlier writes atomically', async () => {
79 + await setup();
80 + await StorageService.put('contacts', { id: 'foreign-id', companyId: 'c2', name: 'Protected' });
81 + const backup = await SettingsController.exportBackup();
82 + backup.data.contacts = [
83 + { id: 'new-first', companyId: 'c1', name: 'must rollback' },
84 + { id: 'foreign-id', companyId: 'c1', name: 'must not overwrite' }
85 + ];
86 + await assert.rejects(SettingsController.importBackup(backup), /شرکت دیگر/);
87 + assert.equal(await StorageService.get('contacts', 'new-first'), undefined);
88 + assert.equal((await StorageService.get('contacts', 'foreign-id')).name, 'Protected');
89 +});
90 +
91 +test('A04: full storage snapshot restores users without accepting backup credentials', async () => {
92 + await setup();
93 + await StorageService.put('users', { id: 'local-user', username: 'local', role: 'user', pwHash: 'LOCAL_HASH', pwSalt: 'LOCAL_SALT', pwIter: 600000 });
94 + const backup = await StorageService.exportAll();
95 + assert.equal(backup.data.users[0].pwHash, undefined);
96 + assert.equal(backup.data.users[0].pwSalt, undefined);
97 + backup.data.users[0].username = 'renamed';
98 + backup.data.users[0].pwHash = 'FORGED_HASH';
99 + backup.data.users.push({ id: 'new-user', username: 'new', pwHash: 'ATTACKER_HASH', role: 'user' });
100 + await StorageService.importAll(backup);
101 + const local = await StorageService.get('users', 'local-user');
102 + const fresh = await StorageService.get('users', 'new-user');
103 + assert.equal(local.username, 'renamed');
104 + assert.equal(local.pwHash, 'LOCAL_HASH');
105 + assert.equal(local.pwSalt, 'LOCAL_SALT');
106 + assert.equal(fresh.pwHash, undefined);
107 + assert.equal(fresh.mustSetPassword, true);
108 +});
109 +
110 +test('A04: a unique-index conflict rolls back the entire full-snapshot transaction', async () => {
111 + await setup();
112 + await StorageService.put('products', { id: 'baseline', companyId: 'c1', name: 'Existing' });
113 + await assert.rejects(StorageService.importAll({
114 + app: 'Factor-easyPro', version: 6,
115 + data: {
116 + products: [{ id: 'new-product', companyId: 'c1', name: 'Must rollback' }],
117 + journal_entries: [
118 + { id: 'journal-a', companyId: 'c1', sourceKey: 'same-key' },
119 + { id: 'journal-b', companyId: 'c1', sourceKey: 'same-key' }
120 + ]
121 + }
122 + }));
123 + assert.equal(await StorageService.get('products', 'new-product'), undefined);
124 + assert.equal((await StorageService.get('products', 'baseline')).name, 'Existing');
125 + assert.equal((await StorageService.getAll('journal_entries')).length, 0);
126 +});