import {createHash} from 'node:crypto'; import {gameAuthorized,validUuid,json} from './game-link.mjs'; import {createPostbankAuthority,entityId} from './postbank-authority.mjs'; import {canDebitAccount} from './postbank-authorisations.mjs'; import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs'; import {PostbankPayments} from './postbank-payments.mjs'; import {BankError} from './postbank-service.mjs'; import {NATIVE_SERVERS} from './native-server-scope.mjs'; export const HOME_FARE_MINOR=2500,HOME_COOLDOWN_MS=15*60*1000; export const HOME_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_home_passages(id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,server VARCHAR(32) NOT NULL,destination_hash CHAR(64) NOT NULL,fingerprint CHAR(64) NOT NULL,source_id BIGINT UNSIGNED NOT NULL,target_id BIGINT UNSIGNED NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,arrived_at BIGINT NULL,INDEX home_actor(actor_id,state,arrived_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; const accountSQL='SELECT a.*,c.entity_id,e.external_key,e.active entity_active,p.state package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id'; const fail=(message,status=409)=>{throw new BankError(message,status);}; export function createHomeTravelService(bank,{resolve,authority,clock=Date.now}={}){ const payments=new PostbankPayments(bank,authority,{clock}); const view=r=>({ok:true,requestId:r.id,state:r.state,fareMinor:HOME_FARE_MINOR,cooldownUntil:r.arrived_at===null?null:Number(r.arrived_at)+HOME_COOLDOWN_MS}); async function execute(input){ const user=await resolve(input.uuid);if(!user)fail('Link your active personal website account first.',403); let unreserved=false;try{return await bank.transaction(async tx=>{ // One personal entity serialises /home on every backend, including different requests. await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[entityId('person',user.id)]); let row=await tx.first('SELECT * FROM pb_home_passages WHERE id=? FOR UPDATE',[input.requestId]); const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.uuid,input.server,input.destinationHash])).digest('hex'); if(row&&(row.actor_id!==user.id||row.fingerprint!==fingerprint))fail('This home travel reference was already used.'); if(input.action==='reserve'){ if(row)return{...view(row),replayed:true}; unreserved=true; const active=await tx.first("SELECT id FROM pb_home_passages WHERE actor_id=? AND state='pending' LIMIT 1",[user.id]);if(active)fail('Your previous home journey is still being completed. Reconnect to its server.'); const last=await tx.first("SELECT arrived_at FROM pb_home_passages WHERE actor_id=? AND state='arrived' ORDER BY arrived_at DESC LIMIT 1",[user.id]); if(last&&Number(last.arrived_at)+HOME_COOLDOWN_MS>clock())fail('Home travel is on cooldown for '+Math.ceil((Number(last.arrived_at)+HOME_COOLDOWN_MS-clock())/1000)+' seconds.'); const meta=await tx.query(accountSQL+" WHERE e.external_key=? AND e.kind='person' AND a.system_key IS NULL ORDER BY a.id",[user.id]),targetMeta=await tx.first("SELECT id FROM pb_accounts WHERE system_key='sys_game_treasury'"); if(!targetMeta)fail('The game treasury is unavailable.',503); const ids=[...meta.map(a=>a.id),targetMeta.id].sort((a,b)=>Number(a)-Number(b)),rows=await tx.query(accountSQL+' WHERE a.id IN ('+ids.map(()=>'?').join(',')+') ORDER BY a.id FOR UPDATE',ids),rights=await authority(user,{bank:tx}); const source=rows.find(a=>a.external_key===user.id&&ordinaryPaymentAccount(a)&&canDebitAccount(rights,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(HOME_FARE_MINOR)),target=rows.find(a=>String(a.id)===String(targetMeta.id)); if(!source)fail('Home travel requires 25 DM available in your central personal bank account.'); if(target?.state!=='active'||BigInt(target.balance_minor)+BigInt(HOME_FARE_MINOR)>9223372036854775807n)fail('The game treasury is unavailable.',503); row={id:input.requestId,actor_id:user.id,minecraft_uuid:input.uuid,server:input.server,destination_hash:input.destinationHash,fingerprint,source_id:source.id,target_id:target.id,state:'pending',created_at:clock(),arrived_at:null}; await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[HOME_FARE_MINOR,source.id]); await tx.query('INSERT INTO pb_home_passages(id,actor_id,minecraft_uuid,server,destination_hash,fingerprint,source_id,target_id,state,created_at,arrived_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)',Object.values(row)); return view(row); } if(!row)fail('This home journey has not been reserved.'); if(row.state!=='pending')return{...view(row),replayed:true}; const rows=await tx.query(accountSQL+' WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[row.source_id,row.target_id]),source=rows.find(a=>String(a.id)===String(row.source_id)),target=rows.find(a=>String(a.id)===String(row.target_id)); if(!source||BigInt(source.reserved_minor){const rows=await db.query("SELECT a.id,a.username,a.role FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')",[uuid]);return rows.length===1?rows[0]:null;}); const service=deps.service||(bank?createHomeTravelService(bank,{resolve,authority:createPostbankAuthority(db,{bank})}):null); return async request=>{ if(!gameAuthorized(request,settings))return json({message:'Unauthorized'},401); if(request.method!=='POST'||new URL(request.url).search||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return json({message:'A JSON home action is required.'},400); let b;try{const reader=request.body.getReader(),chunks=[];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 json({message:'Request too large'},413);}chunks.push(value);}}finally{reader.releaseLock();}b=JSON.parse(Buffer.concat(chunks).toString());}catch{return json({message:'Invalid home action'},400);} if(!b||Object.keys(b).sort().join(',')!=='action,destinationHash,requestId,server,uuid'||!['reserve','arrive','cancel'].includes(b.action)||!validUuid(b.uuid)||!validUuid(b.requestId)||!NATIVE_SERVERS.includes(b.server)||!/^[a-f0-9]{64}$/.test(b.destinationHash||''))return json({message:'Invalid home fields'},400); if(!service)return json({message:'The central bank is unavailable.'},503); try{return json(await service.execute(b));}catch(e){return json({message:e instanceof BankError?e.message:'Home travel could not be confirmed. Your journey remains available for retry.',unreserved:e instanceof BankError&&e.unreserved===true},e instanceof BankError?e.status||409:503);} }; }