Files
MikrotikManager/backend/src/services/bandwidth-operator-writer-window.ts
T

415 lines
31 KiB
TypeScript

/** Explicit operator-only held writer window. No startup activation or external
* stop issuer. Trusted construction must enforce stop/restart prohibition for
* the original inventory; session exclusion alone proves no old executor. */
import { createHash, createPublicKey, verify } from "node:crypto"
import { isDeepStrictEqual, types } from "node:util"
import { isAbsolute, resolve } from "node:path"
import { performance } from "node:perf_hooks"
import { z } from "zod"
import { bandwidthOperatorEnrollmentGrantSchema, type BandwidthOperatorEnrollmentConfig } from "./bandwidth-operator-enrollment.js"
import { canonicalBandwidthNodeValue } from "./bandwidth-node-bootstrap.js"
import { readBandwidthControlFile, type BandwidthControlDispatchFence } from "./bandwidth-control-source.js"
import type { ProbeStorageConnection } from "./server-probe-journal-maintenance.js"
import type { BandwidthPeerRef } from "./bandwidth-peer-reference.js"
export interface BandwidthOperatorScope { deadlineAt: number; signal?: AbortSignal }
type Grant = z.infer<typeof bandwidthOperatorEnrollmentGrantSchema>
export type BandwidthOperatorOriginalAuthoritySnapshot = Readonly<{ grant: Readonly<Grant>; proof: string; end: number; signal?: AbortSignal }>
const originalsBrand = new WeakSet<object>(), fencersBrand = new WeakSet<object>(), peerGuardsBrand = new WeakSet<object>()
const nativeSignalAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted")!.get!
const LOCK_SQL = "SELECT pg_catalog.pg_try_advisory_lock(8723116) AS acquired"
const BACKEND_SQL = "SELECT pg_catalog.pg_backend_pid() AS backend_pid"
const HELD_SQL = "SELECT pg_catalog.pg_backend_pid() AS backend_pid, EXISTS(SELECT 1 FROM pg_catalog.pg_locks WHERE locktype='advisory' AND pid=pg_catalog.pg_backend_pid() AND mode='ExclusiveLock' AND classid=0::pg_catalog.oid AND objid=8723116::pg_catalog.oid AND objsubid=1 AND granted) AS held"
const hash = z.string().regex(/^[a-f0-9]{64}$/)
const configSchema = z.object({ trustKeyFile: z.string(), trustKeySha256: hash, grantFile: z.string(), installationId: z.string().uuid(), issuerKeySha256: hash, quiescenceProof: hash }).strict()
const envelopeSchema = z.object({ format: z.literal("mmapp-bandwidth-operator-enrollment-envelope-v1"), payload: z.string().min(1).max(16000).regex(/^[A-Za-z0-9_-]+$/), signature: z.string().length(86).regex(/^[A-Za-z0-9_-]+$/) }).strict()
const sha = (value: Buffer | string) => createHash("sha256").update(value).digest("hex")
export class BandwidthOperatorWriterFenceError extends Error {
readonly code: string = "BANDWIDTH_OPERATOR_WRITER_FENCE_REFUSED"
readonly automaticReplay = false
constructor() { super("BandwidthOperator held writer fence unavailable") }
}
export class BandwidthOperatorWriterFenceUnknown extends BandwidthOperatorWriterFenceError {
override readonly code = "BANDWIDTH_OPERATOR_WRITER_FENCE_UNKNOWN"
}
const refuse = (): never => { throw new BandwidthOperatorWriterFenceError() }
export interface BandwidthOperatorPeerSourceBinding {
readonly peerRef: BandwidthPeerRef; readonly sourceProof: string; readonly authorityGeneration: string; readonly routingEndpointEpoch: string
}
declare const peerSourceGuardBrand: unique symbol
export interface BandwidthOperatorPeerSourceGuard {
readonly [peerSourceGuardBrand]: true
readonly installationId: string
verifyRead(binding: BandwidthOperatorPeerSourceBinding, scope: Readonly<BandwidthOperatorScope>): Promise<void>
verifyMetadata(binding: BandwidthOperatorPeerSourceBinding, scope: Readonly<BandwidthOperatorScope>): Promise<void>
}
/** Provenance only; every method independently checks the original live window. */
export function assertBandwidthOperatorPeerSourceGuard(value: unknown): asserts value is BandwidthOperatorPeerSourceGuard {
if (!value || typeof value !== "object" || !peerGuardsBrand.has(value)) refuse()
}
function peerBindingSnapshot(raw: BandwidthOperatorPeerSourceBinding): Readonly<BandwidthOperatorPeerSourceBinding> {
if (!raw || types.isProxy(raw) || Object.getPrototypeOf(raw) !== Object.prototype) return refuse()
const fields = Object.getOwnPropertyDescriptors(raw), names = ["peerRef", "sourceProof", "authorityGeneration", "routingEndpointEpoch"]
if (Reflect.ownKeys(raw).length !== names.length || names.some(name => !fields[name] || !("value" in fields[name]) || !fields[name].enumerable)) return refuse()
const peer: unknown = fields.peerRef.value
if (!peer || typeof peer !== "object" || types.isProxy(peer) || Object.getPrototypeOf(peer) !== Object.prototype) return refuse()
const peerFields = Object.getOwnPropertyDescriptors(peer), kind = peerFields.kind
if (!kind || !("value" in kind) || !kind.enumerable || !["server", "external"].includes(kind.value)) return refuse()
const id = kind.value === "server" ? "serverId" : "enrollmentId"
if (Reflect.ownKeys(peer).length !== 2 || !peerFields[id] || !("value" in peerFields[id]) || !peerFields[id].enumerable) return refuse()
const value = z.object({ peerRef: z.union([z.object({ kind: z.literal("server"), serverId: z.number().int().positive().safe() }).strict(),
z.object({ kind: z.literal("external"), enrollmentId: z.string().uuid().regex(/^[a-f0-9-]+$/) }).strict()]), sourceProof: hash,
authorityGeneration: z.string().min(1).max(200), routingEndpointEpoch: z.string().uuid() }).strict().parse({ peerRef: { kind: kind.value, [id]: peerFields[id].value },
sourceProof: fields.sourceProof.value, authorityGeneration: fields.authorityGeneration.value, routingEndpointEpoch: fields.routingEndpointEpoch.value })
Object.freeze(value.peerRef); return Object.freeze(value)
}
function scopeSnapshot(raw: BandwidthOperatorScope): Readonly<BandwidthOperatorScope> {
if (!raw || Object.getPrototypeOf(raw) !== Object.prototype || Reflect.ownKeys(raw).length !== Object.keys(raw).length
|| Object.keys(raw).some(key => !["deadlineAt", "signal"].includes(key))
|| Object.values(Object.getOwnPropertyDescriptors(raw)).some(value => !("value" in value) || !value.enumerable)
|| !Number.isSafeInteger(raw.deadlineAt) || raw.signal !== undefined && !(raw.signal instanceof AbortSignal)) return refuse()
return Object.freeze({ deadlineAt: raw.deadlineAt, signal: raw.signal })
}
function freeze<T>(value: T): T { if (value && typeof value === "object") { Object.values(value).forEach(freeze); Object.freeze(value) } return value }
declare const originalBrand: unique symbol
export interface BandwidthOperatorOriginalAuthority { readonly [originalBrand]: true }
/** Separate original signed authority BEFORE external quiescence. It supplies
* permission to attempt enrollment, never a claim that any executor stopped. */
export function createBandwidthOperatorOriginalAuthorityReader(raw: BandwidthOperatorEnrollmentConfig) {
const config = Object.freeze(configSchema.parse(raw)), issued = new WeakMap<object, BandwidthOperatorOriginalAuthoritySnapshot>()
if ([config.trustKeyFile, config.grantFile].some(path => !isAbsolute(path) || resolve(path) !== path) || config.trustKeyFile === config.grantFile) refuse()
let closed = false
async function read(live: () => void) {
// Independent bounded PUBLIC files. Retain every per-file inode/path/time
// fence and every current read; only overlap their I/O, never cache grant
// authority or move a secret-key read across an async verifier boundary.
live(); const [publicBytes, grantBytes] = await Promise.all([
readBandwidthControlFile(config.trustKeyFile, 16384, live),
readBandwidthControlFile(config.grantFile, 32768, live),
]); live()
const key = createPublicKey(publicBytes)
if (key.asymmetricKeyType !== "ed25519" || sha(key.export({ type: "spki", format: "der" })) !== config.trustKeySha256) refuse()
const signed = envelopeSchema.parse(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(grantBytes)))
const bytes = Buffer.from(signed.payload, "base64url"), signature = Buffer.from(signed.signature, "base64url")
if (bytes.toString("base64url") !== signed.payload || signature.toString("base64url") !== signed.signature || !verify(null, bytes, key, signature)) refuse()
const grant = bandwidthOperatorEnrollmentGrantSchema.parse(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)))
if (canonicalBandwidthNodeValue(grant) !== bytes.toString("utf8") || grant.installationId !== config.installationId || grant.issuerKeySha256 !== config.issuerKeySha256
|| grant.quiescenceProof !== config.quiescenceProof || grant.issuedAt > Date.now() || grant.expiresAt <= Date.now()) refuse()
live(); return freeze({ grant, proof: sha(bytes) })
}
const reader = Object.freeze({
async acquire(rawScope: BandwidthOperatorScope): Promise<BandwidthOperatorOriginalAuthority> {
const scope = scopeSnapshot(rawScope), wall = Date.now(), mono = performance.now(), end = mono + Math.max(0, Math.min(5000, scope.deadlineAt - wall))
const live = () => { if (closed || scope.signal?.aborted || Date.now() >= scope.deadlineAt || performance.now() >= end) refuse() }
const original = await read(live)
const originalEnd = Math.min(end, mono + Math.max(0, original.grant.expiresAt - wall))
live(); if (performance.now() >= originalEnd) refuse()
const capability = Object.freeze(Object.create(null)) as BandwidthOperatorOriginalAuthority
issued.set(capability, Object.freeze({ ...original, end: originalEnd, signal: scope.signal })); return capability
},
async inspect(capability: unknown, rawScope: BandwidthOperatorScope): Promise<BandwidthOperatorOriginalAuthoritySnapshot> {
const origin = capability && typeof capability === "object" ? issued.get(capability) : undefined
if (!origin) return refuse()
const scope = scopeSnapshot(rawScope), wall = Date.now(), mono = performance.now(), end = Math.min(origin.end, mono + Math.max(0, scope.deadlineAt - wall))
const live = () => { if (closed || scope.signal?.aborted || origin.signal?.aborted || Date.now() >= scope.deadlineAt || Date.now() >= origin.grant.expiresAt || performance.now() >= end) refuse() }
const current = await read(live)
if (!isDeepStrictEqual(current.grant, origin.grant) || current.proof !== origin.proof) refuse()
live(); return origin
},
close() { closed = true },
})
originalsBrand.add(reader); return reader
}
type Reader = ReturnType<typeof createBandwidthOperatorOriginalAuthorityReader>
/** A production adapter must hold an ENFORCED external stop+restart prohibition
* across the complete original inventory. A DB lock/empty SQL result, an
* operator signature or network-write permission MUST NOT satisfy this ABI. */
export interface BandwidthOperatorExternalStopAdapter {
acquire(original: BandwidthOperatorOriginalAuthoritySnapshot, scope: Readonly<BandwidthOperatorScope>): Promise<{
assertCurrent(original: BandwidthOperatorOriginalAuthoritySnapshot, scope: Readonly<BandwidthOperatorScope>): Promise<void>
close(): void
}>
}
export function createBandwidthOperatorExternalFencer(adapter: BandwidthOperatorExternalStopAdapter) {
const acquire = adapter.acquire.bind(adapter)
const fencer = Object.freeze({ acquire })
fencersBrand.add(fencer); return fencer
}
type Fencer = ReturnType<typeof createBandwidthOperatorExternalFencer>
export interface BandwidthOperatorNodeSession {
readonly connection: ProbeStorageConnection
binding(): Promise<{ installationId: string; issuerKeySha256: string; quiescenceProof: string }>
keyedProof(purpose: string, value: unknown): Promise<string>
keyedProofs?(inputs: readonly { purpose: string; value: unknown }[]): Promise<readonly string[]>
close(): void
}
export interface BandwidthOperatorRegistryBorrow {
readonly connection: ProbeStorageConnection
binding(): Promise<{ installationId: string; issuerKeySha256: string; quiescenceProof: string }>
keyedProof(purpose: string, value: unknown): Promise<string>
keyedProofs?(inputs: readonly { purpose: string; value: unknown }[]): Promise<readonly string[]>
}
export interface BandwidthOperatorWriterWindowDependencies<T> {
originals: Reader
external: Fencer
/** Actual combined signed source in a future reviewed composition. open MUST
* NOT acquire another lock/lease in its dispatchGuard or wait for this owner. */
source: {
open(scope: BandwidthOperatorScope, dispatchGuard: () => Promise<void>): Promise<BandwidthOperatorNodeSession>
/** Trusted configured-source path: ownership SQL uses its existing raw core
* fence, before the source's final file checks and original authority guard. */
openWithOwnershipFence?(scope: BandwidthOperatorScope, dispatchGuard: () => Promise<void>,
verifyOwnership: (fence: BandwidthControlDispatchFence) => Promise<void>): Promise<BandwidthOperatorNodeSession>
}
/** Captured operator registry factory adapter, never a per-request callback.
* It keeps its own BEGIN/COMMIT. Its finally release(true) is LOGICAL only
* after an exact COMMIT ACK, pending the owner's final read-only verification. */
registry: { register(original: BandwidthOperatorOriginalAuthoritySnapshot, borrowed: BandwidthOperatorRegistryBorrow, scope: BandwidthOperatorScope): Promise<T> }
}
declare const windowBrand: unique symbol
export interface BandwidthOperatorWriterWindow { readonly [windowBrand]: true }
/** BandwidthOperator only. One physical source lease, fixed SESSION exclusive lock,
* private lifetime and two-phase owner/borrow completion. No occupancy API. */
export function createBandwidthOperatorWriterWindows<T>(dependencies: BandwidthOperatorWriterWindowDependencies<T>) {
if (!originalsBrand.has(dependencies.originals) || !fencersBrand.has(dependencies.external)) refuse()
const inspect = dependencies.originals.inspect.bind(dependencies.originals), acquireExternal = dependencies.external.acquire.bind(dependencies.external)
const openSource = dependencies.source.open.bind(dependencies.source), register = dependencies.registry.register.bind(dependencies.registry)
const openWithOwnershipFence = dependencies.source.openWithOwnershipFence?.bind(dependencies.source)
type State = {
original: BandwidthOperatorOriginalAuthoritySnapshot; originalCap: unknown; scope: Readonly<BandwidthOperatorScope>; end: number; controller: AbortController; timer: ReturnType<typeof setTimeout>
phase: "opening" | "held" | "registry" | "logical-release" | "final-read" | "terminal"; commitStarted: boolean; commitAck: boolean
session?: BandwidthOperatorNodeSession; external?: Awaited<ReturnType<Fencer["acquire"]>>; query?: ProbeStorageConnection["query"]
binding?: BandwidthOperatorNodeSession["binding"]; keyedProof?: BandwidthOperatorNodeSession["keyedProof"]; keyedProofs?: BandwidthOperatorNodeSession["keyedProofs"]; backend?: number; busy: boolean
externalClose?: () => void; sessionClose?: () => void; inputAbort: () => void; originalSignal?: AbortSignal; stopReject: (error: Error) => void; stopped: Promise<never>
peerGuards?: Set<object>
lifetimeSignal?: AbortSignal; lifetimeAbort?: () => void
}
const states = new WeakMap<object, State>(), active = new Set<State>()
let closed = false
function retire(state: State) {
if (state.phase === "terminal") return
state.phase = "terminal"; clearTimeout(state.timer); state.originalSignal?.removeEventListener("abort", state.inputAbort)
// Intentional retirement is already terminal before physical destruction
// aborts its lease signal. It must not turn successful COMMIT into UNKNOWN.
if (state.lifetimeSignal && state.lifetimeAbort) Reflect.apply(EventTarget.prototype.removeEventListener, state.lifetimeSignal, ["abort", state.lifetimeAbort])
state.lifetimeAbort = undefined
for (const guard of state.peerGuards ?? []) peerGuardsBrand.delete(guard)
state.peerGuards?.clear()
state.controller.abort()
try { state.sessionClose?.() } catch { /* Terminal, never healthy reuse. */ }
try { state.externalClose?.() } catch { /* Failed external teardown cannot issue readiness. */ }
active.delete(state)
}
const error = (state: State) => state.commitStarted ? new BandwidthOperatorWriterFenceUnknown() : new BandwidthOperatorWriterFenceError()
function stop(state: State) { const failure = error(state); retire(state); state.stopReject(failure) }
function live(state: State) {
if (closed || state.phase === "terminal" || state.controller.signal.aborted || state.originalSignal?.aborted
|| state.lifetimeSignal && Reflect.apply(nativeSignalAborted, state.lifetimeSignal, []) || Date.now() >= state.scope.deadlineAt
|| Date.now() >= state.original.grant.expiresAt || performance.now() >= state.end) throw error(state)
}
async function check(state: State) {
live(state); const current = await inspect(state.originalCap, state.scope); live(state)
if (!isDeepStrictEqual(current, state.original)) throw error(state)
if (state.external) { await state.external.assertCurrent(state.original, state.scope); live(state) }
}
async function checkSessionLock(state: State) {
await check(state)
const held = await state.query!(HELD_SQL, undefined, { signal: state.scope.signal, timeoutMs: Math.max(1, state.scope.deadlineAt - Date.now()) })
await check(state)
if (held.rows.length !== 1 || held.rows[0].held !== true || held.rows[0].backend_pid !== state.backend) throw error(state)
}
async function verifyOwnership(state: State, fence: BandwidthControlDispatchFence) {
live(state)
// Opening must acquire the lock and physical PID before checking ownership.
// Every subsequent configured-source driver dispatch checks BOTH facts on
// the already-held raw lease; never recursively call the source connection.
if (state.phase === "opening") return
if (state.backend === undefined) throw error(state)
const held = await fence.query(HELD_SQL)
live(state)
if (held.rows.length !== 1 || held.rows[0].held !== true || held.rows[0].backend_pid !== state.backend) throw error(state)
}
async function owned<R>(state: State, work: () => Promise<R>): Promise<R> {
live(state)
try { return await Promise.race([Promise.resolve().then(async () => { live(state); return work() }), state.stopped]) }
catch { const failure = error(state); retire(state); throw failure }
}
const windowState = (capability: unknown) => {
const state = capability && typeof capability === "object" ? states.get(capability) : undefined
if (!state) return refuse()
live(state); return state
}
return Object.freeze({
async open(originalCap: BandwidthOperatorOriginalAuthority, rawScope: BandwidthOperatorScope): Promise<BandwidthOperatorWriterWindow> {
if (closed) return refuse()
const input = scopeSnapshot(rawScope), wall = Date.now(), mono = performance.now()
const original = await inspect(originalCap, input)
const originalSignal = input.signal && original.signal ? AbortSignal.any([input.signal, original.signal]) : input.signal ?? original.signal
const controller = new AbortController(), scope = Object.freeze({ deadlineAt: Math.min(input.deadlineAt, original.grant.expiresAt, wall + 5000), signal: controller.signal })
const end = Math.min(original.end, mono + Math.max(0, scope.deadlineAt - wall))
let reject!: (error: Error) => void
const stopped = new Promise<never>((_resolve, failure) => { reject = failure }); void stopped.catch(() => {})
const state: State = { original, originalCap, scope, end, controller, phase: "opening", commitStarted: false, commitAck: false, busy: false,
timer: undefined as unknown as ReturnType<typeof setTimeout>, inputAbort: () => {}, originalSignal, stopReject: reject, stopped }
state.inputAbort = () => stop(state); originalSignal?.addEventListener("abort", state.inputAbort, { once: true })
state.timer = setTimeout(() => stop(state), Math.max(1, end - performance.now())); active.add(state)
return owned(state, async () => {
await check(state)
const external = await acquireExternal(original, scope)
if (state.controller.signal.aborted) { external.close(); throw error(state) }
state.external = { assertCurrent: external.assertCurrent.bind(external), close: external.close.bind(external) }; state.externalClose = state.external.close
await check(state)
const session = openWithOwnershipFence
? await openWithOwnershipFence(scope, () => check(state), fence => verifyOwnership(state, fence))
: await openSource(scope, () => check(state))
if (state.controller.signal.aborted) { session.close(); throw error(state) }
state.session = session; state.sessionClose = session.close.bind(session)
const connection = session.connection
if (types.isProxy(connection)) throw error(state)
const lifetime = Object.getOwnPropertyDescriptor(connection, "lifetimeSignal")
if (lifetime) {
if (!("value" in lifetime)) throw error(state)
if (lifetime.value !== undefined) {
const signal: unknown = lifetime.value
if (!signal || types.isProxy(signal) || !(signal instanceof AbortSignal)) throw error(state)
// Native brand check/read; do not evaluate a subclass/own getter.
Reflect.apply(nativeSignalAborted, signal, [])
state.lifetimeSignal = signal
state.lifetimeAbort = () => { if (state.phase !== "terminal") stop(state) }
Reflect.apply(EventTarget.prototype.addEventListener, signal, ["abort", state.lifetimeAbort, { once: true }])
if (Reflect.apply(nativeSignalAborted, signal, [])) { stop(state); throw error(state) }
}
}
live(state); state.query = connection.query.bind(connection)
state.binding = session.binding.bind(session); state.keyedProof = session.keyedProof.bind(session)
state.keyedProofs = session.keyedProofs?.bind(session)
await check(state); const root = await state.binding(); await check(state)
if (root.installationId !== original.grant.installationId || root.issuerKeySha256 !== original.grant.issuerKeySha256 || root.quiescenceProof !== original.grant.quiescenceProof) throw error(state)
const locked = await state.query(LOCK_SQL, undefined, { signal: scope.signal, timeoutMs: Math.max(1, scope.deadlineAt - Date.now()) }); await check(state)
if (locked.rows.length !== 1 || locked.rows[0].acquired !== true) throw error(state)
const backend = await state.query(BACKEND_SQL, undefined, { signal: scope.signal, timeoutMs: Math.max(1, scope.deadlineAt - Date.now()) }); await check(state)
if (backend.rows.length !== 1 || !Number.isSafeInteger(backend.rows[0].backend_pid) || Number(backend.rows[0].backend_pid) <= 0) throw error(state)
state.backend = Number(backend.rows[0].backend_pid); state.phase = "held"
const capability = Object.freeze(Object.create(null)) as BandwidthOperatorWriterWindow; states.set(capability, state); return capability
})
},
/** Read-only quiescence check suitable for a fixed coordinator adapter.
* It NEVER performs nested session SQL inside source dispatch guards. */
async verify(capability: unknown, originalCap: BandwidthOperatorOriginalAuthority, rawScope: BandwidthOperatorScope) {
const state = windowState(capability), requested = scopeSnapshot(rawScope)
if (state.originalCap !== originalCap || requested.signal?.aborted || Date.now() >= requested.deadlineAt || requested.deadlineAt > state.scope.deadlineAt) throw error(state)
// A shorter verifier call also owns a real bounded lifetime; its abort
// cannot disappear just because the enclosing window has time remaining.
const end = Math.min(state.end, performance.now() + Math.max(0, requested.deadlineAt - Date.now()))
const stopRequested = () => stop(state), timer = setTimeout(stopRequested, Math.max(1, end - performance.now()))
requested.signal?.addEventListener("abort", stopRequested, { once: true })
try { return await owned(state, () => check(state)) }
finally { clearTimeout(timer); requested.signal?.removeEventListener("abort", stopRequested) }
},
/** Fixed server-owned credential source guard. The metadata method is NOT
* held-owner/Q proof; a separate public SQL metadata lease supplies that. */
createPeerSourceGuard(capability: unknown, originalCap: BandwidthOperatorOriginalAuthority): BandwidthOperatorPeerSourceGuard {
const state = windowState(capability)
try { if (state.originalCap !== originalCap || !["held", "registry"].includes(state.phase)
|| !state.lifetimeSignal || Reflect.apply(nativeSignalAborted, state.lifetimeSignal, [])) throw error(state) }
catch { stop(state); throw error(state) }
const original = state.original, originalScope = state.scope, originalEnd = state.end
const expected = peerBindingSnapshot({ peerRef: original.grant.peerRef, sourceProof: original.grant.sourceProof,
authorityGeneration: original.grant.authorityGeneration, routingEndpointEpoch: original.grant.routingEndpointEpoch })
const inspectOriginal = inspect, assertHeld = () => checkSessionLock(state)
let busy = false
const verifySource = async (read: boolean, rawBinding: BandwidthOperatorPeerSourceBinding, rawScope: Readonly<BandwidthOperatorScope>) => {
const enteredWall = Date.now(), enteredMono = performance.now()
let timer: ReturnType<typeof setTimeout> | undefined, requestedSignal: AbortSignal | undefined, aborted: (() => boolean) | undefined
const stopRequested = () => stop(state)
try {
live(state); if (busy || !["held", "registry"].includes(state.phase)) throw error(state); busy = true
const binding = peerBindingSnapshot(rawBinding)
if (!isDeepStrictEqual(binding, expected) || !rawScope || types.isProxy(rawScope) || Object.getPrototypeOf(rawScope) !== Object.prototype) throw error(state)
const fields = Object.getOwnPropertyDescriptors(rawScope)
if (Reflect.ownKeys(rawScope).some(key => typeof key !== "string" || !["deadlineAt", "signal"].includes(key))
|| Object.values(fields).some(field => !("value" in field) || !field.enumerable)) throw error(state)
const deadline: unknown = fields.deadlineAt?.value, signal: unknown = fields.signal?.value
if (typeof deadline !== "number" || !Number.isSafeInteger(deadline) || signal !== undefined && (types.isProxy(signal) || !(signal instanceof AbortSignal))) throw error(state)
requestedSignal = signal as AbortSignal | undefined
const nativeAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted")!.get!
aborted = () => requestedSignal ? Reflect.apply(nativeAborted, requestedSignal, []) : false
if (aborted()) throw error(state)
const deadlineAt = Math.min(deadline, originalScope.deadlineAt, original.grant.expiresAt)
const end = Math.min(originalEnd, enteredMono + Math.max(0, deadlineAt - enteredWall))
const requested = Object.freeze({ deadlineAt, signal: originalScope.signal })
const current = () => { live(state); if (!peerGuardsBrand.has(guard) || aborted!() || Date.now() < enteredWall || Date.now() >= deadlineAt
|| performance.now() >= end || !["held", "registry"].includes(state.phase)) throw error(state) }
current(); timer = setTimeout(stopRequested, Math.max(1, end - performance.now()))
if (requestedSignal) Reflect.apply(EventTarget.prototype.addEventListener, requestedSignal, ["abort", stopRequested, { once: true }])
const originalCurrent = async () => {
current(); const value = await inspectOriginal(originalCap, requested); current()
if (!isDeepStrictEqual(value, original)) throw error(state)
}
await owned(state, async () => {
await originalCurrent()
if (read) { if (state.busy) throw error(state); await assertHeld(); current() }
await originalCurrent(); current()
})
} catch { stop(state); throw error(state) }
finally {
busy = false; if (timer) clearTimeout(timer)
if (requestedSignal) Reflect.apply(EventTarget.prototype.removeEventListener, requestedSignal, ["abort", stopRequested])
}
}
const guard = Object.freeze({ installationId: original.grant.installationId,
verifyRead: (binding: BandwidthOperatorPeerSourceBinding, scope: Readonly<BandwidthOperatorScope>) => verifySource(true, binding, scope),
verifyMetadata: (binding: BandwidthOperatorPeerSourceBinding, scope: Readonly<BandwidthOperatorScope>) => verifySource(false, binding, scope) }) as BandwidthOperatorPeerSourceGuard
peerGuardsBrand.add(guard); (state.peerGuards ??= new Set()).add(guard); return guard
},
async register(capability: unknown): Promise<T> {
const state = windowState(capability)
if (state.phase !== "held") throw error(state)
state.phase = "registry"
return owned(state, async () => {
const io = async <R>(work: () => Promise<R>) => {
live(state); if (state.busy || state.phase !== "registry") throw error(state)
state.busy = true
try {
// Configured sources enforce lock/backend ownership within their
// existing raw before/after driver fences. Legacy structural sources
// retain the original outer SQL checks, with no weaker fallback.
if (openWithOwnershipFence) await check(state); else await checkSessionLock(state)
const result = await work()
if (openWithOwnershipFence) await check(state); else await checkSessionLock(state)
return result
} finally { state.busy = false }
}
const borrowed: BandwidthOperatorRegistryBorrow = Object.freeze({
binding: () => io(() => state.binding!()), keyedProof: (purpose: string, value: unknown) => io(() => state.keyedProof!(purpose, value)),
...(state.keyedProofs ? { keyedProofs: (inputs: readonly { purpose: string; value: unknown }[]) => io(() => state.keyedProofs!(inputs)) } : {}),
connection: Object.freeze({
query: (text: string, values?: unknown[], options?: { signal?: AbortSignal; timeoutMs: number }) => io(async () => {
if (text.trim() === "COMMIT") state.commitStarted = true
const result = await state.query!(text, values, options)
if (text.trim() === "COMMIT" && "command" in result && result.command === "COMMIT") state.commitAck = true
return result
}),
release: () => {
if (state.phase === "terminal") return
if (state.busy || !state.commitAck || state.phase !== "registry") { stop(state); return }
// This is the existing registry finally release(true). The OWNER
// keeps the physical backend alive for one final read-only check.
state.phase = "logical-release"
},
}),
})
const result = await register(state.original, borrowed, state.scope)
live(state); if (!state.commitAck || state.phase !== "logical-release") throw error(state)
state.phase = "final-read"
await check(state) // ONLY original signed authority + held external fence; no driver SQL.
live(state); retire(state); return result
})
},
close() { closed = true; for (const state of [...active]) stop(state) },
})
}