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

223 lines
18 KiB
TypeScript

/** Read-only operator enrollment prerequisite. No runtime default, SQL, issuer
* private key, native execution, alias registration or occupancy reset. The
* signed quiescence statement authenticates its operator, not a writer barrier. */
import { createHash, createPublicKey, verify } from "node:crypto"
import { isAbsolute, resolve } from "node:path"
import { performance } from "node:perf_hooks"
import { isDeepStrictEqual, types } from "node:util"
import { z } from "zod"
import { canonicalBandwidthNodeValue } from "./bandwidth-node-bootstrap.js"
import { readBandwidthControlFile } from "./bandwidth-control-source.js"
import type { BandwidthNodeObservationScope } from "./bandwidth-node-observation.js"
import { createBandwidthPeerObservationReader, type BandwidthPeerObservation, type BandwidthPeerObservationEvidence,
type BandwidthPeerTrustedSource } from "./bandwidth-peer-observation.js"
import { parseBandwidthPeerRef, bandwidthPeerRefKey, type BandwidthPeerRef } from "./bandwidth-peer-reference.js"
const hash = z.string().regex(/^[a-f0-9]{64}$/), uuid = z.string().uuid()
const claim = z.object({ kind: z.enum(["system-id", "software-id"]), value: z.string().min(1).max(256)
.refine(value => Buffer.byteLength(value) <= 256 && value.trim() === value && !/[\u0000-\u001f\u007f]/.test(value)) }).strict()
/** An operator signs canonical UTF-8 JSON, never model-generated readiness.
* Replacing/removing the one current grant file revokes existing capabilities. */
export const bandwidthOperatorEnrollmentGrantSchema = z.object({
format: z.literal("mmapp-bandwidth-operator-enrollment-v1"), grantId: uuid,
operatorId: z.string().trim().min(1).max(200), installationId: uuid, issuerKeySha256: hash,
quiescenceProof: hash, executorInventorySha256: hash, executorsStoppedAt: z.number().int().nonnegative(),
issuedAt: z.number().int().nonnegative(), expiresAt: z.number().int().positive(),
peerRef: z.union([z.object({kind:z.literal("server"),serverId:z.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),
z.object({kind:z.literal("external"),enrollmentId:uuid.regex(/^[a-f0-9-]+$/)}).strict()]), sourceProof: hash,
authorityGeneration: z.string().min(1).max(200), routingEndpointEpoch: uuid,
claims: z.array(claim).min(1).max(2).refine(value => value.length === 1 || value[0].kind === "system-id" && value[1].kind === "software-id"),
}).strict().refine(value => value.executorsStoppedAt <= value.issuedAt && value.issuedAt < value.expiresAt && value.expiresAt - value.issuedAt <= 600000)
type Grant = z.infer<typeof bandwidthOperatorEnrollmentGrantSchema>
/** Independent executor-fence authority, installed only by trusted operator
* composition. Must authenticate the live original fence and inventory on
* EVERY call. Signed grant fields, DB alias existence or network-write scope
* alone must never satisfy this interface. Absence/errors refuse admission. */
export interface BandwidthOperatorQuiescenceVerifier {
verify(grant: Readonly<Grant>, scope: Readonly<BandwidthNodeObservationScope>): Promise<void>
}
const envelope = 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 configuration = z.object({ trustKeyFile: z.string(), trustKeySha256: hash, grantFile: z.string(),
installationId: uuid, issuerKeySha256: hash, quiescenceProof: hash }).strict()
export type BandwidthOperatorEnrollmentConfig = z.infer<typeof configuration>
declare const prerequisiteBrand: unique symbol
export interface BandwidthOperatorEnrollmentPrerequisite {
readonly kind: "operator-bandwidth-enrollment-prerequisite"; readonly [prerequisiteBrand]: true
}
/** PUBLIC metadata snapshot only. Its nested projection cannot substitute for
* the strong coordinator inspection, current Q, writer barrier or dispatch. */
export interface BandwidthOperatorEnrollmentPublicMetadata {
readonly format: "mmapp-bandwidth-operator-enrollment-metadata-v1"
readonly metadata: Readonly<{
observation: BandwidthPeerObservation; evidence: Readonly<BandwidthPeerObservationEvidence>; operatorId: string; grantId: string; executorInventorySha256: string
authority: Readonly<{ installationId: string; issuerKeySha256: string; quiescenceProof: string; authorityProof: string; authorityGeneration: string; expiresAt: number }>
}>
}
export class BandwidthOperatorEnrollmentError extends Error {
readonly code = "BANDWIDTH_OPERATOR_ENROLLMENT_REFUSED"
constructor() { super("Исходный операторский enrollment и наблюдение лицензии не подтверждены") }
}
const refuse = (): never => { throw new BandwidthOperatorEnrollmentError() }
const sha = (value: Buffer | string) => createHash("sha256").update(value).digest("hex")
const coordinators = new WeakSet<object>()
/** Server composition must receive this module's actual fixed reader, never a
* structural JSON/facade that can manufacture original operator authority. */
export function assertBandwidthOperatorEnrollmentCoordinator(value: unknown): asserts value is ReturnType<typeof createBandwidthOperatorEnrollmentPrerequisite> {
if (!value || typeof value !== "object" || !coordinators.has(value)) return refuse()
}
function captureScope(raw: BandwidthNodeObservationScope): Readonly<BandwidthNodeObservationScope> {
if (!raw || typeof raw !== "object" || 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(field => !("value" in field) || !field.enumerable)
|| !Number.isSafeInteger(raw.deadlineAt) || raw.signal !== undefined && !(raw.signal instanceof AbortSignal)) return refuse()
return Object.freeze({ deadlineAt: raw.deadlineAt, signal: raw.signal })
}
/** Construction captures trusted source methods and immutable operator paths.
* No request can choose an endpoint, parser, signing key, SQL or transport. */
export function createBandwidthOperatorEnrollmentPrerequisite(raw: BandwidthOperatorEnrollmentConfig, source: BandwidthPeerTrustedSource,
quiescence: BandwidthOperatorQuiescenceVerifier) {
const config = Object.freeze(configuration.parse(raw))
if ([config.trustKeyFile, config.grantFile].some(path => !isAbsolute(path) || resolve(path) !== path) || config.trustKeyFile === config.grantFile) refuse()
if (!quiescence || typeof quiescence.verify !== "function") refuse()
const verifyQuiescence = quiescence.verify.bind(quiescence), reader = createBandwidthPeerObservationReader(source)
type Origin = { grant: Grant; observation: BandwidthPeerObservation; evidence: BandwidthPeerObservationEvidence; signal?: AbortSignal; end: number }
const origins = new WeakMap<object, Origin>(), windows = new Set<AbortController>(), budgets = new Set<() => void>()
let closed = false
const operation = async <T>(rawScope: BandwidthNodeObservationScope, origin: Origin | undefined,
run: (scope: Readonly<BandwidthNodeObservationScope>, live: () => void) => Promise<T>): Promise<T> => {
const input = captureScope(rawScope)
const deadlineAt = Math.min(input.deadlineAt, Date.now() + 5000, origin?.grant.expiresAt ?? Infinity, origin?.evidence.expiresAt ?? Infinity)
const end = Math.min(performance.now() + Math.max(0, deadlineAt - Date.now()), origin?.end ?? Infinity)
const controller = new AbortController(), abort = () => controller.abort()
const live = () => { if (closed || controller.signal.aborted || input.signal?.aborted || origin?.signal?.aborted || Date.now() >= deadlineAt || performance.now() >= end) refuse() }
live(); windows.add(controller)
input.signal?.addEventListener("abort", abort, { once: true }); origin?.signal?.addEventListener("abort", abort, { once: true })
const timer = setTimeout(abort, Math.max(1, end - performance.now()))
let stop!: () => void
const stopped = new Promise<never>((_resolve, reject) => { stop = () => reject(new BandwidthOperatorEnrollmentError()); controller.signal.addEventListener("abort", stop, { once: true }) })
try { const result = await Promise.race([Promise.resolve().then(() => { live(); return run(Object.freeze({ deadlineAt, signal: controller.signal }), live) }), stopped]); live(); return result }
catch { throw new BandwidthOperatorEnrollmentError() }
finally { clearTimeout(timer); input.signal?.removeEventListener("abort", abort); origin?.signal?.removeEventListener("abort", abort); controller.signal.removeEventListener("abort", stop); windows.delete(controller); controller.abort() }
}
async function current(peerRef: BandwidthPeerRef, live: () => void): Promise<Grant> {
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 = envelope.parse(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(grantBytes)))
const payload = Buffer.from(signed.payload, "base64url"), signature = Buffer.from(signed.signature, "base64url")
if (payload.toString("base64url") !== signed.payload || signature.toString("base64url") !== signed.signature || !verify(null, payload, key, signature)) refuse()
const value = bandwidthOperatorEnrollmentGrantSchema.parse(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(payload)))
if (canonicalBandwidthNodeValue(value) !== payload.toString("utf8") || bandwidthPeerRefKey(value.peerRef) !== bandwidthPeerRefKey(peerRef) || value.installationId !== config.installationId
|| value.issuerKeySha256 !== config.issuerKeySha256 || value.quiescenceProof !== config.quiescenceProof || value.issuedAt > Date.now() || value.expiresAt <= Date.now()) refuse()
Object.freeze(value.peerRef); value.claims.forEach(Object.freeze); Object.freeze(value.claims)
live(); return Object.freeze(value)
}
const matches = (grant: Grant, evidence: BandwidthPeerObservationEvidence) => {
if (bandwidthPeerRefKey(grant.peerRef) !== bandwidthPeerRefKey(evidence.peerRef) || grant.sourceProof !== evidence.sourceProof || grant.authorityGeneration !== evidence.authorityGeneration
|| grant.routingEndpointEpoch !== evidence.routingEndpointEpoch || !isDeepStrictEqual(grant.claims, evidence.claims)) refuse()
}
const coordinator = Object.freeze({
async acquire(rawPeer: BandwidthPeerRef, rawScope: BandwidthNodeObservationScope): Promise<BandwidthOperatorEnrollmentPrerequisite> {
const peerRef = parseBandwidthPeerRef(rawPeer), input = captureScope(rawScope)
// Anchor BOTH the scope and the not-yet-read signed grant to entry time,
// before any file IO. A backward wall jump must not renew either bound.
const enteredWall = Date.now(), enteredMono = performance.now()
let budgetEnd = enteredMono + Math.max(0, Math.min(5000, input.deadlineAt - enteredWall)), published = false
const budget = new AbortController()
let timer: ReturnType<typeof setTimeout>
const cancelBudget = () => { clearTimeout(timer); budget.abort(); budgets.delete(cancelBudget) }
const scheduleBudget = () => { clearTimeout(timer); timer = setTimeout(cancelBudget, Math.max(1, budgetEnd - performance.now())); timer.unref() }
const signal = input.signal ? AbortSignal.any([input.signal, budget.signal]) : budget.signal
budgets.add(cancelBudget); scheduleBudget()
try { return await operation({ ...input, signal }, undefined, async (scope, live) => {
const grant = await current(peerRef, live)
budgetEnd = Math.min(budgetEnd, enteredMono + Math.max(0, grant.expiresAt - enteredWall)); scheduleBudget()
const grantLive = () => { live(); if (signal.aborted || performance.now() >= budgetEnd || Date.now() >= grant.expiresAt) refuse() }
grantLive()
await verifyQuiescence(grant, scope); grantLive()
// Genuine native GET uses the fixed source, never signed response JSON.
// Preserve the ORIGINAL cancellation lifetime. The per-operation
// controller is disposed after acquire and must not revoke its origin.
const observation = await reader.observe(peerRef, { signal, deadlineAt: Math.min(scope.deadlineAt, grant.expiresAt) }); grantLive()
const evidence = await reader.inspect(observation, scope); grantLive(); matches(grant, evidence)
await verifyQuiescence(grant, scope); grantLive()
if (!isDeepStrictEqual(grant, await current(peerRef, grantLive))) refuse()
grantLive()
const capability = Object.freeze({ kind: "operator-bandwidth-enrollment-prerequisite" as const }) as BandwidthOperatorEnrollmentPrerequisite
origins.set(capability, { grant, observation, evidence, signal, end: budgetEnd })
published = true
return capability
}) } finally { if (!published) cancelBudget() }
},
async inspect(capability: unknown, input: BandwidthNodeObservationScope) {
const origin = capability && typeof capability === "object" ? origins.get(capability) : undefined
if (!origin) return refuse()
return operation(input, origin, async (scope, live) => {
// Authenticate the CURRENT original operator/fence before resolving
// management secrets, including inspection of an existing observation.
const before = await current(origin.grant.peerRef, live)
if (!isDeepStrictEqual(before, origin.grant)) refuse()
await verifyQuiescence(before, scope); live()
const evidence = await reader.inspect(origin.observation, scope); live()
if (!isDeepStrictEqual(evidence, origin.evidence)) refuse()
const grant = await current(evidence.peerRef, live)
if (!isDeepStrictEqual(grant, origin.grant)) refuse(); matches(grant, evidence)
await verifyQuiescence(grant, scope); live()
if (!isDeepStrictEqual(grant, await current(evidence.peerRef, live))) refuse()
return Object.freeze({ observation: origin.observation, evidence, operatorId: grant.operatorId, grantId: grant.grantId,
executorInventorySha256: grant.executorInventorySha256,
authority: Object.freeze({ installationId: grant.installationId, issuerKeySha256: grant.issuerKeySha256, quiescenceProof: grant.quiescenceProof,
authorityProof: sha(canonicalBandwidthNodeValue(grant)), authorityGeneration: grant.grantId, expiresAt: Math.min(grant.expiresAt, evidence.expiresAt) }),
writerBarrierVerified: false as const, endpointMappingVerified: false as const })
})
},
async inspectMetadata(capability: unknown, rawScope: BandwidthNodeObservationScope): Promise<Readonly<BandwidthOperatorEnrollmentPublicMetadata>> {
const enteredWall = Date.now(), enteredMono = performance.now()
const origin = capability && typeof capability === "object" ? origins.get(capability) : undefined
if (!origin || closed || !rawScope || types.isProxy(rawScope) || Object.getPrototypeOf(rawScope) !== Object.prototype) return refuse()
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)) return refuse()
const deadlineAt: unknown = fields.deadlineAt?.value, signal: unknown = fields.signal?.value
if (typeof deadlineAt !== "number" || !Number.isSafeInteger(deadlineAt) || signal !== undefined && (types.isProxy(signal) || !(signal instanceof AbortSignal))) return refuse()
const originalSignal = signal as AbortSignal | undefined, aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted")!.get!
const isAborted = () => originalSignal ? Reflect.apply(aborted, originalSignal, []) : false
try { if (isAborted()) return refuse() } catch { return refuse() }
const controller = new AbortController(), abort = () => controller.abort()
if (originalSignal) Reflect.apply(EventTarget.prototype.addEventListener, originalSignal, ["abort", abort, { once: true }])
const end = Math.min(origin.end, enteredMono + Math.max(0, Math.min(5000, deadlineAt - enteredWall)))
try {
return await operation({ deadlineAt, signal: controller.signal }, origin, async (scope, live) => {
const currentLive = () => { live(); const now = Date.now(); if (isAborted() || now < enteredWall || performance.now() >= end) refuse() }
currentLive()
const before = await current(origin.grant.peerRef, currentLive)
if (!isDeepStrictEqual(before, origin.grant)) refuse()
// This new path never invokes Q, reads credentials, or repeats native
// observation. Missing fixed metadata checker MUST refuse in reader.
const inspected = await reader.inspectMetadata(origin.observation, scope); currentLive()
if (inspected.format !== "mmapp-bandwidth-peer-public-metadata-v1" || !isDeepStrictEqual(inspected.evidence, origin.evidence)) refuse()
const grant = await current(origin.grant.peerRef, currentLive)
if (!isDeepStrictEqual(grant, origin.grant)) refuse(); matches(grant, inspected.evidence); currentLive()
const authority = Object.freeze({ installationId: grant.installationId, issuerKeySha256: grant.issuerKeySha256, quiescenceProof: grant.quiescenceProof,
authorityProof: sha(canonicalBandwidthNodeValue(grant)), authorityGeneration: grant.grantId, expiresAt: Math.min(grant.expiresAt, inspected.evidence.expiresAt) })
return Object.freeze({ format: "mmapp-bandwidth-operator-enrollment-metadata-v1" as const,
metadata: Object.freeze({ observation: origin.observation, evidence: inspected.evidence, operatorId: grant.operatorId, grantId: grant.grantId,
executorInventorySha256: grant.executorInventorySha256, authority }) })
})
} finally {
if (originalSignal) Reflect.apply(EventTarget.prototype.removeEventListener, originalSignal, ["abort", abort])
controller.abort()
}
},
close() { closed = true; reader.close(); for (const controller of windows) controller.abort(); for (const cancel of budgets) cancel() },
})
coordinators.add(coordinator)
return coordinator
}