import { randomUUID } from "node:crypto" import { z } from "zod" import { pool } from "../../db/index.js" import { hasPermission } from "../../lib/permissions.js" import { appendClientEventRows, prepareEventRows } from "../events/service/events-service.js" import type { EventInsertInput } from "../events/repository/events-repository.js" import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js" import { effectiveMcpConnection } from "./store.js" import { accessGeneration, encryptSecret, decryptSecret, fingerprint, privateSecretFingerprint, McpError, redact } from "./security.js" import { registerMcpService } from "./service-registry.js" import { eventsBatchSchema, assertEventBatchBudget } from "./events-batch-model.js" import type { add } from "./actions.js" const operation = "events.batch.append" const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.string() }).strict() const conflict = () => new McpError("STATE_CONFLICT", "Пакет событий или область доступа изменились", 409) async function catalog() { const rows = (await pool.query("SELECT id FROM servers ORDER BY id LIMIT 1001")).rows if (rows.length > 1000) throw new McpError("LIMIT_EXCEEDED", "Каталог зависимостей журнала превышает лимит", 409) return rows.map(row => Number(row.id)) } async function sourceProof(ids: number[]) { return privateSecretFingerprint(fingerprint(ids), "events-batch-catalog-v1") } async function access(input: Record, verified = false) { if (verified) await assertVerifiedConfigurationAccess() const principal = principalSchema.parse(input.principal), connection = await effectiveMcpConnection(principal) if (connection.owner_id !== input.ownerId || connection.policy.mode === "observer" || !hasPermission(connection.owner_permissions, "mm:dashboard:read") || !hasPermission(connection.policy.permissions, "mm:dashboard:read")) throw new McpError("PERMISSION_DENIED", "Допуск к записи событий отозван", 403) if (fingerprint(connection.policy) !== input.policyProof || connection.generation !== input.connectionGeneration || await accessGeneration() !== input.generation) throw conflict() const ids = await catalog() if (!connection.policy.scope.allowGlobal || ids.some(id => !connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Глобальный журнал требует полного каталога серверов", 403) if (input.catalogProof !== await sourceProof(ids)) throw conflict() return { principal, ids } } async function batch(input: Record) { const rows = JSON.parse(await decryptSecret(String(input.batchCiphertext))) as EventInsertInput[] assertEventBatchBudget(rows) if (!Array.isArray(rows) || !rows.length || rows.length > 200 || new Set(rows.map(row => row.id)).size !== rows.length || rows.some(row => !z.string().uuid().safeParse(row.id).success)) throw conflict() if (input.batchProof !== await privateSecretFingerprint(fingerprint({ rows, receiptId: input.receiptId, principal: input.principal, ownerId: input.ownerId }), "events-batch-request-v1")) throw conflict() return rows } async function observed(rows: EventInsertInput[]) { const budget = (await pool.query(`WITH chosen AS MATERIALIZED (SELECT * FROM events WHERE id=ANY($1::text[]) ORDER BY id LIMIT 201), limits AS (SELECT count(*) AS n,coalesce(sum(octet_length(row_to_json(chosen)::text)),0) AS bytes FROM chosen) SELECT n>200 OR bytes>131072 AS overflow, CASE WHEN n<=200 AND bytes<=131072 THEN (SELECT coalesce(jsonb_agg(to_jsonb(chosen) ORDER BY id),'[]') FROM chosen) END AS items FROM limits`, [rows.map(row => row.id)])).rows[0] if (!budget || budget.overflow || !Array.isArray(budget.items)) throw new McpError("LIMIT_EXCEEDED", "Сохранённые события превышают бюджет", 409) return budget.items.map((row: Record) => ({ id: row.id, createdAt: new Date(String(row.created_at)).toISOString(), level: row.level, eventType: row.event_type, sourceModule: row.source_module, title: row.title, message: row.message, entityType: row.entity_type ?? null, entityId: row.entity_id ?? null, payload: row.payload_json ?? {} })) } const canonical = (rows: EventInsertInput[]) => rows.map(row => ({ ...row, createdAt: new Date(row.createdAt).toISOString(), entityType: row.entityType ?? null, entityId: row.entityId ?? null, payload: row.payload ?? {} })).sort((a, b) => a.id.localeCompare(b.id)) async function matches(input: Record) { const rows = await batch(input), saved = await observed(rows) return { original: saved.length === 0, desired: fingerprint(saved) === fingerprint(canonical(rows)) } } const resultFor = (input: Record, rows: EventInsertInput[]) => ({ receiptId: input.receiptId, inserted: rows.length, eventIds: rows.map(row => row.id), journalEntriesOnly: true, actionsExecuted: false }) export function registerEventsBatchActions(register: typeof add) { registerMcpService(operation, { current: async input => { await access(input); const state = await matches(input); if (!state.original) throw conflict(); return { catalogProof: input.catalogProof, batchAbsent: true } }, execute: async input => { await access(input, true); const rows = await batch(input) await appendClientEventRows(rows, async () => { await access(input, true); if (!(await matches(input)).original) throw conflict(); await access(input, true) }) await access(input, true) if (!(await matches(input)).desired) throw new McpError("VERIFICATION_FAILED", "Запись пакета событий не подтверждена", 409) return resultFor(input, rows) }, verify: async (input, result) => { await access(input); return fingerprint(result) === fingerprint(resultFor(input, await batch(input))) && (await matches(input)).desired }, reconcile: async (input, authorize) => { await authorize(); await access(input); const state = await matches(input) const result = resultFor(input, await batch(input)) const checkpoints = (await pool.query(`SELECT s.result FROM mcp_operation_steps s JOIN mcp_operations o ON o.id=s.operation_id JOIN mcp_plans p ON p.id=o.plan_id WHERE o.connection_id=$1 AND p.operation_id=$2 AND s.state='verified' AND s.intended_state=$3::jsonb AND s.result=$4::jsonb LIMIT 2`, [principalSchema.parse(input.principal).connectionId, operation, JSON.stringify(redact({ kind: "service", service: operation, input })), JSON.stringify(result)])).rows await authorize(); await access(input) return { matchesOriginalState: state.original, matchesDesiredState: state.desired && checkpoints.length === 1, configurationMatchesDesired: state.desired } }, }) register(operation, "mm_events_batch_append_plan", "Добавить пакет записей в журнал событий приложения", "dashboard", "mm:dashboard:read", "write", "global", eventsBatchSchema, { prepare: async (input, context) => { context.signal?.throwIfAborted() try { assertEventBatchBudget(input) } catch { throw new McpError("INVALID_INPUT", "Пакет событий превышает JSON-бюджет 64 КиБ/12 уровней", 400) } const request = eventsBatchSchema.parse(input), rows = JSON.parse(JSON.stringify(prepareEventRows(request.events))) as EventInsertInput[] for (const row of rows) { if (!Number.isFinite(Date.parse(row.createdAt))) throw new McpError("INVALID_INPUT", "Время события не распознано", 400); row.createdAt = new Date(row.createdAt).toISOString() } try { assertEventBatchBudget(rows) } catch { throw new McpError("INVALID_INPUT", "Нормализованный пакет событий превышает JSON-бюджет", 400) } const ids = await catalog(), catalogProof = await sourceProof(ids), receiptId = randomUUID() const sealed: Record = { principal: context.principal, ownerId: context.connection.owner_id, policyProof: fingerprint(context.connection.policy), connectionGeneration: context.connection.generation, generation: await accessGeneration(), catalogProof, receiptId, batchCiphertext: await encryptSecret(JSON.stringify(rows)) } sealed.batchProof = await privateSecretFingerprint(fingerprint({ rows, receiptId, principal: context.principal, ownerId: context.connection.owner_id }), "events-batch-request-v1") await access(sealed); context.signal?.throwIfAborted() return { target: { scope: "global" }, objects: [{ kind: "events-journal", id: "global" }, ...rows.map(row => ({ kind: "event", id: row.id })), ...ids.map(serverId => ({ kind: "server", id: String(serverId), serverId }))], snapshots: [], before: { catalogProof, batchAbsent: true }, requiresHuman: true, mutationCost: 1, steps: [{ kind: "service", service: operation, input: sealed }], warnings: ["Будет добавлено записей: " + rows.length + ". Подтвердите содержимое пакета во входных данных плана.", "Это записи клиентского журнала, а не доказательства выполнения системных действий. sourceModule/eventType/entity/payload сохраняются как предоставленные данные.", "Пакет вставляется атомарно с серверными UUID. Неизвестный результат не повторяется; для успешной сверки нужен точный VERIFIED checkpoint."] } }, }) }