Merge pull request 'Add clan rebellion decisions and verified Home Block succession' (#442) from feature/rebellion-quest-flow-20261120 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 2m26s
All checks were successful
DuneRealms Web CI / web (push) Successful in 2m26s
This commit is contained in:
commit
35c828fc8b
20 changed files with 474 additions and 9 deletions
59
docs/design/CLAN-REBELLION-JARVIS.md
Normal file
59
docs/design/CLAN-REBELLION-JARVIS.md
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
# Clan rebellion — DR_DEV-000009M
|
||||
|
||||
The current ordinary clan leader declares rebellion from **Clan → Decisions**.
|
||||
The declaration is a QST key, bound to the clan, linked player identity, current
|
||||
office deed, incumbent main clan, registered Home Block, world and active season.
|
||||
There is no election application window. A declaration alone changes no office.
|
||||
Companies and protected institutional clans cannot use this conquest route.
|
||||
House offices require matching player allegiance and clan home-world alignment;
|
||||
Bene/Guild allegiance and the existing Council/sietch eligibility still apply.
|
||||
|
||||
## Website / game contract
|
||||
|
||||
1. `GET /api/clans/decisions/rebellion` returns the current leader's choices and
|
||||
journal. Each available choice contains its current target bindings.
|
||||
2. Same-origin authenticated POST `declare` takes `clanId`, `officeKey`,
|
||||
`expectedTermId`, `expectedHomeBlockId`, UUID `requestId`, and `confirmed:true`.
|
||||
Changed targets require reviewing a fresh choice. POST `cancel` takes only
|
||||
`questKeyId`. Neither browser action can claim victory.
|
||||
3. A future registered game producer calls `recordCapture(producer, {questKeyId,
|
||||
eventId})`. Its injected `resolveVictory` must read authoritative game evidence,
|
||||
never copy an untrusted request payload. The default producer authorizer denies
|
||||
all callers; this batch includes **no Minecraft producer or browser override**.
|
||||
4. Evidence fields: `confirmed:true`, `source:'minecraft'`,
|
||||
`mode:'open-rebellion'`, event/declaration key IDs, attacking/defending clan IDs,
|
||||
Home Block/world IDs, linked winner UUID, source office term ID, declaration
|
||||
timestamp and capture timestamp. The QSM key records this immutable proof.
|
||||
5. `applyCapture(producer, {evidenceKeyId})` verifies both keys and the current
|
||||
domain bindings, consumes the QST once, supersedes the incumbent term, records
|
||||
the successor deed and credits Reputation in one central transaction. The
|
||||
successor keeps the original election cycle and scheduled expiry. Elections,
|
||||
ballots and ordinary clan membership are not rewritten. Existing term-bound
|
||||
access follows the new deed. Return the stored completion receipt to the game;
|
||||
repeating the same evidence returns the same receipt.
|
||||
|
||||
Development/simulated claim snapshots cannot prove a production capture. Tests
|
||||
simulate the trusted producer in isolated databases, including the round trip.
|
||||
|
||||
## Rewards and funding
|
||||
|
||||
Emperor: **10,000 Reputation XP and 25,000 DM**. Other compatible offices:
|
||||
**2,500 Reputation XP and 5,000 DM**. Reputation goes to the incoming holder; DM
|
||||
goes to the winning clan. Rewards are once per clan, office and season. Repeated
|
||||
succession does not create another reward. Personal XP remains separate.
|
||||
|
||||
The DM job waits until both settings are configured:
|
||||
|
||||
- `REBELLION_REWARD_SOURCE_ACCOUNT`: an existing active payment account ID.
|
||||
- `REBELLION_REWARD_SOURCE_OWNER_ID`: its currently authorised funding user UUID.
|
||||
|
||||
The minute scheduler submits through existing `PostbankPayments.transfer` in
|
||||
standard mode. Existing bank processing posts it at the ordinary processing
|
||||
window. No balances are written by the quest consumer, no money is minted, and
|
||||
the defeated player is never debited. Missing funds, expired debit authority or
|
||||
an unavailable clan payment account leave the reward waiting for review. The
|
||||
quest-key UUID is the bank request ID; recovery checks the existing bank order
|
||||
before resubmitting. The journal distinguishes awaiting funding, bank processing
|
||||
and paid. No production funding account has been selected by this change.
|
||||
|
||||
Seasonal cross-type guard/holding awards and their templates remain deferred.
|
||||
|
|
@ -2,12 +2,15 @@ import {randomUUID} from 'node:crypto';
|
|||
import {ELECTION_RULES,electionWindow} from './public/election-rules.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.mjs';
|
||||
export const officeLedgerSchema=[
|
||||
`CREATE TABLE IF NOT EXISTS political_office_terms(id CHAR(36) PRIMARY KEY,kind VARCHAR(16) NOT NULL,faction VARCHAR(32) NOT NULL,election_start BIGINT NOT NULL,round_id CHAR(36) NOT NULL UNIQUE,application_id CHAR(36),user_id CHAR(36),player_uuid CHAR(36),office VARCHAR(32) NOT NULL,starts_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,outcome VARCHAR(16) NOT NULL,streak INTEGER NOT NULL,UNIQUE KEY office_cycle(kind,faction,election_start)) ENGINE=InnoDB`,
|
||||
`CREATE TABLE IF NOT EXISTS political_office_terms(id CHAR(36) PRIMARY KEY,kind VARCHAR(16) NOT NULL,faction VARCHAR(32) NOT NULL,election_start BIGINT NOT NULL,round_id CHAR(36) NOT NULL UNIQUE,application_id CHAR(36),user_id CHAR(36),player_uuid CHAR(36),office VARCHAR(32) NOT NULL,starts_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,outcome VARCHAR(16) NOT NULL,streak INTEGER NOT NULL,UNIQUE KEY office_cycle(kind,faction,election_start,round_id)) ENGINE=InnoDB`,
|
||||
`CREATE TABLE IF NOT EXISTS political_office_locks(scope VARCHAR(64) PRIMARY KEY) ENGINE=InnoDB`,
|
||||
`CREATE TABLE IF NOT EXISTS political_office_events(id CHAR(36) PRIMARY KEY,term_id CHAR(36) NOT NULL,event VARCHAR(32) NOT NULL,payload TEXT NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY term_event(term_id,event)) ENGINE=InnoDB`,
|
||||
`CREATE TABLE IF NOT EXISTS political_election_honours(player_uuid CHAR(36) NOT NULL,kind VARCHAR(16) NOT NULL,faction VARCHAR(32) NOT NULL,title VARCHAR(128) NOT NULL,term_id CHAR(36) NOT NULL,earned_at BIGINT NOT NULL,PRIMARY KEY(player_uuid,kind,faction)) ENGINE=InnoDB`
|
||||
];
|
||||
export async function initializeOfficeLedger(db){for(const sql of officeLedgerSchema)await db.prepare(sql).run();}
|
||||
export async function initializeOfficeLedger(db){
|
||||
for(const sql of officeLedgerSchema)await db.prepare(sql).run();
|
||||
if(db.query&&!db.sqlite){const rows=await db.query("SHOW INDEX FROM political_office_terms WHERE Key_name='office_cycle'");if(rows.length&&rows.length===3){await db.query('ALTER TABLE political_office_terms DROP INDEX office_cycle, ADD UNIQUE KEY office_cycle(kind,faction,election_start,round_id)');}}
|
||||
}
|
||||
const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
|
||||
export function planOfficeTerm(round,application,previous,now){
|
||||
if(!['winner','no_votes'].includes(round.status))throw Error('A final election result is required');
|
||||
|
|
@ -35,9 +38,9 @@ export async function reconcileOfficeResult(db,{roundId,now=Date.now(),makeId=ra
|
|||
const scope=round.kind+':'+round.faction;
|
||||
await q('INSERT INTO political_office_locks(scope) VALUES(?) ON DUPLICATE KEY UPDATE scope=VALUES(scope)',[scope]);
|
||||
await q('SELECT scope FROM political_office_locks WHERE scope=? FOR UPDATE',[scope]);
|
||||
const [existing]=await q('SELECT * FROM political_office_terms WHERE kind=? AND faction=? AND election_start=? FOR UPDATE',[round.kind,round.faction,round.election_start]);
|
||||
const [existing]=await q('SELECT * FROM political_office_terms WHERE round_id=? FOR UPDATE',[round.id]);
|
||||
if(existing){if(existing.round_id!==round.id)throw Error('Conflicting final result');return {id:existing.id,replayed:true};}
|
||||
const [previous]=await q('SELECT * FROM political_office_terms WHERE kind=? AND faction=? ORDER BY election_start DESC LIMIT 1 FOR UPDATE',[round.kind,round.faction]);
|
||||
const [previous]=await q('SELECT * FROM political_office_terms WHERE kind=? AND faction=? ORDER BY election_start DESC,starts_at DESC LIMIT 1 FOR UPDATE',[round.kind,round.faction]);
|
||||
const [application]=round.winner_id?await q('SELECT * FROM political_applications WHERE id=?',[round.winner_id]):[];
|
||||
if(round.kind==='naib_chair'&&application&&!await currentNaib({query:q},application.user_id,{lock:true}))throw Error('Chair winner is no longer a Naib');
|
||||
const term=planOfficeTerm(round,application,previous,now),id=makeId();
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import {mountClientClans} from './cp-v2-client-clans.mjs';
|
||||
import {mountClanRebellions} from './cp-v2-rebellions.mjs';
|
||||
import {mountProgressionDesign} from './cp-v2-progression.mjs';
|
||||
import {mountRealmEvents} from './cp-v2-events.mjs';
|
||||
import {mountElectionDesign,mountAdvertisingDesign} from './cp-v2-election-design.mjs';
|
||||
|
|
@ -10,6 +11,7 @@ import {element as el} from './cp-v2-page-template.mjs';
|
|||
import {mountNativeService} from './cp-v2-native-services.mjs';
|
||||
import {mountUserPage} from './cp-v2-user-pages.mjs';
|
||||
export function mountPlayWorkspace(host,workspace,id,options={}){
|
||||
if(workspace==='clan'&&id==='clan-decisions')return mountClanRebellions(host,{fetcher:options.fetcher||fetch,clanId:options.accountId||null});
|
||||
if(workspace==='quests'||workspace==='clan'&&id==='clan-quests')return mountProgressionDesign(host,{context:workspace==='clan'?'clan':'personal',dashboard:workspace==='quests'&&id==='quest-dashboard'});
|
||||
if(workspace==='events'||workspace==='clan'&&id==='clan-events')return mountRealmEvents(host,{kind:workspace==='clan'?'clan':null,fetcher:options.fetcher||fetch});
|
||||
if(workspace==='clan'&&id==='clan-elections')return mountElectionDesign(host,{context:'clan'});
|
||||
|
|
|
|||
1
website/control-panel/public/cp-v2/cp-v2-rebellions.css
Normal file
1
website/control-panel/public/cp-v2/cp-v2-rebellions.css
Normal file
|
|
@ -0,0 +1 @@
|
|||
.rebellion-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,290px),1fr));gap:18px}.rebellion-card{background:linear-gradient(145deg,#1b3e30,#0b251c);border:1px solid #a99145;border-radius:14px;padding:20px;margin:0 0 18px;min-width:0}.rebellion-card h3{color:#f1d78e;font-family:Georgia,serif;margin:0 0 14px}.rebellion-card dl{display:grid;grid-template-columns:minmax(85px,1fr) 1.5fr;border:1px solid #57704d;border-radius:8px;overflow:hidden}.rebellion-card dt,.rebellion-card dd{margin:0;padding:10px;overflow-wrap:anywhere}.rebellion-card dt{color:#d6bc70;background:#233f31}.rebellion-card dd{background:#102d23}.rebellion-card form{display:grid;gap:16px}.rebellion-card label{display:flex;gap:10px;align-items:flex-start}.rebellion-card input{flex:none}.rebellion-card button{justify-self:start}.rebellion-notice{padding:16px;border-left:3px solid #d3ae52;background:#183c2d}.rebellion-unavailable{color:#c3c8b3;font-style:italic}
|
||||
37
website/control-panel/public/cp-v2/cp-v2-rebellions.mjs
Normal file
37
website/control-panel/public/cp-v2/cp-v2-rebellions.mjs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import {element as el,createCPV2Page} from './cp-v2-page-template.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
const endpoint='/api/clans/decisions/rebellion';
|
||||
const money=n=>new Intl.NumberFormat('en-GB',{maximumFractionDigits:2}).format(n/100)+' DM';
|
||||
const date=n=>new Date(n).toLocaleString('en-GB');
|
||||
|
||||
// The browser declares intent. Only a registered game producer can attest victory.
|
||||
export function mountClanRebellions(host,{fetcher=fetch,clanId=null}={}){
|
||||
const controller=new AbortController(),api=createUserAPI(fetcher,controller.signal);let active=true,busy=false;
|
||||
const decisions=el('div'),journal=el('div'),status=el('p','Reading your clan decisions…');status.setAttribute('role','status');
|
||||
const {root}=createCPV2Page({title:'Clan decisions',description:'Declare open rebellion. Capture the incumbent main-clan Home Block to claim the remaining office term.',artwork:'organisation-deed-keys-v1.png',shellHost:host,tabs:[{id:'rebellion-decisions',label:'Open rebellion',content:decisions},{id:'rebellion-journal',label:'Quest journal',content:journal}]});
|
||||
const css=el('link');css.rel='stylesheet';css.href=new URL('./cp-v2-rebellions.css',import.meta.url).href;
|
||||
const refresh=el('button','Refresh decisions');refresh.type='button';root.prepend(css,status);root.append(refresh);host.replaceChildren(root);
|
||||
async function write(body){if(busy)return;busy=true;root.setAttribute('aria-busy','true');for(const b of root.querySelectorAll('button'))b.disabled=true;try{await api.request(endpoint,body);if(active)await load();}catch(error){if(active)status.textContent=error.message+(error.uncertain?' Refresh the journal before submitting again.':'');}finally{busy=false;if(active){root.removeAttribute('aria-busy');for(const b of root.querySelectorAll('button'))b.disabled=false;}}}
|
||||
function render(data){
|
||||
decisions.replaceChildren();journal.replaceChildren();
|
||||
const notice=el('p','The clan leader may start at any time. A verified Home Block capture is required; the Minecraft connection is pending. Starting a quest does not award an office.','rebellion-notice');decisions.append(notice);
|
||||
const grid=el('div',undefined,'rebellion-grid');decisions.append(grid);
|
||||
for(const choice of data.choices){
|
||||
const card=el('article',undefined,'rebellion-card'),heading=el('h3',choice.title);card.append(heading,el('p','Capture the incumbent main-clan Home Block in open rebellion.'));
|
||||
const facts=el('dl');for(const [label,value]of [['Reputation',choice.reward.reputationXP.toLocaleString('en-GB')+' XP'],['Clan reward',money(choice.reward.amountMinor)],['Reward limit','Once per office, clan and season']])facts.append(el('dt',label),el('dd',value));card.append(facts);
|
||||
if(!choice.eligible){card.append(el('p',choice.reason,'rebellion-unavailable'));grid.append(card);continue;}
|
||||
const target=choice.target;
|
||||
// Service returns the pinned target as an object on eligible choices.
|
||||
card.append(el('p','Target: '+target.defenderName),el('p','Office term ends '+date(target.expiresAt)));
|
||||
const open=data.quests.some(q=>q.officeKey===choice.officeKey&&q.sourceTermId===target.sourceTermId&&q.state==='issued'&&q.expiresAt>Date.now());
|
||||
if(open){card.append(el('p','A rebellion quest is already open for this office.'));grid.append(card);continue;}
|
||||
const form=el('form'),label=el('label'),confirm=el('input'),submit=el('button','Declare open rebellion');confirm.type='checkbox';confirm.required=true;label.append(confirm,document.createTextNode(' I confirm this clan decision and the current target.'));submit.type='submit';form.append(label,submit);let requestId=crypto.randomUUID();
|
||||
form.onsubmit=e=>{e.preventDefault();if(confirm.checked)void write({action:'declare',clanId:data.clanId,officeKey:choice.officeKey,expectedTermId:target.sourceTermId,expectedHomeBlockId:target.homeBlockId,requestId,confirmed:true});};card.append(form);grid.append(card);
|
||||
}
|
||||
if(!data.quests.length)journal.append(el('p','No rebellion quests have been declared.'));
|
||||
for(const quest of data.quests){const card=el('article',undefined,'rebellion-card');card.append(el('h3',quest.quest.title),el('p','Target: '+quest.defenderName),el('p','State: '+quest.state),el('p','Declared '+date(quest.declaredAt)),el('p','Office term ends '+date(quest.expiresAt)));if(quest.receipt)card.append(el('p','Office transferred · Reward: '+quest.receipt.rewardState));else if(quest.state==='issued'){const cancel=el('button','Withdraw rebellion');cancel.type='button';cancel.onclick=()=>void write({action:'cancel',questKeyId:quest.keyId});card.append(cancel);}journal.append(card);}
|
||||
status.textContent='Clan decisions are up to date. DM rewards require a funded quest account and ordinary bank processing.';
|
||||
}
|
||||
async function load(){refresh.disabled=true;try{const data=await api.request(endpoint+(clanId?'?clanId='+encodeURIComponent(clanId):''));if(active)render(data);}catch(error){if(active)status.textContent=error.message;}finally{if(active)refresh.disabled=false;}}
|
||||
refresh.onclick=()=>{if(!busy)void load();};void load();return()=>{active=false;controller.abort();root.remove();};
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -13,6 +13,8 @@ export const MASTER_KEY_TEMPLATES=[
|
|||
action('company.subsidiary','Subsidiary founding','company-subsidiary',[field('parentCompanyId','Mother company'),field('recipient','Recipient')]),
|
||||
action('company.royal','Royal company charter','staff-company-royal',[field('companyId','Company'),reference])]},
|
||||
{id:'politics',label:'POL & orders',actions:[
|
||||
action('politics.rebellion','Declare open rebellion','quest',[field('clanId','Attacking clan'),field('officeKey','Elected office'),field('expectedTermId','Current office deed'),field('expectedHomeBlockId','Incumbent Home Block')],{webIssue:false,domainAdapter:'rebellionQuests.declare',executionStatus:'clan-leader-decision',effect:'Start a clan quest at any time. A verified game capture key transfers only the remaining office term. Rewards are limited once per clan, office and season.'}),
|
||||
action('clan.homeblock-victory','Verified rebellion Home Block victory','quest-milestone',[field('questKeyId','Declared rebellion key'),field('eventId','Verified game capture event')],{webIssue:false,recordOnly:true,domainAdapter:'rebellionQuests.recordCapture',executionStatus:'trusted-game-producer-only',effect:'Signed game evidence consumed by the existing rebellion quest. No browser victory or Minecraft producer is included.'}),
|
||||
action('politics.passive-order','Protected passive Order charter','staff-parent-link',[reference],{domainAdapter:'ensureCrysknifePassiveOrder',fixedTargets:['Order of the Crysknife','Emperor'],effect:'Convert the protected honorary Order to passive POL membership, retaining fixed memorial leadership, private boards and civic records. Mother authority is limited to MOTD and account.'}),
|
||||
action('politics.appoint','Political appointment','political-appointment',[field('office','Office'),field('recipient','Recipient'),field('role','Role'),field('expiresAt','Term end','datetime-local'),reference]),
|
||||
action('politics.membership','Office deed membership','political-clan',[field('termId','Office term'),field('recipient','Recipient')]),
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
import {createRebellionRewards} from '../node/rebellion-rewards.mjs';
|
||||
import {createDeedPurchases} from '../node/deed-purchases.mjs';
|
||||
import {createRebellionQuests,REBELLION_REWARD_SCHEMA} from '../node/rebellion-quests.mjs';
|
||||
import {createRebellionAPI} from '../node/rebellion-api.mjs';
|
||||
import {createPOLProgressionRuntime} from '../node/progression-pol-runtime.mjs';
|
||||
import {initializePOLProgression,ensurePOLProgressionPolicy,polProgressionStore} from '../node/progression-pol.mjs';
|
||||
import {initializeSystemCharacters} from '../node/system-characters.mjs';
|
||||
|
|
@ -219,6 +222,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
const realmEvents=createRealmEvents(db,dependencies.bankDatabase||null,{origin});
|
||||
const rihla=createRihlaAPI(db,dependencies.bankDatabase||null);
|
||||
const networkLayouts=createNetworkLayoutAPI(db);
|
||||
const rebellionAPI=createRebellionAPI(db,dependencies.rebellionQuests||(dependencies.organisationKeys?createRebellionQuests(db,dependencies.organisationKeys):null),{origin});
|
||||
const jarvisManagement=createJarvisManagement(db,dependencies.bankDatabase||null,settings,dependencies.jarvisManagement);
|
||||
const organisationManagement=createOrganisationManagement(db,{origin});
|
||||
const luckperms=createLuckPerms(db,settings,dependencies.luckperms);
|
||||
|
|
@ -337,6 +341,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(['/api/clans/shop','/api/clans/shop/price','/api/clans/game-context'].includes(path))return clanShop(request);
|
||||
if(path.startsWith('/api/clan-emblems/'))return clanEmblems(request);
|
||||
if(path.startsWith('/api/company-emblems/'))return companyEmblems(request);
|
||||
if(path==='/api/clans/decisions/rebellion')return rebellionAPI(request);
|
||||
if(path==='/api/clans'||path.startsWith('/api/clans/'))return clans(request);
|
||||
if(path.startsWith('/api/hosting/'))return hosting(request);
|
||||
if(path==='/api/mail/accounts')return mailAccounts(request);
|
||||
|
|
@ -450,9 +455,9 @@ export async function startPanel(settings=process.env){
|
|||
inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.'));
|
||||
}
|
||||
const bankDatabase=await openPostbankDatabase(settings);
|
||||
const db=await openDatabase(settings);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await initializePOLProgression(db);await ensurePOLProgressionPolicy(db,organisationKeys);const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const handle=createPanel(db,settings,{inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
const db=await openDatabase(settings);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await initializePOLProgression(db);await db.query(REBELLION_REWARD_SCHEMA);await ensurePOLProgressionPolicy(db,organisationKeys);const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const handle=createPanel(db,settings,{inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
|
||||
await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db);
|
||||
const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:bankDatabase?[...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[]});
|
||||
const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:bankDatabase?[{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[]});
|
||||
const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':"default-src 'self'; script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.dunerealms.com; img-src 'self' data: https://www.dunerealms.com https://support.dunerealms.com; frame-src 'self' https://luckperms.net https://www.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://wiki.dunerealms.com; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com"};
|
||||
const server=createServer(async(req,res)=>{try{
|
||||
req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"schemaVersion": 1,
|
||||
"sourceHash": "46858d5ddff2cc8ebecf27d069b15e64499697bebdd19793569f0b8c09d3af3d",
|
||||
"sourceHash": "d4c4bfd709dd4b901041a81c9329fbd64c6f99ed979a4949c53bdabf575d1c74",
|
||||
"actions": [
|
||||
{
|
||||
"id": "clan.clear-protected-rosters",
|
||||
|
|
@ -161,6 +161,80 @@
|
|||
"webIssue": false,
|
||||
"recordOnly": false
|
||||
},
|
||||
{
|
||||
"id": "politics.rebellion",
|
||||
"label": "POL & orders · Declare open rebellion",
|
||||
"version": 1,
|
||||
"keyType": "quest",
|
||||
"fields": [
|
||||
{
|
||||
"name": "ticketId",
|
||||
"label": "Ban / support ticket ID",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"maxLength": 80
|
||||
},
|
||||
{
|
||||
"name": "clanId",
|
||||
"label": "Attacking clan",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "officeKey",
|
||||
"label": "Elected office",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "expectedTermId",
|
||||
"label": "Current office deed",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "expectedHomeBlockId",
|
||||
"label": "Incumbent Home Block",
|
||||
"type": "text",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"effect": "Start a clan quest at any time. A verified game capture key transfers only the remaining office term. Rewards are limited once per clan, office and season.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": false
|
||||
},
|
||||
{
|
||||
"id": "clan.homeblock-victory",
|
||||
"label": "POL & orders · Verified rebellion Home Block victory",
|
||||
"version": 1,
|
||||
"keyType": "quest-milestone",
|
||||
"fields": [
|
||||
{
|
||||
"name": "ticketId",
|
||||
"label": "Ban / support ticket ID",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"maxLength": 80
|
||||
},
|
||||
{
|
||||
"name": "questKeyId",
|
||||
"label": "Declared rebellion key",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "eventId",
|
||||
"label": "Verified game capture event",
|
||||
"type": "text",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"effect": "Signed game evidence consumed by the existing rebellion quest. No browser victory or Minecraft producer is included.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "politics.passive-order",
|
||||
"label": "POL & orders · Protected passive Order charter",
|
||||
|
|
|
|||
19
website/node/office-deed-transfer.mjs
Normal file
19
website/node/office-deed-transfer.mjs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {PUBLIC_OFFICES} from './public-government.mjs';
|
||||
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
|
||||
// Internal deed primitive. The caller must verify its signed source/key in this
|
||||
// transaction. Election and auction source records are never rewritten here.
|
||||
export async function transferOfficeDeed(tx,{termId,sourceTermId,officeKey,winnerId,playerUuid,sourceId,method,now}){
|
||||
const office=PUBLIC_OFFICES.find(o=>o.key===officeKey);
|
||||
if(!office||![termId,sourceTermId,winnerId,playerUuid,sourceId].every(uuid)||method!=='rebellion'||!Number.isSafeInteger(now))throw TypeError('Invalid office deed transfer');
|
||||
const scope=office.kind+':'+office.faction;await tx.query('INSERT INTO political_office_locks(scope) VALUES(?) ON DUPLICATE KEY UPDATE scope=VALUES(scope)',[scope]);await tx.first('SELECT scope FROM political_office_locks WHERE scope=? FOR UPDATE',[scope]);
|
||||
const prior=await tx.first('SELECT * FROM political_office_terms WHERE round_id=?',[sourceId]);
|
||||
if(prior){if(prior.id!==termId||prior.user_id!==winnerId||prior.kind!==office.kind||prior.faction!==office.faction)throw Error('Office transfer reference conflict');return {termId:prior.id,replayed:true};}
|
||||
const active=await tx.query("SELECT * FROM political_office_terms WHERE kind=? AND faction=? AND office=? AND outcome='winner' AND starts_at<=? AND expires_at>? FOR UPDATE",[office.kind,office.faction,office.office,now,now]);
|
||||
if(active.length!==1||active[0].id!==sourceTermId||active[0].user_id===winnerId)throw Error('The incumbent office deed changed');
|
||||
const source=active[0],person=await tx.first("SELECT a.id FROM site_accounts a JOIN site_game_links g ON g.user_id=a.id WHERE a.id=? AND LOWER(g.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('official_account','system_account','memorial')",[winnerId,playerUuid.toLowerCase()]);if(!person)throw Error('Current personal winner identity required');
|
||||
await tx.query("UPDATE political_office_terms SET outcome='superseded',expires_at=? WHERE id=?",[now,sourceTermId]);
|
||||
await tx.query("INSERT INTO political_office_terms(id,kind,faction,election_start,round_id,application_id,user_id,player_uuid,office,starts_at,expires_at,outcome,streak) VALUES(?,?,?,?,?,NULL,?,?,?,?,?,'winner',0)",[termId,office.kind,office.faction,source.election_start,sourceId,winnerId,playerUuid.toLowerCase(),office.office,now,source.expires_at]);
|
||||
for(const [id,event,payload]of [[sourceTermId,'superseded_by_rebellion',{successorTermId:termId,sourceId}],[termId,'rebellion_awarded',{previousTermId:sourceTermId,previousHolderId:source.user_id,sourceId,method}]])await tx.query('INSERT INTO political_office_events(id,term_id,event,payload,created_at) VALUES(?,?,?,?,?)',[randomUUID(),id,event,JSON.stringify(payload),now]);
|
||||
return {termId,previousTermId:sourceTermId,expiresAt:Number(source.expires_at),replayed:false};
|
||||
}
|
||||
24
website/node/rebellion-api.mjs
Normal file
24
website/node/rebellion-api.mjs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import {identity} from './auth.mjs';import {accessFor} from './permissions.mjs';
|
||||
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
|
||||
export function createRebellionAPI(central,service,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,central),access=u=>accessFor(central,u)}={}){
|
||||
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
||||
return async request=>{try{
|
||||
if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405);
|
||||
const actor=await authenticate(request);if(!actor)return reply({message:'Sign in first.'},401);if(!(await access(actor)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403);
|
||||
if(!service)return reply({message:'Rebellion decisions are unavailable.'},503);
|
||||
const url=new URL(request.url);
|
||||
if(request.method==='GET'){
|
||||
if([...url.searchParams.keys()].some(k=>k!=='clanId')||url.searchParams.getAll('clanId').length>1)return reply({message:'Choose one clan.'},400);
|
||||
const clanId=url.searchParams.get('clanId')||(await central.prepare("SELECT clan_id FROM site_clan_members WHERE user_id=? AND clan_role='owner'").bind(actor.id).first())?.clan_id;
|
||||
if(!uuid(clanId))return reply({message:'The clan leader starts rebellion decisions.'},403);
|
||||
return reply({clanId,choices:await service.options(actor,clanId),quests:await service.list(actor,clanId),gameProducerConnected:false});
|
||||
}
|
||||
if(url.search||request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);
|
||||
const raw=await request.text();if(raw.length>4000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Invalid rebellion decision.'},400);}
|
||||
if(!input||typeof input!=='object'||Array.isArray(input))return reply({message:'Invalid rebellion decision.'},400);
|
||||
const fresh=await authenticate(request);if(fresh?.id!==actor.id||!(await access(fresh)).nodes.includes('web.menu.game'))return reply({message:'Your session changed.'},403);
|
||||
const {action,...fields}=input;if(action==='declare')return reply({ok:true,quest:await service.declare(fresh,fields)},201);
|
||||
if(action==='cancel'&&Object.keys(fields).length===1&&uuid(fields.questKeyId))return reply({ok:true,...await service.cancel(fresh,fields)});
|
||||
return reply({message:'Unknown rebellion decision. Victory keys are accepted only through the trusted game adapter.'},400);
|
||||
}catch(error){return reply({message:error.status?error.message:'The rebellion decision could not be verified.'},error.status||503);}};
|
||||
}
|
||||
5
website/node/rebellion-quest-policy.mjs
Normal file
5
website/node/rebellion-quest-policy.mjs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import {PUBLIC_OFFICES} from './public-government.mjs';
|
||||
export const REBELLION_REWARDS=Object.freeze({emperor:Object.freeze({reputationXP:10000,amountMinor:2500000}),office:Object.freeze({reputationXP:2500,amountMinor:500000})});
|
||||
export const CLAN_REALM_FACTIONS=Object.freeze({kaladam:'atreides',giedermark:'harkonnen',kaiterhof:'corrino',sigmadraken_iv:'ordos',arrakduin:'fremen'});
|
||||
export function rebellionQuest(officeKey){const office=PUBLIC_OFFICES.find(o=>o.key===officeKey);if(!office)throw Error('Unknown elected office');return {id:'REBELLION-'+office.key.toUpperCase(),officeKey:office.key,title:office.key==='emperor'?'Seize the Imperial Throne':'Challenge the '+office.name,target:'Capture the incumbent main-clan Home Block in open rebellion',organisationKind:'clan',xpType:'pol',reward:REBELLION_REWARDS[office.key==='emperor'?'emperor':'office'],executionRequirements:{website:true,minecraft:true},producerState:'awaiting-game-adapter',rewardLimit:'once-per-clan-office-season',termPolicy:'remaining-current-term'};}
|
||||
export const UNIVERSAL_REBELLION_QUESTS=Object.freeze(PUBLIC_OFFICES.map(o=>Object.freeze(rebellionQuest(o.key))));
|
||||
89
website/node/rebellion-quests.mjs
Normal file
89
website/node/rebellion-quests.mjs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
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.capturedAt<declaration.declaredAt||proof.capturedAt>clock()||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 account_id,fields_json FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[input.requestId,DECLARE]);if(prior){if(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;
|
||||
}
|
||||
});
|
||||
}
|
||||
45
website/node/rebellion-rewards.mjs
Normal file
45
website/node/rebellion-rewards.mjs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import {PostbankPayments} from './postbank-payments.mjs';
|
||||
import {createPostbankAuthority} from './postbank-authority.mjs';
|
||||
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
|
||||
import {rebellionQuest} from './rebellion-quest-policy.mjs';
|
||||
const accountSQL='SELECT a.*,c.entity_id,e.kind,e.external_key,e.active AS entity_active,p.state AS package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id';
|
||||
const jobs='jarvis_pol_quest_reward_jobs';
|
||||
const fail=message=>{throw Error(message);};
|
||||
const first=async(db,sql,args)=>(await db.query(sql,args))[0]||null;
|
||||
|
||||
// No reward minting. A configured fund owner pays through the existing standard
|
||||
// bank queue, with the quest key as the durable payment reference across crashes.
|
||||
export function createRebellionRewards(central,bank,{sourceAccount,sourceOwnerId,authority=createPostbankAuthority(central,{bank}),payments=null}={}){
|
||||
const owner=async()=>await first(central,"SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[sourceOwnerId]);
|
||||
payments||=new PostbankPayments(bank,authority,{resolveUser:async id=>first(central,"SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id])});
|
||||
async function process(keyId){return central.transaction(async tx=>{
|
||||
const job=await tx.first(`SELECT * FROM ${jobs} WHERE key_id=? FOR UPDATE`,[keyId]);if(!job||!['awaiting_funding','submitted'].includes(job.state))return 'unchanged';
|
||||
const reward=await tx.first('SELECT * FROM jarvis_rebellion_rewards WHERE quest_key_id=?',[keyId]);
|
||||
const instruction=await tx.first("SELECT i.*,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='politics.rebellion'",[keyId]);
|
||||
if(!reward||!instruction||instruction.state!=='applied'||instruction.used_at==null||instruction.revoked_at!=null)fail('Verified completed rebellion key required');
|
||||
const {declaration:d,receipt}=JSON.parse(instruction.manifest_json),policy=rebellionQuest(reward.office_key).reward;
|
||||
if(!receipt||receipt.questKeyId!==keyId||d.attackerClanId!==reward.clan_id||d.officeKey!==reward.office_key||d.winnerId!==reward.winner_id||job.account_id!==reward.winner_id||job.season_id!==reward.season_id||d.seasonId!==reward.season_id||Number(reward.amount_minor)!==policy.amountMinor||Number(reward.xp)!==policy.reputationXP)fail('Rebellion reward bindings changed');
|
||||
const reference='Rebellion reward '+keyId;
|
||||
let order=await bank.first('SELECT * FROM pb_orders WHERE id=?',[keyId]);
|
||||
if(order){
|
||||
const target=await bank.first(accountSQL+' WHERE a.id=?',[order.target_id]);
|
||||
if(order.actor_id!==sourceOwnerId||String(order.source_id)!==String(sourceAccount)||order.memo!==reference||Number(order.amount_minor)!==policy.amountMinor||order.mode!=='standard'||target?.kind!=='clan'||target.external_key!==reward.clan_id)fail('Rebellion payment reference conflict');
|
||||
}else{
|
||||
const actor=await owner();if(!actor)fail('Quest funding owner unavailable');
|
||||
const recipients=await bank.query(accountSQL+" WHERE e.kind='clan' AND e.external_key=? ORDER BY a.id",[reward.clan_id]);
|
||||
const target=recipients.find(ordinaryPaymentAccount);if(!target)fail('Winning clan needs an active payment account');
|
||||
await payments.transfer(actor,{requestId:keyId,sourceAccount:String(sourceAccount),targetNumber:target.account_number,amount:(policy.amountMinor/100).toFixed(2),reference,mode:'standard',confirmed:true},{revalidate:owner});
|
||||
order=await bank.first('SELECT * FROM pb_orders WHERE id=?',[keyId]);
|
||||
}
|
||||
const state=order?.state==='posted'?'paid':order?.state==='queued'?'submitted':'payment_review';
|
||||
await tx.query(`UPDATE ${jobs} SET state=? WHERE key_id=?`,[state,keyId]);
|
||||
receipt.rewardState=state==='paid'?'paid':state==='submitted'?'bank-processing':'payment-review';
|
||||
await tx.query('UPDATE jarvis_generated_instructions SET manifest_json=? WHERE key_id=?',[JSON.stringify({declaration:d,receipt}),keyId]);return state;
|
||||
});}
|
||||
return Object.freeze({async drain(){
|
||||
if(!/^\d{1,12}$/.test(String(sourceAccount||''))||!/^[a-f0-9-]{36}$/i.test(sourceOwnerId||''))return {state:'awaiting-funding-configuration',attempted:0};
|
||||
const pending=await central.query(`SELECT key_id FROM ${jobs} WHERE state IN ('awaiting_funding','submitted') ORDER BY created_at,key_id LIMIT 25`),results=[];
|
||||
for(const job of pending){try{results.push({keyId:job.key_id,state:await process(job.key_id)});}catch{results.push({keyId:job.key_id,state:'awaiting-funding-or-review'});}}
|
||||
return {attempted:pending.length,results};
|
||||
}});
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
(()=>{const frame=document.getElementById('clan-workspace');if(!frame)return;frame.setAttribute('scrolling','no');frame.addEventListener('load',()=>frame.contentWindow?.postMessage({type:'dune-embed-measure'},'https://cp.dunerealms.com'));const cp='https://cp.dunerealms.com',legacy={'clans':'clan/clan-directory','clan-portal':'clan/clan-overview','clan-kits':'clan/clan-tailor','clan-shops':'clan/clan-shop','clan-bank':'clan/clan-bank','clan-settings':'clan/clan-settings','clan-quests':'clan/clan-quests'};
|
||||
const valid=value=>/^(?:clan\/(?:clan-(?:overview|roster|requests|settings|directory|boards|events|elections|advertising|mail|bank|shop|listings|post-listing|tailor|quests|campaigns|claims|subhouses|patronage))|quests\/quests|kits\/kits-exchange|events\/events-calendar)$/.test(value);
|
||||
const valid=value=>/^(?:clan\/(?:clan-(?:overview|roster|requests|settings|directory|boards|events|elections|advertising|mail|bank|shop|listings|post-listing|tailor|quests|decisions|campaigns|claims|subhouses|patronage))|quests\/quests|kits\/kits-exchange|events\/events-calendar)$/.test(value);
|
||||
function show(){const raw=location.hash.slice(1),route=valid(raw)?raw:legacy[raw]||'clan/clan-overview',url=cp+'/clan-cp#'+route;if(frame.src!==url)frame.src=url;}window.addEventListener('hashchange',show);
|
||||
window.addEventListener('message',event=>{if(event.origin!==cp||event.source!==frame.contentWindow)return;if(event.data?.type==='dune-embed-size'&&Number.isFinite(event.data.height)&&event.data.height>=100&&event.data.height<=200000)frame.style.height=Math.ceil(event.data.height)+'px';if(event.data?.type==='dune-clan-route'){const route=event.data.workspace+'/'+event.data.page;if(valid(route))history.replaceState(null,'','#'+route);}});show();})();
|
||||
|
|
|
|||
8
website/tests/office-deed-transfer.test.mjs
Normal file
8
website/tests/office-deed-transfer.test.mjs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
|
||||
import {BankFixture} from './postbank-fixture.mjs';import {officeLedgerSchema} from '../control-panel/election-office-ledger.mjs';import {ELECTION_RULES} from '../control-panel/public/election-rules.mjs';
|
||||
import {transferOfficeDeed} from '../node/office-deed-transfer.mjs';import {electionAuthority} from '../node/election-authority.mjs';import {projectGovernment} from '../node/public-government.mjs';import {REBELLION_REWARDS,UNIVERSAL_REBELLION_QUESTS} from '../node/rebellion-quest-policy.mjs';
|
||||
async function fixture(){const db=new BankFixture();for(const sql of officeLedgerSchema)await db.query(sql.replace(/ ENGINE=InnoDB/g,'').replace(/UNIQUE KEY \w+\s*\(/g,'UNIQUE('));db.sqlite.exec('CREATE TABLE site_accounts(id TEXT,username TEXT,role TEXT,password_hash TEXT);CREATE TABLE site_game_links(user_id TEXT,minecraft_uuid TEXT);CREATE TABLE political_election_rounds(id TEXT PRIMARY KEY,winner_id TEXT);');db.prepare=sql=>({bind:(...args)=>({first:()=>db.first(sql,args),all:async()=>({results:await db.query(sql,args)})})});const now=Date.parse('2026-11-20T20:00:00Z'),first=Date.parse(ELECTION_RULES.imperial.first),cycle=first+Math.floor((now-first)/(ELECTION_RULES.imperial.weeks*604800000))*ELECTION_RULES.imperial.weeks*604800000,expires=cycle+ELECTION_RULES.imperial.weeks*604800000,old=randomUUID(),winner=randomUUID(),playerUuid=randomUUID(),term=randomUUID(),round=randomUUID();for(const [id,name,mc]of [[old,'Incumbent',randomUUID()],[winner,'Successor',playerUuid]]){await db.query("INSERT INTO site_accounts VALUES(?,?,'player','hash')",[id,name]);await db.query('INSERT INTO site_game_links VALUES(?,?)',[id,mc]);}await db.query("INSERT INTO political_office_terms VALUES(?,'imperial','imperium',?,?,NULL,?,?,'emperor',?,?,'winner',2)",[term,cycle,round,old,(await db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[old])).minecraft_uuid,cycle+10800000,expires]);await db.query('INSERT INTO political_election_rounds VALUES(?,?)',[round,old]);const input={termId:randomUUID(),sourceTermId:term,officeKey:'emperor',winnerId:winner,playerUuid,sourceId:randomUUID(),method:'rebellion',now};return {db,now,old,winner,playerUuid,term,round,cycle,expires,input};}
|
||||
test('rebellion transfers the active deed for its remaining term and existing authority reads follow the new holder',async()=>{const f=await fixture();try{await f.db.transaction(tx=>transferOfficeDeed(tx,f.input));const old=await f.db.first('SELECT * FROM political_office_terms WHERE id=?',[f.term]),current=await f.db.first('SELECT * FROM political_office_terms WHERE id=?',[f.input.termId]);assert.equal(old.outcome,'superseded');assert.equal(current.user_id,f.winner);assert.equal(current.election_start,f.cycle);assert.equal(current.expires_at,f.expires);assert.equal(current.streak,0);const rights=await electionAuthority(f.db,{userId:f.winner,playerUuid:f.playerUuid,now:f.now});assert.equal(rights.imperial.active,true);const gov=projectGovernment([{...current,username:'Successor'}],f.now);assert.equal(gov.find(o=>o.key==='emperor').holder.username,'Successor');assert.equal((await f.db.first('SELECT winner_id FROM political_election_rounds WHERE id=?',[f.round])).winner_id,f.old);}finally{f.db.close();}});
|
||||
test('same source replays once; a conflicting or stale conquest cannot replace the current holder',async()=>{const f=await fixture();try{await f.db.transaction(tx=>transferOfficeDeed(tx,f.input));assert.equal((await f.db.transaction(tx=>transferOfficeDeed(tx,f.input))).replayed,true);await assert.rejects(f.db.transaction(tx=>transferOfficeDeed(tx,{...f.input,termId:randomUUID()})),/reference conflict/);await assert.rejects(f.db.transaction(tx=>transferOfficeDeed(tx,{...f.input,sourceId:randomUUID(),termId:randomUUID()})),/incumbent/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_office_terms')).n,2);}finally{f.db.close();}});
|
||||
test('another verified succession in the same election cycle retains both historical deeds',async()=>{const f=await fixture();try{await f.db.transaction(tx=>transferOfficeDeed(tx,f.input));const third=randomUUID(),mc=randomUUID();await f.db.query("INSERT INTO site_accounts VALUES(?,'Third','player','hash')",[third]);await f.db.query('INSERT INTO site_game_links VALUES(?,?)',[third,mc]);await f.db.transaction(tx=>transferOfficeDeed(tx,{...f.input,termId:randomUUID(),sourceTermId:f.input.termId,sourceId:randomUUID(),winnerId:third,playerUuid:mc,now:f.now+1000}));assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_office_terms')).n,3);assert.equal((await f.db.first("SELECT COUNT(*) n FROM political_office_terms WHERE outcome='winner'")).n,1);}finally{f.db.close();}});
|
||||
test('universal quest rewards use Reputation and clan funding, with no company conquest route',()=>{assert.equal(REBELLION_REWARDS.emperor.reputationXP,10000);assert.equal(REBELLION_REWARDS.emperor.amountMinor,2500000);assert.ok(UNIVERSAL_REBELLION_QUESTS.every(q=>q.organisationKind==='clan'&&q.xpType==='pol'&&q.rewardLimit==='once-per-clan-office-season'&&q.producerState==='awaiting-game-adapter'));});
|
||||
14
website/tests/rebellion-api.test.mjs
Normal file
14
website/tests/rebellion-api.test.mjs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {createRebellionAPI} from '../node/rebellion-api.mjs';
|
||||
function fixture(){
|
||||
const user={id:randomUUID()},clanId=randomUUID(),calls=[];let actor=user,nodes=['web.menu.game'],authCalls=0,change=false;
|
||||
const service={options:async(a,id)=>{calls.push(['options',a.id,id]);return[];},list:async()=>[],declare:async(a,input)=>{calls.push(['declare',a.id,input]);return {keyId:randomUUID()};},cancel:async()=>({revoked:true})};
|
||||
const api=createRebellionAPI({prepare:()=>({bind:()=>({first:async()=>({clan_id:clanId})})})},service,{authenticate:async()=>{authCalls++;return change&&authCalls>1?null:actor;},access:async()=>({nodes})});
|
||||
const call=(body,extra={})=>api(new Request('https://cp.dunerealms.com/api/clans/decisions/rebellion'+(extra.query||''),body===undefined?{}:{method:'POST',headers:{origin:extra.origin||'https://cp.dunerealms.com'},body:JSON.stringify(body)}));
|
||||
return{call,calls,user,clanId,logout:()=>actor=null,deny:()=>nodes=[],expire:()=>change=true};
|
||||
}
|
||||
test('rebellion reads remain private and use the signed-in clan leader',async()=>{const f=fixture(),r=await f.call();assert.equal(r.status,200);assert.equal(r.headers.get('Cache-Control'),'private, no-store');assert.deepEqual(f.calls[0],['options',f.user.id,f.clanId]);assert.equal((await f.call(undefined,{query:'?accountId=other'})).status,400);f.logout();assert.equal((await f.call()).status,401);});
|
||||
test('browser can declare intent but cannot attest a capture or award an office',async()=>{const f=fixture();assert.equal((await f.call({action:'complete',winnerId:f.user.id})).status,400);assert.equal((await f.call({action:'recordCapture',eventId:randomUUID()})).status,400);assert.equal(f.calls.length,0);assert.equal((await f.call({action:'declare',clanId:f.clanId})).status,201);assert.equal(f.calls[0][0],'declare');});
|
||||
test('writes reject foreign origins, changed sessions and missing game access',async()=>{const a=fixture();assert.equal((await a.call({action:'declare'},{origin:'https://evil.example'})).status,403);assert.equal(a.calls.length,0);const b=fixture();b.expire();assert.equal((await b.call({action:'declare'})).status,403);assert.equal(b.calls.length,0);const c=fixture();c.deny();assert.equal((await c.call()).status,403);});
|
||||
15
website/tests/rebellion-fixture.mjs
Normal file
15
website/tests/rebellion-fixture.mjs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {companyFixture} from './company-deed-fixture.mjs';import {GENERATOR_SCHEMA} from '../node/jarvis-master-generator.mjs';import {officeLedgerSchema} from '../control-panel/election-office-ledger.mjs';import {initializeProgression} from '../node/progression-schema.mjs';import {initializePOLProgression} from '../node/progression-pol.mjs';import {createRebellionQuests,REBELLION_REWARD_SCHEMA} from '../node/rebellion-quests.mjs';
|
||||
export async function fixture({officeKey='emperor',source='minecraft'}={}){
|
||||
const f=await companyFixture(),db=f.db;db.sqlite.exec('DROP TABLE political_office_terms;DROP TABLE site_clan_members;DROP TABLE site_clans;CREATE TABLE site_clans(id TEXT PRIMARY KEY,name TEXT,owner_id TEXT,home_world TEXT,active INT);CREATE TABLE site_clan_members(clan_id TEXT,user_id TEXT,clan_role TEXT,minecraft_uuid TEXT);CREATE TABLE site_clan_institutions(clan_id TEXT,institution_key TEXT);CREATE TABLE site_character_choices(user_id TEXT,minecraft_uuid TEXT,faction TEXT);CREATE TABLE political_election_rounds(id TEXT PRIMARY KEY,winner_id TEXT);');
|
||||
for(const sql of [...officeLedgerSchema,GENERATOR_SCHEMA,REBELLION_REWARD_SCHEMA])await db.query(sql.replace(/ ENGINE=InnoDB DEFAULT CHARSET=utf8mb4/g,'').replace(/ ENGINE=InnoDB/g,''));await initializeProgression(db);await initializePOLProgression(db);
|
||||
const winner=f.people.Owner,incumbent=f.people.Ceo,attacker=randomUUID(),defender=randomUUID(),mc=randomUUID(),term=randomUUID(),home=randomUUID(),world=randomUUID(),round=randomUUID();let now=Date.parse('2026-11-20T20:00:00Z');
|
||||
for(const person of Object.values(f.people))await db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[person.id===winner.id?mc:randomUUID(),person.id]);
|
||||
for(const [id,person,name]of [[attacker,winner,'Rebel Clan'],[defender,incumbent,'Incumbent Clan']]){await db.query("INSERT INTO site_clans VALUES(?,?,?,'kaladam',1)",[id,name,person.id]);const link=await db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[person.id]);await db.query("INSERT INTO site_clan_members VALUES(?,?,'owner',?)",[id,person.id,link.minecraft_uuid]);}
|
||||
await db.query("INSERT INTO site_character_choices VALUES(?,?,'atreides')",[winner.id,mc]);
|
||||
const kind=officeKey==='emperor'?'imperial':'house',faction=officeKey==='emperor'?'imperium':'atreides',office=officeKey==='emperor'?'emperor':'house_leader';await db.query("INSERT INTO political_office_terms VALUES(?,?,?,?,?,NULL,?,?,?, ?,?,'winner',1)",[term,kind,faction,now-10000,round,incumbent.id,(await db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[incumbent.id])).minecraft_uuid,office,now-1000,now+86400000]);await db.query('INSERT INTO political_election_rounds VALUES(?,?)',[round,incumbent.id]);await db.query('INSERT INTO site_claim_registry VALUES(?,?,?,?,?)',['clan',defender,JSON.stringify({organisationId:defender,source,homeBlock:{id:home,worldUuid:world}}),1,now]);
|
||||
for(const prefix of ['jarvis_','jarvis_pol_'])await db.query(`INSERT INTO ${prefix}progression_seasons(season_id,starts_at,ends_at,level_cap,curve_base,state) VALUES('S01',0,?,0,25,'active')`,[now+100000000]);
|
||||
const producer={},proofs=new Map(),service=createRebellionQuests(db,f.keys,{clock:()=>now,authorizeProducer:async actor=>actor===producer,resolveVictory:async(_actor,eventId)=>proofs.get(eventId)}),input={clanId:attacker,officeKey,expectedTermId:term,expectedHomeBlockId:home,requestId:randomUUID(),confirmed:true};
|
||||
async function capture(declaration,overrides={}){now+=1000;const eventId=randomUUID(),proof={confirmed:true,source:'minecraft',mode:'open-rebellion',eventId,questKeyId:declaration.keyId,attackerClanId:attacker,defenderClanId:defender,homeBlockId:home,worldUuid:world,winnerUuid:mc,sourceTermId:term,declaredAt:declaration.declaredAt,capturedAt:now,...overrides};proofs.set(eventId,proof);return service.recordCapture(producer,{questKeyId:declaration.keyId,eventId});}
|
||||
return {...f,winner,incumbent,attacker,defender,mc,term,home,round,producer,proofs,service,input,capture,clock:value=>now=value,now:()=>now};
|
||||
}
|
||||
28
website/tests/rebellion-quests.test.mjs
Normal file
28
website/tests/rebellion-quests.test.mjs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
|
||||
import {fixture} from './rebellion-fixture.mjs';
|
||||
|
||||
test('leader decision -> signed declaration -> game capture record -> website deed/XP -> acknowledgement round trip',async()=>{const f=await fixture();try{
|
||||
const declared=await f.service.declare(f.winner,f.input);assert.equal(declared.state,'issued');assert.equal((await f.service.declare(f.winner,f.input)).keyId,declared.keyId);assert.equal((await f.db.first('SELECT user_id FROM political_office_terms WHERE id=?',[f.term])).user_id,f.incumbent.id);
|
||||
const evidence=await f.capture(declared),receipt=await f.service.applyCapture(f.producer,evidence);assert.equal(receipt.winnerId,f.winner.id);assert.equal(receipt.winnerUuid,f.mc);assert.equal(receipt.officeTermId,declared.keyId);assert.equal(receipt.rewardState,'awaiting-funding');assert.equal((await f.service.applyCapture(f.producer,evidence)).replayed,true);
|
||||
assert.equal((await f.db.first('SELECT user_id FROM political_office_terms WHERE id=?',[receipt.officeTermId])).user_id,f.winner.id);assert.equal((await f.db.first('SELECT total_xp FROM jarvis_pol_progression_accounts WHERE account_id=?',[f.winner.id])).total_xp,10000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_progression_accounts')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_rebellion_rewards')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_pol_quest_reward_jobs')).n,1);assert.equal((await f.db.first('SELECT winner_id FROM political_election_rounds WHERE id=?',[f.round])).winner_id,f.incumbent.id);
|
||||
}finally{f.db.close();}});
|
||||
test('ordinary members, wrong alignment and wrong homeblocks cannot start or complete the quest',async()=>{const f=await fixture({officeKey:'atreides'});try{
|
||||
await assert.rejects(f.service.declare(f.people.Member,f.input),/clan leader/);await f.db.query("UPDATE site_character_choices SET faction='harkonnen' WHERE user_id=?",[f.winner.id]);await assert.rejects(f.service.declare(f.winner,f.input),/alignment/);await f.db.query("UPDATE site_character_choices SET faction='atreides' WHERE user_id=?",[f.winner.id]);const declared=await f.service.declare(f.winner,f.input);await assert.rejects(f.capture(declared,{homeBlockId:randomUUID()}),/matching verified/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_rebellion_rewards')).n,0);
|
||||
}finally{f.db.close();}});
|
||||
test('untrusted producers, development blocks, stale office deeds and revoked declarations fail without office or XP writes',async()=>{
|
||||
const f=await fixture({source:'web-development'});try{const declared=await f.service.declare(f.winner,f.input);await assert.rejects(f.capture(declared),/Development Home Blocks/);await assert.rejects(f.service.recordCapture(f.winner,{questKeyId:declared.keyId,eventId:randomUUID()}),/registered game/);await f.service.cancel(f.winner,{questKeyId:declared.keyId});assert.equal((await f.keys.list(f.winner.id)).find(k=>k.id===declared.keyId).status,'revoked');}finally{f.db.close();}
|
||||
const g=await fixture();try{const declared=await g.service.declare(g.winner,g.input),evidence=await g.capture(declared);await g.db.query("UPDATE political_office_terms SET outcome='resigned' WHERE id=?",[g.term]);await assert.rejects(g.service.applyCapture(g.producer,evidence));assert.equal((await g.db.first('SELECT COUNT(*) n FROM jarvis_rebellion_rewards')).n,0);assert.equal((await g.keys.list(g.winner.id)).find(k=>k.id===declared.keyId).status,'available');}finally{g.db.close();}
|
||||
});
|
||||
|
||||
test('stale confirmation and revoked evidence cannot transfer a deed or consume the declaration',async()=>{
|
||||
const f=await fixture();try{
|
||||
await assert.rejects(f.service.declare(f.winner,{...f.input,expectedTermId:randomUUID()}),/changed/);
|
||||
assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_generated_instructions')).n,0);
|
||||
const declared=await f.service.declare(f.winner,f.input),evidence=await f.capture(declared);
|
||||
await f.db.query('UPDATE organisation_keys SET revoked_at=? WHERE id=?',[Date.now(),evidence.evidenceKeyId]);
|
||||
await assert.rejects(f.service.applyCapture(f.producer,evidence),/evidence key/);
|
||||
assert.equal((await f.keys.list(f.winner.id)).find(k=>k.id===declared.keyId).status,'available');
|
||||
assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_rebellion_rewards')).n,0);
|
||||
assert.equal((await f.db.first('SELECT outcome FROM political_office_terms WHERE id=?',[f.term])).outcome,'winner');
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
35
website/tests/rebellion-rewards.test.mjs
Normal file
35
website/tests/rebellion-rewards.test.mjs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
|
||||
import {fixture} from './rebellion-fixture.mjs';import {BankFixture} from './postbank-fixture.mjs';
|
||||
import {PostbankService} from '../node/postbank-service.mjs';import {PostbankPayments} from '../node/postbank-payments.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';import {createRebellionRewards} from '../node/rebellion-rewards.mjs';
|
||||
async function setup(){
|
||||
const f=await fixture(),bank=new BankFixture(),fund=f.people.Other,entities=[{id:randomUUID(),kind:'person',key:fund.id,name:'Quest fund'},{id:randomUUID(),kind:'clan',key:f.attacker,name:'Winning clan'}];let allowed=true;
|
||||
const authority=async user=>({entities:entities.map(e=>({...e,canView:true,canActivate:true,canPay:allowed&&user.id===fund.id&&e.key===fund.id})),readAdmin:false,manageAdmin:false});
|
||||
const service=new PostbankService(bank,authority);for(const entity of entities)await service.activate(fund,{entityId:entity.id,packageKey:entity.kind==='clan'?'pb_connect':'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});
|
||||
const accounts=await bank.query("SELECT a.*,c.entity_id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE a.type_code IN ('102','105')"),source=accounts.find(a=>a.entity_id===entities[0].id),target=accounts.find(a=>a.entity_id===entities[1].id);
|
||||
await bank.query('UPDATE pb_accounts SET balance_minor=3000000 WHERE id=?',[source.id]);
|
||||
const payments=new PostbankPayments(bank,authority,{clock:f.now,resolveUser:async id=>Object.values(f.people).find(p=>p.id===id)});
|
||||
const worker=createRebellionRewards(f.db,bank,{sourceAccount:source.id,sourceOwnerId:fund.id,authority,payments});
|
||||
const quest=await f.service.declare(f.winner,f.input),evidence=await f.capture(quest);await f.service.applyCapture(f.producer,evidence);
|
||||
return {...f,bank,worker,payments,source,target,quest,revoke:()=>allowed=false,close:()=>{f.db.close();bank.close();}};
|
||||
}
|
||||
test('verified rebellion reward reserves existing funds, posts balanced bank legs once and recovers a lost job acknowledgement',async()=>{
|
||||
const f=await setup();try{
|
||||
assert.equal((await f.worker.drain()).results[0].state,'submitted');
|
||||
assert.equal((await f.bank.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,2500000);
|
||||
// Simulate loss of the central acknowledgement after the bank accepted it.
|
||||
await f.db.query("UPDATE jarvis_pol_quest_reward_jobs SET state='awaiting_funding' WHERE key_id=?",[f.quest.keyId]);await f.worker.drain();
|
||||
assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
|
||||
assert.equal((await f.payments.processQueue()).posted,1);assert.equal((await f.worker.drain()).results[0].state,'paid');
|
||||
assert.deepEqual({...await f.bank.first('SELECT COUNT(*) n,SUM(amount_minor) net FROM pb_entries WHERE order_id=?',[f.quest.keyId])},{n:2,net:0});
|
||||
assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,2500000);
|
||||
assert.equal((await f.worker.drain()).attempted,0);
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('missing funding configuration or expired debit authority cannot mint a reward',async()=>{
|
||||
const f=await setup();try{
|
||||
assert.equal((await createRebellionRewards(f.db,f.bank).drain()).state,'awaiting-funding-configuration');f.revoke();
|
||||
assert.equal((await f.worker.drain()).results[0].state,'awaiting-funding-or-review');
|
||||
assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
|
||||
assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);
|
||||
}finally{f.close();}
|
||||
});
|
||||
Loading…
Reference in a new issue

Staff