web/website/node/organisation-keys.mjs

104 lines
10 KiB
JavaScript

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({
'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 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 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}={}){
if(typeof secret!=='string'||!(/^[a-f0-9]{64}$/i).test(secret))throw new TypeError('A dedicated organisation key encryption secret is required');
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({
async issue({accountId,keyType,scopeId,expiresAt=null,authorize=null}){
type(keyType);
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.
if(keyType.endsWith('-founding')&&(scopeId!=='original'||expiresAt!==null))throw new TypeError('Founding grant must use the lifetime original 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(keyType==='political-clan'&&(!uuid(scopeId)||expiresAt===null))throw new TypeError('Political clan keys require an expiring office deed');
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 db.transaction(async tx=>{
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');
}
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(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 consume({accountId,keyType,code,targetId,requestId,apply}){
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};
});
}
});
}