diff --git a/website/node/organisation-key-service.mjs b/website/node/organisation-key-service.mjs index bf3260e5..e91fdb3d 100644 --- a/website/node/organisation-key-service.mjs +++ b/website/node/organisation-key-service.mjs @@ -24,7 +24,7 @@ export async function persistentOrganisationSecret({secret,path='/home/dunerealm export async function ensureOriginalKeys(keys,accountId){ const results=[]; - for(const keyType of ['clan-founding','company-founding'])results.push(await keys.issue({accountId,keyType,scopeId:'original'})); + for(const keyType of ['clan-founding','company-founding'])results.push(await keys.issue({accountId,keyType,scopeId:keys.foundingScope||'original'})); return {created:results.filter(r=>r.created).length,existing:results.filter(r=>!r.created).length}; } @@ -46,6 +46,6 @@ export async function currentCodexEdition(db,settings={}){ export async function openOrganisationKeyService(db,settings={}){ await initializeOrganisationKeys(db);await initializeCodexEditions(db); const resolveEdition=()=>currentCodexEdition(db,settings); - 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}); + const edition=await resolveEdition();const editions=createCodexEditions(db,{edition,resolveEdition});await editions.backfill(); + return createOrganisationKeys(db,{secret:await persistentOrganisationSecret({secret:settings.ORGANISATION_KEY_SECRET,path:settings.ORGANISATION_KEY_FILE}),editions,foundingScope:edition.stage==='beta'?'beta-1':'original'}); } diff --git a/website/node/organisation-keys.mjs b/website/node/organisation-keys.mjs index bf23d7a3..32eec77a 100644 --- a/website/node/organisation-keys.mjs +++ b/website/node/organisation-keys.mjs @@ -32,13 +32,15 @@ export async function initializeOrganisationKeys(db){for(const sql of organisati // 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}={}){ +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):[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required'); @@ -59,8 +61,8 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){ 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. - if(keyType.endsWith('-founding')&&(scopeId!=='original'||expiresAt!==null))throw new TypeError('Founding grant must use the lifetime original scope'); + // 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'); @@ -100,6 +102,11 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){ 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); diff --git a/website/tests/original-keys.test.mjs b/website/tests/original-keys.test.mjs index 22efa0d9..19b3f462 100644 --- a/website/tests/original-keys.test.mjs +++ b/website/tests/original-keys.test.mjs @@ -81,3 +81,6 @@ test('concurrent service starts share one private persistent encryption key',{sk }); test('disabled service identities receive no player founding keys',async()=>{const f=fixture();try{f.sql.prepare("UPDATE site_accounts SET password_hash='!service' WHERE id=?").run(other);assert.deepEqual(await grantCurrentAccountKeys(f.db,f.keys),{accounts:1,created:2,existing:0});assert.equal((await f.keys.list(other)).length,0);}finally{f.close();}}); + +test('Beta founding generation revokes only unspent Alpha keys and grants one fresh pair idempotently',async()=>{const f=fixture();try{await ensureOriginalKeys(f.keys,owner);const old=await f.keys.list(owner);const beta=createOrganisationKeys(f.db,{secret:'ab'.repeat(32),foundingScope:'beta-1'});assert.deepEqual(await ensureOriginalKeys(beta,owner),{created:2,existing:0});assert.deepEqual(await ensureOriginalKeys(beta,owner),{created:0,existing:2});const all=await beta.list(owner);assert.equal(all.filter(k=>k.scopeId==='original'&&k.status==='revoked').length,2);assert.equal(all.filter(k=>k.scopeId==='beta-1'&&k.status==='available').length,2);assert.equal(all.filter(k=>k.code).length,2);for(const key of old){assert.equal(all.find(k=>k.id===key.id).code,null);}await assert.rejects(beta.issue({accountId:owner,keyType:'clan-founding',scopeId:'original'}));}finally{f.close();}}); +test('Beta reissue preserves consumed Alpha receipt and rejects disabled identities',async()=>{const f=fixture();try{await ensureOriginalKeys(f.keys,owner);const used=(await f.keys.list(owner)).find(k=>k.keyType==='clan-founding');f.sql.prepare('UPDATE organisation_keys SET used_at=?,target_id=? WHERE id=?').run(42,clan,used.id);const beta=createOrganisationKeys(f.db,{secret:'ab'.repeat(32),foundingScope:'beta-1'});await ensureOriginalKeys(beta,owner);const all=await beta.list(owner);const historical=all.find(k=>k.id===used.id);assert.equal(historical.status,'used');assert.equal(historical.targetId,clan);assert.equal(historical.code,null);assert.equal(all.filter(k=>k.status==='available').length,2);f.sql.prepare("UPDATE site_accounts SET password_hash='!service' WHERE id=?").run(other);await assert.rejects(ensureOriginalKeys(beta,other));assert.equal((await beta.list(other)).length,0);}finally{f.close();}});