Classify JARVIS player keys and sealed system instruments; hide system redemption secrets

This commit is contained in:
unimatrixgit 2026-11-18 22:50:51 +01:00
commit 12da2b6a85
3 changed files with 75 additions and 25 deletions

View file

@ -1,5 +1,6 @@
import {identity} from './auth.mjs';
import {can} from './permissions.mjs';
import {KEY_TYPES} from './organisation-key-policy.mjs';
import {currentCodexEdition} from './organisation-key-service.mjs';
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
const SECTIONS={
@ -24,7 +25,8 @@ export function createJarvisManagement(central,bank,settings={},deps={}){
const db=definition.store==='central'?central:bank;if(!db)return reply({message:'Register temporarily unavailable.'},503);
try{
const args=[26,(page-1)*25],sql=definition.sql+' LIMIT ? OFFSET ?',rows=definition.store==='central'?(await db.prepare(sql).bind(...args).all()).results:await db.query(sql,args);
return reply({section,page,hasMore:rows.length>25,records:rows.slice(0,25)});
const records=rows.slice(0,25).map(row=>section==='keys'?{...row,family:KEY_TYPES[row.type]?.family||'unclassified',operation:KEY_TYPES[row.type]?.operation||'restricted',playerRedeemable:KEY_TYPES[row.type]?.playerRedeemable===true}:row);
return reply({section,page,hasMore:rows.length>25,records});
}catch(error){if(/doesn't exist|no such table|unknown column/i.test(error.message||''))return reply({message:'This register is not installed yet.'},503);throw error;}
};
}

View file

@ -0,0 +1,25 @@
// Single server-side catalogue. Developer capabilities deliberately do not belong
// here: they have no website issuance, receipt or redemption surface.
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({
'progression-policy':system('PRG','progression-policy-configuration'),
'gazette-news':system('NEWS','public-news-record','record'),
'xp-correction':player('XPC','approved-xp-correction'),
'xp-transfer':player('XPX','season-xp-transfer'),
'economy-snapshot':system('ECO-SNAP','immutable-economic-record','record'),
'staff-parent-link':system('STAFF-LINK','protected-parent-link'),
'entity-transfer':system('XFR','entity-transfer'),
'quest':system('QST','persistent-quest'),
'quest-milestone':system('QSM','progression-milestone','record'),
'staff-office-royal':system('STAFF-POL','protected-office-royal'),
'staff-company-royal':system('STAFF-COM','company-royal'),
'clan-subhouse':player('CLAN-SUB','subhouse-founding'),
'company-subsidiary':player('COM-SUB','subsidiary-founding'),
'political-clan':system('POL-CLAN','office-membership'),
'clan-founding':player('CLAN','original-founding'),
'company-founding':player('COM','original-founding'),
'political-appointment':player('POL','appointment')
});
export function keyPolicy(type){const value=KEY_TYPES[type];if(!Object.hasOwn(KEY_TYPES,type))throw TypeError('Unknown organisation key type');return value;}
export function privateKeyPresentation(type){const {family,operation,playerRedeemable}=keyPolicy(type);return {family,operation,playerRedeemable,showCode:playerRedeemable};}

View file

@ -1,22 +1,9 @@
import {KEY_TYPES,keyPolicy} from './organisation-key-policy.mjs';
import {parseOrganisationCode,formatOrganisationCode} from '../control-panel/public/codex-code-format.mjs';
import {createHash,createCipheriv,createDecipheriv,randomBytes,randomUUID} from 'node:crypto';
// Server-only. A secret grants a recorded entitlement; it is never an API credential.
export const ORGANISATION_KEY_TYPES=Object.freeze({
'economy-snapshot':Object.freeze({prefix:'ECO-SNAP',purpose:'immutable-economic-record'}),
'staff-parent-link':Object.freeze({prefix:'STAFF-LINK',purpose:'protected-parent-link'}),
'entity-transfer':Object.freeze({prefix:'XFR',purpose:'entity-transfer'}),
'quest':Object.freeze({prefix:'QST',purpose:'persistent-quest'}),
'quest-milestone':Object.freeze({prefix:'QSM',purpose:'progression-milestone'}),
'staff-office-royal':Object.freeze({prefix:'STAFF-POL',purpose:'protected-office-royal'}),
'staff-company-royal':Object.freeze({prefix:'STAFF-COM',purpose:'company-royal'}),
'clan-subhouse':Object.freeze({prefix:'CLAN-SUB',purpose:'subhouse-founding'}),
'company-subsidiary':Object.freeze({prefix:'COM-SUB',purpose:'subsidiary-founding'}),
'political-clan':Object.freeze({prefix:'POL-CLAN',purpose:'office-membership'}),
'clan-founding':Object.freeze({prefix:'CLAN',purpose:'original-founding'}),
'company-founding':Object.freeze({prefix:'COM',purpose:'original-founding'}),
'political-appointment':Object.freeze({prefix:'POL',purpose:'appointment'})
});
export const ORGANISATION_KEY_TYPES=KEY_TYPES;
export const STAFF_OFFICE_ACCOUNT_ID='00000000-0000-4000-8000-000000000041';
export const organisationKeySchema=Object.freeze([
`CREATE TABLE IF NOT EXISTS organisation_keys (id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,key_type VARCHAR(32) NOT NULL,scope_id VARCHAR(160) NOT NULL,code_hash CHAR(64) NOT NULL UNIQUE,code_sealed TEXT NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NULL,revoked_at BIGINT NULL,used_at BIGINT NULL,target_id CHAR(36) NULL,request_id CHAR(36) NULL,UNIQUE KEY organisation_key_grant(account_id,key_type,scope_id),INDEX organisation_key_owner(account_id,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
@ -54,6 +41,9 @@ 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==='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');
if(['xp-correction','xp-transfer'].includes(keyType)&&(expiresAt!==null||typeof authorize!=='function'))throw new TypeError('XP instruments require a domain authority adapter');
if(keyType==='economy-snapshot'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||!/^snapshot:[a-f0-9-]{36}$/i.test(scopeId)||typeof authorize!=='function'))throw new TypeError('Economic snapshots require a system record and authority adapter');
if(!uuid(accountId)||typeof scopeId!=='string'||!scopeId.trim()||scopeId.length>160||expiresAt!==null&&(!Number.isSafeInteger(expiresAt)||expiresAt<=Date.now()))throw new TypeError('Invalid key grant');
// Founding is once per account for its entire lifetime, including after sale/archive.
@ -66,9 +56,12 @@ 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==='progression-policy')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(keyType==='gazette-news')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(['xp-correction','xp-transfer'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(keyType==='economy-snapshot')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(['staff-parent-link','entity-transfer'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId});
if(['quest','quest-milestone'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId});
if(['quest','quest-milestone'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId,keyId:id});
if(keyType==='staff-office-royal')await authorize(tx,{accountId,keyType,scopeId});
if(keyType==='staff-company-royal')await authorize(tx,{accountId,keyType,scopeId});
if(['clan-subhouse','company-subsidiary'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId});
@ -98,7 +91,7 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){
return rows.map(row=>{const edition=editionMap?.get(row.id);if(editions&&!edition)throw Error('Code edition is unavailable');const available=row.revoked_at==null&&row.used_at==null&&(row.expires_at==null||Number(row.expires_at)>Date.now());const raw=available?unseal(row.code_sealed,`${row.id}:${accountId}:${row.key_type}`):null;return {id:row.id,edition,keyType:row.key_type,scopeId:row.scope_id,createdAt:Number(row.created_at),targetId:row.target_id,status:row.revoked_at!=null?'revoked':row.used_at!=null?'used':row.expires_at!=null&&Number(row.expires_at)<=Date.now()?'expired':'available',code:raw&&edition?formatOrganisationCode(raw,edition):raw};});
},
async consume({accountId,keyType,code,targetId,requestId,apply}){
if(keyType==='economy-snapshot')throw new OrganisationKeyError('Economic snapshots are sealed records and cannot be redeemed');
if(keyPolicy(keyType).operation==='record')throw new OrganisationKeyError('Sealed system records cannot be redeemed');
if(!uuid(accountId)||!uuid(targetId)||!uuid(requestId)||typeof apply!=='function')throw new TypeError('Invalid key redemption');
const hash=hashOrganisationKey(code,keyType);
return db.transaction(async tx=>{