Files
MikrotikManager/backend/src/modules/mcp/wireguard-interface-delete-actions.ts
T

56 lines
6.9 KiB
TypeScript

import { z } from "zod"
import { pool } from "../../db/index.js"
import { hasPermission } from "../../lib/permissions.js"
import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
import { readWireguardInterfaceDeleteState, planWireguardInterfaceDelete, projectWireguardInterfaceDeleteCommand, wireguardInterfaceDeleteProof, deleteWireguardInterfaceGuarded } from "../../services/wireguard-interface-delete.js"
import { effectiveMcpConnection } from "./store.js"
import { routerClient } from "./resources.js"
import { fingerprint, McpError } from "./security.js"
import { registerMcpService } from "./service-registry.js"
import type { ActionContext, ChangeEvidence } from "./action-types.js"
import type { add } from "./actions.js"
const schema = z.object({ serverId: z.number().int().positive().safe(), interfaceId: z.string().regex(/^\*[a-z0-9]+$/i).max(100) }).strict()
export async function prepareWireguardInterfaceDeletion(serverId: number, interfaceId: string, context: ActionContext, cascade = true): Promise<ChangeEvidence> {
schema.parse({ serverId, interfaceId })
const authorize = async () => {
if (context.signal?.aborted) throw new McpError("READ_CANCELLED", "Подготовка удаления WireGuard отменена", 409)
const current = await effectiveMcpConnection(context.principal)
if (!hasPermission(current.owner_permissions, "mm:network:write") || !hasPermission(current.policy.permissions, "mm:network:write")) throw new McpError("PERMISSION_DENIED", "Право изменения сети отозвано", 403)
if (fingerprint(current.policy) !== fingerprint(context.connection.policy) || fingerprint(current.owner_permissions) !== fingerprint(context.connection.owner_permissions)) throw new McpError("RESET_REQUIRED", "Допуск изменился; подготовьте план заново", 409)
}
await authorize()
const { server } = await routerClient(serverId), state = await readWireguardInterfaceDeleteState(server, interfaceId, authorize), commands = planWireguardInterfaceDelete(state, interfaceId, cascade)
const objects: ChangeEvidence["objects"] = [{ kind: "server", id: String(serverId), serverId }, ...commands.map(command => ({ kind: ({ interfaces: "wireguard", peers: "wireguard_peer", ipv4: "ipv4_address", ipv6: "ipv6_address" })[command.resource], id: command.id, serverId }))]
const protections = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1) LIMIT 1001", [String(serverId)])
if (protections.rows.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Превышен предел защит WireGuard", 409)
for (const { object_ref: ref } of protections.rows) objects.push({ kind: ref.kind, id: ref.id, serverId })
const prefixes = [state.proof]
let projected = state
for (const command of commands) { projected = projectWireguardInterfaceDeleteCommand(projected, command); prefixes.push(await wireguardInterfaceDeleteProof(projected)) }
await authorize()
return { target: { scope: "servers", serverIds: [serverId] }, objects, snapshots: [], requiresHuman: true, mutationCost: commands.length + 1,
before: { proof: state.proof }, steps: [{ kind: "service", service: "network.wireguard.interfaces.delete", input: { serverId, interfaceId, cascade, commandSummary: commands.map(({ method, path, id }) => ({ method, path, id })), expectedProof: state.proof, expectedStageProofs: prefixes, proofRevision: 1, beforeFingerprint: fingerprint({ proof: state.proof }) } }],
warnings: [cascade ? "Явный каскад: сначала отключение интерфейса при необходимости, затем его peers и статические IPv4/IPv6 адреса, интерфейс удаляется последним. Передача трафика будет прервана." : "Native DELETE удаляет только пустой интерфейс. Каскадного удаления peers и адресов этот alias не разрешает.", `Подготовлено ${commands.length} native-команд и отдельная запись ревизии. Команды выполняются последовательно с проверкой состояния; операция не атомарна.`, "Маршруты, протоколы, firewall, привязки и NetFlow не изменяются каскадно: используемый ими интерфейс требует отдельных предварительных планов.", "Потеря ответа останавливает каскад без повтора. Доступна read-only сверка исходного, промежуточного и желаемого состояния; универсального обратного плана нет."] }
}
export function registerWireguardInterfaceDeleteActions(register: typeof add) {
const current = async (input: Record<string, unknown>) => ({ proof: (await readWireguardInterfaceDeleteState((await routerClient(Number(input.serverId))).server, String(input.interfaceId))).proof })
registerMcpService("network.wireguard.interfaces.delete", { current,
execute: async input => deleteWireguardInterfaceGuarded((await routerClient(Number(input.serverId))).server, String(input.interfaceId), String(input.expectedProof), assertVerifiedConfigurationAccess, { cascade: input.cascade === true }),
verify: async (input, result) => {
const receipt = result as { verified?: boolean; afterProof?: string } | null
return receipt?.verified === true && (await current(input)).proof === receipt.afterProof
},
reconcile: async (input, authorize) => {
if (input.proofRevision !== 1 || !Array.isArray(input.expectedStageProofs) || input.expectedStageProofs.length < 2 || input.expectedStageProofs.length > 51 || input.expectedStageProofs.some(value => typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value))) throw new McpError("UNSUPPORTED_CAPABILITY", "Нет совместимых prefix proofs для сверки каскада WireGuard", 409)
const state = await readWireguardInterfaceDeleteState((await routerClient(Number(input.serverId))).server, String(input.interfaceId), authorize)
await authorize()
const prefix = input.expectedStageProofs.indexOf(state.proof)
return { matchesOriginalState: prefix === 0, matchesDesiredState: prefix === input.expectedStageProofs.length - 1, matchesExpectedPrefixState: prefix >= 0, verifiedPrefixCommands: prefix < 0 ? null : prefix }
},
})
register("network.wireguard.interfaces.delete", "mm_wireguard_interface_remove_plan", "Удалить WireGuard с явным каскадом peers и статических адресов", "network", "mm:network:write", "write", "servers", schema, {
prepare: (input, context) => prepareWireguardInterfaceDeletion(Number(input.serverId), String(input.interfaceId), context),
})
}