import { isIP } from "node:net" import { randomUUID } from "node:crypto" import { pool } from "../db/index.js" import type { ServerRow } from "../modules/servers/repository/servers-repository.js" import { getServerRowById } from "../modules/servers/repository/servers-repository.js" import { fingerprint, McpError } from "../modules/mcp/security.js" import { readWireguardInterfaceCreateState, wireguardCreatePrefix, wireguardCreateKey } from "./wireguard-interface-create.js" import { wireguardConfigurationRows } from "./wireguard-peer-delete.js" import type { WireguardInterfaceDeleteState } from "./wireguard-interface-delete.js" import { observedBoolean } from "./ospf-observed-values.js" import { observedWireguardPeerKeepalive } from "./wireguard-peer-update.js" import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js" import { greStableRows } from "./gre-mutation-state.js" import { interfaceAddressPath } from "./entity-snapshots.js" import { toRosBody } from "./wireguard-ros.js" import { MikrotikClient, MikrotikError } from "./mikrotik.js" import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js" import { executeGuardedApplicationWrite } from "./config-mutation-policy.js" import { captureAndAppendRevision } from "./config-revisions.js" import { captureWireguardSnapshot } from "./wireguard-live.js" import { sameWireguardEndpoint } from "./wireguard-source.js" import { wireguardCorroboratedPrivateScalar, wireguardPrivateScalarsEqual } from "./wireguard-key-scalar.js" import { assertWireguardImportAllowed, wireguardImportPeerBody, wireguardImportStages, wireguardImportObjects, type WireguardImportPlan, type WireguardImportStage } from "./wireguard-import-plan.js" type State = WireguardInterfaceDeleteState type Row = Record export interface WireguardImportCheckpoint { completedCommands: number; commandCount: number; afterProof: string; interfaceId: string; peerIds: string[] } export interface WireguardImportCommand { method: "PUT" | "PATCH"; path: string; body: Row } export async function wireguardImportProtectionProof(serverId: number, objects: { kind: string; id: string }[]) { const rows = (await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1) OR EXISTS(SELECT 1 FROM jsonb_array_elements($2::jsonb) target WHERE target->>'kind'=object_ref->>'kind' AND target->>'id'=object_ref->>'id') ORDER BY id LIMIT 1001", [String(serverId), JSON.stringify(objects)])).rows if (rows.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Превышен предел защит импорта WireGuard", 409) return fingerprint(rows) } export class WireguardImportExecutionError extends McpError { constructor(public readonly state: "conflict" | "partial" | "needs-review", public readonly verifiedPrefixCommands: number, public readonly commandCount: number, public readonly lastVerifiedProof: string) { super(state === "conflict" ? "STATE_CONFLICT" : state === "partial" ? "VERIFICATION_FAILED" : "MUTATION_OUTCOME_UNKNOWN", state === "conflict" ? "Исходное состояние WireGuard изменилось; импорт не начат" : state === "partial" ? "RouterOS отклонил этап импорта; подтверждённый префикс сохранён. Очистка требует отдельного решения" : "Исход этапа импорта неизвестен; повтор и автоматическая очистка запрещены до сверки", state === "conflict" ? 409 : 502) } } function matches(row: Row, body: Row) { return Object.entries(body).every(([key, value]) => { if (key === "disabled") return observedBoolean(row[key]) === observedBoolean(value) if (key === "endpoint-port") return /^\d+$/.test(row[key] ?? "") && Number(row[key]) === Number(value) if (key === "persistent-keepalive") return observedWireguardPeerKeepalive(row[key] ?? "") === Number(value) if (key === "allowed-address") { try { return fingerprint(row[key].split(",").map(canonicalBgpPolicyPrefix).sort()) === fingerprint(value.split(",").map(canonicalBgpPolicyPrefix).sort()) } catch { return false } } if (key === "private-key" && value === "auto") return wireguardCreateKey.safeParse(row[key]).success if (key === "private-key" && value === "none") return row[key] === "none" || row[key] === "" return (row[key] ?? "") === value }) } function selected(state: State, plan: WireguardImportPlan) { const target = state.base.interfaces.find(row => row.name === plan.interface.name) const belongs = (row: Row) => !!target && [target.name, target[".id"]].includes(row.interface) return { target, belongs } } /** A complete prefix removes precisely this import's additions, then reuses the * existing interface graph proof for every original/foreign/opaque property. */ export async function wireguardImportPrefix(state: State, plan: WireguardImportPlan, baseline: string, count: number): Promise { const stages = wireguardImportStages(plan) if (!Number.isInteger(count) || count < 0 || count > stages.length) return false if (!count) return state.proof === baseline const done = stages.slice(0, count), { target, belongs } = selected(state, plan) if (!target) return false const created = done.filter(stage => stage.kind === "peer").map(stage => stage.peerIndex!) const peers = state.base.peers.filter(belongs) if (peers.length !== created.length) return false for (const index of created) { const rows = peers.filter(row => row["public-key"] === plan.peers[index].publicKey) if (rows.length !== 1 || ["dynamic", "builtin", "default"].some(key => rows[0][key] !== undefined && observedBoolean(rows[0][key]) !== false)) return false const body = wireguardImportPeerBody(plan, index) body.interface = rows[0].interface body.disabled = String(!done.some(stage => stage.kind === "peer-enable" && stage.peerIndex === index)) if (!matches(rows[0], body)) return false } const withoutPeers = structuredClone(state) withoutPeers.base.peers = withoutPeers.base.peers.filter(row => !belongs(row)) const interfaceCount = 1 + Number(done.some(stage => stage.kind === "address")) + Number(done.some(stage => stage.kind === "address-enable")) + Number(done.some(stage => stage.kind === "interface-enable")) return wireguardCreatePrefix(withoutPeers, plan.interface, baseline, interfaceCount) } /** Native defaults and generated secrets become immutable after first readback. */ export function wireguardImportPreserved(before: State, after: State, plan: WireguardImportPlan, stage: WireguardImportStage): boolean { const { target, belongs } = selected(before, plan) if (!target) return stage.kind === "interface" const enablingPeer = stage.kind === "peer-enable" ? plan.peers[stage.peerIndex!].publicKey : undefined for (const [oldRows, newRows, change, ownedInterfaceActivation] of [ [before.base.interfaces.filter(row => row[".id"] === target[".id"]), after.base.interfaces, (_row: Row) => stage.kind === "interface-enable", stage.kind === "interface-enable"], [before.base.peers.filter(belongs), after.base.peers, (row: Row) => stage.kind === "peer-enable" && row["public-key"] === enablingPeer, false], [before.ipv4.filter(row => belongs(row) && observedBoolean(row.dynamic) === false), after.ipv4, (_row: Row) => stage.kind === "address-enable", false], [before.ipv6.filter(row => belongs(row) && observedBoolean(row.dynamic) === false), after.ipv6, (_row: Row) => stage.kind === "address-enable", false], ] as const) for (const old of oldRows) { const row = newRows.find(value => value[".id"] === old[".id"]) if (!row) return false const stable = (value: Row) => fingerprint(greStableRows(wireguardConfigurationRows([{ ...value, disabled: String(observedBoolean(value.disabled)) }]))) const expected: Row = { ...old, ...(change(old) ? { disabled: "false" } : {}) }, observed: Row = { ...row } if (ownedInterfaceActivation && old["private-key"] !== row["private-key"]) { // RouterOS clamps ignored X25519 scalar bits on activation. Accept only // two valid secrets corroborated by the same observed public key, and // only for this import's selected interface during its activation stage. if (!wireguardPrivateScalarsEqual(old["private-key"], row["private-key"], old["public-key"])) return false const canonical = wireguardCorroboratedPrivateScalar(old["private-key"], old["public-key"])! expected["private-key"] = canonical; observed["private-key"] = canonical } if (stable(expected) !== stable(observed)) return false } return true } export function wireguardImportCommand(plan: WireguardImportPlan, stage: WireguardImportStage, state: State): WireguardImportCommand { const input = plan.interface, { target, belongs } = selected(state, plan) if (stage.kind === "interface") return { method: "PUT", path: "/interface/wireguard", body: toRosBody({ name: input.name, "listen-port": String(input.listenPort), mtu: String(input.mtu), comment: input.comment, "private-key": input.privateKey, disabled: "true" }) } if (stage.kind === "address") return { method: "PUT", path: interfaceAddressPath(input.address!), body: { address: input.address!, interface: input.name, disabled: "true", ...(isIP(input.address!.split("/")[0]) === 6 ? { advertise: "false" } : {}) } } if (stage.kind === "peer") return { method: "PUT", path: "/interface/wireguard/peers", body: wireguardImportPeerBody(plan, stage.peerIndex!) } const row = stage.kind === "interface-enable" ? target : stage.kind === "peer-enable" ? state.base.peers.find(row => belongs(row) && row["public-key"] === plan.peers[stage.peerIndex!].publicKey) : [...state.ipv4, ...state.ipv6].find(row => belongs(row) && observedBoolean(row.dynamic) === false) if (!row) throw new McpError("STATE_CONFLICT", "Не найден подготовленный объект WireGuard", 409) const path = stage.kind === "interface-enable" ? "/interface/wireguard" : stage.kind === "peer-enable" ? "/interface/wireguard/peers" : interfaceAddressPath(input.address!) return { method: "PATCH", path: path + "/" + encodeURIComponent(row[".id"]), body: { disabled: "false" } } } export async function executeWireguardImportStages(plan: WireguardImportPlan, baseline: string, deps: { authorize: () => Promise; read: () => Promise dispatch: (command: WireguardImportCommand, fence: () => Promise) => Promise checkpoint: (checkpoint: WireguardImportCheckpoint) => Promise }) { const stages = wireguardImportStages(plan) await deps.authorize() let state = await deps.read(), completed = 0 if (state.proof !== baseline) throw new WireguardImportExecutionError("conflict", 0, stages.length, baseline) assertWireguardImportAllowed(state, plan) for (const stage of stages) { let dispatched = false try { await deps.authorize() const fresh = await deps.read() if (fresh.proof !== state.proof) throw new WireguardImportExecutionError(completed ? "needs-review" : "conflict", completed, stages.length, state.proof) const fence = async () => { await deps.authorize() if ((await deps.read()).proof !== state.proof) throw new McpError("STATE_CONFLICT", "WireGuard изменился после durable intent; команда не отправлена", 409) await deps.authorize() dispatched = true } await deps.dispatch(wireguardImportCommand(plan, stage, fresh), fence) const after = await deps.read() if (!await wireguardImportPrefix(after, plan, baseline, completed + 1) || !wireguardImportPreserved(state, after, plan, stage)) throw Error("unverified prefix") await deps.authorize() const { target, belongs } = selected(after, plan) await deps.checkpoint({ completedCommands: completed + 1, commandCount: stages.length, afterProof: after.proof, interfaceId: target![".id"], peerIds: after.base.peers.filter(belongs).map(row => row[".id"]) }) completed++; state = after } catch (error) { if (!dispatched && error instanceof McpError && !completed) throw error if (dispatched && error instanceof MikrotikError && [400, 401, 403, 404, 405, 409, 422].includes(error.statusCode)) { try { await deps.authorize(); if ((await deps.read()).proof === state.proof) throw new WireguardImportExecutionError("partial", completed, stages.length, state.proof) } catch (confirmed) { if (confirmed instanceof WireguardImportExecutionError) throw confirmed } } throw new WireguardImportExecutionError("needs-review", completed, stages.length, state.proof) } } const { target, belongs } = selected(state, plan) return { ok: true as const, verified: true as const, interfaceId: target![".id"], peerIds: state.base.peers.filter(belongs).map(row => row[".id"]), peersCreated: plan.peers.length, commandCount: stages.length, completedCommands: completed, afterProof: state.proof, forwardingVerified: false as const, automaticReplay: false as const } } export async function executeWireguardImport(server: ServerRow, plan: WireguardImportPlan, expectedProof: string, authorize: () => Promise = async () => {}, options: { recordRevision?: boolean; checkpoint?: (checkpoint: WireguardImportCheckpoint) => Promise; receiptId?: string } = {}) { if (plan.interface.serverId !== server.id) throw new McpError("INVALID_INPUT", "Сервер импорта не совпал", 400) const objects = wireguardImportObjects(plan, options.receiptId ?? randomUUID()) return withApplicationMutationLock(() => withConfigMutationLock([server.id], async () => { await authorize() // Capture before the shared durable application intent, including REST's // default context. A newly protected logical child cannot become baseline. const protectionProof = await wireguardImportProtectionProof(server.id, objects) return executeGuardedApplicationWrite({ kind: "wireguard-import", id: "1" }, [server.id], async () => { const source = async () => { await authorize() const fresh = await getServerRowById(server.id) if (!fresh || !sameWireguardEndpoint(fresh, server) || await wireguardImportProtectionProof(server.id, objects) !== protectionProof) throw new McpError("STATE_CONFLICT", "Источник или защиты WireGuard изменились", 409) } const client = MikrotikClient.fromServer(server) const receipt = await executeWireguardImportStages(plan, expectedProof, { authorize: source, read: () => readWireguardInterfaceCreateState(server, source), dispatch: (command, fence) => command.method === "PUT" ? client.put(command.path, command.body, 15000, fence) : client.patch(command.path, command.body, 15000, fence), checkpoint: options.checkpoint ?? (async () => {}), }) let revisionRecorded = false try { if (options.recordRevision !== false) revisionRecorded = await captureAndAppendRevision({ serverId: server.id, section: "wireguard", source: "copy", capture: () => captureWireguardSnapshot(server, source) }) !== null } catch { /* Never replay native import to repair revision storage. */ } await source() return { ...receipt, revisionRecorded } }, async () => objects) })) }