import { randomUUID } from "node:crypto" import { z } from "zod" import { ipsecInitRequestSchema } from "@mmapp/contracts/ipsec" import { pool } from "../../db/index.js" import { hasPermission } from "../../lib/permissions.js" import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js" import { ipsecPeerDeleteSourceProof } from "../../services/ipsec-peer-delete.js" import { planIpsecServerInit } from "../../services/ipsec-server-init-model.js" import { readIpsecServerInitState, initIpsecServerGuarded } from "../../services/ipsec-server-init.js" import { routerClient } from "./resources.js" import { effectiveMcpConnection, audit } from "./store.js" import { encryptSecret, decryptSecret, fingerprint, McpError, redact } from "./security.js" import { registerMcpService, type McpServiceHandler } from "./service-registry.js" import type { ActionContext, ChangeEvidence } from "./action-types.js" import type { add } from "./actions.js" const operation = "network.ipsec.server.init" const hash = z.string().regex(/^[a-f0-9]{64}$/) // The REST init contract contains no secrets or private export. Unknown plaintext // keys (PSK, passphrase, private keys) are rejected at this public boundary. export const ipsecServerInitActionSchema = z.object({ serverId: z.number().int().positive().safe(), request: ipsecInitRequestSchema.omit({ serverId: true }).strict() }).strict() const bindingSchema = ipsecServerInitActionSchema.extend({ operation: z.literal(operation), principal: z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.string().datetime() }).strict(), ownerId: z.string().min(1), ownerProof: hash, policyProof: hash, generation: z.string().min(1), sourceProof: hash, expectedProof: hash, requestProof: hash, commandCount: z.number().int().min(0).max(2000), receiptId: z.string().uuid(), proofRevision: z.literal(3), }).strict() type Binding = z.infer const serviceInput = z.object({ serverId: z.number().int().positive().safe(), receiptId: z.string().uuid(), bindingCiphertext: z.string().min(1).max(262144) }).strict() const production = { connection: effectiveMcpConnection, router: routerClient, read: readIpsecServerInitState, sourceProof: ipsecPeerDeleteSourceProof, plan: planIpsecServerInit, init: initIpsecServerGuarded, seal: encryptSecret, open: decryptSecret, verifiedAccess: assertVerifiedConfigurationAccess, query: async (sql: string, values: unknown[]) => (await pool.query(sql, values)).rows as Record[], checkpoint: async (ownerId: string, connectionId: string, value: unknown) => audit(pool, ownerId, "ipsec.server.init.checkpoint", connectionId, value), } const conflict = () => new McpError("STATE_CONFLICT", "IPsec, источник или допуск инициализации изменились", 409) export function hasVerifiedIpsecServerInit(candidate: unknown, binding: Binding, input: Record, proof: string): boolean { if (!candidate || typeof candidate !== "object") return false const row = candidate as Record, result = row.result as Record | undefined return row.connection_id === binding.principal.connectionId && row.state === "verified" && fingerprint(row.intended_state) === fingerprint(redact({ kind: "service", service: operation, input })) && !!result && result.ok === true && result.verified === true && result.receiptId === binding.receiptId && result.serverId === binding.serverId && result.commandCount === binding.commandCount && result.completedCommands === binding.commandCount && result.confirmedWrites === binding.commandCount && result.historyRecorded === true && result.revisionRecorded === true && result.afterProof === proof && result.forwardingVerified === false && result.automaticReplay === false } export function createIpsecServerInitAdapter(overrides: Partial = {}) { const deps = { ...production, ...overrides } const access = async (binding: Binding, signal?: AbortSignal, external: () => Promise = async () => {}) => { signal?.throwIfAborted(); await external() const current = await deps.connection(binding.principal) if (Date.parse(binding.principal.credentialExpiresAt) <= Date.now() || current.owner_id !== binding.ownerId || current.policy.status !== "active" || current.policy.mode === "observer" || current.owner_valid_until.getTime() <= Date.now() || Date.parse(current.policy.expiresAt) <= Date.now() || !current.policy.scope.operationIds.includes(operation) || !current.policy.scope.serverIds.includes(binding.serverId) || !hasPermission(current.owner_permissions, "mm:network:write") || !hasPermission(current.policy.permissions, "mm:network:write")) throw new McpError("PERMISSION_DENIED", "Нет актуального допуска инициализации IPsec", 403) if (current.generation !== binding.generation || fingerprint(current.policy) !== binding.policyProof || fingerprint(current.owner_permissions) !== binding.ownerProof || fingerprint({ serverId: binding.serverId, request: binding.request }) !== binding.requestProof) throw conflict() signal?.throwIfAborted() } const request = async (input: Record) => { const parsed = serviceInput.parse(input), binding = bindingSchema.parse(JSON.parse(await deps.open(parsed.bindingCiphertext))) if (binding.serverId !== parsed.serverId || binding.receiptId !== parsed.receiptId) throw conflict() return binding } const source = async (binding: Binding, signal?: AbortSignal, external?: () => Promise) => { const authorize = async () => { await access(binding, signal, external) } await authorize() const { server } = await deps.router(binding.serverId) if (await deps.sourceProof(server) !== binding.sourceProof) throw conflict() const state = await deps.read(server, authorize) if (state.source !== binding.sourceProof) throw conflict() await authorize(); return { server, state, authorize } } const prepare = async (raw: Record, context: ActionContext): Promise => { const value = ipsecServerInitActionSchema.parse(raw) const binding = bindingSchema.parse({ ...value, operation, principal: context.principal, ownerId: context.connection.owner_id, ownerProof: fingerprint(context.connection.owner_permissions), policyProof: fingerprint(context.connection.policy), generation: context.connection.generation, sourceProof: "0".repeat(64), expectedProof: "0".repeat(64), requestProof: fingerprint(value), commandCount: 0, receiptId: randomUUID(), proofRevision: 3 }) await access(binding, context.signal) const { server } = await deps.router(value.serverId) binding.sourceProof = await deps.sourceProof(server) const before = await source(binding, context.signal), plan = deps.plan(before.state, server, { ...value.request, serverId: value.serverId }) binding.expectedProof = before.state.proof; binding.commandCount = plan.commands.length const objects: ChangeEvidence["objects"] = [{ kind: "server", id: String(value.serverId), serverId: value.serverId }, { ...plan.target, serverId: value.serverId }, ...plan.companions.map(ref => ({ ...ref, serverId: value.serverId }))] for (const protection of before.state.protections as Array<{ object_ref: { kind: string; id: string } }>) objects.push({ kind: protection.object_ref.kind, id: protection.object_ref.id, serverId: value.serverId }) if ((await source(binding, context.signal)).state.proof !== binding.expectedProof) throw conflict() return { target: { scope: "servers", serverIds: [value.serverId] }, objects, snapshots: [], requiresHuman: true, mutationCost: plan.commands.length + 1, before: { proof: before.state.proof }, steps: [{ kind: "service", service: operation, input: { serverId: value.serverId, receiptId: binding.receiptId, bindingCiphertext: await deps.seal(JSON.stringify(binding)) } }], warnings: [`Native-команд: ${plan.commands.length}; затем обязательная managed-only история IPsec.`, "Создаются CA и серверный приватный ключ только при отсутствии сертификатов; подпись разрешена только новым ACK-owned сертификатам. Приватный экспорт не выполняется. Существующий неподписанный сертификат блокирует весь план до первой записи.", "Все поля REST поддерживаются. clientDaysValid принимается мастером для совместимости и не создаёт клиентский сертификат. Сертификат с существующим именем повторно не выпускается при изменении endpoint или срока.", "Каждая команда проверяет полный private proof 11 native-каталогов IPsec, маршрутов и интерфейсов, источник и защиты. Потеря ответа или несовпадение read-back останавливают операцию без повтора и автоматического отката; передача трафика не подтверждается."] } } const service: McpServiceHandler = { current: async input => ({ proof: (await source(await request(input))).state.proof }), execute: async input => { const binding = await request(input), before = await source(binding) if (before.state.proof !== binding.expectedProof) throw conflict() const plan = deps.plan(before.state, before.server, { ...binding.request, serverId: binding.serverId }) if (plan.commands.length !== binding.commandCount) throw conflict() const authorize = async () => { await deps.verifiedAccess(); await before.authorize() } await authorize() const { summary: _summary, ...receipt } = await deps.init(before.server, { ...binding.request, serverId: binding.serverId }, binding.expectedProof, authorize, { receiptId: binding.receiptId, checkpoint: async value => { await authorize(); await deps.checkpoint(binding.ownerId, binding.principal.connectionId, { ...value, inputProof: fingerprint(redact(input)) }) } }) return receipt }, verify: async (input, result) => { const binding = await request(input), after = await source(binding); return hasVerifiedIpsecServerInit({ connection_id: binding.principal.connectionId, state: "verified", intended_state: redact({ kind: "service", service: operation, input }), result }, binding, input, after.state.proof) }, reconcile: async (input, external) => { const binding = await request(input), latest = await source(binding, undefined, external) await latest.authorize() const rows = await deps.query("SELECT o.connection_id,s.state,s.intended_state,s.result FROM mcp_operation_steps s JOIN mcp_operations o ON o.id=s.operation_id WHERE o.connection_id=$1 AND s.intended_state->'input'->>'receiptId'=$2 LIMIT 2", [binding.principal.connectionId, binding.receiptId]) const verified = rows.length === 1 && hasVerifiedIpsecServerInit(rows[0], binding, input, latest.state.proof) if ((await source(binding, undefined, external)).state.proof !== latest.state.proof) throw conflict() return { matchesOriginalState: latest.state.proof === binding.expectedProof, matchesDesiredState: verified, automaticReplay: false, forwardingVerified: false } }, } return { prepare, service } } export function registerIpsecServerInitActions(register: typeof add) { const adapter = createIpsecServerInitAdapter() registerMcpService(operation, adapter.service) register(operation, "mm_ipsec_server_init_plan", "Инициализировать сервер IKEv2 с полным preflight и проверкой каждой native-команды", "network", "mm:network:write", "write", "servers", ipsecServerInitActionSchema, { version: 4, prepare: adapter.prepare }) }