98 lines
9.7 KiB
TypeScript
98 lines
9.7 KiB
TypeScript
import { randomUUID } from "node:crypto"
|
|
import type { ServerRow } from "../modules/servers/repository/servers-repository.js"
|
|
import { getServerRowById } from "../modules/servers/repository/servers-repository.js"
|
|
import { McpError, fingerprint, privateFingerprinter } from "../modules/mcp/security.js"
|
|
import { MikrotikClient } from "./mikrotik.js"
|
|
import { readIpsecPeerDeleteState, ipsecPeerDeleteRows, ipsecPeerDeleteValue } from "./ipsec-peer-delete.js"
|
|
import { sameWireguardEndpoint } from "./wireguard-source.js"
|
|
import { observedBoolean } from "./ospf-observed-values.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, mapServerSummary, type IpsecServerState } from "./ipsec-live.js"
|
|
import { ipsecServerInitRequest, planIpsecServerInit, projectIpsecServerInit, validateIpsecServerInitState, type IpsecServerInitState } from "./ipsec-server-init-model.js"
|
|
import { ipsecExternalPoolDependencyPaths, ipsecPoolDependencies } from "./ipsec-pool-dependencies.js"
|
|
|
|
export function ipsecServerInitValue(state: IpsecServerInitState) {
|
|
const value = ipsecPeerDeleteValue(state)
|
|
for (const rows of Object.values(value.catalogs)) for (const row of rows) for (const key of ["disabled", "responder", "template", "nat-traversal", "passive", "trusted"]) {
|
|
if (row[key] === undefined) continue
|
|
const boolean = observedBoolean(row[key])
|
|
if (boolean === null) throw new McpError("STATE_UNAVAILABLE", "Не подтверждён boolean IPsec", 502)
|
|
row[key] = String(boolean)
|
|
}
|
|
return value
|
|
}
|
|
export async function ipsecServerInitProof(state: IpsecServerInitState) { return (await privateFingerprinter("ipsec-server-init-v2"))(fingerprint(ipsecServerInitValue(state))) }
|
|
export async function readIpsecServerInitState(server: ServerRow, authorize: () => Promise<unknown> = async () => {}) {
|
|
const source = async () => { await authorize(); const fresh = await getServerRowById(server.id); if (!fresh || !sameWireguardEndpoint(fresh, server)) throw new McpError("STATE_CONFLICT", "Источник IPsec изменился во время полного чтения", 409) }
|
|
const state = await readIpsecPeerDeleteState(server, source)
|
|
// Always bind NAT source catalogs, including plans which opt out of NAT.
|
|
for (const path of ["/ip/route", "/interface", ...ipsecExternalPoolDependencyPaths]) {
|
|
await source()
|
|
state.catalogs[path] = ipsecPeerDeleteRows(await MikrotikClient.fromServer(server).get(path, 10000, undefined, 1048576))
|
|
await source()
|
|
if (Buffer.byteLength(JSON.stringify(state)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Полное состояние инициализации IPsec превышает 1 МиБ", 502)
|
|
}
|
|
if (Buffer.byteLength(JSON.stringify(state)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Полное состояние инициализации IPsec превышает 1 МиБ", 502)
|
|
validateIpsecServerInitState(state, true)
|
|
ipsecPoolDependencies(state.catalogs)
|
|
await source()
|
|
return { ...state, proof: await ipsecServerInitProof(state) }
|
|
}
|
|
export class IpsecServerInitExecutionError 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 initIpsecServerGuarded(server: ServerRow, 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 body = ipsecServerInitRequest.parse(raw), receiptId = options.receiptId ?? randomUUID()
|
|
return withApplicationMutationLock(() => withConfigMutationLock([server.id], () => executeGuardedApplicationWrite({ kind: "ipsec_server", id: String(server.id) }, [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 readIpsecServerInitState(server, source)
|
|
if (expectedProof !== undefined && state.proof !== expectedProof) throw new McpError("STATE_CONFLICT", "IPsec или зависимости изменились после подготовки", 409)
|
|
const plan = planIpsecServerInit(state, server, body), client = MikrotikClient.fromServer(server), ownedCertificateIds = new Set<string>()
|
|
let completedCommands = 0, confirmedWrites = 0
|
|
const stopped = (code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED", message: string) => new IpsecServerInitExecutionError(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 readIpsecServerInitState(server, source); if (fresh.proof !== state.proof) throw new McpError("STATE_CONFLICT", "IPsec изменился после durable intent; команда не отправлена", 409); await source(); dispatched = true }
|
|
try {
|
|
if (command.action === "create") response = await client.put(command.path, command.fields, 30000, fence)
|
|
else if (command.action === "update") {
|
|
const id = command.id ?? state.catalogs[command.path].find(row => row.name === command.name && ownedCertificateIds.has(row[".id"]))?.[".id"]
|
|
if (!id) throw new McpError("STATE_CONFLICT", "Не подтверждён объект изменения IPsec", 409)
|
|
response = await client.patch(`${command.path}/${encodeURIComponent(id)}`, command.fields, 15000, fence)
|
|
} else response = await client.post(command.path, command.fields, 120000, 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: IpsecServerInitState
|
|
try {
|
|
after = await readIpsecServerInitState(server, source)
|
|
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 readIpsecServerInitState(server, source) }
|
|
}
|
|
} catch { throw stopped("MUTATION_OUTCOME_UNKNOWN", "Команда отправлена, но read-back недоступен; повтор запрещён") }
|
|
try {
|
|
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 path = command.action === "sign" ? "/certificate" : command.path
|
|
const observedRow = after.catalogs[path].find(row => command.action === "sign" ? row.name === command.name : row[".id"] === assignedId)
|
|
const projected = projectIpsecServerInit(state, command, { assignedId, observedRow, ownedCertificateIds })
|
|
if (await ipsecServerInitProof(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 }) }
|
|
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. */ }
|
|
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
|
|
return { ok: true, verified: historyRecorded, receiptId, serverId: server.id, commandCount: plan.commands.length, completedCommands, confirmedWrites, afterProof: state.proof, historyRecorded, revisionRecorded: historyRecorded, state: "applied", summary: mapServerSummary(live, mapClients(live)), automaticReplay: false, forwardingVerified: false }
|
|
})))
|
|
}
|