Files
MikrotikManager/backend/src/modules/mcp/routing-network-native-session.ts
T

451 lines
37 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { isIP } from "node:net"
import { z } from "zod"
import type { QueryConfig } from "pg"
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
import { pool } from "../../db/index.js"
import { hasPermission } from "../../lib/permissions.js"
import { canonicalVrfMembers } from "../../services/vrf-members.js"
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
import { accessGeneration, decryptSecret, fingerprint, McpError, redact } from "./security.js"
import { effectiveMcpConnection } from "./store.js"
import { findMcpOperation } from "./registry.js"
import { assertScopedCommunityRequest } from "./routing-community-scoped-request.js"
import { assertPersistentScopedProfileAuthority, routingProfileAuthorityBindingSchema } from "./routing-profile-authority.js"
import { createRoutingSourceContext, readRoutingEndpoints } from "./routing-observation-source.js"
import { routeContextClients } from "./routing-community-context-native.js"
import { resolveRoutingNetworkDestinationPins } from "./routing-network-native-destination.js"
import { ROUTING_NATIVE_LOG_BUFFER, ROUTING_NATIVE_LOG_PATH } from "./routing-network-native-parser.js"
import { readMeasurementAddress } from "./routing-measurement-address.js"
import { readRouteCommunityContextWithSharedNativeSession, type OwnedRouteCommunityTarget } from "./routing-community-context.js"
import type { ActionContext, ChangeEvidence } from "./action-types.js"
import type { RoutingNetworkForwardRoundConfigurationContext } from "./routing-network-configuration-bridge.js"
const sid = z.number().int().positive().safe()
const address = z.string().min(1).max(45).refine(value => isIP(value) !== 0)
const nativeName = z.string().min(1).max(128).regex(/^[^\u0000-\u001f\u007f]+$/)
const manifestSchema = z.object({ servers: z.array(sid).min(1).max(40), probes: z.array(z.object({
key: z.string().min(1).max(128), serverId: sid, destination: address, source: address, interface: nativeName, probeVrf: nativeName,
}).strict()).max(40).default([]) }).strict()
export type RoutingNetworkNativeManifest = z.input<typeof manifestSchema>
export type RoutingNetworkNativeStage = "before" | "after-forward" | "after-inverse"
type Row = Record<string, unknown>
export type RoutingNetworkNativeServerEnvelope = Readonly<{ serverId: number; routerOsVersion: string;
routes: { resource: "/routing/route"; payload: Row[]; sessionsPayload: Row[]; connectionsPayload: Row[] };
bgp: { resource: "/routing/bgp/session"; payload: Row[]; connectionsPayload: Row[] };
bfd: { resource: "/routing/bfd/session"; payload: Row[] };
logs: { resource: "/log"; buffer: typeof ROUTING_NATIVE_LOG_BUFFER; payload: Row[]; coverage: "unknown" } }>
export type RoutingNetworkNativeProbeEnvelope = Readonly<{ key: string; serverId: number; routerOsVersion: string; pingPayload: Row[]; tracePayload?: Row[];
expectedHopAddresses: { serverId: number; interface: string; address: string }[];
request: { destination: string; source: string; interface: string; probeVrf: string; count: 3; maxHops: 16 } }>
const seenSources = new Set<string>()
const snapshotOwners = new WeakMap<object, { owner: object; configuration?: string; round?: number; startedAt?: number; finishedAt: number }>()
/** Only original snapshots from one native session can bind effect diagnostics. */
export function sameConfigurationBoundForwardRounds(baseline: object, rounds: readonly object[]): boolean {
const initial = snapshotOwners.get(baseline)
if (!initial || initial.configuration !== undefined || rounds.length !== 2) return false
const first = snapshotOwners.get(rounds[0]), second = snapshotOwners.get(rounds[1])
return first?.owner === initial.owner && second?.owner === initial.owner &&
first.round === 1 && second.round === 2 &&
first.startedAt! >= initial.finishedAt && second.startedAt! >= first.finishedAt &&
first.configuration !== undefined && first.configuration === second.configuration
}
declare const sharedContextBrand: unique symbol
export type RoutingNetworkSharedContext = Readonly<{ [sharedContextBrand]: true }>
declare const sharedReadBrand: unique symbol
export type RoutingNetworkSharedContextRead = Readonly<{ [sharedReadBrand]: true }>
type SharedBinding = Readonly<{ sourceOperationId: string; profile: z.infer<typeof routeAiProfileSchema>; principal: ActionContext["principal"];
deadline: number; contextSources: Array<{ serverId: number; proof: string }>; candidateId: string; signal: AbortSignal }>
type SharedContextResult = { scopedTopologyAvailable: boolean; before: { scopedExecutionAvailable: boolean; scopedExecutionReason: string | null; dependencyProof: string; targetRuleProof: string | null;
currentCandidateId: string | null; sourceProofs: Array<{ serverId: number; proof: string }> }; fence(): Promise<void>;
ownedTarget: Pick<OwnedRouteCommunityTarget, "nativeId" | "rawRow" | "matchesRuleProof"> | undefined }
type SharedOwner = { binding: SharedBinding; active(): void; fence(): Promise<void>; close(): void;
read(serverId: number, path: string, body?: Record<string, string>): Promise<unknown>; run(): Promise<SharedContextResult> }
const sharedContexts = new WeakMap<RoutingNetworkSharedContext, SharedOwner>()
const sharedReads = new WeakMap<RoutingNetworkSharedContextRead, SharedOwner>()
const inverseReads = new WeakMap<RoutingNetworkSharedContextRead, string>()
function sharedOwner(context: RoutingNetworkSharedContext): SharedOwner {
const owner = sharedContexts.get(context)
if (!owner) throw fail("STATE_CONFLICT", "Unknown native shared context")
owner.active()
return owner
}
/** Metadata alone cannot create or reconstruct a shared transport owner. */
export function inspectRoutingNetworkSharedContext(context: RoutingNetworkSharedContext): SharedBinding { return sharedOwner(context).binding }
function readOwner(context: RoutingNetworkSharedContextRead): SharedOwner {
const owner = sharedReads.get(context)
if (!owner) throw fail("STATE_CONFLICT", "Unknown or completed shared context acquisition")
owner.active(); return owner
}
/** Capability membership and exact owner identity, not a metadata comparison. */
export function assertRoutingNetworkSharedContextReadOwner(context: RoutingNetworkSharedContext, acquisition: RoutingNetworkSharedContextRead): void {
if (readOwner(acquisition) !== sharedOwner(context)) throw fail("STATE_CONFLICT", "Configuration acquisition belongs to another native owner")
}
export function inspectRoutingNetworkSharedContextRead(context: RoutingNetworkSharedContextRead): SharedBinding {
const binding = readOwner(context).binding, candidateId = inverseReads.get(context)
return candidateId ? Object.freeze({ ...binding, candidateId }) : binding
}
export async function assertRoutingNetworkSharedContextRead(context: RoutingNetworkSharedContextRead) { await readOwner(context).fence() }
export function routingNetworkSharedContextPublicationFence(context: RoutingNetworkSharedContextRead): () => Promise<void> {
const owner = readOwner(context)
return async () => {
try { owner.active(); await owner.fence(); owner.active() }
catch (error) { owner.close(); throw error }
}
}
/** Internal fixed resource reader. No clients, callbacks or transport providers
* can be supplied. Only a genuine process-local session token has membership. */
export async function readRoutingNetworkSharedResource(context: RoutingNetworkSharedContextRead, serverId: number, path: string, body?: Record<string, string>): Promise<unknown> {
return readOwner(context).read(serverId, path, body)
}
export async function readRoutingNetworkSharedCommunityContext(context: RoutingNetworkSharedContext) { return sharedOwner(context).run() }
export function closeRoutingNetworkSharedContext(context: RoutingNetworkSharedContext) { sharedContexts.get(context)?.close() }
const configurationResources = new Set(["/routing/table", "/ip/vrf", "/system/resource", "/routing/bgp/connection", "/routing/bgp/template", "/routing/bgp/instance",
"/routing/filter/rule", "/routing/ospf/instance", "/routing/rip/instance", "/routing/isis/instance", "/routing/filter/select-rule", "/routing/bgp/vpn",
"/routing/rule", "/ip/firewall/mangle", "/ipv6/firewall/mangle", "/interface/gre", "/ip/route", "/ipv6/route", "/interface", "/ip/address", "/ipv6/address"])
const effectiveFields = new Set(["disabled", "templates", "instance", "input.filter-nlri", "output.filter-select", "vrf", "routing-table", "afi", "input.filter", "output.filter-chain"])
const fail = (code: string, message: string) => new McpError(code, message, 409)
function freeze<T>(value: T): T {
if (value && typeof value === "object") { for (const child of Object.values(value)) freeze(child); Object.freeze(value) }
return value
}
/** Unregistered internal reader, not a native-write grant or a network proof.
* The actual encrypted operation/plan supplies authority and endpoint identity;
* the runner callback is an additional fence, never an authority replacement.
* One process allows at most1024 authenticated source sessions, without reopen
* or eviction. Cross-restart budget admission requires a future durable owner. */
export async function createRoutingNetworkNativeSession(options: {
sourceOperationId: string; context: ActionContext; authorize: () => Promise<void>; deadline: number; manifest: RoutingNetworkNativeManifest;
}) {
const sourceOperationId = z.string().uuid().parse(options.sourceOperationId)
const manifest = freeze(manifestSchema.parse(structuredClone(options.manifest)))
if (new Set(manifest.servers).size !== manifest.servers.length || new Set(manifest.probes.map(probe => probe.key)).size !== manifest.probes.length ||
manifest.probes.some(probe => !manifest.servers.includes(probe.serverId))) throw fail("INVALID_INPUT", "Неоднозначный native manifest")
// One baseline plus at most three forward and three inverse rounds.
if ((manifest.servers.length * 6 + manifest.probes.length * 2) * 7 > 256) throw fail("LIMIT_EXCEEDED", "Полный native manifest превышает бюджет256 запросов")
const principal = structuredClone(options.context.principal), connection = structuredClone(options.context.connection)
const trustedAuthorize = options.authorize, deadline = options.deadline, startedAt = Date.now()
if (typeof trustedAuthorize !== "function" || !Number.isFinite(deadline) || deadline <= startedAt || deadline > startedAt + 120000) throw fail("READ_CANCELLED", "Некорректный исходный срок native session")
const abort = new AbortController(), signal = AbortSignal.any([abort.signal, AbortSignal.timeout(Math.max(1, deadline - startedAt)), ...(options.context.signal ? [options.context.signal] : [])])
let closed = false, rows = 0, phase = 0, tail: Promise<unknown> = Promise.resolve()
const rounds = { before: 0, "after-forward": 0, "after-inverse": 0 }
const active = () => { if (closed || signal.aborted || Date.now() >= deadline) throw fail("READ_CANCELLED", "Native session закрыта или истекла") }
const guarded = async <T>(work: () => Promise<T>) => {
active(); await trustedAuthorize(); active()
try { return await work() }
finally { active(); await trustedAuthorize(); active() }
}
// Primitive source reads keep the immutable lifetime checks. The complete
// authority fence surrounds their batch; native dispatch retains its own
// fresh before/after authorization. Avoid recursively re-running the full
// runtime authorization around every SQL/file leaf inside that same fence.
const bounded = async <T>(work: () => Promise<T>) => {
active()
try { return await work() } finally { active() }
}
const currentAuthority = async () => {
const current = await bounded(() => effectiveMcpConnection(principal))
if (current.id !== connection.id || current.owner_id !== connection.owner_id || current.generation !== connection.generation ||
fingerprint(current.policy) !== fingerprint(connection.policy) || fingerprint(current.owner_permissions) !== fingerprint(connection.owner_permissions) ||
!hasPermission(current.owner_permissions, "mm:network:read") || !hasPermission(current.policy.permissions, "mm:network:read") ||
manifest.servers.some(id => !current.policy.scope.serverIds.includes(id))) throw fail("RESET_REQUIRED", "Допуск native session изменён")
}
const sourceRow = async () => {
const query: QueryConfig & { query_timeout: number } = { text: "SELECT o.id,o.state,o.connection_id,o.created_at,p.id AS plan_id,p.operation_id,p.operation_version,p.approved_by,p.expires_at,s.state AS step_state,CASE WHEN octet_length(s.intended_state::text)<=1048576 THEN s.intended_state END AS intended_state,CASE WHEN octet_length(p.evidence::text)<=1048576 THEN p.evidence END AS evidence FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id JOIN mcp_operation_steps s ON s.operation_id=o.id AND s.step_index=0 WHERE o.id=$1 AND o.connection_id=$2 LIMIT 2",
values: [sourceOperationId, principal.connectionId], query_timeout: Math.max(1, Math.min(10000, deadline - Date.now())) }
const result = await bounded(() => pool.query(query))
if (result.rows.length !== 1) throw fail("NOT_FOUND", "Exact source native session недоступен")
const row = result.rows[0]
if (!["running", "applied", "partial"].includes(row.state) || !["intent", "applied", "verified"].includes(row.step_state) || row.operation_id !== "routing.community.switch" || row.operation_version !== findMcpOperation(row.operation_id)?.version || !row.approved_by || !row.evidence?.sealed || !(row.created_at instanceof Date) || !(row.expires_at instanceof Date)) throw fail("STATE_CONFLICT", "Нет совместимого подтверждённого source intent")
return row
}
try {
await guarded(async () => {})
await currentAuthority()
const row = await sourceRow()
if (row.state !== "running" || row.step_state !== "intent") throw fail("STATE_CONFLICT", "Native session требует исходный running intent")
const evidence = JSON.parse(await guarded(() => decryptSecret(row.evidence.sealed))) as ChangeEvidence
if (evidence.steps?.length !== 1 || evidence.steps[0].kind !== "service" || evidence.steps[0].service !== "routing.community.scoped" || evidence.target.scope !== "servers") throw fail("STATE_CONFLICT", "Требуется один исходный scoped intent")
const input = freeze(structuredClone(evidence.steps[0].input)), profile = routeAiProfileSchema.parse(input.profile)
if (fingerprint(row.intended_state) !== fingerprint(redact(evidence.steps[0]))) throw fail("STATE_CONFLICT", "Исходный service intent не соответствует sealed plan")
const fullScope = [...new Set([profile.serverId, ...profile.candidates.flatMap(candidate => [candidate.jumpHostId, candidate.exitNodeId])])].sort((a,b) => a-b)
if (fingerprint([...manifest.servers].sort((a,b) => a-b)) !== fingerprint(fullScope) || fingerprint([...evidence.target.serverIds].sort((a,b) => a-b)) !== fingerprint(fullScope) ||
fingerprint(input.principal) !== fingerprint(principal) || input.ownerId !== connection.owner_id || input.policyProof !== fingerprint(connection.policy) || input.connectionGeneration !== connection.generation) throw fail("SERVER_DENIED", "Native manifest не соответствует полному исходному scope")
await guarded(() => assertScopedCommunityRequest(input))
const generation = await guarded(() => accessGeneration())
if (input.generation !== generation) throw fail("RESET_REQUIRED", "Исходный access generation отозван")
const authorityExpiry = input.persistentProfileAuthority === undefined ? Infinity : Date.parse(routingProfileAuthorityBindingSchema.parse(input.persistentProfileAuthority).packet.validUntil)
if (deadline > Math.min(row.created_at.getTime() + 120000, row.expires_at.getTime(), authorityExpiry, Date.parse(principal.credentialExpiresAt), connection.owner_valid_until.getTime(), Date.parse(connection.policy.expiresAt))) throw fail("PLAN_EXPIRED", "Native session расширяет исходный срок")
await guarded(() => assertPersistentScopedProfileAuthority(input, signal))
const original = profile.autoRecovery ? profile.candidates.find(candidate => candidate.id === input.originalCandidateId) : undefined
if (profile.autoRecovery && (input.proofRevision !== 3 || !original?.controlProbe || manifest.probes.length !== 1 ||
manifest.probes[0].key !== input.candidateId || original.id === input.candidateId)) {
throw fail("STATE_CONFLICT", "Исходный путь возврата отсутствует в подписанном плане")
}
const originalProbe = original ? { key: original.id, serverId: profile.serverId, interface: original.wanInterface, probeVrf: profile.probeVrf } : undefined
const baselineProbes = originalProbe ? [...manifest.probes, originalProbe] : manifest.probes
const probesFor = (stage: RoutingNetworkNativeStage) => stage === "before" ? baselineProbes :
stage === "after-inverse" && originalProbe ? [originalProbe] : manifest.probes
for (const probe of baselineProbes) {
const candidate = profile.candidates.find(candidate => candidate.id === probe.key)
if (!candidate?.controlProbe || probe.serverId !== profile.serverId || probe.interface !== candidate.wanInterface || probe.probeVrf !== profile.probeVrf ||
!candidate.controlProbe.expectedHops.some(hop => hop.serverId === candidate.jumpHostId) || candidate.controlProbe.expectedHops.at(-1)?.serverId !== candidate.exitNodeId) throw fail("SERVER_DENIED", "Probe manifest не соответствует исходному candidate")
}
const fixedRoundCalls = (stage: RoutingNetworkNativeStage) => {
const probes = probesFor(stage), addressServers = new Set<number>()
for (const probe of probes) {
const candidate = profile.candidates.find(candidate => candidate.id === probe.key)!, configured = candidate.controlProbe!
addressServers.add(profile.serverId); addressServers.add(candidate.exitNodeId)
for (const hop of configured.expectedHops) addressServers.add(hop.serverId)
}
return manifest.servers.length * 6 + probes.length * 2 + addressServers.size * 2 + (probes.length ? 1 : 0)
}
// Reject only a known mandatory seven-round footprint. Conditional /get
// fallbacks consume the same measured budget at runtime; exhaustion closes
// the session, without truncating any catalogue or claiming complete proof.
if (fixedRoundCalls("before") + 3 * (fixedRoundCalls("after-forward") + fixedRoundCalls("after-inverse")) > 256) {
throw fail("LIMIT_EXCEEDED", "Обязательный семираундовый native manifest с address catalogues превышает256 запросов")
}
if (seenSources.has(sourceOperationId)) throw fail("STATE_CONFLICT", "Source native session уже создавалась; повтор запрещён")
if (seenSources.size >= 1024) throw fail("LIMIT_EXCEEDED", "Исчерпан process lifetime native sessions")
seenSources.add(sourceOperationId)
const sourceIdentity = fingerprint({ id: row.id, createdAt: row.created_at, planId: row.plan_id, evidence: row.evidence, expiresAt: row.expires_at, intendedState: row.intended_state })
const endpoints = await guarded(() => readRoutingEndpoints(fullScope))
if (endpoints.length !== fullScope.length || endpoints.some(endpoint => !endpoint.enabled) || fingerprint(endpoints.map(endpoint => endpoint.id).sort((a,b) => a-b)) !== fingerprint(fullScope)) throw fail("DEVICE_UNAVAILABLE", "Полный источник native manifest недоступен")
const sources = await guarded(() => createRoutingSourceContext(endpoints))
if (fingerprint(sources.expected) !== fingerprint(input.contextSources)) throw fail("STATE_CONFLICT", "Исходный endpoint manifest изменился")
const fence = async () => guarded(async () => {
await currentAuthority()
if (await bounded(() => accessGeneration()) !== generation) throw fail("RESET_REQUIRED", "Access generation native session изменён")
await bounded(() => assertPersistentScopedProfileAuthority(input, signal))
const current = await sourceRow()
if (fingerprint({ id: current.id, createdAt: current.created_at, planId: current.plan_id, evidence: current.evidence, expiresAt: current.expires_at, intendedState: current.intended_state }) !== sourceIdentity) throw fail("STATE_CONFLICT", "Исходный native intent изменён")
await bounded(() => sources.assertCurrent())
})
const pins = await guarded(() => resolveRoutingNetworkDestinationPins(endpoints, { deadline, signal, authorize: fence }))
await fence()
const clients = routeContextClients(freeze(structuredClone(endpoints)), signal, { deadline, maxCalls: 256, maxBytes: 8 * 1048576, pins })
const readRaw = async (serverId: number, path: string, body?: Record<string, string>) => {
await fence()
const client = clients.get(serverId)
if (!client) throw fail("SERVER_DENIED", "Shared native read вне исходного scope")
const timeout = Math.max(1, Math.min(10000, deadline - Date.now()))
const raw = await guarded(() => body ? client.post<unknown>(path, body, timeout) : client.get<unknown>(path, timeout))
await fence()
const payload = Array.isArray(raw) ? raw : (path === "/system/resource" || path.endsWith("/get")) && raw && typeof raw === "object" ? [raw] : null
if (!payload || payload.length > 1000 || payload.some(value => !value || typeof value !== "object" || Array.isArray(value))) throw fail("INVALID_NATIVE_RESPONSE", "Native response не является bounded каталогом")
rows += payload.length
if (rows > 10000) throw fail("LIMIT_EXCEEDED", "Превышен общий бюджет10000 native rows")
return raw
}
const read = async (serverId: number, path: string, body?: Record<string, string>) => {
const raw = await readRaw(serverId, path, body)
return (Array.isArray(raw) ? raw : [raw]) as Row[]
}
const sharedContext = Object.freeze({}) as RoutingNetworkSharedContext
const close = () => { closed = true; abort.abort(); sharedContexts.delete(sharedContext) }
sharedContexts.set(sharedContext, {
binding: Object.freeze({ sourceOperationId, profile: freeze(structuredClone(profile)), principal: freeze(structuredClone(principal)), deadline,
contextSources: freeze(structuredClone(input.contextSources as Array<{ serverId: number; proof: string }>)), candidateId: String(input.candidateId), signal }),
active, fence, close,
read: async (serverId, path, body) => {
try {
const resource = body === undefined ? path : path.endsWith("/get") ? path.slice(0, -4) : ""
if (!configurationResources.has(resource) || body !== undefined && (Object.keys(body).length !== 2 ||
!Object.hasOwn(body, ".id") || !Object.hasOwn(body, "value-name") || !/^\*[a-z0-9]+$/i.test(body[".id"]) || !effectiveFields.has(body["value-name"]))) throw fail("PERMISSION_DENIED", "Shared context допускает только fixed read resources и effective fields")
return await readRaw(serverId, path, body)
} catch (error) { close(); throw error }
},
run: () => {
const run = tail.then(async () => {
const acquisition = Object.freeze({}) as RoutingNetworkSharedContextRead
try {
active(); sharedReads.set(acquisition, sharedOwner(sharedContext))
return await readRouteCommunityContextWithSharedNativeSession(acquisition)
}
catch (error) { close(); throw error }
finally { sharedReads.delete(acquisition) }
})
tail = run.catch(() => {})
return run
},
})
let originalProbeIdentity: string | undefined
const acquireSnapshot = async (stage: RoutingNetworkNativeStage) => {
try {
active()
if (stage === "before" && phase === 0) { rounds.before++; phase = 1 }
else if (stage === "after-forward" && phase === 1 && rounds[stage] < 3) rounds[stage]++
else if (stage === "after-inverse" && phase >= 1 && rounds["after-forward"] >= 2 && rounds[stage] < 3) { rounds[stage]++; phase = 2 }
else throw fail("STATE_CONFLICT", "Native round нельзя повторить сверх лимита или переставить")
const startedAt = new Date(Date.now()).toISOString()
const servers: RoutingNetworkNativeServerEnvelope[] = [], probes: RoutingNetworkNativeProbeEnvelope[] = []
const catalogues = new Map<string, Row[]>()
const catalogue = async (serverId: number, path: string) => {
const key = serverId + ":" + path
if (!catalogues.has(key)) catalogues.set(key, await read(serverId, path))
return catalogues.get(key)!
}
const disabledValues = new Map<string, unknown>()
const readDisabled = async (serverId: number, path: string, id: string) => {
if (!/^\*[a-z0-9]+$/i.test(id)) throw fail("INVALID_NATIVE_RESPONSE", "Не подтверждён native ID probe dependency")
const key = serverId + path + id
if (!disabledValues.has(key)) {
const values = await read(serverId, path + "/get", { ".id": id, "value-name": "disabled" })
if (values.length !== 1) throw fail("INVALID_NATIVE_RESPONSE", "Не подтверждён disabled probe dependency")
disabledValues.set(key, values[0])
}
return disabledValues.get(key)
}
const enabled = async (serverId: number, path: string, row: Row) => {
const [observed] = await readOspfEffectiveDisabled<Row & { ".id": string; disabled?: string }>([row], id => readDisabled(serverId, path, id))
if (![false, "false", "no"].includes(observed.disabled as string | boolean) || [true, "true", "yes"].includes(observed.invalid as string | boolean)) throw fail("MEASUREMENT_UNKNOWN", "Probe dependency не подтверждена включённой")
}
const addressOf = async (serverId: number, iface: string, selected?: string) => {
const interfaces = (await catalogue(serverId, "/interface")).filter(row => row.name === iface)
if (interfaces.length !== 1) throw fail("MEASUREMENT_UNKNOWN", "Не подтверждён exact probe interface")
await enabled(serverId, "/interface", interfaces[0])
const path = profile.family === "ipv4" ? "/ip/address" : "/ipv6/address"
const selectedAddress = await readMeasurementAddress(await catalogue(serverId, path), { dstInterface: iface, family: profile.family, dstAddress: selected }, id => readDisabled(serverId, path, id))
if (selectedAddress.linkLocal) throw fail("UNSUPPORTED_CAPABILITY", "Link-local probe требует отдельного контракта")
return selectedAddress.address
}
for (const serverId of manifest.servers) {
const resource = await read(serverId, "/system/resource"), version = resource.length === 1 ? resource[0].version : null
if (typeof version !== "string" || version.length > 128) throw fail("INVALID_NATIVE_RESPONSE", "RouterOS version не подтверждена")
const routes = await read(serverId, "/routing/route"), connectionsPayload = await read(serverId, "/routing/bgp/connection")
const bgp = await read(serverId, "/routing/bgp/session"), bfd = await read(serverId, "/routing/bfd/session")
const logs = await read(serverId, ROUTING_NATIVE_LOG_PATH)
servers.push({ serverId, routerOsVersion: version, routes: { resource: "/routing/route", payload: routes, sessionsPayload: bgp, connectionsPayload }, bgp: { resource: "/routing/bgp/session", payload: bgp, connectionsPayload }, bfd: { resource: "/routing/bfd/session", payload: bfd }, logs: { resource: "/log", buffer: ROUTING_NATIVE_LOG_BUFFER, payload: logs, coverage: "unknown" } })
}
for (const probe of probesFor(stage)) {
const candidate = profile.candidates.find(candidate => candidate.id === probe.key)!, configured = candidate.controlProbe!
const interfaceNames = new Set((await catalogue(profile.serverId, "/interface")).map(row => row.name))
let owner: unknown = null
const vrfs = await catalogue(profile.serverId, "/ip/vrf")
for (const row of vrfs) {
const members = canonicalVrfMembers(row.interfaces).split(",")
if ([true, "true", "yes"].includes(row.disabled as string | boolean)) continue
await enabled(profile.serverId, "/ip/vrf", row)
if (members.some(member => !["all", "none"].includes(member) && !interfaceNames.has(member))) throw fail("UNSUPPORTED_CAPABILITY", "VRF interface-list требует отдельного resolver")
if (members.includes("all") || members.includes(candidate.wanInterface)) { owner = row.name; break }
}
if (owner !== profile.probeVrf) throw fail("MEASUREMENT_UNKNOWN", "Probe WAN не принадлежит exact ordered VRF")
const source = await addressOf(profile.serverId, candidate.wanInterface, configured.sourceAddress)
const destination = await addressOf(candidate.exitNodeId, configured.targetInterface, configured.targetAddress)
if ("source" in probe && "destination" in probe && (source !== probe.source || destination !== probe.destination)) {
throw fail("STATE_CONFLICT", "Probe manifest addresses не соответствуют native ownership")
}
const expectedHopAddresses = []
for (const hop of configured.expectedHops) expectedHopAddresses.push({ serverId: hop.serverId, interface: hop.interface, address: await addressOf(hop.serverId, hop.interface, hop.address) })
const request = { destination, source, interface: probe.interface, probeVrf: probe.probeVrf, count: 3 as const, maxHops: 16 as const }
if (probe === originalProbe) {
const identity = fingerprint({ request, expectedHopAddresses })
if (stage === "before") originalProbeIdentity = identity
else if (originalProbeIdentity !== identity) throw fail("STATE_CONFLICT", "Адреса исходного пути изменились после возврата")
}
const routerOsVersion = servers.find(server => server.serverId === probe.serverId)!.routerOsVersion
const pingRequest = { address: destination, "src-address": source, interface: probe.interface, vrf: probe.probeVrf, count: "3" }
const pingPayload = await read(probe.serverId, "/tool/ping", pingRequest)
// This is a command-selection check, never a failure proof. The
// parser must still validate every raw counter/row independently.
const terminal = pingPayload.at(-1), loss = terminal?.["packet-loss"]
const zeroReceived = [3,"3"].includes(terminal?.sent as string | number) && [0,"0"].includes(terminal?.received as string | number) &&
(loss === undefined || loss === 100 || typeof loss === "string" && /^100(?:\.0+)?%?$/.test(loss))
const tracePayload = zeroReceived ? undefined : await read(probe.serverId, "/tool/traceroute", { ...pingRequest, "max-hops": "16" })
probes.push({ key: probe.key, serverId: probe.serverId, routerOsVersion, pingPayload, ...(tracePayload === undefined ? {} : { tracePayload }), expectedHopAddresses, request })
}
await fence()
const observedAt = new Date(Date.now()).toISOString()
const snapshot = freeze({ sourceOperationId, stage, round: rounds[stage], startedAt, observedAt, servers, probes, securityProof: false as const, logCoverage: "unknown" as const, budget: { ...clients.readBudget(), rows } })
if (stage === "before") snapshotOwners.set(snapshot, { owner: sharedContext, finishedAt: Date.parse(observedAt) })
return snapshot
} catch (error) {
close()
if (error instanceof McpError) throw error
throw fail("STATE_UNAVAILABLE", "Native read session не подтверждена; повтор запрещён")
}
}
const readSnapshot = (stage: RoutingNetworkNativeStage) => {
const run = tail.then(() => acquireSnapshot(stage))
tail = run.catch(() => {})
return run
}
const readConfigurationBoundForwardSnapshot = (configuration: RoutingNetworkForwardRoundConfigurationContext) => {
const run = tail.then(async () => {
const acquisition = Object.freeze({}) as RoutingNetworkSharedContextRead
try {
active()
sharedReads.set(acquisition, sharedOwner(sharedContext))
// Fixed lazy import avoids a bridge/session initialization cycle.
// No caller can supply a verifier, reader, proof JSON or client.
const { readRoutingNetworkForwardRoundConfigurationContext } = await import("./routing-network-configuration-bridge.js")
const before = await readRoutingNetworkForwardRoundConfigurationContext(configuration, acquisition)
const snapshot = await acquireSnapshot("after-forward")
const after = await readRoutingNetworkForwardRoundConfigurationContext(configuration, acquisition)
await fence()
const capturedAt = Date.now()
const ordered = [before.checkpointObservedAt, before.observedAt, snapshot.startedAt,
snapshot.observedAt, after.observedAt].map(value => Date.parse(value))
ordered.push(capturedAt)
if (before.operationId !== sourceOperationId || after.operationId !== sourceOperationId || before.phase !== "forward" || after.phase !== "forward" ||
!Number.isFinite(before.deadline) || before.deadline > deadline || before.deadline !== after.deadline ||
!before.sharedNetworkBudgetVerified || !after.sharedNetworkBudgetVerified ||
before.checkpointObservedAt !== after.checkpointObservedAt || before.checkpointProof !== after.checkpointProof ||
ordered.some((time, index) => !Number.isFinite(time) || time >= before.deadline || index > 0 && time < ordered[index - 1]) ||
fingerprint(before.configuration) !== fingerprint(after.configuration)) throw fail("STATE_CONFLICT", "Forward-round configuration changed")
// Both readbacks consume this owner's measured transport and row
// budget. Preserve raw observation times; publication is later.
const bound = freeze({ ...snapshot, configurationReadbacks: { before, after }, capturedAt: new Date(capturedAt).toISOString(),
budget: { ...clients.readBudget(), rows }, securityProof: false as const, forwardingVerified: false as const })
snapshotOwners.set(bound, { owner: sharedContext, round: bound.round, startedAt: ordered[1], finishedAt: capturedAt,
configuration: fingerprint({ deadline: before.deadline, checkpointProof: before.checkpointProof, configuration: before.configuration }) })
return bound
} catch (error) { close(); throw error }
finally { sharedReads.delete(acquisition) }
})
tail = run.catch(() => {})
return run
}
const readConfigurationBoundInverseSnapshot = (assertCheckpoint: () => Promise<void>) => {
const run = tail.then(async () => {
const acquisition = Object.freeze({}) as RoutingNetworkSharedContextRead
try {
active()
if (!originalProbe || !originalProbeIdentity || rounds["after-forward"] < 2 || rounds["after-inverse"] >= 3) {
throw fail("STATE_CONFLICT", "Исходный раунд A для возврата не подтверждён")
}
sharedReads.set(acquisition, sharedOwner(sharedContext))
inverseReads.set(acquisition, originalProbe.key)
const body = await guarded(() => decryptSecret(String(input.originalRuleCiphertext)))
const assertOriginalConfiguration = async () => {
await guarded(assertCheckpoint)
const current = await readRouteCommunityContextWithSharedNativeSession(acquisition)
if (!current.scopedTopologyAvailable || current.before.currentCandidateId !== originalProbe.key ||
current.before.dependencyProof !== input.dependencyProof || current.ownedTarget?.nativeId !== input.nativeId ||
!current.ownedTarget?.matchesRuleProof(body, input.originalTargetProof)) {
throw fail("STATE_CONFLICT", "Конфигурация A изменилась во время обратного раунда")
}
await current.fence()
await guarded(assertCheckpoint)
}
await assertOriginalConfiguration()
const snapshot = await acquireSnapshot("after-inverse")
await assertOriginalConfiguration()
return freeze({ ...snapshot, budget: { ...clients.readBudget(), rows } })
} catch (error) { close(); throw error }
finally { inverseReads.delete(acquisition); sharedReads.delete(acquisition) }
})
tail = run.catch(() => {})
return run
}
return Object.freeze({ readSnapshot, readConfigurationBoundForwardSnapshot, readConfigurationBoundInverseSnapshot,
sharedContext, close, readBudget: () => Object.freeze({ ...clients.readBudget(), rows, closed }) })
} catch (error) {
closed = true; abort.abort()
if (error instanceof McpError) throw error
throw fail("STATE_UNAVAILABLE", "Исходный native session не подтверждён")
}
}