MC/website/node/political-agreements.mjs
2026-11-27 23:43:05 +00:00

86 lines
16 KiB
JavaScript

import {createHash} from 'node:crypto';
import {boardReadStore} from './board-deed-source.mjs';
import {officeAuthority} from './political-decisions.mjs';
import {politicalDecision} from '../control-panel/public/political-decision-policy.mjs';
import {PUBLIC_OFFICES} from './public-government.mjs';
import {currentOfficeController} from './entity-relations.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {validUuid} from './game-link.mjs';
import {readCompanyDeed} from './company-deeds.mjs';
import {identity} from './auth.mjs';
import {appointPoliticalInTransaction,activePoliticalAppointments} from './political-appointments.mjs';
export const POLITICAL_AGREEMENT_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_political_agreement_replies(decision_request CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,key_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,term_id CHAR(36) NOT NULL,choice VARCHAR(12) NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
export const POLITICAL_COMPANY_REPLY_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_political_company_replies(decision_request CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,key_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,company_id CHAR(36) NOT NULL,choice VARCHAR(12) NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
export const POLITICAL_PERSON_REPLY_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_political_person_replies(decision_request CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,key_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,person_id CHAR(36) NOT NULL,choice VARCHAR(12) NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
const replyTable=d=>d.targetKind==='company'?'jarvis_political_company_replies':d.targetKind==='person'?'jarvis_political_person_replies':'jarvis_political_agreement_replies';
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
export function createPoliticalAgreements(raw,keys,{clock=Date.now,petitions=null}={}){
if(typeof raw?.query!=='function')return{targets:async()=>[],create:async()=>fail('Political agreements unavailable.',503),read:async()=>fail('Political agreements unavailable.',503),reply:async()=>fail('Political agreements unavailable.',503)};
const db=boardReadStore(raw,raw);
async function holder(tx,office,actor,now,lock=false){const h=await officeAuthority(tx,{office},actor,now,lock);if(!h)return null;const term=await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[h.termId]);return term?{...h,expiresAt:Number(term.expires_at)}:null;}
async function resolve(tx,d,actor,office,now){
if(office===d.office||!PUBLIC_OFFICES.some(o=>o.key===office))fail('Choose another current political office.',400);
const target=await currentOfficeController(tx,office,now),h=target&&await holder(tx,office,{id:target.userId},now,true);
if(!h||h.userId===actor.id)fail('A different current Royal office holder must receive this proposal.',403);
return h;
}
async function company(tx,id,{lock=false}={}){tx=boardReadStore(tx,db);if(lock)await tx.first('SELECT company_id FROM site_company_deeds WHERE company_id=? FOR UPDATE',[id]);try{const deed=await readCompanyDeed(tx,id);const owner=await tx.first("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' AND NOT EXISTS(SELECT 1 FROM site_memorials m WHERE m.user_id=site_accounts.id)",[deed.company.owner_account_id]);return deed.company.status==='active'&&owner?{userId:deed.company.owner_account_id,bindingId:id,name:deed.company.name}:null;}catch{return null;}}
async function person(tx,id,{lock=false}={}){const row=await tx.first("SELECT a.id,a.username FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE a.id=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('official_account','memorial') AND NOT EXISTS(SELECT 1 FROM site_memorials m WHERE m.user_id=a.id)"+(lock?' FOR UPDATE':''),[id]);return row?{userId:row.id,bindingId:row.id,name:row.username}:null;}
async function targets(tx,d,actor,now){if(d.targetKind==='person')return tx.query("SELECT a.id,a.username name FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE a.id<>? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('official_account','memorial') AND NOT EXISTS(SELECT 1 FROM site_memorials m WHERE m.user_id=a.id) ORDER BY a.username LIMIT 1000",[actor.id]);if(d.targetKind==='company'){return tx.query("SELECT c.id,c.name FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id JOIN site_company_members m ON m.company_id=c.id AND m.user_id=d.owner_account_id JOIN site_accounts a ON a.id=d.owner_account_id WHERE c.status='active' AND d.owner_account_id<>? AND a.password_hash NOT LIKE '!%' ORDER BY c.name,c.id LIMIT 1000",[actor.id]);}const rows=[];for(const o of PUBLIC_OFFICES){if(o.key===d.office)continue;const target=await currentOfficeController(tx,o.key,now);if(target&&target.userId!==actor.id&&await holder(tx,o.key,{id:target.userId},now))rows.push({id:o.key,name:o.scope});}return rows;}
async function create(tx,{d,actor,payload,holder:source,now}){
tx=boardReadStore(tx,db);const target=d.targetKind==='company'?await company(tx,payload.targetCompanyId,{lock:true}):d.targetKind==='person'?await person(tx,payload.targetPersonId,{lock:true}):await resolve(tx,d,actor,payload.targetOffice,now);if(!target||target.userId===actor.id)fail(d.targetKind==='company'?'Choose an active company with a different current legal owner.':'Choose a different active eligible recipient.',403);const sourceTerm=await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[source.termId]),responseUntil=now+d.responseMs,mandateUntil=Math.min(Number(sourceTerm?.expires_at||0),target.expiresAt??Number(sourceTerm?.expires_at||0));
if(mandateUntil<=responseUntil)fail('Both mandates must extend beyond the full proposal response window.');
return{...(d.targetKind==='company'?{targetKind:'company',targetCompanyId:payload.targetCompanyId,targetName:target.name}:d.targetKind==='person'?{targetKind:'person',targetPersonId:payload.targetPersonId,targetName:target.name}:{targetOffice:payload.targetOffice,targetTermId:target.termId}),targetActorId:target.userId,responseUntil,mandateUntil,durationMs:d.durationMs};
}
async function verified(tx,row,now){
const d=politicalDecision(row?.decision_id);if(!d||d.kind!=='agreement')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",[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),a=receipt.agreement;
if(!a||(d.targetKind==='company'?a.targetKind!=='company'||a.targetCompanyId!==payload.targetCompanyId||!validUuid(a.targetCompanyId):d.targetKind==='person'?a.targetKind!=='person'||a.targetPersonId!==payload.targetPersonId||!validUuid(a.targetPersonId):a.targetOffice!==payload.targetOffice||!validUuid(a.targetTermId))||a.targetActorId!==row.recipient_id||a.responseUntil!==Number(row.created_at)+d.responseMs||a.durationMs!==d.durationMs||!Number.isSafeInteger(a.mandateUntil))return null;
const source=await holder(tx,d.office,{id:row.actor_id},now),target=d.targetKind==='company'?await company(tx,a.targetCompanyId):d.targetKind==='person'?await person(tx,a.targetPersonId):await holder(tx,a.targetOffice,{id:a.targetActorId},now);
return{d,a,payload,mandates:source?.termId===row.term_id&&(['company','person'].includes(d.targetKind)?target?.userId===a.targetActorId:target?.termId===a.targetTermId)};
}
async function projection(tx,row,actor,now){
if(![row.actor_id,row.recipient_id].includes(actor.id))return null;const v=await verified(tx,row,now);if(!v)return null;
const reply=await tx.first('SELECT r.*,k.id verified_key FROM '+replyTable(v.d)+' r LEFT JOIN organisation_keys k ON k.id=r.key_id AND k.account_id=? AND k.key_type=\'entity-state\' AND k.scope_id=CONCAT(\'state:political-agreement-reply:\',r.request_id) AND k.revoked_at IS NULL WHERE r.decision_request=?',[STAFF_OFFICE_ACCOUNT_ID,row.request_id]);
const replyValid=reply?.verified_key&&reply.actor_id===v.a.targetActorId&&(v.d.targetKind==='company'?reply.company_id===v.a.targetCompanyId:v.d.targetKind==='person'?reply.person_id===v.a.targetPersonId:reply.term_id===v.a.targetTermId)&&['accept','decline'].includes(reply.choice)&&Number(reply.created_at)>=Number(row.created_at)&&Number(reply.created_at)<v.a.responseUntil&&reply.input_hash===hash([reply.actor_id,row.request_id,reply.choice]);
const petition=v.d.agreementMode==='petition';
const endsAt=!petition&&replyValid&&reply.choice==='accept'?Math.min(Number(reply.created_at)+v.a.durationMs,v.a.mandateUntil):null;
let state=petition&&replyValid?(reply.choice==='accept'?'acknowledged':'declined'):!v.mandates?'mandate-ended':reply&&!replyValid?'response-unavailable':replyValid?(reply.choice==='decline'?'declined':now<endsAt?'accepted':'expired'):now<v.a.responseUntil?'pending':'expired';
if(v.d.agreementMode==='representation'&&state==='accepted'){const appointment=await tx.first("SELECT id FROM political_appointment_deeds WHERE request_id=? AND appointment_type='political-adviser' AND revoked_at IS NULL",[reply.request_id]);if(!appointment||(await activePoliticalAppointments(tx,{userId:row.actor_id,clock:()=>now})).every(a=>a.id!==appointment.id))state='representation-ended';}
if(v.d.agreementMode==='steward'&&state==='accepted'){const appointment=await tx.first("SELECT id FROM political_appointment_deeds WHERE request_id=? AND appointment_type='imperial-steward' AND revoked_at IS NULL",[reply.request_id]);if(!appointment||(await activePoliticalAppointments(tx,{userId:v.a.targetActorId,clock:()=>now})).every(a=>a.id!==appointment.id))state='appointment-ended';}
return{id:row.request_id,mode:petition?'petition':v.d.agreementMode==='representation'?'representation':v.d.agreementMode==='steward'?'steward':'agreement',respondedAt:replyValid?Number(reply.created_at):null,title:v.payload.title,terms:v.payload.terms,decisionId:v.d.id,sourceOffice:v.d.office,targetOffice:v.a.targetOffice||null,targetName:v.a.targetName||PUBLIC_OFFICES.find(o=>o.key===v.a.targetOffice)?.scope||v.a.targetOffice,responseUntil:v.a.responseUntil,endsAt,state,canReply:state==='pending'&&actor.id===v.a.targetActorId,reference:row.key_id};
}
async function read(actor){const rows=await db.query('SELECT * FROM jarvis_political_decisions WHERE actor_id=? OR recipient_id=? ORDER BY created_at DESC,request_id DESC LIMIT 100',[actor.id,actor.id]),items=[];for(const row of rows){const item=await projection(db,row,actor,clock());if(item)items.push(item);}return{agreements:[...items,...(petitions?await petitions.read(actor):[])]};}
async function reply(actor,input){
if(!input||Object.keys(input).sort().join(',')!=='choice,confirmed,proposalId,requestId'||input.confirmed!==true||!validUuid(input.requestId)||!validUuid(input.proposalId)||!['accept','decline'].includes(input.choice))fail('Review and confirm this proposal response.',400);
if(!keys||!raw.transaction)fail('Agreement records unavailable.',503);
if(petitions&&!await db.first('SELECT request_id FROM jarvis_political_decisions WHERE request_id=?',[input.proposalId]))return petitions.reply(actor,input);
return raw.transaction(async original=>{const tx=boardReadStore(original,db),now=clock(),row=await tx.first('SELECT * FROM jarvis_political_decisions WHERE request_id=? FOR UPDATE',[input.proposalId]);if(!row||row.recipient_id!==actor.id)fail('This proposal is not addressed to your office.',403);
const policy=politicalDecision(row.decision_id);if(policy?.kind!=='agreement')fail('Registered agreement required.',400);const digest=hash([actor.id,input.proposalId,input.choice]),old=await tx.first('SELECT * FROM '+replyTable(policy)+' WHERE decision_request=? OR request_id=? FOR UPDATE',[row.request_id,input.requestId]);
if(old){if(old.request_id!==input.requestId||old.input_hash!==digest||old.actor_id!==actor.id)fail('This proposal already has a response.');return{ok:true,replayed:true,reference:old.key_id};}
const v=await verified(tx,row,now);if(!v||!v.mandates||now>=v.a.responseUntil)fail('The proposal or one of its mandates has expired.');
const source=await holder(tx,v.d.office,{id:row.actor_id},now,true),target=v.d.targetKind==='company'?await company(tx,v.a.targetCompanyId,{lock:true}):v.d.targetKind==='person'?await person(tx,v.a.targetPersonId,{lock:true}):await holder(tx,v.a.targetOffice,actor,now,true);if(source?.termId!==row.term_id||(['company','person'].includes(v.d.targetKind)?target?.userId!==actor.id:target?.termId!==v.a.targetTermId))fail('Both original mandates must still be current.',403);
let reference;await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:political-agreement-reply:'+input.requestId,transactionStore:tx,authorize:async(_,{keyId})=>{reference=keyId;await tx.query('INSERT INTO '+replyTable(v.d)+' VALUES(?,?,?,?,?,?,?,?)',[row.request_id,input.requestId,keyId,actor.id,v.d.targetKind==='company'?v.a.targetCompanyId:v.d.targetKind==='person'?v.a.targetPersonId:target.termId,input.choice,digest,now]);
if(v.d.agreementMode==='steward'&&input.choice==='accept'){
const newer=await tx.first("SELECT request_id FROM jarvis_political_decisions WHERE decision_id='IMP-03' AND term_id=? AND created_at>? ORDER BY created_at DESC LIMIT 1",[row.term_id,row.created_at]);if(newer)fail('A newer Steward nomination supersedes this proposal.');
await tx.query("UPDATE political_appointment_deeds SET revoked_at=? WHERE office_key='emperor' AND appointment_type='imperial-steward' AND revoked_at IS NULL",[now]);
const appointment=await appointPoliticalInTransaction(tx,{id:row.actor_id},{officeKey:'emperor',userId:actor.id,requestId:input.requestId,type:'job',title:'Imperial Steward',expiresAt:Math.min(now+v.a.durationMs,v.a.mandateUntil)},{clock:()=>now,allowSteward:true});
await tx.query("UPDATE political_appointment_deeds SET role_key='steward',appointment_type='imperial-steward' WHERE id=?",[appointment.id]);
}
if(v.d.agreementMode==='representation'&&input.choice==='accept'){
if((await activePoliticalAppointments(tx,{userId:row.actor_id,clock:()=>now})).some(a=>a.office_key===v.a.targetOffice))fail('This applicant already has a current appointment in the receiving office.');
const appointment=await appointPoliticalInTransaction(tx,actor,{officeKey:v.a.targetOffice,userId:row.actor_id,requestId:input.requestId,type:'job',title:'Court Advisory Representative',expiresAt:Math.min(now+v.a.durationMs,v.a.mandateUntil)},{clock:()=>now});
await tx.query("UPDATE political_appointment_deeds SET role_key='observer',appointment_type='political-adviser' WHERE id=?",[appointment.id]);
}
}});return{ok:true,replayed:false,reference};
});
}
return{targets,create,read,reply};
}
export function createPoliticalAgreementAPI(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 agreement 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:'Response too large.'},413);let input;try{input=JSON.parse(body);}catch{return respond({message:'Invalid response.'},400);}return respond(await service.reply(actor,input));
}catch(error){return respond({message:error.status?error.message:'Political agreements are temporarily unavailable.'},error.status||503);}};}