import {identity} from './auth.mjs';import {accessFor} from './permissions.mjs'; import {currentOfficeController,entityParent} from './entity-relations.mjs'; import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';import {validUuid} from './game-link.mjs'; import {FAITH_BLESSINGS,faithBlessing} from '../control-panel/public/faith-blessing-policy.mjs'; import {faithAuthority,currentClanFaith} from './clan-faith.mjs'; import {boardReadStore} from './board-deed-source.mjs'; export const FAITH_BLESSING_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_faith_blessings(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,decision_id VARCHAR(24) NOT NULL,clan_id CHAR(36) NOT NULL,actor_id CHAR(36) NOT NULL,source_term_id CHAR(36) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; const first=async(db,sql,args=[])=>(await db.query(sql,args))[0]||null; const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});}; const proofSQL="SELECT b.*,k.id verified_key FROM jarvis_faith_blessings b JOIN organisation_keys k ON k.id=b.key_id AND k.key_type='entity-state' AND k.account_id=? AND k.scope_id=CONCAT('state:faith-blessing:',b.request_id) AND k.revoked_at IS NULL"; async function authority(db,actor,clanId,now,{lock=false,office='muad_dib'}={}){ db=boardReadStore(db,db); if(office!=='muad_dib'){ if(!await first(db,'SELECT id FROM site_clans WHERE id=? AND active=1'+(lock?' FOR UPDATE':''),[clanId]))return null; const a=await faithAuthority(db,office,actor,now,{clanId,lock});if(!a)return null;const term=await first(db,'SELECT user_id,expires_at FROM political_office_terms WHERE id=?'+(lock?' FOR UPDATE':''),[a.termId]);if(!term)return null; if(term.user_id===actor.id)return{role:'doci',termId:a.termId,expiresAt:Number(term.expires_at)}; return await first(db,'SELECT clan_id FROM site_clan_members WHERE user_id=? AND clan_id=?',[actor.id,clanId])?{role:'prior',termId:a.termId,expiresAt:a.expiresAt}:null; } const charter=await first(db,"SELECT c.staff_key_id FROM political_office_charters c JOIN organisation_keys k ON k.id=c.staff_key_id AND k.key_type='staff-office-royal' AND k.scope_id='office:muad_dib' AND k.account_id=? AND k.used_at IS NOT NULL AND k.revoked_at IS NULL WHERE c.office_key='muad_dib' AND c.charter_kind='royal'"+(lock?' FOR UPDATE':''),[STAFF_OFFICE_ACCOUNT_ID]);if(!charter)return null; const clan=await first(db,'SELECT id FROM site_clans WHERE id=? AND active=1'+(lock?' FOR UPDATE':''),[clanId]);if(!clan)return null; const leader=await currentOfficeController(db,'muad_dib',now); if(leader?.userId===actor?.id){const term=await first(db,'SELECT expires_at FROM political_office_terms WHERE id=?'+(lock?' FOR UPDATE':''),[leader.termId]);return{role:'doci',termId:leader.termId,expiresAt:Number(term.expires_at)};} const prior=await first(db,"SELECT d.source_term_id,t.expires_at,d.expires_at appointment_expires FROM political_appointment_deeds d JOIN political_office_terms t ON t.id=d.source_term_id JOIN site_clan_members m ON m.user_id=d.user_id AND m.clan_id=? JOIN site_accounts a ON a.id=m.user_id AND a.password_hash NOT LIKE '!%' WHERE d.user_id=? AND d.office_key='muad_dib' AND d.role_key='officer' AND d.title='Prior' AND d.revoked_at IS NULL AND d.starts_at<=? AND d.expires_at>? AND (d.target_kind IS NULL OR d.target_kind='clan' AND d.target_id=?) AND t.kind='church' AND t.faction='muad_dib' AND t.outcome='winner' AND t.starts_at<=? AND t.expires_at>? ORDER BY d.expires_at DESC LIMIT 1"+(lock?' FOR UPDATE':''),[clanId,actor?.id,now,now,clanId,now,now]);return prior?{role:'prior',termId:prior.source_term_id,expiresAt:Math.min(Number(prior.expires_at),Number(prior.appointment_expires))}:null; } async function previous(db,d,clanId){return first(db,'SELECT * FROM jarvis_faith_blessings WHERE decision_id=?'+(d.role==='prior'?' AND clan_id=?':'')+' ORDER BY created_at DESC,request_id DESC LIMIT 1',d.role==='prior'?[d.id,clanId]:[d.id]);} export function createFaithBlessings(db,keys,{clock=Date.now}={}){ async function read(actor){const clans=await db.query('SELECT id,name FROM site_clans WHERE active=1 ORDER BY name LIMIT 1000'),choices=[];for(const clan of clans){const decisions=[],authorities=new Map(),consent=db.clanFaithEnabled?await currentClanFaith(db,clan.id):null;for(const d of FAITH_BLESSINGS){if(consent&&consent.faith!==d.office)continue;if(!authorities.has(d.office))authorities.set(d.office,await authority(db,actor,clan.id,clock(),{office:d.office}));const a=authorities.get(d.office);if(!a||a.role!=='doci'&&d.role!=='prior')continue;const last=await previous(db,d,clan.id),until=last?Number(last.created_at)+d.cooldownMs:null;decisions.push({...d,available:!until||clock()>=until,cooldownUntil:until});}if(decisions.length)choices.push({...clan,role:authorities.get(decisions[0].office)?.role,decisions});}return{clans:choices,stacking:'Overlapping blessings cap at 2×; they do not multiply each other.'};} async function grant(actor,input){ if(!input||Object.keys(input).sort().join(',')!=='clanId,decisionId,requestId'||!validUuid(input.requestId)||!validUuid(input.clanId)||!faithBlessing(input.decisionId))fail('Choose a registered blessing and clan.',400);const d=faithBlessing(input.decisionId); await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:faith-blessing:'+input.requestId,authorize:async(tx,{keyId})=>{ const now=clock(),a=await authority(tx,actor,input.clanId,now,{lock:true,office:d.office});if(!a||a.role!=='doci'&&d.role!=='prior')fail('Current faith leader or assigned officer authority required.',403); const existing=await first(tx,'SELECT * FROM jarvis_faith_blessings WHERE request_id=?',[input.requestId]);if(existing){if(existing.actor_id!==actor.id||existing.clan_id!==input.clanId||existing.decision_id!==d.id)fail('Blessing reference already used.');return;} if(db.clanFaithEnabled&&(await currentClanFaith(tx,input.clanId)).faith!==d.office)fail('The clan’s legal owner must first accept this faith.',403); const last=await previous(tx,d,input.clanId);if(last&&now? WHERE b.clan_id IN ("+clans.map(()=>'?').join(',')+') AND b.created_at<=? AND b.expires_at>? ORDER BY b.created_at DESC,b.request_id DESC',[STAFF_OFFICE_ACCOUNT_ID,now,now,...clans,now,now]); const cutoff=base.clanFaithEnabled?await consentCutoff(db):null,memberFaiths=new Set();let hasExplicitFaith=false; if(base.clanFaithEnabled)for(const m of await db.query('SELECT clan_id FROM site_clan_members WHERE user_id=?',[accountId])){const c=await currentClanFaith(db,m.clan_id);if(c.requestId)hasExplicitFaith=true;if(c.faith)memberFaiths.add(c.faith);} for(const r of rows){const d=faithBlessing(r.decision_id);if(!d)throw Error('Unknown blessing record');let consent=null; if(base.clanFaithEnabled){consent=await currentClanFaith(db,r.clan_id);if(consent.requestId&&consent.faith!==d.office||hasExplicitFaith&&!memberFaiths.has(d.office))continue;if(consent.faith!==d.office&&(cutoff===null||Number(r.created_at)>=cutoff))continue;if(consent.faith===d.office&&!memberFaiths.has(d.office))continue;} for(const kind of ['xp','dm'])if(d[kind]>out[kind]){out[kind]=d[kind];out[kind+'Proof']={keyId:r.key_id,clanId:r.clan_id,accountId,occurredAt:now,multiplier:d[kind],...(consent?.faith===d.office?{faithConsentRequestId:consent.requestId}:{})};}}return out; } export async function validFaithReward(db,proof,{accountId,claimedAt}){ if(!proof||proof.accountId!==accountId||proof.multiplier!==2||!Number.isSafeInteger(proof.occurredAt)||proof.occurredAt>claimedAt||claimedAt-proof.occurredAt>30000)return false; const row=await first(db,proofSQL+' WHERE b.key_id=? AND b.clan_id=? FOR UPDATE',[STAFF_OFFICE_ACCOUNT_ID,proof.keyId,proof.clanId]);if(!row||faithBlessing(row.decision_id)?.dm!==2||Number(row.created_at)>proof.occurredAt||Number(row.expires_at)<=proof.occurredAt)return false; const cutoff=await consentCutoff(db);if(!proof.faithConsentRequestId)return cutoff===null||Number(row.created_at)identity(r,db),access=a=>accessFor(db,a),clock=Date.now}={}){ const service=createFaithBlessings(db,keys,{clock}),reply=(v,status=200)=>Response.json(v,{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(!(await access(actor)).nodes.includes('web.menu.game'))return reply({message:'Player access required.'},403);if(new URL(request.url).search)return reply({message:'Identity overrides are not accepted.'},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);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);const raw=await request.text();if(raw.length>2048)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Invalid blessing.'},400);}return reply(await service.grant(actor,input));}catch(e){return reply({message:e.status?e.message:'Blessing was not confirmed. Refresh before retrying.'},e.status||503);}}; }