From 44c82e767aca5395a98098a8c30de0e4473e0d39 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:53:31 +0100 Subject: [PATCH] Give newly provisioned Lobby players a once-only 1000 DM starting budget --- website/control-panel/server.mjs | 4 +- website/node/lobby-account.mjs | 2 +- website/node/lobby-starting-budget.mjs | 43 ++++++++++++++ website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md | 12 +++- website/tests/lobby-starting-budget.test.mjs | 61 ++++++++++++++++++++ 5 files changed, 117 insertions(+), 5 deletions(-) create mode 100644 website/node/lobby-starting-budget.mjs create mode 100644 website/tests/lobby-starting-budget.test.mjs diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 8623a3e9..4347a019 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,4 +1,4 @@ -import {ensureBasicCurrentAccount} from '../node/postbank-payroll-accounts.mjs'; +import {provisionLobbyStartingBank} from '../node/lobby-starting-budget.mjs'; import {LOBBY_ACCOUNT_SCHEMA,createLobbyAccountAPI} from '../node/lobby-account.mjs'; import {initializeImperialRaids} from '../node/imperial-raid-orders.mjs'; import {createImperialRaidRuntime} from '../node/imperial-raid-runtime.mjs'; @@ -306,7 +306,7 @@ export function createPanel(db,settings={},dependencies={}){ const progressionRuntime=dependencies.progressionRuntime||(dependencies.organisationKeys?createProgressionRuntime(db,dependencies.bankDatabase||null,dependencies.organisationKeys):null); const progression=createProgressionAPI(db,{...progressionRuntime,origin}); const polRuntime=dependencies.polProgressionRuntime||(dependencies.organisationKeys?createPOLProgressionRuntime(db,dependencies.organisationKeys,{bank:dependencies.bankDatabase||null}):null); - const lobbyAccount=createLobbyAccountAPI(db,settings,{onProvisioned:async user=>{if(!dependencies.bankDatabase)throw Error('The basic bank account service is unavailable');await dependencies.bankDatabase.transaction(tx=>ensureBasicCurrentAccount(tx,user,{source:'lobby'}));await ensureRihlaAccount(dependencies.bankDatabase,user.id);if(dependencies.organisationKeys)await ensureOriginalKeys(dependencies.organisationKeys,user.id);}}); + const lobbyAccount=createLobbyAccountAPI(db,settings,{onProvisioned:async user=>{if(!dependencies.bankDatabase)throw Error('The basic bank account service is unavailable');await provisionLobbyStartingBank(dependencies.bankDatabase,user);await ensureRihlaAccount(dependencies.bankDatabase,user.id);if(dependencies.organisationKeys)await ensureOriginalKeys(dependencies.organisationKeys,user.id);}}); const gameHouseSelection=createHouseSelectionAPI(db,dependencies.organisationKeys,settings,{readBriefing:createGameBriefing({personal:progressionRuntime,pol:polRuntime,bank:dependencies.bankDatabase||null,authority:createPostbankAuthority(db,{bank:dependencies.bankDatabase||null}),organisations:actor=>readGameMemberships(db,actor),identity:actor=>readGamePublicIdentity(db,actor),wars:actor=>readWarStatistics(db,dependencies.bankDatabase||null,actor)})}); const gameStarter=dependencies.organisationKeys?createGameStarterKit(db,dependencies.organisationKeys,settings):null; const gameResearch=dependencies.organisationKeys?createGameResearch(db,dependencies.organisationKeys):null; diff --git a/website/node/lobby-account.mjs b/website/node/lobby-account.mjs index 9e891138..87e6b754 100644 --- a/website/node/lobby-account.mjs +++ b/website/node/lobby-account.mjs @@ -76,7 +76,7 @@ export function createLobbyAccountService(db,{encryptionKey,clock=Date.now,onPro // The existing bank has its own transaction. An outage retains this exact // provisioning reference and encrypted password; retry never creates a user // twice or sends credentials before the zero-balance account is ready. - if(readyId)await onProvisioned({id:readyId,username:result.username}); + if(readyId)await onProvisioned({id:readyId,username:result.username,uuid}); return result; } return {execute}; diff --git a/website/node/lobby-starting-budget.mjs b/website/node/lobby-starting-budget.mjs new file mode 100644 index 00000000..492a9cb3 --- /dev/null +++ b/website/node/lobby-starting-budget.mjs @@ -0,0 +1,43 @@ +import {createHash,randomUUID} from 'node:crypto'; +import {validUuid} from './game-link.mjs'; +import {ensureBasicCurrentAccount} from './postbank-payroll-accounts.mjs'; +import {REGISTRY_ACTOR} from './postbank-registry.mjs'; + +export const LOBBY_STARTING_MINOR=100000n; +export function lobbyBudgetId(uuid){ + if(!validUuid(uuid))throw Error('A verified Minecraft identity is required'); + const h=createHash('sha256').update('lobby-starting-budget-v1:'+uuid).digest('hex'); + return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32); +} +// Only the first-join provisioning callback calls this policy. No caller-chosen +// amount, source account or recipient account is admitted by the game endpoint. +export async function provisionLobbyStartingBank(bank,recipient,{clock=Date.now}={}){ + if(!validUuid(recipient?.id)||!validUuid(recipient?.uuid)||!recipient.username)throw Error('Verified first-join account required'); + return bank.transaction(async tx=>{ + const ready=await ensureBasicCurrentAccount(tx,recipient,{source:'lobby',now:clock()}); + const issuer=await tx.first("SELECT id FROM pb_accounts WHERE system_key='sys_bank_capital_issuer'"); + if(!issuer)throw Error('The starting-budget reserve is unavailable'); + const rows=await tx.query('SELECT a.*,c.entity_id,e.external_key,e.kind,e.active AS entity_active,p.state AS package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[issuer.id,ready.accountId]); + const source=rows.find(a=>String(a.id)===String(issuer.id)),target=rows.find(a=>String(a.id)===ready.accountId); + if(!source||source.system_key!=='sys_bank_capital_issuer'||source.state!=='active'||source.type_code!=='979'||!target||target.system_key||target.state!=='active'||target.package_state!=='active'||target.kind!=='person'||target.external_key!==recipient.id||Number(target.entity_active)!==1||!['102','108'].includes(target.type_code))throw Error('The starting-budget account requires review'); + const id=lobbyBudgetId(recipient.uuid),fingerprint=createHash('sha256').update(JSON.stringify(['lobby-starting-budget-v1',recipient.uuid,recipient.id,String(source.id),String(target.id),String(LOBBY_STARTING_MINOR)])).digest('hex'); + const prior=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[id]); + if(prior){ + if(prior.fingerprint!==fingerprint||prior.state!=='posted'||prior.mode!=='grant'||String(prior.amount_minor)!==String(LOBBY_STARTING_MINOR)||String(prior.source_id)!==String(source.id)||String(prior.target_id)!==String(target.id))throw Error('The original starting-budget receipt requires review'); + const entries=await tx.query('SELECT account_id,amount_minor FROM pb_entries WHERE order_id=? ORDER BY account_id',[id]); + if(entries.length!==2||!entries.some(e=>String(e.account_id)===String(source.id)&&BigInt(e.amount_minor)===-LOBBY_STARTING_MINOR)||!entries.some(e=>String(e.account_id)===String(target.id)&&BigInt(e.amount_minor)===LOBBY_STARTING_MINOR))throw Error('The starting-budget ledger requires review'); + return {accountId:ready.accountId,paymentId:id,replayed:true}; + } + const debit=BigInt(source.balance_minor)-LOBBY_STARTING_MINOR,credit=BigInt(target.balance_minor)+LOBBY_STARTING_MINOR; + // The existing capital issuer is the bank's issuance account. It may have a + // negative reserve balance, using the same balanced grant policy as bank grants. + if(debit< -9223372036854775808n||credit>9223372036854775807n)throw Error('Starting-budget balance limit reached'); + const now=clock(); + await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at,posted_at) VALUES(?,?,?,?,?,?,?,'grant','posted',?,?)",[id,REGISTRY_ACTOR,source.id,target.id,fingerprint,String(LOBBY_STARTING_MINOR),'Lobby starting budget ยท 1000 DM',now,now]); + await tx.query('UPDATE pb_accounts SET balance_minor=? WHERE id=?',[String(debit),source.id]); + await tx.query('UPDATE pb_accounts SET balance_minor=? WHERE id=?',[String(credit),target.id]); + for(const [a,amount,balance] of [[source,-LOBBY_STARTING_MINOR,debit],[target,LOBBY_STARTING_MINOR,credit]])await tx.query('INSERT INTO pb_entries(order_id,account_id,amount_minor,balance_after_minor,created_at) VALUES(?,?,?,?,?)',[id,a.id,String(amount),String(balance),now]); + await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),REGISTRY_ACTOR,'lobby_starting_budget',ready.entityId,JSON.stringify({paymentId:id,uuid:recipient.uuid,accountId:recipient.id,amountDM:'1000.00',policy:'lobby-starting-budget-v1'}),now]); + return {accountId:ready.accountId,paymentId:id,replayed:false}; + }); +} diff --git a/website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md b/website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md index ab615240..8c279053 100644 --- a/website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md +++ b/website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md @@ -11,8 +11,13 @@ The website skips the age question without inserting a declaration. It stores Initial website sign-in still requires changing the generated password and accepting the terms. The usual House selector remains the player's choice. -The central service provides a free `pb_start` current account (108), zero opening -balance and no monthly charge, through the existing basic-account provisioner. +The central service provides a free `pb_start` current account (108), with no +monthly charge, through the existing basic-account provisioner. It then posts +exactly 1,000 DM starting funds from the existing capital issuer using a balanced +bank grant. Its immutable payment ID is derived from the verified Minecraft UUID; +retries, reconnects and replacement website identities cannot issue it again. +The account and two ledger entries commit in one bank transaction. A partial +receipt, changed recipient or blocked account requires review, not another grant. Existing blocked accounts are not bypassed. It also readies the normal Rihla identity and founding keys. A bank outage retains the exact website account and request; the plugin retries without creating another user or changing a balance. @@ -50,3 +55,6 @@ forwarding, backend loopback binding, current source/artifact hashes and startup No retained JAR, resource pack, world or planet installation changes are required. Use disposable protocol fixtures for credentials/bank tests; do not create real players or payment transactions just for release checks. + +This starting budget applies only to newly provisioned first-join accounts. It +does not top up existing player accounts or repeat prior one-off console grants. diff --git a/website/tests/lobby-starting-budget.test.mjs b/website/tests/lobby-starting-budget.test.mjs new file mode 100644 index 00000000..2ebd39f2 --- /dev/null +++ b/website/tests/lobby-starting-budget.test.mjs @@ -0,0 +1,61 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {DatabaseSync} from 'node:sqlite'; +import {randomUUID} from 'node:crypto'; +import {provisionLobbyStartingBank,lobbyBudgetId} from '../node/lobby-starting-budget.mjs'; +const actor={id:'11111111-1111-4111-a111-111111111111',uuid:'22222222-2222-4222-a222-222222222222',username:'new_player'}; +function fixture(){ + const sql=new DatabaseSync(':memory:');sql.exec(` + CREATE TABLE pb_entities(id TEXT PRIMARY KEY,kind TEXT,external_key TEXT,display_name TEXT,active INTEGER,created_at INTEGER); + CREATE TABLE pb_clients(client_number TEXT PRIMARY KEY,entity_id TEXT UNIQUE,created_at INTEGER); + CREATE TABLE pb_packages(id TEXT PRIMARY KEY,client_number TEXT,package_key TEXT,monthly_minor INTEGER,terms_version TEXT,accepted_by TEXT,accepted_at INTEGER,state TEXT); + CREATE TABLE pb_accounts(id INTEGER PRIMARY KEY AUTOINCREMENT,client_number TEXT,package_id TEXT,type_code TEXT,display_name TEXT,account_number TEXT,balance_minor INTEGER DEFAULT 0,reserved_minor INTEGER DEFAULT 0,state TEXT,created_at INTEGER,system_key TEXT UNIQUE); + CREATE TABLE pb_activations(entity_id TEXT PRIMARY KEY,package_id TEXT); + CREATE TABLE pb_orders(id TEXT PRIMARY KEY,actor_id TEXT,source_id INTEGER,target_id INTEGER,fingerprint TEXT,amount_minor INTEGER,memo TEXT,mode TEXT,state TEXT,created_at INTEGER,posted_at INTEGER); + CREATE TABLE pb_entries(order_id TEXT,account_id INTEGER,amount_minor INTEGER,balance_after_minor INTEGER,created_at INTEGER,UNIQUE(order_id,account_id)); + CREATE TABLE pb_audit(id TEXT PRIMARY KEY,actor_id TEXT,action TEXT,entity_id TEXT,details TEXT,created_at INTEGER); + INSERT INTO pb_accounts(id,type_code,display_name,state,system_key) VALUES(1,'979','Capital issuer','active','sys_bank_capital_issuer');`); + const clean=s=>s.replace(/ FOR UPDATE/g,'').replace(/ON DUPLICATE KEY UPDATE id=id/,'ON CONFLICT(id) DO NOTHING').replace(/ON DUPLICATE KEY UPDATE entity_id=entity_id/,'ON CONFLICT(entity_id) DO NOTHING'); + const tx={async first(s,v=[]){return sql.prepare(clean(s)).get(...v)||null;},async query(s,v=[]){const q=sql.prepare(clean(s));if(/^SELECT/.test(s))return q.all(...v);const r=q.run(...v);return {insertId:r.lastInsertRowid};}}; + const bank={async transaction(work){sql.exec('BEGIN');try{const r=await work(tx);sql.exec('COMMIT');return r;}catch(e){sql.exec('ROLLBACK');throw e;}}}; + return {sql,bank}; +} +test('new basic account receives exactly 1000 DM with two balanced entries; rejoin/retry cannot credit it twice',async()=>{ + const f=fixture();try{ + const a=await provisionLobbyStartingBank(f.bank,actor),b=await provisionLobbyStartingBank(f.bank,actor); + assert.equal(a.replayed,false);assert.equal(b.replayed,true);assert.equal(a.paymentId,b.paymentId); + const p=f.sql.prepare('SELECT * FROM pb_packages').get();assert.equal(p.package_key,'pb_start');assert.equal(p.monthly_minor,0); + const current=f.sql.prepare('SELECT * FROM pb_accounts WHERE id=?').get(a.accountId);assert.equal(current.type_code,'108');assert.equal(current.balance_minor,100000);assert.equal(current.reserved_minor,0); + assert.equal(f.sql.prepare('SELECT balance_minor FROM pb_accounts WHERE id=1').get().balance_minor,-100000); + assert.equal(f.sql.prepare('SELECT COUNT(*) n,SUM(amount_minor) total FROM pb_entries').get().n,2);assert.equal(f.sql.prepare('SELECT SUM(amount_minor) total FROM pb_entries').get().total,0); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_orders').get().n,1); + }finally{f.sql.close();} +}); +test('failed ledger entry rolls back account creation and grant together; exact retry posts once',async()=>{ + const f=fixture();try{ + f.sql.exec("CREATE TRIGGER broken_credit BEFORE INSERT ON pb_entries WHEN NEW.amount_minor>0 BEGIN SELECT RAISE(ABORT,'posting unavailable');END"); + await assert.rejects(provisionLobbyStartingBank(f.bank,actor),/posting unavailable/); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_packages').get().n,0);assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_orders').get().n,0);assert.equal(f.sql.prepare('SELECT balance_minor FROM pb_accounts WHERE id=1').get().balance_minor,0); + f.sql.exec('DROP TRIGGER broken_credit');assert.equal((await provisionLobbyStartingBank(f.bank,actor)).replayed,false); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_entries').get().n,2); + }finally{f.sql.close();} +}); +test('same Minecraft UUID cannot claim another starting budget with a different website account',async()=>{ + const f=fixture();try{ + await provisionLobbyStartingBank(f.bank,actor); + await assert.rejects(provisionLobbyStartingBank(f.bank,{...actor,id:randomUUID()}),/original starting-budget/); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_packages').get().n,1);assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_orders').get().n,1); + }finally{f.sql.close();} +}); +test('blocked current account and incomplete prior receipt fail closed without replacement or another grant',async()=>{ + const f=fixture();try{ + const a=await provisionLobbyStartingBank(f.bank,actor);f.sql.prepare("UPDATE pb_accounts SET state='blocked' WHERE id=?").run(a.accountId); + await assert.rejects(provisionLobbyStartingBank(f.bank,actor),/needs review/); + f.sql.prepare("UPDATE pb_accounts SET state='active' WHERE id=?").run(a.accountId);f.sql.exec('DELETE FROM pb_entries WHERE amount_minor>0'); + await assert.rejects(provisionLobbyStartingBank(f.bank,actor),/ledger requires review/); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_orders').get().n,1); + }finally{f.sql.close();} +}); +test('payment reference is bound to the Minecraft UUID and cannot be chosen by the client',()=>{ + assert.equal(lobbyBudgetId(actor.uuid),lobbyBudgetId(actor.uuid));assert.notEqual(lobbyBudgetId(actor.uuid),lobbyBudgetId(randomUUID()));assert.throws(()=>lobbyBudgetId('arbitrary'),/verified/); +}); -- 2.53.0