/** Fixed operator-owned managed source. Not a runtime default or model API. * The genuine held-window guard controls every management secret projection. */ import { performance } from "node:perf_hooks" import { isDeepStrictEqual, types } from "node:util" import { z } from "zod" import { assertBandwidthOperatorPeerSourceGuard, type BandwidthOperatorPeerSourceGuard, type BandwidthOperatorPeerSourceBinding, } from "./bandwidth-operator-writer-window.js" import type { BandwidthPeerSourceSnapshot, BandwidthPeerTrustedSource } from "./bandwidth-peer-observation.js" import type { BandwidthNodeObservationScope } from "./bandwidth-node-observation.js" import { createManagedBandwidthPeerMetadataChecker } from "./bandwidth-peer-metadata-source.js" import { createProbeStorageConnectionConnector } from "./server-probe-storage-connection.js" const hash = z.string().regex(/^[a-f0-9]{64}$/) const configSchema = z.object({ serverId: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), sourceProof: hash, authorityGeneration: z.string().min(1).max(200).refine(value => Buffer.byteLength(value) <= 200 && value.trim() === value && !/[\u0000-\u001f\u007f]/.test(value)), routingEndpointEpoch: z.string().uuid() }).strict() const endpointSchema = z.object({ host: z.string().min(1).max(1000).refine(value => Buffer.byteLength(value) <= 1000 && !/[\s/\\\u0000-\u001f\u007f]/.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), routingEndpointEpoch: z.string().uuid() }).strict() const SQL = `/* bandwidth-managed:guarded-credentials */ WITH chosen AS MATERIALIZED ( SELECT pg_catalog.jsonb_build_object('host',host,'port',port,'useSsl',use_ssl,'verifySsl',verify_ssl, 'username',username,'password',password,'routingEndpointEpoch',routing_endpoint_epoch) AS endpoint FROM public.servers WHERE id=$1::bigint AND enabled IS TRUE AND routing_endpoint_epoch=$2::uuid LIMIT 2) SELECT CASE WHEN pg_catalog.octet_length(endpoint::text)<=70000 THEN endpoint END AS endpoint FROM chosen` export class BandwidthManagedPeerSourceRefused extends Error { readonly code = "BANDWIDTH_MANAGED_PEER_SOURCE_REFUSED" constructor() { super("Managed operator peer source unavailable") } } const refuse = (): never => { throw new BandwidthManagedPeerSourceRefused() } function data(raw: unknown, names: readonly string[]): Record { if (!raw || typeof raw !== "object" || types.isProxy(raw) || Object.getPrototypeOf(raw) !== Object.prototype) return refuse() const fields = Object.getOwnPropertyDescriptors(raw) if (Reflect.ownKeys(raw).length !== names.length || names.some(name => !fields[name]) || Object.values(fields).some(field => !("value" in field) || !field.enumerable)) return refuse() return Object.fromEntries(names.map(name => [name, fields[name].value])) } function captureSnapshot(raw: unknown): Readonly { const value = data(raw, ["peerRef", "enabled", "sourceProof", "authorityGeneration", "endpoint"]) const peer = data(value.peerRef, ["kind", "serverId"]) if (peer.kind !== "server" || !Number.isSafeInteger(peer.serverId) || Number(peer.serverId) < 1 || value.enabled !== true || !hash.safeParse(value.sourceProof).success || typeof value.authorityGeneration !== "string") refuse() const endpoint = endpointSchema.parse(data(value.endpoint, ["host", "port", "useSsl", "verifySsl", "username", "password", "routingEndpointEpoch"])) return Object.freeze({ peerRef: Object.freeze({ kind: "server" as const, serverId: Number(peer.serverId) }), enabled: true, sourceProof: String(value.sourceProof), authorityGeneration: value.authorityGeneration as string, endpoint: Object.freeze(endpoint) }) } export function createConfiguredManagedBandwidthPeerSource(raw: z.infer, guard: BandwidthOperatorPeerSourceGuard) { assertBandwidthOperatorPeerSourceGuard(guard) const config = Object.freeze(configSchema.parse(data(raw, ["serverId", "sourceProof", "authorityGeneration", "routingEndpointEpoch"]))) const verifyRead = guard.verifyRead.bind(guard), verifyMetadata = guard.verifyMetadata.bind(guard) const peerRef = Object.freeze({ kind: "server" as const, serverId: config.serverId }) const binding: Readonly = Object.freeze({ peerRef, sourceProof: config.sourceProof, authorityGeneration: config.authorityGeneration, routingEndpointEpoch: config.routingEndpointEpoch }) const checker = createManagedBandwidthPeerMetadataChecker() const connector = createProbeStorageConnectionConnector(async () => (await import("../db/index.js")).pool.connect()) let closed = false, busy = false, end: number | undefined, wallStart: number | undefined, firstDeadline: number | undefined let original: Readonly | undefined const pending = new Set<() => void>() const close = () => { if (closed) return; closed = true; original = undefined; for (const stop of [...pending]) stop() } async function operation(input: BandwidthNodeObservationScope, work: (scope: Readonly, live: () => void) => Promise): Promise { const wall = Date.now(), mono = performance.now() let stop: (() => void) | undefined, timer: ReturnType | undefined, signal: AbortSignal | undefined try { if (closed || busy) { close(); return refuse() } busy = true if (!input || typeof input !== "object" || types.isProxy(input) || Object.getPrototypeOf(input) !== Object.prototype) refuse() const fields = data(input, Object.hasOwn(input, "signal") ? ["deadlineAt", "signal"] : ["deadlineAt"]) if (!Number.isSafeInteger(fields.deadlineAt) || fields.signal !== undefined && (types.isProxy(fields.signal) || !(fields.signal instanceof AbortSignal))) refuse() signal = fields.signal as AbortSignal | undefined const deadlineAt = Math.min(Number(fields.deadlineAt), wall + 5000, firstDeadline ?? Infinity) firstDeadline ??= deadlineAt end ??= mono + Math.max(0, deadlineAt - wall); wallStart ??= wall const boundedEnd = Math.min(end, mono + Math.max(0, deadlineAt - wall)) const controller = new AbortController(), aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted")!.get! let rejectStopped!: (error: BandwidthManagedPeerSourceRefused) => void, active = true const stopped = new Promise((_resolve, reject) => { rejectStopped = reject }); void stopped.catch(() => {}) stop = () => { if (!active) return; active = false; controller.abort(); rejectStopped(new BandwidthManagedPeerSourceRefused()) } const abort = stop const live = () => { const now = Date.now(); if (closed || !active || now < wall || now < wallStart! || now >= deadlineAt || performance.now() >= boundedEnd || signal && Reflect.apply(aborted, signal, [])) refuse() } live(); pending.add(stop) timer = setTimeout(() => { close(); abort() }, Math.max(1, Math.ceil(boundedEnd - performance.now()))) if (signal) Reflect.apply(EventTarget.prototype.addEventListener, signal, ["abort", stop, { once: true }]) const scope = Object.freeze({ deadlineAt, signal: controller.signal }) try { const result = await Promise.race([stopped, Promise.resolve().then(() => { live(); return work(scope, live) })]); live(); return result } finally { active = false; controller.abort() } } catch { close(); throw new BandwidthManagedPeerSourceRefused() } finally { clearTimeout(timer) if (stop) { pending.delete(stop); if (signal) Reflect.apply(EventTarget.prototype.removeEventListener, signal, ["abort", stop]) } busy = false } } const source = Object.freeze({ async read(rawPeer: Parameters[0], scope: BandwidthNodeObservationScope): Promise> { return operation(scope, async (current, live) => { const peer = data(rawPeer, ["kind", "serverId"]) if (peer.kind !== "server" || peer.serverId !== config.serverId) refuse() // Authenticate metadata before even borrowing the application lease. await verifyMetadata(binding, current); live() const connection = await connector(current) let snapshot: Readonly try { live() await verifyRead(binding, current); live() const result = await connection.query(SQL, [config.serverId, config.routingEndpointEpoch], { signal: current.signal, timeoutMs: Math.max(1, Math.ceil(Math.min(5000, current.deadlineAt - Date.now()))) }) live() if (!("command" in result) || result.command !== "SELECT" || result.rows.length !== 1) refuse() const row = data(result.rows[0], ["endpoint"]) snapshot = captureSnapshot({ peerRef, enabled: true, sourceProof: config.sourceProof, authorityGeneration: config.authorityGeneration, endpoint: data(row.endpoint, ["host", "port", "useSsl", "verifySsl", "username", "password", "routingEndpointEpoch"]) }) if (snapshot.endpoint.routingEndpointEpoch !== config.routingEndpointEpoch || original && !isDeepStrictEqual(original, snapshot)) refuse() } finally { connection.release(true) } live() await checker.assertMetadataCurrent(snapshot!, current); live() await verifyRead(binding, current); live() original ??= snapshot! return original }) }, async assertMetadataCurrent(expected: Readonly, scope: BandwidthNodeObservationScope): Promise { if (!original) return refuse() return operation(scope, async (current, live) => { const captured = captureSnapshot(expected) if (!original || !isDeepStrictEqual(captured, original)) refuse() await verifyMetadata(binding, current); live() await checker.assertMetadataCurrent(captured, current); live() await verifyMetadata(binding, current); live() }) }, close, } satisfies BandwidthPeerTrustedSource & { close(): void }) return source }