Files
MikrotikManager/backend/src/modules/mcp/wireguard-peer-create-actions.ts
T
DenozordecandClaude Opus 5.5 af4203d9f1 fix(mcp): ускорить сервисы WireGuard - собственная проверка раз на этап, файлы состояния через stat
Профиль приёмки создания WireGuard (81 с): ~3000 свежих проверок прав MCP, ~20000
проверок источника прав и ~63000 чтений файлов состояния с диска (24 с) - всё перед
каждым чтением роутера.
- сервисы WireGuard (создание интерфейса и пира, изменение, импорт): собственная
  проверка (ключи, защиты, допуск) раз на этап, чтения переиспользуют доказательство
  моложе 2 с; перед каждой нативной записью права MCP и защиты по-прежнему
  проверяются заново (executeGuardedConfigurationWrite), у создания интерфейса и
  собственная проверка перед отправкой свежая;
- assertVerifiedConfigurationReadAccess - проверка этапа только для чтений;
  assertVerifiedConfigurationAccess остаётся свежей (записи и публикации);
- access-generation и отметки отзыва портала проверяются через stat и перечитываются
  только при изменении файла (замена видна сразу); ключ шифрования читается как раньше.

Приёмка создания WireGuard 81 -> 14 с отдельно; шарды WireGuard 224/198 -> 69/66 с;
весь набор зелёный, 149 строк результатов на месте.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 13:59:39 +07:00

