MC/website/node/postbank-transfer-security.mjs

64 lines
6.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}