Files
MikrotikManager/backend/src/services/bounded-database-dump.ts
T

44 lines
3.7 KiB
TypeScript

import { spawn } from "node:child_process"
export const MAX_DATABASE_DUMP_BYTES = 64 * 1024 * 1024
export class DatabaseDumpCommandError extends Error {
constructor(readonly code: string, message: string, readonly diagnosticKinds: string[] = [], readonly exitCode?: number | null) { super(message) }
}
/** Collect only bounded output; every cancellation kills and drains before settling. */
export function boundedDatabaseCommand(command: string, args: string[], options: { env?: NodeJS.ProcessEnv; signal?: AbortSignal; maxBytes?: number; timeoutMs?: number; authorize?: () => Promise<void> } = {}): Promise<Buffer> {
const maxBytes = options.maxBytes ?? MAX_DATABASE_DUMP_BYTES
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_DATABASE_DUMP_BYTES) throw new Error("Invalid database command limit")
return new Promise((resolve, reject) => {
if (options.signal?.aborted) { reject(new Error("Экспорт базы отменён")); return }
const child = spawn(command, args, { env: options.env, stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true })
const chunks: Buffer[] = []
let bytes = 0, stderrBytes = 0, failure: Error | undefined
const diagnosticKinds = new Set<string>()
const stop = (message: string, code: string) => { if (!failure) { failure = new DatabaseDumpCommandError(code, message); chunks.length = 0; child.kill("SIGKILL") } }
const abort = () => stop("Экспорт базы отменён", "DATABASE_DUMP_CANCELLED")
const timer = setTimeout(() => stop("Истёк срок экспорта базы", "DATABASE_DUMP_TIMEOUT"), options.timeoutMs ?? 120000)
let checking = false
const accessTimer = options.authorize ? setInterval(() => {
if (checking || failure) return
checking = true
void options.authorize!().catch(() => stop("Допуск к экспорту базы отозван", "DATABASE_DUMP_ACCESS_REVOKED")).finally(() => { checking = false })
}, 250) : undefined
options.signal?.addEventListener("abort", abort, { once: true })
child.stdout.on("data", (chunk: Buffer) => { bytes += chunk.length; if (bytes > maxBytes) stop("Архив базы превышает 64 МиБ", "DATABASE_DUMP_SIZE_LIMIT"); else if (!failure) chunks.push(chunk) })
// Drain stderr without retaining PostgreSQL diagnostics, URLs or passwords.
child.stderr.on("data", (chunk: Buffer) => {
stderrBytes += chunk.length
// Retain only a fixed allowlist of categories, never raw diagnostics.
const text = chunk.toString("utf8").toLowerCase()
for (const [kind, pattern] of [["version", /version mismatch|server version/], ["authentication", /authentication failed|no password supplied/], ["connection", /could not connect|connection refused|connection to server/], ["tls", /certificate verify failed|certificate verification failed/], ["permission", /permission denied/], ["lock", /lock timeout|deadlock detected/]] as const) if (pattern.test(text)) diagnosticKinds.add(kind)
if (stderrBytes > 65536) stop("Диагностика экспорта базы превысила предел", "DATABASE_DUMP_STDERR_LIMIT")
})
child.on("error", () => { failure ??= new DatabaseDumpCommandError("DATABASE_DUMP_TOOL_UNAVAILABLE", "Утилита PostgreSQL недоступна") })
child.on("close", code => {
clearTimeout(timer); if (accessTimer) clearInterval(accessTimer); options.signal?.removeEventListener("abort", abort)
if (failure || code !== 0) reject(failure ?? new DatabaseDumpCommandError("DATABASE_DUMP_EXIT", "Экспорт PostgreSQL не завершён", [...diagnosticKinds], code))
else resolve(Buffer.concat(chunks, bytes))
})
})
}