web/website/node/staff-homeblock-keys.mjs
2026-11-21 20:22:37 +01:00

38 lines
5.1 KiB
JavaScript

import {createHash,randomUUID} from 'node:crypto';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
const action='claims.remove-homeblock',uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const first=async(db,sql,args=[])=>db.first?db.first(sql,args):(await db.query(sql,args))[0]||null;
const hash=v=>createHash('sha256').update(v).digest('hex');
const fail=message=>{throw Error(message);};
// Ordinary staff overwrite key: no control panel, timer, election reset or war
// controller. Removing the marker makes existing Home Block rules deny the chain.
export function createStaffHomeBlockKeys(db,keys,{authorizeStaff,clock=Date.now}={}){
if(typeof authorizeStaff!=='function')throw TypeError('Existing staff overwrite authority adapter required');
async function allowed(actor,store){if(!uuid(actor?.id)||await authorizeStaff(actor,store)!==true)fail('Current staff overwrite authority required');}
return Object.freeze({
async issue(actor,input){
await allowed(actor,db);if(!input||Object.keys(input).some(k=>!['kind','id','expectedRevision','ticketId','reason','requestId'].includes(k))||!['clan','company','protected'].includes(input.kind)||!uuid(input.id)||!uuid(input.requestId)||!Number.isSafeInteger(input.expectedRevision)||input.expectedRevision<1||typeof input.ticketId!=='string'||!input.ticketId.trim()||input.ticketId.length>80||typeof input.reason!=='string'||input.reason.trim().length<5||input.reason.length>500)throw TypeError('Choose the Home Block, current revision and staff ticket reason');
const fields={kind:input.kind,id:input.id,expectedRevision:input.expectedRevision,ticketId:input.ticketId.trim(),reason:input.reason.trim()},scope='homeblock:'+input.kind+':'+input.id+':'+input.requestId;
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-claim',scopeId:scope,authorize:async(tx,{keyId})=>{
await allowed(actor,tx);const prior=await tx.first('SELECT fields_json,manifest_json FROM jarvis_generated_instructions WHERE request_id=?',[input.requestId]);if(prior){if(prior.fields_json!==JSON.stringify(fields)||JSON.parse(prior.manifest_json).actorId!==actor.id)fail('Staff Home Block reference conflict');return;}
const row=await tx.first('SELECT * FROM site_claim_registry WHERE organisation_kind=? AND organisation_id=? FOR UPDATE',[input.kind,input.id]);if(!row||Number(row.revision)!==input.expectedRevision||!JSON.parse(row.snapshot_json).homeBlock)fail('Current Home Block revision required');
const manifest={actorId:actor.id,snapshotHash:hash(row.snapshot_json),previousHomeBlock:JSON.parse(row.snapshot_json).homeBlock};
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(?,?,?,?,1,?,?,'issued',?)",[keyId,input.requestId,actor.id,action,JSON.stringify(fields),JSON.stringify(manifest),clock()]);
}});return {keyId:grant.id,created:grant.created};
},
async apply(actor,{keyId,requestId}){
await allowed(actor,db);if(!uuid(keyId)||!uuid(requestId))throw TypeError('Choose the issued staff Home Block key');
const row=await first(db,'SELECT * FROM jarvis_generated_instructions WHERE key_id=? AND action_id=?',[keyId,action]);if(!row)fail('Staff Home Block instruction unavailable');const fields=JSON.parse(row.fields_json),manifest=JSON.parse(row.manifest_json);if(row.state==='applied'){if(manifest.receipt?.requestId!==requestId)fail('Staff Home Block execution reference conflict');return {replayed:true,...manifest.receipt};}
const key=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===keyId&&k.keyType==='staff-claim');if(!key)fail('Staff Home Block key unavailable');
return keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-claim',code:key.code,targetId:fields.id,requestId,apply:async(tx,context)=>{
await allowed(actor,tx);if(context.scopeId!=='homeblock:'+fields.kind+':'+fields.id+':'+row.request_id)fail('Staff Home Block scope mismatch');
const locked=await tx.first('SELECT * FROM site_claim_registry WHERE organisation_kind=? AND organisation_id=? FOR UPDATE',[fields.kind,fields.id]);if(!locked||Number(locked.revision)!==fields.expectedRevision||hash(locked.snapshot_json)!==manifest.snapshotHash)fail('The Home Block changed; review the staff instruction');
const snapshot=JSON.parse(locked.snapshot_json);snapshot.homeBlock=null;
await tx.query('UPDATE site_claim_registry SET snapshot_json=?,revision=revision+1,updated_at=? WHERE organisation_kind=? AND organisation_id=?',[JSON.stringify(snapshot),clock(),fields.kind,fields.id]);
manifest.receipt={keyId,requestId,kind:fields.kind,id:fields.id,revision:fields.expectedRevision+1,actorId:actor.id,appliedAt:clock()};
await tx.query("UPDATE jarvis_generated_instructions SET state='applied',manifest_json=? WHERE key_id=?",[JSON.stringify(manifest),keyId]);
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'staff-homeblock-removed',JSON.stringify({...fields,keyId,requestId}),clock()]);
}});
}
});
}