import {assertWebIssuableMaster} from './jarvis-web-key-boundary.mjs'; import {hashOrganisationKey} from './organisation-keys.mjs'; import {parseOrganisationCode} from '../control-panel/public/codex-code-format.mjs'; import {TEST_IDENTITY_SCHEMA,TEST_IDENTITY_ACTION,TEST_IDENTITY_PERMISSION,prepareTestIdentity,applyTestIdentity} from './account-test-identity.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); const first=(db,sql,args=[])=>db.prepare(sql).bind(...args).first(); export async function initializeJarvisGenerator(db,{mysql=true}={}){ await db.query(GENERATOR_SCHEMA); await db.query(TEST_IDENTITY_SCHEMA); if(mysql){const column=await first(db,"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 * 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 * FROM site_clan_members WHERE clan_id=? ORDER BY user_id FOR UPDATE',[id]); const deed=await tx.first('SELECT * FROM site_clan_deeds WHERE clan_id=? FOR UPDATE',[id]); const requests=await tx.query("SELECT * FROM site_clan_requests WHERE clan_id=? AND status='pending' ORDER BY user_id FOR UPDATE",[id]); targets.push({...clan,institution:institution.institution_key,members,deed,requests}); } 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');return {templates:await Promise.all(MASTER_KEY_TEMPLATES.map(async t=>({...t,actions:await Promise.all(t.actions.map(async a=>({...a,available:a.webIssue===true&&await authorize(actor,a.permission)===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'); if(!['clan.clear-protected-rosters',TEST_IDENTITY_ACTION].includes(actionId))throw Error('Choose a connected domain adapter'); await permitted(actor,action.permission);const fields=validateMasterFields(action,values),encoded=JSON.stringify(fields); const prior=await first(db,'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 accountAction=actionId===TEST_IDENTITY_ACTION,scopePrefix=accountAction?'test-identity:':'protected-roster:'; const result=await keys.issue({accountId:actor.id,keyType:action.keyType,scopeId:scopePrefix+requestId,expiresAt:clock()+86400000,authorize:async(tx,{keyId})=>{ await permitted(actor,action.permission);const manifest=accountAction?await prepareTestIdentity(tx,fields.accountName):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,ticketId:fields.ticketId,manifestHash:hash(manifest)}),clock()]); }});const stored=await first(db,'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}){ if(typeof code!=='string'||!uuid(requestId))throw TypeError('Enter the generated key'); const accountAction=parseOrganisationCode(code).prefix==='ACC-TEST',keyType=accountAction?'account-test-identity':'clan-administration',permission=accountAction?TEST_IDENTITY_PERMISSION:'web.jarvis.clans.reset',actionId=accountAction?TEST_IDENTITY_ACTION:'clan.clear-protected-rosters',scopePrefix=accountAction?'test-identity:':'protected-roster:'; await permitted(actor,permission); const own=await first(db,'SELECT id FROM organisation_keys WHERE account_id=? AND key_type=? AND code_hash=?',[actor.id,keyType,hashOrganisationKey(code,keyType)]);if(!own)throw Error('Key unavailable for this account'); const instruction=await first(db,'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,code,targetId:instruction.request_id,requestId,apply:async(tx,{keyId,scopeId})=>{ await permitted(actor,permission); 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!==actionId||Number(row.template_version)!==1||scopeId!==scopePrefix+row.request_id)throw Error('Instruction scope changed'); if(accountAction){ const manifest=JSON.parse(row.manifest_json),fields=JSON.parse(row.fields_json); if(manifest.account?.username.toLowerCase()!==fields.accountName.toLowerCase())throw Error('Instruction account scope changed'); await applyTestIdentity(tx,manifest,{keyId,actorId:actor.id,now:clock()}); await tx.query("UPDATE jarvis_generated_instructions SET state='completed' WHERE key_id=?",[keyId]); return; } 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()]); }}); } }); }