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'; import {currentGuildSurcharge,currentGuildDiscount,standardGuildFare} from './guild-tariff-policy.mjs'; export const HOME_FARE_MINOR=2500,HOME_COOLDOWN_MS=15*60*1000; export const RESCUE_FARE_MINOR=100000,RESCUE_COOLDOWN_MS=24*60*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,guildFare=10000}={}){ const payments=new PostbankPayments(bank,authority,{clock}); const view=(r,fare,cooldown)=>({ok:true,requestId:r.id,state:r.state,fareMinor:fare,cooldownUntil:r.arrived_at===null?null:Number(r.arrived_at)+cooldown}); async function execute(input){ const rescue=input.mode==='rescue'; const worldHome=input.mode==='world'; let fare=rescue?RESCUE_FARE_MINOR:HOME_FARE_MINOR; const cooldown=rescue||worldHome?RESCUE_COOLDOWN_MS:HOME_COOLDOWN_MS; const serviceName=rescue?'Emergency rescue':worldHome?'World home travel':'Home travel'; // Keep old journal rows and their fingerprints readable during rolling upgrades. let server=rescue?input.server+':rescue':input.server; 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]); if(worldHome&&row?.server.startsWith(input.server+':w')){ server=row.server; fare=Number.parseInt(server.slice(input.server.length+2),36); }else if(worldHome&&!row){ fare=typeof guildFare==='function'?await guildFare(user,input.uuid,clock()):guildFare; if(!Number.isSafeInteger(fare)||fare<1||fare>100000000)fail('The Guild tariff requires review.',503); server=input.server+':w'+fare.toString(36); }else if(worldHome||row&&row.server!==server){ fail('This home travel reference was already used.'); } if(!Number.isSafeInteger(fare)||fare<1||fare>100000000)fail('Home fare is unavailable.',503); const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.uuid,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,fare,cooldown),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' AND CASE WHEN server LIKE '%:rescue' THEN 'rescue' WHEN server LIKE '%:w%' THEN 'world' ELSE 'normal' END=? ORDER BY arrived_at DESC LIMIT 1",[user.id,input.mode||'normal']); if(last&&Number(last.arrived_at)+cooldown>clock())fail(serviceName+' is on cooldown for '+Math.ceil((Number(last.arrived_at)+cooldown-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(fare)),target=rows.find(a=>String(a.id)===String(targetMeta.id)); if(!source)fail(serviceName+' requires '+(fare/100)+' DM available in your central personal bank account.'); if(target?.state!=='active'||BigInt(target.balance_minor)+BigInt(fare)>9223372036854775807n)fail('The game treasury is unavailable.',503); row={id:input.requestId,actor_id:user.id,minecraft_uuid:input.uuid,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=?',[fare,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,fare,cooldown); } if(!row)fail('This home journey has not been reserved.'); if(row.state!=='pending')return{...view(row,fare,cooldown),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 guildFare=async(user,uuid,now)=>{ const selection=await first(db,'SELECT faction FROM site_character_choices WHERE user_id=? AND LOWER(minecraft_uuid)=?',[user.id,uuid.toLowerCase()]); const [percent,reduction]=await Promise.all([currentGuildSurcharge(db,now),currentGuildDiscount(db,selection?.faction,now)]); return standardGuildFare(Number(settings.GUILD_FARE_MINOR||10000),percent,reduction); }; const service=deps.service||(bank?createHomeTravelService(bank,{resolve,authority:createPostbankAuthority(db,{bank}),guildFare}):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(',')!==(['rescue','world'].includes(b.mode)?'action,destinationHash,mode,requestId,server,uuid':'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);} }; }