Files
MikrotikManager/backend/src/services/ospf-link-catalog.ts
T

81 lines
7.3 KiB
TypeScript

import { isIP } from "node:net"
import { z } from "zod"
import type { MikrotikClient } from "./mikrotik.js"
import { readOspfIdentityCatalog, ospfLiteralRouterId } from "./ospf-identity-catalog.js"
import { observedBoolean } from "./ospf-observed-values.js"
import { ipv6ToInt } from "./traffic-flow-ip.js"
import { fingerprint, McpError } from "../modules/mcp/security.js"
type Family = "ipv4" | "ipv6"
const text = z.string().min(1).max(200)
const rowsSchema = z.array(z.record(z.string(), z.unknown())).max(10000)
const boolean = (value: unknown) => observedBoolean(typeof value === "boolean" ? String(value) : typeof value === "string" ? value : undefined)
function endpoint(value: unknown, allowPrefix = false) {
const raw = text.parse(value), parts = /^([^%@/]+)(?:%([^@/]+))?(?:@([^/]+))?(?:\/(\d+))?$/.exec(raw)
if (!parts || !allowPrefix && parts[4] !== undefined) throw new Error("Не подтверждён адрес соседства OSPF")
const family = isIP(parts[1])
if (!family || parts[4] !== undefined && Number(parts[4]) > (family === 4 ? 32 : 128)) throw new Error("Недостоверный IP соседства OSPF")
return { key: family + ":" + (family === 4 ? parts[1] : ipv6ToInt(parts[1])!.toString(16)), family, interface: parts[2] ?? null, vrf: parts[3] ?? null, prefix: parts[4] === undefined ? null : Number(parts[4]) }
}
export async function readOspfLinkCatalog(client: Pick<MikrotikClient, "get" | "post">, family: Family, beforeRead: () => Promise<unknown> = async () => {}, initial?: {
identity: Awaited<ReturnType<typeof readOspfIdentityCatalog>>; neighbors: unknown;
}) {
const identity = initial?.identity ?? await readOspfIdentityCatalog(client, beforeRead)
const read = async (path: string) => { await beforeRead(); return client.get<unknown>(path) }
const rawNeighbors = rowsSchema.parse(initial ? initial.neighbors : await read("/routing/ospf/neighbor"))
const path = family === "ipv4" ? "/ip/address" : "/ipv6/address", rawAddresses = rowsSchema.parse(await read(path))
for (const rows of [rawNeighbors, rawAddresses]) {
if (rows.some(row => typeof row[".id"] !== "string" || !row[".id"]) || new Set(rows.map(row => row[".id"])).size !== rows.length) throw new Error("Не подтверждены native IDs контекста соседства OSPF")
}
const count = identity.rows + rawNeighbors.length + rawAddresses.length, bytes = identity.bytes + Buffer.byteLength(JSON.stringify({ rawNeighbors, rawAddresses }))
if (count > 10000 || bytes > 1048576) throw new Error("Контекст соседства OSPF превышает 10000 строк или 1 МиБ")
const neighbors = rawNeighbors.map(row => {
const state = text.parse(row.state).toLowerCase(), address = endpoint(row.address), iface = text.parse(row.interface), routerId = ospfLiteralRouterId(row["router-id"])
if (!routerId || !["down", "attempt", "init", "2-way", "exstart", "exchange", "loading", "full"].includes(state) || address.interface && address.interface !== iface || boolean(row.inactive) === true && state === "full") throw new Error("Не подтверждён контекст native OSPF соседа")
const instance = text.parse(row.instance), owners = identity.instances.filter(item => [item[".id"], item.name].includes(instance))
if (owners.length !== 1 || state === "full" && (owners[0].disabled !== "false" || address.vrf && address.vrf !== owners[0].vrf)) throw new Error("Не подтверждён единственный экземпляр native OSPF соседа")
return { id: String(row[".id"]), instance, instanceId: owners[0][".id"], interface: iface, routerId, address, state }
}).sort((a, b) => a.id.localeCompare(b.id))
let getters = 0
const flag = async (row: Record<string, unknown>, name: string) => {
let value = boolean(row[name])
if (row[name] === undefined) {
if (!/^\*[a-z0-9]+$/i.test(String(row[".id"])) || ++getters > 128) throw new Error("Не подтверждён native ID адреса или превышен бюджет уточнения OSPF")
await beforeRead()
const response = await client.post<{ ret?: unknown }>(path + "/get", { ".id": String(row[".id"]), "value-name": name })
value = boolean(response?.ret)
}
if (value === null) throw new Error("Не подтверждён флаг адреса контекста OSPF")
return value
}
const addresses = []
for (const row of rawAddresses) {
const address = endpoint(row.address, true), iface = text.parse(row.interface), disabled = await flag(row, "disabled")
if (address.family !== (family === "ipv4" ? 4 : 6) || address.interface && address.interface !== iface) throw new Error("Семейство или интерфейс адреса OSPF не подтверждены")
addresses.push({ id: String(row[".id"]), address, interface: iface, disabled, invalid: disabled ? boolean(row.invalid) : await flag(row, "invalid") })
}
addresses.sort((a, b) => a.id.localeCompare(b.id))
return { identity, neighbors, addresses, rows: count, bytes, fingerprint: fingerprint({ family, identity: identity.fingerprint, neighbors, addresses }) }
}
export type OspfLinkCatalog = Awaited<ReturnType<typeof readOspfLinkCatalog>>
/** Resolve an observed adjacency, not a globally unique ID or equal VRF names. */
export function resolveOspfLinkOwner(localId: number, local: OspfLinkCatalog, instanceId: string, neighborId: string, candidates: readonly { serverId: number; catalog: OspfLinkCatalog }[]) {
const instance = local.identity.instances.find(row => row[".id"] === instanceId), neighbor = local.neighbors.find(row => row.id === neighborId)
if (!instance || !neighbor || neighbor.instanceId !== instanceId || instance.disabled !== "false" || neighbor.state !== "full" || neighbor.routerId === instance["router-id"] || neighbor.address.vrf && neighbor.address.vrf !== instance.vrf) return null
const localAddresses = local.addresses.filter(row => row.interface === neighbor.interface && !row.disabled && row.invalid === false && (!row.address.vrf || row.address.vrf === instance.vrf)).map(row => row.address.key)
const matches: { serverId: number; instanceId: string; vrf: string; interface: string }[] = []
for (const { serverId, catalog } of candidates) {
if (serverId === localId) continue
for (const peer of catalog.identity.instances) {
if (peer.disabled !== "false" || peer.version !== instance.version || peer["router-id"] !== neighbor.routerId) continue
const peerAddresses = catalog.addresses.filter(row => row.address.key === neighbor.address.key && !row.disabled && row.invalid === false && (!row.address.vrf || row.address.vrf === peer.vrf))
const reverse = catalog.neighbors.filter(row => row.instanceId === peer[".id"] && row.state === "full" && row.routerId === instance["router-id"] && localAddresses.includes(row.address.key) && (!row.address.vrf || row.address.vrf === peer.vrf) && peerAddresses.some(address => address.interface === row.interface))
for (const row of reverse) matches.push({ serverId, instanceId: peer[".id"], vrf: peer.vrf!, interface: row.interface })
}
}
if (matches.length > 1) throw new McpError("MEASUREMENT_UNKNOWN", "Неоднозначное двустороннее соседство OSPF между устройствами или VRF", 409)
return matches[0] ?? null
}