forked from unimatrix/web
feat(postbank): central UUID client numbers and My Banking Information
This commit is contained in:
parent
d065aef3c8
commit
ad97dcd233
7 changed files with 94 additions and 3 deletions
|
|
@ -38,3 +38,10 @@ Website first. No game plugin code changes in this work package without later sc
|
|||
Executed the explicitly confirmed destructive reset against both authoritative stores. Gameplay: nine current balances and nine savings balances set to zero; seven non-player wallet rows removed (one faction, five official, one staff). Cleared bank ledgers, bank transfer receipts, fee accruals and savings interest state; verified empty within the reset transaction. Website registry: 23 accounts before, seven non-UUID accounts removed (one faction, six server), eight associated authorisations removed, 16 UUID-keyed account registrations retained. No site roles, game memberships, inventory or paid shop receipt records changed.
|
||||
|
||||
Private rollback copies: gameplay `/root/postbank-reset-20261113T165203Z`; website `/var/lib/dunerealms-maintenance/postbank-reset-20261113T165220Z`. These contain sensitive pre-reset data and must never be committed or published. This is a point-in-time reset, not a claim that existing game services can never create a new account or earn new currency afterward. No plugin code was modified. Seven-column desktop portal CSS is committed, not yet deployed by this pull.
|
||||
|
||||
## Client identity API
|
||||
`GET /api/bank/client` returns the signed-in user's linked-player client identity: `{ "clientNumber": "012345678901", "linked": true }` (illustrative number only). Unlinked and game-link-exempt service identities return null/false. The client number is a string so leading zeroes survive JSON/UI handling. No UUID or account override is accepted; the route rechecks the authenticated link before returning.
|
||||
|
||||
SHA-256 of a versioned, canonical UUID namespace produces a 12-digit candidate. The new additive `bank_clients` table persists assignments with unique UUID and number constraints; bounded alternate hash candidates resolve collisions without changing existing numbers. This is an identifier, not a secret or authorisation token. UUID relinking follows the linked player, not the website username. No balances or account privileges are inferred from it.
|
||||
|
||||
The Accounts menu now starts with My Banking Information: actual client identity plus explicitly planned banking-profile fields. The existing profile/mandate features are not claimed connected. Focused client/legacy bank import tests: six passed; navigation tests: three passed; Worker build passed. Local full CP cutover tests could not load absent mysql2 in this new worktree; complete-source CI is required before merge/deployment.
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import {mountImperialRevenue} from './cp-v2-imperial-revenue.mjs';
|
|||
import {mountDesignPage} from './cp-v2-design-pages.mjs';
|
||||
import {DESIGN_PAGES} from './cp-v2-design-catalog.mjs';
|
||||
import {mountBankPlaceholder} from './cp-v2-planned-pages.mjs';
|
||||
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
|
||||
export const BANK_IMPORTS=Object.freeze({
|
||||
'bank-overview':{kind:'accounts',title:'Treasury Overview'},
|
||||
'personal-bank':{kind:'accounts',title:'My Accounts'},
|
||||
|
|
@ -13,6 +14,7 @@ export const BANK_IMPORTS=Object.freeze({
|
|||
'staff-bank':{kind:'revenue',title:'Imperial Revenue'}
|
||||
});
|
||||
export function mountBankPage(host,id,{fetcher=fetch}={}){
|
||||
if(id==='bank-information')return mountBankInformation(host,{fetcher});
|
||||
const page=BANK_IMPORTS[id];
|
||||
if(page?.kind==='accounts')return mountNativeService(host,'personal-bank',{fetcher,singleHeading:true,title:page.title,wireTransfer:page.wireTransfer});
|
||||
if(page?.kind==='ledger')return mountUserCommerce(host,'transactions',{fetcher,title:page.title});
|
||||
|
|
@ -21,3 +23,16 @@ export function mountBankPage(host,id,{fetcher=fetch}={}){
|
|||
// These V1 sections were already planned-only; no lending/account-management API is invented.
|
||||
return mountBankPlaceholder(host,id,{singleHeading:true});
|
||||
}
|
||||
export function mountBankInformation(host,{fetcher=fetch}={}){
|
||||
const controller=new AbortController();let active=true;
|
||||
const identity=el('section',undefined,'cp-v2-personal-box'),number=el('strong','Loading…'),status=el('p');status.setAttribute('role','status');
|
||||
identity.append(el('h4','Client identity'),el('p','Your permanent Imperial Postbank client number.'),number,status);
|
||||
const placeholder=el('section',undefined,'cp-v2-personal-box');
|
||||
placeholder.append(el('h4','Banking profile'),el('p','PLANNED · Banking profile details are not connected yet.'));
|
||||
const list=el('dl');for(const label of ['Account holder','Banking relationship','Account authorisations','Client documents'])list.append(el('dt',label),el('dd','Not available yet'));placeholder.append(list);
|
||||
const content=el('div');content.append(identity,placeholder);
|
||||
const {root}=createCPV2Page({shellHost:host,title:'My Banking Information',description:'Your client identity and banking relationship with Imperial Postbank.',artwork:'imperial-postbank-v2.png',tabs:[{id:'information',label:'Banking information',content}]});host.replaceChildren(root);
|
||||
const timeout=setTimeout(()=>controller.abort(),15000);
|
||||
void(async()=>{try{const response=await fetcher('/api/bank/client',{credentials:'same-origin',cache:'no-store',signal:controller.signal});if(!response.ok)throw Error(response.status===401?'Sign in to view your client identity.':'Client identity is temporarily unavailable.');const data=await response.json();if(!active)return;if(data.linked===false&&data.clientNumber===null){number.textContent='Not assigned';status.textContent='A linked player UUID is required for a banking client number.';return;}if(data.linked!==true||typeof data.clientNumber!=='string'||!/^\d{12}$/.test(data.clientNumber))throw Error('Client identity could not be verified.');number.textContent=data.clientNumber;status.textContent='Confirmed by the central client service.';}catch(error){if(active){number.textContent='Unavailable';status.textContent=error.message;}}finally{clearTimeout(timeout);}})();
|
||||
return()=>{active=false;clearTimeout(timeout);controller.abort();root.remove();};
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -77,6 +77,7 @@ import {identity} from '../node/auth.mjs';
|
|||
import {createHonourRoute} from '../node/honour-route.mjs';
|
||||
import {panelBodyLimit} from './request-limits.mjs';
|
||||
import {initializeHonours} from '../node/honours.mjs';
|
||||
import {createBankClientApi} from '../node/bank-clients.mjs';
|
||||
import {createInventoryHandler,createSalesHistoryHandler} from './inventory/inventory-api.mjs';
|
||||
import {createMarketBridge} from './inventory/market-bridge.mjs';
|
||||
import {createGameLink,json} from '../node/game-link.mjs';
|
||||
|
|
@ -119,6 +120,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
const managedTransfers=createManagedTransfers(db,settings,dependencies.managedTransfers);
|
||||
const bankTransfers=createBankTransfers(db,settings,dependencies.bankTransfers);
|
||||
const banking=createBanking(db,settings,dependencies.banking);
|
||||
const bankClient=createBankClientApi(db,dependencies.bankClient);
|
||||
const v1PersonalBank=createV1PersonalBank(banking,{enabled:process.env.DUNE_API_V1_BANK_STAGING==='true'});
|
||||
const quests=createQuests(db,settings,dependencies.quests),clanShop=createClanShop(db,settings,dependencies.clanShop);
|
||||
const sso=createIntegrationSSO(db,settings);
|
||||
|
|
@ -175,6 +177,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(path==='/api/bank/official')return officialBank(request);
|
||||
if(path==='/api/bank/managed-transfer')return managedTransfers(request);
|
||||
if(path==='/api/bank/transfer-own'||path==='/api/bank/remittance')return bankTransfers(request);
|
||||
if(path==='/api/bank/client')return bankClient(request);
|
||||
if(path==='/api/bank/personal'||path==='/api/bank/staff'||path==='/api/bank/faction')return banking(request);
|
||||
if(path==='/api/v1/me/bank')return v1PersonalBank(request);
|
||||
if(path==='/api/quests'||path.startsWith('/api/quests/'))return quests(request);
|
||||
|
|
|
|||
51
website/node/bank-clients.mjs
Normal file
51
website/node/bank-clients.mjs
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
import {identity} from './auth.mjs';
|
||||
|
||||
export function canonicalClientUuid(value){
|
||||
if(typeof value!=='string'||! /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value))throw new TypeError('A canonical player UUID is required.');
|
||||
return value.toLowerCase();
|
||||
}
|
||||
export function clientNumberCandidate(uuid,attempt=0){
|
||||
uuid=canonicalClientUuid(uuid);
|
||||
if(!Number.isSafeInteger(attempt)||attempt<0||attempt>=32)throw new RangeError('Invalid client number attempt.');
|
||||
const hash=createHash('sha256').update('dunerealms:postbank:client:v1:'+uuid+':'+attempt).digest('hex');
|
||||
return (BigInt('0x'+hash)%1000000000000n).toString().padStart(12,'0');
|
||||
}
|
||||
// A truncated UUID hash alone cannot guarantee uniqueness. Persist the assigned
|
||||
// number, with independent unique keys for UUID and number, and retry collisions.
|
||||
export async function ensureBankClient(db,uuid,{candidate=clientNumberCandidate}={}){
|
||||
uuid=canonicalClientUuid(uuid);
|
||||
const find=()=>db.prepare('SELECT client_number FROM bank_clients WHERE minecraft_uuid=?').bind(uuid).first();
|
||||
const existing=await find();if(existing)return existing.client_number;
|
||||
for(let attempt=0;attempt<32;attempt++){
|
||||
const number=candidate(uuid,attempt);
|
||||
if(typeof number!=='string'||!/^\d{12}$/.test(number))throw Error('Invalid client number candidate.');
|
||||
try{
|
||||
await db.prepare('INSERT INTO bank_clients(minecraft_uuid,client_number,created_at) VALUES(?,?,?)').bind(uuid,number,Date.now()).run();
|
||||
return number;
|
||||
}catch(error){
|
||||
if(error.code!=='ER_DUP_ENTRY'&&!String(error.message).includes('UNIQUE constraint'))throw error;
|
||||
const assigned=await find();if(assigned)return assigned.client_number;
|
||||
}
|
||||
}
|
||||
throw Error('Client number allocation is temporarily unavailable.');
|
||||
}
|
||||
export function createBankClientApi(db,{authenticate=r=>identity(r,db)}={}){
|
||||
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
||||
const linked=id=>db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(id).first();
|
||||
return async request=>{
|
||||
if(request.method!=='GET')return reply({message:'Method not allowed.'},405);
|
||||
if(new URL(request.url).search)return reply({message:'Client identity does not accept account overrides.'},400);
|
||||
const user=await authenticate(request);if(!user)return reply({message:'Sign in first.'},401);
|
||||
const link=await linked(user.id);
|
||||
const policy=await db.prepare('SELECT game_link_exempt FROM site_account_policies WHERE user_id=?').bind(user.id).first();
|
||||
if(policy?.game_link_exempt)return reply({clientNumber:null,linked:false});
|
||||
if(!link?.minecraft_uuid)return reply({clientNumber:null,linked:false});
|
||||
try{
|
||||
const uuid=canonicalClientUuid(link.minecraft_uuid),number=await ensureBankClient(db,uuid);
|
||||
const current=await authenticate(request),fresh=current?.id===user.id?await linked(user.id):null;
|
||||
if(!fresh?.minecraft_uuid||canonicalClientUuid(fresh.minecraft_uuid)!==uuid)return reply({message:'Your linked account changed. Refresh your client identity.'},409);
|
||||
return reply({clientNumber:number,linked:true});
|
||||
}catch{return reply({message:'Client identity is temporarily unavailable.'},503);}
|
||||
};
|
||||
}
|
||||
|
|
@ -54,6 +54,11 @@ CREATE TABLE IF NOT EXISTS site_game_links (
|
|||
CREATE TABLE IF NOT EXISTS site_game_identities (
|
||||
minecraft_uuid CHAR(36) PRIMARY KEY, first_linked_at BIGINT NOT NULL, last_name VARCHAR(32) NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS bank_clients (
|
||||
minecraft_uuid CHAR(36) PRIMARY KEY,
|
||||
client_number CHAR(12) NOT NULL UNIQUE,
|
||||
created_at BIGINT NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS site_link_challenges (
|
||||
user_id CHAR(36) PRIMARY KEY, token_hash CHAR(64) NOT NULL UNIQUE, expires_at BIGINT NOT NULL,
|
||||
FOREIGN KEY(user_id) REFERENCES site_accounts(id)
|
||||
|
|
|
|||
10
website/tests/bank-clients.test.mjs
Normal file
10
website/tests/bank-clients.test.mjs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {LocalD1} from './d1-adapter.mjs';
|
||||
import {canonicalClientUuid,clientNumberCandidate,ensureBankClient,createBankClientApi} from '../node/bank-clients.mjs';
|
||||
const a='12345678-1234-4234-8234-123456789abc',b='22345678-1234-4234-8234-123456789abc';
|
||||
function fixture(){return new LocalD1('CREATE TABLE bank_clients(minecraft_uuid TEXT PRIMARY KEY,client_number TEXT NOT NULL UNIQUE,created_at INTEGER NOT NULL);CREATE TABLE site_game_links(user_id TEXT PRIMARY KEY,minecraft_uuid TEXT);CREATE TABLE site_account_policies(user_id TEXT PRIMARY KEY,game_link_exempt INTEGER);');}
|
||||
test('UUID derivation is canonical, deterministic and twelve decimal characters',()=>{assert.equal(canonicalClientUuid(a.toUpperCase()),a);assert.equal(clientNumberCandidate(a),clientNumberCandidate(a.toUpperCase()));assert.match(clientNumberCandidate(a),/^\d{12}$/);assert.notEqual(clientNumberCandidate(a),clientNumberCandidate(b));assert.throws(()=>clientNumberCandidate('not-a-uuid'));assert.throws(()=>clientNumberCandidate(a,32));});
|
||||
test('persistent assignments preserve leading zeroes and resolve actual unique-number collisions',async()=>{const db=fixture();try{const candidate=(_,n)=>n===0?'000000000001':'000000000002';assert.equal(await ensureBankClient(db,a,{candidate}),'000000000001');assert.equal(await ensureBankClient(db,b,{candidate}),'000000000002');assert.equal(await ensureBankClient(db,a,{candidate:()=>{throw Error('must not recompute');}}),'000000000001');const results=await Promise.all(Array.from({length:8},()=>ensureBankClient(db,a)));assert.equal(new Set(results).size,1);assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM bank_clients').get().n,2);}finally{db.close();}});
|
||||
test('client API is self-only, excludes exempt service identities, and returns no fabricated unlinked number',async()=>{const db=fixture();try{let user=null;const api=createBankClientApi(db,{authenticate:async()=>user}),get=(suffix='',method='GET')=>api(new Request('https://cp.dunerealms.com/api/bank/client'+suffix,{method}));assert.equal((await get()).status,401);user={id:'u'};assert.deepEqual(await(await get()).json(),{clientNumber:null,linked:false});assert.equal((await get('?uuid='+a)).status,400);assert.equal((await get('','POST')).status,405);db.sqlite.prepare('INSERT INTO site_game_links VALUES(?,?)').run('u',a);const data=await(await get()).json();assert.equal(data.linked,true);assert.match(data.clientNumber,/^\d{12}$/);db.sqlite.prepare('INSERT INTO site_account_policies VALUES(?,1)').run('u');assert.deepEqual(await(await get()).json(),{clientNumber:null,linked:false});}finally{db.close();}});
|
||||
test('a changed linked identity is rejected before returning the client number',async()=>{const db=fixture();try{db.sqlite.prepare('INSERT INTO site_game_links VALUES(?,?)').run('u',a);let calls=0;const api=createBankClientApi(db,{authenticate:async()=>{if(++calls===2)db.sqlite.prepare('UPDATE site_game_links SET minecraft_uuid=?').run(b);return{id:'u'};}});assert.equal((await api(new Request('https://cp.dunerealms.com/api/bank/client'))).status,409);}finally{db.close();}});
|
||||
Loading…
Reference in a new issue

Staff