forked from unimatrix/web
feat(postbank): independent database and first three activation pages
This commit is contained in:
parent
8c70b5712c
commit
53916cbcca
18 changed files with 360 additions and 61 deletions
|
|
@ -45,3 +45,16 @@ Private rollback copies: gameplay `/root/postbank-reset-20261113T165203Z`; websi
|
|||
SHA-256 of a versioned, canonical UUID namespace produces a 12-digit candidate. The new additive `bank_clients` table persists assignments with unique UUID and number constraints; bounded alternate hash candidates resolve collisions without changing existing numbers. This is an identifier, not a secret or authorisation token. UUID relinking follows the linked player, not the website username. No balances or account privileges are inferred from it.
|
||||
|
||||
The Accounts menu now starts with My Banking Information: actual client identity plus explicitly planned banking-profile fields. The existing profile/mandate features are not claimed connected. Focused client/legacy bank import tests: six passed; navigation tests: three passed; Worker build passed. Local full CP cutover tests could not load absent mysql2 in this new worktree; complete-source CI is required before merge/deployment.
|
||||
|
||||
## Authoritative foundation scope — 13 November 2026 evening
|
||||
Owner resumed coding, website-only, one central API with a completely separate bank SQL database. The old website and gameplay databases are read-only sources of identity/organisation metadata; no old balance, account or financial history is imported. Do not delete or reset the old data during this cutover. All personal users must choose Start or Flow and accept before their client number, package and first account are generated. Imported Clan/Company/House/Office/Staff entities stay Not activated until an authorised user accepts a package. Company registry is currently empty; provide an integration contract without inventing companies. Server account is excluded and remains Not linked. Credentials are private and outside Git.
|
||||
|
||||
Final catalogue: Start (free,108,no options/no instant); Flow (5DM,102+103,one extra current at3DM,max2,5instant/month); Connect (10DM,clan/company105,two extras at3DM,max3,15instant); Scale (25DM,clan/company105+reserved106,nine extras at2DM,max10,40instant); Civic (free,House/Office107,10instant); Public (free,human Staff979,25instant). Personal identifiers derive from the central account UUID, not an in-game bank account; professional prefixes CL/HO/PO/CO/ST use10digits. Future server prefix OF. Codes103savings,104Savings+,106securities. No 979 investments. Own-person investments remain distinct from public/civic money.
|
||||
|
||||
Batch1 pages: My Banking Information, Banking Overview, Accounts & Packages. Single shell-owned page banner; no repeated Your accounts heading; English UI. Footer + Workspace details contains the ONLY Reload workspace action, no separate Refresh bank. Errors stay visible. The new public API dispatch is inside the current central CP process; POSTBANK_ENABLED retires old /api/bank routes and /api/v1/me/bank, with no game fallback. New Postbank DB config loaded from a private path. Atomic acceptance with unique entity/client keys, zero balances, permissions rechecked before commit, duplicate replay safe. Securities remains a clearly restricted planned account, no trading. Monthly billing collection is explicitly planned in this foundation batch (no silent charge).
|
||||
|
||||
Owner approved local coding, push and CI/live promotion per3pages. After the FULL agreed bank foundation (not after the first3pages), perform a website-wide retrospective pass for the new banner/diagnostic/reload design rules. Owner will inspect visual results. Required next bank pages: unified transfer (From all accessible debit accounts; To accessible accounts or search user/IBAN), activity/statements, staff account/client/transfer views. Own-account transfers have no extra UI review/approval step; authorisation, funds and idempotency checks remain mandatory. Tax/Revenue/Bank administration payment forms have FIXED From title and external recipient search. P&O NEVER appears as a manual source/target.
|
||||
|
||||
Deferred planning only: P&O sys_payroll_po is a clientless979 issuer with infinite DISPLAY funding, no ordinary manual transfers; staff menu account+history. Future base NET25DM, economy indexbaseline100 pending livefeed, editable gross wage; monthly automatic payroll, Force(currentmonth idempotent), all-or-nothing rollback latest batch if funds available. Excel upload/download next-payroll draft with gross base,bonus,OT hours/rate/reason, generated paystub memo; no immediate payout on upload. Owner chose simplified Belgian game payroll taxes. Withholdings +future securities taxes go to staff Tax Treasury; bank earnings go to separate finite Bank Treasury. Payroll/tax/trading implementation explicitly postponed by latest Owner “werk enkel de basis eerst”. Do not enable payroll, billing taxes or real trades in batch1. No company fixtures or paid transactions.
|
||||
|
||||
Actual server: separate DB dunerealms_postbank and dune_postbank credentials created, only own-schema privileges; private credential /home/dunerealms/.config/postbank-database.json, root recovery /var/lib/dunerealms-maintenance/postbank-bootstrap-20261113T193358Z. Schema12tables initialised, currently no clients/accounts activated by agent. No old databases changed by bootstrap.
|
||||
|
|
|
|||
|
|
@ -1,38 +1,12 @@
|
|||
import {mountNativeService} from './cp-v2-native-services.mjs';
|
||||
import {mountUserCommerce} from './cp-v2-user-commerce.mjs';
|
||||
import {mountImperialRevenue} from './cp-v2-imperial-revenue.mjs';
|
||||
import {mountDesignPage} from './cp-v2-design-pages.mjs';
|
||||
import {DESIGN_PAGES} from './cp-v2-design-catalog.mjs';
|
||||
import {mountBankPlaceholder} from './cp-v2-planned-pages.mjs';
|
||||
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
|
||||
export const BANK_IMPORTS=Object.freeze({
|
||||
'bank-overview':{kind:'accounts',title:'Treasury Overview'},
|
||||
'personal-bank':{kind:'accounts',title:'My Accounts'},
|
||||
'bank-transfers':{kind:'accounts',title:'Wire Transfer',wireTransfer:true},
|
||||
'bank-statements':{kind:'ledger',title:'Account Ledger'},
|
||||
'bank-history':{kind:'ledger',title:'Transfer History'},
|
||||
'staff-bank':{kind:'revenue',title:'Imperial Revenue'}
|
||||
});
|
||||
import {mountPostbankFoundation,FOUNDATION_PAGES} from './cp-v2-postbank-foundation.mjs';
|
||||
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:'planned'},'bank-statements':{kind:'planned'},'bank-history':{kind:'planned'},'staff-bank':{kind:'planned'}});
|
||||
const titles={'bank-transfers':'Wire Transfer','bank-statements':'Transactions & Statements','bank-history':'Payment History','bank-beneficiaries':'Beneficiaries','loan-centre':'Credit Applications','bank-loans':'My Loans','loan-administration':'Credit Administration','bank-dashboard':'Bank Operations','staff-bank':'Bank Treasury','company-finance':'Corporate Accounts','bank-audit':'Bank Audit'};
|
||||
export function mountBankPage(host,id,{fetcher=fetch}={}){
|
||||
if(id==='bank-information')return mountBankInformation(host,{fetcher});
|
||||
const page=BANK_IMPORTS[id];
|
||||
if(page?.kind==='accounts')return mountNativeService(host,'personal-bank',{fetcher,singleHeading:true,title:page.title,wireTransfer:page.wireTransfer});
|
||||
if(page?.kind==='ledger')return mountUserCommerce(host,'transactions',{fetcher,title:page.title});
|
||||
if(page?.kind==='revenue')return mountImperialRevenue(host,{fetcher,singleHeading:true});
|
||||
if(DESIGN_PAGES['bank/'+id])return mountDesignPage(host,'bank/'+id);
|
||||
// These V1 sections were already planned-only; no lending/account-management API is invented.
|
||||
return mountBankPlaceholder(host,id,{singleHeading:true});
|
||||
}
|
||||
export function mountBankInformation(host,{fetcher=fetch}={}){
|
||||
const controller=new AbortController();let active=true;
|
||||
const identity=el('section',undefined,'cp-v2-personal-box'),number=el('strong','Loading…'),status=el('p');status.setAttribute('role','status');
|
||||
identity.append(el('h4','Client identity'),el('p','Your permanent Imperial Postbank client number.'),number,status);
|
||||
const placeholder=el('section',undefined,'cp-v2-personal-box');
|
||||
placeholder.append(el('h4','Banking profile'),el('p','PLANNED · Banking profile details are not connected yet.'));
|
||||
const list=el('dl');for(const label of ['Account holder','Banking relationship','Account authorisations','Client documents'])list.append(el('dt',label),el('dd','Not available yet'));placeholder.append(list);
|
||||
const content=el('div');content.append(identity,placeholder);
|
||||
const {root}=createCPV2Page({shellHost:host,title:'My Banking Information',description:'Your client identity and banking relationship with Imperial Postbank.',artwork:'imperial-postbank-v2.png',tabs:[{id:'information',label:'Banking information',content}]});host.replaceChildren(root);
|
||||
const timeout=setTimeout(()=>controller.abort(),15000);
|
||||
void(async()=>{try{const response=await fetcher('/api/bank/client',{credentials:'same-origin',cache:'no-store',signal:controller.signal});if(!response.ok)throw Error(response.status===401?'Sign in to view your client identity.':'Client identity is temporarily unavailable.');const data=await response.json();if(!active)return;if(data.linked===false&&data.clientNumber===null){number.textContent='Not assigned';status.textContent='A linked player UUID is required for a banking client number.';return;}if(data.linked!==true||typeof data.clientNumber!=='string'||!/^\d{12}$/.test(data.clientNumber))throw Error('Client identity could not be verified.');number.textContent=data.clientNumber;status.textContent='Confirmed by the central client service.';}catch(error){if(active){number.textContent='Unavailable';status.textContent=error.message;}}finally{clearTimeout(timeout);}})();
|
||||
return()=>{active=false;clearTimeout(timeout);controller.abort();root.remove();};
|
||||
if(FOUNDATION_PAGES.includes(id))return mountPostbankFoundation(host,id,{fetcher});
|
||||
const frame=createCPV2ContentPage({host,title:titles[id]||'Bank service',description:'Independent website banking through the central API.',reload:()=>{}});
|
||||
frame.status.hidden=true;frame.content.append(el('p','Planned function. No financial operation is available from this placeholder.'));
|
||||
const spec=el('pre');spec.textContent=id==='bank-transfers'?'Required: POST /api/bank/transfers\nFields: requestId, sourceAccount, targetAccount, amount, reference, mode, confirmed\nResponse: paymentId, state (queued / posted / rejected)':'Required: GET /api/bank/'+(id==='bank-dashboard'?'admin/overview':'activity')+'\nResponse: authorised bank records';frame.content.append(spec,el('p','No request sent. No fallback to the game bank.'));
|
||||
frame.reloadButton.disabled=true;return()=>frame.root.remove();
|
||||
}
|
||||
export const mountBankInformation=(host,options)=>mountPostbankFoundation(host,'bank-information',options);
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ export function mountNativeService(host,id,{fetcher=fetch,singleHeading=false,in
|
|||
const base=NATIVE_SERVICES[id];if(!base)throw Error('Unknown native service.');const spec={...base,url:nativeServiceURL(id,{initialTab,listingId,folder,composeMessage,wireTransfer}),...(typeof title==='string'?{title}:{} )};
|
||||
let active=true,controller=null,frame=null,hasSize=false,ownObserver=null;
|
||||
const status=el('p','Checking your workspace access…','cp-v2-news-status');status.setAttribute('role','status');
|
||||
const workspace=el('section',undefined,'cp-v2-native-workspace'),tools=el('div',undefined,'cp-v2-company-actions'),retry=el('button','Reload workspace');retry.type='button';tools.append(retry);workspace.append(status);
|
||||
const workspace=el('section',undefined,'cp-v2-native-workspace'),tools=el('details',undefined,'pb-workspace-details'),retry=el('button','Reload workspace');retry.type='button';tools.append(el('summary','+ Workspace details'),el('p','Native workspace connection tools'),retry);workspace.append(status);
|
||||
const container=el('div',undefined,'cp-v2-native-frame');workspace.append(container,tools);
|
||||
const {root}=createCPV2Page({shellHost:singleHeading?host:null,title:spec.title,description:spec.description,artwork:id==='forum-admin'?'nav-boards-v2.webp':'nav-support-v2.webp',tabs:[{id:'native-workspace',label:spec.label,content:workspace}]});host.replaceChildren(root);
|
||||
const origin=new URL(spec.url).origin;
|
||||
|
|
|
|||
|
|
@ -2,6 +2,15 @@
|
|||
// Each page supplies its banner, full-width center panel, and feature TabMenu.
|
||||
const ASSETS='https://www.dunerealms.com/assets/';
|
||||
export function element(tag,text,cls){const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e}
|
||||
// Bank foundation pattern: one shell banner, no repeated inner title/tab bar.
|
||||
// Diagnostics and the single reload action stay collapsed after the content.
|
||||
export function createCPV2ContentPage({host,title,description,artwork='imperial-postbank-v2.png',reload=()=>{}}){
|
||||
const root=element('section',undefined,'cp-v2-template-page pb-page');
|
||||
if(!applyShellHeading(host,{title,description,artwork})){const header=element('header',undefined,'cp-v2-template-heading');header.append(element('h3',title),element('p',description));root.append(header);}
|
||||
const status=element('p','Opening the central bank service…','pb-message');status.setAttribute('role','status');
|
||||
const content=element('div',undefined,'pb-content'),details=element('details',undefined,'pb-workspace-details'),summary=element('summary','+ Workspace details'),diagnostics=element('p','Central API · No game bank connection'),reloadButton=element('button','Reload workspace');reloadButton.type='button';reloadButton.onclick=()=>reload();details.append(summary,diagnostics,reloadButton);root.append(status,content,details);host.replaceChildren(root);
|
||||
return {root,content,status,details,diagnostics,reloadButton};
|
||||
}
|
||||
export function createCPV2Page({title,description='',artwork='nav-staff-v2.webp',tabs=[],onActivate=()=>{},shellHost=null}={}){
|
||||
if(!title||!tabs.length)throw new Error('CP V2 page requires a title and feature tabs');
|
||||
const root=element('section',undefined,'cp-v2-template-page');const header=element('header',undefined,'cp-v2-template-heading');const img=element('img');img.src=ASSETS+artwork;img.alt='';img.width=54;img.height=54;const titleGroup=element('div');titleGroup.append(element('h3',title),element('p',description));header.append(img,titleGroup);if(!applyShellHeading(shellHost,{title,description,artwork}))root.append(header);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,55 @@
|
|||
import {element as el,createCPV2ContentPage} from './cp-v2-page-template.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
const meta={
|
||||
'bank-information':['My Banking Information','Your client identity, banking entities and package information.'],
|
||||
'bank-overview':['Banking Overview','Your personal accounts and authorised banking entities, kept clearly separate.'],
|
||||
'personal-bank':['Accounts & Packages','Activate your banking entities and view the accounts in each package.']
|
||||
};
|
||||
export const FOUNDATION_PAGES=Object.freeze(Object.keys(meta));
|
||||
const number=value=>typeof value==='string'&&/^DR\d{14}$/.test(value)?value.match(/.{4}/g).join(' '):'Not activated';
|
||||
const accountNames={'102':'Current','103':'Savings','104':'Savings+','105':'Corporate current','106':'Securities','107':'Civic current','108':'Start','979':'Official current'};
|
||||
function box(title){const section=el('section',undefined,'pb-box');section.append(el('h4',title));return section;}
|
||||
function datum(parent,label,value){const row=el('div',undefined,'pb-datum');row.append(el('span',label),el('strong',String(value)));parent.append(row);}
|
||||
export function mountPostbankFoundation(host,page,{fetcher=fetch}={}){
|
||||
const spec=meta[page];if(!spec)throw Error('Unknown foundation page.');
|
||||
const controller=new AbortController(),api=createUserAPI(fetcher,controller.signal);let active=true,busy=false,view=null,notice=null;
|
||||
const frame=createCPV2ContentPage({host,title:spec[0],description:spec[1],reload:()=>void load()});
|
||||
async function load(){if(busy)return;busy=true;frame.reloadButton.disabled=true;frame.status.hidden=false;frame.status.textContent='Loading your current banking authority…';frame.content.replaceChildren();try{view=await api.request('/api/bank/overview');if(!active)return;render();frame.status.hidden=!notice;if(notice){frame.status.textContent=notice;notice=null;}frame.diagnostics.textContent='GET /api/bank/overview · Confirmed by the central API · '+new Date().toLocaleString('en-GB')+' · Independent bank database';}catch(error){if(active){frame.status.hidden=false;frame.status.textContent=error.message;frame.diagnostics.textContent='GET /api/bank/overview · Not confirmed · No fallback to game accounts';}}finally{busy=false;if(active)frame.reloadButton.disabled=false;}}
|
||||
function activation(entity){
|
||||
const form=el('form',undefined,'pb-activation'),choices=view.catalogue.filter(p=>p.kinds.includes(entity.kind)),select=el('select');select.required=true;select.setAttribute('aria-label','Choose banking package for '+entity.name);
|
||||
for(const choice of choices){const option=el('option',choice.name+' · '+(choice.monthly==='0.00'?'Free':choice.monthly+' DM/month'));option.value=choice.key;select.append(option);}
|
||||
const notice=el('p',entity.kind==='person'?'Choose Start or Flow to open your personal bank account.':'This existing entity has not been activated in the new bank. Accept its package to generate a new bank client and account.');
|
||||
const consent=el('input');consent.type='checkbox';consent.required=true;const label=el('label',undefined,'pb-consent');label.append(consent,el('span','I accept the selected package and its disclosed monthly price.'));
|
||||
const detail=el('p'),submit=el('button','Accept & Generate');submit.type='submit';submit.disabled=!entity.canActivate;
|
||||
const description=()=>{const p=choices.find(c=>c.key===select.value);detail.textContent=!p?'Package unavailable.':p.name+': one current account; '+(p.savings?'a savings account included; ':'')+(p.securities?'securities account reserved for a future service; ':'')+(p.instant?p.instant+' instant payments per calendar month.':'No instant payments or additional products.');};select.onchange=description;description();
|
||||
form.append(notice,select,detail,label,submit);if(!entity.canActivate)form.append(el('p','Activation requires the entity owner or an authorised bank administrator.','pb-muted'));
|
||||
form.onsubmit=async event=>{event.preventDefault();if(busy||!form.reportValidity())return;busy=true;submit.disabled=true;frame.status.hidden=false;frame.status.textContent='Confirming your package and generating the banking records…';try{await api.request('/api/bank/activate',{entityId:entity.id,packageKey:select.value,termsVersion:view.termsVersion,accepted:true,requestId:crypto.randomUUID()});}catch(error){notice=error.uncertain?'Activation was not confirmed. The latest records are shown below; do not repeat acceptance until these records are confirmed.':error.message+' Select your package again.';}finally{busy=false;await load();}};
|
||||
return form;
|
||||
}
|
||||
function render(){
|
||||
frame.content.replaceChildren();const entities=Array.isArray(view.entities)?view.entities:[];
|
||||
if(!entities.length)frame.content.append(el('p','No personal or organisational banking entity is currently available for this account.'));
|
||||
for(const entity of entities){
|
||||
const section=box(entity.name),tag=el('span',entity.kind+' · '+(entity.state==='active'?'Active':'Not activated'),'pb-badge');section.append(tag);
|
||||
if(!entity.clientNumber){section.append(activation(entity));frame.content.append(section);continue;}
|
||||
datum(section,'Client number',entity.clientNumber);
|
||||
if(page==='bank-information'){
|
||||
datum(section,'Banking entity',entity.kind);datum(section,'Access',entity.canPay?'Account operator':'Read only');
|
||||
if(entity.expiresAt)datum(section,'Authority expires',new Date(entity.expiresAt).toLocaleString('en-GB'));
|
||||
}
|
||||
for(const p of entity.packages||[]){const packageBox=el('div',undefined,'pb-package');datum(packageBox,'Package',p.name);datum(packageBox,'Monthly package price',p.monthly+' DM');section.append(packageBox);}
|
||||
const rows=el('div',undefined,'pb-account-list');
|
||||
for(const a of entity.accounts||[]){
|
||||
const card=el('article',undefined,'pb-account');card.append(el('strong',accountNames[a.type]||'Bank account'),el('code',number(a.number)));
|
||||
if(a.state==='planned')card.append(el('span','Planned service · Not available for payments','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,'Account state',a.state);datum(detail,'Package',entity.packages.find(p=>p.id===a.packageId)?.name||'Not available');card.append(detail);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);}
|
||||
}
|
||||
void load();return()=>{active=false;controller.abort();frame.root.remove();};
|
||||
}
|
||||
|
|
@ -183,3 +183,6 @@
|
|||
.cp-v2-company-table tr[data-direction=credit]{border-left:3px solid #79b888}.cp-v2-company-table tr[data-direction=debit]{border-left:3px solid #d28c76}.cp-v2-company-table tr[data-direction=credit] td:nth-last-child(2){color:#a8d7ae}.cp-v2-company-table tr[data-direction=debit] td:nth-last-child(2){color:#e5b4a2}.cp-v2-company-table td:nth-child(2){overflow-wrap:anywhere}.cp-v2-company-table details code{display:block;overflow-wrap:anywhere;white-space:normal;padding:8px 0}
|
||||
|
||||
[hidden]{display:none!important}.cp-v2-auth{max-width:900px;margin:32px auto;padding:30px;border:1px solid #baa05e;border-radius:14px;background:linear-gradient(130deg,#204431,#102a21);color:#f2e4c2}.cp-v2-auth>img{float:left;margin:0 24px 18px 0;object-fit:contain}.cp-v2-auth h1{font:36px Georgia,serif;color:#eed393}.cp-v2-auth-eyebrow{font-size:12px;letter-spacing:.15em;color:#d8b967}.cp-v2-auth form{display:grid;gap:16px;max-width:600px;margin:24px 0}.cp-v2-auth label{display:grid;gap:8px}.cp-v2-auth input:not([type=checkbox]),.cp-v2-auth select{box-sizing:border-box;width:100%;padding:14px;border:1px solid #899168;border-radius:7px;background:#0c241b;color:#f2e4c2;font:inherit}.cp-v2-auth button,.cp-v2-account-bar button{padding:12px 20px;border:1px solid #c1a25a;border-radius:8px;background:#193729;color:#efd18b;font:inherit;cursor:pointer}.cp-v2-account-bar{display:flex;gap:16px;justify-content:flex-end;align-items:center;padding:12px 24px;background:#102b20;color:#e8d7a8}.cp-v2-auth .cp-v2-personal-box{margin-top:20px}.cp-v2-auth form label:has(input[type=checkbox]){display:flex;align-items:center;gap:10px}.cp-v2-auth button:disabled{opacity:.5;cursor:wait}@media(max-width:650px){.cp-v2-auth{margin:14px;padding:20px}.cp-v2-auth>img{float:none}.cp-v2-account-bar{flex-wrap:wrap}}
|
||||
|
||||
/* Postbank: one page banner, compact centre panels and collapsed footer tools. */
|
||||
.pb-page{display:grid;gap:16px}.pb-content{display:grid;gap:16px}.pb-box{border:1px solid #8c8150;border-radius:12px;padding:20px;background:linear-gradient(135deg,#1c3c2e,#102b21)}.pb-box h4{margin:0 0 12px;font:700 21px Georgia,serif;color:#ead18b}.pb-badge{display:inline-block;padding:5px 10px;border:1px solid #8b8553;border-radius:20px;color:#ded4ab;font-size:12px;text-transform:capitalize;margin-bottom:12px}.pb-datum{display:flex;justify-content:space-between;gap:16px;padding:7px 0;border-bottom:1px solid #78916933}.pb-datum span,.pb-muted{color:#b7c7b4;font-size:13px}.pb-datum strong{overflow-wrap:anywhere}.pb-package{padding:10px 0;margin:8px 0}.pb-account-list{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:12px;margin-top:12px}.pb-account{display:grid;gap:8px;padding:16px;border:1px solid #71855c;border-radius:10px;background:#10291f}.pb-account code{color:#dfce97;font-size:14px}.pb-balance{font-size:24px;color:#e5c67a}.pb-account details{font-size:13px}.pb-account summary,.pb-workspace-details summary{cursor:pointer;color:#dfc783}.pb-workspace-details{border-top:1px solid #8c815066;padding:14px 0;margin-top:12px;font-size:13px}.pb-workspace-details>summary{padding:8px 0;font-weight:650}.pb-workspace-details button{margin-top:8px}.pb-activation{display:grid;gap:12px;max-width:680px}.pb-activation select{width:100%;min-width:0}.pb-activation button{justify-self:start}.pb-consent{display:flex;align-items:flex-start;gap:10px}.pb-consent input{width:20px;height:20px;min-width:20px}.pb-message{padding:16px;border-left:3px solid #d9b964;border-radius:8px;background:#4a421e55}.pb-message[hidden]{display:none!important}@media(max-width:650px){.pb-box{padding:15px}.pb-datum{display:grid;gap:4px}.pb-account-list{grid-template-columns:1fr}}
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -1,3 +1,5 @@
|
|||
import {createPostbankApi} from '../node/postbank-api.mjs';
|
||||
import {openPostbankDatabase} from '../node/postbank-db.mjs';
|
||||
import {createItemRegister} from './item-register.mjs';
|
||||
import {createManagedTransfers} from './managed-bank-transfer.mjs';
|
||||
import {createOfficialBank} from './official-bank.mjs';
|
||||
|
|
@ -120,6 +122,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
const managedTransfers=createManagedTransfers(db,settings,dependencies.managedTransfers);
|
||||
const bankTransfers=createBankTransfers(db,settings,dependencies.bankTransfers);
|
||||
const banking=createBanking(db,settings,dependencies.banking);
|
||||
const postbank=createPostbankApi(db,dependencies.bankDatabase||null,settings,dependencies.postbank);
|
||||
const bankClient=createBankClientApi(db,dependencies.bankClient);
|
||||
const v1PersonalBank=createV1PersonalBank(banking,{enabled:process.env.DUNE_API_V1_BANK_STAGING==='true'});
|
||||
const quests=createQuests(db,settings,dependencies.quests),clanShop=createClanShop(db,settings,dependencies.clanShop);
|
||||
|
|
@ -142,6 +145,8 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(path==='/api/items/catalogue')return itemRegister(request);
|
||||
if(path==='/api/worlds')return request.method==='GET'?worldStatus():new Response('Method not allowed',{status:405});
|
||||
const onboarding=await firstLoginGate(request,db);if(onboarding)return onboarding;
|
||||
if(settings.POSTBANK_ENABLED==='true'&&path.startsWith('/api/bank/'))return postbank(request);
|
||||
if(settings.POSTBANK_ENABLED==='true'&&path==='/api/v1/me/bank')return json({message:'The game-linked bank has been retired from this website.'},410);
|
||||
if(['/api/politics/ballot/house','/api/politics/ballot/imperial'].includes(path))return electionVoting(request);
|
||||
if(path==='/api/politics/charters')return imperialCharters(request);
|
||||
if(path==='/api/politics/proclamations')return proclamations(request);
|
||||
|
|
@ -237,7 +242,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405});
|
||||
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'}});}
|
||||
// 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-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-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'}});
|
||||
|
|
@ -254,7 +259,8 @@ export async function startPanel(settings=process.env){
|
|||
else{const {Pool}=await import('pg');inventoryPool=new Pool({connectionString:settings.DUNE_INVENTORY_DATABASE_URL,max:3,connectionTimeoutMillis:5000,idleTimeoutMillis:30000});}
|
||||
inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.'));
|
||||
}
|
||||
const db=await openDatabase(settings);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);const handle=createPanel(db,settings,{inventoryPool}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
const bankDatabase=await openPostbankDatabase(settings);
|
||||
const db=await openDatabase(settings);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);const handle=createPanel(db,settings,{inventoryPool,bankDatabase}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db);
|
||||
const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db);
|
||||
const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':"default-src 'self'; script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.dunerealms.com; img-src 'self' data: https://www.dunerealms.com https://support.dunerealms.com; frame-src 'self' https://luckperms.net https://www.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com https://clans.dunerealms.com https://wiki.dunerealms.com; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com"};
|
||||
|
|
@ -267,7 +273,7 @@ export async function startPanel(settings=process.env){
|
|||
}catch(error){console.error('Panel request failed:',error.code||error.name);res.writeHead(503,security);res.end('{"message":"The account panel is temporarily unavailable."}');}});
|
||||
server.headersTimeout=10000;server.requestTimeout=30000;
|
||||
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(Number(settings.CP_PORT||3003),'127.0.0.1',resolve);});
|
||||
process.once('SIGTERM',()=>{stopOfficeLedger();stopElectionClock();stopBanSync();stopInternalMail();server.close(async()=>{await Promise.allSettled([db.close(),inventoryPool?.end()]);process.exit(0);});});console.log('Account panel listening on localhost');return server;
|
||||
process.once('SIGTERM',()=>{stopOfficeLedger();stopElectionClock();stopBanSync();stopInternalMail();server.close(async()=>{await Promise.allSettled([db.close(),bankDatabase?.close(),inventoryPool?.end()]);process.exit(0);});});console.log('Account panel listening on localhost');return server;
|
||||
}
|
||||
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)await startPanel();
|
||||
|
||||
|
|
|
|||
28
website/node/postbank-api.mjs
Normal file
28
website/node/postbank-api.mjs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
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;
|
||||
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(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(path==='/api/bank/contracts'&&request.method==='GET')return reply({contracts:POSTBANK_CONTRACTS});
|
||||
if(path==='/api/bank/activate'){
|
||||
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 service.activate(user,body,{revalidate:()=>auth(request)}));}catch(error){return reply({message:error.status?error.message:'Activation failed. Return to the package selection and try 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);
|
||||
};
|
||||
}
|
||||
44
website/node/postbank-authority.mjs
Normal file
44
website/node/postbank-authority.mjs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
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']);
|
||||
export const HOUSES=Object.freeze({atreides:'House Aerdrecht',harkonnen:'House Harkveen',corrino:'House Korenholt',ordos:'House Oordwijk',fremen:'Vrijduin',veiled_concord:'Veiled Concord',spacing_guild:'Vaerkring'});
|
||||
export function entityId(kind,key){const h=createHash('sha256').update('postbank:entity:'+kind+':'+key).digest('hex');return `${h.slice(0,8)}-${h.slice(8,12)}-5${h.slice(13,16)}-a${h.slice(17,20)}-${h.slice(20,32)}`;}
|
||||
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}={}){
|
||||
const rows=async(sql,args=[])=>(await central.prepare(sql).bind(...args).all()).results||[];
|
||||
return async user=>{
|
||||
const rights=await accessFor(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']);
|
||||
const add=(kind,key,name,operators=[],viewers=[],expiresAt=null)=>sources.push({id:entityId(kind,key),kind,key,name,canView:readAdmin||operators.includes(user.id)||viewers.includes(user.id),canActivate:manageAdmin||operators.includes(user.id),canPay:operators.includes(user.id),expiresAt});
|
||||
const policy=await central.prepare('SELECT game_link_exempt FROM site_account_policies WHERE user_id=?').bind(user.id).first();
|
||||
if(!policy?.game_link_exempt&&!['memorial','official_account'].includes(user.role))add('person',user.id,user.username,[user.id]);
|
||||
const clans=await rows('SELECT id,name,owner_id FROM site_clans WHERE active=1');
|
||||
const members=await rows('SELECT clan_id,user_id,clan_role FROM site_clan_members');
|
||||
for(const clan of clans)add('clan',clan.id,clan.name,[clan.owner_id,...members.filter(m=>m.clan_id===clan.id&&operatorRoles.has(m.clan_role)).map(m=>m.user_id)],members.filter(m=>m.clan_id===clan.id).map(m=>m.user_id));
|
||||
const companies=await rows("SELECT id,name,founded_by,ceo_account_id FROM corrino_companies WHERE status='active'");
|
||||
for(const company of companies)add('company',company.id,company.name,[company.founded_by,company.ceo_account_id].filter(Boolean));
|
||||
const terms=await rows("SELECT user_id,office,faction,expires_at FROM political_office_terms WHERE outcome='winner' AND starts_at<=? AND expires_at>?",[now,now]);
|
||||
const bootstrap=await rows('SELECT website_id,roles_json,expires_at FROM drforum_dune_political_roles WHERE expires_at>?',[Math.floor(now/1000)]);
|
||||
const bootstrapRoles=bootstrap.map(b=>{let roles=[];try{roles=JSON.parse(b.roles_json);}catch{}return {...b,roles:Array.isArray(roles)?roles:[]};});
|
||||
for(const [key,name]of Object.entries(HOUSES)){
|
||||
const current=terms.filter(t=>t.faction===key&&['house_leader','reverent_mother'].includes(t.office));
|
||||
add('house',key,name,current.map(t=>t.user_id),[],current.length?Math.min(...current.map(t=>Number(t.expires_at))):null);
|
||||
}
|
||||
const emperors=terms.filter(t=>t.office==='emperor'),beforeFirstHandover=now<Date.parse('2026-11-15T18:00:00Z');
|
||||
const provisional=beforeFirstHandover?bootstrapRoles.filter(b=>b.roles.includes('emperor')):[];
|
||||
const emperorActors=[...emperors.map(t=>t.user_id),...provisional.map(b=>b.website_id)];
|
||||
const emperorExpiry=emperors.length?Math.min(...emperors.map(t=>Number(t.expires_at))):provisional.length?Math.min(...provisional.map(b=>Number(b.expires_at)*1000),Date.parse('2026-11-15T18:00:00Z')):null;
|
||||
add('office','emperor','Office of the Emperor',emperorActors,[],emperorExpiry);
|
||||
for(const [key,name]of Object.entries(HOUSES)){
|
||||
const current=terms.filter(t=>t.faction===key&&['house_leader','reverent_mother'].includes(t.office));
|
||||
add('office','leader:'+key,key==='veiled_concord'?'Office of the Reverent Mother':name+' Leadership',current.map(t=>t.user_id),[],current.length?Math.min(...current.map(t=>Number(t.expires_at))):null);
|
||||
}
|
||||
// Staff eligibility follows current central access roles, not cosmetic honours.
|
||||
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'}};
|
||||
};
|
||||
}
|
||||
27
website/node/postbank-catalogue.mjs
Normal file
27
website/node/postbank-catalogue.mjs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
export const BANK_VERSION='postbank-foundation-2026-11-13';
|
||||
export const PACKAGES=Object.freeze([
|
||||
{key:'pb_start',name:'Start',kinds:['person'],monthly:0,code:'108',extra:0,extraFee:0,instant:0},
|
||||
{key:'pb_flow',name:'Flow',kinds:['person'],monthly:500,code:'102',extra:1,extraFee:300,instant:5,savings:true},
|
||||
{key:'pb_connect',name:'Connect',kinds:['clan','company'],monthly:1000,code:'105',extra:2,extraFee:300,instant:15},
|
||||
{key:'pb_scale',name:'Scale',kinds:['clan','company'],monthly:2500,code:'105',extra:9,extraFee:200,instant:40,securities:true},
|
||||
{key:'pb_civic',name:'Civic',kinds:['house','office'],monthly:0,code:'107',extra:0,extraFee:0,instant:10},
|
||||
{key:'pb_public',name:'Public',kinds:['staff'],monthly:0,code:'979',extra:0,extraFee:0,instant:25}
|
||||
].map(Object.freeze));
|
||||
export const ENTITY_PREFIXES=Object.freeze({clan:'CL',house:'HO',office:'PO',company:'CO',staff:'ST',server:'OF'});
|
||||
export const ACCOUNT_TYPES=Object.freeze({'102':'Residential current account','103':'Savings account','104':'Savings+','105':'Corporate current account','106':'Securities account','107':'Civic current account','108':'Start account','979':'Official current account'});
|
||||
export function clientCandidate(kind,key,attempt=0){
|
||||
if(!['person',...Object.keys(ENTITY_PREFIXES)].includes(kind)||typeof key!=='string'||!key||key.length>96||!Number.isInteger(attempt)||attempt<0||attempt>31)throw Error('Invalid client identity.');
|
||||
const hash=BigInt('0x'+createHash('sha256').update('postbank:client:v2:'+kind+':'+key.toLowerCase()+':'+attempt).digest('hex'));
|
||||
return kind==='person'?(hash%1000000000000n).toString().padStart(12,'0'):ENTITY_PREFIXES[kind]+(hash%10000000000n).toString().padStart(10,'0');
|
||||
}
|
||||
export function bankNumber(code,id){
|
||||
if(!Object.hasOwn(ACCOUNT_TYPES,code)||!Number.isSafeInteger(id)||id<1||id>999999999)throw Error('Invalid account number.');
|
||||
const bban=code+String(id).padStart(9,'0'),digits=String(98n-BigInt(bban+'132700')%97n).padStart(2,'0');return 'DR'+digits+bban;
|
||||
}
|
||||
export function validBankNumber(number){return typeof number==='string'&&/^DR\d{14}$/.test(number)&&Object.hasOwn(ACCOUNT_TYPES,number.slice(4,7))&&BigInt(number.slice(4)+'1327'+number.slice(2,4))%97n===1n;}
|
||||
export const formatBankNumber=n=>validBankNumber(n)?n.match(/.{4}/g).join(' '):'Not activated';
|
||||
export function minorAmount(value){if(typeof value!=='string'||! /^(?:0|[1-9]\d{0,6})(?:\.\d{1,2})?$/.test(value))throw Error('Use an amount with at most two decimals.');const [a,b='']=value.split('.'),n=BigInt(a)*100n+BigInt(b.padEnd(2,'0'));if(n<=0n||n>100000000n)throw Error('Amount must be between 0.01 and 1,000,000 DM.');return n;}
|
||||
export const money=n=>{const a=BigInt(n),v=a<0n?-a:a;return(a<0n?'-':'')+(v/100n)+'.'+String(v%100n).padStart(2,'0');};
|
||||
export const availablePackages=kind=>PACKAGES.filter(p=>p.kinds.includes(kind));
|
||||
export const canInvest=kind=>['person','clan','company'].includes(kind);
|
||||
8
website/node/postbank-contract.mjs
Normal file
8
website/node/postbank-contract.mjs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
export const POSTBANK_CONTRACTS=Object.freeze({
|
||||
server:{title:'Game server link',state:'not_linked',request:{method:'POST',path:'/api/bank/integrations/game/payments',fields:['requestId','sourceAccount','targetAccount','amount','reference','gameReceipt']},response:{paymentId:'unique payment reference',state:'queued | posted | rejected'},note:'Future server-to-server integration. No request is sent from this placeholder. Server credentials must never be supplied by a browser.'},
|
||||
mandates:{title:'Account authorisations',state:'planned',request:{method:'POST',path:'/api/bank/authorisations',fields:['accountNumber','clientNumber','permissions','startsAt','expiresAt','confirmed']},response:{authorisationId:'new authorisation reference',state:'active | pending'},note:'Creation, editing and revocation of mandates are deferred. Existing imported authority remains checked by the central API.'},
|
||||
investments:{title:'Securities service',state:'planned',request:{method:'POST',path:'/api/bank/investments/orders',fields:['requestId','securitiesAccount','settlementAccount','instrument','side','quantity','confirmed']},response:{orderId:'unique order reference',state:'accepted | rejected'},note:'No trading request is sent. Civic/Public and all 979 funding or settlement accounts are forbidden. Personal eligibility does not grant access to official money.'},
|
||||
loans:{title:'Credit applications',state:'planned',request:{method:'POST',path:'/api/bank/loans/applications',fields:['requestId','accountNumber','amount','motivation','confirmed']},response:{applicationId:'application reference',state:'submitted'},note:'Credit applications, approvals, payouts and repayments are deferred.'},
|
||||
companies:{title:'Company registration link',state:'prepared',request:{method:'POST',path:'/api/bank/integrations/entities',fields:['sourceEventId','kind','externalKey','displayName']},response:{entityId:'bank entity reference',state:'not_activated'},note:'Trusted central company-registry event, not a browser endpoint. No companies are invented. Existing approved companies are read from the central registry.'},
|
||||
economy:{title:'Cost-of-living index',state:'baseline',request:{method:'GET',path:'/api/bank/integrations/economy-index',fields:[]},response:{index:100,base:100,source:'baseline',observedAt:null},note:'No live economy feed is linked. P&O uses the published baseline until an independently verified index is integrated.'}
|
||||
});
|
||||
13
website/node/postbank-db.mjs
Normal file
13
website/node/postbank-db.mjs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import mysql from 'mysql2/promise';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
export async function openPostbankDatabase(settings){
|
||||
if(settings.POSTBANK_DB_CONFIG){const raw=JSON.parse(await readFile(settings.POSTBANK_DB_CONFIG,'utf8'));settings={...settings,BANK_DB_NAME:raw.database,BANK_DB_USER:raw.user,BANK_DB_PASSWORD:raw.password,BANK_DB_HOST:raw.host,BANK_DB_PORT:raw.port};}
|
||||
const name=settings.BANK_DB_NAME;
|
||||
if(!name)return null;
|
||||
if(!/^[a-z][a-z0-9_]{2,63}$/.test(name)||name===settings.DB_NAME||!settings.BANK_DB_USER||!settings.BANK_DB_PASSWORD)throw Error('A separate Postbank database and credentials are required.');
|
||||
const pool=mysql.createPool({host:settings.BANK_DB_HOST||'127.0.0.1',port:Number(settings.BANK_DB_PORT||3306),database:name,user:settings.BANK_DB_USER,password:settings.BANK_DB_PASSWORD,connectionLimit:4,supportBigNumbers:true,bigNumberStrings:true,charset:'utf8mb4',connectTimeout:8000});
|
||||
const api=c=>({async query(sql,args=[]){return(await c.execute(sql,args))[0];},async first(sql,args=[]){return(await c.execute(sql,args))[0][0]||null;}});
|
||||
const db={async query(sql,args=[]){return(await pool.execute(sql,args))[0];},async first(sql,args=[]){return(await pool.execute(sql,args))[0][0]||null;},async transaction(work){const c=await pool.getConnection();try{await c.beginTransaction();const result=await work(api(c));await c.commit();return result;}catch(error){await c.rollback();throw error;}finally{c.release();}},async close(){await pool.end();}};
|
||||
try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);}catch(error){await pool.end();throw error;}
|
||||
return db;
|
||||
}
|
||||
60
website/node/postbank-schema.sql
Normal file
60
website/node/postbank-schema.sql
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
CREATE TABLE IF NOT EXISTS pb_entities (
|
||||
id CHAR(36) PRIMARY KEY, kind VARCHAR(16) NOT NULL, external_key VARCHAR(96) NOT NULL,
|
||||
display_name VARCHAR(160) NOT NULL, active INT NOT NULL DEFAULT 1, created_at BIGINT NOT NULL,
|
||||
UNIQUE KEY entity_source(kind,external_key)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_clients (
|
||||
client_number CHAR(12) PRIMARY KEY, entity_id CHAR(36) NOT NULL UNIQUE, created_at BIGINT NOT NULL,
|
||||
FOREIGN KEY(entity_id) REFERENCES pb_entities(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_packages (
|
||||
id CHAR(36) PRIMARY KEY, client_number CHAR(12) NOT NULL, package_key VARCHAR(32) NOT NULL,
|
||||
monthly_minor BIGINT NOT NULL, terms_version VARCHAR(64) NOT NULL, accepted_by CHAR(36) NOT NULL,
|
||||
accepted_at BIGINT NOT NULL, state VARCHAR(16) NOT NULL DEFAULT 'active',
|
||||
FOREIGN KEY(client_number) REFERENCES pb_clients(client_number)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_activations (
|
||||
entity_id CHAR(36) PRIMARY KEY, package_id CHAR(36) NOT NULL UNIQUE,
|
||||
FOREIGN KEY(entity_id) REFERENCES pb_entities(id), FOREIGN KEY(package_id) REFERENCES pb_packages(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_accounts (
|
||||
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, account_number CHAR(16) UNIQUE,
|
||||
client_number CHAR(12) NULL, package_id CHAR(36) NULL, system_key VARCHAR(40) UNIQUE NULL, type_code CHAR(3) NOT NULL,
|
||||
display_name VARCHAR(160) NOT NULL, balance_minor BIGINT NOT NULL DEFAULT 0,
|
||||
reserved_minor BIGINT NOT NULL DEFAULT 0, state VARCHAR(16) NOT NULL DEFAULT 'active', created_at BIGINT NOT NULL,
|
||||
FOREIGN KEY(client_number) REFERENCES pb_clients(client_number), FOREIGN KEY(package_id) REFERENCES pb_packages(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_orders (
|
||||
id CHAR(36) PRIMARY KEY, actor_id CHAR(36) NOT NULL, source_id BIGINT UNSIGNED NOT NULL,
|
||||
target_id BIGINT UNSIGNED NOT NULL, fingerprint CHAR(64) NOT NULL, amount_minor BIGINT NOT NULL,
|
||||
memo VARCHAR(140) NOT NULL, mode VARCHAR(8) NOT NULL, state VARCHAR(16) NOT NULL,
|
||||
created_at BIGINT NOT NULL, posted_at BIGINT NULL, failure VARCHAR(160) NULL,
|
||||
FOREIGN KEY(source_id) REFERENCES pb_accounts(id), FOREIGN KEY(target_id) REFERENCES pb_accounts(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_entries (
|
||||
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, order_id CHAR(36) NOT NULL, account_id BIGINT UNSIGNED NOT NULL,
|
||||
amount_minor BIGINT NOT NULL, balance_after_minor BIGINT NOT NULL, created_at BIGINT NOT NULL,
|
||||
UNIQUE KEY order_leg(order_id,account_id), FOREIGN KEY(order_id) REFERENCES pb_orders(id), FOREIGN KEY(account_id) REFERENCES pb_accounts(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_instant_usage (
|
||||
package_id CHAR(36) NOT NULL, month CHAR(7) NOT NULL, used INT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY(package_id,month), FOREIGN KEY(package_id) REFERENCES pb_packages(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_client_limits (
|
||||
client_number CHAR(12) PRIMARY KEY, last_instant_at BIGINT NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY(client_number) REFERENCES pb_clients(client_number)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_audit (
|
||||
id CHAR(36) PRIMARY KEY, actor_id CHAR(36) NOT NULL, action VARCHAR(40) NOT NULL,
|
||||
entity_id CHAR(36) NULL, details TEXT NOT NULL, created_at BIGINT NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_payroll_runs (
|
||||
period CHAR(7) PRIMARY KEY, index_value INT NOT NULL, wage_minor BIGINT NOT NULL,
|
||||
state VARCHAR(16) NOT NULL, created_at BIGINT NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_payroll_items (
|
||||
period CHAR(7) NOT NULL, actor_id CHAR(36) NOT NULL, actor_name VARCHAR(80) NOT NULL,
|
||||
account_id BIGINT UNSIGNED NULL, order_id CHAR(36) NULL, amount_minor BIGINT NOT NULL,
|
||||
state VARCHAR(24) NOT NULL, created_at BIGINT NOT NULL,
|
||||
PRIMARY KEY(period,actor_id), FOREIGN KEY(period) REFERENCES pb_payroll_runs(period)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
55
website/node/postbank-service.mjs
Normal file
55
website/node/postbank-service.mjs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import {randomUUID} 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;}}
|
||||
const duplicate=e=>e.code==='ER_DUP_ENTRY'||String(e.message).includes('UNIQUE constraint');
|
||||
export class PostbankService{
|
||||
constructor(db,authority,{clock=Date.now,makeId=randomUUID}={}){this.db=db;this.authority=authority;this.clock=clock;this.makeId=makeId;}
|
||||
async sync(user){
|
||||
const context=await this.authority(user),now=this.clock();
|
||||
// Import identity metadata only. Imported entities remain unactivated and have
|
||||
// no client/account number or balance until explicit acceptance succeeds.
|
||||
const signature=JSON.stringify(context.entities.filter(e=>e.kind!=='person').map(e=>[e.id,e.kind,e.key,e.name]));
|
||||
for(const e of signature===this.lastImportSignature?[]:context.entities){
|
||||
if(e.kind==='person')continue;
|
||||
await this.db.query('INSERT INTO pb_entities(id,kind,external_key,display_name,active,created_at) VALUES(?,?,?,?,1,?) ON DUPLICATE KEY UPDATE display_name=VALUES(display_name),active=1',[e.id,e.kind,e.key,e.name,now]);
|
||||
}
|
||||
this.lastImportSignature=signature;return context;
|
||||
}
|
||||
async overview(user){
|
||||
const context=await this.sync(user),entities=[];
|
||||
for(const e of context.entities.filter(e=>e.canView)){
|
||||
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 id,account_number,type_code,display_name,balance_minor,reserved_minor,state,package_id FROM pb_accounts WHERE client_number=? ORDER BY 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:money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),state:a.state,packageId:a.package_id}))});
|
||||
}
|
||||
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.'}};
|
||||
}
|
||||
async activate(user,input,{revalidate=async()=>user}={}){
|
||||
if(!input||Object.keys(input).some(k=>!['entityId','packageKey','termsVersion','accepted','requestId'].includes(k))||input.accepted!==true||input.termsVersion!==BANK_VERSION||! /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(input.requestId||''))throw new BankError('Select a package and accept the current package terms.');
|
||||
const context=await this.sync(user),entity=context.entities.find(e=>e.id===input.entityId&&e.canView&&e.canActivate);
|
||||
if(!entity)throw new BankError('You are not authorised to activate this banking entity.',403);
|
||||
const choice=availablePackages(entity.kind).find(p=>p.key===input.packageKey);if(!choice)throw new BankError('This package is not available for the selected banking entity.');
|
||||
return this.db.transaction(async tx=>{
|
||||
await tx.query('INSERT INTO pb_entities(id,kind,external_key,display_name,active,created_at) VALUES(?,?,?,?,1,?) ON DUPLICATE KEY UPDATE display_name=VALUES(display_name)',[entity.id,entity.kind,entity.key,entity.name,this.clock()]);
|
||||
await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[entity.id]);
|
||||
const previous=await tx.first('SELECT p.id,p.package_key,c.client_number FROM pb_activations a JOIN pb_packages p ON p.id=a.package_id JOIN pb_clients c ON c.entity_id=a.entity_id WHERE a.entity_id=?',[entity.id]);
|
||||
if(previous){if(previous.package_key!==choice.key)throw new BankError('This entity has already accepted a different package. Reload your accounts.',409);return {ok:true,replayed:true,clientNumber:previous.client_number,packageId:previous.id};}
|
||||
let number=null;
|
||||
for(let n=0;n<32;n++){const candidate=clientCandidate(entity.kind,entity.key,n);try{await tx.query('INSERT INTO pb_clients(client_number,entity_id,created_at) VALUES(?,?,?)',[candidate,entity.id,this.clock()]);number=candidate;break;}catch(error){if(!duplicate(error))throw error;}}
|
||||
if(!number)throw new BankError('A unique client number could not be allocated. Please select your package again.',503);
|
||||
const packageId=this.makeId(),now=this.clock();
|
||||
await tx.query('INSERT INTO pb_packages(id,client_number,package_key,monthly_minor,terms_version,accepted_by,accepted_at,state) VALUES(?,?,?,?,?,?,?,?)',[packageId,number,choice.key,choice.monthly,BANK_VERSION,user.id,now,'active']);
|
||||
const types=[choice.code,...(choice.savings?['103']:[]),...(choice.securities?['106']:[])];
|
||||
for(const code of types){
|
||||
const result=await tx.query('INSERT INTO pb_accounts(client_number,package_id,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,?,?,?,0,0,?,?)',[number,packageId,code,entity.name+' · '+(code==='103'?'Savings':code==='106'?'Securities':'Current'),code==='106'?'planned':'active',now]);
|
||||
const id=Number(result.insertId);await tx.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber(code,id),id]);
|
||||
}
|
||||
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);
|
||||
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};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -54,11 +54,7 @@ CREATE TABLE IF NOT EXISTS site_game_links (
|
|||
CREATE TABLE IF NOT EXISTS site_game_identities (
|
||||
minecraft_uuid CHAR(36) PRIMARY KEY, first_linked_at BIGINT NOT NULL, last_name VARCHAR(32) NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS bank_clients (
|
||||
minecraft_uuid CHAR(36) PRIMARY KEY,
|
||||
client_number CHAR(12) NOT NULL UNIQUE,
|
||||
created_at BIGINT NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS site_link_challenges (
|
||||
user_id CHAR(36) PRIMARY KEY, token_hash CHAR(64) NOT NULL UNIQUE, expires_at BIGINT NOT NULL,
|
||||
FOREIGN KEY(user_id) REFERENCES site_accounts(id)
|
||||
|
|
|
|||
|
|
@ -1,16 +1,4 @@
|
|||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import test from 'node:test';import assert from 'node:assert/strict';import {readFileSync} from 'node:fs';
|
||||
import {BANK_IMPORTS} from '../control-panel/public/cp-v2/cp-v2-bank-pages.mjs';
|
||||
import {nativeServiceURL,NATIVE_SERVICES,nativeServiceAccess} from '../control-panel/public/cp-v2/cp-v2-native-services.mjs';
|
||||
|
||||
test('Postbank imports existing account, statement and revenue services while retaining bank authority',()=>{
|
||||
for(const id of ['bank-overview','personal-bank','bank-transfers'])assert.equal(BANK_IMPORTS[id].kind,'accounts');
|
||||
for(const id of ['bank-statements','bank-history'])assert.equal(BANK_IMPORTS[id].kind,'ledger');assert.equal(BANK_IMPORTS['staff-bank'].kind,'revenue');
|
||||
assert.equal(nativeServiceAccess({permissions:[]},NATIVE_SERVICES['personal-bank']),false);assert.equal(nativeServiceAccess({permissions:['web.bank.personal.view']},NATIVE_SERVICES['personal-bank']),true);
|
||||
const url=new URL(nativeServiceURL('personal-bank',{wireTransfer:true}));assert.equal(url.origin,'https://cp.dunerealms.com');assert.equal(url.searchParams.get('service'),'bank');assert.equal(url.searchParams.get('wire'),'1');assert.equal(new URL(nativeServiceURL('personal-bank')).searchParams.has('wire'),false);
|
||||
});
|
||||
test('the Wire Transfer entry only opens the existing form after a fresh authorised bank read',async()=>{
|
||||
const source=await readFile(new URL('../control-panel/public/banking.mjs',import.meta.url),'utf8'),adapter=source.slice(source.indexOf('export async function openPersonalWireTransfer'));
|
||||
assert.match(adapter,/permissions\.includes\('web\.bank\.personal\.view'\)/);assert.match(adapter,/await load\('personal-bank'\)/);assert.match(adapter,/version!==generation/);assert.match(adapter,/showWireTransfer/);assert.doesNotMatch(adapter,/method:.*POST|fetch\(|\/api\/bank\/(?:remittance|transfer-own)/);
|
||||
});
|
||||
test('the new bank pages use the independent central bank service, never the old game iframe',()=>{for(const id of ['bank-information','bank-overview','personal-bank'])assert.equal(BANK_IMPORTS[id].kind,'foundation');const source=readFileSync(new URL('../control-panel/public/cp-v2/cp-v2-bank-pages.mjs',import.meta.url),'utf8');assert.doesNotMatch(source,/mountNativeService|banking\.mjs|mountImperialRevenue/);assert.equal(BANK_IMPORTS['bank-transfers'].kind,'planned');});
|
||||
test('the first bank visit reads records, and acceptance is the only account creation action',()=>{const source=readFileSync(new URL('../control-panel/public/cp-v2/cp-v2-postbank-foundation.mjs',import.meta.url),'utf8');assert.match(source,/api\.request\('\/api\/bank\/overview'\)/);assert.match(source,/api\.request\('\/api\/bank\/activate'/);assert.match(source,/Accept & Generate/);assert.match(source,/termsVersion:view\.termsVersion,accepted:true/);assert.doesNotMatch(source,/\/bank\/player|15433|transfer-own/);});
|
||||
|
|
|
|||
20
website/tests/postbank-foundation.test.mjs
Normal file
20
website/tests/postbank-foundation.test.mjs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {DatabaseSync} from 'node:sqlite';import {readFileSync} from 'node:fs';
|
||||
import {PostbankService} from '../node/postbank-service.mjs';import {createPostbankApi} from '../node/postbank-api.mjs';
|
||||
import {BANK_VERSION,bankNumber,validBankNumber,clientCandidate,PACKAGES} from '../node/postbank-catalogue.mjs';
|
||||
const user={id:'12345678-1234-4234-8234-123456789abc',username:'test_citizen'},entity={id:'22345678-1234-4234-8234-123456789abc',kind:'person',key:user.id,name:'Test citizen',canView:true,canActivate:true,canPay:true};
|
||||
const authority=async()=>({entities:[entity],readAdmin:false,manageAdmin:false,eligibleStaff:[]});
|
||||
class BankFixture{
|
||||
constructor(){this.sqlite=new DatabaseSync(':memory:');this.sqlite.exec('PRAGMA foreign_keys=ON');let schema=readFileSync(new URL('../node/postbank-schema.sql',import.meta.url),'utf8').replace(/BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY/g,'INTEGER PRIMARY KEY AUTOINCREMENT').replace(/UNIQUE KEY \w+\(/g,'UNIQUE(').replace(/\) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4/g,')');this.sqlite.exec(schema);this.serial=Promise.resolve();}
|
||||
async query(sql,args=[]){sql=sql.replace(/ FOR UPDATE/g,'').replace(/ON DUPLICATE KEY UPDATE ([\s\S]+)$/,(all,updates)=>'ON CONFLICT DO UPDATE SET '+updates.replace(/VALUES\((\w+)\)/g,'excluded.$1'));const s=this.sqlite.prepare(sql);if(/^\s*(SELECT|WITH)/i.test(sql))return s.all(...args);const r=s.run(...args);return{insertId:Number(r.lastInsertRowid),affectedRows:Number(r.changes)};}
|
||||
async first(sql,args=[]){return(await this.query(sql,args))[0]||null;}
|
||||
async transaction(fn){const before=this.serial;let release;this.serial=new Promise(r=>{release=r;});await before;this.sqlite.exec('BEGIN');try{const v=await fn({query:this.query.bind(this),first:this.first.bind(this)});this.sqlite.exec('COMMIT');return v;}catch(error){this.sqlite.exec('ROLLBACK');throw error;}finally{release();}}
|
||||
close(){this.sqlite.close();}
|
||||
}
|
||||
const input=(key='pb_flow')=>({entityId:entity.id,packageKey:key,termsVersion:BANK_VERSION,accepted:true,requestId:'32345678-1234-4234-8234-123456789abc'});
|
||||
test('a bank visit imports no personal account, number or package before acceptance',async()=>{const db=new BankFixture();try{const service=new PostbankService(db,authority),v=await service.overview(user);assert.equal(v.entities[0].state,'not_activated');assert.equal(v.entities[0].clientNumber,null);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_clients')).n,0);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_accounts')).n,0);assert.equal(v.server.state,'not_linked');assert.equal(v.catalogue.length,6);}finally{db.close();}});
|
||||
test('accepted activation creates zero-funded client, package and correct numbers exactly once',async()=>{const db=new BankFixture();try{const service=new PostbankService(db,authority);const first=await service.activate(user,input());assert.match(first.clientNumber,/^\d{12}$/);const again=await service.activate(user,input());assert.equal(again.replayed,true);assert.equal(again.clientNumber,first.clientNumber);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_clients')).n,1);const accounts=await db.query('SELECT * FROM pb_accounts ORDER BY id');assert.deepEqual(accounts.map(a=>a.type_code),['102','103']);assert.ok(accounts.every(a=>a.balance_minor===0&&validBankNumber(a.account_number)));await assert.rejects(service.activate(user,input('pb_start')),e=>e.status===409);}finally{db.close();}});
|
||||
test('repeated concurrent acceptance cannot create two packages or two clients',async()=>{const db=new BankFixture();try{const service=new PostbankService(db,authority);await Promise.all(Array.from({length:5},()=>service.activate(user,input())));assert.equal((await db.first('SELECT COUNT(*) n FROM pb_packages')).n,1);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_clients')).n,1);}finally{db.close();}});
|
||||
test('account insertion failure and revoked authority roll back all activation records',async()=>{const db=new BankFixture();try{const service=new PostbankService(db,authority);db.sqlite.exec("CREATE TRIGGER fail_account BEFORE INSERT ON pb_accounts BEGIN SELECT RAISE(ABORT,'injected failure'); END;");await assert.rejects(service.activate(user,input()));for(const table of ['pb_clients','pb_packages','pb_accounts','pb_activations'])assert.equal((await db.first('SELECT COUNT(*) n FROM '+table)).n,0);db.sqlite.exec('DROP TRIGGER fail_account');await assert.rejects(service.activate(user,input(),{revalidate:async()=>null}),e=>e.status===409);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_clients')).n,0);}finally{db.close();}});
|
||||
test('corporate entities remain pending; forbidden package or foreign entity cannot be accepted',async()=>{const db=new BankFixture(),clan={...entity,kind:'clan',name:'Existing clan'};try{const service=new PostbankService(db,async()=>({...await authority(),entities:[clan]}));const snap=await service.overview(user);assert.equal(snap.entities[0].clientNumber,null);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_entities')).n,1);await assert.rejects(service.activate(user,input('pb_flow')));const done=await service.activate(user,input('pb_connect'));assert.match(done.clientNumber,/^CL\d{10}$/);const a=await db.first('SELECT * FROM pb_accounts');assert.equal(a.type_code,'105');const denied=new PostbankService(db,async()=>({...await authority(),entities:[]}));await assert.rejects(denied.activate(user,input()),e=>e.status===403);}finally{db.close();}});
|
||||
test('central bank API rejects unauthenticated, cross-origin and account-override requests',async()=>{const db=new BankFixture();try{const api=createPostbankApi(null,db,{}, {authenticate:async()=>user,authority});const url='https://cp.dunerealms.com/api/bank/activate';const r=await api(new Request(url,{method:'POST',headers:{Origin:'https://other.invalid','Content-Type':'application/json'},body:JSON.stringify(input())}));assert.equal(r.status,403);assert.equal((await api(new Request('https://cp.dunerealms.com/api/bank/overview?client=other'))).status,400);const noAuth=createPostbankApi(null,db,{}, {authenticate:async()=>null,authority});assert.equal((await noAuth(new Request(url))).status,401);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_accounts')).n,0);}finally{db.close();}});
|
||||
test('all agreed product codes have valid account check digits and professional identifiers are distinct',()=>{for(const code of ['102','103','104','105','106','107','108','979'])assert.equal(validBankNumber(bankNumber(code,1)),true);for(const [kind,prefix]of [['clan','CL'],['company','CO'],['house','HO'],['office','PO'],['staff','ST']])assert.match(clientCandidate(kind,'stable-source'),new RegExp('^'+prefix+'\\d{10}$'));assert.equal(PACKAGES.find(p=>p.key==='pb_start').instant,0);});
|
||||
Loading…
Reference in a new issue

Staff