فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
test(A03): harden chain validation and exercise mixed legacy, corrupt backup and concurrent append
davoodmehraban89 committed
Oct 20, 2026 at 09:11 UTC
894e1f54409a7f12455ee27b6e3d8b80f4899a55
10 files changed
+103
-22
STATUS.md
+7
@@ -71,3 +71,10 @@ Review CI on latest A03 PR head, fix failing fixtures and ensure restore authori
71
- This evidence verifies the application code at the stated SHA. A STATUS-only documentation commit will require its own final-head CI run before completion.
72
- Independent three-agent review remains NOT VERIFIED: this execution environment does not expose a multi-agent reviewer launch capability. No approval or merge is claimed.
73
- Local clone/npm test remains unavailable because container DNS cannot resolve github.com; GitHub Actions is the actual test runner.
74
+
75
+## A03 three-pass review initiated (2026-10-20)
76
+- Three sequential code-review passes were performed against PR #116 because no callable subagent/Task tool is exposed. These are NOT independent agents.
77
+- Functional pass: previous completed CI run 39374969382, SHA 95f6c976a04a72e2ddaf27f20773994e871e0250, Linux 257/257, Windows 257/257. Edge coverage gaps found; new tests added, pending new CI.
78
+- Security/quality pass: found malformed non-array input could throw from verifyChain; addressed with invalid result. Public authorizeRestore remains a client trust-boundary limitation, not a cryptographic authorization mechanism. O(n) audit-history read per append remains a scalability concern; no unverified performance claim.
79
+- Edge-case pass: missing explicit tests for empty/single chains, mixed legacy+hashed history, corrupted JSON, wrong anchors and concurrent writes. Added regression tests; results pending CI.
80
+- Final approval and merge remain withheld until CI and repeat review.
reviews/A03-agent1.md
new
+7
@@ -0,0 +1,7 @@
1
+# A03 Functional QA — sequential pass 1 (not an independent agent)
2
+
3
+Scope: PR #116 and requirements, fresh read of AuditService.js, AuditChain.js, StorageService.js, SettingsController.js and a03-audit-integration.test.mjs.
4
+
5
+Evidence: GitHub Actions run 39374969382, SHA 95f6c976a04a72e2ddaf27f20773994e871e0250, completed success; Linux 257/257 and Windows 257/257.
6
+
7
+Findings: four tamper types and legacy v6 migration covered. Missing explicit concurrency, malformed backup JSON and wrong-anchor rollback coverage. New regression tests added in this change; await CI. No final approval yet.
reviews/A03-agent2.md
new
+7
@@ -0,0 +1,7 @@
1
+# A03 Code quality and security — sequential pass 2 (not an independent agent)
2
+
3
+Fresh-read evidence: src/core/AuditChain.js lines 28-42 canonical serialization and verifyChain; src/core/AuditService.js lines 49-99 append, restore and public authorizeRestore; src/core/StorageService.js lines 380-499 import/export.
4
+
5
+Findings: verifyChain(null) previously threw instead of returning an invalid result; fixed with Array.isArray guard and regression test. SHA-256 known vector tested; eventHash excludes itself and includes prevHash. Head in same backup is NOT independently trusted; a malicious client can rewrite both data and anchor. Public authorizeRestore is callable by an admin client and cannot be treated as a strong security boundary. Audit append reads all company history, O(n) per append; scalability issue remains, requires indexed-head migration outside A03 scope.
6
+
7
+Review method: sequential pass; no independent agent claim. No final approval while security and performance limitations remain.
reviews/A03-agent3.md
new
+7
@@ -0,0 +1,7 @@
1
+# A03 Edge cases and real-user testing — sequential pass 3 (not an independent agent)
2
+
3
+Fresh-read evidence: src/core/AuditChain.js lines 31-65; SettingsController.js lines 165-203; CompanyBackupService.js lines 38-66; tests/a03-audit-chain.test.mjs.
4
+
5
+Findings: no explicit tests for empty/single log, partial hash metadata, mixed legacy prefix and hashed suffix, corrupt JSON, wrong anchor, concurrent writes. Added tests and prepareAuditRows migration/validation helper. Await CI to establish behavior.
6
+
7
+Review method: sequential pass, not an independent subagent.
src/controllers/SettingsController.js
+2
-5
@@ -7,7 +7,7 @@ import { StorageService, STORES } from '../core/StorageService.js';
7
import { Auth } from '../core/Auth.js';
8
import { DataScope } from '../core/DataScope.js';
9
import { restoreCompanyBackup, COMPANY_BACKUP_STORES } from '../core/CompanyBackupService.js';
10
-import { verifyChain } from '../core/AuditChain.js';
10
+import { verifyChain, prepareAuditRows } from '../core/AuditChain.js';
11
12
class SettingsControllerImpl {
13
async getInvoiceSettings() {
@@ -188,10 +188,7 @@ class SettingsControllerImpl {
188
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)) {
192
- const result = verifyChain(history, backup.auditAnchor ?? null);
193
- if (!result.valid) throw new Error('زنجیره ممیزی یا لنگر پشتیبان نامعتبر است');
194
- }
191
+ backup.data.audit_events = prepareAuditRows(history, backup.auditAnchor ?? null);
192
193
const companyId = await DataScope.companyId();
194
// Prevent an accidental merge of one company's books into another.
src/core/AuditChain.js
+16
@@ -29,6 +29,7 @@ export const canonical = value => JSON.stringify(sort(value));
29
function sort(value){if(Array.isArray(value))return value.map(sort);if(value&&typeof value==='object')return Object.fromEntries(Object.keys(value).sort().map(k=>[k,sort(value[k])]));return value;}
30
export const auditHash = row => sha256(canonical(Object.fromEntries(Object.entries(row).filter(([k])=>k!=='eventHash'))));
31
export function verifyChain(rows, anchor = null) {
32
+ if (!Array.isArray(rows)) return { valid: false, index: 0, reason: 'invalid rows' };
33
const ordered=[...rows];
34
let previous=null;
35
const companyId = ordered[0]?.companyId;
@@ -64,3 +65,18 @@ export function normalizeLegacyAudit(row, index, prevHash) {
65
}
66
return copy;
67
}
68
+
69
+/** Normalize unhashed legacy rows in input order, then verify the complete chain. */
70
+export function prepareAuditRows(rows, anchor = null) {
71
+ if (!Array.isArray(rows)) throw new Error('زنجیره ممیزی پشتیبان نامعتبر است');
72
+ let previous = null;
73
+ const normalized = rows.map((row, index) => {
74
+ const legacy = row && typeof row === 'object' && !Array.isArray(row) &&
75
+ row.chainIndex === undefined && row.prevHash === undefined && row.eventHash === undefined;
76
+ const current = legacy ? normalizeLegacyAudit(row, index, previous) : row;
77
+ previous = current?.eventHash;
78
+ return current;
79
+ });
80
+ if (!verifyChain(normalized, anchor).valid) throw new Error('زنجیره ممیزی یا لنگر پشتیبان نامعتبر است');
81
+ return normalized;
82
+}
src/core/CompanyBackupService.js
+3
-6
@@ -3,7 +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';
6
+import { normalizeLegacyAudit, prepareAuditRows } from './AuditChain.js';
7
import { assertJalaliDate, validateAccount, validateFiscalPeriod, validateJournalLines, journalSourceKey } from './AccountingCore.mjs';
8
9
export const COMPANY_BACKUP_STORES = Object.freeze([
@@ -54,15 +54,12 @@ 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('زنجیره ممیزی پشتیبان نامعتبر است');
57
+ const auditRows = prepareAuditRows(data.audit_events || []);
58
const counts = { added: 0, updated: 0, skipped: 0 };
59
// Reads, ownership validation, foreign-key validation and writes share one IndexedDB transaction.
60
return StorageService.transaction([...COMPANY_BACKUP_STORES, 'settings'], async tx => {
61
for (const store of COMPANY_BACKUP_STORES) {
63
- const incomingRows = store === 'audit_events'
64
- ? [...(data[store] || [])].sort((a,b) => (a.chainIndex ?? 0) - (b.chainIndex ?? 0))
65
- : data[store] || [];
62
+ const incomingRows = store === 'audit_events' ? auditRows : data[store] || [];
63
for (const incoming of incomingRows) {
64
const immutable = store === 'audit_events' || store === 'document_corrections';
65
// Historical audit/correction events cannot be reassigned to a new company.
src/core/StorageService.js
+5
-10
@@ -1,5 +1,5 @@
1
import { isAuditServiceRow, AuditService } from './AuditService.js';
2
-import { verifyChain, normalizeLegacyAudit } from './AuditChain.js';
2
+import { verifyChain, normalizeLegacyAudit, prepareAuditRows } from './AuditChain.js';
3
4
// ============================================================
5
// StorageService — IndexedDB wrapper
@@ -446,7 +446,8 @@ class StorageServiceImpl {
446
}
447
}
448
449
- const auditRowsForValidation = json.data.audit_events || [];
449
+ const incomingAudit = json.data.audit_events || [];
450
+ const auditRowsForValidation = prepareAuditRows(incomingAudit);
451
if (json.auditAnchors !== undefined) {
452
if (!json.auditAnchors || typeof json.auditAnchors !== 'object' || Array.isArray(json.auditAnchors))
453
throw new Error('لنگر پشتیبان نامعتبر است');
@@ -459,14 +460,9 @@ class StorageServiceImpl {
460
if (!verifyChain(rows, json.auditAnchors[companyId]).valid)
461
throw new Error('زنجیره ممیزی یا لنگر پشتیبان نامعتبر است');
462
}
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
- }
463
}
464
await this.transaction(STORES, async tx => {
469
- const auditRows = (json.data.audit_events || []).filter(item => !!item);
465
+ const auditRows = auditRowsForValidation;
466
for (const companyId of new Set(auditRows.map(row => row.companyId))) {
467
AuditService.authorizeRestore(tx, {
468
companyId, rows: auditRows.filter(row => row.companyId === companyId)
@@ -480,8 +476,7 @@ class StorageServiceImpl {
476
} else if (APPEND_ONLY_STORES.has(store)) {
477
// Backup replay may re-add history but can never rewrite it.
478
// A conflicting record aborts the WHOLE multi-store restore.
483
- const historical = store === 'audit_events'
484
- ? [...items].sort((a,b) => (a.chainIndex ?? 0) - (b.chainIndex ?? 0)) : items;
479
+ const historical = store === 'audit_events' ? auditRowsForValidation : items;
480
for (const item of historical) {
481
if (!item.id || typeof item.id !== 'string' ||
482
!item.companyId || typeof item.companyId !== 'string') {
tests/a03-audit-chain.test.mjs
+25
-1
@@ -1,6 +1,6 @@
1
import test from 'node:test';
2
import assert from 'node:assert/strict';
3
-import { sha256, auditHash, verifyChain, normalizeLegacyAudit } from '../src/core/AuditChain.js';
3
+import { sha256, auditHash, verifyChain, normalizeLegacyAudit, prepareAuditRows } from '../src/core/AuditChain.js';
4
5
function sample() {
6
let previous = null;
@@ -61,3 +61,27 @@ test('A03: foreign-company event cannot join an otherwise valid hash chain', ()
61
test('A03: invalid anchor metadata is rejected', () => {
62
assert.equal(verifyChain(sample(), { count: -1, headHash: null }).valid, false);
63
});
64
+
65
+test('A03: empty chain and single event are valid with matching anchors', () => {
66
+ assert.equal(verifyChain([], { count: 0, headHash: null }).valid, true);
67
+ const one = sample().slice(0, 1);
68
+ assert.equal(verifyChain(one, { count: 1, headHash: one[0].eventHash }).valid, true);
69
+});
70
+test('A03: malformed rows, partial hash metadata and wrong anchor are rejected', () => {
71
+ assert.equal(verifyChain(null).valid, false);
72
+ assert.equal(verifyChain([null]).valid, false);
73
+ assert.throws(() => prepareAuditRows([null]), /زنجیره ممیزی/);
74
+ assert.throws(() => prepareAuditRows([{ id: 'x', companyId: 'c1', eventHash: 'bad' }]), /زنجیره ممیزی/);
75
+ assert.throws(() => prepareAuditRows(sample(), { count: 3, headHash: '0'.repeat(64) }), /لنگر/);
76
+});
77
+test('A03: mixed legacy prefix and already-hashed suffix are accepted only when linked', () => {
78
+ const old = { id: 'old', companyId: 'company-1', eventType: 'journal_posted' };
79
+ const migrated = normalizeLegacyAudit(old, 0, null);
80
+ const newer = { id: 'new', companyId: 'company-1', chainIndex: 1,
81
+ prevHash: migrated.eventHash, eventType: 'journal_posted' };
82
+ newer.eventHash = auditHash(newer);
83
+ const result = prepareAuditRows([old, newer], { count: 2, headHash: newer.eventHash });
84
+ assert.equal(verifyChain(result).valid, true);
85
+ assert.deepEqual(result[0], migrated);
86
+ assert.throws(() => prepareAuditRows([old, { ...newer, prevHash: null }]), /زنجیره/);
87
+});
tests/a03-audit-integration.test.mjs
+24
@@ -321,3 +321,27 @@ test('A03: legacy v6 backup imports audit rows without new metadata and exports
321
data: { audit_events: [old] } });
322
assert.equal((await StorageService.getAll('audit_events')).length, 1);
323
});
324
+
325
+
326
+test('A03: concurrent audited transactions serialize their chain indexes', async () => {
327
+ await setup();
328
+ await Promise.all(['concurrent-a','concurrent-b'].map(id =>
329
+ StorageService.transaction('audit_events', tx => AuditService.append(tx, {
330
+ companyId: company, eventType: 'journal_posted', sourceType: 'journal',
331
+ sourceId: id, commandKey: id, businessDate
332
+ }))));
333
+ assert.equal((await AuditService.verifyChain({ companyId: company })).valid, true);
334
+ const events = await StorageService.getAllByIndex('audit_events', 'companyId', company);
335
+ assert.equal(new Set(events.map(event => event.chainIndex)).size, events.length);
336
+});
337
+
338
+test('A03: company import rejects corrupted JSON and incorrect hash anchor without mutation', async () => {
339
+ await setup();
340
+ const backup = await SettingsController.exportBackup();
341
+ const count = (await AuditService.list()).length;
342
+ await assert.rejects(SettingsController.importBackup('{corrupt'), /JSON/);
343
+ const wrong = structuredClone(backup);
344
+ wrong.auditAnchor.headHash = '0'.repeat(64);
345
+ await assert.rejects(SettingsController.importBackup(wrong), /لنگر پشتیبان|زنجیره ممیزی/);
346
+ assert.equal((await AuditService.list()).length, count);
347
+});