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

47 lines
5.4 KiB
JavaScript

import {createHash} from 'node:crypto';
import {validUuid} from './game-link.mjs';
import {researchScopes,researchAuthority,researchClaims} from './organisation-research.mjs';
import {researchUnlocked} from '../control-panel/public/organisation-research-policy.mjs';
import {organisationRefitPlan,ORGANISATION_REFIT_POLICY} from '../control-panel/public/organisation-refit-policy.mjs';
import {politicalOfficeId} from './political-office-charters.mjs';
import {NATIVE_SERVERS} from './native-server-scope.mjs';
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
const exact=(row,names)=>row&&typeof row==='object'&&!Array.isArray(row)&&Object.keys(row).length===names.length&&names.every(n=>Object.hasOwn(row,n));
const first=async(store,sql,args=[])=> (await store.query(sql,args))[0]||null;
export function refitSnapshot(input,requestId){
if(!exact(input,['fingerprint','slot','instanceId','revision','amount','kind','equipmentMark','quality','material','enchantments'])||!validUuid(requestId)||!/^([a-f0-9]{64})$/.test(input.fingerprint)||!Number.isInteger(input.slot)||input.slot<0||input.slot>8||input.amount!==1)throw TypeError('Hold one supported original item.');
if(input.instanceId!==null&&!/^[a-f0-9-]{36}:[0-9]{1,4}$/i.test(input.instanceId))throw TypeError('Registered original item identity required.');
if(input.instanceId===null&&input.revision!==1)throw TypeError('Unregistered original item revision.');
if(!input.enchantments||typeof input.enchantments!=='object'||Array.isArray(input.enchantments)||Object.keys(input.enchantments).length>32)throw TypeError('Verified equipment enchantments required.');
return {...input,instanceId:input.instanceId||requestId.toLowerCase()+':0'};
}
export function createGameRefits(db,keys,{clock=Date.now}={}){
async function list(actor){return{ok:true,owners:await researchScopes(db,actor,{clock})};}
async function context(store,actor,input){
if(!exact(input.owner,['kind','id'])||!['clan','company','politics','office'].includes(input.owner.kind)||!await researchAuthority(db,store,actor,input.owner,{clock}))throw Error('Current organisation specialist authority required.');
const link=await first(store,'SELECT user_id FROM site_game_links WHERE LOWER(minecraft_uuid)=? FOR UPDATE',[input.uuid.toLowerCase()]);if(link?.user_id!==actor.id)throw Error('Current Minecraft identity required.');
const seasons=await store.query("SELECT season_id FROM jarvis_pol_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[clock(),clock()]);if(seasons.length!==1)throw Error('Current POL season required.');
const rep=await first(store,'SELECT level_no FROM jarvis_pol_progression_accounts WHERE account_id=? FOR UPDATE',[actor.id]),snapshot=refitSnapshot(input.snapshot,input.requestId),owner=input.owner;
let tag,id=owner.id,kind=owner.kind;
if(kind==='clan')tag=(await first(store,'SELECT tag FROM site_clans WHERE id=? AND active=1',[id]))?.tag;
else if(kind==='company')tag=(await first(store,"SELECT name FROM corrino_companies WHERE id=? AND status='active'",[id]))?.name;
else{kind='politics';tag=owner.id;id=politicalOfficeId(owner.id);}
tag=String(tag||'').replace(/[^A-Za-z0-9_-]/g,'').slice(0,16);if(!tag)throw Error('Registered organisation name required.');
const plan=organisationRefitPlan(snapshot,{organisation:{kind,id,tag},reputationLevel:Number(rep?.level_no||1),season:'S'+Number(seasons[0].season_id.slice(1)),maxMark:14});
if(!researchUnlocked(plan.output,await researchClaims(store,actor.id,seasons[0].season_id),owner))throw Error('Quest research must unlock the target rarity and MK for this specialist and organisation.');
return{policy:ORGANISATION_REFIT_POLICY,accountId:actor.id,uuid:input.uuid.toLowerCase(),requestId:input.requestId,server:input.server,npcUuid:input.npcUuid,snapshot:input.snapshot,plan};
}
async function prepare(actor,input){
if(!validUuid(input.uuid)||!validUuid(input.requestId)||!validUuid(input.npcUuid)||!NATIVE_SERVERS.includes(input.server))throw TypeError('Visit the current quartermaster.');
// Outer validation also runs for an idempotent key replay.
const result=await context(db,actor,input),fingerprint=hash(result),expiresAt=clock()+30000;
await keys.issue({accountId:actor.id,keyType:'organisation-action',scopeId:'game:'+input.requestId,authorize:async(tx,{keyId})=>{
if(hash(await context(tx,actor,input))!==fingerprint)throw Error('The refit authority or equipment profile changed.');
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(?,?,?,?,?,?,?,?,?,?)',[input.requestId,keyId,actor.id,input.uuid.toLowerCase(),'refit',fingerprint,JSON.stringify(result),'prepared',expiresAt,clock()]);
}});
const saved=await first(db,"SELECT result_json,input_hash,expires_at FROM jarvis_game_organisation_actions WHERE request_id=? AND account_id=? AND action_id='refit'",[input.requestId,actor.id]);
if(!saved||saved.input_hash!==fingerprint||hash(JSON.parse(saved.result_json))!==fingerprint||Number(saved.expires_at)<=clock())throw Error('The refit instruction changed or expired. Reopen the workshop.');
return{ok:true,allowed:true,action:'prepare_refit',playerUuid:result.uuid,requestId:input.requestId,server:input.server,npcUuid:input.npcUuid,expiresAt:Number(saved.expires_at),instructionHash:fingerprint,snapshot:result.snapshot,plan:result.plan};
}
return{list,prepare};
}