import { isIP } from "node:net" import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js" import { pool } from "../db/index.js" import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js" import { fingerprint, McpError, privateFingerprinter } from "../modules/mcp/security.js" import { readWireguardPeerDeletionState, wireguardPeerDeletionTarget, wireguardConfigurationRows, type WireguardPeerDeletionState } from "./wireguard-peer-delete.js" import { greStableRows, assertGreDeleteDependencies } from "./gre-mutation-state.js" import { observedBoolean } from "./ospf-observed-values.js" import { isRouterOsPreHeaderGetReset, MikrotikClient } from "./mikrotik.js" import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js" import { executeGuardedApplicationWrite } from "./config-mutation-policy.js" import { captureAndAppendRevision } from "./config-revisions.js" import { captureWireguardSnapshot } from "./wireguard-live.js" import { sameWireguardEndpoint } from "./wireguard-source.js" import { wireguardInterfaceDependencyPaths, wireguardInterfaceRuntimeDependencyPaths } from "./routeros-native-paths.js" import { markWireguardGetFailure, markWireguardReadFailure } from "./wireguard-read-diagnostic.js" export { wireguardInterfaceDependencyPaths } from "./routeros-native-paths.js" type Row = Record export interface WireguardInterfaceDeleteState { base: WireguardPeerDeletionState; ipv4: Row[]; ipv6: Row[]; dependencies: Record; filters: { id: number; gatewayTunnelId: string; gateway: string }[]; proof: string; } export interface WireguardInterfaceDeleteCommand { method: "PATCH" | "DELETE"; path: string; resource: "interfaces" | "peers" | "ipv4" | "ipv6"; id: string; body?: Record } const runtimePaths = new Set(wireguardInterfaceRuntimeDependencyPaths) const fail = (code: string, message: string) => new McpError(code, message, ["STATE_UNAVAILABLE", "MUTATION_OUTCOME_UNKNOWN", "VERIFICATION_FAILED"].includes(code) ? 502 : 409) const automaticLinkLocal = (row: Row) => observedBoolean(row.dynamic) === true && /^fe80:/i.test(row.address ?? "") const ordered = (path: string) => ["/ip/vrf", "/routing/rule", "/routing/filter/rule", "/routing/bfd/configuration"].includes(path) || /^\/(?:ip|ipv6)\/firewall\//.test(path) const interfaceRows = (rows: Row[]) => greStableRows(wireguardConfigurationRows(rows)) export function wireguardInterfaceDeleteValue(state: Omit) { const wgNames = new Set(state.base.interfaces.map(row => row.name)) return { source: state.base.serverProof, interfaces: interfaceRows(state.base.interfaces), peers: wireguardConfigurationRows(state.base.peers), bindings: state.base.bindings, flow: state.base.flow, ipv4: greStableRows(state.ipv4.filter(row => observedBoolean(row.dynamic) !== true)), ipv6: greStableRows(state.ipv6.filter(row => observedBoolean(row.dynamic) !== true)), filters: state.filters, dependencies: Object.fromEntries(Object.entries(state.dependencies).map(([path, rows]) => [path, runtimePaths.has(path) ? "runtime-inspected-not-sealed" : greStableRows(rows.filter(row => observedBoolean(row.dynamic) !== true && !(path === "/interface" && wgNames.has(row.name))).map(row => path === "/interface" ? { ".id": row[".id"], name: row.name, type: row.type ?? "" } : /\/(?:ip|ipv6)\/dhcp-client$/.test(path) ? Object.fromEntries(Object.entries(row).filter(([key]) => !["status", "expires-after", "address", "prefix", "gateway", "dhcp-server", "dhcp-server-address", "dhcp-server-duid", "primary-dns", "secondary-dns"].includes(key))) : row), ordered(path))])) } } export async function wireguardInterfaceDeleteProof(state: Omit) { return (await privateFingerprinter("wireguard-interface-delete-v1"))(fingerprint(wireguardInterfaceDeleteValue(state))) } async function source(server: ServerRow, authorize: () => Promise) { await authorize() const fresh = await getServerRowById(server.id) if (!fresh || !sameWireguardEndpoint(fresh, server)) throw fail("STATE_CONFLICT", "Источник WireGuard изменился") } function nativeRows(raw: unknown, required: string[] = []): Row[] { if (!Array.isArray(raw) || raw.length > 2000 || raw.some(row => !row || typeof row !== "object" || Array.isArray(row) || Object.values(row).some(value => typeof value !== "string") || typeof row[".id"] !== "string" || !/^\*[a-z0-9]+$/i.test(row[".id"]) || required.some(key => !row[key]?.trim()))) throw fail("STATE_UNAVAILABLE", "Недостоверный каталог зависимостей WireGuard") if (new Set(raw.map(row => row[".id"])).size !== raw.length) throw fail("STATE_UNAVAILABLE", "Повторяющиеся ID в каталоге WireGuard") return raw as Row[] } /** Retry at most two distinct catalogue GETs per capture, with fresh source authority. */ export function createWireguardDependencyReader(client: Pick, authorizeSource: () => Promise, now = () => performance.now()) { const timeoutMs = 10_000, maxBytes = 1_048_576 const unavailable = () => fail("STATE_UNAVAILABLE", "Не прочитан обязательный источник зависимостей WireGuard") const retriedPaths = new Set() return async (path: string): Promise => { await authorizeSource() const deadline = now() + timeoutMs try { return await client.get(path, timeoutMs, undefined, maxBytes) } catch (error) { const retryableCatalogue = path === "/ip/address" || path === "/ipv6/address" || wireguardInterfaceDependencyPaths.includes(path) if (retriedPaths.size >= 2 || retriedPaths.has(path) || !retryableCatalogue || !isRouterOsPreHeaderGetReset(error) || now() >= deadline) throw markWireguardGetFailure(unavailable(), path, 1, error) } retriedPaths.add(path) await authorizeSource() const remaining = Math.floor(deadline - now()) if (remaining < 1) throw markWireguardReadFailure(unavailable(), path, 2, "read-deadline") try { return await client.get(path, remaining, undefined, maxBytes) } catch (error) { throw markWireguardGetFailure(unavailable(), path, 2, error) } } } export async function readWireguardInterfaceDeleteState(server: ServerRow, id: string, authorize: () => Promise = async () => {}): Promise { const base = await readWireguardPeerDeletionState(server, authorize), client = MikrotikClient.fromServer(server) const readDependency = createWireguardDependencyReader(client, () => source(server, authorize)) let totalRows = base.interfaces.length + base.peers.length, bytes = Buffer.byteLength(JSON.stringify([base.interfaces, base.peers])) const read = async (path: string, required: string[] = []) => { const raw = await readDependency(path) bytes += Buffer.byteLength(JSON.stringify(raw)) let rows: Row[] try { rows = nativeRows(raw, required) } catch (error) { if (!(error instanceof McpError)) throw error throw markWireguardReadFailure(error, path, undefined, Array.isArray(raw) && raw.length > 2000 ? "catalogue-limit" : "invalid-catalogue") } totalRows += rows.length if (bytes > 1048576 || totalRows > 10000) throw markWireguardReadFailure(fail("STATE_UNAVAILABLE", "Превышен предел зависимостей WireGuard: 10000 строк / 1 МиБ"), path, undefined, "catalogue-limit") return rows } const ipv4 = await read("/ip/address", ["address", "interface"]), ipv6 = await read("/ipv6/address", ["address", "interface"]) const dependencies: Record = {} for (const path of wireguardInterfaceDependencyPaths) dependencies[path] = await read(path, path === "/interface" ? ["name"] : []) const parent = base.interfaces.find(row => row[".id"] === id) if (parent && [...ipv4, ...ipv6].filter(row => [parent.name, id].includes(row.interface) && !automaticLinkLocal(row)).length + base.peers.filter(row => [parent.name, id].includes(row.interface)).length > 49) throw fail("STATE_UNAVAILABLE", "Каскад WireGuard превышает предел зависимых объектов") if (parent) for (const [path, rows] of [["/ip/address", ipv4], ["/ipv6/address", ipv6]] as const) for (const row of rows.filter(row => [parent.name, id].includes(row.interface))) { try { canonicalBgpPolicyPrefix(row.address) if (isIP(row.address.split("/")[0]) !== (path === "/ip/address" ? 4 : 6)) throw new Error("family") } catch { throw fail("STATE_UNAVAILABLE", "Не подтверждён адрес выбранного WireGuard") } if (row.dynamic === undefined) { await source(server, authorize) let ret: unknown try { ret = await client.post(path + "/get", { ".id": row[".id"], "value-name": "dynamic" }) } catch { throw fail("STATE_UNAVAILABLE", "Не подтверждено происхождение адреса WireGuard") } if (!ret || typeof ret !== "object" || !("ret" in ret) || typeof ret.ret !== "string" || observedBoolean(ret.ret) === null) throw fail("STATE_UNAVAILABLE", "Не подтверждено происхождение адреса WireGuard") row.dynamic = ret.ret } if (observedBoolean(row.dynamic) === null) throw fail("STATE_UNAVAILABLE", "Неизвестное происхождение адреса WireGuard") } await source(server, authorize) const filters = (await pool.query('SELECT id,gateway_tunnel_id AS "gatewayTunnelId",gateway FROM filter_rules WHERE server_id=$1 ORDER BY id LIMIT 1001', [server.id])).rows if (filters.length > 1000) throw fail("STATE_UNAVAILABLE", "Превышен предел DB-зависимостей WireGuard") if (bytes + Buffer.byteLength(JSON.stringify([filters, base.bindings, base.flow])) > 1048576) throw fail("STATE_UNAVAILABLE", "Превышен суммарный предел зависимостей WireGuard: 1 МиБ") await source(server, authorize) const state = { base, ipv4, ipv6, dependencies, filters } return { ...state, proof: await wireguardInterfaceDeleteProof(state) } } export function planWireguardInterfaceDelete(state: WireguardInterfaceDeleteState, id: string, cascade = true): WireguardInterfaceDeleteCommand[] { if (!/^\*[a-z0-9]+$/i.test(id) || id.length > 100) throw new McpError("INVALID_INPUT", "Требуется стабильный ID WireGuard", 400) const target = state.base.interfaces.find(row => row[".id"] === id) if (!target?.name || state.base.interfaces.filter(row => row.name === target.name).length !== 1) throw fail("STATE_CONFLICT", "Интерфейс WireGuard не найден однозначно") for (const flag of ["dynamic", "builtin", "default"]) if (target[flag] !== undefined && observedBoolean(target[flag]) !== false) throw fail("PROTECTED_OBJECT", "Системный интерфейс WireGuard нельзя удалить") if (observedBoolean(target.disabled) === null) throw fail("STATE_UNAVAILABLE", "Не подтверждено состояние интерфейса WireGuard") if (target.comment === "MikrotikManager traffic-flow overlay" || target.name === "wg-flow" && state.base.flow.registered === true) throw fail("PROTECTED_OBJECT", "Интерфейс управляется NetFlow; используйте отдельное изменение NetFlow") if (target.name === "wg-flow" && state.base.flow.registered === null) throw fail("STATE_UNAVAILABLE", "Не подтверждено владение интерфейсом NetFlow") const generic = state.dependencies["/interface"].filter(row => row.name === target.name || row[".id"] === id) if (generic.length !== 1 || generic[0].name !== target.name || generic[0][".id"] !== id) throw fail("STATE_CONFLICT", "Расходится общий и WireGuard native ID") const belongs = (row: Row) => [target.name, id].includes(row.interface) try { assertGreDeleteDependencies({ dependencies: state.dependencies, bindings: state.base.bindings, filters: state.filters }, target, "WireGuard") } catch { throw fail("DEPENDENCY_CONFLICT", "WireGuard используется интерфейсом, маршрутизацией, firewall или объектом приложения; сначала измените зависимости") } const peers = state.base.peers.filter(belongs) for (const peer of peers) wireguardPeerDeletionTarget(state.base, peer[".id"]) const addresses = [...state.ipv4, ...state.ipv6].filter(belongs) if (addresses.some(row => observedBoolean(row.dynamic) !== false && !automaticLinkLocal(row))) throw fail("DEPENDENCY_CONFLICT", "WireGuard имеет динамический адрес; сначала измените создающий его сервис") // Detect literal local-address references even when a protocol does not name its interface. const ipKey = (ip: string) => isIP(ip) ? canonicalBgpPolicyPrefix(ip + (isIP(ip) === 4 ? "/32" : "/128")) : ip const local = new Set(addresses.map(row => row.address.split("/")[0]).filter(ip => isIP(ip) !== 0).map(ipKey)) const addressFields = new Set(["local-address", "local.address", "pref-src", "src-address", "gateway"]) for (const [path, rows] of Object.entries(state.dependencies)) if (rows.some(row => !(observedBoolean(row.dynamic) === true && ["/ip/route", "/ipv6/route"].includes(path) && (row.connect === "true" || row["belongs-to"]?.startsWith("connected"))) && Object.entries(row).some(([key, value]) => addressFields.has(key) && value.split(/[,\s%/]+/).some(part => local.has(ipKey(part)))))) throw fail("DEPENDENCY_CONFLICT", "Локальный адрес WireGuard используется конфигурацией протокола") for (const template of state.dependencies["/routing/ospf/interface-template"]) { const interfaces = (template.interfaces ?? "").split(",").map(value => value.trim()).filter(Boolean) if (interfaces.length && !interfaces.some(value => ["all", target.name, id].includes(value))) continue for (const network of (template.networks ?? "").split(",").map(value => value.trim()).filter(Boolean)) { try { const expected = canonicalBgpPolicyPrefix(network), mask = expected.split("/")[1] if (addresses.some(row => isIP(row.address.split("/")[0]) === isIP(expected.split("/")[0]) && canonicalBgpPolicyPrefix(row.address.split("/")[0] + "/" + mask) === expected)) throw fail("DEPENDENCY_CONFLICT", "Сеть адреса WireGuard используется шаблоном OSPF") } catch (error) { if (error instanceof McpError) throw error; throw fail("STATE_UNAVAILABLE", "Не подтверждён сетевой selector OSPF") } } } if (!cascade && (peers.length || addresses.some(row => !automaticLinkLocal(row)))) throw fail("DEPENDENCY_CONFLICT", "Native DELETE не удаляет peers/адреса каскадно; используйте отдельный явный сервисный план") const commands: WireguardInterfaceDeleteCommand[] = [] if (cascade && observedBoolean(target.disabled) === false) commands.push({ method: "PATCH", path: "/interface/wireguard", resource: "interfaces", id, body: { disabled: "true" } }) for (const peer of peers) commands.push({ method: "DELETE", path: "/interface/wireguard/peers", resource: "peers", id: peer[".id"] }) for (const [path, resource, rows] of [["/ip/address", "ipv4", state.ipv4], ["/ipv6/address", "ipv6", state.ipv6]] as const) for (const row of rows.filter(row => belongs(row) && observedBoolean(row.dynamic) === false)) commands.push({ method: "DELETE", path, resource, id: row[".id"] }) commands.push({ method: "DELETE", path: "/interface/wireguard", resource: "interfaces", id }) if (commands.length > 50) throw fail("STATE_UNAVAILABLE", "Каскад WireGuard превышает 50 команд; сначала уменьшите число зависимых объектов") return commands } export function projectWireguardInterfaceDeleteCommand(state: WireguardInterfaceDeleteState, command: WireguardInterfaceDeleteCommand): WireguardInterfaceDeleteState { const next = structuredClone(state) const rows = command.resource === "interfaces" ? next.base.interfaces : command.resource === "peers" ? next.base.peers : next[command.resource] const target = rows.find(row => row[".id"] === command.id) if (!target) throw fail("STATE_CONFLICT", "Не найден объект запланированной команды WireGuard") if (command.method === "PATCH") Object.assign(target, command.body) else rows.splice(rows.indexOf(target), 1) if (command.resource === "interfaces" && command.method === "DELETE") next.dependencies["/interface"] = next.dependencies["/interface"].filter(row => row[".id"] !== command.id && row.name !== target.name) return next } export async function deleteWireguardInterfaceGuarded(server: ServerRow, id: string, expectedProof?: string, authorize: () => Promise = async () => {}, options: { recordRevision?: boolean; cascade?: boolean } = {}) { if (!/^\*[a-z0-9]+$/i.test(id) || id.length > 100) throw new McpError("INVALID_INPUT", "Требуется стабильный ID WireGuard", 400) return withApplicationMutationLock(() => withConfigMutationLock([server.id], () => executeGuardedApplicationWrite({ kind: "wireguard", id }, [server.id], async () => { let state = await readWireguardInterfaceDeleteState(server, id, authorize) if (expectedProof && state.proof !== expectedProof) throw fail("STATE_CONFLICT", "WireGuard или зависимости изменились после подготовки") const commands = planWireguardInterfaceDelete(state, id, options.cascade !== false), client = MikrotikClient.fromServer(server) let completedCommands = 0 for (const command of commands) { const fresh = await readWireguardInterfaceDeleteState(server, id, authorize) if (fresh.proof !== state.proof) throw fail(completedCommands ? "VERIFICATION_FAILED" : "STATE_CONFLICT", "WireGuard изменился между командами; выполнение остановлено") planWireguardInterfaceDelete(fresh, id, options.cascade !== false) const projected = projectWireguardInterfaceDeleteCommand(fresh, command), desiredProof = await wireguardInterfaceDeleteProof(projected) await source(server, authorize) try { const path = command.path + "/" + encodeURIComponent(command.id) if (command.method === "PATCH") await client.patch(path, command.body!) else await client.delete(path) } catch (error) { if (error instanceof McpError) throw error; throw fail("MUTATION_OUTCOME_UNKNOWN", "Исход команды WireGuard не подтверждён; каскад остановлен без повтора") } try { state = await readWireguardInterfaceDeleteState(server, id, authorize) } catch { throw fail("MUTATION_OUTCOME_UNKNOWN", "Команда отправлена, но сверка WireGuard недоступна; каскад остановлен без повтора") } if (state.proof !== desiredProof) throw fail("VERIFICATION_FAILED", "Команда WireGuard или сохранность остальной конфигурации не подтверждена; каскад остановлен") completedCommands++ } let revisionRecorded = false try { if (options.recordRevision !== false) revisionRecorded = await captureAndAppendRevision({ serverId: server.id, section: "wireguard", source: "apply", capture: () => captureWireguardSnapshot(server, () => source(server, authorize)) }) !== null } catch { /* Never replay native commands for revision storage. */ } return { ok: true, verified: true, interfaceId: id, commandCount: commands.length, completedCommands, afterProof: state.proof, revisionRecorded, forwardingVerified: false } }))) }