forked from unimatrix/web
code: persist Codex key editions without reissuing rights
This commit is contained in:
parent
6ab50e5b57
commit
21af4ed8ed
3 changed files with 188 additions and 90 deletions
18
website/node/codex-editions.mjs
Normal file
18
website/node/codex-editions.mjs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import {validateCodeEdition} from '../control-panel/public/codex-code-format.mjs';
|
||||
export const CODEX_EDITION_SCHEMA=`CREATE TABLE IF NOT EXISTS codex_instance_editions(instance_id CHAR(36) PRIMARY KEY,release_stage VARCHAR(8) NOT NULL,release_version VARCHAR(16) NOT NULL,season_id VARCHAR(8) NOT NULL,recorded_at BIGINT NOT NULL,legacy_baseline TINYINT NOT NULL DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
|
||||
export async function initializeCodexEditions(db){await db.query(CODEX_EDITION_SCHEMA);}
|
||||
export function createCodexEditions(db,{edition,resolveEdition=null,clock=Date.now}={}){
|
||||
const current=validateCodeEdition(edition);
|
||||
const values=row=>({stage:row.release_stage,version:row.release_version,season:row.season_id,legacyBaseline:!!row.legacy_baseline});
|
||||
return Object.freeze({
|
||||
async current(){return validateCodeEdition(resolveEdition?await resolveEdition():edition);},
|
||||
async record(tx,id,issuedEdition){const current=validateCodeEdition(issuedEdition||edition);await tx.query('INSERT INTO codex_instance_editions(instance_id,release_stage,release_version,season_id,recorded_at,legacy_baseline) VALUES(?,?,?,?,?,0)',[id,current.stage,current.version,current.season,clock()]);},
|
||||
async read(id,tx=db){const [row]=await tx.query('SELECT release_stage,release_version,season_id,legacy_baseline FROM codex_instance_editions WHERE instance_id=?',[id]);if(!row)throw Error('Code edition is unavailable');return values(row);},
|
||||
async forAccount(accountId){const rows=await db.query('SELECT e.* FROM codex_instance_editions e JOIN organisation_keys k ON k.id=e.instance_id WHERE k.account_id=?',[accountId]);return new Map(rows.map(row=>[row.instance_id,values(row)]));},
|
||||
async backfill(){
|
||||
// First registration of old records is labelled as a baseline, never an invented earlier release.
|
||||
// The primary key retains each instance's original edition on later deployments/seasons.
|
||||
await db.query('INSERT IGNORE INTO codex_instance_editions(instance_id,release_stage,release_version,season_id,recorded_at,legacy_baseline) SELECT id,?,?,?, ?,1 FROM organisation_keys',[current.stage,current.version,current.season,clock()]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -1,3 +1,6 @@
|
|||
import {readFileSync} from 'node:fs';
|
||||
import {readMenuBadges} from './menu-badges.mjs';
|
||||
import {createCodexEditions,initializeCodexEditions} from './codex-editions.mjs';
|
||||
import {randomBytes,randomUUID} from 'node:crypto';
|
||||
import {mkdir,writeFile,link,unlink,readFile,lstat} from 'node:fs/promises';
|
||||
import {dirname} from 'node:path';
|
||||
|
|
@ -37,6 +40,9 @@ export async function grantCurrentAccountKeys(db,keys){
|
|||
}
|
||||
|
||||
export async function openOrganisationKeyService(db,settings={}){
|
||||
await initializeOrganisationKeys(db);
|
||||
return createOrganisationKeys(db,{secret:await persistentOrganisationSecret({secret:settings.ORGANISATION_KEY_SECRET,path:settings.ORGANISATION_KEY_FILE})});
|
||||
await initializeOrganisationKeys(db);await initializeCodexEditions(db);
|
||||
const release=JSON.parse(readFileSync(new URL('../web/release.json',import.meta.url),'utf8'));
|
||||
const resolveEdition=async()=>({stage:settings.CODEX_RELEASE_STAGE||release.stage,version:settings.CODEX_RELEASE_VERSION||(await readMenuBadges(db)).releaseVersion,season:settings.CODEX_SEASON_ID||'S01'});
|
||||
const editions=createCodexEditions(db,{edition:await resolveEdition(),resolveEdition});await editions.backfill();
|
||||
return createOrganisationKeys(db,{secret:await persistentOrganisationSecret({secret:settings.ORGANISATION_KEY_SECRET,path:settings.ORGANISATION_KEY_FILE}),editions});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,81 +1,84 @@
|
|||
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({
|
||||
'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 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()}`;}
|
||||
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({
|
||||
'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 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 prefix=type(keyType).prefix;
|
||||
if(typeof code!=='string'||!new RegExp(`^${prefix}-[A-F0-9]{48}$`).test(code.trim().toUpperCase()))throw new TypeError('Invalid organisation code');
|
||||
return createHash('sha256').update(code.trim().toUpperCase()).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}={}){
|
||||
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}){
|
||||
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');
|
||||
const code=generateOrganisationKey(keyType),id=randomUUID(),now=Date.now();
|
||||
try{return await db.transaction(async tx=>{
|
||||
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]);
|
||||
await event(tx,{id,account_id:accountId},'issued',null,now);
|
||||
return {id,code,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]);
|
||||
return rows.map(row=>({id:row.id,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:row.revoked_at==null&&row.used_at==null&&(row.expires_at==null||Number(row.expires_at)>Date.now())?unseal(row.code_sealed,`${row.id}:${accountId}:${row.key_type}`):null}));
|
||||
},
|
||||
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 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});
|
||||
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};
|
||||
});
|
||||
}
|
||||
});
|
||||
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}){
|
||||
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');
|
||||
const code=generateOrganisationKey(keyType),id=randomUUID(),now=Date.now(),issuedEdition=editions?await editions.current():null;
|
||||
try{return await db.transaction(async tx=>{
|
||||
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});
|
||||
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};
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff