53 lines
5.3 KiB
TypeScript
53 lines
5.3 KiB
TypeScript
import { z } from "zod"
|
||
import { randomUUID } from "node:crypto"
|
||
import { pool } from "../../db/index.js"
|
||
import { fingerprint, McpError, redact } from "./security.js"
|
||
import { effectiveMcpConnection } from "./store.js"
|
||
import { registerMcpService } from "./service-registry.js"
|
||
import { createDatabaseBackupArtifact, databaseBackupAuthority, databaseBackupAuthoritySchema, readDatabaseBackupSource, verifyDatabaseBackupArtifact } from "./database-backup-artifact.js"
|
||
import type { add } from "./actions.js"
|
||
|
||
export function registerDatabaseBackupActions(register: typeof add) {
|
||
const authority = (input: Record<string, unknown>) => databaseBackupAuthoritySchema.parse(input.authority)
|
||
const current = async (input: Record<string, unknown>) => ({ proof: (await readDatabaseBackupSource(authority(input))).proof })
|
||
const verify = async (input: Record<string, unknown>, result: unknown) => {
|
||
const receipt = result as { artifactId?: string; humanDownloadOnly?: boolean; databaseContentReturned?: boolean; bytes?: unknown; sha256?: unknown } | null
|
||
return receipt?.humanDownloadOnly === true && receipt.databaseContentReturned === false && !!receipt.artifactId && await verifyDatabaseBackupArtifact(receipt.artifactId, authority(input), String(input.expectedProof), String(input.attemptRef), receipt)
|
||
}
|
||
registerMcpService("database.backup", { current,
|
||
execute: input => createDatabaseBackupArtifact(authority(input), String(input.expectedProof), z.string().uuid().parse(input.attemptRef)),
|
||
verify,
|
||
reconcile: async (input, authorize) => {
|
||
await authorize()
|
||
const access = authority(input), attemptRef = z.string().uuid().parse(input.attemptRef)
|
||
const rows = (await pool.query(`SELECT s.intended_state,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 AND p.connection_id=o.connection_id
|
||
WHERE o.connection_id=$1 AND p.operation_id='database.backup' AND s.state='verified'
|
||
AND s.intended_state->>'kind'='service' AND s.intended_state->>'service'='database.backup'
|
||
AND s.intended_state->'input'->>'attemptRef'=$2
|
||
AND octet_length(s.intended_state::text)<=32768 AND octet_length(s.result::text)<=4096 LIMIT 2`, [access.principal.connectionId, attemptRef])).rows
|
||
await authorize()
|
||
// Creating a dump leaves topology metadata unchanged. Only the exact saved
|
||
// verified receipt proves export; a missing acknowledgement stays unresolved.
|
||
const exact = rows.length === 1 && fingerprint(rows[0].intended_state) === fingerprint(redact({ kind: "service", service: "database.backup", input }))
|
||
const desired = exact && await verify(input, rows[0].result).catch(() => false)
|
||
await authorize()
|
||
return { matchesDesiredState: desired, matchesOriginalState: false }
|
||
},
|
||
})
|
||
register("database.backup", "mm_database_backup_plan", "Создать полную резервную копию PostgreSQL для скачивания владельцем после подтверждения", "settings", "mm:settings:admin", "write", "global", z.object({}).strict(), {
|
||
prepare: async (_input, context) => {
|
||
const authorize = async () => {
|
||
context.signal?.throwIfAborted()
|
||
if (fingerprint((await effectiveMcpConnection(context.principal)).policy) !== fingerprint(context.connection.policy)) throw new McpError("RESET_REQUIRED", "Допуск изменился; подготовьте план заново", 409)
|
||
}
|
||
await authorize()
|
||
const access = await databaseBackupAuthority(context.principal, context.connection.owner_id, context.connection.policy), source = await readDatabaseBackupSource(access)
|
||
await authorize()
|
||
return { target: { scope: "global" }, objects: [{ kind: "database-backup", id: "global" }, ...source.serverIds.map(serverId => ({ kind: "server", id: String(serverId), serverId })), ...source.objects], snapshots: [], before: { proof: source.proof }, requiresHuman: true, mutationCost: 1,
|
||
steps: [{ kind: "service", service: "database.backup", input: { authority: access, attemptRef: randomUUID(), expectedProof: source.proof, beforeFingerprint: fingerprint({ proof: source.proof }) } }],
|
||
warnings: ["Полная база содержит пароли, ключи и закрытые данные. Архив создаётся только после человеческого подтверждения и доступен вошедшему владельцу 15 минут.", "Модель получает только квитанцию; содержимое базы доступно через человеческий web API. Предел архива — 64 МиБ, экспорта — 120 секунд.", "MCP-экспорт поддерживает PostgreSQL URI с одним host и значениями, представимыми в service file. Неподдержанная форма подключения отклоняется без потери параметров.", "Экспорт временно приостанавливает обработчики базы, планировщик и NetFlow. Отзыв допуска или изменение области блокирует экспорт и выдачу. Автоматического повторения нет."] }
|
||
},
|
||
})
|
||
}
|