MC/website/tests/postbank-payments.test.mjs
2026-11-27 23:43:05 +00:00

119 lines
22 KiB
JavaScript

import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {PostbankPayments,standardCycle} from '../node/postbank-payments.mjs';import {createPostbankApi} from '../node/postbank-api.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';
async function setup(){
const db=new BankFixture(),users=[0,1,2].map((n)=>({id:randomUUID(),username:'citizen_'+n})),entities=users.map((u)=>({id:randomUUID(),kind:'person',key:u.id,name:u.username}));let revoked=false;
const authority=async u=>({entities:entities.map(e=>({...e,canView:e.key===u.id,canActivate:e.key===u.id,canPay:e.key===u.id&&!revoked})),readAdmin:false,manageAdmin:false});
const packages=new PostbankService(db,authority);for(let i=0;i<users.length;i++)await packages.activate(users[i],{entityId:entities[i].id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});
const records=await db.query('SELECT a.*,c.entity_id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number ORDER BY a.id');const current=i=>records.find(a=>a.entity_id===entities[i].id&&a.type_code==='102'),savings=i=>records.find(a=>a.entity_id===entities[i].id&&a.type_code==='103');
await db.query('UPDATE pb_accounts SET balance_minor=10000 WHERE id=?',[current(0).id]);
const service=new PostbankPayments(db,authority,{resolveUser:async id=>users.find(u=>u.id===id),clock:()=>Date.parse('2026-11-13T20:00:00Z')});
const input=(extra={})=>({requestId:randomUUID(),sourceAccount:String(current(0).id),targetNumber:savings(0).account_number,amount:'10.00',reference:'Fixture transfer',mode:'standard',confirmed:false,...extra});
return {db,users,entities,current,savings,authority,service,input,revoke:()=>{revoked=true;}};
}
test('queued own transfer reserves funds and two workers post exactly once with balanced entries',async()=>{const f=await setup();try{const body=f.input(),r=await f.service.transfer(f.users[0],body);assert.equal(r.state,'queued');assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).reserved_minor,1000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);assert.equal((await f.service.transfer(f.users[0],body)).replayed,true);const results=await Promise.all([f.service.processQueue(),f.service.processQueue()]);assert.equal(results.reduce((n,r)=>n+r.posted,0),1);const a=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id]),b=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.savings(0).id]);assert.equal(a.balance_minor,9000);assert.equal(a.reserved_minor,0);assert.equal(b.balance_minor,1000);assert.equal((await f.db.first('SELECT SUM(amount_minor) total FROM pb_entries')).total,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,2);}finally{f.db.close();}});
test('concurrent instructions cannot spend reserved money or reuse a request for different details',async()=>{const f=await setup();try{const results=await Promise.allSettled(Array.from({length:8},()=>f.service.transfer(f.users[0],f.input({amount:'30.00'}))));assert.equal(results.filter(r=>r.status==='fulfilled').length,3);const a=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id]);assert.equal(a.reserved_minor,9000);assert.equal(a.balance_minor,10000);const one=f.input({amount:'1.00'});await f.service.transfer(f.users[0],one);await assert.rejects(f.service.transfer(f.users[0],{...one,reference:'Changed'}),e=>e.status===409);await f.service.processQueue();assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).balance_minor,900);}finally{f.db.close();}});
test('external payments require confirmation and only actual operators can debit accounts',async()=>{const f=await setup();try{await assert.rejects(f.service.transfer(f.users[0],f.input({targetNumber:f.current(1).account_number})));await assert.rejects(f.service.transfer(f.users[1],f.input({confirmed:true})),e=>e.status===403);const r=await f.service.transfer(f.users[0],f.input({targetNumber:f.current(1).account_number,confirmed:true,mode:'instant'}));assert.equal(r.state,'posted');const account=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(1).id]);assert.equal(account.balance_minor,1000);assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).balance_minor,9000);}finally{f.db.close();}});
test('instant package allowance is atomic, counts unique instructions and never silently falls back',async()=>{const f=await setup();try{for(let i=0;i<5;i++){const body=f.input({mode:'instant',amount:'1.00'});await f.service.transfer(f.users[0],body);assert.equal((await f.service.transfer(f.users[0],body)).replayed,true);}await assert.rejects(f.service.transfer(f.users[0],f.input({mode:'instant'})),e=>e.status===409);assert.equal((await f.db.first('SELECT * FROM pb_instant_usage')).used,5);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,5);}finally{f.db.close();}});
test('revoked queued authority releases the reservation without moving money',async()=>{const f=await setup();try{const body=f.input();await f.service.transfer(f.users[0],body);f.revoke();const r=await f.service.processQueue();assert.equal(r.rejected,1);const a=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id]);assert.equal(a.balance_minor,10000);assert.equal(a.reserved_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);assert.equal((await f.db.first('SELECT * FROM pb_orders')).state,'rejected');}finally{f.db.close();}});
test('failed ledger posting rolls back both balances, instant usage and the instruction',async()=>{const f=await setup();try{f.db.sqlite.exec("CREATE TRIGGER fail_entry BEFORE INSERT ON pb_entries BEGIN SELECT RAISE(ABORT,'injected ledger failure'); END;");await assert.rejects(f.service.transfer(f.users[0],f.input({mode:'instant'})));assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).balance_minor,10000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_instant_usage')).n,0);}finally{f.db.close();}});
test('recipient lookup is literal and statements expose only authorised account records',async()=>{const f=await setup();try{const r=await f.service.recipients(f.users[0],f.current(1).account_number);assert.equal(r.length,1);assert.equal(r[0].number,f.current(1).account_number);assert.equal((await f.service.recipients(f.users[0],'citizen_1')).length,2);assert.deepEqual(await f.service.recipients(f.users[0],'citizen%'),[]);await f.service.transfer(f.users[0],f.input({mode:'instant'}));const statement=await f.service.activity(f.users[0],{accountId:String(f.current(0).id)});assert.equal(statement.records[0].balanceAfter,'90.00');assert.equal(statement.records[0].direction,'debit');await assert.rejects(f.service.activity(f.users[1],{accountId:String(f.current(0).id)}),e=>e.status===403);assert.equal((await f.service.activity(f.users[2])).records.length,0);}finally{f.db.close();}});
test('planned, dormant and system accounts cannot be payment sources or beneficiaries',async()=>{const f=await setup();try{await f.db.query("UPDATE pb_accounts SET system_key='sys_payroll_po' WHERE id=?",[f.savings(0).id]);const opts=await f.service.accounts(f.users[0]);assert.equal(opts.find(a=>a.id===String(f.savings(0).id)).canReceive,false);await assert.rejects(f.service.transfer(f.users[0],f.input()),e=>e.status===409);await f.db.query("UPDATE pb_accounts SET system_key=NULL,state='dormant' WHERE id=?",[f.savings(0).id]);await assert.rejects(f.service.transfer(f.users[0],f.input()),e=>e.status===409);}finally{f.db.close();}});
test('bank transfer routes reject wrong origin, identity overrides and fractional JSON numbers',async()=>{const f=await setup();try{const api=createPostbankApi(null,f.db,{}, {authenticate:async()=>f.users[0],authority:f.authority}),base='https://cp.dunerealms.com';const request=(body,origin=base)=>new Request(base+'/api/bank/transfers',{method:'POST',headers:{Origin:origin,'Content-Type':'application/json'},body:JSON.stringify(body)});assert.equal((await api(request(f.input(),'https://other.invalid'))).status,403);assert.equal((await api(request(f.input({amount:10.1})))).status,400);assert.equal((await api(new Request(base+'/api/bank/activity?actor=other'))).status,400);assert.equal((await api(new Request(base+'/api/bank/transfer-options'))).status,200);}finally{f.db.close();}});
test('one failed queued posting retains its hold without blocking another instruction',async()=>{const f=await setup();try{const bad=f.input(),good=f.input();await f.service.transfer(f.users[0],bad);await f.service.transfer(f.users[0],good);f.db.sqlite.exec("CREATE TRIGGER fail_one_entry BEFORE INSERT ON pb_entries WHEN NEW.order_id='"+bad.requestId+"' BEGIN SELECT RAISE(ABORT,'isolated ledger fault'); END;");const result=await f.service.processQueue();assert.equal(result.failed,1);assert.equal(result.posted,1);const a=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id]);assert.equal(a.balance_minor,9000);assert.equal(a.reserved_minor,1000);assert.equal((await f.db.first('SELECT * FROM pb_orders WHERE id=?',[bad.requestId])).state,'queued');f.db.sqlite.exec('DROP TRIGGER fail_one_entry');assert.equal((await f.service.processQueue()).posted,1);assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).reserved_minor,0);}finally{f.db.close();}});
test('standard settlement uses four-hour Brussels windows and leaves newer instructions reserved',async()=>{assert.deepEqual(standardCycle(Date.parse('2026-11-13T20:30:00Z')),{cutoff:Date.parse('2026-11-13T19:00:00Z'),nextAt:Date.parse('2026-11-13T23:00:00Z')});assert.deepEqual(standardCycle(Date.parse('2026-10-25T02:30:00Z')),{cutoff:Date.parse('2026-10-24T22:00:00Z'),nextAt:Date.parse('2026-10-25T03:00:00Z')});assert.deepEqual(standardCycle(Date.parse('2026-03-29T01:30:00Z')),{cutoff:Date.parse('2026-03-28T23:00:00Z'),nextAt:Date.parse('2026-03-29T02:00:00Z')});const f=await setup();try{await f.service.transfer(f.users[0],f.input());const tooEarly=await f.service.processQueue({cutoff:Date.parse('2026-11-13T19:00:00Z')});assert.equal(tooEarly.attempted,0);assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).reserved_minor,1000);assert.equal((await f.service.processQueue({cutoff:Date.parse('2026-11-13T23:00:00Z')})).posted,1);}finally{f.db.close();}});
test('Instant payment security rejects before any funds or quota move, then posts once with the correct secret',async()=>{
const f=await setup();try{
const {PostbankTransferSecurity}=await import('../node/postbank-transfer-security.mjs'),{scryptSync}=await import('node:crypto');
const password='Website fixture password 123',secret='Payment fixture secret 456',salt='fixture-salt';
const central={prepare(){return {bind(){return this;},async first(){return {password_salt:salt,password_hash:scryptSync(password,salt,64).toString('hex')};}};}};
const security=new PostbankTransferSecurity(f.db,central);f.service.security=security;
await security.save(f.users[0],{websitePassword:password,currentSecret:'',newSecret:secret,threshold:'5.00',enabled:true,version:0,confirmed:true});
const input=f.input({mode:'instant'});
await assert.rejects(f.service.transfer(f.users[0],input),e=>e.status===403);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_instant_usage')).n,0);
const result=await f.service.transfer(f.users[0],{...input,paymentSecret:secret});assert.equal(result.state,'posted');
assert.equal((await f.service.transfer(f.users[0],{...input,paymentSecret:secret})).replayed,true);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
assert(!JSON.stringify(await f.db.query('SELECT * FROM pb_orders')).includes(secret));
}finally{f.db.close();}
});
test('Pro permits repeated instant payments beyond Flow quota and amounts above one million without duplicate posting',async()=>{
const f=await setup();try{
await f.db.query("UPDATE pb_packages SET package_key='pb_pro',monthly_minor=1500");
await f.db.query('UPDATE pb_accounts SET balance_minor=300000000 WHERE id=?',[f.current(0).id]);
for(let i=0;i<8;i++)await f.service.transfer(f.users[0],f.input({mode:'instant',amount:'1.00'}));
const instruction=f.input({mode:'instant',amount:'1000000.01'});
assert.equal((await f.service.transfer(f.users[0],instruction)).state,'posted');
assert.equal((await f.service.transfer(f.users[0],instruction)).replayed,true);
assert.equal((await f.db.first('SELECT used FROM pb_instant_usage')).used,9);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,9);
assert.equal((await f.db.first('SELECT SUM(amount_minor) total FROM pb_entries')).total,0);
const accounts=await f.service.accounts(f.users[0]);assert.equal(accounts.find(a=>a.id===String(f.current(0).id)).unlimitedInstant,true);
await assert.rejects(f.service.transfer(f.users[0],f.input({mode:'instant',amount:'2000000.00'})),/Insufficient available funds/);
}finally{f.db.close();}
});
test('transfer amounts retain exact cents and reject ledger overflow and malformed values',async()=>{
const {transferAmount}=await import('../node/postbank-catalogue.mjs');
assert.equal(transferAmount('92233720368547758.07'),9223372036854775807n);
assert.equal(transferAmount('1000000.01'),100000001n);
for(const value of ['92233720368547758.08','0','-1','1.001','1e7',1000001,'01.00'])assert.throws(()=>transferAmount(value));
});
test('old tariff policies gain Pro without resetting existing customised prices',async()=>{
const {defaultBankRates,readFinancialPolicy}=await import('../node/postbank-financial-policy.mjs');const old=defaultBankRates();delete old.packages.pb_pro;old.packages.pb_flow.monthlyMinor=650;
const bank={first:async()=>({policy_json:JSON.stringify(old),version:4,updated_at:123})};const policy=await readFinancialPolicy(bank,'bank_rates');assert.equal(policy.value.packages.pb_flow.monthlyMinor,650);assert.equal(policy.value.packages.pb_pro.monthlyMinor,1500);assert.equal(policy.version,4);
});
test('Big Four can find and credit a standalone Federal Reserve; normal users cannot and no reserve debit is granted',async()=>{const f=await setup();try{const reserve=f.current(2);await f.db.query("UPDATE pb_accounts SET client_number=NULL,package_id=NULL,system_key='sys_bank_capital_issuer',type_code='979',display_name='Federal Reserve',balance_minor=-10000 WHERE id=?",[reserve.id]);assert.deepEqual(await f.service.recipients(f.users[0],'federal'),[]);f.service.canInspectAll=async u=>u.id===f.users[0].id;const match=await f.service.recipients(f.users[0],'federal');assert.equal(match[0].number,reserve.account_number);const view=(await f.service.accounts(f.users[0])).find(a=>a.id===String(reserve.id));assert.equal(view.canReceive,true);assert.equal(view.canDebit,false);const input=f.input({targetNumber:reserve.account_number,confirmed:true});await f.service.transfer(f.users[0],input);assert.equal((await f.service.processQueue()).posted,1);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[reserve.id])).balance_minor,-9000);assert.equal((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n,0);assert.equal((await f.service.activity(f.users[0],{accountId:String(reserve.id)})).records.length,1);await assert.rejects(f.service.transfer(f.users[0],f.input({sourceAccount:String(reserve.id),targetNumber:f.current(0).account_number,confirmed:true})),e=>e.status===403);}finally{f.db.close();}});
test('P&O stays excluded even for Big Four; privilege revoked before settlement releases the reservation',async()=>{const f=await setup();try{const reserve=f.current(2);await f.db.query("UPDATE pb_accounts SET client_number=NULL,package_id=NULL,system_key='sys_payroll_po',display_name='P&O Payroll' WHERE id=?",[reserve.id]);f.service.canInspectAll=async()=>true;assert.equal((await f.service.accounts(f.users[0])).some(a=>a.id===String(reserve.id)),false);assert.deepEqual(await f.service.recipients(f.users[0],'Payroll'),[]);await assert.rejects(f.service.transfer(f.users[0],f.input({targetNumber:reserve.account_number,confirmed:true})),e=>e.status===409);await f.db.query("UPDATE pb_accounts SET system_key='sys_tax_treasury',display_name='I.D. Taxes' WHERE id=?",[reserve.id]);await f.service.transfer(f.users[0],f.input({targetNumber:reserve.account_number,confirmed:true}));f.service.canInspectAll=async()=>false;assert.equal((await f.service.processQueue()).rejected,1);assert.equal((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.current(0).id])).reserved_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);}finally{f.db.close();}});
test('Big Four system beneficiaries can be saved, and become inactive when the mandate ends',async()=>{const f=await setup();try{const {PostbankBeneficiaries}=await import('../node/postbank-beneficiaries.mjs');const reserve=f.current(2);await f.db.query("UPDATE pb_accounts SET client_number=NULL,package_id=NULL,system_key='sys_bank_capital_issuer',display_name='Federal Reserve' WHERE id=?",[reserve.id]);let allowed=true;const book=new PostbankBeneficiaries(f.db,{canInspectAll:async()=>allowed});await book.write(f.users[0],{requestId:randomUUID(),number:reserve.account_number,label:'Federal Reserve'});assert.equal((await book.list(f.users[0])).beneficiaries[0].active,true);allowed=false;assert.equal((await book.list(f.users[0])).beneficiaries[0].active,false);}finally{f.db.close();}});
test('bank-wide mandate follows protected owner/executive identities, not service or ordinary bank permissions',async()=>{const {canInspectAllBankAccounts,bankRecipientAllowed}=await import('../node/postbank-recipient-policy.mjs');for(const kind of ['owner','executive','service','officer',null]){const central={prepare(){return {bind(){return this;},async first(){return kind?{principal_kind:kind}:null;}};}};assert.equal(await canInspectAllBankAccounts(central,{id:'ordinary-identity'}),['owner','executive'].includes(kind));}assert.equal(bankRecipientAllowed({state:'active',system_key:'sys_payroll_po'},true),false);assert.equal(bankRecipientAllowed({state:'active',system_key:'sys_bank_capital_issuer'},true),true);assert.equal(bankRecipientAllowed({state:'dormant',system_key:'sys_tax_treasury'},true),false);});
test('wire picker access stays scoped while permitted external accounts remain searchable',async()=>{
const f=await setup();try{
f.service.canInspectAll=async()=>true;const accounts=await f.service.accounts(f.users[0]);
assert.equal(accounts.find(a=>a.id===String(f.current(0).id)).canView,true);assert.equal(accounts.find(a=>a.id===String(f.current(1).id)).canView,false);
assert.equal((await f.service.recipientPage(f.users[0],'citizen_1')).recipients.length,2);
const formatted=f.current(1).account_number.match(/.{1,4}/g).join(' ');assert.equal((await f.service.recipientPage(f.users[0],formatted)).recipients[0].number,f.current(1).account_number);
assert((await f.service.recipientPage(f.users[0],formatted.slice(0,9))).recipients.some(a=>a.number===f.current(1).account_number));
}finally{f.db.close();}
});
test('recipient pages include every eligible match beyond the former ten-result cap',async()=>{
const f=await setup();try{
const {bankNumber}=await import('../node/postbank-catalogue.mjs'),sample=f.current(1);
for(let i=0;i<38;i++)await f.db.query("INSERT INTO pb_accounts(client_number,package_id,account_number,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,?,?,'102',?,0,0,'active',0)",[sample.client_number,sample.package_id,bankNumber('102',1000+i),'Search match '+i]);
// Many unavailable matches must not consume a page or hide valid matches.
for(let i=0;i<12;i++)await f.db.query("UPDATE pb_accounts SET state='blocked' WHERE account_number=?",[bankNumber('102',1000+i)]);
const first=await f.service.recipientPage(f.users[0],'Search match'),second=await f.service.recipientPage(f.users[0],'Search match',{page:2});assert.equal(first.recipients.length,25);assert.equal(first.hasMore,true);assert.equal(second.recipients.length,1);assert.equal(second.hasMore,false);assert.equal(new Set([...first.recipients,...second.recipients].map(a=>a.number)).size,26);
for(const account of first.recipients)assert.deepEqual(Object.keys(account).sort(),['holder','name','number']);
await assert.rejects(f.service.recipientPage(f.users[0],'match',{page:0}));assert.deepEqual((await f.service.recipientPage(f.users[0],'Search%')).recipients,[]);
}finally{f.db.close();}
});
test('saved-beneficiary search aliases are private and use current account eligibility',async()=>{
const f=await setup();try{
const {PostbankBeneficiaries}=await import('../node/postbank-beneficiaries.mjs'),book=new PostbankBeneficiaries(f.db);
await book.write(f.users[0],{requestId:randomUUID(),number:f.current(1).account_number,label:'Secret alias example'});
assert.equal((await f.service.recipientPage(f.users[0],'Secret alias')).recipients.length,1);assert.equal((await f.service.recipientPage(f.users[2],'Secret alias')).recipients.length,0);
await f.db.query("UPDATE pb_accounts SET state='blocked' WHERE id=?",[f.current(1).id]);assert.equal((await f.service.recipientPage(f.users[0],'Secret alias')).recipients.length,0);
}finally{f.db.close();}
});
test('recipient API validates paging, and rejects identity changes while loading results',async()=>{
const f=await setup();try{
let changed=false;const api=createPostbankApi(null,f.db,{}, {authenticate:async()=>changed?f.users[1]:f.users[0],authority:f.authority}),base='https://cp.dunerealms.com/api/bank/recipients?q=citizen';
for(const suffix of ['&page=0','&page=1.5','&page=1&page=2','&user=other'])assert.equal((await api(new Request(base+suffix))).status,400);
const response=await api(new Request(base+'&page=1'));assert.equal(response.status,200);assert.equal((await response.json()).page,1);
const authority=async user=>{changed=true;return f.authority(user);};let reads=0;
const changedApi=createPostbankApi(null,f.db,{}, {authenticate:async()=>++reads===1?f.users[0]:f.users[1],authority});assert.equal((await changedApi(new Request(base))).status,403);
}finally{f.db.close();}
});