forked from unimatrix/web
156 lines
19 KiB
JavaScript
156 lines
19 KiB
JavaScript
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=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`,
|
|
`CREATE TABLE IF NOT EXISTS organisation_key_events (id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL,account_id CHAR(36) NOT NULL,event_type VARCHAR(16) NOT NULL,target_id CHAR(36) NULL,created_at BIGINT NOT NULL,INDEX organisation_key_history(key_id,created_at)) 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);
|
|
const readFirst=(db,sql,args=[])=>typeof db.first==='function'?db.first(sql,args):db.prepare(sql).bind(...args).first();
|
|
const type=v=>{if(!Object.hasOwn(ORGANISATION_KEY_TYPES,v))throw new TypeError('Unknown organisation key type');return ORGANISATION_KEY_TYPES[v];};
|
|
export function generateOrganisationKey(keyType){return `${type(keyType).prefix}-${randomBytes(24).toString('hex').toUpperCase()}`;}
|
|
export function hashOrganisationKey(code,keyType){
|
|
const parsed=parseOrganisationCode(code);if(parsed.prefix!==type(keyType).prefix)throw new TypeError('Invalid organisation code');
|
|
return createHash('sha256').update(parsed.canonical).digest('hex');
|
|
}
|
|
export class OrganisationKeyError extends Error {}
|
|
export function checkOrganisationKey(row,{accountId,keyType,targetId,requestId,now=Date.now()}){
|
|
if(!row||row.account_id!==accountId||row.key_type!==keyType)throw new OrganisationKeyError('Code unavailable for this account and purpose');
|
|
if(row.revoked_at!=null)throw new OrganisationKeyError('Code revoked');
|
|
if(row.used_at!=null){
|
|
if(row.target_id===targetId&&row.request_id===requestId)return 'replayed';
|
|
throw new OrganisationKeyError('Code already used');
|
|
}
|
|
if(row.expires_at!=null&&Number(row.expires_at)<=now)throw new OrganisationKeyError('Code expired');
|
|
return 'available';
|
|
}
|
|
export async function initializeOrganisationKeys(db){for(const sql of organisationKeySchema)await db.query(sql);}
|
|
|
|
// These methods are internal: callers must check identity and domain authority first.
|
|
// In particular, POL issuance requires an existing valid political decision.
|
|
export function createOrganisationKeys(db,{secret,editions=null,foundingScope='original'}={}){
|
|
if(typeof secret!=='string'||!(/^[a-f0-9]{64}$/i).test(secret))throw new TypeError('A dedicated organisation key encryption secret is required');
|
|
if(!['original','beta-1'].includes(foundingScope))throw new TypeError('Unknown founding grant generation');
|
|
const encryptionKey=Buffer.from(secret,'hex');
|
|
const seal=(code,aad)=>{const iv=randomBytes(12),cipher=createCipheriv('aes-256-gcm',encryptionKey,iv);cipher.setAAD(Buffer.from(aad));const encrypted=Buffer.concat([cipher.update(code,'utf8'),cipher.final()]);return [iv,cipher.getAuthTag(),encrypted].map(v=>v.toString('base64')).join('.');};
|
|
const unseal=(value,aad)=>{const [iv,tag,data]=value.split('.').map(v=>Buffer.from(v,'base64')),cipher=createDecipheriv('aes-256-gcm',encryptionKey,iv);cipher.setAAD(Buffer.from(aad));cipher.setAuthTag(tag);return Buffer.concat([cipher.update(data),cipher.final()]).toString('utf8');};
|
|
const event=(tx,row,action,targetId,now)=>tx.query('INSERT INTO organisation_key_events(id,key_id,account_id,event_type,target_id,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),row.id,row.account_id,action,targetId,now]);
|
|
return Object.freeze({
|
|
foundingScope,
|
|
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,transactionStore=null}){
|
|
if(transactionStore&&(!(keyType==='organisation-action'||keyType==='entity-state'&&accountId===STAFF_OFFICE_ACCOUNT_ID&&/^state:(?:political-decision|political-review-publication|political-agreement-reply|political-ballot-vote|imperial-rally-vote|naib-council|world-trade|war-medal|imperial-raid|imperial-raid-refund):[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required');
|
|
type(keyType);
|
|
if(keyType==='economy-operation'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^economy\.(reset-balances|repay-loans|federal-cycle):[a-f0-9-]{36}$/i.test(scopeId)))throw TypeError('Economic keys require a scoped system authority adapter');
|
|
if(keyType==='kit-definition'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^kitset:[a-f0-9-]{36}:v[1-9]\d{0,5}$/i.test(scopeId)))throw TypeError('Kit definitions require a saved set and authority adapter');
|
|
if(keyType==='item-definition'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^item:[a-f0-9-]{36}:v[1-9]\d{0,5}$/i.test(scopeId)))throw TypeError('Item definitions require a versioned system record and editor authority adapter');
|
|
if(keyType==='organisation-action'&&(expiresAt!==null||typeof authorize!=='function'||!/^game:[a-f0-9-]{36}$/.test(scopeId)))throw TypeError('Game organisation actions require a current deed adapter');
|
|
if(keyType==='character-allegiance'&&(expiresAt!==null||typeof authorize!=='function'||!/^house:[a-f0-9-]{36}:v[1-9]\d{0,8}$/.test(scopeId)))throw TypeError('House selection requires the authenticated current-player adapter');
|
|
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:(?:POL:)?S\d{2,4}:v[1-9]\d{0,5}$/.test(scopeId)))throw new TypeError('Progression policies require the system configuration adapter');
|
|
if(keyType==='system-identity'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^character:[a-z0-9_]{3,32}:v1$/.test(scopeId)))throw TypeError('System identities require a verified character adapter');
|
|
if(keyType==='entity-state'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^state:[a-z0-9_-]{1,32}:[a-f0-9-]{36}$/i.test(scopeId)))throw TypeError('Entity state requires a verified system event adapter');
|
|
if(keyType==='board-state'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^board:(clan|company|politics):[a-f0-9-]{36}$/i.test(scopeId)))throw TypeError('Board records require a resolved deed 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 per explicitly selected launch generation.
|
|
if(keyType.endsWith('-founding')&&(scopeId!==foundingScope||expiresAt!==null))throw new TypeError('Founding grant must use the current approved scope');
|
|
if(['clan-subhouse','company-subsidiary'].includes(keyType)&&(!(scopeId.split(':').length===3&&scopeId.split(':')[0]==='parent'&&uuid(scopeId.split(':')[1])&&uuid(scopeId.split(':')[2]))||typeof authorize!=='function'))throw new TypeError('Subhouse keys require a parent-deed scope and an authority adapter');
|
|
if(['quest','quest-milestone'].includes(keyType)&&(!/^S[0-9]{2,4}:[A-Za-z0-9_-]{1,96}$/.test(scopeId)||expiresAt!==null||typeof authorize!=='function'))throw new TypeError('Quest instruments require a stable seasonal scope and authority adapter');
|
|
if(keyType==='political-clan'&&(!uuid(scopeId)||expiresAt===null))throw new TypeError('Political clan keys require an expiring office deed');
|
|
if(['staff-parent-link','entity-transfer'].includes(keyType)&&(typeof authorize!=='function'||keyType==='staff-parent-link'&&accountId!==STAFF_OFFICE_ACCOUNT_ID))throw new TypeError('Parent links require an authority adapter');
|
|
if(keyType==='staff-claim'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^homeblock:(clan|company|protected):[a-f0-9-]{36}:[a-f0-9-]{36}$/i.test(scopeId)))throw new TypeError('Staff Home Block keys require the system issuer and staff overwrite authority');
|
|
if(keyType==='staff-office-royal'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||!/^office:[a-z_]{1,32}$/.test(scopeId)||typeof authorize!=='function'))throw new TypeError('Staff office keys require the system issuer and a protected-office authority adapter');
|
|
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 (transactionStore?(fn=>fn(transactionStore)):db.transaction.bind(db))(async tx=>{
|
|
if(keyType==='kit-definition')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
|
|
if(keyType==='item-definition')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
|
|
if(keyType==='organisation-action')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
|
|
if(keyType==='character-allegiance')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==='system-identity')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
|
|
if(keyType==='entity-state')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
|
|
if(keyType==='board-state')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(keyType==='economy-operation'){
|
|
if(accountId!==STAFF_OFFICE_ACCOUNT_ID||typeof authorize!=='function')throw new OrganisationKeyError('Economic system authority required');
|
|
await authorize(tx,{accountId,keyType,scopeId,keyId:id});
|
|
}
|
|
if(['staff-parent-link','entity-transfer'].includes(keyType))await authorize(tx,{accountId,keyType,scopeId,keyId:id});
|
|
if(keyType==='staff-claim')await authorize(tx,{accountId,keyType,scopeId,keyId:id});
|
|
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});
|
|
if(keyType==='political-clan'){
|
|
const term=await tx.first("SELECT faction,office,expires_at FROM political_office_terms WHERE id=? AND user_id=? AND outcome='winner' AND starts_at<=? AND expires_at>? FOR UPDATE",[scopeId,accountId,now,now]);
|
|
if(!term||Number(term.expires_at)!==expiresAt)throw new OrganisationKeyError('An active matching political office deed is required');
|
|
const count=await tx.first("SELECT COUNT(*) total FROM political_office_terms WHERE faction=? AND office=? AND outcome='winner' AND starts_at<=? AND expires_at>?",[term.faction,term.office,now,now]);
|
|
if(Number(count.total)!==1)throw new OrganisationKeyError('Political office deed is ambiguous');
|
|
}
|
|
|
|
if(keyType.endsWith('-founding')&&foundingScope==='beta-1'){
|
|
const account=await tx.first("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' FOR UPDATE",[accountId]);if(!account)throw new OrganisationKeyError('Eligible founding account required');
|
|
const previous=await tx.query("SELECT id,account_id FROM organisation_keys WHERE account_id=? AND key_type=? AND scope_id='original' AND revoked_at IS NULL AND used_at IS NULL FOR UPDATE",[accountId,keyType]);
|
|
for(const prior of previous){await tx.query('UPDATE organisation_keys SET revoked_at=? WHERE id=? AND used_at IS NULL AND revoked_at IS NULL',[now,prior.id]);await event(tx,prior,'revoked',null,now);}
|
|
}
|
|
await tx.query('INSERT INTO organisation_keys(id,account_id,key_type,scope_id,code_hash,code_sealed,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?)',[id,accountId,keyType,scopeId,hashOrganisationKey(code,keyType),seal(code,`${id}:${accountId}:${keyType}`),now,expiresAt]);
|
|
if(editions)await editions.record(tx,id,issuedEdition);
|
|
await event(tx,{id,account_id:accountId},'issued',null,now);
|
|
const edition=editions?await editions.read(id,tx):null;return {id,code:edition?formatOrganisationCode(code,edition):code,edition,created:true};
|
|
});}catch(error){
|
|
if(transactionStore||error.code!=='ER_DUP_ENTRY')throw error;
|
|
const prior=await db.query('SELECT id FROM organisation_keys WHERE account_id=? AND key_type=? AND scope_id=?',[accountId,keyType,scopeId]);
|
|
if(!prior[0])throw error;
|
|
// No replacement secret and no restored entitlement on retry.
|
|
return {id:prior[0].id,created:false};
|
|
}
|
|
},
|
|
async list(accountId){
|
|
if(!uuid(accountId))throw new TypeError('Invalid account');
|
|
const rows=await db.query('SELECT * FROM organisation_keys WHERE account_id=? ORDER BY created_at,id',[accountId]);
|
|
const editionMap=editions?await editions.forAccount(accountId):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 revoke({accountId,keyId,authorize}){
|
|
if(!uuid(accountId)||!uuid(keyId)||typeof authorize!=='function')throw new TypeError('Scoped key revocation authority required');
|
|
return db.transaction(async tx=>{
|
|
const row=await tx.first('SELECT * FROM organisation_keys WHERE id=? FOR UPDATE',[keyId]);
|
|
if(!row||row.account_id!==accountId)throw new OrganisationKeyError('Key unavailable for this account');
|
|
if(row.used_at!=null)throw new OrganisationKeyError('A used key cannot be revoked');
|
|
if(await authorize(tx,{accountId,keyId,keyType:row.key_type,scopeId:row.scope_id})!==true)throw new OrganisationKeyError('Current key revocation authority required');
|
|
if(row.revoked_at!=null)return {id:keyId,replayed:true};
|
|
const now=Date.now();await tx.query('UPDATE organisation_keys SET revoked_at=? WHERE id=?',[now,keyId]);await event(tx,row,'revoked',null,now);return {id:keyId,replayed:false};
|
|
});
|
|
},
|
|
async consume({accountId,keyType,code,targetId,requestId,apply}){
|
|
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=>{
|
|
const row=await tx.first('SELECT * FROM organisation_keys WHERE code_hash=? FOR UPDATE',[hash]),now=Date.now();
|
|
const parsed=parseOrganisationCode(code);if(parsed.edition){if(!row||!editions)throw new OrganisationKeyError('Code edition could not be verified');const edition=await editions.read(row.id,tx);if(['stage','version','season'].some(k=>parsed.edition[k]!==edition[k]))throw new OrganisationKeyError('Code edition does not match its original record');}
|
|
const state=checkOrganisationKey(row,{accountId,keyType,targetId,requestId,now});
|
|
if(state==='replayed')return {id:row.id,targetId,replayed:true};
|
|
// Domain writes MUST use this transaction. A failed creation/appointment consumes nothing.
|
|
await apply(tx,{keyId:row.id,targetId,purpose:type(keyType).purpose,scopeId:row.scope_id});
|
|
await tx.query('UPDATE organisation_keys SET used_at=?,target_id=?,request_id=? WHERE id=?',[now,targetId,requestId,row.id]);
|
|
await event(tx,row,'used',targetId,now);
|
|
return {id:row.id,targetId,replayed:false};
|
|
});
|
|
}
|
|
});
|
|
}
|

Staff