MC/website/node/postbank-api.mjs

52 lines
5.8 KiB
JavaScript

import {createPostbankPayments} 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 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)&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400);
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 reserved and processed automatically in bounded batches, usually within one minute.'},fees:{state:'planned',message:'Automated transfer fee billing is not active in this foundation batch.'}});
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.until<now)lookups.delete(key);if(lookups.size>10000)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.until<now)transferAttempts.delete(key);const count=transferAttempts.get(user.id)||{until:now+60000,count:0};count.count++;transferAttempts.set(user.id,count);if(count.count>10||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);
};
}