From d88d96e87c7dff30ab10ef0c10e6c812ae40662a Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:40:15 +0100 Subject: [PATCH] Provision linked Lobby accounts with private credential delivery and basic banking --- website/control-panel/server.mjs | 6 +- website/node/lobby-account.mjs | 97 +++++++++++++++++ website/node/postbank-payroll-accounts.mjs | 10 +- website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md | 51 +++++++++ website/ops/configure-lobby-account.py | 53 +++++++++ website/ops/test_lobby_account_config.py | 18 +++ website/tests/lobby-account.test.mjs | 103 ++++++++++++++++++ .../tests/postbank-payroll-accounts.test.mjs | 10 +- 8 files changed, 344 insertions(+), 4 deletions(-) create mode 100644 website/node/lobby-account.mjs create mode 100644 website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md create mode 100644 website/ops/configure-lobby-account.py create mode 100644 website/ops/test_lobby_account_config.py create mode 100644 website/tests/lobby-account.test.mjs diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 090acb86..8623a3e9 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,3 +1,5 @@ +import {ensureBasicCurrentAccount} from '../node/postbank-payroll-accounts.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'; import {createGameImperialRaidsAPI} from '../node/game-imperial-raids.mjs'; @@ -304,6 +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 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; @@ -418,6 +421,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path==='/api/politics/directory'){const response=await electionDirectory(request);if(request.method==='GET'&&response.ok&&progressionRuntime){try{const visitor=await identity(request,db);if(visitor)await progressionRuntime.recordPoliticalVisit(visitor);}catch{}}return response;} if(['/api/politics/ballot/house','/api/politics/ballot/imperial','/api/politics/ballot/bene','/api/politics/ballot/church','/api/politics/ballot/guild','/api/politics/ballot/clan_delegate','/api/politics/ballot/naib_chair'].includes(path))return electionVoting(request); if(path==='/api/account/character')return characterChoice(request); + if(path==='/internal/game/lobby-account')return lobbyAccount(request); if(path==='/internal/game/house')return gameHouseSelection(request); if(path==='/internal/game/native-state')return gameNativeState(request); if(path==='/internal/game/imperial-raids')return gameImperialRaids(request); @@ -629,7 +633,7 @@ export async function startPanel(settings=process.env){ inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.')); } const bankDatabase=await openPostbankDatabase(settings); - const db=await openDatabase(settings);await db.query(WAR_MEDAL_SCHEMA);await initializeItemDesigns(db);await db.query(ITEM_GIFT_SCHEMA);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await db.query(POLITICAL_REVIEW_PUBLICATION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);await initializeHouseFaith(db);await db.query(POLITICAL_AGREEMENT_SCHEMA);await db.query(POLITICAL_COMPANY_REPLY_SCHEMA);await db.query(POLITICAL_PERSON_REPLY_SCHEMA);for(const sql of POLITICAL_CONSULTATION_SCHEMA)await db.query(sql);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeElectionRallies(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;db.paxEnabled=true;db.guildSubsidyEnabled=true;db.exchangeIncentiveEnabled=true;await initializeProgression(db);db.questAchievementsEnabled=true;await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureProgressionPolicy(db,organisationKeys,{policy:{...XP_POLICY,version:2},definitions:QUEST_DEFINITIONS.filter(d=>HOUSE_PROLOGUE_IDS.includes(d.id))});await initializeHousePrologue(db);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);await db.query(POL_DOSSIER_SCHEMA);await db.query(POL_CARGO_SCHEMA);await db.query(POL_COOP_CARGO_SCHEMA);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensureFaunaQuestPolicy(db,organisationKeys);db.faunaQuestsEnabled=true;db.smugglerContractsEnabled=true;db.polSupplyEnabled=true;db.polContractMissionsEnabled=true;await ensureBountyQuestPolicy(db,organisationKeys);db.bountyQuestsEnabled=true;await ensureSpiceUpgradeQuestPolicy(db,organisationKeys);db.spiceUpgradeEnabled=true;await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);let rihla; + const db=await openDatabase(settings);await db.query(WAR_MEDAL_SCHEMA);await initializeItemDesigns(db);await db.query(ITEM_GIFT_SCHEMA);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await db.query(POLITICAL_REVIEW_PUBLICATION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);await initializeHouseFaith(db);await db.query(POLITICAL_AGREEMENT_SCHEMA);await db.query(POLITICAL_COMPANY_REPLY_SCHEMA);await db.query(POLITICAL_PERSON_REPLY_SCHEMA);for(const sql of POLITICAL_CONSULTATION_SCHEMA)await db.query(sql);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);if(settings.LOBBY_ACCOUNT_ENABLED==='true')await db.query(LOBBY_ACCOUNT_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeElectionRallies(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;db.paxEnabled=true;db.guildSubsidyEnabled=true;db.exchangeIncentiveEnabled=true;await initializeProgression(db);db.questAchievementsEnabled=true;await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureProgressionPolicy(db,organisationKeys,{policy:{...XP_POLICY,version:2},definitions:QUEST_DEFINITIONS.filter(d=>HOUSE_PROLOGUE_IDS.includes(d.id))});await initializeHousePrologue(db);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);await db.query(POL_DOSSIER_SCHEMA);await db.query(POL_CARGO_SCHEMA);await db.query(POL_COOP_CARGO_SCHEMA);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensureFaunaQuestPolicy(db,organisationKeys);db.faunaQuestsEnabled=true;db.smugglerContractsEnabled=true;db.polSupplyEnabled=true;db.polContractMissionsEnabled=true;await ensureBountyQuestPolicy(db,organisationKeys);db.bountyQuestsEnabled=true;await ensureSpiceUpgradeQuestPolicy(db,organisationKeys);db.spiceUpgradeEnabled=true;await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);let rihla; db.imperialRaidsEnabled=settings.IMPERIAL_RAIDS_ENABLED==='true'&&settings.WAR_BRIDGE_ENABLED==='true'&&settings.POSTBANK_ENABLED==='true'; if(db.imperialRaidsEnabled){if(!bankDatabase)throw Error('Imperial raids require the existing bank and war services');await initializeImperialRaids(db);} const imperialRaidRuntime=db.imperialRaidsEnabled?createImperialRaidRuntime(db,bankDatabase,organisationKeys):null; diff --git a/website/node/lobby-account.mjs b/website/node/lobby-account.mjs new file mode 100644 index 00000000..9e891138 --- /dev/null +++ b/website/node/lobby-account.mjs @@ -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);} + }; +} diff --git a/website/node/postbank-payroll-accounts.mjs b/website/node/postbank-payroll-accounts.mjs index e95e0713..dd8b11ad 100644 --- a/website/node/postbank-payroll-accounts.mjs +++ b/website/node/postbank-payroll-accounts.mjs @@ -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}; } diff --git a/website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md b/website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md new file mode 100644 index 00000000..dfbca471 --- /dev/null +++ b/website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md @@ -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 ` +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. diff --git a/website/ops/configure-lobby-account.py b/website/ops/configure-lobby-account.py new file mode 100644 index 00000000..36e12c50 --- /dev/null +++ b/website/ops/configure-lobby-account.py @@ -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() diff --git a/website/ops/test_lobby_account_config.py b/website/ops/test_lobby_account_config.py new file mode 100644 index 00000000..cff109db --- /dev/null +++ b/website/ops/test_lobby_account_config.py @@ -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() diff --git a/website/tests/lobby-account.test.mjs b/website/tests/lobby-account.test.mjs new file mode 100644 index 00000000..1a3adf39 --- /dev/null +++ b/website/tests/lobby-account.test.mjs @@ -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); +}); diff --git a/website/tests/postbank-payroll-accounts.test.mjs b/website/tests/postbank-payroll-accounts.test.mjs index e90e106e..7a3ffea4 100644 --- a/website/tests/postbank-payroll-accounts.test.mjs +++ b/website/tests/postbank-payroll-accounts.test.mjs @@ -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/); +});