Files
MikrotikManager/backend/src/modules/mcp/arp-actions.ts
T

67 lines
5.6 KiB
TypeScript

import { z } from "zod"
import { isIP } from "node:net"
import type { add } from "./actions.js"
import type { ChangeEvidence } from "./action-types.js"
import { isStaticArpRow, readRosSnapshot, resourceById, validateRosStep } from "./resources.js"
import { ospfInterfaceResources } from "./routing-dependencies.js"
import { McpError } from "./security.js"
const serverId = z.number().int().positive().safe()
const rowId = z.string().regex(/^\*[a-z0-9]+$/i).max(200)
export function registerArpActions(register: typeof add) {
const resource = resourceById("ip_arp")
for (const action of ["create", "update", "delete"] as const) {
const schema = z.object({ serverId, ...(action === "create" ? {} : { id: rowId }), ...(action === "delete" ? {} : { fields: resource.fields }) }).strict()
register(`ros.ip_arp.${action}`, `mm_ip_arp_${action}_plan`, `${resource.title}: ${action}`, "network", "mm:network:write", "write", "servers", schema, {
prepare: async input => {
const sid = Number(input.serverId), id = typeof input.id === "string" ? input.id : undefined
const fields = validateRosStep(resource, action, input.fields ?? {}, id)
const before = await readRosSnapshot(sid, resource.id)
const current = action === "create" ? undefined : before.rows.find(row => row[".id"] === id)
if (action !== "create" && !current) throw new McpError("NOT_FOUND", "Запись ARP не найдена", 404)
if (current && !isStaticArpRow(current)) throw new McpError("PROTECTED_OBJECT", "План изменяет только подтверждённую статическую запись ARP", 409)
if (action === "update" && Object.keys(fields).some(key => {
const value = current?.[key], validator = resource.fields.shape[key]
if (value === undefined || value === null) return true
const previous = validator.safeParse(true).success && (value === "true" || value === "false") ? value === "true" : value
return !validator.safeParse(previous).success
})) throw new McpError("STATE_UNAVAILABLE", "Не подтверждено прежнее значение ARP для обратного плана", 409)
const desired = { ...current, ...fields }
if (typeof desired.interface !== "string" || !desired.interface || typeof desired.address !== "string" || isIP(desired.address) !== 4) throw new McpError("STATE_UNAVAILABLE", "Не подтверждена привязка записи ARP", 409)
if (action !== "delete") {
const mac = desired["mac-address"], proxy = desired.published === "true"
const validMac = typeof mac === "string" && /^(?:[0-9a-f]{2}:){5}[0-9a-f]{2}$/.test(mac) && Number.parseInt(mac.slice(0, 2), 16) % 2 === 0
if ((!validMac || mac === "00:00:00:00:00:00") && !(proxy && (mac === undefined || mac === "00:00:00:00:00:00"))) throw new McpError("INVALID_INPUT", "Требуется индивидуальный MAC-адрес или явная публикация proxy ARP", 400)
if (before.rows.some(row => row[".id"] !== id && row.address === desired.address && (row.interface === desired.interface || typeof row.interface !== "string" || !row.interface))) throw new McpError("STATE_CONFLICT", "Адрес ARP уже занят или его привязка не подтверждена", 409)
}
const names = new Set([desired.interface, current?.interface].filter((name): name is string => typeof name === "string" && name.length > 0))
const inventory = await readRosSnapshot(sid, "interface_inventory", undefined, before.sourceProof)
const objects: ChangeEvidence["objects"] = [{ kind: resource.id, id: id ?? "new", serverId: sid }]
const snapshots = [before, inventory]
const addRef = (kind: string, value: unknown) => {
if (typeof value !== "string" || !/^\*[a-z0-9]+$/i.test(value)) throw new McpError("STATE_UNAVAILABLE", "Не подтверждён ID интерфейса ARP", 409)
objects.push({ kind, id: value, serverId: sid })
}
for (const name of names) {
const rows = inventory.rows.filter(row => row.name === name)
if (rows.length !== 1) throw new McpError("STATE_CONFLICT", "Интерфейс ARP отсутствует или неоднозначен", 409)
addRef("interface", rows[0][".id"])
}
for (const kind of ospfInterfaceResources) {
const snapshot = await readRosSnapshot(sid, kind, undefined, before.sourceProof)
snapshots.push(snapshot)
for (const row of snapshot.rows) if (names.has(String(row.name))) addRef(kind, row[".id"])
}
const vrfs = await readRosSnapshot(sid, "vrf", undefined, before.sourceProof)
snapshots.push(vrfs)
const assigned = new Set([...names].map(name => vrfs.rows.find(row => typeof row.interfaces === "string" && row.interfaces.split(",").map(member => member.trim()).some(member => member === "all" || member === name))))
for (const vrf of assigned) if (vrf) addRef("vrf", vrf[".id"])
return { target: { scope: "servers", serverIds: [sid] }, objects, snapshots, requiresHuman: true,
steps: [{ kind: "ros", step: { serverId: sid, resource: resource.id, action, id, fields } }],
warnings: ["Изменение статической записи меняет разрешение адреса IPv4 в MAC на указанном интерфейсе.", ...(desired.published === "true" ? ["Публикация включает ответы proxy ARP для этого адреса при наличии активного маршрута."] : [])] }
},
})
}
}