Beta 1.0.2.0: connect paid Imperial raids to JARVIS, Reputation and existing wars #630
36 changed files with 1104 additions and 31 deletions
|
|
@ -15,5 +15,5 @@ export function agreedWarBlock(parties,selections){
|
|||
}
|
||||
export function warProposalFacts(proposal){
|
||||
const mode=WAR_MODES[proposal.mode];
|
||||
return [mode?.label||'War proposal',mode?mode.parties+' sides · '+mode.playersPerSide+' players per side':'',proposal.state==='scheduled'?(proposal.forcedEmperor?'Qualified rebellion scheduled after Imperial deadline':'All parties agreed'):proposal.state==='cancelled'?'Withdrawn':'Awaiting matching calendar blocks'].filter(Boolean);
|
||||
return [mode?.label||'War proposal',proposal.raidEscalation?'Both complete clan rosters':mode?mode.parties+' sides · '+mode.playersPerSide+' players per side':'',proposal.state==='scheduled'?(proposal.raidEscalation?'Automatic escalation after the third retaliation':proposal.forcedEmperor?'Qualified rebellion scheduled after Imperial deadline':'All parties agreed'):proposal.state==='cancelled'?'Withdrawn':'Awaiting matching calendar blocks'].filter(Boolean);
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
60
website/docs/PILLAGER-RAID-CONTRACT-20261129.md
Normal file
60
website/docs/PILLAGER-RAID-CONTRACT-20261129.md
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
# Beta 1.0.2.0 — Imperial raid bridge contract
|
||||
|
||||
Central implementation is ready for review: strict authenticated endpoint, atomic existing Postbank/key receipts, original-war automation, Reputation quest adapter and durable recovery jobs are implemented. Activation remains OFF unless the committed feature flag and existing bank/war bridge flags are explicitly enabled. This is source/test evidence, not a deployment or real-payment claim. The completed-release backup is verified at `unimatrixgit/serverplugins` main3485eec4 and `unimatrixgit/duneweb` main0097a856; all19/11 branches match DuneGit and both fresh full-history clones pass Git integrity checks. The previous backup and Claude branch are unchanged.
|
||||
|
||||
## Authority and transport
|
||||
|
||||
Use the existing authenticated native game bridge at `/internal/game/imperial-raids`. The connector supplies its actual canonical server. Initial scope is the loaded target Home Block on that same backend/world; crossworld requests fail with travel guidance. No remote world loading or interplanetary war system is implied.
|
||||
|
||||
Every request is JSON with exactly `action`, `server` and the fields for that action below. UUIDs are lowercase canonical strings, account IDs and minor-unit monetary amounts are strings, input hashes are64 lowercase hexadecimal characters, times/durations are integer milliseconds. Unknown fields are rejected. The fixed policy is ten-minute warning, fifteen actual active raid minutes, base4 raiders plus1 per defender capped14, no newly invented minimum-defender requirement,24h ordering cooldown and6h target cooldown. Retaliation fees are2500000/3000000/3500000/4000000 minor units for chain levels0/1/2/3. Fee recipient is the existing Tax treasury, matching the supplied raid design.
|
||||
|
||||
Context and preparation require a linked active personal actor, current clan-war authority and eligible CLAN bank debit authority. Do not fall back to an owner's personal account. Select the eligible account automatically only if exactly one exists; otherwise require an explicit selector. Friendly/protected/unavailable targets, conflicting wars, changed deeds/Home Blocks, cooldowns and insufficient funds fail closed. Native faction projection is a preflight, not the bank/deed authority.
|
||||
|
||||
## Actions
|
||||
|
||||
- `context`: `uuid, orderingClanId, targetClanId`. Returns `{ok:true,schema:1,context:{actorUuid,orderingClanId,targetClanId,orderingClanName,targetClanName,server,accounts:[{id,name,availableMinor}],uniqueSourceAccountId,feeMinor,currency:'DM',chainId,retaliationLevel,home,policy}}`. `uniqueSourceAccountId` is null unless exactly one eligible account exists. No debit or paid permit.
|
||||
- `prepare`: `uuid, requestId, orderingClanId, targetClanId, sourceAccountId`. Returns `{ok:true,schema:1,state:'prepared',order:{id,requestId,inputHash,preflightNonce,preparedAt,expiresAt,actorUuid,orderingClanId,targetClanId,orderingClanName,targetClanName,sourceAccountId,feeMinor,currency:'DM',server,chainId,retaliationLevel,home,policy}}`. `id=requestId`, expiry is two minutes. `home={worldUuid,position:{x,y,z},claimRevision}` and public `policy={noticeMs,durationMs,baseRaiders,perDefender,maxRaiders,minDefendersOnline}`. Preparation cannot debit or spawn.
|
||||
- `status`: exactly the same original intent fields as prepare. Reads the original request, never changes its target/account. A missing intent returns `state:'unknown',definitive:false` and cannot unlock an uncertain client reference. A prepared intent returns the original prepared order; a paid intent returns the original accepted receipt.
|
||||
- `cancel_prepared`: exactly the same original intent fields as prepare. Atomically cancels an unpaid intent. If it has not arrived yet, create a cancellation tombstone for that original intent, so a delayed prepare cannot revive it. Cancellation does not require retained clan-debit rights, but requires the original linked actor and exact original binding. A different actor/target/account using the same ID conflicts.
|
||||
- `accept`: `orderId,eventId,inputHash,preflightNonce,preflight`, where `preflight={worldUuid,position:{x,y,z},claimRevision,defendersOnline,spawnable:true,protected:false,observedAt}`. `protected` refers to actual raid exclusion/protected-target policy, not a blanket refusal of the target's own estate. Native preflight is current and within the prepared expiry; central rechecks every authority, current quote/chain/Home Block and available balance. Use the existing atomic Postbank posting and JARVIS key transaction; no separately committed debit. Accepted response is `{ok:true,schema:1,state:'accepted',charged:true,order:acceptedOrder}`; acceptedOrder extends the original order with `receiptKeyId,bankOrderId,acceptedAt`. Same event/order retries return the same receipt, never another charge. Changed event data conflicts.
|
||||
- `poll`: no extra fields. Returns `{ok:true,schema:1,orders:[acceptedOrder,...]}` for this backend only. Never returns prepared orders as spawnable. The native journal deduplicates the same receipt across all warnings/starts/retries.
|
||||
- `ack`: `orderId,eventId,phase,occurredAt`, where phase is `warning` or `started`. The event is durable and input-bound. Success echoes `{ok:true,schema:1,orderId,eventId,state}` with warning/started state. A generic success cannot clear the outbox.
|
||||
- `outcome`: `orderId,eventId,outcome,startedAt,occurredAt,activeMillis`. Outcomes are `survived`, `commander_defeated`, `interrupted`, `spawn_failed`, `cancelled`. Success echoes `{ok:true,schema:1,orderId,eventId,state}`; terminal state is completed/failed/neutral. Original event and immutable order bindings are checked before acknowledgement. No unrecorded/empty party can produce a victory.
|
||||
|
||||
The canonical intent hash is SHA256 of the UTF-8 JSON array `[server,uuid,requestId,orderingClanId,targetClanId,sourceAccountId]` in that exact order. Prepare/status/cancel share it, ignoring action. UUIDs are normalized before hashing. This is an input binding, not a replacement authentication credential. The accepted immutable order/key also seals the authoritative quoted fee, chain, account and Home Block; caller-provided values never replace those terms.
|
||||
|
||||
## Unpaid rejection and safe resumption
|
||||
|
||||
Definitive unpaid responses are exactly `{ok:true,schema:1,orderId,requestId,inputHash,state,definitive:true,charged:false,message?}`, where state is cancelled/rejected/expired. Both IDs equal the original request UUID. Native may unlock only after matching IDs and the original hash. A business rejection persists an unpaid tombstone; malformed input or transient backend failure is not silently reclassified as a definitive rejection.
|
||||
|
||||
`cancel_prepared` is idempotent and wins races against a delayed preparation through the same order transaction lock. Expired preparations are recorded as unpaid expired. Once payment was accepted, cancellation cannot return an unpaid response; return the original accepted order instead. Never clear on generic409/503, generate a fresh request ID on timeout, or accept a generic `ok:true` as acknowledgement. The native pending intent is journaled before its first network request.
|
||||
|
||||
## Spawn, terminal result and original-payment recovery
|
||||
|
||||
`acceptedAt+noticeMs` is the warning deadline, not evidence that a party exists. Start the active timer only after actual successful party and commander spawn, then report the stable started event. Victory requires the same recorded start, surviving commander and900000 active milliseconds. Commander defeat is failure. Post-accept spawn failure, restart/interruption or server cancellation is neutral; no victory for missing entities, unloaded areas or elapsed offline time.
|
||||
|
||||
The coordinator chooses full original-fee recovery for these neutral service failures unless this order has already delivered its automatic war. Queue one idempotent refund against the original posted bank order, original source and original Tax destination, for exactly its fee. Reuse existing Postbank posting in the reverse direction with a stable refund reference and a JARVIS recovery record. Never mint compensation, choose a different recipient, reset a balance or mark a refund paid before posting. If the original account/treasury cannot safely settle it, keep the refund queued for reconciliation. An acknowledged neutral outcome may include `refundState:'queued'|'posted'`; the central durable job owns that liability after native acknowledgement. Preserve cooldown/chain audit history rather than erase the paid order to enable free replay.
|
||||
|
||||
Only real completed/failed raids produce the ordering-clan quest result:1000 Reputation XP for survival,100 for commander defeat, zero Personal XP and zero currency. Rejection, spawn failure, cancellation and restart are neutral. Stable order/outcome identifiers prevent reward replay. Use the existing quest/Reputation authority and outbox, not a native reward command.
|
||||
|
||||
At the third paid retaliation, enqueue one stable chain-bound war job in `waiting_start`. Release it only after the matched actual STARTED acknowledgement, matching the supplied design's party-spawn threshold event. The job automates the ORIGINAL war declaration/campaign flow with NOW and both actual clan rosters. Skip manual date/roster input only. Ordinary scheduled wars retain their existing rules; do not invent a parallel war engine, fake consent/identities or truncate an entire clan to a random eight. A neutral result before a war is committed cancels its pending war job and permits the original-fee refund. War creation and the order's durable campaign receipt must commit atomically, serialized against neutral outcomes. Once that original war has actually launched, a later neutral raid interruption gives no automatic refund: respond `refundState:'not_due',refundReason:'war_started'`, retain the existing war and award no neutral quest reward. This prevents a failed-spawn or interruption from creating a free war. War/quest/refund work is durable and retried after the accepting transaction; no nested key transaction or payment replay.
|
||||
|
||||
## Release gates
|
||||
|
||||
Require transactional/replay/cancel-race tests, actor/deed/funding/Home Block changes, failed posting rollback, terminal/reward/refund/war idempotency, ordinary war regressions and actual retained-backend compatibility. Native and central source must both pass exact-head CI before any rollout. Existing private backups and source history copies are recovery inputs, not permission to replace working backends indiscriminately. No live financial transaction or raid is run as an agent test.
|
||||
|
||||
## Implemented integration and operation boundaries
|
||||
|
||||
Acceptance reserves native delivery capacity before posting: at most100 active paid orders per server and at most262144 bytes for the full UTF-8 poll response. Overflow refuses the next debit; existing orders are never silently truncated. The global500-order register guard remains a reconciliation boundary. Regression coverage also exercises the actual central MySQL root interface (`query/transaction`, without a root `first` convenience), including original-war storage qualification.
|
||||
|
||||
`imperial-raid-runtime.mjs` combines the existing banking/key adapter, durable order service and post-commit jobs. The existing central scheduler drains jobs every15 seconds; no second payment worker or native reward command is introduced. Feature activation requires `IMPERIAL_RAIDS_ENABLED=true`, `POSTBANK_ENABLED=true` and `WAR_BRIDGE_ENABLED=true`. `ops/configure-imperial-raids.mjs` is a plan-by-default built helper, restricted to the exact immutable reviewed release via `--source=<40-character commit>`. `--apply` privately backs up the environment and changes only its feature flag, preserving ownership/mode. It neither seeds balances nor runs a payment. Restart uses the existing release process. Do not run a draft/local script on the host.
|
||||
|
||||
Paid acceptance and normal war booking use the ORIGINAL bank calendar lock. Acceptance rechecks current campaign/slot records before posting, and new matching clan calendar agreement is refused while a paid raid is pending/active. Known third-retaliation peace, full-roster and province failures are checked before charge and rechecked at actual launch. A later changed original-war rule leaves the stable war job queued; it cannot invent permission or silently substitute a campaign. Complete rosters are bounded at5000 per side: exceeding the verified bound rejects rather than truncates. Ordinary war limits/hour rules remain unchanged.
|
||||
|
||||
Private Home Block/claim mutation reservations hold both named clans steady during a paid raid. These are not added to native war/enemy/PvP state. The original war projection contains only real committed campaigns, with an exact root `raidEscalation={orderId,chainId,receiptKeyId}` marker for the authenticated native roster exception. The original capture, province and settlement services continue to apply.
|
||||
|
||||
The ordering actor's existing Reputation journal receives one `Summon a Rival Raid` objective per paid order, bound privately to the active Reputation season at preparation. The normal POL quest key, claim and XP ledger are reused. Its terminal receipt authorises exactly1000 survival or100 commander-defeat XP, without faith/mentor multipliers, Personal XP, currency or reward jobs. Actor link, paid key, existing Gurney issuer, season and immutable outcome must still verify. Missing authority or an ended original season keeps the job pending for explicit reconciliation; there is no cross-season reward substitution. Neutral orders cannot claim a reward.
|
||||
|
||||
Plugin/config rollback preserves native prepare/paid/outcome journals and central accepted liabilities. Restoring an old plugin does NOT mean those orders were refunded. With real accepted orders, reconciliation must recover their verified journals/outcomes or redeploy the compatible worker. Do not clear journals, generate fresh order IDs, disable recovery blindly or use a balance edit as compensation. Initial canary checks deliberately create no paid raid, cash transaction or new claim.
|
||||
|
||||
Local evidence: full website suite1911 passed, zero failed, six skipped before the final calendar refinement; the changed calendar/receipt/navigation suites were rerun after that refinement. Synthetic native interoperability generated by the actual Java request/journal classes passed all7 strict request validations, including exact intent-hash equality. Linux deployment checks and final-head build/CI remain release gates. No live client raid, loot drop, debit/refund, quest award or automatic war is claimed tested.
|
||||
12
website/node/game-imperial-raids.mjs
Normal file
12
website/node/game-imperial-raids.mjs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import {gameAuthorized,json} from './game-link.mjs';
|
||||
import {validateImperialRaidInput} from './imperial-raid-protocol.mjs';
|
||||
|
||||
export function createGameImperialRaidsAPI(runtime,settings){return async request=>{
|
||||
if(request.method!=='POST')return json({message:'Method not allowed'},405);
|
||||
if(!gameAuthorized(request,settings))return json({message:'Unauthorized'},401);
|
||||
if(new URL(request.url).search||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return json({message:'Invalid request'},400);
|
||||
const raw=await request.text();if(Buffer.byteLength(raw,'utf8')>16384)return json({message:'Invalid request'},400);
|
||||
let input;try{input=validateImperialRaidInput(JSON.parse(raw));}catch{return json({message:'Invalid Imperial raid request'},400);}
|
||||
if(!runtime||settings.IMPERIAL_RAIDS_ENABLED!=='true'||settings.WAR_BRIDGE_ENABLED!=='true'||settings.POSTBANK_ENABLED!=='true')return json({message:'The Pillager Update is not enabled.'},503);
|
||||
try{return json(await runtime.execute(input));}catch(error){return json({message:error.status?error.message:'Imperial raids are temporarily unavailable. Retain the original request reference.'},error.status||503);}
|
||||
};}
|
||||
|
|
@ -22,7 +22,7 @@ export const GAME_ORGANISATION_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_game_or
|
|||
const arrays={clan:'clans',company:'companies',protected:'offices'};
|
||||
const hash=input=>createHash('sha256').update(JSON.stringify(input)).digest('hex');
|
||||
const first=(store,sql,args=[])=>store.first?store.first(sql,args):store.query(sql,args).then(rows=>rows[0]||null);
|
||||
export function createGameOrganisations(db,keys,{clock=Date.now,readState=()=>readGameNativeState(db),bank=null,extraWars=async()=>[],normalizeLogo=normalizeClanImage}={}){
|
||||
export function createGameOrganisations(db,keys,{clock=Date.now,readState=()=>readGameNativeState(db),bank=null,extraWars=async()=>[],extraHomeReservations=async()=>[],normalizeLogo=normalizeClanImage}={}){
|
||||
const reader=tx=>{const r=boardReadStore(tx,db);r.readSnapshot=undefined;return r;};
|
||||
const currentWars=async tx=>[...await createRebellionQuests(reader(tx),null,{clock}).nativeWars(),...await extraWars()];
|
||||
async function claimPlan(kind,id,tier){if(!bank)throw fail('The claim entitlement bank is unavailable.',503);const paid=await bank.first('SELECT tier FROM pb_claim_entitlements WHERE entity_id=?',[entityId(kind,id)]);const plan=claimTariffs(kind).find(p=>p.code===(paid?.tier||tier));if(!plan)throw fail('The registered claim entitlement requires review.');return plan;}
|
||||
|
|
@ -82,6 +82,7 @@ export function createGameOrganisations(db,keys,{clock=Date.now,readState=()=>re
|
|||
// Never silently rewrite upgraded estates or their WorldEdit geometry.
|
||||
if(existing&&!move&&(existing.usedChunks!==1||existing.estates?.length!==1))throw fail('This estate needs a scoped relocation; its existing claims were preserved.');
|
||||
const active=await currentWars(tx);if(active.some(w=>(w.active||w.reserved)&&(w.attackerId===input.id||w.defenderId===input.id)))throw fail('A Home Block cannot be moved while a war is scheduled or active.');
|
||||
if((await extraHomeReservations(tx)).some(w=>w.attackerId===input.id||w.defenderId===input.id))throw fail('A Home Block cannot be moved while a paid Imperial raid is pending or active.');
|
||||
const homes=await tx.query('SELECT organisation_kind,organisation_id,snapshot_json FROM site_claim_registry ORDER BY organisation_kind,organisation_id FOR UPDATE');
|
||||
if(homes.length>1500)throw fail('The claim registry requires review.');
|
||||
for(const other of homes){if(other.organisation_kind===input.kind&&other.organisation_id===input.id)continue;const s=JSON.parse(other.snapshot_json),h=s.source==='minecraft'?s.homeBlock:null;if(h&&h.worldUuid===location.worldUuid&®isteredClaimChunks(s).some(c=>c.x===Math.floor(location.position.x/16)&&c.z===Math.floor(location.position.z/16)))throw fail('Another organisation already owns this estate chunk.');}
|
||||
|
|
@ -99,6 +100,7 @@ export function createGameOrganisations(db,keys,{clock=Date.now,readState=()=>re
|
|||
if(!existing?.homeBlock||existing.source!=='minecraft'||existing.homeBlock.worldUuid!==location.worldUuid||nativeServer(existing.homeBlock.worldName)!==location.server)throw fail('Stand on this organisation’s registered home planet to expand its estate.');
|
||||
if(Number(old.revision)!==input.expectedRevision)throw fail('Your estate changed. Refresh before expanding.');
|
||||
const active=await currentWars(tx);if(active.some(w=>(w.active||w.reserved)&&(w.attackerId===input.id||w.defenderId===input.id)))throw fail('The estate cannot be expanded while a war is scheduled or active.');
|
||||
if((await extraHomeReservations(tx)).some(w=>w.attackerId===input.id||w.defenderId===input.id))throw fail('The estate cannot be expanded while a paid Imperial raid is pending or active.');
|
||||
const plan=await claimPlan(input.kind,input.id,existing.tier);
|
||||
const rows=await tx.query('SELECT organisation_kind,organisation_id,snapshot_json FROM site_claim_registry ORDER BY organisation_kind,organisation_id FOR UPDATE');if(rows.length>1500)throw fail('The claim registry requires review.');
|
||||
const others=rows.filter(r=>r.organisation_kind!==input.kind||r.organisation_id!==input.id).map(r=>JSON.parse(r.snapshot_json));
|
||||
|
|
|
|||
|
|
@ -77,7 +77,7 @@ export function createGameWarAPI(db,store,settings,{clock=Date.now,readState=()=
|
|||
const state=await readState(),keys=await readCharters(),campaigns=[];
|
||||
for(const row of rows){
|
||||
const campaign=JSON.parse(row.snapshot_json);if(campaignPhase(campaign,clock())!=='active')continue;
|
||||
try{const players=currentClanCampaign(campaign,await withWarGuestIdentities(db,state,campaign),keys);campaigns.push({id:campaign.id,endsAt:campaign.endsAt,leaseUntil:Math.min(clock()+45000,campaign.endsAt),teams:campaign.teams.map(t=>({id:t.id,roster:t.roster.filter(p=>players.has(p.uuid))})),provinces:campaign.provinces,report:warCampaignReport(campaign,clock())});}catch(error){if(!error.status)throw error;}
|
||||
try{const players=currentClanCampaign(campaign,await withWarGuestIdentities(db,state,campaign),keys);campaigns.push({id:campaign.id,...(campaign.raidEscalation?{raidEscalation:campaign.raidEscalation}:{}),endsAt:campaign.endsAt,leaseUntil:Math.min(clock()+45000,campaign.endsAt),teams:campaign.teams.map(t=>({id:t.id,roster:t.roster.filter(p=>players.has(p.uuid))})),provinces:campaign.provinces,report:warCampaignReport(campaign,clock())});}catch(error){if(!error.status)throw error;}
|
||||
}
|
||||
return json({ok:true,observedAt:clock(),campaigns});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,7 +53,7 @@ export function createHomeRelocation(db,bank,keys,settings={},deps={}){
|
|||
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);
|
||||
const wars=[...await createRebellionQuests(r,null,{clock}).nativeWars(),...(deps.extraWars?await deps.extraWars(r,lock):[])],blocked=wars.find(w=>(w.active||w.reserved)&&(w.attackerId===id||w.defenderId===id));if(blocked)throw new BankError(blocked.kind==='imperial-raid'?'Home Blocks cannot move while a paid Imperial raid is pending or active.':'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){
|
||||
|
|
|
|||
121
website/node/imperial-raid-commerce.mjs
Normal file
121
website/node/imperial-raid-commerce.mjs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
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,buildClanCampaignSnapshot} 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';
|
||||
import {lockWarCalendar} from './war-muster.mjs';
|
||||
import {paxBlocksWar} from './imperial-pax.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','jarvis_pol_progression_seasons'];
|
||||
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','jarvis_war_calendar_guard','jarvis_war_proposals','jarvis_war_slots']:[]});
|
||||
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.');
|
||||
const seasons=await r.query("SELECT season_id FROM jarvis_pol_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[clock(),clock()]);
|
||||
if(seasons.length!==1)fail('A single active Reputation season is required before accepting a raid.');
|
||||
const seasonId=seasons[0].season_id;
|
||||
return {seasonId,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,seasonId},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);
|
||||
if(verifyCampaigns){
|
||||
// The ORIGINAL war booking lock also serializes this paid acceptance. Repeat
|
||||
// the campaign/slot check with current locking reads after obtaining it.
|
||||
await lockWarCalendar(b);
|
||||
const state=await readState(r,{clock}),clans=new Set([p.orderingClanId,p.targetClanId].flatMap(id=>clanWarBranch(state.clans,id).map(c=>c.id)));
|
||||
const campaigns=await b.query('SELECT snapshot_json FROM jarvis_war_campaigns WHERE ends_at>? ORDER BY starts_at,id LIMIT 501 FOR UPDATE',[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=>clans.has(id))))fail('A participating clan already has a scheduled or active campaign.');}
|
||||
const slots=await b.query("SELECT p.parties_json FROM jarvis_war_proposals p JOIN jarvis_war_slots s ON s.proposal_id=p.id WHERE p.state='scheduled' AND s.ends_at>? ORDER BY p.id,s.party_key LIMIT 501 FOR UPDATE",[clock()]);if(slots.length>500)fail('The war calendar requires reconciliation.');
|
||||
if(slots.some(row=>JSON.parse(row.parties_json).some(party=>party.kind==='clan'&&clanWarBranch(state.clans,party.id).some(c=>clans.has(c.id)))))fail('A participating clan already has a scheduled war.');
|
||||
if(p.retaliationLevel===3){
|
||||
const parties=[p.orderingClanId,p.targetClanId].map(id=>({kind:'clan',id})),earliest=clock()+600000;
|
||||
if(await paxBlocksWar(r,parties,{startsAt:earliest,endsAt:earliest+3600000},clock()))fail('The original war peace rules currently protect this escalation.');
|
||||
const charters=await r.query('SELECT clan_id,key_id FROM site_clan_charters ORDER BY clan_id LIMIT 501');if(charters.length>500)fail('The charter register requires reconciliation.');
|
||||
// Verify both COMPLETE rosters and registered provinces before accepting the
|
||||
// escalation fee. The real paid marker is issued only by the commit below.
|
||||
buildClanCampaignSnapshot(state,parties,charters,{}, {},[],{raidEscalation:{orderId:p.id,chainId:p.chainId,receiptKeyId:p.preflightNonce}});
|
||||
}
|
||||
}
|
||||
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};
|
||||
}
|
||||
8
website/node/imperial-raid-configuration.mjs
Normal file
8
website/node/imperial-raid-configuration.mjs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
export function imperialRaidEnvironment(payload){
|
||||
const lines=payload.split(/(?<=\n)/),matches=[];
|
||||
for(let i=0;i<lines.length;i++)if(/^\s*(?:export\s+)?IMPERIAL_RAIDS_ENABLED\s*=/.test(lines[i]))matches.push(i);
|
||||
if(matches.length>1)throw Error('Duplicate Imperial raid activation setting requires review');
|
||||
if(matches.length)lines[matches[0]]='IMPERIAL_RAIDS_ENABLED=true'+(lines[matches[0]].endsWith('\r\n')?'\r\n':lines[matches[0]].endsWith('\n')?'\n':'');
|
||||
else{if(payload&&!payload.endsWith('\n'))lines.push('\n');lines.push('IMPERIAL_RAIDS_ENABLED=true\n');}
|
||||
return lines.join('');
|
||||
}
|
||||
29
website/node/imperial-raid-jobs.mjs
Normal file
29
website/node/imperial-raid-jobs.mjs
Normal 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;
|
||||
}
|
||||
194
website/node/imperial-raid-orders.mjs
Normal file
194
website/node/imperial-raid-orders.mjs
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
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,season_id VARCHAR(8) 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 pollOrders(store,server,{candidate=null,lock=false}={}){
|
||||
const rows=await store.query("SELECT accepted_json FROM jarvis_imperial_raid_orders WHERE state IN ('accepted','warning','started') ORDER BY created_at,id LIMIT 501"+(lock?' FOR UPDATE':''));
|
||||
if(rows.length>500)fail('The active raid register requires reconciliation.');
|
||||
const orders=rows.map(r=>parse(r.accepted_json)).filter(p=>p?.server===server);if(candidate)orders.push(candidate);
|
||||
const response={ok:true,schema:1,orders};
|
||||
if(orders.length>100||Buffer.byteLength(JSON.stringify(response),'utf8')>262144)fail('This server’s raid delivery register is full. Resolve existing raids before another paid order.');
|
||||
return response;
|
||||
}
|
||||
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.query('SELECT * FROM jarvis_imperial_raid_clans WHERE clan_id=?'+(create?' FOR UPDATE':''),[id]))[0]||{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=?,season_id=? WHERE id=?',[JSON.stringify({authority:c.authority}),c.seasonId||null,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.
|
||||
// Reserve actual native delivery capacity BEFORE any debit. Both UUID fields
|
||||
// below have the exact final serialized size; no silent page/truncation.
|
||||
await pollOrders(tx,input.server,{candidate:{...p,receiptKeyId:p.preflightNonce,bankOrderId:p.id,acceptedAt:now},lock:true});
|
||||
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'){
|
||||
return pollOrders(db,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);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
55
website/node/imperial-raid-protocol.mjs
Normal file
55
website/node/imperial-raid-protocol.mjs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
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']);
|
||||
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;
|
||||
const account=v=>typeof v==='string'&&/^[1-9]\d{0,11}$/.test(v);
|
||||
const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
|
||||
const exact=(v,fields)=>object(v)&&Object.keys(v).length===fields.length&&fields.every(k=>Object.hasOwn(v,k));
|
||||
const fail=message=>{throw Object.assign(Error(message),{status:400});};
|
||||
const intentFields=['uuid','requestId','orderingClanId','targetClanId','sourceAccountId'];
|
||||
const fields=Object.freeze({
|
||||
context:['uuid','orderingClanId','targetClanId'],
|
||||
prepare:intentFields,status:intentFields,cancel_prepared:intentFields,
|
||||
accept:['orderId','eventId','inputHash','preflightNonce','preflight'],
|
||||
poll:[],ack:['orderId','eventId','phase','occurredAt'],
|
||||
outcome:['orderId','eventId','outcome','startedAt','occurredAt','activeMillis']
|
||||
});
|
||||
export function validateImperialRaidInput(value){
|
||||
if(!object(value)||!Object.hasOwn(fields,value.action)||!exact(value,['action','server',...fields[value.action]])||!NATIVE_SERVERS.includes(value.server)||value.server==='lobby')fail('Invalid Imperial raid request.');
|
||||
const input=structuredClone(value);
|
||||
for(const k of ['uuid','requestId','orderingClanId','targetClanId','orderId','eventId','preflightNonce'])if(Object.hasOwn(input,k)){
|
||||
if(!uuid(input[k]))fail('Invalid Imperial raid reference.');input[k]=input[k].toLowerCase();
|
||||
}
|
||||
if(Object.hasOwn(input,'sourceAccountId')&&!account(input.sourceAccountId))fail('Choose a current clan funding account.');
|
||||
if(input.action==='accept'){
|
||||
const p=input.preflight;
|
||||
if(!digest(input.inputHash)||!exact(p,['worldUuid','position','claimRevision','defendersOnline','spawnable','protected','observedAt'])||!uuid(p.worldUuid)||!exact(p.position,['x','y','z'])||!Object.values(p.position).every(v=>Number.isFinite(v)&&Math.abs(v)<=30000000)||!Number.isSafeInteger(p.claimRevision)||p.claimRevision<1||!Number.isSafeInteger(p.defendersOnline)||p.defendersOnline<0||p.defendersOnline>5000||p.spawnable!==true||p.protected!==false||!time(p.observedAt))fail('A current safe native preflight is required.');
|
||||
p.worldUuid=p.worldUuid.toLowerCase();
|
||||
}
|
||||
if(input.action==='ack'&&(!['warning','started'].includes(input.phase)||!time(input.occurredAt)))fail('Invalid raid acknowledgement.');
|
||||
if(input.action==='outcome'&&(!IMPERIAL_RAID_OUTCOMES.includes(input.outcome)||!time(input.startedAt)||!time(input.occurredAt)||!time(input.activeMillis)||input.activeMillis>IMPERIAL_RAID_POLICY.durationMs))fail('Invalid raid outcome.');
|
||||
return input;
|
||||
}
|
||||
// The same canonical intent binds prepare, status and cancellation. A cancel can
|
||||
// therefore win a race against a delayed prepare without a paid operation.
|
||||
export function imperialRaidIntent(input){
|
||||
const {server,uuid,requestId,orderingClanId,targetClanId,sourceAccountId}=input;
|
||||
return {server,uuid,requestId,orderingClanId,targetClanId,sourceAccountId};
|
||||
}
|
||||
export const imperialRaidInputHash=input=>createHash('sha256').update(JSON.stringify(Object.values(imperialRaidIntent(input)))).digest('hex');
|
||||
const canonical=value=>Array.isArray(value)?value.map(canonical):object(value)?Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value;
|
||||
export const imperialRaidEventHash=input=>createHash('sha256').update(JSON.stringify(canonical(input))).digest('hex');
|
||||
export function imperialRaidFee(level){if(!Number.isSafeInteger(level)||level<0||level>IMPERIAL_RAID_POLICY.warAfter)throw TypeError('Invalid retaliation level');return (BigInt(IMPERIAL_RAID_POLICY.baseFeeMinor)+BigInt(IMPERIAL_RAID_POLICY.feeStepMinor)*BigInt(level)).toString();}
|
||||
export function unpaidRaidResponse(orderId,inputHash,state,message=null){
|
||||
if(!uuid(orderId)||!digest(inputHash)||!unpaidFinalStates.has(state))throw TypeError('A definitive unpaid state is required');
|
||||
return {ok:true,schema:1,orderId,requestId:orderId,inputHash,state,definitive:true,charged:false,...(message?{message}:{} )};
|
||||
}
|
||||
export function raidEventAcknowledgement(orderId,eventId,state){
|
||||
if(!uuid(orderId)||!uuid(eventId)||!['warning','started','completed','failed','neutral'].includes(state))throw TypeError('Bound raid acknowledgement required');
|
||||
return {ok:true,schema:1,orderId,eventId,state};
|
||||
}
|
||||
66
website/node/imperial-raid-quests.mjs
Normal file
66
website/node/imperial-raid-quests.mjs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import {createPOLProgression} from './progression-pol.mjs';
|
||||
import {createSystemCharacters} from './system-characters.mjs';
|
||||
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
||||
import {imperialRaidInputHash,imperialRaidEventHash} from './imperial-raid-protocol.mjs';
|
||||
|
||||
const parse=JSON.parse;
|
||||
export const isImperialRaidQuest=id=>/^RAID-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(id||'');
|
||||
const definition=r=>({id:'RAID-'+r.id,season:r.season_id,branch:'clan',title:'Summon a Rival Raid',objective:'Complete this paid Imperial raid: 1,000 Reputation XP if the commander survives; 100 if defeated.',issuer:'gurney_halleck',issuerName:'Gurney Halleck',metric:'pol-raid-'+r.id,target:1,requires:[],requiresAny:[],verifiedOnly:true,optional:false,revision:1,xp:1000,imperialRaid:true});
|
||||
|
||||
// Rewards remain ordinary POL quest keys/claims/XP ledger entries. Only a
|
||||
// receipt-bound terminal order can supply this adapter's completion evidence.
|
||||
export function createImperialRaidQuests(central,keys,{clock=Date.now}={}){
|
||||
const observer=Object.freeze({source:'imperial-raid-receipts'});
|
||||
async function actorFor(id,store=central){return (await store.query("SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]))[0]||null;}
|
||||
async function verified(actor,store=central,{lock=false}={}){
|
||||
const raw=store.sourceStore||store;
|
||||
const links=await raw.query('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?'+(lock?' FOR UPDATE':''),[actor.id]);
|
||||
if(links.length!==1)throw Error('Current raid quest identity required');
|
||||
const rows=await raw.query("SELECT * FROM jarvis_imperial_raid_orders WHERE actor_id=? AND accepted_json IS NOT NULL ORDER BY created_at,id"+(lock?' FOR UPDATE':''),[actor.id]);
|
||||
const verified=[];
|
||||
for(const row of rows){
|
||||
const intent=parse(row.intent_json),order=parse(row.accepted_json);
|
||||
const key=(await raw.query('SELECT account_id,key_type,scope_id,revoked_at FROM organisation_keys WHERE id=?',[order.receiptKeyId]))[0];
|
||||
if(!row.season_id||intent.uuid!==String(links[0].minecraft_uuid).toLowerCase()||row.minecraft_uuid!==intent.uuid||order.actorUuid!==intent.uuid||order.id!==row.id||order.requestId!==row.id||order.bankOrderId!==row.id||row.input_hash!==imperialRaidInputHash(intent)||order.inputHash!==row.input_hash||order.feeMinor!==String(2500000+500000*order.retaliationLevel)||![0,1,2,3].includes(order.retaliationLevel)||key?.account_id!==STAFF_OFFICE_ACCOUNT_ID||key.key_type!=='entity-state'||key.scope_id!=='state:imperial-raid:'+row.id||key.revoked_at!==null)throw Error('The original paid raid quest receipt requires reconciliation');
|
||||
const season=(await raw.query('SELECT starts_at,ends_at FROM jarvis_pol_progression_seasons WHERE season_id=?',[row.season_id]))[0];
|
||||
if(!season||order.acceptedAt<Number(season.starts_at)||order.acceptedAt>=Number(season.ends_at))throw Error('Original raid Reputation season required');
|
||||
let xp=null,eventId=null;
|
||||
if(['completed','failed'].includes(row.state)){
|
||||
const terminal=parse(row.outcome_json),event=(await raw.query('SELECT event_hash,response_json FROM jarvis_imperial_raid_events WHERE event_id=? AND order_id=?',[row.terminal_event_id,row.id]))[0],response=event&&parse(event.response_json);
|
||||
if(!event||event.event_hash!==imperialRaidEventHash(terminal)||terminal.eventId!==row.terminal_event_id||terminal.orderId!==row.id||response.orderId!==row.id||response.eventId!==terminal.eventId||response.state!==row.state||row.started_at===null||terminal.startedAt!==Number(row.started_at)||row.state==='completed'&&(terminal.outcome!=='survived'||terminal.activeMillis!==900000)||row.state==='failed'&&terminal.outcome!=='commander_defeated')throw Error('Verified terminal raid proof required');
|
||||
xp=row.state==='completed'?1000:100;eventId=terminal.eventId;
|
||||
}
|
||||
verified.push({...row,xp,eventId,definition:definition(row)});
|
||||
}
|
||||
return verified;
|
||||
}
|
||||
async function engineFor(actor){
|
||||
const records=await verified(actor),definitions=records.map(r=>r.definition);
|
||||
const engine=createPOLProgression(central,keys,{clock,definitions,
|
||||
authorizePlayer:async(a,store)=>!!await actorFor(a.id,store),resolvePlayer:actorFor,verifyAcquisition:async()=>false,
|
||||
authorizeIssuer:async(tx,d)=>{const identity=await createSystemCharacters(tx.sourceStore||tx,keys,{authorizeOperator:async()=>false}).inspect(d.issuer);if(!identity?.capabilities.includes('quest.issue'))throw Error('Verified raid quest issuer unavailable');return identity;},
|
||||
authorizeObservation:async(a,input,store)=>a===observer&&(await verified({id:input.accountId},store,{lock:true})).some(r=>r.definition.metric===input.metric&&r.season_id===input.seasonId&&r.xp!==null&&input.eventId==='raid-terminal:'+r.eventId&&input.value===1),
|
||||
authorizeClaim:async(a,d,store)=>(await verified(a,store,{lock:true})).some(r=>r.definition.id===d.id&&r.xp!==null),
|
||||
resolveAward:async(a,d,store)=>{const r=(await verified(a,store,{lock:true})).find(r=>r.definition.id===d.id);if(r?.xp===null||!r)throw Error('Raid outcome is not rewardable');return {xp:r.xp,reward:{},basis:{orderId:r.id,eventId:r.eventId,outcome:r.state,reputationOnly:true}};}
|
||||
});return {engine,records};
|
||||
}
|
||||
async function collect(actor){
|
||||
const {engine,records}=await engineFor(actor);
|
||||
const seasons=await central.query("SELECT season_id FROM jarvis_pol_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[clock(),clock()]);
|
||||
if(seasons.length!==1)throw Error('Current Reputation season required');
|
||||
for(const r of records)if(r.xp!==null&&r.season_id===seasons[0].season_id)await engine.observe(observer,{accountId:actor.id,seasonId:r.season_id,metric:r.definition.metric,value:1,eventId:'raid-terminal:'+r.eventId,source:'paid-raid-terminal'});
|
||||
return {engine,records};
|
||||
}
|
||||
return Object.freeze({
|
||||
collect,
|
||||
async list(actor){const {engine,records}=await collect(actor);if(!records.length)return {state:'active',quests:[]};const view=await engine.list(actor);return {...view,quests:view.quests.map(q=>{const r=records.find(r=>r.definition.id===q.id);return {...q,xp:r.xp??1000,baseXP:r.xp??1000,rewardPolicy:{success:1000,defeat:100,xpType:'pol',personalXP:0,currency:0},canStart:q.canStart&&!['neutral'].includes(r.state),canClaim:q.canClaim&&r.xp!==null};})};},
|
||||
async start(actor,input){if(!isImperialRaidQuest(input.definitionId))throw Error('Unknown Imperial raid quest');const {engine,records}=await engineFor(actor);if(records.find(r=>r.definition.id===input.definitionId)?.state==='neutral')throw Error('Neutral raids do not award a quest');return engine.start(actor,input);},
|
||||
async claim(actor,input){const {engine}=await collect(actor);return engine.claim(actor,input);},
|
||||
async complete(_job,payload){
|
||||
const actor=await actorFor(payload.actorId);if(!actor)throw Error('Original raid actor unavailable');
|
||||
const {records}=await engineFor(actor),r=records.find(r=>r.id===payload.orderId);
|
||||
if(!r||r.eventId!==payload.eventId||r.xp!==payload.xp||parse(r.outcome_json).outcome!==payload.outcome)throw Error('Original raid quest job binding required');
|
||||
await this.claim(actor,{definitionId:r.definition.id,revision:1,requestId:r.eventId});return {done:true,orderId:r.id,xp:r.xp,xpType:'pol'};
|
||||
}
|
||||
});
|
||||
}
|
||||
15
website/node/imperial-raid-reservations.mjs
Normal file
15
website/node/imperial-raid-reservations.mjs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import {clanWarBranch} from './war-rosters.mjs';
|
||||
// Private Home Block/claim mutation guard only. NPC raids are never projected
|
||||
// into native wars or faction enemy/PvP state.
|
||||
export async function imperialRaidHomeReservations(store,{lock=false}={}){
|
||||
const rows=await store.query("SELECT id,accepted_json FROM jarvis_imperial_raid_orders WHERE state IN ('accepted','warning','started') ORDER BY id"+(lock?' FOR UPDATE':''));
|
||||
return rows.map(row=>{const p=JSON.parse(row.accepted_json);return {id:row.id,kind:'imperial-raid',reserved:true,active:false,attackerId:p.orderingClanId,defenderId:p.targetClanId};});
|
||||
}
|
||||
|
||||
// Called while the original bank calendar lock is held. Paid accept obtains the
|
||||
// same lock before any debit, so a new booking cannot race an invisible payment.
|
||||
export async function imperialRaidCalendarAvailable(central,parties,state){
|
||||
const clans=new Set(parties.filter(p=>p.kind==='clan').flatMap(p=>clanWarBranch(state.clans,p.id).map(c=>c.id)));
|
||||
if(!clans.size)return true;
|
||||
return !(await imperialRaidHomeReservations(central)).some(r=>clans.has(r.attackerId)||clans.has(r.defenderId));
|
||||
}
|
||||
19
website/node/imperial-raid-runtime.mjs
Normal file
19
website/node/imperial-raid-runtime.mjs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import {createImperialRaidCommerce} from './imperial-raid-commerce.mjs';
|
||||
import {createImperialRaidOrders,lockImperialRaidGuard} from './imperial-raid-orders.mjs';
|
||||
import {createImperialRaidWar} from './imperial-raid-war.mjs';
|
||||
import {createImperialRaidQuests} from './imperial-raid-quests.mjs';
|
||||
import {processImperialRaidJobs} from './imperial-raid-jobs.mjs';
|
||||
|
||||
export function createImperialRaidRuntime(db,bank,keys,{clock=Date.now,...adapters}={}){
|
||||
const commerce=createImperialRaidCommerce(db,bank,keys,{clock,...adapters});
|
||||
const orders=createImperialRaidOrders(db,{...commerce,clock}),war=createImperialRaidWar(db,bank,{clock,...adapters}),quests=createImperialRaidQuests(db,keys,{clock});
|
||||
return Object.freeze({
|
||||
async execute(input){await commerce.ready();return orders.execute(input);},
|
||||
async processJobs(){await commerce.ready();return processImperialRaidJobs(db,{war:war.launch,quest:(job,payload)=>quests.complete(job,payload),refund:async(_job,payload)=>db.transaction(async tx=>{
|
||||
await lockImperialRaidGuard(tx);const row=await tx.first('SELECT * FROM jarvis_imperial_raid_orders WHERE id=? FOR UPDATE',[payload.orderId]);
|
||||
if(!row||row.terminal_event_id!==payload.eventId||JSON.parse(row.outcome_json).outcome!==payload.outcome)throw Error('Original refund job binding required');
|
||||
if(row.war_campaign_id)return {done:true,refundState:'not_due',refundReason:'war_started'};
|
||||
const result=await commerce.refund(tx,row);return {...result,done:result.refundState==='posted'};
|
||||
})},{clock});}
|
||||
});
|
||||
}
|
||||
72
website/node/imperial-raid-war.mjs
Normal file
72
website/node/imperial-raid-war.mjs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
import {atomicBankAccess} from './atomic-bank-access.mjs';
|
||||
import {boardReadStore} from './board-deed-source.mjs';
|
||||
import {readGameNativeState} from './game-native-state.mjs';
|
||||
import {buildClanCampaignSnapshot} from './war-rosters.mjs';
|
||||
import {lockWarCalendar} from './war-muster.mjs';
|
||||
import {launchVerifiedWarCampaign} from './war-campaign-store.mjs';
|
||||
import {eventInput} from './jarvis-events.mjs';
|
||||
import {createRealmEventRecord} from './realm-event-records.mjs';
|
||||
import {paxBlocksWar} from './imperial-pax.mjs';
|
||||
import {lockImperialRaidGuard} from './imperial-raid-orders.mjs';
|
||||
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
||||
import {WAR_BLOCK_MS,warPartyKey} from '../control-panel/public/war-exchange-policy.mjs';
|
||||
const fail=message=>{throw Object.assign(Error(message),{status:409});};
|
||||
export const raidWarId=chainId=>{const h=createHash('sha256').update('imperial-raid-war:'+chainId).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);};
|
||||
const reference=(warId,purpose)=>raidWarId(warId+':'+purpose);
|
||||
const warTables=['jarvis_war_calendar_guard','jarvis_war_proposals','jarvis_war_slots','jarvis_war_rosters','jarvis_war_history','jarvis_war_campaigns','jarvis_war_roster_keys','jarvis_events','jarvis_event_history'];
|
||||
|
||||
// This automates inputs to the existing War Exchange records and shared launch
|
||||
// commit path. It does not introduce another campaign/capture/settlement engine.
|
||||
export function createImperialRaidWar(central,bank,{clock=Date.now,verifyStorage,readState=readGameNativeState,allowBlock=async(db,parties,block,now)=>!await paxBlocksWar(db,parties,block,now)}={}){
|
||||
const banking=atomicBankAccess(boardReadStore(central,central),bank,{verifyStorage,centralTables:['jarvis_imperial_raid_guard','jarvis_imperial_raid_orders','jarvis_imperial_raid_jobs','organisation_keys','site_clans','site_clan_charters','site_claim_registry'],bankTables:warTables});
|
||||
async function launch(_job,payload){
|
||||
await banking.ready();return central.transaction(async raw=>{
|
||||
const tx=boardReadStore(raw,central);tx.readSnapshot=undefined;await lockImperialRaidGuard(tx);
|
||||
const row=await tx.first('SELECT * FROM jarvis_imperial_raid_orders WHERE id=? FOR UPDATE',[payload.orderId]);
|
||||
if(!row?.accepted_json)fail('A paid third-retaliation receipt is required.');
|
||||
const order=JSON.parse(row.accepted_json),b=banking.view(tx),warId=raidWarId(order.chainId);
|
||||
if(order.retaliationLevel!==3||payload.chainId!==order.chainId||payload.orderingClanId!==order.orderingClanId||payload.targetClanId!==order.targetClanId)fail('The original retaliation chain changed.');
|
||||
const key=await tx.first("SELECT id FROM organisation_keys WHERE id=? AND account_id=? AND key_type='entity-state' AND scope_id=? AND revoked_at IS NULL",[order.receiptKeyId,STAFF_OFFICE_ACCOUNT_ID,'state:imperial-raid:'+row.id]);
|
||||
const payment=await b.first('SELECT o.*,a.system_key target_system_key FROM pb_orders o JOIN pb_accounts a ON a.id=o.target_id WHERE o.id=?',[order.bankOrderId]);
|
||||
if(!key||!payment||payment.state!=='posted'||payment.id!==row.id||payment.actor_id!==row.actor_id||String(payment.source_id)!==order.sourceAccountId||String(payment.amount_minor)!==order.feeMinor||payment.fingerprint!==order.inputHash||payment.target_system_key!=='sys_tax_treasury')fail('The original paid JARVIS raid receipt requires reconciliation.');
|
||||
if(row.war_campaign_id){
|
||||
const recorded=await b.first('SELECT snapshot_json FROM jarvis_war_campaigns WHERE id=?',[row.war_campaign_id]);
|
||||
const campaign=recorded&&JSON.parse(recorded.snapshot_json);
|
||||
if(row.war_campaign_id!==warId||campaign?.raidEscalation?.orderId!==row.id||campaign.raidEscalation.chainId!==order.chainId||campaign.raidEscalation.receiptKeyId!==order.receiptKeyId)fail('The original escalation campaign requires reconciliation.');
|
||||
return {done:true,warId,replayed:true};
|
||||
}
|
||||
if(row.started_at===null||!['started','completed','failed'].includes(row.state))fail('A real started third retaliation is required; neutral raids cannot start wars.');
|
||||
await lockWarCalendar(b);
|
||||
for(const id of [order.orderingClanId,order.targetClanId].sort())await tx.first('SELECT id FROM site_clans WHERE id=? FOR UPDATE',[id]);
|
||||
const state=await readState(tx,{clock}),parties=[order.orderingClanId,order.targetClanId].map(id=>{const clan=state.clans.find(c=>c.id===id&&c.lifecycle==='active');if(!clan)fail('An escalation clan is no longer active.');return {kind:'clan',id,name:clan.name};});
|
||||
const now=clock(),block={startsAt:now,endsAt:now+WAR_BLOCK_MS};
|
||||
if(!await allowBlock(tx,parties,block,now))fail('The original war rules currently protect this calendar block.');
|
||||
const marker={orderId:row.id,chainId:order.chainId,receiptKeyId:order.receiptKeyId},charters=await tx.query('SELECT clan_id,key_id FROM site_clan_charters ORDER BY clan_id LIMIT 501');
|
||||
if(charters.length>500)fail('The charter register requires reconciliation.');
|
||||
const snapshot=buildClanCampaignSnapshot(state,parties,charters,{}, {},[],{raidEscalation:marker});
|
||||
for(const party of parties){
|
||||
if(await b.first("SELECT p.id FROM jarvis_war_proposals p JOIN jarvis_war_slots s ON s.proposal_id=p.id WHERE p.state='scheduled' AND s.party_key=? AND s.starts_at<? AND s.ends_at>? LIMIT 1",[warPartyKey(party),block.endsAt,block.startsAt]))fail('A participating clan already has a scheduled war in this block.');
|
||||
}
|
||||
if(await b.first('SELECT id FROM jarvis_war_proposals WHERE id=?',[warId]))fail('An incomplete original escalation proposal requires reconciliation.');
|
||||
const title='Imperial raid escalation',message='Automatic declaration after the third actual retaliation. Original paid order '+row.id+'.';
|
||||
await b.query("INSERT INTO jarvis_war_proposals(id,request_id,actor_id,scope_kind,scope_id,mode,title,message,parties_json,state,revision,calendar_event_id,created_at,updated_at) VALUES(?,?,?,'clan',?,'clan',?,?,?,'scheduled',1,NULL,?,?)",[warId,warId,STAFF_OFFICE_ACCOUNT_ID,order.orderingClanId,title,message,JSON.stringify(parties),now,now]);
|
||||
const rosters={};
|
||||
for(const team of snapshot.teams){
|
||||
const party=warPartyKey(team.party),selection=team.roster.map(m=>m.uuid);rosters[party]=selection;
|
||||
await b.query('INSERT INTO jarvis_war_slots VALUES(?,?,?,?,?,?,?)',[warId,party,block.startsAt,block.endsAt,STAFF_OFFICE_ACCOUNT_ID,reference(warId,'slot:'+party),now]);
|
||||
await b.query('INSERT INTO jarvis_war_rosters VALUES(?,?,?,?,?,?)',[warId,party,JSON.stringify(selection),STAFF_OFFICE_ACCOUNT_ID,reference(warId,'roster:'+party),now]);
|
||||
}
|
||||
const event=eventInput({kind:'clan',scopeId:order.orderingClanId,requestId:reference(warId,'calendar'),title,description:message,...block,confirmed:true});
|
||||
const calendar=await createRealmEventRecord(b,{id:STAFF_OFFICE_ACCOUNT_ID},event,now);
|
||||
await b.query('UPDATE jarvis_war_proposals SET calendar_event_id=? WHERE id=?',[calendar.eventId,warId]);
|
||||
await b.query('INSERT INTO jarvis_war_history VALUES(?,?,?,?,?,?)',[reference(warId,'origin'),warId,STAFF_OFFICE_ACCOUNT_ID,'raid-escalation',JSON.stringify({...marker,systemAutomation:true,manualConsent:false,rosters}),now]);
|
||||
const result=await launchVerifiedWarCampaign(b,{id:warId,mode:'clan',state:'scheduled',parties,block,rosters},snapshot,now,STAFF_OFFICE_ACCOUNT_ID,{automatic:true});
|
||||
// Same MySQL transaction as the ORIGINAL campaign records: neutral outcomes
|
||||
// cannot race a launch and refund a war whose service was already delivered.
|
||||
await tx.query('UPDATE jarvis_imperial_raid_orders SET war_campaign_id=?,updated_at=? WHERE id=?',[warId,now,row.id]);
|
||||
return {done:true,warId:result.warId,replayed:false};
|
||||
});
|
||||
}
|
||||
return {launch};
|
||||
}
|
||||
|
|
@ -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');
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {createImperialRaidQuests,isImperialRaidQuest} from './imperial-raid-quests.mjs';
|
||||
import {awardOrganisationMission} from './organisation-quest-rewards.mjs';
|
||||
import {faithQuestEvidence} from './faith-quest-evidence.mjs';
|
||||
import {mentorAward,currentMentorPolicy,mentorXP} from './pol-mentor-rewards.mjs';
|
||||
|
|
@ -26,6 +27,7 @@ import {collectPOLAcquisition} from './pol-acquisition-evidence.mjs';
|
|||
import {derivePOLContractMissions} from './pol-contract-mission-evidence.mjs';
|
||||
export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyObservation=null,bank=null}={}){
|
||||
const observer=Object.freeze({internal:'pol-key-source-reader'});
|
||||
const raidQuests=central.imperialRaidsEnabled?createImperialRaidQuests(central,keys,{clock}):null;
|
||||
const resolvePlayer=async id=>(await central.query("SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]))[0]||null;
|
||||
const authorizePlayer=async(actor,store)=>{
|
||||
if(typeof actor.revalidate==='function'&&(await actor.revalidate())?.id!==actor.id)return false;
|
||||
|
|
@ -75,8 +77,8 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO
|
|||
return {engine:createPOLProgression(central,keys,scoped),definitions};
|
||||
}
|
||||
const quests=Object.freeze({...engine,
|
||||
async start(actor,input){return (await engineFor(actor,input.definitionId)).engine.start(actor,input);},
|
||||
async claim(actor,input){return (await engineFor(actor,input.definitionId)).engine.claim(actor,input);},
|
||||
async start(actor,input){if(raidQuests&&isImperialRaidQuest(input.definitionId))return raidQuests.start(actor,input);return (await engineFor(actor,input.definitionId)).engine.start(actor,input);},
|
||||
async claim(actor,input){if(raidQuests&&isImperialRaidQuest(input.definitionId))return raidQuests.claim(actor,input);return (await engineFor(actor,input.definitionId)).engine.claim(actor,input);},
|
||||
async observe(actor,input){return (await engineFor({id:input.accountId})).engine.observe(actor,input);},
|
||||
async list(actor){const current=await engineFor(actor),result=await current.engine.list(actor),proof=typeof verifyObservation==='function'||result.state!=='active'?null:await evidence(actor);
|
||||
const claimedIds=result.quests.filter(q=>q.state==='claimed'&&q.keyId).map(q=>q.keyId),claimedAwards=new Map((claimedIds.length?await central.query('SELECT key_id,xp FROM jarvis_pol_quest_claims WHERE account_id=? AND key_id IN ('+claimedIds.map(()=>'?').join(',')+')',[actor.id,...claimedIds]):[]).map(r=>[r.key_id,Number(r.xp)]));
|
||||
|
|
@ -84,11 +86,12 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO
|
|||
const faith=await faithMultipliers(central,central,actor.id,{clock}),fremenIds=current.definitions.filter(d=>d.faction==='fremen').map(d=>d.id),fremenRewards=new Map((fremenIds.length?await central.query('SELECT definition_id,reward_json FROM jarvis_pol_quest_config WHERE definition_id IN ('+fremenIds.map(()=>'?').join(',')+')',fremenIds):[]).map(r=>[r.definition_id,r.reward_json?JSON.parse(r.reward_json):null]));
|
||||
const bonusPolicy=central.polMentorBonusEnabled?await currentMentorPolicy(central):null,bonusIssuers=new Map();
|
||||
if(bonusPolicy){const characters=createSystemCharacters(central,keys,{authorizeOperator:async()=>false});for(const issuer of new Set(current.definitions.map(d=>d.issuer))){const identity=await characters.inspect(issuer);bonusIssuers.set(issuer,!!identity?.capabilities.includes('quest.reward-bonus'));}}
|
||||
return {...result,affiliations:central.secondaryAffiliationsEnabled?await readSmugglerAffiliations(central,keys,actor.id):[],quests:result.quests.map(q=>{const d=current.definitions.find(d=>d.id===q.id),verified=typeof verifyObservation==='function'||!!proof&&(proof.totals.get(q.metric)||0)>=q.target,derived=!!(d.repeatable||d.research)&&q.revision===null,baseXP=derived?d.xp:q.xp,xp=claimedAwards.has(q.keyId)?claimedAwards.get(q.keyId):Number.isSafeInteger(baseXP)&&bonusPolicy&&bonusIssuers.get(d.issuer)?mentorXP(baseXP,bonusPolicy.xpBonusBps):baseXP;return {...q,npcRole:d.npcRole||polQuestContact(d),dialogue:d.dialogue||polQuestDialogue(d),...(central.polSupplyEnabled&&polSupplyTask(q.id)?{supply:polSupplyTask(q.id)}:{}),...(d.faction==='fremen'?{personalXP:d.personalXP,baseDMMinor:(fremenRewards.has(d.id)?fremenRewards.get(d.id):d.reward)?.amountMinor??null}:{}),...(q.metric==='pol-repeat-spice'&&q.state!=='claimed'&&proof?{progress:Math.min(q.target,proof.totals.get(q.metric)||0)}:{}),...(d.research?{research:{owner:d.owner,kind:d.kind,tier:d.tier,samples:d.samples,reputationLevel:d.reputationLevel,personalXP:d.personalXP,organisationDM:d.amountMinor/100}}:{}),baseXP,xp,mentorBonusXP:q.state==='claimed'?null:Number.isSafeInteger(xp)?xp-baseXP:0,revision:derived?1:q.revision,rewardConfigured:derived||q.rewardConfigured,canClaim:(q.canClaim||derived&&q.state==='completed')&&verified&&(!q.cooldownUntil||q.cooldownUntil<=clock()),...(q.state==='completed'&&!verified?{state:q.keyId?'active':'not-started'}:{})};}).map(q=>q.state==='claimed'||faith.xp===1||!Number.isSafeInteger(q.xp)?q:{...q,faithBonusXP:q.xp,xp:q.xp*2}).map(flightDossier).map(q=>{if(!q.research||q.state==='claimed')return q;const until=researchLast==null?null:Number(researchLast)+RESEARCH_COOLDOWN_MS,available=(!until||until<=clock())&&result.profile.level>=q.research.reputationLevel;return {...q,canClaim:q.canClaim&&available,canStart:q.canStart&&available,cooldownUntil:until&&until>clock()?until:null,cooldownMs:RESEARCH_COOLDOWN_MS};}).map(q=>{const d=current.definitions.find(d=>d.id===q.id);if(!d?.displayUnits)return q;const offset=d.target-d.displayUnits;return {...q,target:d.displayUnits,progress:Math.max(0,Math.min(d.displayUnits,q.progress-offset))};}),xpType:'pol',branches:[...(central.organisationResearchEnabled?[{id:'rd',title:'Organisation R&D',theme:'Specialist rarity and MK research'}]:[]),...POL_QUEST_BRANCHES.filter(b=>current.definitions.some(d=>d.branch===b.id)).map(b=>({id:b.id,title:b.title,theme:b.theme})),...(central.polRepeatablesEnabled?[{id:'spice-harvesting',title:'Official Spice Harvesting',theme:'Verified native harvesting, not sales'},{id:'repeatables',title:'Ongoing duties',theme:'Verified repeating objectives'}]:[])]};
|
||||
const view={...result,affiliations:central.secondaryAffiliationsEnabled?await readSmugglerAffiliations(central,keys,actor.id):[],quests:result.quests.map(q=>{const d=current.definitions.find(d=>d.id===q.id),verified=typeof verifyObservation==='function'||!!proof&&(proof.totals.get(q.metric)||0)>=q.target,derived=!!(d.repeatable||d.research)&&q.revision===null,baseXP=derived?d.xp:q.xp,xp=claimedAwards.has(q.keyId)?claimedAwards.get(q.keyId):Number.isSafeInteger(baseXP)&&bonusPolicy&&bonusIssuers.get(d.issuer)?mentorXP(baseXP,bonusPolicy.xpBonusBps):baseXP;return {...q,npcRole:d.npcRole||polQuestContact(d),dialogue:d.dialogue||polQuestDialogue(d),...(central.polSupplyEnabled&&polSupplyTask(q.id)?{supply:polSupplyTask(q.id)}:{}),...(d.faction==='fremen'?{personalXP:d.personalXP,baseDMMinor:(fremenRewards.has(d.id)?fremenRewards.get(d.id):d.reward)?.amountMinor??null}:{}),...(q.metric==='pol-repeat-spice'&&q.state!=='claimed'&&proof?{progress:Math.min(q.target,proof.totals.get(q.metric)||0)}:{}),...(d.research?{research:{owner:d.owner,kind:d.kind,tier:d.tier,samples:d.samples,reputationLevel:d.reputationLevel,personalXP:d.personalXP,organisationDM:d.amountMinor/100}}:{}),baseXP,xp,mentorBonusXP:q.state==='claimed'?null:Number.isSafeInteger(xp)?xp-baseXP:0,revision:derived?1:q.revision,rewardConfigured:derived||q.rewardConfigured,canClaim:(q.canClaim||derived&&q.state==='completed')&&verified&&(!q.cooldownUntil||q.cooldownUntil<=clock()),...(q.state==='completed'&&!verified?{state:q.keyId?'active':'not-started'}:{})};}).map(q=>q.state==='claimed'||faith.xp===1||!Number.isSafeInteger(q.xp)?q:{...q,faithBonusXP:q.xp,xp:q.xp*2}).map(flightDossier).map(q=>{if(!q.research||q.state==='claimed')return q;const until=researchLast==null?null:Number(researchLast)+RESEARCH_COOLDOWN_MS,available=(!until||until<=clock())&&result.profile.level>=q.research.reputationLevel;return {...q,canClaim:q.canClaim&&available,canStart:q.canStart&&available,cooldownUntil:until&&until>clock()?until:null,cooldownMs:RESEARCH_COOLDOWN_MS};}).map(q=>{const d=current.definitions.find(d=>d.id===q.id);if(!d?.displayUnits)return q;const offset=d.target-d.displayUnits;return {...q,target:d.displayUnits,progress:Math.max(0,Math.min(d.displayUnits,q.progress-offset))};}),xpType:'pol',branches:[...(central.organisationResearchEnabled?[{id:'rd',title:'Organisation R&D',theme:'Specialist rarity and MK research'}]:[]),...POL_QUEST_BRANCHES.filter(b=>current.definitions.some(d=>d.branch===b.id)).map(b=>({id:b.id,title:b.title,theme:b.theme})),...(central.polRepeatablesEnabled?[{id:'spice-harvesting',title:'Official Spice Harvesting',theme:'Verified native harvesting, not sales'},{id:'repeatables',title:'Ongoing duties',theme:'Verified repeating objectives'}]:[])]};
|
||||
return raidQuests?{...view,quests:[...view.quests,...(await raidQuests.list(actor)).quests]}:view;
|
||||
}
|
||||
});
|
||||
async function collect(actor){
|
||||
if(!await authorizePlayer(actor,central))throw Error('Current player identity required');let acquisitionAvailable=true;if(bank)try{await collectPOLAcquisition(central,bank,keys,actor,{clock});}catch{acquisitionAvailable=false;}const proof=await evidence(actor);if(!proof)return {state:'verified-key-sources',sources:[{source:'pol-activity-keys',available:false,reason:'pending-verified-producer'}]};
|
||||
if(!await authorizePlayer(actor,central))throw Error('Current player identity required');if(raidQuests)await raidQuests.collect(actor);let acquisitionAvailable=true;if(bank)try{await collectPOLAcquisition(central,bank,keys,actor,{clock});}catch{acquisitionAvailable=false;}const proof=await evidence(actor);if(!proof)return {state:'verified-key-sources',sources:[{source:'pol-activity-keys',available:false,reason:'pending-verified-producer'}]};
|
||||
const digest=createHash('sha256').update(JSON.stringify(proof.proofIds)).digest('hex');
|
||||
const current=await engineFor(actor),metrics=new Set(current.definitions.map(d=>d.metric));for(const [metric,value]of proof.totals)if(metrics.has(metric))await current.engine.observe(observer,{accountId:actor.id,seasonId:proof.season.season_id,metric,value,eventId:'pol-activity:'+actor.id+':'+metric+':'+digest.slice(0,32),source:'verified-activity-key'});
|
||||
if((proof.totals.get('flight-elytra-acquired')||0)>0)await current.engine.completeVerifiedBranch(actor,'elytra');
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ export function polQuestKeys(keys,{authorizeIssuer,definitions=POL_QUEST_DEFINIT
|
|||
const prior=await tx.first('SELECT key_id FROM jarvis_pol_quest_states WHERE account_id=? AND definition_id=? AND season_id=?',[input.accountId,definition.id,definition.season]);
|
||||
if(prior){const saved=await tx.first('SELECT issuer_key_id,issuer_name FROM jarvis_pol_quest_issuers WHERE quest_key_id=?',[prior.key_id]);if(saved?.issuer_key_id!==issuer.keyId||saved?.issuer_name!==issuer.username)throw Error('POL quest issuer changed; review required');}
|
||||
await input.authorize(polProgressionStore(tx),{...context,scopeId:unscoped(context.scopeId)});
|
||||
if(definition.repeatable||definition.research){const config=await tx.first('SELECT definition_id FROM jarvis_pol_quest_config WHERE definition_id=? FOR UPDATE',[definition.id]);if(!config)await tx.query('INSERT INTO jarvis_pol_quest_config(definition_id,revision,xp,reward_json,updated_by,updated_at) VALUES(?,?,?,?,?,?)',[definition.id,1,definition.xp,definition.research?JSON.stringify({schema:'organisation-research-reward-v1',owner:{kind:definition.owner.kind,id:definition.owner.id},amountMinor:definition.amountMinor,personalXP:definition.personalXP}):definition.reward?JSON.stringify(definition.reward):null,issuer.id,Date.now()]);}
|
||||
if(definition.repeatable||definition.research||definition.imperialRaid){const config=await tx.first('SELECT definition_id FROM jarvis_pol_quest_config WHERE definition_id=? FOR UPDATE',[definition.id]);if(!config)await tx.query('INSERT INTO jarvis_pol_quest_config(definition_id,revision,xp,reward_json,updated_by,updated_at) VALUES(?,?,?,?,?,?)',[definition.id,1,definition.xp,definition.research?JSON.stringify({schema:'organisation-research-reward-v1',owner:{kind:definition.owner.kind,id:definition.owner.id},amountMinor:definition.amountMinor,personalXP:definition.personalXP}):definition.reward?JSON.stringify(definition.reward):null,issuer.id,Date.now()]);}
|
||||
if(!prior)await tx.query('INSERT INTO jarvis_pol_quest_issuers(quest_key_id,issuer_key_id,issuer_name) VALUES(?,?,?)',[context.keyId,issuer.keyId,issuer.username]);
|
||||
}});},
|
||||
list:async id=>(await keys.list(id)).filter(k=>k.keyType==='quest'&&/^S\d{2,4}:POL_/.test(k.scopeId)).map(k=>({...k,scopeId:unscoped(k.scopeId)})),
|
||||
|
|
|
|||
|
|
@ -9,13 +9,16 @@ const homeChunk=home=>({x:Math.floor(home.position.x/16),z:Math.floor(home.posit
|
|||
|
||||
// Internal server model. Callers supply an authenticated, current deed/claim
|
||||
// snapshot, never browser-provided province ownership or player rosters.
|
||||
export function createWarCampaign({id,mode,startsAt,endsAt,teams,provinces,coalitions=[],launchedAt=null,worldIntervention=false,forcedEmperor=false}){
|
||||
export function createWarCampaign({id,mode,startsAt,endsAt,teams,provinces,coalitions=[],launchedAt=null,worldIntervention=false,forcedEmperor=false,raidEscalation=null}){
|
||||
const policy=WAR_MODES[mode];
|
||||
// Only the internal paid-raid adapter supplies this verified receipt binding.
|
||||
// Browser/native requests cannot select this mode or supply their own rosters.
|
||||
if(raidEscalation&&(mode!=='clan'||!['orderId','chainId','receiptKeyId'].every(k=>uuid(raidEscalation[k]))||Object.keys(raidEscalation).some(k=>!['orderId','chainId','receiptKeyId'].includes(k))||launchedAt!==startsAt))reject('A verified immediate raid escalation is required.');
|
||||
if(launchedAt!==null&&(!Number.isSafeInteger(launchedAt)||launchedAt<startsAt||launchedAt>=endsAt))reject('Campaign launch must be inside its agreed block.');
|
||||
if(!uuid(id)||!policy||!Number.isSafeInteger(startsAt)||startsAt<0||startsAt%3600000!==0||endsAt!==startsAt+3600000||!Array.isArray(teams)||teams.length!==(worldIntervention&&mode==='world'?3:policy.parties)||!Array.isArray(provinces)||!provinces.length||provinces.length>500)reject('Invalid campaign snapshot.');
|
||||
if(!uuid(id)||!policy||!Number.isSafeInteger(startsAt)||startsAt<0||!raidEscalation&&startsAt%3600000!==0||endsAt!==startsAt+3600000||!Array.isArray(teams)||teams.length!==(worldIntervention&&mode==='world'?3:policy.parties)||!Array.isArray(provinces)||!provinces.length||provinces.length>500)reject('Invalid campaign snapshot.');
|
||||
const sideIds=new Set(),players=new Set();
|
||||
for(const team of teams){
|
||||
if(typeof team.id!=='string'||!/^[a-z0-9_-]{1,36}$/i.test(team.id)||sideIds.has(team.id)||typeof team.name!=='string'||!team.name.trim()||!Array.isArray(team.roster)||(!team.roster.length&&!(forcedEmperor&&mode==='universal'&&team.party?.id==='emperor'))||team.roster.length>policy.playersPerSide)reject('Review campaign sides and roster limits.');
|
||||
if(typeof team.id!=='string'||!/^[a-z0-9_-]{1,36}$/i.test(team.id)||sideIds.has(team.id)||typeof team.name!=='string'||!team.name.trim()||!Array.isArray(team.roster)||(!team.roster.length&&!(forcedEmperor&&mode==='universal'&&team.party?.id==='emperor'))||team.roster.length>(raidEscalation?5000:policy.playersPerSide))reject('Review campaign sides and roster limits.');
|
||||
sideIds.add(team.id);
|
||||
for(const member of team.roster){const player=member.uuid?.toLowerCase();if(!uuid(player)||players.has(player))reject('A player can belong to only one campaign side.');players.add(player);}
|
||||
}
|
||||
|
|
@ -29,7 +32,7 @@ export function createWarCampaign({id,mode,startsAt,endsAt,teams,provinces,coali
|
|||
}
|
||||
if(imperial>1||new Set(provinces.map(p=>p.id)).size!==provinces.length||teams.some(t=>!provinces.some(p=>p.sideId===t.id)))reject('Every side needs distinct registered provinces.');
|
||||
if(['universal','religious'].includes(mode)&&imperial!==1)reject('This campaign requires the protected Imperial final province.');
|
||||
const result={id,mode,startsAt,endsAt,...(launchedAt!==null?{launchedAt}:{}),revision:1,...(forcedEmperor?{forcedEmperor:true}:{}),teams:clone(teams),provinces:provinces.map(p=>({...clone(p),ownerSideId:p.sideId})),captures:[],participation:{},winnerSideId:null,imperialUnlockedAt:null};
|
||||
const result={id,mode,startsAt,endsAt,...(launchedAt!==null?{launchedAt}:{}),revision:1,...(forcedEmperor?{forcedEmperor:true}:{}),...(raidEscalation?{raidEscalation:clone(raidEscalation)}:{}),teams:clone(teams),provinces:provinces.map(p=>({...clone(p),ownerSideId:p.sideId})),captures:[],participation:{},winnerSideId:null,imperialUnlockedAt:null};
|
||||
if(mode!=='clan')result.coalitions=clone(coalitions);
|
||||
for(const team of result.teams)for(const member of team.roster)member.uuid=member.uuid.toLowerCase();
|
||||
return result;
|
||||
|
|
@ -86,8 +89,8 @@ export function captureWarProvince(campaign,{eventId,playerUuid,provinceId,serve
|
|||
}
|
||||
|
||||
export function warCampaignReport(campaign,now=Date.now()){
|
||||
return {id:campaign.id,mode:campaign.mode,phase:campaignPhase(campaign,now),revision:campaign.revision,startsAt:campaign.startsAt,endsAt:campaign.endsAt,winnerSideId:campaign.winnerSideId,
|
||||
teams:campaign.teams.map((t,i)=>({id:t.id,name:t.name,color:WAR_SIDE_COLORS[i],players:t.roster.length,capacity:WAR_MODES[campaign.mode].playersPerSide,homeBlocks:campaign.provinces.filter(p=>p.ownerSideId===t.id).length,totalHomeBlocks:campaign.provinces.length,progressPercent:Math.round(100*campaign.provinces.filter(p=>p.ownerSideId===t.id).length/campaign.provinces.length)})),
|
||||
return {id:campaign.id,mode:campaign.mode,phase:campaignPhase(campaign,now),revision:campaign.revision,startsAt:campaign.startsAt,endsAt:campaign.endsAt,winnerSideId:campaign.winnerSideId,...(campaign.raidEscalation?{raidEscalation:clone(campaign.raidEscalation)}:{}),
|
||||
teams:campaign.teams.map((t,i)=>({id:t.id,name:t.name,color:WAR_SIDE_COLORS[i],players:t.roster.length,capacity:campaign.raidEscalation?t.roster.length:WAR_MODES[campaign.mode].playersPerSide,homeBlocks:campaign.provinces.filter(p=>p.ownerSideId===t.id).length,totalHomeBlocks:campaign.provinces.length,progressPercent:Math.round(100*campaign.provinces.filter(p=>p.ownerSideId===t.id).length/campaign.provinces.length)})),
|
||||
provinceCount:campaign.provinces.length,
|
||||
provinces:campaign.provinces.map((p,slot)=>({...p,slot})).filter(p=>!imperialProvinceLocked(campaign,p)).map(p=>({id:p.id,name:p.name,slot:p.slot,ownerSideId:p.ownerSideId,imperial:!!p.imperial,color:p.imperial&&p.ownerSideId===p.sideId?IMPERIAL_PROVINCE_COLOR:WAR_SIDE_COLORS[campaign.teams.findIndex(t=>t.id===p.ownerSideId)]}))};
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff