MC/website/node/postbank-authorisations.mjs

23 lines
9.9 KiB
JavaScript

import {BankError} from './postbank-service.mjs';import {randomUUID} from 'node:crypto';
const uuid=s=>typeof s==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s);
export const canViewAccount=(context,entityId,accountId)=>context.entities.some(e=>e.id===entityId&&e.canView&&(e.viewAllAccounts||!e.accountRights||e.accountRights[String(accountId)]?.canView));
export const canDebitAccount=(context,entityId,accountId)=>context.entities.some(e=>e.id===entityId&&(e.canPay||e.accountRights?.[String(accountId)]?.canPay));
export async function delegatedAuthority(context,user,bank,now=Date.now()){
if(!bank)return context;const ranks=context.rankKeys||[user.role].filter(Boolean),args=[now,now,user.id,...ranks];
// Actual query joins client identity explicitly; grants never widen to other accounts of that client.
const grants=await bank.query("SELECT m.account_id,m.can_pay,e.id,e.kind,e.external_key,e.display_name FROM pb_account_authorisations m JOIN pb_accounts a ON a.id=m.account_id JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id WHERE m.state='active' AND m.can_view=1 AND m.starts_at<=? AND (m.expires_at IS NULL OR m.expires_at>?) AND e.active=1 AND a.state='active' AND (m.grantee_kind='user' AND m.grantee_key=?"+(ranks.length?" OR m.grantee_kind='rank' AND m.grantee_key IN ("+ranks.map(()=>'?').join(',')+")":"")+")",args);
const entities=context.entities.map(e=>({...e}));for(const g of grants){let e=entities.find(e=>e.id===g.id);if(e?.canPay)continue;if(e&&!e.accountRights){e.viewAllAccounts=!!e.canView;e.accountRights={};}if(!e){e={id:g.id,kind:g.kind,key:g.external_key,name:g.display_name,canView:true,canActivate:false,canPay:false,accountRights:{}};entities.push(e);}e.canView=true;e.accountRights??={};e.accountRights[String(g.account_id)]={canView:true,canPay:!!Number(g.can_pay)};}return {...context,entities};
}
export class PostbankAuthorisations{
constructor(bank,central,authority,{clock=Date.now}={}){this.db=bank;this.central=central;this.authority=authority;this.clock=clock;}
async scope(user,accountId,staff=false,store=this.db){const context=await this.authority(user,{bank:store});if(staff&&!context.readAdmin)throw new BankError('Bank administration permission is required.',403);const account=await store.first('SELECT a.*,e.id entity_id,e.kind,e.display_name holder,e.active entity_active FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id WHERE a.id=?',[accountId]);const entity=account&&context.entities.find(e=>e.id===account.entity_id&&e.canView&&(e.viewAllAccounts||!e.accountRights||e.accountRights[String(account.id)]));if(!account||!staff&&!entity)throw new BankError('Account authorisation access denied.',403);const protectedAccount=!!account.system_key||account.type_code==='106';return {context,account,entity,canManage:!protectedAccount&&(staff?!!context.manageAdmin:!!entity?.canActivate&&account.type_code!=='979')};}
async list(user,staff=false,{accountId=null,q=''}={}){const context=await this.authority(user);if(staff&&!context.readAdmin)throw new BankError('Bank administration permission is required.',403);if(typeof q!=='string'||q.length>80||accountId!==null&&!/^\d{1,12}$/.test(accountId))throw new BankError('Choose valid authorisation filters.');const ids=context.entities.filter(e=>e.canView).map(e=>e.id);if(!staff&&!ids.length)return {accounts:[],grants:[]};const term='%'+q.trim().replace(/[!%_]/g,c=>'!'+c)+'%',args=[...(!staff?ids:[]),term,term,...(accountId?[accountId]:[])];const rows=await this.db.query("SELECT a.id,a.account_number,a.display_name,e.id entity_id,e.display_name holder FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id WHERE a.system_key IS NULL AND a.type_code<>'106'"+(!staff?' AND e.id IN ('+ids.map(()=>'?').join(',')+')':'')+" AND (e.display_name LIKE ? ESCAPE '!' OR a.account_number LIKE ? ESCAPE '!')"+(accountId?' AND a.id=?':'')+' ORDER BY e.display_name,a.id LIMIT 30',args);const accounts=rows.filter(row=>staff||context.entities.find(e=>e.id===row.entity_id)?.viewAllAccounts||!context.entities.find(e=>e.id===row.entity_id)?.accountRights||context.entities.find(e=>e.id===row.entity_id).accountRights[String(row.id)]).map(row=>({id:String(row.id),name:row.display_name,holder:row.holder,number:row.account_number}));if(!accounts.length)return {accounts:[],grants:[]};const selected=accounts.find(a=>a.id===accountId)||accounts[0],scope=await this.scope(user,selected.id,staff);const grants=await this.db.query('SELECT id,grantee_kind,grantee_key,can_pay,starts_at,expires_at,state,version FROM pb_account_authorisations WHERE account_id=? ORDER BY created_at,id',[selected.id]);const visible=scope.canManage||staff?grants:grants.filter(g=>g.grantee_kind==='user'?g.grantee_key===user.id:(context.rankKeys||[user.role]).includes(g.grantee_key));const keys=[...new Set(visible.map(g=>g.grantee_key))],labels=new Map();if(keys.length){const marks=keys.map(()=>'?').join(',');for(const r of (await this.central.prepare('SELECT id,username FROM site_accounts WHERE id IN ('+marks+')').bind(...keys).all()).results||[])labels.set(r.id,r.username);for(const r of (await this.central.prepare('SELECT rank_key,label FROM cp_ranks WHERE rank_key IN ('+marks+')').bind(...keys).all()).results||[])labels.set(r.rank_key,r.label);}return {accounts,selectedAccount:selected.id,canManage:scope.canManage,grants:visible.map(g=>({id:g.id,kind:g.grantee_kind,key:g.grantee_key,label:labels.get(g.grantee_key)||'Former grantee',canPay:!!Number(g.can_pay),startsAt:Number(g.starts_at),expiresAt:g.expires_at===null?null:Number(g.expires_at),state:g.state,version:Number(g.version)}))};}
async lookup(user,q,kind='user',staff=false){const context=await this.authority(user);if(staff&&!context.manageAdmin)throw new BankError('Bank management permission is required.',403);if(!['user','rank'].includes(kind)||kind==='rank'&&!staff||typeof q!=='string'||q.trim().length<3||q.length>60)throw new BankError('Search for a user name using at least three characters.');const term='%'+q.trim().replace(/[!%_]/g,c=>'!'+c)+'%';const result=kind==='user'?await this.central.prepare("SELECT id,username FROM site_accounts WHERE username LIKE ? ESCAPE '!' AND password_hash NOT LIKE '!%' ORDER BY username LIMIT 10").bind(term).all():await this.central.prepare("SELECT rank_key,label FROM cp_ranks WHERE (rank_key LIKE ? ESCAPE '!' OR label LIKE ? ESCAPE '!') AND kind='access' ORDER BY label LIMIT 10").bind(term,term).all();return {matches:(result.results||[]).map(r=>({kind,key:r.id||r.rank_key,label:r.username||r.label}))};}
async write(user,input,staff=false,{revalidate=async()=>user}={}){
if(!input||!uuid(input.requestId)||!/^\d{1,12}$/.test(String(input.accountId))||!['save','revoke'].includes(input.action)||input.confirmed!==true||Object.keys(input).some(k=>!['requestId','accountId','action','kind','key','canPay','expiresAt','version','confirmed'].includes(k)))throw new BankError('Review and confirm the account authorisation.');const scope=await this.scope(user,input.accountId,staff);if(!scope.canManage)throw new BankError('Only the account owner or an authorised bank manager may change these mandates.',403);
const now=this.clock(),expiry=input.expiresAt===null?null:Number(input.expiresAt);if(!['user','rank'].includes(input.kind)||input.kind==='rank'&&!staff||typeof input.key!=='string'||input.key.length>40||typeof input.canPay!=='boolean'||!Number.isInteger(input.version)||input.version<0||expiry!==null&&(!Number.isSafeInteger(expiry)||expiry<=now))throw new BankError('Choose a verified grantee, valid expiry and current mandate version.');
const target=input.kind==='user'?await this.central.prepare("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'").bind(input.key).first():await this.central.prepare("SELECT rank_key FROM cp_ranks WHERE rank_key=? AND kind='access'").bind(input.key).first();if(!target)throw new BankError('The selected grantee is unavailable.');
return this.db.transaction(async tx=>{await tx.first('SELECT id FROM pb_accounts WHERE id=? FOR UPDATE',[scope.account.id]);const prior=await tx.first('SELECT details FROM pb_audit WHERE id=?',[input.requestId]);const fingerprint=JSON.stringify([user.id,input.accountId,input.action,input.kind,input.key,input.canPay,expiry,input.version]);if(prior){const d=JSON.parse(prior.details);if(d.fingerprint!==fingerprint)throw new BankError('This request reference was already used.',409);return {ok:true,replayed:true};}const fresh=await revalidate();if(!fresh||fresh.id!==user.id||(await this.scope(fresh,input.accountId,staff,tx)).canManage!==true)throw new BankError('Your mandate-management authority changed.',403);const old=await tx.first('SELECT * FROM pb_account_authorisations WHERE account_id=? AND grantee_kind=? AND grantee_key=? FOR UPDATE',[scope.account.id,input.kind,input.key]);if(Number(old?.version||0)!==input.version)throw new BankError('The authorisation changed. Refresh before editing.',409);if(input.action==='revoke'){if(!old)throw new BankError('Authorisation not found.',404);await tx.query("UPDATE pb_account_authorisations SET state='revoked',version=version+1,updated_at=? WHERE id=?",[now,old.id]);}else if(old)await tx.query("UPDATE pb_account_authorisations SET can_pay=?,expires_at=?,state='active',version=version+1,updated_at=? WHERE id=?",[input.canPay?1:0,expiry,now,old.id]);else await tx.query('INSERT INTO pb_account_authorisations(id,account_id,grantee_kind,grantee_key,can_view,can_pay,starts_at,expires_at,state,created_by,created_at,updated_at) VALUES(?,?,?,?,1,?,?,?,\'active\',?,?,?)',[randomUUID(),scope.account.id,input.kind,input.key,input.canPay?1:0,now,expiry,user.id,now,now]);await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,user.id,'authorisation_'+input.action,scope.account.entity_id,JSON.stringify({accountId:String(scope.account.id),fingerprint,granteeKind:input.kind,granteeKey:input.key}),now]);return {ok:true,replayed:false};});
}
}