Bind raid orders and recovery to atomic Postbank receipts

This commit is contained in:
unimatrixgit 2026-11-29 15:55:27 +01:00
commit 23b1879de2
5 changed files with 451 additions and 4 deletions

View file

@ -0,0 +1,98 @@
import {createHash} from 'node:crypto';
import {atomicBankAccess} from './atomic-bank-access.mjs';
import {boardReadStore} from './board-deed-source.mjs';
import {clanWarAuthority} from './clan-deeds.mjs';
import {readGameNativeState} from './game-native-state.mjs';
import {clanWarBranch} from './war-rosters.mjs';
import {createPostbankAuthority,entityId} from './postbank-authority.mjs';
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
import {canDebitAccount} from './postbank-authorisations.mjs';
import {PostbankPayments} from './postbank-payments.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
const accountsSQL='SELECT a.*,c.entity_id,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 tables=['jarvis_imperial_raid_guard','jarvis_imperial_raid_orders','jarvis_imperial_raid_clans','jarvis_imperial_raid_events','jarvis_imperial_raid_jobs','organisation_keys','organisation_key_events','codex_instance_editions','site_accounts','site_game_links','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_claim_registry'];
export function raidRecoveryId(orderId){const h=createHash('sha256').update('imperial-raid-refund:'+orderId).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);}
export function createImperialRaidCommerce(raw,bank,keys,{clock=Date.now,verifyStorage,readState=readGameNativeState,warAuthority=clanWarAuthority,bankAuthority=createPostbankAuthority,verifyCampaigns=true}={}){
const db=boardReadStore(raw,raw),banking=atomicBankAccess(db,bank,{verifyStorage,centralTables:tables,bankTables:verifyCampaigns?['jarvis_war_campaigns']:[]});
const reader=tx=>{const r=boardReadStore(tx,raw);r.readSnapshot=undefined;return r;};
async function resolveActor(tx,uuid,{lock=false}={}){
const rows=await tx.query('SELECT a.id,a.username,a.role,a.password_hash FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE l.minecraft_uuid=?'+(lock?' FOR UPDATE':''),[uuid]);
if(rows.length!==1||String(rows[0].password_hash).startsWith('!')||['system_account','official','official_account','memorial'].includes(rows[0].role))fail('Link an active personal Minecraft account first.',403);
return rows[0];
}
async function funding(tx,actor,clanId){
const r=reader(tx),b=banking.view(r),rights=await bankAuthority(r,{bank:b,clock})(actor,{bank:b});
return (await b.query(accountsSQL+' WHERE c.entity_id=? AND a.system_key IS NULL ORDER BY a.id',[entityId('clan',clanId)])).filter(a=>ordinaryPaymentAccount(a)&&canDebitAccount(rights,a.entity_id,a.id));
}
async function resolveContext(tx,input,{lock=false}={}){
const actor=await resolveActor(tx,input.uuid,{lock});
if(lock){
const ids=[input.orderingClanId,input.targetClanId].sort();
await tx.query('SELECT id FROM site_clans WHERE id IN (?,?) ORDER BY id FOR UPDATE',ids);
await tx.query('SELECT clan_id FROM site_clan_deeds WHERE clan_id IN (?,?) ORDER BY clan_id FOR UPDATE',ids);
await tx.query('SELECT clan_id FROM site_clan_charters WHERE clan_id IN (?,?) ORDER BY clan_id FOR UPDATE',ids);
await tx.query('SELECT user_id FROM site_clan_members WHERE clan_id IN (?,?) ORDER BY clan_id,user_id FOR UPDATE',ids);
await tx.query("SELECT organisation_id FROM site_claim_registry WHERE organisation_kind='clan' AND organisation_id IN (?,?) ORDER BY organisation_id FOR UPDATE",ids);
}
const r=reader(tx),rights=await warAuthority(r,actor.id,input.orderingClanId);
if(!rights.canManageWar)fail('Current clan war authority is required.',403);
const state=await readState(r,{clock}),a=state.clans.find(c=>c.id===input.orderingClanId),b=state.clans.find(c=>c.id===input.targetClanId);
if(!a||!b||a.lifecycle!=='active'||b.lifecycle!=='active'||a.protected||b.protected||a.hidden||b.hidden)fail('Choose two active unprotected rival clans.');
const branchA=new Set(clanWarBranch(state.clans,a.id).map(c=>c.id)),branchB=new Set(clanWarBranch(state.clans,b.id).map(c=>c.id));
if([...branchA].some(id=>branchB.has(id)))fail('Members of the same clan hierarchy cannot order raids against each other.');
if(b.homeServer!==input.server||!b.homeBlock||b.homeBlock.source!=='minecraft')fail('Travel to the target clan’s registered world before ordering this raid.');
if((state.wars||[]).some(w=>(w.active||w.reserved)&&[w.attackerId,w.defenderId].some(id=>branchA.has(id)||branchB.has(id))))fail('A participating clan already has a scheduled or active war.');
if(verifyCampaigns){
const campaigns=await banking.view(r).query('SELECT snapshot_json FROM jarvis_war_campaigns WHERE ends_at>? ORDER BY starts_at,id LIMIT 501',[clock()]);
if(campaigns.length>500)fail('The war register requires reconciliation.');
for(const row of campaigns){const c=JSON.parse(row.snapshot_json);if(c.cancelledAt==null&&!c.winnerSideId&&c.teams.some(t=>(t.clanIds||[t.id]).some(id=>branchA.has(id)||branchB.has(id))))fail('A participating clan already has a scheduled or active campaign.');}
}
const accounts=await funding(r,actor,a.id);
if(!accounts.length)fail('This clan needs a current authorised clan bank account. Personal accounts cannot fund Imperial raids.',403);
const charters=await r.query('SELECT clan_id,key_id FROM site_clan_charters WHERE clan_id IN (?,?) ORDER BY clan_id',[a.id,b.id]);
if(charters.length!==2)fail('Both current clan charters are required.');
return {orderingClanName:a.name,targetClanName:b.name,home:{worldUuid:b.homeBlock.worldUuid.toLowerCase(),position:structuredClone(b.homeBlock.position),claimRevision:b.claimRevision},authority:{actorId:actor.id,orderingVersion:a.version,targetVersion:b.version,orderingOwnerUuid:a.ownerUuid,targetOwnerUuid:b.ownerUuid,charters},accounts:accounts.map(a=>({id:String(a.id),name:a.display_name,availableMinor:String(BigInt(a.balance_minor)-BigInt(a.reserved_minor))}))};
}
async function issue(tx,scopeId,authorize){
if(!keys)fail('JARVIS raid receipts are unavailable.',503);
const existing=await tx.first("SELECT id FROM organisation_keys WHERE account_id=? AND key_type='entity-state' AND scope_id=? FOR UPDATE",[STAFF_OFFICE_ACCOUNT_ID,scopeId]);
if(existing)fail('The original raid receipt requires reconciliation.');
return keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId,transactionStore:reader(tx),authorize});
}
async function charge(tx,p){
const r=reader(tx),b=banking.view(r),actor=await resolveActor(r,p.actorUuid,{lock:true});
if(actor.id!==p.actorId)fail('The original raid actor changed.',403);
const tax=await b.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'");if(!tax)fail('The existing Tax treasury is unavailable.',503);
const meta=await b.first(accountsSQL+' WHERE a.id=?',[p.sourceAccountId]);if(meta?.entity_id!==entityId('clan',p.orderingClanId))fail('The original clan bank account is required.',403);
await b.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[meta.entity_id]);
await b.query('SELECT id FROM pb_accounts WHERE id IN (?,?) ORDER BY id FOR UPDATE',[p.sourceAccountId,tax.id]);
await b.query('SELECT id FROM pb_account_authorisations WHERE account_id=? ORDER BY id FOR UPDATE',[p.sourceAccountId]);
const source=(await funding(r,actor,p.orderingClanId)).find(a=>String(a.id)===p.sourceAccountId),target=await b.first('SELECT * FROM pb_accounts WHERE id=?',[tax.id]),amount=BigInt(p.feeMinor);
if(!source||!target||target.state!=='active'||target.system_key!=='sys_tax_treasury'||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<amount||BigInt(target.balance_minor)+amount>9223372036854775807n)fail('Insufficient authorised clan funds or unavailable Tax treasury.');
if(await b.first('SELECT id FROM pb_orders WHERE id=? FOR UPDATE',[p.id]))fail('This bank reference already belongs to another operation.');
const key=await issue(r,'state:imperial-raid:'+p.id,async(_tx,{keyId})=>{
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',?)",[p.id,actor.id,source.id,target.id,p.inputHash,p.feeMinor,'Imperial raid '+p.id,clock()]);
await new PostbankPayments(bank,null,{clock}).post(b,{id:p.id,actor_id:actor.id,amount_minor:p.feeMinor},source,target,false);
});
return {receiptKeyId:key.id,bankOrderId:p.id};
}
async function refund(rawTx,row){
const tx=reader(rawTx),b=banking.view(tx),p=JSON.parse(row.accepted_json),outcome=JSON.parse(row.outcome_json),refundId=raidRecoveryId(row.id),scope='state:imperial-raid-refund:'+row.id;
if(row.state!=='neutral'||row.war_campaign_id||!['spawn_failed','interrupted','cancelled'].includes(outcome.outcome)||p.bankOrderId!==row.id)fail('A bound refundable neutral paid raid is required.');
const original=await b.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[p.bankOrderId]);
if(!original||original.state!=='posted'||String(original.source_id)!==p.sourceAccountId||String(original.amount_minor)!==p.feeMinor||original.fingerprint!==p.inputHash||original.actor_id!==row.actor_id)fail('The original posted raid payment requires reconciliation.');
const previous=await b.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[refundId]),priorKey=await tx.first("SELECT id FROM organisation_keys WHERE account_id=? AND key_type='entity-state' AND scope_id=? AND revoked_at IS NULL",[STAFF_OFFICE_ACCOUNT_ID,scope]);
const fingerprint=createHash('sha256').update(JSON.stringify([row.id,row.terminal_event_id,p.bankOrderId,p.feeMinor,'neutral-refund'])).digest('hex');
if(previous){if(!priorKey||previous.state!=='posted'||String(previous.source_id)!==String(original.target_id)||String(previous.target_id)!==String(original.source_id)||String(previous.amount_minor)!==p.feeMinor||previous.fingerprint!==fingerprint)fail('The original raid refund requires reconciliation.');return {refundState:'posted',refundOrderId:refundId,receiptKeyId:priorKey.id};}
await b.query('SELECT id FROM pb_accounts WHERE id IN (?,?) ORDER BY id FOR UPDATE',[original.source_id,original.target_id]);
const rows=await b.query(accountsSQL+' WHERE a.id IN (?,?) ORDER BY a.id',[original.source_id,original.target_id]),source=rows.find(a=>String(a.id)===String(original.target_id)),target=rows.find(a=>String(a.id)===String(original.source_id)),amount=BigInt(p.feeMinor);
if(!source||source.system_key!=='sys_tax_treasury'||source.state!=='active'||!target||target.state!=='active'||target.entity_id!==entityId('clan',p.orderingClanId)||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<amount||BigInt(target.balance_minor)+amount>9223372036854775807n)fail('Original raid refund remains queued; the original accounts cannot settle safely.');
const key=await issue(tx,scope,async()=>{
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',?)",[refundId,STAFF_OFFICE_ACCOUNT_ID,source.id,target.id,fingerprint,p.feeMinor,'Imperial raid refund '+row.id,clock()]);
await new PostbankPayments(bank,null,{clock}).post(b,{id:refundId,actor_id:STAFF_OFFICE_ACCOUNT_ID,amount_minor:p.feeMinor},{...source,entity_id:source.entity_id??null},target,false);
});
return {refundState:'posted',refundOrderId:refundId,receiptKeyId:key.id};
}
return {ready:banking.ready,resolveActor,resolveContext,charge,refund,bankView:banking.view};
}

