import {createHash} from 'node:crypto'; import {createBoardDeedResolver,boardReadStore} from './board-deed-source.mjs'; import {readCompanyDeed,companyDeedView} from './company-deeds.mjs'; import {politicalOfficeId} from './political-office-charters.mjs'; import {PUBLIC_OFFICES} from './public-government.mjs'; import {validUuid} from './game-link.mjs'; const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex'); const first=async(store,sql,args=[])=>(await store.query(sql,args))[0]||null; export const RESEARCH_SPECIALIST_SCHEMA='CREATE TABLE IF NOT EXISTS jarvis_research_specialists(key_id CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,organisation_kind VARCHAR(12) NOT NULL,organisation_id CHAR(36) NOT NULL,revision INT NOT NULL,account_id CHAR(36) NOT NULL,input_hash CHAR(64) NOT NULL,result_json TEXT NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY research_specialist_revision(organisation_kind,organisation_id,revision)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'; export async function initializeResearchSpecialists(db){await db.query(RESEARCH_SPECIALIST_SCHEMA);db.researchSpecialistsEnabled=true;} function organisation(owner){ if(owner?.kind==='company'&&validUuid(owner.id))return{kind:'company',id:owner.id}; if(['office','politics'].includes(owner?.kind)&&PUBLIC_OFFICES.some(o=>o.key===owner.id))return{kind:'politics',id:politicalOfficeId(owner.id)}; throw TypeError('Choose a registered company or political office. Clan specialists use the existing Master of Arms appointment.'); } async function context(base,store,owner,{clock=Date.now}={}){ const org=organisation(owner),deed=await createBoardDeedResolver(base,{clock})(store,org.kind,org.id); if(deed.organisation.lifecycle!=='active')throw Object.assign(Error('Current organisation deed required.'),{status:403}); const source={...deed.source};delete source.version; return{org,deed,sourceBinding:hash(source)}; } const latest=(store,org)=>first(store,'SELECT a.*,k.key_type,k.scope_id,k.revoked_at,k.account_id key_account FROM jarvis_research_specialists a JOIN organisation_keys k ON k.id=a.key_id WHERE a.organisation_kind=? AND a.organisation_id=? ORDER BY a.revision DESC LIMIT 1',[org.kind,org.id]); function resolved(row,c){ if(!row)return{revision:0,specialist:null};const value=JSON.parse(row.result_json),member=c.deed.policy.members.find(m=>m.id===value.userId); const active=value.policy==='research-specialist-v1'&&value.organisation.kind===c.org.kind&&value.organisation.id===c.org.id&&value.revision===Number(row.revision)&&row.key_type==='organisation-action'&&row.scope_id==='game:'+row.request_id&&row.revoked_at===null&&row.key_account===row.account_id&&value.sourceBinding===c.sourceBinding&&!!member?.binding&&member.binding===value.memberBinding; return{revision:Number(row.revision),specialist:active?{id:member.id}:null}; } async function manager(base,store,actor,owner,c){ if(c.org.kind==='politics')return c.deed.policy.managers.includes(actor.id); const deed=await readCompanyDeed(boardReadStore(store,base),owner.id);return deed.company.status==='active'&&companyDeedView(deed,actor.id).canManage; } export async function isResearchSpecialist(base,store,actor,owner,options={}){ if(!base.researchSpecialistsEnabled)return false; try{const org=organisation(owner),row=await latest(store,org);if(!row)return false;return resolved(row,await context(base,store,owner,options)).specialist?.id===actor.id;} catch(error){if([403,404,409].includes(error.status)||/^(Board |No resolved board |An unambiguous active office deed)/.test(error.message))return false;throw error;} } // An appointment is a sealed organisation-action record, not a bearer permission // or a native console command. Its projection is written in issue.authorize. export function createResearchSpecialists(db,keys,{clock=Date.now}={}){ async function read(actor,owner){ const c=await context(db,db,owner,{clock});let canManage=false;try{canManage=await manager(db,db,actor,owner,c);}catch(error){if(error.status!==403)throw error;} if(!canManage&&!c.deed.policy.members.some(member=>member.id===actor.id))throw Object.assign(Error('Current organisation membership required.'),{status:403}); const current=resolved(await latest(db,c.org),c),ids=[...new Set([...(canManage?c.deed.policy.members.map(member=>member.id):[]),current.specialist?.id].filter(Boolean))]; const people=ids.length?await db.query('SELECT id,username,display_name FROM site_accounts WHERE id IN ('+ids.map(()=>'?').join(',')+") AND password_hash NOT LIKE '!%'",ids):[]; return{owner,revision:current.revision,canManage,specialist:current.specialist?people.find(person=>person.id===current.specialist.id)||null:null,candidates:canManage?people:[]}; } async function appoint(actor,input){ if(!validUuid(actor?.id)||!validUuid(input?.requestId)||input.userId!==null&&!validUuid(input.userId)||!Number.isSafeInteger(input.revision)||input.revision<0||input.confirmed!==true)throw TypeError('Confirm the current specialist appointment.'); const org=organisation(input.owner),fingerprint=hash([actor.id,org,input.userId,input.revision]),prior=await first(db,'SELECT account_id,input_hash FROM jarvis_research_specialists WHERE request_id=?',[input.requestId]); if(prior){if(prior.account_id!==actor.id||prior.input_hash!==fingerprint)throw Error('Specialist appointment reference conflict.');return{...await read(actor,input.owner),replayed:true};} if(!keys?.issue)throw Error('Specialist appointment service unavailable.'); const grant=await keys.issue({accountId:actor.id,keyType:'organisation-action',scopeId:'game:'+input.requestId,authorize:async(tx,{keyId})=>{ await tx.first(org.kind==='company'?'SELECT company_id FROM site_company_deeds WHERE company_id=? FOR UPDATE':'SELECT organisation_id FROM political_office_charters WHERE organisation_id=? FOR UPDATE',[org.id]); const c=await context(db,tx,input.owner,{clock});if(!await manager(db,tx,actor,input.owner,c))throw Object.assign(Error('Current organisation management required.'),{status:403}); const current=resolved(await latest(tx,org),c);if(current.revision!==input.revision)throw Error('Specialist appointment changed. Refresh first.'); const member=input.userId===null?null:c.deed.policy.members.find(person=>person.id===input.userId&&person.binding); if(input.userId!==null&&(!member||!await tx.first("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[input.userId])))throw Object.assign(Error('Choose a current organisation member.'),{status:403}); const result={policy:'research-specialist-v1',organisation:org,userId:member?.id||null,memberBinding:member?.binding||null,sourceBinding:c.sourceBinding,revision:current.revision+1}; await tx.query('INSERT INTO jarvis_research_specialists(key_id,request_id,organisation_kind,organisation_id,revision,account_id,input_hash,result_json,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[keyId,input.requestId,org.kind,org.id,result.revision,actor.id,fingerprint,JSON.stringify(result),clock()]); }}); const saved=await first(db,'SELECT account_id,input_hash FROM jarvis_research_specialists WHERE key_id=?',[grant.id]);if(saved?.account_id!==actor.id||saved?.input_hash!==fingerprint)throw Error('Specialist appointment reference conflict.'); return{...await read(actor,input.owner),replayed:!grant.created}; } return{read,appoint}; }