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

89 lines
11 KiB
JavaScript
Raw 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 {clanKitAuthority} from './clan-deeds.mjs';
import {readCompanyDeed,companyDeedView} from './company-deeds.mjs';
import {boardReadStore} from './board-deed-source.mjs';
import {PUBLIC_OFFICES} from './public-government.mjs';
import {currentOfficeController} from './entity-relations.mjs';
import {politicalOfficeId} from './political-office-charters.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {RESEARCH_POLICY,RESEARCH_COOLDOWN_MS,researchNode,researchId,researchUnlocked} from '../control-panel/public/organisation-research-policy.mjs';
import {validUuid} from './game-link.mjs';
import {NATIVE_SERVERS} from './native-server-scope.mjs';
import {isResearchSpecialist} from './research-specialists.mjs';
import {researchSupplyDefinitions,supplyItemDefinition} from './research-supplies.mjs';
const first=async(tx,sql,args=[])=>(await tx.query(sql,args))[0]||null;
const digest=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
const uuid=v=>{const h=digest(v);return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);};
export async function researchAuthority(base,store,actor,owner,{clock=Date.now}={}){
const r=boardReadStore(store,base);r.readSnapshot=undefined;
try{
if(!validUuid(actor?.id)||!owner||!['clan','company','politics','office'].includes(owner.kind))return false;
if(owner.kind==='clan')return validUuid(owner.id)&&(await clanKitAuthority(r,actor.id,owner.id)).canGenerate;
if(owner.kind==='company'){if(!validUuid(owner.id))return false;const deed=await readCompanyDeed(r,owner.id);return deed.company.status==='active'&&(companyDeedView(deed,actor.id).canManage||await isResearchSpecialist(base,store,actor,owner,{clock}));}
if(!PUBLIC_OFFICES.some(o=>o.key===owner.id))return false;
if((await currentOfficeController(r,owner.id,clock()))?.userId!==actor.id)return isResearchSpecialist(base,store,actor,owner,{clock});
return !!await r.first("SELECT c.staff_key_id FROM political_office_charters c JOIN organisation_keys k ON k.id=c.staff_key_id WHERE c.office_key=? AND c.organisation_id=? AND c.charter_kind='royal' AND k.account_id=? AND k.key_type='staff-office-royal' AND k.scope_id=? AND k.target_id=c.organisation_id AND k.used_at IS NOT NULL AND k.revoked_at IS NULL",[owner.id,politicalOfficeId(owner.id),STAFF_OFFICE_ACCOUNT_ID,'office:'+owner.id]);
}catch(error){if([403,404,409].includes(error.status))return false;throw error;}
}
export async function researchScopes(db,actor,options={}){
const [clans,companies]=await Promise.all([db.query('SELECT id,name FROM site_clans WHERE active=1 ORDER BY name LIMIT 1000'),db.query("SELECT id,name FROM corrino_companies WHERE status='active' ORDER BY name LIMIT 1000")]);
const candidates=[...clans.map(c=>({kind:'clan',id:c.id,label:c.name+' · Clan'})),...companies.map(c=>({kind:'company',id:c.id,label:c.name+' · Company'})),...PUBLIC_OFFICES.flatMap(o=>[{kind:'politics',id:o.key,label:o.scope+' · POL'},{kind:'office',id:o.key,label:o.name+' · Office'}])],out=[];
for(const owner of candidates)try{if(await researchAuthority(db,db,actor,owner,options))out.push(owner);}catch(e){if(![403,404,409].includes(e.status))throw e;}
return out;
}
export function researchDefinitions(owner,{season='S01'}={}){
const result=[];
for(const kind of ['mark','quality'])for(let tier=0;tier<=(kind==='mark'?14:4);tier++){
const node=researchNode(kind,tier),id=researchId(owner,node),previous=tier?researchId(owner,researchNode(kind,tier-1)):null;
result.push({...node,id,owner,season,title:owner.label+' · Research '+node.label,objective:'As the current organisation specialist, reach Reputation level '+node.reputationLevel+' and surrender '+node.samples.map(s=>s.quantity+' '+s.material.replaceAll('_',' ')).join(', ')+' to Gurney Halleck in game. Claim this quest to unlock '+node.label+' for your own designs for this organisation. One hour between research claims. Reward: '+node.xp+' Reputation XP, '+node.personalXP+' Personal XP and '+(node.amountMinor/100)+' DM to the organisation.',branch:'rd',metric:id.toLowerCase(),target:1,requires:previous?[previous]:[],requiresAny:[],revision:1,research:true,verifiedOnly:true,optional:false,issuer:'gurney_halleck',issuerName:'Gurney Halleck',xpType:'pol',executionRequirements:{website:true,minecraft:true}});
}return result;
}
export async function currentResearchDefinitions(db,actor,options={}){
if(!db.organisationResearchEnabled)return[];
const definitions=[];for(const owner of await researchScopes(db,actor,options)){definitions.push(...researchDefinitions(owner));if(db.researchSuppliesEnabled)definitions.push(...await researchSupplyDefinitions(db,actor,owner,options));}return definitions;
}
export async function researchClaims(store,accountId,season='S01'){
return new Set((await store.query("SELECT s.definition_id FROM jarvis_pol_quest_states s JOIN jarvis_pol_quest_claims c ON c.key_id=s.key_id JOIN organisation_keys k ON k.id=s.key_id WHERE s.account_id=? AND s.season_id=? AND s.state='claimed' AND s.definition_id LIKE 'RD-%' AND k.used_at IS NOT NULL AND k.revoked_at IS NULL",[accountId,season])).map(r=>r.definition_id));
}
export async function validateResearchDesign(base,store,actor,design){
if(!await researchAuthority(base,store,actor,design.owner))throw Error('Current organisation specialist authority required.');
const claimed=await researchClaims(store,actor.id);
for(const row of design.items)if(!researchUnlocked(row.design,claimed,design.owner))throw TypeError('Complete this organisation specialist’s rarity and MK research quests before saving or publishing this kit.');
}
export async function researchEvidence(store,accountId,season='S01'){
const rows=await store.query("SELECT a.request_id,a.result_json FROM jarvis_game_organisation_actions a JOIN organisation_keys k ON k.id=a.key_id AND k.account_id=a.account_id AND k.key_type='organisation-action' AND k.revoked_at IS NULL AND k.scope_id=CONCAT('game:',a.request_id) WHERE a.account_id=? AND a.action_id='research' AND a.state='recorded' ORDER BY a.created_at LIMIT 2000",[accountId]),totals=new Map(),proofIds=[];
for(const row of rows){const p=JSON.parse(row.result_json);if(p.policy!==RESEARCH_POLICY||p.accountId!==accountId||p.seasonId!==season)continue;totals.set(p.definitionId.toLowerCase(),1);proofIds.push(row.request_id);}return{totals,proofIds};
}
export async function authorizeResearchClaim(base,tx,actor,d,{clock=Date.now}={}){
if(!d.research||!await researchAuthority(base,tx,actor,d.owner,{clock}))return false;
const state=await first(tx,'SELECT level_no FROM jarvis_pol_progression_accounts WHERE account_id=? FOR UPDATE',[actor.id]);
if(Number(state?.level_no||1)<d.reputationLevel)return false;
const prior=await first(tx,"SELECT MAX(c.claimed_at) claimed_at FROM jarvis_pol_quest_claims c JOIN jarvis_pol_quest_states s ON s.key_id=c.key_id WHERE c.account_id=? AND s.definition_id LIKE 'RD-%'",[actor.id]);
if(prior?.claimed_at!=null&&Number(prior.claimed_at)+RESEARCH_COOLDOWN_MS>clock())throw Error('Quest research cooldown is active. Wait one hour after your previous research claim.');
return (await researchEvidence(tx,actor.id,d.season)).totals.get(d.metric)===1;
}
// Prepared ordinary Jarvis actions use the existing native inventory transaction
// and receipt queue. A browser cannot manufacture the corresponding observation.
export function createGameResearch(db,keys,{clock=Date.now}={}){
async function prepare(actor,input){
if(!validUuid(input.uuid)||!validUuid(input.npcUuid)||!NATIVE_SERVERS.includes(input.server))throw TypeError('Visit the quest quartermaster.');
const d=(await currentResearchDefinitions(db,actor,{clock,requestedDefinitionId:input.definitionId})).find(d=>d.id===input.definitionId);if(!d)throw Error('Current organisation specialist authority required.');
if(d.tokenId){const claimed=await researchClaims(db,actor.id,d.season);if(!d.requires.every(id=>claimed.has(id)))throw Error('Quest requires the preceding organisation research.');}
const rep=await first(db,'SELECT level_no FROM jarvis_pol_progression_accounts WHERE account_id=?',[actor.id]);if(Number(rep?.level_no||1)<d.reputationLevel)throw Error('Quest requires Reputation level '+d.reputationLevel+'.');
const requestId=uuid([RESEARCH_POLICY,actor.id,d.season,d.id]),result={policy:RESEARCH_POLICY,requestId,accountId:actor.id,uuid:input.uuid.toLowerCase(),seasonId:d.season,definitionId:d.id,owner:{kind:d.owner.kind,id:d.owner.id},samples:d.samples,...(d.tokenId?{tokenId:d.tokenId}: {})};
await keys.issue({accountId:actor.id,keyType:'organisation-action',scopeId:'game:'+requestId,authorize:async(tx,{keyId})=>{
if(!await researchAuthority(db,tx,actor,d.owner,{clock}))throw Error('Current organisation specialist authority required.');
const linked=await first(tx,'SELECT user_id FROM site_game_links WHERE LOWER(minecraft_uuid)=? FOR UPDATE',[result.uuid]);if(linked?.user_id!==actor.id)throw Error('Current Minecraft identity required.');
await tx.query('INSERT INTO jarvis_game_organisation_actions(request_id,key_id,account_id,minecraft_uuid,action_id,input_hash,result_json,state,expires_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',[requestId,keyId,actor.id,result.uuid,'research',digest(result),JSON.stringify(result),'prepared',0,clock()]);
}});
const saved=await first(db,"SELECT result_json FROM jarvis_game_organisation_actions WHERE request_id=? AND account_id=? AND action_id='research'",[requestId,actor.id]);if(!saved||digest(JSON.parse(saved.result_json))!==digest(result))throw Error('Quest research instruction requires review.');
return{ok:true,allowed:true,action:'prepare_research',playerUuid:result.uuid,requestId,npcUuid:input.npcUuid,server:input.server,expiresAt:clock()+30000,samples:d.samples,instructionHash:digest(result),...(d.tokenId?{tokenId:d.tokenId,tokenDefinition:supplyItemDefinition(d.tokenId)}:{})};
}
async function record(input){
if(!validUuid(input.eventId)||!validUuid(input.uuid)||!NATIVE_SERVERS.includes(input.server)||input.kind!=='research_submitted'||!Number.isSafeInteger(input.occurredAt)||input.occurredAt<=0||input.occurredAt>clock()+30000)throw TypeError('Verified native research receipt required.');
return db.transaction(async tx=>{const row=await first(tx,"SELECT a.* FROM jarvis_game_organisation_actions a JOIN organisation_keys k ON k.id=a.key_id AND k.account_id=a.account_id AND k.key_type='organisation-action' AND k.revoked_at IS NULL WHERE a.request_id=? AND a.action_id='research' FOR UPDATE",[input.eventId]);if(!row||row.minecraft_uuid!==input.uuid.toLowerCase()||input.occurredAt<Number(row.created_at))throw Error('Verified research instruction required.');
const link=await first(tx,'SELECT user_id FROM site_game_links WHERE LOWER(minecraft_uuid)=?',[input.uuid]);if(link?.user_id!==row.account_id)throw Error('Current research identity required.');
await tx.query("UPDATE jarvis_game_organisation_actions SET state='recorded' WHERE request_id=? AND state='prepared'",[input.eventId]);return{ok:true,eventId:input.eventId};});
}
return{prepare,record};
}