115 lines
13 KiB
JavaScript
115 lines
13 KiB
JavaScript
import {createHash,randomUUID} from 'node:crypto';
|
|
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
|
export const BOARD_STATE_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_board_states(key_id CHAR(36) PRIMARY KEY,organisation_kind VARCHAR(12) NOT NULL,organisation_id CHAR(36) NOT NULL,revision INT NOT NULL,desired_json TEXT NOT NULL,fingerprint CHAR(64) NOT NULL,watch_fingerprint CHAR(64) NULL,delivery_state VARCHAR(16) NOT NULL,native_json TEXT NULL,native_policy_fingerprint CHAR(64) NULL,applied_revision INT NOT NULL DEFAULT 0,attempts INT NOT NULL DEFAULT 0,next_attempt_at BIGINT NOT NULL DEFAULT 0,lease_token CHAR(36) NULL,lease_until BIGINT NOT NULL DEFAULT 0,last_error VARCHAR(100) NULL,updated_at BIGINT NOT NULL,UNIQUE KEY board_identity(organisation_kind,organisation_id))`;
|
|
export async function initializeBoardStates(db){await db.query(BOARD_STATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');}
|
|
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
|
|
const kinds=['clan','company','politics'];
|
|
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
const first=async(store,sql,args=[])=>store.first?store.first(sql,args):(await store.query(sql,args))[0]||null;
|
|
const fail=message=>{throw Error(message);};
|
|
export function boardDesiredState(input,{kind,id}){
|
|
if(!kinds.includes(kind)||!uuid(id)||!input||input.organisation?.kind!==kind||input.organisation?.id!==id)throw TypeError('Resolved board organisation required');
|
|
const org=input.organisation,source=input.source,policy=input.policy;
|
|
if(typeof org.name!=='string'||!org.name.trim()||org.name.length>120||/[\u0000-\u001f]/.test(org.name)||!['active','archived'].includes(org.lifecycle))throw TypeError('Resolved board name and lifecycle required');
|
|
if(!source||!['clan-deed','company-deed','office-deed','passive-order-deed'].includes(source.kind)||!uuid(source.id)||!Number.isSafeInteger(source.version)||source.version<1||!(uuid(source.ownerId)||kind==='politics'&&source.ownerId===null))throw TypeError('Resolved deed reference and version required');
|
|
const alias=kind==='company'&&source.kind==='passive-order-deed'&&source.refs?.legacyCompanyId===id;
|
|
if(!alias&&source.kind!==({'clan':'clan-deed','company':'company-deed','politics':'office-deed'})[kind])throw TypeError('Board source kind mismatch');
|
|
if(!alias&&kind!=='politics'&&source.id!==id)throw TypeError('Board source organisation mismatch');
|
|
if(input.template?.id!=='private-organisation'||input.template.version!==1)throw TypeError('Registered board template required');
|
|
if(!policy||!Array.isArray(policy.members)||policy.members.length>500||!Array.isArray(policy.managers)||!policy.managers.every(uuid)||policy.managers.length>50)throw TypeError('Current board role policy required');
|
|
const members=policy.members.map(m=>{const binding=m.binding??null;if(!uuid(m.id)||!['owner','officer','member','officeholder','appointee'].includes(m.role)||binding!==null&&(typeof binding!=='string'||!/^[a-z0-9:_-]{1,120}$/i.test(binding)))throw TypeError('Resolved board membership required');return {id:m.id,role:m.role,binding};}).sort((a,b)=>a.id.localeCompare(b.id));
|
|
if(new Set(members.map(m=>m.id)).size!==members.length||policy.managers.some(id=>!members.some(m=>m.id===id))||org.lifecycle==='active'&&source.ownerId!==null&&!members.some(m=>m.id===source.ownerId))throw TypeError('Board management must belong to its current roster');
|
|
const refs={};for(const [name,value]of Object.entries(source.refs||{}).sort(([a],[b])=>a.localeCompare(b))){if(!/^[a-zA-Z][a-zA-Z0-9]{0,39}$/.test(name)||value!==null&&!uuid(value))throw TypeError('Invalid board deed binding');refs[name]=value;}
|
|
const expiresAt=source.expiresAt??null;if(expiresAt!==null&&(!Number.isSafeInteger(expiresAt)||expiresAt<1))throw TypeError('Invalid board source expiry');
|
|
return {version:1,organisation:{kind,id,name:org.name.trim(),lifecycle:org.lifecycle},source:{kind:source.kind,id:source.id,version:source.version,ownerId:source.ownerId,expiresAt,refs},template:{id:'private-organisation',version:1},policy:{members,managers:[...new Set(policy.managers)].sort()}};
|
|
}
|
|
const joined="SELECT b.*,k.account_id,k.key_type,k.scope_id,k.revoked_at FROM jarvis_board_states b JOIN organisation_keys k ON k.id=b.key_id";
|
|
function checked(row){
|
|
if(!row||row.account_id!==STAFF_OFFICE_ACCOUNT_ID||row.key_type!=='board-state'||row.revoked_at!=null||row.scope_id!=='board:'+row.organisation_kind+':'+row.organisation_id)fail('Board key requires review');
|
|
const desired=boardDesiredState(JSON.parse(row.desired_json),{kind:row.organisation_kind,id:row.organisation_id});
|
|
if(hash(desired)!==row.fingerprint)fail('Board key data changed');return desired;
|
|
}
|
|
function view(row){return {keyId:row.key_id,revision:Number(row.revision),desired:checked(row),fingerprint:row.fingerprint,state:row.delivery_state,appliedRevision:Number(row.applied_revision),native:row.native_json?JSON.parse(row.native_json):null};}
|
|
// Private identity reads never provision a board or return redeemable codes.
|
|
export async function currentBoardKeyStates(db,organisations,{includeArchived=false}={}){
|
|
const result=new Map();if(!organisations.length)return result;
|
|
if(organisations.length>100)throw TypeError('Board membership inventory exceeds its bound');
|
|
const rows=await db.query(joined+' WHERE '+organisations.map(()=>'(b.organisation_kind=? AND b.organisation_id=?)').join(' OR '),organisations.flatMap(o=>[o.kind,o.id]));
|
|
for(const row of rows)try{const desired=checked(row);if(includeArchived||desired.organisation.lifecycle==='active')result.set(row.organisation_kind+':'+row.organisation_id,desired);}catch{/* A damaged dossier cannot grant private board access. */}
|
|
return result;
|
|
}
|
|
// The authenticated native integration bridge receives leased references only.
|
|
// It reads the actual key dossier rather than trusting a publisher's JSON body.
|
|
export async function boardPublicationRecords(db,refs,{clock=Date.now}={}){
|
|
if(!Array.isArray(refs)||refs.length>25||new Set(refs.map(r=>r?.keyId)).size!==refs.length||refs.some(r=>!r||Object.keys(r).some(k=>!['keyId','revision','fingerprint','leaseToken'].includes(k))||!uuid(r.keyId)||!uuid(r.leaseToken)||!Number.isSafeInteger(r.revision)||r.revision<1||!(/^[a-f0-9]{64}$/).test(r.fingerprint||'')))throw TypeError('Choose a bounded leased board-key batch');
|
|
if(!refs.length)return {records:[],rejected:[]};
|
|
const rows=await db.query(joined+' WHERE b.key_id IN ('+refs.map(()=>'?').join(',')+')',refs.map(r=>r.keyId)),map=new Map(rows.map(r=>[r.key_id,r])),records=[],rejected=[];
|
|
for(const ref of refs){const row=map.get(ref.keyId);if(!row||Number(row.revision)!==ref.revision||row.fingerprint!==ref.fingerprint||row.lease_token!==ref.leaseToken||Number(row.lease_until)<=clock()){rejected.push({keyId:ref.keyId,state:'stale'});continue;}
|
|
try{const desired=checked(row);records.push({keyId:row.key_id,revision:Number(row.revision),fingerprint:row.fingerprint,desiredJson:JSON.stringify(desired)});}catch{rejected.push({keyId:ref.keyId,state:'review'});}
|
|
}return {records,rejected};
|
|
}
|
|
// A writable BRD dossier and its delivery state belong to one ordinary system
|
|
// record key. Source deeds, user secrets and native forum content are untouched.
|
|
export function createBoardStateKeys(db,keys,{resolveSource,authorizePublisher,clock=Date.now}={}){
|
|
if(typeof resolveSource!=='function'||typeof authorizePublisher!=='function')throw TypeError('Resolved deed and native publisher adapters required');
|
|
const load=(store,kind,id,lock='')=>first(store,joined+' WHERE b.organisation_kind=? AND b.organisation_id=?'+lock,[kind,id]);
|
|
const publisher=async actor=>{if(await authorizePublisher(actor)!==true)fail('Registered board publisher required');};
|
|
return Object.freeze({
|
|
async refresh(kind,id,{watchFingerprint=null}={}){
|
|
if(!kinds.includes(kind)||!uuid(id))throw TypeError('Choose a board organisation');
|
|
if(watchFingerprint!==null&&!/^[a-f0-9]{64}$/.test(watchFingerprint))throw TypeError('Invalid board source observation');
|
|
let row=await load(db,kind,id);
|
|
if(!row){
|
|
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'board-state',scopeId:'board:'+kind+':'+id,authorize:async(tx,{keyId})=>{
|
|
const desired=boardDesiredState(await resolveSource(tx,kind,id),{kind,id});
|
|
await tx.query("INSERT INTO jarvis_board_states(key_id,organisation_kind,organisation_id,revision,desired_json,fingerprint,delivery_state,updated_at) VALUES(?,?,?,1,?,?,'pending',?)",[keyId,kind,id,JSON.stringify(desired),hash(desired),clock()]);
|
|
}});row=await load(db,kind,id);checked(row);
|
|
}
|
|
return db.transaction(async tx=>{
|
|
const current=await load(tx,kind,id,' FOR UPDATE');checked(current);
|
|
const desired=boardDesiredState(await resolveSource(tx,kind,id),{kind,id}),fingerprint=hash(desired);
|
|
if(current.fingerprint===fingerprint){if(watchFingerprint!==null&¤t.watch_fingerprint!==watchFingerprint)await tx.query('UPDATE jarvis_board_states SET watch_fingerprint=? WHERE key_id=?',[watchFingerprint,current.key_id]);return {...view(current),changed:false};}
|
|
const revision=Number(current.revision)+1;if(!Number.isSafeInteger(revision)||revision>2147483647)fail('Board revision requires review');
|
|
await tx.query("UPDATE jarvis_board_states SET revision=?,desired_json=?,fingerprint=?,watch_fingerprint=?,delivery_state='pending',attempts=0,next_attempt_at=0,lease_token=NULL,lease_until=0,last_error=NULL,updated_at=? WHERE key_id=?",[revision,JSON.stringify(desired),fingerprint,watchFingerprint,clock(),current.key_id]);
|
|
await tx.query('INSERT INTO organisation_key_events(id,key_id,account_id,event_type,target_id,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),current.key_id,STAFF_OFFICE_ACCOUNT_ID,'board-updated',id,clock()]);
|
|
return {...view(await load(tx,kind,id)),changed:true};
|
|
});
|
|
},
|
|
async read(kind,id){const row=await load(db,kind,id);return row?view(row):null;},
|
|
async claimBatch(actor,{limit=25}={}){
|
|
await publisher(actor);if(!Number.isSafeInteger(limit)||limit<1||limit>25)throw TypeError('Choose a bounded board batch');
|
|
return db.transaction(async tx=>{
|
|
const rows=await tx.query(joined+" WHERE b.delivery_state IN ('pending','retry') AND b.next_attempt_at<=? AND b.lease_until<=? AND k.revoked_at IS NULL ORDER BY b.updated_at,b.key_id LIMIT "+limit+' FOR UPDATE',[clock(),clock()]);
|
|
const lease=randomUUID(),result=[];
|
|
for(const row of rows){let item;try{item=view(row);}catch{await tx.query("UPDATE jarvis_board_states SET delivery_state='review',last_error='Board key requires review',lease_token=NULL,lease_until=0 WHERE key_id=?",[row.key_id]);continue;}await tx.query('UPDATE jarvis_board_states SET lease_token=?,lease_until=? WHERE key_id=?',[lease,clock()+120000,row.key_id]);result.push({...item,leaseToken:lease});}return result;
|
|
});
|
|
},
|
|
async acknowledge(actor,{keyId,revision,fingerprint,leaseToken,native,policyFingerprint=null}){
|
|
await publisher(actor);if(!uuid(keyId)||!uuid(leaseToken)||!Number.isSafeInteger(revision)||!native||!['forumId','memberGroupId','leaderGroupId'].every(k=>Number.isSafeInteger(native[k])&&native[k]>0))throw TypeError('Verified native board receipt required');
|
|
if(policyFingerprint!==null&&!/^[a-f0-9]{64}$/.test(policyFingerprint))throw TypeError('Invalid native group policy receipt');
|
|
return db.transaction(async tx=>{
|
|
const row=await first(tx,joined+' WHERE b.key_id=? FOR UPDATE',[keyId]);checked(row);
|
|
if(Number(row.revision)!==revision||row.fingerprint!==fingerprint||row.lease_token!==leaseToken)return {accepted:false,stale:true};
|
|
const old=row.native_json?JSON.parse(row.native_json):null;if(old&&['forumId','memberGroupId','leaderGroupId'].some(k=>old[k]!==native[k]))fail('Existing native board mapping must be preserved');
|
|
const mapping=Object.fromEntries(['forumId','memberGroupId','leaderGroupId'].map(k=>[k,native[k]]));
|
|
await tx.query("UPDATE jarvis_board_states SET native_json=?,native_policy_fingerprint=?,applied_revision=?,delivery_state='applied',lease_token=NULL,lease_until=0,last_error=NULL WHERE key_id=?",[JSON.stringify(mapping),policyFingerprint,revision,keyId]);return {accepted:true};
|
|
});
|
|
},
|
|
async queueNativePolicy(actor,fingerprint){
|
|
await publisher(actor);if(!/^[a-f0-9]{64}$/.test(fingerprint||''))throw TypeError('Native group policy fingerprint required');
|
|
return db.query("UPDATE jarvis_board_states SET delivery_state='pending',next_attempt_at=0 WHERE delivery_state='applied' AND (native_policy_fingerprint IS NULL OR native_policy_fingerprint<>?)",[fingerprint]);
|
|
},
|
|
async review(actor,{keyId,leaseToken}){
|
|
await publisher(actor);if(!uuid(keyId)||!uuid(leaseToken))throw TypeError('Choose the leased board key');
|
|
return db.query("UPDATE jarvis_board_states SET delivery_state='review',lease_token=NULL,lease_until=0,last_error='Native board mapping requires review' WHERE key_id=? AND lease_token=?",[keyId,leaseToken]);
|
|
},
|
|
async retry(actor,{keyId,leaseToken}){
|
|
await publisher(actor);if(!uuid(keyId)||!uuid(leaseToken))throw TypeError('Choose the leased board key');
|
|
return db.transaction(async tx=>{
|
|
const row=await first(tx,'SELECT attempts FROM jarvis_board_states WHERE key_id=? AND lease_token=? FOR UPDATE',[keyId,leaseToken]);if(!row)return {stale:true};
|
|
const attempts=Number(row.attempts)+1,delay=Math.min(300000,5000*2**Math.min(attempts-1,6));
|
|
await tx.query("UPDATE jarvis_board_states SET delivery_state='retry',attempts=?,next_attempt_at=?,lease_token=NULL,lease_until=0,last_error='Native board publication unavailable' WHERE key_id=? AND lease_token=?",[attempts,clock()+delay,keyId,leaseToken]);return {queued:true};
|
|
});
|
|
}
|
|
});
|
|
}
|

Staff