forked from unimatrix/web
Continue consolidated Postbank alpha with private saved beneficiaries
This commit is contained in:
parent
dff64a0207
commit
4eae923d6a
3 changed files with 58 additions and 1 deletions
|
|
@ -1,3 +1,4 @@
|
|||
import {PostbankBeneficiaries} from './postbank-beneficiaries.mjs';
|
||||
import {PostbankAdmin} from './postbank-admin.mjs';
|
||||
import {createPostbankPayments,standardCycle} from './postbank-payments.mjs';
|
||||
import {identity} from './auth.mjs';
|
||||
|
|
@ -8,6 +9,7 @@ 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 beneficiaries=bank?new PostbankBeneficiaries(bank,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=>{
|
||||
|
|
@ -15,6 +17,16 @@ export function createPostbankApi(central,bank,settings={},deps={}){
|
|||
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==='/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/admin/')){
|
||||
try{
|
||||
if(path==='/api/bank/admin/transfers/cancel'){
|
||||
|
|
@ -44,7 +56,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){
|
|||
}
|
||||
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/transfer-options')return reply({accounts:await payments.accounts(user),beneficiaries:(await beneficiaries.list(user)).beneficiaries,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.until<now)lookups.delete(key);if(lookups.size>10000)return reply({message:'Recipient lookup is busy. Try shortly.'},429);
|
||||
|
|
|
|||
27
website/node/postbank-beneficiaries.mjs
Normal file
27
website/node/postbank-beneficiaries.mjs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import {createHash,randomUUID} from 'node:crypto';import {BankError} from './postbank-service.mjs';import {validBankNumber} from './postbank-catalogue.mjs';
|
||||
const uuid=s=>typeof s==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s);
|
||||
export class PostbankBeneficiaries{
|
||||
constructor(db,{clock=Date.now}={}){this.db=db;this.clock=clock;}
|
||||
async list(user){const rows=await this.db.query('SELECT b.id,b.label,b.created_at,a.account_number,a.display_name,a.state,a.type_code,a.system_key,p.state package_state,e.active entity_active,e.display_name holder FROM pb_beneficiaries b JOIN pb_accounts a ON a.id=b.account_id JOIN pb_packages p ON p.id=a.package_id JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id WHERE b.owner_id=? ORDER BY b.label,b.id',[user.id]);return {beneficiaries:rows.map(r=>({id:r.id,label:r.label,number:r.account_number,name:r.display_name,holder:r.holder,active:r.state==='active'&&r.package_state==='active'&&Number(r.entity_active)===1&&r.type_code!=='106'&&!r.system_key,createdAt:Number(r.created_at)}))};}
|
||||
async write(user,input,remove=false,{revalidate=async()=>user}={}){
|
||||
const allowed=remove?['requestId','beneficiaryId']:['requestId','number','label'];if(!input||Object.keys(input).some(k=>!allowed.includes(k))||!uuid(input.requestId))throw new BankError('Complete the beneficiary details.');
|
||||
const number=typeof input.number==='string'?input.number.replace(/\s/g,'').toUpperCase():null;
|
||||
if(remove?!uuid(input.beneficiaryId):!validBankNumber(number)||typeof input.label!=='string'||!input.label.trim()||input.label.trim().length>80||/[\u0000-\u001f]/.test(input.label))throw new BankError(remove?'Select a saved beneficiary.':'Use a verified account number and a name of 1–80 characters.');
|
||||
const fingerprint=createHash('sha256').update(JSON.stringify([user.id,remove?'remove':'save',remove?input.beneficiaryId:number,remove?'':input.label.trim()])).digest('hex');
|
||||
return this.db.transaction(async tx=>{
|
||||
// Serialise address-book writes for this actor, including simultaneous replay.
|
||||
await tx.query('INSERT INTO pb_contact_locks(owner_id) VALUES(?) ON DUPLICATE KEY UPDATE owner_id=VALUES(owner_id)',[user.id]);await tx.first('SELECT owner_id FROM pb_contact_locks WHERE owner_id=? FOR UPDATE',[user.id]);
|
||||
const previous=await tx.first('SELECT actor_id,action,details FROM pb_audit WHERE id=?',[input.requestId]);if(previous){let details;try{details=JSON.parse(previous.details);}catch{}if(previous.actor_id!==user.id||previous.action!=='beneficiary_changed'||details?.fingerprint!==fingerprint)throw new BankError('This request number was already used.',409);return {ok:true,replayed:true};}
|
||||
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed. The beneficiary was not modified.',409);
|
||||
let account=null;
|
||||
if(remove)await tx.query('DELETE FROM pb_beneficiaries WHERE id=? AND owner_id=?',[input.beneficiaryId,user.id]);
|
||||
else{
|
||||
account=await tx.first("SELECT a.id,a.state,a.type_code,a.system_key,p.state package_state,e.active entity_active FROM pb_accounts a JOIN pb_packages p ON p.id=a.package_id JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id WHERE a.account_number=?",[number]);
|
||||
if(!account||account.state!=='active'||account.package_state!=='active'||Number(account.entity_active)!==1||account.type_code==='106'||account.system_key)throw new BankError('This account is not available as a beneficiary.',409);
|
||||
const count=await tx.first('SELECT COUNT(*) n FROM pb_beneficiaries WHERE owner_id=?',[user.id]),existing=await tx.first('SELECT id FROM pb_beneficiaries WHERE owner_id=? AND account_id=?',[user.id,account.id]);if(Number(count.n)>=100&&!existing)throw new BankError('You can save up to 100 beneficiaries. Remove an old entry first.',409);
|
||||
const now=this.clock();await tx.query('INSERT INTO pb_beneficiaries(id,owner_id,account_id,label,created_at,updated_at) VALUES(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE label=VALUES(label),updated_at=VALUES(updated_at)',[randomUUID(),user.id,account.id,input.label.trim(),now,now]);
|
||||
}
|
||||
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,user.id,'beneficiary_changed',null,JSON.stringify({operation:remove?'remove':'save',fingerprint}),this.clock()]);return {ok:true,replayed:false};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -72,3 +72,14 @@ CREATE TABLE IF NOT EXISTS pb_account_options (
|
|||
terms_version VARCHAR(64) NOT NULL, updated_at BIGINT NOT NULL,
|
||||
FOREIGN KEY(account_id) REFERENCES pb_accounts(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS pb_beneficiaries (
|
||||
id CHAR(36) PRIMARY KEY, owner_id CHAR(36) NOT NULL, account_id BIGINT UNSIGNED NOT NULL,
|
||||
label VARCHAR(80) NOT NULL, created_at BIGINT NOT NULL, updated_at BIGINT NOT NULL,
|
||||
UNIQUE KEY owner_beneficiary(owner_id,account_id),
|
||||
FOREIGN KEY(account_id) REFERENCES pb_accounts(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS pb_contact_locks (
|
||||
owner_id CHAR(36) PRIMARY KEY
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff