import { isIP } from "node:net" import { ipsecUserPatchSchema } from "@mmapp/contracts/ipsec" import type { ServerRow } from "../modules/servers/repository/servers-repository.js" import { McpError } from "../modules/mcp/security.js" import type { IpsecPeerDeleteState } from "./ipsec-peer-delete.js" import { mapClients, resolveIpsecClientTarget, type IpsecServerState } from "./ipsec-live.js" import { IPSEC_COMMON_NAME, IPSEC_SERVER_CERT, isIpsecManagedComment, isManagedIpsecModeConfig, ipsecUserComment, normalizeIpsecRemoteId, parseIpsecUserComment, resolveIke2ServerCert, selectIke2Peers, selectSharedIke2Identity, userModeConfigName } from "./ipsec-config.js" import { identityRosBody } from "./ipsec-ros.js" import { observedBoolean } from "./ospf-observed-values.js" type Row = Record type State = IpsecPeerDeleteState export interface IpsecUserUpdateCommand { action: "create" | "update" | "delete"; path: "/ip/ipsec/identity" | "/ip/ipsec/mode-config"; id?: string; fields: Row } export interface IpsecUserUpdateObject { kind: string; id: string } 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"] const fail = (code: string, message: string) => new McpError(code, message, code === "INVALID_INPUT" ? 400 : code === "NOT_FOUND" ? 404 : code === "STATE_UNAVAILABLE" ? 502 : 409) const exactId = (id: unknown): id is string => typeof id === "string" && /^\*[a-z0-9]+$/i.test(id) && id.length <= 100 function validateState(state: State) { if (!state?.source || !Array.isArray(state.protections) || !state.catalogs) throw fail("STATE_UNAVAILABLE", "Неполное состояние IPsec") for (const path of paths) { const rows = state.catalogs[path] if (!Array.isArray(rows) || rows.length > 2000 || rows.some(row => !row || typeof row !== "object" || Array.isArray(row) || !exactId(row[".id"]) || Object.values(row).some(value => typeof value !== "string")) || new Set(rows.map(row => row[".id"])).size !== rows.length) throw fail("STATE_UNAVAILABLE", "Неполный или неоднозначный native-каталог IPsec") const names = rows.map(row => row.name?.trim()).filter(Boolean) if (path !== "/ip/ipsec/active-peers" && new Set(names).size !== names.length) throw fail("STATE_CONFLICT", "Неоднозначное имя объекта IPsec") } } function mutable(row: Row) { for (const flag of ["dynamic", "builtin", "default"]) if (row[flag] !== undefined && observedBoolean(row[flag]) !== false) throw fail("PROTECTED_OBJECT", "Системный или неподтверждённый объект IPsec нельзя изменять") } /** An inert view: client is never constructed or used by the pure mapping functions. */ function liveState(state: State, server: ServerRow): IpsecServerState { const c = state.catalogs return { server, client: undefined as unknown as IpsecServerState["client"], peers: c["/ip/ipsec/peer"], identities: c["/ip/ipsec/identity"], modeConfigs: c["/ip/ipsec/mode-config"], pools: c["/ip/pool"], policies: c["/ip/ipsec/policy"], nat: c["/ip/firewall/nat"], active: c["/ip/ipsec/active-peers"], certs: c["/certificate"] } } const taken = (rows: Array<{ name?: string; address?: string; "address-prefix"?: string }>) => rows.filter(row => (row.name ?? "").startsWith("mc-ipsec-")).map(row => (row.address ?? row["address-prefix"] ?? "").replace(/\/\d+$/, "").trim()).filter(Boolean) /** Plans every legacy PATCH branch before the first effect, including certificate promotion. */ export function planIpsecUserUpdate(state: State, server: ServerRow, clientId: string, raw: unknown) { const parsed = ipsecUserPatchSchema.safeParse(raw) if (!parsed.success) throw fail("INVALID_INPUT", "Некорректные поля клиента IPsec") const d = parsed.data if (typeof d.staticIp === "string" && isIP(d.staticIp.trim()) !== 4) throw fail("INVALID_INPUT", "Некорректный статический IPv4 адрес") if (!clientId || clientId.length > 200 || /[\x00-\x1f\x7f]/.test(clientId)) throw fail("INVALID_INPUT", "Некорректный ID клиента IPsec") validateState(state) const certToken = clientId.startsWith("cert:") ? clientId.slice(5) : clientId.startsWith("identity:") ? undefined : clientId if (certToken && state.catalogs["/certificate"].filter(row => row[".id"] === certToken || row.name === certToken).length > 1) throw fail("STATE_CONFLICT", "Неоднозначный ID или имя сертификата клиента") const live = liveState(state, server), resolved = resolveIpsecClientTarget(live, clientId) if (resolved.ambiguous) throw fail("STATE_CONFLICT", "Неоднозначный ID клиента. Обновите список IPsec") let { identity, certRow } = resolved if (certRow) { identity = live.identities.find(row => row["remote-certificate"] === certRow?.name) if (identity) certRow = undefined } if (!identity && !certRow) throw fail("NOT_FOUND", "Клиент не найден") const peers = selectIke2Peers(live.peers) const serverCert = resolveIke2ServerCert(live.certs, peers, live.identities) const oldName = identity ? (parseIpsecUserComment(identity.comment) ?? identity.comment ?? "") : String(certRow?.["common-name"] ?? certRow?.name ?? "").trim() const newName = d.name?.trim() || oldName, sharedMc = live.modeConfigs.find(row => (row.name ?? "").trim() === IPSEC_COMMON_NAME), sharedName = (sharedMc?.name ?? "").trim() const remoteId = d.remoteId === undefined ? undefined : normalizeIpsecRemoteId(d.remoteId) if (d.name && newName !== oldName && mapClients(live).some(row => row.name === newName && (identity ? row.rosId !== `identity:${identity[".id"]}` : row.certName !== certRow?.name))) throw fail("STATE_CONFLICT", "Имя уже используется другим клиентом") if (identity && remoteId !== undefined && live.identities.some(row => row[".id"] !== identity[".id"] && row.peer === identity.peer && row["auth-method"] === "pre-shared-key" && row["remote-id"] === remoteId)) throw fail("STATE_CONFLICT", "Remote ID уже используется клиентом этого peer") const currentMc = (identity?.["mode-config"] ?? "").trim() if (d.staticIp && taken(live.modeConfigs.filter(row => !currentMc || row.name !== currentMc)).includes(d.staticIp.trim())) throw fail("STATE_CONFLICT", "IP уже назначен другому клиенту") const commands: IpsecUserUpdateCommand[] = [], seeds: Array<{ path: string; row: Row }> = [] const seed = (path: string, row: unknown) => { if (row) seeds.push({ path, row: row as Row }) } seed(identity ? "/ip/ipsec/identity" : "/certificate", identity ?? certRow) const add = (action: IpsecUserUpdateCommand["action"], path: IpsecUserUpdateCommand["path"], fields: Row, row?: { ".id"?: string }) => { if (row) { mutable(row as Row); seed(path, row) } commands.push({ action, path, ...(row ? { id: row[".id"]! } : {}), fields }) } const patchIdentity = (fields: Row) => add("update", "/ip/ipsec/identity", fields, identity) const upsertMc = (name: string, ip: string) => { const matches = state.catalogs["/ip/ipsec/mode-config"].filter(row => row.name?.trim() === name) if (matches[0] && matches[0].name !== name) throw fail("STATE_CONFLICT", "Не подтверждено точное имя mode-config") add(matches.length ? "update" : "create", "/ip/ipsec/mode-config", { name, address: ip, responder: "yes", "address-prefix-length": "32" }, matches[0]) } const deletePersonal = (name: string, projectedMc: string) => { if (!name || name === sharedName) return const row = state.catalogs["/ip/ipsec/mode-config"].find(row => row.name === name) seed("/ip/ipsec/mode-config", row) if (row && isManagedIpsecModeConfig(row) && !live.identities.some(other => other[".id"] === identity?.[".id"] ? projectedMc === name : other["mode-config"] === name)) add("delete", "/ip/ipsec/mode-config", {}, row) } const createCertificateIdentity = (modeConfig: string, requireCert: boolean) => { const peer = peers.find(row => isIpsecManagedComment(row.comment)) ?? peers[0] if (!peer || (requireCert && !serverCert)) throw fail("STATE_CONFLICT", "Нет IKEv2 peer или серверного сертификата") const certificateName = serverCert?.name ?? (requireCert ? undefined : IPSEC_SERVER_CERT) const certificateMatches = state.catalogs["/certificate"].filter(row => row.name === certificateName) if (!certificateName || certificateName !== certificateName.trim() || certificateMatches.length !== 1) throw fail("STATE_CONFLICT", "Не подтверждён точный серверный сертификат IKEv2") const shared = selectSharedIke2Identity(live.identities, [(peer.name ?? "").trim()]) seed("/ip/ipsec/peer", peer); seed("/certificate", certificateMatches[0]); seed("/ip/ipsec/identity", shared) seed("/ip/ipsec/mode-config", state.catalogs["/ip/ipsec/mode-config"].find(row => row.name === modeConfig)) add("create", "/ip/ipsec/identity", identityRosBody({ peerName: requireCert ? (peer.name ?? "") : (peer.name ?? "").trim(), modeConfig, comment: ipsecUserComment(requireCert ? d.name! : newName), authMethod: "certificate", certificate: certificateName, remoteCertificate: requireCert ? certRow!.name : String(certRow!.name ?? "").trim(), policyTemplateGroup: shared?.["policy-template-group"] })) } if (d.name && d.name !== oldName) { if (identity) patchIdentity({ comment: isIpsecManagedComment(identity.comment) ? ipsecUserComment(d.name) : d.name.trim() }) if (certRow && !d.staticIp) createCertificateIdentity(sharedName, true) } if (identity && d.staticIp !== undefined) { seed("/ip/ipsec/mode-config", sharedMc) if (d.staticIp == null) { if (sharedName) patchIdentity({ "mode-config": sharedName }) deletePersonal(currentMc, sharedName || currentMc) } else { const name = userModeConfigName(newName) upsertMc(name, d.staticIp.trim()); patchIdentity({ "mode-config": name }) if (currentMc !== name) deletePersonal(currentMc, name) } } else if (!identity && certRow && d.staticIp) { // Validate peer before adding either command; the returned plan is always complete. if (!peers.length) throw fail("STATE_CONFLICT", "На роутере нет IKEv2 peer для привязки клиента") const name = userModeConfigName(newName) upsertMc(name, d.staticIp.trim()); createCertificateIdentity(name, false) } if (identity) { const fields: Row = {} if (d.psk) fields.secret = d.psk if (remoteId !== undefined) fields["remote-id"] = remoteId if (d.disabled !== undefined) fields.disabled = d.disabled ? "yes" : "no" if (Object.keys(fields).length) patchIdentity(fields) } const kinds: Record = { "/ip/ipsec/peer": "ipsec_peer", "/ip/ipsec/identity": "ipsec_identity", "/ip/ipsec/mode-config": "ipsec_mode_config", "/ip/pool": "ip_pool", "/certificate": "certificate", "/ip/ipsec/profile": "ipsec_profile", "/ip/ipsec/proposal": "ipsec_proposal", "/ip/ipsec/policy/group": "ipsec_policy_group" } const references: Record = { peer: "/ip/ipsec/peer", "mode-config": "/ip/ipsec/mode-config", "address-pool": "/ip/pool", certificate: "/certificate", "remote-certificate": "/certificate", ca: "/certificate", profile: "/ip/ipsec/profile", proposal: "/ip/ipsec/proposal", "policy-template-group": "/ip/ipsec/policy/group" } const companions: IpsecUserUpdateObject[] = [], seen = new Set() for (let index = 0; index < seeds.length; index++) { const { path, row } = seeds[index], key = `${path}:${row[".id"]}` if (seen.has(key)) continue seen.add(key); companions.push({ kind: kinds[path] ?? path, id: row[".id"] }) for (const [field, refPath] of Object.entries(references)) { const ref = row[field] if (!ref || ["none", "auto", "ignore"].includes(ref)) continue const matches = state.catalogs[refPath].filter(item => item.name === ref || item[".id"] === ref) if (matches.length !== 1) throw fail("STATE_CONFLICT", "Не подтверждена однозначная зависимость IPsec") seed(refPath, matches[0]) } if (path === "/ip/ipsec/mode-config") for (const consumer of state.catalogs["/ip/ipsec/identity"].filter(item => item["mode-config"] === row.name)) seed("/ip/ipsec/identity", consumer) } return { commands, target: { kind: "ipsec_user", id: clientId }, companions, objects: companions, ignoredFields: identity ? [] : ["psk", "remoteId", "disabled", ...(d.staticIp === null ? ["staticIp"] : [])].filter(key => Object.hasOwn(d, key)), oldName, newName } } /** Preserve all prior raw fields and ordering. Only a newly acknowledged row admits defaults. */ export function projectIpsecUserUpdate(state: State, command: IpsecUserUpdateCommand, options: { assignedId?: string; createdRow?: Row } = {}): State { const next = structuredClone(state), rows = next.catalogs[command.path] if (!rows) throw fail("STATE_UNAVAILABLE", "Неизвестный каталог IPsec") if (command.action === "create") { const row = options.createdRow, id = options.assignedId ?? row?.[".id"] if (!row || !exactId(id) || row[".id"] !== id || rows.some(existing => existing[".id"] === id) || Object.values(row).some(value => typeof value !== "string")) throw fail("VERIFICATION_FAILED", "Не подтверждён созданный native объект IPsec") for (const flag of ["dynamic", "builtin", "default"]) if (row[flag] !== undefined && observedBoolean(row[flag]) !== false) throw fail("VERIFICATION_FAILED", "Созданный объект IPsec имеет системный или неподтверждённый флаг") for (const [key, value] of Object.entries(command.fields)) { if (row[key] !== value && !(["disabled", "responder"].includes(key) && ["yes", "no", "true", "false"].includes(value) && observedBoolean(row[key]) === observedBoolean(value))) throw fail("VERIFICATION_FAILED", "Поля созданного объекта IPsec не подтверждены") } rows.push(structuredClone(row)) } else { const index = rows.findIndex(row => row[".id"] === command.id) if (index < 0 || rows.filter(row => row[".id"] === command.id).length !== 1) throw fail("STATE_CONFLICT", "Запланированный native объект IPsec отсутствует") if (command.action === "delete") rows.splice(index, 1) else Object.assign(rows[index], command.fields) } return next }