View file

@ -0,0 +1,29 @@
import {randomUUID} from 'node:crypto';
// Domain handlers run AFTER the lease transaction. Existing quest/key/war
// services may open their own transactions; none is nested beneath this lease.
// Every handler must bind its side effect to the original durable order ID.
export async function processImperialRaidJobs(db,handlers,{clock=Date.now,limit=20,leaseMs=30000,makeId=randomUUID}={}){
if(!Number.isSafeInteger(limit)||limit<1||limit>100||!Number.isSafeInteger(leaseMs)||leaseMs<1000||leaseMs>300000)throw TypeError('Bounded raid recovery worker required');
const now=clock(),rows=await db.query("SELECT order_id,kind FROM jarvis_imperial_raid_jobs WHERE state='queued' OR (state='processing' AND lease_until<=?) ORDER BY COALESCE(attempted_at,created_at),created_at,order_id,kind LIMIT "+limit,[now]);
const result={attempted:0,completed:0,deferred:0};
for(const ref of rows){
const token=makeId(),job=await db.transaction(async tx=>{
const row=await tx.first('SELECT * FROM jarvis_imperial_raid_jobs WHERE order_id=? AND kind=? FOR UPDATE',[ref.order_id,ref.kind]);
if(!row||row.state!=='queued'&&!(row.state==='processing'&&Number(row.lease_until)<=clock()))return null;
await tx.query("UPDATE jarvis_imperial_raid_jobs SET state='processing',attempted_at=?,lease_token=?,lease_until=? WHERE order_id=? AND kind=?",[clock(),token,clock()+leaseMs,row.order_id,row.kind]);return row;
});
if(!job)continue;result.attempted++;
try{
const handler=handlers[job.kind];if(typeof handler!=='function')throw Error('Raid recovery adapter unavailable');
const response=await handler(job,JSON.parse(job.payload_json));
if(!response||response.done===false)throw Error('Raid recovery remains pending');
const saved=await db.query("UPDATE jarvis_imperial_raid_jobs SET state='completed',completed_at=?,lease_token=NULL,lease_until=NULL,result_json=? WHERE order_id=? AND kind=? AND state='processing' AND lease_token=?",[clock(),JSON.stringify(response),job.order_id,job.kind,token]);
if(Number(saved.affectedRows||0)===1)result.completed++;else result.deferred++;
}catch{
// No raw bank response, item payload, player ID or secret is logged here.
await db.query("UPDATE jarvis_imperial_raid_jobs SET state='queued',lease_token=NULL,lease_until=NULL WHERE order_id=? AND kind=? AND state='processing' AND lease_token=?",[job.order_id,job.kind,token]);result.deferred++;
}
}
return result;
}

