forked from unimatrix/web
60 lines
12 KiB
JavaScript
60 lines
12 KiB
JavaScript
import {createPaidPaxDossier,PAX_PEACE} from './imperial-pax.mjs';
|
|
import {createHash} from 'node:crypto';
|
|
import {boardReadStore} from './board-deed-source.mjs';
|
|
import {officeAuthority} from './political-decisions.mjs';
|
|
import {PUBLIC_OFFICES} from './public-government.mjs';
|
|
import {currentOfficeController} from './entity-relations.mjs';
|
|
import {readClanDeed} from './clan-deeds.mjs';
|
|
import {politicalDecision} from '../control-panel/public/political-decision-policy.mjs';
|
|
import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs';
|
|
import {decisionBallotOutcome} from '../control-panel/public/decision-ballot-policy.mjs';
|
|
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
|
import {validUuid} from './game-link.mjs';
|
|
import {identity} from './auth.mjs';
|
|
export const POLITICAL_CONSULTATION_SCHEMA=[
|
|
`CREATE TABLE IF NOT EXISTS jarvis_political_consultations(request_id CHAR(36) PRIMARY KEY,closes_at BIGINT NOT NULL,closed_at BIGINT,tally_json TEXT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
`CREATE TABLE IF NOT EXISTS jarvis_political_consultation_votes(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,ballot_id CHAR(36) NOT NULL,seat_key VARCHAR(64) 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 political_ballot_seat(ballot_id,seat_key)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
|
];
|
|
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});},hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
|
|
export function createPoliticalConsultations(raw,keys,{clock=Date.now}={}){
|
|
if(typeof raw?.query!=='function')return{read:async()=>fail('Consultations unavailable.',503),create:async()=>fail('Consultations unavailable.',503),vote:async()=>fail('Consultations unavailable.',503),reconcile:async()=>({closed:0})};
|
|
const db=boardReadStore(raw,raw);
|
|
async function seat(tx,d,s,actor,now,lock=false){
|
|
if(d.electorate==='houses'){
|
|
if(s.kind!=='office'||!PUBLIC_OFFICES.some(o=>o.key===s.id&&o.kind==='house'))return false;const holder=await officeAuthority(tx,{office:s.id},actor,now,lock);return holder?.termId===s.termId;
|
|
}
|
|
if(s.kind!=='clan'||!validUuid(s.id))return false;if(lock)await tx.first('SELECT id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[s.id]);
|
|
try{const deed=await readClanDeed(tx,s.id);return deed.owner?.id===actor.id&&tradeWorld(deed.clan.home_world)===d.ballotWorld;}catch{return false;}
|
|
}
|
|
async function electorate(tx,d,now){
|
|
const seats=[];
|
|
if(d.electorate==='houses'){for(const office of PUBLIC_OFFICES.filter(o=>o.kind==='house')){const h=await currentOfficeController(tx,office.key,now);if(h&&await officeAuthority(tx,{office:office.key},{id:h.userId},now,true))seats.push({kind:'office',id:office.key,name:office.scope,termId:h.termId});}}
|
|
else{const clans=await tx.query('SELECT id,name,home_world FROM site_clans WHERE active=1 ORDER BY id LIMIT 1001 FOR SHARE');if(clans.length>1000)fail('Narrow the consultation registry.',503);for(const c of clans)if(tradeWorld(c.home_world)===d.ballotWorld){try{const deed=await readClanDeed(tx,c.id);if(deed.owner)seats.push({kind:'clan',id:c.id,name:c.name});}catch(cause){throw Object.assign(Error('A native clan deed requires review.',{cause}),{status:409});}}}
|
|
if(!seats.length)fail('No eligible institutional seats are currently registered.');return seats;
|
|
}
|
|
async function create(tx,{d,holder,now,requestId,payload}){
|
|
tx=boardReadStore(tx,db);
|
|
const term=await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[holder.termId]);if(Number(term?.expires_at||0)<=now+d.ballotMs+(d.pax?PAX_PEACE:0))fail('This mandate must cover the complete consultation.');
|
|
const seats=await electorate(tx,d,now);if(Buffer.byteLength(JSON.stringify(seats),'utf8')>48000)fail('The institutional electorate exceeds the safe consultation size.',413);await tx.query('INSERT INTO jarvis_political_consultations(request_id,closes_at) VALUES(?,?)',[requestId,now+d.ballotMs]);const paxDossierId=d.pax?await createPaidPaxDossier(tx,{requestId,actorId:holder.userId,title:payload.title,terms:payload.terms,now}):null;return{closesAt:now+d.ballotMs,seats,...(paxDossierId?{paxDossierId}:{})};
|
|
}
|
|
async function verified(tx,row,now,lock=false){
|
|
const d=politicalDecision(row?.decision_id);if(d?.kind!=='ballot')return null;
|
|
const key=await tx.first("SELECT id FROM organisation_keys WHERE id=? AND account_id=? AND key_type='entity-state' AND scope_id=? AND revoked_at IS NULL"+(lock?' FOR SHARE':''),[row.key_id,STAFF_OFFICE_ACCOUNT_ID,'state:political-decision:'+row.request_id]);if(!key)return null;
|
|
const receipt=JSON.parse(row.receipt_json),payload=JSON.parse(row.payload_json),ballot=receipt.ballot;if(!ballot||ballot.closesAt!==Number(row.created_at)+d.ballotMs||!Array.isArray(ballot.seats)||!ballot.seats.length||ballot.seats.length>1000||new Set(ballot.seats.map(s=>s.kind+':'+s.id)).size!==ballot.seats.length)return null;
|
|
const holder=await officeAuthority(tx,d,{id:row.actor_id},now,lock);return{d,payload,ballot,mandate:holder?.termId===row.term_id};
|
|
}
|
|
async function votes(tx,id){return tx.query("SELECT v.*,k.id verified_key FROM jarvis_political_consultation_votes v LEFT 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:political-ballot-vote:',v.request_id) AND k.revoked_at IS NULL WHERE v.ballot_id=? ORDER BY v.seat_key",[STAFF_OFFICE_ACCOUNT_ID,id]);}
|
|
function outcome(v,rows,id){const known=new Set(v.ballot.seats.map(s=>s.kind+':'+s.id));if(rows.some(r=>!known.has(r.seat_key)||Number(r.created_at)>=v.ballot.closesAt||r.input_hash!==hash([r.actor_id,id,r.seat_key,r.choice])))fail('Consultation vote records require review.');return decisionBallotOutcome(['yes','no'],known.size,rows.map(r=>({identity:r.seat_key,choice:r.choice})));}
|
|
async function read(actor){const rows=await db.query("SELECT p.*,c.closed_at,c.tally_json FROM jarvis_political_consultations c JOIN jarvis_political_decisions p ON p.request_id=c.request_id ORDER BY p.created_at DESC,p.request_id DESC LIMIT 100"),ballots=[],now=clock(),owned=new Set((await db.query('SELECT id FROM site_clans WHERE active=1 AND owner_id=?',[actor.id])).map(c=>c.id)),officeSeats=new Set(),seatCache=new Map();for(const o of PUBLIC_OFFICES.filter(o=>o.kind==='house'))if((await currentOfficeController(db,o.key,now))?.userId===actor.id)officeSeats.add(o.key);for(const row of rows){const v=await verified(db,row,now);if(!v)continue;const recorded=await votes(db,row.request_id),cast=recorded.filter(r=>r.verified_key),own=[];for(const s of v.ballot.seats){if(s.kind==='clan'?!owned.has(s.id):!officeSeats.has(s.id))continue;const cacheKey=[s.kind,s.id,s.termId||'',v.d.ballotWorld||''].join(':');if(!seatCache.has(cacheKey))seatCache.set(cacheKey,await seat(db,v.d,s,actor,now));if(seatCache.get(cacheKey))own.push({id:s.kind+':'+s.id,name:s.name,vote:(recorded.find(r=>r.seat_key===s.kind+':'+s.id)?(cast.find(r=>r.seat_key===s.kind+':'+s.id)?.choice||'recorded-invalid'):null)});}const state=row.closed_at!=null?'closed':!v.mandate?'mandate-ended':now>=v.ballot.closesAt?'awaiting-result':'open';ballots.push({id:row.request_id,decisionId:v.d.id,title:v.payload.title,terms:v.payload.terms,closesAt:v.ballot.closesAt,state,seats:v.ballot.seats.length,participation:cast.length,ownSeats:own,canVote:state==='open'&&own.some(s=>!s.vote),tally:row.closed_at!=null?JSON.parse(row.tally_json):null,reference:row.key_id});}return{ballots};}
|
|
async function vote(actor,input){
|
|
if(!input||Object.keys(input).sort().join(',')!=='ballotId,choice,confirmed,requestId,seatKey'||input.confirmed!==true||!validUuid(input.ballotId)||!validUuid(input.requestId)||typeof input.seatKey!=='string'||input.seatKey.length>64||!['yes','no'].includes(input.choice))fail('Review and confirm your institutional vote.',400);if(!keys||!raw.transaction)fail('Consultations unavailable.',503);
|
|
return raw.transaction(async original=>{const tx=boardReadStore(original,db),row=await tx.first('SELECT p.*,c.closed_at FROM jarvis_political_consultations c JOIN jarvis_political_decisions p ON p.request_id=c.request_id WHERE c.request_id=? FOR UPDATE',[input.ballotId]);if(!row)fail('Consultation not found.',404);
|
|
const digest=hash([actor.id,input.ballotId,input.seatKey,input.choice]),prior=await tx.first('SELECT * FROM jarvis_political_consultation_votes WHERE request_id=? OR (ballot_id=? AND seat_key=?) FOR UPDATE',[input.requestId,input.ballotId,input.seatKey]);if(prior){if(prior.request_id!==input.requestId||prior.input_hash!==digest||prior.actor_id!==actor.id)fail('This institutional seat already voted.');return{ok:true,replayed:true,reference:prior.key_id};}
|
|
const now=clock(),v=await verified(tx,row,now,true),s=v?.ballot.seats.find(s=>s.kind+':'+s.id===input.seatKey);if(!v||!v.mandate||row.closed_at!=null||now>=v.ballot.closesAt)fail('This consultation is no longer open.');if(!s||!await seat(tx,v.d,s,actor,now,true))fail('The current independent institutional deed is required.',403);
|
|
let reference;await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:political-ballot-vote:'+input.requestId,transactionStore:tx,authorize:async(_,{keyId})=>{reference=keyId;await tx.query('INSERT INTO jarvis_political_consultation_votes VALUES(?,?,?,?,?,?,?,?)',[input.requestId,keyId,input.ballotId,input.seatKey,actor.id,input.choice,digest,now]);}});return{ok:true,replayed:false,reference};
|
|
});
|
|
}
|
|
async function reconcile(){const rows=await db.query('SELECT c.request_id FROM jarvis_political_consultations c JOIN jarvis_political_decisions p ON p.request_id=c.request_id WHERE c.closed_at IS NULL AND c.closes_at<=? ORDER BY c.closes_at,p.request_id LIMIT 100',[clock()]);let closed=0;for(const candidate of rows)await raw.transaction(async original=>{const tx=boardReadStore(original,db),row=await tx.first('SELECT p.*,c.closed_at FROM jarvis_political_consultations c JOIN jarvis_political_decisions p ON p.request_id=c.request_id WHERE c.request_id=? FOR UPDATE',[candidate.request_id]),now=clock();if(!row||row.closed_at!=null)return;const policy=politicalDecision(row.decision_id),atDeadline=policy?.kind==='ballot'?Math.min(now,Number(row.created_at)+policy.ballotMs-1):now,v=await verified(tx,row,atDeadline,true);if(v?.mandate&&now<v.ballot.closesAt)return;const tally=v?.mandate?outcome(v,(await votes(tx,row.request_id)).filter(r=>r.verified_key),row.request_id):{result:'cancelled',reason:'issuing-mandate-ended-or-revoked'};await tx.query('UPDATE jarvis_political_consultations SET closed_at=?,tally_json=? WHERE request_id=?',[now,JSON.stringify(tally),row.request_id]);closed++;});return{closed};}
|
|
return{create,read,vote,reconcile};
|
|
}
|
|
export function createPoliticalConsultationAPI(db,service,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db)}={}){return async request=>{const respond=(value,status=200)=>Response.json(value,{status,headers:{'Cache-Control':'private, no-store'}});try{if(!['GET','POST'].includes(request.method))return respond({message:'Method not allowed.'},405);const actor=await authenticate(request);if(!actor)return respond({message:'Sign in first.'},401);if(new URL(request.url).search)return respond({message:'Unexpected consultation fields.'},400);if(request.method==='GET')return respond(await service.read(actor));if(request.headers.get('origin')!==origin)return respond({message:'Origin rejected.'},403);const body=await request.text();if(body.length>4096)return respond({message:'Vote too large.'},413);let input;try{input=JSON.parse(body);}catch{return respond({message:'Invalid vote.'},400);}return respond(await service.vote(actor,input));}catch(error){return respond({message:error.status?error.message:'Consultations are temporarily unavailable.'},error.status||503);}};}
|

Staff