31 lines
2.1 KiB
JavaScript
31 lines
2.1 KiB
JavaScript
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});
|
|
}
|
|
});
|
|
}
|

Staff