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

70 lines
7.2 KiB
TypeScript

import { ipsecUserPatchSchema } 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 { MikrotikClient } from "./mikrotik.js"
import { readIpsecPeerDeleteState, ipsecPeerDeleteValue, type IpsecPeerDeleteState } from "./ipsec-peer-delete.js"
import { observedBoolean } from "./ospf-observed-values.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 } from "./ipsec-live.js"
import { planIpsecUserUpdate, projectIpsecUserUpdate } from "./ipsec-user-update-model.js"
export const ipsecUserUpdatePatchSchema = ipsecUserPatchSchema.strict()
export function ipsecUserUpdateValue(state: IpsecPeerDeleteState) {
const value = ipsecPeerDeleteValue(state)
for (const [path, key] of [["/ip/ipsec/identity", "disabled"], ["/ip/ipsec/mode-config", "responder"]]) for (const row of value.catalogs[path] ?? []) {
if (row[key] === undefined) continue
const observed = observedBoolean(row[key])
if (observed === null) throw new McpError("STATE_UNAVAILABLE", "Не подтверждён boolean IPsec", 502)
row[key] = String(observed)
}
return value
}
export async function ipsecUserUpdateProof(state: IpsecPeerDeleteState) { return (await privateFingerprinter("ipsec-user-update-v2"))(fingerprint(ipsecUserUpdateValue(state))) }
export async function readIpsecUserUpdateState(server: ServerRow, authorize: () => Promise<unknown> = async () => {}) {
const state = await readIpsecPeerDeleteState(server, authorize)
return { ...state, proof: await ipsecUserUpdateProof(state) }
}
export class IpsecUserUpdateExecutionError 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 updateIpsecUserGuarded(server: ServerRow, clientId: string, raw: unknown, expectedProof?: string, authorize: () => Promise<unknown> = async () => {}, options: { recordRevision?: typeof captureAndAppendRevision; receiptId?: string; checkpoint?: (value: { receiptId: string; commandCount: number; completedCommands: number; afterProof: string }) => Promise<unknown> } = {}) {
const patch = ipsecUserUpdatePatchSchema.parse(raw)
return withApplicationMutationLock(() => withConfigMutationLock([server.id], () => executeGuardedApplicationWrite({ kind: "ipsec_user", id: clientId }, [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 readIpsecUserUpdateState(server, source)
if (expectedProof !== undefined && state.proof !== expectedProof) throw new McpError("STATE_CONFLICT", "IPsec или зависимости изменились после подготовки", 409)
const plan = planIpsecUserUpdate(state, server, clientId, patch), client = MikrotikClient.fromServer(server)
let completedCommands = 0, confirmedWrites = 0
const stopped = (code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED", message: string) => new IpsecUserUpdateExecutionError(code, message, confirmedWrites, completedCommands, plan.commands.length)
for (const command of plan.commands) {
let dispatched = false, response: unknown
const fence = async () => { const fresh = await readIpsecUserUpdateState(server, source); if (fresh.proof !== state.proof) throw new McpError("STATE_CONFLICT", "IPsec изменился после durable intent; команда не отправлена", 409); await source(); dispatched = true }
try {
response = command.action === "create" ? await client.put(command.path, command.fields, 15000, fence) : command.action === "update" ? await client.patch(command.path + "/" + encodeURIComponent(command.id!), command.fields, 15000, fence) : await client.delete(command.path + "/" + encodeURIComponent(command.id!), 10000, fence)
confirmedWrites++
} catch (error) {
if (!dispatched && !completedCommands && error instanceof McpError) throw error
throw stopped(dispatched ? "MUTATION_OUTCOME_UNKNOWN" : "VERIFICATION_FAILED", "Изменение клиента IPsec остановлено; повтор команды запрещён, требуется сверка")
}
let after: IpsecPeerDeleteState
try { after = await readIpsecUserUpdateState(server, source) } catch { throw stopped("MUTATION_OUTCOME_UNKNOWN", "Команда отправлена, но read-back недоступен; повтор запрещён") }
try {
const assignedId = command.action === "create" ? (response as Record<string, unknown> | null)?.[".id"] : undefined
const createdRow = command.action === "create" ? after.catalogs[command.path].find(row => row[".id"] === assignedId) : undefined
if (command.action === "create" && typeof assignedId !== "string") throw Error("native create ACK missing")
const projected = projectIpsecUserUpdate(state, command, { assignedId: typeof assignedId === "string" ? assignedId : undefined, createdRow })
if (await ipsecUserUpdateProof(projected) !== after.proof) throw Error("configuration mismatch")
} catch { throw stopped("VERIFICATION_FAILED", "Не подтверждены изменение клиента и сохранность остальных объектов IPsec; повтор запрещён") }
state = after; completedCommands++
try { await source(); await options.checkpoint?.({ receiptId: options.receiptId ?? "", commandCount: plan.commands.length, completedCommands, afterProof: state.proof }) } 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 a native command for history. */ }
return { ok: true, verified: true, receiptId: options.receiptId ?? null, clientId, commandCount: plan.commands.length, completedCommands, confirmedWrites, afterProof: state.proof, historyRecorded, revisionRecorded: historyRecorded, state: "applied", ignoredFields: plan.ignoredFields, automaticReplay: false, forwardingVerified: false }
})))
}