forked from unimatrix/web
122 lines
17 KiB
JavaScript
122 lines
17 KiB
JavaScript
import {randomUUID,createHash} from 'node:crypto';
|
||
import {identity} from './auth.mjs';
|
||
import {accessFor} from './permissions.mjs';
|
||
import {gameAuthorized,validUuid as uuid} from './game-link.mjs';
|
||
import {boardReadStore} from './board-deed-source.mjs';
|
||
import {readClanDeed,clanDeedAuthority} from './clan-deeds.mjs';
|
||
import {readCompanyDeed,companyDeedView} from './company-deeds.mjs';
|
||
import {createRebellionQuests} from './rebellion-quests.mjs';
|
||
import {CLAN_HOMEWORLDS} from '../control-panel/clans.mjs';
|
||
import {nativeServer,NATIVE_SERVERS} from './native-server-scope.mjs';
|
||
import {entityId,createPostbankAuthority} from './postbank-authority.mjs';
|
||
import {canDebitAccount} from './postbank-authorisations.mjs';
|
||
import {PostbankPayments} from './postbank-payments.mjs';
|
||
import {BankError} from './postbank-service.mjs';
|
||
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
|
||
const first=(db,sql,args=[])=>db.first?db.first(sql,args):db.query(sql,args).then(rows=>rows[0]||null);
|
||
const houseWorld={atreides:'kaladam',harkonnen:'giedermark',corrino:'kaiterhof',ordos:'sigmadraken_iv',fremen:'arrakduin'};
|
||
const accountsSQL='SELECT a.*,c.entity_id,e.kind,e.external_key,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';
|
||
export function relocationFee(accounts){return (accounts.reduce((sum,a)=>sum+(BigInt(a.balance_minor)>0n?BigInt(a.balance_minor):0n),0n)+9n)/10n;}
|
||
export function createHomeRelocation(db,bank,keys,settings={},deps={}){
|
||
const clock=deps.clock||Date.now,authenticate=deps.authenticate||(r=>identity(r,db)),access=deps.access||(u=>accessFor(db,u));
|
||
const read=tx=>{const reader=boardReadStore(tx,db);if(tx!==db)reader.readSnapshot=async work=>work(reader);return reader;};let schema,storage;
|
||
async function ready(){if(!storage)storage=(async()=>{
|
||
if(!bank||!keys)throw new BankError('Home Block banking is unavailable.',503);
|
||
if(deps.verifyStorage){schema=await deps.verifyStorage();return;}
|
||
const [b,c]=await Promise.all([bank.first('SELECT DATABASE() db,@@hostname host,@@port port,@@server_id server_id'),first(db,'SELECT DATABASE() db,@@hostname host,@@port port,@@server_id server_id')]);
|
||
if(!/^[a-z][a-z0-9_]{2,63}$/.test(b?.db||'')||!c||['host','port','server_id'].some(k=>String(b[k])!==String(c[k])))throw Error('Relocation requires one transaction server');schema=b.db;
|
||
// Fail closed before quoting if the central transaction cannot access its bank tables.
|
||
await first(db,'SELECT id FROM `'+schema+'`.pb_accounts LIMIT 1');
|
||
const required={
|
||
[schema]:['pb_entities','pb_clients','pb_packages','pb_accounts','pb_account_authorisations','pb_orders','pb_entries','pb_audit'],
|
||
[c.db]:['site_claim_registry','jarvis_game_organisation_actions','organisation_keys','organisation_key_events','codex_instance_editions','account_audit']
|
||
};
|
||
for(const [database,tables]of Object.entries(required)){
|
||
const rows=await db.query('SELECT TABLE_NAME name,ENGINE engine FROM information_schema.TABLES WHERE TABLE_SCHEMA=? AND TABLE_NAME IN ('+tables.map(()=>'?').join(',')+')',[database,...tables]);
|
||
if(tables.some(name=>!rows.some(row=>row.name===name&&String(row.engine).toLowerCase()==='innodb')))throw Error('Relocation requires transactional tables');
|
||
}
|
||
})().catch(e=>{storage=null;throw e;});return storage;}
|
||
function banking(tx){if(!schema)return tx;const qualify=sql=>sql.replace(/\b(pb_[a-z_]+)\b/g,'`'+schema+'`.`$1`');return{query:(sql,args=[])=>tx.query(qualify(sql),args),first:(sql,args=[])=>first(tx,qualify(sql),args)};}
|
||
async function context(tx,user,kind,id,lock=false){
|
||
if(!['clan','company'].includes(kind)||!uuid(id))throw new BankError('Choose a clan or company.');
|
||
if(lock)await tx.first(kind==='clan'?'SELECT id FROM site_clans WHERE id=? FOR UPDATE':'SELECT company_id FROM site_company_deeds WHERE company_id=? FOR UPDATE',[id]);
|
||
const r=read(tx);let ownerId,charter,name,version,worldKey,institution;
|
||
if(kind==='clan'){
|
||
const p=await clanDeedAuthority(r,user.id,id),d=p.deed||await readClanDeed(r,id);if(!p.canManage||!d.clan.active)throw new BankError('Current clan management is required.',403);
|
||
({name}=d.clan);ownerId=d.clan.owner_id;charter=d.kind;version=d.version;institution=d.clan.institution_key;
|
||
const choice=await r.first('SELECT c.faction FROM site_character_choices c JOIN site_game_links l ON l.minecraft_uuid=c.minecraft_uuid WHERE l.user_id=?',[ownerId]);worldKey=houseWorld[choice?.faction]||d.clan.home_world;
|
||
}else{
|
||
const d=await readCompanyDeed(r,id);if(!companyDeedView(d,user.id).canManage||d.company.status!=='active')throw new BankError('Current company management is required.',403);
|
||
name=d.company.name;ownerId=d.company.owner_account_id;charter=d.company.charter_kind;version=d.version;institution=d.company.institution_key;
|
||
const official=await r.first('SELECT institution_key FROM site_company_institutions WHERE company_id=?',[id]);institution||=official?.institution_key;
|
||
}
|
||
if(institution)throw new BankError('Official homeworlds follow their office deed.',403);
|
||
const linked=await r.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[user.id]);if(!uuid(linked?.minecraft_uuid))throw new BankError('Link Minecraft before moving a Home Block.',403);
|
||
const basic=!['original','royal'].includes(charter),funding={entityId:entityId(basic?'person':kind,basic?ownerId:id),types:basic?['102','108']:['105'],name:basic?'Owner’s personal accounts':name+' treasury'};
|
||
const wars=[...await createRebellionQuests(r,null,{clock}).nativeWars(),...(deps.extraWars?await deps.extraWars():[])];if(wars.some(w=>(w.active||w.reserved)&&(w.attackerId===id||w.defenderId===id)))throw new BankError('Home Blocks cannot move while a war is scheduled or active.',409);
|
||
return{name,version,ownerId,worldKey,funding,uuid:linked.minecraft_uuid.toLowerCase()};
|
||
}
|
||
async function quoteIn(tx,user,input,lock=false){
|
||
const c=await context(tx,user,input.kind,input.id,lock),row=await first(tx,'SELECT snapshot_json,revision FROM site_claim_registry WHERE organisation_kind=? AND organisation_id=?'+(lock?' FOR UPDATE':''),[input.kind,input.id]);
|
||
if(!row)throw new BankError('Register a Home Block first.',409);const snapshot=JSON.parse(row.snapshot_json);
|
||
if(snapshot.relocation&&snapshot.relocation.phase!=='completed')return{pending:true,phase:snapshot.relocation.phase,requestId:snapshot.relocation.requestId,destination:snapshot.relocation.worldKey,kind:input.kind,id:input.id};
|
||
if(!snapshot.homeBlock||!['minecraft','web-development'].includes(snapshot.source)||row.snapshot_json.length>45000)throw new BankError('The current estate requires review.',409);
|
||
const worldKey=input.kind==='clan'?c.worldKey:input.worldKey,world=CLAN_HOMEWORLDS.find(w=>w.key===worldKey);if(!world)throw new BankError('Choose a destination world.');
|
||
const b=banking(tx),accounts=await b.query(accountsSQL+' WHERE c.entity_id=? AND a.type_code IN ('+c.funding.types.map(()=>'?').join(',')+') AND a.system_key IS NULL ORDER BY a.id'+(lock?' FOR SHARE':''),[c.funding.entityId,...c.funding.types]);
|
||
const usable=accounts.filter(a=>a.state==='active'&&a.package_state==='active'&&Number(a.entity_active)===1),authority=deps.authority||createPostbankAuthority(rFor(tx),{bank:b}),rights=await authority(user,{bank:b}),fee=relocationFee(usable);
|
||
const choices=usable.filter(a=>canDebitAccount(rights,c.funding.entityId,a.id)).map(a=>({id:String(a.id),number:a.account_number,name:a.display_name,availableMinor:String(BigInt(a.balance_minor)-BigInt(a.reserved_minor))}));
|
||
if(!choices.length)throw new BankError('An authorised funding account is required.',403);
|
||
const result={kind:input.kind,id:input.id,name:c.name,version:c.version,revision:Number(row.revision),worldKey,worldName:world.name,fromWorld:snapshot.homeBlock.worldName,feeMinor:String(fee),funding:c.funding.name,accounts:choices,worlds:input.kind==='company'?CLAN_HOMEWORLDS:CLAN_HOMEWORLDS.filter(w=>w.key===worldKey)};
|
||
result.quoteHash=hash({...result,accounts:undefined});return{...result,_context:c,_snapshot:snapshot};
|
||
}
|
||
const rFor=tx=>{const r=read(tx);r.clanDeedsEnabled=db.clanDeedsEnabled;r.companyDeedsEnabled=db.companyDeedsEnabled;return r;};
|
||
const publicQuote=q=>{const {_context,_snapshot,...out}=q;return out;};
|
||
async function quote(user,input){await ready();return publicQuote(await quoteIn(db,user,input));}
|
||
async function accept(user,input){
|
||
if(!uuid(input.requestId)||input.confirmed!==true||typeof input.quoteHash!=='string'||!/^[a-f0-9]{64}$/.test(input.quoteHash)||!/^\d{1,12}$/.test(input.sourceAccount||''))throw new BankError('Review and confirm the relocation quote.');
|
||
await ready();const digest=hash([user.id,input]);return db.transaction(async tx=>{
|
||
// Serialise requests for this deed before checking either the charge or its key.
|
||
const c=await context(tx,user,input.kind,input.id,true),prior=await tx.first('SELECT * FROM jarvis_game_organisation_actions WHERE request_id=? FOR UPDATE',[input.requestId]);
|
||
if(prior){if(prior.account_id!==user.id||prior.action_id!=='home-relocate'||prior.input_hash!==digest)throw new BankError('This request reference was already used.',409);return{...JSON.parse(prior.result_json),previous:undefined,replayed:true};}
|
||
// Match normal bank transfers: entity first, then every affected account in ID order.
|
||
const b=banking(tx);await b.first('SELECT id FROM pb_entities WHERE id=? FOR SHARE',[c.funding.entityId]);
|
||
const taxMeta=await b.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'");if(!taxMeta)throw new BankError('The tax treasury is unavailable.',503);
|
||
const fundingIds=await b.query('SELECT a.id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE c.entity_id=? AND a.type_code IN ('+c.funding.types.map(()=>'?').join(',')+') AND a.system_key IS NULL',[c.funding.entityId,...c.funding.types]);
|
||
const lockIds=[...new Set([...fundingIds.map(a=>String(a.id)),String(taxMeta.id)])];
|
||
await b.query('SELECT id FROM pb_accounts WHERE id IN ('+lockIds.map(()=>'?').join(',')+') ORDER BY id FOR UPDATE',lockIds);
|
||
const q=await quoteIn(tx,user,input,true);if(q.pending||q.quoteHash!==input.quoteHash)throw new BankError('The relocation quote changed. Refresh it before confirming.',409);
|
||
if(!q.accounts.some(a=>a.id===input.sourceAccount))throw new BankError('Choose an authorised funding account.',403);
|
||
const sourceMeta=await b.first(accountsSQL+' WHERE a.id=?',[input.sourceAccount]);
|
||
const rows=await b.query('SELECT * FROM pb_accounts WHERE id IN (?,?) ORDER BY id FOR UPDATE',[input.sourceAccount,taxMeta.id]),sourceRow=rows.find(a=>String(a.id)===input.sourceAccount),source=sourceMeta&&sourceRow?{...sourceMeta,...sourceRow}:null,tax=rows.find(a=>String(a.id)===String(taxMeta.id)),amount=BigInt(q.feeMinor);
|
||
if(!source||!tax||source.entity_id!==c.funding.entityId||source.state!=='active'||tax.state!=='active'||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<amount)throw new BankError('Insufficient available funds.',409);
|
||
if(String(source.id)===String(tax.id)||BigInt(tax.balance_minor)+amount>9223372036854775807n)throw new BankError('The transfer cannot be posted safely.',409);
|
||
let receipt;
|
||
await keys.issue({accountId:user.id,keyType:'organisation-action',scopeId:'game:'+input.requestId,transactionStore:tx,authorize:async(_,{keyId})=>{
|
||
const old=q._snapshot,fromServer=old.source==='minecraft'?nativeServer(old.homeBlock.worldName):null,toServer=nativeServer(q.worldKey),now=clock();if(!toServer||old.source==='minecraft'&&!fromServer)throw new BankError('The registered world requires review.',409);
|
||
receipt={ok:true,kind:input.kind,id:input.id,requestId:input.requestId,keyId,feeMinor:q.feeMinor,worldKey:q.worldKey,fromServer,toServer,phase:fromServer?'cleanup':'ready',previous:old};
|
||
if(amount>0n){await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[input.requestId,user.id,source.id,tax.id,digest,String(amount),'Home Block relocation · '+q.name,now]);await new PostbankPayments(bank,null,{clock}).post(b,{id:input.requestId,actor_id:user.id,amount_minor:String(amount)},source,tax,false);}
|
||
const relocation={requestId:input.requestId,keyId,worldKey:q.worldKey,fromServer,toServer,phase:receipt.phase,requestedAt:now};
|
||
const snapshot={...old,source:'relocating',keyId,homeBlock:null,estates:[],usedChunks:0,relocation};
|
||
await tx.query('UPDATE site_claim_registry SET snapshot_json=?,revision=revision+1,updated_at=? WHERE organisation_kind=? AND organisation_id=?',[JSON.stringify(snapshot),now,input.kind,input.id]);
|
||
await tx.query('INSERT INTO jarvis_game_organisation_actions(request_id,key_id,account_id,minecraft_uuid,action_id,input_hash,result_json,state,expires_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',[input.requestId,keyId,user.id,c.uuid,'home-relocate',digest,JSON.stringify(receipt),'pending',0,now]);
|
||
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),user.id,'home-block-relocation',JSON.stringify({kind:input.kind,id:input.id,keyId,requestId:input.requestId,feeMinor:q.feeMinor,fromServer,toServer}),now]);
|
||
}});return{...receipt,previous:undefined};
|
||
});
|
||
}
|
||
async function acknowledge(input){
|
||
if(!NATIVE_SERVERS.includes(input.server)||input.server==='lobby'||!uuid(input.requestId)||!uuid(input.keyId))throw new BankError('Invalid cleanup receipt.');
|
||
return db.transaction(async tx=>{const action=await tx.first("SELECT * FROM jarvis_game_organisation_actions WHERE request_id=? AND action_id='home-relocate' FOR UPDATE",[input.requestId]);if(!action||action.key_id!==input.keyId)throw new BankError('Unknown relocation receipt.',409);const result=JSON.parse(action.result_json);if(result.fromServer!==input.server)throw new BankError('Cleanup belongs to another server.',403);
|
||
const row=await tx.first('SELECT snapshot_json FROM site_claim_registry WHERE organisation_kind=? AND organisation_id=? FOR UPDATE',[result.kind,result.id]);if(!row)throw new BankError('The estate changed.',409);const snapshot=JSON.parse(row.snapshot_json),r=snapshot.relocation;if(r?.requestId!==input.requestId||r.keyId!==input.keyId)throw new BankError('The relocation changed.',409);if(r.phase==='ready'||r.phase==='completed')return{ok:true,replayed:true};if(r.phase!=='cleanup')throw new BankError('Cleanup is not pending.',409);
|
||
const instrument=await tx.first('SELECT id FROM organisation_keys WHERE id=? AND revoked_at IS NULL',[input.keyId]);if(!instrument)throw new BankError('The relocation instrument requires review.',409);
|
||
r.phase='ready';r.cleanedAt=clock();result.phase='ready';await tx.query('UPDATE site_claim_registry SET snapshot_json=?,revision=revision+1,updated_at=? WHERE organisation_kind=? AND organisation_id=?',[JSON.stringify(snapshot),clock(),result.kind,result.id]);await tx.query('UPDATE jarvis_game_organisation_actions SET result_json=? WHERE request_id=?',[JSON.stringify(result),input.requestId]);return{ok:true,phase:'ready'};
|
||
});
|
||
}
|
||
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
||
async function api(request){try{
|
||
const url=new URL(request.url),user=await authenticate(request);if(!user)return reply({message:'Sign in to move a Home Block.'},401);if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Game access required.'},403);
|
||
if(request.method==='GET'){const input=Object.fromEntries(url.searchParams);if(Object.keys(input).some(k=>!['kind','id','worldKey'].includes(k)))throw new BankError('Invalid fields.');return reply(await quote(user,input));}
|
||
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);if(url.search||request.headers.get('origin')!==(settings.CP_ORIGIN||'https://cp.dunerealms.com'))throw new BankError('Request origin rejected.',403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))throw new BankError('JSON required.',415);const raw=await request.text();if(raw.length>2048)throw new BankError('Request too large.',413);const input=JSON.parse(raw);if(Object.keys(input).some(k=>!['kind','id','worldKey','requestId','sourceAccount','quoteHash','confirmed'].includes(k)))throw new BankError('Invalid fields.');return reply(await accept(user,input));
|
||
}catch(e){return reply({message:e.status?e.message:'Home Block relocation is temporarily unavailable.'},e.status||503);}}
|
||
async function cleanupAPI(request){try{if(request.method!=='POST'||!gameAuthorized(request,settings))return reply({message:'Unauthorized'},401);const raw=await request.text();if(raw.length>512)throw new BankError('Invalid receipt.');const input=JSON.parse(raw);if(Object.keys(input).some(k=>!['server','requestId','keyId'].includes(k)))throw new BankError('Invalid receipt.');return reply(await acknowledge(input));}catch(e){return reply({message:e.status?e.message:'Cleanup receipt could not be recorded.'},e.status||503);}}
|
||
return{quote,accept,acknowledge,api,cleanupAPI};
|
||
}
|

Staff