Add scoped account authorisations for users and bank staff
This commit is contained in:
parent
0d6a7fc25f
commit
3711cfd45a
13 changed files with 101 additions and 22 deletions
|
|
@ -1,6 +1,6 @@
|
|||
import {NATIVE_SERVICES,nativeServiceAccess} from './cp-v2-native-services.mjs';
|
||||
import {canSubmitDevRequest} from '../dev-request-access.mjs';
|
||||
const legacy={"tax-treasury":"web.bank.staff.manage","bank-dashboard":"web.bank.personal.view","loan-centre":"web.bank.personal.view","loan-administration":"web.bank.staff.manage","electoral-roll":"web.menu.game","imperial-inbox":"web.mail.internal.view","faction-inbox":"web.mail.internal.view","staff-inbox":"web.mail.staff.view","clan-inbox":"web.mail.internal.view","council-motd":"web.menu.game","applications":"web.menu.game","formal-council":"web.menu.game","shared-inbox":"web.mail.internal.view","house-elections":"web.menu.game","imperial-elections":"web.menu.game","imperial-command":"web.menu.game","imperial-water":"web.menu.game","imperial-spice":"web.menu.game","discord-link":"web.menu.security","support-management":"web.tickets.admin","landsraad":"web.menu.game","hosting-control":"web.menu.security","user-management":"web.accounts.view","manual-seals":"web.accounts.assign","company-management":"web.accounts.assign","community-goals":"web.community.manage","marketplace-home":"web.menu.inventory","adventure-home":"web.menu.game","account-home":"web.menu.security","server-kits":"web.ranks.manage","kit-checkout":"web.menu.inventory","rewards-codes":"web.menu.rewards","transactions":"web.menu.inventory","kits-exchange":"web.menu.inventory","redeem-code":"web.menu.rewards","discovery-rewards":"web.quests.view","shop-settings":"web.menu.inventory","exchange-settings":"web.menu.inventory","shop-admin":"web.shop.support","exchange-settings-admin":"web.exchange.manage","user-home":null,"staff-home":null,"exchange":"web.menu.game","clans":"web.menu.game","imperial-atelier":"web.menu.game","personal-bank":"web.bank.personal.view","staff-bank":"web.bank.staff.view","clan-portal":"web.menu.game","clan-shops":"web.menu.game","clan-kits":"web.menu.game","clan-bank":"web.menu.game","clan-settings":"web.menu.game","clan-quests":"web.menu.game","clan-quests-player":"web.menu.game","clan-quests-clan":"web.menu.game","clan-quests-guild":"web.menu.game","quests":"web.quests.view","quests-admin":"web.quests.manage","game":"web.menu.game","webmail":"web.menu.security","git-admin":"web.git.admin","git-control":"web.menu.security","site-profile":"web.menu.security","planetary-inventory":"web.menu.inventory","rewards":"web.menu.rewards","security":"web.menu.security","server-operations":"web.menu.servers","staff":"web.menu.administration","permissions":"web.menu.permissions","game-permissions":"web.ranks.manage","items":"web.menu.items","staff-manual":"web.menu.staffmanual","luckperms":"web.menu.luckperms","tickets":"web.menu.tickets","staff-tickets":"web.tickets.staff","forum-admin":"web.menu.forum","exchange-admin":"web.menu.exchange","website-posts":"web.menu.posts","bans":"web.menu.bans","ban-evidence":"web.menu.bans","kit-publishing":"web.ranks.manage","kit-claims":"web.ranks.manage","company-management-v2":"web.accounts.assign","company-audit":"web.accounts.assign","seal-generator":"web.accounts.assign","bank-audit":"web.bank.staff.view","stock-admin":"web.exchange.manage","stock-surveillance":"web.exchange.manage","git-repositories":"web.menu.security","mail-admin":"web.menu.administration"};
|
||||
const legacy={"account-authorisations":"web.bank.staff.view","tax-treasury":"web.bank.staff.manage","bank-dashboard":"web.bank.personal.view","loan-centre":"web.bank.personal.view","loan-administration":"web.bank.staff.manage","electoral-roll":"web.menu.game","imperial-inbox":"web.mail.internal.view","faction-inbox":"web.mail.internal.view","staff-inbox":"web.mail.staff.view","clan-inbox":"web.mail.internal.view","council-motd":"web.menu.game","applications":"web.menu.game","formal-council":"web.menu.game","shared-inbox":"web.mail.internal.view","house-elections":"web.menu.game","imperial-elections":"web.menu.game","imperial-command":"web.menu.game","imperial-water":"web.menu.game","imperial-spice":"web.menu.game","discord-link":"web.menu.security","support-management":"web.tickets.admin","landsraad":"web.menu.game","hosting-control":"web.menu.security","user-management":"web.accounts.view","manual-seals":"web.accounts.assign","company-management":"web.accounts.assign","community-goals":"web.community.manage","marketplace-home":"web.menu.inventory","adventure-home":"web.menu.game","account-home":"web.menu.security","server-kits":"web.ranks.manage","kit-checkout":"web.menu.inventory","rewards-codes":"web.menu.rewards","transactions":"web.menu.inventory","kits-exchange":"web.menu.inventory","redeem-code":"web.menu.rewards","discovery-rewards":"web.quests.view","shop-settings":"web.menu.inventory","exchange-settings":"web.menu.inventory","shop-admin":"web.shop.support","exchange-settings-admin":"web.exchange.manage","user-home":null,"staff-home":null,"exchange":"web.menu.game","clans":"web.menu.game","imperial-atelier":"web.menu.game","personal-bank":"web.bank.personal.view","staff-bank":"web.bank.staff.view","clan-portal":"web.menu.game","clan-shops":"web.menu.game","clan-kits":"web.menu.game","clan-bank":"web.menu.game","clan-settings":"web.menu.game","clan-quests":"web.menu.game","clan-quests-player":"web.menu.game","clan-quests-clan":"web.menu.game","clan-quests-guild":"web.menu.game","quests":"web.quests.view","quests-admin":"web.quests.manage","game":"web.menu.game","webmail":"web.menu.security","git-admin":"web.git.admin","git-control":"web.menu.security","site-profile":"web.menu.security","planetary-inventory":"web.menu.inventory","rewards":"web.menu.rewards","security":"web.menu.security","server-operations":"web.menu.servers","staff":"web.menu.administration","permissions":"web.menu.permissions","game-permissions":"web.ranks.manage","items":"web.menu.items","staff-manual":"web.menu.staffmanual","luckperms":"web.menu.luckperms","tickets":"web.menu.tickets","staff-tickets":"web.tickets.staff","forum-admin":"web.menu.forum","exchange-admin":"web.menu.exchange","website-posts":"web.menu.posts","bans":"web.menu.bans","ban-evidence":"web.menu.bans","kit-publishing":"web.ranks.manage","kit-claims":"web.ranks.manage","company-management-v2":"web.accounts.assign","company-audit":"web.accounts.assign","seal-generator":"web.accounts.assign","bank-audit":"web.bank.staff.view","stock-admin":"web.exchange.manage","stock-surveillance":"web.exchange.manage","git-repositories":"web.menu.security","mail-admin":"web.menu.administration"};
|
||||
export function visibleCPItem(user,workspace,item){
|
||||
if(workspace==='bank'&&item.id==='federal-reserve')return true;
|
||||
if(!user||!Array.isArray(user.permissions))return false;
|
||||
|
|
|
|||
13
website/control-panel/public/cp-v2/cp-v2-authorisations.mjs
Normal file
13
website/control-panel/public/cp-v2/cp-v2-authorisations.mjs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import {element as el,createCPV2ContentPage} from './cp-v2-page-template.mjs';import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
const number=n=>n?.match(/.{1,4}/g)?.join(' ')||'—';function field(name,input){const label=el('label',undefined,'pb-transfer-field');label.append(el('span',name),input);return label;}function option(select,label,value){const o=el('option',label);o.value=value;select.append(o);}
|
||||
export function mountAuthorisations(host,{staff=false,fetcher=fetch}={}){
|
||||
const abort=new AbortController(),api=createUserAPI(fetcher,abort.signal),base=staff?'/api/bank/admin/authorisations':'/api/bank/authorisations';let active=true,busy=false,accountId=null,q='',choices=[];
|
||||
const frame=createCPV2ContentPage({host,title:staff?'Account Authorisations':'My Authorisations',description:'Review who can view or pay from an account. Every authorisation is limited to its named account.',reload:()=>void load()});
|
||||
async function load(){if(busy)return;busy=true;frame.status.hidden=false;frame.status.textContent='Loading current account authorisations…';try{const data=await api.request(base+'?'+new URLSearchParams({...q?{q}:{},...accountId?{accountId}:{}}));if(!active)return;if(!accountId||!choices.length)choices=data.accounts;accountId=data.selectedAccount||null;frame.content.replaceChildren();const search=el('input');search.type='search';search.value=q;search.maxLength=80;const filter=el('form',undefined,'pb-admin-tools'),apply=el('button','Find accounts');apply.type='submit';filter.append(field('Account holder or account number',search),apply);filter.onsubmit=e=>{e.preventDefault();q=search.value;accountId=null;void load();};frame.content.append(filter);if(!data.accounts.length){frame.content.append(el('p','No accessible account matches this search.'));frame.status.hidden=true;return;}const select=el('select');for(const a of choices)option(select,a.holder+' · '+a.name+' · '+number(a.number),a.id);select.value=accountId;select.onchange=()=>{accountId=select.value;void load();};frame.content.append(field('Account',select));const wrap=el('div',undefined,'pb-ledger-scroll'),table=el('table',undefined,'pb-ledger'),head=el('thead'),tr=el('tr'),body=el('tbody');for(const h of ['Grantee','Type','Access','Expires','State','Action'])tr.append(el('th',h));head.append(tr);table.append(head,body);wrap.append(table);
|
||||
for(const grant of data.grants){const row=el('tr'),action=el('td');for(const text of [grant.label,grant.kind==='rank'?'Group':'User',grant.canPay?'View & pay':'View only',grant.expiresAt?new Date(grant.expiresAt).toLocaleString('en-GB'):'No end date',grant.state])row.append(el('td',text));if(data.canManage&&grant.state==='active'){const panel=el('details');panel.append(el('summary','Revoke authorisation'));const consent=el('input');consent.type='checkbox';const label=el('label',undefined,'pb-consent');label.append(consent,el('span','I confirm removal of this authorisation.'));const button=el('button','Revoke');button.type='button';button.disabled=true;consent.onchange=()=>{button.disabled=!consent.checked;};let requestId=crypto.randomUUID();button.onclick=()=>void write({requestId,accountId,action:'revoke',kind:grant.kind,key:grant.key,canPay:grant.canPay,expiresAt:null,version:grant.version,confirmed:true},button);panel.append(label,button);action.append(panel);}row.append(action);body.append(row);}frame.content.append(wrap);if(!data.grants.length)frame.content.append(el('p','No additional authorisations are registered for this account.'));if(data.canManage)addForm(data.grants);else frame.content.append(el('p','You can review your authorisation. Managing other grantees requires the account owner or bank management.','pb-muted'));frame.status.hidden=true;frame.diagnostics.textContent='Central API · Per-account scope · Revocation and expiry rechecked before settlement';}catch(error){if(active)frame.status.textContent=error.message;}finally{busy=false;}}
|
||||
function addForm(existing){const form=el('form',undefined,'pb-transfer-form'),kind=el('select'),search=el('input'),find=el('button','Find grantee'),grantee=el('select'),pay=el('input'),expiry=el('input'),consent=el('input'),send=el('button','Save authorisation'),status=el('p');option(kind,'User','user');if(staff)option(kind,'Group','rank');search.type='search';search.minLength=3;search.maxLength=60;find.type='button';grantee.disabled=true;grantee.required=true;pay.type=consent.type='checkbox';consent.required=true;expiry.type='datetime-local';send.type='submit';send.disabled=true;const permission=el('label',undefined,'pb-consent');permission.append(pay,el('span','Allow payments from this account'));const confirmation=el('label',undefined,'pb-consent');confirmation.append(consent,el('span','I confirm the selected grantee and account access.'));form.append(el('h3','Add or update an authorisation'),field('Grantee type',kind),field('Search name',search),find,field('Verified grantee',grantee),field('Expires · optional',expiry),permission,confirmation,send,status);frame.content.append(form);let matches=[],pending=null,sequence=0;const clear=()=>{sequence++;matches=[];grantee.replaceChildren();grantee.disabled=send.disabled=true;};search.oninput=kind.onchange=clear;find.onclick=async()=>{if(busy||pending||search.value.trim().length<3)return;const own=++sequence;busy=true;find.disabled=true;try{const result=await api.request(base+'/lookup?'+new URLSearchParams({q:search.value,kind:kind.value}));if(!active||own!==sequence)return;matches=result.matches;grantee.replaceChildren();for(const m of matches)option(grantee,m.label,m.key);grantee.disabled=send.disabled=!matches.length;status.textContent=matches.length?'Choose a grantee and review the rights.':'No matching grantee.';}catch(e){if(active)status.textContent=e.message;}finally{busy=false;if(active)find.disabled=false;}};
|
||||
form.onsubmit=async e=>{e.preventDefault();if(busy||!form.reportValidity())return;if(!pending){const m=matches.find(m=>m.key===grantee.value);if(!m)return;const old=existing.find(g=>g.kind===m.kind&&g.key===m.key);pending={requestId:crypto.randomUUID(),accountId,action:'save',kind:m.kind,key:m.key,canPay:pay.checked,expiresAt:expiry.value?new Date(expiry.value).getTime():null,version:old?.version||0,confirmed:true};}for(const c of [kind,search,find,grantee,pay,expiry,consent])c.disabled=true;const result=await write(pending,send);if(result==='rejected'){pending=null;for(const c of [kind,search,find,grantee,pay,expiry,consent])c.disabled=false;}};
|
||||
}
|
||||
async function write(payload,button){if(busy)return;busy=true;button.disabled=true;try{await api.request(base+'/change',payload);busy=false;await load();return 'saved';}catch(e){if(active){frame.status.hidden=false;frame.status.textContent=e.uncertain?'Result not confirmed. Retry the same instruction to check it safely.':e.message;}return e.uncertain?'uncertain':'rejected';}finally{busy=false;if(active)button.disabled=false;}}
|
||||
void load();return()=>{active=false;abort.abort();frame.root.remove();};
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import {mountAuthorisations} from './cp-v2-authorisations.mjs';
|
||||
import {mountReserveLedger} from './cp-v2-reserve-ledger.mjs';
|
||||
import {mountPostbankCredit} from './cp-v2-postbank-credit.mjs';
|
||||
import {mountPostbankBeneficiaries} from './cp-v2-postbank-beneficiaries.mjs';
|
||||
|
|
@ -8,6 +9,7 @@ import {createCPV2ContentPage,element as el} from './cp-v2-page-template.mjs';
|
|||
export const BANK_IMPORTS=Object.freeze({'bank-information':{kind:'foundation'},'bank-overview':{kind:'foundation'},'personal-bank':{kind:'foundation'},'bank-transfers':{kind:'payments'},'bank-statements':{kind:'payments'},'bank-history':{kind:'payments'},'staff-bank':{kind:'admin'}});
|
||||
const titles={'bank-transfers':'Transfers','bank-statements':'Transactions','bank-history':'Transactions','bank-beneficiaries':'Beneficiaries','loan-centre':'Loan Applications','bank-loans':'My Loans','loan-administration':'Loan Management','bank-dashboard':'Operations Dashboard','staff-bank':'Treasury Accounts','company-finance':'Business Accounts','bank-audit':'Audit Log'};
|
||||
export function mountBankPage(host,id,{fetcher=fetch,accountId=null}={}){
|
||||
if(id==='bank-authorisations')return mountAuthorisations(host,{fetcher});
|
||||
if(id==='federal-reserve')return mountReserveLedger(host,{fetcher});
|
||||
if(['loan-centre','bank-loans','loan-administration'].includes(id))return mountPostbankCredit(host,id,{fetcher});
|
||||
if(id==='bank-beneficiaries')return mountPostbankBeneficiaries(host,{fetcher});
|
||||
|
|
|
|||
|
|
@ -89,13 +89,13 @@ export function mountPostbankFoundation(host,page,{fetcher=fetch}={}){
|
|||
const card=el('article',undefined,'pb-account pb-account-'+a.type);card.tabIndex=0;card.setAttribute('role','link');card.setAttribute('aria-label','View transactions for '+a.name);const openTransactions=()=>{location.hash='bank/bank-statements/'+a.id;};card.onclick=event=>{if(event.target.closest('details,a,button,input,select,textarea,label'))return;openTransactions();};card.onkeydown=event=>{if(event.target!==card||!['Enter',' '].includes(event.key))return;event.preventDefault();openTransactions();};card.append(el('strong',accountNames[a.type]||'Bank account'),el('code',number(a.number)));
|
||||
if(['planned','dormant','closed'].includes(a.state))card.append(el('span',a.state==='planned'?'Planned service · Not available for payments':a.state==='dormant'?'Dormant · Preserved after package change':'Closed','pb-muted'));
|
||||
else card.append(el('strong',a.balance+' DM','pb-balance'),el('small','Available: '+a.available+' DM'));
|
||||
const detail=el('details'),summary=el('summary','+ Account details');detail.append(summary);datum(detail,'Account holder',entity.name);datum(detail,'Client number',entity.clientNumber);datum(detail,'Banking entity',entity.kind);datum(detail,'Access',entity.canPay?'Account operator':'Read only');if(entity.expiresAt)datum(detail,'Authority expires',new Date(entity.expiresAt).toLocaleString('en-GB'));datum(detail,'Account state',a.state);datum(detail,'Package',entity.packages.find(p=>p.id===a.packageId)?.name||'Not available');card.append(detail);if(page==='personal-bank'&&a.options?.balanceGuardEligible)card.append(accountOptions(entity,a));rows.append(card);
|
||||
const detail=el('details'),summary=el('summary','+ Account details');detail.append(summary);datum(detail,'Account holder',entity.name);datum(detail,'Client number',entity.clientNumber);datum(detail,'Banking entity',entity.kind);datum(detail,'Access',(a.canPay??entity.canPay)?'Account operator':'Read only');if(entity.expiresAt)datum(detail,'Authority expires',new Date(entity.expiresAt).toLocaleString('en-GB'));datum(detail,'Account state',a.state);datum(detail,'Package',entity.packages.find(p=>p.id===a.packageId)?.name||'Not available');card.append(detail);if(page==='personal-bank'&&a.options?.balanceGuardEligible)card.append(accountOptions(entity,a));rows.append(card);
|
||||
}
|
||||
section.append(rows);frame.content.append(section);
|
||||
}
|
||||
const server=box('Game server account');server.append(el('span','Not linked','pb-badge'),el('p',view.server.message),el('p','Required API: POST /api/bank/integrations/game/payments','pb-muted'),el('p','No request sent. The website bank does not read or write game balances.','pb-muted'));frame.content.append(server);
|
||||
|
||||
if(view.billing?.state==='planned'){const billing=box('Monthly billing');billing.append(el('p',view.billing.message),el('p','Automated fee collection is a separate function; no monthly charge has been executed by this page.','pb-muted'));frame.content.append(billing);}
|
||||
if(page==='personal-bank'){const access=box('Authorisations and additional products');access.append(el('p','Planned · Mandate editing, delegates, additional account opening and trading are not active in this foundation batch.'),el('p','Required API: POST /api/bank/authorisations · No request sent.','pb-muted'));frame.content.append(access);}
|
||||
if(page==='personal-bank'){const link=el('a','Manage account authorisations →');link.href='#bank/bank-authorisations';frame.content.append(link);}
|
||||
}
|
||||
void load();return()=>{active=false;controller.abort();frame.root.remove();};
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -244,7 +244,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});}
|
||||
if(path==='/federal-reserve'||path==='/federal-reserve/')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/reserve-ledger.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}});
|
||||
// V2 shell is public; private data and writes retain their authenticated API gates.
|
||||
if(['/','/index.html','/v2','/v2/','/v2/cp-v2-politics-pages.mjs','/v2/cp-v2-auth.mjs','/v2/cp-v2-access.mjs','/v2/citizens-registry.mjs','/v2/cp-v2-page-template.mjs','/v2/imperial-permissions.mjs','/v2/honours-seals.mjs','/v2/cp-v2-planned-pages.mjs','/v2/cp-v2-choam-pages.mjs','/v2/cp-v2-bureau-pages.mjs','/v2/cp-v2-service-pages.mjs','/v2/cp-v2-newsroom.mjs','/v2/cp-v2-moderation.mjs','/v2/cp-v2-native-services.mjs','/v2/cp-v2-exchange-authority.mjs','/v2/cp-v2-crysknife.mjs','/v2/cp-v2-post-menu.mjs','/v2/cp-v2-postbank-foundation.mjs','/v2/cp-v2-postbank-payments.mjs','/v2/cp-v2-postbank-admin.mjs','/v2/cp-v2-tax-treasury.mjs','/v2/cp-v2-reserve-ledger.mjs','/v2/cp-v2-reserve-entry.mjs','/v2/cp-v2-postbank-credit.mjs','/v2/cp-v2-postbank-beneficiaries.mjs','/v2/cp-v2-postbank-statement-archive.mjs','/v2/cp-v2-bank-pages.mjs','/v2/cp-v2-post-pages.mjs','/v2/cp-v2-rewards.mjs','/v2/cp-v2-user-commerce.mjs','/v2/cp-v2-user-pages.mjs','/v2/cp-v2-user-api.mjs','/v2/cp-v2-security.mjs','/v2/cp-v2-passport.mjs','/v2/cp-v2-personal-records.mjs','/v2/cp-v2-design-pages.mjs','/v2/cp-v2-design-catalog.mjs','/v2/cp-v2-forge-pages.mjs','/v2/cp-v2-hosting.mjs','/v2/cp-v2-community-treasury.mjs','/v2/cp-v2-item-register.mjs','/v2/cp-v2-kit-directorate.mjs','/v2/cp-v2-campaigns.mjs','/v2/cp-v2-imperial-revenue.mjs','/v2/cp-v2-read-register.mjs','/v2/cp-v2-bureau-data.mjs','/v2/cp-v2-company-actions.mjs','/v2/v2.css','/v2/v2.js'].includes(path)){
|
||||
if(['/','/index.html','/v2','/v2/','/v2/cp-v2-politics-pages.mjs','/v2/cp-v2-auth.mjs','/v2/cp-v2-access.mjs','/v2/citizens-registry.mjs','/v2/cp-v2-page-template.mjs','/v2/imperial-permissions.mjs','/v2/honours-seals.mjs','/v2/cp-v2-planned-pages.mjs','/v2/cp-v2-choam-pages.mjs','/v2/cp-v2-bureau-pages.mjs','/v2/cp-v2-service-pages.mjs','/v2/cp-v2-newsroom.mjs','/v2/cp-v2-moderation.mjs','/v2/cp-v2-native-services.mjs','/v2/cp-v2-exchange-authority.mjs','/v2/cp-v2-crysknife.mjs','/v2/cp-v2-post-menu.mjs','/v2/cp-v2-postbank-foundation.mjs','/v2/cp-v2-postbank-payments.mjs','/v2/cp-v2-postbank-admin.mjs','/v2/cp-v2-authorisations.mjs','/v2/cp-v2-tax-treasury.mjs','/v2/cp-v2-reserve-ledger.mjs','/v2/cp-v2-reserve-entry.mjs','/v2/cp-v2-postbank-credit.mjs','/v2/cp-v2-postbank-beneficiaries.mjs','/v2/cp-v2-postbank-statement-archive.mjs','/v2/cp-v2-bank-pages.mjs','/v2/cp-v2-post-pages.mjs','/v2/cp-v2-rewards.mjs','/v2/cp-v2-user-commerce.mjs','/v2/cp-v2-user-pages.mjs','/v2/cp-v2-user-api.mjs','/v2/cp-v2-security.mjs','/v2/cp-v2-passport.mjs','/v2/cp-v2-personal-records.mjs','/v2/cp-v2-design-pages.mjs','/v2/cp-v2-design-catalog.mjs','/v2/cp-v2-forge-pages.mjs','/v2/cp-v2-hosting.mjs','/v2/cp-v2-community-treasury.mjs','/v2/cp-v2-item-register.mjs','/v2/cp-v2-kit-directorate.mjs','/v2/cp-v2-campaigns.mjs','/v2/cp-v2-imperial-revenue.mjs','/v2/cp-v2-read-register.mjs','/v2/cp-v2-bureau-data.mjs','/v2/cp-v2-company-actions.mjs','/v2/v2.css','/v2/v2.js'].includes(path)){
|
||||
const moduleFile=path.endsWith('.mjs')||path.endsWith('.js');
|
||||
const file=path.endsWith('.mjs')?path.slice('/v2/'.length):path.endsWith('.js')?'v2.js':path.endsWith('.css')?'v2.css':'index.html';
|
||||
return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+file,import.meta.url)),{headers:{'Content-Type':moduleFile?'text/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
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';
|
||||
|
|
@ -10,13 +11,14 @@ 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 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):null;
|
||||
const admin=bank?new PostbankAdmin(bank,central,authority,deps):null;
|
||||
const beneficiaries=bank?new PostbankBeneficiaries(bank,deps):null;
|
||||
const statements=bank?new PostbankStatementArchive(bank,payments,{...deps,...statementSettings(settings)}):null;
|
||||
const reserveLedger=createReserveLedger(bank,deps);
|
||||
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=>{
|
||||
|
|
@ -25,7 +27,7 @@ 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);
|
||||
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'].includes(path)&&!path.startsWith('/api/bank/admin/')&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400);
|
||||
if(!['/api/bank/recipients','/api/bank/activity','/api/bank/statements','/api/bank/statements/archive','/api/bank/authorisations','/api/bank/authorisations/lookup'].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/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);
|
||||
|
|
@ -67,6 +69,17 @@ export function createPostbankApi(central,bank,settings={},deps={}){
|
|||
const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);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(['/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(path.startsWith('/api/bank/admin/')){
|
||||
try{
|
||||
if(['/api/bank/admin/transfers/cancel','/api/bank/admin/treasuries/transfer','/api/bank/admin/reserve/grants','/api/bank/admin/taxes/payments'].includes(path)){
|
||||
|
|
|
|||
23
website/node/postbank-authorisations.mjs
Normal file
23
website/node/postbank-authorisations.mjs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
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};});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import {delegatedAuthority} from './postbank-authorisations.mjs';
|
||||
import {createHash} from 'node:crypto';
|
||||
import {accessFor} from './permissions.mjs';
|
||||
const STAFF_ROLES=new Set(['owners','web_net_admin','network_admin','web_network','web_support','web_net_owner','corestaff','web_admin','web_dev']);
|
||||
|
|
@ -6,9 +7,9 @@ export function entityId(kind,key){const h=createHash('sha256').update('postbank
|
|||
const can= (rights,key)=>rights.nodes.includes(key);
|
||||
// Central identity/organisation records are read-only sources. No gameplay bank,
|
||||
// bearer gateway, old balance or historical bank transaction is read here.
|
||||
export function createPostbankAuthority(central,{clock=Date.now,rightsFor=accessFor}={}){
|
||||
export function createPostbankAuthority(central,{clock=Date.now,rightsFor=accessFor,bank=null}={}){
|
||||
const rows=async(sql,args=[])=>(await central.prepare(sql).bind(...args).all()).results||[];
|
||||
return async user=>{
|
||||
return async (user,{bank:store=bank}={})=>{
|
||||
const rights=await rightsFor(central,user),readAdmin=can(rights,'web.bank.staff.view'),manageAdmin=can(rights,'web.bank.staff.manage'),now=clock();
|
||||
const sources=[],operatorRoles=new Set(['owner','officer','admin','leader']);
|
||||
// Administrative inspection belongs to separate admin routes, never personal activation cards.
|
||||
|
|
@ -40,6 +41,6 @@ export function createPostbankAuthority(central,{clock=Date.now,rightsFor=access
|
|||
const staff=await rows("SELECT a.id,a.username,a.role FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.password_hash NOT LIKE '!%' AND COALESCE(p.game_link_exempt,0)=0");
|
||||
const eligibleStaff=staff.filter(a=>STAFF_ROLES.has(a.role));
|
||||
for(const actor of eligibleStaff)add('staff',actor.id,actor.username+' · Staff',[actor.id]);
|
||||
return {entities:sources,readAdmin,manageAdmin,eligibleStaff:eligibleStaff.map(a=>({id:a.id,username:a.username})),server:{state:'not_linked',name:'Game server account'}};
|
||||
return delegatedAuthority({entities:sources,readAdmin,manageAdmin,rankKeys:rights.ranks||[user.role],eligibleStaff:eligibleStaff.map(a=>({id:a.id,username:a.username})),server:{state:'not_linked',name:'Game server account'}},user,store,now);
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {canViewAccount,canDebitAccount} from './postbank-authorisations.mjs';
|
||||
import {reconcilePostbankClans} from './postbank-registry.mjs';
|
||||
import {PostbankStatementArchive,statementSettings} from './postbank-statement-archive.mjs';
|
||||
import {createHash,randomUUID} from 'node:crypto';
|
||||
|
|
@ -14,7 +15,7 @@ export class PostbankPayments{
|
|||
async accounts(user){
|
||||
const context=await this.authority(user),entities=context.entities.filter(e=>e.canView);if(!entities.length)return [];
|
||||
const rows=await this.db.query(accountSQL+' WHERE c.entity_id IN ('+entities.map(()=>'?').join(',')+') ORDER BY a.id',entities.map(e=>e.id));
|
||||
return rows.map(a=>({id:String(a.id),number:a.account_number,name:a.display_name,holder:a.holder,entityId:a.entity_id,kind:a.kind,isPersonalOwner:a.kind==='person'&&a.external_key===user.id,state:a.state,type:a.type_code,canReceive:payable(a),available:money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),canDebit:payable(a)&&!!entities.find(e=>e.id===a.entity_id)?.canPay,instantQuota:PACKAGES.find(p=>p.key===a.package_key)?.instant||0}));
|
||||
return rows.filter(a=>canViewAccount(context,a.entity_id,a.id)).map(a=>({id:String(a.id),number:a.account_number,name:a.display_name,holder:a.holder,entityId:a.entity_id,kind:a.kind,isPersonalOwner:a.kind==='person'&&a.external_key===user.id,state:a.state,type:a.type_code,canReceive:payable(a),available:money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),canDebit:payable(a)&&canDebitAccount(context,a.entity_id,a.id),instantQuota:PACKAGES.find(p=>p.key===a.package_key)?.instant||0}));
|
||||
}
|
||||
async recipients(user,query){
|
||||
if(typeof query!=='string'||query.trim().length<3||query.trim().length>80)throw new BankError('Enter at least three characters of a name, or a full account number.');
|
||||
|
|
@ -35,7 +36,7 @@ export class PostbankPayments{
|
|||
let amount;try{amount=minorAmount(input.amount);}catch(e){throw new BankError(e.message);}
|
||||
const targetNumber=typeof input.targetNumber==='string'?input.targetNumber.replace(/\s/g,'').toUpperCase():'';if(!validBankNumber(targetNumber))throw new BankError('Select or verify a valid beneficiary account.');
|
||||
const context=await this.authority(user),source=await this.db.first(accountSQL+' WHERE a.id=?',[input.sourceAccount]),target=await this.db.first(accountSQL+' WHERE a.account_number=?',[targetNumber]);
|
||||
if(!source||!context.entities.some(e=>e.id===source.entity_id&&e.canPay))throw new BankError('You cannot debit this account.',403);
|
||||
if(!source||!canDebitAccount(context,source.entity_id,source.id))throw new BankError('You cannot debit this account.',403);
|
||||
if(!target)throw new BankError('The beneficiary account is not available.');
|
||||
if(String(source.id)===String(target.id))throw new BankError('Choose two different accounts.');
|
||||
if(!ownPayment(source,target,user)&&!input.confirmed)throw new BankError('Confirm the beneficiary before sending this transfer.');
|
||||
|
|
@ -50,7 +51,7 @@ export class PostbankPayments{
|
|||
if(BigInt(debit.balance_minor)-BigInt(debit.reserved_minor)<amount)throw new BankError('Insufficient available funds.',409);
|
||||
if(BigInt(credit.balance_minor)+amount>9223372036854775807n)throw new BankError('The beneficiary balance limit would be exceeded.',409);
|
||||
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed. The transfer was not sent.',409);
|
||||
const latest=await this.authority(fresh);if(!latest.entities.some(e=>e.id===debit.entity_id&&e.canPay))throw new BankError('Your authority to debit this account has expired.',403);
|
||||
const latest=await this.authority(fresh,{bank:tx});if(!canDebitAccount(latest,debit.entity_id,debit.id))throw new BankError('Your authority to debit this account has expired.',403);
|
||||
const now=this.clock();
|
||||
if(input.mode==='instant'){
|
||||
const quota=PACKAGES.find(p=>p.key===debit.package_key)?.instant||0;if(!quota)throw new BankError('This package does not include instant payments. Choose standard processing.');
|
||||
|
|
@ -89,8 +90,8 @@ export class PostbankPayments{
|
|||
const rows=await tx.query(accountSQL+' WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[order.source_id,order.target_id]),source=rows.find(a=>String(a.id)===String(order.source_id)),target=rows.find(a=>String(a.id)===String(order.target_id));
|
||||
const amount=BigInt(order.amount_minor);if(!source||BigInt(source.reserved_minor)<amount)throw new BankError('A queued reservation requires reconciliation.',409);
|
||||
// Re-read authority while financial rows are locked; offices may have expired since submission.
|
||||
const latestActor=await this.resolveUser(item.actor_id);const latest=latestActor?await this.authority(latestActor):null;
|
||||
const allowed=latest?.entities.some(e=>e.id===source.entity_id&&e.canPay);
|
||||
const latestActor=await this.resolveUser(item.actor_id);const latest=latestActor?await this.authority(latestActor,{bank:tx}):null;
|
||||
const allowed=latest&&canDebitAccount(latest,source.entity_id,source.id);
|
||||
if(!allowed||!payable(source)||!payable(target)||BigInt(source.balance_minor)<amount||BigInt(target.balance_minor)+amount>9223372036854775807n){
|
||||
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[amount.toString(),source.id]);
|
||||
await tx.query("UPDATE pb_orders SET state='rejected',failure=? WHERE id=?",[!allowed?'Account authority is no longer valid.':'An account is unavailable or has insufficient funds.',order.id]);
|
||||
|
|
@ -111,7 +112,7 @@ export class PostbankPayments{
|
|||
if(start>=end)throw new BankError('Choose dates within the last 30 days.');
|
||||
const context=await this.authority(user),ids=context.entities.filter(e=>e.canView).map(e=>e.id);if(!ids.length)return {records:[],hasMore:false,page};
|
||||
const accounts=await this.db.query(accountSQL+' WHERE c.entity_id IN ('+ids.map(()=>'?').join(',')+') ORDER BY a.id',ids);
|
||||
const visible=accountId?accounts.filter(a=>String(a.id)===accountId):accounts;if(accountId&&!visible.length)throw new BankError('You cannot view this account.',403);if(!visible.length)return {records:[],hasMore:false,page};
|
||||
const allowedAccounts=accounts.filter(a=>canViewAccount(context,a.entity_id,a.id));const visible=accountId?allowedAccounts.filter(a=>String(a.id)===accountId):allowedAccounts;if(accountId&&!visible.length)throw new BankError('You cannot view this account.',403);if(!visible.length)return {records:[],hasMore:false,page};
|
||||
const values=visible.map(a=>String(a.id)),marks=values.map(()=>'?').join(',');
|
||||
const search=q.trim()?'%'+q.trim().replace(/[!%_]/g,c=>'!'+c)+'%':null;
|
||||
const extra=' AND o.created_at>=? AND o.created_at<?'+(state?' AND o.state=?':'')+(search?" AND (o.memo LIKE ? ESCAPE '!' OR COALESCE(es.display_name,s.display_name) LIKE ? ESCAPE '!' OR COALESCE(et.display_name,t.display_name) LIKE ? ESCAPE '!' OR s.account_number LIKE ? ESCAPE '!' OR t.account_number LIKE ? ESCAPE '!')":'');
|
||||
|
|
@ -124,7 +125,7 @@ export class PostbankPayments{
|
|||
return {records,hasMore:rows.length>25,page,window:{from:windowStart,to:now,days:30}};
|
||||
}
|
||||
}
|
||||
export function createPostbankPayments(central,bank,deps={}){return bank?new PostbankPayments(bank,deps.authority||createPostbankAuthority(central),{...deps,resolveUser:deps.resolveUser||(id=>central.prepare("SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'").bind(id).first())}):null;}
|
||||
export function createPostbankPayments(central,bank,deps={}){return bank?new PostbankPayments(bank,deps.authority||createPostbankAuthority(central,{bank}),{...deps,resolveUser:deps.resolveUser||(id=>central.prepare("SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'").bind(id).first())}):null;}
|
||||
// Fixed four-hour settlement windows in the bank's Brussels calendar, including DST.
|
||||
const calendar=new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit',hourCycle:'h23'});
|
||||
const partsAt=time=>Object.fromEntries(calendar.formatToParts(new Date(time)).filter(p=>p.type!=='literal').map(p=>[p.type,Number(p.value)]));
|
||||
|
|
|
|||
|
|
@ -130,3 +130,20 @@ CREATE TABLE IF NOT EXISTS pb_credit_settings (
|
|||
setting_key VARCHAR(64) PRIMARY KEY, setting_value VARCHAR(160) NOT NULL,
|
||||
updated_by CHAR(36) NOT NULL, updated_at BIGINT NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS pb_account_authorisations (
|
||||
id CHAR(36) PRIMARY KEY, account_id BIGINT UNSIGNED NOT NULL,
|
||||
grantee_kind VARCHAR(8) NOT NULL, grantee_key VARCHAR(40) NOT NULL,
|
||||
can_view INT NOT NULL DEFAULT 1, can_pay INT NOT NULL DEFAULT 0,
|
||||
starts_at BIGINT NOT NULL, expires_at BIGINT NULL, state VARCHAR(16) NOT NULL DEFAULT 'active',
|
||||
created_by CHAR(36) NOT NULL, created_at BIGINT NOT NULL, updated_at BIGINT NOT NULL,
|
||||
source_request CHAR(36) NULL, version INT NOT NULL DEFAULT 1,
|
||||
UNIQUE KEY account_grantee(account_id,grantee_kind,grantee_key), FOREIGN KEY(account_id) REFERENCES pb_accounts(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_project_accounts (
|
||||
request_id CHAR(36) PRIMARY KEY, ticket_id BIGINT NOT NULL UNIQUE, entity_id CHAR(36) NOT NULL,
|
||||
client_number CHAR(12) NOT NULL UNIQUE, account_id BIGINT UNSIGNED NOT NULL UNIQUE,
|
||||
expires_at BIGINT NOT NULL, created_at BIGINT NOT NULL,
|
||||
FOREIGN KEY(entity_id) REFERENCES pb_entities(id), FOREIGN KEY(client_number) REFERENCES pb_clients(client_number),
|
||||
FOREIGN KEY(account_id) REFERENCES pb_accounts(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {canViewAccount,canDebitAccount} from './postbank-authorisations.mjs';
|
||||
import {randomUUID,createHash} from 'node:crypto';
|
||||
import {PACKAGES,BANK_VERSION,clientCandidate,bankNumber,money,availablePackages} from './postbank-catalogue.mjs';
|
||||
export class BankError extends Error{constructor(message,status=400){super(message);this.status=status;}}
|
||||
|
|
@ -22,7 +23,7 @@ export class PostbankService{
|
|||
const client=await this.db.first('SELECT client_number FROM pb_clients WHERE entity_id=?',[e.id]);
|
||||
const packages=client?await this.db.query('SELECT id,package_key,monthly_minor,state FROM pb_packages WHERE client_number=? ORDER BY accepted_at,id',[client.client_number]):[];
|
||||
const accounts=client?await this.db.query('SELECT a.id,a.account_number,a.type_code,a.display_name,a.balance_minor,a.reserved_minor,a.state,a.package_id,a.system_key,COALESCE(o.balance_guard,0) AS balance_guard FROM pb_accounts a LEFT JOIN pb_account_options o ON o.account_id=a.id WHERE a.client_number=? ORDER BY a.id',[client.client_number]):[];
|
||||
entities.push({id:e.id,kind:e.kind,name:e.name,clientNumber:client?.client_number||null,state:client?'active':'not_activated',canActivate:e.canActivate,canPay:e.canPay,expiresAt:e.expiresAt,packages:packages.map(p=>({id:p.id,key:p.package_key,name:PACKAGES.find(s=>s.key===p.package_key)?.name||p.package_key,monthly:money(p.monthly_minor),state:p.state})),accounts:accounts.map(a=>({id:String(a.id),number:a.account_number,type:a.type_code,name:a.display_name,balance:money(a.balance_minor),available:a.type_code==='106'?'0.00':money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),state:a.state,packageId:a.package_id,options:{balanceGuardEligible:a.type_code!=='979'&&!a.system_key,balanceGuard:Boolean(a.balance_guard),monthly:money(a.balance_guard?100:0),state:'configured_pending_billing'}}))});
|
||||
entities.push({id:e.id,kind:e.kind,name:e.name,clientNumber:client?.client_number||null,state:client?'active':'not_activated',canActivate:e.canActivate,canPay:e.canPay,expiresAt:e.expiresAt,packages:packages.map(p=>({id:p.id,key:p.package_key,name:PACKAGES.find(s=>s.key===p.package_key)?.name||p.package_key,monthly:money(p.monthly_minor),state:p.state})),accounts:accounts.filter(a=>canViewAccount(context,e.id,a.id)).map(a=>({canPay:canDebitAccount(context,e.id,a.id),id:String(a.id),number:a.account_number,type:a.type_code,name:a.display_name,balance:money(a.balance_minor),available:a.type_code==='106'?'0.00':money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),state:a.state,packageId:a.package_id,options:{balanceGuardEligible:a.type_code!=='979'&&!a.system_key,balanceGuard:Boolean(a.balance_guard),monthly:money(a.balance_guard?100:0),state:'configured_pending_billing'}}))});
|
||||
}
|
||||
return {entities,catalogue:PACKAGES.map(p=>({...p,monthly:money(p.monthly),extraFee:money(p.extraFee)})),termsVersion:BANK_VERSION,admin:{canView:context.readAdmin,canManage:context.manageAdmin},server:{state:'not_linked',name:'Game server account',message:'The game bank is not connected. No game balances or transactions are imported.'},billing:{state:'planned',message:'Monthly fees are disclosed in the package catalogue. Automated billing is not enabled in this foundation batch.'}};
|
||||
}
|
||||
|
|
@ -48,7 +49,7 @@ export class PostbankService{
|
|||
}
|
||||
await tx.query('INSERT INTO pb_activations(entity_id,package_id) VALUES(?,?)',[entity.id,packageId]);
|
||||
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed. Select your package again.',409);
|
||||
const latest=await this.authority(fresh);if(!latest.entities.some(e=>e.id===entity.id&&e.canActivate))throw new BankError('Your authority changed. Select your package again.',409);
|
||||
const latest=await this.authority(fresh,{bank:tx});if(!latest.entities.some(e=>e.id===entity.id&&e.canActivate))throw new BankError('Your authority changed. Select your package again.',409);
|
||||
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[this.makeId(),user.id,'entity_activated',entity.id,JSON.stringify({packageKey:choice.key,requestId:input.requestId}),now]);
|
||||
return {ok:true,replayed:false,clientNumber:number,packageId};
|
||||
});
|
||||
|
|
@ -92,7 +93,7 @@ export class PostbankService{
|
|||
const id=Number(result.insertId);await tx.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber(code,id),id]);
|
||||
}
|
||||
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed. Reload before changing the package.',409);
|
||||
const latest=await this.authority(fresh);if(!latest.entities.some(e=>e.id===entity.id&&e.canActivate))throw new BankError('Your authority to change this package has expired.',409);
|
||||
const latest=await this.authority(fresh,{bank:tx});if(!latest.entities.some(e=>e.id===entity.id&&e.canActivate))throw new BankError('Your authority to change this package has expired.',409);
|
||||
const now=this.clock();await tx.query('UPDATE pb_packages SET package_key=?,monthly_minor=?,terms_version=?,accepted_by=?,accepted_at=? WHERE id=?',[choice.key,choice.monthly,BANK_VERSION,user.id,now,current.id]);
|
||||
await tx.query('INSERT INTO pb_package_changes(request_id,actor_id,entity_id,package_id,fingerprint,from_key,to_key,created_at) VALUES(?,?,?,?,?,?,?,?)',[input.requestId,user.id,entity.id,current.id,fingerprint,current.package_key,choice.key,now]);
|
||||
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[this.makeId(),user.id,'package_changed',entity.id,JSON.stringify({packageId:current.id,from:current.package_key,to:choice.key,requestId:input.requestId}),now]);
|
||||
|
|
@ -117,7 +118,7 @@ export class PostbankService{
|
|||
const previous=await tx.first('SELECT balance_guard FROM pb_account_options WHERE account_id=?',[input.accountId]);
|
||||
if(Boolean(previous?.balance_guard)!==input.expectedBalanceGuard)throw new BankError('The account option changed. Reload before confirming.',409);
|
||||
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed. Reload before confirming.',409);
|
||||
const latest=await this.authority(fresh);if(!latest.entities.some(e=>e.id===entity.id&&e.canPay))throw new BankError('Your account authority expired.',409);
|
||||
const latest=await this.authority(fresh,{bank:tx});if(!latest.entities.some(e=>e.id===entity.id&&e.canPay))throw new BankError('Your account authority expired.',409);
|
||||
const now=this.clock(),fee=input.balanceGuard?100:0;
|
||||
await tx.query('INSERT INTO pb_account_options(account_id,balance_guard,monthly_minor,accepted_by,terms_version,updated_at) VALUES(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE balance_guard=VALUES(balance_guard),monthly_minor=VALUES(monthly_minor),accepted_by=VALUES(accepted_by),terms_version=VALUES(terms_version),updated_at=VALUES(updated_at)',[current.id,input.balanceGuard?1:0,fee,user.id,BANK_VERSION,now]);
|
||||
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,user.id,'account_options_changed',entity.id,JSON.stringify({accountId:input.accountId,balanceGuard:input.balanceGuard,monthlyMinor:fee,fingerprint,state:'configured_pending_billing'}),now]);
|
||||
|
|
|
|||
7
website/tests/postbank-authorisations.test.mjs
Normal file
7
website/tests/postbank-authorisations.test.mjs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {PostbankPayments} from '../node/postbank-payments.mjs';import {PostbankAuthorisations,delegatedAuthority} from '../node/postbank-authorisations.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';
|
||||
async function fixture(){const db=new BankFixture();db.sqlite.exec('CREATE TABLE site_accounts(id TEXT PRIMARY KEY,username TEXT,password_hash TEXT);CREATE TABLE cp_ranks(rank_key TEXT PRIMARY KEY,label TEXT,kind TEXT);');const users=['holder','delegate','bank_manager'].map((username,i)=>({id:randomUUID(),username,role:i===2?'network_admin':'user'})),entity={id:randomUUID(),kind:'person',key:users[0].id,name:users[0].username};for(const u of users)await db.query('INSERT INTO site_accounts VALUES(?,?,?)',[u.id,u.username,'hash']);await db.query("INSERT INTO cp_ranks VALUES('user','User','access')");const central={prepare(sql){let a=[];return {bind(...args){a=args;return this;},async first(){return db.first(sql,a);},async all(){return {results:await db.query(sql,a)};}};}};const authority=async(u,{bank=db}={})=>delegatedAuthority({entities:[{...entity,canView:u.id===users[0].id,canActivate:u.id===users[0].id,canPay:u.id===users[0].id}],rankKeys:[u.role],readAdmin:u.id===users[2].id,manageAdmin:u.id===users[2].id},u,bank);const service=new PostbankService(db,authority);await service.activate(users[0],{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const rows=await db.query('SELECT * FROM pb_accounts ORDER BY id'),current=rows.find(a=>a.type_code==='102'),savings=rows.find(a=>a.type_code==='103');await db.query('UPDATE pb_accounts SET balance_minor=5000 WHERE id=?',[current.id]);return {db,users,authority,service,central,current,savings,mandates:new PostbankAuthorisations(db,central,authority),payments:new PostbankPayments(db,authority,{resolveUser:async id=>users.find(u=>u.id===id)})};}
|
||||
const grant=(f,extra={})=>({requestId:randomUUID(),accountId:String(f.current.id),action:'save',kind:'user',key:f.users[1].id,canPay:true,expiresAt:null,version:0,confirmed:true,...extra});
|
||||
test('one-account mandate cannot expose or debit another account owned by the same client',async()=>{const f=await fixture();try{const input=grant(f);await f.mandates.write(f.users[0],input);assert.equal((await f.mandates.write(f.users[0],input)).replayed,true);const accounts=await f.payments.accounts(f.users[1]);assert.equal(accounts.length,1);assert.equal(accounts[0].id,String(f.current.id));assert.equal(accounts[0].canDebit,true);const overview=await f.service.overview(f.users[1]);assert.equal(overview.entities[0].accounts.length,1);assert.equal(overview.entities[0].canActivate,false);await assert.rejects(f.payments.activity(f.users[1],{accountId:String(f.savings.id)}),e=>e.status===403);await assert.rejects(f.payments.transfer(f.users[1],{requestId:randomUUID(),sourceAccount:String(f.savings.id),targetNumber:f.current.account_number,amount:'1.00',reference:'Cannot use sibling account',mode:'standard',confirmed:true}),e=>e.status===403);await assert.rejects(f.mandates.write(f.users[1],grant(f,{key:f.users[2].id})),e=>e.status===403);}finally{f.db.close();}});
|
||||
test('revoking a mandate before settlement releases held money without moving funds',async()=>{const f=await fixture();try{await f.mandates.write(f.users[0],grant(f));const order={requestId:randomUUID(),sourceAccount:String(f.current.id),targetNumber:f.savings.account_number,amount:'10.00',reference:'Mandated transfer',mode:'standard',confirmed:true};await f.payments.transfer(f.users[1],order);await f.mandates.write(f.users[0],grant(f,{action:'revoke',version:1}));const work=await f.payments.processQueue();assert.equal(work.rejected,1);assert.equal((await f.db.first('SELECT balance_minor,reserved_minor FROM pb_accounts WHERE id=?',[f.current.id])).balance_minor,5000);assert.equal((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.current.id])).reserved_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);}finally{f.db.close();}});
|
||||
test('read-only and expired mandates cannot pay; group membership is checked dynamically',async()=>{const f=await fixture();try{await f.mandates.write(f.users[0],grant(f,{canPay:false}));assert.equal((await f.payments.accounts(f.users[1]))[0].canDebit,false);await f.mandates.write(f.users[2],grant(f,{kind:'rank',key:'user'}),true);assert.equal((await f.payments.accounts(f.users[1]))[0].canDebit,true);f.users[1].role='former';assert.equal((await f.payments.accounts(f.users[1]))[0].canDebit,false);await f.db.query('UPDATE pb_account_authorisations SET expires_at=1');assert.equal((await f.payments.accounts(f.users[1])).length,0);}finally{f.db.close();}});
|
||||
test('mandate writes reject foreign scope, stale versions and unauthorized group assignments',async()=>{const f=await fixture();try{await assert.rejects(f.mandates.write(f.users[1],grant(f)),e=>e.status===403);await assert.rejects(f.mandates.write(f.users[0],grant(f,{kind:'rank',key:'user'})));await f.mandates.write(f.users[0],grant(f));await assert.rejects(f.mandates.write(f.users[0],grant(f)),e=>e.status===409);await assert.rejects(f.mandates.write(f.users[0],grant(f,{version:1}),false,{revalidate:async()=>f.users[1]}),e=>e.status===403);const list=await f.mandates.list(f.users[0]);assert.equal(list.grants[0].label,'delegate');assert.equal(list.canManage,true);}finally{f.db.close();}});
|
||||
Loading…
Reference in a new issue

Staff