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 } 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 = 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 = async () => {}, options: { recordRevision?: typeof captureAndAppendRevision; receiptId?: string; exportPrefix?: string; checkpoint?: (value: { receiptId: string; commandCount: number; completedCommands: number; afterProof: string }) => Promise; saveBundle?: (bundle: IpsecCertBundle, afterProof: string) => Promise> } = {}) { 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() let completedCommands = 0, confirmedWrites = 0, bundle: IpsecCertBundle | undefined, artifactReceipt: Record | 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) { 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 response = await client.post(command.path, command.fields, command.action === "sign" ? 120000 : 60000, undefined, fence) confirmedWrites++ } catch (error) { if (!dispatched && !completedCommands && error instanceof McpError) throw error throw stopped(dispatched ? "MUTATION_OUTCOME_UNKNOWN" : "VERIFICATION_FAILED", "Создание IPsec остановлено; повтор native-команды запрещён, требуется сверка") } 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 stopped("MUTATION_OUTCOME_UNKNOWN", "Команда отправлена, но read-back недоступен; повтор запрещён") } try { const path = command.action === "sign" ? "/certificate" : command.action === "export" ? "/file" : command.path if (command.action === "create") { const ack = response as Record | null if (typeof ack?.[".id"] !== "string") throw Error("missing create ACK") assignedId = ack[".id"] } else if (command.action === "export") { const candidates = after.catalogs["/file"].filter(row => row.name === command.name && !state.catalogs["/file"].some(old => old[".id"] === row[".id"])) if (candidates.length !== 1) throw Error("missing unique export file") assignedId = candidates[0][".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 }) if (await ipsecUserCreateProof(projected) !== after.proof) throw Error("configuration mismatch") if (command.action === "create" && command.path === "/certificate") ownedCertificateIds.add(assignedId!) } catch { throw stopped("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 stopped("MUTATION_OUTCOME_UNKNOWN", "Команда проверена, но checkpoint или приватный артефакт не сохранён; повтор запрещён") } } 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 } }))) }