Extend Navigator catalogs and owned Home Block smuggler travel

This commit is contained in:
unimatrixgit 2026-11-29 23:54:36 +01:00
commit ff0161117e
11 changed files with 466 additions and 33 deletions

View file

@ -1,14 +1,15 @@
import {createBankTradePolicy} from './world-trade-governance.mjs';
import {tradeWorld} from '../control-panel/public/world-trade-policy.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 {canDebitAccount} from './postbank-authorisations.mjs';
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
import {PostbankPayments} from './postbank-payments.mjs';
import {createGuildPassageLedger} from './guild-passage-ledger.mjs';
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';
@ -20,58 +21,66 @@ 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 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 createGuildService(bank,{authority,resolve,allowArrakis=async()=>false,recordArrival=async()=>{},allowJourney=async()=>true,clock=Date.now,fareMinor=10000,surcharge=async()=>0,discount=async()=>0,allowSmuggling=null,smugglerFareMinor=fareMinor,prologueReady=async()=>true,subsidies=null}={}){
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,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 payments=new PostbankPayments(bank,authority,{clock});
const ledger=createGuildPassageLedger(bank,{authority,clock,subsidies}),{funds,release,reserve,settle}=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]&&(destination===routes[user.faction]||destination==='arrakis'&&await allowArrakis(user.faction,user));
async function funds(tx,user,amount,lock=false){const context=await authority(user,{bank:tx});return(await tx.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? AND a.system_key IS NULL ORDER BY a.id"+(lock?' FOR UPDATE':''),[user.id])).find(a=>ordinaryPaymentAccount(a)&&canDebitAccount(context,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(amount));}
async function release(tx,r){if(r.state!=='pending')return;const a=await tx.first('SELECT id,reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[r.source_id]);if(!a||BigInt(a.reserved_minor)<BigInt(r.fare_minor))throw Error('Guild reservation requires reconciliation');await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[r.fare_minor,r.source_id]);if(subsidies)await subsidies.release(tx,r.id);await tx.query("UPDATE pb_guild_passages SET state='expired' WHERE id=?",[r.id]);}
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;}
async function quote(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);if(!ready)return {ok:true,destination:routes[user.faction],destinations:[],fareMinor:(await quotedFare(user)).price,affordable:false,account:null,prologueRequired:true};const {price,offer}=await quotedFare(user),source=await funds(bank,user,price),destinations=[routes[user.faction]];if(!destinations.includes('arrakis')&&await allowArrakis(user.faction,user))destinations.push('arrakis');const open=[];for(const destination of destinations)if(await allowJourney(sourceWorld,destination,bank,false))open.push(destination);return{ok:true,destination:routes[user.faction],destinations:open,fareMinor:price,...(offer?{subsidyMinor:offer.amount}:{}),affordable:!!source,account:source?.account_number||null};}
async function smugglerPermit(user,uuid,source,tx,lock=false){if(!allowSmuggling||source!=='lobby'||!routes[user?.faction]||!await readyForTravel(user,uuid))return null;if(await allowed(user,'arrakis')&&await allowJourney(source,'arrakis',tx,lock))return null;return allowSmuggling(user,uuid,clock());}
async function quoteSmuggler(uuid,sourceWorld='lobby'){await expire();const user=await resolve(uuid);if(!user)fail('Link your active website account and choose your House first.',403);const eligible=!!allowSmuggling&&sourceWorld==='lobby'&&!!routes[user.faction]&&await readyForTravel(user,uuid)&&(!await allowed(user,'arrakis')||!await allowJourney(sourceWorld,'arrakis',bank,false)),permit=eligible?await allowSmuggling(user,uuid,clock()):null;return{ok:true,eligible,allowed:!!permit,permitExpiresAt:permit?.expiresAt||null,fareMinor:smugglerFareMinor,affordable:!!permit&&!!await funds(bank,user,smugglerFareMinor),keyId:user.keyId,version:user.version};}
async function quote(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),{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.':!boardingOpen(clock())?'Boarding opens at :00, :20 and :40 for five minutes.':!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<1||input.fareMinor>100000000)fail('Invalid Guild fare.',400);const destination=input.destination??routes[user.faction];if(smuggler?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 fingerprint=createHash('sha256').update(JSON.stringify([input.uuid,user.id,input.keyId,input.version,destination,input.fareMinor,...(smuggler?["smuggler"]:[])])).digest('hex');
if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);if(!Number.isSafeInteger(input.fareMinor)||input.fareMinor<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;
return bank.transaction(async tx=>{
const prior=await tx.first('SELECT * FROM pb_guild_passages WHERE id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==user.id||prior.fingerprint!==fingerprint)fail('This passage reference was already used.');return{ok:true,...view(prior),...(smuggler?{smuggler:true}:{}),replayed:true};}
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 {price,offer}=smuggler?{price:smugglerFareMinor,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):null;if(smuggler&&!permit)fail("Meet Esmar Tuek for a current personal smuggler permission.",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 source=await funds(tx,user,price,true);if(!source)fail('Not enough available Dunemarks in your central personal bank account.');
const other=await tx.first("SELECT id FROM pb_guild_passages WHERE minecraft_uuid=? AND state='pending' FOR UPDATE",[input.uuid]);if(other)fail('Your previous passage is still awaiting arrival.');
const target=await tx.first("SELECT * FROM pb_accounts WHERE system_key='sys_game_treasury' FOR UPDATE");if(!target||target.state!=='active')fail('The Guild receiving account is unavailable.',503);
const now=clock(),r={id:input.requestId,actor_id:user.id,minecraft_uuid:input.uuid,house_key:input.keyId,house_version:input.version,destination,fare_minor:price,source_id:source.id,target_id:target.id,fingerprint,state:'pending',created_at:now,expires_at:smuggler?Math.min(now+120000,permit.expiresAt):now+120000};
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[price,source.id]);
await tx.query('INSERT INTO pb_guild_passages(id,actor_id,minecraft_uuid,house_key,house_version,destination,fare_minor,source_id,target_id,fingerprint,state,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',Object.values(r));if(smuggler)await tx.query("INSERT INTO pb_smuggler_passages(id,permit_key) VALUES(?,?)",[r.id,permit.keyId]);if(offer)await subsidies.reserve(tx,r.id,offer);return{ok:true,...view(r),...(smuggler?{smuggler:true}:{})};
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(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) ORDER BY created_at DESC LIMIT 1 FOR UPDATE",[uuid,user.id,server]);if(!r)return null;
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;}
const accounts=await tx.query(accountSQL+' WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[r.source_id,r.target_id]),source=accounts.find(a=>String(a.id)===String(r.source_id)),target=accounts.find(a=>String(a.id)===String(r.target_id));
if(!ordinaryPaymentAccount(source)||!target||target.system_key!=='sys_game_treasury'||target.state!=='active'||BigInt(source.reserved_minor)<BigInt(r.fare_minor))fail('The passage payment needs review.');
if(!canDebitAccount(await authority(user,{bank:tx}),source.entity_id,source.id))fail('Your bank account authority changed.',403);
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'guild','queued',?)",[r.id,user.id,r.source_id,r.target_id,r.fingerprint,r.fare_minor,(marker?'Smuggler passage · ':'Spacing Guild passage · ')+r.destination,clock()]);
await payments.post(tx,{id:r.id,actor_id:user.id,amount_minor:String(r.fare_minor)},source,target,true);if(subsidies)await subsidies.settle(tx,r.id,r.target_id);
r.state='arrived';r.arrived_at=clock();await tx.query("UPDATE pb_guild_passages SET state='arrived',arrived_at=? WHERE id=?",[r.arrived_at,r.id]);return r;
await settle(tx,r,user,!!marker);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]);}return{ok:true,passage:row?{...view(row),...(row.smuggler?{smuggler:true}:{})}:null};
}
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||source!=='arrakis'||!allowSmuggling)fail('Meet Esmar Tuek on Arrakis.',403);const r=await bank.first("SELECT p.id,s.permit_key FROM pb_guild_passages p LEFT JOIN pb_smuggler_passages s ON s.id=p.id WHERE p.actor_id=? AND p.minecraft_uuid=? AND p.destination='arrakis' AND p.state='arrived' ORDER BY p.arrived_at DESC,p.id DESC LIMIT 1",[user.id,uuid]);if(!r?.permit_key)fail('No confirmed personal smuggler arrival is available for return.',403);return{ok:true,source,destination:'lobby',expiresAt:clock()+5000,smuggler:true};}
return{quote,quoteSmuggler,board,arrive,expire,checkTravel,smugglerReturn};
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,...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;};
@ -79,14 +88,19 @@ export function createGuildQuestReceipts(db,bank,keys,{clock=Date.now}={}){
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)=>{const rows=await db.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 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,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),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);
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),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'],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<1||Object.hasOwn(b,'destination')&&!Object.values(routes).includes(b.destination))||b.action==='arrive'&&!Object.values(routes).includes(b.server))return json({message:'Invalid Guild fields'},400);
if(!service)return json({message:'The central bank is unavailable.'},503);

