import { assertNoCallerCreateId } from "./native-create-identity.js" import { z } from "zod" import { isIP } from "node:net" import { eq } from "drizzle-orm" import { db } from "../../db/index.js" import { servers } from "../../db/schema.js" import { MikrotikClient } from "../../services/mikrotik.js" import { readRouterOsSnapshotGet } from "../../services/routeros-snapshot-read.js" import { McpError, fingerprint, privateFingerprinter, privateSecretFingerprint } from "./security.js" import { readOspfEffectiveDisabled } from "../../services/ospf-effective-disabled.js" import { greNativeFieldsSchema } from "../../services/gre-mutation-input.js" import { canonicalVrfMembers } from "../../services/vrf-members.js" import { canonicalBridgeVlanValue } from "../../services/bridge-vlan-values.js" import { canonicalBgpPolicyPrefix } from "../../services/bgp-community-policy-model.js" import { observedBoolean, observedDurationMs } from "../../services/ospf-observed-values.js" import { ipv6NdFields, ipv6NdPrefixFields, ipv6NdSettingsFields, normalizeIpv6NdRow } from "../../services/ipv6-nd-configuration.js" const text = z.string().max(1000) const name = z.string().trim().min(1).max(100) const bool = z.boolean() const vlanIds = z.string().min(1).max(16384).refine(value => { try { canonicalBridgeVlanValue("vlan-ids", value); return true } catch { return false } }, "Требуется непересекающийся список VLAN ID/диапазонов 1..4094") const integer = (min: number, max: number) => z.number().int().min(min).max(max) const common = { name: name.optional(), comment: text.optional(), disabled: bool.optional() } const ipv4 = name.refine(value => isIP(value) === 4, "Требуется IPv4 router/area ID") const ospfRouterId = name.refine(value => isIP(value) === 4 || /^[a-z0-9_.-]+$/i.test(value) && !/^[\d.]+$/.test(value), "Требуется IPv4 или имя Router ID") const ospfFilterName = z.string().max(100).refine(value => value.trim() === value && !/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(value)) export const ospfFilterFields = z.object({ "in-filter-chain": ospfFilterName.optional(), "out-filter-chain": ospfFilterName.optional(), "out-filter-select": ospfFilterName.optional() }).strict() const ospfRouteSources = z.enum(["connected", "static", "rip", "ospf", "isis", "bgp", "vpn", "dhcp", "fantasy", "modem", "bgp-mpls-vpn", "slaac"]) const ospfRedistribute = text.transform((value, context) => { if (value === "") return "" const sources = value.split(",").map(source => source.trim()) if (new Set(sources).size !== sources.length || sources.some(source => !ospfRouteSources.safeParse(source).success)) { context.addIssue({ code: "custom", message: "Требуется список источников OSPF без повторов" }) return z.NEVER } return sources.sort().join(",") }) const interval = z.string().regex(/^(?:[1-9]|[1-5][0-9]|60)s$/) const ospfTimerFields = ["hello-interval", "dead-interval", "retransmit-interval", "transmit-delay"] as const function canonicalOspfTimer(value: string): string | undefined { const ms = observedDurationMs(value) return ms !== null && ms > 0 && ms % 1000 === 0 ? `${ms / 1000}s` : undefined } const ospfLinkStateInterval = z.string().max(64).transform((value, context) => { const canonical = canonicalOspfTimer(value) if (canonical) return canonical context.addIssue({ code: "custom", message: "Укажите положительный интервал OSPF в целых секундах с единицей времени" }) return z.NEVER }) function canonicalBfdInterval(ms: number | null): string | null { if (ms === null || ms < 1 || ms > 60_000) return null const wholeMs = Math.round(ms) if (Math.abs(ms - wholeMs) > 1e-9) return null return wholeMs % 1000 === 0 ? `${wholeMs / 1000}s` : `${wholeMs}ms` } const bfdInterval = z.string().regex(/^[1-9]\d{0,4}(?:ms|s)$/).transform((value, context) => { const normalized = canonicalBfdInterval(observedDurationMs(value)) if (normalized !== null) return normalized context.addIssue({ code: "custom", message: "Укажите интервал BFD от 1ms до 60s" }) return z.NEVER }) const bfdAddressPrefix = name.transform((value, context) => { try { const prefix = canonicalBgpPolicyPrefix(value) if (!prefix.endsWith("/0")) return prefix } catch { /* The schema reports a common error for invalid prefixes. */ } context.addIssue({ code: "custom", message: "Укажите явный IPv4/IPv6-префикс BFD с ненулевой длиной" }) return z.NEVER }) const ospfNetworks = text.min(1).transform((value, context) => { try { const prefixes = value.split(",").map(canonicalBgpPolicyPrefix) if (new Set(prefixes).size !== prefixes.length) throw new Error("Duplicate prefixes") return prefixes.join(",") } catch { context.addIssue({ code: "custom", message: "Требуется список IPv4/IPv6-префиксов без повторов" }) return z.NEVER } }) const firewall = { chain: name.optional(), action: name.optional(), protocol: text.optional(), "src-address": text.optional(), "dst-address": text.optional(), "src-port": text.optional(), "dst-port": text.optional(), "in-interface": text.optional(), "out-interface": text.optional(), "src-address-list": text.optional(), "dst-address-list": text.optional(), "connection-state": text.optional(), comment: text.optional(), disabled: bool.optional(), log: bool.optional(), "log-prefix": text.optional(), } const ipv4Mangle = { ...firewall, "tcp-flags": z.string().regex(/^!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)(?:,!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)){0,7}$/) .refine(value => new Set(value.replaceAll("!", "").split(",")).size === value.split(",").length, "Флаги TCP не должны повторяться").optional(), "tcp-mss": z.string().regex(/^(?:0|[1-9]\d{0,4})(?:-(?:0|[1-9]\d{0,4}))?$/).refine(value => { const [min, max = min] = value.split("-").map(Number) return min <= max && max <= 65535 }, "Требуется значение или диапазон TCP MSS от 0 до 65535").optional(), "new-mss": integer(1, 65535).optional(), passthrough: bool.optional(), } const route = { "dst-address": name.optional(), gateway: name.optional(), distance: integer(1, 255).optional(), scope: integer(0, 255).optional(), "target-scope": integer(0, 255).optional(), "routing-table": name.optional(), "check-gateway": z.enum(["none", "ping", "arp", "bfd"]).optional(), disabled: bool.optional(), comment: text.optional(), } export interface RosResourceSpec { id: string; path: string; title: string; permission: string; fields: z.ZodObject; create: boolean; remove: boolean; requiredOnCreate?: string[]; readOnly?: boolean /** Native configuration sealed for drift checks, never accepted as writes. */ observeFields?: readonly string[] } export const rosResources: RosResourceSpec[] = [ { id: "routing_filter", path: "/routing/filter/rule", title: "Фильтры маршрутизации", permission: "mm:filters", fields: z.object({ chain: text.optional(), rule: text.optional(), comment: text.optional(), disabled: bool.optional() }).strict(), create: false, remove: false, readOnly: true }, { id: "ethernet", path: "/interface/ethernet", title: "Ethernet", permission: "mm:network", fields: z.object({ ...common, mtu: integer(68, 65535).optional(), "auto-negotiation": bool.optional() }).strict(), create: false, remove: false }, { id: "bridge", path: "/interface/bridge", title: "Bridge", permission: "mm:network", fields: z.object({ ...common, mtu: integer(68, 65535).optional(), "vlan-filtering": bool.optional(), pvid: integer(1, 4094).optional(), "frame-types": z.enum(["admit-all", "admit-only-vlan-tagged", "admit-only-untagged-and-priority-tagged"]).optional(), "ingress-filtering": bool.optional(), "protocol-mode": z.enum(["none", "stp", "rstp", "mstp"]).optional() }).strict(), observeFields: ["mvrp"], create: true, remove: true, requiredOnCreate: ["name"] }, { id: "bridge_port", path: "/interface/bridge/port", title: "Порты bridge", permission: "mm:network", fields: z.object({ bridge: name.optional(), interface: name.optional(), pvid: integer(1, 4094).optional(), "ingress-filtering": bool.optional(), "frame-types": z.enum(["admit-all", "admit-only-vlan-tagged", "admit-only-untagged-and-priority-tagged"]).optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["bridge", "interface"] }, { id: "bridge_vlan", path: "/interface/bridge/vlan", title: "Bridge VLAN membership", permission: "mm:network", fields: z.object({ bridge: name.optional(), "vlan-ids": vlanIds.optional(), tagged: text.optional(), untagged: text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["bridge", "vlan-ids"] }, { id: "vlan", path: "/interface/vlan", title: "VLAN", permission: "mm:network", fields: z.object({ ...common, interface: name.optional(), "vlan-id": integer(1, 4094).optional(), mtu: integer(68, 65535).optional(), "use-service-tag": bool.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "interface", "vlan-id"] }, { id: "ipv4_address", path: "/ip/address", title: "IPv4-адреса", permission: "mm:network", fields: z.object({ address: name.optional(), interface: name.optional(), network: name.optional(), comment: text.optional(), disabled: bool.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["address", "interface"] }, { id: "ipv6_address", path: "/ipv6/address", title: "IPv6-адреса", permission: "mm:network", fields: z.object({ address: name.optional(), interface: name.optional(), advertise: bool.optional(), comment: text.optional(), disabled: bool.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["address", "interface"] }, { id: "ipv4_route", path: "/ip/route", title: "Маршруты IPv4", permission: "mm:network", fields: z.object(route).strict(), create: true, remove: true, requiredOnCreate: ["dst-address"] }, { id: "ipv6_route", path: "/ipv6/route", title: "Маршруты IPv6", permission: "mm:network", fields: z.object(route).strict(), create: true, remove: true, requiredOnCreate: ["dst-address"] }, { id: "routing_table", path: "/routing/table", title: "Таблицы маршрутизации", permission: "mm:network", fields: z.object({ name: name.optional(), fib: bool.optional(), disabled: bool.optional() }).strict(), observeFields: ["invalid"], create: true, remove: true, requiredOnCreate: ["name"] }, { id: "routing_rule", path: "/routing/rule", title: "Правила маршрутизации", permission: "mm:network", fields: z.object({ "src-address": text.optional(), "dst-address": text.optional(), interface: text.optional(), action: z.enum(["lookup", "lookup-only-in-table", "drop", "unreachable"]).optional(), table: name.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["action"] }, { id: "vrf", path: "/ip/vrf", title: "VRF", permission: "mm:network", fields: z.object({ name: name.optional(), interfaces: text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "interfaces"] }, { id: "ip_settings", path: "/ip/settings", title: "RPF и IPv4 hash-policy", permission: "mm:network", fields: z.object({ "rp-filter": z.enum(["no", "loose", "strict"]).optional(), "ipv4-multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false }, { id: "ipv6_settings", path: "/ipv6/settings", title: "IPv6 hash-policy", permission: "mm:network", fields: z.object({ "multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false }, ...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(family === "ip" && table === "mangle" ? ipv4Mangle : firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))), { id: "gre", path: "/interface/gre", title: "GRE", permission: "mm:network", fields: greNativeFieldsSchema, create: true, remove: true, requiredOnCreate: ["name", "remote-address"] }, { id: "wireguard", path: "/interface/wireguard", title: "WireGuard", permission: "mm:network", fields: z.object({ ...common, "listen-port": integer(1, 65535).optional(), mtu: integer(68, 65535).optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name"] }, { id: "wireguard_peer", path: "/interface/wireguard/peers", title: "WireGuard peers", permission: "mm:network", fields: z.object({ interface: name.optional(), "public-key": name.optional(), "allowed-address": text.optional(), "endpoint-address": text.optional(), "endpoint-port": integer(0, 65535).optional(), "persistent-keepalive": text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["interface", "public-key", "allowed-address"] }, { id: "vxlan", path: "/interface/vxlan", title: "VXLAN", permission: "mm:network", fields: z.object({ ...common, vni: integer(1, 16777215).optional(), port: integer(1, 65535).optional(), "local-address": text.optional(), interface: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "vni"] }, { id: "ospf_template", path: "/routing/ospf/interface-template", title: "OSPF templates", permission: "mm:network", fields: z.object({ interfaces: text.optional(), networks: ospfNetworks.optional(), "prefix-list": z.union([z.literal(""), name]).optional(), area: name.optional(), "instance-id": integer(0, 255).optional(), cost: integer(1, 65535).optional(), priority: integer(0, 255).optional(), type: z.enum(["broadcast", "nbma", "ptp", "ptmp", "ptmp-broadcast", "ptp-unnumbered"]).optional(), passive: bool.optional(), "use-bfd": bool.optional(), "hello-interval": interval.optional(), "dead-interval": interval.optional(), "retransmit-interval": ospfLinkStateInterval.optional(), "transmit-delay": ospfLinkStateInterval.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["area"] }, { id: "ospf_neighbor", path: "/routing/ospf/neighbor", title: "Соседи OSPF", permission: "mm:network", fields: z.object({ "router-id": text.optional(), interface: text.optional(), state: text.optional(), address: text.optional(), area: text.optional(), instance: text.optional() }).strict(), create: false, remove: false, readOnly: true }, { id: "ospf_instance", path: "/routing/ospf/instance", title: "OSPF instances", permission: "mm:network", fields: z.object({ ...common, "router-id": ospfRouterId.optional(), version: z.enum(["2", "3"]).optional(), "routing-table": name.optional(), vrf: name.optional(), redistribute: ospfRedistribute.optional(), "originate-default": z.enum(["never", "always", "if-installed"]).optional(), ...ospfFilterFields.shape }).strict(), create: true, remove: true, requiredOnCreate: ["name", "router-id", "version", "vrf"] }, { id: "ospf_area", path: "/routing/ospf/area", title: "OSPF areas", permission: "mm:network", fields: z.object({ ...common, instance: name.optional(), "area-id": ipv4.optional(), type: z.enum(["default", "stub", "nssa"]).optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "instance", "area-id"] }, { id: "bfd_configuration", path: "/routing/bfd/configuration", title: "Правила BFD", permission: "mm:network", fields: z.object({ interfaces: name.optional(), addresses: bfdAddressPrefix.optional(), "address-list": name.optional(), vrf: name.optional(), "forbid-bfd": bool.optional(), "min-rx": bfdInterval.optional(), "min-tx": bfdInterval.optional(), multiplier: integer(2, 50).optional(), disabled: bool.optional(), comment: text.optional() }).strict(), observeFields: ["inactive", "keyring"], create: true, remove: true, requiredOnCreate: ["vrf"] }, { id: "bfd_session", path: "/routing/bfd/session", title: "Наблюдаемые сессии BFD", permission: "mm:network", fields: z.object({ "remote-address": text.optional(), "local-address": text.optional(), vrf: text.optional(), interface: text.optional(), state: text.optional() }).strict(), create: false, remove: false, readOnly: true }, { id: "bgp_session", path: "/routing/bgp/session", title: "BGP sessions", permission: "mm:bgp", fields: z.object({}).strict(), create: false, remove: false, readOnly: true }, { id: "bgp_instance", path: "/routing/bgp/instance", title: "BGP instances", permission: "mm:bgp", fields: z.object({ ...common, as: integer(1, 4294967295).optional(), "router-id": ipv4.optional(), vrf: name.optional(), "routing-table": name.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "as", "router-id", "vrf", "routing-table"] }, { id: "bgp_connection", path: "/routing/bgp/connection", title: "BGP connections", permission: "mm:bgp", fields: z.object({ ...common, instance: name.optional(), "remote.address": name.refine(value => isIP(value) > 0, "Требуется конкретный адрес BGP-соседа").optional(), "local.address": name.refine(value => isIP(value) > 0).optional(), "remote.as": integer(1, 4294967295).optional(), "local.role": z.enum(["ibgp", "ibgp-rr", "ebgp", "ebgp-provider", "ebgp-customer", "ebgp-peer", "ebgp-rs", "ebgp-rs-client"]).optional(), connect: bool.optional(), listen: bool.optional(), afi: z.enum(["ip", "ipv6", "ip,ipv6"]).optional(), "use-bfd": bool.optional(), "routing-table": name.optional(), vrf: name.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "instance", "remote.address", "remote.as", "local.address", "local.role"] }, { id: "ipsec_peer", path: "/ip/ipsec/peer", title: "IPsec peers", permission: "mm:network", fields: z.object({ ...common, address: text.optional(), "exchange-mode": z.enum(["ike2", "main", "aggressive"]).optional(), profile: name.optional(), passive: bool.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "address"] }, { id: "container", path: "/container", title: "Контейнеры", permission: "mm:network", fields: z.object({ comment: text.optional(), "start-on-boot": bool.optional() }).strict(), create: false, remove: true }, { id: "certificate", path: "/certificate", title: "Сертификаты", permission: "mm:certificates", fields: z.object({ name: name.optional(), trusted: bool.optional() }).strict(), create: false, remove: true }, ] const ospfRouterIdDependency: RosResourceSpec = { id: "ospf_router_id", path: "/routing/id", title: "OSPF Router ID dependency", permission: "mm:network", fields: z.object({}).strict(), observeFields: ["name", "id", "dynamic-id", "disabled", "inactive", "select-dynamic-id", "select-from-vrf"], create: false, remove: false, readOnly: true, } const ospfFilterSelectDependency: RosResourceSpec = { id: "routing_filter_select", path: "/routing/filter/select-rule", title: "Routing filter selection dependency", permission: "mm:filters", fields: z.object({}).strict(), create: false, remove: false, readOnly: true, } export type ConfigurationRow = Record export function isStaticArpRow(row: ConfigurationRow): boolean { const manual = row.dynamic === "false" && row.dhcp === "false" const permanent = row.status === "permanent" && [undefined, "false"].includes(row.dynamic as string | undefined) && [undefined, "false"].includes(row.dhcp as string | undefined) return (manual || permanent) && ![true, "true", "yes"].includes(row.builtin as string | boolean) && ![true, "true", "yes"].includes(row.default as string | boolean) } export interface RosStep { serverId: number; resource: string; action: "create" | "update" | "delete"; id?: string; fields: Record; placeBeforeId?: string; expectedCost?: number; expectedServerProof?: string } export function supportsRosPlacement(step: Pick) { return step.placeBeforeId === undefined || step.action === "create" && ["vrf", "bfd_configuration"].includes(step.resource) && /^\*[a-z0-9]+$/i.test(step.placeBeforeId) } export const ROS_SNAPSHOT_VERSION = 3 // OSPF cost plans and archived inverses issued before prefix-list evidence cannot be reused. export const isSingletonRosResource = (resource: string) => ["ip_settings", "ipv6_settings", "ipv6_nd_settings"].includes(resource) export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd", "ip_mangle"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION export interface RosSnapshot { serverId: number; resource: string; rows: ConfigurationRow[]; fingerprint: string; projectionVersion?: number; sourceProof?: string } const firewallAddressListResources = ["ip_address_list", "ipv6_address_list"] const routingPolicyResources = new Set(["routing_rule", "routing_filter", "routing_filter_select", "bfd_configuration", ...firewallAddressListResources, "ip_filter", "ip_nat", "ip_mangle", "ip_raw", "ipv6_filter", "ipv6_nat", "ipv6_mangle", "ipv6_raw"]) const routingPolicyPrefix = "routing_policy:" const routingPolicyCounters = new Set(["bytes", "packets"]) export function isRoutingPolicySnapshot(resource: string) { return resource.startsWith(routingPolicyPrefix) && routingPolicyResources.has(resource.slice(routingPolicyPrefix.length)) } export function readRoutingPolicySnapshot(serverId: number, resource: string, expectedSourceProof?: string, beforeRead?: () => Promise) { if (!routingPolicyResources.has(resource)) throw new McpError("UNSUPPORTED_CAPABILITY", "Неизвестный каталог политики маршрутизации", 409) return readRosSnapshot(serverId, routingPolicyPrefix + resource, beforeRead, expectedSourceProof) } async function routingPolicyRows(resource: string, payload: unknown): Promise { if (!Array.isArray(payload)) throw new McpError("STATE_CONFLICT", "Каталог политики маршрутизации не подтверждён", 409) const filterCatalog = resource === routingPolicyPrefix + "routing_filter" || resource === routingPolicyPrefix + "routing_filter_select" const bfdCatalog = resource === routingPolicyPrefix + "bfd_configuration" const addressList = firewallAddressListResources.includes(resource.slice(routingPolicyPrefix.length)) if ((filterCatalog || bfdCatalog || addressList) && (payload.length > 1000 || Buffer.byteLength(JSON.stringify(payload)) > 1048576)) throw new McpError("STATE_UNAVAILABLE", "Каталог политики маршрутизации превышает лимит", 409) const identify = await privateFingerprinter(`mcp-routing-policy-v1:${resource}`) const ids = new Set() const rows = payload.map(row => { const id = row?.[".id"] if (!row || typeof row !== "object" || Array.isArray(row) || typeof id !== "string" || !id.trim() || ids.has(id)) { throw new McpError("STATE_CONFLICT", "Неоднозначные ID каталога политики маршрутизации", 409) } ids.add(id) // Seal the native rule, including selectors outside the write schema. const configuration = Object.fromEntries(Object.entries(row).filter(([name]) => bfdCatalog || resource === routingPolicyPrefix + "routing_rule" || !routingPolicyCounters.has(name))) const timed = ![undefined, null, "", "0", "0s", "none-static"].includes(row.timeout) if (addressList && timed) configuration.timeout = "non-permanent" const proof = identify(fingerprint(configuration)) if (bfdCatalog) delete configuration[".nextid"] return { ".id": id, action: row.action ?? null, disabled: row.disabled ?? null, ...(filterCatalog ? { chain: row.chain ?? null, invalid: row.invalid ?? null, inactive: row.inactive ?? null } : {}), ...(bfdCatalog ? { dynamic: row.dynamic ?? null, builtin: row.builtin ?? null, default: row.default ?? null, ruleProof: identify(fingerprint(configuration)) } : {}), ...(addressList ? { list: row.list ?? null, address: row.address ?? null, dynamic: row.dynamic ?? null, timed } : {}), proof } }) return addressList ? rows.sort((a, b) => a[".id"].localeCompare(b[".id"])) : rows } const ipv6NdResources: Record = { ipv6_nd: { id: "ipv6_nd", path: "/ipv6/nd", title: "IPv6 Router Advertisement", permission: "mm:network", fields: ipv6NdFields, observeFields: ["invalid"], create: true, remove: true, requiredOnCreate: ["interface"] }, ipv6_nd_prefix: { id: "ipv6_nd_prefix", path: "/ipv6/nd/prefix", title: "Префиксы IPv6 ND", permission: "mm:network", fields: ipv6NdPrefixFields, observeFields: ["invalid"], create: true, remove: true, requiredOnCreate: ["interface", "prefix"] }, ipv6_nd_settings: { id: "ipv6_nd_settings", path: "/ipv6/nd/settings", title: "Глобальные настройки IPv6 ND", permission: "mm:network", fields: ipv6NdSettingsFields, create: false, remove: false }, } const ipArpResource: RosResourceSpec = { id: "ip_arp", path: "/ip/arp", title: "Статический ARP", permission: "mm:network", fields: z.object({ address: z.string().refine(value => isIP(value) === 4).optional(), interface: name.optional(), "mac-address": z.string().regex(/^(?:[0-9a-f]{2}:){5}[0-9a-f]{2}$/i).transform(value => value.toLowerCase()).optional(), published: bool.optional(), disabled: bool.optional(), }).strict(), observeFields: ["dhcp", "vrf", "comment", "status"], create: true, remove: true, requiredOnCreate: ["address", "interface"], } export function resourceById(id: string): RosResourceSpec { if (Object.hasOwn(ipv6NdResources, id)) return ipv6NdResources[id] if (id === ipArpResource.id) return ipArpResource if (id === ospfRouterIdDependency.id) return ospfRouterIdDependency if (id === ospfFilterSelectDependency.id) return ospfFilterSelectDependency if (id === "ospf_prefix_bindings") return { id, path: "/routing/ospf/interface-template?.proplist=.id,prefix-list", title: "OSPF prefix-list bindings", permission: "mm:network", fields: z.object({}).strict(), observeFields: ["prefix-list"], create: false, remove: false, readOnly: true } const interfaceDependency = interfaceDependencies.get(id) if (interfaceDependency) return { id, path: interfaceDependency.path, title: id, permission: "mm:network", fields: z.object({}).strict(), observeFields: interfaceDependency.fields, create: false, remove: false, readOnly: true } if (firewallAddressListResources.includes(id)) return { id, path: `/${id === "ip_address_list" ? "ip" : "ipv6"}/firewall/address-list`, title: "Firewall address-list dependency", permission: "mm:network", fields: z.object({}).strict(), create: false, remove: false, readOnly: true } const resource = rosResources.find(item => item.id === id) if (!resource) throw new McpError("UNSUPPORTED_CAPABILITY", "Неизвестный тип сетевого объекта", 400) return resource } const interfaceDependencies = new Map([ ["interface_list", { path: "/interface/list", fields: ["name", "include", "exclude"] }], ["interface_list_member", { path: "/interface/list/member", fields: ["list", "interface", "disabled"] }], ["interface_inventory", { path: "/interface", fields: ["name", "type", "disabled"] }], ]) export async function routerClient(serverId: number) { const [server] = await db.select().from(servers).where(eq(servers.id, serverId)).limit(1) if (!server || !server.enabled) throw new McpError("DEVICE_UNAVAILABLE", "Сервер отключён или не найден", 409) return { server, client: MikrotikClient.fromServer(server) } } /** Preserve rule/member order and the observed OSPF template listing order. * Sorting templates by ID would hide a native reordering from source proofs. */ export function isOrderedRosResource(resourceId: string): boolean { return ["ip_filter", "ip_nat", "ip_mangle", "ip_raw", "ipv6_filter", "ipv6_nat", "ipv6_mangle", "ipv6_raw", "routing_rule", "vrf", "bfd_configuration", "ospf_template"].includes(resourceId) } export function configurationRows(resource: RosResourceSpec, payload: unknown): ConfigurationRow[] { const rows = Array.isArray(payload) ? payload : payload && typeof payload === "object" ? [payload] : null if (!rows || rows.some(row => !row || typeof row !== "object" || Array.isArray(row))) throw new McpError("STATE_CONFLICT", "Недостоверная конфигурация RouterOS", 409) const fields = Object.keys(resource.fields.shape) // RouterOS creates/removes IPv6 link-local rows with interface runtime state. // They cannot be configured independently and must not invalidate a sealed // inverse plan when its own GRE is disabled. Explicit addresses remain sealed. const configuration = rows.filter(row => !(resource.id === "ipv6_address" && [true, "true"].includes((row as ConfigurationRow).dynamic as boolean | string) && /^fe80:/i.test(String((row as ConfigurationRow).address))) // These rows are generated from bridge/port PVID, not independently // configurable VLAN entries. Their inputs remain sealed in bridge/ports. && !(resource.id === "bridge_vlan" && [true, "true", "yes"].includes((row as ConfigurationRow).dynamic as boolean | string))) const selectedRows = configuration.map(row => { const selected = Object.fromEntries(Object.entries(row as ConfigurationRow).filter(([key]) => [".id", "dynamic", "builtin", "default", ...fields, ...(resource.observeFields ?? [])].includes(key))) // RouterOS 7.24.5 returns an explicit empty fib flag for non-FIB tables. // Normalize only this observed field; missing values must remain unknown. if (resource.id === "routing_table" && selected.fib === "") selected.fib = "false" if (resource.id === "vrf" && selected.interfaces !== undefined) selected.interfaces = canonicalVrfMembers(selected.interfaces) if (Object.hasOwn(ipv6NdResources, resource.id)) normalizeIpv6NdRow(resource.id, selected) if (resource.id === "ip_arp") { if (typeof selected["mac-address"] === "string") selected["mac-address"] = selected["mac-address"].toLowerCase() for (const key of ["dynamic", "dhcp", "disabled", "published"]) { const value = selected[key] const flag = typeof value === "boolean" ? value : typeof value === "string" ? observedBoolean(value) : null if (flag !== null) selected[key] = String(flag) } // Reachability status and learned MAC addresses are not static configuration. if (selected.status !== "permanent" || selected.dynamic !== undefined && selected.dhcp !== undefined) delete selected.status if (selected.dynamic === "true" || selected.dhcp === "true") delete selected["mac-address"] } if (resource.id === "ospf_template") { if (selected.networks !== undefined) { const networks = ospfNetworks.safeParse(selected.networks) if (networks.success) selected.networks = networks.data } for (const field of ospfTimerFields) { const observed = selected[field] if (typeof observed !== "string") continue selected[field] = canonicalOspfTimer(observed) ?? observed } } if (resource.id === "ospf_instance" && selected.redistribute !== undefined) { const sources = ospfRedistribute.safeParse(selected.redistribute) if (sources.success) selected.redistribute = sources.data } if (resource.id === "bfd_configuration" && selected.addresses !== undefined) { const prefix = bfdAddressPrefix.safeParse(selected.addresses) if (prefix.success) selected.addresses = prefix.data } if (resource.id === "bfd_configuration") for (const field of ["min-rx", "min-tx"]) { const observed = selected[field] if (typeof observed !== "string") continue selected[field] = canonicalBfdInterval(observedDurationMs(observed)) ?? observed } if (["bridge_port", "bridge_vlan"].includes(resource.id) && selected.comment === undefined) selected.comment = "" if (resource.id === "bridge_vlan") { try { for (const field of ["vlan-ids", "tagged", "untagged"]) selected[field] = canonicalBridgeVlanValue(field, selected[field]) } catch { throw new McpError("STATE_CONFLICT", "Недостоверная конфигурация VLAN membership", 409) } } return selected }) // Reordering an ordered catalog changes configuration even with unchanged rows. return isOrderedRosResource(resource.id) ? selectedRows : selectedRows.sort((a, b) => String(a[".id"] ?? a.name ?? "").localeCompare(String(b[".id"] ?? b.name ?? ""))) } export async function readRosSnapshot(serverId: number, resourceId: string, beforeRead: () => Promise = async () => {}, expectedSourceProof?: string): Promise { await beforeRead() const policy = isRoutingPolicySnapshot(resourceId) const resource = resourceById(policy ? resourceId.slice(routingPolicyPrefix.length) : resourceId), { client, server } = await routerClient(serverId) const sourceProof = await rosSnapshotSourceProof(server) if (expectedSourceProof !== undefined && expectedSourceProof !== sourceProof) throw new McpError("STATE_CONFLICT", "Источник сетевого снимка изменился до опроса", 409) const checkSource = async () => { await beforeRead() if (await rosSnapshotSourceProof((await routerClient(serverId)).server) !== sourceProof) throw new McpError("STATE_CONFLICT", "Источник сетевого снимка изменился во время чтения", 409) } await checkSource() const payload = resourceId === "ospf_template" ? await client.getOspfInterfaceTemplates(checkSource) : ["ospf_instance", "ospf_area", "bgp_instance", "bgp_connection"].includes(resourceId) ? await readOspfEffectiveDisabled(await client.get(resource.path), async id => { await checkSource() return client.post(resource.path + "/get", { ".id": id, "value-name": "disabled" }) }) : await readRouterOsSnapshotGet({ client, path: resource.path, assertCurrent: checkSource }) await checkSource() if (resourceId === "ip_arp" && (!Array.isArray(payload) || payload.length > 10000 || Buffer.byteLength(JSON.stringify(payload)) > 1048576)) throw new McpError("STATE_UNAVAILABLE", "Не подтверждён ограниченный каталог ARP", 409) if (Object.hasOwn(ipv6NdResources, resourceId) && (resourceId !== "ipv6_nd_settings" && (!Array.isArray(payload) || payload.length > 1000) || Buffer.byteLength(JSON.stringify(payload) ?? "") > 1048576)) throw new McpError("STATE_UNAVAILABLE", "Каталог IPv6 ND превышает предел или недоступен", 409) if (interfaceDependencies.has(resourceId) && (!Array.isArray(payload) || payload.length > 1000 || Buffer.byteLength(JSON.stringify(payload)) > 1048576)) { throw new McpError("STATE_UNAVAILABLE", "Каталог интерфейсов OSPF превышает предел или недоступен", 409) } const rows = policy ? await routingPolicyRows(resourceId, payload) : configurationRows(resource, payload) if (resourceId === "ip_arp") { const ids = rows.map(row => row[".id"]) if (ids.some(id => typeof id !== "string" || !/^\*[a-z0-9]+$/i.test(id)) || new Set(ids).size !== ids.length) throw new McpError("STATE_UNAVAILABLE", "Недостоверные ID каталога ARP", 409) } if (resourceId === "ipv6_nd_settings") { if (rows.length !== 1 || rows[0][".id"] !== undefined) throw new McpError("STATE_UNAVAILABLE", "Не подтверждены глобальные настройки IPv6 ND", 409) } else if (Object.hasOwn(ipv6NdResources, resourceId)) { const ids = rows.map(row => row[".id"]) if (ids.some(id => typeof id !== "string" || !/^\*[a-z0-9]+$/i.test(id)) || new Set(ids).size !== ids.length) throw new McpError("STATE_UNAVAILABLE", "Недостоверные ID каталога IPv6 ND", 409) } if (resourceId === "ospf_prefix_bindings") { const ids = rows.map(row => row[".id"]) if (!Array.isArray(payload) || rows.length > 1000 || ids.some(id => typeof id !== "string" || !/^\*[a-z0-9]+$/i.test(id)) || new Set(ids).size !== ids.length || rows.some(row => row["prefix-list"] !== undefined && typeof row["prefix-list"] !== "string")) { throw new McpError("STATE_UNAVAILABLE", "Не подтверждены привязки prefix-list OSPF", 409) } } if (interfaceDependencies.has(resourceId)) { const ids = rows.map(row => row[".id"]) if (ids.some(id => typeof id !== "string" || !/^\*[a-z0-9]+$/i.test(id)) || new Set(ids).size !== ids.length) { throw new McpError("STATE_UNAVAILABLE", "Недостоверные ID каталога интерфейсов OSPF", 409) } } if (resourceId === ospfRouterIdDependency.id) { if (!Array.isArray(payload) || rows.length > 10000 || Buffer.byteLength(JSON.stringify(payload)) > 1048576 || rows.some(row => typeof row[".id"] !== "string" || !/^\*[a-z0-9]+$/i.test(row[".id"])) || new Set(rows.map(row => row[".id"])).size !== rows.length) { throw new McpError("STATE_UNAVAILABLE", "Недостоверный каталог Router ID", 409) } let getters = 0 for (const row of rows) for (const flag of ["disabled", "inactive"]) { if (row[flag] !== undefined) continue if (++getters > 128) throw new McpError("STATE_UNAVAILABLE", "Превышен бюджет чтения Router ID", 409) await checkSource() const response = await client.post<{ ret?: string }>(resource.path + "/get", { ".id": String(row[".id"]), "value-name": flag }) const value = typeof response?.ret === "string" ? observedBoolean(response.ret) : null if (value === null) throw new McpError("STATE_UNAVAILABLE", "Не подтверждено состояние Router ID", 409) row[flag] = String(value) } await checkSource() } return { serverId, resource: resourceId, rows, fingerprint: fingerprint(rows), projectionVersion: rosSnapshotVersion(resourceId), sourceProof } } export async function rosSnapshotSourceProof(server: Awaited>["server"]): Promise { return privateSecretFingerprint(fingerprint({ id: server.id, enabled: server.enabled, host: server.host, port: server.port, useSsl: server.useSsl, verifySsl: server.verifySsl, username: server.username, password: server.password, epoch: server.routingEndpointEpoch }), "mcp-ros-snapshot-source-v3") } export function validateRosStep(resource: RosResourceSpec, action: RosStep["action"], fields: unknown, id?: string) { assertNoCallerCreateId({ action, id }) if (isSingletonRosResource(resource.id) && id !== undefined) throw new McpError("INVALID_INPUT", "Настройки устройства не имеют RouterOS ID строки", 400) if (resource.readOnly || action === "create" && !resource.create || action === "delete" && !resource.remove) throw new McpError("UNSUPPORTED_CAPABILITY", "Действие не поддерживается для объекта", 400) if (action !== "create" && !isSingletonRosResource(resource.id) && !id) throw new McpError("INVALID_INPUT", "Требуется стабильный RouterOS ID", 400) const parsed = resource.fields.parse(fields ?? {}) as Record if (action === "create" && resource.requiredOnCreate?.some(field => parsed[field] === undefined)) throw new McpError("INVALID_INPUT", "Не заполнены обязательные поля создания", 400) if (resource.id === "bfd_configuration" && action === "create") { if (!parsed.interfaces && !parsed["address-list"]) throw new McpError("INVALID_INPUT", "Для правила BFD укажите интерфейсы или address-list", 400) if (parsed.interfaces && parsed.addresses === undefined && String(parsed.interfaces).split(",").some(value => !value.trim() || /^(?:all|none)$/i.test(value.trim()))) { throw new McpError("INVALID_INPUT", "Для правила BFD без адреса укажите конкретные интерфейсы", 400) } } if (resource.id === "ospf_template" && typeof parsed.interfaces === "string" && !parsed.interfaces.trim()) throw new McpError("INVALID_INPUT", "Пустой список интерфейсов OSPF", 400) if (resource.id === "ospf_template" && action !== "update" && parsed["prefix-list"] === "") throw new McpError("INVALID_INPUT", "Снятие prefix-list выполняется обновлением шаблона OSPF", 400) if (resource.id === "ospf_template" && action === "create" && !parsed.networks && !String(parsed.interfaces ?? "").trim()) throw new McpError("INVALID_INPUT", "Укажите interfaces или networks для шаблона OSPF", 400) if (action !== "delete" && !Object.keys(parsed).length) throw new McpError("INVALID_INPUT", "Нет параметров для изменения", 400) return Object.fromEntries(Object.entries(parsed).map(([key, value]) => [key, resource.id === "vrf" && key === "interfaces" ? canonicalVrfMembers(value) : String(value)])) } /** An unset is a separate native command and must have its own intent/checkpoint. */ export function splitOspfUnsetUpdate(step: RosStep): RosStep[] { if (step.resource !== "ospf_template" || step.action !== "update") return [step] const fields = { ...step.fields } const steps: RosStep[] = [] // Detach the v3-only prefix list before any change of OSPF area. if (fields["prefix-list"] === "") { steps.push({ ...step, fields: { "prefix-list": "" } }) delete fields["prefix-list"] } const unsetPassive = fields.passive === "false" if (unsetPassive) delete fields.passive if (Object.keys(fields).length) steps.push({ ...step, fields }) if (unsetPassive) steps.push({ ...step, fields: { passive: "false" } }) return steps.length ? steps : [step] } export async function executeRosStep(step: RosStep): Promise { assertNoCallerCreateId(step) const resource = resourceById(step.resource) if (!supportsRosPlacement(step)) throw new McpError("INVALID_INPUT", "Недопустимая позиция создания записи", 400) // These resources require full private dependency proofs. Retired generic // steps (including previously approved inverses) must not bypass the shared // services by reaching the raw native dispatcher. if (["ipsec_peer", "certificate"].includes(resource.id)) throw new McpError("UNSUPPORTED_CAPABILITY", "IPsec peer и сертификаты изменяются только через сервис с полным proof зависимостей; старый native шаг недоступен", 409) if (resource.id === "vrf") throw new McpError("UNSUPPORTED_CAPABILITY", "VRF изменяется только через production companion executor; raw/legacy шаг недоступен", 409) const singletonSettings = isSingletonRosResource(resource.id) if (singletonSettings && (step.action !== "update" || step.id !== undefined)) throw new McpError("INVALID_INPUT", "Настройки устройства поддерживают только изменение без RouterOS ID строки", 400) const { client, server } = await routerClient(step.serverId) if (singletonSettings) return client.post(resource.path + "/set", step.fields) if (resource.id === "wireguard" && step.action === "delete") { const { deleteWireguardInterfaceGuarded } = await import("../../services/wireguard-interface-delete.js") const { assertVerifiedConfigurationAccess } = await import("../../services/config-mutation-policy.js") return deleteWireguardInterfaceGuarded(server, step.id!, undefined, assertVerifiedConfigurationAccess, { cascade: false, recordRevision: false }) } if (resource.id === "wireguard_peer" && step.action === "update") { const { updateWireguardPeer, wireguardPeerNativeUpdate } = await import("../../services/wireguard-peer-update.js") const { assertVerifiedConfigurationAccess } = await import("../../services/config-mutation-policy.js") return updateWireguardPeer(server, step.id!, wireguardPeerNativeUpdate(step.fields), undefined, assertVerifiedConfigurationAccess, { recordRevision: false }) } if (resource.id === "wireguard_peer" && step.action === "delete") { const { deleteWireguardPeer } = await import("../../services/wireguard-peer-delete.js") const { assertVerifiedConfigurationAccess } = await import("../../services/config-mutation-policy.js") return deleteWireguardPeer(server, step.id!, undefined, assertVerifiedConfigurationAccess, { recordRevision: false }) } if (resource.id === "ospf_template" && step.action === "update" && Object.keys(step.fields).length === 1 && step.fields.cost !== undefined && step.id) { await client.setOspfInterfaceTemplateCost(step.id, Number(step.fields.cost), step.expectedCost, step.expectedServerProof) return { cost: step.fields.cost, readBackVerified: true } } if(resource.id==="gre"&&(step.action==="delete"||step.action==="update"&&step.fields.name!==undefined)){ const {mutateGreNativeTunnel,greNativeMutationSchema}=await import("../../services/gre-native-mutation.js") const fields=Object.fromEntries(Object.entries(step.fields).map(([key,value])=>[key,key==="disabled"?["true","yes"].includes(value)?true:["false","no"].includes(value)?false:value:key==="mtu"&&value!=="auto"?Number(value):value])) const mutation=greNativeMutationSchema.parse({operation:step.action,id:step.id,...(step.action==="update"?{fields}:{})}) const receipt=await mutateGreNativeTunnel(server,mutation,undefined,{recordRevision:false}) if(!receipt.verified)throw new McpError("VERIFICATION_FAILED","Native GRE изменение не подтверждено; повтор запрещён",409) return receipt } if (resource.id === "container" && step.action === "delete") { const { removeStoppedContainer } = await import("../../services/container-removal.js") await removeStoppedContainer(client, step.id!) return { deleted: true } } if (resource.id === "ospf_template" && step.action === "update") { const field = step.fields["prefix-list"] === "" ? "prefix-list" : step.fields.passive === "false" ? "passive" : undefined if (field) { if (!step.id || Object.keys(step.fields).length !== 1) throw new McpError("INVALID_INPUT", "Снятие свойства OSPF требует отдельного шага плана", 400) return client.post(resource.path + "/unset", { ".id": step.id, "value-name": field }) } } if (step.action === "create") { const fields = resource.id === "ospf_template" && step.fields.passive === "false" ? Object.fromEntries(Object.entries(step.fields).filter(([key]) => key !== "passive")) : step.fields return client.put(resource.path, { ...fields, ...(step.placeBeforeId ? { "place-before": step.placeBeforeId } : {}) }) } const destination = step.id ? `${resource.path}/${encodeURIComponent(step.id)}` : resource.path if (step.action === "delete") return client.delete(destination) return client.patch(destination, step.fields) }