Files
MikrotikManager/backend/src/services/ipsec-user-create.ts
T
Denozordec 165f5e1260
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m23s
Docker images / backend-image (push) Successful in 2m35s
Docker images / frontend-image (push) Successful in 2m38s
Docker images / updater-image (push) Successful in 1m7s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
fix(ipsec): исправить сверку списка файлов при экспорте сертификатов
2026-11-22 15:36:37 +07:00

129 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { randomBytes, randomUUID } from "node:crypto"
import type { IpsecCertBundle } from "@mmapp/contracts/ipsec"
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
import { McpError, fingerprint, privateFingerprinter } from "../modules/mcp/security.js"
import { MAX_OWNED_FILE_BYTES, MikrotikClient, MikrotikError } from "./mikrotik.js"
import { readIpsecPeerDeleteState, ipsecPeerDeleteRows } from "./ipsec-peer-delete.js"
import { ipsecUserUpdateValue } from "./ipsec-user-update.js"
import { sameWireguardEndpoint } from "./wireguard-source.js"
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { executeGuardedApplicationWrite } from "./config-mutation-policy.js"
import { captureAndAppendRevision } from "./config-revisions.js"
import { captureIpsecSnapshot, mapClients, type IpsecServerState } from "./ipsec-live.js"
import { buildClientInstructions, buildSswanConfig } from "./ipsec-config.js"
import { ipsecUserCreateRequest, planIpsecUserCreate, projectIpsecUserCreate, type IpsecUserCreateState } from "./ipsec-user-create-model.js"
export async function ipsecUserCreateProof(state: IpsecUserCreateState) { return (await privateFingerprinter("ipsec-user-create-v1"))(fingerprint(ipsecUserUpdateValue(state))) }
export async function readIpsecUserCreateState(server: ServerRow, authorize: () => Promise<unknown> = async () => {}) {
const state = await readIpsecPeerDeleteState(server, authorize)
await authorize()
state.catalogs["/file"] = ipsecPeerDeleteRows(await MikrotikClient.fromServer(server).get("/file", 10000, undefined, 1048576))
if (Buffer.byteLength(JSON.stringify(state)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Полное состояние создания IPsec превышает 1 МиБ", 502)
await authorize()
return { ...state, proof: await ipsecUserCreateProof(state) }
}
export class IpsecUserCreateExecutionError extends McpError {
constructor(code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED", message: string, readonly confirmedWrites: number, readonly completedCommands: number, readonly commandCount: number) { super(code, message, 502) }
}
export async function createIpsecUserGuarded(server: ServerRow, raw: unknown, expectedProof?: string, authorize: () => Promise<unknown> = async () => {}, options: { recordRevision?: typeof captureAndAppendRevision; receiptId?: string; exportPrefix?: string; checkpoint?: (value: { receiptId: string; commandCount: number; completedCommands: number; afterProof: string }) => Promise<unknown>; saveBundle?: (bundle: IpsecCertBundle, afterProof: string) => Promise<Record<string, unknown>> } = {}) {
const parsed = ipsecUserCreateRequest.parse(raw)
const body = { ...parsed, ...(parsed.authMethod === "certificate" && !parsed.passphrase?.trim() ? { passphrase: randomBytes(24).toString("base64url") } : {}) }
const receiptId = options.receiptId ?? randomUUID(), exportPrefix = options.exportPrefix ?? `mm-ipsec-${receiptId}`
return withApplicationMutationLock(() => withConfigMutationLock([server.id], () => executeGuardedApplicationWrite({ kind: "ipsec_user", id: body.name.trim() }, [server.id], async () => {
const source = async () => { await authorize(); const fresh = await getServerRowById(server.id); if (!fresh || !sameWireguardEndpoint(fresh, server)) throw new McpError("STATE_CONFLICT", "Источник IPsec изменился", 409) }
let state = await readIpsecUserCreateState(server, source)
if (expectedProof !== undefined && state.proof !== expectedProof) throw new McpError("STATE_CONFLICT", "IPsec или зависимости изменились после подготовки", 409)
const plan = planIpsecUserCreate(state, server, body, exportPrefix), client = MikrotikClient.fromServer(server), ownedCertificateIds = new Set<string>()
let completedCommands = 0, confirmedWrites = 0, bundle: IpsecCertBundle | undefined, artifactReceipt: Record<string, unknown> | undefined
const stopped = (code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED", message: string) => new IpsecUserCreateExecutionError(code, message, confirmedWrites, completedCommands, plan.commands.length)
for (const command of plan.commands) {
const stage = {
create: command.path === "/certificate" ? "создание сертификата" : command.path === "/ip/ipsec/mode-config" ? "назначение персонального IP" : "создание привязки IKEv2",
update: "обновление персонального IP",
sign: "подпись сертификата",
export: "экспорт .p12",
cleanup: "удаление временного .p12",
}[command.action]
const stoppedAtStage = (code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED", detail: string) =>
stopped(code, `Создание IKEv2 остановлено на этапе «${stage}». ${detail}`)
let dispatched = false, response: unknown, assignedId: string | undefined
const fence = async () => { const fresh = await readIpsecUserCreateState(server, source); if (fresh.proof !== state.proof) throw new McpError("STATE_CONFLICT", "IPsec изменился после durable intent; команда не отправлена", 409); await source(); dispatched = true }
try {
if (command.action === "cleanup") {
const row = state.catalogs["/file"].find(item => item.name === command.name)
if (!row) throw new McpError("STATE_CONFLICT", "Файл экспорта отсутствует", 409)
assignedId = row[".id"]
response = await client.delete(`/file/${encodeURIComponent(assignedId)}`, 10000, fence)
} else if (command.action === "create") response = await client.put(command.path, command.fields, 30000, fence)
else if (command.action === "update") response = await client.patch(`${command.path}/${encodeURIComponent(command.id!)}`, command.fields, 15000, fence)
else {
// RouterOS signs and exports by native id only; the certificate is the one this run created and ACKed.
const certificate = command.action === "sign" ? command.name : command.certificate
const id = state.catalogs["/certificate"].find(row => row.name === certificate && ownedCertificateIds.has(row[".id"]))?.[".id"]
if (!id) throw new McpError("STATE_CONFLICT", "Не подтверждён сертификат команды IPsec", 409)
response = await client.post(command.path, { ".id": id, ...command.fields }, command.action === "sign" ? 120000 : 60000, undefined, fence)
}
confirmedWrites++
} catch (error) {
if (!dispatched && !completedCommands && error instanceof McpError) throw error
const detail = !dispatched ? "Команда не отправлена." : error instanceof MikrotikError ? `RouterOS вернул HTTP ${error.statusCode}.` : "Ответ RouterOS не подтверждён."
throw stoppedAtStage(dispatched ? "MUTATION_OUTCOME_UNKNOWN" : "VERIFICATION_FAILED", `${detail} Перед повтором требуется сверка.`)
}
let after: IpsecUserCreateState
try {
after = await readIpsecUserCreateState(server, source)
// sign is asynchronous. Read-only polling never repeats the sign command.
if (command.action === "sign") {
const deadline = Date.now() + 90000
while (!after.catalogs["/certificate"].find(row => row.name === command.name)?.["invalid-after"] && Date.now() < deadline) { await new Promise(resolve => setTimeout(resolve, 1000)); after = await readIpsecUserCreateState(server, source) }
}
} catch { throw stoppedAtStage("MUTATION_OUTCOME_UNKNOWN", "Команда отправлена. Не удалось перечитать состояние RouterOS.") }
let exportIndex: number | undefined
if (command.action === "export") {
const files = after.catalogs["/file"]
const candidates = files.filter(row => row.name === command.name && !state.catalogs["/file"].some(old => old[".id"] === row[".id"]))
if (candidates.length !== 1) throw stoppedAtStage("VERIFICATION_FAILED", "В списке RouterOS не найден единственный новый файл с ожидаемым именем.")
assignedId = candidates[0][".id"]
exportIndex = files.indexOf(candidates[0])
}
try {
const path = command.action === "sign" ? "/certificate" : command.action === "export" ? "/file" : command.path
if (command.action === "create") {
const ack = response as Record<string, unknown> | null
if (typeof ack?.[".id"] !== "string") throw Error("missing create ACK")
assignedId = ack[".id"]
}
const observedRow = after.catalogs[path].find(row => command.action === "sign" ? row.name === command.name : row[".id"] === assignedId)
const projected = projectIpsecUserCreate(state, command, { assignedId, observedRow, ownedCertificateIds, exportIndex })
if (await ipsecUserCreateProof(projected) !== after.proof) throw Error("configuration mismatch")
if (command.action === "create" && command.path === "/certificate") ownedCertificateIds.add(assignedId!)
} catch { throw stoppedAtStage("VERIFICATION_FAILED", "Проверка результата команды и состояния IPsec не пройдена.") }
state = after; completedCommands++
try {
await source(); await options.checkpoint?.({ receiptId, commandCount: plan.commands.length, completedCommands, afterProof: state.proof })
if (command.action === "export") {
const file = state.catalogs["/file"].find(row => row[".id"] === assignedId)!, size = Number(file.size)
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_OWNED_FILE_BYTES) throw Error("private export exceeds the exact-ID /file/get limit of 61438 bytes")
await source()
const content = await client.downloadOwnedFile({ name: file.name, id: assignedId!, size }, { authorize: source })
try {
if (content.length !== size) throw Error("incomplete private export")
await source()
if ((await readIpsecUserCreateState(server, source)).proof !== state.proof) throw Error("export changed")
const p12B64 = content.toString("base64"), passphrase = body.passphrase!
bundle = { user: body.name, serverEndpoint: plan.serverEndpoint, filename: file.name, contentB64: p12B64, mime: "application/x-pkcs12", passphrase, sswanFilename: `${plan.certName}.sswan`, sswanContent: buildSswanConfig({ name: `IKEv2 ${plan.serverEndpoint}`, serverEndpoint: plan.serverEndpoint, serverId: plan.serverEndpoint, p12B64 }), instructions: buildClientInstructions({ userName: body.name, serverEndpoint: plan.serverEndpoint, p12Filename: file.name, passphrase, dns: plan.dns }) }
} finally { content.fill(0) }
}
} catch { throw stoppedAtStage("MUTATION_OUTCOME_UNKNOWN", "Команда подтверждена. Не удалось прочитать приватный файл или сохранить квитанцию.") }
}
const reader = { get: async (path: string) => { await source(); if (!Object.hasOwn(state.catalogs, path)) throw new McpError("STATE_UNAVAILABLE", "Неизвестный каталог истории IPsec", 502); return structuredClone(state.catalogs[path]) } } as unknown as MikrotikClient
let historyRecorded = false
try { await source(); historyRecorded = (await (options.recordRevision ?? captureAndAppendRevision)({ serverId: server.id, section: "ipsec", source: "apply", capture: () => captureIpsecSnapshot(server, reader) })) !== null } catch { /* Never replay native writes for history. */ }
if (options.saveBundle && bundle && historyRecorded) { try { await source(); artifactReceipt = await options.saveBundle(bundle, state.proof); bundle = undefined } catch { throw stopped("MUTATION_OUTCOME_UNKNOWN", "IPsec применён, но приватный артефакт не сохранён; повтор запрещён") } }
const c = state.catalogs
const live = { server, 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"] } as IpsecServerState
const created = mapClients(live).find(row => row.name === body.name.trim()) ?? null
return { ok: true, verified: true, receiptId, clientId: body.name.trim(), commandCount: plan.commands.length, completedCommands, confirmedWrites, afterProof: state.proof, historyRecorded, revisionRecorded: historyRecorded, state: "applied", client: created, ...(bundle ? { bundle } : {}), ...(artifactReceipt ?? {}), automaticReplay: false, forwardingVerified: false }
})))
}