View file

@ -0,0 +1,185 @@
import {randomUUID} from 'node:crypto';
import {IMPERIAL_RAID_POLICY as P,validateImperialRaidInput,imperialRaidIntent,imperialRaidInputHash,imperialRaidEventHash,imperialRaidFee,unpaidRaidResponse,raidEventAcknowledgement} from './imperial-raid-protocol.mjs';
export const IMPERIAL_RAID_SCHEMA=[
`CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_guard(id INTEGER PRIMARY KEY) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_orders(id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,input_hash CHAR(64) NOT NULL,intent_json TEXT NOT NULL,state VARCHAR(16) NOT NULL,prepared_json TEXT NULL,accepted_json TEXT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,updated_at BIGINT NOT NULL,started_at BIGINT NULL,terminal_event_id CHAR(36) NULL,outcome_json TEXT NULL,war_campaign_id CHAR(36) NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_clans(clan_id CHAR(36) PRIMARY KEY,last_order_at BIGINT NULL,last_raided_at BIGINT NULL,revenge_against CHAR(36) NULL,revenge_until BIGINT NULL,revenge_level INTEGER NOT NULL DEFAULT 0,chain_id CHAR(36) NULL,active_order_id CHAR(36) NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_events(event_id CHAR(36) PRIMARY KEY,order_id CHAR(36) NOT NULL,event_hash CHAR(64) NOT NULL,response_json TEXT NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS jarvis_imperial_raid_jobs(order_id CHAR(36) NOT NULL,kind VARCHAR(16) NOT NULL,payload_json TEXT NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,attempted_at BIGINT NULL,completed_at BIGINT NULL,lease_token CHAR(36) NULL,lease_until BIGINT NULL,result_json TEXT NULL,PRIMARY KEY(order_id,kind)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
];
export const initializeImperialRaids=async db=>{for(const sql of IMPERIAL_RAID_SCHEMA)await db.query(sql);};
export async function lockImperialRaidGuard(tx){
await tx.query('INSERT INTO jarvis_imperial_raid_guard(id) VALUES(1) ON DUPLICATE KEY UPDATE id=VALUES(id)');
await tx.first('SELECT id FROM jarvis_imperial_raid_guard WHERE id=1 FOR UPDATE');
}
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
const publicPolicy=()=>Object.fromEntries(['noticeMs','durationMs','baseRaiders','perDefender','maxRaiders','minDefendersOnline'].map(k=>[k,P[k]]));
const paid=row=>!!row?.accepted_json;
const accepted=row=>({ok:true,schema:1,state:'accepted',charged:true,order:JSON.parse(row.accepted_json)});
const finalUnpaid=row=>unpaidRaidResponse(row.id,row.input_hash,row.state,row.outcome_json?JSON.parse(row.outcome_json).message:null);
const parse=value=>value?JSON.parse(value):null;
const same=(a,b)=>imperialRaidEventHash(a)===imperialRaidEventHash(b);
const selectedAccount=(quote,id)=>{const account=quote.accounts.find(a=>String(a.id)===id);if(!account)fail('Choose a currently authorised clan bank account.');if(!/^\d+$/.test(account.availableMinor)||BigInt(account.availableMinor)<BigInt(quote.feeMinor))fail('Insufficient authorised clan funds.');return account;};
// resolveActor and resolveContext read the ORIGINAL linked account, clan deed,
// Home Block and debit rights inside this transaction. charge must post the
// existing bank/key operation on the supplied transaction, never another pool.
export function createImperialRaidOrders(db,{resolveActor,resolveContext,charge,clock=Date.now,makeId=randomUUID}={}){
if(![resolveActor,resolveContext,charge].every(f=>typeof f==='function'))throw TypeError('Authoritative Imperial raid adapters required');
async function locked(work){return db.transaction(async tx=>{
await lockImperialRaidGuard(tx);
return work(tx);
});}
const order=(tx,id)=>tx.first('SELECT * FROM jarvis_imperial_raid_orders WHERE id=? FOR UPDATE',[id]);
async function bind(tx,input){
const actor=await resolveActor(tx,input.uuid,{lock:true});if(!actor?.id)fail('Link an active personal Minecraft account first.',403);
const row=await order(tx,input.requestId),hash=imperialRaidInputHash(input);
if(row&&(row.actor_id!==actor.id||row.input_hash!==hash||row.minecraft_uuid!==input.uuid))fail('This raid reference belongs to a different original intent.');
return {actor,row,hash};
}
async function insert(tx,input,actor,hash,state,prepared=null,message=null){
const now=clock();await tx.query('INSERT INTO jarvis_imperial_raid_orders(id,actor_id,minecraft_uuid,input_hash,intent_json,state,prepared_json,accepted_json,created_at,expires_at,updated_at,started_at,terminal_event_id,outcome_json) VALUES(?,?,?,?,?,?,?,NULL,?,?,?,NULL,NULL,?)',[input.requestId,actor.id,input.uuid,hash,JSON.stringify(imperialRaidIntent(input)),state,prepared?JSON.stringify(prepared):null,now,prepared?.expiresAt||now,now,message?JSON.stringify({message}):null]);
return order(tx,input.requestId);
}
async function expire(tx,row){
if(row.state==='prepared'&&Number(row.expires_at)<=clock()){
await tx.query("UPDATE jarvis_imperial_raid_orders SET state='expired',updated_at=? WHERE id=?",[clock(),row.id]);return {...row,state:'expired'};
}return row;
}
async function rejectPrepared(tx,row,message){
await tx.query("UPDATE jarvis_imperial_raid_orders SET state='rejected',outcome_json=?,updated_at=? WHERE id=?",[JSON.stringify({message}),clock(),row.id]);
return finalUnpaid({...row,state:'rejected',outcome_json:JSON.stringify({message})});
}
async function clan(tx,id,create=false){
if(create)await tx.query('INSERT INTO jarvis_imperial_raid_clans(clan_id) VALUES(?) ON DUPLICATE KEY UPDATE clan_id=VALUES(clan_id)',[id]);
return await tx.first('SELECT * FROM jarvis_imperial_raid_clans WHERE clan_id=?'+(create?' FOR UPDATE':''),[id])||{clan_id:id};
}
async function quote(tx,input,{lock=false}={}){
const context=await resolveContext(tx,input,{lock}),a=await clan(tx,input.orderingClanId,lock),b=await clan(tx,input.targetClanId,lock),now=clock();
if(input.orderingClanId===input.targetClanId)fail('Choose a rival clan.');
if(b.active_order_id)fail('This clan already has an active Imperial raid.');
const retaliation=a.revenge_against===input.targetClanId&&Number(a.revenge_until)>now,level=retaliation?Number(a.revenge_level)+1:0;
if(!retaliation&&a.last_order_at!==null&&a.last_order_at!==undefined&&now-Number(a.last_order_at)<P.ordererCooldownMs)fail('The ordering clan is still on its Imperial raid cooldown.');
if(!retaliation&&b.last_raided_at!==null&&b.last_raided_at!==undefined&&now-Number(b.last_raided_at)<P.targetCooldownMs)fail('The target clan is still protected by its raid cooldown.');
const feeMinor=imperialRaidFee(level),accounts=context.accounts||[];
return {context,a,b,level,feeMinor,chainId:retaliation?a.chain_id:null,accounts};
}
async function eventReplay(tx,input){
const prior=await tx.first('SELECT * FROM jarvis_imperial_raid_events WHERE event_id=? FOR UPDATE',[input.eventId]);
if(!prior)return null;if(prior.order_id!==input.orderId||prior.event_hash!==imperialRaidEventHash(input))fail('This raid event reference changed.');
return JSON.parse(prior.response_json);
}
async function saveEvent(tx,input,response){
await tx.query('INSERT INTO jarvis_imperial_raid_events(event_id,order_id,event_hash,response_json,created_at) VALUES(?,?,?,?,?)',[input.eventId,input.orderId,imperialRaidEventHash(input),JSON.stringify(response),clock()]);return response;
}
async function requirePaid(tx,input){
const row=await order(tx,input.orderId);if(!paid(row)||parse(row.intent_json).server!==input.server)fail('This backend has no accepted receipt for that order.');return row;
}
async function queue(tx,row,kind,payload,state='queued'){
await tx.query('INSERT INTO jarvis_imperial_raid_jobs(order_id,kind,payload_json,state,created_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE order_id=VALUES(order_id)',[row.id,kind,JSON.stringify(payload),state,clock()]);
}
async function prepare(tx,input){
const {actor,row:existing,hash}=await bind(tx,input);
if(existing){const row=await expire(tx,existing);if(paid(row))return accepted(row);if(row.state==='prepared')return {ok:true,schema:1,state:'prepared',order:parse(row.prepared_json)};return finalUnpaid(row);}
let q;
try{q=await quote(tx,input,{lock:true});selectedAccount(q,input.sourceAccountId);}
catch(error){if(!error.status)throw error;return finalUnpaid(await insert(tx,input,actor,hash,'rejected',null,error.message));}
const now=clock(),c=q.context,prepared={id:input.requestId,requestId:input.requestId,inputHash:hash,preflightNonce:makeId(),preparedAt:now,expiresAt:now+P.preparedMs,actorUuid:input.uuid,orderingClanId:input.orderingClanId,targetClanId:input.targetClanId,orderingClanName:c.orderingClanName,targetClanName:c.targetClanName,sourceAccountId:input.sourceAccountId,feeMinor:q.feeMinor,currency:'DM',server:input.server,chainId:q.chainId||makeId(),retaliationLevel:q.level,home:c.home,policy:publicPolicy()};
await insert(tx,input,actor,hash,'prepared',prepared);
// Internal authority versions stay outside the native public DTO.
await tx.query('UPDATE jarvis_imperial_raid_orders SET outcome_json=? WHERE id=?',[JSON.stringify({authority:c.authority}),input.requestId]);
return {ok:true,schema:1,state:'prepared',order:prepared};
}
async function accept(tx,input){
const row=await order(tx,input.orderId);if(!row||parse(row.intent_json).server!==input.server)fail('Prepared Imperial raid unavailable.');
const prior=await eventReplay(tx,input);if(prior)return prior;
const p=parse(row.prepared_json);if(!p||p.inputHash!==input.inputHash||p.preflightNonce!==input.preflightNonce)fail('The original prepared raid binding is required.');
if(paid(row))return saveEvent(tx,input,accepted(row));
const fresh=await expire(tx,row);if(fresh.state!=='prepared')return finalUnpaid(fresh);
const evidence=input.preflight,now=clock();
if(evidence.observedAt<now-30000||evidence.observedAt>now+10000||!same(evidence.position,p.home.position)||evidence.worldUuid!==p.home.worldUuid||evidence.claimRevision!==p.home.claimRevision) return rejectPrepared(tx,row,'The native Home Block preflight changed or expired.');
let q;
try{
const intent=parse(row.intent_json),actor=await resolveActor(tx,intent.uuid,{lock:true});if(actor?.id!==row.actor_id)fail('The original linked actor changed.',403);
q=await quote(tx,intent,{lock:true});
if(q.feeMinor!==p.feeMinor||q.level!==p.retaliationLevel||(q.chainId&&q.chainId!==p.chainId)||!same(q.context.home,p.home)||!same(q.context.authority,parse(row.outcome_json)?.authority))fail('The clan authority, fee, chain or Home Block changed.');
selectedAccount(q,p.sourceAccountId);
if(evidence.defendersOnline<P.minDefendersOnline)fail('Too few defenders are online.');
}catch(error){if(!error.status)throw error;return rejectPrepared(tx,row,error.message);}
// Do not catch posting failures inside this transaction: a timeout, partial
// write or failed key insert must roll EVERYTHING back, leaving the same intent.
const receipt=await charge(tx,{...p,actorId:row.actor_id});
if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(receipt?.receiptKeyId||'')||receipt.bankOrderId!==row.id)throw Error('Original atomic paid raid receipt required');
const resultOrder={...p,receiptKeyId:receipt.receiptKeyId,bankOrderId:receipt.bankOrderId,acceptedAt:now};
await tx.query("UPDATE jarvis_imperial_raid_orders SET state='accepted',accepted_json=?,updated_at=? WHERE id=?",[JSON.stringify(resultOrder),now,row.id]);
if(q.level)await tx.query('UPDATE jarvis_imperial_raid_clans SET revenge_against=NULL,revenge_until=NULL,revenge_level=0 WHERE clan_id=?',[p.orderingClanId]);
else await tx.query('UPDATE jarvis_imperial_raid_clans SET last_order_at=? WHERE clan_id=?',[now,p.orderingClanId]);
await tx.query('UPDATE jarvis_imperial_raid_clans SET last_raided_at=?,active_order_id=?,revenge_against=?,revenge_until=?,revenge_level=?,chain_id=? WHERE clan_id=?',[now,row.id,q.level>=P.warAfter?null:p.orderingClanId,q.level>=P.warAfter?null:now+P.revengeMs,q.level>=P.warAfter?0:q.level,p.chainId,p.targetClanId]);
if(q.level===P.warAfter)await queue(tx,row,'war',{orderId:row.id,chainId:p.chainId,orderingClanId:p.orderingClanId,targetClanId:p.targetClanId},'waiting_start');
return saveEvent(tx,input,{ok:true,schema:1,state:'accepted',charged:true,order:resultOrder});
}
async function acknowledge(tx,input){
const row=await requirePaid(tx,input),prior=await eventReplay(tx,input);if(prior)return prior;
const p=parse(row.accepted_json);
if(input.occurredAt<p.acceptedAt||input.occurredAt>clock()+30000)fail('Raid acknowledgement time is invalid.');
if(input.phase==='started'){
if(input.occurredAt<p.acceptedAt+P.noticeMs)fail('The full raid warning must finish before starting.');
if(row.started_at!==null&&Number(row.started_at)!==input.occurredAt)fail('The original actual start time changed.');
if(row.terminal_event_id)fail('This raid already has a terminal outcome.');
await tx.query("UPDATE jarvis_imperial_raid_orders SET state='started',started_at=?,updated_at=? WHERE id=?",[input.occurredAt,clock(),row.id]);
await tx.query("UPDATE jarvis_imperial_raid_jobs SET state='queued' WHERE order_id=? AND kind='war' AND state='waiting_start'",[row.id]);
}else if(row.state==='accepted')await tx.query("UPDATE jarvis_imperial_raid_orders SET state='warning',updated_at=? WHERE id=?",[clock(),row.id]);
return saveEvent(tx,input,raidEventAcknowledgement(row.id,input.eventId,input.phase));
}
async function outcome(tx,input){
const row=await requirePaid(tx,input),prior=await eventReplay(tx,input);if(prior)return prior;
if(row.terminal_event_id)fail('The original terminal outcome is already recorded.');
const p=parse(row.accepted_json),started=row.started_at===null?null:Number(row.started_at),neutral=['interrupted','spawn_failed','cancelled'].includes(input.outcome);
if(input.occurredAt<p.acceptedAt||input.occurredAt>clock()+30000||started===null&&(input.startedAt!==0||input.activeMillis!==0)||started!==null&&(input.startedAt!==started||input.occurredAt<started||input.activeMillis>input.occurredAt-started+1000))fail('The original actual raid interval is required.');
if(!neutral&&started===null)fail('A real party start must be acknowledged before a combat outcome.');
if(input.outcome==='survived'&&input.activeMillis!==P.durationMs)fail('The commander must survive fifteen actual active minutes.');
if(input.outcome==='spawn_failed'&&started!==null)fail('An already started raid must use interruption, not spawn failure.');
const state=neutral?'neutral':input.outcome==='survived'?'completed':'failed';
await tx.query('UPDATE jarvis_imperial_raid_orders SET state=?,terminal_event_id=?,outcome_json=?,updated_at=? WHERE id=?',[state,input.eventId,JSON.stringify(input),clock(),row.id]);
await tx.query('UPDATE jarvis_imperial_raid_clans SET active_order_id=NULL WHERE clan_id=? AND active_order_id=?',[p.targetClanId,row.id]);
if(neutral){
if(!row.war_campaign_id){
await tx.query("UPDATE jarvis_imperial_raid_jobs SET state='cancelled' WHERE order_id=? AND kind='war' AND state IN ('waiting_start','queued','processing')",[row.id]);
await queue(tx,row,'refund',{orderId:row.id,eventId:input.eventId,outcome:input.outcome});
}
}
else await queue(tx,row,'quest',{orderId:row.id,eventId:input.eventId,actorId:row.actor_id,outcome:input.outcome,xp:state==='completed'?1000:100});
return saveEvent(tx,input,{...raidEventAcknowledgement(row.id,input.eventId,state),...(neutral?(row.war_campaign_id?{refundState:'not_due',refundReason:'war_started'}:{refundState:'queued'}):{})});
}
return Object.freeze({
async execute(value){
const input=validateImperialRaidInput(value);
if(input.action==='context'){
const actor=await resolveActor(db,input.uuid);if(!actor?.id)fail('Link an active personal Minecraft account first.',403);
const q=await quote(db,input),c=q.context;
return {ok:true,schema:1,context:{actorUuid:input.uuid,orderingClanId:input.orderingClanId,targetClanId:input.targetClanId,orderingClanName:c.orderingClanName,targetClanName:c.targetClanName,server:input.server,accounts:q.accounts,uniqueSourceAccountId:q.accounts.length===1?String(q.accounts[0].id):null,feeMinor:q.feeMinor,currency:'DM',chainId:q.chainId,retaliationLevel:q.level,home:c.home,policy:publicPolicy()}};
}
if(input.action==='poll'){
const rows=await db.query("SELECT accepted_json FROM jarvis_imperial_raid_orders WHERE state IN ('accepted','warning','started') ORDER BY created_at,id LIMIT 501");
if(rows.length>500)fail('The active raid register requires reconciliation.');
return {ok:true,schema:1,orders:rows.map(r=>parse(r.accepted_json)).filter(p=>p?.server===input.server)};
}
return locked(async tx=>{
if(input.action==='prepare')return prepare(tx,input);
if(input.action==='accept')return accept(tx,input);
if(input.action==='ack')return acknowledge(tx,input);
if(input.action==='outcome')return outcome(tx,input);
const {actor,row:old,hash}=await bind(tx,input),row=old?await expire(tx,old):null;
if(paid(row))return accepted(row);
if(input.action==='cancel_prepared'){
if(!row)return finalUnpaid(await insert(tx,input,actor,hash,'cancelled'));
if(row.state==='prepared')await tx.query("UPDATE jarvis_imperial_raid_orders SET state='cancelled',updated_at=? WHERE id=?",[clock(),row.id]);
return finalUnpaid({...row,state:row.state==='prepared'?'cancelled':row.state});
}
if(!row)return {ok:true,schema:1,orderId:input.requestId,requestId:input.requestId,inputHash:hash,state:'unknown',definitive:false};
return row.state==='prepared'?{ok:true,schema:1,state:'prepared',order:parse(row.prepared_json)}:finalUnpaid(row);
});
}
});
}

View file

@ -3,7 +3,7 @@ import {NATIVE_SERVERS} from './native-server-scope.mjs';
export const IMPERIAL_RAID_POLICY=Object.freeze({noticeMs:600000,durationMs:900000,baseRaiders:4,perDefender:1,maxRaiders:14,minDefendersOnline:0,ordererCooldownMs:86400000,targetCooldownMs:21600000,revengeMs:86400000,preparedMs:120000,baseFeeMinor:'2500000',feeStepMinor:'500000',warAfter:3});
export const IMPERIAL_RAID_OUTCOMES=Object.freeze(['survived','commander_defeated','interrupted','spawn_failed','cancelled']);
export const unpaidFinalStates=new Set(['cancelled','rejected','expired']);
const unpaidFinalStates=new Set(['cancelled','rejected','expired']);
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const digest=v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
const time=v=>Number.isSafeInteger(v)&&v>=0;

View file

@ -43,7 +43,7 @@ export function createOrganisationKeys(db,{secret,editions=null,foundingScope='o
foundingScope,
async inspect(code,{accountId=null,expectedType=null}={}){let parsed,keyType,hash;try{parsed=parseOrganisationCode(code);keyType=Object.keys(ORGANISATION_KEY_TYPES).find(k=>ORGANISATION_KEY_TYPES[k].prefix===parsed.prefix);if(!keyType)return{valid:false,state:'unsupported'};hash=hashOrganisationKey(code,keyType);}catch{return{valid:false,state:'invalid'};}const row=await readFirst(db,'SELECT id,account_id,key_type,expires_at,revoked_at,used_at FROM organisation_keys WHERE code_hash=?',[hash]);if(!row||accountId&&row.account_id!==accountId||expectedType&&row.key_type!==expectedType)return{valid:false,state:'invalid'};if(parsed.edition){if(!editions)return{valid:false,state:'unavailable'};const edition=await editions.read(row.id);if(['stage','version','season'].some(k=>edition[k]!==parsed.edition[k]))return{valid:false,state:'invalid'};}return{valid:true,type:row.key_type,purpose:type(row.key_type).purpose,state:row.revoked_at!=null?'revoked':row.used_at!=null?'used':row.expires_at!=null&&Number(row.expires_at)<=Date.now()?'expired':'available'};},
async issue({accountId,keyType,scopeId,expiresAt=null,authorize=null,transactionStore=null}){
if(transactionStore&&(!(keyType==='organisation-action'||keyType==='entity-state'&&accountId===STAFF_OFFICE_ACCOUNT_ID&&/^state:(?:political-decision|political-review-publication|political-agreement-reply|political-ballot-vote|imperial-rally-vote|naib-council|world-trade|war-medal):[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required');
if(transactionStore&&(!(keyType==='organisation-action'||keyType==='entity-state'&&accountId===STAFF_OFFICE_ACCOUNT_ID&&/^state:(?:political-decision|political-review-publication|political-agreement-reply|political-ballot-vote|imperial-rally-vote|naib-council|world-trade|war-medal|imperial-raid|imperial-raid-refund):[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required');
type(keyType);
if(keyType==='economy-operation'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^economy\.(reset-balances|repay-loans|federal-cycle):[a-f0-9-]{36}$/i.test(scopeId)))throw TypeError('Economic keys require a scoped system authority adapter');
if(keyType==='kit-definition'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^kitset:[a-f0-9-]{36}:v[1-9]\d{0,5}$/i.test(scopeId)))throw TypeError('Kit definitions require a saved set and authority adapter');