Files
MikrotikManager/backend/src/services/bandwidth-control-source.ts
T

517 lines
42 KiB
TypeScript

/** Operational reader for an externally signed, explicitly provisioned control
* source. Constructor/import performs no I/O or enrollment. This authenticates a
* configured component source, not general application-schema READY or physical
* node identity, and cannot certify rollback of the control provider itself. */
import { constants, type Stats } from "node:fs"
import { lstat, open, realpath } from "node:fs/promises"
import { isAbsolute, resolve } from "node:path"
import { createHash, createHmac, createPublicKey, verify, type KeyObject } from "node:crypto"
import { performance } from "node:perf_hooks"
import { types } from "node:util"
import { Pool } from "pg"
import { z } from "zod"
import { BANDWIDTH_ADMISSION_PROPOSAL_DDL } from "./bandwidth-admission-schema.js"
import { BANDWIDTH_CONTROL_SOURCE_DDL } from "./bandwidth-control-source-schema.js"
import { observeBandwidthControlCatalog } from "./bandwidth-control-catalog.js"
import { assertBandwidthControlRegistryIdentity } from "./bandwidth-control-registry-identity.js"
import { assertBandwidthControlIdentity, type BandwidthControlIdentityExpected } from "./bandwidth-control-identity.js"
import { createProbeStorageConnectionConnector } from "./server-probe-storage-connection.js"
import type { ProbeStorageConnection } from "./server-probe-journal-maintenance.js"
import type { BandwidthScope } from "./bandwidth-admission.js"
import { bandwidthNodeBootstrapSchema,bandwidthNodeBootstrapEnvelopeSchema,canonicalBandwidthNodeBootstrap,bandwidthNodeRegistrySchemaSourceSha256,bandwidthPeerRegistrySchemaSourceSha256,type BandwidthNodeBootstrap } from "./bandwidth-node-bootstrap.js"
export { BANDWIDTH_CONTROL_SOURCE_DDL, observeBandwidthControlCatalog }
const hash=z.string().regex(/^[a-f0-9]{64}$/),role=z.string().regex(/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/)
export const bandwidthControlRecordSchema=z.object({
format:z.literal("mmapp-bandwidth-control-source-v1"),installationId:z.string().uuid(),controlGeneration:z.string().uuid(),
databaseName:z.string().min(1).max(63),databaseOid:z.number().int().positive().max(4294967295),runtimeRole:role,ownerRole:role,
endpointSha256:hash,schemaSourceSha256:hash,catalogSha256:hash,eventKeySha256:hash,attestationRef:z.string().trim().min(30).max(2000),
}).strict()
export type BandwidthControlRecord=z.infer<typeof bandwidthControlRecordSchema>
export interface BandwidthControlSourceConfig {
databaseUrl:string;applicationDatabaseUrl:string;attestationFile:string;trustKeyFile:string;trustKeySha256:string;eventKeyFile:string
}
export class BandwidthControlSourceError extends Error {readonly code="BANDWIDTH_CONTROL_SOURCE_UNAVAILABLE";constructor(){super("Подписанный источник bandwidth control не подтверждён")}}
const refused=():never=>{throw new BandwidthControlSourceError()}
const digest=(value:string|Buffer)=>createHash("sha256").update(value).digest("hex")
function canonical(value:unknown):string {
if(Array.isArray(value))return "["+value.map(canonical).join(",")+"]"
if(value&&typeof value==="object")return "{"+Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key,item])=>JSON.stringify(key)+":"+canonical(item)).join(",")+"}"
return JSON.stringify(value)
}
export function canonicalBandwidthControlRecord(value:unknown):string{return canonical(bandwidthControlRecordSchema.parse(value))}
export function bandwidthControlSchemaSourceSha256():string{return digest(BANDWIDTH_ADMISSION_PROPOSAL_DDL+"\n"+BANDWIDTH_CONTROL_SOURCE_DDL)}
function databaseUrl(raw:string):URL {
let value:URL;try{value=new URL(raw)}catch{throw new BandwidthControlSourceError()}
if(!["postgres:","postgresql:"].includes(value.protocol)||!value.hostname||!value.username||!value.password||value.hash||!/^\/[^/]+$/.test(value.pathname))refused()
// pg-connection-string lets query parameters override authority/path fields.
// In particular ?user=owner must never bypass the application-role fence.
const allowed=new Set(["sslmode","sslrootcert","sslcert","sslkey","sslpassword"]),seen=new Set<string>()
for(const key of value.searchParams.keys()){if(!allowed.has(key)||seen.has(key))refused();seen.add(key)}
return value
}
export function bandwidthControlEndpointSha256(raw:string):string {
const value=databaseUrl(raw);value.password="";value.protocol="postgresql:";value.hostname=value.hostname.toLowerCase();value.port=value.port||"5432";value.searchParams.sort()
return digest(value.toString())
}
const envelopeSchema=z.object({format:z.literal("mmapp-bandwidth-control-envelope-v1"),payload:z.string().min(1).max(24000).regex(/^[A-Za-z0-9_-]+$/),signature:z.string().length(86).regex(/^[A-Za-z0-9_-]+$/)}).strict()
type Material={record:BandwidthControlRecord;recordHash:string;eventKey:Buffer;trustKey:KeyObject}
type PublicMaterial=Pick<Material,"record"|"recordHash"|"trustKey">
export interface BandwidthVerifiedNodeBootstrap {
bootstrap:Readonly<BandwidthNodeBootstrap>
source:Readonly<{installationId:string;controlGeneration:string;sourceRecordSha256:string;databaseName:string;runtimeRole:string;ownerRole:string}>
}
/** Public signed metadata only. No current key, credential, SQL/source-role,
* quiescence or dispatch authority. Deliberately not the strong verified type. */
export interface BandwidthPublicNodeBootstrapMetadata {
format:"mmapp-bandwidth-public-node-metadata-v1"
bootstrap:Readonly<BandwidthNodeBootstrap>
source:Readonly<{installationId:string;controlGeneration:string;sourceRecordSha256:string}>
publicDatabase:Readonly<{databaseName:string;runtimeRole:string;ownerRole:string;databaseOid:number;catalogSha256:string}>
}
/** Current public SQL metadata only, never a writer/Q/strong-source lease. */
export interface BandwidthPublicRegistryMetadataLease {
inspect(envelope:unknown):Promise<Readonly<{format:"mmapp-bandwidth-public-registry-metadata-v1";metadata:BandwidthPublicNodeBootstrapMetadata;backendPid:number}>>
close():void
}
const PUBLIC_PID_SQL="SELECT pg_catalog.pg_backend_pid() AS backend_pid"
const PUBLIC_LOCK_SQL="SELECT pg_catalog.pg_try_advisory_lock(8723116) AS acquired"
const PUBLIC_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 classid=0::pg_catalog.oid AND objid=8723116::pg_catalog.oid AND objsubid=1 AND mode='ExclusiveLock' AND granted) AS held"
function publicDataFields(value:unknown,keys:readonly string[]){
if(!value||typeof value!=="object"||types.isProxy(value)||Object.getPrototypeOf(value)!==Object.prototype)refused()
const descriptors=Object.getOwnPropertyDescriptors(value)
if(Reflect.ownKeys(descriptors).some(key=>typeof key!=="string"||!keys.includes(key))
||Object.values(descriptors).some(item=>!("value"in item)||!item.enumerable))refused()
return descriptors
}
function capturePublicEnvelope(envelope:unknown){
const fields=publicDataFields(envelope,["format","payload","signature"])
return bandwidthNodeBootstrapEnvelopeSchema.parse({format:fields.format?.value,payload:fields.payload?.value,signature:fields.signature?.value})
}
function publicNodeMetadata(signed:ReturnType<typeof bandwidthNodeBootstrapEnvelopeSchema.parse>,value:PublicMaterial):BandwidthPublicNodeBootstrapMetadata{
const nodeBytes=Buffer.from(signed.payload,"base64url"),nodeSignature=Buffer.from(signed.signature,"base64url")
if(nodeBytes.toString("base64url")!==signed.payload||nodeSignature.toString("base64url")!==signed.signature||nodeSignature.length!==64||!verify(null,nodeBytes,value.trustKey,nodeSignature))refused()
const nodeText=new TextDecoder("utf-8",{fatal:true}).decode(nodeBytes),bootstrap=bandwidthNodeBootstrapSchema.parse(JSON.parse(nodeText)),record=value.record
if(canonicalBandwidthNodeBootstrap(bootstrap)!==nodeText||bootstrap.installationId!==record.installationId
||bootstrap.issuerKeySha256===record.eventKeySha256||bootstrap.registrySchemaSourceSha256!==(bootstrap.format==="mmapp-bandwidth-node-bootstrap-v2"?bandwidthPeerRegistrySchemaSourceSha256():bandwidthNodeRegistrySchemaSourceSha256()))refused()
return Object.freeze({format:"mmapp-bandwidth-public-node-metadata-v1" as const,bootstrap:Object.freeze(bootstrap),source:Object.freeze({installationId:record.installationId,controlGeneration:record.controlGeneration,sourceRecordSha256:value.recordHash}),publicDatabase:Object.freeze({databaseName:record.databaseName,runtimeRole:record.runtimeRole,ownerRole:record.ownerRole,databaseOid:record.databaseOid,catalogSha256:record.catalogSha256})})
}
/** Server-only, single-dispatch scope. Retaining it past the fixed guard cannot
* bypass source checks or perform late SQL; it never owns another pool lease. */
export interface BandwidthControlDispatchFence {
query(text:string,values?:unknown[]):Promise<{rows:Record<string,unknown>[]}>
verifyNodeBootstrap(envelope:unknown):Promise<BandwidthVerifiedNodeBootstrap>
sourceIdentity():Promise<Readonly<{installationId:string;controlGeneration:string;sourceRecordSha256:string}>>
}
export interface BandwidthControlRegistryDispatchFence extends BandwidthControlDispatchFence {
/** Only a genuine verified object from THIS phase; executes fixed joint SQL. */
assertRegistryIdentity(verified:BandwidthVerifiedNodeBootstrap):Promise<void>
}
function verifyNodeRecord(signed:ReturnType<typeof bandwidthNodeBootstrapEnvelopeSchema.parse>,value:Material):BandwidthVerifiedNodeBootstrap{
const bytes=Buffer.from(signed.payload,"base64url"),signature=Buffer.from(signed.signature,"base64url")
if(bytes.toString("base64url")!==signed.payload||signature.toString("base64url")!==signed.signature||signature.length!==64||!verify(null,bytes,value.trustKey,signature))refused()
const text=new TextDecoder("utf-8",{fatal:true}).decode(bytes),record=bandwidthNodeBootstrapSchema.parse(JSON.parse(text))
if(canonicalBandwidthNodeBootstrap(record)!==text||record.installationId!==value.record.installationId
||record.issuerKeySha256===value.record.eventKeySha256||record.registrySchemaSourceSha256!==(record.format==="mmapp-bandwidth-node-bootstrap-v2"?bandwidthPeerRegistrySchemaSourceSha256():bandwidthNodeRegistrySchemaSourceSha256()))refused()
return Object.freeze({bootstrap:Object.freeze(record),source:Object.freeze({installationId:value.record.installationId,
controlGeneration:value.record.controlGeneration,sourceRecordSha256:value.recordHash,databaseName:value.record.databaseName,
runtimeRole:value.record.runtimeRole,ownerRole:value.record.ownerRole})})
}
function sameFile(a:Stats,b:Stats){return a.dev===b.dev&&a.ino===b.ino&&a.size===b.size&&a.mtimeMs===b.mtimeMs&&a.ctimeMs===b.ctimeMs}
export async function readBandwidthControlFile(path:string,max:number,live:()=>void):Promise<Buffer>{
live();const before=await lstat(path);live()
if(!before.isFile()||before.isSymbolicLink()||before.size<1||before.size>max)refused()
if(await realpath(path)!==path)refused();live()
const handle=await open(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0));let scratch:Buffer|undefined
try{
live()
const opened=await handle.stat();live();if(!opened.isFile()||!sameFile(before,opened))refused()
// The opened inode's exact size was bounded and matched against lstat.
// Read that size (allowing short reads), then compare fstat again. An extra
// EOF read adds no evidence: truncation, append or replacement must already
// fail the unchanged inode/size/time checks below. Never cache file bytes.
const data=Buffer.alloc(opened.size);scratch=data;let length=0
while(length<opened.size){const part=await handle.read(data,length,opened.size-length,length);live();if(!part.bytesRead)break;length+=part.bytesRead}
const after=await handle.stat();live();if(length>max||length!==opened.size||!sameFile(opened,after))refused()
return Buffer.from(data.subarray(0,length))
}finally{scratch?.fill(0);await handle.close()}
}
const readBounded=readBandwidthControlFile
/** All arguments are server/operator configuration, never model JSON. Missing
* files, namespace or signed identity refuse; no key, marker or pool fallback. */
export function createConfiguredBandwidthControlSource(raw:BandwidthControlSourceConfig){
const config=Object.freeze({...raw})
const target=databaseUrl(config.databaseUrl),application=databaseUrl(config.applicationDatabaseUrl)
const name=decodeURIComponent(target.pathname.slice(1)),runtime=decodeURIComponent(target.username),appRole=decodeURIComponent(application.username)
if(name===decodeURIComponent(application.pathname.slice(1))||runtime===appRole||!hash.safeParse(config.trustKeySha256).success||!role.safeParse(runtime).success||!role.safeParse(appRole).success)refused()
const paths=[config.attestationFile,config.trustKeyFile,config.eventKeyFile]
if(paths.some(path=>typeof path!=="string"||!isAbsolute(path)||resolve(path)!==path)||new Set(paths).size!==3)refused()
let pool:Pool|undefined,closed=false,closing:Promise<void>|undefined
const verifiedHashes=new WeakMap<ProbeStorageConnection,string>()
const publicStops=new Set<()=>void>()
async function publicMaterial(live:()=>void):Promise<PublicMaterial>{
const [bytes,publicBytes]=await Promise.all([readBounded(config.attestationFile,32768,live),readBounded(config.trustKeyFile,16384,live)])
live()
const publicKey=createPublicKey(publicBytes)
if(publicKey.asymmetricKeyType!=="ed25519"||digest(publicKey.export({type:"spki",format:"der"}))!==config.trustKeySha256)refused()
const control=envelopeSchema.parse(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)))
const payload=Buffer.from(control.payload,"base64url"),signature=Buffer.from(control.signature,"base64url")
if(payload.toString("base64url")!==control.payload||signature.toString("base64url")!==control.signature||signature.length!==64||!verify(null,payload,publicKey,signature))refused()
const text=new TextDecoder("utf-8",{fatal:true}).decode(payload),record=bandwidthControlRecordSchema.parse(JSON.parse(text))
if(canonicalBandwidthControlRecord(record)!==text||record.databaseName!==name||record.runtimeRole!==runtime||record.ownerRole===runtime
||record.endpointSha256!==bandwidthControlEndpointSha256(config.databaseUrl)||record.schemaSourceSha256!==bandwidthControlSchemaSourceSha256())refused()
live();return {record,recordHash:digest(payload),trustKey:publicKey}
}
async function inspectPublicNodeBootstrap(envelope:unknown,input:BandwidthScope):Promise<BandwidthPublicNodeBootstrapMetadata>{
// Capture only inert own data properties before any await. In particular,
// zod/JSON must never invoke a caller getter, toJSON or proxy trap.
const startedAt=Date.now(),startedMono=performance.now()
let active=true,timer:ReturnType<typeof setTimeout>|undefined,signal:AbortSignal|undefined,stop:(()=>void)|undefined
try{
const signed=capturePublicEnvelope(envelope)
const lifetime=publicDataFields(input,["deadlineAt","signal"])
const deadlineAt=lifetime.deadlineAt?.value,capturedSignal=lifetime.signal?.value
if(!Number.isSafeInteger(deadlineAt)||types.isProxy(capturedSignal)||capturedSignal!==undefined&&!(capturedSignal instanceof AbortSignal))refused()
signal=capturedSignal
const end=startedMono+Math.max(0,Math.min(deadlineAt-startedAt,10000))
const live=()=>{const now=Date.now();if(!active||closed||signal&&Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")!.get!.call(signal)||now<startedAt||now>=deadlineAt||performance.now()>=end)refused()}
live()
const stopped=new Promise<never>((_resolve,reject)=>{stop=()=>{active=false;reject(new BandwidthControlSourceError())}})
publicStops.add(stop!)
timer=setTimeout(stop!,Math.max(1,Math.ceil(end-performance.now())))
if(signal)EventTarget.prototype.addEventListener.call(signal,"abort",stop!,{once:true})
return await Promise.race([stopped,(async()=>{
live()
const result=publicNodeMetadata(signed,await publicMaterial(live));live();return result
})()])
}catch{throw new BandwidthControlSourceError()}
finally{active=false;clearTimeout(timer);if(stop){publicStops.delete(stop);if(signal)EventTarget.prototype.removeEventListener.call(signal,"abort",stop)}}
}
async function material(live:()=>void):Promise<Material>{
// Public files are independent. Complete both reads before acquiring the
// secret key, so a stalled public read cannot retain a key buffer.
const [bytes,publicBytes]=await Promise.all([readBounded(config.attestationFile,32768,live),readBounded(config.trustKeyFile,16384,live)])
const eventKey=await readBounded(config.eventKeyFile,32,live)
try{
if(eventKey.length!==32)refused()
const publicKey=createPublicKey(publicBytes)
if(publicKey.asymmetricKeyType!=="ed25519"||digest(publicKey.export({type:"spki",format:"der"}))!==config.trustKeySha256)refused()
const envelope=envelopeSchema.parse(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)))
const payload=Buffer.from(envelope.payload,"base64url"),signature=Buffer.from(envelope.signature,"base64url")
if(payload.toString("base64url")!==envelope.payload||signature.toString("base64url")!==envelope.signature||signature.length!==64||!verify(null,payload,publicKey,signature))refused()
const text=new TextDecoder("utf-8",{fatal:true}).decode(payload),record=bandwidthControlRecordSchema.parse(JSON.parse(text))
if(canonicalBandwidthControlRecord(record)!==text||record.databaseName!==name||record.runtimeRole!==runtime||record.ownerRole===runtime
||record.endpointSha256!==bandwidthControlEndpointSha256(config.databaseUrl)||record.schemaSourceSha256!==bandwidthControlSchemaSourceSha256()||record.eventKeySha256!==digest(eventKey))refused()
live();return {record,recordHash:digest(payload),eventKey,trustKey:publicKey}
}catch{eventKey.fill(0);throw new BandwidthControlSourceError()}
}
const connector=createProbeStorageConnectionConnector(async()=>{
if(closed)refused()
if(!pool){pool=new Pool({connectionString:config.databaseUrl,max:4,connectionTimeoutMillis:3000,query_timeout:5000,options:"-c search_path=pg_catalog",application_name:"mmapp-bandwidth-control"});pool.on("error",()=>{/* Idle backend loss: every later borrow re-verifies its source. */})}
return pool.connect()
})
/** Fixed public metadata inspection on one physical lease. The session lock
* is observed here, not a quiescence proof or permission to execute writes. */
async function openPublicRegistryMetadata(envelope:unknown,input:BandwidthScope):Promise<BandwidthPublicRegistryMetadataLease>{
const wall=Date.now(),mono=performance.now()
let retire=()=>{}
try{
const originalSigned=capturePublicEnvelope(envelope),fields=publicDataFields(input,["deadlineAt","signal"])
const requested:unknown=fields.deadlineAt?.value,signal:unknown=fields.signal?.value
if(typeof requested!=="number"||!Number.isSafeInteger(requested)||signal!==undefined&&(types.isProxy(signal)||!(signal instanceof AbortSignal)))refused()
const deadlineAt=Math.min(requested as number,wall+10000),end=mono+Math.max(0,deadlineAt-wall),originalSignal=signal as AbortSignal|undefined
const aborted=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")!.get!
const isAborted=()=>originalSignal?Reflect.apply(aborted,originalSignal,[]):false
isAborted() // Reject forged native prototypes before installing listeners.
const controller=new AbortController(),scope=Object.freeze({deadlineAt,signal:controller.signal})
let active=true,busy=false,released=false,connection:ProbeStorageConnection|undefined,pid:number|undefined,pin:string|undefined
let rejectStopped!:(error:BandwidthControlSourceError)=>void
const stopped=new Promise<never>((_resolve,reject)=>{rejectStopped=reject})
void stopped.catch(()=>{})
const live=()=>{const now=Date.now();if(!active||closed||connection?.lifetimeSignal?.aborted||isAborted()||now<wall||now>=deadlineAt||performance.now()>=end)refused()}
const release=()=>{if(connection&&!released){released=true;try{connection.release(true)}catch{/* Destroy attempt only; never healthy pool reuse. */}}}
retire=()=>{if(!active){release();return}active=false;clearTimeout(timer);publicStops.delete(retire);if(originalSignal)Reflect.apply(EventTarget.prototype.removeEventListener,originalSignal,["abort",retire]);controller.abort();release();rejectStopped(new BandwidthControlSourceError())}
publicStops.add(retire)
const timer=setTimeout(retire,Math.max(1,Math.ceil(end-performance.now())))
if(originalSignal)Reflect.apply(EventTarget.prototype.addEventListener,originalSignal,["abort",retire,{once:true}])
let fixedRegistrySql:readonly string[]=[]
const query=async(text:string,values?:unknown[])=>{
live()
if(!connection||![PUBLIC_PID_SQL,PUBLIC_LOCK_SQL,PUBLIC_HELD_SQL,...fixedRegistrySql].includes(text))refused()
const result=await connection!.query(text,values,{signal:controller.signal,timeoutMs:Math.max(1,Math.ceil(Math.min(5000,end-performance.now(),deadlineAt-Date.now())))})
live();if(!result||!("command"in result)||result.command!=="SELECT"||!Array.isArray(result.rows))refused()
return result
}
const singleton=(rows:Record<string,unknown>[],names:readonly string[])=>{if(rows.length!==1)refused();const fields=publicDataFields(rows[0],names);if(Object.keys(fields).length!==names.length)refused();return fields}
const held=async()=>{
const fields=singleton((await query(PUBLIC_HELD_SQL)).rows,["backend_pid","held"])
if(fields.backend_pid.value!==pid||fields.held.value!==true)refused()
}
const current=async(signed:ReturnType<typeof capturePublicEnvelope>)=>{
live();const value=await publicMaterial(live),metadata=publicNodeMetadata(signed,value),fingerprint=canonical(metadata)
live();if(pin!==undefined&&pin!==fingerprint)refused();pin??=fingerprint
return {value,metadata}
}
const identity=async(value:PublicMaterial,metadata:BandwidthPublicNodeBootstrapMetadata)=>{
const record=value.record,bootstrap=metadata.bootstrap
await assertBandwidthControlRegistryIdentity({query},{databaseName:name,runtimeRole:runtime,ownerRole:record.ownerRole,applicationRole:appRole,databaseOid:record.databaseOid,installationId:record.installationId,controlGeneration:record.controlGeneration,sourceRecordSha256:value.recordHash,eventKeySha256:record.eventKeySha256,catalogSha256:record.catalogSha256},
{databaseName:name,runtimeRole:runtime,ownerRole:record.ownerRole,installationId:bootstrap.installationId,issuerKeySha256:bootstrap.issuerKeySha256,quiescenceProof:bootstrap.quiescenceProof,registryCatalogSha256:bootstrap.registryCatalogSha256},bootstrap.format,live)
}
const inspect=async(rawEnvelope:unknown)=>{
try{
live();if(busy)refused();busy=true
const signed=capturePublicEnvelope(rawEnvelope)
return await Promise.race([stopped,(async()=>{
const before=await current(signed)
await held()
await identity(before.value,before.metadata)
await held();const after=await current(signed);live()
return Object.freeze({format:"mmapp-bandwidth-public-registry-metadata-v1" as const,metadata:after.metadata,backendPid:pid!})
})()])
}catch{retire();throw new BandwidthControlSourceError()}
finally{busy=false}
}
return await Promise.race([stopped,(async()=>{
live()
// Only this new public lease needs the fixed SQL constants. Existing
// strong APIs retain their original static module dependency surface.
const sql=await import("./bandwidth-control-registry-identity.js");live()
fixedRegistrySql=Object.freeze([sql.BANDWIDTH_CONTROL_NODE_IDENTITY_SQL,sql.BANDWIDTH_CONTROL_PEER_IDENTITY_SQL])
const first=await current(originalSigned)
connection=await connector(scope)
if(!active){release();refused()}
live()
const backend=singleton((await query(PUBLIC_PID_SQL)).rows,["backend_pid"])
if(typeof backend.backend_pid.value!=="number"||!Number.isSafeInteger(backend.backend_pid.value)||backend.backend_pid.value<1||backend.backend_pid.value>2147483647)refused()
pid=backend.backend_pid.value
// Authenticate current role/source/catalog before acquiring a session
// lock; signed public expectations alone never admit a raw DB role.
await identity(first.value,first.metadata)
await current(originalSigned)
const lock=singleton((await query(PUBLIC_LOCK_SQL)).rows,["acquired"])
if(lock.acquired.value!==true)refused()
await held();await current(originalSigned);live()
return Object.freeze({inspect,close:retire})
})()])
}catch{retire();throw new BandwidthControlSourceError()}
}
async function identity(connection:ProbeStorageConnection,value:Material,scope:BandwidthScope,live:()=>void){
const sql={query:async(text:string,values?:unknown[])=>{live();const result=await connection.query(text,values,{signal:scope.signal,timeoutMs:Math.max(1,Math.min(5000,scope.deadlineAt-Date.now()))});live();return result}}
const record=value.record
await assertBandwidthControlIdentity(sql,{databaseName:name,runtimeRole:runtime,ownerRole:record.ownerRole,applicationRole:appRole,
databaseOid:record.databaseOid,installationId:record.installationId,controlGeneration:record.controlGeneration,
sourceRecordSha256:value.recordHash,eventKeySha256:record.eventKeySha256,catalogSha256:record.catalogSha256},live)
live()
}
async function connect(input:BandwidthScope,dispatchGuard?:(fence:BandwidthControlDispatchFence)=>Promise<void>):Promise<ProbeStorageConnection>{
if(dispatchGuard!==undefined&&typeof dispatchGuard!=="function")refused()
if(!input||!Number.isSafeInteger(input.deadlineAt)||input.signal!==undefined&&!(input.signal instanceof AbortSignal))refused()
const scope=Object.freeze({signal:input.signal,deadlineAt:Math.min(input.deadlineAt,Date.now()+10000)})
let active=true,released=false,busy=false,connection:ProbeStorageConnection|undefined,owned:ProbeStorageConnection|undefined,pinnedRecordHash:string|undefined,stop!:()=>void
const close=(unsafe:boolean)=>{active=false;if(owned)verifiedHashes.delete(owned);if(connection&&!released){released=true;try{connection.release(unsafe)}catch{/* No unsafe pool reuse. */}}}
const live=()=>{if(closed||!active||connection?.lifetimeSignal?.aborted||scope.signal?.aborted||Date.now()>=scope.deadlineAt)refused()}
let rejectStopped!:(error:BandwidthControlSourceError)=>void
const stopped=new Promise<never>((_resolve,reject)=>{rejectStopped=reject;stop=()=>retire(true)})
const timer=setTimeout(stop,Math.max(1,scope.deadlineAt-Date.now()));scope.signal?.addEventListener("abort",stop,{once:true})
function retire(unsafe:boolean){clearTimeout(timer);scope.signal?.removeEventListener("abort",stop);close(unsafe);rejectStopped(new BandwidthControlSourceError())}
const checked=async()=>{
const value=await material(live)
try{if(!connection||pinnedRecordHash!==undefined&&value.recordHash!==pinnedRecordHash)refused();await identity(connection!,value,scope,live);pinnedRecordHash??=value.recordHash;return {recordHash:value.recordHash}}
finally{value.eventKey.fill(0)}
}
const fence=async()=>{
if(!dispatchGuard)return
let running=true,using=false
const valid=()=>{live();if(!running)refused()}
const exclusive=async<T>(work:()=>Promise<T>)=>{valid();if(using){retire(true);refused()};using=true;try{const result=await work();valid();return result}finally{using=false}}
const context:BandwidthControlDispatchFence=Object.freeze({
query:(text:string,values?:unknown[])=>exclusive(async()=>{const result=await connection!.query(text,values,{signal:scope.signal,timeoutMs:Math.max(1,Math.min(5000,scope.deadlineAt-Date.now()))});valid();return result}),
verifyNodeBootstrap:(envelope:unknown)=>{
const signed=bandwidthNodeBootstrapEnvelopeSchema.parse(envelope)
return exclusive(async()=>{const value=await material(valid);try{if(value.recordHash!==pinnedRecordHash)refused();return verifyNodeRecord(signed,value)}finally{value.eventKey.fill(0)}})
},
sourceIdentity:()=>exclusive(async()=>{
const value=await material(valid)
try{
if(value.recordHash!==pinnedRecordHash)refused()
return Object.freeze({installationId:value.record.installationId,controlGeneration:value.record.controlGeneration,sourceRecordSha256:value.recordHash})
}finally{value.eventKey.fill(0)}
}),
})
try{await dispatchGuard(context);valid();if(using)refused()}
finally{running=false;if(using)retire(true)}
}
try{return await Promise.race([Promise.resolve().then(async()=>{
live();const first=await material(live);pinnedRecordHash=first.recordHash;first.eventKey.fill(0)
connection=await connector(scope);if(!active){close(true);refused()}
const initial=await checked()
const lifetimeSignal=connection.lifetimeSignal
owned=Object.freeze({
...(lifetimeSignal?{lifetimeSignal}:{}),
async query(text:string,values?:unknown[],options?:{signal?:AbortSignal;timeoutMs:number}){
if(busy) {retire(true);refused()};busy=true
const work=async()=>{
try{live();await checked();await fence();live();const result=await connection!.query(text,values,options);live();const current=await checked();await fence();live();verifiedHashes.set(owned!,current.recordHash);return result}
catch{retire(true);throw new BandwidthControlSourceError()}
finally{busy=false}
}
return Promise.race([work(),stopped])
},
release(unsafe=false){retire(unsafe||busy)},
})
verifiedHashes.set(owned!,initial.recordHash);return owned!
}),stopped])}catch{clearTimeout(timer);scope.signal?.removeEventListener("abort",stop);close(true);throw new BandwidthControlSourceError()}
}
async function connectRegistry(input:BandwidthScope,dispatchGuard:(fence:BandwidthControlRegistryDispatchFence)=>Promise<void>):Promise<ProbeStorageConnection>{
if(typeof dispatchGuard!=="function")refused()
if(!input||!Number.isSafeInteger(input.deadlineAt)||input.signal!==undefined&&!(input.signal instanceof AbortSignal))refused()
const scope=Object.freeze({signal:input.signal,deadlineAt:Math.min(input.deadlineAt,Date.now()+10000)})
let active=true,released=false,busy=false,connection:ProbeStorageConnection|undefined,owned:ProbeStorageConnection|undefined,pinnedRecordHash:string|undefined,stop!:()=>void
const close=(unsafe:boolean)=>{active=false;if(owned)verifiedHashes.delete(owned);if(connection&&!released){released=true;try{connection.release(unsafe)}catch{/* No unsafe pool reuse. */}}}
const live=()=>{if(closed||!active||connection?.lifetimeSignal?.aborted||scope.signal?.aborted||Date.now()>=scope.deadlineAt)refused()}
let rejectStopped!:(error:BandwidthControlSourceError)=>void
const stopped=new Promise<never>((_resolve,reject)=>{rejectStopped=reject;stop=()=>retire(true)})
const timer=setTimeout(stop,Math.max(1,scope.deadlineAt-Date.now()));scope.signal?.addEventListener("abort",stop,{once:true})
function retire(unsafe:boolean){clearTimeout(timer);scope.signal?.removeEventListener("abort",stop);close(unsafe);rejectStopped(new BandwidthControlSourceError())}
const checked=async()=>{
const value=await material(live)
try{if(!connection||pinnedRecordHash!==undefined&&value.recordHash!==pinnedRecordHash)refused();await identity(connection!,value,scope,live);pinnedRecordHash??=value.recordHash;return {recordHash:value.recordHash}}
finally{value.eventKey.fill(0)}
}
const fence=async()=>{
let running=true,using=false,verification=0,checkedVerification=0,sqlSequence=0
let latest: {verified:BandwidthVerifiedNodeBootstrap;hash:string;recordHash:string;sqlSequence:number}|undefined,checked:{hash:string;recordHash:string}|undefined
const genuine=new WeakMap<object,{core:BandwidthControlIdentityExpected;hash:string;recordHash:string;verification:number}>()
const valid=()=>{live();if(!running)refused()}
const exclusive=async<T>(work:()=>Promise<T>)=>{valid();if(using){retire(true);refused()};using=true;try{const result=await work();valid();return result}finally{using=false}}
const context:BandwidthControlRegistryDispatchFence=Object.freeze({
query:(text:string,values?:unknown[])=>exclusive(async()=>{sqlSequence++;const result=await connection!.query(text,values,{signal:scope.signal,timeoutMs:Math.max(1,Math.min(5000,scope.deadlineAt-Date.now()))});valid();return result}),
verifyNodeBootstrap:(envelope:unknown)=>{
const signed=bandwidthNodeBootstrapEnvelopeSchema.parse(envelope)
return exclusive(async()=>{const value=await material(valid);try{if(value.recordHash!==pinnedRecordHash)refused()
const verified=verifyNodeRecord(signed,value),record=value.record,bootstrapHash=digest(canonicalBandwidthNodeBootstrap(verified.bootstrap))
const captured={core:{databaseName:name,runtimeRole:runtime,ownerRole:record.ownerRole,applicationRole:appRole,databaseOid:record.databaseOid,installationId:record.installationId,controlGeneration:record.controlGeneration,sourceRecordSha256:value.recordHash,eventKeySha256:record.eventKeySha256,catalogSha256:record.catalogSha256},hash:bootstrapHash,recordHash:value.recordHash,verification:++verification}
genuine.set(verified,captured);latest={verified,hash:bootstrapHash,recordHash:value.recordHash,sqlSequence};return verified}finally{value.eventKey.fill(0)}})
},
assertRegistryIdentity:(verified:BandwidthVerifiedNodeBootstrap)=>exclusive(async()=>{
const captured=verified&&typeof verified==="object"?genuine.get(verified):undefined
if(!captured||latest?.verified!==verified||captured.verification!==verification||checked)refused()
const bootstrap=verified.bootstrap
const expected={databaseName:captured!.core.databaseName,runtimeRole:captured!.core.runtimeRole,ownerRole:captured!.core.ownerRole,installationId:bootstrap.installationId,issuerKeySha256:bootstrap.issuerKeySha256,quiescenceProof:bootstrap.quiescenceProof,registryCatalogSha256:bootstrap.registryCatalogSha256}
const sql={query:async(text:string,values?:unknown[])=>{valid();const result=await connection!.query(text,values,{signal:scope.signal,timeoutMs:Math.max(1,Math.min(5000,scope.deadlineAt-Date.now()))});valid();return result}}
sqlSequence++;await assertBandwidthControlRegistryIdentity(sql,captured!.core,expected,bootstrap.format,valid)
valid();checked={hash:captured!.hash,recordHash:captured!.recordHash};checkedVerification=captured!.verification
}),
sourceIdentity:()=>exclusive(async()=>{
const value=await material(valid)
try{
if(value.recordHash!==pinnedRecordHash)refused()
return Object.freeze({installationId:value.record.installationId,controlGeneration:value.record.controlGeneration,sourceRecordSha256:value.recordHash})
}finally{value.eventKey.fill(0)}
}),
})
try{await dispatchGuard(context);valid()
if(using||!checked||!latest||verification<=checkedVerification||latest.sqlSequence!==sqlSequence||latest.hash!==checked.hash||latest.recordHash!==checked.recordHash||latest.recordHash!==pinnedRecordHash)refused()
return {recordHash:latest!.recordHash}
}
finally{running=false;if(using)retire(true)}
}
try{return await Promise.race([Promise.resolve().then(async()=>{
live();const first=await material(live);pinnedRecordHash=first.recordHash;first.eventKey.fill(0)
connection=await connector(scope);if(!active){close(true);refused()}
const initial=await checked()
const lifetimeSignal=connection.lifetimeSignal
owned=Object.freeze({
...(lifetimeSignal?{lifetimeSignal}:{}),
async query(text:string,values?:unknown[],options?:{signal?:AbortSignal;timeoutMs:number}){
if(busy) {retire(true);refused()};busy=true
const work=async()=>{
try{live();await fence();live();const result=await connection!.query(text,values,options);live();const current=await fence();live();verifiedHashes.set(owned!,current.recordHash);return result}
catch{retire(true);throw new BandwidthControlSourceError()}
finally{busy=false}
}
return Promise.race([work(),stopped])
},
release(unsafe=false){retire(unsafe||busy)},
})
verifiedHashes.set(owned!,initial.recordHash);return owned!
}),stopped])}catch{clearTimeout(timer);scope.signal?.removeEventListener("abort",stop);close(true);throw new BandwidthControlSourceError()}
}
async function withSource<T>(scope:BandwidthScope,work:(value:Material)=>T):Promise<T>{
const connection=await connect(scope)
try{const live=()=>{if(closed||connection.lifetimeSignal?.aborted||scope.signal?.aborted||Date.now()>=scope.deadlineAt)refused()};const value=await material(live);try{live();if(verifiedHashes.get(connection)!==value.recordHash)refused();const result=work(value);live();return result}finally{value.eventKey.fill(0)}}finally{connection.release()}
}
async function eventProofOnConnection(event:unknown,connection:ProbeStorageConnection,input:BandwidthScope){
try{
// Capture the event before any await: caller mutation must not change the
// authenticated event after the operation has begun.
const text=JSON.stringify(event)
if(typeof text!=="string"||Buffer.byteLength(text)>65536)refused()
const snapshot=canonical(JSON.parse(text))
if(!input||!Number.isSafeInteger(input.deadlineAt)||input.signal!==undefined&&!(input.signal instanceof AbortSignal))refused()
const scope=Object.freeze({deadlineAt:input.deadlineAt,signal:input.signal})
const live=()=>{if(closed||!verifiedHashes.has(connection)||connection.lifetimeSignal?.aborted||scope.signal?.aborted||Date.now()>=scope.deadlineAt)refused()}
live()
await connection.query("SELECT 1",undefined,{signal:scope.signal,timeoutMs:Math.max(1,Math.min(5000,scope.deadlineAt-Date.now()))})
live()
const value=await material(live)
try{
if(verifiedHashes.get(connection)!==value.recordHash)refused()
live()
return createHmac("sha256",value.eventKey).update("bandwidth-control-event-v1:"+snapshot).digest("hex")
}finally{value.eventKey.fill(0)}
}catch{throw new BandwidthControlSourceError()}
}
return Object.freeze({connect,connectRegistry,eventProofOnConnection,inspectPublicNodeBootstrap,openPublicRegistryMetadata,
/** Domain-separated admission proofs, including the existing 8 MiB native
* terminal envelope. The expected original source record is never adopted
* from a later valid generation. This is server-owned broker input only. */
async admissionProof(purpose:string,value:unknown,expectedSourceRecordSha256:string,scope:BandwidthScope){
try{
if(!["bandwidth-request-v1","bandwidth-command-v1","bandwidth-binding-v1","bandwidth-terminal-v1","bandwidth-endpoint-v1"].includes(purpose)||!hash.safeParse(expectedSourceRecordSha256).success)refused()
const text=JSON.stringify(value)
if(typeof text!=="string"||Buffer.byteLength(text)>9*1048576)refused()
const snapshot=canonical(JSON.parse(text))
return await withSource(scope,material=>{
if(material.recordHash!==expectedSourceRecordSha256)refused()
return createHmac("sha256",material.eventKey).update("mmapp-bandwidth-admission-v1:"+purpose+":"+snapshot).digest("hex")
})
}catch{throw new BandwidthControlSourceError()}
},
/** Verify the fixed node bootstrap on THIS active physical source lease.
* No nested checkout: a registry transaction and its key/authority guards
* must not exhaust the pool by recursively borrowing additional clients.
* Neither a JSON lease nor a released/foreign source connection is valid. */
async verifyNodeBootstrap(envelope:unknown,connection:ProbeStorageConnection,input:BandwidthScope){
const scope=Object.freeze({deadlineAt:input.deadlineAt,signal:input.signal})
const live=()=>{if(closed||!verifiedHashes.has(connection)||connection.lifetimeSignal?.aborted||!Number.isSafeInteger(scope.deadlineAt)||scope.signal?.aborted||Date.now()>=scope.deadlineAt)refused()}
try{
const signed=bandwidthNodeBootstrapEnvelopeSchema.parse(envelope)
live();await connection.query("SELECT 1",undefined,{signal:scope.signal,timeoutMs:Math.max(1,Math.min(5000,scope.deadlineAt-Date.now()))});live()
const value=await material(live)
try{
if(verifiedHashes.get(connection)!==value.recordHash)refused()
live();return verifyNodeRecord(signed,value)
}finally{value.eventKey.fill(0)}
}catch{throw new BandwidthControlSourceError()}
},
async eventProof(event:unknown,scope:BandwidthScope){try{const text=JSON.stringify(event);if(typeof text!=="string"||Buffer.byteLength(text)>65536)refused();const snapshot=canonical(JSON.parse(text));return await withSource(scope,value=>createHmac("sha256",value.eventKey).update("bandwidth-control-event-v1:"+snapshot).digest("hex"))}catch{throw new BandwidthControlSourceError()}},
identity:(scope:BandwidthScope)=>withSource(scope,value=>Object.freeze({installationId:value.record.installationId,controlGeneration:value.record.controlGeneration,sourceAuthenticated:true as const,applicationSchemaReady:false as const})),
close(){closed=true;for(const stop of publicStops)stop();closing??=pool?pool.end():Promise.resolve();return closing},
})
}
let productionSource:ReturnType<typeof createConfiguredBandwidthControlSource>|undefined
/** Fixed lazy server assembly. No caller configuration or automatic bootstrap;
* absence affects the caller requesting this source, not registry imports. */
export function getProductionBandwidthControlSource(){
if(productionSource)return productionSource
const required=(name:string)=>{const value=process.env[name];if(!value?.trim())throw new BandwidthControlSourceError();return value}
productionSource=createConfiguredBandwidthControlSource({databaseUrl:required("MMAPP_BANDWIDTH_CONTROL_URL"),applicationDatabaseUrl:required("DATABASE_URL"),
attestationFile:required("MMAPP_BANDWIDTH_CONTROL_ATTESTATION_FILE"),trustKeyFile:required("MMAPP_BANDWIDTH_CONTROL_TRUST_KEY_FILE"),
trustKeySha256:required("MMAPP_BANDWIDTH_CONTROL_TRUST_KEY_SHA256"),eventKeyFile:required("MMAPP_BANDWIDTH_CONTROL_EVENT_KEY_FILE")})
return productionSource
}
export async function closeProductionBandwidthControlSource(){await productionSource?.close()}