Build template-driven JARVIS key generation and recipient-bound protected clan reset redemption

This commit is contained in:
unimatrixgit 2026-11-19 19:29:27 +01:00
commit 76bbe902fe
6 changed files with 222 additions and 36 deletions

View file

@ -0,0 +1,27 @@
import {identity} from './auth.mjs';import {can} from './permissions.mjs';import {createMasterKeyGenerator} from './jarvis-master-generator.mjs';
export function createMasterKeyGeneratorAPI(db,keys,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),authorize=(u,node)=>can(db,u,node)}={}){
const service=keys?createMasterKeyGenerator(db,keys,{authorize}):null;
const reply=(d,s=200)=>Response.json(d,{status:s,headers:{'Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}});
return async request=>{
const user=await authenticate(request);if(!user)return reply({message:'Sign in to use J.A.R.V.I.S.'},401);
const url=new URL(request.url);if(url.search)return reply({message:'Query overrides are not accepted.'},400);
if(!await authorize(user,'web.jarvis.keys.view'))return reply({message:'Masterkey access required.'},403);
if(!service)return reply({message:'The key service is unavailable.'},503);
try{
if(request.method==='GET'){
if(url.pathname.endsWith('/history')){const rows=(await db.prepare('SELECT action_id,template_version,state,created_at FROM jarvis_generated_instructions WHERE account_id=? ORDER BY created_at DESC LIMIT 100').bind(user.id).all()).results;return reply({records:rows});}
return reply(await service.catalogue(user));
}
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403);
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
const reader=request.body?.getReader(),parts=[];let size=0;if(!reader)return reply({message:'Instruction required.'},400);
while(true){const r=await reader.read();if(r.done)break;size+=r.value.byteLength;if(size>8192){await reader.cancel();return reply({message:'Instruction too large.'},413);}parts.push(r.value);}
let input;try{input=JSON.parse(Buffer.concat(parts).toString('utf8'));}catch{return reply({message:'Invalid instruction.'},400);}
const redeem=url.pathname.endsWith('/redeem'),fields=redeem?['code','requestId','confirmed']:['actionId','templateVersion','values','requestId','confirmed'];
if(!input||Array.isArray(input)||input.confirmed!==true||Object.keys(input).some(k=>!fields.includes(k)))return reply({message:'Review and confirm the instruction.'},400);
const fresh=await authenticate(request);if(fresh?.id!==user.id||!await authorize(fresh,'web.jarvis.keys.view'))return reply({message:'Your session or authority changed.'},403);
return reply({ok:true,...await service[redeem?'redeem':'issue'](fresh,input)});
}catch(error){const message=error.message||'';const safe=/^(Devkeys|Masterkey|Choose |Invalid |Unknown |Instruction |Protected |Clan inventory|Key unavailable|Enter |Dossier)/.test(message);return reply({message:safe?message:'The instruction could not be confirmed. Reload before retrying.'},/authority/.test(message)?403:409);}
};
}

View file

@ -0,0 +1,62 @@
import {assertWebIssuableMaster} from './jarvis-web-key-boundary.mjs';
import {hashOrganisationKey} from './organisation-keys.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)`;
export const PROTECTED_RESET_TARGETS=Object.freeze(['113e9471-6288-43d6-ad8e-25286964413f','b82339e5-a2d4-4335-85de-463fd3ee827f']);
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
export async function initializeJarvisGenerator(db,{mysql=true}={}){
await db.query(GENERATOR_SCHEMA);
if(mysql){const column=await db.first("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;
}
async function snapshot(tx){
const targets=[];
for(const id of PROTECTED_RESET_TARGETS){
const clan=await tx.first('SELECT id,name,owner_id,active,version FROM site_clans WHERE id=? FOR UPDATE',[id]);
const institution=await tx.first('SELECT institution_key FROM site_clan_institutions WHERE clan_id=? FOR UPDATE',[id]);
if(!clan||Number(clan.active)!==1||!institution||!['bene','guild'].includes(institution.institution_key))throw Error('Protected clan identity changed');
const members=await tx.query('SELECT user_id,clan_role FROM site_clan_members WHERE clan_id=? ORDER BY user_id FOR UPDATE',[id]);
targets.push({...clan,institution:institution.institution_key,members});
}
return {targets,inventoryHash:hash(targets),preserve:['clans','claims','POL','Crysknife','companies','balances']};
}
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 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');
await permitted(actor,action.permission);const fields=validateMasterFields(action,values),encoded=JSON.stringify(fields);
const prior=await db.first('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);
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,manifestHash:manifest.inventoryHash}),clock()]);
}});const stored=await db.first('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 db.first('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');
const instruction=await db.first('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');
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');
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]);
await tx.query('UPDATE site_clans SET owner_id=NULL,version=version+1,updated_at=? WHERE id=?',[clock(),clan.id]);
await tx.query('UPDATE site_clan_deeds SET heir_account_id=NULL,consort_account_id=NULL,heir_joined_at=NULL,consort_joined_at=NULL,envoy_account_id=NULL,envoy_joined_at=NULL,arms_account_id=NULL,arms_joined_at=NULL,version=version+1,updated_at=? WHERE clan_id=?',[clock(),clan.id]);
await tx.query("UPDATE site_clan_requests SET status='closed',updated_at=? WHERE clan_id=? AND status='pending'",[clock(),clan.id]);
}
await tx.query("UPDATE jarvis_generated_instructions SET state='completed' WHERE key_id=?",[keyId]);
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'jarvis-protected-rosters-cleared',JSON.stringify({keyId,targets:PROTECTED_RESET_TARGETS,membersRemoved:current.targets.reduce((n,c)=>n+c.members.length,0),ownersVacated:true}),clock()]);
}});
}
});
}

View file

@ -0,0 +1,6 @@
// This is a fixed boundary, not a permission node. Owners cannot override it.
const reserved=/^(?:dev(?:eloper)?(?:[-_.:]|$)|root(?:[-_.:]|$)|sudo(?:[-_.:]|$))/i;
export function assertWebIssuableMaster(action){
if(!action||typeof action.id!=='string'||typeof action.keyType!=='string'||reserved.test(action.id)||reserved.test(action.keyType)||action.devOnly===true||action.family==='developer'||action.family==='dev'||action.serverOnly===true)throw Error('Devkeys cannot be generated or updated by the website');
return action;
}

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({
'clan-administration':player('CLAN-ADM','protected-clan-roster-reset'),
'project-action':system('PRJ','server-project-action'),
'progression-policy':system('PRG','progression-policy-configuration'),
'gazette-news':system('NEWS','public-news-record','record'),

View file

@ -41,6 +41,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 db.first('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==='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');
if(keyType==='gazette-news'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^news:[a-f0-9-]{36}:v[1-9]\d{0,5}$/i.test(scopeId)))throw new TypeError('Gazette instruments require a confirmed system publication adapter');
@ -57,6 +58,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(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

@ -1,6 +1,8 @@
import {JARVIS_IDENTITY,isJarvisIdentity} from './jarvis-identity.mjs';
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.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',