import {createHash} from 'node:crypto'; import {boardReadStore} from './board-deed-source.mjs'; import {currentNaib} from './naib-membership.mjs'; import {currentOfficeController} from './entity-relations.mjs'; import {officeAuthority} from './political-decisions.mjs'; import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; import {validUuid} from './game-link.mjs'; import {JarvisError} from './jarvis-listings.mjs'; import {naibDecision} from '../control-panel/public/naib-council-policy.mjs'; export const NAIB_PETITION_POLICY=naibDecision('FRE-07'); export const NAIB_PETITION_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_naib_petitions(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,clan_id CHAR(36) NOT NULL,target_actor CHAR(36) NOT NULL,target_term CHAR(36) NOT NULL,title VARCHAR(100) NOT NULL,message TEXT NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL,response_until BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; const fail=(message,status=409)=>{throw new JarvisError(message,status);},hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex'),P=NAIB_PETITION_POLICY; export function createNaibPetitions(raw,keys,billing,{clock=Date.now}={}){ if(!raw?.query||!raw?.transaction)return{context:async()=>fail('Sietch petitions unavailable.',503),propose:async()=>fail('Sietch petitions unavailable.',503),read:async()=>[],reply:async()=>fail('Sietch petition not found.',404)}; const db=boardReadStore(raw,raw); async function emperor(tx,now,lock=false){const h=await currentOfficeController(tx,'emperor',now);if(!h||!await officeAuthority(tx,{office:'emperor'},{id:h.userId},now,lock))return null;const term=await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[h.termId]);return{...h,expiresAt:Number(term?.expires_at||0)};} async function context(actor){const now=clock(),seat=await currentNaib(db,actor.id),recipient=await emperor(db,now),funding=seat&&billing?await billing.context(actor,seat):null,row=seat?await db.first('SELECT MAX(created_at) last_at FROM jarvis_naib_petitions WHERE clan_id=? OR actor_id=?',[seat.clan_id,actor.id]):null,cooldownUntil=row?.last_at==null?null:Number(row.last_at)+P.cooldownMs,policy=funding?.policies?.find(p=>p.id===P.id);return{...P,canManage:!!seat,canExecute:!!keys&&!!recipient&&recipient.userId!==actor.id&&recipient.expiresAt>now+P.responseMs&&!!policy?.canExecute&&(!cooldownUntil||now>=cooldownUntil),cooldownUntil,recipient:recipient?'Current Emperor':null,levelNow:funding?.levelNow||0,accounts:funding?.accounts||[]};} async function propose(actor,input){ if(!input||Object.keys(input).sort().join(',')!=='confirmed,message,requestId,sourceAccount,title'||input.confirmed!==true||!validUuid(input.requestId)||typeof input.sourceAccount!=='string'||!/^\d{1,12}$/.test(input.sourceAccount)||typeof input.title!=='string'||input.title.trim().length<3||input.title.length>100||typeof input.message!=='string'||input.message.trim().length<20||input.message.length>4000||/[\x00-\x1f\x7f]/.test(input.title)||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(input.message))fail('Review the petition and its sietch funding.',400); if(!keys||!billing||raw.naibCouncilPaidEnabled!==true)fail('Sietch petition banking unavailable.',503);await billing.ready();const digest=hash([actor.id,input.sourceAccount,input.title.trim(),input.message.trim()]); return raw.transaction(async original=>{const tx=boardReadStore(original,db),now=clock(),seat=await currentNaib(tx,actor.id,{lock:true});if(!seat)fail('Current independent sietch ownership required.',403); const scope='petition:sietch:'+seat.clan_id;await tx.query('INSERT INTO jarvis_council_proposal_locks(scope_key) VALUES(?) ON DUPLICATE KEY UPDATE scope_key=VALUES(scope_key)',[scope]);await tx.first('SELECT scope_key FROM jarvis_council_proposal_locks WHERE scope_key=? FOR UPDATE',[scope]); const prior=await tx.first('SELECT * FROM jarvis_naib_petitions WHERE request_id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==actor.id||prior.input_hash!==digest)fail('Petition reference conflict.');return{ok:true,replayed:true,reference:prior.key_id};} const previous=await tx.first('SELECT MAX(created_at) last_at FROM jarvis_naib_petitions WHERE clan_id=? OR actor_id=?',[seat.clan_id,actor.id]);if(previous?.last_at!=null&&now=Number(row.created_at)&&Number(answer.created_at)=Number(row.response_until)?'expired':'pending';items.push({id:row.request_id,mode:'petition',decisionId:P.id,title:row.title,terms:row.message,sourceOffice:'independent_sietch',targetOffice:'emperor',targetName:'Emperor',responseUntil:Number(row.response_until),respondedAt:valid?Number(answer.created_at):null,endsAt:null,state,canReply:state==='pending'&&actor.id===row.target_actor,reference:row.key_id});}return items;} async function reply(actor,input){if(!input||Object.keys(input).sort().join(',')!=='choice,confirmed,proposalId,requestId'||input.confirmed!==true||!validUuid(input.proposalId)||!validUuid(input.requestId)||!['accept','decline'].includes(input.choice))fail('Review this petition response.',400);if(!keys)fail('Petition signatures unavailable.',503);return raw.transaction(async original=>{const tx=boardReadStore(original,db),row=await tx.first('SELECT * FROM jarvis_naib_petitions WHERE request_id=? FOR UPDATE',[input.proposalId]);if(!row||row.target_actor!==actor.id)fail('This petition is not addressed to your account.',403);const digest=hash([actor.id,row.request_id,input.choice]),old=await tx.first('SELECT * FROM jarvis_political_agreement_replies WHERE decision_request=? OR request_id=? FOR UPDATE',[row.request_id,input.requestId]);if(old){if(old.request_id!==input.requestId||old.actor_id!==actor.id||old.input_hash!==digest)fail('This petition already has a response.');return{ok:true,replayed:true,reference:old.key_id};}const now=clock(),proof=await verified(tx,row,now);if(!proof?.current||now>=Number(row.response_until))fail('This petition or one of its original mandates has expired.');const seat=await currentNaib(tx,row.actor_id,{lock:true}),target=await emperor(tx,now,true);if(seat?.clan_id!==row.clan_id||target?.userId!==actor.id||target.termId!==row.target_term)fail('Both original mandates must remain 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 jarvis_political_agreement_replies VALUES(?,?,?,?,?,?,?,?)',[row.request_id,input.requestId,keyId,actor.id,target.termId,input.choice,digest,now]);}});return{ok:true,replayed:false,reference};});} return{context,propose,read,reply}; }