import { createPrivateKey, createPublicKey } from "node:crypto" import { isIP } from "node:net" import { z } from "zod" import { pool } from "../db/index.js" import { wgCreateInterfaceSchema, wgCreatePeerSchema } from "@mmapp/contracts/wireguard" import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js" import { fingerprint, McpError } from "../modules/mcp/security.js" import { readWireguardInterfaceDeleteState, wireguardInterfaceDeleteProof, type WireguardInterfaceDeleteState } from "./wireguard-interface-delete.js" import { assertGreDeleteDependencies, greStableRows } from "./gre-mutation-state.js" import { wireguardConfigurationRows } from "./wireguard-peer-delete.js" import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js" import { observedBoolean } from "./ospf-observed-values.js" import { observedWireguardPeerKeepalive } from "./wireguard-peer-update.js" import { interfaceAddressPath, interfaceAddressKey } from "./entity-snapshots.js" import { toRosBody } from "./wireguard-ros.js" import { MikrotikClient } 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 { wireguardCorroboratedPrivateScalar, wireguardPrivateScalarsEqual } from "./wireguard-key-scalar.js" const text = z.string().max(1000).refine(value => !/[\u0000-\u001f\u007f]/.test(value)) export const wireguardCreateKey = z.string().regex(/^[A-Za-z0-9+/]{43}=$/).refine(value => Buffer.from(value, "base64").toString("base64") === value && Buffer.from(value, "base64").some(byte => byte !== 0)) const peerSchema = wgCreatePeerSchema.extend({ publicKey: wireguardCreateKey, allowedAddresses: z.array(z.string().max(100).refine(value => { try { canonicalBgpPolicyPrefix(value); return true } catch { return false } })).min(1).max(100), endpointAddress: text.max(253).optional(), endpointPort: z.number().int().min(1).max(65535).optional(), persistentKeepalive: z.number().int().min(0).max(65535).optional(), comment: text.optional(), name: text.max(128).optional(), privateKey: z.union([wireguardCreateKey, z.enum(["auto", "none"])]).optional(), clientAddress: text.optional(), clientDns: text.optional(), clientEndpoint: text.optional() }).strict() export const wireguardInterfaceCreateSchema = wgCreateInterfaceSchema.extend({ serverId: z.number().int().positive().safe(), name: text.min(1).max(64).refine(value => value.trim().length > 0), listenPort: z.number().int().min(1).max(65535).default(13231), mtu: z.number().int().min(1).max(65535).default(1420), comment: text.optional(), privateKey: wireguardCreateKey.optional(), peer: peerSchema.optional() }).strict() export type WireguardInterfaceCreate = z.infer type State = WireguardInterfaceDeleteState type Row = Record const fail = (code: string, message: string) => new McpError(code, message, code === "INVALID_INPUT" ? 400 : ["STATE_UNAVAILABLE", "MUTATION_OUTCOME_UNKNOWN", "VERIFICATION_FAILED"].includes(code) ? 502 : 409) export const readWireguardInterfaceCreateState = (server: ServerRow, authorize: () => Promise = async () => {}) => readWireguardInterfaceDeleteState(server, "*0", authorize) export async function wireguardCreateProtectionProof(serverId: number) { 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) ORDER BY id LIMIT 1001", [String(serverId)]) if (rows.length > 1000) throw fail("STATE_UNAVAILABLE", "Превышен предел защит WireGuard") return fingerprint(rows) } export function wireguardPublicKey(privateKey: string) { const key = createPrivateKey({ key: Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), Buffer.from(privateKey, "base64")]), format: "der", type: "pkcs8" }) return createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64") } export function wireguardCreatePeerBody(input: WireguardInterfaceCreate) { const peer = input.peer! return toRosBody({ interface: input.name, "public-key": peer.publicKey, "allowed-address": peer.allowedAddresses.join(","), "endpoint-address": peer.endpointAddress, "endpoint-port": peer.endpointPort === undefined ? undefined : String(peer.endpointPort), "persistent-keepalive": peer.persistentKeepalive === undefined ? undefined : String(peer.persistentKeepalive), comment: peer.comment, name: peer.name, "private-key": peer.privateKey, "client-address": peer.clientAddress, "client-dns": peer.clientDns, "client-endpoint": peer.clientEndpoint, disabled: "true" }) } export function wireguardCreateStages(input: WireguardInterfaceCreate) { return ["interface", ...(input.address ? ["address"] : []), ...(input.peer ? ["peer", ...(input.peer.disabled ? [] : ["peer-enable"])] : []), ...(input.address ? ["address-enable"] : []), ...(input.disabled ? [] : ["interface-enable"])] } export function assertWireguardCreateAllowed(state: State, input: WireguardInterfaceCreate) { if (input.name === "wg-flow" || input.comment === "MikrotikManager traffic-flow overlay" || input.peer?.comment === "MM traffic-flow collector" || input.peer?.name === "mm-collector" || input.peer?.publicKey === state.base.flow.hostPublicKey) throw fail("PROTECTED_OBJECT", "Имя или peer зарезервированы сервисом NetFlow") if (state.base.interfaces.some(row => row.name === input.name) || state.dependencies["/interface"].some(row => row.name === input.name)) throw fail("STATE_CONFLICT", "Имя интерфейса уже занято") try { assertGreDeleteDependencies({ dependencies: state.dependencies, bindings: state.base.bindings, filters: state.filters }, { ".id": "*0", name: input.name }, "Новый WireGuard") } catch { throw fail("DEPENDENCY_CONFLICT", "Новый WireGuard используется существующей конфигурацией или привязкой; сначала измените зависимости") } if (state.dependencies["/ip/vrf"].some(row => row.name !== "main" && row.interfaces?.split(",").includes("all"))) throw fail("DEPENDENCY_CONFLICT", "Новый интерфейс попадёт в существующий VRF selector; требуется отдельный план VRF") if (input.address) { const ip = input.address.split("/")[0], family = isIP(ip) const exact = (value: string) => { try { return canonicalBgpPolicyPrefix(value + (family === 4 ? "/32" : "/128")) } catch { return null } } if ([...state.ipv4, ...state.ipv6].some(row => isIP(row.address?.split("/")[0]) === family && exact(row.address.split("/")[0]) === exact(ip))) throw fail("DEPENDENCY_CONFLICT", "Локальный адрес уже используется") for (const row of state.dependencies["/routing/ospf/interface-template"]) for (const network of (row.networks ?? "").split(",").filter(Boolean)) { try { if (isIP(network.split("/")[0]) === family && canonicalBgpPolicyPrefix(ip + "/" + network.split("/")[1]) === canonicalBgpPolicyPrefix(network)) throw fail("DEPENDENCY_CONFLICT", "Адрес активирует существующий сетевой selector OSPF") } catch (error) { if (error instanceof McpError) throw error; throw fail("STATE_UNAVAILABLE", "Не подтверждён selector OSPF") } } } } function matches(row: Row, body: Record) { return Object.entries(body).every(([key, value]) => { if (key === "disabled" || key === "advertise") return observedBoolean(row[key]) === observedBoolean(value) if (["mtu", "listen-port", "endpoint-port"].includes(key)) return /^\d+$/.test(row[key] ?? "") && Number(row[key]) === Number(value) if (key === "persistent-keepalive") return observedWireguardPeerKeepalive(row[key] ?? "") === Number(value) if (key === "address") { try { return interfaceAddressKey(row[key]) === interfaceAddressKey(value) } catch { return false } } 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 }) } /** Strip exactly the verified additions; seal every other object and opaque property. */ export async function wireguardCreatePrefix(state: State, input: WireguardInterfaceCreate, baseline: string, stageCount: number) { const stages = wireguardCreateStages(input), done = new Set(stages.slice(0, stageCount)), next = structuredClone(state) if (!Number.isInteger(stageCount) || stageCount < 0 || stageCount > stages.length) return false const selected = next.base.interfaces.filter(row => row.name === input.name) if (!done.has("interface")) return selected.length === 0 && state.proof === baseline if (selected.length !== 1) return false const target = selected[0], id = target[".id"], generic = next.dependencies["/interface"].filter(row => row.name === input.name || row[".id"] === id) if (generic.length !== 1 || generic[0][".id"] !== id || generic[0].name !== input.name) return false if (["dynamic", "builtin", "default"].some(key => target[key] !== undefined && observedBoolean(target[key]) !== false)) return false if (!matches(target, { name: input.name, "listen-port": String(input.listenPort), mtu: String(input.mtu), comment: input.comment ?? "", disabled: String(!done.has("interface-enable")) })) return false if (input.privateKey ? target["public-key"] !== wireguardPublicKey(input.privateKey) : !wireguardCreateKey.safeParse(target["public-key"]).success) return false if (input.privateKey && target["private-key"] !== undefined && !wireguardPrivateScalarsEqual(target["private-key"], input.privateKey, target["public-key"])) return false const belongs = (row: Row) => [id, input.name].includes(row.interface) const peers = next.base.peers.filter(belongs) if (peers.length !== (done.has("peer") ? 1 : 0)) return false if (peers.length) { const body = wireguardCreatePeerBody(input); body.interface = peers[0].interface; body.disabled = String(!done.has("peer-enable")) if (!matches(peers[0], body) || ["dynamic", "builtin", "default"].some(key => peers[0][key] !== undefined && observedBoolean(peers[0][key]) !== false)) return false } const addressRows = [...next.ipv4, ...next.ipv6].filter(row => belongs(row) && !(observedBoolean(row.dynamic) === true && /^fe80:/i.test(row.address ?? ""))) if (addressRows.length !== (done.has("address") ? 1 : 0)) return false if (addressRows.length) { const address = addressRows[0] if (observedBoolean(address.dynamic) !== false || !matches(address, { address: input.address!, disabled: String(!done.has("address-enable")), ...(isIP(input.address!.split("/")[0]) === 6 ? { advertise: "false" } : {}) })) return false if (!(isIP(input.address!.split("/")[0]) === 4 ? next.ipv4 : next.ipv6).includes(address)) return false } next.base.interfaces = next.base.interfaces.filter(row => row[".id"] !== id) next.base.peers = next.base.peers.filter(row => !belongs(row)) next.ipv4 = next.ipv4.filter(row => !belongs(row)); next.ipv6 = next.ipv6.filter(row => !belongs(row)) next.dependencies["/interface"] = next.dependencies["/interface"].filter(row => row[".id"] !== id) return await wireguardInterfaceDeleteProof(next) === baseline } /** Native defaults become sealed after the first read-back of each new object. */ export function wireguardCreatePreserved(before: State, after: State, input: WireguardInterfaceCreate, stage: string) { const target = before.base.interfaces.find(row => row.name === input.name) if (!target) return stage === "interface" const belongs = (row: Row) => [input.name, target[".id"]].includes(row.interface) for (const [oldRows, newRows, allowed, interfaceActivation] of [ [before.base.interfaces.filter(row => row[".id"] === target[".id"]), after.base.interfaces, stage === "interface-enable", stage === "interface-enable"], [before.base.peers.filter(belongs), after.base.peers, stage === "peer-enable", false], [before.ipv4.filter(row => belongs(row) && observedBoolean(row.dynamic) === false), after.ipv4, stage === "address-enable", false], [before.ipv6.filter(row => belongs(row) && observedBoolean(row.dynamic) === false), after.ipv6, stage === "address-enable", false], ] as const) for (const old of oldRows) { const current = newRows.find(row => row[".id"] === old[".id"]) if (!current) return false const expected: Row = { ...old, ...(allowed ? { disabled: "false" } : {}) } const observed: Row = { ...current } if (interfaceActivation) { const first = wireguardCorroboratedPrivateScalar(expected["private-key"], expected["public-key"]), second = wireguardCorroboratedPrivateScalar(observed["private-key"], observed["public-key"]) if (first !== undefined && second !== undefined && first === second) { expected["private-key"] = first; observed["private-key"] = second } } if (fingerprint(greStableRows(wireguardConfigurationRows([expected]))) !== fingerprint(greStableRows(wireguardConfigurationRows([observed])))) return false } return true } export async function createWireguardInterface(server: ServerRow, raw: unknown, expectedProof?: string, authorize: () => Promise = async () => {}, options: { recordRevision?: boolean; authorizeWrite?: () => Promise } = {}) { const parsed = wireguardInterfaceCreateSchema.safeParse(raw) if (!parsed.success || parsed.data.serverId !== server.id) throw fail("INVALID_INPUT", "Некорректные параметры создания WireGuard") const input = parsed.data let protectionProof: string | undefined // `authorize` guards reads (may reuse a stage proof); the pre-dispatch fence re-proves rights. const source = async () => { await (options.authorizeWrite ?? authorize)() const fresh = await getServerRowById(server.id) if (!fresh?.enabled || fingerprint(fresh) !== fingerprint(server)) throw fail("STATE_CONFLICT", "Источник WireGuard изменился") if (protectionProof !== undefined && await wireguardCreateProtectionProof(server.id) !== protectionProof) throw fail("STATE_CONFLICT", "Защиты WireGuard изменились; требуется новый план") } return withApplicationMutationLock(() => withConfigMutationLock([server.id], () => executeGuardedApplicationWrite({ kind: "wireguard", id: input.name }, [server.id], async () => { protectionProof = await wireguardCreateProtectionProof(server.id) let state = await readWireguardInterfaceCreateState(server, authorize) if (expectedProof && state.proof !== expectedProof) throw fail("STATE_CONFLICT", "WireGuard или зависимости изменились после подготовки") assertWireguardCreateAllowed(state, input) const baseline = state.proof, stages = wireguardCreateStages(input), client = MikrotikClient.fromServer(server) for (let index = 0; index < stages.length; index++) { const fresh = await readWireguardInterfaceCreateState(server, authorize) if (fresh.proof !== state.proof) throw fail(index ? "VERIFICATION_FAILED" : "STATE_CONFLICT", "Конфигурация изменилась между командами WireGuard") const stage = stages[index], target = fresh.base.interfaces.find(row => row.name === input.name) const dispatchFence = async () => { const current = await readWireguardInterfaceCreateState(server, authorize) if (current.proof !== fresh.proof) throw fail(index ? "VERIFICATION_FAILED" : "STATE_CONFLICT", "WireGuard изменился после записи native intent; команда не отправлена") await source() } await source() try { if (stage === "interface") await client.put("/interface/wireguard", toRosBody({ name: input.name, "listen-port": String(input.listenPort), mtu: String(input.mtu), comment: input.comment, "private-key": input.privateKey, disabled: "true" }), 15000, dispatchFence) else if (stage === "address") await client.put(interfaceAddressPath(input.address!), { address: input.address!, interface: input.name, disabled: "true", ...(isIP(input.address!.split("/")[0]) === 6 ? { advertise: "false" } : {}) }, 15000, dispatchFence) else if (stage === "peer") await client.put("/interface/wireguard/peers", wireguardCreatePeerBody(input), 15000, dispatchFence) else if (stage === "interface-enable") await client.patch("/interface/wireguard/" + encodeURIComponent(target![".id"]), { disabled: "false" }, 15000, dispatchFence) else if (stage === "peer-enable") await client.patch("/interface/wireguard/peers/" + encodeURIComponent(fresh.base.peers.find(row => [input.name, target![".id"]].includes(row.interface))![".id"]), { disabled: "false" }, 15000, dispatchFence) else { const rows = isIP(input.address!.split("/")[0]) === 4 ? fresh.ipv4 : fresh.ipv6; await client.patch(interfaceAddressPath(input.address!) + "/" + encodeURIComponent(rows.find(row => [input.name, target![".id"]].includes(row.interface) && observedBoolean(row.dynamic) === false)![".id"]), { disabled: "false" }, 15000, dispatchFence) } } catch (error) { if (error instanceof McpError) throw error; throw fail("MUTATION_OUTCOME_UNKNOWN", "Исход команды создания WireGuard неизвестен; выполнение остановлено без повтора") } const prior = state try { state = await readWireguardInterfaceCreateState(server, authorize) } catch { throw fail("MUTATION_OUTCOME_UNKNOWN", "Команда WireGuard отправлена, read-back недоступен; повтор запрещён") } if (!await wireguardCreatePrefix(state, input, baseline, index + 1)) throw fail("VERIFICATION_FAILED", "Создание WireGuard или сохранность зависимостей не подтверждены; повтор запрещён") if (!wireguardCreatePreserved(prior, state, input, stage)) throw fail("VERIFICATION_FAILED", "Сохранность ранее подготовленных объектов WireGuard не подтверждена; повтор запрещён") } let revisionRecorded = false try { if (options.recordRevision !== false) revisionRecorded = await captureAndAppendRevision({ serverId: server.id, section: "wireguard", source: "apply", capture: () => captureWireguardSnapshot(server, source) }) !== null } catch { /* Never repeat native creation to repair revision storage. */ } return { ok: true, verified: true, interfaceId: state.base.interfaces.find(row => row.name === input.name)![".id"], afterProof: state.proof, commandCount: stages.length, revisionRecorded, forwardingVerified: false } }))) }