import {randomUUID} from 'node:crypto'; import {currentOfficeController} from './entity-relations.mjs'; import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; import {electionDates,ELECTION_RULES} from '../control-panel/public/election-rules.mjs'; import {identity} from './auth.mjs'; export const RALLY_HOUSES=Object.freeze(['atreides','harkonnen','corrino','ordos','fremen']); export const RALLY_SCHEMA=[ `CREATE TABLE IF NOT EXISTS political_election_rallies(id CHAR(36) PRIMARY KEY,term_id CHAR(36) NOT NULL,reason TEXT NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,election_start BIGINT NULL,KEY rally_term(term_id,state)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, `CREATE TABLE IF NOT EXISTS political_election_rally_votes(request_id CHAR(36) PRIMARY KEY,rally_id CHAR(36) NOT NULL,house VARCHAR(32) NOT NULL,actor_id CHAR(36) NOT NULL,term_id CHAR(36) NOT NULL,choice VARCHAR(8) NOT NULL,reason TEXT NOT NULL,key_id CHAR(36) NOT NULL UNIQUE,created_at BIGINT NOT NULL,UNIQUE KEY rally_house(rally_id,house),UNIQUE KEY rally_actor(rally_id,actor_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4` ]; const HOUR=3600000,uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); const first=async(db,sql,args=[])=>db.first?db.first(sql,args):((await db.query(sql,args))[0]||null); const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});}; export async function initializeElectionRallies(db){for(const sql of RALLY_SCHEMA)await db.query(sql);db.electionRalliesEnabled=true;} export function forcedElectionStart(now){const next=Date.parse(electionDates('imperial',now,1)[0]),start=Math.ceil((now+24*HOUR)/60000)*60000;return start+6*HOUR102*HOUR;} export function rallyOutcome(votes){const choices=new Map();for(const vote of votes){if(!RALLY_HOUSES.includes(vote.house)||!['support','oppose'].includes(vote.choice)||choices.has(vote.house))continue;choices.set(vote.house,vote.choice);}const support=[...choices.values()].filter(c=>c==='support').length,oppose=[...choices.values()].filter(c=>c==='oppose').length;return {support,oppose,state:oppose>=2?'denied':support>=2?'scheduled':'open'};} export async function approvedForcedStart(db,kind,start){if(kind!=='imperial'||!db.electionRalliesEnabled)return false;return !!await first(db,"SELECT id FROM political_election_rallies WHERE state='scheduled' AND election_start=?",[Number(start)]);} export async function forcedElectionCalendar(db,now=Date.now()){ if(!db.electionRalliesEnabled)return null; const row=await first(db,"SELECT election_start,term_id FROM political_election_rallies WHERE state='scheduled' AND election_start IS NOT NULL ORDER BY election_start DESC LIMIT 1");if(!row)return null; const start=Number(row.election_start),firstRegular=Date.parse(ELECTION_RULES.imperial.first),period=ELECTION_RULES.imperial.weeks*7*86400000,nextRegular=firstRegular+(Math.floor((start-firstRegular)/period)+1)*period; return now?) ORDER BY created_at DESC,id DESC LIMIT 1",[term,now]):null;const votes=active?await signedVotes(db,active.id,now):[];return {seat:seat?.house||null,canStart:!!(seat&&term&&!active&&canOpenRally(now)&&!await forcedElectionCalendar(db,now)),rally:active?{id:active.id,reason:active.reason,state:active.state,expiresAt:Number(active.expires_at),electionStart:active.election_start==null?null:Number(active.election_start),votes:votes.map(v=>({house:v.house,choice:v.choice,reason:v.reason})),canVote:!!(seat&&active.state==='open'&&!votes.some(v=>v.house===seat.house||v.actor_id===actor.id))}:null};} async function vote(actor,input){if(!actor?.id||!input||!uuid(input.requestId)||!['start','support','oppose'].includes(input.action)||input.confirmed!==true||(input.action!=='start'&&!uuid(input.rallyId)))fail('Confirm a valid rally action.',400);const reason=typeof input.reason==='string'?input.reason.trim():'';if((input.action==='start'||input.action==='oppose')&&(reason.length<10||reason.length>2000)||reason.length>2000)fail('Supply a reason between 10 and 2000 characters.',400);if(!keys)fail('Rally key authority unavailable.',503); return db.transaction(async tx=>{const now=clock(),term=await current(tx,now);if(!term)fail('No current Imperial mandate.');await tx.first('SELECT id FROM political_office_terms WHERE id=? FOR UPDATE',[term]);if(await current(tx,now)!==term)fail('Imperial mandate changed.');const seat=await holder(tx,actor,now);if(!seat)fail('A current native House leader is required.',403);await tx.first('SELECT id FROM political_office_terms WHERE id=? FOR UPDATE',[seat.termId]);const live=await holder(tx,actor,now);if(live?.termId!==seat.termId)fail('House mandate changed.',403); const prior=await tx.first('SELECT * FROM political_election_rally_votes WHERE request_id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==actor.id||prior.choice!==(input.action==='start'?'support':input.action)||prior.reason!==reason||input.action!=='start'&&prior.rally_id!==input.rallyId)fail('Rally reference already used.');return {replayed:true,rallyId:prior.rally_id};} await tx.query("UPDATE political_election_rallies SET state='expired' WHERE term_id=? AND state='open' AND expires_at<=?",[term,now]);let rally=await tx.first("SELECT * FROM political_election_rallies WHERE term_id=? AND state IN ('open','scheduled') ORDER BY created_at DESC LIMIT 1 FOR UPDATE",[term]); if(input.action==='start'){if(rally||!canOpenRally(now)||await forcedElectionCalendar({query:tx.query.bind(tx),electionRalliesEnabled:true},now))fail('A rally is already pending or the regular election is too close.');const id=randomUUID();const expires=now+72*HOUR;await tx.query("INSERT INTO political_election_rallies(id,term_id,reason,state,created_at,expires_at) VALUES(?,?,?,'open',?,?)",[id,term,reason,now,expires]);rally={id,state:'open',expires_at:expires};} if(!rally||rally.state!=='open'||(input.action!=='start'&&rally.id!==input.rallyId)||Number(rally.expires_at)<=now)fail('No open rally is available.');if(await tx.first('SELECT request_id FROM political_election_rally_votes WHERE rally_id=? AND (house=? OR actor_id=?) FOR UPDATE',[rally.id,seat.house,actor.id]))fail('This House has already voted.'); await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:imperial-rally-vote:'+input.requestId,transactionStore:tx,authorize:async(_,{keyId})=>{await tx.query('INSERT INTO political_election_rally_votes(request_id,rally_id,house,actor_id,term_id,choice,reason,key_id,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[input.requestId,rally.id,seat.house,actor.id,seat.termId,input.action==='start'?'support':input.action,reason,keyId,now]);}}); const tally=rallyOutcome(await signedVotes(tx,rally.id,now));if(tally.state==='scheduled'){const start=forcedElectionStart(now);if(!start)fail('The regular election is too close.');await tx.query("UPDATE political_election_rallies SET state='scheduled',election_start=? WHERE id=?",[start,rally.id]);return {...tally,rallyId:rally.id,electionStart:start};}if(tally.state==='denied')await tx.query("UPDATE political_election_rallies SET state='denied' WHERE id=?",[rally.id]);return {...tally,rallyId:rally.id}; });} return {read,vote}; } export function createRallyAPI(db,service,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db)}={}){const reply=(value,status=200)=>Response.json(value,{status,headers:{'Cache-Control':'private, no-store'}});return async request=>{try{const actor=await authenticate(request);if(!actor)return reply({message:'Sign in first.'},401);if(new URL(request.url).search)return reply({message:'Unexpected query.'},400);if(request.method==='GET')return reply(await service.read(actor));if(request.method!=='POST')return reply({message:'Method not allowed.'},405);if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403);const raw=await request.text();if(raw.length>6000)return reply({message:'Request too large.'},413);let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid rally request.'},400);}return reply(await service.vote(actor,body));}catch(e){return reply({message:e.status?e.message:'Rally processing unavailable.'},e.status||503);}};}