import {createHash} from 'node:crypto'; import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; import {PUBLIC_OFFICES} from './public-government.mjs'; import {officeDeedFor} from './political-appointments.mjs'; import {currentNaib} from './naib-membership.mjs'; import {CLAN_REALM_FACTIONS,rebellionQuest} from './rebellion-quest-policy.mjs'; import {transferOfficeDeed} from './office-deed-transfer.mjs'; import {polProgressionStore} from './progression-pol.mjs'; import {lockXPAccount,readActiveXPSeason,saveXPAccount} from './progression-xp-store.mjs'; import {creditXP} from './progression-xp-ledger.mjs'; const DECLARE='politics.rebellion',CAPTURE='clan.homeblock-victory'; const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); const proofFields=['confirmed','source','mode','eventId','questKeyId','attackerClanId','defenderClanId','homeBlockId','worldUuid','winnerUuid','sourceTermId','declaredAt','capturedAt']; const canonicalProof=v=>v&&Object.fromEntries(proofFields.map(k=>[k,v[k]])); const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex'); const first=async(db,sql,args=[])=>db.first?db.first(sql,args):(await db.query(sql,args))[0]||null; const reject=(message,status=409)=>{throw Object.assign(Error(message),{status});}; export const REBELLION_REWARD_SCHEMA='CREATE TABLE IF NOT EXISTS jarvis_rebellion_rewards(clan_id CHAR(36) NOT NULL,office_key VARCHAR(32) NOT NULL,season_id VARCHAR(8) NOT NULL,quest_key_id CHAR(36) NOT NULL UNIQUE,winner_id CHAR(36) NOT NULL,xp INTEGER NOT NULL,amount_minor BIGINT NOT NULL,created_at BIGINT NOT NULL,PRIMARY KEY(clan_id,office_key,season_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'; export function createRebellionQuests(central,keys,{clock=Date.now,authorizeProducer=async()=>false,resolveVictory=async()=>null}={}){ async function leader(db,actor,clanId){ if(!uuid(actor?.id)||!uuid(clanId))reject('Choose your clan.',400); const row=await first(db,"SELECT c.id,c.name,c.owner_id,c.home_world,l.minecraft_uuid,i.institution_key FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id AND m.user_id=c.owner_id AND m.clan_role='owner' JOIN site_accounts a ON a.id=m.user_id JOIN site_game_links l ON l.user_id=m.user_id AND LOWER(l.minecraft_uuid)=LOWER(m.minecraft_uuid) LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.id=? AND c.owner_id=? AND c.active=1 AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('official_account','system_account','memorial')",[clanId,actor.id]); if(!row||row.institution_key||!uuid(row.minecraft_uuid))reject('The current ordinary clan leader and linked identity are required.',403);return row; } async function target(db,actor,clanId,officeKey){ const office=PUBLIC_OFFICES.find(o=>o.key===officeKey);if(!office)reject('Choose an elected office.',400); const attacker=await leader(db,actor,clanId),now=clock(),term=await officeDeedFor(db,officeKey,now);if(term.user_id===actor.id)reject('You already hold this office.'); const defender=await first(db,"SELECT c.id,c.name FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id AND m.user_id=c.owner_id AND m.clan_role='owner' LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.owner_id=? AND c.active=1 AND i.institution_key IS NULL",[term.user_id]);if(!defender||defender.id===clanId)reject('The incumbent has no eligible main-clan Home Block.'); const choice=await first(db,'SELECT faction FROM site_character_choices WHERE user_id=? AND LOWER(minecraft_uuid)=?',[actor.id,attacker.minecraft_uuid.toLowerCase()]); if(office.kind==='house'&&(choice?.faction!==office.faction||CLAN_REALM_FACTIONS[attacker.home_world]!==office.faction)||['bene','guild'].includes(office.kind)&&choice?.faction!==office.faction)reject('The clan and political alignment do not match this office.',403); if(office.kind==='naib_chair'&&!await currentNaib(db,actor.id,{lock:true}))reject('A current sietch deed is required for this office.',403); const registry=await first(db,"SELECT snapshot_json,revision FROM site_claim_registry WHERE organisation_kind='clan' AND organisation_id=?",[defender.id]);let snapshot;try{snapshot=JSON.parse(registry?.snapshot_json);}catch{} if(!snapshot||snapshot.organisationId!==defender.id||snapshot.simulation===true||!uuid(snapshot.homeBlock?.id)||!uuid(snapshot.homeBlock?.worldUuid))reject('The incumbent Home Block is not registered.'); return {officeKey,sourceTermId:term.id,incumbentId:term.user_id,attackerClanId:clanId,attackerName:attacker.name,winnerId:actor.id,winnerUuid:attacker.minecraft_uuid.toLowerCase(),defenderClanId:defender.id,defenderName:defender.name,homeBlockId:snapshot.homeBlock.id,worldUuid:snapshot.homeBlock.worldUuid,homeBlockRevision:Number(registry.revision),homeBlockSource:snapshot.source,expiresAt:Number(term.expires_at)}; } const load=(db,keyId,action)=>first(db,'SELECT i.*,k.key_type,k.account_id AS key_owner,k.scope_id,k.used_at,k.revoked_at FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.key_id=? AND i.action_id=?',[keyId,action]); const project=row=>{const m=JSON.parse(row.manifest_json);return {keyId:row.key_id,state:row.state,...m.declaration,receipt:m.receipt||null,quest:rebellionQuest(m.declaration.officeKey)};}; async function insert(db,{keyId,requestId,accountId,action,fields,manifest,state}){await db.query('INSERT INTO jarvis_generated_instructions(key_id,request_id,account_id,action_id,template_version,fields_json,manifest_json,state,created_at) VALUES(?,?,?,?,1,?,?,?,?)',[keyId,requestId,accountId,action,JSON.stringify(fields),JSON.stringify(manifest),state,clock()]);} function checkProof(proof,declaration,questKeyId,eventId){ if(!proof||proof.confirmed!==true||proof.source!=='minecraft'||proof.mode!=='open-rebellion'||proof.eventId!==eventId||proof.questKeyId!==questKeyId||proof.attackerClanId!==declaration.attackerClanId||proof.defenderClanId!==declaration.defenderClanId||proof.homeBlockId!==declaration.homeBlockId||proof.worldUuid!==declaration.worldUuid||proof.winnerUuid?.toLowerCase()!==declaration.winnerUuid||proof.sourceTermId!==declaration.sourceTermId||proof.declaredAt!==declaration.declaredAt||!Number.isSafeInteger(proof.capturedAt)||proof.capturedAtclock()||proof.capturedAt>=declaration.expiresAt)reject('A matching verified open-rebellion Home Block victory is required.'); if(declaration.homeBlockSource!=='minecraft')reject('Development Home Blocks cannot verify an ingame victory.'); } return Object.freeze({ async declare(actor,input){ if(!input||Object.keys(input).some(k=>!['clanId','officeKey','expectedTermId','expectedHomeBlockId','requestId','confirmed'].includes(k))||!uuid(input.requestId)||!uuid(input.expectedTermId)||!uuid(input.expectedHomeBlockId)||input.confirmed!==true)reject('Confirm the rebellion decision.',400); const season=await readActiveXPSeason(polProgressionStore(central),clock()); const fields={clanId:input.clanId,officeKey:input.officeKey,expectedTermId:input.expectedTermId,expectedHomeBlockId:input.expectedHomeBlockId},scope=season.season_id+':REBELLION_'+input.requestId; const grant=await keys.issue({accountId:actor.id,keyType:'quest',scopeId:scope,authorize:async(tx,{keyId})=>{ const prior=await tx.first('SELECT i.account_id,i.fields_json,k.scope_id FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.request_id=? AND i.action_id=?',[input.requestId,DECLARE]);if(prior){if(prior.scope_id!==scope||prior.account_id!==actor.id||prior.fields_json!==JSON.stringify(fields))reject('Rebellion reference conflict.');return;} const declaration={...await target(tx,actor,input.clanId,input.officeKey),seasonId:season.season_id,declaredAt:clock()};if(declaration.sourceTermId!==input.expectedTermId||declaration.homeBlockId!==input.expectedHomeBlockId)reject('The incumbent or Home Block changed. Review the current decision.'); const active=await tx.first("SELECT i.key_id FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.action_id=? AND i.account_id=? AND i.state='issued' AND k.revoked_at IS NULL AND i.fields_json=?",[DECLARE,actor.id,JSON.stringify(fields)]);if(active)reject('This clan already has an open rebellion quest for that office.'); await insert(tx,{keyId,requestId:input.requestId,accountId:actor.id,action:DECLARE,fields,manifest:{declaration},state:'issued'}); }});const row=await load(central,grant.id,DECLARE);if(!row||row.account_id!==actor.id||row.fields_json!==JSON.stringify(fields))reject('Rebellion reference conflict.');return project(row); }, async list(actor,clanId){await leader(central,actor,clanId);const rows=await central.query('SELECT * FROM jarvis_generated_instructions WHERE account_id=? AND action_id=? ORDER BY created_at DESC',[actor.id,DECLARE]);return rows.map(project).filter(q=>q.attackerClanId===clanId);}, async options(actor,clanId){await leader(central,actor,clanId);const result=[];for(const office of PUBLIC_OFFICES){try{const snapshot=await target(central,actor,clanId,office.key);result.push({...rebellionQuest(office.key),eligible:true,target:snapshot});}catch(error){if(!error.status)throw error;result.push({...rebellionQuest(office.key),eligible:false,reason:error.message});}}return result;}, async cancel(actor,{questKeyId}){if(!uuid(questKeyId))reject('Choose your rebellion quest.',400);return keys.revoke({accountId:actor.id,keyId:questKeyId,authorize:async(tx,context)=>{const row=await load(tx,questKeyId,DECLARE);if(!row||row.account_id!==actor.id||context.keyType!=='quest'||context.scopeId!==row.scope_id)reject('Rebellion quest unavailable.',403);const d=JSON.parse(row.manifest_json).declaration;await leader(tx,actor,d.attackerClanId);await tx.query("UPDATE jarvis_generated_instructions SET state='cancelled' WHERE key_id=?",[questKeyId]);return true;}});}, async recordCapture(producer,{questKeyId,eventId}){ if(!uuid(questKeyId)||!uuid(eventId)||await authorizeProducer(producer,central)!==true)reject('A registered game key producer is required.',403); const declaration=await load(central,questKeyId,DECLARE);if(!declaration||declaration.revoked_at!=null)reject('The declared rebellion key is unavailable.');const savedManifest=JSON.parse(declaration.manifest_json),d=savedManifest.declaration;if(declaration.state==='applied'&&savedManifest.receipt?.eventId!==eventId)reject('This rebellion quest is already completed.'); const proof=canonicalProof(await resolveVictory(producer,eventId,central));checkProof(proof,d,questKeyId,eventId); const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'quest-milestone',scopeId:d.seasonId+':HOME_BLOCK_'+eventId,authorize:async(tx,{keyId})=>{ if(await authorizeProducer(producer,tx)!==true)reject('Game producer authority changed.',403);const verified=canonicalProof(await resolveVictory(producer,eventId,tx));checkProof(verified,d,questKeyId,eventId);if(hash(verified)!==hash(proof))reject('Home Block proof changed.'); const prior=await tx.first('SELECT fields_json FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[eventId,CAPTURE]);if(prior){if(prior.fields_json!==JSON.stringify(proof))reject('Home Block event reference conflict.');return;} await insert(tx,{keyId,requestId:eventId,accountId:STAFF_OFFICE_ACCOUNT_ID,action:CAPTURE,fields:proof,manifest:{questKeyId,proof},state:'recorded'}); }});const saved=await load(central,grant.id,CAPTURE);if(!saved||saved.fields_json!==JSON.stringify(proof)||JSON.parse(saved.manifest_json).questKeyId!==questKeyId)reject('Home Block event reference conflict.');return {evidenceKeyId:grant.id,eventId,questKeyId}; }, async applyCapture(producer,{evidenceKeyId}){ if(!uuid(evidenceKeyId)||await authorizeProducer(producer,central)!==true)reject('A registered game key consumer is required.',403); const evidence=await load(central,evidenceKeyId,CAPTURE);if(!evidence||evidence.key_owner!==STAFF_OFFICE_ACCOUNT_ID||evidence.key_type!=='quest-milestone'||evidence.revoked_at!=null)reject('Verified Home Block evidence key required.'); const {questKeyId,proof}=JSON.parse(evidence.manifest_json),row=await load(central,questKeyId,DECLARE);if(!row)reject('The rebellion declaration is unavailable.');const manifest=JSON.parse(row.manifest_json),d=manifest.declaration; if(row.state==='applied'){if(manifest.receipt?.evidenceKeyId!==evidenceKeyId)reject('Rebellion completion reference conflict.');return {...manifest.receipt,replayed:true};} const key=(await keys.list(row.account_id)).find(k=>k.id===questKeyId);if(key?.status!=='available')reject('The rebellion quest key is unavailable.'); await keys.consume({accountId:row.account_id,keyType:'quest',code:key.code,targetId:row.account_id,requestId:proof.eventId,apply:async(tx,{keyId,scopeId})=>{ if(await authorizeProducer(producer,tx)!==true||scopeId!==row.scope_id)reject('Game consumer authority changed.',403); await tx.first('SELECT id FROM organisation_keys WHERE id=? FOR UPDATE',[evidenceKeyId]);const currentEvidence=await load(tx,evidenceKeyId,CAPTURE);if(!currentEvidence||currentEvidence.revoked_at!=null||currentEvidence.key_type!=='quest-milestone'||currentEvidence.key_owner!==STAFF_OFFICE_ACCOUNT_ID||currentEvidence.fields_json!==JSON.stringify(proof)||currentEvidence.manifest_json!==evidence.manifest_json)reject('Home Block evidence changed or was revoked.'); const locked=await load(tx,keyId,DECLARE);if(!locked||locked.state!=='issued'||locked.manifest_json!==row.manifest_json)reject('Rebellion declaration changed.');checkProof(proof,d,keyId,proof.eventId); const current=await target(tx,{id:d.winnerId},d.attackerClanId,d.officeKey);for(const field of ['sourceTermId','incumbentId','winnerUuid','defenderClanId','homeBlockId','worldUuid'])if(current[field]!==d[field])reject('The rebellion target or clan authority changed.'); const office=await transferOfficeDeed(tx,{termId:keyId,sourceTermId:d.sourceTermId,officeKey:d.officeKey,winnerId:d.winnerId,playerUuid:d.winnerUuid,sourceId:proof.eventId,method:'rebellion',now:clock()}); const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,clock(),d.seasonId),reward=rebellionQuest(d.officeKey).reward; const prior=await tx.first('SELECT quest_key_id FROM jarvis_rebellion_rewards WHERE clan_id=? AND office_key=? AND season_id=? FOR UPDATE',[d.attackerClanId,d.officeKey,season.season_id]);let rewardState='already-awarded'; if(!prior){const state=await lockXPAccount(pol,d.winnerId,clock());await saveXPAccount(pol,d.winnerId,creditXP(state,reward.reputationXP,{capXP:Number.MAX_SAFE_INTEGER}),season,keyId,'quest-claimed',{definitionId:'REBELLION-'+d.officeKey.toUpperCase(),xp:reward.reputationXP,clanId:d.attackerClanId,sourceKey:evidenceKeyId},clock());await tx.query('INSERT INTO jarvis_rebellion_rewards(clan_id,office_key,season_id,quest_key_id,winner_id,xp,amount_minor,created_at) VALUES(?,?,?,?,?,?,?,?)',[d.attackerClanId,d.officeKey,season.season_id,keyId,d.winnerId,reward.reputationXP,reward.amountMinor,clock()]);await pol.query("INSERT INTO jarvis_quest_reward_jobs(key_id,account_id,season_id,payload_json,state,created_at) VALUES(?,?,?,?,'awaiting_funding',?)",[keyId,d.winnerId,season.season_id,JSON.stringify({kind:'clan-rebellion',clanId:d.attackerClanId,officeKey:d.officeKey,amountMinor:reward.amountMinor,evidenceKeyId}),clock()]);rewardState='awaiting-funding';} manifest.receipt={questKeyId:keyId,evidenceKeyId,eventId:proof.eventId,clanId:d.attackerClanId,winnerId:d.winnerId,winnerUuid:d.winnerUuid,officeKey:d.officeKey,officeTermId:office.termId,expiresAt:office.expiresAt,rewardState,completedAt:clock()}; await tx.query("UPDATE jarvis_generated_instructions SET state='applied',manifest_json=? WHERE key_id=?",[JSON.stringify(manifest),keyId]); }});return JSON.parse((await load(central,questKeyId,DECLARE)).manifest_json).receipt; } }); }