View file

@ -0,0 +1,30 @@
import {PostbankPayments} from './postbank-payments.mjs';
import {BankError} from './postbank-service.mjs';
import {canDebitAccount} from './postbank-authorisations.mjs';
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
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);};
// Shared by ordinary Guild, Esmar and owned-home routes. One reservation and ledger.
export function createGuildPassageLedger(bank,{authority,clock=Date.now,subsidies=null}){
const payments=new PostbankPayments(bank,authority,{clock});
async function funds(tx,user,amount,lock=false,authorise=authority){const context=await authorise(user,{bank:tx});return(await tx.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? AND a.system_key IS NULL ORDER BY a.id"+(lock?' FOR UPDATE':''),[user.id])).find(a=>ordinaryPaymentAccount(a)&&canDebitAccount(context,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(amount));}
async function release(tx,r){if(r.state!=='pending')return;const a=await tx.first('SELECT id,reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[r.source_id]);if(!a||BigInt(a.reserved_minor)<BigInt(r.fare_minor))throw Error('Guild reservation requires reconciliation');await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[r.fare_minor,r.source_id]);if(subsidies)await subsidies.release(tx,r.id);await tx.query("UPDATE pb_guild_passages SET state='expired' WHERE id=?",[r.id]);r.state='expired';}
async function reserve(tx,input,user,{price,fingerprint,destination,expiresAt,permitKey=null,offer=null,authorise=authority}){
const source=await funds(tx,user,price,true,authorise);if(!source)fail('Not enough available Dunemarks in your central personal bank account.');
if(await tx.first("SELECT id FROM pb_guild_passages WHERE minecraft_uuid=? AND state='pending' FOR UPDATE",[input.uuid]))fail('Your previous passage is still awaiting arrival.');
const target=await tx.first("SELECT * FROM pb_accounts WHERE system_key='sys_game_treasury' FOR UPDATE");if(!target||target.state!=='active')fail('The Guild receiving account is unavailable.',503);
const r={id:input.requestId,actor_id:user.id,minecraft_uuid:input.uuid,house_key:input.keyId,house_version:input.version,destination,fare_minor:price,source_id:source.id,target_id:target.id,fingerprint,state:'pending',created_at:clock(),expires_at:expiresAt};
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[price,source.id]);
await tx.query('INSERT INTO pb_guild_passages(id,actor_id,minecraft_uuid,house_key,house_version,destination,fare_minor,source_id,target_id,fingerprint,state,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',Object.values(r));
if(permitKey)await tx.query('INSERT INTO pb_smuggler_passages(id,permit_key) VALUES(?,?)',[r.id,permitKey]);if(offer)await subsidies.reserve(tx,r.id,offer);return r;
}
async function settle(tx,r,user,smuggler=false,authorise=authority){
const accounts=await tx.query(accountSQL+' WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[r.source_id,r.target_id]),source=accounts.find(a=>String(a.id)===String(r.source_id)),target=accounts.find(a=>String(a.id)===String(r.target_id));
if(!ordinaryPaymentAccount(source)||!target||target.system_key!=='sys_game_treasury'||target.state!=='active'||BigInt(source.reserved_minor)<BigInt(r.fare_minor))fail('The passage payment needs review.');
if(!canDebitAccount(await authorise(user,{bank:tx}),source.entity_id,source.id))fail('Your bank account authority changed.',403);
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'guild','queued',?)",[r.id,user.id,r.source_id,r.target_id,r.fingerprint,r.fare_minor,(smuggler?'Smuggler passage · ':'Spacing Guild passage · ')+r.destination,clock()]);
await payments.post(tx,{id:r.id,actor_id:user.id,amount_minor:String(r.fare_minor)},source,target,true);if(subsidies)await subsidies.settle(tx,r.id,r.target_id);
r.state='arrived';r.arrived_at=clock();await tx.query("UPDATE pb_guild_passages SET state='arrived',arrived_at=? WHERE id=?",[r.arrived_at,r.id]);return r;
}
return {funds,release,reserve,settle};
}

View file

@ -0,0 +1,3 @@
// Route receipt metadata only; organisation ownership stays in original deeds.
export const GUILD_ROUTE_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_guild_route_bindings(id CHAR(36) PRIMARY KEY,route_kind VARCHAR(16) NOT NULL,source_world VARCHAR(32) NOT NULL,binding_json TEXT NULL,delivered_at BIGINT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
export const passageView=r=>({requestId:r.id,destination:r.destination,state:r.state,fareMinor:Number(r.fare_minor),expiresAt:Number(r.expires_at)});

View file

@ -0,0 +1,62 @@
import {createHash} from 'node:crypto';
import {BankError} from './postbank-service.mjs';
import {passageView} from './guild-route-bindings.mjs';
import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs';
const fail=(message,status=409)=>{throw new BankError(message,status);};
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
export function createOwnedSmugglerPassages(bank,routes,{resolve,clock,price,ledger,expire,readyForTravel,authorityForStore=null}){
const reference=h=>({kind:h.kind,id:h.id,homeBlockId:h.homeBlockId,claimRevision:h.claimRevision});
const home=h=>({kind:h.kind,id:h.id,homeBlockId:h.homeBlockId,revision:h.claimRevision,worldUuid:h.home.worldUuid,worldName:h.home.worldName,position:h.home.position});
const ticket=(r,b)=>({ok:true,schema:1,...passageView(r),smuggler:true,paid:r.state==='arrived',...(r.state==='expired'?{cancelled:true}:{}),home:b.home});
const identity=async uuid=>{const u=await resolve(uuid);if(!u)fail('Link an active character first.',403);return u;};
const binding=input=>[input.uuid,input.sourceWorld,input.origin,input.target,input.originHomeBlockId,input.originRevision,input.targetHomeBlockId,input.targetRevision,input.keyId,input.version,input.fareMinor];
async function lookup(tx,id,user,server=null,lock=false){
const r=await tx.first('SELECT * FROM pb_guild_passages WHERE id=?'+(lock?' FOR UPDATE':''),[id]);
const marker=await tx.first("SELECT * FROM pb_guild_route_bindings WHERE id=? AND route_kind='owned-home'"+(lock?' FOR UPDATE':''),[id]);
if(!r||!marker||r.actor_id!==user.id||(user.uuid&&r.minecraft_uuid!==user.uuid)||(server&&r.destination!==tradeWorld(server)))fail('This Home Block passage is unavailable.',404);
return {r,marker,b:JSON.parse(marker.binding_json)};
}
async function list(input){await expire();const user=await identity(input.uuid),result=await routes.list(user,input),ready=await readyForTravel(user,input.uuid);return {ok:true,schema:1,destinations:result.destinations.map(({home,...h})=>({...h,fareMinor:price,available:h.available&&ready,reason:!ready?'Complete your House Prologue first.':h.reason}))};}
async function quote(input){await expire();const user=await identity(input.uuid),ctx=await routes.quote(user,input);if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);return {ok:true,schema:1,origin:reference(ctx.origin),target:reference(ctx.target),keyId:user.keyId,version:user.version,fareMinor:price,affordable:!!await ledger.funds(bank,user,price),expiresAt:clock()+60000};}
async function board(input){
await expire();const user=await identity(input.uuid),fingerprint=hash([user.id,...binding(input)]);
const prior=await bank.first('SELECT * FROM pb_guild_passages WHERE id=?',[input.requestId]);
if(prior){const saved=await lookup(bank,input.requestId,{...user,uuid:input.uuid});if(prior.fingerprint!==fingerprint)fail('This passage reference was already used.');return {...ticket(saved.r,saved.b),replayed:true};}
if(user.keyId!==input.keyId||user.version!==input.version||input.fareMinor!==price||input.confirmed!==true)fail('Your House key or smuggler fare changed. Reopen the Navigator.');
if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);
return routes.withLock(user,input,'board',async(ctx,fresh,reader)=>bank.transaction(async tx=>{
const previous=await tx.first('SELECT * FROM pb_guild_passages WHERE id=? FOR UPDATE',[input.requestId]);
if(previous){const saved=await lookup(tx,input.requestId,{...fresh,uuid:input.uuid});if(previous.fingerprint!==fingerprint)fail('This passage reference was already used.');return {...ticket(saved.r,saved.b),replayed:true};}
if(fresh.keyId!==input.keyId||fresh.version!==input.version)fail('Your House key changed.',403);
const r=await ledger.reserve(tx,input,fresh,{price,fingerprint,destination:ctx.target.server,expiresAt:clock()+120000,permitKey:fresh.keyId,...(authorityForStore?{authorise:authorityForStore(reader)}:{})});
const b={origin:reference(ctx.origin),target:reference(ctx.target),home:home(ctx.target)};
await tx.query("INSERT INTO pb_guild_route_bindings(id,route_kind,source_world,binding_json,created_at) VALUES(?,'owned-home',?,?,?)",[r.id,input.sourceWorld,JSON.stringify(b),clock()]);return ticket(r,b);
}));
}
async function arrive(input){await expire();const user=await identity(input.uuid);const rows=await bank.query("SELECT p.* FROM pb_guild_passages p JOIN pb_guild_route_bindings b ON b.id=p.id AND b.route_kind='owned-home' WHERE p.actor_id=? AND p.minecraft_uuid=? AND p.destination=? AND (p.state='pending' OR p.state='arrived') AND b.delivered_at IS NULL ORDER BY p.created_at,p.id LIMIT 1",[user.id,input.uuid,tradeWorld(input.server)]);if(!rows.length)return {ok:true,schema:1,ticket:null};const saved=await lookup(bank,rows[0].id,{...user,uuid:input.uuid},input.server);return {ok:true,schema:1,ticket:ticket(saved.r,saved.b)};}
async function ready(input){
await expire();const user=await identity(input.uuid),saved=await lookup(bank,input.requestId,{...user,uuid:input.uuid},input.server);
if(saved.r.state==='expired')return {ok:true,schema:1,requestId:input.requestId,state:'expired',paid:false,cancelled:true};
if(saved.r.state==='pending'&&!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);
const proof={uuid:input.uuid,target:saved.b.target,targetHomeBlockId:saved.b.home.homeBlockId,targetRevision:saved.b.home.revision};
try{return await routes.withLock(user,proof,'ready',async(ctx,fresh,reader)=>bank.transaction(async tx=>{
const current=await lookup(tx,input.requestId,{...fresh,uuid:input.uuid},input.server,true),r=current.r;
if(hash(home(ctx.target))!==hash(current.b.home))fail('The registered destination changed.');
if(r.state==='arrived')return {...ticket(r,current.b),replayed:true};
if(r.state!=='pending')return {ok:true,schema:1,requestId:r.id,state:r.state,cancelled:r.state==='expired',paid:false};
if(Number(r.expires_at)<=clock()){await ledger.release(tx,r);return {ok:true,schema:1,requestId:r.id,state:'expired',paid:false,cancelled:true};}
if(fresh.keyId!==r.house_key||fresh.version!==Number(r.house_version))fail('Your House key changed.',403);
await ledger.settle(tx,r,fresh,true,authorityForStore?authorityForStore(reader):undefined);return ticket(r,current.b);
}));}catch(error){if(saved.r.state==='arrived'&&error instanceof BankError)return {ok:false,schema:1,requestId:input.requestId,state:'review',paid:true,needsReview:true,message:'Your paid passage needs destination review. Keep the original reference.'};throw error;}
}
async function delivered(input){
const user=await identity(input.uuid);return bank.transaction(async tx=>{
const {r,marker,b}=await lookup(tx,input.requestId,{...user,uuid:input.uuid},input.server,true),receipt=hash([input.requestId,input.arrivedAt,input.arrival]);
if(marker.delivered_at!=null){if(b.deliveryReceipt!==receipt)fail('Arrival receipt reference conflict.');return {ok:true,schema:1,requestId:r.id,delivered:true,replayed:true};}
const at=input.arrival?.position;
if(r.state!=='arrived'||input.arrival?.worldUuid!==b.home.worldUuid||!Number.isSafeInteger(input.arrivedAt)||input.arrivedAt<Number(r.arrived_at)-5000||input.arrivedAt>clock()+10000||!at||!['x','y','z'].every(k=>Number.isFinite(at[k]))||['x','y','z'].reduce((n,k)=>n+(at[k]-b.home.position[k])**2,0)>9)fail('A matching native Home Block arrival is required.');
b.deliveryReceipt=receipt;await tx.query('UPDATE pb_guild_route_bindings SET delivered_at=?,binding_json=? WHERE id=? AND delivered_at IS NULL',[input.arrivedAt,JSON.stringify(b),r.id]);await tx.query("UPDATE pb_guild_passages SET reported_at=? WHERE id=? AND state='arrived'",[clock(),r.id]);return {ok:true,schema:1,requestId:r.id,delivered:true};
});
}
return {home_list:list,home_quote:quote,home_board:board,home_arrive:arrive,home_ready:ready,home_delivered:delivered};
}

View file

@ -0,0 +1,14 @@
import {validUuid} from './game-link.mjs';
import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs';
const exact=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join(',')===[...keys].sort().join(',');
const ref=v=>exact(v,['kind','id'])&&['clan','company'].includes(v.kind)&&validUuid(v.id);
const position=v=>exact(v,['x','y','z'])&&Object.values(v).every(Number.isFinite)&&Math.abs(v.x)<=29999980&&Math.abs(v.z)<=29999980&&v.y>=-64&&v.y<=320;
export function validOwnedSmugglerRequest(b){
const fields={home_list:['origin','sourceWorld','sourceLocation'],home_quote:['origin','sourceWorld','sourceLocation','target'],home_board:['origin','sourceWorld','sourceLocation','target','requestId','keyId','version','fareMinor','confirmed','originHomeBlockId','originRevision','targetHomeBlockId','targetRevision'],home_arrive:['server'],home_ready:['server','requestId'],home_delivered:['server','requestId','arrivedAt','arrival']}[b?.action];
if(!fields||!exact(b,['action','uuid',...fields])||!validUuid(b.uuid))return false;
if(fields.includes('origin')&&(!ref(b.origin)||tradeWorld(b.sourceWorld)!==b.sourceWorld||!exact(b.sourceLocation,['worldUuid','position','observedAt'])||!validUuid(b.sourceLocation.worldUuid)||!position(b.sourceLocation.position)||!Number.isSafeInteger(b.sourceLocation.observedAt)))return false;
if(fields.includes('target')&&!ref(b.target)||fields.includes('server')&&(!tradeWorld(b.server)||tradeWorld(b.server)!==b.server||b.server==='lobby')||fields.includes('requestId')&&!validUuid(b.requestId))return false;
if(b.action==='home_board'&&(!validUuid(b.keyId)||!validUuid(b.originHomeBlockId)||!validUuid(b.targetHomeBlockId)||![b.version,b.originRevision,b.targetRevision,b.fareMinor].every(n=>Number.isSafeInteger(n)&&n>0)||b.fareMinor>100000000||b.confirmed!==true))return false;
if(b.action==='home_delivered'&&(!Number.isSafeInteger(b.arrivedAt)||!exact(b.arrival,['worldUuid','position'])||!validUuid(b.arrival.worldUuid)||!position(b.arrival.position)))return false;
return true;
}

View file

@ -0,0 +1,58 @@
import {boardReadStore} from './board-deed-source.mjs';
import {clanDeedAuthority} from './clan-deeds.mjs';
import {readCompanyDeed} from './company-deeds.mjs';
import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs';
import {BankError} from './postbank-service.mjs';
const fail=(message,status=409)=>{throw new BankError(message,status);};
const ref=value=>value&&['clan','company'].includes(value.kind)&&typeof value.id==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value.id);
export function createOwnedSmugglerRoutes(db,{resolve,clock=Date.now}){
async function home(store,user,item){
if(!ref(item))fail('Choose a registered clan or company.',400);
let name;
if(item.kind==='clan'){const p=await clanDeedAuthority(store,user.id,item.id);if(!p.isOwner||!p.canManage)fail('Only your own active clan Home Blocks are available.',403);name=p.deed.clan.name;}
else{let d;try{d=await readCompanyDeed(store,item.id);}catch(error){if([403,404,409].includes(error.status))fail('The current company deed requires review.',error.status);throw error;}if(d.company.status!=='active'||d.company.owner_account_id!==user.id)fail('Only your own active company Home Blocks are available.',403);name=d.company.name;}
const row=await store.first('SELECT revision,snapshot_json FROM site_claim_registry WHERE organisation_kind=? AND organisation_id=?',[item.kind,item.id]);
const snapshot=row?JSON.parse(row.snapshot_json):null,h=snapshot?.source==='minecraft'?snapshot.homeBlock:null;
return {...item,name,homeBlockId:h?.id||null,claimRevision:Number(row?.revision||0),server:tradeWorld(h?.worldName),home:h};
}
function sourceProof(origin,input){
const p=input.sourceLocation,h=origin.home,at=p?.position;
if(!h||origin.server!==tradeWorld(input.sourceWorld))fail('Meet this organisation’s registered Home Block NPC on its own world.',403);
if(p?.worldUuid!==h.worldUuid||!at||Object.keys(at).sort().join(',')!=='x,y,z'||!Object.values(at).every(Number.isFinite)||!Number.isSafeInteger(p.observedAt)||Math.abs(clock()-p.observedAt)>30000||['x','y','z'].reduce((n,k)=>n+(at[k]-h.position[k])**2,0)>100)fail('Reopen the Navigator beside the registered Home Block NPC.',403);
}
async function context(store,user,input,stage){
let origin=null;if(stage!=='ready'){origin=await home(store,user,input.origin);sourceProof(origin,input);}
const target=await home(store,user,input.target);
if(!target.home||!target.server)fail('The destination has no registered game Home Block.');
if(stage!=='ready'&&target.server===origin.server)fail('This Home Block is on your current world.');
if(stage!=='quote'&&(target.homeBlockId!==input.targetHomeBlockId||target.claimRevision!==input.targetRevision||stage==='board'&&(origin.homeBlockId!==input.originHomeBlockId||origin.claimRevision!==input.originRevision)))fail('A Home Block changed. Reopen the Navigator.');
return {origin,target};
}
async function list(user,input){
const reader=boardReadStore(db,db),origin=await home(reader,user,input.origin);sourceProof(origin,input);
const clans=await db.query('SELECT id FROM site_clans WHERE active=1 AND owner_id=? ORDER BY id',[user.id]),companies=await db.query("SELECT c.id FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id WHERE c.status='active' AND d.owner_account_id=? ORDER BY c.id",[user.id]);
if(clans.length+companies.length>500)fail('Your owned organisation registry requires review.');
const destinations=[];
for(const item of [...clans.map(c=>({kind:'clan',id:c.id})),...companies.map(c=>({kind:'company',id:c.id}))]){try{const h=await home(reader,user,item),available=!!h.home&&!!h.server&&h.server!==origin.server;destinations.push({...h,available,reason:!h.home?'No registered Home Block.':h.server===origin.server?'Already on this world.':!h.server?'Unregistered destination world.':''});}catch(error){if(error.status!==403&&error.status!==404)throw error;}}
return {origin,destinations};
}
async function withLock(user,input,stage,work){
// Central changes nothing. Its deed/read locks remain held through the one
// atomic bank reservation/posting transaction, avoiding distributed writes.
return db.transaction(async tx=>{
const reader=boardReadStore(tx,db);reader.readSnapshot=undefined;
await tx.query('SELECT id FROM site_accounts WHERE id=? FOR SHARE',[user.id]);await tx.query('SELECT minecraft_uuid FROM site_game_links WHERE user_id=? FOR SHARE',[user.id]);
await tx.query('SELECT version FROM site_character_choices WHERE user_id=? FOR SHARE',[user.id]);await tx.query('SELECT key_id FROM jarvis_house_selections WHERE account_id=? FOR SHARE',[user.id]);
let fresh=await resolve(input.uuid,reader);if(!fresh||fresh.id!==user.id)fail('Your linked character changed.',403);
await tx.query('SELECT id FROM organisation_keys WHERE id=? FOR SHARE',[fresh.keyId]);
const checked=await resolve(input.uuid,reader);if(!checked||checked.id!==fresh.id||checked.keyId!==fresh.keyId||checked.version!==fresh.version)fail('Your House key changed.',403);fresh=checked;
if([input.origin,input.target].some(r=>r?.kind==='clan')){await tx.query('SELECT id FROM site_clans WHERE active=1 ORDER BY id LIMIT 501 FOR SHARE');await tx.query('SELECT clan_id FROM site_clan_deeds ORDER BY clan_id LIMIT 501 FOR SHARE');await tx.query('SELECT user_id FROM site_clan_members WHERE user_id=? FOR SHARE',[user.id]);}
for(const item of [input.origin,input.target].filter(ref).sort((a,b)=>(a.kind+a.id).localeCompare(b.kind+b.id))){
if(item.kind==='company'){await tx.query('SELECT id FROM corrino_companies WHERE id=? FOR SHARE',[item.id]);await tx.query('SELECT company_id FROM site_company_deeds WHERE company_id=? FOR SHARE',[item.id]);await tx.query('SELECT user_id FROM site_company_members WHERE company_id=? AND user_id=? FOR SHARE',[item.id,user.id]);}
await tx.query('SELECT revision FROM site_claim_registry WHERE organisation_kind=? AND organisation_id=? FOR SHARE',[item.kind,item.id]);
}
return work(await context(reader,fresh,input,stage),fresh,reader);
});
}
return {list,quote:(user,input)=>context(boardReadStore(db,db),user,input,'quote'),withLock};
}

View file

@ -5,6 +5,7 @@ import {WAR_MUSTER_SCHEMA} from './war-muster.mjs';
import {WAR_EXCHANGE_SCHEMA} from './war-exchange.mjs';
import {EXCHANGE_INCENTIVE_SCHEMA} from './exchange-incentive.mjs';
import {GUILD_SUBSIDY_SCHEMA} from './guild-subsidy.mjs';
import {GUILD_ROUTE_SCHEMA} from './guild-route-bindings.mjs';
import {GUILD_SCHEMA,SMUGGLER_PASSAGE_SCHEMA} from './game-guild.mjs';
import {HOME_SCHEMA} from './game-home.mjs';
import {DEED_PURCHASE_SCHEMA} from './deed-purchases.mjs';
@ -30,7 +31,7 @@ export async function openPostbankDatabase(settings){
const pool=mysql.createPool({host:settings.BANK_DB_HOST||'127.0.0.1',port:Number(settings.BANK_DB_PORT||3306),database:name,user:settings.BANK_DB_USER,password:settings.BANK_DB_PASSWORD,connectionLimit:4,supportBigNumbers:true,bigNumberStrings:true,charset:'utf8mb4',connectTimeout:8000});
const api=c=>({async query(sql,args=[]){return(await c.execute(sql,args))[0];},async first(sql,args=[]){return(await c.execute(sql,args))[0][0]||null;}});
const db={async query(sql,args=[]){return(await pool.execute(sql,args))[0];},async first(sql,args=[]){return(await pool.execute(sql,args))[0][0]||null;},async transaction(work){const c=await pool.getConnection();try{await c.beginTransaction();const result=await work(api(c));await c.commit();return result;}catch(error){await c.rollback();throw error;}finally{c.release();}},async close(){await pool.end();}};
try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...RIHLA_CASH_SCHEMA,...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,...WAR_MUSTER_SCHEMA,WAR_CAMPAIGN_SCHEMA,WAR_SETTLEMENT_JOB_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(DEED_PURCHASE_SCHEMA);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await db.query(GUILD_SCHEMA);for(const sql of [...GUILD_SUBSIDY_SCHEMA,...EXCHANGE_INCENTIVE_SCHEMA])await db.query(sql);await db.query(SMUGGLER_PASSAGE_SCHEMA);await db.query(HOME_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);await db.query(ECONOMY_OPERATION_SCHEMA);}catch(error){await pool.end();throw error;}
try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...RIHLA_CASH_SCHEMA,...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,...WAR_MUSTER_SCHEMA,WAR_CAMPAIGN_SCHEMA,WAR_SETTLEMENT_JOB_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(DEED_PURCHASE_SCHEMA);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await db.query(GUILD_SCHEMA);for(const sql of [...GUILD_SUBSIDY_SCHEMA,...EXCHANGE_INCENTIVE_SCHEMA])await db.query(sql);await db.query(SMUGGLER_PASSAGE_SCHEMA);await db.query(GUILD_ROUTE_SCHEMA);db.guildRouteBindingsEnabled=true;await db.query(HOME_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);await db.query(ECONOMY_OPERATION_SCHEMA);}catch(error){await pool.end();throw error;}
return db;
}

