Files
MikrotikManager/backend/src/services/bandwidth-external-peer-source.ts
T

151 lines
12 KiB
TypeScript

/** Explicitly configured encrypted external management endpoint, one peer and
* one original operator-window lifetime. No provisioning/default source or
* wire mapping. Public metadata never certifies keys, Q or current license. */
import { createDecipheriv, createHash } from "node:crypto"
import { lstat, realpath } from "node:fs/promises"
import { dirname, isAbsolute, resolve } from "node:path"
import { performance } from "node:perf_hooks"
import { isDeepStrictEqual, types } from "node:util"
import { z } from "zod"
import { readBandwidthControlFile } from "./bandwidth-control-source.js"
import { canonicalBandwidthNodeValue as canonical } from "./bandwidth-node-bootstrap.js"
import { parseBandwidthPeerRef, type BandwidthPeerRef } from "./bandwidth-peer-reference.js"
import type { BandwidthNodeObservationScope } from "./bandwidth-node-observation.js"
import type { BandwidthPeerSourceSnapshot, BandwidthPeerTrustedSource } from "./bandwidth-peer-observation.js"
import { assertBandwidthOperatorPeerSourceGuard, type BandwidthOperatorPeerSourceGuard, type BandwidthOperatorPeerSourceBinding } from "./bandwidth-operator-writer-window.js"
export interface ExternalBandwidthPeerSourceConfig {
profileFile:string;keyFile:string;installationId:string;enrollmentId:string;keySha256:string
}
export class BandwidthExternalPeerSourceError extends Error {
readonly code="BANDWIDTH_EXTERNAL_PEER_SOURCE_UNAVAILABLE"
constructor(){super("Configured external peer source unavailable")}
}
const fail=():never=>{throw new BandwidthExternalPeerSourceError()}
const hash=z.string().regex(/^[a-f0-9]{64}$/),uuid=z.string().uuid().refine(value=>value===value.toLowerCase())
const profileSchema=z.object({format:z.literal("mmapp-bandwidth-external-management-v1"),installationId:uuid,enrollmentId:uuid,generation:uuid,enabled:z.boolean(),routingEndpointEpoch:uuid,keySha256:hash,ciphertext:z.string().min(39).max(131072).regex(/^[A-Za-z0-9_-]+$/)}).strict()
const endpointSchema=z.object({host:z.string().min(1).max(1000).refine(value=>!/[\s/\\\x00-\x1f\x7f]/.test(value)),port:z.number().int().min(1).max(65535),useSsl:z.boolean(),verifySsl:z.boolean(),username:z.string().refine(value=>Buffer.byteLength(value)<=1000),password:z.string().refine(value=>Buffer.byteLength(value)<=65536)}).strict()
const sha=(value:string|Buffer)=>createHash("sha256").update(value).digest("hex")
function fields(value:unknown,names:readonly string[],optional=false){
if(!value||typeof value!=="object"||types.isProxy(value)||Object.getPrototypeOf(value)!==Object.prototype)fail()
const descriptors=Object.getOwnPropertyDescriptors(value)
if(Reflect.ownKeys(descriptors).some(key=>typeof key!=="string"||!names.includes(key))||!optional&&Object.keys(descriptors).length!==names.length||Object.values(descriptors).some(field=>!("value"in field)||!field.enumerable))fail()
return descriptors
}
function peer(value:unknown,enrollmentId:string){
fields(value,["kind","enrollmentId"])
const parsed=parseBandwidthPeerRef(value)
if(parsed.kind!=="external"||parsed.enrollmentId!==enrollmentId)fail()
return parsed
}
type Directory={dev:number;ino:number}
/** Trusted server construction only. Profile/AAD is canonical UTF-8 JSON.
* ciphertext is base64url(iv12 || GCM-tag16 || ciphertext), following the
* existing seal framing with NEW AAD binding ALL public header fields. */
export function createConfiguredExternalBandwidthPeerSource(raw:ExternalBandwidthPeerSourceConfig,guard:BandwidthOperatorPeerSourceGuard):BandwidthPeerTrustedSource&{close():void}{
let config:Readonly<ExternalBandwidthPeerSourceConfig>
try{
const data=fields(raw,["profileFile","keyFile","installationId","enrollmentId","keySha256"])
config=Object.freeze({profileFile:data.profileFile.value,keyFile:data.keyFile.value,installationId:uuid.parse(data.installationId.value),enrollmentId:uuid.parse(data.enrollmentId.value),keySha256:hash.parse(data.keySha256.value)})
if([config.profileFile,config.keyFile].some(path=>typeof path!=="string"||!isAbsolute(path)||resolve(path)!==path)||config.profileFile===config.keyFile)fail()
assertBandwidthOperatorPeerSourceGuard(guard)
if(config.installationId!==guard.installationId)fail()
}catch{return fail()}
const verifyRead=guard.verifyRead.bind(guard),verifyMetadata=guard.verifyMetadata.bind(guard),directory=dirname(config.profileFile)
let closed=false,busy=false,directoryPin:Directory|undefined,horizon:{wall:number;end:number;deadlineAt:number}|undefined
let retained:Readonly<BandwidthPeerSourceSnapshot>|undefined
const operations=new Set<AbortController>()
const close=()=>{closed=true;retained=undefined;for(const operation of operations)operation.abort()}
function operation(input:BandwidthNodeObservationScope){
const wall=Date.now(),mono=performance.now(),data=fields(input,["deadlineAt","signal"],true),requested:unknown=data.deadlineAt?.value,signal:unknown=data.signal?.value
if(closed||busy||typeof requested!=="number"||!Number.isSafeInteger(requested)||signal!==undefined&&(types.isProxy(signal)||!(signal instanceof AbortSignal)))fail()
const external=signal as AbortSignal|undefined,aborted=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")!.get!
const isAborted=()=>external?Reflect.apply(aborted,external,[]):false
isAborted()
const deadlineAt=Math.min(requested as number,wall+5000,horizon?.deadlineAt??Infinity),end=Math.min(mono+Math.max(0,deadlineAt-wall),horizon?.end??Infinity)
if(wall<(horizon?.wall??wall)||wall>=deadlineAt||mono>=end||isAborted())fail()
horizon??={wall,end,deadlineAt};busy=true
const controller=new AbortController(),scope=Object.freeze({deadlineAt,signal:controller.signal}),abort=()=>controller.abort()
let rejectStopped!:(error:BandwidthExternalPeerSourceError)=>void
const stopped=new Promise<never>((_resolve,reject)=>{rejectStopped=reject});void stopped.catch(()=>{})
const stop=()=>{close();rejectStopped(new BandwidthExternalPeerSourceError())}
controller.signal.addEventListener("abort",stop,{once:true});operations.add(controller)
const timer=setTimeout(abort,Math.max(1,Math.ceil(end-performance.now())))
if(external)Reflect.apply(EventTarget.prototype.addEventListener,external,["abort",abort,{once:true}])
const live=()=>{const now=Date.now();if(closed||controller.signal.aborted||isAborted()||now<wall||now<horizon!.wall||now>=deadlineAt||performance.now()>=end)fail()}
return {scope,live,stopped,dispose(){clearTimeout(timer);if(external)Reflect.apply(EventTarget.prototype.removeEventListener,external,["abort",abort]);controller.signal.removeEventListener("abort",stop);operations.delete(controller);controller.abort();busy=false}}
}
async function dir(live:()=>void){
live();if(await realpath(directory)!==directory)fail();live()
const stat=await lstat(directory);live();if(!stat.isDirectory()||stat.isSymbolicLink())fail()
const value={dev:stat.dev,ino:stat.ino}
if(directoryPin&&!isDeepStrictEqual(value,directoryPin))fail()
return value
}
async function publicProfile(live:()=>void){
const before=await dir(live),bytes=await readBandwidthControlFile(config.profileFile,131072,live),after=await dir(live)
if(!isDeepStrictEqual(before,after))fail();directoryPin??=Object.freeze(before)
const text=new TextDecoder("utf-8",{fatal:true}).decode(bytes),profile=profileSchema.parse(JSON.parse(text))
if(canonical(profile)!==text||profile.installationId!==config.installationId||profile.enrollmentId!==config.enrollmentId||profile.keySha256!==config.keySha256||!profile.enabled)fail()
const binding=Object.freeze({peerRef:Object.freeze({kind:"external" as const,enrollmentId:config.enrollmentId}),sourceProof:sha(text),authorityGeneration:profile.generation,routingEndpointEpoch:profile.routingEndpointEpoch})
if(retained&&(retained.sourceProof!==binding.sourceProof||retained.authorityGeneration!==binding.authorityGeneration||retained.endpoint.routingEndpointEpoch!==binding.routingEndpointEpoch))fail()
live();return {profile,binding}
}
function expectedSnapshot(raw:unknown){
const data=fields(raw,["peerRef","enabled","sourceProof","authorityGeneration","endpoint"]),endpoint=fields(data.endpoint.value,["host","port","useSsl","verifySsl","username","password","routingEndpointEpoch"])
const values=Object.fromEntries(Object.entries(endpoint).filter(([name])=>name!=="routingEndpointEpoch").map(([name,field])=>[name,field.value])),captured=endpointSchema.parse(values)
if(data.enabled.value!==true)fail()
return Object.freeze({peerRef:peer(data.peerRef.value,config.enrollmentId),enabled:true,sourceProof:hash.parse(data.sourceProof.value),authorityGeneration:uuid.parse(data.authorityGeneration.value),endpoint:Object.freeze({...captured,routingEndpointEpoch:uuid.parse(endpoint.routingEndpointEpoch.value)})})
}
return Object.freeze({
async read(rawPeer:BandwidthPeerRef,input:Readonly<BandwidthNodeObservationScope>){
let owned:ReturnType<typeof operation>|undefined
try{
peer(rawPeer,config.enrollmentId);owned=operation(input)
return await Promise.race([owned.stopped,(async()=>{
let key:Buffer|undefined,plain:Buffer|undefined
const pieces:Buffer[]=[]
try{
const first=await publicProfile(owned!.live)
await verifyRead(first.binding,owned!.scope);owned!.live()
key=await readBandwidthControlFile(config.keyFile,32,owned!.live);owned!.live()
if(key.length!==32||sha(key)!==config.keySha256)fail()
await verifyRead(first.binding,owned!.scope);owned!.live()
const data=Buffer.from(first.profile.ciphertext,"base64url")
if(data.length<29||data.toString("base64url")!==first.profile.ciphertext)fail()
const {ciphertext:_ciphertext,...header}=first.profile;void _ciphertext
const decipher=createDecipheriv("aes-256-gcm",key,data.subarray(0,12));decipher.setAAD(Buffer.from(canonical(header)));decipher.setAuthTag(data.subarray(12,28))
pieces.push(decipher.update(data.subarray(28)));pieces.push(decipher.final());plain=Buffer.concat(pieces)
const text=new TextDecoder("utf-8",{fatal:true}).decode(plain),endpoint=endpointSchema.parse(JSON.parse(text))
if(canonical(endpoint)!==text)fail()
const value=Object.freeze({peerRef:first.binding.peerRef,enabled:true,sourceProof:first.binding.sourceProof,authorityGeneration:first.binding.authorityGeneration,endpoint:Object.freeze({...endpoint,routingEndpointEpoch:first.binding.routingEndpointEpoch})})
const final=await publicProfile(owned!.live)
if(!isDeepStrictEqual(final.binding,first.binding))fail()
await verifyRead(first.binding,owned!.scope);owned!.live()
if(retained&&!isDeepStrictEqual(retained,value))fail();retained??=value
return retained
}finally{key?.fill(0);plain?.fill(0);for(const piece of pieces)piece.fill(0)}
})()])
}catch{close();throw new BandwidthExternalPeerSourceError()}
finally{owned?.dispose()}
},
async assertMetadataCurrent(expected:Readonly<BandwidthPeerSourceSnapshot>,input:Readonly<BandwidthNodeObservationScope>){
let owned:ReturnType<typeof operation>|undefined
try{
const captured=expectedSnapshot(expected)
if(!retained||!isDeepStrictEqual(captured,retained))fail()
owned=operation(input)
await Promise.race([owned.stopped,(async()=>{
const binding:Readonly<BandwidthOperatorPeerSourceBinding>=Object.freeze({peerRef:retained!.peerRef,sourceProof:retained!.sourceProof,authorityGeneration:retained!.authorityGeneration,routingEndpointEpoch:retained!.endpoint.routingEndpointEpoch})
await verifyMetadata(binding,owned!.scope);owned!.live()
const current=await publicProfile(owned!.live)
if(!isDeepStrictEqual(current.binding,binding))fail()
await verifyMetadata(binding,owned!.scope);owned!.live()
})()])
}catch{close();throw new BandwidthExternalPeerSourceError()}
finally{owned?.dispose()}
},
close,
})
}