import {randomUUID,randomBytes} from 'node:crypto'; import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; import {systemCharacter} from './system-character-catalogue.mjs'; export const SYSTEM_IDENTITY_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_system_identities(user_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,character_key VARCHAR(32) NOT NULL UNIQUE,minecraft_uuid CHAR(36) NOT NULL UNIQUE,identity_json TEXT NOT NULL,created_by CHAR(36) NOT NULL,created_at BIGINT NOT NULL)`; export async function initializeSystemCharacters(db){await db.query(SYSTEM_IDENTITY_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); export function createSystemCharacters(db,keys,{authorizeOperator,clock=Date.now}={}){ if(typeof authorizeOperator!=='function')throw TypeError('Current system identity operator authority required'); const first=async(store,sql,args=[])=>store.first?store.first(sql,args):(await store.query(sql,args))[0]||null; async function record(store,key){ const row=await first(store,"SELECT i.*,a.username,a.display_name,a.role,a.password_hash,l.minecraft_uuid AS linked_uuid,k.key_type,k.scope_id,k.account_id AS key_account_id,k.expires_at,k.revoked_at FROM jarvis_system_identities i JOIN site_accounts a ON a.id=i.user_id JOIN organisation_keys k ON k.id=i.key_id LEFT JOIN site_game_links l ON l.user_id=i.user_id WHERE i.character_key=?",[key]); if(!row)return null;const character=systemCharacter(key); if(!character||row.username!==character.username||row.role!=='system_account'||row.password_hash!=='!system'||row.linked_uuid!==row.minecraft_uuid||row.key_type!=='system-identity'||row.key_account_id!==STAFF_OFFICE_ACCOUNT_ID||row.expires_at!==null||row.scope_id!=='character:'+key+':v1'||row.revoked_at!==null||row.identity_json!==JSON.stringify(character))throw Error('System identity requires review; existing data was not overwritten'); return {id:row.user_id,keyId:row.key_id,username:row.username,name:row.display_name,minecraftUuid:row.minecraft_uuid,synthetic:true,kind:'system_account',house:character.house,characterRole:character.role,capabilities:character.capabilities}; } return Object.freeze({ async provision(actor,key){ const character=systemCharacter(key);if(!character||!uuid(actor?.id)||await authorizeOperator(actor,db)!==true)throw Error('Current account operator authority required'); const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'system-identity',scopeId:'character:'+key+':v1',authorize:async(tx,{keyId})=>{ if(await authorizeOperator(actor,tx)!==true)throw Error('Account operator authority changed'); const existing=await first(tx,'SELECT user_id FROM jarvis_system_identities WHERE character_key=? FOR UPDATE',[key]);if(existing){await record(tx,key);return;} const collision=await first(tx,'SELECT id FROM site_accounts WHERE LOWER(username)=LOWER(?) FOR UPDATE',[character.username]);if(collision)throw Error('System username already belongs to another account; no account was overwritten'); const id=randomUUID(),minecraftUuid=randomUUID(),now=clock(); await tx.query("INSERT INTO site_accounts(id,username,display_name,password_salt,password_hash,role,created_at) VALUES(?,?,?,?,'!system','system_account',?)",[id,character.username,character.name,randomBytes(16).toString('hex'),now]); await tx.query('INSERT INTO site_game_links(user_id,minecraft_uuid,minecraft_name,linked_at) VALUES(?,?,?,?)',[id,minecraftUuid,character.username,now]); await tx.query('INSERT INTO site_game_identities(minecraft_uuid,first_linked_at,last_name) VALUES(?,?,?)',[minecraftUuid,now,character.username]); await tx.query('INSERT INTO jarvis_system_identities(user_id,key_id,character_key,minecraft_uuid,identity_json,created_by,created_at) VALUES(?,?,?,?,?,?,?)',[id,keyId,key,minecraftUuid,JSON.stringify(character),actor.id,now]); await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'jarvis-system-character-created',JSON.stringify({keyId,accountId:id,character:key,minecraftUuid,synthetic:true,normalPermissions:false}),now]); }}); const identity=await record(db,key);if(!identity||identity.keyId!==grant.id)throw Error('System identity key mismatch');return {...identity,created:grant.created}; }, async inspect(key){return record(db,key);}, async permits(userId,capability,store=db){ const row=await first(store,'SELECT character_key FROM jarvis_system_identities WHERE user_id=?',[userId]);if(!row)return false; const identity=await record(store,row.character_key);return !!identity?.capabilities.includes(capability); } }); }