View file

@ -0,0 +1,27 @@
# Navigator route extension
Deploy the reviewed central release before the paired Navigator plugins. Existing Guild requests and the permitted `destinations` string array remain compatible. `quote` and `smuggler_quote` additionally return `routes`, containing every planet once: `server`, central `name`, `available`, human-readable `reason`, and `fareMinor`. Unavailable destinations remain visible and cannot submit a boarding action. The ordinary Guild still applies its original House/Imperial permission, embargo, boarding clock, personal available funds and prologue rules. Esmar keeps the current personal permission and smuggler fare, evaluated for each destination. Lobby is the origin/return hub, not another planet row.
New personal smuggler bookings record their actual departure world. Return permission is tied to the latest confirmed arrival on the current world, and returns to that booking's recorded origin. Legacy lobby–Arrakis records still return to Lobby. An owned Home Block ticket does not grant personal Esmar return permission.
## Owned Home Block contract
All requests use the existing private `/internal/game/guild` credential and strict action-specific fields. The backend owns `uuid`, `sourceWorld` and the real-world contact proof. The menu cannot supply another player's identity or bank account. Source NPC contact must be rechecked on the server, after returning from the virtual menu world.
`home_list`, `home_quote` and `home_board` require `origin: {kind,id}` and `sourceLocation: {worldUuid,position:{x,y,z},observedAt}`. The origin must be the player's current owned clan/company Home Block, on the serving world, within ten blocks and thirty seconds of the observed contact. The catalog lists every owned clan/company, including same-world and unregistered destinations with disabled reasons. A manager or parent controller is not treated as an owner.
`home_quote` additionally takes `target: {kind,id}` and returns current House `keyId`/`version`, `fareMinor`, `affordable`, `expiresAt`, and origin/target references containing `homeBlockId` and `claimRevision`.
`home_board` adds a durable `requestId`, the exact House key/version and fare, `confirmed:true`, `originHomeBlockId`, `originRevision`, `targetHomeBlockId` and `targetRevision`. An accepted reference is checked before rejecting stale contact proof. Fresh contact proof may be refreshed on an unrecorded retry; immutable quote/home/identity/fare fields must remain identical. The fare is reserved in the original Guild ledger and the returned pending ticket contains its exact destination server and Home Block.
At the destination, `home_arrive` (`uuid`, `server`) returns `{ok:true,schema:1,ticket}` or a null ticket. Native code checks the actual loaded UUID world, target chunk and safe floor/feet/head space. Only then does `home_ready` (`uuid`, `server`, `requestId`) revalidate current ownership and the Home Block pin and post the original reservation once. It returns the bound ticket with `state:'arrived', paid:true`. A paid ticket remains recoverable after its original reservation deadline; it is not a second purchase. Native code then teleports and durably sends `home_delivered` with the same ID, `arrivedAt`, and `arrival:{worldUuid,position}`. The acknowledgement echoes schema, request ID and `delivered:true` before the native journal can clear it.
An unfulfilled pending booking expires through the original fare-release worker. A paid receipt whose target changed returns a bound review response, preserving the receipt rather than minting a new payment or inventing refund authority. This is intentionally distinct from silently redirecting a player into a new owner's Home Block.
## Persistence and validation
`pb_guild_route_bindings` is additive bank receipt metadata, not another ownership registry. Central deed/account/claim shared read locks remain held through the single atomic bank transaction; central storage is not mutated by this route. No distributed write, cross-database grant or new bank ledger is required. All fares still use `pb_guild_passages`, the existing personal account authority and the In-game Bank Treasury. Ordinary arrival workers skip owned-home tickets, and smuggler markers continue to exclude these journeys from lawful Guild quest rewards.
Tests cover the existing Guild fare/passage behavior, distinct full catalogs, original confirmed booking replay, recorded return origins, real company/clan owner authority, contact world/distance/time, changed pins, failed ledger rollback, paid receipt recovery, malformed requests and wrong destination/arrival evidence. No real payment or player travel is generated by these checks. Source/build/host readiness and an actual player fare are separate acceptance facts.
Preserve native booking/arrival journals and bank receipts during an operational rollback. An older central/native release cannot resume this new paid Home Block protocol; do not treat restoring JARs as a refund or erase an unresolved paid delivery. Initial canary checks can use catalogs and navigation without submitting a fare.

