Files
MikrotikManager/backend/src/services/wireguard-import-plan.ts
T

75 lines
6.2 KiB
TypeScript

import { parseWireguardImport } from "./wireguard-import.js"
import { WG_CONFIG_LIMITS } from "./wireguard-config.js"
import { z } from "zod"
import { wireguardInterfaceCreateSchema, wireguardCreatePeerBody, assertWireguardCreateAllowed, wireguardCreateKey, type WireguardInterfaceCreate } from "./wireguard-interface-create.js"
import { wireguardPeerCreateSchema } from "./wireguard-peer-create.js"
import type { WireguardInterfaceDeleteState } from "./wireguard-interface-delete.js"
import { McpError, redact } from "../modules/mcp/security.js"
export const WIREGUARD_IMPORT_MAX_BYTES = WG_CONFIG_LIMITS.bytes
export const WIREGUARD_IMPORT_MAX_PEERS = WG_CONFIG_LIMITS.peers
const comment = z.string().max(1000).refine(value => !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value)).optional()
const importInterfaceSchema = wireguardInterfaceCreateSchema.extend({ comment })
const importPeerSchema = wireguardPeerCreateSchema.extend({ comment })
export interface WireguardImportPlan {
format: "rsc" | "conf"
interface: WireguardInterfaceCreate
peers: NonNullable<WireguardInterfaceCreate["peer"]>[]
}
export type WireguardImportStage = { kind: "interface" | "address" | "peer" | "peer-enable" | "address-enable" | "interface-enable"; peerIndex?: number }
const invalid = (message: string) => new McpError("INVALID_INPUT", message, 400)
/** Raw content is accepted only by the shared human REST boundary. MCP resolves
* its owner/purpose/server content reference before calling this function. */
export function parseWireguardImportPlan(content: string, format: "auto" | "rsc" | "conf", serverId: number): WireguardImportPlan {
if (typeof content !== "string" || Buffer.byteLength(content) > WIREGUARD_IMPORT_MAX_BYTES) throw invalid("Конфигурация WireGuard превышает 256 КиБ")
let parsed
try { parsed = parseWireguardImport(content, format) } catch { throw invalid("Конфигурация WireGuard не поддерживается или содержит некорректные параметры") }
if (parsed.peers.length > WIREGUARD_IMPORT_MAX_PEERS) throw invalid("Импорт WireGuard превышает 100 пиров")
const iface = importInterfaceSchema.safeParse({ serverId, ...parsed.interface })
if (!iface.success) throw invalid("Некорректные параметры интерфейса WireGuard")
const peers = parsed.peers.map(peer => {
const result = importPeerSchema.safeParse({ serverId, interfaceName: iface.data.name, ...peer })
if (!result.success) throw invalid("Некорректные параметры пира WireGuard")
const { serverId: _server, interfaceName: _name, ...fields } = result.data
return fields
})
if (new Set(peers.map(peer => peer.publicKey)).size !== peers.length || new Set(peers.filter(peer => peer.name).map(peer => peer.name)).size !== peers.filter(peer => peer.name).length) throw invalid("Импорт содержит повторяющиеся ключи или имена пиров")
return { format: parsed.format, interface: iface.data, peers }
}
export function wireguardImportStages(plan: WireguardImportPlan): WireguardImportStage[] {
return [{ kind: "interface" }, ...(plan.interface.address ? [{ kind: "address" as const }] : []),
...plan.peers.map((_, peerIndex) => ({ kind: "peer" as const, peerIndex })),
...plan.peers.flatMap((peer, peerIndex) => peer.disabled ? [] : [{ kind: "peer-enable" as const, peerIndex }]),
...(plan.interface.address ? [{ kind: "address-enable" as const }] : []), ...(plan.interface.disabled ? [] : [{ kind: "interface-enable" as const }])]
}
/** Every logical object consumes the plan's object budget. Opaque IDs bind
* protections to the sealed receipt without exposing imported names or keys. */
export function wireguardImportObjects(plan: WireguardImportPlan, receiptId: string) {
if (!z.string().uuid().safeParse(receiptId).success) throw invalid("Нет идентификатора плана импорта")
const serverId = plan.interface.serverId
return [{ kind: "server", id: String(serverId), serverId }, { kind: "wireguard-import", id: "1", serverId },
{ kind: "wireguard", id: `${receiptId}:interface`, serverId },
...(plan.interface.address ? [{ kind: "interface-address", id: `${receiptId}:address`, serverId }] : []),
...plan.peers.map((_, index) => ({ kind: "wireguard_peer", id: `${receiptId}:peer:${index}`, serverId }))]
}
export function assertWireguardImportAllowed(state: WireguardInterfaceDeleteState, plan: WireguardImportPlan): void {
assertWireguardCreateAllowed(state, plan.interface)
for (const peer of plan.peers) assertWireguardCreateAllowed(state, { ...plan.interface, peer })
}
export function wireguardImportPeerBody(plan: WireguardImportPlan, index: number) {
const peer = plan.peers[index]
if (!peer) throw invalid("Не найден пир этапа WireGuard")
return wireguardCreatePeerBody({ ...plan.interface, peer })
}
/** Preview never contains key material, including public keys or literal keys
* echoed into names/comments by the imported document. */
export function wireguardImportPreview(plan: WireguardImportPlan) {
const keys = [plan.interface.privateKey, ...plan.peers.flatMap(peer => [peer.publicKey, peer.privateKey])].filter((value): value is string => typeof value === "string" && wireguardCreateKey.safeParse(value).success)
const scrub = (value: unknown): unknown => typeof value === "string" ? keys.reduce((text, key) => text.split(key).join("[KEY]"), value) : Array.isArray(value) ? value.map(scrub) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([key, field]) => [key, scrub(field)])) : value
const { privateKey, peer: _peer, serverId: _serverId, ...iface } = plan.interface
return scrub(redact({ format: plan.format, interface: { ...iface, privateKeyConfigured: Boolean(privateKey) },
peers: plan.peers.map(({ publicKey: _public, privateKey: key, ...peer }, index) => ({ ...peer, index, publicKeyConfigured: true, privateKeyConfigured: Boolean(key), keyMode: key === "auto" || key === "none" ? key : key ? "stored" : "omitted" })),
peerCount: plan.peers.length, commandCount: wireguardImportStages(plan).length, stagedDisabled: true, automaticCompensation: false, automaticReplay: false }))
}