import { isDeepStrictEqual } from "node:util" import { performance } from "node:perf_hooks" export interface BandwidthNodeObservationScope { deadlineAt: number; signal?: AbortSignal } export interface BandwidthNodeEndpoint { host: string; port: number; useSsl: boolean; verifySsl: boolean; username: string; password: string; routingEndpointEpoch: string } export interface BandwidthNodeSourceSnapshot { serverId: number; enabled: boolean; sourceProof: string; authorityGeneration: string; endpoint: BandwidthNodeEndpoint } /** Server-owned composition only. This fixed reader must itself check current * authority and honor its owned deadline/signal. No callback or endpoint is * accepted by observe()/inspect(), and native transport is never injectable. */ export interface BandwidthNodeTrustedSource { read(serverId: number, scope: Readonly): Promise } export type BandwidthNodeLicenseKind = "system-id" | "software-id" export interface BandwidthNodeLicenseClaim { readonly kind: BandwidthNodeLicenseKind; readonly value: string } declare const observationBrand: unique symbol export interface BandwidthNodeObservation { readonly kind: "routeros-license-observation" readonly [observationBrand]: true } export interface BandwidthNodeObservationEvidence { readonly version: 1; readonly serverId: number; readonly sourceProof: string; readonly authorityGeneration: string readonly routingEndpointEpoch: string; readonly observedAt: number; readonly expiresAt: number readonly claims: readonly BandwidthNodeLicenseClaim[] readonly physicalUniquenessVerified: false; readonly cloneResistanceVerified: false } export class BandwidthNodeObservationError extends Error { constructor(readonly code: "INVALID_INPUT" | "CANCELLED" | "SOURCE_CHANGED" | "SOURCE_UNAVAILABLE" | "INVALID_LICENSE_RESPONSE" | "NOT_GENUINE" | "CLOSED") { super("Bandwidth node observation: " + code) } } const MAX_OBSERVATION_MS = 5000, MAX_LICENSE_BYTES = 16384 function fail(code: BandwidthNodeObservationError["code"]): never { throw new BandwidthNodeObservationError(code) } const plain = (value: unknown): value is Record => !!value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype function fields(value: unknown, names: string[]): asserts value is Record { if (!plain(value)) fail("INVALID_INPUT") const descriptors = Object.getOwnPropertyDescriptors(value) if (Reflect.ownKeys(value).length !== names.length || Object.keys(descriptors).sort().join(",") !== names.sort().join(",") || Object.values(descriptors).some(item => !("value" in item) || !item.enumerable)) fail("INVALID_INPUT") } const text = (value: unknown, max: number): value is string => typeof value === "string" && value.length > 0 && Buffer.byteLength(value) <= max && value.trim() === value && !/[\u0000-\u001f\u007f]/.test(value) function capture(raw: unknown, serverId: number): Readonly { fields(raw, ["serverId", "enabled", "sourceProof", "authorityGeneration", "endpoint"]) fields(raw.endpoint, ["host", "port", "useSsl", "verifySsl", "username", "password", "routingEndpointEpoch"]) const endpoint = raw.endpoint if (raw.serverId !== serverId || raw.enabled !== true || typeof raw.sourceProof !== "string" || !/^[a-f0-9]{64}$/.test(raw.sourceProof) || !text(raw.authorityGeneration, 200) || !text(endpoint.host, 1000) || /[\s/\\]/.test(endpoint.host) || !Number.isSafeInteger(endpoint.port) || Number(endpoint.port) < 1 || Number(endpoint.port) > 65535 || typeof endpoint.useSsl !== "boolean" || typeof endpoint.verifySsl !== "boolean" || typeof endpoint.username !== "string" || Buffer.byteLength(endpoint.username) > 1000 || typeof endpoint.password !== "string" || Buffer.byteLength(endpoint.password) > 65536 || typeof endpoint.routingEndpointEpoch !== "string" || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(endpoint.routingEndpointEpoch)) fail("SOURCE_UNAVAILABLE") return Object.freeze({ ...raw, endpoint: Object.freeze({ ...endpoint }) }) as unknown as Readonly } function claims(raw: unknown): readonly BandwidthNodeLicenseClaim[] { const row: unknown = Array.isArray(raw) ? raw.length === 1 ? raw[0] : undefined : raw if (!plain(row) || Object.keys(row).length > 64) fail("INVALID_LICENSE_RESPONSE") const result: BandwidthNodeLicenseClaim[] = [] // Kind and fixed vector order are significant, including when both values // happen to be equal. No preferred-ID fallback or identifier normalization. for (const kind of ["system-id", "software-id"] as const) { if (!Object.hasOwn(row, kind)) continue if (!text(row[kind], 256)) fail("INVALID_LICENSE_RESPONSE") result.push(Object.freeze({ kind, value: row[kind] })) } if (!result.length) fail("INVALID_LICENSE_RESPONSE") return Object.freeze(result) } type Origin = { source: Readonly; claims: readonly BandwidthNodeLicenseClaim[]; observedAt: number; expiresAt: number; monotonicEnd: number; signal?: AbortSignal } /** Inert construction/import: no default pool, authority lookup, key generation * or native request. Actual observation lazily imports the existing client; * its transitive imports may allocate their existing pool, but no DB query is * used here. A future issuer must pin THIS reader, not trust any JSON evidence. */ export function createBandwidthNodeObservationReader(trustedSource: BandwidthNodeTrustedSource) { if (!trustedSource || typeof trustedSource.read !== "function") fail("INVALID_INPUT") const readSource = trustedSource.read.bind(trustedSource), observations = new WeakMap(), windows = new Set() let closed = false const active = () => { if (closed) fail("CLOSED") } function window(raw: BandwidthNodeObservationScope, origin?: Origin) { active() if (!plain(raw) || Reflect.ownKeys(raw).length !== Object.keys(raw).length || Object.values(Object.getOwnPropertyDescriptors(raw)).some(item => !("value" in item) || !item.enumerable) || Object.keys(raw).some(key => !["deadlineAt", "signal"].includes(key)) || !Number.isSafeInteger(raw.deadlineAt) || raw.signal !== undefined && !(raw.signal instanceof AbortSignal)) fail("INVALID_INPUT") const external = raw.signal const duration = Math.min(MAX_OBSERVATION_MS, raw.deadlineAt - Date.now(), origin ? origin.expiresAt - Date.now() : Infinity, origin ? origin.monotonicEnd - performance.now() : Infinity) if (duration <= 0 || external?.aborted || origin?.signal?.aborted) fail("CANCELLED") const deadlineAt = Math.min(raw.deadlineAt, Date.now() + Math.floor(duration), origin?.expiresAt ?? Infinity) const monotonicEnd = performance.now() + duration, controller = new AbortController() windows.add(controller) const abort = () => controller.abort(), timer = setTimeout(abort, Math.max(1, Math.ceil(duration))) external?.addEventListener("abort", abort, { once: true }); origin?.signal?.addEventListener("abort", abort, { once: true }) const live = () => { active(); if (controller.signal.aborted || external?.aborted || origin?.signal?.aborted || Date.now() >= deadlineAt || performance.now() >= monotonicEnd) fail("CANCELLED") } const ownedScope = Object.freeze({ deadlineAt, signal: controller.signal }) const wait = async (work: () => Promise): Promise => { live() let stop!: () => void const cancelled = new Promise((_resolve, reject) => { stop = () => reject(new BandwidthNodeObservationError("CANCELLED")); controller.signal.addEventListener("abort", stop, { once: true }) }) try { const result = await Promise.race([Promise.resolve().then(() => { live(); return work() }), cancelled]); live(); return result } finally { controller.signal.removeEventListener("abort", stop) } } return { live, wait, scope: ownedScope, external, monotonicEnd, dispose() { clearTimeout(timer); external?.removeEventListener("abort", abort); origin?.signal?.removeEventListener("abort", abort); windows.delete(controller); controller.abort() } } } return Object.freeze({ async observe(serverId: number, scope: BandwidthNodeObservationScope): Promise { if (!Number.isSafeInteger(serverId) || serverId < 1) fail("INVALID_INPUT") const owned = window(scope) try { const before = capture(await owned.wait(() => readSource(serverId, owned.scope)), serverId) const fence = async () => { const current = capture(await owned.wait(() => readSource(serverId, owned.scope)), serverId) if (!isDeepStrictEqual(current, before)) fail("SOURCE_CHANGED") } const { MikrotikClient } = await owned.wait(() => import("./mikrotik.js")) const client = new MikrotikClient(before.endpoint) const raw = await owned.wait(() => client.get("/system/license", Math.max(1, owned.scope.deadlineAt - Date.now()), owned.scope.signal, MAX_LICENSE_BYTES, fence)) const observedAt = Date.now(), vector = claims(raw) await fence(); owned.live() const observation = Object.freeze({ kind: "routeros-license-observation" as const }) as BandwidthNodeObservation observations.set(observation, { source: before, claims: vector, observedAt, expiresAt: owned.scope.deadlineAt, monotonicEnd: owned.monotonicEnd, signal: owned.external }) return observation } catch (error) { if (error instanceof BandwidthNodeObservationError) throw error throw new BandwidthNodeObservationError("SOURCE_UNAVAILABLE") } finally { owned.dispose() } }, async inspect(observation: unknown, scope: BandwidthNodeObservationScope): Promise { active() const origin = observation && typeof observation === "object" ? observations.get(observation) : undefined if (!origin) fail("NOT_GENUINE") const owned = window(scope, origin) try { const current = capture(await owned.wait(() => readSource(origin.source.serverId, owned.scope)), origin.source.serverId) if (!isDeepStrictEqual(current, origin.source)) fail("SOURCE_CHANGED") owned.live() return Object.freeze({ version: 1 as const, serverId: origin.source.serverId, sourceProof: origin.source.sourceProof, authorityGeneration: origin.source.authorityGeneration, routingEndpointEpoch: origin.source.endpoint.routingEndpointEpoch, observedAt: origin.observedAt, expiresAt: origin.expiresAt, claims: origin.claims, physicalUniquenessVerified: false as const, cloneResistanceVerified: false as const }) } catch (error) { if (error instanceof BandwidthNodeObservationError) throw error throw new BandwidthNodeObservationError("SOURCE_UNAVAILABLE") } finally { owned.dispose() } }, /** Backend-only strict client from this reader's genuine origin. Neither * request JSON nor a copied observation can choose its endpoint/credentials. * The server ID retains the existing configuration policy/audit boundary. */ async strictClient(observation:unknown,scope:BandwidthNodeObservationScope){ active() const origin=observation&&typeof observation==="object"?observations.get(observation):undefined if(!origin)fail("NOT_GENUINE") const owned=window(scope,origin) const fresh=async()=>{ const current=capture(await owned.wait(()=>readSource(origin.source.serverId,owned.scope)),origin.source.serverId) if(!isDeepStrictEqual(current,origin.source))fail("SOURCE_CHANGED") } try{ await fresh() const {MikrotikClient}=await owned.wait(()=>import("./mikrotik.js")) await fresh();owned.live() return new MikrotikClient(origin.source.endpoint,origin.source.serverId,{requireBandwidthPermit:true}) }catch(error){ if(error instanceof BandwidthNodeObservationError)throw error throw new BandwidthNodeObservationError("SOURCE_UNAVAILABLE") }finally{owned.dispose()} }, close() { closed = true; for (const controller of windows) controller.abort() }, }) }