import {createEntityStateKeys} from './entity-state-keys.mjs'; import {PostbankEstates} from './postbank-estates.mjs'; import {createEconomyHistory} from './jarvis-economy-public.mjs'; import {canInspectAllBankAccounts} from './postbank-recipient-policy.mjs'; import {randomUUID} from 'node:crypto'; import {PostbankPayroll} from './postbank-payroll.mjs'; import {PostbankPayrollCycle} from './postbank-payroll-cycle.mjs'; import {PostbankFinancialPolicies} from './postbank-financial-policy.mjs'; import {PostbankRatePublications} from './postbank-rate-publications.mjs'; import {PostbankClientManagement} from './postbank-client-management.mjs'; import {PostbankCompensation} from './postbank-compensation.mjs'; import {PostbankStandingInstructions} from './postbank-standing-instructions.mjs'; import {CentralScheduler} from './central-scheduler.mjs'; import {canRunScheduler} from './scheduler-authority.mjs'; import {createPostbankTasks} from './postbank-payments.mjs'; import {PostbankTransferSecurity} from './postbank-transfer-security.mjs'; import {PostbankCreditEngine} from './postbank-credit-engine.mjs'; import {PostbankAuthorisations} from './postbank-authorisations.mjs'; import {createReserveLedger} from './postbank-reserve-ledger.mjs'; import {PostbankCredit} from './postbank-credit.mjs'; import {reconcilePostbankClans} from './postbank-registry.mjs'; import {PostbankStatementArchive,statementSettings} from './postbank-statement-archive.mjs'; import {PostbankBeneficiaries} from './postbank-beneficiaries.mjs'; import {PostbankAdmin,RESERVE_OWNER_ID} from './postbank-admin.mjs'; import {createPostbankPayments,standardCycle} from './postbank-payments.mjs'; import {identity} from './auth.mjs'; import {PostbankService} from './postbank-service.mjs'; import {createPostbankAuthority} from './postbank-authority.mjs'; import {POSTBANK_CONTRACTS} from './postbank-contract.mjs'; export function createPostbankApi(central,bank,settings={},deps={}){ const auth=deps.authenticate||(request=>identity(request,central)),authority=deps.authority||createPostbankAuthority(central,{bank}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; const service=bank?new PostbankService(bank,authority,deps):null,payments=createPostbankPayments(central,bank,{...deps,authority}); const credit=bank?new PostbankCredit(bank,authority,{...deps,central}):null; const creditEnabled=settings.POSTBANK_CREDIT_ENABLED==='true',creditEngine=bank?new PostbankCreditEngine(bank,central,authority,deps):null; const scheduler=bank?new CentralScheduler(bank,deps.scheduledTasks||createPostbankTasks(central,bank,settings,deps),deps):null; const payroll=bank?new PostbankPayroll(central,bank,deps):null,financialPolicies=bank?new PostbankFinancialPolicies(bank,central,authority,deps):null; const payrollCycle=bank?new PostbankPayrollCycle(central,bank,deps):null; const transferSecurity=bank?new PostbankTransferSecurity(bank,central,deps):null; const admin=bank?new PostbankAdmin(bank,central,authority,deps):null; const stateKeys=deps.entityStateKeys||(deps.organisationKeys?createEntityStateKeys(central,deps.organisationKeys,{authorizeEvent:async()=>false,authorizeRead:async actor=>!!(await authority(actor)).readAdmin,authorizeEvidence:async actor=>!!(await authority(actor)).manageAdmin}):null); const estates=bank&&stateKeys?new PostbankEstates(bank,central,stateKeys,authority,deps):null; const clients=bank?new PostbankClientManagement(bank,authority,deps):null; const compensation=bank?new PostbankCompensation(bank,authority,deps):null,standing=bank?new PostbankStandingInstructions(bank,authority,deps):null; const beneficiaries=bank?new PostbankBeneficiaries(bank,{...deps,canInspectAll:deps.canInspectAll||(user=>canInspectAllBankAccounts(central,user))}):null; const statements=bank?new PostbankStatementArchive(bank,payments,{...deps,...statementSettings(settings)}):null; const reserveLedger=createReserveLedger(bank,deps); const economyHistory=createEconomyHistory(central,{...deps,bank}); const rates=bank?new PostbankRatePublications(bank,{...deps,python:settings.POSTBANK_PYTHON,logo:settings.POSTBANK_STATEMENT_LOGO}):null; const authorisations=bank?new PostbankAuthorisations(bank,central,authority,deps):null; const lookups=new Map(),transferAttempts=new Map(); const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}); return async request=>{ const url=new URL(request.url),path=url.pathname; if(path==='/api/bank/public/reserve-ledger')return reserveLedger(request); if(path==='/api/bank/public/economy')return economyHistory(request); if(['/api/bank/public/rates','/api/bank/public/rates.pdf'].includes(path))return rates?rates.publicResponse(request):Response.json({message:'The public tariff register is being prepared.'},{status:503,headers:{'Access-Control-Allow-Origin':'*','Cache-Control':'no-store'}}); const user=await auth(request);if(!user)return reply({message:'Sign in to use Imperial Postbank.'},401); if(!service)return reply({message:'The independent bank database is not linked yet.',state:'not_linked'},503); try{await reconcilePostbankClans(central,bank);}catch{return reply({message:'The bank could not verify the current organisation registry. Please retry shortly.'},503);} if(!['/api/bank/recipients','/api/bank/activity','/api/bank/statements','/api/bank/statements/archive','/api/bank/authorisations','/api/bank/authorisations/lookup','/api/bank/credit/details'].includes(path)&&!path.startsWith('/api/bank/admin/')&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400); if(path==='/api/bank/transfer-security'){ try{ if(request.method==='GET')return reply(await transferSecurity.settings(user)); if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413); let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid security settings.'},400);} return reply(await transferSecurity.save(user,body,{revalidate:()=>auth(request)})); }catch(error){return reply({message:error.status?error.message:'Payment security could not be confirmed. Reload before retrying.'},error.status||503);} } if(path==='/api/bank/statements/archive'){ if(request.method!=='GET')return reply({message:'Method not allowed.'},405); if([...url.searchParams.keys()].some(k=>!['accountId','page'].includes(k))||url.searchParams.getAll('accountId').length!==1||url.searchParams.getAll('page').length>1)return reply({message:'Select an archive account.'},400); try{const accountId=url.searchParams.get('accountId'),data=await statements.list(user,{accountId,page:url.searchParams.get('page')||1}),fresh=await auth(request);if(!fresh||fresh.id!==user.id||!(await payments.accounts(fresh)).some(a=>a.id===accountId))return reply({message:'Your account access changed.'},403);return reply(data);}catch(error){return reply({message:error.status?error.message:'The statement archive could not be loaded.'},error.status||503);} } if(path==='/api/bank/statements'){ if(request.method!=='GET')return reply({message:'Method not allowed.'},405); if([...url.searchParams.keys()].some(k=>!['accountId','month'].includes(k))||['accountId','month'].some(k=>url.searchParams.getAll(k).length!==1))return reply({message:'Choose one account and month.'},400); try{const accountId=url.searchParams.get('accountId'),result=await statements.download(user,{accountId,month:url.searchParams.get('month')}),fresh=await auth(request); if(!fresh||fresh.id!==user.id||!(await payments.accounts(fresh)).some(a=>a.id===accountId))return reply({message:'Your account access changed. Reload the workspace.'},403); return new Response(result.pdf,{headers:{'Content-Type':'application/pdf','Content-Disposition':'attachment; filename="'+result.filename+'"','Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}}); }catch(error){return reply({message:error.status?error.message:'Your archived statement could not be downloaded. Please retry shortly.'},error.status||503);} } if(path==='/api/bank/beneficiaries'&&request.method==='GET'){ try{const data=await beneficiaries.list(user),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Reload the workspace.'},403);return reply(data);}catch{return reply({message:'Saved beneficiaries could not be confirmed.'},503);} } if(['/api/bank/beneficiaries/save','/api/bank/beneficiaries/remove'].includes(path)){ if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); const raw=await request.text();if(raw.length>2000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the beneficiary form.'},400);} try{return reply(await beneficiaries.write(user,input,path.endsWith('/remove'),{revalidate:()=>auth(request)}));}catch(error){return reply({message:error.status?error.message:'The beneficiary change was not confirmed. Reload the list before retrying.'},error.status||503);} } if(path.startsWith('/api/bank/credit/')){ try{ if(path==='/api/bank/credit/overview'&&request.method==='GET'){ if(url.search)return reply({message:'Account overrides are not accepted.'},400); const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403); // Rebuild with fresh authority so a revoked organisational scope cannot leak records. return reply({...await credit.overview(fresh),intakeEnabled:creditEnabled}); } if(path==='/api/bank/credit/details'&&request.method==='GET'){ if([...url.searchParams.keys()].some(k=>k!=='loanId')||url.searchParams.getAll('loanId').length!==1)return reply({message:'Choose one credit contract.'},400);const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);return reply(await credit.details(fresh,url.searchParams.get('loanId'))); } if(!['/api/bank/credit/simulate','/api/bank/credit/apply','/api/bank/credit/action'].includes(path))return reply({message:'Credit route not found.'},404); if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); if(url.search)return reply({message:'Account overrides are not accepted.'},400); const raw=await request.text();if(raw.length>7000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the credit form.'},400);} if(!path.endsWith('/simulate')&&!creditEnabled)return reply({message:'Credit application intake is not open yet. No application or payment was made.',state:'not_active'},409); const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403); if(path.endsWith('/apply')){const result=await credit.apply(fresh,input,{revalidate:()=>auth(request)});return reply(result);} if(path.endsWith('/action')){const options={revalidate:()=>auth(request)};if(input.action==='accept')return reply(await creditEngine.accept(fresh,input,options));if(input.action==='withdraw')return reply(await creditEngine.decision(fresh,input,options));if(input.action==='repay')return reply(await creditEngine.requestRepayment(fresh,input,options));return reply({message:'Unknown credit action.'},400);} return reply(await credit.simulate(fresh,input)); }catch(error){return reply({message:error.status?error.message:'The credit operation could not be confirmed.'},error.status||503);} } if(path==='/api/bank/admin/credit/details'){ if(request.method!=='GET')return reply({message:'Method not allowed.'},405);if([...url.searchParams.keys()].some(k=>k!=='loanId')||url.searchParams.getAll('loanId').length!==1)return reply({message:'Choose one credit contract.'},400); try{const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);return reply(await credit.details(fresh,url.searchParams.get('loanId'),true));}catch(error){return reply({message:error.status?error.message:'Credit details could not be confirmed.'},error.status||503);} } if(['/api/bank/admin/credit/decision','/api/bank/admin/credit/recover'].includes(path)){ if(request.method!=='POST')return reply({message:'Method not allowed.'},405);if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);if(url.search)return reply({message:'Account overrides are not accepted.'},400);if(!creditEnabled)return reply({message:'Credit processing is not active.'},409); try{const raw=await request.text();if(raw.length>2500)return reply({message:'Request too large.'},413);const input=JSON.parse(raw),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);if(!(await authority(fresh)).manageAdmin)return reply({message:'Bank management permission is required.'},403);const recovery=path.endsWith('/recover');if(recovery?input.action!=='recover':!['approve','decline'].includes(input.action))return reply({message:'Unknown staff credit action.'},400);const result=await (recovery?creditEngine.requestRepayment(fresh,input,{revalidate:()=>auth(request)}):creditEngine.decision(fresh,input,{revalidate:()=>auth(request)}));if(!recovery)return reply({...result,notice:input.action==='approve'?'Approval recorded in the J.A.R.V.I.S. dossier. The borrower must accept the offer before payment at a four-hour bank window.':'Rejection recorded in the J.A.R.V.I.S. dossier.'});return reply(result);}catch(error){return reply({message:error.status?error.message:'The credit instruction could not be confirmed.'},error.status||503);} } if(['/api/bank/authorisations','/api/bank/authorisations/lookup','/api/bank/authorisations/change','/api/bank/admin/authorisations','/api/bank/admin/authorisations/lookup','/api/bank/admin/authorisations/change'].includes(path)){ const staff=path.startsWith('/api/bank/admin/'); try{ if(request.method==='GET'&&!path.endsWith('/change')){ const lookup=path.endsWith('/lookup'),allowed=lookup?['q','kind']:['q','accountId'];if([...url.searchParams.keys()].some(k=>!allowed.includes(k)||url.searchParams.getAll(k).length!==1))return reply({message:'Invalid authorisation filters.'},400); const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);return reply(lookup?await authorisations.lookup(fresh,url.searchParams.get('q'),url.searchParams.get('kind')||'user',staff):await authorisations.list(fresh,staff,Object.fromEntries(url.searchParams))); } if(request.method!=='POST'||!path.endsWith('/change'))return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);if(url.search)return reply({message:'Account overrides are not accepted.'},400);const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the authorisation form.'},400);}return reply(await authorisations.write(user,input,staff,{revalidate:()=>auth(request)})); }catch(error){return reply({message:error.status?error.message:'The authorisation change could not be confirmed.'},error.status||503);} } if(['/api/bank/admin/payroll','/api/bank/admin/payroll/run'].includes(path)){ try{ if(url.search)return reply({message:'Payroll overrides are not accepted.'},400); const fresh=await auth(request);if(!fresh||fresh.id!==user.id||!await canRunScheduler(central,fresh))return reply({message:'P&O payroll management is reserved for the Big Four.'},403); if(request.method==='GET'&&!path.endsWith('/run')){const result={...await payroll.overview(),cycle:await payrollCycle.preview(),additionalCycle:await payrollCycle.previewAdditional()},current=await auth(request);if(!current||current.id!==user.id||!await canRunScheduler(central,current))return reply({message:'Payroll access changed.'},403);return reply(result);} if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); const raw=await request.text();if(raw.length>4000)return reply({message:'Request too large.'},413); let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the payroll settings.'},400);} if(path.endsWith('/run'))return reply(await payrollCycle.run(fresh,input,{revalidate:()=>auth(request)})); return reply(await financialPolicies.save(fresh,'payroll',input,{revalidate:()=>auth(request)})); }catch(error){return reply({message:error.status?error.message:'Payroll could not be confirmed. Reload before retrying.'},error.status||503);} } if(['/api/bank/admin/scheduler','/api/bank/admin/scheduler/run'].includes(path)){ try{ if(url.search)return reply({message:'Scheduler overrides are not accepted.'},400); const fresh=await auth(request);if(!fresh||fresh.id!==user.id||!await canRunScheduler(central,fresh))return reply({message:'Only the Big Four may run the central scheduler.'},403); if(path.endsWith('/run')){ if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); const raw=await request.text();if(raw.length>300)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Confirm the scheduler run.'},400);} if(!input||input.confirmed!==true||Object.keys(input).some(k=>k!=='confirmed'))return reply({message:'Confirm running due tasks. Future dates cannot be forced.'},400); const auditId=randomUUID();await bank.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[auditId,fresh.id,'central_scheduler_run',null,JSON.stringify({state:'started',recheckAll:true}),Date.now()]);const result=await scheduler.runDue({recheck:true,beforeTask:async()=>{const current=await auth(request);if(!current||current.id!==fresh.id||!await canRunScheduler(central,current))throw Error('Scheduler access changed');}});await bank.query('UPDATE pb_audit SET details=? WHERE id=?',[JSON.stringify({state:'completed',recheckAll:true,...result}),auditId]);return reply(result); } if(request.method!=='GET')return reply({message:'Method not allowed.'},405);return reply({tasks:await scheduler.status()}); }catch{return reply({message:'The scheduler result could not be confirmed. Reload its status before retrying.'},503);} } if(path.startsWith('/api/bank/admin/')){ try{ if(['/api/bank/admin/compensation','/api/bank/admin/compensation/pay','/api/bank/admin/standing-instructions'].includes(path)){ if(url.search)return reply({message:'No account overrides are accepted.'},400); if(request.method==='GET'&&!path.endsWith('/pay')){const result=path.endsWith('/compensation')?await compensation.overview(user):await standing.overview(user),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);await (path.endsWith('/compensation')?compensation.access(fresh):standing.access(fresh));return reply(result);} if(request.method!=='POST'||path.endsWith('/compensation'))return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); const raw=await request.text();if(raw.length>2500)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the bank instruction.'},400);} return reply(await (path.endsWith('/pay')?compensation.pay(user,input,{revalidate:()=>auth(request)}):standing.save(user,input,{revalidate:()=>auth(request)}))); } if(['/api/bank/admin/client','/api/bank/admin/client/package','/api/bank/admin/client/options'].includes(path)){ if(path.endsWith('/client')){ if(request.method!=='GET')return reply({message:'Method not allowed.'},405); if([...url.searchParams.keys()].some(k=>k!=='entityId')||url.searchParams.getAll('entityId').length!==1)return reply({message:'Select one banking client.'},400); const result=await clients.detail(user,url.searchParams.get('entityId')),fresh=await auth(request); if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403); const latest=await clients.scope(fresh,url.searchParams.get('entityId'));result.canManage=latest.canManage;return reply(result); } if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); if(url.search)return reply({message:'Account overrides are not accepted.'},400); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413); let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the client management form.'},400);} return reply(await clients.change(user,input,path.endsWith('/package')?'package':'options',{revalidate:()=>auth(request)})); } if(['/api/bank/admin/estates','/api/bank/admin/estates/freeze','/api/bank/admin/estates/unlock'].includes(path)){ if(!estates)return reply({message:'The ESK estate adapter is unavailable.'},503); if(url.search)return reply({message:'Account overrides are not accepted.'},400); const fresh=await auth(request);if(fresh?.id!==user.id)return reply({message:'Your session changed.'},403); if(path==='/api/bank/admin/estates')return request.method==='GET'?reply(await estates.list(fresh)):reply({message:'Method not allowed.'},405); if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); const raw=await request.text();if(raw.length>2000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the ESK estate form.'},400);} const allowed=path.endsWith('/unlock')?['keyId','revision','requestId','reason','confirmed']:['keyId','reason','confirmed']; if(!input||Array.isArray(input)||Object.keys(input).some(k=>!allowed.includes(k)))return reply({message:'Review the ESK estate fields.'},400); return reply(await (path.endsWith('/unlock')?estates.unlock(fresh,input):estates.freeze(fresh,input))); } if(['/api/bank/admin/transfers/cancel','/api/bank/admin/treasuries/transfer','/api/bank/admin/reserve/grants','/api/bank/admin/taxes/payments'].includes(path)){ if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); if(url.search)return reply({message:'Account overrides are not accepted.'},400);const raw=await request.text();if(raw.length>2000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the cancellation form.'},400);} return reply(await (path.endsWith('/cancel')?admin.cancel(user,input,{revalidate:()=>auth(request)}):path.endsWith('/grants')?admin.issueGrant(user,input,{revalidate:()=>auth(request)}):path.endsWith('/taxes/payments')?admin.taxPayment(user,input,{revalidate:()=>auth(request)}):admin.treasuryTransfer(user,input,{revalidate:()=>auth(request)}))); } if(request.method!=='GET')return reply({message:'Method not allowed.'},405); const permitted=path==='/api/bank/admin/credit'?['loanId']:path.endsWith('/taxes/recipients')?['q']:path.endsWith('/overview')?[]:path.endsWith('/accounts')?['entityId']:path.endsWith('/activity')?['accountId','page']:['q','kind','page'];if([...url.searchParams.keys()].some(k=>!permitted.includes(k)||url.searchParams.getAll(k).length!==1))return reply({message:'Invalid bank administration filter.'},400); const input=Object.fromEntries(url.searchParams);let result; if(path==='/api/bank/admin/overview')result=await admin.overview(user); else if(path==='/api/bank/admin/entities')result=await admin.entities(user,input); else if(path==='/api/bank/admin/corporate')result=await admin.entities(user,input,true); else if(path==='/api/bank/admin/taxes/overview')result=await admin.taxOverview(user); else if(path==='/api/bank/admin/taxes/recipients')result=await admin.taxRecipients(user,input.q); else if(path==='/api/bank/admin/treasuries')result=await admin.treasuries(user,input); else if(path==='/api/bank/admin/credit')result={...await credit.staff(user,input),processing:creditEnabled?'active':'not_active'}; else if(path==='/api/bank/admin/accounts')result=await admin.accounts(user,input.entityId); else if(path==='/api/bank/admin/activity')result=await admin.activity(user,input); else if(path==='/api/bank/admin/audit')result=await admin.audit(user,input); else if(path==='/api/bank/admin/pending')result=await admin.pending(user,input); else return reply({message:'Bank administration route not found.'},404); const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Reload the bank workspace.'},403);const rights=await admin.access(fresh);if(result.permissions){try{result.permissions.canRunScheduler=await canRunScheduler(central,fresh);}catch{result.permissions.canRunScheduler=false;}result.permissions.canManage=rights.manageAdmin;result.permissions.canCompensate=!!(rights.manageAdmin||rights.manageClients);result.permissions.canIssueReserve=fresh.id===RESERVE_OWNER_ID&&!!rights.manageAdmin;}if('canManage' in result)result.canManage=rights.manageAdmin; return reply(result); }catch(error){return reply({message:error.status?error.message:'The bank could not confirm the administrative operation.'},error.status||503);} } if(request.method==='GET'&&['/api/bank/overview','/api/bank/client','/api/bank/accounts'].includes(path)){ try{return reply(await service.overview(user));}catch{return reply({message:'The bank could not confirm the current records. Reload the workspace.'},503);} } if(request.method==='GET'&&['/api/bank/transfer-options','/api/bank/recipients','/api/bank/activity'].includes(path)){ try{ if(path==='/api/bank/transfer-options')return reply({accounts:await payments.accounts(user),beneficiaries:(await beneficiaries.list(user)).beneficiaries,actorId:user.id,security:await transferSecurity.settings(user),standard:{state:'active',processing:'Standard payments are processed in batches every four hours: 00:00, 04:00, 08:00, 12:00, 16:00 and 20:00 Europe/Brussels.',nextAt:standardCycle().nextAt},fees:{state:'planned',message:'Transfer fees are not currently being charged.'}}); if(path==='/api/bank/recipients'){ if([...url.searchParams.keys()].some(k=>!['q','page'].includes(k))||url.searchParams.getAll('q').length!==1||url.searchParams.getAll('page').length>1)return reply({message:'Use the recipient search and page fields.'},400); const now=Date.now();for(const [key,value]of lookups)if(value.until10000)return reply({message:'Recipient lookup is busy. Try shortly.'},429); const value=lookups.get(user.id)||{until:now+60000,count:0};value.count++;lookups.set(user.id,value);if(value.count>20)return reply({message:'Too many recipient searches. Try again in one minute.'},429); const rawPage=url.searchParams.get('page')||'1';if(!/^[1-9]\d{0,3}$/.test(rawPage))return reply({message:'Choose a valid beneficiary page.'},400); const result=await payments.recipientPage(user,url.searchParams.get('q'),{page:Number(rawPage)}),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Search again.'},403);return reply(result); } if([...url.searchParams.keys()].some(k=>!['accountId','page','q','state','from','to'].includes(k))||url.searchParams.getAll('accountId').length>1||['page','q','state','from','to'].some(k=>url.searchParams.getAll(k).length>1))return reply({message:'Invalid statement filter.'},400); const raw=url.searchParams.get('page')||'1';if(!/^[1-9]\d{0,3}$/.test(raw))return reply({message:'Choose a valid statement page.'},400); return reply(await payments.activity(user,{accountId:url.searchParams.get('accountId'),page:Number(raw),...Object.fromEntries(['q','state','from','to'].map(k=>[k,url.searchParams.get(k)||'']))})); }catch(error){return reply({message:error.status?error.message:'The bank could not confirm the requested records.'},error.status||503);} } if(path==='/api/bank/transfers'){ if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); const now=Date.now();for(const [key,value]of transferAttempts)if(value.until10||transferAttempts.size>10000)return reply({message:'Too many payment attempts. Keep the same payment reference and try again in one minute.'},429); const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413);let body;try{body=JSON.parse(raw);}catch{return reply({message:'Complete the transfer form.'},400);} try{return reply(await payments.transfer(user,body,{revalidate:()=>auth(request)}));}catch(error){return reply({message:error.status?error.message:'The transfer result could not be confirmed. Keep the same payment reference when retrying.'},error.status||503);} } if(path==='/api/bank/contracts'&&request.method==='GET')return reply({contracts:{...POSTBANK_CONTRACTS,loans:{...POSTBANK_CONTRACTS.loans,state:creditEnabled?'active':'prepared'}}}); if(['/api/bank/activate','/api/bank/packages/change','/api/bank/accounts/options'].includes(path)){ if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); const text=await request.text();if(text.length>3000)return reply({message:'Request too large.'},413); let body;try{body=JSON.parse(text);}catch{return reply({message:'Select your package again.'},400);} try{return reply(await (path==='/api/bank/activate'?service.activate(user,body,{revalidate:()=>auth(request)}):path==='/api/bank/packages/change'?service.changePackage(user,body,{revalidate:()=>auth(request)}):service.setAccountOptions(user,body,{revalidate:()=>auth(request)})));}catch(error){return reply({message:error.status?error.message:'The package operation was not confirmed. Reload the current records before trying again.',returnTo:'package_selection'},error.status||503);} } return reply({message:'This bank function is not implemented yet. No request was forwarded to the old game bank.',state:'planned'},501); }; }