web/tools/jarvis-dev-key.mjs

36 lines
2.9 KiB
JavaScript

// Server/CLI only. Never import this module into website code or expose it by API.
import {createHmac,createHash,randomUUID,timingSafeEqual} from 'node:crypto';
const hash=value=>createHash('sha256').update(value).digest('hex');
const canonical=value=>{
if(value===null||typeof value==='boolean'||typeof value==='string')return JSON.stringify(value);
if(typeof value==='number'&&Number.isSafeInteger(value))return String(value);
if(Array.isArray(value))return '['+value.map(canonical).join(',')+']';
if(value&&Object.getPrototypeOf(value)===Object.prototype)return '{'+Object.keys(value).sort().map(k=>JSON.stringify(k)+':'+canonical(value[k])).join(',')+'}';
throw TypeError('Invalid batch manifest');
};
export function createDevKeyAuthority({secret,environment,authorize,clock=Date.now}){
if(typeof secret!=='string'||!/^\w+$/.test(environment||'')||!/^[a-f0-9]{64}$/i.test(secret)||typeof authorize!=='function')throw TypeError('Developer authority configuration required');
const sign=payload=>createHmac('sha256',Buffer.from(secret,'hex')).update(payload).digest('hex');
const allowed=async actor=>{if(!actor?.id||!await authorize(actor))throw Error('Developer access required');};
return Object.freeze({
async issue(actor,manifest,{ttlMs=600000}={}){
await allowed(actor);
if(!Number.isSafeInteger(ttlMs)||ttlMs<1||ttlMs>900000||!['clan-reset','tariff-publication'].includes(manifest?.action)||manifest.state!=='planned')throw TypeError('Invalid developer batch');
const now=clock(),record={id:randomUUID(),environment,actorId:actor.id,issuedAt:now,expiresAt:now+ttlMs,manifestHash:hash(canonical(manifest)),manifest:JSON.parse(canonical(manifest))};
const payload=Buffer.from(canonical(record)).toString('base64url');
const key='DEV-BATCH.'+payload+'.'+sign(payload);
return {key,record,audit:{id:record.id,actorId:actor.id,environment,manifestHash:record.manifestHash,keyHash:hash(key),issuedAt:now,expiresAt:record.expiresAt}};
},
async verify(actor,key,expectedManifest){
await allowed(actor);
if(typeof key!=='string'||key.length>65536)throw Error('Invalid developer key');
const parts=key.split('.');if(parts.length!==3||parts[0]!=='DEV-BATCH'||!/^[a-f0-9]{64}$/.test(parts[2]))throw Error('Invalid developer key');
const wanted=Buffer.from(sign(parts[1]),'hex'),given=Buffer.from(parts[2],'hex');
if(!timingSafeEqual(wanted,given))throw Error('Invalid developer key');
let record;try{record=JSON.parse(Buffer.from(parts[1],'base64url').toString());}catch{throw Error('Invalid developer key');}
if(record.environment!==environment||record.actorId!==actor.id||record.expiresAt<=clock()||record.issuedAt>clock()||record.expiresAt-record.issuedAt>900000)throw Error('Developer key unavailable');
if(record.manifestHash!==hash(canonical(record.manifest))||record.manifestHash!==hash(canonical(expectedManifest)))throw Error('Batch manifest changed');
return record;
}
});
}