Files
MikrotikManager/backend/src/services/bandwidth-node-key-effect.ts
T

99 lines
6.7 KiB
TypeScript

/** Fixed local key/MAC primitive for the prospective closed operator pipeline.
* This is NOT an authority/Q capability. No runtime caller is wired to it.
* The dispatcher must verify current public source, actor, Q and same-owner
* metadata immediately before calling, then post-check before using results.
* Only a local regular 32-byte key is supported. Synchronous OS I/O cannot be
* preempted; late returns are refused, not presented as bounded OS latency. */
import {constants,lstatSync,realpathSync,openSync,fstatSync,readSync,closeSync,type Stats} from "node:fs"
import {createHash,createHmac} from "node:crypto"
import {dirname,isAbsolute,resolve} from "node:path"
import {performance} from "node:perf_hooks"
import {types} from "node:util"
import {bandwidthNodeBootstrapSchema,type BandwidthNodeBootstrap} from "./bandwidth-node-bootstrap.js"
import {captureBandwidthNodeProofBatch,type BandwidthNodeProofInput} from "./bandwidth-node-proof-input.js"
export class BandwidthNodeKeyEffectRefused extends Error {
constructor(){super("Bandwidth local key effect refused")}
}
const fail=():never=>{throw new BandwidthNodeKeyEffectRefused()}
const same=(a:Stats,b:Stats)=>a.dev===b.dev&&a.ino===b.ino&&a.size===b.size&&a.mtimeMs===b.mtimeMs&&a.ctimeMs===b.ctimeMs
function fields(value:unknown,names:readonly string[]):Record<string,unknown>{
if(!value||typeof value!=="object"||types.isProxy(value)||Object.getPrototypeOf(value)!==Object.prototype)fail()
const ds=Object.getOwnPropertyDescriptors(value),keys=Reflect.ownKeys(ds)
if(keys.length!==names.length||keys.some(key=>typeof key!=="string"||!names.includes(key)))fail()
const result:Record<string,unknown>={}
for(const name of names){const d=ds[name];if(!d||!("value"in d)||!d.enumerable)fail();result[name]=d.value}
return result
}
const aborted=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")!.get!
function isAborted(value:AbortSignal):boolean{return Reflect.apply(aborted,value,[]) as boolean}
const addAbort=EventTarget.prototype.addEventListener,removeAbort=EventTarget.prototype.removeEventListener
/** Inert construction. Both signals and the original five-second horizon are
* pinned before any filesystem access; later calls cannot renew this object. */
export function createBandwidthNodeKeyEffect(raw:{keyFile:string;bootstrap:BandwidthNodeBootstrap;deadlineAt:number;signal:AbortSignal;ownerSignal:AbortSignal}){
const beganWall=Date.now(),beganMono=performance.now()
let keyFile:string,bootstrap:BandwidthNodeBootstrap,deadlineAt:number,signal:AbortSignal,ownerSignal:AbortSignal
let actorAborted=false,ownerAborted=false,actorListening=false,ownerListening=false,calculating=false
const actorStop=()=>{actorAborted=true},ownerStop=()=>{ownerAborted=true}
const detach=()=>{
if(actorListening){actorListening=false;Reflect.apply(removeAbort,signal,["abort",actorStop])}
if(ownerListening){ownerListening=false;Reflect.apply(removeAbort,ownerSignal,["abort",ownerStop])}
}
try{
const c=fields(raw,["keyFile","bootstrap","deadlineAt","signal","ownerSignal"])
if(typeof c.keyFile!=="string"||!isAbsolute(c.keyFile)||resolve(c.keyFile)!==c.keyFile||!Number.isFinite(c.deadlineAt)||types.isProxy(c.signal)||types.isProxy(c.ownerSignal))fail()
keyFile=c.keyFile as string;deadlineAt=c.deadlineAt as number;signal=c.signal as AbortSignal;ownerSignal=c.ownerSignal as AbortSignal
// Node implements even its builtin aborted getter in JS against an own
// configurable symbol. Reject accessors BEFORE invoking that getter, and
// never inspect any signal property while the scratch key is live.
for(const value of [signal,ownerSignal])if(!value||typeof value!=="object"||Reflect.ownKeys(value).some(name=>!("value"in Object.getOwnPropertyDescriptor(value,name)!)))fail()
actorAborted=isAborted(signal);ownerAborted=isAborted(ownerSignal)
bootstrap=bandwidthNodeBootstrapSchema.parse(fields(c.bootstrap,Object.keys(bandwidthNodeBootstrapSchema.shape)))
Reflect.apply(addAbort,signal,["abort",actorStop,{once:true}]);actorListening=true
Reflect.apply(addAbort,ownerSignal,["abort",ownerStop,{once:true}]);ownerListening=true
}catch{try{detach()}catch{/* No key/file exists during constructor cleanup. */}return fail()}
const wallEnd=Math.min(deadlineAt,beganWall+5000),monoEnd=beganMono+Math.max(0,wallEnd-beganWall)
let closed=false,directory:Stats|undefined
const live=()=>{if(closed||actorAborted||ownerAborted||Date.now()>=wallEnd||performance.now()>=monoEnd)fail()}
const directoryCurrent=()=>{
live();const parent=dirname(keyFile),now=lstatSync(parent);live()
if(!now.isDirectory()||now.isSymbolicLink()||realpathSync(parent)!==parent)fail();live()
if(directory&&(directory.dev!==now.dev||directory.ino!==now.ino))fail()
directory??=now
}
return Object.freeze({
calculate(inputs:readonly BandwidthNodeProofInput[]):readonly string[]{
let key:Buffer|undefined,fd:number|undefined
try{
calculating=true
live();const captured=captureBandwidthNodeProofBatch(inputs)
for(const {purpose,text}of captured){
if(purpose.startsWith("external-")&&bootstrap.format!=="mmapp-bandwidth-node-bootstrap-v2")fail()
if(purpose!=="claim"){
const value=JSON.parse(text)
if(value.installationId!==bootstrap.installationId||value.issuerKeySha256!==bootstrap.issuerKeySha256||value.quiescenceProof!==bootstrap.quiescenceProof)fail()
}
}
directoryCurrent();const before=lstatSync(keyFile);live()
if(!before.isFile()||before.isSymbolicLink()||before.size!==32||realpathSync(keyFile)!==keyFile)fail();live()
fd=openSync(keyFile,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0));live()
const opened=fstatSync(fd);live();if(!opened.isFile()||!same(before,opened))fail()
key=Buffer.alloc(32);let length=0
while(length<32){live();const n=readSync(fd,key,length,32-length,length);live();if(!n)fail();length+=n}
const after=fstatSync(fd);live();if(!same(opened,after)||!same(after,lstatSync(keyFile)))fail()
directoryCurrent();live()
if(createHash("sha256").update(key).digest("hex")!==bootstrap.issuerKeySha256)fail()
const result=captured.map(({purpose,text})=>{live();return createHmac("sha256",key!).update("mmapp-bandwidth-node-"+purpose+"-v1:"+text).digest("hex")})
live();return Object.freeze(result)
}catch{closed=true;return fail()}
finally{
key?.fill(0)
try{if(fd!==undefined){try{closeSync(fd);live()}catch{closed=true;fail()}}}
finally{calculating=false;if(closed){try{detach()}catch{closed=true;fail()}}}
}
},
close(){closed=true;if(!calculating){try{detach()}catch{return fail()}}},
})
}