forked from unimatrix/web
85 lines
11 KiB
JavaScript
85 lines
11 KiB
JavaScript
import {createHash,randomUUID} from 'node:crypto';
|
|
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
|
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 fail=message=>{throw Object.assign(new Error(message),{status:409});};
|
|
const text=(v,max)=>typeof v==='string'&&v.length>0&&v.length<=max&&!/[\x00-\x1f\x7f]/.test(v);
|
|
export const ENTITY_STATE_SCHEMA=Object.freeze([
|
|
`CREATE TABLE IF NOT EXISTS jarvis_entity_state_events(key_id CHAR(36) PRIMARY KEY,source VARCHAR(32) NOT NULL,event_id CHAR(36) NOT NULL,issuer_id CHAR(36) NOT NULL,target_uuid CHAR(36) NOT NULL,action VARCHAR(16) NOT NULL,scope VARCHAR(64) NOT NULL,occurred_at BIGINT NOT NULL,fingerprint CHAR(64) NOT NULL,payload_json TEXT NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY esk_source_event(source,event_id),INDEX esk_target(target_uuid,scope,occurred_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
`CREATE TABLE IF NOT EXISTS jarvis_entity_state_receipts(key_id CHAR(36) NOT NULL,consumer VARCHAR(64) NOT NULL,reference_id VARCHAR(96) NOT NULL,actor_id CHAR(36) NOT NULL,fingerprint CHAR(64) NOT NULL,result_json TEXT NOT NULL,created_at BIGINT NOT NULL,PRIMARY KEY(key_id,consumer,reference_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
|
]);
|
|
export async function initializeEntityState(db){for(const sql of ENTITY_STATE_SCHEMA)await db.query(sql);}
|
|
export function validateEntityState(input,{now=Date.now()}={}){
|
|
const allowed=['eventId','source','action','targetUuid','targetKind','entityType','actorUuid','cause','scope','world','occurredAt','expiresAt','previousKeyId','references','attributes'];
|
|
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!allowed.includes(k)))throw TypeError('Invalid entity state fields');
|
|
if(!uuid(input.eventId)||!uuid(input.targetUuid)||!text(input.source,32)||!/^[a-z0-9_-]+$/.test(input.source)||!['death','respawn','ban','unban'].includes(input.action)||!['player','mob'].includes(input.targetKind)||!text(input.entityType,64)||!/^[a-z0-9_:]+$/.test(input.entityType)||!text(input.cause,160)||!text(input.scope,64)||!text(input.world,96)||!Number.isSafeInteger(input.occurredAt)||input.occurredAt<0||input.occurredAt>now+60000)throw TypeError('Invalid entity state event');
|
|
if(input.targetKind==='player'&&input.entityType!=='minecraft:player'||input.targetKind==='mob'&&['ban','unban'].includes(input.action))throw TypeError('Invalid entity state target');
|
|
const actorUuid=input.actorUuid??null,expiresAt=input.expiresAt??null,previousKeyId=input.previousKeyId??null;
|
|
if(actorUuid!==null&&!uuid(actorUuid)||previousKeyId!==null&&!uuid(previousKeyId)||expiresAt!==null&&(input.action!=='ban'||!Number.isSafeInteger(expiresAt)||expiresAt<=input.occurredAt))throw TypeError('Invalid entity state timing or identity');
|
|
const references={},attributes={};
|
|
for(const [name,value]of Object.entries(input.references||{})){if(!['questId','missionId','contractId','deedId','deedVersion','ticketId'].includes(name)||!(typeof value==='string'&&text(value,96)||name==='deedVersion'&&Number.isSafeInteger(value)&&value>0))throw TypeError('Invalid entity state reference');references[name]=value;}
|
|
if(input.references!==undefined&&(!input.references||typeof input.references!=='object'||Array.isArray(input.references)))throw TypeError('Invalid entity state references');
|
|
if(input.attributes!==undefined&&(!input.attributes||typeof input.attributes!=='object'||Array.isArray(input.attributes)||Object.keys(input.attributes).length>24))throw TypeError('Invalid entity state attributes');
|
|
for(const name of Object.keys(input.attributes||{}).sort()){const value=input.attributes[name];if(!/^[a-z][a-zA-Z0-9]{0,39}$/.test(name)||!['string','boolean','number'].includes(typeof value)||typeof value==='string'&&!text(value,160)||typeof value==='number'&&!Number.isSafeInteger(value))throw TypeError('Invalid entity state attribute');attributes[name]=value;}
|
|
const sorted=Object.fromEntries(Object.entries(references).sort(([a],[b])=>a.localeCompare(b)));
|
|
return {version:1,eventId:input.eventId.toLowerCase(),source:input.source,action:input.action,targetUuid:input.targetUuid.toLowerCase(),targetKind:input.targetKind,entityType:input.entityType,actorUuid:actorUuid?.toLowerCase()||null,cause:input.cause,scope:input.scope,world:input.world,occurredAt:input.occurredAt,expiresAt,previousKeyId:previousKeyId?.toLowerCase()||null,references:sorted,attributes};
|
|
}
|
|
export function entityStateMatches(event,conditions){
|
|
const direct=['action','targetUuid','targetKind','entityType','actorUuid','cause','scope','world'];
|
|
if(Object.keys(conditions).some(k=>![...direct,'references','attributes','occurredAfter','occurredBefore'].includes(k)))throw TypeError('Invalid entity state conditions');
|
|
for(const [field,value]of Object.entries(conditions)){
|
|
if(field==='references'||field==='attributes'){if(!value||typeof value!=='object'||Array.isArray(value))throw TypeError('Invalid entity state conditions');if(Object.entries(value).some(([k,v])=>event[field]?.[k]!==v))return false;}
|
|
else if(field==='occurredAfter'||field==='occurredBefore'){if(!Number.isSafeInteger(value))throw TypeError('Invalid entity state condition time');if(field==='occurredAfter'?event.occurredAt<value:event.occurredAt>value)return false;}
|
|
else if(event[field]!==value)return false;
|
|
}
|
|
return true;
|
|
}
|
|
// The existing organisation key is the instrument. This table is its typed event
|
|
// dossier; consumers keep independent receipts instead of globally consuming it.
|
|
export function createEntityStateKeys(db,keys,{authorizeEvent,authorizeRead,authorizeEvidence,clock=Date.now}={}){
|
|
if(![authorizeEvent,authorizeRead,authorizeEvidence].every(f=>typeof f==='function'))throw TypeError('Entity state authority adapters required');
|
|
const first=async(store,sql,args=[])=>store.first?store.first(sql,args):(await store.query(sql,args))[0]||null;
|
|
const read=async(store,keyId)=>{
|
|
if(!uuid(keyId))throw TypeError('Choose an entity state key');
|
|
const row=await first(store,"SELECT e.*,k.scope_id,k.key_type,k.account_id,k.revoked_at FROM jarvis_entity_state_events e JOIN organisation_keys k ON k.id=e.key_id WHERE e.key_id=?",[keyId]);
|
|
if(!row||row.key_type!=='entity-state'||row.account_id!==STAFF_OFFICE_ACCOUNT_ID||row.revoked_at!==null)fail('Entity state evidence is unavailable');
|
|
const payload=JSON.parse(row.payload_json);
|
|
if(hash(payload)!==row.fingerprint||row.scope_id!=='state:'+payload.source+':'+payload.eventId||row.target_uuid!==payload.targetUuid||row.action!==payload.action)fail('Entity state evidence changed');
|
|
return {keyId:row.key_id,issuerId:row.issuer_id,...payload};
|
|
};
|
|
return Object.freeze({
|
|
async record(actor,input){
|
|
const payload=validateEntityState(input,{now:clock()});
|
|
if(!uuid(actor?.id)||await authorizeEvent(actor,payload,db)!==true)fail('Verified entity state issuer required');
|
|
const fingerprint=hash(payload);
|
|
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:'+payload.source+':'+payload.eventId,authorize:async(tx,{keyId})=>{
|
|
if(await authorizeEvent(actor,payload,tx)!==true)fail('Entity state issuer authority changed');
|
|
if(payload.previousKeyId){const previous=await read(tx,payload.previousKeyId);if(previous.targetUuid!==payload.targetUuid||previous.scope!==payload.scope||previous.occurredAt>payload.occurredAt)fail('Entity state predecessor does not match');if(payload.action==='unban'&&previous.action!=='ban'||payload.action==='respawn'&&previous.action!=='death')fail('Entity state transition does not match');}
|
|
const prior=await first(tx,'SELECT key_id,fingerprint,issuer_id FROM jarvis_entity_state_events WHERE source=? AND event_id=? FOR UPDATE',[payload.source,payload.eventId]);
|
|
if(prior){if(prior.fingerprint!==fingerprint||prior.issuer_id!==actor.id)fail('Entity state event reference conflict');return;}
|
|
await tx.query('INSERT INTO jarvis_entity_state_events(key_id,source,event_id,issuer_id,target_uuid,action,scope,occurred_at,fingerprint,payload_json,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)',[keyId,payload.source,payload.eventId,actor.id,payload.targetUuid,payload.action,payload.scope,payload.occurredAt,fingerprint,JSON.stringify(payload),clock()]);
|
|
}});
|
|
const record=await read(db,grant.id);if(hash((({keyId,issuerId,...p})=>p)(record))!==fingerprint||record.issuerId!==actor.id)fail('Entity state event reference conflict');
|
|
return {keyId:grant.id,created:grant.created};
|
|
},
|
|
async get(actor,keyId){const event=await read(db,keyId);if(await authorizeRead(actor,event,db)!==true)fail('Entity state read authority required');return event;},
|
|
async useEvidence(actor,{keyId,consumer,referenceId,conditions,intent=null},apply){
|
|
if(!uuid(actor?.id)||!text(consumer,64)||!/^[a-z][a-z0-9_.-]+$/.test(consumer)||!text(referenceId,96)||typeof apply!=='function'||!conditions||typeof conditions!=='object'||Array.isArray(conditions)||!Object.keys(conditions).length)throw TypeError('Scoped entity state consumer required');
|
|
entityStateMatches({},conditions);
|
|
if(intent!==null&&!text(intent,1000))throw TypeError('Invalid entity state consumer intent');
|
|
const fingerprint=hash({conditions:Object.fromEntries(Object.entries(conditions).sort(([a],[b])=>a.localeCompare(b))),intent});
|
|
return db.transaction(async tx=>{
|
|
const event=await read(tx,keyId);
|
|
if(await authorizeEvidence(actor,{event,consumer,referenceId,conditions},tx)!==true)fail('Entity state consumer authority required');
|
|
if(!entityStateMatches(event,conditions))fail('Entity state evidence does not satisfy the objective');
|
|
// Lock the instrument to serialize consumers; the key remains reusable by
|
|
// DIFFERENT quest/contract/deed references, never twice by the same one.
|
|
const key=await first(tx,'SELECT id,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[keyId]);if(!key||key.revoked_at!==null)fail('Entity state evidence is unavailable');
|
|
const prior=await first(tx,'SELECT actor_id,fingerprint,result_json FROM jarvis_entity_state_receipts WHERE key_id=? AND consumer=? AND reference_id=?',[keyId,consumer,referenceId]);
|
|
if(prior){if(prior.actor_id!==actor.id||prior.fingerprint!==fingerprint)fail('Entity state receipt reference conflict');return {replayed:true,result:JSON.parse(prior.result_json)};}
|
|
const result=await apply(tx,event);
|
|
await tx.query('INSERT INTO jarvis_entity_state_receipts(key_id,consumer,reference_id,actor_id,fingerprint,result_json,created_at) VALUES(?,?,?,?,?,?,?)',[keyId,consumer,referenceId,actor.id,fingerprint,JSON.stringify(result??null),clock()]);return {replayed:false,result:result??null};
|
|
});
|
|
}
|
|
});
|
|
}
|

Staff