View file

@ -0,0 +1,119 @@
{
"home_list": {
"action": "home_list",
"origin": {
"kind": "clan",
"id": "00000000-0000-4000-8000-000000000002"
},
"uuid": "00000000-0000-4000-8000-000000000001",
"sourceWorld": "caladan",
"sourceLocation": {
"worldUuid": "00000000-0000-4000-8000-000000000004",
"position": {
"x": 14,
"y": 66,
"z": -22
},
"observedAt": 1795990000000
}
},
"home_quote": {
"target": {
"kind": "company",
"id": "00000000-0000-4000-8000-000000000003"
},
"action": "home_quote",
"origin": {
"kind": "clan",
"id": "00000000-0000-4000-8000-000000000002"
},
"uuid": "00000000-0000-4000-8000-000000000001",
"sourceWorld": "caladan",
"sourceLocation": {
"worldUuid": "00000000-0000-4000-8000-000000000004",
"position": {
"x": 14,
"y": 66,
"z": -22
},
"observedAt": 1795990000000
}
},
"home_board": {
"target": {
"kind": "company",
"id": "00000000-0000-4000-8000-000000000003"
},
"requestId": "00000000-0000-4000-8000-000000000008",
"confirmed": true,
"keyId": "00000000-0000-4000-8000-000000000005",
"version": 3,
"fareMinor": 12507,
"originHomeBlockId": "00000000-0000-4000-8000-000000000006",
"originRevision": 4,
"targetHomeBlockId": "00000000-0000-4000-8000-000000000007",
"targetRevision": 8,
"action": "home_board",
"origin": {
"kind": "clan",
"id": "00000000-0000-4000-8000-000000000002"
},
"uuid": "00000000-0000-4000-8000-000000000001",
"sourceWorld": "caladan",
"sourceLocation": {
"worldUuid": "00000000-0000-4000-8000-000000000004",
"position": {
"x": 14,
"y": 66,
"z": -22
},
"observedAt": 1795990000000
}
},
"home_arrive": {
"action": "home_arrive",
"uuid": "00000000-0000-4000-8000-000000000001",
"server": "kaitain"
},
"home_ready": {
"action": "home_ready",
"uuid": "00000000-0000-4000-8000-000000000001",
"server": "kaitain",
"requestId": "00000000-0000-4000-8000-000000000008"
},
"home_delivered": {
"action": "home_delivered",
"uuid": "00000000-0000-4000-8000-000000000001",
"server": "kaitain",
"requestId": "00000000-0000-4000-8000-000000000008",
"arrivedAt": 1795990001000,
"arrival": {
"worldUuid": "00000000-0000-4000-8000-000000000009",
"position": {
"x": 100,
"y": 72,
"z": 200
}
}
},
"smuggler_quote": {
"action": "smuggler_quote",
"uuid": "00000000-0000-4000-8000-000000000001",
"sourceWorld": "sigma_draconis_iv"
},
"smuggler_board": {
"action": "smuggler_board",
"requestId": "00000000-0000-4000-8000-000000000010",
"keyId": "00000000-0000-4000-8000-000000000005",
"version": 3,
"fareMinor": 12507,
"destination": "kaitain",
"uuid": "00000000-0000-4000-8000-000000000001",
"sourceWorld": "sigma_draconis_iv"
},
"smuggler_return": {
"action": "smuggler_return",
"uuid": "00000000-0000-4000-8000-000000000001",
"sourceWorld": "kaitain"
}
}