120 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { z } from "zod"
import { randomUUID } from "node:crypto"
import { pool } from "../../db/index.js"
import { hasPermission } from "../../lib/permissions.js"
import { assertVerifiedConfigurationAccess, assertVerifiedConfigurationReadAccess } from "../../services/config-mutation-policy.js"
import { wireguardCreateKey, wireguardCreateProtectionProof, readWireguardInterfaceCreateState } from "../../services/wireguard-interface-create.js"
import { wireguardPeerCreateSchema, assertWireguardPeerCreateAllowed, createWireguardPeer, wireguardPeerCreateStages } from "../../services/wireguard-peer-create.js"
import { wireguardReadDiagnostic } from "../../services/wireguard-read-diagnostic.js"
import { WIREGUARD_PEER_KEY_PURPOSE } from "./wireguard-interface-create-actions.js"
import { effectiveMcpConnection } from "./store.js"
import { routerClient } from "./resources.js"
import { coalesceAuthorization } from "./authorization-stage.js"
import { fingerprint, McpError, decryptSecret, privateSecretFingerprint, redact } from "./security.js"
import { registerMcpService } from "./service-registry.js"
import type { add } from "./actions.js"
export const wireguardPeerCreatePlanSchema = wireguardPeerCreateSchema.omit({ privateKey: true }).extend({ privateKeyRef: z.string().uuid().optional(), privateKeyMode: z.enum(["auto", "none"]).optional() }).strict().refine(value => !(value.privateKeyRef && value.privateKeyMode), "Выберите ссылку или режим ключа")
const fail = (code: string, message: string) => new McpError(code, message, 409)
function reportPeerSourceFailure(phase: "current" | "apply-source" | "apply-executor", error: unknown) {
const read = wireguardReadDiagnostic(error)
if (read || error instanceof McpError && error.code === "STATE_UNAVAILABLE") {
try {
console.error(JSON.stringify({ event: "mcp.wireguard.peer-create-source-failed", phase, read }))
} catch { /* A diagnostic must not replace the failure. */ }
}
}
async function access(input: Record<string, unknown>, signal?: AbortSignal) {
if (signal?.aborted) throw fail("READ_CANCELLED", "Подготовка peer отменена")
const principal = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.string() }).strict().parse(input.principal)
const current = await effectiveMcpConnection(principal)
if (current.owner_id !== input.ownerId || !hasPermission(current.policy.permissions, "mm:network:write") || !hasPermission(current.owner_permissions, "mm:network:write")) throw fail("PERMISSION_DENIED", "Допуск WireGuard отозван")
if (!current.policy.scope.serverIds.includes(Number(input.serverId))) throw fail("SERVER_DENIED", "Сервер вне области допуска")
if (fingerprint(current.policy) !== input.policyProof || fingerprint(current.owner_permissions) !== input.ownerProof) throw fail("RESET_REQUIRED", "Допуск изменился; подготовьте новый план")
}
async function material(input: Record<string, unknown>, signal?: AbortSignal) {
await access(input, signal)
const request = wireguardPeerCreatePlanSchema.parse(input.request)
if (fingerprint(request) !== input.requestProof) throw fail("STATE_CONFLICT", "Параметры peer не соответствуют сохранённому proof")
let privateKey: string | undefined, referenceProof = fingerprint([])
if (request.privateKeyRef) {
await access(input, signal)
const id = request.privateKeyRef
const row = (await pool.query("SELECT purpose,server_id,created_by,CASE WHEN octet_length(ciphertext)<=16384 THEN ciphertext ELSE NULL END AS ciphertext FROM mcp_secrets WHERE id=$1 AND created_by=$2", [id, input.ownerId])).rows[0]
if (!row || row.server_id !== request.serverId || row.purpose !== WIREGUARD_PEER_KEY_PURPOSE || typeof row.ciphertext !== "string") throw fail("SECRET_UNAVAILABLE", "Ссылка не выдана владельцу для ключа peer и этого сервера")
let value: unknown
try { value = await decryptSecret(row.ciphertext) } catch { throw fail("SECRET_UNAVAILABLE", "Ключ peer недоступен") }
const parsed = wireguardCreateKey.safeParse(value)
if (!parsed.success) throw fail("SECRET_UNAVAILABLE", "Неподдерживаемый формат ключа peer")
privateKey = parsed.data
referenceProof = await privateSecretFingerprint(fingerprint({ id, ...row }), "wireguard-peer-create-reference-v1")
}
const { privateKeyRef: _ref, privateKeyMode, ...fields } = request
await access(input, signal)
return { body: wireguardPeerCreateSchema.parse({ ...fields, privateKey: privateKey ?? privateKeyMode }), referenceProof }
}
export function registerWireguardPeerCreateActions(register: typeof add) {
const source = async (input: Record<string, unknown>, signal?: AbortSignal) => {
const keys = await material(input, signal), protectionProof = await wireguardCreateProtectionProof(Number(input.serverId))
// Service checks run once per stage (reads reuse a proof younger than 2 s); every native write
// still re-proves MCP rights and protections in executeGuardedConfigurationWrite.
const authorize = coalesceAuthorization(async () => {
if ((await material(input, signal)).referenceProof !== keys.referenceProof) throw fail("STATE_CONFLICT", "Ссылка на ключ peer изменилась")
if (await wireguardCreateProtectionProof(Number(input.serverId)) !== protectionProof) throw fail("STATE_CONFLICT", "Защиты WireGuard изменились")
}).coalesced
const { server } = await routerClient(Number(input.serverId)), state = await readWireguardInterfaceCreateState(server, authorize)
await authorize()
return { ...keys, state, server, authorize, publicState: { proof: state.proof, referenceProof: keys.referenceProof, protectionProof } }
}
registerMcpService("network.wireguard.peers.create", {
current: async input => {
try { return (await source(input)).publicState }
catch (error) { reportPeerSourceFailure("current", error); throw error }
},
execute: async input => {
let phase: "apply-source" | "apply-executor" = "apply-source"
try {
const before = await source(input)
if (fingerprint(before.publicState) !== input.beforeFingerprint) throw fail("STATE_CONFLICT", "Источник, ключи или зависимости peer изменились")
phase = "apply-executor"
return await createWireguardPeer(before.server, before.body, before.state.proof, async () => { await assertVerifiedConfigurationReadAccess(); await before.authorize() })
} catch (error) {
reportPeerSourceFailure(phase, error)
throw error
}
},
verify: async (input, result) => { const receipt = result as { verified?: boolean; afterProof?: string } | null; return receipt?.verified === true && (await source(input)).state.proof === receipt.afterProof },
reconcile: async (input, authorize) => {
if (input.proofRevision !== 1 || typeof input.expectedProof !== "string" || !/^[a-f0-9]{64}$/.test(input.expectedProof) || !z.string().uuid().safeParse(input.receiptId).success) throw fail("UNSUPPORTED_CAPABILITY", "Нет совместимого proof и checkpoint создания peer")
await authorize()
const latest = await source(input)
if (latest.referenceProof !== input.expectedReferenceProof) throw fail("STATE_CONFLICT", "Ссылка на ключ изменилась после подготовки")
const principal = input.principal as { connectionId: string }
const receipts = (await pool.query("SELECT s.result FROM mcp_operation_steps s JOIN mcp_operations o ON o.id=s.operation_id WHERE o.connection_id=$1 AND s.state='verified' AND s.intended_state->>'kind'='service' AND s.intended_state->>'service'=$2 AND s.intended_state->'input'->>'receiptId'=$3 AND s.intended_state->'input'=$4::jsonb AND s.result->>'verified'='true' LIMIT 2", [principal.connectionId, "network.wireguard.peers.create", input.receiptId, JSON.stringify(redact(input))])).rows
await authorize()
const fresh = await source(input)
if (fingerprint(fresh.publicState) !== fingerprint(latest.publicState)) throw fail("STATE_CONFLICT", "WireGuard изменился во время сверки")
const receipt = receipts.length === 1 ? receipts[0].result : undefined
const afterProof = /^[a-f0-9]{64}$/.test(receipt?.afterProof ?? "") && /^\*[a-z0-9]+$/i.test(receipt?.peerId ?? "") ? receipt.afterProof as string : undefined
const original = latest.state.proof === input.expectedProof, desired = afterProof !== undefined && latest.state.proof === afterProof && latest.state.base.peers.some(row => row[".id"] === receipt.peerId && row["public-key"] === latest.body.publicKey)
await authorize()
return { matchesOriginalState: original, matchesDesiredState: desired, matchesExpectedPrefixState: original || desired, verifiedPrefixCommands: desired ? wireguardPeerCreateStages(latest.body).length : original ? 0 : null, verifiedFinalCheckpointAvailable: afterProof !== undefined, forwardingVerified: false }
},
})
register("network.wireguard.peers.create", "mm_wireguard_peer_add_plan", "Создать peer WireGuard с отключённой подготовкой и проверкой родителя", "network", "mm:network:write", "write", "servers", wireguardPeerCreatePlanSchema, {
prepare: async (input, context) => {
// Seal the same JSON representation that survives durable plan storage.
const request = wireguardPeerCreatePlanSchema.parse(JSON.parse(JSON.stringify(input))), internal = { request, requestProof: fingerprint(request), serverId: request.serverId, principal: context.principal, ownerId: context.connection.owner_id, policyProof: fingerprint(context.connection.policy), ownerProof: fingerprint(context.connection.owner_permissions) }
const before = await source(internal, context.signal), parent = assertWireguardPeerCreateAllowed(before.state, before.body)
const objects = [{ kind: "server", id: String(request.serverId), serverId: request.serverId }, { kind: "wireguard", id: parent[".id"], serverId: request.serverId }, { kind: "wireguard_peer", id: request.publicKey, serverId: request.serverId }]
const protections = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1) LIMIT 1001", [String(request.serverId)])
if (protections.rows.length > 1000) throw fail("STATE_UNAVAILABLE", "Превышен предел защит WireGuard")
for (const { object_ref: ref } of protections.rows) objects.push({ kind: ref.kind, id: ref.id, serverId: request.serverId })
await before.authorize()
return { target: { scope: "servers", serverIds: [request.serverId] }, objects, snapshots: [], requiresHuman: true, mutationCost: wireguardPeerCreateStages(before.body).length + 1, before: before.publicState,
steps: [{ kind: "service", service: "network.wireguard.peers.create", input: { ...internal, receiptId: randomUUID(), expectedProof: before.state.proof, expectedReferenceProof: before.referenceProof, proofRevision: 1, beforeFingerprint: fingerprint(before.publicState) } }],
warnings: ["Peer создаётся отключённым и затем включается отдельной командой, если это запрошено; возможна остановка в промежуточном состоянии.", "Приватный ключ принимается через owner/purpose/server secret reference либо режим auto/none; plaintext не возвращается модели.", "Каждая команда требует свежий источник и read-back; при потере ответа повтор запрещён. Сверка признаёт только исходный proof или сохранённый проверенный checkpoint с native ID. Автоматического отката нет.", "Handshake, передача трафика, маршрутизация и firewall требуют отдельной приёмки."] }
},
})
}