import {createHash,randomUUID} from 'node:crypto'; import {claimTariffs,CLAIM_REVENUE_SYSTEM_KEY,CLAIM_TARIFF_VERSION} from '../control-panel/public/cp-v2/cp-v2-claim-tariffs.mjs'; export class ClaimCommandError extends Error{constructor(message,status=409){super(message);this.status=status;}} const uuid=s=>typeof s==='string'&&/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(s); export function nextClaimUpgrade(state,charter='basic'){ const rows=claimTariffs(state.kind),index=rows.findIndex(r=>r.code===state.tier),next=rows[index+1]; if(index<0)throw new ClaimCommandError('Current claim tier is unavailable.'); if(!next)return null; if(state.pendingUpgrade)return {...next,blocked:'An upgrade is awaiting game/payment confirmation.'}; if(next.stage==='Keyed'&&!['original','royal'].includes(charter))return {...next,blocked:'Redeem your original organisation key before unlocking Keyed claim tiers.'}; if(next.stage==='Royal'&&charter!=='royal')return {...next,blocked:'A verified Royal appointment is required.'}; return next; } // One command contract for web and future authenticated game callers. Persistence // and bank/WorldGuard coordination belong to adapters, not to either user interface. export function createClaimCommandService({store,adapter}){ return { async read(context){const state=await store.read(context);return {...state,next:nextClaimUpgrade(state,context.charter),tariffVersion:CLAIM_TARIFF_VERSION,provider:adapter.name,simulation:adapter.simulation===true};}, async upgrade(context,id,input){ if(!uuid(id)||!input||input.action!=='claim.tier.upgrade'||input.confirmed!==true||!uuid(input.requestId)||!Number.isSafeInteger(input.expectedRevision)||input.expectedRevision<1||typeof input.targetTier!=='string'||Object.keys(input).some(k=>!['action','confirmed','requestId','expectedRevision','targetTier','tariffVersion','expectedUnlockMinor'].includes(k)))throw new ClaimCommandError('Review and confirm a valid claim upgrade.',400); return store.exclusive(context,id,async state=>{ const fingerprint=createHash('sha256').update(JSON.stringify([context.userId,context.organisationId,id,input.action,input.targetTier,input.expectedRevision,input.tariffVersion,input.expectedUnlockMinor])).digest('hex'),prior=state.receipts[input.requestId]; if(prior){if(prior.fingerprint!==fingerprint)throw new ClaimCommandError('This request reference belongs to another command.');return {...prior.result,replayed:true};} if(state.pendingUpgrade)throw new ClaimCommandError('An upgrade is already pending confirmation.'); if(state.revision!==input.expectedRevision)throw new ClaimCommandError('The Home Block changed. Refresh before upgrading.'); const next=nextClaimUpgrade(state,context.charter);if(!next||next.code!==input.targetTier)throw new ClaimCommandError('Only the next sequential claim tier can be unlocked.'); if(input.tariffVersion!==CLAIM_TARIFF_VERSION||input.expectedUnlockMinor!==next.unlockMinor)throw new ClaimCommandError('The tariff quote changed. Refresh and review the new price.'); if(next.blocked)throw new ClaimCommandError(next.blocked,403); // The adapter must authorise payment, protect the region and settle once. A // real adapter may return pending; never report pending as a completed upgrade. const applied=await adapter.executeUpgrade({state:structuredClone(state),context,next,requestId:input.requestId,revenueSystemKey:CLAIM_REVENUE_SYSTEM_KEY}); if(!['applied','pending'].includes(applied.status))throw new ClaimCommandError('The game/payment adapter did not confirm an upgrade.'); const result={ok:true,status:applied.status,simulation:adapter.simulation===true,homeBlock:applied.state,paidMinor:applied.status==='applied'?next.unlockMinor:0}; if(applied.status==='applied')Object.assign(state,applied.state);else state.pendingUpgrade={requestId:input.requestId,targetTier:next.code}; state.receipts[input.requestId]={fingerprint,result};return result; }); } }; } export function createClaimSimulation(){ const states=new Map(),locks=new Map(),limit=500,ttl=2*60*60*1000; const identity=c=>c.userId+':'+c.organisationId; const fresh=c=>{const state={id:randomUUID(),organisationId:c.organisationId,name:c.name,kind:c.kind,tier:claimTariffs(c.kind)[0].code,revision:1,capacity:1,usedChunks:1,worldUuid:'00000000-0000-4000-8000-000000000001',serverKey:'simulation-only',position:{x:8,y:64,z:8},testCreditMinor:100000,testTaxMinor:0,worldguardRegions:[],receipts:{},expiresAt:Date.now()+ttl,claimedChunks:[{x:0,z:0}]};state.worldguardRegions=[{id:'fixture_'+state.id.replaceAll('-','')+'_0_0',type:'cuboid',min:{x:0,y:-64,z:0},max:{x:15,y:319,z:15}}];return state;}; const stateFor=c=>{const key=identity(c);let state=states.get(key);if(state&&state.expiresAt<=Date.now()){states.delete(key);state=null;}if(!state){for(const [k,v]of states)if(v.expiresAt<=Date.now())states.delete(k);if(states.size>=limit)throw new ClaimCommandError('The simulation is busy. Try again later.',503);state=fresh(c);states.set(key,state);}return state;}; const visible=state=>{const {receipts,expiresAt,...snapshot}=state;return structuredClone(snapshot);}; const store={async read(c){return visible(stateFor(c));},async exclusive(c,id,work){const key=identity(c),previous=locks.get(key)||Promise.resolve();let release;const held=new Promise(r=>{release=r;});const queued=previous.then(()=>held);locks.set(key,queued);await previous;try{const state=stateFor(c);if(state.id!==id||state.organisationId!==c.organisationId)throw new ClaimCommandError('Home Block access denied.',403);const result=await work(state);return structuredClone(result);}finally{release();if(locks.get(key)===queued)locks.delete(key);}}}; const adapter={name:'fake-worldguard-and-bank',simulation:true,async executeUpgrade({state,next,revenueSystemKey}){ if(state.testCreditMinor{ return {id:'fixture_'+state.id.replaceAll('-','')+'_'+x+'_'+z,type:'cuboid',min:{x:x*16,y:-64,z:z*16},max:{x:x*16+15,y:319,z:z*16+15}};}); return {status:'applied',state:{...visible(state),tier:next.code,capacity:next.chunks,revision:state.revision+1,testCreditMinor:state.testCreditMinor-next.unlockMinor,testTaxMinor:state.testTaxMinor+next.unlockMinor,revenueSystemKey,worldguardRegions}}; }}; return createClaimCommandService({store,adapter}); }