forked from unimatrix/web
Protect large instant user payments with a separate configurable payment secret
This commit is contained in:
parent
2138030e13
commit
e4fd0f2ce9
4 changed files with 191 additions and 9 deletions
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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)]));
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
64
website/node/postbank-transfer-security.mjs
Normal file
64
website/node/postbank-transfer-security.mjs
Normal 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;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue

Staff