Register scoped Jarvis account test identity action with synthetic UUID adapter
All checks were successful
DuneRealms Web CI / web (push) Successful in 3m7s

This commit is contained in:
unimatrixgit 2026-11-19 20:57:23 +01:00
commit 3cd5510f03
7 changed files with 125 additions and 14 deletions

View file

@ -0,0 +1,31 @@
import {randomUUID} from 'node:crypto';
export const TEST_IDENTITY_SCHEMA=`CREATE TABLE IF NOT EXISTS site_test_game_identities(minecraft_uuid CHAR(36) PRIMARY KEY,user_id CHAR(36) NOT NULL,key_id CHAR(36) NOT NULL UNIQUE,issued_by CHAR(36) NOT NULL,created_at BIGINT NOT NULL)`;
export const TEST_IDENTITY_ACTION='accounts.test-minecraft-identity';
export const TEST_IDENTITY_PERMISSION='web.jarvis.accounts.test-identity';
async function target(tx,username){
if(typeof username!=='string'||! /^[A-Za-z0-9_]{1,32}$/.test(username))throw TypeError('Invalid target account name');
const row=await tx.first("SELECT id,username,role FROM site_accounts WHERE LOWER(username)=LOWER(?) AND password_hash NOT LIKE '!%' FOR UPDATE",[username]);
if(!row||['memorial','official_account'].includes(row.role))throw Error('Instruction requires an active ordinary test account');
const link=await tx.first('SELECT * FROM site_game_links WHERE user_id=? FOR UPDATE',[row.id]);
const challenge=await tx.first('SELECT * FROM site_link_challenges WHERE user_id=? FOR UPDATE',[row.id]);
if(link||challenge)throw Error('Instruction cannot overwrite an existing game link or pending link challenge');
return row;
}
export async function prepareTestIdentity(tx,username){
const account=await target(tx,username),minecraftUuid=randomUUID();
return {version:1,action:TEST_IDENTITY_ACTION,account,minecraftUuid,minecraftName:('TEST_'+account.username).slice(0,32),synthetic:true};
}
export async function applyTestIdentity(tx,manifest,{keyId,actorId,now}){
if(manifest?.version!==1||manifest.action!==TEST_IDENTITY_ACTION||manifest.synthetic!==true||! /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(manifest.minecraftUuid||''))throw Error('Instruction test identity scope is invalid');
const account=await target(tx,manifest.account?.username);
if(JSON.stringify(account)!==JSON.stringify(manifest.account)||manifest.minecraftName!==('TEST_'+account.username).slice(0,32))throw Error('Instruction target account changed');
if(await tx.first('SELECT minecraft_uuid FROM site_game_identities WHERE minecraft_uuid=? FOR UPDATE',[manifest.minecraftUuid]))throw Error('Instruction UUID is already registered');
await tx.query('INSERT INTO site_game_links(user_id,minecraft_uuid,minecraft_name,linked_at) VALUES(?,?,?,?)',[account.id,manifest.minecraftUuid,manifest.minecraftName,now]);
await tx.query('INSERT INTO site_game_identities(minecraft_uuid,first_linked_at,last_name) VALUES(?,?,?)',[manifest.minecraftUuid,now,manifest.minecraftName]);
await tx.query('INSERT INTO site_test_game_identities(minecraft_uuid,user_id,key_id,issued_by,created_at) VALUES(?,?,?,?,?)',[manifest.minecraftUuid,account.id,keyId,actorId,now]);
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actorId,'jarvis-test-game-identity-assigned',JSON.stringify({keyId,accountId:account.id,minecraftUuid:manifest.minecraftUuid,synthetic:true}),now]);
}

View file

@ -26,6 +26,7 @@ export function createGameLink(db,settings,origin){
const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401);
if(request.method==='GET'&&path==='/api/game-link'){
const link=await db.prepare('SELECT l.minecraft_uuid,l.minecraft_name,l.linked_at,i.first_linked_at FROM site_game_links l LEFT JOIN site_game_identities i ON i.minecraft_uuid=l.minecraft_uuid WHERE l.user_id=?').bind(user.id).first();
if(link?.minecraft_uuid&&db.jarvisGeneratorEnabled&&await db.prepare('SELECT minecraft_uuid FROM site_test_game_identities WHERE user_id=? AND minecraft_uuid=?').bind(user.id,link.minecraft_uuid).first())link.identityKind='synthetic-test';
return json({linked:!!link?.minecraft_uuid,link:link?.minecraft_uuid?link:null});
}
if(request.method!=='POST')return json({message:'Method not allowed'},405);

