Treasury & Bank Transfer Management System — سامانه مدیریت خزانهداری و حوالههای بانکی
Close payment TOCTOU window: revalidate duplicate fingerprint, casefold reference and account under SQLite write lock
davoodmehraban89 committed
Oct 23, 2026 at 10:59 UTC
f5eb089f70c8ffb7ea1d012bfe6012241c54446a
1 file changed
+28
-1
src/platform/application/treasury-service.ts
+28
-1
@@ -98,7 +98,34 @@ export class TreasuryService{
98
state:'DRAFT'
99
};
100
this.store.update(d=>{
101
- if(d.payments.some(x=>x.tenantId===payment.tenantId&&(x.id===payment.id||x.clientReference===payment.clientReference))) throw new Error('duplicate payment reference');
101
+ // Recheck all financial preconditions against the snapshot acquired *under*
102
+ // the store write transaction. Preflight reads above can race another
103
+ // desktop/process writer, particularly across multiple SQLite connections.
104
+ const accounts=d.accounts.filter(x=>x.tenantId===payment.tenantId);
105
+ const beneficiaries=d.beneficiaries.filter(x=>x.tenantId===payment.tenantId);
106
+ const prior=d.payments.filter(x=>x.tenantId===payment.tenantId);
107
+ if(!accounts.some(x=>x.id===payment.sourceAccountId))throw new Error('source account not found');
108
+ const currentBeneficiary=beneficiaries.find(x=>x.id===payment.beneficiaryId);
109
+ if(!currentBeneficiary)throw new Error('beneficiary not found');
110
+ const normalizedReference=payment.clientReference.toLowerCase();
111
+ if(prior.some(x=>x.id===payment.id||x.clientReference.trim().toLowerCase()===normalizedReference)){
112
+ throw new Error('duplicate payment reference');
113
+ }
114
+ const currentGuard=evaluatePaymentGuard({
115
+ sourceAccountId:payment.sourceAccountId,
116
+ beneficiaryId:payment.beneficiaryId,
117
+ iban:currentBeneficiary.iban,
118
+ amountIrr:payment.amountIrr,
119
+ clientReference:payment.clientReference,
120
+ paymentDate:payment.paymentDate
121
+ },prior.map(x=>({
122
+ sourceAccountId:x.sourceAccountId,beneficiaryId:x.beneficiaryId,
123
+ iban:beneficiaries.find(b=>b.id===x.beneficiaryId)?.iban??'',
124
+ amountIrr:x.amountIrr,clientReference:x.clientReference,paymentDate:x.paymentDate
125
+ })));
126
+ if(!currentGuard.ok)throw new Error(currentGuard.code==='DUPLICATE_PAYMENT'
127
+ ? 'duplicate payment' : currentGuard.code==='DUPLICATE_REFERENCE'
128
+ ? 'duplicate payment reference' : 'invalid Iranian IBAN');
129
d.payments.push(payment);
130
this.appendAuditTo(d,'PAYMENT_CREATED',payment.id);
131
return d;