MC/website/node/jarvis-master-generator.mjs

62 lines
7.1 KiB
JavaScript

import {assertWebIssuableMaster} from './jarvis-web-key-boundary.mjs';
import {hashOrganisationKey} from './organisation-keys.mjs';
import {createHash,randomUUID} from 'node:crypto';
import {MASTER_KEY_TEMPLATES,masterAction,validateMasterFields} from '../control-panel/public/jarvis-master-keys.mjs';
export const GENERATOR_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_generated_instructions(key_id CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,account_id CHAR(36) NOT NULL,action_id VARCHAR(80) NOT NULL,template_version INTEGER NOT NULL,fields_json TEXT NOT NULL,manifest_json MEDIUMTEXT NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL)`;
export const PROTECTED_RESET_TARGETS=Object.freeze(['113e9471-6288-43d6-ad8e-25286964413f','b82339e5-a2d4-4335-85de-463fd3ee827f']);
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
export async function initializeJarvisGenerator(db,{mysql=true}={}){
await db.query(GENERATOR_SCHEMA);
if(mysql){const column=await db.first("SELECT IS_NULLABLE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='site_clans' AND COLUMN_NAME='owner_id'");if(column?.IS_NULLABLE==='NO')await db.query('ALTER TABLE site_clans MODIFY owner_id CHAR(36) NULL');}
db.jarvisGeneratorEnabled=true;
}
async function snapshot(tx){
const targets=[];
for(const id of PROTECTED_RESET_TARGETS){
const clan=await tx.first('SELECT id,name,owner_id,active,version FROM site_clans WHERE id=? FOR UPDATE',[id]);
const institution=await tx.first('SELECT institution_key FROM site_clan_institutions WHERE clan_id=? FOR UPDATE',[id]);
if(!clan||Number(clan.active)!==1||!institution||!['bene','guild'].includes(institution.institution_key))throw Error('Protected clan identity changed');
const members=await tx.query('SELECT user_id,clan_role FROM site_clan_members WHERE clan_id=? ORDER BY user_id FOR UPDATE',[id]);
targets.push({...clan,institution:institution.institution_key,members});
}
return {targets,inventoryHash:hash(targets),preserve:['clans','claims','POL','Crysknife','companies','balances']};
}
export function createMasterKeyGenerator(db,keys,{authorize,clock=Date.now}){
const permitted=async(actor,node)=>{if(!actor?.id||!await authorize(actor,node))throw Error('Masterkey authority required');};
async function availableCode(result,accountId){const record=(await keys.list(accountId)).find(k=>k.id===result.id);return {keyId:result.id,code:record?.status==='available'?record.code:null,status:record?.status||'unavailable',created:result.created};}
return Object.freeze({
async catalogue(actor){await permitted(actor,'web.jarvis.keys.view');const reset=await authorize(actor,'web.jarvis.clans.reset');return {templates:MASTER_KEY_TEMPLATES.map(t=>({...t,actions:t.actions.map(a=>({...a,available:a.webIssue===true&&reset===true}))})),recipient:actor.username};},
async issue(actor,{actionId,templateVersion,values,requestId}){
const action=masterAction(actionId);assertWebIssuableMaster(action);if(!action||action.version!==templateVersion||!action.webIssue||!uuid(requestId))throw Error('Choose a connected masterkey action');
await permitted(actor,action.permission);const fields=validateMasterFields(action,values),encoded=JSON.stringify(fields);
const prior=await db.first('SELECT * FROM jarvis_generated_instructions WHERE request_id=?',[requestId]);
if(prior){if(prior.account_id!==actor.id||prior.action_id!==actionId||prior.fields_json!==encoded)throw Error('Instruction reference conflict');return availableCode({id:prior.key_id,created:false},actor.id);}
const result=await keys.issue({accountId:actor.id,keyType:'clan-administration',scopeId:'protected-roster:'+requestId,expiresAt:clock()+86400000,authorize:async(tx,{keyId})=>{
await permitted(actor,action.permission);const manifest=await snapshot(tx);
await tx.query('INSERT INTO jarvis_generated_instructions(key_id,request_id,account_id,action_id,template_version,fields_json,manifest_json,state,created_at) VALUES(?,?,?,?,?,?,?,\'issued\',?)',[keyId,requestId,actor.id,actionId,templateVersion,encoded,JSON.stringify(manifest),clock()]);
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'jarvis-key-generated',JSON.stringify({keyId,actionId,requestId,manifestHash:manifest.inventoryHash}),clock()]);
}});const stored=await db.first('SELECT fields_json FROM jarvis_generated_instructions WHERE key_id=? AND account_id=?',[result.id,actor.id]);if(!stored||stored.fields_json!==encoded)throw Error('Instruction reference conflict');return availableCode(result,actor.id);
},
async redeem(actor,{code,requestId}){
await permitted(actor,'web.jarvis.clans.reset');if(typeof code!=='string'||!uuid(requestId))throw TypeError('Enter the generated key');
const own=await db.first('SELECT id FROM organisation_keys WHERE account_id=? AND key_type=? AND code_hash=?',[actor.id,'clan-administration',hashOrganisationKey(code,'clan-administration')]);if(!own)throw Error('Key unavailable for this account');
const instruction=await db.first('SELECT * FROM jarvis_generated_instructions WHERE key_id=? AND account_id=?',[own.id,actor.id]);if(!instruction)throw Error('Instruction unavailable');
return keys.consume({accountId:actor.id,keyType:'clan-administration',code,targetId:instruction.request_id,requestId,apply:async(tx,{keyId,scopeId})=>{
await permitted(actor,'web.jarvis.clans.reset');
const row=await tx.first('SELECT * FROM jarvis_generated_instructions WHERE key_id=? AND account_id=? FOR UPDATE',[keyId,actor.id]);
if(!row||row.state!=='issued'||row.action_id!=='clan.clear-protected-rosters'||Number(row.template_version)!==1||scopeId!=='protected-roster:'+row.request_id)throw Error('Instruction scope changed');
const original=JSON.parse(row.manifest_json),current=await snapshot(tx);if(!equal(original,current))throw Error('Clan inventory changed; generate a fresh instruction');
for(const clan of current.targets){
await tx.query('DELETE FROM site_clan_members WHERE clan_id=?',[clan.id]);
await tx.query('UPDATE site_clans SET owner_id=NULL,version=version+1,updated_at=? WHERE id=?',[clock(),clan.id]);
await tx.query('UPDATE site_clan_deeds SET heir_account_id=NULL,consort_account_id=NULL,heir_joined_at=NULL,consort_joined_at=NULL,envoy_account_id=NULL,envoy_joined_at=NULL,arms_account_id=NULL,arms_joined_at=NULL,version=version+1,updated_at=? WHERE clan_id=?',[clock(),clan.id]);
await tx.query("UPDATE site_clan_requests SET status='closed',updated_at=? WHERE clan_id=? AND status='pending'",[clock(),clan.id]);
}
await tx.query("UPDATE jarvis_generated_instructions SET state='completed' WHERE key_id=?",[keyId]);
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'jarvis-protected-rosters-cleared',JSON.stringify({keyId,targets:PROTECTED_RESET_TARGETS,membersRemoved:current.targets.reduce((n,c)=>n+c.members.length,0),ownersVacated:true}),clock()]);
}});
}
});
}