Files
MikrotikManager/backend/src/services/ipsec-user-create-model.ts
T

137 lines
15 KiB
TypeScript

import { isIP } from "node:net"
import { ipsecUserCreateRequestSchema } from "@mmapp/contracts/ipsec"
import type { ServerRow } from "../modules/servers/repository/servers-repository.js"
import { McpError } from "../modules/mcp/security.js"
import { ipsecPeerDeletePaths, type IpsecPeerDeleteState } from "./ipsec-peer-delete.js"
import { mapClients, type IpsecServerState } from "./ipsec-live.js"
import { IPSEC_COMMON_NAME, clientCertName, ipsecManagedComment, ipsecUserComment, isIpsecManagedComment, isManagedIpsecModeConfig, isIke2RemoteAccessIdentity, normalizeIpsecRemoteId, resolveIke2CaName, resolveIke2ServerCert, selectIke2Peers, selectSharedIke2Identity, userModeConfigName } from "./ipsec-config.js"
import { identityRosBody } from "./ipsec-ros.js"
import { observedBoolean } from "./ospf-observed-values.js"
type Row = Record<string, string>
export type IpsecUserCreateState = IpsecPeerDeleteState
export const ipsecUserCreateRequest = ipsecUserCreateRequestSchema.strict()
export interface IpsecUserCreateCommand { action: "create" | "update" | "sign" | "export" | "cleanup"; path: string; fields: Row; id?: string; name?: string }
const fail = (message: string, code = "STATE_CONFLICT") => new McpError(code, message, code === "INVALID_INPUT" ? 400 : code === "STATE_UNAVAILABLE" ? 502 : 409)
const exactId = (value: unknown): value is string => typeof value === "string" && /^\*[a-z0-9]+$/i.test(value) && value.length <= 100
export function validateIpsecUserCreateState(state: IpsecUserCreateState) {
if (!state?.source || !state.catalogs || !Array.isArray(state.protections)) throw fail("Неполное состояние IPsec", "STATE_UNAVAILABLE")
for (const path of [...ipsecPeerDeletePaths, "/file"]) {
const rows = state.catalogs[path]
if (!Array.isArray(rows) || rows.length > 2000 || rows.some(row => !row || !exactId(row[".id"]) || Object.values(row).some(value => typeof value !== "string")) || new Set(rows.map(row => row[".id"].toLowerCase())).size !== rows.length) throw fail("Неполный native-каталог IPsec", "STATE_UNAVAILABLE")
const names = rows.map(row => row.name?.trim()).filter(Boolean)
if (path !== "/ip/ipsec/active-peers" && new Set(names).size !== names.length) throw fail("Неоднозначное имя IPsec")
}
}
/** All dependencies and every branch are resolved before the first native effect. */
export function planIpsecUserCreate(state: IpsecUserCreateState, server: ServerRow, raw: unknown, exportPrefix: string) {
const parsed = ipsecUserCreateRequest.safeParse(raw)
if (!parsed.success) throw fail("Некорректные поля создания клиента IPsec", "INVALID_INPUT")
const body = parsed.data
if (Number(body.serverId) !== server.id || !body.name.trim() || /[\x00-\x1f\x7f]/.test(body.name) || !/^mm-ipsec-[a-z0-9-]{1,80}$/i.test(exportPrefix)) throw fail("Некорректный сервер, имя или идентификатор экспорта IPsec", "INVALID_INPUT")
if (body.staticIp !== undefined && isIP(body.staticIp.trim()) !== 4) throw fail("Некорректный статический IPv4 адрес", "INVALID_INPUT")
if (body.authMethod === "pre-shared-key" && !body.psk) throw fail("Для PSK клиента требуется secret", "INVALID_INPUT")
validateIpsecUserCreateState(state)
const c = state.catalogs
const live = { server, client: undefined, 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"] } as unknown as IpsecServerState
const peers = selectIke2Peers(live.peers), names = peers.map(row => (row.name ?? "").trim()).filter(Boolean)
const peer = body.peerName ? live.peers.find(row => row.name === body.peerName!.trim()) : peers.find(row => isIpsecManagedComment(row.comment)) ?? peers.find(row => row.name === IPSEC_COMMON_NAME) ?? peers[0]
if (!peer || !peer.name || peer.name !== peer.name.trim()) throw fail("Выбранный peer IPsec не найден")
const mcName = live.identities.filter(row => isIpsecManagedComment(row.comment) || isIke2RemoteAccessIdentity(row, names)).map(row => (row["mode-config"] ?? "").trim()).find(name => name && !name.startsWith("mc-ipsec-"))
const sharedMc = (mcName ? live.modeConfigs.find(row => row.name === mcName) : undefined) ?? live.modeConfigs.find(row => row.name === IPSEC_COMMON_NAME)
const serverCert = resolveIke2ServerCert(live.certs, peers, live.identities), caName = resolveIke2CaName(live.certs, serverCert)
const certName = body.authMethod === "certificate" ? clientCertName(body.name) : undefined
if (body.authMethod === "certificate" && (!caName || !serverCert?.name)) throw fail("Нет CA или серверного сертификата IKEv2")
if (mapClients(live).some(row => row.name === body.name.trim()) || (certName && live.certs.some(row => row.name === certName))) throw fail("Клиент уже существует")
if (body.authMethod === "pre-shared-key" && live.identities.some(row => row.peer === peer.name && row["auth-method"] === "pre-shared-key" && row["remote-id"] === normalizeIpsecRemoteId(body.remoteId ?? body.name))) throw fail("Remote ID уже используется клиентом этого peer")
const commands: IpsecUserCreateCommand[] = [], seeds: Array<{ path: string; row: Row }> = []
const seed = (path: string, row: unknown) => { if (row) seeds.push({ path, row: row as Row }) }
seed("/ip/ipsec/peer", peer); seed("/ip/ipsec/mode-config", sharedMc)
const sharedIdentity = selectSharedIke2Identity(live.identities, names)
seed("/ip/ipsec/identity", sharedIdentity)
let modeConfig = sharedMc?.name ?? ""
if (body.staticIp) {
if (live.modeConfigs.some(row => (row.name ?? "").startsWith("mc-ipsec-") && (row.address ?? row["address-prefix"] ?? "").replace(/\/\d+$/, "").trim() === body.staticIp!.trim())) throw fail("IP уже назначен другому клиенту")
modeConfig = userModeConfigName(body.name)
const existing = c["/ip/ipsec/mode-config"].find(row => row.name?.trim() === modeConfig)
if (existing && existing.name !== modeConfig) throw fail("Не подтверждено точное имя mode-config")
if (existing && (!isManagedIpsecModeConfig(existing) || c["/ip/ipsec/identity"].some(row => row["mode-config"] === existing.name || row["mode-config"]?.toLowerCase() === existing[".id"].toLowerCase()))) throw fail("Персональный mode-config уже используется другим клиентом; адрес чужого или общего объекта изменять нельзя")
if (existing) for (const flag of ["dynamic", "builtin", "default"]) if (existing[flag] !== undefined && observedBoolean(existing[flag]) !== false) throw fail("Системный mode-config нельзя изменять", "PROTECTED_OBJECT")
seed("/ip/ipsec/mode-config", existing)
commands.push({ action: existing ? "update" : "create", path: "/ip/ipsec/mode-config", ...(existing ? { id: existing[".id"] } : {}), fields: { name: modeConfig, address: body.staticIp.trim(), responder: "yes", "address-prefix-length": "32" } })
}
if (certName) {
seed("/certificate", serverCert); seed("/certificate", c["/certificate"].find(row => row.name === caName))
commands.push({ action: "create", path: "/certificate", fields: { name: certName, "common-name": body.name.trim(), "key-size": "2048", "key-usage": "digital-signature,key-encipherment,tls-client", "days-valid": String(body.daysValid ?? 1825), comment: ipsecManagedComment(`client ${body.name.trim()}`) } })
commands.push({ action: "sign", path: "/certificate/sign", name: certName, fields: { name: certName, ca: caName!, "days-valid": String(body.daysValid ?? 1825) } })
}
if (body.authMethod !== "certificate" || body.staticIp || !sharedIdentity) commands.push({ action: "create", path: "/ip/ipsec/identity", fields: identityRosBody({ peerName: peer.name, modeConfig, comment: certName && !body.staticIp ? ipsecManagedComment("IKEv2 listener") : ipsecUserComment(body.name), authMethod: body.authMethod, certificate: certName ? serverCert!.name : undefined, remoteCertificate: body.staticIp ? certName : undefined, secret: body.psk, remoteId: body.authMethod === "pre-shared-key" ? body.remoteId ?? body.name : undefined, policyTemplateGroup: sharedIdentity?.["policy-template-group"] }) })
if (certName) {
if (c["/file"].some(row => row.name === `${exportPrefix}.p12`)) throw fail("Имя файла экспорта занято")
commands.push({ action: "export", path: "/certificate/export-certificate", name: `${exportPrefix}.p12`, fields: { name: certName, type: "pkcs12", "file-name": exportPrefix, "export-passphrase": body.passphrase ?? "" } }, { action: "cleanup", path: "/file", name: `${exportPrefix}.p12`, fields: {} })
}
const kinds: Record<string, string> = { "/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", "/ip/ipsec/policy": "ipsec_policy" }
const refs: Record<string, string> = { 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" }
for (const command of commands) for (const [field, refPath] of Object.entries(refs)) {
const value = command.fields[field]
if (!value || ["none", "auto", "ignore"].includes(value) || commands.some(item => item.action === "create" && item.path === refPath && item.fields.name === value)) continue
const matches = c[refPath].filter(row => row.name === value || row[".id"] === value)
if (matches.length !== 1) throw fail("Не подтверждена зависимость создаваемого объекта IPsec")
seed(refPath, matches[0])
}
const companions: Array<{ kind: string; id: string }> = [], seen = new Set<string>()
for (let i = 0; i < seeds.length; i++) {
const { path, row } = seeds[i], 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(refs)) {
const value = row[field]
if (!value || ["none", "auto", "ignore"].includes(value)) continue
const matches = c[refPath].filter(item => item.name === value || item[".id"] === value)
if (matches.length !== 1) throw fail("Не подтверждена однозначная зависимость IPsec")
seed(refPath, matches[0])
}
const reference = (value: string | undefined) => value === row.name || value?.toLowerCase() === row[".id"].toLowerCase()
if (path === "/ip/ipsec/mode-config") for (const consumer of c["/ip/ipsec/identity"].filter(item => reference(item["mode-config"]))) seed("/ip/ipsec/identity", consumer)
if (path === "/ip/ipsec/policy/group") for (const policy of c["/ip/ipsec/policy"].filter(item => reference(item.group))) seed("/ip/ipsec/policy", policy)
if (path === "/certificate") {
for (const child of c["/certificate"].filter(item => reference(item.ca))) seed("/certificate", child)
for (const dependentPath of ["/ip/ipsec/identity", "/ip/ipsec/peer"]) for (const consumer of c[dependentPath].filter(item => reference(item.certificate) || reference(item["remote-certificate"]))) seed(dependentPath, consumer)
}
}
return { commands, companions, target: { kind: "ipsec_user", id: body.name.trim() }, certName, serverEndpoint: String(serverCert?.["common-name"] ?? "").trim() || server.host, dns: sharedMc?.["static-dns"]?.trim() || undefined }
}
/** Native defaults are admitted solely for the ACK-owned newly created row.
* Signing can change only documented generated fields of that new certificate. */
export function projectIpsecUserCreate(state: IpsecUserCreateState, command: IpsecUserCreateCommand, options: { assignedId?: string; observedRow?: Row; ownedCertificateIds?: Set<string> } = {}) {
const next = structuredClone(state)
const path = command.action === "sign" ? "/certificate" : command.action === "export" || command.action === "cleanup" ? "/file" : command.path
const rows = next.catalogs[path]
if (!rows) throw fail("Неизвестный каталог IPsec", "STATE_UNAVAILABLE")
if (command.action === "cleanup") {
const matches = rows.filter(row => row.name === command.name)
if (matches.length !== 1 || matches[0][".id"] !== options.assignedId) throw fail("Не подтверждён файл очистки", "VERIFICATION_FAILED")
rows.splice(rows.indexOf(matches[0]), 1)
} else if (command.action === "update") {
const row = rows.find(item => item[".id"] === command.id)
if (!row) throw fail("Mode-config отсутствует")
Object.assign(row, command.fields)
} else if (command.action === "sign") {
const row = rows.find(item => item.name === command.name), observed = options.observedRow
if (!row || !options.ownedCertificateIds?.has(row[".id"]) || !observed || observed[".id"] !== row[".id"] || !observed["invalid-after"]?.trim() || !observed.fingerprint?.trim()) throw fail("Не подтверждена подпись нового сертификата", "VERIFICATION_FAILED")
const generated = new Set(["ca", "ca-crl-host", "serial-number", "fingerprint", "invalid-before", "invalid-after", "expires-after", "akid", "skid", "issuer", "private-key", "issued", "status", "trusted"])
for (const key of new Set([...Object.keys(row), ...Object.keys(observed)])) if (!generated.has(key) && observed[key] !== row[key]) throw fail("При подписи изменены исходные поля сертификата", "VERIFICATION_FAILED")
if (observed.ca !== command.fields.ca) throw fail("CA подписи не подтверждён", "VERIFICATION_FAILED")
rows[rows.indexOf(row)] = structuredClone(observed)
} else {
const row = options.observedRow, id = options.assignedId
if (!row || !exactId(id) || row[".id"] !== id || rows.some(item => item[".id"].toLowerCase() === id.toLowerCase()) || Object.values(row).some(value => typeof value !== "string")) throw fail("Не подтверждён ACK нового объекта", "VERIFICATION_FAILED")
for (const flag of ["dynamic", "builtin", "default"]) if (row[flag] !== undefined && observedBoolean(row[flag]) !== false) throw fail("Создан системный объект", "VERIFICATION_FAILED")
const fields = command.action === "export" ? { name: command.name! } : command.fields
for (const [key, value] of Object.entries(fields)) if (row[key] !== value && !(["disabled", "responder"].includes(key) && observedBoolean(row[key]) !== null && observedBoolean(row[key]) === observedBoolean(value))) throw fail("Поля нового объекта не подтверждены", "VERIFICATION_FAILED")
rows.push(structuredClone(row))
}
return next
}