368 lines
27 KiB
TypeScript
368 lines
27 KiB
TypeScript
/** Fixed operational registry source/key assembly. It does not issue actor,
|
|
* enrollment or native execution authority, create keys/rows/schema, or certify
|
|
* rollback/clone fencing of the provider. Each session uses ONE core lease;
|
|
* key/catalog guards never recursively borrow another control connection. */
|
|
import {createHash,createHmac} from "node:crypto"
|
|
import {isAbsolute,resolve} from "node:path"
|
|
import {performance} from "node:perf_hooks"
|
|
import {types} from "node:util"
|
|
import {z} from "zod"
|
|
import {bandwidthNodeProofShapes as shapes,captureBandwidthNodeProofBatch as captureProofBatch,type BandwidthNodeProofInput} from "./bandwidth-node-proof-input.js"
|
|
import {getProductionBandwidthControlSource,readBandwidthControlFile,type createConfiguredBandwidthControlSource,type BandwidthControlDispatchFence,type BandwidthControlRegistryDispatchFence,type BandwidthPublicNodeBootstrapMetadata} from "./bandwidth-control-source.js"
|
|
import {canonicalBandwidthNodeValue,bandwidthNodeBootstrapEnvelopeSchema,bandwidthNodeBootstrapSchema,type BandwidthNodeBootstrap} from "./bandwidth-node-bootstrap.js"
|
|
import type {ProbeStorageConnection} from "./server-probe-journal-maintenance.js"
|
|
import type {BandwidthScope} from "./bandwidth-admission.js"
|
|
import {assertResolvedBandwidthNodesOnFence,type BandwidthResolvedNodeFence} from "./bandwidth-node-fence.js"
|
|
import {assertResolvedBandwidthPeersOnFence,type BandwidthResolvedPeerFence} from "./bandwidth-peer-fence.js"
|
|
|
|
type Core=ReturnType<typeof createConfiguredBandwidthControlSource>
|
|
type Verified=Awaited<ReturnType<Core["verifyNodeBootstrap"]>>
|
|
export interface BandwidthNodeSourceConfig {issuerKeyFile:string;issuerKeySha256:string;bootstrapFile:string}
|
|
export type {BandwidthNodeProofInput} from "./bandwidth-node-proof-input.js"
|
|
/** Public signed metadata ONLY. Does not prove a current issuer/event key,
|
|
* installed catalog/ownership, held Q, SQL lease or native execution authority. */
|
|
export interface BandwidthNodePublicBootstrapMetadata extends BandwidthPublicNodeBootstrapMetadata {readonly bootstrapSha256:string}
|
|
export interface BandwidthNodePublicRegistryMetadataSnapshot {
|
|
readonly format:"mmapp-bandwidth-public-registry-metadata-v1"
|
|
readonly metadata:Readonly<BandwidthNodePublicBootstrapMetadata>
|
|
readonly backendPid:number
|
|
}
|
|
/** Public SQL metadata only; exposes neither a query handle nor Q/write proof. */
|
|
export interface BandwidthNodePublicRegistryMetadataLease {
|
|
inspect():Promise<Readonly<BandwidthNodePublicRegistryMetadataSnapshot>>
|
|
close():void
|
|
}
|
|
export class BandwidthNodeSourceError extends Error {
|
|
readonly code="BANDWIDTH_NODE_SOURCE_UNAVAILABLE"
|
|
constructor(){super("Операторская привязка и ключ реестра bandwidth не подтверждены")}
|
|
}
|
|
const fail=():never=>{throw new BandwidthNodeSourceError()}
|
|
const hash=z.string().regex(/^[a-f0-9]{64}$/),uuid=z.string().uuid()
|
|
const digest=(value:Buffer|string)=>createHash("sha256").update(value).digest("hex")
|
|
const root=(value:BandwidthNodeBootstrap)=>({installationId:value.installationId,issuerKeySha256:value.issuerKeySha256,quiescenceProof:value.quiescenceProof})
|
|
const publicMetadataSchema=z.object({format:z.literal("mmapp-bandwidth-public-node-metadata-v1"),bootstrap:bandwidthNodeBootstrapSchema,
|
|
source:z.object({installationId:uuid,controlGeneration:uuid,sourceRecordSha256:hash}).strict(),
|
|
publicDatabase:z.object({databaseName:z.string().min(1).max(63),runtimeRole:z.string().min(1).max(63),ownerRole:z.string().min(1).max(63),
|
|
databaseOid:z.number().int().min(1).max(4294967295),catalogSha256:hash}).strict()}).strict()
|
|
function capturePublicData(input:unknown):unknown{
|
|
let nodes=0,bytes=0
|
|
const copy=(value:unknown,depth=0):unknown=>{
|
|
if(++nodes>256||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)||Object.getPrototypeOf(value)!==Object.prototype)return fail()
|
|
const result:Record<string,unknown>={}
|
|
for(const key of Reflect.ownKeys(value)){
|
|
if(typeof key!=="string"||key==="__proto__")return fail()
|
|
const field=Object.getOwnPropertyDescriptor(value,key)
|
|
if(!field||!("value"in field)||!field.enumerable)return fail()
|
|
bytes+=Buffer.byteLength(key);if(bytes>65536)fail()
|
|
Object.defineProperty(result,key,{value:copy(field.value,depth+1),enumerable:true})
|
|
}
|
|
return Object.freeze(result)
|
|
}
|
|
return copy(input)
|
|
}
|
|
|
|
/** Server-owned construction only, never request JSON. The production getter
|
|
* below fixes the genuine core source and operator paths. Construction is inert.
|
|
* dispatchGuard must check the original actor/source grant without re-entering
|
|
* this control lease; the core invokes it AFTER its own async metadata guards,
|
|
* immediately before actual driver SQL and before acknowledging the result. */
|
|
export function createConfiguredBandwidthNodeSource(coreSource:Core,raw:BandwidthNodeSourceConfig){
|
|
const config=Object.freeze({...raw})
|
|
if(!hash.safeParse(config.issuerKeySha256).success||[config.issuerKeyFile,config.bootstrapFile].some(path=>typeof path!=="string"||!isAbsolute(path)||resolve(path)!==path)
|
|
||config.issuerKeyFile===config.bootstrapFile)fail()
|
|
const baseConnect=coreSource.connect.bind(coreSource)
|
|
const registryConnect=(coreSource as Partial<Pick<Core,"connectRegistry">>).connectRegistry?.bind(coreSource)
|
|
const inspectPublic=(coreSource as Partial<Pick<Core,"inspectPublicNodeBootstrap">>).inspectPublicNodeBootstrap?.bind(coreSource)
|
|
const openPublicRegistry=(coreSource as Partial<Pick<Core,"openPublicRegistryMetadata">>).openPublicRegistryMetadata?.bind(coreSource)
|
|
const core=Object.freeze({connect:(scope:BandwidthScope,guard:(fence:BandwidthControlDispatchFence)=>Promise<void>)=>
|
|
registryConnect?registryConnect(scope,guard):baseConnect(scope,guard)})
|
|
let closed=false
|
|
const sessions=new Set<()=>void>()
|
|
const publicOperations=new Set<()=>void>()
|
|
async function inspectPublicBootstrap(input:BandwidthScope):Promise<Readonly<BandwidthNodePublicBootstrapMetadata>>{
|
|
// Capture the caller's FIRST immutable horizon before any file/core await.
|
|
const wall=Date.now(),mono=performance.now()
|
|
if(closed||!input||types.isProxy(input)||Object.getPrototypeOf(input)!==Object.prototype)fail()
|
|
const descriptors=Object.getOwnPropertyDescriptors(input)
|
|
if(Reflect.ownKeys(input).some(key=>typeof key!=="string"||!["deadlineAt","signal"].includes(key))
|
|
||Object.values(descriptors).some(field=>!("value"in field)||!field.enumerable))fail()
|
|
const requestedDeadline:unknown=descriptors.deadlineAt?.value,signal:unknown=descriptors.signal?.value
|
|
if(typeof requestedDeadline!=="number"||!Number.isSafeInteger(requestedDeadline)||signal!==undefined&&(types.isProxy(signal)||!(signal instanceof AbortSignal)))return fail()
|
|
const deadlineAt=Math.min(requestedDeadline,wall+10000),end=mono+Math.max(0,deadlineAt-wall),originalSignal=signal as AbortSignal|undefined
|
|
// Native operations ignore hostile AbortSignal subclass accessors/methods.
|
|
const aborted=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")!.get!
|
|
const isAborted=()=>originalSignal?Reflect.apply(aborted,originalSignal,[]):false
|
|
try{isAborted()}catch{return fail()}
|
|
const controller=new AbortController(),scope=Object.freeze({deadlineAt,signal:controller.signal})
|
|
let active=true,rejectStopped!:(error:BandwidthNodeSourceError)=>void
|
|
const live=()=>{const now=Date.now();if(closed||!active||isAborted()||controller.signal.aborted||now<wall||now>=deadlineAt||performance.now()>=end)fail()}
|
|
const stopped=new Promise<never>((_resolve,reject)=>{rejectStopped=reject})
|
|
const stop=()=>{if(!active)return;active=false;controller.abort();rejectStopped(new BandwidthNodeSourceError())}
|
|
const timer=setTimeout(stop,Math.max(1,Math.min(2147483647,end-performance.now())))
|
|
publicOperations.add(stop);if(originalSignal)Reflect.apply(EventTarget.prototype.addEventListener,originalSignal,["abort",stop,{once:true}])
|
|
const readPublic=async()=>{
|
|
live();const bytes=await readBandwidthControlFile(config.bootstrapFile,32768,live);live()
|
|
const envelope=bandwidthNodeBootstrapEnvelopeSchema.parse(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)))
|
|
if(!inspectPublic)return fail()
|
|
const value=publicMetadataSchema.parse(await inspectPublic(envelope,scope));live()
|
|
if(value.bootstrap.issuerKeySha256!==config.issuerKeySha256||value.source.installationId!==value.bootstrap.installationId)fail()
|
|
Object.freeze(value.bootstrap);Object.freeze(value.source);Object.freeze(value.publicDatabase)
|
|
return Object.freeze({...value,bootstrapSha256:digest(canonicalBandwidthNodeValue(value.bootstrap))})
|
|
}
|
|
try{
|
|
live()
|
|
return await Promise.race([Promise.resolve().then(async()=>{
|
|
const before=await readPublic(),after=await readPublic();live()
|
|
if(canonicalBandwidthNodeValue(before)!==canonicalBandwidthNodeValue(after))fail()
|
|
return after
|
|
}),stopped])
|
|
}catch{throw new BandwidthNodeSourceError()}
|
|
finally{active=false;clearTimeout(timer);if(originalSignal)Reflect.apply(EventTarget.prototype.removeEventListener,originalSignal,["abort",stop]);publicOperations.delete(stop);controller.abort()}
|
|
}
|
|
async function openPublicRegistryMetadata(input:BandwidthScope):Promise<Readonly<BandwidthNodePublicRegistryMetadataLease>>{
|
|
const wall=Date.now(),mono=performance.now()
|
|
if(closed||!input||types.isProxy(input)||Object.getPrototypeOf(input)!==Object.prototype)return fail()
|
|
const fields=Object.getOwnPropertyDescriptors(input)
|
|
if(Reflect.ownKeys(input).some(key=>typeof key!=="string"||!["deadlineAt","signal"].includes(key))
|
|
||Object.values(fields).some(field=>!("value"in field)||!field.enumerable))return fail()
|
|
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)))return fail()
|
|
const deadlineAt=Math.min(requested,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
|
|
try{isAborted()}catch{return fail()}
|
|
const controller=new AbortController(),scope=Object.freeze({deadlineAt,signal:controller.signal})
|
|
type PublicCoreLease={inspect(envelope:unknown):Promise<unknown>;close():void}
|
|
let active=true,busy=true,owned:PublicCoreLease|undefined,physicallyClosed=false,pinned:Readonly<BandwidthNodePublicRegistryMetadataSnapshot>|undefined
|
|
let originalFile:string|undefined,rejectStopped!:(error:BandwidthNodeSourceError)=>void
|
|
const stopped=new Promise<never>((_resolve,reject)=>{rejectStopped=reject});void stopped.catch(()=>{})
|
|
const closeOwned=()=>{
|
|
if(!owned||physicallyClosed)return
|
|
for(let attempt=0;attempt<2;attempt++)try{owned.close();physicallyClosed=true;return}catch{/* Never return this lease healthy. */}
|
|
}
|
|
const live=()=>{const now=Date.now();if(closed||!active||isAborted()||controller.signal.aborted||now<wall||now>=deadlineAt||performance.now()>=end)fail()}
|
|
const stop=()=>{
|
|
if(!active)return
|
|
active=false;clearTimeout(timer);controller.abort();closeOwned()
|
|
if(originalSignal)Reflect.apply(EventTarget.prototype.removeEventListener,originalSignal,["abort",stop])
|
|
publicOperations.delete(stop);rejectStopped(new BandwidthNodeSourceError())
|
|
}
|
|
const timer=setTimeout(stop,Math.max(1,Math.min(2147483647,end-performance.now())))
|
|
publicOperations.add(stop);if(originalSignal)Reflect.apply(EventTarget.prototype.addEventListener,originalSignal,["abort",stop,{once:true}])
|
|
const readEnvelope=async()=>{
|
|
live();const bytes=await readBandwidthControlFile(config.bootstrapFile,32768,live);live()
|
|
const file=digest(bytes)
|
|
if(originalFile!==undefined&&file!==originalFile)fail()
|
|
const envelope=bandwidthNodeBootstrapEnvelopeSchema.parse(capturePublicData(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes))))
|
|
const payload=Buffer.from(envelope.payload,"base64url"),text=new TextDecoder("utf-8",{fatal:true}).decode(payload)
|
|
const bootstrap=bandwidthNodeBootstrapSchema.parse(capturePublicData(JSON.parse(text)))
|
|
if(payload.toString("base64url")!==envelope.payload||canonicalBandwidthNodeValue(bootstrap)!==text||bootstrap.issuerKeySha256!==config.issuerKeySha256)fail()
|
|
return {file,envelope}
|
|
}
|
|
const captureLease=(raw:unknown):PublicCoreLease=>{
|
|
if(!raw||typeof raw!=="object"||types.isProxy(raw)||Object.getPrototypeOf(raw)!==Object.prototype)return fail()
|
|
const descriptors=Object.getOwnPropertyDescriptors(raw),inspect=descriptors.inspect,close=descriptors.close
|
|
const cleanup=()=>{if(close&&"value"in close&&typeof close.value==="function")try{Reflect.apply(close.value,raw,[])}catch{/* Malformed producer lease is refused. */}}
|
|
if(!Object.isFrozen(raw)||Reflect.ownKeys(raw).length!==2||!inspect||!("value"in inspect)||typeof inspect.value!=="function"||!inspect.enumerable
|
|
||!close||!("value"in close)||typeof close.value!=="function"||!close.enumerable){cleanup();return fail()}
|
|
return Object.freeze({inspect:(envelope:unknown)=>Reflect.apply(inspect.value,raw,[envelope]) as Promise<unknown>,close:()=>{Reflect.apply(close.value,raw,[])}})
|
|
}
|
|
const captureResult=(raw:unknown,envelope:ReturnType<typeof bandwidthNodeBootstrapEnvelopeSchema.parse>):Readonly<BandwidthNodePublicRegistryMetadataSnapshot>=>{
|
|
if(!raw||typeof raw!=="object"||types.isProxy(raw)||!Object.isFrozen(raw))return fail()
|
|
const value=z.object({format:z.literal("mmapp-bandwidth-public-registry-metadata-v1"),metadata:publicMetadataSchema,backendPid:z.number().int().positive().max(2147483647)}).strict().parse(capturePublicData(raw))
|
|
if(value.metadata.bootstrap.issuerKeySha256!==config.issuerKeySha256||value.metadata.source.installationId!==value.metadata.bootstrap.installationId)fail()
|
|
const payload=Buffer.from(envelope.payload,"base64url")
|
|
if(payload.toString("base64url")!==envelope.payload||new TextDecoder("utf-8",{fatal:true}).decode(payload)!==canonicalBandwidthNodeValue(value.metadata.bootstrap))fail()
|
|
Object.freeze(value.metadata.bootstrap);Object.freeze(value.metadata.source);Object.freeze(value.metadata.publicDatabase)
|
|
const metadata=Object.freeze({...value.metadata,bootstrapSha256:digest(canonicalBandwidthNodeValue(value.metadata.bootstrap))})
|
|
return Object.freeze({format:value.format,metadata,backendPid:value.backendPid})
|
|
}
|
|
const inspectSpan=async()=>{
|
|
const before=await readEnvelope()
|
|
const first=await owned!.inspect(before.envelope);live()
|
|
const captured=captureResult(first,before.envelope),after=await readEnvelope()
|
|
if(canonicalBandwidthNodeValue(before.envelope)!==canonicalBandwidthNodeValue(after.envelope))fail()
|
|
const second=await owned!.inspect(after.envelope);live()
|
|
const result=captureResult(second,after.envelope);await readEnvelope();live()
|
|
if(canonicalBandwidthNodeValue(captured)!==canonicalBandwidthNodeValue(result)
|
|
||pinned&&canonicalBandwidthNodeValue(pinned)!==canonicalBandwidthNodeValue(result))fail()
|
|
pinned??=result;return result
|
|
}
|
|
try{
|
|
live()
|
|
return await Promise.race([Promise.resolve().then(async()=>{
|
|
const initial=await readEnvelope();originalFile=initial.file
|
|
if(!openPublicRegistry)return fail()
|
|
// Capture/close even a producer that ignores abort and returns late.
|
|
owned=captureLease(await openPublicRegistry(initial.envelope,scope))
|
|
if(!active){closeOwned();return fail()}
|
|
live();await inspectSpan();live();busy=false
|
|
return Object.freeze({
|
|
async inspect(){
|
|
try{
|
|
live();if(busy){stop();return fail()}busy=true
|
|
return await Promise.race([Promise.resolve().then(inspectSpan),stopped])
|
|
}catch{stop();throw new BandwidthNodeSourceError()}
|
|
finally{busy=false}
|
|
},close:stop,
|
|
})
|
|
}),stopped])
|
|
}catch{stop();throw new BandwidthNodeSourceError()}
|
|
}
|
|
async function open(input:BandwidthScope,dispatchGuard?:()=>Promise<void>,ownershipGuard?:(fence:BandwidthControlDispatchFence)=>Promise<void>){
|
|
if(!input||!Number.isSafeInteger(input.deadlineAt)||input.signal!==undefined&&!(input.signal instanceof AbortSignal)
|
|
||dispatchGuard!==undefined&&typeof dispatchGuard!=="function"||ownershipGuard!==undefined&&typeof ownershipGuard!=="function")fail()
|
|
const began=Date.now(),end=performance.now()+Math.max(0,Math.min(10000,input.deadlineAt-began))
|
|
const scope=Object.freeze({deadlineAt:Math.min(input.deadlineAt,began+10000),signal:input.signal})
|
|
type Captured={verified:Verified;key:Buffer;bootstrapHash:string}
|
|
let connection:ProbeStorageConnection|undefined,active=true,released=false,busy=false,pinned:Verified|undefined,pinnedBootstrap:string|undefined,captureRequested=false,captured:Captured|undefined
|
|
const keys=new Set<Buffer>()
|
|
const wipe=(key:Buffer)=>{key.fill(0);keys.delete(key)}
|
|
const live=()=>{if(closed||!active||connection?.lifetimeSignal?.aborted||scope.signal?.aborted||Date.now()>=scope.deadlineAt||performance.now()>=end)fail()}
|
|
const close=()=>{active=false;for(const key of keys)key.fill(0);keys.clear();captured=undefined;if(connection&&!released){released=true;try{connection.release(true)}catch{/* The lease is never reused healthy. */}}}
|
|
const clearCapture=()=>{if(captured)wipe(captured.key);captured=undefined}
|
|
let stop!:()=>void
|
|
const stopped=new Promise<never>((_resolve,reject)=>{stop=()=>{dispose();reject(new BandwidthNodeSourceError())}})
|
|
const timer=setTimeout(stop,Math.max(1,Math.min(scope.deadlineAt-Date.now(),end-performance.now())))
|
|
const dispose=()=>{clearTimeout(timer);scope.signal?.removeEventListener("abort",stop);sessions.delete(stop);close()}
|
|
sessions.add(stop);scope.signal?.addEventListener("abort",stop,{once:true})
|
|
async function files(fence:BandwidthControlDispatchFence):Promise<Captured>{
|
|
live()
|
|
const bytes=await readBandwidthControlFile(config.bootstrapFile,32768,live)
|
|
const verified=await fence.verifyNodeBootstrap(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)));live()
|
|
const bootstrapHash=digest(canonicalBandwidthNodeValue(verified.bootstrap))
|
|
if(pinnedBootstrap!==undefined&&(bootstrapHash!==pinnedBootstrap||verified.source.sourceRecordSha256!==pinned!.source.sourceRecordSha256))fail()
|
|
if(verified.bootstrap.issuerKeySha256!==config.issuerKeySha256)fail()
|
|
let key:Buffer|undefined
|
|
try{
|
|
key=await readBandwidthControlFile(config.issuerKeyFile,32,live)
|
|
keys.add(key);live()
|
|
if(key.length!==32||digest(key)!==config.issuerKeySha256)fail()
|
|
live()
|
|
return {verified,key,bootstrapHash}
|
|
}catch(error){if(key)wipe(key);throw error}
|
|
}
|
|
const dispatch=async(fence:BandwidthControlDispatchFence)=>{
|
|
let before:Captured|undefined,after:Captured|undefined
|
|
try{
|
|
before=await files(fence)
|
|
const sql={query:async(text:string,values?:unknown[])=>{live();const result=await fence.query(text,values);live();return result}}
|
|
const verified=before.verified
|
|
const v2=verified.bootstrap.format==="mmapp-bandwidth-node-bootstrap-v2"
|
|
const expected=root(verified.bootstrap)
|
|
const role={databaseName:verified.source.databaseName,runtimeRole:verified.source.runtimeRole,ownerRole:verified.source.ownerRole}
|
|
const joint=fence as BandwidthControlDispatchFence & Partial<BandwidthControlRegistryDispatchFence>
|
|
if(typeof joint.assertRegistryIdentity==="function"){
|
|
await joint.assertRegistryIdentity(verified);live()
|
|
}else if(v2){
|
|
const {assertBandwidthPeerIdentity}=await import("./bandwidth-peer-identity.js")
|
|
live();await assertBandwidthPeerIdentity(sql,{...role,...expected,registryCatalogSha256:verified.bootstrap.registryCatalogSha256},live)
|
|
}else{
|
|
const {assertBandwidthNodeIdentity}=await import("./bandwidth-node-identity.js")
|
|
live();await assertBandwidthNodeIdentity(sql,{...role,...expected,registryCatalogSha256:verified.bootstrap.registryCatalogSha256},live)
|
|
}
|
|
// Fixed ownership checks use this SAME raw driver fence, never a
|
|
// recursive source query or another lease. Files are re-read AFTER it.
|
|
await ownershipGuard?.(fence);live()
|
|
// Re-read after ALL asynchronous registry metadata. A key/bootstrap
|
|
// changed during those queries cannot produce one last stale HMAC.
|
|
after=await files(fence)
|
|
if(after.bootstrapHash!==before.bootstrapHash||after.verified.source.sourceRecordSha256!==before.verified.source.sourceRecordSha256)fail()
|
|
await dispatchGuard?.();live()
|
|
pinned??=after.verified;pinnedBootstrap??=after.bootstrapHash
|
|
if(captureRequested){clearCapture();captured=after;after=undefined}
|
|
}finally{if(before)wipe(before.key);if(after)wipe(after.key)}
|
|
}
|
|
const fresh=async<T>(work:(value:Captured)=>T)=>{
|
|
captureRequested=true;clearCapture()
|
|
try{
|
|
live();await connection!.query("SELECT 1",undefined,{signal:scope.signal,timeoutMs:Math.max(1,Math.min(5000,scope.deadlineAt-Date.now()))});live()
|
|
const value=captured as Captured|undefined;if(!value)fail()
|
|
captured=undefined
|
|
try{const result=work(value!);live();return result}finally{wipe(value!.key)}
|
|
}finally{captureRequested=false;clearCapture()}
|
|
}
|
|
const owned=async<T>(work:()=>Promise<T>):Promise<T>=>{
|
|
live();if(busy){stop();fail()};busy=true
|
|
try{return await Promise.race([Promise.resolve().then(async()=>{live();return work()}),stopped])}
|
|
catch{dispose();throw new BandwidthNodeSourceError()}
|
|
finally{busy=false}
|
|
}
|
|
try{
|
|
return await Promise.race([Promise.resolve().then(async()=>{
|
|
live();await dispatchGuard?.();live();connection=await core.connect(scope,dispatch)
|
|
if(!active||closed){close();fail()};live();await fresh(()=>undefined)
|
|
const lifetimeSignal=connection.lifetimeSignal
|
|
const facade:ProbeStorageConnection=Object.freeze({
|
|
...(lifetimeSignal?{lifetimeSignal}:{}),
|
|
query:(text:string,values?:unknown[],options?:{signal?:AbortSignal;timeoutMs:number})=>owned(async()=>{
|
|
live();const result=await connection!.query(text,values,options);live();return result
|
|
}),
|
|
release:()=>stop(),
|
|
})
|
|
return Object.freeze({connection:facade,
|
|
binding:()=>owned(()=>fresh(value=>Object.freeze({...root(value.verified.bootstrap),bootstrapSha256:value.bootstrapHash,
|
|
controlGeneration:value.verified.source.controlGeneration,sourceRecordSha256:value.verified.source.sourceRecordSha256}))),
|
|
keyedProof:(purpose:string,value:unknown)=>{
|
|
if(!Object.hasOwn(shapes,purpose))return Promise.reject(new BandwidthNodeSourceError())
|
|
let text:string
|
|
try{text=canonicalBandwidthNodeValue(shapes[purpose as keyof typeof shapes].parse(value));if(Buffer.byteLength(text)>65536)fail()}catch{return Promise.reject(new BandwidthNodeSourceError())}
|
|
return owned(()=>fresh(material=>{
|
|
if(purpose.startsWith("external-")&&material.verified.bootstrap.format!=="mmapp-bandwidth-node-bootstrap-v2")fail()
|
|
if(purpose!=="claim"){
|
|
const record=JSON.parse(text),expected=root(material.verified.bootstrap)
|
|
if(record.installationId!==expected.installationId||record.issuerKeySha256!==expected.issuerKeySha256||record.quiescenceProof!==expected.quiescenceProof)fail()
|
|
}
|
|
return createHmac("sha256",material.key).update("mmapp-bandwidth-node-"+purpose+"-v1:"+text).digest("hex")
|
|
}))
|
|
},
|
|
keyedProofs:(inputs:readonly BandwidthNodeProofInput[])=>{
|
|
let captured:ReturnType<typeof captureProofBatch>
|
|
try{captured=captureProofBatch(inputs)}catch{return Promise.reject(new BandwidthNodeSourceError())}
|
|
return owned(()=>fresh(material=>{
|
|
const expected=root(material.verified.bootstrap)
|
|
// All MACs are pure synchronous operations on ONE freshly checked
|
|
// key. No await, user callback or authority cache between them.
|
|
const values=captured.map(({purpose,text})=>{
|
|
if(purpose.startsWith("external-")&&material.verified.bootstrap.format!=="mmapp-bandwidth-node-bootstrap-v2")fail()
|
|
if(purpose!=="claim"){
|
|
const record=JSON.parse(text)
|
|
if(record.installationId!==expected.installationId||record.issuerKeySha256!==expected.issuerKeySha256||record.quiescenceProof!==expected.quiescenceProof)fail()
|
|
}
|
|
return createHmac("sha256",material.key).update("mmapp-bandwidth-node-"+purpose+"-v1:"+text).digest("hex")
|
|
})
|
|
return Object.freeze(values)
|
|
}))
|
|
},
|
|
close:()=>stop(),
|
|
})
|
|
}),stopped])
|
|
}catch{dispose();throw new BandwidthNodeSourceError()}
|
|
}
|
|
return Object.freeze({open,inspectPublicBootstrap,openPublicRegistryMetadata,
|
|
/** Operator-window composition only: capture an additional fixed raw
|
|
* ownership observer inside every existing before/after source fence. */
|
|
openWithOwnershipFence:(input:BandwidthScope,dispatchGuard:()=>Promise<void>,ownershipGuard:(fence:BandwidthControlDispatchFence)=>Promise<void>)=>{
|
|
if(typeof ownershipGuard!=="function")return Promise.reject(new BandwidthNodeSourceError())
|
|
return open(input,dispatchGuard,ownershipGuard)
|
|
},
|
|
assertResolvedOnFence:(fence:BandwidthControlDispatchFence,expected:BandwidthResolvedNodeFence,scope:BandwidthScope)=>assertResolvedBandwidthNodesOnFence(config,sessions,()=>closed,fence,expected,scope),
|
|
assertResolvedPeersOnFence:(fence:BandwidthControlDispatchFence,expected:BandwidthResolvedPeerFence,scope:BandwidthScope)=>assertResolvedBandwidthPeersOnFence(config,sessions,()=>closed,fence,expected,scope),
|
|
close(){closed=true;for(const stop of [...publicOperations])stop();for(const stop of [...sessions])stop()}})
|
|
}
|
|
|
|
let production:ReturnType<typeof createConfiguredBandwidthNodeSource>|undefined
|
|
/** No fallback key/path, no startup I/O and no automatic marker. Missing
|
|
* operator configuration affects the requesting operation, not tool discovery. */
|
|
export function getProductionBandwidthNodeSource(){
|
|
if(production)return production
|
|
const required=(name:string)=>{const value=process.env[name];if(!value?.trim())throw new BandwidthNodeSourceError();return value}
|
|
const config={issuerKeyFile:required("MMAPP_BANDWIDTH_NODE_ISSUER_KEY_FILE"),issuerKeySha256:required("MMAPP_BANDWIDTH_NODE_ISSUER_KEY_SHA256"),bootstrapFile:required("MMAPP_BANDWIDTH_NODE_BOOTSTRAP_FILE")}
|
|
production=createConfiguredBandwidthNodeSource(getProductionBandwidthControlSource(),config)
|
|
return production
|
|
}
|
|
export function closeProductionBandwidthNodeSource(){production?.close()}
|