MC/website/node/world-trade-governance.mjs
2026-11-27 23:43:05 +00:00

77 lines
11 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {createHash} from 'node:crypto';
import {boardReadStore} from './board-deed-source.mjs';
import {officeAuthority} from './political-decisions.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {validUuid} from './game-link.mjs';
import {identity} from './auth.mjs';
import {accessFor} from './permissions.mjs';
import {entityId} from './postbank-authority.mjs';
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
import {polProgressionStore} from './progression-pol.mjs';
import {readActiveXPSeason} from './progression-xp-store.mjs';
import {levelForXP} from './progression-definitions.mjs';
import {TRADE_WORLDS,tradeDecision,TRADE_COOLDOWN_MS,EMBARGO_DURATION_MS} from '../control-panel/public/world-trade-policy.mjs';
export const WORLD_TRADE_SCHEMA=[
`CREATE TABLE IF NOT EXISTS jarvis_trade_rules(scope_key VARCHAR(32) PRIMARY KEY,request_id CHAR(36)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS jarvis_trade_governance(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,scope_key VARCHAR(32) NOT NULL,decision_id VARCHAR(24) NOT NULL,office_key VARCHAR(32) NOT NULL,world VARCHAR(32) NOT NULL,percent INT NOT NULL,actor_id CHAR(36) NOT NULL,term_id CHAR(36) NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
];
const scopes=['guild',...TRADE_WORLDS.map(w=>'house:'+w.house)];
export async function initializeWorldTrade(db){for(const sql of WORLD_TRADE_SCHEMA)await db.query(sql);for(const scope of scopes)await db.query('INSERT INTO jarvis_trade_rules(scope_key) VALUES(?) ON DUPLICATE KEY UPDATE scope_key=VALUES(scope_key)',[scope]);db.worldTradeEnabled=true;}
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
const stateSQL="SELECT r.scope_key,g.*,k.id verified_key FROM jarvis_trade_rules r LEFT JOIN jarvis_trade_governance g ON g.request_id=r.request_id LEFT JOIN organisation_keys k ON k.id=g.key_id AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:world-trade:',g.request_id) AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at>?)";
export async function worldTradeSnapshot(store,now=Date.now(),{lock=false}={}){
const rows=await store.query(stateSQL+(lock?' FOR SHARE':''),[STAFF_OFFICE_ACCOUNT_ID,now]);
const worlds=Object.fromEntries(TRADE_WORLDS.map(w=>[w.id,{world:w.id,house:w.house,percent:0,taxRequestId:null,embargoUntil:null}]));
for(const row of rows){const w=worlds[row.world];if(!w||!row.verified_key)continue;
if(row.scope_key==='house:'+w.house&&row.office_key===w.house&&row.decision_id===tradeDecision(({atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',fremen:'FRE'})[w.house]+'-TRADE')?.id&&Number.isInteger(Number(row.percent))&&Number(row.percent)>=0&&Number(row.percent)<=5){w.percent=Number(row.percent);w.taxRequestId=row.request_id;}
if(row.scope_key==='guild'&&row.office_key==='spacing_guild'&&row.decision_id==='SG-EMBARGO'&&Number(row.expires_at)>now&&Number(row.expires_at)===Number(row.created_at)+EMBARGO_DURATION_MS)w.embargoUntil=Number(row.expires_at);
}
return worlds;
}
// Read policy through the purchase's original bank connection, after verifying
// that central policy and bank records share one transactional MySQL server.
export function createBankTradePolicy(db,bank){let ready;
async function view(){if(!ready)ready=(async()=>{
const sql='SELECT DATABASE() db,@@hostname host,@@port port,@@server_id server_id';
const [central,b]=await Promise.all([boardReadStore(db,db).first(sql),bank.first(sql)]);
if(!/^[a-z][a-z0-9_]{2,63}$/.test(central?.db||'')||!b||['host','port','server_id'].some(k=>String(central[k])!==String(b[k])))throw Error('Transactional trade policy storage required');
const names=['jarvis_trade_rules','jarvis_trade_governance','organisation_keys'],rows=await bank.query('SELECT TABLE_NAME name,ENGINE engine FROM information_schema.TABLES WHERE TABLE_SCHEMA=? AND TABLE_NAME IN (?,?,?)',[central.db,...names]);
if(names.some(n=>!rows.some(r=>r.name===n&&r.engine==='InnoDB')))throw Error('Transactional trade policy tables required');
return central.db;
})().catch(e=>{ready=null;throw e;});return ready;}
return async(tx,now=Date.now(),lock=false)=>{const schema=await view(),qualify=sql=>sql.replace(/\b(jarvis_trade_rules|jarvis_trade_governance|organisation_keys)\b/g,'`'+schema+'`.`$1`');return worldTradeSnapshot({query:(sql,args)=>tx.query(qualify(sql),args)},now,{lock});};
}
export function createWorldTradeGovernance(base,keys,{clock=Date.now,bank=null,eligibleHouse=async house=>{if(!bank)return false;const rows=await bank.query("SELECT a.*,e.active entity_active,p.state package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id WHERE e.id=? AND a.system_key IS NULL",[entityId('office','leader:'+house)]);return rows.some(ordinaryPaymentAccount);}}={}){
if(typeof base?.query!=='function')return{read:async()=>fail('Trade decisions are unavailable.',503),execute:async()=>fail('Trade decisions are unavailable.',503)};
const db=boardReadStore(base,base);db.transaction=typeof base.transaction==='function'?base.transaction.bind(base):async()=>fail('Trade decisions are unavailable.',503);
async function level(tx,actor,now){const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,now),row=await pol.first('SELECT effective_xp FROM jarvis_progression_accounts WHERE account_id=?',[actor.id]);return levelForXP(Number(row?.effective_xp||0),{base:Number(season.curve_base),cap:Number(season.level_cap)||null});}
async function read(actor,id){const d=tradeDecision(id);if(!d)fail('Unknown trade decision.',400);const now=clock(),scope=d.kind==='tax'?'house:'+d.office:'guild',row=await db.first('SELECT g.* FROM jarvis_trade_rules r LEFT JOIN jarvis_trade_governance g ON g.request_id=r.request_id WHERE r.scope_key=?',[scope]),holder=await officeAuthority(db,d,actor,now),levelNow=holder?await level(db,actor,now):0,cooldownUntil=row?.created_at?Number(row.created_at)+TRADE_COOLDOWN_MS:null;
return{...d,available:base.worldTradeEnabled!==false,bankReady:d.kind!=='tax'||!!holder&&await eligibleHouse(d.office),worlds:TRADE_WORLDS,policies:await worldTradeSnapshot(db,now),canManage:!!holder,canExecute:base.worldTradeEnabled!==false&&!!holder&&!!keys&&levelNow>=d.level&&(!cooldownUntil||now>=cooldownUntil),levelNow,cooldownUntil,requestId:row?.request_id||null};
}
async function execute(actor,input){
if(base.worldTradeEnabled===false)fail('Trade decisions are being prepared. Please return shortly.',503);
const d=tradeDecision(input?.decisionId),fields=d?.kind==='tax'?'confirmed,decisionId,percent,requestId':'confirmed,decisionId,requestId,world';
if(!d||!input||Object.keys(input).sort().join(',')!==fields||input.confirmed!==true||!validUuid(input.requestId)||d.kind==='tax'&&(!Number.isInteger(input.percent)||input.percent<0||input.percent>5)||d.kind==='embargo'&&!TRADE_WORLDS.some(w=>w.id===input.world))fail('Review and confirm a registered trade decision.',400);
if(!keys)fail('The key service is unavailable.',503);
const scope=d.kind==='tax'?'house:'+d.office:'guild',world=d.world||input.world,percent=d.kind==='tax'?input.percent:0,requestId=input.requestId.toLowerCase(),digest=createHash('sha256').update(JSON.stringify([actor.id,d.id,world,percent])).digest('hex');let receipt;
await db.transaction(async raw=>{const tx=boardReadStore(raw,db),now=clock(),holder=await officeAuthority(tx,d,actor,now,true);if(!holder)fail('The current elected office holder is required.',403);
const rule=await tx.first('SELECT * FROM jarvis_trade_rules WHERE scope_key=? FOR UPDATE',[scope]);if(!rule)fail('Trade policy is unavailable.',503);
const prior=await tx.first('SELECT * FROM jarvis_trade_governance WHERE request_id=?',[requestId]);if(prior){if(prior.actor_id!==actor.id||prior.input_hash!==digest)fail('This decision reference was already used.');receipt={ok:true,requestId,keyId:prior.key_id,replayed:true};return;}
const latest=rule.request_id&&await tx.first('SELECT created_at FROM jarvis_trade_governance WHERE request_id=?',[rule.request_id]);if(latest&&now<Number(latest.created_at)+TRADE_COOLDOWN_MS)fail('This office decision is on its seven-day cooldown.');
if(await level(tx,actor,now)<d.level)fail('Reputation level '+d.level+' is required.',403);
if(d.kind==='tax'&&percent>0&&!await eligibleHouse(d.office))fail('Activate this House’s bank account before enabling a trade levy. No policy was changed.',409);
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:world-trade:'+requestId,transactionStore:tx,authorize:async(_,{keyId})=>{
await tx.query('INSERT INTO jarvis_trade_governance(request_id,key_id,scope_key,decision_id,office_key,world,percent,actor_id,term_id,input_hash,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)',[requestId,keyId,scope,d.id,d.office,world,percent,actor.id,holder.termId,digest,now,d.kind==='embargo'?now+EMBARGO_DURATION_MS:null]);
await tx.query('UPDATE jarvis_trade_rules SET request_id=? WHERE scope_key=?',[requestId,scope]);receipt={ok:true,requestId,keyId,replayed:false};
}});
});return{...receipt,...await read(actor,d.id)};
}
return{read,execute};
}
export function createWorldTradeAPI(db,keys,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=a=>accessFor(db,a),bank=null,service=createWorldTradeGovernance(db,keys,{bank})}={}){
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
return async request=>{try{const actor=await authenticate(request);if(!actor)return reply({message:'Sign in first.'},401);if(!(await access(actor)).nodes.includes('web.menu.game'))return reply({message:'Player access required.'},403);
const url=new URL(request.url);if(request.method==='GET'){if(url.searchParams.size!==1||url.searchParams.getAll('decisionId').length!==1)return reply({message:'Choose one decision.'},400);return reply(await service.read(actor,url.searchParams.get('decisionId')));}
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);if(url.search||request.headers.get('origin')!==origin)return reply({message:'Origin or query rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);const raw=await request.text();if(raw.length>2048)return reply({message:'Request too large.'},413);let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid trade decision.'},400);}return reply(await service.execute(actor,body));
}catch(e){return reply({message:e.status?e.message:'Trade decision was not confirmed. Refresh before retrying.'},e.status||503);}};
}