web/website/node/kitsets.mjs

54 lines
5.3 KiB
JavaScript

import {createHash} from 'node:crypto';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {validateKitset,KITSET_LIMITS} from '../control-panel/public/kitset-model.mjs';
export async function initializeKitsets(db){
for(const sql of [
'CREATE TABLE IF NOT EXISTS jarvis_kitset_scopes(scope_kind VARCHAR(16) NOT NULL,scope_id VARCHAR(64) NOT NULL,PRIMARY KEY(scope_kind,scope_id))',
'CREATE TABLE IF NOT EXISTS jarvis_kitsets(id CHAR(36) PRIMARY KEY,author_id CHAR(36) NOT NULL,scope_kind VARCHAR(16) NOT NULL,scope_id VARCHAR(64) NOT NULL,revision INT NOT NULL,design_json TEXT NOT NULL,updated_at BIGINT NOT NULL)',
'CREATE TABLE IF NOT EXISTS jarvis_kitset_versions(key_id CHAR(36) PRIMARY KEY,kitset_id CHAR(36) NOT NULL,revision INT NOT NULL,author_id CHAR(36) NOT NULL,design_json TEXT NOT NULL,fingerprint CHAR(64) NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY kitset_version(kitset_id,revision))'
])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
}
const uuid=value=>typeof value==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
const first=async(db,sql,args)=>(await db.query(sql,args))[0]||null;
const hash=value=>createHash('sha256').update(value).digest('hex');
const view=row=>({id:row.id,revision:Number(row.revision),design:validateKitset(JSON.parse(row.design_json))});
export function createKitsets(db,keys,{authorize,clock=Date.now}={}){
if(typeof authorize!=='function')throw TypeError('A current kitset authority adapter is required.');
const allowed=async(actor,tx,owner=null)=>{if(!uuid(actor?.id)||await authorize(actor,tx,owner)!==true)throw Error('Kitset management required.');};
const identity=(id,revision)=>{if(!uuid(id)||!Number.isSafeInteger(revision)||revision<0||revision>=999999)throw TypeError('Use the saved kitset identity and revision.');return id.toLowerCase();};
return Object.freeze({
async list(actor){await allowed(actor,db);const rows=await db.query('SELECT * FROM jarvis_kitsets ORDER BY updated_at DESC,id LIMIT 1000');const visible=[];for(const row of rows){const item=view(row);if(await authorize(actor,db,item.design.owner)===true)visible.push(item);}return visible;},
async save(actor,{id,revision,design}){
id=identity(id,revision);const validated=validateKitset(design),raw=JSON.stringify(validated),owner=validated.owner;
return db.transaction(async tx=>{
await allowed(actor,tx,owner);
// Serialise creation as well as updates. A missing draft cannot be row-locked.
await tx.query('INSERT INTO jarvis_kitset_scopes(scope_kind,scope_id) VALUES(?,?) ON DUPLICATE KEY UPDATE scope_id=VALUES(scope_id)',[owner.kind,owner.id]);
await tx.query('SELECT scope_id FROM jarvis_kitset_scopes WHERE scope_kind=? AND scope_id=? FOR UPDATE',[owner.kind,owner.id]);
const row=await first(tx,'SELECT * FROM jarvis_kitsets WHERE id=? FOR UPDATE',[id]);
if(row&&(row.scope_kind!==owner.kind||row.scope_id!==owner.id||Number(row.revision)!==revision)||!row&&revision!==0)throw Error('Kitset changed. Refresh before saving.');
if(!row){const existing=await tx.query('SELECT id FROM jarvis_kitsets WHERE scope_kind=? AND scope_id=? FOR UPDATE',[owner.kind,owner.id]);if(existing.length>=KITSET_LIMITS[owner.kind])throw Error('Kitset limit reached for this office or organisation. Edit an existing design.');}
const next=revision+1,now=clock();
if(row)await tx.query('UPDATE jarvis_kitsets SET revision=?,design_json=?,updated_at=? WHERE id=?',[next,raw,now,id]);
else await tx.query('INSERT INTO jarvis_kitsets(id,author_id,scope_kind,scope_id,revision,design_json,updated_at) VALUES(?,?,?,?,?,?,?)',[id,actor.id,owner.kind,owner.id,next,raw,now]);
return {id,revision:next,design:JSON.parse(raw)};
});
},
async generate(actor,{id,revision}){
id=identity(id,revision);await allowed(actor,db);if(!keys)throw Error('Kitset key service unavailable.');
const row=await first(db,'SELECT * FROM jarvis_kitsets WHERE id=?',[id]);
if(!row||Number(row.revision)!==revision)throw Error('Kitset changed. Save and refresh before generating.');
const design=validateKitset(JSON.parse(row.design_json));await allowed(actor,db,design.owner);if(!design.items.length)throw TypeError('Add at least one item before generating a kit.');
const raw=JSON.stringify(design),fingerprint=hash(raw);
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'kit-definition',scopeId:`kitset:${id}:v${revision}`,authorize:async(tx,{keyId})=>{
await allowed(actor,tx,design.owner);const current=await first(tx,'SELECT * FROM jarvis_kitsets WHERE id=? FOR UPDATE',[id]);
if(!current||current.scope_kind!==design.owner.kind||current.scope_id!==design.owner.id||Number(current.revision)!==revision||hash(current.design_json)!==fingerprint)throw Error('Kitset changed. Save and refresh before generating.');
await tx.query('INSERT INTO jarvis_kitset_versions(key_id,kitset_id,revision,author_id,design_json,fingerprint,created_at) VALUES(?,?,?,?,?,?,?)',[keyId,id,revision,actor.id,raw,fingerprint,clock()]);
}});
const saved=await first(db,'SELECT * FROM jarvis_kitset_versions WHERE key_id=?',[grant.id]);
if(!saved||saved.kitset_id!==id||saved.fingerprint!==fingerprint)throw Error('Kitset revision conflict.');
return {id,revision,keyId:grant.id,replayed:!grant.created,design:JSON.parse(saved.design_json),state:'definition'};
}
});
}