diff --git a/docs/design/CODEX-CONSUMABLE-FOUNDATION.md b/docs/design/CODEX-CONSUMABLE-FOUNDATION.md new file mode 100644 index 00000000..128f1de4 --- /dev/null +++ b/docs/design/CODEX-CONSUMABLE-FOUNDATION.md @@ -0,0 +1,38 @@ +# Codex consumable foundation + +Code batch, 17 November 2026. Internal modules only; no new public endpoint, +no automatic grants, no table initialization on application startup, and no +migration of existing organisation keys or kits in this batch. + +`codex-proofs.mjs` provides bounded, authenticated instance/revision proofs using +server-only HMAC-SHA256 keys. The active key issues new proofs; a configured +verification key ring retains historical verification across rotation. The +signed environment separates test from production. Signing keys must be supplied +by trusted server configuration and must remain distinct from encryption keys. +No rotation UI or persistent key-ring provisioning is enabled by this module. +A proof is not a private/public SSH key pair and does not convey domain authority. + +`codex-consumables.mjs` supplies the transactional consumable ledger. A trusted +server definition must provide issuance authority, use authority and an effect +handler. Issue identity, recipient, issuer, environment and edition are recorded. +The unique issue request prevents duplicate issuance; altered retries conflict. +Use locks the instance, checks domain authority and revision, performs the effect +and marks consumption in the same transaction. A failed effect rolls everything +back. Retrying the same completed request returns a replay result without another +effect. Copied proofs identify the same row and cannot consume it twice. +External mail/Discord/game delivery must use a transactional outbox, never a +network side effect inside the effect handler. Production MariaDB integration +must exercise simultaneous issuance and use before enabling a consuming adapter. + +This foundation does not yet provide transfers, replacement/revocation, staff +issuance screens, persistent physical-item custody, recruitment fees or listing +publication. These require their own domain adapters and audit events. Existing +organisation key consumption remains authoritative until explicitly migrated; +no second entitlement is granted here. Persistent items must not use this +consumable handler. + +Validation: cryptographic tampering, environment separation and verification-key +rotation tests; transactional database tests for duplicate use, same-request +replay, ownership, issuance authority, request conflicts and failed-handler +rollback. The local SQLite adapter serializes concurrent transactions; it checks +the service contract but does not establish MariaDB locking behaviour by itself. diff --git a/website/node/codex-consumables.mjs b/website/node/codex-consumables.mjs new file mode 100644 index 00000000..cdaf0b1b --- /dev/null +++ b/website/node/codex-consumables.mjs @@ -0,0 +1,40 @@ +import {randomUUID} from 'node:crypto'; +import {validateCodeEdition} from '../control-panel/public/codex-code-format.mjs'; +export const CODEX_CONSUMABLE_SCHEMA=`CREATE TABLE IF NOT EXISTS codex_consumable_instances(id CHAR(36) PRIMARY KEY,definition_id VARCHAR(64) NOT NULL,account_id CHAR(36) NOT NULL,issuer_id CHAR(36) NOT NULL,environment_id VARCHAR(48) NOT NULL,issue_request_id CHAR(36) NOT NULL UNIQUE,release_stage VARCHAR(8) NOT NULL,release_version VARCHAR(16) NOT NULL,season_id VARCHAR(8) NOT NULL,created_at BIGINT NOT NULL,revision INT NOT NULL,state VARCHAR(16) NOT NULL,use_request_id CHAR(36) NULL,used_at BIGINT NULL) 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); +export async function initializeCodexConsumables(db){await db.query(CODEX_CONSUMABLE_SCHEMA);} +// Internal foundation: no public issuance endpoint. Every definition supplies domain checks. +export function createCodexConsumables(db,{proofs,definitions,edition,clock=Date.now}){ + const types=new Map(Object.entries(definitions)); + for(const [id,d] of types)if(!/^[a-z][a-z0-9-]{0,63}$/.test(id)||!['authorizeIssue','authorizeUse','apply'].every(k=>typeof d[k]==='function'))throw TypeError('Incomplete Codex definition'); + const definition=id=>{const d=types.get(id);if(!d)throw Error('Unknown Codex definition');return d;}; + const output=row=>({id:row.id,definitionId:row.definition_id,state:row.state,edition:{stage:row.release_stage,version:row.release_version,season:row.season_id},proof:row.state==='available'?proofs.issue({instanceId:row.id,revision:Number(row.revision)}):null}); + return Object.freeze({ + async issue(actor,{definitionId,accountId,requestId}){ + if(!uuid(actor?.id)||!uuid(accountId)||!uuid(requestId))throw TypeError('Invalid Codex issuance'); + const d=definition(definitionId),origin=validateCodeEdition(await edition()); + return db.transaction(async tx=>{ + await d.authorizeIssue(tx,actor,{accountId}); + const prior=await tx.first('SELECT * FROM codex_consumable_instances WHERE issue_request_id=? FOR UPDATE',[requestId]); + if(prior){if(prior.account_id!==accountId||prior.definition_id!==definitionId||prior.environment_id!==proofs.environment||prior.issuer_id!==actor.id)throw Error('Codex request conflict');return output(prior);} + const row={id:randomUUID(),definition_id:definitionId,account_id:accountId,release_stage:origin.stage,release_version:origin.version,season_id:origin.season,revision:1,state:'available'}; + await tx.query('INSERT INTO codex_consumable_instances(id,definition_id,account_id,issuer_id,environment_id,issue_request_id,release_stage,release_version,season_id,created_at,revision,state) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)',[row.id,definitionId,accountId,actor.id,proofs.environment,requestId,origin.stage,origin.version,origin.season,clock(),1,'available']); + return output(row); + }); + }, + async use(actor,{proof,requestId}){ + if(!uuid(requestId))throw TypeError('Invalid Codex action');const identity=proofs.verify(proof); + return db.transaction(async tx=>{ + const row=await tx.first('SELECT * FROM codex_consumable_instances WHERE id=? FOR UPDATE',[identity.instanceId]); + if(!row||row.environment_id!==identity.environment)throw Error('Codex instance unavailable'); + const d=definition(row.definition_id);await d.authorizeUse(tx,actor,{accountId:row.account_id,instanceId:row.id}); + if(row.state==='used'&&row.use_request_id===requestId)return {id:row.id,replayed:true}; + if(row.state!=='available'||Number(row.revision)!==identity.revision)throw Error('Codex instance already used or changed'); + // Handler writes must use tx; external delivery belongs in its durable outbox. + await d.apply(tx,actor,{instanceId:row.id,accountId:row.account_id,requestId}); + await tx.query("UPDATE codex_consumable_instances SET state='used',revision=revision+1,use_request_id=?,used_at=? WHERE id=?",[requestId,clock(),row.id]); + return {id:row.id,replayed:false}; + }); + } + }); +} diff --git a/website/node/codex-proofs.mjs b/website/node/codex-proofs.mjs new file mode 100644 index 00000000..a04dc4fa --- /dev/null +++ b/website/node/codex-proofs.mjs @@ -0,0 +1,31 @@ +import {createHmac,timingSafeEqual} from 'node:crypto'; + +// Internal proof codec. Domain authority and atomic ledger consumption remain mandatory. +export function createCodexProofs({environment,activeKeyId,keys}) { + if(!/^[a-z0-9-]{1,48}$/.test(environment||''))throw TypeError('Invalid Codex environment'); + const ring=new Map(Object.entries(keys||{}).map(([id,key])=>{ + if(!/^[A-Za-z0-9_-]{1,48}$/.test(id)||typeof key!=='string'||!/^[a-f0-9]{64}$/i.test(key))throw TypeError('Invalid Codex signing key'); + return [id,Buffer.from(key,'hex')]; + })); + if(!ring.has(activeKeyId))throw TypeError('Active Codex signing key unavailable'); + const valid=p=>p&&p.v===1&&p.environment===environment&&typeof p.instanceId==='string'&&/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(p.instanceId)&&Number.isSafeInteger(p.revision)&&p.revision>=1; + const signature=(key,body)=>createHmac('sha256',key).update('dunerealms:codex:proof:v1\0').update(body).digest(); + return Object.freeze({ + environment, + issue({instanceId,revision}) { + const p={v:1,environment,instanceId,revision};if(!valid(p))throw TypeError('Invalid Codex instance identity'); + const body=Buffer.from(JSON.stringify(p)).toString('base64url'); + return `${activeKeyId}.${body}.${signature(ring.get(activeKeyId),body).toString('base64url')}`; + }, + verify(proof) { + if(typeof proof!=='string'||proof.length>1024)throw Error('Invalid Codex proof'); + const parts=proof.split('.');if(parts.length!==3||parts.some(x=>!x||!/^[A-Za-z0-9_-]+$/.test(x)))throw Error('Invalid Codex proof'); + const [keyId,body,mac]=parts,key=ring.get(keyId);if(!key)throw Error('Unknown Codex signing key'); + const received=Buffer.from(mac,'base64url'),expected=signature(key,body); + if(received.length!==expected.length||!timingSafeEqual(received,expected))throw Error('Invalid Codex proof'); + let p;try{p=JSON.parse(Buffer.from(body,'base64url').toString('utf8'));}catch{throw Error('Invalid Codex proof');} + if(!valid(p)||Object.keys(p).sort().join(',')!=='environment,instanceId,revision,v')throw Error('Invalid Codex proof'); + return Object.freeze({...p,keyId}); + } + }); +} diff --git a/website/tests/codex-consumables.test.mjs b/website/tests/codex-consumables.test.mjs new file mode 100644 index 00000000..0328d8e8 --- /dev/null +++ b/website/tests/codex-consumables.test.mjs @@ -0,0 +1,6 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {BankFixture} from './postbank-fixture.mjs';import {CODEX_CONSUMABLE_SCHEMA,createCodexConsumables} from '../node/codex-consumables.mjs';import {createCodexProofs} from '../node/codex-proofs.mjs'; +async function fixture(){const db=new BankFixture();await db.query(CODEX_CONSUMABLE_SCHEMA.replace(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4',''));await db.query('CREATE TABLE effects(id CHAR(36) PRIMARY KEY)');const owner={id:randomUUID()},staff={id:randomUUID()};let fail=false;const service=createCodexConsumables(db,{proofs:createCodexProofs({environment:'test',activeKeyId:'a',keys:{a:'11'.repeat(32)}}),edition:async()=>({stage:'alpha',version:'1.0.1.0',season:'S01'}),definitions:{'test-key':{authorizeIssue:async(tx,actor)=>{if(actor.id!==staff.id)throw Error('denied');},authorizeUse:async(tx,actor,{accountId})=>{if(actor.id!==accountId)throw Error('denied');},apply:async(tx,actor,{instanceId})=>{await tx.query('INSERT INTO effects(id) VALUES(?)',[instanceId]);if(fail)throw Error('domain failure');}}}});return {db,owner,staff,service,setFail:v=>{fail=v;}};} +test('a duplicated consumable has only one effect, with safe retries and ownership checks',async()=>{const f=await fixture();try{const requestId=randomUUID(),issued=await f.service.issue(f.staff,{definitionId:'test-key',accountId:f.owner.id,requestId});assert.equal((await f.service.issue(f.staff,{definitionId:'test-key',accountId:f.owner.id,requestId})).id,issued.id);await assert.rejects(f.service.issue(f.owner,{definitionId:'test-key',accountId:f.owner.id,requestId:randomUUID()}),/denied/);await assert.rejects(f.service.use(f.staff,{proof:issued.proof,requestId:randomUUID()}),/denied/);const action=randomUUID(),results=await Promise.allSettled([f.service.use(f.owner,{proof:issued.proof,requestId:action}),f.service.use(f.owner,{proof:issued.proof,requestId:randomUUID()})]);assert.equal(results.filter(r=>r.status==='fulfilled').length,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM effects')).n,1);assert.equal((await f.service.use(f.owner,{proof:issued.proof,requestId:action})).replayed,true);const retry=await f.service.issue(f.staff,{definitionId:'test-key',accountId:f.owner.id,requestId});assert.equal(retry.state,'used');assert.equal(retry.proof,null);}finally{f.db.close();}}); +test('domain failure rolls back both effect and consumption, and altered issuance retries conflict',async()=>{const f=await fixture();try{const requestId=randomUUID(),issued=await f.service.issue(f.staff,{definitionId:'test-key',accountId:f.owner.id,requestId});await assert.rejects(f.service.issue(f.staff,{definitionId:'test-key',accountId:randomUUID(),requestId}),/conflict/);f.setFail(true);await assert.rejects(f.service.use(f.owner,{proof:issued.proof,requestId:randomUUID()}),/domain failure/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM effects')).n,0);assert.equal((await f.db.first('SELECT state FROM codex_consumable_instances')).state,'available');f.setFail(false);await f.service.use(f.owner,{proof:issued.proof,requestId:randomUUID()});assert.equal((await f.db.first('SELECT COUNT(*) n FROM effects')).n,1);}finally{f.db.close();}}); + diff --git a/website/tests/codex-proofs.test.mjs b/website/tests/codex-proofs.test.mjs new file mode 100644 index 00000000..72ca9996 --- /dev/null +++ b/website/tests/codex-proofs.test.mjs @@ -0,0 +1,32 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {createCodexProofs} from '../node/codex-proofs.mjs'; +const instanceId='12345678-1234-4234-8234-123456789abc'; +const old='11'.repeat(32),next='22'.repeat(32); +const codec=(activeKeyId='s1',keys={s1:old},environment='production')=>createCodexProofs({environment,activeKeyId,keys}); +test('rotation retains old proof verification and issues under the new key',()=>{ + const proof=codec().issue({instanceId,revision:1}); + const rotated=codec('s2',{s1:old,s2:next}); + assert.equal(rotated.verify(proof).keyId,'s1'); + assert.equal(rotated.verify(rotated.issue({instanceId,revision:2})).keyId,'s2'); + assert.throws(()=>codec('s2',{s2:next}).verify(proof)); +}); +test('test proofs cannot cross into production even with the same key',()=>{ + const proof=codec('s1',{s1:old},'test').issue({instanceId,revision:1}); + assert.throws(()=>codec().verify(proof)); +}); +test('changed identity or revision cannot retain a valid proof',()=>{ + const c=codec(),proof=c.issue({instanceId,revision:1}),parts=proof.split('.'); + const payload=JSON.parse(Buffer.from(parts[1],'base64url').toString());payload.revision=2; + parts[1]=Buffer.from(JSON.stringify(payload)).toString('base64url');assert.throws(()=>c.verify(parts.join('.'))); + assert.throws(()=>c.verify(proof+'.extra')); + assert.throws(()=>c.issue({instanceId,revision:0})); + assert.throws(()=>c.verify('x'.repeat(1025))); +}); +test('proof discloses only instance identity and revision, never signing material',()=>{ + const c=codec(),proof=c.issue({instanceId,revision:3}); + assert.deepEqual(c.verify(proof),{v:1,environment:'production',instanceId,revision:3,keyId:'s1'}); + assert.equal(proof.includes(old),false); + assert.throws(()=>codec('missing')); + assert.throws(()=>codec('s1',{s1:'weak'})); +});