Files
MikrotikManager/backend/src/modules/mcp/routing-community-context.ts
T
DenozordecandClaude Opus 5.5 171c0e6162 fix(mcp): ускорить scoped-маршрутизацию и сервисы IPsec - проверка раз на этап для чтений
- контекст маршрута: проверка перед каждым GET (права, ключ источника, поколение,
  SQL) переиспользует доказательство этапа (2 с); границы фаз и внешний
  context.fence() по-прежнему проверяют заново;
- IPsec (удаление пира, пользователя, сертификата, изменение пира): собственная
  проверка сервиса раз на этап для чтений, assertVerifiedConfigurationReadAccess для
  чтений; перед каждой нативной записью права и защиты проверяются заново
  (executeGuardedConfigurationWrite), checkpoint-записи аудита - свежая проверка;
  сверка (reconcile) остаётся строгой: отзыв прав останавливает следующее же чтение.

Шарды: scoped forward/inverse/route-ai 205/240/324 -> 61/88/133 с, overlay-ipsec
175 -> 133 с (четыре приёмки IPsec 49 -> 19 с); весь набор 276 с, 149 строк на месте.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 14:21:27 +07:00

297 lines
29 KiB
TypeScript

import { isConfirmedRoutingFibTable } from "../../services/routing-table-fib.js"
import { coalesceAuthorization } from "./authorization-stage.js"
import { prepareOriginalEffectSelection } from "./routing-original-effects.js"
import type { RouteAiProfile } from "@mmapp/contracts/mcp-routing"
import { pool } from "../../db/index.js"
import { nativeBgpRows, bgpTemplateReferences, type NativeBgpRow } from "../../services/bgp-export-model.js"
import { bgpFilterName, effectiveBgpFilter, stableBgpPolicyRow } from "../../services/bgp-filter-binding-model.js"
import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js"
import { canonicalVrfMembers } from "../../services/vrf-members.js"
import { hasPermission } from "../../lib/permissions.js"
import { effectiveMcpConnection } from "./store.js"
import { fingerprint, McpError, privateFingerprinter, constantEqual } from "./security.js"
import { readRoutingEndpoints, createRoutingSourceContext, type RoutingEndpoint } from "./routing-observation-source.js"
import { candidateIdentifiesGateway, recognizedCommunityGateway, routeContextExecutionReason, routeGatewayContext, routeBgpContextMode, routeCandidateAvailabilityError } from "./routing-community-context-model.js"
import type { ActionContext } from "./action-types.js"
import { readMeasurementAddress } from "./routing-measurement-address.js"
import { routeContextClients } from "./routing-community-context-native.js"
import { pathProofTag } from "./path-proof-purpose.js"
import { assertManagementTransport, managementTransportClient, type ManagementTransportCapability } from "./management-transport.js"
import { assertRoutingNetworkSharedContextRead, inspectRoutingNetworkSharedContextRead, readRoutingNetworkSharedResource, routingNetworkSharedContextPublicationFence, type RoutingNetworkSharedContextRead } from "./routing-network-native-session.js"
import { scopedTargetRuleMatches } from "./routing-community-scoped-model.js"
export function routeContextAccess(context: ActionContext) {
return async () => {
if (context.signal?.aborted) throw new McpError("READ_CANCELLED", "Чтение контекста пути отменено", 409)
const current = await effectiveMcpConnection(context.principal)
if (!hasPermission(current.owner_permissions, "mm:network:read") || !hasPermission(current.policy.permissions, "mm:network:read")) throw new McpError("PERMISSION_DENIED", "Право чтения контекста пути отозвано", 403)
if (fingerprint(current.policy) !== fingerprint(context.connection.policy)) throw new McpError("RESET_REQUIRED", "Область контекста пути изменилась", 409)
}
}
export type RouteContextOptions = { authorize?: () => Promise<void>; signal?: AbortSignal; expectedSources?: Array<{ serverId: number; proof: string }>; selectedCandidateId?: string; managementTransport?: ManagementTransportCapability }
export type OwnedRouteCommunityTarget = { nativeId: string; rawRow: NativeBgpRow; endpoint: Readonly<RoutingEndpoint>; desiredTargetProof: (ruleBody: string) => string; matchesRuleProof: (ruleBody: string, proof: unknown) => boolean }
/** Fixed endpoint clients and private proofs are retained in closures. Public
* results contain no credentials, native rules, arbitrary comments or SQL rows. */
async function readContext(profile: RouteAiProfile, options: RouteContextOptions, sharedContext?: RoutingNetworkSharedContextRead) {
const ids = [...new Set([profile.serverId, ...profile.candidates.flatMap(candidate => [candidate.jumpHostId, candidate.exitNodeId])])].sort((a, b) => a - b)
await options.authorize?.()
const endpoints = await readRoutingEndpoints(ids)
if (!endpoints.some(endpoint => endpoint.id === profile.serverId && endpoint.enabled)) throw new McpError("DEVICE_UNAVAILABLE", "Основной источник контекста пути отсутствует или отключён", 409)
const sources = await createRoutingSourceContext(endpoints)
if (options.expectedSources && fingerprint(sources.expected) !== fingerprint(options.expectedSources)) throw new McpError("STATE_CONFLICT", "Источник контекста пути изменился; новый endpoint не опрашивается", 409)
const sign = await privateFingerprinter("route-ai-context-v1")
const clients: Map<number, { get<T>(path: string, timeoutMs?: number): Promise<T>; post<T>(path: string, body: Record<string, string>, timeoutMs?: number): Promise<T> }> = sharedContext ? new Map(endpoints.filter(endpoint => endpoint.enabled).map(endpoint => [endpoint.id, {
get: <T>(path: string) => readRoutingNetworkSharedResource(sharedContext, endpoint.id, path) as Promise<T>,
post: <T>(path: string, body: Record<string, string>) => readRoutingNetworkSharedResource(sharedContext, endpoint.id, path, body) as Promise<T>,
}])) : routeContextClients(endpoints.filter(endpoint => endpoint.enabled), options.signal)
if (options.managementTransport) {
await assertManagementTransport(options.managementTransport)
const alternate = managementTransportClient(options.managementTransport, options.signal)
if (!endpoints.some(endpoint => endpoint.id === alternate.serverId && endpoint.enabled)) throw new McpError("SERVER_DENIED", "Management transport вне контекста пути", 409)
clients.set(alternate.serverId, alternate)
}
const unavailableIds = ids.filter(id => !endpoints.some(endpoint => endpoint.id === id && endpoint.enabled))
const unavailableSourcesProof = sign("unavailable-sources:" + fingerprint(endpoints.filter(endpoint => unavailableIds.includes(endpoint.id))))
const fence = async () => {
await options.authorize?.(); await sources.assertCurrent()
if (options.managementTransport) await assertManagementTransport(options.managementTransport)
if (unavailableIds.length && unavailableSourcesProof !== sign("unavailable-sources:" + fingerprint(await readRoutingEndpoints(unavailableIds)))) throw new McpError("STATE_CONFLICT", "Недоступный источник контекста пути изменился", 409)
}
// Per-GET fence: reuses a proof from the current stage (2 s). Phase boundaries and callers use fence().
const readFence = coalesceAuthorization(fence).coalesced
const rawProof: unknown[] = [{ unavailableIds, unavailableSourcesProof }], caches = new Map<string, NativeBgpRow[]>(), failures = new Map<string, unknown>()
let totalRows = 0, totalBytes = 0, calls = 0
const budget = (value: unknown) => {
totalBytes += Buffer.byteLength(JSON.stringify(value), "utf8")
if (++calls > 2000 || totalBytes > 8 * 1024 * 1024) throw new McpError("LIMIT_EXCEEDED", "Превышен бюджет контекста пути", 409)
}
const get = async (serverId: number, path: string): Promise<NativeBgpRow[]> => {
const key = serverId + path, cached = caches.get(key)
if (cached) return cached
if (failures.has(key)) throw failures.get(key)
await readFence()
const client = clients.get(serverId)
if (!client) throw new McpError("DEVICE_UNAVAILABLE", "Источник кандидата отсутствует или отключён", 409)
let value: unknown
try { value = await client.get<unknown>(path) }
catch (error) {
if (routeCandidateAvailabilityError(error)) { failures.set(key, error); rawProof.push({ serverId, path, unavailable: true }) }
throw error
}
budget(value)
let rows: NativeBgpRow[]
try { rows = nativeBgpRows(value) }
catch { throw new McpError("INVALID_NATIVE_RESPONSE", "Источник контекста пути вернул недостоверный каталог", 409) }
if (rows.length > 1000 || (totalRows += rows.length) > 10000) throw new McpError("LIMIT_EXCEEDED", "Каталог контекста пути превышает лимит", 409)
const stable = (row: NativeBgpRow) => path === "/interface" ? Object.fromEntries(Object.entries(row).filter(([property]) => !/^(?:rx-|tx-|fp-|last-link-|link-downs$|driver-)/.test(property))) : stableBgpPolicyRow(row)
caches.set(key, rows); rawProof.push({ serverId, path, rows: rows.map(stable) }); return rows
}
const post = async (serverId: number, path: string, body: Record<string, string>) => {
await readFence(); const value = await clients.get(serverId)!.post<unknown>(path, body); budget(value); rawProof.push({ serverId, path, body, value }); return value
}
const enabled = async (serverId: number, path: string, row: NativeBgpRow) => {
const [result] = await readOspfEffectiveDisabled<NativeBgpRow & { disabled?: string }>([row], id => post(serverId, path + "/get", { ".id": id, "value-name": "disabled" }))
if (!["false", "no", false].includes(result.disabled as string | boolean) || ["true", "yes", true].includes(result.invalid as string | boolean)) throw new McpError("STATE_UNAVAILABLE", "Зависимость пути отключена или не подтверждена", 409)
return result
}
const unique = (rows: NativeBgpRow[], ref: unknown) => {
const found = rows.filter(row => row.name === ref || row[".id"] === ref)
if (found.length !== 1) throw new McpError("STATE_UNAVAILABLE", "Контекст пути отсутствует или неоднозначен", 409)
return found[0]
}
const sourceId = profile.serverId, tables = await get(sourceId, "/routing/table"), vrfs = await get(sourceId, "/ip/vrf")
const table = unique(tables, profile.table)
if (!isConfirmedRoutingFibTable(table)) throw new McpError("STATE_UNAVAILABLE", "FIB таблицы назначения не подтверждён", 409)
await enabled(sourceId, "/ip/vrf", unique(vrfs, profile.probeVrf))
// Keep ordered VRF membership (first matching row wins), never equate an
// arbitrary policy table with the diagnostic VRF's same-name table.
for (const row of vrfs) canonicalVrfMembers(row.interfaces)
await fence()
const resource = await clients.get(sourceId)!.get<unknown>("/system/resource")
budget(resource); rawProof.push({ serverId: sourceId, path: "/system/resource", mode: routeBgpContextMode(resource), version: resource && typeof resource === "object" ? (Array.isArray(resource) ? resource[0]?.version : (resource as Record<string, unknown>).version) : null })
const bgpContextMode = routeBgpContextMode(resource), legacy = bgpContextMode === "legacy-read-only"
const connections = await get(sourceId, "/routing/bgp/connection"), templates = await get(sourceId, "/routing/bgp/template"), instances = legacy ? [] : await get(sourceId, "/routing/bgp/instance")
if (connections.length > 100 || templates.length > 100) throw new McpError("LIMIT_EXCEEDED", "Граф BGP контекста превышает 100 подключений/шаблонов", 409)
const effectiveCache = new Map<string, Record<string, string | null>>()
const resolve = async (path: string, row: NativeBgpRow, stack: string[] = [], disabledConnection = false): Promise<Record<string, string | null>> => {
const key = path + row[".id"], cached = effectiveCache.get(key)
if (stack.includes(key) || stack.length >= 16) throw new McpError("STATE_UNAVAILABLE", "Цикл или глубина BGP templates не подтверждены", 409)
if (cached) return cached
if (!disabledConnection) await enabled(sourceId, path, row)
const refs = bgpTemplateReferences(await post(sourceId, path + "/get", { ".id": row[".id"], "value-name": "templates" }))
const parents: Record<string, string | null>[] = []
for (const ref of refs) parents.push(await resolve("/routing/bgp/template", unique(templates, ref), [...stack, key]))
const result: Record<string, string | null> = {}
for (const property of [...(legacy ? [] : ["instance", "input.filter-nlri", "output.filter-select"]), "vrf", "routing-table", "afi", "input.filter", "output.filter-chain"]) {
const local = bgpFilterName(await post(sourceId, path + "/get", { ".id": row[".id"], "value-name": property }))
const inherited = parents.map(parent => parent[property]).filter((value): value is string => value !== null)
result[property] = local !== null ? local : inherited.length ? effectiveBgpFilter(null, inherited) : null
}
effectiveCache.set(key, result); return result
}
const bindings: Array<{ connectionId: string; instance: string | null; vrf: string; table: string; afi: string; inputChain: string; outputChain: string }> = []
const disabledBindings: Array<{ connectionId: string; inputChain: string; outputChain: string }> = []
const otherBgpReferences: Array<{ connectionId: string; chain: string }> = []
for (const connection of connections) {
const [observed] = await readOspfEffectiveDisabled<NativeBgpRow & { disabled?: string }>([connection], id => post(sourceId, "/routing/bgp/connection/get", { ".id": id, "value-name": "disabled" }))
const disabled = ["true", "yes", true].includes(observed.disabled as string | boolean)
const effective = await resolve("/routing/bgp/connection", observed, [], disabled)
for (const property of ["input.filter-nlri", "output.filter-select"]) if (effective[property]) otherBgpReferences.push({ connectionId: connection[".id"], chain: effective[property]! })
// Disabled peers still resolve all inheritance and filter references. Their
// dormant chain references continue to block a supposedly private write.
if (disabled) { disabledBindings.push({ connectionId: connection[".id"], inputChain: effective["input.filter"] ?? "", outputChain: effective["output.filter-chain"] ?? "" }); continue }
const instance = legacy ? null : await enabled(sourceId, "/routing/bgp/instance", unique(instances, effective.instance))
const values: Record<string, string | null> = { ...effective }
for (const property of ["vrf", "routing-table"]) if (!values[property] && instance) values[property] = bgpFilterName(await post(sourceId, "/routing/bgp/instance/get", { ".id": instance[".id"], "value-name": property }))
if (!values.vrf || !values["routing-table"] || !values.afi || values["input.filter"] === null) throw new McpError("STATE_UNAVAILABLE", "Не подтверждены effective BGP table/VRF/AFI/input binding", 409)
const boundTable = unique(tables, values["routing-table"])
if (!isConfirmedRoutingFibTable(boundTable)) throw new McpError("STATE_UNAVAILABLE", "FIB BGP таблицы не подтверждён", 409)
await enabled(sourceId, "/ip/vrf", unique(vrfs, values.vrf))
bindings.push({ connectionId: connection[".id"], instance: instance ? String(instance.name) : null, vrf: values.vrf, table: values["routing-table"]!, afi: values.afi, inputChain: values["input.filter"]!, outputChain: values["output.filter-chain"] ?? "" })
}
const matching = bindings.filter(binding => binding.table === profile.table && binding.vrf === (profile.bgpContext?.vrf ?? "main") && binding.afi.split(",").includes(profile.family === "ipv4" ? "ip" : "ipv6") && (profile.bgpContext ? binding.connectionId === profile.bgpContext.connectionId && binding.instance === profile.bgpContext.instance && binding.inputChain === profile.bgpContext.inputChain : profile.table === "main" && binding.inputChain === "bgp-in"))
const selected = matching.length === 1 ? matching[0] : null
const filters = await get(sourceId, "/routing/filter/rule")
for (const row of filters.filter(row => row.chain === selected?.inputChain)) Object.assign(row, await enabled(sourceId, "/routing/filter/rule", row))
const current = selected ? recognizedCommunityGateway(filters, selected.inputChain, profile.community, profile.family) : null
const externalReferences: Array<{ path: string; id: string }> = []
for (const path of ["/routing/ospf/instance", "/routing/rip/instance", "/routing/isis/instance", "/routing/filter/select-rule", "/routing/bgp/vpn", "/routing/rule", "/ip/firewall/mangle", "/ipv6/firewall/mangle"]) {
const rows = await get(sourceId, path)
for (const row of rows) if (selected && Object.entries(row).some(([key, value]) => (key.includes("filter") || key === "do-where" || path === "/routing/filter/select-rule" && key === "chain") && (typeof value === "string" ? value.split(",").includes(selected.inputChain) : Array.isArray(value) && value.includes(selected.inputChain)))) externalReferences.push({ path, id: row[".id"] })
}
for (const row of filters) if (selected && row.chain !== selected.inputChain && typeof row.rule === "string" && /\bjump\b/.test(row.rule)) {
// Opaque jump syntax cannot prove that the selected input chain is private.
externalReferences.push({ path: "/routing/filter/rule", id: row[".id"] })
}
const candidateRows = new Map<string, NativeBgpRow>()
const candidateDiagnostics = profile.candidates.map(candidate => ({ candidateId: candidate.id, status: "available" as "available" | "candidate-unavailable", reason: null as string | null }))
const unavailableCandidate = (candidateId: string, error: unknown) => {
if (!routeCandidateAvailabilityError(error)) throw error
const diagnostic = candidateDiagnostics.find(row => row.candidateId === candidateId)!
diagnostic.status = "candidate-unavailable"; diagnostic.reason = "CANDIDATE_CONTEXT_UNAVAILABLE"
rawProof.push({ candidateId, status: diagnostic.status, reason: diagnostic.reason })
}
for (const candidate of profile.candidates) {
try {
const path = { gre: "/interface/gre", ipv4_route: "/ip/route", ipv6_route: "/ipv6/route" }[candidate.gatewayRef.resource]
const row = (await get(sourceId, path)).find(row => row[".id"] === candidate.gatewayRef.id)
if (!row) throw new McpError("STATE_UNAVAILABLE", "Gateway кандидата отсутствует", 409)
candidateRows.set(candidate.id, row)
await enabled(sourceId, path, row)
if (!candidateIdentifiesGateway(profile, candidate, { gateway: candidate.gateway, gatewayInterface: candidate.gatewayRef.resource === "gre" ? String(row.name ?? "") : "" }, row)) throw new McpError("STATE_UNAVAILABLE", "Gateway кандидата не связан с точным owned объектом", 409)
let gateway: ReturnType<typeof routeGatewayContext>
try { gateway = routeGatewayContext(candidate.gateway) } catch { throw new McpError("STATE_UNAVAILABLE", "Gateway кандидата не подтверждён", 409) }
const resolver = unique(tables, gateway.resolverTable)
if (!isConfirmedRoutingFibTable(resolver)) throw new McpError("STATE_UNAVAILABLE", "FIB resolver таблицы не подтверждён", 409)
if (unavailableIds.includes(candidate.jumpHostId) || unavailableIds.includes(candidate.exitNodeId)) throw new McpError("DEVICE_UNAVAILABLE", "Источник кандидата отсутствует или отключён", 409)
} catch (error) { unavailableCandidate(candidate.id, error) }
}
const probeEndpoints = new Map<string, { destination: string; expected: string[]; source?: string }>()
const address = async (serverId: number, iface: string, selected?: string) => {
const path = profile.family === "ipv4" ? "/ip/address" : "/ipv6/address"
const interfaces = await get(serverId, "/interface")
await enabled(serverId, "/interface", unique(interfaces, iface))
const rows = await get(serverId, path)
const value = await readMeasurementAddress(rows, { dstInterface: iface, family: profile.family, dstAddress: selected }, id => post(serverId, path + "/get", { ".id": id, "value-name": "disabled" }))
if (value.linkLocal) throw new McpError("STATE_UNAVAILABLE", "Link-local control probe требует отдельного scoped исполнителя", 409)
return value.address
}
for (const candidate of profile.candidates.filter(candidate => candidate.controlProbe)) {
if (candidateDiagnostics.find(row => row.candidateId === candidate.id)!.status !== "available") continue
try {
const probe = candidate.controlProbe!
// RouterOS VRF rows are ordered. Interface lists and inherited membership
// are deliberately unknown instead of guessing the first matching VRF.
let owner: string | null = null
const interfaceNames = new Set((await get(sourceId, "/interface")).map(row => String(row.name)))
for (const row of vrfs) {
const members = canonicalVrfMembers(row.interfaces).split(",")
if (["true", "yes", true].includes(row.disabled as string | boolean)) continue
await enabled(sourceId, "/ip/vrf", row)
if (members.some(member => !["all", "none"].includes(member) && !interfaceNames.has(member))) throw new McpError("STATE_UNAVAILABLE", "VRF interface-list membership требует отдельного resolver", 409)
if (members.includes("all") || members.includes(candidate.wanInterface)) { owner = String(row.name); break }
}
if (owner !== profile.probeVrf) throw new McpError("STATE_UNAVAILABLE", "WAN интерфейс не принадлежит указанному probe VRF", 409)
await enabled(sourceId, "/interface", unique(await get(sourceId, "/interface"), candidate.wanInterface))
const destination = await address(candidate.exitNodeId, probe.targetInterface, probe.targetAddress), expected: string[] = []
for (const hop of probe.expectedHops) expected.push(await address(hop.serverId, hop.interface, hop.address))
const source = probe.sourceAddress ? await address(sourceId, candidate.wanInterface, probe.sourceAddress) : undefined
probeEndpoints.set(candidate.id, { destination, expected, source })
} catch (error) { unavailableCandidate(candidate.id, error) }
}
if (options.selectedCandidateId && candidateDiagnostics.find(row => row.candidateId === options.selectedCandidateId)?.status !== "available") throw new McpError("STATE_UNAVAILABLE", "CANDIDATE_CONTEXT_UNAVAILABLE", 409)
const currentCandidates = current && selected ? profile.candidates.filter(candidate => candidateIdentifiesGateway(profile, candidate, current, candidateRows.get(candidate.id))) : []
await fence()
const protections = (await pool.query(`WITH chosen AS MATERIALIZED (SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=ANY($1::text[]) OR (object_ref->>'kind'='server' AND object_ref->>'id'=ANY($1::text[])) LIMIT 1001),
budget AS (SELECT count(*) AS count,coalesce(sum(octet_length(object_ref::text)),0) AS bytes FROM chosen)
SELECT CASE WHEN budget.count<=1000 AND budget.bytes<=1048576 THEN (SELECT coalesce(jsonb_agg(object_ref),'[]') FROM chosen) END AS refs,budget.count>1000 OR budget.bytes>1048576 AS overflow FROM budget`, [ids.map(String)])).rows[0]
if (!protections || protections.overflow || !Array.isArray(protections.refs)) throw new McpError("LIMIT_EXCEEDED", "Не подтверждён ограниченный каталог защит пути", 409)
await fence()
const allChainBindings = [...bindings, ...disabledBindings]
const sharedConnectionIds = selected ? allChainBindings.filter(binding => binding.inputChain === selected.inputChain).map(binding => binding.connectionId) : []
const dependencyReason = !selected ? "BGP_CONTEXT_UNCONFIRMED" : selected.afi !== (profile.family === "ipv4" ? "ip" : "ipv6") || sharedConnectionIds.length !== 1 || allChainBindings.some(binding => binding.outputChain === selected.inputChain) || otherBgpReferences.some(binding => binding.chain === selected.inputChain) || externalReferences.length ? "SHARED_BINDING_REQUIRES_SCOPED_EXECUTOR" : !current || currentCandidates.length !== 1 ? "CURRENT_GATEWAY_CONTEXT_UNCONFIRMED" : null
const reason = legacy ? "LEGACY_BGP_READ_ONLY" : routeContextExecutionReason(profile) ?? dependencyReason
const topologyReason = legacy ? "LEGACY_BGP_READ_ONLY" : !profile.bgpContext && (profile.table !== "main" || profile.probeVrf !== "main" || selected && (selected.vrf !== "main" || selected.inputChain !== "bgp-in")) ? "EXPLICIT_BGP_CONTEXT_REQUIRED" : dependencyReason
const scopedReason = legacy ? topologyReason : profile.autoRecovery ? "ROUTE_RECOVERY_EXECUTOR_UNAVAILABLE" : topologyReason
const targetRule = selected && current ? filters.find(row => row.chain === selected.inputChain)! : null
// The owned target body has a separate seal so a scoped executor can prove
// untouched dependencies after its deliberate, exact body replacement.
const targetRuleProof = targetRule ? sign("target-rule:" + fingerprint(stableBgpPolicyRow(targetRule))) : null
const immutableTarget = targetRule ? structuredClone(targetRule) : null
const ownedTarget: OwnedRouteCommunityTarget | undefined = immutableTarget ? (() => {
const desiredTargetProof = (ruleBody: string) => {
if (typeof ruleBody !== "string" || Buffer.byteLength(ruleBody, "utf8") > 65536) throw new McpError("LIMIT_EXCEEDED", "Тело scoped Community фильтра превышает лимит", 409)
return sign("target-rule:" + fingerprint(stableBgpPolicyRow({ ...immutableTarget, rule: ruleBody })))
}
return {
nativeId: immutableTarget[".id"], rawRow: structuredClone(immutableTarget), endpoint: Object.freeze({ ...endpoints.find(endpoint => endpoint.id === sourceId)! }),
desiredTargetProof, matchesRuleProof: (ruleBody: string, proof: unknown) => scopedTargetRuleMatches({ rawRow: immutableTarget, desiredTargetProof }, ruleBody, proof),
}
})() : undefined
const dependencies = rawProof.map(value => {
const snapshot = value as { path?: string; rows?: Record<string, unknown>[] }
return snapshot.path === "/routing/filter/rule" && snapshot.rows && targetRule ? { ...snapshot, rows: snapshot.rows.map(row => row[".id"] === targetRule[".id"] ? { ...row, rule: "[separately-sealed-owned-body]" } : row) } : value
})
const dependencyProof = sign("dependencies:" + fingerprint({ profile, sources: sources.expected, rawProof: dependencies, protections: protections.refs }))
const before = { contextVerified: !!selected, bgpContextMode, candidateDiagnostics, table: profile.table, probeVrf: profile.probeVrf, family: profile.family,
bgpConnectionId: selected?.connectionId ?? null, bgpVrf: selected?.vrf ?? null, instance: selected?.instance ?? null, inputChain: selected?.inputChain ?? null,
currentCandidateId: currentCandidates.length === 1 ? currentCandidates[0].id : null, currentGateway: current?.gateway ?? null,
nativeRuleId: selected && current ? filters.find(row => row.chain === selected.inputChain)![".id"] : null, ownedCompilerRecognized: !!current,
sharedConnectionIds, bindings, disabledConnectionIds: disabledBindings.map(binding => binding.connectionId), externalReferences, executionAvailable: reason === null, executionReason: reason, scopedExecutionAvailable: scopedReason === null, scopedExecutionReason: scopedReason, targetRuleProof, dependencyProof, sourceProofs: sources.expected }
return { before, clients, fence, probeEndpoints, ownedTarget, scopedTopologyAvailable: topologyReason === null,
captureOriginalEffectSelection: async (candidateId: string) => {
try {
const routes = await get(sourceId, "/routing/route"), sessions = await get(sourceId, "/routing/bgp/session")
await fence()
return prepareOriginalEffectSelection(profile, candidateId, selected, { routes, connections, sessions,
candidate: candidateRows.get(candidateId), probe: probeEndpoints.get(candidateId) })
} catch { await fence(); return { status: "unknown" as const, reason: "prepared-effect-catalogue-unavailable" } }
},
signEvidence: (value: unknown) => sign(pathProofTag("community") + fingerprint({ dependencyProof, targetRuleProof, value })),
verifyEvidence: (value: unknown, proof: unknown) => typeof proof === "string" && constantEqual(sign(pathProofTag("community") + fingerprint({ dependencyProof, targetRuleProof, value })), proof),
}
}
export async function readRouteCommunityContext(profile: RouteAiProfile, options: RouteContextOptions = {}) {
try { return await readContext(profile, options) }
catch (error) {
if (error instanceof McpError) throw error
throw new McpError("STATE_UNAVAILABLE", "Не подтверждены bounded BGP/routing dependencies пути", 409)
}
}
/** Private token-only path. Profile, source identities, candidate, authority,
* signal and transport all come from the authenticated native session owner.
* It preserves every existing execution reason, including autoRecovery. */
export async function readRouteCommunityContextWithSharedNativeSession(sharedContext: RoutingNetworkSharedContextRead) {
const binding = inspectRoutingNetworkSharedContextRead(sharedContext)
const result = await readContext(binding.profile, { selectedCandidateId: binding.candidateId, signal: binding.signal,
expectedSources: binding.contextSources, authorize: () => assertRoutingNetworkSharedContextRead(sharedContext) }, sharedContext)
await result.fence()
// The acquisition ends when this function returns. Later publication fences
// must use the owner rather than retain a completed transport-read permit.
return { before: result.before, scopedTopologyAvailable: result.scopedTopologyAvailable, fence: routingNetworkSharedContextPublicationFence(sharedContext),
ownedTarget: result.ownedTarget ? { nativeId: result.ownedTarget.nativeId, rawRow: structuredClone(result.ownedTarget.rawRow), matchesRuleProof: result.ownedTarget.matchesRuleProof } : undefined }
}