Files
MikrotikManager/backend/src/services/bandwidth-node-proof-input.ts
T

58 lines
4.5 KiB
TypeScript

/** Pure, bounded capture shared by the existing strong source and the fixed
* key effect. No files, SQL, keys, authority or caller callbacks. */
import {types} from "node:util"
import {z} from "zod"
import {canonicalBandwidthNodeValue} from "./bandwidth-node-bootstrap.js"
export interface BandwidthNodeProofInput {readonly purpose:string;readonly value:unknown}
const fail=():never=>{throw new Error("Bandwidth proof input refused")}
const hash=z.string().regex(/^[a-f0-9]{64}$/),uuid=z.string().uuid(),sid=z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
const rootFields={installationId:uuid,issuerKeySha256:hash,quiescenceProof:hash}
const claim=z.object({kind:z.enum(["system-id","software-id"]),value:z.string().min(1).refine(value=>Buffer.byteLength(value)<=256&&value.trim()===value&&!/[\u0000-\u001f\u007f]/.test(value))}).strict()
export const bandwidthNodeProofShapes={
claim:z.array(claim).min(1).max(2).refine(value=>value.length===1||value[0].kind==="system-id"&&value[1].kind==="software-id"),
node:z.object({...rootFields,nodeId:uuid,claimProof:hash}).strict(),
alias:z.object({...rootFields,serverId:sid,incarnation:uuid,nodeId:uuid,status:z.enum(["active","tombstoned","quarantined"])}).strict(),
event:z.object({...rootFields,eventId:uuid,serverId:sid,incarnation:uuid,nodeId:uuid,kind:z.enum(["enroll","tombstone","quarantine"]),
oldStatus:z.literal("active").nullable(),newStatus:z.enum(["active","tombstoned","quarantined"]),authorityProof:hash}).strict()
.refine(value=>value.kind==="enroll"?value.oldStatus===null&&value.newStatus==="active":value.oldStatus==="active"&&value.newStatus===(value.kind==="tombstone"?"tombstoned":"quarantined")),
"external-alias":z.object({...rootFields,enrollmentId:uuid,incarnation:uuid,nodeId:uuid,status:z.enum(["active","tombstoned","quarantined"])}).strict(),
"external-event":z.object({...rootFields,eventId:uuid,enrollmentId:uuid,incarnation:uuid,nodeId:uuid,kind:z.enum(["enroll","tombstone","quarantine"]),
oldStatus:z.literal("active").nullable(),newStatus:z.enum(["active","tombstoned","quarantined"]),authorityProof:hash}).strict()
.refine(value=>value.kind==="enroll"?value.oldStatus===null&&value.newStatus==="active":value.oldStatus==="active"&&value.newStatus===(value.kind==="tombstone"?"tombstoned":"quarantined")),
} as const
/** Capture a small plain batch before any IO. Never evaluate accessors or
* serializers, retain caller objects, or let request code run under the key. */
export function captureBandwidthNodeProofBatch(input:readonly BandwidthNodeProofInput[]){
let bytes=0,nodes=0
const copy=(value:unknown,depth=0):unknown=>{
if(++nodes>512||depth>8)fail()
if(value===null||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return value
if(typeof value==="string"){bytes+=Buffer.byteLength(value);if(bytes>65536)fail();return value}
if(!value||typeof value!=="object"||types.isProxy(value))return fail()
const array=Array.isArray(value),descriptors=Object.getOwnPropertyDescriptors(value)
if(Object.getPrototypeOf(value)!==(array?Array.prototype:Object.prototype)||Reflect.ownKeys(value).some(key=>typeof key!=="string"))fail()
if(array){
const length=descriptors.length?.value
if(!Number.isSafeInteger(length)||length<0||length>64||Object.keys(descriptors).length!==length+1)fail()
return Object.freeze(Array.from({length},(_,index)=>{const field=descriptors[String(index)];if(!field||!("value"in field)||!field.enumerable)fail();return copy(field.value,depth+1)}))
}
const result:Record<string,unknown>={}
for(const [name,field]of Object.entries(descriptors)){
if(!("value"in field)||!field.enumerable||name==="__proto__")fail()
bytes+=Buffer.byteLength(name);if(bytes>65536)fail()
Object.defineProperty(result,name,{value:copy(field.value,depth+1),enumerable:true})
}
return Object.freeze(result)
}
const entries=copy(input) as BandwidthNodeProofInput[]
if(!Array.isArray(entries)||entries.length<1||entries.length>4)fail()
let total=0
return Object.freeze(entries.map(entry=>{
if(!entry||typeof entry!=="object"||Object.keys(entry).sort().join(",")!=="purpose,value"||typeof entry.purpose!=="string"||!Object.hasOwn(bandwidthNodeProofShapes,entry.purpose))fail()
const text=canonicalBandwidthNodeValue(bandwidthNodeProofShapes[entry.purpose as keyof typeof bandwidthNodeProofShapes].parse(entry.value));total+=Buffer.byteLength(text)
if(total>65536)fail()
return Object.freeze({purpose:entry.purpose,text})
}))
}