import {createHash} from 'node:crypto'; import {identity} from './auth.mjs'; import {gameAuthorized,json,validUuid} from './game-link.mjs'; import {money,transferAmount} from './postbank-catalogue.mjs'; export const RIHLA_SCHEMA=[ `CREATE TABLE IF NOT EXISTS ria_accounts(owner_id CHAR(36) PRIMARY KEY,account_number VARCHAR(40) NOT NULL UNIQUE,balance_minor BIGINT NOT NULL DEFAULT 0,reserved_minor BIGINT NOT NULL DEFAULT 0,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, `CREATE TABLE IF NOT EXISTS ria_transfers(id CHAR(36) PRIMARY KEY,transaction_number VARCHAR(40) NOT NULL UNIQUE,sender_id CHAR(36) NOT NULL,recipient_id CHAR(36) NOT NULL,sender_name VARCHAR(100) NOT NULL,recipient_name VARCHAR(100) NOT NULL,amount_minor BIGINT NOT NULL,tax_minor BIGINT NOT NULL,state VARCHAR(16) NOT NULL,jarvis_instance_id CHAR(36) NOT NULL UNIQUE,created_at BIGINT NOT NULL,INDEX ria_sender_history(sender_id,created_at,id),INDEX ria_recipient_history(recipient_id,created_at,id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4` ]; // Use the existing private financial store and transaction wrapper. Rihla is not // a Postbank package/account: normal account, staff and statement queries cannot include it. export const RIHLA_INSTRUMENT=Object.freeze({id:'rihla-transfer',prefix:'RIA',currency:'DM',use:'ingame-only',states:['created','paid','cancelled'],taxRecipient:'sys_tax_treasury',ownerVisible:true,staffVisible:false}); const uuid=id=>typeof id==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id); export const rihlaAccountNumber=id=>'RIA-'+createHash('sha256').update('rihla:account:'+id).digest('hex').slice(0,24).toUpperCase(); export function rihlaQuote(value){const amount=transferAmount(value),rate=amount>300000n?5n:1n,tax=(amount*rate+99n)/100n,total=amount+tax;if(total>9223372036854775807n)throw Error('Amount and tax exceed the ledger limit.');return{amountMinor:String(amount),taxMinor:String(tax),totalMinor:String(total),ratePercent:Number(rate),recipient:RIHLA_INSTRUMENT.taxRecipient};} export async function ensureRihlaAccount(bank,ownerId,{clock=Date.now}={}){if(!uuid(ownerId))throw Error('Account identity required');await bank.query('INSERT INTO ria_accounts(owner_id,account_number,balance_minor,reserved_minor,created_at) VALUES(?,?,0,0,?) ON DUPLICATE KEY UPDATE owner_id=VALUES(owner_id)',[ownerId,rihlaAccountNumber(ownerId),clock()]);} export async function provisionRihlaAccounts(central,bank,{clock=Date.now}={}){if(!bank)return{state:'unavailable',accounts:0};let cursor='',accounts=0;while(true){const rows=await central.query('SELECT id FROM site_accounts WHERE id>? ORDER BY id LIMIT 200',[cursor]);if(!rows.length)break;await bank.transaction(async tx=>{for(const row of rows)await ensureRihlaAccount(tx,row.id,{clock});});accounts+=rows.length;cursor=rows.at(-1).id;}return{state:'ready',accounts};} export function createRihlaAPI(central,bank,{authenticate=r=>identity(r,central),clock=Date.now}={}){return async request=>{const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}});try{ const user=await authenticate(request);if(!user)return reply({message:'Sign in to view Rihla.'},401); if(request.method!=='GET')return reply({message:'Rihla on the website is read-only. Use the in-game service.'},405); const url=new URL(request.url);if([...url.searchParams.keys()].some(k=>k!=='page')||url.searchParams.getAll('page').length>1)return reply({message:'Account overrides are not accepted.'},400);const raw=url.searchParams.get('page')||'1';if(!/^[1-9]\d{0,5}$/.test(raw))return reply({message:'Invalid page.'},400);const page=Number(raw);if(page>10000)return reply({message:'Invalid page.'},400); if(!bank)return reply({message:'Rihla records are temporarily unavailable.'},503); await ensureRihlaAccount(bank,user.id,{clock});const account=await bank.first('SELECT account_number,balance_minor,reserved_minor FROM ria_accounts WHERE owner_id=?',[user.id]);const rows=await bank.query('SELECT transaction_number,sender_name,recipient_name,amount_minor,state FROM ria_transfers WHERE sender_id=? OR recipient_id=? ORDER BY created_at DESC,id DESC LIMIT 26 OFFSET '+((page-1)*25),[user.id,user.id]); return reply({account:{number:account.account_number,balance:money(account.balance_minor),available:money(BigInt(account.balance_minor)-BigInt(account.reserved_minor)),currency:'DM'},page,hasMore:rows.length>25,transactions:rows.slice(0,25).map(r=>({number:r.transaction_number,sender:r.sender_name,recipient:r.recipient_name,amount:money(r.amount_minor),status:r.state}))}); }catch{return reply({message:'Rihla records are temporarily unavailable.'},503);}};} export function createGameRihlaAPI(central,bank,settings={},deps={}){ const clock=deps.clock??Date.now; const quoteReference=(actor,recipient,quote)=>createHash('sha256') .update(JSON.stringify([actor.id,recipient.id,quote.amountMinor,quote.taxMinor])).digest('hex'); const transferView=row=>({number:row.transaction_number,state:row.state, amountMinor:String(row.amount_minor),taxMinor:String(row.tax_minor)}); const resolve=deps.resolve??(async uuid=>{ const rows=await central.query(`SELECT a.id,a.username FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')`,[uuid]); return rows.length===1?rows[0]:null; }); return async request=>{ if(request.method!=='POST')return json({message:'Method not allowed.'},405); if(!gameAuthorized(request,settings))return json({message:'Unauthorized.'},401); let input; try{ const body=await request.text(); if(body.length>2048)return json({message:'Rihla request is too large.'},413); input=JSON.parse(body); }catch{return json({message:'Invalid Rihla request.'},400);} if(!input||!validUuid(input.uuid))return json({message:'Invalid Rihla request.'},400); const fields={ read:['action','uuid'],quote:['action','uuid','amount','recipientUuid'], create:['action','uuid','amount','recipientUuid','quoteReference','requestId'], cancel:['action','uuid','number'],collect:['action','uuid','number'] }; if(!Object.hasOwn(fields,input.action)||Object.keys(input).some(key=>!fields[input.action].includes(key))) return json({message:'Invalid Rihla request.'},400); try{ const actor=await resolve(input.uuid); if(!actor)return json({message:'Link your active personal website account first.'},403); if(!bank)return json({message:'Rihla records are temporarily unavailable.'},503); if(input.action==='create'&&deps.reservationsEnabled!==true&&typeof deps.postFee!=='function') return json({message:'Rihla transfer settlement is unavailable.'},503); if(input.action==='quote'||input.action==='create'){ if(!validUuid(input.recipientUuid)||input.recipientUuid===input.uuid) return json({message:'Choose another linked player.'},400); let quote; try{quote=rihlaQuote(input.amount);}catch(error){return json({message:error.message},400);} const recipient=await resolve(input.recipientUuid); if(!recipient||recipient.id===actor.id)return json({message:'Choose another linked player.'},400); const reference=quoteReference(actor,recipient,quote); if(input.action==='quote')return json({...quote,recipientName:recipient.username,quoteReference:reference}); if(!validUuid(input.requestId)||input.quoteReference!==reference) return json({message:'The Rihla quote changed. Request a fresh quote.'},409); return await bank.transaction(async tx=>{ await ensureRihlaAccount(tx,actor.id,{clock}); const account=await tx.first('SELECT balance_minor,reserved_minor FROM ria_accounts WHERE owner_id=? FOR UPDATE',[actor.id]); const prior=await tx.first('SELECT * FROM ria_transfers WHERE jarvis_instance_id=? FOR UPDATE',[input.requestId]); if(prior){ if(prior.sender_id!==actor.id||prior.recipient_id!==recipient.id|| String(prior.amount_minor)!==quote.amountMinor||String(prior.tax_minor)!==quote.taxMinor) return json({message:'This Rihla request reference was already used.'},409); return json(transferView(prior)); } const total=BigInt(quote.totalMinor),reserved=BigInt(account.reserved_minor),balance=BigInt(account.balance_minor); if(reserved<0n||balance-reserved{ const reference=await tx.first('SELECT sender_id FROM ria_transfers WHERE transaction_number=? AND recipient_id=?', [input.number,actor.id]); if(!reference)return json({message:'Transfer unavailable.'},404); if(reference.sender_id===actor.id)throw Error('Rihla transfer must have two parties.'); for(const id of [reference.sender_id,actor.id].sort())await ensureRihlaAccount(tx,id,{clock}); const accounts=await tx.query('SELECT owner_id,balance_minor,reserved_minor FROM ria_accounts WHERE owner_id IN (?,?) ORDER BY owner_id FOR UPDATE', [reference.sender_id,actor.id]); const row=await tx.first('SELECT * FROM ria_transfers WHERE transaction_number=? AND recipient_id=? FOR UPDATE', [input.number,actor.id]); if(!row||row.sender_id!==reference.sender_id)return json({message:'Transfer unavailable.'},404); if(row.state==='paid')return json(transferView(row)); if(row.state!=='created')return json({message:'This transfer cannot be collected.'},409); const sender=accounts.find(account=>account.owner_id===row.sender_id); const recipient=accounts.find(account=>account.owner_id===actor.id); if(!sender||!recipient)throw Error('Rihla accounts are unavailable.'); const amount=BigInt(row.amount_minor),tax=BigInt(row.tax_minor),total=amount+tax; const held=BigInt(sender.reserved_minor),balance=BigInt(sender.balance_minor); const received=BigInt(recipient.balance_minor)+amount; if(amount<=0n||tax<=0n||held9223372036854775807n) throw Error('Rihla reservation cannot be settled safely.'); await deps.postFee(tx,{transferId:row.id,taxMinor:tax}); await tx.query('UPDATE ria_accounts SET balance_minor=?,reserved_minor=? WHERE owner_id=?', [String(balance-total),String(held-total),row.sender_id]); await tx.query('UPDATE ria_accounts SET balance_minor=? WHERE owner_id=?',[String(received),actor.id]); await tx.query("UPDATE ria_transfers SET state='paid' WHERE id=?",[row.id]); return json(transferView({...row,state:'paid'})); }); } if(input.action==='cancel'){ if(typeof input.number!=='string'||!/^RIA-[A-Z0-9-]{1,36}$/.test(input.number)) return json({message:'Invalid RIA reference.'},400); return await bank.transaction(async tx=>{ const account=await tx.first('SELECT reserved_minor FROM ria_accounts WHERE owner_id=? FOR UPDATE',[actor.id]); const row=await tx.first('SELECT * FROM ria_transfers WHERE transaction_number=? AND sender_id=? FOR UPDATE', [input.number,actor.id]); if(!row)return json({message:'Transfer unavailable.'},404); if(row.state==='cancelled')return json(transferView(row)); if(row.state!=='created')return json({message:'This transfer cannot be cancelled.'},409); const released=BigInt(row.amount_minor)+BigInt(row.tax_minor); if(!account||released<=0n||BigInt(account.reserved_minor){ await ensureRihlaAccount(tx,actor.id,{clock}); const account=await tx.first('SELECT account_number,balance_minor,reserved_minor FROM ria_accounts WHERE owner_id=?',[actor.id]); const rows=await tx.query(`SELECT transaction_number,sender_id,sender_name,recipient_name,amount_minor,tax_minor,state,created_at FROM ria_transfers WHERE sender_id=? OR recipient_id=? ORDER BY created_at DESC,id DESC LIMIT 25`,[actor.id,actor.id]); const pending=await tx.first("SELECT COALESCE(SUM(amount_minor),0) AS total_minor FROM ria_transfers WHERE recipient_id=? AND state='created'",[actor.id]); return {accountNo:account.account_number,balanceMinor:String(account.balance_minor),reservedMinor:String(account.reserved_minor), collectableMinor:String(pending.total_minor),transfers:rows.map(row=>{ const sent=row.sender_id===actor.id; return {number:row.transaction_number,direction:sent?'sent':'received', counterparty:sent?row.recipient_name:row.sender_name,amountMinor:String(row.amount_minor),taxMinor:String(row.tax_minor), state:row.state,createdAt:Number(row.created_at)}; })}; })); }catch{return json({message:'Rihla records are temporarily unavailable.'},503);} }; }