Provision audited Rihla cash custody and persistent activation

This commit is contained in:
unimatrixgit 2026-11-29 13:56:34 +01:00
commit 0097a856f7
4 changed files with 134 additions and 0 deletions

View file

@ -0,0 +1,15 @@
# Activate the existing Rihla cash custody service
The deployed ATM can render and select denominations, but live read-only inspection found all three Rihla activation/backing settings absent and no dedicated Rihla backing account. The existing central route therefore cannot construct its cash ledger. The owner's cash-operation history contained no operation rows at diagnosis; no agent cash transaction was performed.
## Bounded execution
Build and review this source through the website pipeline. Run the built `ops/configure-rihla-cash.mjs` first without arguments, then with `--apply`. It validates the existing native receipt reader and shared transactional MySQL server before setup. It creates a dedicated internal type-999 custody account with zero balance and zero reserve, using the existing Postbank account/audit tables. It does not create a client, payment, ledger entry, cash serial, voucher or account mandate, and never funds custody from a treasury or resets existing custody funds.
The tool privately backs up the environment and setup plan, validates the existing tax treasury and backing account, and atomically writes only `RIHLA_POSTBANK_ENABLED`, `RIHLA_CASH_ENABLED` and `RIHLA_POSTBANK_BACKING_SYSTEM_KEY`. File ownership/mode and all other values remain preserved. A concurrent environment change stops activation. If activation fails after creating the empty account, retain that audited account and retry; do not delete later cash custody. A normal runtime restart is required to read the settings; record it and verify the existing route's read-only account response. Do not invoke `cash_pending` merely as a read test, because pending recovery refreshes custody state.
## Acceptance and tests
Tests cover write-free planning, zero-balance creation, replay after subsequent custody funds, incompatible-account refusal, missing treasury, audit rollback, and configuration preservation/idempotency. Existing Rihla custody, reserve, settlement and native receipt tests must also pass. Production cash movement is not a test: the owner may verify an actual action after deployment, with the real native/bank receipt used as evidence. Never clear a pending operation or invent a replacement reference.
Rollback disables the three activation settings by restoring the private environment backup and restarting through the existing runtime service. Retain the custody account and all native/bank operation records; never reverse an actual withdrawal by deleting data. This change does not alter transaction rules, permissions, prices, fees or backend JARs.

View file

@ -0,0 +1,36 @@
import {randomUUID} from 'node:crypto';
import {REGISTRY_ACTOR} from './postbank-registry.mjs';
export const RIHLA_BACKING_KEY='sys_rihla_cash';
export const RIHLA_CONFIGURATION=Object.freeze({RIHLA_POSTBANK_ENABLED:'true',RIHLA_CASH_ENABLED:'true',RIHLA_POSTBANK_BACKING_SYSTEM_KEY:RIHLA_BACKING_KEY});
export function rihlaEnvironment(payload){
const lines=payload.split(/\r?\n/),seen=new Set();
const output=lines.map(line=>{
const match=line.match(/^\s*(?:export\s+)?([A-Z_]+)\s*=/);
if(!match||!Object.hasOwn(RIHLA_CONFIGURATION,match[1]))return line;
if(seen.has(match[1]))throw Error('Duplicate Rihla setting requires review');
seen.add(match[1]);return match[1]+'='+RIHLA_CONFIGURATION[match[1]];
});
while(output.at(-1)==='')output.pop();
for(const [key,value] of Object.entries(RIHLA_CONFIGURATION))if(!seen.has(key))output.push(key+'='+value);
return output.join('\n')+'\n';
}
export function validateRihlaBacking(row){
if(!row||row.system_key!==RIHLA_BACKING_KEY||row.type_code!=='999'||row.state!=='active'||row.client_number!==null||row.package_id!==null||BigInt(row.balance_minor)<0n||BigInt(row.reserved_minor)<0n||BigInt(row.reserved_minor)>BigInt(row.balance_minor))throw Error('Existing Rihla backing requires reconciliation');
return row;
}
export async function provisionRihlaBacking(bank,{apply=false,clock=Date.now}={}){
const inspect=async tx=>{
const tax=await tx.first("SELECT id,state FROM pb_accounts WHERE system_key='sys_tax_treasury'");
if(tax?.state!=='active')throw Error('Active tax treasury required');
const row=await tx.first('SELECT * FROM pb_accounts WHERE system_key=?'+(apply?' FOR UPDATE':''),[RIHLA_BACKING_KEY]);
if(row){validateRihlaBacking(row);return {created:false,systemKey:RIHLA_BACKING_KEY,id:String(row.id)};}
if(!apply)return {created:false,wouldCreate:true,systemKey:RIHLA_BACKING_KEY,openingBalanceMinor:'0'};
const now=clock();
const result=await tx.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,'999','Rihla cash custody',0,0,'active',?)",[RIHLA_BACKING_KEY,now]);
const created=validateRihlaBacking(await tx.first('SELECT * FROM pb_accounts WHERE id=?',[result.insertId]));
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),REGISTRY_ACTOR,'rihla_custody_configured',null,JSON.stringify({accountId:String(created.id),systemKey:RIHLA_BACKING_KEY,openingBalanceMinor:'0'}),now]);
return {created:true,systemKey:RIHLA_BACKING_KEY,id:String(created.id),openingBalanceMinor:'0'};
};
return apply?bank.transaction(inspect):inspect(bank);
}

