forked from unimatrix/web
107 lines
16 KiB
JavaScript
107 lines
16 KiB
JavaScript
import {createHash} from 'node:crypto';
|
|
import {boardReadStore} from './board-deed-source.mjs';
|
|
import {officeAuthority} from './political-decisions.mjs';
|
|
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
|
import {validUuid} from './game-link.mjs';
|
|
import {polProgressionStore} from './progression-pol.mjs';
|
|
import {readActiveXPSeason} from './progression-xp-store.mjs';
|
|
import {levelForXP} from './progression-definitions.mjs';
|
|
import {identity} from './auth.mjs';
|
|
import {accessFor} from './permissions.mjs';
|
|
import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs';
|
|
import {decisionBallotOutcome} from '../control-panel/public/decision-ballot-policy.mjs';
|
|
import {FAITH_BALLOT_MS,FAITH_LAW_MS,HOUSE_FAITH_DECISIONS,houseFaithDecision} from '../control-panel/public/house-faith-policy.mjs';
|
|
export const HOUSE_FAITH_SCHEMA=[
|
|
`CREATE TABLE IF NOT EXISTS jarvis_house_faith_locks(office_key VARCHAR(32) PRIMARY KEY,last_proposed_at BIGINT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
`CREATE TABLE IF NOT EXISTS jarvis_house_faith_ballots(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,decision_id VARCHAR(24) NOT NULL,office_key VARCHAR(32) NOT NULL,world VARCHAR(32) NOT NULL,faith_key VARCHAR(32) NOT NULL,prohibited INT NOT NULL,actor_id CHAR(36) NOT NULL,term_id CHAR(36) NOT NULL,input_hash CHAR(64) NOT NULL,electorate TEXT NOT NULL,opens_at BIGINT NOT NULL,closes_at BIGINT NOT NULL,mandate_expires_at BIGINT NOT NULL,state VARCHAR(24) NOT NULL,result VARCHAR(24),expires_at BIGINT,tally_json TEXT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
`CREATE TABLE IF NOT EXISTS jarvis_house_faith_votes(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,ballot_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,actor_id CHAR(36) NOT NULL,choice VARCHAR(8) NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY faith_ballot_player(ballot_id,minecraft_uuid)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
`CREATE TABLE IF NOT EXISTS jarvis_house_faith_rules(world VARCHAR(32) NOT NULL,faith_key VARCHAR(32) NOT NULL,request_id CHAR(36) NOT NULL,PRIMARY KEY(world,faith_key)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
|
];
|
|
const fail=(m,status=409)=>{throw Object.assign(Error(m),{status});};
|
|
const digest=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
|
|
const exact=(v,names)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join(',')===names;
|
|
const faiths=['veiled_concord','muad_dib'];
|
|
export async function initializeHouseFaith(db){for(const sql of HOUSE_FAITH_SCHEMA)await db.query(sql);for(const d of HOUSE_FAITH_DECISIONS)await db.query('INSERT INTO jarvis_house_faith_locks(office_key) VALUES(?) ON DUPLICATE KEY UPDATE office_key=VALUES(office_key)',[d.office]);db.houseFaithEnabled=true;}
|
|
async function electors(db,office,{lock=false}={}){
|
|
const rows=await db.query("SELECT a.id userId,l.minecraft_uuid playerUuid FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id JOIN site_character_choices c ON c.minecraft_uuid=l.minecraft_uuid WHERE c.faction=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial') AND NOT EXISTS(SELECT 1 FROM site_memorials m WHERE m.user_id=a.id) AND (SELECT COUNT(*) FROM site_game_links x WHERE LOWER(x.minecraft_uuid)=LOWER(l.minecraft_uuid))=1 ORDER BY a.id LIMIT 5001"+(lock?' FOR SHARE':''),[office]);
|
|
if(rows.length>5000)fail('The House electorate requires review.',503);
|
|
if(rows.some(r=>!validUuid(r.userId)||!validUuid(r.playerUuid))||new Set(rows.map(r=>r.playerUuid.toLowerCase())).size!==rows.length||new Set(rows.map(r=>r.userId)).size!==rows.length)fail('The House electorate requires review.',409);
|
|
return rows.map(r=>({userId:r.userId,playerUuid:r.playerUuid.toLowerCase()}));
|
|
}
|
|
// A referendum is distinct from a candidate election: one verified personal
|
|
// identity, no vote allocations consumed and no change to the election clock.
|
|
export function faithBallotOutcome(seats,votes){
|
|
let tally;try{tally=decisionBallotOutcome(['yes','no'],seats,votes.map(v=>({identity:v.minecraft_uuid,choice:v.choice})));}catch{fail('Faith ballot records require review.');}
|
|
return{participation:tally.participation,quorum:tally.quorum,yes:tally.counts.yes,no:tally.counts.no,result:tally.result==='yes'?'adopted':tally.result==='no'?'not_adopted':tally.result};
|
|
}
|
|
const proofSQL="SELECT b.*,k.id verified_key FROM jarvis_house_faith_ballots b LEFT JOIN organisation_keys k ON k.id=b.key_id AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:house-faith-ballot:',b.request_id) AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at>?)";
|
|
function validBallot(row){
|
|
const d=houseFaithDecision(row?.decision_id);return !!row?.verified_key&&!!d&&d.world===row.world&&d.office===row.office_key&&faiths.includes(row.faith_key)&&[0,1].includes(Number(row.prohibited))&&Number.isSafeInteger(Number(row.opens_at))&&Number(row.closes_at)===Number(row.opens_at)+FAITH_BALLOT_MS&&Number(row.mandate_expires_at)>Number(row.closes_at)&&row.input_hash===digest([row.actor_id,d.id,row.faith_key,!!Number(row.prohibited)]);
|
|
}
|
|
export async function missionaryFaithOutlawed(tx,clanId,faith,now){
|
|
if(!faiths.includes(faith))fail('Unknown faith.',400);
|
|
const clan=(await tx.query('SELECT home_world FROM site_clans WHERE id=? AND active=1 FOR SHARE',[clanId]))[0],world=tradeWorld(clan?.home_world);if(!world)return false;
|
|
const row=(await tx.query(proofSQL+' JOIN jarvis_house_faith_rules r ON r.request_id=b.request_id WHERE r.world=? AND r.faith_key=? FOR SHARE',[STAFF_OFFICE_ACCOUNT_ID,now,world,faith]))[0];
|
|
if(!validBallot(row)||row.state!=='closed'||row.result!=='adopted'||Number(row.prohibited)!==1||!Number.isSafeInteger(Number(row.expires_at))||Number(row.expires_at)<=now||Number(row.expires_at)>Math.min(Number(row.closes_at)+FAITH_LAW_MS,Number(row.mandate_expires_at))||row.world!==world||row.faith_key!==faith)return false;
|
|
const d=houseFaithDecision(row.decision_id);if(!d||d.world!==world||d.office!==row.office_key)return false;
|
|
const holder=await officeAuthority(tx,d,{id:row.actor_id},now);return holder?.termId===row.term_id;
|
|
}
|
|
export function createHouseFaithLaws(base,keys,{clock=Date.now}={}){
|
|
if(typeof base?.query!=='function')return{read:async()=>fail('House faith records unavailable.',503),propose:async()=>fail('House faith records unavailable.',503),vote:async()=>fail('House faith records unavailable.',503),reconcile:async()=>fail('House faith records unavailable.',503)};
|
|
const db=boardReadStore(base,base);
|
|
async function authority(tx,d,actor,now,lock=false){const holder=await officeAuthority(tx,d,actor,now,lock);if(!holder)return null;const term=await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[holder.termId]);return term?{...holder,expiresAt:Number(term.expires_at)}:null;}
|
|
async function level(tx,actor,now){const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,now),xp=await pol.first('SELECT effective_xp FROM jarvis_progression_accounts WHERE account_id=?',[actor.id]);return levelForXP(Number(xp?.effective_xp||0),{base:Number(season.curve_base),cap:Number(season.level_cap)||null});}
|
|
async function read(actor,id){
|
|
const d=houseFaithDecision(id);if(!d)fail('Unknown House decision.',400);const now=clock(),holder=await authority(db,d,actor,now),row=await db.first('SELECT last_proposed_at FROM jarvis_house_faith_locks WHERE office_key=?',[d.office]),cooldownUntil=row?.last_proposed_at==null?null:Number(row.last_proposed_at)+FAITH_LAW_MS,current=await electors(db,d.office),me=current.find(p=>p.userId===actor.id),levelNow=holder?await level(db,actor,now):0;
|
|
const ballots=await db.query(proofSQL+' WHERE b.office_key=? ORDER BY b.opens_at DESC,b.request_id DESC LIMIT 30',[STAFF_OFFICE_ACCOUNT_ID,now,d.office]),views=[];
|
|
for(const b of ballots){const electorate=JSON.parse(b.electorate),votes=await db.query('SELECT v.minecraft_uuid,v.choice FROM jarvis_house_faith_votes v JOIN organisation_keys k ON k.id=v.key_id AND k.account_id=? AND k.key_type=\'entity-state\' AND k.scope_id=CONCAT(\'state:house-faith-vote:\',v.request_id) AND k.revoked_at IS NULL WHERE v.ballot_id=?',[STAFF_OFFICE_ACCOUNT_ID,b.request_id]),ownVote=me?votes.find(v=>v.minecraft_uuid===me.playerUuid)?.choice||null:null;
|
|
views.push({id:b.request_id,faith:b.faith_key,prohibited:!!b.prohibited,opensAt:Number(b.opens_at),closesAt:Number(b.closes_at),expiresAt:b.expires_at==null?null:Number(b.expires_at),state:b.state,result:b.result,electorate:electorate.length,ownVote,canVote:!!b.verified_key&&!!me&&!ownVote&&b.state==='open'&&now<Number(b.closes_at)&&electorate.some(e=>e.userId===me.userId&&e.playerUuid===me.playerUuid),tally:b.state==='closed'&&b.tally_json?JSON.parse(b.tally_json):null});
|
|
}
|
|
return{...d,canManage:!!holder,levelNow,cooldownUntil,canPropose:!!keys&&!!holder&&levelNow>=d.level&&holder.expiresAt>now+FAITH_BALLOT_MS&&(!cooldownUntil||now>=cooldownUntil)&¤t.length>0,ballots:views};
|
|
}
|
|
async function propose(actor,input){
|
|
const d=houseFaithDecision(input?.decisionId);if(!d||!exact(input,'confirmed,decisionId,faith,prohibited,requestId')||!validUuid(input.requestId)||!faiths.includes(input.faith)||typeof input.prohibited!=='boolean'||input.confirmed!==true)fail('Review and confirm a House faith referendum.',400);if(!keys)fail('Key service unavailable.',503);
|
|
input={...input,requestId:input.requestId.toLowerCase()};
|
|
const hash=digest([actor.id,d.id,input.faith,input.prohibited]);let receipt;
|
|
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:house-faith-ballot:'+input.requestId,authorize:async(raw,{keyId})=>{
|
|
const tx=boardReadStore(raw,db),now=clock(),holder=await authority(tx,d,actor,now,true);if(!holder)fail('The current elected House holder is required.',403);
|
|
const lock=await tx.first('SELECT * FROM jarvis_house_faith_locks WHERE office_key=? FOR UPDATE',[d.office]);if(!lock)fail('House faith policy unavailable.',503);
|
|
const prior=await tx.first('SELECT * FROM jarvis_house_faith_ballots WHERE request_id=?',[input.requestId]);if(prior){if(prior.actor_id!==actor.id||prior.input_hash!==hash)fail('Referendum reference already used.');receipt={id:prior.request_id,replayed:true};return;}
|
|
if(lock.last_proposed_at!=null&&now<Number(lock.last_proposed_at)+FAITH_LAW_MS)fail('This House decision is on its seven-day cooldown.');
|
|
if(holder.expiresAt<=now+FAITH_BALLOT_MS)fail('This mandate ends before voting would close.');if(await level(tx,actor,now)<d.level)fail('Reputation level '+d.level+' required.',403);
|
|
const electorate=await electors(tx,d.office,{lock:true});if(!electorate.length)fail('No verified House citizens are available.');
|
|
await tx.query("INSERT INTO jarvis_house_faith_ballots(request_id,key_id,decision_id,office_key,world,faith_key,prohibited,actor_id,term_id,input_hash,electorate,opens_at,closes_at,mandate_expires_at,state) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,'open')",[input.requestId,keyId,d.id,d.office,d.world,input.faith,input.prohibited?1:0,actor.id,holder.termId,hash,JSON.stringify(electorate),now,now+FAITH_BALLOT_MS,holder.expiresAt]);
|
|
await tx.query('UPDATE jarvis_house_faith_locks SET last_proposed_at=? WHERE office_key=?',[now,d.office]);receipt={id:input.requestId,replayed:false};
|
|
}});return receipt;
|
|
}
|
|
async function vote(actor,input){
|
|
if(!exact(input,'ballotId,choice,confirmed,requestId')||!validUuid(input.requestId)||!validUuid(input.ballotId)||!['yes','no'].includes(input.choice)||input.confirmed!==true)fail('Confirm one referendum vote.',400);if(!keys)fail('Key service unavailable.',503);
|
|
input={...input,requestId:input.requestId.toLowerCase(),ballotId:input.ballotId.toLowerCase()};
|
|
const hash=digest([actor.id,input.ballotId,input.choice]);let receipt;
|
|
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:house-faith-vote:'+input.requestId,authorize:async(raw,{keyId})=>{
|
|
const tx=boardReadStore(raw,db),now=clock(),b=await tx.first(proofSQL+' WHERE b.request_id=? FOR UPDATE',[STAFF_OFFICE_ACCOUNT_ID,now,input.ballotId]);if(!validBallot(b))fail('Verified referendum not found.',404);
|
|
const me=(await electors(tx,b.office_key,{lock:true})).find(p=>p.userId===actor.id);if(!me||!JSON.parse(b.electorate).some(p=>p.userId===me.userId&&p.playerUuid===me.playerUuid))fail('A current recorded House citizen is required.',403);
|
|
const prior=await tx.first('SELECT * FROM jarvis_house_faith_votes WHERE request_id=?',[input.requestId]);if(prior){if(prior.input_hash!==hash||prior.actor_id!==actor.id)fail('Vote reference already used.');receipt={ok:true,replayed:true};return;}
|
|
if(b.state!=='open'||now>=Number(b.closes_at))fail('Referendum voting has closed.');
|
|
if(await tx.first('SELECT request_id FROM jarvis_house_faith_votes WHERE ballot_id=? AND minecraft_uuid=?',[b.request_id,me.playerUuid]))fail('This personal identity has already voted.');
|
|
await tx.query('INSERT INTO jarvis_house_faith_votes(request_id,key_id,ballot_id,minecraft_uuid,actor_id,choice,input_hash,created_at) VALUES(?,?,?,?,?,?,?,?)',[input.requestId,keyId,b.request_id,me.playerUuid,actor.id,input.choice,hash,now]);receipt={ok:true,replayed:false};
|
|
}});return receipt;
|
|
}
|
|
async function reconcile(){
|
|
const due=await db.query("SELECT request_id FROM jarvis_house_faith_ballots WHERE state='open' AND closes_at<=? ORDER BY closes_at,request_id LIMIT 100",[clock()]);
|
|
for(const row of due)await base.transaction(async raw=>{const tx=boardReadStore(raw,db),now=clock(),b=await tx.first(proofSQL+' WHERE b.request_id=? FOR UPDATE',[STAFF_OFFICE_ACCOUNT_ID,now,row.request_id]);if(!b||b.state!=='open')return;
|
|
const d=houseFaithDecision(b.decision_id),holder=d&&await authority(tx,d,{id:b.actor_id},now,true),votes=await tx.query("SELECT v.minecraft_uuid,v.choice FROM jarvis_house_faith_votes v JOIN organisation_keys k ON k.id=v.key_id AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:house-faith-vote:',v.request_id) AND k.revoked_at IS NULL WHERE v.ballot_id=?",[STAFF_OFFICE_ACCOUNT_ID,b.request_id]);
|
|
const outcome=faithBallotOutcome(JSON.parse(b.electorate).length,votes),result=!validBallot(b)||holder?.termId!==b.term_id?'mandate_ended':outcome.result,expiresAt=result==='adopted'?Math.min(Number(b.closes_at)+FAITH_LAW_MS,Number(b.mandate_expires_at),holder.expiresAt):null;
|
|
await tx.query("UPDATE jarvis_house_faith_ballots SET state='closed',result=?,expires_at=?,tally_json=? WHERE request_id=?",[result,expiresAt,JSON.stringify(outcome),b.request_id]);
|
|
if(result==='adopted')await tx.query('INSERT INTO jarvis_house_faith_rules(world,faith_key,request_id) VALUES(?,?,?) ON DUPLICATE KEY UPDATE request_id=VALUES(request_id)',[b.world,b.faith_key,b.request_id]);
|
|
});return{closed:due.length};
|
|
}
|
|
return{read,propose,vote,reconcile};
|
|
}
|
|
export function createHouseFaithAPI(db,keys,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=a=>accessFor(db,a),service=createHouseFaithLaws(db,keys)}={}){
|
|
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
|
return async request=>{try{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:'Player access required.'},403);const u=new URL(request.url);
|
|
if(request.method==='GET'){if(u.searchParams.size!==1||u.searchParams.getAll('decisionId').length!==1)return reply({message:'Choose one House decision.'},400);return reply(await service.read(actor,u.searchParams.get('decisionId')));}
|
|
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);if(u.search||request.headers.get('origin')!==origin)return reply({message:'Origin or query rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);const raw=await request.text();if(raw.length>2048)return reply({message:'Request too large.'},413);let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid referendum request.'},400);}const {action,...input}=body||{};if(!['propose','vote'].includes(action))return reply({message:'Unknown referendum action.'},400);return reply(await service[action](actor,input));
|
|
}catch(e){return reply({message:e.status?e.message:'Referendum was not confirmed. Refresh before retrying.'},e.status||503);}};
|
|
}
|

Staff