View file

@ -4,6 +4,6 @@ export async function jarvisGeneratorCan(db,user,node,{readAccess=accessFor}={})
if(!user)return false;const access=await readAccess(db,user);if(!access)return false;
const nodes=new Set(access.nodes||[]);if(nodes.has(node))return true;
if(node==='web.jarvis.keys.view')return ['web.items.manage','cp.items.manage','web.ranks.manage','cp.ranks.manage'].some(n=>nodes.has(n));
if(node==='web.jarvis.clans.reset')return access.organisation?.mode==='active'&&access.rank==='org_owner_ceo'&&(nodes.has('web.ranks.manage')||nodes.has('cp.ranks.manage'));
if(['web.jarvis.clans.reset','web.jarvis.accounts.test-identity'].includes(node))return access.organisation?.mode==='active'&&access.rank==='org_owner_ceo'&&(nodes.has('web.ranks.manage')||nodes.has('cp.ranks.manage'));
return false;
}

View file

@ -1,5 +1,7 @@
import {assertWebIssuableMaster} from './jarvis-web-key-boundary.mjs';
import {hashOrganisationKey} from './organisation-keys.mjs';
import {parseOrganisationCode} from '../control-panel/public/codex-code-format.mjs';
import {TEST_IDENTITY_SCHEMA,TEST_IDENTITY_ACTION,TEST_IDENTITY_PERMISSION,prepareTestIdentity,applyTestIdentity} from './account-test-identity.mjs';
import {createHash,randomUUID} from 'node:crypto';
import {MASTER_KEY_TEMPLATES,masterAction,validateMasterFields} from '../control-panel/public/jarvis-master-keys.mjs';
export const GENERATOR_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_generated_instructions(key_id CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,account_id CHAR(36) NOT NULL,action_id VARCHAR(80) NOT NULL,template_version INTEGER NOT NULL,fields_json TEXT NOT NULL,manifest_json MEDIUMTEXT NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL)`;
@ -10,6 +12,7 @@ const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
const first=(db,sql,args=[])=>db.prepare(sql).bind(...args).first();
export async function initializeJarvisGenerator(db,{mysql=true}={}){
await db.query(GENERATOR_SCHEMA);
await db.query(TEST_IDENTITY_SCHEMA);
if(mysql){const column=await first(db,"SELECT IS_NULLABLE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='site_clans' AND COLUMN_NAME='owner_id'");if(column?.IS_NULLABLE==='NO')await db.query('ALTER TABLE site_clans MODIFY owner_id CHAR(36) NULL');}
db.jarvisGeneratorEnabled=true;
}
@ -30,26 +33,37 @@ export function createMasterKeyGenerator(db,keys,{authorize,clock=Date.now}){
const permitted=async(actor,node)=>{if(!actor?.id||!await authorize(actor,node))throw Error('Masterkey authority required');};
async function availableCode(result,accountId){const record=(await keys.list(accountId)).find(k=>k.id===result.id);return {keyId:result.id,code:record?.status==='available'?record.code:null,status:record?.status||'unavailable',created:result.created};}
return Object.freeze({
async catalogue(actor){await permitted(actor,'web.jarvis.keys.view');const reset=await authorize(actor,'web.jarvis.clans.reset');return {templates:MASTER_KEY_TEMPLATES.map(t=>({...t,actions:t.actions.map(a=>({...a,available:a.webIssue===true&&reset===true}))})),recipient:actor.username};},
async catalogue(actor){await permitted(actor,'web.jarvis.keys.view');return {templates:await Promise.all(MASTER_KEY_TEMPLATES.map(async t=>({...t,actions:await Promise.all(t.actions.map(async a=>({...a,available:a.webIssue===true&&await authorize(actor,a.permission)===true})))}))),recipient:actor.username};},
async issue(actor,{actionId,templateVersion,values,requestId}){
const action=masterAction(actionId);assertWebIssuableMaster(action);if(!action||action.version!==templateVersion||!action.webIssue||!uuid(requestId))throw Error('Choose a connected masterkey action');
if(!['clan.clear-protected-rosters',TEST_IDENTITY_ACTION].includes(actionId))throw Error('Choose a connected domain adapter');
await permitted(actor,action.permission);const fields=validateMasterFields(action,values),encoded=JSON.stringify(fields);
const prior=await first(db,'SELECT * FROM jarvis_generated_instructions WHERE request_id=?',[requestId]);
if(prior){if(prior.account_id!==actor.id||prior.action_id!==actionId||prior.fields_json!==encoded)throw Error('Instruction reference conflict');return availableCode({id:prior.key_id,created:false},actor.id);}
const result=await keys.issue({accountId:actor.id,keyType:'clan-administration',scopeId:'protected-roster:'+requestId,expiresAt:clock()+86400000,authorize:async(tx,{keyId})=>{
await permitted(actor,action.permission);const manifest=await snapshot(tx);
const accountAction=actionId===TEST_IDENTITY_ACTION,scopePrefix=accountAction?'test-identity:':'protected-roster:';
const result=await keys.issue({accountId:actor.id,keyType:action.keyType,scopeId:scopePrefix+requestId,expiresAt:clock()+86400000,authorize:async(tx,{keyId})=>{
await permitted(actor,action.permission);const manifest=accountAction?await prepareTestIdentity(tx,fields.accountName):await snapshot(tx);
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(?,?,?,?,?,?,?,\'issued\',?)',[keyId,requestId,actor.id,actionId,templateVersion,encoded,JSON.stringify(manifest),clock()]);
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'jarvis-key-generated',JSON.stringify({keyId,actionId,requestId,ticketId:fields.ticketId,manifestHash:manifest.inventoryHash}),clock()]);
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'jarvis-key-generated',JSON.stringify({keyId,actionId,requestId,ticketId:fields.ticketId,manifestHash:hash(manifest)}),clock()]);
}});const stored=await first(db,'SELECT fields_json FROM jarvis_generated_instructions WHERE key_id=? AND account_id=?',[result.id,actor.id]);if(!stored||stored.fields_json!==encoded)throw Error('Instruction reference conflict');return availableCode(result,actor.id);
},
async redeem(actor,{code,requestId}){
await permitted(actor,'web.jarvis.clans.reset');if(typeof code!=='string'||!uuid(requestId))throw TypeError('Enter the generated key');
const own=await first(db,'SELECT id FROM organisation_keys WHERE account_id=? AND key_type=? AND code_hash=?',[actor.id,'clan-administration',hashOrganisationKey(code,'clan-administration')]);if(!own)throw Error('Key unavailable for this account');
if(typeof code!=='string'||!uuid(requestId))throw TypeError('Enter the generated key');
const accountAction=parseOrganisationCode(code).prefix==='ACC-TEST',keyType=accountAction?'account-test-identity':'clan-administration',permission=accountAction?TEST_IDENTITY_PERMISSION:'web.jarvis.clans.reset',actionId=accountAction?TEST_IDENTITY_ACTION:'clan.clear-protected-rosters',scopePrefix=accountAction?'test-identity:':'protected-roster:';
await permitted(actor,permission);
const own=await first(db,'SELECT id FROM organisation_keys WHERE account_id=? AND key_type=? AND code_hash=?',[actor.id,keyType,hashOrganisationKey(code,keyType)]);if(!own)throw Error('Key unavailable for this account');
const instruction=await first(db,'SELECT * FROM jarvis_generated_instructions WHERE key_id=? AND account_id=?',[own.id,actor.id]);if(!instruction)throw Error('Instruction unavailable');
return keys.consume({accountId:actor.id,keyType:'clan-administration',code,targetId:instruction.request_id,requestId,apply:async(tx,{keyId,scopeId})=>{
await permitted(actor,'web.jarvis.clans.reset');
return keys.consume({accountId:actor.id,keyType,code,targetId:instruction.request_id,requestId,apply:async(tx,{keyId,scopeId})=>{
await permitted(actor,permission);
const row=await tx.first('SELECT * FROM jarvis_generated_instructions WHERE key_id=? AND account_id=? FOR UPDATE',[keyId,actor.id]);
if(!row||row.state!=='issued'||row.action_id!=='clan.clear-protected-rosters'||Number(row.template_version)!==1||scopeId!=='protected-roster:'+row.request_id)throw Error('Instruction scope changed');
if(!row||row.state!=='issued'||row.action_id!==actionId||Number(row.template_version)!==1||scopeId!==scopePrefix+row.request_id)throw Error('Instruction scope changed');
if(accountAction){
const manifest=JSON.parse(row.manifest_json),fields=JSON.parse(row.fields_json);
if(manifest.account?.username.toLowerCase()!==fields.accountName.toLowerCase())throw Error('Instruction account scope changed');
await applyTestIdentity(tx,manifest,{keyId,actorId:actor.id,now:clock()});
await tx.query("UPDATE jarvis_generated_instructions SET state='completed' WHERE key_id=?",[keyId]);
return;
}
const original=JSON.parse(row.manifest_json),current=await snapshot(tx);if(!equal(original,current))throw Error('Clan inventory changed; generate a fresh instruction');
for(const clan of current.targets){
await tx.query('DELETE FROM site_clan_members WHERE clan_id=?',[clan.id]);

View file

@ -3,6 +3,7 @@
const player=(prefix,purpose)=>Object.freeze({prefix,purpose,family:'player',operation:'redeem',playerRedeemable:true});
const system=(prefix,purpose,operation='execute')=>Object.freeze({prefix,purpose,family:'system',operation,playerRedeemable:false});
export const KEY_TYPES=Object.freeze({
'account-test-identity':player('ACC-TEST','synthetic-game-identity'),
'clan-administration':player('CLAN-ADM','protected-clan-roster-reset'),
'project-action':system('PRJ','server-project-action'),
'progression-policy':system('PRG','progression-policy-configuration'),

View file

@ -42,6 +42,7 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){
async inspect(code,{accountId=null,expectedType=null}={}){let parsed,keyType,hash;try{parsed=parseOrganisationCode(code);keyType=Object.keys(ORGANISATION_KEY_TYPES).find(k=>ORGANISATION_KEY_TYPES[k].prefix===parsed.prefix);if(!keyType)return{valid:false,state:'unsupported'};hash=hashOrganisationKey(code,keyType);}catch{return{valid:false,state:'invalid'};}const row=await readFirst(db,'SELECT id,account_id,key_type,expires_at,revoked_at,used_at FROM organisation_keys WHERE code_hash=?',[hash]);if(!row||accountId&&row.account_id!==accountId||expectedType&&row.key_type!==expectedType)return{valid:false,state:'invalid'};if(parsed.edition){if(!editions)return{valid:false,state:'unavailable'};const edition=await editions.read(row.id);if(['stage','version','season'].some(k=>edition[k]!==parsed.edition[k]))return{valid:false,state:'invalid'};}return{valid:true,type:row.key_type,purpose:type(row.key_type).purpose,state:row.revoked_at!=null?'revoked':row.used_at!=null?'used':row.expires_at!=null&&Number(row.expires_at)<=Date.now()?'expired':'available'};},
async issue({accountId,keyType,scopeId,expiresAt=null,authorize=null}){
type(keyType);
if(keyType==='account-test-identity'&&(typeof authorize!=='function'||!/^test-identity:[a-f0-9-]{36}$/i.test(scopeId)||expiresAt===null))throw TypeError('Test identities require a bound dossier and authority adapter');
if(keyType==='clan-administration'&&(typeof authorize!=='function'||!/^protected-roster:[a-f0-9-]{36}$/i.test(scopeId)||expiresAt===null))throw TypeError('Clan administration requires a bound dossier and authority adapter');
if(keyType==='project-action'&&(expiresAt!==null||typeof authorize!=='function'||!/^project:[a-f0-9-]{36}:[a-f0-9-]{36}$/i.test(scopeId)))throw new TypeError('Projects require a domain authority adapter');
if(keyType==='progression-policy'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^policy:S\d{2,4}:v[1-9]\d{0,5}$/.test(scopeId)))throw new TypeError('Progression policies require the system configuration adapter');
@ -59,7 +60,7 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){
if(keyType==='staff-company-royal'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||!/^company:[a-f0-9-]{36}$/i.test(scopeId)||typeof authorize!=='function'))throw new TypeError('Staff company keys require the system issuer and a company authority adapter');
const code=generateOrganisationKey(keyType),id=randomUUID(),now=Date.now(),issuedEdition=editions?await editions.current():null;
try{return await db.transaction(async tx=>{
if(keyType==='clan-administration')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(['clan-administration','account-test-identity'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(keyType==='project-action')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(keyType==='progression-policy')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(keyType==='gazette-news')await authorize(tx,{accountId,keyType,scopeId,keyId:id});

View file

@ -3,6 +3,7 @@ import {organisationRuntimeAccess} from './organisation-runtime.mjs';
export const NODES={
'web.jarvis.clans.reset':'Issue and redeem fixed protected-clan roster reset keys',
'web.jarvis.keys.view':'Browse JARVIS masterkey templates',
'web.jarvis.accounts.test-identity':'Issue and redeem synthetic test identities for unlinked accounts',
'web.progression.xp.correct':'Issue support-approved XP correction instruments',
'web.progression.seasons.manage':'Manage sealed seasonal XP transfers',
'web.projects.review':'Review and fund server projects from the Tax treasury',