import {randomUUID} from 'node:crypto'; import {identity} from '../node/auth.mjs';import {accessFor} from '../node/permissions.mjs';import {createPoliticsPreview} from './politics-preview.mjs';import {ELECTION_RULES} from './public/election-rules.mjs'; export const charterSchema=[`CREATE TABLE IF NOT EXISTS political_charter_slots(resource VARCHAR(8) PRIMARY KEY,version INTEGER NOT NULL) ENGINE=InnoDB`,`CREATE TABLE IF NOT EXISTS political_charters(id CHAR(36) PRIMARY KEY,resource VARCHAR(8) NOT NULL,clan_id CHAR(36) NOT NULL,author_id CHAR(36) NOT NULL,decree TEXT NOT NULL,starts_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,revoked_at BIGINT,KEY resource_date(resource,starts_at)) ENGINE=InnoDB`]; export async function initializeCharters(db){for(const sql of charterSchema)await db.prepare(sql).run();for(const resource of ['water','spice'])await db.prepare('INSERT INTO political_charter_slots(resource,version) VALUES(?,0) ON DUPLICATE KEY UPDATE resource=VALUES(resource)').bind(resource).run();} export function charterExpiry(now){const first=Date.parse(ELECTION_RULES.imperial.first),period=ELECTION_RULES.imperial.weeks*604800000;return now4000))throw Error('Choose a clan and write a decree of 10–4,000 characters.');return input;} export async function changeCharter(db,{resource,userId,input,now=Date.now()}){ validateCharter(input);if(!['water','spice'].includes(resource))throw Error('Unknown resource'); const[result]=await db.batch([{async run(c){const q=async(sql,args=[])=>(await c.execute(sql,args))[0];const[slot]=await q('SELECT version FROM political_charter_slots WHERE resource=? FOR UPDATE',[resource]);if(!slot||Number(slot.version)!==input.version)throw Error('Charter changed; refresh.'); if(input.action==='grant'){const[clan]=await q('SELECT id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[input.clanId]);if(!clan)throw Error('Clan is no longer active.');} await q('UPDATE political_charters SET revoked_at=? WHERE resource=? AND revoked_at IS NULL AND expires_at>?',[now,resource,now]);let id=null; if(input.action==='grant'){id=randomUUID();await q('INSERT INTO political_charters(id,resource,clan_id,author_id,decree,starts_at,expires_at) VALUES(?,?,?,?,?,?,?)',[id,resource,input.clanId,userId,input.decree.trim(),now,charterExpiry(now)]);} await q('UPDATE political_charter_slots SET version=version+1 WHERE resource=?',[resource]);await q('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),userId,'imperial-charter-'+input.action,JSON.stringify({resource,clanId:input.clanId||null,charterId:id}),now]);return{id,version:input.version+1};}}]);return result; } export function createImperialCharters(db,settings={},deps={}){const origin=settings.CP_ORIGIN||'https://cp.dunerealms.com',auth=deps.authenticate||(r=>identity(r,db)),access=deps.access||(u=>accessFor(db,u)),preview=deps.preview||createPoliticsPreview(db,settings),change=deps.change||changeCharter; const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}); return async request=>{const url=new URL(request.url),resource=url.searchParams.get('resource');if(!['water','spice'].includes(resource)||[...url.searchParams.keys()].some(k=>k!=='resource'))return reply({message:'Unknown charter.'},400);if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405);if(request.method==='POST'&&(request.headers.get('origin')!==new URL(origin).origin||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||'')))return reply({message:'Invalid request origin.'},403); const user=await auth(request);if(!user)return reply({message:'Sign in first.'},401);if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Realm access required.'},403); let input;if(request.method==='POST'){const raw=await request.text();if(raw.length>8000)return reply({message:'Decree too large.'},413);try{input=validateCharter(JSON.parse(raw));}catch(error){return reply({message:error.message},400);}} const response=await preview(new Request(new URL('/api/politics/preview',origin),{headers:request.headers}));if(!response.ok)return reply({message:'Political authority unavailable.'},503);const context=await response.json(),current=await auth(request);if(!current||current.id!==user.id||!(await access(current)).nodes.includes('web.menu.game'))return reply({message:'Access changed.'},403); if(request.method==='POST'){if(context.emperor!==true)return reply({message:'Only the current Emperor may issue or revoke a charter.'},403);try{return reply({ok:true,...await change(db,{resource,userId:user.id,input})});}catch(error){return reply({message:error.message},409);}} const {results:records}=await db.prepare('SELECT p.id,p.decree,p.starts_at,p.expires_at,p.revoked_at,c.name AS clan,c.tag,c.active AS clan_active,a.username AS author FROM political_charters p JOIN site_clans c ON c.id=p.clan_id JOIN site_accounts a ON a.id=p.author_id WHERE p.resource=? ORDER BY p.starts_at DESC,p.id DESC LIMIT 100').bind(resource).all();const slot=await db.prepare('SELECT version FROM political_charter_slots WHERE resource=?').bind(resource).first();const clans=context.emperor?(await db.prepare('SELECT id,name,tag FROM site_clans WHERE active=1 ORDER BY name_key LIMIT 500').all()).results:[]; return reply({resource,records,clans,canGrant:context.emperor===true,version:Number(slot.version),expiresAt:charterExpiry(Date.now())});};}