Files
MikrotikManager/backend/src/services/wireguard-interface-update.ts
T

163 lines
17 KiB
TypeScript

import { z } from "zod"
import { wgPatchInterfaceSchema } from "@mmapp/contracts/wireguard"
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
import { fingerprint, McpError, privateFingerprinter } from "../modules/mcp/security.js"
import { readWireguardInterfaceDeleteState, planWireguardInterfaceDelete, wireguardInterfaceDeleteProof, type WireguardInterfaceDeleteState } from "./wireguard-interface-delete.js"
import { wireguardCreateKey, wireguardPublicKey, wireguardCreateProtectionProof, assertWireguardCreateAllowed } from "./wireguard-interface-create.js"
import { observedBoolean, observedInteger } from "./ospf-observed-values.js"
import { interfaceAddressKey, interfaceAddressPath } from "./entity-snapshots.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 { sameWireguardEndpoint } from "./wireguard-source.js"
import { greStableRows } from "./gre-mutation-state.js"
import { wireguardConfigurationRows } from "./wireguard-peer-delete.js"
import { wireguardCorroboratedPrivateScalar, wireguardPrivateScalarsEqual } from "./wireguard-key-scalar.js"
const text = z.string().max(1000).refine(value => !/[\u0000-\u001f\u007f]/.test(value))
export const wireguardInterfaceUpdateSchema = wgPatchInterfaceSchema.extend({ name: text.min(1).max(64).refine(value => value.trim().length > 0).optional(), listenPort: z.number().int().min(1).max(65535).optional(), mtu: z.number().int().min(1).max(65535).optional(), comment: text.optional(), privateKey: wireguardCreateKey.optional() }).strict().refine(value => Object.values(value).some(item => item !== undefined), "Нет полей для изменения")
export type WireguardInterfaceUpdate = z.infer<typeof wireguardInterfaceUpdateSchema>
export function wireguardInterfaceNativeUpdate(fields: Record<string, unknown>) {
const mapping: Record<string, string> = { name: "name", "listen-port": "listenPort", mtu: "mtu", comment: "comment", disabled: "disabled" }, patch: Record<string, unknown> = {}
for (const [key, value] of Object.entries(fields)) {
if (!mapping[key]) throw new McpError("UNSUPPORTED_CAPABILITY", "Поле native WireGuard не поддерживается общим планом", 409)
patch[mapping[key]] = key === "disabled" && typeof value === "string" ? observedBoolean(value) ?? value : ["mtu", "listen-port"].includes(key) && typeof value === "string" && /^\d+$/.test(value) ? Number(value) : value
}
return wireguardInterfaceUpdateSchema.parse(patch)
}
type State = WireguardInterfaceDeleteState
export interface WireguardInterfaceUpdateCommand { method: "PATCH" | "DELETE" | "PUT"; path: string; resource: "interfaces" | "ipv4" | "ipv6"; id?: string; body?: Record<string, string> }
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)
const genericMirrors = new Set(["mtu", "listen-port", "disabled", "comment", "public-key", "private-key"])
function privateMirrorMatches(observed: string, expected: string | undefined, publicKey: string | undefined) {
if (observed === expected) return true
return wireguardPrivateScalarsEqual(observed, expected, publicKey)
}
function genericWireguardConfiguration(state: State) {
const result: Record<string, string>[] = []
for (const parent of state.base.interfaces) {
const rows = state.dependencies["/interface"].filter(row => row[".id"] === parent[".id"] || row.name === parent.name)
if (rows.length !== 1 || rows[0][".id"] !== parent[".id"] || rows[0].name !== parent.name) throw fail("STATE_CONFLICT", "Расходятся общий и WireGuard каталоги интерфейсов")
const generic = rows[0]
for (const key of genericMirrors) if (generic[key] !== undefined) {
const expected = parent[key] ?? (key === "comment" ? "" : undefined)
const equal = key === "private-key" ? privateMirrorMatches(generic[key], expected, parent["public-key"]) : key === "disabled" ? observedBoolean(generic[key]) !== null && observedBoolean(generic[key]) === observedBoolean(expected ?? "") : ["mtu", "listen-port"].includes(key) ? observedInteger(generic[key], 1, 65535) !== null && observedInteger(generic[key], 1, 65535) === observedInteger(expected ?? "", 1, 65535) : expected !== undefined && generic[key] === expected
if (!equal) throw fail("STATE_UNAVAILABLE", "Противоречат конфигурационные свойства общего и WireGuard каталогов")
}
// Mirrors are independently validated against the complete WG rows. Seal every other stable generic property.
result.push(Object.fromEntries(Object.entries(generic).filter(([key]) => !genericMirrors.has(key) && !["fp-rx-byte", "fp-tx-byte", "fp-rx-packet", "fp-tx-packet", "rx-drop", "tx-drop", "rx-error", "tx-error", "tx-queue-drop"].includes(key))))
}
return greStableRows(wireguardConfigurationRows(result))
}
export async function wireguardInterfaceUpdateProof(state: State) {
// Normalize a private proof-only clone. Never alter captured source rows, secret references or native command bodies.
const normalized = structuredClone(state)
for (const row of normalized.base.interfaces) {
const scalar = wireguardCorroboratedPrivateScalar(row["private-key"], row["public-key"])
if (scalar !== undefined) row["private-key"] = scalar
}
return (await privateFingerprinter("wireguard-interface-update-v2"))(fingerprint({ configuration: await wireguardInterfaceDeleteProof(normalized), genericInterfaces: genericWireguardConfiguration(state) }))
}
export async function readWireguardInterfaceUpdateState(server: ServerRow, id: string, authorize: () => Promise<unknown> = async () => {}) {
const state = await readWireguardInterfaceDeleteState(server, id, authorize)
state.proof = await wireguardInterfaceUpdateProof(state)
return state
}
export function planWireguardInterfaceUpdate(state: State, id: string, raw: unknown): WireguardInterfaceUpdateCommand[] {
const parsed = wireguardInterfaceUpdateSchema.safeParse(raw)
if (!parsed.success) throw fail("INVALID_INPUT", "Некорректные поля изменения WireGuard")
const input = parsed.data
// Also validates stable identity, ownership, all parent dependencies and child protections.
planWireguardInterfaceDelete(state, id)
const target = state.base.interfaces.find(row => row[".id"] === id)!
if (input.name === "wg-flow" || input.comment === "MikrotikManager traffic-flow overlay") throw fail("PROTECTED_OBJECT", "Имя и комментарий зарезервированы NetFlow")
if (input.name && input.name !== target.name) {
if (input.address !== undefined) throw fail("STATE_CONFLICT", "Изменяйте имя и адрес WireGuard отдельными операциями")
assertWireguardCreateAllowed(state, { serverId: 1, name: input.name, listenPort: 13231, mtu: 1420 })
}
const fields: Record<string, string> = {}
for (const [name, key] of [["name", "name"], ["listenPort", "listen-port"], ["mtu", "mtu"], ["comment", "comment"], ["privateKey", "private-key"], ["disabled", "disabled"]] as const) if (input[name] !== undefined) fields[key] = String(input[name])
const commands: WireguardInterfaceUpdateCommand[] = Object.keys(fields).length ? [{ method: "PATCH", path: "/interface/wireguard", resource: "interfaces", id, body: fields }] : []
if (input.address !== undefined) {
const belongs = (row: Record<string, string>) => [target.name, id].includes(row.interface)
const all = [...state.ipv4, ...state.ipv6].filter(belongs).sort((a, b) => Number(observedBoolean(a.disabled) === true) - Number(observedBoolean(b.disabled) === true) || a.address.localeCompare(b.address))
const statics = all.filter(row => observedBoolean(row.dynamic) === false)
if (statics.some(row => Boolean(row["from-pool"]) || observedBoolean(row["eui-64"]) === true)) throw fail("DEPENDENCY_CONFLICT", "Адрес из IPv6-пула или EUI-64 требует отдельной настройки")
const primary = statics[0]
const secondary = statics.filter(row => row.address !== primary?.address)
const desired = input.address ? interfaceAddressKey(input.address) : null
for (const row of statics) if (!secondary.includes(row) && (desired === null || interfaceAddressKey(row.address) !== desired)) commands.push({ method: "DELETE", path: interfaceAddressPath(row.address), resource: interfaceAddressPath(row.address) === "/ip/address" ? "ipv4" : "ipv6", id: row[".id"] })
const retainedPrimary = statics.find(row => !secondary.includes(row) && desired !== null && interfaceAddressKey(row.address) === desired)
if (retainedPrimary && (observedBoolean(retainedPrimary.disabled) !== false || interfaceAddressPath(retainedPrimary.address) === "/ipv6/address" && observedBoolean(retainedPrimary.advertise) !== false)) commands.push({ method: "PATCH", path: interfaceAddressPath(retainedPrimary.address), resource: interfaceAddressPath(retainedPrimary.address) === "/ip/address" ? "ipv4" : "ipv6", id: retainedPrimary[".id"], body: { disabled: "false", ...(interfaceAddressPath(retainedPrimary.address) === "/ipv6/address" ? { advertise: "false" } : {}) } })
if (input.address && !statics.some(row => interfaceAddressKey(row.address) === desired)) {
// Check literal address collisions and selectors without treating the existing interface as a new object.
const check = structuredClone(state); check.base.interfaces = check.base.interfaces.filter(row => row[".id"] !== id); check.dependencies["/interface"] = check.dependencies["/interface"].filter(row => row[".id"] !== id)
assertWireguardCreateAllowed(check, { serverId: 1, name: target.name, listenPort: 13231, mtu: 1420, address: input.address })
commands.push({ method: "PUT", path: interfaceAddressPath(input.address), resource: interfaceAddressPath(input.address) === "/ip/address" ? "ipv4" : "ipv6", body: { address: input.address, interface: target.name, disabled: "false", ...(interfaceAddressPath(input.address) === "/ipv6/address" ? { advertise: "false" } : {}) } })
}
}
return commands
}
export function projectWireguardInterfaceUpdate(state: State, command: WireguardInterfaceUpdateCommand, createdId?: string) {
const next = structuredClone(state), rows = command.resource === "interfaces" ? next.base.interfaces : next[command.resource]
if (command.method === "PUT") { if (!createdId) throw fail("STATE_UNAVAILABLE", "Не подтверждён ID нового адреса"); rows.push({ ".id": createdId, dynamic: "false", ...command.body! }); return next }
const target = rows.find(row => row[".id"] === command.id)
if (!target) throw fail("STATE_CONFLICT", "Объект команды WireGuard исчез")
if (command.method === "DELETE") rows.splice(rows.indexOf(target), 1)
else {
const oldName = target.name
const privateKeyObserved = target["private-key"] !== undefined
Object.assign(target, command.body)
if (command.body?.["private-key"]) {
target["public-key"] = wireguardPublicKey(command.body["private-key"])
// Public-key derivation proves the replacement even on sources that omit private material.
if (!privateKeyObserved) delete target["private-key"]
}
if (command.body?.name && command.body.name !== oldName) {
for (const row of [...next.base.peers, ...next.ipv4, ...next.ipv6]) if (row.interface === oldName) row.interface = command.body.name
const generic = next.dependencies["/interface"].find(row => row[".id"] === command.id); if (generic) generic.name = command.body.name
}
if (command.resource === "interfaces") {
const generic = next.dependencies["/interface"].find(row => row[".id"] === command.id)
if (generic) for (const key of genericMirrors) if (generic[key] !== undefined && target[key] !== undefined) generic[key] = target[key]
}
}
return next
}
export async function updateWireguardInterface(server: ServerRow, id: string, raw: unknown, expectedProof?: string, authorize: () => Promise<unknown> = async () => {}, options: { recordRevision?: boolean } = {}) {
const parsed = wireguardInterfaceUpdateSchema.safeParse(raw)
if (!parsed.success) throw fail("INVALID_INPUT", "Некорректные поля изменения WireGuard")
return withApplicationMutationLock(() => withConfigMutationLock([server.id], () => executeGuardedApplicationWrite({ kind: "wireguard", id }, [server.id], async () => {
const protections = await wireguardCreateProtectionProof(server.id)
const source = async () => { await authorize(); const current = await getServerRowById(server.id); if (!current || !sameWireguardEndpoint(current, server) || await wireguardCreateProtectionProof(server.id) !== protections) throw fail("STATE_CONFLICT", "Источник или защиты WireGuard изменились") }
let state = await readWireguardInterfaceUpdateState(server, id, source)
if (expectedProof && expectedProof !== state.proof) throw fail("STATE_CONFLICT", "WireGuard изменился после подготовки")
const commands = planWireguardInterfaceUpdate(state, id, parsed.data), client = MikrotikClient.fromServer(server)
let completedCommands = 0
for (const command of commands) {
const fresh = await readWireguardInterfaceUpdateState(server, id, source)
if (fresh.proof !== state.proof) throw fail(completedCommands ? "VERIFICATION_FAILED" : "STATE_CONFLICT", "WireGuard изменился между командами")
const fence = async () => { const current = await readWireguardInterfaceUpdateState(server, id, source); if (current.proof !== fresh.proof) throw fail("STATE_CONFLICT", "WireGuard изменился после native intent"); await source() }
await source()
try { const path = command.path + (command.id ? "/" + encodeURIComponent(command.id) : ""); if (command.method === "PATCH") await client.patch(path, command.body!, 15000, fence); else if (command.method === "PUT") await client.put(path, command.body!, 15000, fence); else await client.delete(path, 15000, fence) }
catch (error) { if (error instanceof McpError) throw error; throw fail("MUTATION_OUTCOME_UNKNOWN", "Исход команды WireGuard неизвестен; повтор запрещён") }
let after: State
try { after = await readWireguardInterfaceUpdateState(server, id, source) } catch { throw fail("MUTATION_OUTCOME_UNKNOWN", "Команда отправлена, read-back недоступен; повтор запрещён") }
try { planWireguardInterfaceDelete(after, id) } catch { throw fail("VERIFICATION_FAILED", "Идентичность или зависимости WireGuard изменились после команды; повтор запрещён") }
let projected: State
if (command.method === "PUT") {
const added = after[command.resource as "ipv4" | "ipv6"].filter(row => !fresh[command.resource as "ipv4" | "ipv6"].some(old => old[".id"] === row[".id"]))
if (added.length !== 1 || observedBoolean(added[0].dynamic) !== false || Object.entries(command.body!).some(([key, value]) => key === "address" ? interfaceAddressKey(added[0][key]) !== interfaceAddressKey(value) : ["disabled", "advertise"].includes(key) ? observedBoolean(added[0][key]) !== observedBoolean(value) : added[0][key] !== value && !(key === "interface" && added[0][key] === id))) throw fail("VERIFICATION_FAILED", "Новый адрес WireGuard не подтверждён; повтор запрещён")
projected = structuredClone(fresh); projected[command.resource as "ipv4" | "ipv6"].push(added[0])
} else projected = projectWireguardInterfaceUpdate(fresh, command)
if (await wireguardInterfaceUpdateProof(projected) !== after.proof) throw fail("VERIFICATION_FAILED", "Изменение WireGuard или сохранность зависимостей не подтверждены; повтор запрещён")
state = after; completedCommands++
}
let revisionRecorded = false
try { if (options.recordRevision !== false) revisionRecorded = await captureAndAppendRevision({ serverId: server.id, section: "wireguard", source: "apply", capture: () => captureWireguardSnapshot(server, source) }) !== null } catch { /* A verified mutation is never replayed for history storage. */ }
return { ok: true, verified: true, interfaceId: id, afterProof: state.proof, commandCount: commands.length, completedCommands, revisionRecorded, forwardingVerified: false }
})))
}