View file

@ -0,0 +1,32 @@
import {readFile,writeFile,mkdir,stat,chmod,chown,rename,realpath} from 'node:fs/promises';
import {resolve} from 'node:path';
import {pathToFileURL} from 'node:url';
import mysql from 'mysql2/promise';
import {provisionRihlaBacking,rihlaEnvironment,RIHLA_CONFIGURATION} from '../node/rihla-configuration.mjs';
import {createRihlaPostbank} from '../node/rihla-postbank.mjs';
import {openRihlaCashReceiptReader} from '../node/rihla-cash.mjs';
async function main(){
const envPath='/home/dunerealms/.config/dunerealms.env',apply=process.argv.includes('--apply');
const old=await readFile(envPath,'utf8'),meta=await stat(envPath);process.loadEnvFile(envPath);
const settings=process.env,config=JSON.parse(await readFile(settings.POSTBANK_DB_CONFIG,'utf8'));
const pool=mysql.createPool({...config,supportBigNumbers:true,bigNumberStrings:true}),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 bank={...api(pool),async transaction(work){const c=await pool.getConnection();try{await c.beginTransaction();const value=await work(api(c));await c.commit();return value}catch(error){await c.rollback();throw error}finally{c.release()}}};
let native;
try{
const url=new URL(settings.DUNE_INVENTORY_DATABASE_URL);if(url.protocol!=='mysql:')throw Error('Verified native MySQL connection required');
native=mysql.createPool(url.href);
await openRihlaCashReceiptReader(bank,{dialect:'mysql',async query(sql){return{rows:(await native.query(sql))[0]}}},url.href);
const candidate=rihlaEnvironment(old),plan=await provisionRihlaBacking(bank);
if(!apply){console.log(JSON.stringify({applied:false,backing:plan,configuration:RIHLA_CONFIGURATION,financialTransactions:false}));return;}
const backup=resolve('/root/dunerealms-rihla-configuration-backups',new Date().toISOString().replace(/[:.]/g,'-'));await mkdir(backup,{recursive:true,mode:0o700});
await writeFile(resolve(backup,'environment.before'),old,{mode:0o600,flag:'wx'});
await writeFile(resolve(backup,'plan.json'),JSON.stringify(plan),{mode:0o600,flag:'wx'});
const backing=await provisionRihlaBacking(bank,{apply:true});
await createRihlaPostbank(bank,{authority:async()=>{throw Error('No financial operation allowed during setup')},backingSystemKey:RIHLA_CONFIGURATION.RIHLA_POSTBANK_BACKING_SYSTEM_KEY}).verifyConfiguration();
if(await readFile(envPath,'utf8')!==old)throw Error('Environment changed during setup; zero-balance custody retained, activation not applied');
const temporary=envPath+'.rihla-'+process.pid;await writeFile(temporary,candidate,{mode:meta.mode&0o777,flag:'wx'});await chown(temporary,meta.uid,meta.gid);await chmod(temporary,meta.mode&0o777);await rename(temporary,envPath);
console.log(JSON.stringify({applied:true,backing,configuration:RIHLA_CONFIGURATION,backup,restartRequired:true,financialTransactions:false}));
}finally{await pool.end();if(native)await native.end()}
}
if(process.argv[1]&&import.meta.url===pathToFileURL(await realpath(resolve(process.argv[1]))).href)await main();

