web/website/node/game-guild.mjs
unimatrixgit 633cb376e9
All checks were successful
DuneRealms Web CI / web (push) Successful in 5m6s
Keep Guild routes selectable before scheduled boarding
2026-12-05 14:07:55 +01:00

147 lines
26 KiB
JavaScript

import {createBankTradePolicy} from './world-trade-governance.mjs';
import {tradeWorld,TRADE_WORLDS} from '../control-panel/public/world-trade-policy.mjs';
import {createGuildSubsidies,verifyGuildSubsidy} from './guild-subsidy.mjs';
import {currentGuildSurcharge,currentGuildDiscount,standardGuildFare} from './guild-tariff-policy.mjs';
import {createHash} from 'node:crypto';
import {gameAuthorized,validUuid,json} from './game-link.mjs';
import {boardingOpen} from './game-organisation-policy.mjs';
import {createPostbankAuthority} from './postbank-authority.mjs';
import {createGuildPassageLedger} from './guild-passage-ledger.mjs';
import {paidTariff,effectiveTrips,classifyRoute,BOUNTY_MULTIPLIER} from './travel-tariff.mjs';
import {createNativeHoldingCheck} from './travel-holdings.mjs';
import {createTravelBountyClaims,TRAVEL_BOUNTY_CLAIM_SCHEMA} from './travel-bounty-claims.mjs';
export {TRAVEL_BOUNTY_CLAIM_SCHEMA};
export const TRAVEL_OPEN_PASSAGE_SCHEMA="CREATE TABLE IF NOT EXISTS pb_guild_open_passages(id CHAR(36) PRIMARY KEY,source_world VARCHAR(32) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
import {createOwnedSmugglerRoutes} from './owned-smuggler-routes.mjs';
import {createOwnedSmugglerPassages} from './owned-smuggler-passages.mjs';
import {validOwnedSmugglerRequest} from './owned-smuggler-request.mjs';
import {BankError} from './postbank-service.mjs';
import {createPOLActivityEvents} from './pol-activity-events.mjs';
import {createPersonalActivityEvents} from './personal-activity-events.mjs';
import {hasOrganisationPassage} from './imperial-organisation-passage.mjs';
import {hasImperialPassage} from './imperial-passage.mjs';
import {activeSmugglerPermit} from './smuggler-passage.mjs';
import {housePrologueState} from './house-prologue.mjs';
export const GUILD_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_guild_passages(id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,house_key CHAR(36) NOT NULL,house_version INT NOT NULL,destination VARCHAR(32) NOT NULL,fare_minor BIGINT NOT NULL,source_id BIGINT UNSIGNED NOT NULL,target_id BIGINT UNSIGNED NOT NULL,fingerprint CHAR(64) NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,arrived_at BIGINT NULL,reported_at BIGINT NULL,INDEX guild_pending(minecraft_uuid,state,expires_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
export const SMUGGLER_PASSAGE_SCHEMA="CREATE TABLE IF NOT EXISTS pb_smuggler_passages(id CHAR(36) PRIMARY KEY,permit_key CHAR(36) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
const routes={atreides:'caladan',harkonnen:'giedi_prime',corrino:'kaitain',ordos:'sigma_draconis_iv',fremen:'arrakis'};
const fail=(message,status=409)=>{throw new BankError(message,status);};
export const TRAVEL_LADDER_SCHEMA="CREATE TABLE IF NOT EXISTS pb_travel_ladder(actor_id CHAR(36) PRIMARY KEY,trips INT NOT NULL,last_paid_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
export const TRAVEL_BOUNTY_SCHEMA="CREATE TABLE IF NOT EXISTS pb_travel_bounties(id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,traveller VARCHAR(64) NOT NULL,world VARCHAR(32) NOT NULL,fare_minor BIGINT NOT NULL,amount_minor BIGINT NOT NULL,state VARCHAR(12) NOT NULL,created_at BIGINT NOT NULL,claimed_by CHAR(36) NULL,claimed_at BIGINT NULL,claim_request CHAR(36) NULL UNIQUE,INDEX travel_bounty_open(minecraft_uuid,state,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
export function createGuildService(bank,{authority,resolve,allowArrakis=async()=>false,recordArrival=async()=>{},allowJourney=async()=>true,clock=Date.now,fareMinor=10000,surcharge=async()=>0,discount=async()=>0,openTravel=false,holdingOnWorld=async()=>false,allowSmuggling=null,smugglerFareMinor=fareMinor,prologueReady=async()=>true,subsidies=null,routeBindings=false,homeRoutes=null,authorityForStore=null}={}){
if(!Number.isSafeInteger(fareMinor)||fareMinor<1||fareMinor>100000000||!Number.isSafeInteger(smugglerFareMinor)||smugglerFareMinor<1||smugglerFareMinor>100000000)throw Error('Invalid Guild fare');
const ledger=createGuildPassageLedger(bank,{authority,clock,subsidies}),{funds,release,reserve,settle,payout}=ledger;
async function quotedFare(user,store=bank,lock=false){const percent=await surcharge(clock()),reduction=await discount(user.faction,clock());const normal=standardGuildFare(fareMinor,percent,reduction);if(normal===null)fail('The Guild tariff requires review.',503);const offer=subsidies?await subsidies.quote(store,normal,reduction,lock):null;return {price:offer?.price??normal,offer};}
const view=r=>({requestId:r.id,destination:r.destination,state:r.state,fareMinor:Number(r.fare_minor),expiresAt:Number(r.expires_at)});
const readyForTravel=async(user,uuid,store=bank)=>await prologueReady(user,uuid)||!!await store.first("SELECT id FROM pb_guild_passages WHERE actor_id=? AND minecraft_uuid=? AND state='arrived' LIMIT 1",[user.id,uuid]);
const allowed=async(user,destination)=>!!routes[user?.faction]&&(openTravel?Object.values(routes).includes(destination):destination===routes[user.faction]||destination==='arrakis'&&await allowArrakis(user.faction,user));
async function expire(){const expired=await bank.transaction(async tx=>{const rows=await tx.query("SELECT * FROM pb_guild_passages WHERE state='pending' AND expires_at<=? ORDER BY id LIMIT 25 FOR UPDATE",[clock()]);for(const r of rows)await release(tx,r);return rows.length;});if(subsidies)await subsidies.expire();return expired;}
// ---- Open travel: race world and Lobby are free, every other world is paid and carries a bounty ----
async function tariff(user,uuid,destination,store,lock=false){
const decree=destination==='arrakis'&&await allowArrakis(user.faction,user),route=classifyRoute({destination,raceWorld:routes[user.faction],decree});
if(route.free)return{free:true,reason:route.reason,fareMinor:0,bountyMinor:0};
const row=await store.first('SELECT trips,last_paid_at FROM pb_travel_ladder WHERE actor_id=?'+(lock?' FOR UPDATE':''),[user.id]);
const trips=effectiveTrips(row?.trips??0,row?.last_paid_at??null,clock());
return{free:false,reason:'paid',...paidTariff({trips,reduced:await holdingOnWorld(user,uuid,destination,{fresh:lock})})};
}
async function recordTrip(tx,r,user){
const fare=Number(r.fare_minor);if(fare<1)return; // a free passage carries no bounty and does not move the ladder
const now=clock(),row=await tx.first('SELECT trips,last_paid_at FROM pb_travel_ladder WHERE actor_id=? FOR UPDATE',[user.id]),trips=effectiveTrips(row?.trips??0,row?.last_paid_at??null,now)+1;
if(row)await tx.query('UPDATE pb_travel_ladder SET trips=?,last_paid_at=? WHERE actor_id=?',[trips,now,user.id]);else await tx.query('INSERT INTO pb_travel_ladder(actor_id,trips,last_paid_at) VALUES(?,?,?)',[user.id,trips,now]);
await tx.query("INSERT INTO pb_travel_bounties(id,actor_id,minecraft_uuid,traveller,world,fare_minor,amount_minor,state,created_at) VALUES(?,?,?,?,?,?,?,'open',?)",[r.id,user.id,r.minecraft_uuid,String(user.username).slice(0,64),r.destination,fare,fare*BOUNTY_MULTIPLIER,now]);
}
async function quoteOpen(uuid,sourceWorld){
await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403);
const ready=await readyForTravel(user,uuid),open=[],catalog=[];
for(const world of TRADE_WORLDS){
const t=await tariff(user,uuid,world.id,bank),journey=await allowJourney(sourceWorld,world.id,bank,false),source=ready&&journey&&t.fareMinor>0?await funds(bank,user,t.fareMinor):null;
const reason=!ready?'Complete your House Prologue first.':world.id===tradeWorld(sourceWorld)?'Already on this world.':tradeWorld(sourceWorld)!=='lobby'?'Board ordinary passages from the Guild Lobby.':!journey?'The Spacing Guild has embargoed this route.':t.fareMinor>0&&!source?'Not enough available Dunemarks.':'';
if(!reason)open.push(world.id);
catalog.push({server:world.id,name:world.name,available:!reason,reason,fareMinor:t.fareMinor,free:t.free,...(t.free?{freeReason:t.reason}:{bountyMinor:t.bountyMinor,reduced:t.reduced,trip:t.trip})});
}
const home=catalog.find(r=>r.server===routes[user.faction]);
return{ok:true,openTravel:true,destination:routes[user.faction],destinations:open,routes:catalog,fareMinor:home?.fareMinor??0,affordable:open.length>0,...(!ready?{prologueRequired:true}:{})};
}
const bountyClaim=createTravelBountyClaims(bank,{resolve,clock,payout,enabled:()=>openTravel});
async function quote(uuid,sourceWorld='lobby'){
if(openTravel)return quoteOpen(uuid,sourceWorld);
await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403);
const ready=await readyForTravel(user,uuid),{price,offer}=await quotedFare(user),source=ready?await funds(bank,user,price):null,open=[],catalog=[];
for(const world of TRADE_WORLDS){const lawful=await allowed(user,world.id),journey=lawful&&await allowJourney(sourceWorld,world.id,bank,false);if(ready&&journey)open.push(world.id);
const reason=!ready?'Complete your House Prologue first.':world.id===tradeWorld(sourceWorld)?'Already on this world.':!lawful?'Your House has no Imperial passage for this destination.':!journey?'The Spacing Guild has embargoed this route.':!source?'Not enough available Dunemarks.':'';
catalog.push({server:world.id,name:world.name,available:!reason,reason,fareMinor:price});
}
return {ok:true,destination:routes[user.faction],destinations:[...new Set([routes[user.faction],...open])].filter(w=>open.includes(w)),routes:catalog,fareMinor:price,...(offer?{subsidyMinor:offer.amount}:{}),affordable:!!source,account:source?.account_number||null,...(!ready?{prologueRequired:true}:{})};
}
async function smugglerPermit(user,uuid,source,tx,lock=false,destination='arrakis'){
if(!allowSmuggling||!tradeWorld(source)||(!routeBindings&&(source!=='lobby'||destination!=='arrakis'))||source===destination||!routes[user?.faction]||!await readyForTravel(user,uuid))return null;
if(await allowed(user,destination)&&await allowJourney(source,destination,tx,lock))return null;return allowSmuggling(user,uuid,clock());
}
async function quoteSmuggler(uuid,sourceWorld='lobby'){
await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403);
const ready=await readyForTravel(user,uuid),currentPermit=allowSmuggling&&ready?await allowSmuggling(user,uuid,clock()):null,source=ready?await funds(bank,user,smugglerFareMinor):null,catalog=[];
for(const world of TRADE_WORLDS){const lawful=await allowed(user,world.id)&&await allowJourney(sourceWorld,world.id,bank,false),eligible=!!allowSmuggling&&!!tradeWorld(sourceWorld)&&ready&&world.id!==tradeWorld(sourceWorld)&&!lawful&&(routeBindings||sourceWorld==='lobby'&&world.id==='arrakis'),permit=eligible?currentPermit:null;
const reason=!ready?'Complete your House Prologue first.':world.id===tradeWorld(sourceWorld)?'Already on this world.':lawful?'Use ordinary Guild passage for this lawful route.':!eligible?'This smuggler route is unavailable.':!permit?'Meet Esmar for a current personal smuggler permission.':!source?'Not enough available Dunemarks.':'';
catalog.push({server:world.id,name:world.name,available:!reason,reason,fareMinor:smugglerFareMinor,eligible,allowed:!!permit,affordable:!!permit&&!!source,permitExpiresAt:permit?.expiresAt||null});
}
const legacy=catalog.find(r=>r.server==='arrakis');return {ok:true,eligible:legacy.eligible,allowed:legacy.allowed,permitExpiresAt:legacy.permitExpiresAt,fareMinor:smugglerFareMinor,affordable:legacy.affordable,keyId:user.keyId,version:user.version,routes:catalog};
}
async function board(input,smuggler=false){await expire();const user=await resolve(input.uuid);if(!user||!routes[user.faction]||user.keyId!==input.keyId||user.version!==input.version)fail('Your House key changed. Reopen the Guild menu.',403);
if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);if(!Number.isSafeInteger(input.fareMinor)||input.fareMinor<(openTravel&&!smuggler?0:1)||input.fareMinor>100000000)fail('Invalid Guild fare.',400);const destination=input.destination??routes[user.faction];if(smuggler?!Object.values(routes).includes(destination)||!tradeWorld(input.sourceWorld)||destination===tradeWorld(input.sourceWorld)||!routeBindings&&(destination!=='arrakis'||input.sourceWorld!=='lobby'):!await allowed(user,destination))fail(smuggler?'A current smuggler passage is required.':'Your House has no Imperial passage for this destination.',403);const legacyFingerprint=createHash('sha256').update(JSON.stringify([input.uuid,user.id,input.keyId,input.version,destination,input.fareMinor,...(smuggler?["smuggler"]:[])])).digest('hex'),fingerprint=smuggler&&routeBindings?createHash('sha256').update(JSON.stringify([legacyFingerprint,input.sourceWorld])).digest('hex'):legacyFingerprint;
if(openTravel&&!smuggler&&tradeWorld(input.sourceWorld||'lobby')!=='lobby')fail('Board ordinary Guild passages from the Guild Lobby.',403);
return bank.transaction(async tx=>{
const prior=await tx.first('SELECT * FROM pb_guild_passages WHERE id=? FOR UPDATE',[input.requestId]);if(prior){const legacy=smuggler&&routeBindings&&destination==='arrakis'&&input.sourceWorld==='lobby'&&prior.fingerprint===legacyFingerprint&&!await tx.first('SELECT id FROM pb_guild_route_bindings WHERE id=?',[prior.id]);if(prior.actor_id!==user.id||prior.fingerprint!==fingerprint&&!legacy)fail('This passage reference was already used.');return{ok:true,...view(prior),...(smuggler?{smuggler:true}:{}),replayed:true};}
const openRoute=openTravel&&!smuggler?await tariff(user,input.uuid,destination,tx,true):null,{price,offer}=smuggler?{price:smugglerFareMinor,offer:null}:openRoute?{price:openRoute.fareMinor,offer:null}:await quotedFare(user,tx,true);if(input.fareMinor!==price)fail('The Guild fare changed. Reopen the passage menu.');
if(!smuggler&&!await allowJourney(input.sourceWorld||'lobby',destination,tx,true))fail('The Spacing Guild has embargoed this world. Smuggler routes remain available.',403);
if(!smuggler&&!boardingOpen(clock()))fail('Boarding opens at :00, :20 and :40 for five minutes.');
const fresh=await resolve(input.uuid);if(!fresh||fresh.id!==user.id||fresh.keyId!==input.keyId||fresh.version!==input.version||!await readyForTravel(fresh,input.uuid,tx)||!smuggler&&!await allowed(fresh,destination))fail('Your House key or Imperial passage changed.',403);
const permit=smuggler?await smugglerPermit(fresh,input.uuid,input.sourceWorld,tx,true,destination):null;if(smuggler&&!permit)fail("Meet Esmar Tuek for a current personal smuggler permission.",403);
// Lock this customer's accounts before checking their other in-flight passage.
const now=clock(),r=await reserve(tx,input,user,{price,fingerprint,destination,expiresAt:smuggler?Math.min(now+120000,permit.expiresAt):now+120000,permitKey:permit?.keyId||null,offer});
if(openRoute)await tx.query('INSERT INTO pb_guild_open_passages(id,source_world,created_at) VALUES(?,?,?)',[r.id,'lobby',now]);
if(smuggler&&routeBindings)await tx.query("INSERT INTO pb_guild_route_bindings(id,route_kind,source_world,created_at) VALUES(?,'esmar',?,?)",[r.id,input.sourceWorld,now]);return{ok:true,...view(r),...(smuggler?{smuggler:true}:{})};
});
}
async function arrive(uuid,server){
await expire();const user=await resolve(uuid);if(!user)fail('A current linked personal account is required.',403);
const row=await bank.transaction(async tx=>{
const r=await tx.first("SELECT * FROM pb_guild_passages WHERE minecraft_uuid=? AND actor_id=? AND destination=? AND (state='pending' OR state='arrived' AND reported_at IS NULL)"+(routeBindings?" AND NOT EXISTS(SELECT 1 FROM pb_guild_route_bindings b WHERE b.id=pb_guild_passages.id AND b.route_kind='owned-home')":"")+" ORDER BY created_at DESC LIMIT 1 FOR UPDATE",[uuid,user.id,server]);if(!r)return null;
const marker=allowSmuggling?await tx.first('SELECT permit_key FROM pb_smuggler_passages WHERE id=? FOR UPDATE',[r.id]):null;r.smuggler=!!marker;if(r.state==='arrived')return r;
if(Number(r.expires_at)<=clock()){await release(tx,r);return null;}
if(user.keyId!==r.house_key||user.version!==Number(r.house_version)||!await readyForTravel(user,uuid,tx)||(marker?(await allowSmuggling(user,uuid,clock()))?.keyId!==marker.permit_key:!await allowed(user,r.destination)||!await allowJourney('lobby',r.destination,tx,true))){await release(tx,r);return null;}
await settle(tx,r,user,!!marker);if(openTravel&&!marker&&await tx.first('SELECT id FROM pb_guild_open_passages WHERE id=?',[r.id]))await recordTrip(tx,r,user);return r;
});
if(row){if(!row.smuggler)await recordArrival(user,row);await bank.query("UPDATE pb_guild_passages SET reported_at=? WHERE id=? AND state='arrived'",[clock(),row.id]);}let bounty=null;if(row&&openTravel&&!row.smuggler&&Number(row.fare_minor)>0){const b=await bank.first('SELECT * FROM pb_travel_bounties WHERE id=?',[row.id]);if(b)bounty={requestId:b.id,traveller:b.traveller,world:b.world,amountMinor:Number(b.amount_minor),state:b.state};}return{ok:true,passage:row?{...view(row),...(row.smuggler?{smuggler:true}:{})}:null,...(bounty?{bounty}:{})};
}
async function checkTravel(uuid,source,destination){if(!await resolve(uuid))fail('A linked account is required.',403);return bank.transaction(async tx=>{if(!await allowJourney(source,destination,tx,true))fail('The Spacing Guild has embargoed journeys to and from this world. Smuggler routes remain available.',403);return{ok:true,source,destination,expiresAt:clock()+5000};});}
async function smugglerReturn(uuid,source){const user=await resolve(uuid);if(!user||!Object.values(routes).includes(source)||!routeBindings&&source!=='arrakis'||!allowSmuggling)fail('Meet Esmar Tuek on the arrival world.',403);const r=await bank.first("SELECT p.id,s.permit_key"+(routeBindings?',b.source_world,b.route_kind':'')+" FROM pb_guild_passages p LEFT JOIN pb_smuggler_passages s ON s.id=p.id"+(routeBindings?' LEFT JOIN pb_guild_route_bindings b ON b.id=p.id':'')+" WHERE p.actor_id=? AND p.minecraft_uuid=? AND p.destination=? AND p.state='arrived'"+" ORDER BY p.arrived_at DESC,p.id DESC LIMIT 1",[user.id,uuid,source]);if(!r?.permit_key||r.route_kind==='owned-home')fail('No confirmed personal smuggler arrival is available for return.',403);const destination=tradeWorld(r.source_world||'lobby');if(!destination||destination===source)fail('The recorded return route requires review.');return{ok:true,source,destination,expiresAt:clock()+5000,smuggler:true};}
const owned=routeBindings&&homeRoutes?createOwnedSmugglerPassages(bank,homeRoutes,{resolve,clock,price:smugglerFareMinor,ledger,expire,readyForTravel,authorityForStore}):{};
return{quote,quoteSmuggler,board,arrive,expire,checkTravel,smugglerReturn,bountyClaim,openTravel,...owned};
}
export function createGuildQuestReceipts(db,bank,keys,{clock=Date.now}={}){
const authorize=metric=>async(_actor,p)=>{const row=await bank.first("SELECT * FROM pb_guild_passages WHERE id=? AND state='arrived' AND NOT EXISTS(SELECT 1 FROM pb_smuggler_passages s WHERE s.id=pb_guild_passages.id)",[p.eventId]);return !!row&&row.actor_id===p.accountId&&row.minecraft_uuid===p.minecraftUuid&&p.metric===metric&&p.quantity===1&&p.occurredAt===Number(row.arrived_at)&&p.reference===(metric==='guild-travel'?'guild:':'guild-route:')+row.id;};
const personal=keys?createPersonalActivityEvents(db,keys,{clock,authorizeProducer:authorize('guild-travel')}):null,pol=keys&&db?.polActivityEventsEnabled?createPOLActivityEvents(db,keys,{clock,authorizeProducer:authorize('pol-verified-route')}):null;
return async(user,row)=>{for(const [service,metric,prefix]of [[personal,'guild-travel','guild:'],[pol,'pol-verified-route','guild-route:']])if(service)await service.record(user,{eventId:row.id,accountId:user.id,minecraftUuid:row.minecraft_uuid,seasonId:'S01',metric,quantity:1,occurredAt:Number(row.arrived_at),reference:prefix+row.id});};
}
export function createGameGuildAPI(db,bank,keys,settings={},dependencies={}){
const resolve=dependencies.resolve||(async(uuid,store=db)=>{const rows=await store.query("SELECT a.id,a.username,a.role,c.faction,c.version,h.key_id keyId FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id JOIN site_character_choices c ON c.user_id=a.id AND c.minecraft_uuid=l.minecraft_uuid JOIN jarvis_house_selections h ON h.account_id=a.id AND h.minecraft_uuid=l.minecraft_uuid AND h.version=c.version AND h.faction=c.faction JOIN organisation_keys k ON k.id=h.key_id AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at>UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000) 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],version:Number(rows[0].version)}:null;});
const tradePolicy=db?.worldTradeEnabled&&bank?createBankTradePolicy(db,bank):null;
const allowJourney=async(source,destination,tx,lock)=>{if(!tradePolicy)return true;const policy=await tradePolicy(tx,Date.now(),lock);return ![source,destination].some(w=>policy[tradeWorld(w)]?.embargoUntil>Date.now());};
const service=dependencies.service||(bank?createGuildService(bank,{resolve,allowJourney,clock:dependencies.clock||Date.now,routeBindings:bank.guildRouteBindingsEnabled===true,authorityForStore:reader=>createPostbankAuthority(reader,{bank}),homeRoutes:db?.transaction?createOwnedSmugglerRoutes(db,{resolve,clock:dependencies.clock||Date.now}):null,surcharge:now=>currentGuildSurcharge(db,now),discount:(house,now)=>currentGuildDiscount(db,house,now),allowArrakis:async(house,user)=>await hasImperialPassage(db,house)||await hasOrganisationPassage(db,user),authority:createPostbankAuthority(db,{bank}),fareMinor:Number(settings.GUILD_FARE_MINOR||10000),openTravel:settings.GUILD_OPEN_TRAVEL==='true',holdingOnWorld:createNativeHoldingCheck(db),recordArrival:createGuildQuestReceipts(db,bank,keys),allowSmuggling:(user,uuid,now)=>activeSmugglerPermit(db,keys,user,uuid,now),smugglerFareMinor:Number(settings.SMUGGLER_FARE_MINOR||settings.GUILD_FARE_MINOR||10000),prologueReady:async(user,uuid)=>(await housePrologueState(db,keys,user,uuid)).ready,subsidies:db?.guildSubsidyEnabled?createGuildSubsidies(bank,{verify:(pool,now)=>verifyGuildSubsidy(db,pool,now)}):null}):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 Guild action is required.'},400);
let b;const reader=request.body?.getReader();if(!reader)return json({message:'Guild action required'},400);try{let bytes=0;const chunks=[];while(true){const {done,value}=await reader.read();if(done)break;bytes+=value.byteLength;if(bytes>2048){await reader.cancel();return json({message:'Request too large'},413);}chunks.push(value);}b=JSON.parse(Buffer.concat(chunks).toString());}catch{return json({message:'Invalid Guild action'},400);}finally{reader.releaseLock();}
if(typeof b?.action==='string'&&b.action.startsWith('home_')){
if(!validOwnedSmugglerRequest(b))return json({message:'Invalid Home Block passage fields'},400);
if(!service||typeof service[b.action]!=='function')return json({message:'Home Block navigation is unavailable.'},503);
try{const result=await service[b.action](b);return json(result,result.needsReview?409:200);}catch(error){return json({message:error instanceof BankError?error.message:'The passage could not be confirmed. Retry the original reference.'},error instanceof BankError?error.status||409:503);}
}
const fields={smuggler_return:['action','uuid','sourceWorld'],smuggler_quote:['action','uuid','sourceWorld'],smuggler_board:['action','uuid','requestId','keyId','version','fareMinor','sourceWorld','destination'],travel_check:['action','uuid','sourceWorld','destination'],quote:['action','uuid',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[])],board:['action','uuid','requestId','keyId','version','fareMinor',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[]),...(Object.hasOwn(b||{},'destination')?['destination']:[])],arrive:['action','uuid','server'],bounty_claim:['action','uuid','victim','requestId','server'],expire:['action']}[b?.action];
if((Object.hasOwn(b||{},'sourceWorld')&&!tradeWorld(b.sourceWorld))||b?.action==='travel_check'&&b.destination!=='lobby'||!fields||Object.keys(b).length!==fields.length||fields.some(f=>!Object.hasOwn(b,f))||b.action!=='expire'&&!validUuid(b.uuid)||['board','smuggler_board'].includes(b.action)&&(!validUuid(b.requestId)||!validUuid(b.keyId)||!Number.isSafeInteger(b.version)||b.version<1||!Number.isSafeInteger(b.fareMinor)||b.fareMinor<(b.action==='board'&&service?.openTravel?0:1)||Object.hasOwn(b,'destination')&&!Object.values(routes).includes(b.destination))||b.action==='arrive'&&!Object.values(routes).includes(b.server)||b.action==='bounty_claim'&&(!validUuid(b.victim)||!validUuid(b.requestId)||b.victim===b.uuid||!Object.values(routes).includes(b.server)))return json({message:'Invalid Guild fields'},400);
if(!service)return json({message:'The central bank is unavailable.'},503);
try{return json(b.action==='smuggler_return'?await service.smugglerReturn(b.uuid,b.sourceWorld):b.action==='smuggler_quote'?await service.quoteSmuggler(b.uuid,b.sourceWorld):b.action==='smuggler_board'?await service.board(b,true):b.action==='quote'?await service.quote(b.uuid,b.sourceWorld):b.action==='travel_check'?await service.checkTravel(b.uuid,b.sourceWorld,b.destination):b.action==='board'?await service.board(b):b.action==='arrive'?await service.arrive(b.uuid,b.server):b.action==='bounty_claim'?await service.bountyClaim({killer:b.uuid,victim:b.victim,requestId:b.requestId,server:b.server}):{ok:true,expired:await service.expire()});}catch(e){return json({message:e instanceof BankError?e.message:'The Guild could not confirm this passage. Retry the same reference.'},e instanceof BankError?e.status||409:503);}
};
}