Merge pull request 'Alpha 1.0.0.7 — The Great Migration' (#307) from dev/MC:dev/alpha-1.0.0.7-the-great-migration into main

This commit is contained in:
Dev 2026-11-15 05:35:56 +01:00
commit 556cbc5883
10 changed files with 191 additions and 9 deletions

View file

@ -26,16 +26,17 @@ export function mountPostbankPayments(host,page,{fetcher=fetch,accountId=null}={
const reference=el('textarea');reference.required=true;reference.maxLength=140;reference.rows=2;reference.placeholder='Payment reference';
const standard=el('input'),instant=el('input');standard.type=instant.type='radio';standard.name=instant.name='payment-processing';standard.checked=true;const modes=el('fieldset',undefined,'pb-transfer-modes');modes.append(el('legend','Processing'));const standardLabel=el('label',undefined,'pb-processing-choice'),instantLabel=el('label',undefined,'pb-processing-choice');standardLabel.append(standard,el('strong','Standard'),el('small','Every four hours'));instantLabel.append(instant,el('strong','Instant'),el('small','Within your package allowance'));modes.append(standardLabel,instantLabel);const processing=el('p',undefined,'pb-muted');
const confirm=el('input');confirm.type='checkbox';const confirmLabel=el('label',undefined,'pb-consent');confirmLabel.append(confirm,el('span','I confirm the beneficiary and payment details.'));
const paymentSecret=el('input');paymentSecret.type='password';paymentSecret.autocomplete='off';paymentSecret.maxLength=256;paymentSecret.minLength=12;const secretField=field('Separate payment secret',paymentSecret),secretHelp=el('p',undefined,'pb-muted'),securityLink=el('a','Manage payment security');securityLink.href='#realm/security';secretHelp.append(securityLink);
const submit=el('button','Send transfer');submit.type='submit';const moneyRow=el('div',undefined,'pb-remittance-amount');moneyRow.append(field('Amount · DM',amount),field('Reference / message',reference));
const body=el('div',undefined,'pb-remittance-body'),recap=el('aside',undefined,'pb-transfer-recap'),recapAmount=el('strong','0.00 DM','pb-recap-amount'),recapFrom=el('p'),recapTo=el('p'),recapMode=el('p');fromBox.append(balance);body.append(grid,searchArea,moneyRow,modes,processing,confirmLabel,el('p',options.fees.message,'pb-muted'),submit);recap.append(el('small','YOUR TRANSFER'),recapAmount,el('h5','From'),recapFrom,el('h5','To'),recapTo,el('h5','Processing'),recapMode,el('p','Your bank confirms the instruction before any balance is posted.','pb-muted'));form.append(body,recap);frame.content.append(form);const history=el('a','Open Transactions');history.href='#bank/bank-statements';frame.content.append(history);let pending=null,finished=false;
const body=el('div',undefined,'pb-remittance-body'),recap=el('aside',undefined,'pb-transfer-recap'),recapAmount=el('strong','0.00 DM','pb-recap-amount'),recapFrom=el('p'),recapTo=el('p'),recapMode=el('p');fromBox.append(balance);body.append(grid,searchArea,moneyRow,modes,processing,secretField,secretHelp,confirmLabel,el('p',options.fees.message,'pb-muted'),submit);recap.append(el('small','YOUR TRANSFER'),recapAmount,el('h5','From'),recapFrom,el('h5','To'),recapTo,el('h5','Processing'),recapMode,el('p','Your bank confirms the instruction before any balance is posted.','pb-muted'));form.append(body,recap);frame.content.append(form);const history=el('a','Open Transactions');history.href='#bank/bank-statements';frame.content.append(history);let pending=null,finished=false;
const currentSource=()=>sources.find(a=>a.id===from.value),currentTarget=()=>to.value==='external'?external:targets.find(a=>a.number===to.value);
const isOwn=()=>{const a=currentSource(),b=currentTarget();return !!a?.isPersonalOwner&&a.entityId===b?.entityId;};
function update(){const source=currentSource();balance.textContent='Available: '+source.available+' DM';for(const o of to.options)o.disabled=o.value===source.number;if(to.value===source.number)to.value=[...to.options].find(o=>!o.disabled)?.value||'external';searchArea.hidden=to.value!=='external';query.required=!searchArea.hidden;found.required=!searchArea.hidden;instant.disabled=source.instantQuota===0;if(instant.disabled){instant.checked=false;standard.checked=true;}processing.textContent=instant.checked?'Instant payments included in this package: '+source.instantQuota+' per calendar month.':options.standard.processing+(options.standard.nextAt>Date.now()?' Next batch: '+new Date(options.standard.nextAt).toLocaleString('en-GB',{timeZone:'Europe/Brussels'})+' (Belgian time).':'');recapAmount.textContent=(amount.value||'0.00')+' DM';recapFrom.textContent=currentSource().holder;recapTo.textContent=currentTarget()?.holder||'Select a beneficiary';recapMode.textContent=instant.checked?'Instant':'Standard · Every four hours';confirmLabel.hidden=isOwn();confirm.required=!isOwn();}
function update(){const source=currentSource();balance.textContent='Available: '+source.available+' DM';for(const o of to.options)o.disabled=o.value===source.number;if(to.value===source.number)to.value=[...to.options].find(o=>!o.disabled)?.value||'external';searchArea.hidden=to.value!=='external';query.required=!searchArea.hidden;found.required=!searchArea.hidden;instant.disabled=source.instantQuota===0;if(instant.disabled){instant.checked=false;standard.checked=true;}processing.textContent=instant.checked?'Instant payments included in this package: '+source.instantQuota+' per calendar month.':options.standard.processing+(options.standard.nextAt>Date.now()?' Next batch: '+new Date(options.standard.nextAt).toLocaleString('en-GB',{timeZone:'Europe/Brussels'})+' (Belgian time).':'');recapAmount.textContent=(amount.value||'0.00')+' DM';recapFrom.textContent=currentSource().holder;recapTo.textContent=currentTarget()?.holder||'Select a beneficiary';recapMode.textContent=instant.checked?'Instant':'Standard · Every four hours';const protectedAmount=instant.checked&&options.security?.enabled!==false&&Number(amount.value)>Number(options.security?.threshold||'5000.00');secretField.hidden=!protectedAmount;secretHelp.hidden=!protectedAmount;paymentSecret.required=protectedAmount&&!!options.security?.configured;if(!protectedAmount)paymentSecret.value='';securityLink.textContent=options.security?.configured?'Manage payment security':'Set your payment secret before sending this amount, or choose Standard';submit.disabled=protectedAmount&&!options.security?.configured;confirmLabel.hidden=isOwn();confirm.required=!isOwn();}
from.onchange=()=>{confirm.checked=false;update();};to.onchange=()=>{confirm.checked=false;update();};instant.onchange=standard.onchange=update;amount.oninput=update;query.oninput=()=>{external=null;found.replaceChildren();searchVersion++;confirm.checked=false;};found.onchange=()=>{external=found._results?.find(a=>a.number===found.value)||null;confirm.checked=false;update();};
search.onclick=async()=>{const version=++searchVersion;external=null;found.replaceChildren();search.disabled=true;searchStatus.textContent='Searching…';try{const data=await api.request('/api/bank/recipients?q='+encodeURIComponent(query.value));if(!active||version!==searchVersion)return;found._results=data.recipients;selectOption(found,'Choose a beneficiary','');for(const r of data.recipients)selectOption(found,r.holder+' · '+formatNumber(r.number),r.number);searchStatus.textContent=data.recipients.length?'Select and confirm the matching account.':'No active matching account was found.';}catch(error){if(active&&version===searchVersion)searchStatus.textContent=error.message;}finally{if(active)search.disabled=false;}};
form.onsubmit=async event=>{
event.preventDefault();if(busy||finished)return;
if(!pending){if(!form.reportValidity())return;const target=currentTarget();if(!target){announce('Find and select a verified beneficiary.');return;}pending={requestId:crypto.randomUUID(),sourceAccount:from.value,targetNumber:target.number,amount:amount.value,reference:reference.value,mode:instant.checked?'instant':'standard',confirmed:confirm.checked};}
if(!pending){if(!form.reportValidity())return;const target=currentTarget();if(!target){announce('Find and select a verified beneficiary.');return;}pending={requestId:crypto.randomUUID(),sourceAccount:from.value,targetNumber:target.number,amount:amount.value,reference:reference.value,mode:instant.checked?'instant':'standard',confirmed:confirm.checked,...(instant.checked?{paymentSecret:paymentSecret.value}:{})};}
busy=true;submit.disabled=true;for(const node of form.querySelectorAll('input,select,textarea,button'))if(node!==submit)node.disabled=true;announce('Sending payment instruction…');
try{const result=await api.request('/api/bank/transfers',pending);if(!active)return;uncertain=false;finished=true;const receipt=el('section',undefined,'pb-payment-receipt');receipt.append(el('h4',result.state==='posted'?'Payment posted':'Payment reserved'),el('p',result.amount+' DM · '+result.reference),el('p','Status: '+result.state+(result.state==='queued'?' · Standard settlement every four hours.':'')),el('code',result.paymentId));const link=el('a','View Transactions');link.href='#bank/bank-statements';receipt.append(link);const next=el('button','New payment');next.type='button';next.onclick=()=>void load();receipt.append(next);form.replaceWith(receipt);frame.status.hidden=true;}
catch(error){if(!active)return;uncertain=uncertain||!!error.uncertain;announce(uncertain?'The result is not confirmed. Retry below using the SAME payment reference. Do not create another instruction.':error.message);submit.textContent=uncertain?'Check / retry same payment':'Send transfer';if(!uncertain){pending=null;for(const node of form.querySelectorAll('input,select,textarea,button'))node.disabled=false;update();}}

View file

@ -24,6 +24,17 @@ export function mountSecurity(host,{fetcher=fetch}={}){
const passwordSave=el('button','Change password & sign out other sessions');passwordSave.type='submit';const passwordStatus=el('p');passwordStatus.setAttribute('role','status');passwordFields.append(passwordSave);passwordForm.append(passwordFields);passwordBox.append(passwordForm,passwordStatus);
const mailStatus=el('p','Opening your notification settings…');mailStatus.setAttribute('role','status');const mailBody=el('div'),reload=el('button','Reload security settings');reload.type='button';
contactBox.append(el('h4','Support notification email'),el('p','Add a private contact for ticket updates. Ownership must be verified before notifications use it. This does not change your website login.'),mailStatus,mailBody,reload);
const bankBox=el('section',undefined,'cp-v2-personal-box');body.append(bankBox);
async function loadPaymentSecurity(){
bankBox.replaceChildren(el('h4','Instant payment secret'));const status=el('p','Loading payment security…');status.setAttribute('role','status');const reloadBank=el('button','Reload payment security');reloadBank.type='button';reloadBank.onclick=()=>void loadPaymentSecurity();bankBox.append(status,reloadBank);
try{const data=await request('/api/bank/transfer-security');if(!active)return;status.textContent=(data.configured?'Separate secret configured. ':'No payment secret configured. ')+(data.enabled?'Required for instant transfers above '+data.threshold+' DM.':'Extra payment-secret protection is disabled.');
bankBox.append(el('p','This secret is separate from your website password. Changing the secret, its threshold or disabling protection requires the current secret. If forgotten, use Standard transfers and contact Support.'));
const form=el('form'),fields=el('fieldset'),enabled=input(fields,'Protect instant payments above my threshold','checkbox'),threshold=input(fields,'Instant payment threshold · DM','number'),website=input(fields,'Current website password','password'),old=input(fields,'Current payment secret','password'),fresh=input(fields,'New payment secret · leave blank to keep it','password'),consent=input(fields,'I confirm these payment-security settings.','checkbox');
enabled.checked=data.enabled;threshold.value=data.threshold;threshold.min='0';threshold.max='1000000';threshold.step='0.01';threshold.required=true;website.autocomplete='current-password';website.required=true;old.autocomplete='off';old.required=data.configured;fresh.autocomplete='new-password';fresh.minLength=12;website.maxLength=old.maxLength=fresh.maxLength=256;consent.required=true;const updateRequired=()=>{fresh.required=enabled.checked&&!data.configured;};enabled.onchange=updateRequired;updateRequired();const save=el('button','Save payment security');save.type='submit';fields.append(save);form.append(fields);bankBox.append(form);
form.onsubmit=async event=>{event.preventDefault();if(!form.reportValidity())return;fields.disabled=true;status.textContent='Saving payment security…';try{await request('/api/bank/transfer-security',{websitePassword:website.value,currentSecret:old.value,newSecret:fresh.value,threshold:threshold.value,enabled:enabled.checked,version:data.version,confirmed:consent.checked});website.value=old.value=fresh.value='';await loadPaymentSecurity();}catch(e){status.textContent=e.message;fields.disabled=false;}};
}catch(e){if(active)status.textContent=e.message;}
}
void loadPaymentSecurity();
const {root}=createCPV2Page({shellHost:host,title:'Account Security',description:'Protect your website account and manage verified support notifications.',artwork:'nav-account-v2.webp',tabs:[{id:'security',label:'Password & notifications',content:body}]});host.replaceChildren(root);
function controls(){passwordFields.disabled=busy||uncertain;reload.disabled=busy;for(const control of mailBody.querySelectorAll('button,input'))control.disabled=busy||uncertain;}
async function load(){if(busy)return;busy=true;passwordFields.disabled=true;reload.disabled=true;mailBody.replaceChildren();

View file

@ -0,0 +1,24 @@
# Separate instant-payment secret
Account Security lets a user configure a separate secret and their own threshold
(default 5,000 DM). An instant instruction above that threshold needs the secret.
The default unconfigured state requires setup for such payments; Standard
processing stays available. This is a per-instruction control, not a second
authentication factor or a cumulative spending limit.
Initial setup verifies the current website password. After setup, changing the
secret, changing the threshold or disabling protection also requires the current
payment secret. A website session or password reset cannot clear it. There is no
self-service forgotten-secret bypass; Standard payments and Support remain
available. New secrets must differ from the website password.
Secrets use independent salts and scrypt hashes. Plaintext does not enter orders,
audits, local storage or settings responses. Five incorrect secret attempts cause
a 15-minute lock; counters commit independently of a rejected financial posting.
An internal proof is checked against the locked settings version inside the
payment transaction so changing settings invalidates an in-flight instruction.
The secret is excluded from the payment idempotency fingerprint.
Staff treasury and tax postings use their existing authorised posting paths and
do not acquire a user payment-secret prompt. A staff member using the ordinary
user transfer form follows the same personal security settings as any user.

View file

@ -1,3 +1,4 @@
import {PostbankTransferSecurity} from './postbank-transfer-security.mjs';
import {PostbankCreditEngine} from './postbank-credit-engine.mjs';
import {PostbankAuthorisations} from './postbank-authorisations.mjs';
import {createReserveLedger} from './postbank-reserve-ledger.mjs';
@ -16,6 +17,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){
const service=bank?new PostbankService(bank,authority,deps):null,payments=createPostbankPayments(central,bank,{...deps,authority});
const credit=bank?new PostbankCredit(bank,authority,{...deps,central}):null;
const creditEnabled=settings.POSTBANK_CREDIT_ENABLED==='true',creditEngine=bank?new PostbankCreditEngine(bank,central,authority,deps):null;
const transferSecurity=bank?new PostbankTransferSecurity(bank,central,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;
@ -30,6 +32,17 @@ export function createPostbankApi(central,bank,settings={},deps={}){
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','/api/bank/authorisations','/api/bank/authorisations/lookup','/api/bank/credit/details'].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/transfer-security'){
try{
if(request.method==='GET')return reply(await transferSecurity.settings(user));
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403);
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413);
let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid security settings.'},400);}
return reply(await transferSecurity.save(user,body,{revalidate:()=>auth(request)}));
}catch(error){return reply({message:error.status?error.message:'Payment security could not be confirmed. Reload before retrying.'},error.status||503);}
}
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);
@ -129,7 +142,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){
}
if(request.method==='GET'&&['/api/bank/transfer-options','/api/bank/recipients','/api/bank/activity'].includes(path)){
try{
if(path==='/api/bank/transfer-options')return reply({accounts:await payments.accounts(user),beneficiaries:(await beneficiaries.list(user)).beneficiaries,actorId:user.id,standard:{state:'active',processing:'Standard payments are processed in batches every four hours: 00:00, 04:00, 08:00, 12:00, 16:00 and 20:00 Europe/Brussels.',nextAt:standardCycle().nextAt},fees:{state:'planned',message:'Transfer fees are not currently being charged.'}});
if(path==='/api/bank/transfer-options')return reply({accounts:await payments.accounts(user),beneficiaries:(await beneficiaries.list(user)).beneficiaries,actorId:user.id,security:await transferSecurity.settings(user),standard:{state:'active',processing:'Standard payments are processed in batches every four hours: 00:00, 04:00, 08:00, 12:00, 16:00 and 20:00 Europe/Brussels.',nextAt:standardCycle().nextAt},fees:{state:'planned',message:'Transfer fees are not currently being charged.'}});
if(path==='/api/bank/recipients'){
if([...url.searchParams.keys()].some(k=>k!=='q')||url.searchParams.getAll('q').length!==1)return reply({message:'Use only the recipient name or account search field.'},400);
const now=Date.now();for(const [key,value]of lookups)if(value.until<now)lookups.delete(key);if(lookups.size>10000)return reply({message:'Recipient lookup is busy. Try shortly.'},429);

View file

@ -1,3 +1,4 @@
import {PostbankTransferSecurity} from './postbank-transfer-security.mjs';
import {PostbankCreditEngine} from './postbank-credit-engine.mjs';
import {canViewAccount,canDebitAccount} from './postbank-authorisations.mjs';
import {reconcilePostbankClans} from './postbank-registry.mjs';
@ -12,7 +13,7 @@ const payable=a=>a&&Number(a.entity_active)===1&&a.state==='active'&&a.package_s
const receipt=o=>({paymentId:o.id,state:o.state,amount:money(o.amount_minor),reference:o.memo,mode:o.mode,createdAt:Number(o.created_at),postedAt:o.posted_at?Number(o.posted_at):null,failure:o.failure||null});
export const ownPayment=(source,target,user)=>source.kind==='person'&&source.external_key===user.id&&source.client_number===target.client_number;
export class PostbankPayments{
constructor(db,authority,{clock=Date.now,makeId=randomUUID,resolveUser=async()=>null}={}){this.db=db;this.authority=authority;this.clock=clock;this.makeId=makeId;this.resolveUser=resolveUser;}
constructor(db,authority,{clock=Date.now,makeId=randomUUID,resolveUser=async()=>null,security=null}={}){this.db=db;this.authority=authority;this.clock=clock;this.makeId=makeId;this.resolveUser=resolveUser;this.security=security;}
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));
@ -32,8 +33,8 @@ export class PostbankPayments{
return rows.filter(payable).map(a=>({number:a.account_number,name:a.display_name,holder:a.holder}));
}
async transfer(user,input,{revalidate=async()=>user}={}){
const allowed=['requestId','sourceAccount','targetNumber','amount','reference','mode','confirmed'];
if(!input||Object.keys(input).some(k=>!allowed.includes(k))||!uuid(input.requestId)||typeof input.sourceAccount!=='string'||!/^\d{1,12}$/.test(input.sourceAccount)||!['standard','instant'].includes(input.mode)||typeof input.reference!=='string'||!input.reference.trim()||input.reference.trim().length>140||/[\u0000-\u001f]/.test(input.reference)||typeof input.confirmed!=='boolean')throw new BankError('Complete the transfer amount, reference and beneficiary details.');
const allowed=['requestId','sourceAccount','targetNumber','amount','reference','mode','confirmed','paymentSecret'];
if(!input||Object.keys(input).some(k=>!allowed.includes(k))||input.paymentSecret!==undefined&&(typeof input.paymentSecret!=='string'||input.paymentSecret.length>256)||!uuid(input.requestId)||typeof input.sourceAccount!=='string'||!/^\d{1,12}$/.test(input.sourceAccount)||!['standard','instant'].includes(input.mode)||typeof input.reference!=='string'||!input.reference.trim()||input.reference.trim().length>140||/[\u0000-\u001f]/.test(input.reference)||typeof input.confirmed!=='boolean')throw new BankError('Complete the transfer amount, reference and beneficiary details.');
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]);
@ -42,6 +43,7 @@ export class PostbankPayments{
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.');
const reference=input.reference.trim(),fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.sourceAccount,targetNumber,amount.toString(),reference,input.mode])).digest('hex');
const securityProof=await this.security?.preflight(user,{mode:input.mode,amount,paymentSecret:input.paymentSecret});
return this.db.transaction(async tx=>{
for(const id of [...new Set([source.entity_id,target.entity_id])].sort())await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[id]);
const previous=await tx.first('SELECT * FROM pb_orders WHERE id=?',[input.requestId]);
@ -55,6 +57,7 @@ export class PostbankPayments{
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'){
if(this.security)await this.security.assertCurrent(tx,fresh,amount,securityProof);
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.');
const parts=new Intl.DateTimeFormat('en-CA',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit'}).formatToParts(new Date(now));const month=parts.find(p=>p.type==='year').value+'-'+parts.find(p=>p.type==='month').value;
await tx.query('INSERT INTO pb_instant_usage(package_id,month,used) VALUES(?,?,0) ON DUPLICATE KEY UPDATE package_id=VALUES(package_id)',[debit.package_id,month]);
@ -126,7 +129,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,{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;}
export function createPostbankPayments(central,bank,deps={}){return bank?new PostbankPayments(bank,deps.authority||createPostbankAuthority(central,{bank}),{...deps,security:deps.security||new PostbankTransferSecurity(bank,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;}
// 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)]));

View file

@ -160,3 +160,9 @@ CREATE TABLE IF NOT EXISTS pb_credit_concessions (
event_key VARCHAR(96) PRIMARY KEY, loan_id CHAR(36) NOT NULL UNIQUE, created_at BIGINT NOT NULL,
FOREIGN KEY(loan_id) REFERENCES pb_credit_loans(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS pb_transfer_security (
user_id CHAR(36) PRIMARY KEY, secret_salt CHAR(32) NULL, secret_hash CHAR(128) NULL,
threshold_minor BIGINT NOT NULL DEFAULT 500000, enabled INT NOT NULL DEFAULT 1,
version INT NOT NULL DEFAULT 0, failures INT NOT NULL DEFAULT 0,
blocked_until BIGINT NOT NULL DEFAULT 0, updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

View file

@ -0,0 +1,64 @@
import {randomBytes,randomUUID,scrypt as rawScrypt,timingSafeEqual} from 'node:crypto';
import {promisify} from 'node:util';
import {BankError} from './postbank-service.mjs';
import {minorAmount,money} from './postbank-catalogue.mjs';
const scrypt=promisify(rawScrypt),DEFAULT_THRESHOLD=500000n;
async function matches(value,salt,hash){
if(typeof value!=='string'||value.length>256||!salt||!hash||!/^[a-f0-9]{128}$/.test(hash))return false;
return timingSafeEqual(await scrypt(value,salt,64),Buffer.from(hash,'hex'));
}
export class PostbankTransferSecurity{
constructor(bank,central,{clock=Date.now}={}){this.db=bank;this.central=central;this.clock=clock;}
async settings(user){
const row=await this.db.first('SELECT * FROM pb_transfer_security WHERE user_id=?',[user.id]);
return {configured:!!row?.secret_hash,enabled:row?!!Number(row.enabled):true,threshold:money(row?.threshold_minor??DEFAULT_THRESHOLD),version:Number(row?.version||0),blockedUntil:Number(row?.blocked_until||0)};
}
async attempt(tx,user,row,secret){
const now=this.clock();if(Number(row.blocked_until)>now)return {message:'Payment secret temporarily locked. Try later or use standard processing.',status:429};
if(await matches(secret,row.secret_salt,row.secret_hash)){
if(Number(row.failures)||Number(row.blocked_until))await tx.query('UPDATE pb_transfer_security SET failures=0,blocked_until=0 WHERE user_id=?',[user.id]);
return null;
}
const failures=Number(row.failures||0)+1,blocked=failures>=5?now+15*60000:0;
await tx.query('UPDATE pb_transfer_security SET failures=?,blocked_until=? WHERE user_id=?',[blocked?0:failures,blocked,user.id]);
return {message:blocked?'Payment secret temporarily locked. Try later or use standard processing.':'Incorrect payment secret.',status:blocked?429:403};
}
async preflight(user,{mode,amount,paymentSecret}){
if(mode!=='instant')return null;
const result=await this.db.transaction(async tx=>{
const row=await tx.first('SELECT * FROM pb_transfer_security WHERE user_id=? FOR UPDATE',[user.id]);
const required=(!row||Number(row.enabled)===1)&&amount>BigInt(row?.threshold_minor??DEFAULT_THRESHOLD);
if(!required)return {version:Number(row?.version||0),verified:false};
if(!row?.secret_hash)return {error:{message:'Set a payment secret in Account Security or choose standard processing for this amount.',status:403}};
const error=await this.attempt(tx,user,row,paymentSecret);return error?{error}:{version:Number(row.version),verified:true};
});
// Failed-attempt counters must commit before the financial operation is rejected.
if(result.error)throw new BankError(result.error.message,result.error.status);return result;
}
async assertCurrent(tx,user,amount,proof){
const row=await tx.first('SELECT * FROM pb_transfer_security WHERE user_id=? FOR UPDATE',[user.id]);
if(!proof||proof.version!==Number(row?.version||0))throw new BankError('Payment security changed. Review and submit again.',409);
if((!row||Number(row.enabled)===1)&&amount>BigInt(row?.threshold_minor??DEFAULT_THRESHOLD)&&!proof.verified)throw new BankError('A payment secret is required for this amount.',403);
}
async save(user,input,{revalidate=async()=>user}={}){
if(!input||Object.keys(input).some(k=>!['websitePassword','currentSecret','newSecret','threshold','enabled','version','confirmed'].includes(k))||input.confirmed!==true||typeof input.threshold!=='string'||typeof input.enabled!=='boolean'||!Number.isSafeInteger(input.version)||input.version<0||typeof input.websitePassword!=='string'||input.websitePassword.length>256||typeof input.currentSecret!=='string'||input.currentSecret.length>256||typeof input.newSecret!=='string'||input.newSecret.length>256||input.newSecret&&input.newSecret.length<12)throw new BankError('Confirm your payment-security settings and use a secret of 12–256 characters.');
let threshold;try{threshold=/^0(?:\.0{1,2})?$/.test(input.threshold)?0n:minorAmount(input.threshold);}catch{throw new BankError('Choose a threshold from 0 to 1,000,000 DM.');}
const login=await this.central.prepare("SELECT password_salt,password_hash FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'").bind(user.id).first();
if(!await matches(input.websitePassword,login?.password_salt,login?.password_hash))throw new BankError('Incorrect current website password.',403);
if(input.newSecret&&input.newSecret===input.websitePassword)throw new BankError('Choose a payment secret different from your website password.');
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);
const result=await this.db.transaction(async tx=>{
const row=await tx.first('SELECT * FROM pb_transfer_security WHERE user_id=? FOR UPDATE',[user.id]);
if(Number(row?.version||0)!==input.version)throw new BankError('Payment security changed. Reload before saving.',409);
if(row?.secret_hash){const error=await this.attempt(tx,user,row,input.currentSecret);if(error)return {error};}
if(input.enabled&&!row?.secret_hash&&!input.newSecret)throw new BankError('Set a separate payment secret before enabling this protection.');
const salt=input.newSecret?randomBytes(16).toString('hex'):row?.secret_salt||null;
const hash=input.newSecret?(await scrypt(input.newSecret,salt,64)).toString('hex'):row?.secret_hash||null;
const now=this.clock(),version=Number(row?.version||0)+1;
await tx.query('INSERT INTO pb_transfer_security(user_id,secret_salt,secret_hash,threshold_minor,enabled,version,failures,blocked_until,updated_at) VALUES(?,?,?,?,?,?,0,0,?) ON DUPLICATE KEY UPDATE secret_salt=VALUES(secret_salt),secret_hash=VALUES(secret_hash),threshold_minor=VALUES(threshold_minor),enabled=VALUES(enabled),version=VALUES(version),failures=0,blocked_until=0,updated_at=VALUES(updated_at)',[user.id,salt,hash,String(threshold),input.enabled?1:0,version,now]);
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),user.id,'transfer_security_updated',null,JSON.stringify({enabled:input.enabled,threshold:money(threshold),version,secretChanged:!!input.newSecret}),now]);
return {ok:true,version};
});
if(result.error)throw new BankError(result.error.message,result.error.status);return result;
}
}

View file

@ -43,4 +43,4 @@ atomic(manifest, (json.dumps(existing, indent=2)+'\n').encode())
atomic(target / 'organisation-seals.json', (root / 'integrations/organisation-seals.json').read_bytes())
for name in names:
atomic(target / name, (root / 'integrations' / name).read_bytes())
print(f'Installed {len(entries)} seals and three custom adapters; native core unchanged')
print(f'Installed {len(entries)} seals and four custom adapters; native core unchanged')

View file

@ -23,3 +23,19 @@ test('bank transfer routes reject wrong origin, identity overrides and fractiona
test('one failed queued posting retains its hold without blocking another instruction',async()=>{const f=await setup();try{const bad=f.input(),good=f.input();await f.service.transfer(f.users[0],bad);await f.service.transfer(f.users[0],good);f.db.sqlite.exec("CREATE TRIGGER fail_one_entry BEFORE INSERT ON pb_entries WHEN NEW.order_id='"+bad.requestId+"' BEGIN SELECT RAISE(ABORT,'isolated ledger fault'); END;");const result=await f.service.processQueue();assert.equal(result.failed,1);assert.equal(result.posted,1);const a=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id]);assert.equal(a.balance_minor,9000);assert.equal(a.reserved_minor,1000);assert.equal((await f.db.first('SELECT * FROM pb_orders WHERE id=?',[bad.requestId])).state,'queued');f.db.sqlite.exec('DROP TRIGGER fail_one_entry');assert.equal((await f.service.processQueue()).posted,1);assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).reserved_minor,0);}finally{f.db.close();}});
test('standard settlement uses four-hour Brussels windows and leaves newer instructions reserved',async()=>{assert.deepEqual(standardCycle(Date.parse('2026-11-13T20:30:00Z')),{cutoff:Date.parse('2026-11-13T19:00:00Z'),nextAt:Date.parse('2026-11-13T23:00:00Z')});assert.deepEqual(standardCycle(Date.parse('2026-10-25T02:30:00Z')),{cutoff:Date.parse('2026-10-24T22:00:00Z'),nextAt:Date.parse('2026-10-25T03:00:00Z')});assert.deepEqual(standardCycle(Date.parse('2026-03-29T01:30:00Z')),{cutoff:Date.parse('2026-03-28T23:00:00Z'),nextAt:Date.parse('2026-03-29T02:00:00Z')});const f=await setup();try{await f.service.transfer(f.users[0],f.input());const tooEarly=await f.service.processQueue({cutoff:Date.parse('2026-11-13T19:00:00Z')});assert.equal(tooEarly.attempted,0);assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).reserved_minor,1000);assert.equal((await f.service.processQueue({cutoff:Date.parse('2026-11-13T23:00:00Z')})).posted,1);}finally{f.db.close();}});
test('Instant payment security rejects before any funds or quota move, then posts once with the correct secret',async()=>{
const f=await setup();try{
const {PostbankTransferSecurity}=await import('../node/postbank-transfer-security.mjs'),{scryptSync}=await import('node:crypto');
const password='Website fixture password 123',secret='Payment fixture secret 456',salt='fixture-salt';
const central={prepare(){return {bind(){return this;},async first(){return {password_salt:salt,password_hash:scryptSync(password,salt,64).toString('hex')};}};}};
const security=new PostbankTransferSecurity(f.db,central);f.service.security=security;
await security.save(f.users[0],{websitePassword:password,currentSecret:'',newSecret:secret,threshold:'5.00',enabled:true,version:0,confirmed:true});
const input=f.input({mode:'instant'});
await assert.rejects(f.service.transfer(f.users[0],input),e=>e.status===403);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_instant_usage')).n,0);
const result=await f.service.transfer(f.users[0],{...input,paymentSecret:secret});assert.equal(result.state,'posted');
assert.equal((await f.service.transfer(f.users[0],{...input,paymentSecret:secret})).replayed,true);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
assert(!JSON.stringify(await f.db.query('SELECT * FROM pb_orders')).includes(secret));
}finally{f.db.close();}
});

View file

@ -0,0 +1,44 @@
import test from 'node:test';import assert from 'node:assert/strict';
import {randomUUID,scryptSync} from 'node:crypto';
import {BankFixture} from './postbank-fixture.mjs';
import {PostbankTransferSecurity} from '../node/postbank-transfer-security.mjs';
const websitePassword='Current website password 123',secret='Separate payment secret 456';
function fixture(){const db=new BankFixture(),user={id:randomUUID()},salt='test-login-salt';let now=1000000;
const central={prepare(){return{bind(){return this;},async first(){return{password_salt:salt,password_hash:scryptSync(websitePassword,salt,64).toString('hex')};}};}};
const security=new PostbankTransferSecurity(db,central,{clock:()=>now});
const save=(body={})=>security.save(user,{websitePassword,currentSecret:secret,newSecret:'',threshold:'5000.00',enabled:true,version:0,confirmed:true,...body});
return{db,user,security,save,advance:()=>{now+=16*60000;}};
}
test('Default threshold protects large instant payments while standard and smaller payments remain available',async()=>{
const f=fixture();try{assert.deepEqual(await f.security.settings(f.user),{configured:false,enabled:true,threshold:'5000.00',version:0,blockedUntil:0});
assert.equal(await f.security.preflight(f.user,{mode:'standard',amount:1000000n}),null);
assert.deepEqual(await f.security.preflight(f.user,{mode:'instant',amount:500000n}),{version:0,verified:false});
await assert.rejects(f.security.preflight(f.user,{mode:'instant',amount:500001n}),e=>e.status===403);
}finally{f.db.close();}
});
test('Setup stores a separate hash and audit contains no passwords; old secret is required even to disable protection',async()=>{
const f=fixture();try{await assert.rejects(f.save({newSecret:websitePassword}),/different/);await f.save({newSecret:secret});
const stored=await f.db.first('SELECT * FROM pb_transfer_security');assert.notEqual(stored.secret_hash,secret);assert.equal(stored.version,1);
const audit=JSON.stringify(await f.db.query('SELECT * FROM pb_audit'));assert(!audit.includes(secret));assert(!audit.includes(websitePassword));
await assert.rejects(f.save({version:1,enabled:false,currentSecret:'wrong'}),e=>e.status===403);assert.equal((await f.security.settings(f.user)).enabled,true);
await f.save({version:1,enabled:false});assert.equal((await f.security.settings(f.user)).enabled,false);
}finally{f.db.close();}
});
test('Failed guesses commit their counter and lockout; the financial transaction cannot roll them back',async()=>{
const f=fixture();try{await f.save({newSecret:secret});
for(let i=0;i<5;i++)await assert.rejects(f.security.preflight(f.user,{mode:'instant',amount:600000n,paymentSecret:'wrong'}),e=>e.status===(i===4?429:403));
assert((await f.security.settings(f.user)).blockedUntil>0);
await assert.rejects(f.security.preflight(f.user,{mode:'instant',amount:600000n,paymentSecret:secret}),e=>e.status===429);
f.advance();assert.deepEqual(await f.security.preflight(f.user,{mode:'instant',amount:600000n,paymentSecret:secret}),{version:1,verified:true});
}finally{f.db.close();}
});
test('Changing a threshold invalidates an in-flight proof and cannot race a posting',async()=>{
const f=fixture();try{await f.save({newSecret:secret});const proof=await f.security.preflight(f.user,{mode:'instant',amount:300000n});
await f.save({version:1,threshold:'1000.00'});
await assert.rejects(f.db.transaction(tx=>f.security.assertCurrent(tx,f.user,300000n,proof)),e=>e.status===409);
const verified=await f.security.preflight(f.user,{mode:'instant',amount:300000n,paymentSecret:secret});await f.db.transaction(tx=>f.security.assertCurrent(tx,f.user,300000n,verified));
}finally{f.db.close();}
});
test('A failed audit rolls back secret configuration',async()=>{
const f=fixture();try{f.db.sqlite.exec("CREATE TRIGGER fail_security_audit BEFORE INSERT ON pb_audit BEGIN SELECT RAISE(ABORT,'audit failure'); END;");await assert.rejects(f.save({newSecret:secret}),/audit failure/);assert.equal((await f.security.settings(f.user)).configured,false);}finally{f.db.close();}
});