Provision linked Lobby accounts with private credential delivery and basic banking

This commit is contained in:
unimatrixgit 2026-12-02 11:40:15 +01:00
commit d88d96e87c
8 changed files with 344 additions and 4 deletions

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,97 @@
import {randomBytes,randomUUID,createHash,createCipheriv,createDecipheriv,scrypt as rawScrypt,timingSafeEqual} from 'node:crypto';
import {promisify} from 'node:util';
import {validUuid} from './game-link.mjs';
const scrypt=promisify(rawScrypt),digest=v=>createHash('sha256').update(v).digest('hex');
const fault=(message,status=409)=>Object.assign(Error(message),{status});
export const LOBBY_ACCOUNT_SCHEMA=`CREATE TABLE IF NOT EXISTS site_lobby_account_provisions (
minecraft_uuid CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,minecraft_name VARCHAR(32) NOT NULL,
account_id CHAR(36) NOT NULL,credential_hash CHAR(64) NOT NULL,ciphertext TEXT,
created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,delivered_at BIGINT,
FOREIGN KEY(account_id) REFERENCES site_accounts(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
export const LOBBY_PLACEHOLDER_EMAIL='no_reply@dunerealms.com';
const ttl=7*86400000;
function seal(password,key,binding){
const iv=randomBytes(12),cipher=createCipheriv('aes-256-gcm',key,iv);cipher.setAAD(Buffer.from(binding));
const data=Buffer.concat([cipher.update(password,'utf8'),cipher.final()]);
return [iv,cipher.getAuthTag(),data].map(x=>x.toString('base64url')).join('.');
}
function unseal(value,key,binding){
const [iv,tag,data]=value.split('.').map(x=>Buffer.from(x,'base64url'));
const cipher=createDecipheriv('aes-256-gcm',key,iv);cipher.setAAD(Buffer.from(binding));cipher.setAuthTag(tag);
return Buffer.concat([cipher.update(data),cipher.final()]).toString('utf8');
}
export function createLobbyAccountService(db,{encryptionKey,clock=Date.now,onProvisioned=async()=>{}}={}){
if(!/^[a-f0-9]{64}$/.test(encryptionKey||''))throw Error('Lobby account encryption key is unavailable');
const key=Buffer.from(encryptionKey,'hex');
async function execute(input){
if(input.schema!==1||!validUuid(input.uuid)||!validUuid(input.requestId)||!['provision','ack'].includes(input.action)||input.action==='provision'&&!/^[A-Za-z0-9_.-]{1,32}$/.test(input.name||''))throw fault('Invalid lobby account request',400);
const {uuid,requestId,action}=input,now=clock(),binding=uuid+':'+requestId;
const base={ok:true,schema:1,action,requestId,uuid};
// Hash before entering the transaction; no password is logged or put in audit details.
const password=action==='provision'?randomBytes(24).toString('base64url'):null;
const salt=password?randomBytes(16).toString('hex'):null;
const hash=password?(await scrypt(password,salt,64)).toString('hex'):null;
let readyId;
const result=await db.transaction(async tx=>{
const prior=await tx.first('SELECT * FROM site_lobby_account_provisions WHERE minecraft_uuid=? FOR UPDATE',[uuid]);
if(prior){
if(prior.request_id!==requestId||action==='provision'&&prior.minecraft_name!==input.name)throw fault('The original provisioning reference is required');
const account=await tx.first('SELECT a.id,a.username,a.password_hash,l.minecraft_uuid FROM site_accounts a LEFT JOIN site_game_links l ON l.user_id=a.id WHERE a.id=? FOR UPDATE',[prior.account_id]);
if(!account||account.minecraft_uuid!==uuid)throw fault('The account link needs manual review');
if(action==='ack'){
await tx.query('UPDATE site_lobby_account_provisions SET ciphertext=NULL,delivered_at=COALESCE(delivered_at,?) WHERE minecraft_uuid=? AND request_id=?',[now,uuid,requestId]);
return {...base,state:'delivered'};
}
if(prior.delivered_at!==null)return {...base,state:'delivered',username:account.username};
if(digest(account.password_hash)!==prior.credential_hash||now>=Number(prior.expires_at)||!prior.ciphertext){
await tx.query('UPDATE site_lobby_account_provisions SET ciphertext=NULL WHERE minecraft_uuid=?',[uuid]);
return {...base,state:'recovery_required',username:account.username};
}
readyId=account.id;
return {...base,state:'created',username:account.username,password:unseal(prior.ciphertext,key,binding)};
}
if(action==='ack')throw fault('No matching provisioning reference');
const reused=await tx.first('SELECT minecraft_uuid FROM site_lobby_account_provisions WHERE request_id=? FOR UPDATE',[requestId]);
if(reused)throw fault('Provisioning reference conflict');
const linked=await tx.first('SELECT a.id,a.username,a.password_hash,a.role FROM site_game_links l JOIN site_accounts a ON a.id=l.user_id WHERE l.minecraft_uuid=? FOR UPDATE',[uuid]);
if(linked)return {...base,state:'existing',username:linked.username};
if(await tx.first('SELECT minecraft_uuid FROM site_game_identities WHERE minecraft_uuid=? FOR UPDATE',[uuid]))return {...base,state:'manual_link_required',username:''};
let username=input.name.toLowerCase().replace(/[^a-z0-9_]/g,'_');if(username.length<3)username='mc_'+username;
if(await tx.first('SELECT id FROM site_accounts WHERE username=? FOR UPDATE',[username]))username=username.slice(0,15)+'_'+uuid.replaceAll('-','').slice(0,16);
if(await tx.first('SELECT id FROM site_accounts WHERE username=? FOR UPDATE',[username]))throw fault('Website username needs manual review');
const id=randomUUID();
await tx.query('INSERT INTO site_accounts(id,username,display_name,password_salt,password_hash,role,created_at) VALUES(?,?,?,?,?,?,?)',[id,username,input.name,salt,hash,'user',now]);
await tx.query('INSERT INTO player_profiles(user_id,display_name,minecraft_name,discord_name,created_at,updated_at) VALUES(?,?,?,?,?,?)',[id,input.name,input.name,'',now,now]);
await tx.query('INSERT INTO site_profiles(user_id,bio,public_info,socials_json,updated_at) VALUES(?,?,?,?,?)',[id,'DuneRealms player '+input.name+'.','','{}',now]);
await tx.query('INSERT INTO site_game_links(user_id,minecraft_uuid,minecraft_name,linked_at) VALUES(?,?,?,?)',[id,uuid,input.name,now]);
await tx.query('INSERT INTO site_game_identities(minecraft_uuid,first_linked_at,last_name) VALUES(?,?,?)',[uuid,now,input.name]);
await tx.query('INSERT INTO site_contact_emails(user_id,address,verified_at) VALUES(?,?,NULL)',[id,LOBBY_PLACEHOLDER_EMAIL]);
await tx.query('INSERT INTO site_first_login(user_id,password_changed,created_at) VALUES(?,0,?)',[id,now]);
await tx.query('INSERT INTO site_lobby_account_provisions(minecraft_uuid,request_id,minecraft_name,account_id,credential_hash,ciphertext,created_at,expires_at,delivered_at) VALUES(?,?,?,?,?,?,?,?,NULL)',[uuid,requestId,input.name,id,digest(hash),seal(password,key,binding),now,now+ttl]);
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),id,'lobby-account-provisioned',JSON.stringify({requestId,uuid,source:'lobby',ageDeclared:false,placeholderEmail:true}),now]);
readyId=id;
return {...base,state:'created',username,password};
});
// 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});
return result;
}
return {execute};
}
export function createLobbyAccountAPI(db,settings={},deps={}){
const enabled=settings.LOBBY_ACCOUNT_ENABLED==='true';
const token=settings.LOBBY_ACCOUNT_TOKEN||'',validToken=/^[A-Za-z0-9_-]{43,128}$/.test(token);
const service=enabled&&validToken?deps.service||createLobbyAccountService(db,{encryptionKey:settings.LOBBY_ACCOUNT_ENCRYPTION_KEY,onProvisioned:deps.onProvisioned}):null;
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store','Pragma':'no-cache'}});
return async request=>{
const auth=request.headers.get('authorization')||'';
if(!service||!timingSafeEqual(Buffer.from(digest(auth)),Buffer.from(digest('Bearer '+token))))return reply({message:'Unauthorized'},401);
if(request.method!=='POST'||new URL(request.url).search||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'Invalid lobby account request'},400);
let b;try{const reader=request.body.getReader(),parts=[];let bytes=0;try{while(true){const {done,value}=await reader.read();if(done)break;bytes+=value.length;if(bytes>1024){await reader.cancel();return reply({message:'Request too large'},413);}parts.push(value);}}finally{reader.releaseLock();}b=JSON.parse(Buffer.concat(parts).toString());}catch{return reply({message:'Invalid lobby account request'},400);}
if(!b||Array.isArray(b)||Object.keys(b).sort().join(',')!==(b.action==='ack'?'action,requestId,schema,uuid':'action,name,requestId,schema,uuid'))return reply({message:'Invalid lobby account fields'},400);
try{return reply(await service.execute(b));}catch(e){return reply({message:e.status?e.message:'Account setup is temporarily unavailable. Retry the original reference.'},e.status||503);}
};
}

View file

@ -6,6 +6,12 @@ import {REGISTRY_ACTOR} from './postbank-registry.mjs';
// Internal payroll operation. The caller supplies a freshly verified staff
// recipient and runs this inside the payroll transaction, never a public route.
export async function ensurePayrollCurrentAccount(tx,recipient,{now=Date.now(),makeId=randomUUID}={}){
return ensureBasicCurrentAccount(tx,recipient,{now,makeId,source:'payroll'});
}
// First-join provisioning shares the same zero-balance basic product. It never
// bypasses an existing blocked current account or records player acceptance.
export async function ensureBasicCurrentAccount(tx,recipient,{now=Date.now(),makeId=randomUUID,source}={}){
if(!['payroll','lobby'].includes(source))throw Error('A reviewed basic-account source is required.');
if(!recipient?.id||!recipient.username)throw Error('A verified payroll recipient is required.');
const id=entityId('person',recipient.id);
await tx.query("INSERT INTO pb_entities(id,kind,external_key,display_name,active,created_at) VALUES(?,'person',?,?,1,?) ON DUPLICATE KEY UPDATE id=id",[id,recipient.id,recipient.username,now]);
@ -27,11 +33,11 @@ export async function ensurePayrollCurrentAccount(tx,recipient,{now=Date.now(),m
if(!client)throw Error('Personal client number could not be allocated.');
}
const packageId=makeId();
await tx.query("INSERT INTO pb_packages(id,client_number,package_key,monthly_minor,terms_version,accepted_by,accepted_at,state) VALUES(?,?,'pb_start',0,'payroll-provisioned-basic-v1',?,?,'active')",[packageId,client.client_number,REGISTRY_ACTOR,now]);
await tx.query(`INSERT INTO pb_packages(id,client_number,package_key,monthly_minor,terms_version,accepted_by,accepted_at,state) VALUES(?,?,'pb_start',0,'${source}-provisioned-basic-v1',?,?,'active')`,[packageId,client.client_number,REGISTRY_ACTOR,now]);
const result=await tx.query("INSERT INTO pb_accounts(client_number,package_id,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,?,'108',?,0,0,'active',?)",[client.client_number,packageId,recipient.username+' · Current',now]);
const accountId=String(result.insertId);
await tx.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber('108',Number(accountId)),accountId]);
await tx.query('INSERT INTO pb_activations(entity_id,package_id) VALUES(?,?) ON DUPLICATE KEY UPDATE entity_id=entity_id',[id,packageId]);
await tx.query("INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,'payroll_account_provisioned',?,?,?)",[makeId(),REGISTRY_ACTOR,id,JSON.stringify({recipientId:recipient.id,accountId,packageKey:'pb_start',typeCode:'108',openingBalanceMinor:0}),now]);
await tx.query(`INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,'${source}_account_provisioned',?,?,?)`,[makeId(),REGISTRY_ACTOR,id,JSON.stringify({recipientId:recipient.id,accountId,packageKey:'pb_start',typeCode:'108',openingBalanceMinor:0}),now]);
return {accountId,created:true,entityId:id};
}

View file

@ -0,0 +1,51 @@
# Lobby first-join accounts
New authenticated Lobby players receive an ordinary website account linked to
their real Java or Floodgate UUID. The standalone Lobby plugin owns first-join
detection and player-only delivery; planets do not install it. Existing links
and passwords are retained. Historical unlinked identities need manual linking.
Website-name collisions use a deterministic UUID suffix, never account takeover.
The website skips the age question without inserting a declaration. It stores
`no_reply@dunerealms.com` as an unverified placeholder, never a verified mailbox.
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.
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.
## Private protocol
`POST /internal/game/lobby-account` uses a dedicated Lobby bearer, not the shared
game bearer. Exact schema-1 provision fields are `action`, `requestId`, `uuid`,
`name`, `schema`; ack omits `name`. Client fields cannot choose an account ID,
role, House, email, age, bank plan or balance. The server fixes these defaults.
The plugin stores the original UUID/name/request before its first network call.
Only `created` contains the generated password. Retries with the original binding
return that same password until delivery acknowledgement, password change or
seven-day expiry. AES-GCM ciphertext is bound to the UUID/request and stored in
the private central database. Acknowledgement erases it. Expired or changed
credentials require recovery and are never silently reset. Responses and audit
records never log credentials. The player's client may retain its own received DM.
## Release
Both web and plugin changes require their exact canonical CI and normal merge.
Run the immutable release's `ops/configure-lobby-account.py --source <commit>`
to inspect, then add `--apply` to prepare private server configuration. It changes
only three Lobby-account environment settings. It does not restart the website.
Use the existing staged website promotion so schema creation and readiness happen
before the new plugin activates. Never put its generated private material in Git
or a public artifact.
Transfer the private token directly to `/etc/dunerealms/lobby-account.token` on
Lobby, mode 0600 owned by its service user. The encryption key remains web-only.
Use the plugin's Lobby-only installer and verify authenticated modern Velocity
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.

View file

@ -0,0 +1,53 @@
"""Prepare private Lobby provisioning credentials for a reviewed website release."""
import argparse
import json
import os
from pathlib import Path
import re
import secrets
import tempfile
ENV=Path('/home/dunerealms/.config/dunerealms.env')
STATE=Path('/var/lib/dunerealms-operations/lobby-account')
KEYS={'LOBBY_ACCOUNT_ENABLED','LOBBY_ACCOUNT_TOKEN','LOBBY_ACCOUNT_ENCRYPTION_KEY'}
def configured(text,token,key):
if not re.fullmatch(r'[A-Za-z0-9_-]{43}',token) or not re.fullmatch(r'[a-f0-9]{64}',key):
raise ValueError('Invalid private provisioning material')
lines=[line for line in text.splitlines() if not re.match(r'^\s*(?:export\s+)?(?:'+ '|'.join(KEYS)+r')\s*=',line)]
return '\n'.join(lines)+f'\nLOBBY_ACCOUNT_ENABLED=true\nLOBBY_ACCOUNT_TOKEN={token}\nLOBBY_ACCOUNT_ENCRYPTION_KEY={key}\n'
def atomic(path,data,uid,gid):
fd,name=tempfile.mkstemp(prefix='.lobby-account-',dir=path.parent)
try:
with os.fdopen(fd,'w') as stream:
os.fchmod(stream.fileno(),0o600);os.fchown(stream.fileno(),uid,gid)
stream.write(data);stream.flush();os.fsync(stream.fileno())
os.replace(name,path)
finally:
Path(name).unlink(missing_ok=True)
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--source',required=True);p.add_argument('--apply',action='store_true');a=p.parse_args()
if not re.fullmatch(r'[a-f0-9]{40}',a.source) or Path(__file__).resolve().parents[1]!=Path('/home/dunerealms/apps/dunerealms/releases/ci-'+a.source):
raise ValueError('Run the exact immutable website release helper')
if ENV.resolve()!=ENV or not ENV.is_file() or ENV.stat().st_mode&0o077:
raise ValueError('Existing private website environment required')
if not a.apply:
print(json.dumps({'applied':False,'source':a.source,'scope':'Lobby account provisioning only','secretsExposed':False}));return
STATE.mkdir(parents=True,exist_ok=True,mode=0o700)
if STATE.resolve()!=STATE or STATE.stat().st_mode&0o077:raise ValueError('Private canonical state directory required')
material=STATE/'credentials.json'
if material.exists():
if material.is_symlink() or material.stat().st_mode&0o077:raise ValueError('Private credential file required')
s=json.loads(material.read_text())
else:
s={'token':secrets.token_urlsafe(32),'key':secrets.token_hex(32)}
fd=os.open(material,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
with os.fdopen(fd,'w') as f:json.dump(s,f)
current=ENV.read_text();updated=configured(current,s['token'],s['key']);st=ENV.stat()
atomic(STATE/'lobby-account.token',s['token']+'\n',0,0)
if current!=updated:atomic(ENV,updated,st.st_uid,st.st_gid)
print(json.dumps({'applied':True,'source':a.source,'websiteRestartRequired':True,'privateTokenFile':str(STATE/'lobby-account.token'),'secretsExposed':False}))
if __name__=='__main__':main()

View file

@ -0,0 +1,18 @@
import importlib.util
from pathlib import Path
import unittest
s=importlib.util.spec_from_file_location('lobby_config',Path(__file__).with_name('configure-lobby-account.py'))
m=importlib.util.module_from_spec(s);s.loader.exec_module(m)
class ConfigTests(unittest.TestCase):
def test_only_three_settings_change_and_replay_is_stable(self):
old='# private config\nDB_PASSWORD=untouched\nLOBBY_ACCOUNT_ENABLED=false\nexport LOBBY_ACCOUNT_TOKEN=old\nOTHER=true\n'
result=m.configured(old,'a'*43,'b'*64)
self.assertIn('DB_PASSWORD=untouched',result);self.assertIn('OTHER=true',result)
self.assertNotIn('=old',result);self.assertEqual(result,m.configured(result,'a'*43,'b'*64))
self.assertEqual(result.count('LOBBY_ACCOUNT_TOKEN='),1)
def test_invalid_material_cannot_enter_environment(self):
with self.assertRaises(ValueError):m.configured('',"x\nBAD=true",'b'*64)
if __name__=='__main__':unittest.main()

View file

@ -0,0 +1,103 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {DatabaseSync} from 'node:sqlite';
import {scryptSync,randomUUID} from 'node:crypto';
import {writeFile} from 'node:fs/promises';
import {LOBBY_ACCOUNT_SCHEMA,createLobbyAccountService,createLobbyAccountAPI} from '../node/lobby-account.mjs';
const key='ab'.repeat(32),token='X'.repeat(43),uuid='5195da0c-ba50-4f82-baa7-1c99a73c810b';
function fixture(){
const sql=new DatabaseSync(':memory:');sql.exec(`
CREATE TABLE site_accounts(id TEXT PRIMARY KEY,username TEXT UNIQUE,display_name TEXT,password_salt TEXT,password_hash TEXT,role TEXT,created_at INTEGER);
CREATE TABLE site_game_links(user_id TEXT PRIMARY KEY,minecraft_uuid TEXT UNIQUE,minecraft_name TEXT,linked_at INTEGER);
CREATE TABLE site_game_identities(minecraft_uuid TEXT PRIMARY KEY,first_linked_at INTEGER,last_name TEXT);
CREATE TABLE player_profiles(user_id TEXT PRIMARY KEY,display_name TEXT,minecraft_name TEXT,discord_name TEXT,created_at INTEGER,updated_at INTEGER);
CREATE TABLE site_profiles(user_id TEXT PRIMARY KEY,bio TEXT,public_info TEXT,socials_json TEXT,updated_at INTEGER);
CREATE TABLE site_contact_emails(user_id TEXT PRIMARY KEY,address TEXT,verified_at INTEGER);
CREATE TABLE site_first_login(user_id TEXT PRIMARY KEY,password_changed INTEGER,created_at INTEGER);
CREATE TABLE site_age_declarations(user_id TEXT PRIMARY KEY,age_band TEXT,declared_at INTEGER);
CREATE TABLE account_audit(id TEXT PRIMARY KEY,actor_id TEXT,action TEXT,details TEXT,created_at INTEGER);
${LOBBY_ACCOUNT_SCHEMA.replace(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4','')}`);
const clean=s=>s.replace(/ FOR UPDATE/g,'');
const tx={async first(s,v=[]){return sql.prepare(clean(s)).get(...v)||null;},async query(s,v=[]){return sql.prepare(clean(s)).run(...v);}};
const db={async transaction(work){sql.exec('BEGIN');try{const r=await work(tx);sql.exec('COMMIT');return r;}catch(e){sql.exec('ROLLBACK');throw e;}}};
let now=1000000;const service=createLobbyAccountService(db,{encryptionKey:key,clock:()=>now});
const input={schema:1,action:'provision',requestId:randomUUID(),uuid,name:'Torch5907'};
return {sql,db,service,input,advance:ms=>now+=ms};
}
test('new account, verified game link and encrypted replay commit together; age undeclared and placeholder unverified',async()=>{
const f=fixture();try{
const a=await f.service.execute(f.input),b=await f.service.execute(f.input);
assert.equal(a.state,'created');assert.equal(a.username,'torch5907');assert.equal(a.password,b.password);assert.equal(a.password.length,32);
const account=f.sql.prepare('SELECT * FROM site_accounts').get();assert.equal(account.role,'user');assert.equal(scryptSync(a.password,account.password_salt,64).toString('hex'),account.password_hash);
assert.equal(f.sql.prepare('SELECT minecraft_uuid FROM site_game_links').get().minecraft_uuid,uuid);
const email=f.sql.prepare('SELECT * FROM site_contact_emails').get();assert.equal(email.address,'no_reply@dunerealms.com');assert.equal(email.verified_at,null);
assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM site_age_declarations').get().n,0);
assert.equal(f.sql.prepare('SELECT password_changed FROM site_first_login').get().password_changed,0);
const raw=f.sql.prepare('SELECT * FROM site_lobby_account_provisions').get();assert.ok(!JSON.stringify(raw).includes(a.password));assert.ok(!f.sql.prepare('SELECT details FROM account_audit').get().details.includes(a.password));
if(process.env.LOBBY_ACCOUNT_WIRE_OUTPUT){
const ack=await f.service.execute({schema:1,action:'ack',uuid,requestId:f.input.requestId});
const delivered=await f.service.execute(f.input);
await writeFile(process.env.LOBBY_ACCOUNT_WIRE_OUTPUT,JSON.stringify({syntheticTestOnly:true,request:f.input,responses:{created:a,replayed:b,ack,delivered}},null,2));
}
}finally{f.sql.close();}
});
test('ack is durable, input-bound and erases password ciphertext; no credential replay after delivery',async()=>{
const f=fixture();try{
await f.service.execute(f.input);
await assert.rejects(f.service.execute({...f.input,requestId:randomUUID()}),/original/);
await assert.rejects(f.service.execute({...f.input,name:'Other'}),/original/);
const ack={schema:1,action:'ack',uuid,requestId:f.input.requestId};assert.equal((await f.service.execute(ack)).state,'delivered');assert.equal((await f.service.execute(ack)).state,'delivered');
assert.equal(f.sql.prepare('SELECT ciphertext FROM site_lobby_account_provisions').get().ciphertext,null);
assert.equal((await f.service.execute(f.input)).password,undefined);
}finally{f.sql.close();}
});
test('existing links are not reset, renamed or reassigned; historical unlinked identity requires manual linking',async()=>{
const f=fixture();try{
f.sql.exec("INSERT INTO site_accounts VALUES('existing','original','Original','salt','unchanged','user',1);INSERT INTO site_game_links VALUES('existing','"+uuid+"','Torch5907',1)");
const r=await f.service.execute(f.input);assert.equal(r.state,'existing');assert.equal(r.password,undefined);assert.equal(r.username,'original');assert.equal(f.sql.prepare('SELECT password_hash FROM site_accounts').get().password_hash,'unchanged');
f.sql.exec('DELETE FROM site_game_links');f.sql.prepare('INSERT INTO site_game_identities VALUES(?,1,?)').run(uuid,'Torch5907');
assert.equal((await f.service.execute(f.input)).state,'manual_link_required');assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM site_accounts').get().n,1);
}finally{f.sql.close();}
});
test('username collision and Bedrock punctuation never take over an existing website account',async()=>{
const f=fixture();try{
f.sql.exec("INSERT INTO site_accounts VALUES('existing','torch5907','Original','salt','unchanged','user',1)");
const r=await f.service.execute(f.input);assert.match(r.username,/^torch5907_5195da0cba504f82$/);assert.equal(f.sql.prepare("SELECT password_hash FROM site_accounts WHERE id='existing'").get().password_hash,'unchanged');
const bedrock=await f.service.execute({...f.input,uuid:randomUUID(),requestId:randomUUID(),name:'.A'});assert.equal(bedrock.username,'mc__a');
}finally{f.sql.close();}
});
test('password change and expiry suppress old credentials without resetting the password',async()=>{
for(const expired of [false,true]){const f=fixture();try{
await f.service.execute(f.input);if(expired)f.advance(7*86400000);else f.sql.exec("UPDATE site_accounts SET password_hash='changed'");
const r=await f.service.execute(f.input);assert.equal(r.state,'recovery_required');assert.equal(r.password,undefined);assert.equal(f.sql.prepare('SELECT ciphertext FROM site_lobby_account_provisions').get().ciphertext,null);
}finally{f.sql.close();}}
});
test('failed link insertion rolls the entire new account back',async()=>{
const f=fixture();try{
f.sql.exec("CREATE TRIGGER broken_link BEFORE INSERT ON site_game_links BEGIN SELECT RAISE(ABORT,'link unavailable');END");
await assert.rejects(f.service.execute(f.input),/link unavailable/);
for(const name of ['site_accounts','player_profiles','site_profiles','site_lobby_account_provisions','account_audit'])assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM '+name).get().n,0);
}finally{f.sql.close();}
});
test('bank outage retains the account and original secret; retry completes readiness without another account',async()=>{
const f=fixture();let unavailable=true,actor;
const service=createLobbyAccountService(f.db,{encryptionKey:key,clock:()=>1000000,onProvisioned:async user=>{actor=user;if(unavailable)throw Error('Bank unavailable');}});
try{
await assert.rejects(service.execute(f.input),/Bank unavailable/);
assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM site_accounts').get().n,1);
const ciphertext=f.sql.prepare('SELECT ciphertext FROM site_lobby_account_provisions').get().ciphertext;
unavailable=false;const r=await service.execute(f.input);assert.equal(r.state,'created');assert.equal(r.username,actor.username);assert.ok(actor.id);
assert.equal(f.sql.prepare('SELECT ciphertext FROM site_lobby_account_provisions').get().ciphertext,ciphertext);
assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM site_accounts').get().n,1);
}finally{f.sql.close();}
});
test('dedicated bearer, schema, exact fields and body bounds protect the Lobby-only endpoint',async()=>{
let called=0;const settings={LOBBY_ACCOUNT_ENABLED:'true',LOBBY_ACCOUNT_TOKEN:token};
const api=createLobbyAccountAPI(null,settings,{service:{async execute(b){called++;return {ok:true,...b,state:'existing',username:'old'};}}});
const request=(body,auth=token)=>new Request('https://cp.dunerealms.com/internal/game/lobby-account',{method:'POST',headers:{Authorization:'Bearer '+auth,'Content-Type':'application/json'},body:JSON.stringify(body)});
assert.equal((await api(request({action:'provision'},'shared-game-token'))).status,401);
assert.equal((await api(request({schema:1,action:'provision',uuid,requestId:randomUUID(),name:'Player',server:'arrakis'}))).status,400);
assert.equal((await api(request({blob:'x'.repeat(1100)}))).status,413);assert.equal(called,0);
const r=await api(request({schema:1,action:'provision',uuid,requestId:randomUUID(),name:'Player'}));assert.equal(r.status,200);assert.equal(r.headers.get('cache-control'),'no-store');assert.equal(called,1);
assert.equal((await createLobbyAccountAPI(null,{})(request({}))).status,401);
});

View file

@ -1,6 +1,6 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {ensurePayrollCurrentAccount} from '../node/postbank-payroll-accounts.mjs';
import {ensurePayrollCurrentAccount,ensureBasicCurrentAccount} from '../node/postbank-payroll-accounts.mjs';
const recipient={id:'f3ffda37-01e4-41ea-b89d-fbeda82e453e',username:'unimatrix999'};
function fixture(accounts=[],hasClient=true){
const writes=[];return {writes,
@ -39,3 +39,11 @@ test('an inactive package cannot be bypassed by reusing its otherwise active acc
await assert.rejects(ensurePayrollCurrentAccount(tx,recipient),/needs review/);
assert.equal(tx.writes.some(w=>w.sql.includes('INSERT INTO pb_packages')),false);
});
test('Lobby provisioning uses a free basic current account with honest source attribution and no ledger credit',async()=>{
const tx=fixture([],false),r=await ensureBasicCurrentAccount(tx,recipient,{source:'lobby'});
assert.equal(r.created,true);assert.match(tx.writes.find(w=>w.sql.includes('INSERT INTO pb_packages')).sql,/lobby-provisioned-basic-v1/);
assert.match(tx.writes.find(w=>w.sql.includes('INSERT INTO pb_packages')).sql,/'pb_start',0/);
assert.match(tx.writes.find(w=>w.sql.includes('INSERT INTO pb_audit')).sql,/lobby_account_provisioned/);
assert.equal(tx.writes.some(w=>w.sql.includes('pb_entries')||w.sql.includes('pb_orders')),false);
await assert.rejects(ensureBasicCurrentAccount(fixture(),recipient,{source:'untrusted'}),/reviewed/);
});