View file

@ -0,0 +1,51 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {BankFixture} from './postbank-fixture.mjs';
import {provisionRihlaBacking,rihlaEnvironment,RIHLA_BACKING_KEY} from '../node/rihla-configuration.mjs';
async function fixture(){const db=new BankFixture();await db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES('sys_tax_treasury','979','Tax',12345,'active',0)");return db;}
test('plan has no writes; setup creates only zero-balance custody and replay preserves subsequent funds',async()=>{
const db=await fixture();try{
const before=await db.query('SELECT * FROM pb_accounts');
assert.equal((await provisionRihlaBacking(db)).wouldCreate,true);
assert.deepEqual(await db.query('SELECT * FROM pb_accounts'),before);
const first=await provisionRihlaBacking(db,{apply:true});assert.equal(first.created,true);
const row=await db.first('SELECT * FROM pb_accounts WHERE system_key=?',[RIHLA_BACKING_KEY]);
assert.equal(row.type_code,'999');assert.equal(row.balance_minor,0);assert.equal(row.reserved_minor,0);assert.equal(row.client_number,null);assert.equal(row.package_id,null);
// Simulate later real custody; rerunning setup must never reset its funds.
await db.query('UPDATE pb_accounts SET balance_minor=2000,reserved_minor=500 WHERE id=?',[row.id]);
assert.equal((await provisionRihlaBacking(db,{apply:true})).created,false);
assert.equal((await db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[row.id])).balance_minor,2000);
assert.equal((await db.first('SELECT COUNT(*) n FROM pb_audit')).n,1);
assert.equal((await db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
assert.equal((await db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);
assert.deepEqual((await db.query("SELECT * FROM pb_accounts WHERE system_key='sys_tax_treasury'")),before);
}finally{db.close()}
});
test('configuration refuses incompatible custody and missing treasury without repairing balances or status',async()=>{
const db=await fixture();try{
await provisionRihlaBacking(db,{apply:true});
await db.query("UPDATE pb_accounts SET type_code='979' WHERE system_key=?",[RIHLA_BACKING_KEY]);
await assert.rejects(provisionRihlaBacking(db,{apply:true}),/reconciliation/);
await db.query("DELETE FROM pb_accounts WHERE system_key='sys_tax_treasury'");
await assert.rejects(provisionRihlaBacking(db,{apply:true}),/treasury/);
}finally{db.close()}
});
test('audit failure rolls back custody creation',async()=>{
const db=await fixture();try{
const original=db.transaction.bind(db);db.transaction=work=>original(tx=>work({...tx,query(sql,args){if(sql.startsWith('INSERT INTO pb_audit'))throw Error('audit unavailable');return tx.query(sql,args)}}));
await assert.rejects(provisionRihlaBacking(db,{apply:true}),/audit unavailable/);
assert.equal(await db.first('SELECT * FROM pb_accounts WHERE system_key=?',[RIHLA_BACKING_KEY]),null);
}finally{db.close()}
});
test('environment update changes only three activation settings and is idempotent',()=>{
const input='# Private configuration\nGAME_LINK_SECRET=preserve-this-exact-value\nRIHLA_CASH_ENABLED=false\nPOSTBANK_ENABLED=true\n';
const result=rihlaEnvironment(input);
assert.ok(result.includes('GAME_LINK_SECRET=preserve-this-exact-value\n'));
assert.ok(result.includes('POSTBANK_ENABLED=true\n'));
assert.ok(result.includes('RIHLA_POSTBANK_ENABLED=true\n'));
assert.ok(result.includes('RIHLA_CASH_ENABLED=true\n'));
assert.ok(result.includes('RIHLA_POSTBANK_BACKING_SYSTEM_KEY=sys_rihla_cash\n'));
assert.equal(rihlaEnvironment(result),result);
assert.throws(()=>rihlaEnvironment('RIHLA_CASH_ENABLED=false\nRIHLA_CASH_ENABLED=true\n'),/Duplicate/);
});