Files
MikrotikManager/backend/src/services/bandwidth-peer-resolver.ts
T

133 lines
12 KiB
TypeScript

/** Read-only peer resolution on the caller-owned verified node session. One
* SELECT captures alias/node/event/authority in the same MVCC snapshot. It
* never enrolls, retires, mutates occupancy or acquires a second connection. */
import { isDeepStrictEqual } from "node:util"
import { performance } from "node:perf_hooks"
import { z } from "zod"
import { parseBandwidthPeerRef, type BandwidthPeerRef } from "./bandwidth-peer-reference.js"
import type { BandwidthPeerObservationEvidence } from "./bandwidth-peer-observation.js"
import type { BandwidthPeerRegistryReceipt } from "./bandwidth-peer-fence.js"
import type { BandwidthScope } from "./bandwidth-admission.js"
import type { ProbeStorageConnection } from "./server-probe-journal-maintenance.js"
const hash = z.string().regex(/^[a-f0-9]{64}$/), uuid = z.string().uuid()
const authoritySchema = z.object({ installationId: uuid, issuerKeySha256: hash, quiescenceProof: hash, authorityProof: hash,
authorityGeneration: z.string().min(1).max(200), expiresAt: z.number().int().positive().safe() }).strict()
type Authority = z.infer<typeof authoritySchema>
const claim = z.object({ kind: z.enum(["system-id", "software-id"]), value: z.string().min(1).refine(value => Buffer.byteLength(value) <= 256 && value.trim() === value && !/[\u0000-\u001f\u007f]/.test(value)) }).strict()
const evidenceSchema = z.object({ version: z.literal(2), peerRef: z.unknown().transform(parseBandwidthPeerRef), sourceProof: hash, authorityGeneration: z.string().min(1).max(200),
routingEndpointEpoch: uuid, observedAt: z.number().int().nonnegative().safe(), expiresAt: z.number().int().positive().safe(),
claims: z.array(claim).min(1).max(2).refine(value => value.length === 1 || value[0].kind === "system-id" && value[1].kind === "software-id"),
physicalUniquenessVerified: z.literal(false), cloneResistanceVerified: z.literal(false) }).strict()
const eventSchema = z.object({ event_id: uuid, incarnation: uuid, node_id: uuid, kind: z.literal("enroll"), old_status: z.null(), new_status: z.literal("active"), authority_proof: hash, event_mac: hash }).strict()
const rowSchema = z.object({ subject: z.string().min(1).max(64), incarnation: uuid, node_id: uuid, status: z.literal("active"), record_mac: hash, claim_proof: hash,
enrollment_mac: hash, installation_id: uuid, issuer_key_sha256: hash, quiescence_proof: hash, authority_status: z.literal("active"), events: z.array(eventSchema).length(1) }).strict()
export interface BandwidthPeerResolverDependencies {
inspect(observation: unknown, scope: BandwidthScope): Promise<BandwidthPeerObservationEvidence>
authorize(peer: BandwidthPeerRef, scope: BandwidthScope, evidence: Readonly<BandwidthPeerObservationEvidence>): Promise<Authority>
connect(scope: BandwidthScope): Promise<ProbeStorageConnection>
keyedProof(purpose: string, value: unknown, scope: BandwidthScope): Promise<string>
/** Optional genuine node-session atomic 1..4 issuer, captured at construction.
* All MACs use one freshly verified key with no awaits between materials. */
keyedProofs?(inputs: readonly Readonly<{ purpose: string; value: unknown }>[], scope: BandwidthScope): Promise<readonly string[]>
}
export class BandwidthPeerResolverError extends Error {
readonly code = "BANDWIDTH_PEER_RESOLUTION_REFUSED"
readonly automaticReplay = false
constructor() { super("Текущая постоянная привязка bandwidth peer не подтверждена") }
}
function fail(): never { throw new BandwidthPeerResolverError() }
const select = (external: boolean) => external ? EXTERNAL : MANAGED
const query = (external: boolean) => `WITH alias AS MATERIALIZED (
SELECT ${external ? "enrollment_id::pg_catalog.text" : "server_id::pg_catalog.text"} AS subject,incarnation,node_id,status,record_mac
FROM mmapp_control.${external ? "bandwidth_external_node_aliases" : "bandwidth_node_aliases"}
WHERE ${external ? "enrollment_id=$1::pg_catalog.uuid" : "server_id=$1::pg_catalog.int8"} LIMIT 2
), events AS MATERIALIZED (
SELECT event_id::pg_catalog.text,incarnation::pg_catalog.text,node_id::pg_catalog.text,kind,old_status,new_status,authority_proof,event_mac
FROM mmapp_control.${external ? "bandwidth_external_node_events" : "bandwidth_node_events"}
WHERE ${external ? "enrollment_id=$1::pg_catalog.uuid" : "server_id=$1::pg_catalog.int8"} ORDER BY kind LIMIT 3
)
SELECT a.subject,a.incarnation::pg_catalog.text,a.node_id::pg_catalog.text,a.status,a.record_mac,n.claim_proof,n.enrollment_mac,
r.installation_id::pg_catalog.text,r.issuer_key_sha256,r.quiescence_proof,r.status AS authority_status,
COALESCE((SELECT pg_catalog.jsonb_agg(pg_catalog.to_jsonb(e)) FROM events e),'[]'::pg_catalog.jsonb) AS events
FROM alias a JOIN mmapp_control.bandwidth_nodes n ON n.node_id=a.node_id
JOIN mmapp_control.bandwidth_node_authority r ON r.id=1 LIMIT 2`
// The only two SQL statements are constructed at module load from literals.
// Request values select a validated reference variant, never SQL identifiers.
const MANAGED = query(false), EXTERNAL = query(true)
export function createBandwidthPeerResolver(dependencies: BandwidthPeerResolverDependencies) {
const inspect = dependencies.inspect.bind(dependencies), authorize = dependencies.authorize.bind(dependencies), connect = dependencies.connect.bind(dependencies), keyedProof = dependencies.keyedProof.bind(dependencies)
const keyedProofs = dependencies.keyedProofs?.bind(dependencies)
return Object.freeze({ async resolve(observation: unknown, rawScope: BandwidthScope): Promise<Readonly<BandwidthPeerRegistryReceipt>> {
const enteredWall = Date.now(), enteredMono = performance.now()
if (!rawScope || typeof rawScope !== "object" || Object.getPrototypeOf(rawScope) !== Object.prototype || Reflect.ownKeys(rawScope).length !== Object.keys(rawScope).length
|| Object.values(Object.getOwnPropertyDescriptors(rawScope)).some(field => !("value" in field) || !field.enumerable)
|| Object.keys(rawScope).some(key => !["deadlineAt", "signal"].includes(key)) || !Number.isSafeInteger(rawScope.deadlineAt)
|| rawScope.signal !== undefined && !(rawScope.signal instanceof AbortSignal)) fail()
let expiry = Math.min(rawScope.deadlineAt, enteredWall + 10000), active = true, connection: ProbeStorageConnection | undefined, released = false
const signal = rawScope.signal, controller = new AbortController()
const scope = () => Object.freeze({ deadlineAt: expiry, signal: controller.signal })
const live = () => { if (!active || signal?.aborted || controller.signal.aborted || Date.now() >= expiry || performance.now() >= enteredMono + Math.max(0, expiry - enteredWall)) fail() }
const release = () => { if (connection && !released) { released = true; try { connection.release(true) } catch { /* Never reuse a potentially stale lease. */ } } }
let reject!: (error: Error) => void
const stopped = new Promise<never>((_resolve, rejectPromise) => { reject = rejectPromise })
const stop = () => { active = false; controller.abort(); release(); reject(new BandwidthPeerResolverError()) }
let timer: ReturnType<typeof setTimeout> | undefined
const schedule = () => { clearTimeout(timer); timer = setTimeout(stop, Math.max(1, Math.min(expiry - Date.now(), enteredMono + Math.max(0, expiry - enteredWall) - performance.now()))) }
schedule(); signal?.addEventListener("abort", stop, { once: true })
const work = async () => {
try {
live(); const evidence = evidenceSchema.parse(await inspect(observation, scope())); live()
evidence.claims.forEach(Object.freeze); Object.freeze(evidence.claims); Object.freeze(evidence)
expiry = Math.min(expiry, evidence.expiresAt); schedule(); live()
const authority = Object.freeze(authoritySchema.parse(await authorize(evidence.peerRef, scope(), evidence))); live()
expiry = Math.min(expiry, authority.expiresAt); schedule(); live()
const guard = async () => {
live(); if (!isDeepStrictEqual(evidenceSchema.parse(await inspect(observation, scope())), evidence)) fail()
live(); if (!isDeepStrictEqual(authoritySchema.parse(await authorize(evidence.peerRef, scope(), evidence)), authority)) fail()
live()
}
const proof = async (purpose: string, value: unknown) => { await guard(); const mac = await keyedProof(purpose, value, scope()); await guard(); if (!hash.safeParse(mac).success) fail(); return mac }
await guard(); const opened = await connect(scope()); connection = opened
if (!active) { release(); fail() }; live()
const peerRef = evidence.peerRef, external = peerRef.kind === "external", subject = peerRef.kind === "external" ? peerRef.enrollmentId : peerRef.serverId
await guard(); const result: { rows: Record<string, unknown>[]; command?: unknown } = await opened.query(select(external), [subject], { signal: controller.signal, timeoutMs: Math.max(1, Math.min(5000, expiry - Date.now())) }); await guard()
if (result.command !== "SELECT" || result.rows.length !== 1) fail()
const row = rowSchema.parse(result.rows[0]), event = row.events[0]
if (row.subject !== String(subject) || row.installation_id !== authority.installationId || row.issuer_key_sha256 !== authority.issuerKeySha256 || row.quiescence_proof !== authority.quiescenceProof
|| event.incarnation !== row.incarnation || event.node_id !== row.node_id) fail()
const root = { installationId: authority.installationId, issuerKeySha256: authority.issuerKeySha256, quiescenceProof: authority.quiescenceProof }
if (keyedProofs) {
// Every material is parsed/captured before the first issuer await.
// The dependent node material uses the exact persisted claim proof,
// preserving the original domain/root/linkage validation unchanged.
const inputs = Object.freeze([
Object.freeze({ purpose: "claim", value: evidence.claims }),
Object.freeze({ purpose: "node", value: Object.freeze({ ...root, nodeId: row.node_id, claimProof: row.claim_proof }) }),
Object.freeze({ purpose: external ? "external-alias" : "alias", value: Object.freeze({ ...root, ...(external ? { enrollmentId: String(subject) } : { serverId: Number(subject) }), incarnation: row.incarnation, nodeId: row.node_id, status: "active" }) }),
Object.freeze({ purpose: external ? "external-event" : "event", value: Object.freeze({ ...root, eventId: event.event_id, ...(external ? { enrollmentId: String(subject) } : { serverId: Number(subject) }), incarnation: row.incarnation, nodeId: row.node_id, kind: "enroll", oldStatus: null, newStatus: "active", authorityProof: event.authority_proof }) }),
])
await guard(); const raw = await keyedProofs(inputs, scope()); await guard()
if (!Array.isArray(raw) || !Object.isFrozen(raw) || raw.length !== 4 || Reflect.ownKeys(raw).length !== 5) fail()
const descriptors = Object.getOwnPropertyDescriptors(raw)
const values = Object.freeze([0, 1, 2, 3].map(index => {
const field = descriptors[String(index)]
if (!field || !("value" in field) || !field.enumerable || !hash.safeParse(field.value).success) fail()
return field.value as string
}))
if (row.claim_proof !== values[0] || row.enrollment_mac !== values[1] || row.record_mac !== values[2] || event.event_mac !== values[3]) fail()
} else if (row.claim_proof !== await proof("claim", evidence.claims)
|| row.enrollment_mac !== await proof("node", { ...root, nodeId: row.node_id, claimProof: row.claim_proof })
|| row.record_mac !== await proof(external ? "external-alias" : "alias", { ...root, ...(external ? { enrollmentId: String(subject) } : { serverId: Number(subject) }), incarnation: row.incarnation, nodeId: row.node_id, status: "active" })
|| event.event_mac !== await proof(external ? "external-event" : "event", { ...root, eventId: event.event_id, ...(external ? { enrollmentId: String(subject) } : { serverId: Number(subject) }), incarnation: row.incarnation, nodeId: row.node_id, kind: "enroll", oldStatus: null, newStatus: "active", authorityProof: event.authority_proof })) fail()
await guard()
return Object.freeze({ peerRef: parseBandwidthPeerRef(evidence.peerRef), canonicalNodeId: row.node_id, incarnation: row.incarnation, status: "active" as const, outcome: "existing" as const })
} catch { throw new BandwidthPeerResolverError() }
finally { release() }
}
try { return await Promise.race([work(), stopped]) }
finally { active = false; clearTimeout(timer); signal?.removeEventListener("abort", stop); controller.abort() }
} })
}