View file

@ -0,0 +1,30 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {randomUUID} from 'node:crypto';
import {companyFixture} from './company-deed-fixture.mjs';
import {initializeClans} from '../control-panel/clans.mjs';
import {createOwnedSmugglerRoutes} from '../node/owned-smuggler-routes.mjs';
async function fixture(){
const f=await companyFixture(),owner=f.people.Owner,uuid=randomUUID(),origin=await f.create();let now=1200000;
await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[uuid,owner.id]);
const key=await f.keys.issue({accountId:owner.id,keyType:'character-allegiance',scopeId:'house:'+owner.id+':v1',authorize:async()=>{}});
f.db.sqlite.exec('CREATE TABLE site_character_choices(user_id TEXT,version INT);CREATE TABLE jarvis_house_selections(account_id TEXT,key_id TEXT);');await f.db.query('INSERT INTO site_character_choices VALUES(?,1)',[owner.id]);await f.db.query('INSERT INTO jarvis_house_selections VALUES(?,?)',[owner.id,key.id]);
async function company(name){const id=randomUUID();await f.db.query("INSERT INTO corrino_companies(id,slug,name,description,status,founded_by,created_at,updated_at) VALUES(?,?,?,'','active',?,1,1)",[id,name.toLowerCase(),name,owner.id]);await f.db.query("INSERT INTO site_company_deeds(company_id,owner_account_id,created_at,updated_at) VALUES(?,?,1,1)",[id,owner.id]);await f.db.query('INSERT INTO site_company_members VALUES(?,?,1)',[id,owner.id]);return id;}
async function claim(kind,id,world){const h={id:randomUUID(),worldUuid:randomUUID(),worldName:world,position:{x:8,y:64,z:8}};await f.db.query('INSERT INTO site_claim_registry VALUES(?,?,?,1,1)',[kind,id,JSON.stringify({organisationId:id,source:'minecraft',homeBlock:h,usedChunks:1})]);return h;}
const target=await company('Target'),unregistered=await company('Unregistered'),oh=await claim('company',origin,'caladan'),th=await claim('company',target,'arrakis'),user={...owner,keyId:key.id,version:1,faction:'atreides'};
const resolve=async(id,store=f.db)=>{const row=await store.first("SELECT a.id FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE l.minecraft_uuid=? AND a.password_hash NOT LIKE '!%'",[id]);const k=await store.first('SELECT revoked_at FROM organisation_keys WHERE id=?',[key.id]);return row?.id===owner.id&&k&&k.revoked_at==null?user:null;};
const routes=createOwnedSmugglerRoutes(f.db,{resolve,clock:()=>now}),input={uuid,sourceWorld:'caladan',origin:{kind:'company',id:origin},target:{kind:'company',id:target},sourceLocation:{worldUuid:oh.worldUuid,position:{x:8.5,y:64,z:8.5},observedAt:now},originHomeBlockId:oh.id,originRevision:1,targetHomeBlockId:th.id,targetRevision:1};
return {...f,owner,uuid,key,user,origin,target,unregistered,oh,th,routes,input,claim,setTime:v=>now=v};
}
test('actual company owner catalog retains same-world and unregistered rows and current Home Block pins',async()=>{
const f=await fixture();try{const result=await f.routes.list(f.user,f.input);assert.equal(result.destinations.length,3);assert.equal(result.destinations.find(r=>r.id===f.origin).available,false);assert.equal(result.destinations.find(r=>r.id===f.unregistered).available,false);assert.equal(result.destinations.find(r=>r.id===f.target).available,true);assert.equal((await f.routes.quote(f.user,f.input)).target.homeBlockId,f.th.id);}finally{f.db.close();}
});
test('company management alone does not grant owned-home travel, and stale target revision cannot enter the bank callback',async()=>{
const f=await fixture();try{await f.db.query('INSERT INTO site_company_members VALUES(?,?,1)',[f.target,f.people.Other.id]);await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.people.Other.id,f.target]);await f.db.query('UPDATE corrino_companies SET ceo_account_id=? WHERE id=?',[f.owner.id,f.target]);let called=false;await assert.rejects(f.routes.withLock(f.user,f.input,'board',async()=>called=true),/own active company/);assert.equal(called,false);await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.owner.id,f.target]);await f.db.query("UPDATE site_claim_registry SET revision=2 WHERE organisation_kind='company' AND organisation_id=?",[f.target]);await assert.rejects(f.routes.withLock(f.user,f.input,'board',async()=>called=true),/Home Block changed/);assert.equal(called,false);}finally{f.db.close();}
});
test('NPC contact is world-, position- and time-bound, and linked character revocation is rechecked under locks',async()=>{
const f=await fixture();try{for(const sourceLocation of [{...f.input.sourceLocation,worldUuid:randomUUID()},{...f.input.sourceLocation,position:{x:1000,y:64,z:1000}},{...f.input.sourceLocation,observedAt:1}])await assert.rejects(f.routes.quote(f.user,{...f.input,sourceLocation}),/Reopen the Navigator/);await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[f.key.id]);await assert.rejects(f.routes.withLock(f.user,f.input,'board',async()=>assert.fail('No bank callback allowed')),/character changed/);}finally{f.db.close();}
});
test('original clan deed ownership participates in the same catalog without adding a clan or changing membership',async()=>{
const f=await fixture();try{f.db.sqlite.exec('DROP TABLE site_clan_members;DROP TABLE site_clans;');await initializeClans(f.db,{mysql:false});const id=randomUUID();await f.db.query("INSERT INTO site_clans(id,name,name_key,tag,description,owner_id,home_world,created_at,updated_at) VALUES(?,'Clan','clan','CLAN','',?,'arrakduin',1,1)",[id,f.owner.id]);await f.db.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',1)",[f.owner.id,f.uuid,id]);await f.db.query('INSERT INTO site_clan_deeds(clan_id,updated_at) VALUES(?,1)',[id]);await f.claim('clan',id,'arrakis');const result=await f.routes.list(f.user,f.input);assert.equal(result.destinations.length,4);assert.equal(result.destinations.find(r=>r.kind==='clan'&&r.id===id).available,true);let entered=false;await f.routes.withLock(f.user,{...f.input,target:{kind:'clan',id},targetHomeBlockId:result.destinations.find(r=>r.id===id).homeBlockId},'board',async()=>{entered=true;});assert.equal(entered,true);assert.equal((await f.db.first('SELECT COUNT(*) n FROM site_clan_members')).n,1);}finally{f.db.close();}
});

View file

@ -0,0 +1,75 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {randomUUID} from 'node:crypto';
import {BankFixture} from './postbank-fixture.mjs';
import {PostbankService,BankError} from '../node/postbank-service.mjs';
import {BANK_VERSION} from '../node/postbank-catalogue.mjs';
import {createGuildService,createGameGuildAPI,GUILD_SCHEMA,SMUGGLER_PASSAGE_SCHEMA} from '../node/game-guild.mjs';
import {GUILD_ROUTE_SCHEMA} from '../node/guild-route-bindings.mjs';
import {readFile,writeFile} from 'node:fs/promises';
async function fixture(){
const bank=new BankFixture();for(const s of [GUILD_SCHEMA,SMUGGLER_PASSAGE_SCHEMA,GUILD_ROUTE_SCHEMA])await bank.query(s.replace(/,INDEX guild_pending\([^)]*\)/,'').replace(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4',''));
const user={id:randomUUID(),username:'traveller',uuid:randomUUID(),faction:'atreides',version:1,keyId:randomUUID()},entity={id:randomUUID(),kind:'person',key:null,name:'traveller'};entity.key=user.id;
const authority=async()=>({entities:[{...entity,canView:true,canActivate:true,canPay:true}]}),products=new PostbankService(bank,authority);
await products.activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const source=(await bank.first("SELECT id FROM pb_accounts WHERE type_code='102' AND system_key IS NULL")).id;
await bank.query('UPDATE pb_accounts SET balance_minor=40000 WHERE id=?',[source]);await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES('sys_game_treasury','999','Game treasury',0,0,'active',0)");
let now=1200000,embargo=false,owned=true,originOwned=true,revision=2,permit={keyId:randomUUID(),expiresAt:9000000};
const origin={kind:'clan',id:randomUUID(),name:'Origin',homeBlockId:randomUUID(),claimRevision:1,server:'caladan',home:{worldUuid:randomUUID(),worldName:'caladan',position:{x:8,y:64,z:8}}},target={kind:'company',id:randomUUID(),name:'Destination',homeBlockId:randomUUID(),claimRevision:2,server:'arrakis',home:{worldUuid:randomUUID(),worldName:'arrakis',position:{x:100,y:64,z:100}}};
const ref=h=>({kind:h.kind,id:h.id});
const check=(input,stage)=>{
if(!owned)throw new BankError('Current target owner required',403);if(stage!=='ready'&&!originOwned)throw new BankError('Current source owner required',403);
if(stage!=='ready'&&(Math.abs(now-input.sourceLocation.observedAt)>30000||input.sourceLocation.worldUuid!==origin.home.worldUuid))throw new BankError('Stale NPC contact',403);
if(stage!=='quote'&&input.targetRevision!==revision)throw new BankError('Home Block changed',409);return {origin,target:{...target,claimRevision:revision}};
};
const homeRoutes={list:async()=>({origin,destinations:[{...origin,available:false,reason:'Already on this world.'},{...target,available:true,reason:''},{kind:'company',id:randomUUID(),name:'Unregistered',home:null,server:null,homeBlockId:null,claimRevision:0,available:false,reason:'No registered Home Block.'}]}),quote:async(_u,i)=>check(i,'quote'),withLock:async(_u,i,stage,work)=>work(check(i,stage),user)};
const opts={authority,resolve:async uuid=>uuid===user.uuid?user:null,clock:()=>now,routeBindings:true,homeRoutes,allowSmuggling:async()=>permit,allowJourney:async()=>!embargo};
const service=createGuildService(bank,opts),input=()=>({action:'home_board',uuid:user.uuid,sourceWorld:'caladan',origin:ref(origin),target:ref(target),sourceLocation:{worldUuid:origin.home.worldUuid,position:{x:8,y:64,z:8},observedAt:now},requestId:randomUUID(),keyId:user.keyId,version:1,fareMinor:10000,confirmed:true,originHomeBlockId:origin.homeBlockId,originRevision:1,targetHomeBlockId:target.homeBlockId,targetRevision:2});
return {bank,user,source,origin,target,service,opts,input,setTime:n=>now=n,setOwned:v=>owned=v,setOriginOwned:v=>originOwned=v,setRevision:n=>revision=n,setEmbargo:v=>embargo=v,setPermit:p=>permit=p,account:()=>bank.first('SELECT balance_minor,reserved_minor FROM pb_accounts WHERE id=?',[source]),ready:i=>service.home_ready({action:'home_ready',uuid:user.uuid,server:'arrakis',requestId:i.requestId})};
}
test('ordinary Guild catalog contains every canonical world once, retaining lawful compatibility order and disabled reasons',async()=>{
const f=await fixture();try{const q=await f.service.quote(f.user.uuid);assert.equal(q.routes.length,5);assert.equal(new Set(q.routes.map(r=>r.server)).size,5);assert.equal(q.routes.filter(r=>r.name==='Arrakis').length,1);assert.deepEqual(q.destinations,['caladan']);assert.equal(q.routes.find(r=>r.server==='caladan').available,true);assert.match(q.routes.find(r=>r.server==='giedi_prime').reason,/no Imperial passage/);f.setEmbargo(true);assert.match((await f.service.quote(f.user.uuid)).routes.find(r=>r.server==='caladan').reason,/embargoed/);}finally{f.bank.close();}
});
test('Esmar routes use destination eligibility and record actual origin for confirmed return, binding retries to the same origin',async()=>{
const f=await fixture();try{const q=await f.service.quoteSmuggler(f.user.uuid,'arrakis');assert.equal(q.routes.length,5);assert.equal(q.routes.find(r=>r.server==='giedi_prime').available,true);assert.equal(q.routes.find(r=>r.server==='arrakis').available,false);assert.match(q.routes.find(r=>r.server==='caladan').reason,/ordinary Guild/);
const i={uuid:f.user.uuid,requestId:randomUUID(),keyId:f.user.keyId,version:1,fareMinor:10000,sourceWorld:'arrakis',destination:'giedi_prime'};await f.service.board(i,true);assert.equal((await f.account()).balance_minor,40000);await assert.rejects(f.service.board({...i,sourceWorld:'kaitain'},true),/already used/);await f.service.arrive(f.user.uuid,'giedi_prime');assert.equal((await f.account()).balance_minor,30000);assert.equal((await f.service.smugglerReturn(f.user.uuid,'giedi_prime')).destination,'arrakis');await assert.rejects(f.service.smugglerReturn(f.user.uuid,'kaitain'),/No confirmed/);
}finally{f.bank.close();}
});
test('an old pending lobby-Arrakis booking remains retryable when route metadata is enabled',async()=>{
const f=await fixture();try{const legacy=createGuildService(f.bank,{...f.opts,routeBindings:false,homeRoutes:null}),i={uuid:f.user.uuid,requestId:randomUUID(),keyId:f.user.keyId,version:1,fareMinor:10000,sourceWorld:'lobby',destination:'arrakis'};await legacy.board(i,true);assert.equal((await f.service.board(i,true)).replayed,true);assert.equal((await f.account()).reserved_minor,10000);await f.service.arrive(f.user.uuid,'arrakis');assert.equal((await f.service.smugglerReturn(f.user.uuid,'arrakis')).destination,'lobby');}finally{f.bank.close();}
});
test('owned list retains unavailable organisations and one reservation settles only after matching destination preflight',async()=>{
const f=await fixture();try{const i=f.input(),list=await f.service.home_list(i);assert.equal(list.destinations.length,3);assert.equal(list.destinations.filter(r=>!r.available).length,2);const quote=await f.service.home_quote(i);assert.equal(quote.fareMinor,10000);assert.equal(quote.affordable,true);
await f.service.home_board(i);assert.equal((await f.account()).reserved_minor,10000);assert.equal((await f.service.arrive(f.user.uuid,'arrakis')).passage,null);assert.equal((await f.account()).balance_minor,40000);
assert.equal((await f.service.home_arrive({uuid:f.user.uuid,server:'kaitain'})).ticket,null);assert.equal((await f.service.home_arrive({uuid:f.user.uuid,server:'arrakis'})).ticket.requestId,i.requestId);
const paid=await f.ready(i);assert.equal(paid.paid,true);assert.equal((await f.account()).balance_minor,30000);f.setTime(1500000);assert.equal((await f.ready(i)).replayed,true);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
const ack={action:'home_delivered',uuid:f.user.uuid,server:'arrakis',requestId:i.requestId,arrivedAt:1500000,arrival:{worldUuid:f.target.home.worldUuid,position:{x:100.5,y:64,z:100.5}}};await f.service.home_delivered(ack);assert.equal((await f.service.home_delivered(ack)).replayed,true);assert.equal((await f.service.home_arrive({uuid:f.user.uuid,server:'arrakis'})).ticket,null);await assert.rejects(f.service.home_delivered({...ack,arrivedAt:1500001}),/conflict/);await assert.rejects(f.service.smugglerReturn(f.user.uuid,'arrakis'),/No confirmed/);
}finally{f.bank.close();}
});
test('accepted board replays stale contact proof, but new requests and changed binding cannot reserve another fare',async()=>{
const f=await fixture();try{const i=f.input();await f.service.home_board(i);f.setTime(1240000);assert.equal((await f.service.home_board(i)).replayed,true);await assert.rejects(f.service.home_board({...i,targetRevision:3}),/already used/);await assert.rejects(f.service.home_board({...i,requestId:randomUUID()}),/Stale NPC/);assert.equal((await f.account()).reserved_minor,10000);}finally{f.bank.close();}
});
test('changed ownership before settlement leaves money untouched and expires; after settlement it preserves a paid review receipt',async()=>{
const f=await fixture();try{let i=f.input();await f.service.home_board(i);f.setOwned(false);await assert.rejects(f.ready(i),/owner/);assert.equal((await f.account()).balance_minor,40000);f.setTime(1320001);await f.service.expire();assert.equal((await f.account()).reserved_minor,0);f.setOwned(true);i=f.input();await f.service.home_board(i);await f.ready(i);f.setRevision(3);const review=await f.ready(i);assert.equal(review.needsReview,true);assert.equal(review.paid,true);assert.equal(review.requestId,i.requestId);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.bank.close();}
});
test('failed ledger posting rolls back exactly one reservation and metadata cannot create orphan fares',async()=>{
const f=await fixture();try{const i=f.input();await f.service.home_board(i);f.bank.sqlite.exec("CREATE TRIGGER reject_entry BEFORE INSERT ON pb_entries BEGIN SELECT RAISE(ABORT,'ledger down');END");await assert.rejects(f.ready(i),/ledger down/);assert.equal((await f.account()).balance_minor,40000);assert.equal((await f.account()).reserved_minor,10000);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);f.bank.sqlite.exec('DROP TRIGGER reject_entry');await f.ready(i);assert.equal((await f.account()).reserved_minor,0);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.bank.close();}
});
test('owned and ordinary bookings share the same pending-fare guard and arrival rejects wrong server or position',async()=>{
const f=await fixture();try{const i=f.input();await f.service.home_board(i);await assert.rejects(f.service.board({uuid:f.user.uuid,requestId:randomUUID(),keyId:f.user.keyId,version:1,fareMinor:10000,destination:'caladan'}),/previous passage/);await assert.rejects(f.service.home_ready({uuid:f.user.uuid,server:'kaitain',requestId:i.requestId}),/unavailable/);await f.ready(i);await assert.rejects(f.service.home_delivered({uuid:f.user.uuid,server:'arrakis',requestId:i.requestId,arrivedAt:1200000,arrival:{worldUuid:f.target.home.worldUuid,position:{x:1000,y:64,z:1000}}}),/matching native/);}finally{f.bank.close();}
});
test('home protocol rejects browser credentials, account overrides and malformed proof before service calls',async()=>{
const f=await fixture();try{const secret='s'.repeat(64),api=createGameGuildAPI(null,null,null,{GAME_LINK_SECRET:secret},{service:f.service}),send=(b,auth=secret)=>api(new Request('https://cp.dunerealms.com/internal/game/guild',{method:'POST',headers:{authorization:'Bearer '+auth,'content-type':'application/json'},body:JSON.stringify(b)}));const i=f.input();assert.equal((await send(i,'browser')).status,401);assert.equal((await send({...i,accountId:'other'})).status,400);assert.equal((await send({...i,sourceLocation:{...i.sourceLocation,worldUuid:'bad'}})).status,400);assert.equal((await send(i)).status,200);assert.equal((await f.account()).reserved_minor,10000);}finally{f.bank.close();}
});
test('actual Java wire-builder fixture passes every strict central action parser',async()=>{
const fixture=JSON.parse(await readFile(new URL('./fixtures/navigator-native-wire.json',import.meta.url),'utf8')),calls=[],service=Object.fromEntries(['home_list','home_quote','home_board','home_arrive','home_ready','home_delivered'].map(action=>[action,async b=>{calls.push(b.action);return {ok:true,schema:1};}]));
service.quoteSmuggler=async()=>{calls.push('smuggler_quote');return {ok:true};};service.board=async()=>{calls.push('smuggler_board');return {ok:true};};service.smugglerReturn=async()=>{calls.push('smuggler_return');return {ok:true};};
const secret='s'.repeat(64),api=createGameGuildAPI(null,null,null,{GAME_LINK_SECRET:secret},{service});
for(const [action,body]of Object.entries(fixture)){const result=await api(new Request('https://cp.dunerealms.com/internal/game/guild',{method:'POST',headers:{authorization:'Bearer '+secret,'content-type':'application/json'},body:JSON.stringify(body)}));assert.equal(result.status,200,action+': '+await result.text());}
assert.deepEqual(calls,Object.keys(fixture));
});
test('central response fixture comes from actual synthetic reservation, posting and delivery methods',async()=>{
const f=await fixture();try{const i=f.input(),responses={guild_quote:await f.service.quote(f.user.uuid),smuggler_quote:await f.service.quoteSmuggler(f.user.uuid),home_list:await f.service.home_list(i),home_quote:await f.service.home_quote(i)};responses.home_board=await f.service.home_board(i);responses.home_arrive=await f.service.home_arrive({uuid:f.user.uuid,server:'arrakis'});responses.home_ready=await f.ready(i);f.setRevision(3);responses.home_review=await f.ready(i);f.setRevision(2);const delivered={action:'home_delivered',uuid:f.user.uuid,server:'arrakis',requestId:i.requestId,arrivedAt:1200000,arrival:{worldUuid:f.target.home.worldUuid,position:{x:100.5,y:64,z:100.5}}};responses.home_delivered=await f.service.home_delivered(delivered);assert.equal(responses.home_ready.paid,true);assert.equal(responses.home_delivered.delivered,true);const expired=f.input();await f.service.home_board(expired);f.setTime(1320001);responses.home_expired=await f.ready(expired);assert.equal(responses.home_expired.cancelled,true);if(process.env.NAVIGATOR_WIRE_OUTPUT)await writeFile(process.env.NAVIGATOR_WIRE_OUTPUT,JSON.stringify({request:i,deliveryRequest:delivered,responses},null,2));}finally{f.bank.close();}
});
test('owned reservations and settlement reuse the held central reader for authority instead of opening another pool connection',async()=>{
const f=await fixture();try{const pinned={},original=f.opts.homeRoutes.withLock;let scopes=0;const service=createGuildService(f.bank,{...f.opts,homeRoutes:{...f.opts.homeRoutes,withLock:(u,i,s,work)=>original(u,i,s,(ctx,user)=>work(ctx,user,pinned))},authorityForStore:reader=>{assert.equal(reader,pinned);scopes++;return f.opts.authority;}}),i=f.input();await service.home_board(i);await service.home_ready({uuid:f.user.uuid,server:'arrakis',requestId:i.requestId});assert.equal(scopes,2);assert.equal((await f.account()).balance_minor,30000);}finally{f.bank.close();}
});