import {PostbankAdmin} 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),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; const service=bank?new PostbankService(bank,authority,deps):null,payments=createPostbankPayments(central,bank,{...deps,authority}); const admin=bank?new PostbankAdmin(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; 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); if(!['/api/bank/recipients','/api/bank/activity'].includes(path)&&!path.startsWith('/api/bank/admin/')&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400); if(path.startsWith('/api/bank/admin/')){ try{ if(path==='/api/bank/admin/transfers/cancel'){ 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 admin.cancel(user,input,{revalidate:()=>auth(request)})); } if(request.method!=='GET')return reply({message:'Method not allowed.'},405); const permitted=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/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)result.permissions.canManage=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),actorId:user.id,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=>k!=='q')||url.searchParams.getAll('q').length!==1)return reply({message:'Use only the recipient name or account search field.'},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); return reply({recipients:await payments.recipients(user,url.searchParams.get('q'))}); } 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:'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)})); }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}); 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); }; }