import { assertPoolMutationDependencies,ipsecExternalPoolDependencyPaths } from "./ipsec-pool-dependencies.js" import { McpError } from "../modules/mcp/security.js" import type { IpsecPeerDeleteState } from "./ipsec-peer-delete.js" import { IPSEC_CA_CERT, IPSEC_SERVER_CERT, IPSEC_POLICY_GROUP, isIpsecManagedComment, isManagedIpsecModeConfig } from "./ipsec-config.js" import { observedBoolean } from "./ospf-observed-values.js" type Row = Record const paths = ["/ip/ipsec/peer", "/ip/ipsec/identity", "/ip/ipsec/mode-config", "/ip/pool", "/ip/ipsec/policy", "/ip/firewall/nat", "/certificate", "/ip/ipsec/profile", "/ip/ipsec/proposal", "/ip/ipsec/policy/group", "/ip/ipsec/active-peers"] as const export type IpsecServerDeletePath = "/ip/ipsec/identity" | "/ip/ipsec/peer" | "/ip/ipsec/policy" | "/ip/ipsec/mode-config" | "/ip/pool" | "/ip/firewall/nat" | "/ip/ipsec/policy/group" | "/certificate" export interface IpsecServerDeleteCommand { path: IpsecServerDeletePath; id: string; cascadeIds?: string[] } export interface IpsecServerDeleteObject { kind: string; id: string } export interface IpsecServerDeletePlan { commands: IpsecServerDeleteCommand[]; objects: IpsecServerDeleteObject[]; companions: IpsecServerDeleteObject[]; removeCertificates: boolean } const kinds: Record = { "/ip/ipsec/identity": "ipsec_identity", "/ip/ipsec/peer": "ipsec_peer", "/ip/ipsec/policy": "ipsec_policy", "/ip/ipsec/mode-config": "ipsec_mode_config", "/ip/pool": "ip_pool", "/ip/firewall/nat": "ip_nat", "/ip/ipsec/policy/group": "ipsec_policy_group", "/certificate": "certificate" } const fail = (code: string, message: string): never => { throw new McpError(code, message, code === "STATE_UNAVAILABLE" ? 502 : 409) } const exactId = (value: unknown): value is string => typeof value === "string" && /^\*[a-z0-9]+$/i.test(value) && value.length <= 100 const idKey=(value:string)=>value.toLowerCase().replace(/^\*0+(?=[a-z0-9])/,"*") function validate(state: IpsecPeerDeleteState) { if (!state?.source || !Array.isArray(state.protections) || !state.catalogs) fail("STATE_UNAVAILABLE", "Неполное состояние IPsec") const indexes = new Map>() for (const path of paths) { const rows = state.catalogs[path] if (!Array.isArray(rows) || rows.length > 2000) fail("STATE_UNAVAILABLE", "Неполный native-каталог IPsec") const aliases = new Map(), ids = new Set() for (const row of rows) { if (!row || typeof row !== "object" || Array.isArray(row) || !exactId(row[".id"]) || Object.values(row).some(value => typeof value !== "string")) fail("STATE_UNAVAILABLE", "Некорректная строка native-каталога IPsec") if (ids.has(idKey(row[".id"]))) fail("STATE_CONFLICT", "Повторяющийся native ID IPsec") ids.add(idKey(row[".id"])) for (const alias of [row[".id"], row.name?.trim()].filter((value): value is string => !!value)) { const key = exactId(alias) ? idKey(alias) : alias if (aliases.has(key) && aliases.get(key) !== row) fail("STATE_CONFLICT", "Неоднозначное имя или native ID IPsec") aliases.set(key, row) } } indexes.set(path, aliases) } return indexes } function protect(row: Row) { for (const flag of ["dynamic", "builtin", "default"]) if (row[flag] !== undefined && observedBoolean(row[flag]) !== false) fail("PROTECTED_OBJECT", "Системный или неподтверждённый объект IPsec нельзя удалить") } /** Full server removal, with the same managed markers and reserved names as REST cleanup. */ export function planIpsecServerDelete(state: IpsecPeerDeleteState, removeCertificates = false): IpsecServerDeletePlan { if (typeof removeCertificates !== "boolean") fail("STATE_UNAVAILABLE", "Некорректный режим удаления сертификатов") const indexes = validate(state), catalogs = state.catalogs const resolve = (path: string, raw: string): Row => { const key = exactId(raw) ? idKey(raw) : raw return indexes.get(path)?.get(key) ?? fail("STATE_UNAVAILABLE", "Не найден родитель зависимости IPsec") } const owned = new Map>() for (const path of paths) owned.set(path, new Set()) for (const path of ["/ip/ipsec/identity", "/ip/ipsec/peer", "/ip/ipsec/policy", "/ip/ipsec/mode-config", "/ip/pool", "/ip/firewall/nat"]) { for (const row of catalogs[path]) { // Generated policies are runtime observations, excluded by the common state proof. if (path === "/ip/ipsec/policy" && observedBoolean(row.dynamic) === true) continue if (isIpsecManagedComment(row.comment) || (path === "/ip/ipsec/mode-config" && isManagedIpsecModeConfig(row))) owned.get(path)!.add(row) } } // A reserved policy group is owned only when a managed policy actually links it. for (const policy of owned.get("/ip/ipsec/policy")!) if (policy.group?.trim()) { const group = resolve("/ip/ipsec/policy/group", policy.group.trim()) if (group.name === IPSEC_POLICY_GROUP) owned.get("/ip/ipsec/policy/group")!.add(group) } if (removeCertificates) for (const cert of catalogs["/certificate"]) if (isIpsecManagedComment(cert.comment) || cert.name === IPSEC_CA_CERT || cert.name === IPSEC_SERVER_CERT || cert.name?.startsWith("ipsec-user-")) owned.get("/certificate")!.add(cert) for (const set of owned.values()) for (const row of set) protect(row) // Resolve exact scalar names first; only policy.peer has CSV reference semantics. const edges: { path: string; row: Row; parentPath: string; parent: Row }[] = [] const refs = (path: string, row: Row, field: string, parentPath: string, sentinels: string[] = ["none"]) => { const raw = row[field]?.trim() if (!raw) return const exactAlias = indexes.get(parentPath)!.has(exactId(raw) ? idKey(raw) : raw) const parts = path === "/ip/ipsec/policy" && field === "peer" && !exactAlias ? raw.split(",").map(value => value.trim()) : [raw] if (parts.some(value => !value)) fail("STATE_UNAVAILABLE", "Некорректная зависимость IPsec") const resolved = new Set() for (const value of parts) { if (sentinels.includes(value) && !indexes.get(parentPath)!.has(value)) continue const parent = resolve(parentPath, value) if (path === "/certificate" && field === "ca" && parent.authority !== undefined && observedBoolean(parent.authority) !== true) fail("STATE_UNAVAILABLE", "Не подтверждён CA-издатель сертификата") if (resolved.has(parent)) fail("STATE_CONFLICT", "Повторяющаяся или неоднозначная зависимость IPsec") resolved.add(parent) edges.push({ path, row, parentPath, parent }) if (!owned.get(path)!.has(row) && owned.get(parentPath)!.has(parent) && !(path === "/ip/ipsec/policy" && observedBoolean(row.dynamic) === true)) fail("DEPENDENCY_CONFLICT", "Управляемый объект IPsec используется чужой конфигурацией") } } for (const row of catalogs["/ip/ipsec/identity"]) { refs("/ip/ipsec/identity", row, "peer", "/ip/ipsec/peer") refs("/ip/ipsec/identity", row, "mode-config", "/ip/ipsec/mode-config", ["none", "request-only"]) refs("/ip/ipsec/identity", row, "policy-template-group", "/ip/ipsec/policy/group", ["default"]) for (const field of ["certificate", "remote-certificate"]) refs("/ip/ipsec/identity", row, field, "/certificate") } for (const row of catalogs["/ip/ipsec/peer"]) { refs("/ip/ipsec/peer", row, "certificate", "/certificate") refs("/ip/ipsec/peer", row, "profile", "/ip/ipsec/profile", ["default"]) } for (const row of catalogs["/ip/ipsec/policy"]) { if (observedBoolean(row.dynamic) === true) continue // Generated policies are runtime, not independently managed dependencies. refs("/ip/ipsec/policy", row, "peer", "/ip/ipsec/peer") refs("/ip/ipsec/policy", row, "group", "/ip/ipsec/policy/group", ["default"]) refs("/ip/ipsec/policy", row, "proposal", "/ip/ipsec/proposal", ["default"]) } for (const row of catalogs["/ip/ipsec/mode-config"]) refs("/ip/ipsec/mode-config", row, "address-pool", "/ip/pool", ["none", "static-only"]) for (const row of catalogs["/ip/pool"]) refs("/ip/pool", row, "next-pool", "/ip/pool") for (const row of catalogs["/certificate"]) refs("/certificate", row, "ca", "/certificate", []) const descendantsByPath = new Map>() // Iterative graph walk bounds stack use for the maximum 2,000-row catalog. for (const path of ["/certificate", "/ip/pool"]) { const children = new Map(), done = new Map(), active = new Set() for (const row of catalogs[path]) children.set(row, []) for (const edge of edges) if (edge.path === path && edge.parentPath === path) children.get(edge.parent)!.push(edge.row) for (const root of catalogs[path]) { if (done.has(root)) continue const stack: { row: Row; exit: boolean }[] = [{ row: root, exit: false }] while (stack.length) { const { row, exit } = stack.pop()! if (done.has(row)) continue if (exit) { done.set(row, children.get(row)!.flatMap(child => [...done.get(child)!, child])) active.delete(row) } else { if (active.has(row)) fail("STATE_CONFLICT", "Циклическая зависимость IPsec") active.add(row); stack.push({ row, exit: true }) for (const child of children.get(row)!) stack.push({ row: child, exit: false }) } } } descendantsByPath.set(path, done) } const descendants = (path: string, row: Row): Row[] => descendantsByPath.get(path)!.get(row)! const commands: IpsecServerDeleteCommand[] = [], objects: IpsecServerDeleteObject[] = [] for (const path of ["/ip/ipsec/identity", "/ip/ipsec/policy", "/ip/ipsec/peer", "/ip/ipsec/mode-config", "/ip/pool", "/ip/firewall/nat", "/ip/ipsec/policy/group"] as IpsecServerDeletePath[]) { const rows = [...owned.get(path)!] if (path === "/ip/pool") rows.sort((a, b) => descendants(path, a).length - descendants(path, b).length) for (const row of rows) { commands.push({ path, id: row[".id"] }); objects.push({ kind: kinds[path], id: row[".id"] }) } } const certs = owned.get("/certificate")!, covered = new Set() const crlBlocks = (row: Row) => { const issuer = edges.find(edge => edge.path === "/certificate" && edge.row === row)?.parent if (!issuer) return false if (issuer.crl !== undefined && observedBoolean(issuer.crl) === null) fail("STATE_UNAVAILABLE", "Неоднозначный CRL CA") return observedBoolean(issuer.crl) === true && (observedBoolean(row.issued) !== false || (row.revoked !== undefined && observedBoolean(row.revoked) !== false)) } // RouterOS CA removal cascades the entire issued chain. Only a closed, fully owned // subtree may use that operation, and every indirect removal is in the manifest. const roots = [...certs].filter(row => !edges.some(edge => edge.path === "/certificate" && edge.row === row && certs.has(edge.parent))) for (const root of roots) { const children = descendants("/certificate", root) if (children.some(row => !certs.has(row))) fail("DEPENDENCY_CONFLICT", "Управляемый CA подписал чужой сертификат") if (crlBlocks(root)) fail("DEPENDENCY_CONFLICT", "Сертификат выдан чужим CA с CRL; удаление CA выходит за границы операции") if (children.some(crlBlocks)) { commands.push({ path: "/certificate", id: root[".id"], cascadeIds: children.map(row => row[".id"]) }) for (const row of [...children, root]) covered.add(row) } } for (const row of [...certs].sort((a, b) => descendants("/certificate", a).length - descendants("/certificate", b).length)) { if (!covered.has(row)) commands.push({ path: "/certificate", id: row[".id"] }) objects.push({ kind: "certificate", id: row[".id"] }) } // A marker on an external allocator never authorizes its indirect disruption. assertPoolMutationDependencies(catalogs,[...owned.get("/ip/pool")!],commands.filter(cmd=>["/ip/ipsec/mode-config","/ip/pool"].includes(cmd.path)).map(cmd=>({path:cmd.path,id:cmd.id}))) const externalKinds:Record={"/ip/dhcp-server":"dhcp_server","/ppp/profile":"ppp_profile","/ppp/secret":"ppp_secret","/ip/hotspot":"hotspot_server","/ip/hotspot/user/profile":"hotspot_user_profile"} return { commands, objects, companions: [...objects.map(object => ({ ...object })),...ipsecExternalPoolDependencyPaths.flatMap(path=>catalogs[path].map(row=>({kind:externalKinds[path],id:row[".id"]})))], removeCertificates } } /** Exact declared removal only; opaque fields, foreign rows and order survive unchanged. */ export function projectIpsecServerDelete(state: IpsecPeerDeleteState, command: IpsecServerDeleteCommand): IpsecPeerDeleteState { if (!Object.hasOwn(kinds, command.path) || !exactId(command.id) || (command.cascadeIds && (command.path !== "/certificate" || command.cascadeIds.some(id => !exactId(id))))) fail("STATE_CONFLICT", "Некорректная команда удаления IPsec") const ids = [command.id, ...(command.cascadeIds ?? [])], rows = state.catalogs[command.path] if (!Array.isArray(rows) || new Set(ids).size !== ids.length || ids.some(id => rows.filter(row => row[".id"] === id).length !== 1)) fail("STATE_CONFLICT", "Точные объекты удаления IPsec не подтверждены") for (const row of rows.filter(row => ids.includes(row[".id"]))) protect(row) if (command.path === "/certificate") { const aliases = validate(state).get("/certificate")!, closure = new Set([command.id]) let changed = true while (changed) { changed = false for (const row of rows) { const raw = row.ca?.trim(), parent = raw ? aliases.get(exactId(raw) ? idKey(raw) : raw) : undefined if (parent && closure.has(parent[".id"]) && !closure.has(row[".id"])) { closure.add(row[".id"]); changed = true } } } if (closure.size !== ids.length || ids.some(id => !closure.has(id))) fail("STATE_CONFLICT", "Каскад удаления CA не совпадает с точным манифестом") if (command.cascadeIds) for (const row of rows.filter(row => closure.has(row[".id"]))) if (!(isIpsecManagedComment(row.comment) || row.name === IPSEC_CA_CERT || row.name === IPSEC_SERVER_CERT || row.name?.startsWith("ipsec-user-"))) fail("DEPENDENCY_CONFLICT", "Каскад удаления CA затрагивает чужой сертификат") } const next = structuredClone(state) next.catalogs[command.path] = next.catalogs[command.path].filter(row => !ids.includes(row[".id"])) return next }