diff --git a/website/control-panel/public/codex-code-format.mjs b/website/control-panel/public/codex-code-format.mjs index 64b93949..7283ebc4 100644 --- a/website/control-panel/public/codex-code-format.mjs +++ b/website/control-panel/public/codex-code-format.mjs @@ -1,6 +1,6 @@ // Shared syntax only: a readable edition is never proof of ownership or authority. -const legacy=/^(CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-([A-F0-9]{48})$/; -const versioned=/^(CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/; +const legacy=/^(ACC-TEST|CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-([A-F0-9]{48})$/; +const versioned=/^(ACC-TEST|CLAN-ADM|PRJ|PRG|NEWS|XPC|XPX|ECO-SNAP|STAFF-LINK|STAFF-COM|STAFF-POL|XFR|CLAN-SUB|COM-SUB|POL-CLAN|QST|QSM|CLAN|COM|POL)-(ALPHA|BETA|LIVE)-((?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})-(S\d{2,4})-([A-F0-9]{8}(?:-[A-F0-9]{8}){5})$/; export function parseOrganisationCode(value){ if(typeof value!=='string'||value.length>128)throw new TypeError('Invalid organisation code'); const code=value.trim().toUpperCase(),old=code.match(legacy); diff --git a/website/control-panel/public/cp-v2/cp-v2-key-generator.mjs b/website/control-panel/public/cp-v2/cp-v2-key-generator.mjs index 8564f90c..c051f211 100644 --- a/website/control-panel/public/cp-v2/cp-v2-key-generator.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-key-generator.mjs @@ -28,7 +28,7 @@ export function createKeyGeneratorDesign({fetcher=fetch}={}){ function renderTemplates(){const before=component.input.value;component.input.replaceChildren();for(const t of templates){const o=el('option',t.label);o.value=t.id;component.input.append(o);}if(templates.some(t=>t.id===before))component.input.value=before;renderActions();} async function request(path,options){const response=await fetcher(path,{credentials:'same-origin',cache:'no-store',signal:controller.signal,...options});const data=await response.json();if(!response.ok)throw Error(data.message||'J.A.R.V.I.S. could not confirm the request.');return data;} async function write(path,body){busy=true;controls();try{const result=await request(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});if(!alive)return null;return result;}catch(error){if(alive){uncertain=true;status.textContent=error.message+' Reload before another write; no automatic retry is sent.';}return null;}finally{busy=false;if(alive)controls();}} - form.onsubmit=async e=>{e.preventDefault();if(busy||uncertain||issued||!form.reportValidity()||!confirmed.checked)return;const a=selected();if(!a?.available)return;const values=Object.fromEntries([...inputs].map(([name,{field,input}])=>[name,field.type==='number'?Number(input.value):input.value]));const result=await write('/api/jarvis/generator',{actionId:a.id,templateVersion:a.version,values,requestId:issueId,confirmed:true});if(!result)return;issued=true;issuedCode=result.code||'';output.textContent=issuedCode||'This instruction is '+result.status+'.';codeInput.value=issuedCode;copy.disabled=!issuedCode;status.textContent=issuedCode?'Key generated. This instruction is locked. Choose New instruction to generate another. No clan has been changed.':'Existing instruction returned; no duplicate key was issued.';updateSummary();}; + form.onsubmit=async e=>{e.preventDefault();if(busy||uncertain||issued||!form.reportValidity()||!confirmed.checked)return;const a=selected();if(!a?.available)return;const values=Object.fromEntries([...inputs].map(([name,{field,input}])=>[name,field.type==='number'?Number(input.value):input.value]));const result=await write('/api/jarvis/generator',{actionId:a.id,templateVersion:a.version,values,requestId:issueId,confirmed:true});if(!result)return;issued=true;issuedCode=result.code||'';output.textContent=issuedCode||'This instruction is '+result.status+'.';codeInput.value=issuedCode;copy.disabled=!issuedCode;status.textContent=issuedCode?'Key generated. This instruction is locked. Choose New instruction to generate another.':'Existing instruction returned; no duplicate key was issued.';updateSummary();}; redeemForm.onsubmit=async e=>{e.preventDefault();if(busy||uncertain||!redeemCheck.checked||!redeemForm.reportValidity())return;const result=await write('/api/jarvis/generator/redeem',{code:codeInput.value.trim(),requestId:redeemId,confirmed:true});if(!result)return;status.textContent=result.replayed?'This instruction was already completed.':'Instruction completed. Result recorded in J.A.R.V.I.S. history.';redeemCheck.checked=false;codeInput.value='';redeemId=crypto.randomUUID();controls();}; copy.onclick=()=>navigator.clipboard.writeText(issuedCode).then(()=>{if(alive)status.textContent='Key copied.';}).catch(()=>{if(alive)status.textContent='Select the key text to copy it.';}); fresh.onclick=()=>{renderFields();status.textContent='New instruction started with a new request reference.';}; diff --git a/website/control-panel/public/jarvis-master-keys.mjs b/website/control-panel/public/jarvis-master-keys.mjs index 7c0f121d..e64fc01d 100644 --- a/website/control-panel/public/jarvis-master-keys.mjs +++ b/website/control-panel/public/jarvis-master-keys.mjs @@ -28,6 +28,8 @@ export const MASTER_KEY_TEMPLATES=[ action('progression.policy','Season progression policy','progression-policy',[field('season','Season'),field('policyVersion','Policy version','number',{min:1})])]}, {id:'projects',label:'Server projects',actions:[action('projects.action','Project decision','project-action',[field('projectId','Project'),field('decision','Decision'),reference])]}, {id:'news',label:'Gazette',actions:[action('news.record','Confirmed public announcement','gazette-news',[field('sourceId','Confirmed source event'),reference],{recordOnly:true})]}, + {id:'accounts',label:'Accounts',actions:[ + action('accounts.test-minecraft-identity','Assign a synthetic test Minecraft UUID','account-test-identity',[field('accountName','Target account name'),reference],{webIssue:true,permission:'web.jarvis.accounts.test-identity',effect:'Generate and assign one synthetic test UUID to the named unlinked account. Never overwrites a game link or pending link challenge. This is not proof of Minecraft ownership.'})]}, {id:'items',label:'Items & kits',actions:[]}, {id:'events',label:'Events',actions:[]}, {id:'rihla',label:'Rihla',actions:[]} diff --git a/website/node/account-test-identity.mjs b/website/node/account-test-identity.mjs new file mode 100644 index 00000000..896d7745 --- /dev/null +++ b/website/node/account-test-identity.mjs @@ -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]); +} diff --git a/website/node/game-link.mjs b/website/node/game-link.mjs index 31ef5a86..14ee2bab 100644 --- a/website/node/game-link.mjs +++ b/website/node/game-link.mjs @@ -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); diff --git a/website/node/jarvis-generator-access.mjs b/website/node/jarvis-generator-access.mjs index a2d9aba3..4228618a 100644 --- a/website/node/jarvis-generator-access.mjs +++ b/website/node/jarvis-generator-access.mjs @@ -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; } diff --git a/website/node/jarvis-master-generator.mjs b/website/node/jarvis-master-generator.mjs index fc2d8baf..915b78ea 100644 --- a/website/node/jarvis-master-generator.mjs +++ b/website/node/jarvis-master-generator.mjs @@ -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]); diff --git a/website/node/organisation-key-policy.mjs b/website/node/organisation-key-policy.mjs index 8a2a4e66..8aa86455 100644 --- a/website/node/organisation-key-policy.mjs +++ b/website/node/organisation-key-policy.mjs @@ -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'), diff --git a/website/node/organisation-keys.mjs b/website/node/organisation-keys.mjs index 59e282ca..da5e6d82 100644 --- a/website/node/organisation-keys.mjs +++ b/website/node/organisation-keys.mjs @@ -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}); diff --git a/website/node/permissions.mjs b/website/node/permissions.mjs index d05a0a58..42c4b398 100644 --- a/website/node/permissions.mjs +++ b/website/node/permissions.mjs @@ -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', diff --git a/website/tests/account-test-identity.test.mjs b/website/tests/account-test-identity.test.mjs new file mode 100644 index 00000000..0b1ecfc1 --- /dev/null +++ b/website/tests/account-test-identity.test.mjs @@ -0,0 +1,59 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {companyFixture} from './company-deed-fixture.mjs'; +import {createMasterKeyGenerator,initializeJarvisGenerator} from '../node/jarvis-master-generator.mjs'; +import {TEST_IDENTITY_ACTION,TEST_IDENTITY_PERMISSION} from '../node/account-test-identity.mjs'; +import {createOrganisationKeys} from '../node/organisation-keys.mjs'; + +async function fixture(){ + const f=await companyFixture(); + f.db.sqlite.exec("ALTER TABLE site_game_links ADD COLUMN minecraft_name TEXT;ALTER TABLE site_game_links ADD COLUMN linked_at INTEGER;CREATE TABLE site_game_identities(minecraft_uuid TEXT PRIMARY KEY,first_linked_at INTEGER,last_name TEXT);CREATE TABLE site_link_challenges(user_id TEXT PRIMARY KEY,token_hash TEXT,expires_at INTEGER);CREATE TABLE account_audit(id TEXT PRIMARY KEY,actor_id TEXT,action TEXT,details TEXT,created_at INTEGER);"); + await f.db.query('DELETE FROM site_game_links WHERE user_id=?',[f.people.Other.id]); + await f.db.query("UPDATE site_accounts SET username='gsmaccount' WHERE id=?",[f.people.Other.id]); + let allowed=true,fail=false; + const central={prepare:f.db.prepare.bind(f.db),query:f.db.query.bind(f.db),transaction:work=>f.db.transaction(tx=>work({...tx,query:async(sql,args)=>{if(fail&&sql.startsWith('INSERT INTO site_test_game_identities'))throw Error('Storage failure');return tx.query(sql,args);}}))}; + await initializeJarvisGenerator(central,{mysql:false}); + const keys=createOrganisationKeys(central,{secret:'ab'.repeat(32)}),authorize=async(actor,node)=>allowed&&actor?.id===f.people.Owner.id; + return {...f,central,keys,authorize,service:createMasterKeyGenerator(central,keys,{authorize}),input:{actionId:TEST_IDENTITY_ACTION,templateVersion:1,requestId:randomUUID(),values:{ticketId:'unimatrix override',accountName:'gsmaccount',reference:'Owner-requested test identity'}},revoke:()=>{allowed=false;},fail:()=>{fail=true;}}; +} +test('saved master template generates one scoped key; redemption assigns a labelled test UUID once',async()=>{ + const f=await fixture();try{ + const others=await f.db.query('SELECT * FROM site_game_links ORDER BY user_id'),accounts=await f.db.query('SELECT * FROM site_accounts ORDER BY id'); + const key=await f.service.issue(f.people.Owner,f.input);assert.match(key.code,/^ACC-TEST-/);assert.deepEqual(await f.db.query('SELECT * FROM site_game_links ORDER BY user_id'),others); + assert.equal((await f.service.issue(f.people.Owner,f.input)).keyId,key.keyId); + const request={code:key.code,requestId:randomUUID()};await f.service.redeem(f.people.Owner,request);assert.equal((await f.service.redeem(f.people.Owner,request)).replayed,true); + const link=await f.db.first('SELECT * FROM site_game_links WHERE user_id=?',[f.people.Other.id]);assert.match(link.minecraft_uuid,/^[a-f0-9-]{14}4/);assert.equal(link.minecraft_name,'TEST_gsmaccount'); + const record=await f.db.first('SELECT * FROM site_test_game_identities WHERE minecraft_uuid=?',[link.minecraft_uuid]);assert.equal(record.key_id,key.keyId);assert.equal(record.issued_by,f.people.Owner.id); + assert.deepEqual(await f.db.query('SELECT * FROM site_game_links WHERE user_id<>? ORDER BY user_id',[f.people.Other.id]),others);assert.deepEqual(await f.db.query('SELECT * FROM site_accounts ORDER BY id'),accounts); + assert.equal((await f.db.first("SELECT COUNT(*) n FROM account_audit WHERE action='jarvis-test-game-identity-assigned'")).n,1); + }finally{f.db.close();} +}); +for(const scenario of ['linked','pending','renamed','disabled','role-change'])test('target change is rejected without consuming the key: '+scenario,async()=>{ + const f=await fixture();try{const key=await f.service.issue(f.people.Owner,f.input),id=f.people.Other.id; + if(scenario==='linked')await f.db.query('INSERT INTO site_game_links(user_id,minecraft_uuid) VALUES(?,?)',[id,randomUUID()]); + if(scenario==='pending')await f.db.query('INSERT INTO site_link_challenges VALUES(?,?,?)',[id,'pending',Date.now()+60000]); + if(scenario==='renamed')await f.db.query("UPDATE site_accounts SET username='changed' WHERE id=?",[id]); + if(scenario==='disabled')await f.db.query("UPDATE site_accounts SET password_hash='!locked' WHERE id=?",[id]); + if(scenario==='role-change')await f.db.query("UPDATE site_accounts SET role='owners' WHERE id=?",[id]); + const before=await f.db.query('SELECT * FROM site_game_links ORDER BY user_id');await assert.rejects(f.service.redeem(f.people.Owner,{code:key.code,requestId:randomUUID()}),/Instruction/);assert.deepEqual(await f.db.query('SELECT * FROM site_game_links ORDER BY user_id'),before);assert.equal((await f.keys.list(f.people.Owner.id)).find(k=>k.id===key.keyId).status,'available'); + }finally{f.db.close();} +}); +test('wrong issuer, revoked permission and injected fields cannot assign an identity',async()=>{ + const f=await fixture();try{ + await assert.rejects(f.service.issue(f.people.Member,f.input),/authority/); + await assert.rejects(f.service.issue(f.people.Owner,{...f.input,values:{...f.input.values,uuid:randomUUID()}}),/Unknown/); + const key=await f.service.issue(f.people.Owner,f.input);await assert.rejects(f.service.redeem(f.people.Member,{code:key.code,requestId:randomUUID()}),/authority/);f.revoke();await assert.rejects(f.service.redeem(f.people.Owner,{code:key.code,requestId:randomUUID()}),/authority/); + }finally{f.db.close();} +}); +test('UUID collision and partial write failure roll back the entire identity assignment',async()=>{ + for(const collision of [true,false]){const f=await fixture();try{ + const key=await f.service.issue(f.people.Owner,f.input),row=await f.db.first('SELECT manifest_json FROM jarvis_generated_instructions WHERE key_id=?',[key.keyId]),manifest=JSON.parse(row.manifest_json); + if(collision)await f.db.query('INSERT INTO site_game_identities VALUES(?,?,?)',[manifest.minecraftUuid,1,'already-used']);else f.fail(); + await assert.rejects(f.service.redeem(f.people.Owner,{code:key.code,requestId:randomUUID()}));assert.equal(await f.db.first('SELECT * FROM site_game_links WHERE user_id=?',[f.people.Other.id]),null);assert.equal(await f.db.first('SELECT * FROM site_test_game_identities WHERE key_id=?',[key.keyId]),null);assert.equal((await f.keys.list(f.people.Owner.id)).find(k=>k.id===key.keyId).status,'available'); + }finally{f.db.close();}} +}); +test('catalogue availability follows this action permission, not unrelated clan permissions',async()=>{ + const f=await fixture();try{const service=createMasterKeyGenerator(f.central,f.keys,{authorize:async(actor,node)=>node!==TEST_IDENTITY_PERMISSION}),catalogue=await service.catalogue(f.people.Owner);assert.equal(catalogue.templates.find(t=>t.id==='accounts').actions[0].available,false);await assert.rejects(service.issue(f.people.Owner,f.input),/authority/);}finally{f.db.close();} +}); +test('the core key service refuses unscoped or adapter-less account identity grants',async()=>{ + const f=await fixture();try{await assert.rejects(f.keys.issue({accountId:f.people.Owner.id,keyType:'account-test-identity',scopeId:'original'}),/bound dossier/);}finally{f.db.close();} +}); diff --git a/website/tests/jarvis-generator-access.test.mjs b/website/tests/jarvis-generator-access.test.mjs index c64472d7..f0fd0665 100644 --- a/website/tests/jarvis-generator-access.test.mjs +++ b/website/tests/jarvis-generator-access.test.mjs @@ -1,4 +1,5 @@ import test from 'node:test';import assert from 'node:assert/strict';import {jarvisGeneratorCan} from '../node/jarvis-generator-access.mjs'; const check=(access,node)=>jarvisGeneratorCan({}, {id:'verified-account'},node,{readAccess:async()=>access}); test('verified active central Owner CEO can use keygen without a newly seeded permission policy',async()=>{const access={rank:'org_owner_ceo',organisation:{mode:'active'},nodes:['web.ranks.manage']};assert.equal(await check(access,'web.jarvis.keys.view'),true);assert.equal(await check(access,'web.jarvis.clans.reset'),true);assert.equal(await check(access,'web.jarvis.dev.issue'),false);}); +test('synthetic account keys reuse verified owner authority; ordinary staff cannot inherit it',async()=>{assert.equal(await check({rank:'org_owner_ceo',organisation:{mode:'active'},nodes:['web.ranks.manage']},'web.jarvis.accounts.test-identity'),true);assert.equal(await check({rank:'org_officer',organisation:{mode:'active'},nodes:['web.ranks.manage']},'web.jarvis.accounts.test-identity'),false);}); test('existing staff can view through bureau authority but rank managers and former owners cannot inherit the protected reset',async()=>{for(const access of [{rank:'org_officer',organisation:{mode:'active'},nodes:['web.ranks.manage']},{rank:'user',nodes:['web.items.manage']}]){assert.equal(await check(access,'web.jarvis.keys.view'),true);assert.equal(await check(access,'web.jarvis.clans.reset'),false);}assert.equal(await check({rank:'org_owner_ceo',organisation:{mode:'active'},nodes:[]},'web.jarvis.clans.reset'),false);assert.equal(await check({rank:'user',nodes:['web.menu.exchange']},'web.jarvis.keys.view'),false);});