web/website/node/clan-faith.mjs
2026-11-27 23:43:05 +00:00

86 lines
14 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {createHash} from 'node:crypto';
import {boardReadStore} from './board-deed-source.mjs';
import {readClanDeed} from './clan-deeds.mjs';
import {officeDeedFor,activePoliticalAppointments} from './political-appointments.mjs';
import {officeAuthority} from './political-decisions.mjs';
import {faithPOL} from '../control-panel/public/faith-pol-policy.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {validUuid} from './game-link.mjs';
import {identity} from './auth.mjs';
import {accessFor} from './permissions.mjs';
import {polProgressionStore} from './progression-pol.mjs';
import {readActiveXPSeason} from './progression-xp-store.mjs';
import {levelForXP} from './progression-definitions.mjs';
import {CLAN_FAITH_POLICY as POLICY,clanFaithDecision} from '../control-panel/public/clan-faith-policy.mjs';
export const CLAN_FAITH_SCHEMA=[
`CREATE TABLE IF NOT EXISTS jarvis_clan_faith(clan_id CHAR(36) PRIMARY KEY,faith_key VARCHAR(32),request_id CHAR(36),changed_at BIGINT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS jarvis_faith_office_locks(office_key VARCHAR(32) PRIMARY KEY,last_offer_at BIGINT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS jarvis_faith_offers(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,office_key VARCHAR(32) NOT NULL,source_term_id CHAR(36) NOT NULL,actor_id CHAR(36) NOT NULL,clan_id CHAR(36) NOT NULL,input_hash CHAR(64) NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS jarvis_faith_consents(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,offer_id CHAR(36),clan_id CHAR(36) NOT NULL,actor_id CHAR(36) NOT NULL,faith_key VARCHAR(32),choice VARCHAR(16) NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
];
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
const digest=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
const exact=(v,fields)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join(',')===fields;
async function reputation(tx,actor,now){const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,now),row=await pol.first('SELECT effective_xp FROM jarvis_progression_accounts WHERE account_id=?',[actor.id]);return levelForXP(Number(row?.effective_xp||0),{base:Number(season.curve_base),cap:Number(season.level_cap)||null});}
export async function initializeClanFaith(db){for(const sql of CLAN_FAITH_SCHEMA)await db.query(sql);for(const office of ['veiled_concord','muad_dib'])await db.query('INSERT INTO jarvis_faith_office_locks(office_key) VALUES(?) ON DUPLICATE KEY UPDATE office_key=VALUES(office_key)',[office]);db.clanFaithEnabled=true;}
export async function currentClanFaith(store,clanId){
const row=(await store.query("SELECT f.*,k.id verified_key FROM jarvis_clan_faith f LEFT JOIN organisation_keys k ON k.id=(SELECT c.key_id FROM jarvis_faith_consents c WHERE c.request_id=f.request_id AND c.clan_id=f.clan_id AND c.choice='accept' AND c.faith_key=f.faith_key) AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:clan-faith:',f.request_id) AND k.revoked_at IS NULL WHERE f.clan_id=?",[STAFF_OFFICE_ACCOUNT_ID,clanId]))[0];
return{faith:row?.verified_key&&faithPOL(row.faith_key)?row.faith_key:null,requestId:row?.request_id||null,changedAt:row?.changed_at===null||row?.changed_at===undefined?null:Number(row.changed_at)};
}
export async function faithAuthority(tx,office,actor,now,{clanId=null,lock=false}={}){
if(!faithPOL(office))return null;
let term;try{term=await officeDeedFor(tx,office,now,{lock});}catch(e){if([403,404,409].includes(e.status))return null;throw e;}
const holder=await officeAuthority(tx,{office},{id:term.user_id},now,lock);if(!holder||holder.termId!==term.id)return null;
if(actor.id===term.user_id)return{termId:term.id,clanIds:null,expiresAt:Number(term.expires_at)};
const appointments=(await activePoliticalAppointments(tx,{userId:actor.id,clock:()=>now})).filter(a=>a.office_key===office&&a.appointment_type==='job'&&a.role_key==='officer'&&a.title===faithPOL(office).roles.officer);
const general=appointments.find(a=>a.target_kind===null);if(general){if(lock)await tx.first('SELECT id FROM political_appointment_deeds WHERE id=? FOR UPDATE',[general.id]);return{termId:term.id,clanIds:null,expiresAt:Math.min(Number(term.expires_at),Number(general.expires_at))};}
const ids=[];let expiresAt=0;for(const a of appointments){if(a.target_kind!=='clan'||clanId&&a.target_id!==clanId)continue;if(await tx.first('SELECT clan_id FROM site_clan_members WHERE user_id=? AND clan_id=?',[actor.id,a.target_id])){ids.push(a.target_id);expiresAt=Math.max(expiresAt,Number(a.expires_at));}}
return ids.length?{termId:term.id,clanIds:ids,expiresAt:Math.min(Number(term.expires_at),expiresAt)}:null;
}
async function legalClanOwner(tx,actor,clanId){await tx.first('SELECT id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[clanId]);const deed=await readClanDeed(tx,clanId);if(deed.owner?.id!==actor.id)fail('Only this clan’s current legal owner can choose its faith.',403);return deed;}
export function createClanFaith(base,keys,{clock=Date.now,isOutlawed=async()=>false}={}){
if(typeof base?.query!=='function')return{office:async()=>fail('Faith records unavailable.',503),clan:async()=>fail('Faith records unavailable.',503),offer:async()=>fail('Faith records unavailable.',503),reply:async()=>fail('Faith records unavailable.',503)};
const db=boardReadStore(base,base);
async function office(actor,officeKey){const now=clock(),a=await faithAuthority(db,officeKey,actor,now),lock=await db.first('SELECT last_offer_at FROM jarvis_faith_office_locks WHERE office_key=?',[officeKey]);if(!faithPOL(officeKey))fail('Unknown faith.',400);
const clans=a?await db.query('SELECT id,name FROM site_clans WHERE active=1'+(a.clanIds?' AND id IN ('+a.clanIds.map(()=>'?').join(',')+')':'')+' ORDER BY name LIMIT 1000',a.clanIds||[]):[];
const offers=a?await db.query('SELECT request_id,clan_id,state,created_at,expires_at FROM jarvis_faith_offers WHERE office_key=? ORDER BY created_at DESC,request_id DESC LIMIT 100',[officeKey]):[];
const levelNow=a?await reputation(db,actor,now):0,cooldownUntil=lock?.last_offer_at===null||lock?.last_offer_at===undefined?null:Number(lock.last_offer_at)+POLICY.officeCooldownMs;
return{office:officeKey,name:faithPOL(officeKey).name,canManage:!!a,canExecute:!!a&&levelNow>=5&&(!cooldownUntil||now>=cooldownUntil),levelNow,clans,offers:offers.filter(o=>!a?.clanIds||a.clanIds.includes(o.clan_id)),cooldownUntil,policy:POLICY};
}
async function eligibleClans(actor,officeKey){const state=await office(actor,officeKey);if(!state.canExecute)return[];const now=clock(),eligible=[];for(const clan of state.clans){if((await currentClanFaith(db,clan.id)).faith===officeKey||await isOutlawed(db,clan.id,officeKey,now))continue;eligible.push(clan);}return eligible;}
async function clan(actor,clanId){if(!validUuid(clanId))fail('Choose a clan.',400);const deed=await readClanDeed(db,clanId),owner=deed.owner?.id===actor.id,faith=await currentClanFaith(db,clanId),offers=owner?await db.query("SELECT o.request_id,o.office_key,o.expires_at FROM jarvis_faith_offers o JOIN organisation_keys k ON k.id=o.key_id AND k.revoked_at IS NULL WHERE o.clan_id=? AND o.state='open' AND o.expires_at>? ORDER BY o.created_at DESC",[clanId,clock()]):[];return{clanId,name:deed.clan.name,...faith,canManage:owner,offers,cooldownUntil:faith.changedAt===null?null:faith.changedAt+POLICY.clanCooldownMs,policy:POLICY};}
async function offer(actor,input){
if(!exact(input,'clanId,confirmed,decisionId,requestId')||input.confirmed!==true||!validUuid(input.requestId)||!validUuid(input.clanId)||!clanFaithDecision(input.decisionId))fail('Review the faith invitation.',400);if(!keys)fail('Key service unavailable.',503);
const d=clanFaithDecision(input.decisionId),hash=digest([actor.id,d.id,input.clanId]);
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:faith-offer:'+input.requestId,authorize:async(raw,{keyId})=>{const tx=boardReadStore(raw,db),now=clock(),a=await faithAuthority(tx,d.office,actor,now,{clanId:input.clanId,lock:true});if(!a)fail('A current faith leader or appointed officer is required.',403);
const clan=await tx.first('SELECT id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[input.clanId]);if(!clan)fail('Active clan required.',404);
const lock=await tx.first('SELECT last_offer_at FROM jarvis_faith_office_locks WHERE office_key=? FOR UPDATE',[d.office]),prior=await tx.first('SELECT * FROM jarvis_faith_offers WHERE request_id=?',[input.requestId]);if(prior){if(prior.actor_id!==actor.id||prior.input_hash!==hash)fail('Invitation reference already used.');return;}
if(lock?.last_offer_at!==null&&lock?.last_offer_at!==undefined&&now<Number(lock.last_offer_at)+POLICY.officeCooldownMs)fail('This faith’s invitation decision is on cooldown.');
if(await reputation(tx,actor,now)<d.level)fail('Reputation level '+d.level+' is required.',403);
if((await currentClanFaith(tx,input.clanId)).faith===d.faith)fail('This clan already follows this faith.');if(await isOutlawed(tx,input.clanId,d.faith,now))fail('Missionary activity for this faith is outlawed on the clan’s homeworld.',403);
await tx.query("INSERT INTO jarvis_faith_offers(request_id,key_id,office_key,source_term_id,actor_id,clan_id,input_hash,state,created_at,expires_at) VALUES(?,?,?,?,?,?,?,'open',?,?)",[input.requestId,keyId,d.office,a.termId,actor.id,input.clanId,hash,now,now+POLICY.offerDurationMs]);await tx.query('UPDATE jarvis_faith_office_locks SET last_offer_at=? WHERE office_key=?',[now,d.office]);
}});return{ok:true,requestId:input.requestId,...await office(actor,d.office)};
}
async function reply(actor,input){
if(!exact(input,'choice,clanId,confirmed,offerId,requestId')||input.confirmed!==true||!validUuid(input.requestId)||!validUuid(input.clanId)||!validUuid(input.offerId)||!['accept','decline'].includes(input.choice))fail('Confirm a clan faith choice.',400);if(!keys)fail('Key service unavailable.',503);const hash=digest([actor.id,input.clanId,input.offerId,input.choice]);
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:clan-faith:'+input.requestId,authorize:async(raw,{keyId})=>{const tx=boardReadStore(raw,db),now=clock(),offer=await tx.first('SELECT * FROM jarvis_faith_offers WHERE request_id=? AND clan_id=?',[input.offerId,input.clanId]);if(!offer)fail('Faith invitation not found.',404);
const a=await faithAuthority(tx,offer.office_key,{id:offer.actor_id},now,{clanId:input.clanId,lock:true});await legalClanOwner(tx,actor,input.clanId);
const prior=await tx.first('SELECT * FROM jarvis_faith_consents WHERE request_id=?',[input.requestId]);if(prior){if(prior.actor_id!==actor.id||prior.input_hash!==hash)fail('Consent reference already used.');return;}
const current=await tx.first('SELECT * FROM jarvis_faith_offers WHERE request_id=? FOR UPDATE',[input.offerId]),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 FOR SHARE",[offer.key_id,STAFF_OFFICE_ACCOUNT_ID,'state:faith-offer:'+input.offerId]);
if(!a||a.termId!==offer.source_term_id||!key||current.state!=='open'||Number(current.expires_at)<=now)fail('This invitation expired or its faith authority changed.');
const faith=await currentClanFaith(tx,input.clanId);if(input.choice==='accept'){
if(faith.changedAt!==null&&now<faith.changedAt+POLICY.clanCooldownMs)fail('The clan’s seven-day faith cooldown has not elapsed.');if(await isOutlawed(tx,input.clanId,offer.office_key,now))fail('This faith is outlawed on the clan’s homeworld.',403);
await tx.query('INSERT INTO jarvis_clan_faith(clan_id,faith_key,request_id,changed_at) VALUES(?,?,?,?) ON DUPLICATE KEY UPDATE faith_key=VALUES(faith_key),request_id=VALUES(request_id),changed_at=VALUES(changed_at)',[input.clanId,offer.office_key,input.requestId,now]);
}
await tx.query('INSERT INTO jarvis_faith_consents(request_id,key_id,offer_id,clan_id,actor_id,faith_key,choice,input_hash,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[input.requestId,keyId,input.offerId,input.clanId,actor.id,offer.office_key,input.choice,hash,now]);await tx.query('UPDATE jarvis_faith_offers SET state=? WHERE request_id=?',[input.choice==='accept'?'accepted':'declined',input.offerId]);
}});return{ok:true,requestId:input.requestId,...await clan(actor,input.clanId)};
}
return{office,eligibleClans,clan,offer,reply};
}
export function createClanFaithAPI(db,keys,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=a=>accessFor(db,a),service=createClanFaith(db,keys)}={}){
const response=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
return async request=>{try{const actor=await authenticate(request);if(!actor)return response({message:'Sign in first.'},401);if(!(await access(actor)).nodes.includes('web.menu.game'))return response({message:'Player access required.'},403);const url=new URL(request.url);
if(request.method==='GET'){if(url.searchParams.size!==1)return response({message:'Choose one clan or faith office.'},400);if(url.searchParams.has('clanId'))return response(await service.clan(actor,url.searchParams.get('clanId')));if(url.searchParams.has('office'))return response(await service.office(actor,url.searchParams.get('office')));return response({message:'Unknown faith view.'},400);}
if(request.method!=='POST')return response({message:'Method not allowed.'},405);if(url.search||request.headers.get('origin')!==origin)return response({message:'Origin or query rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return response({message:'JSON required.'},415);const raw=await request.text();if(raw.length>2048)return response({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return response({message:'Invalid faith decision.'},400);}const action=input?.action;if(!['offer','reply'].includes(action))return response({message:'Unknown faith action.'},400);const {action:_,...body}=input;return response(await service[action](actor,body));
}catch(e){return response({message:e.status?e.message:'Faith decision was not confirmed. Refresh before retrying.'},e.status||503);}};
}