Files
MikrotikManager/backend/src/services/server-probe-public-result.ts
T

42 lines
3.9 KiB
TypeScript

import { createHash } from "node:crypto"
import { z } from "zod"
import type { ServerProbeReceipt } from "./server-probe-execution.js"
const LIMIT = 131072, PAGE_BYTES = 9000
const sensitive = /password|passwd|secret|private.?key|preshared|pre.shared|authorization|auth.?key|authentication.?key|tcp.?md5.?key|api.?key|certificate.?contents|token|ciphertext/i
const schema = z.object({ receiptId: z.string().uuid(), tool: z.enum(["ping", "traceroute", "bandwidth", "dns", "route", "mtu"]), serverId: z.number().int().positive().safe(), destinationServerId: z.number().int().positive().safe().optional(), state: z.enum(["completed", "failed", "cancelled", "unknown"]), httpStatus: z.number().int().min(100).max(599), output: z.string().max(LIMIT).optional(), data: z.record(z.string(), z.unknown()).optional(), errorCode: z.string().regex(/^[A-Z_]+$/).max(100).optional(), attemptedStages: z.number().int().min(0).max(11), completedStages: z.number().int().min(0).max(11), automaticReplay: z.literal(false), forwardingVerified: z.literal(false) }).strict()
function text(value: string) {
return value.replace(/\bBearer\s+[^\s,;]+/gi, "Bearer [redacted]")
.replace(/\bmmcp_[a-z]+_[A-Za-z0-9_-]+/g, "[redacted]")
.replace(/((?:password|secret|private-key|preshared-key|auth-key|authentication-key|tcp-md5-key|api-key|token)\s*[=:]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi, "$1[redacted]")
}
/** Same sensitive fields/text as generic MCP redaction, with explicit whole
* receipt byte/depth limits instead of silent string/array truncation. Known
* endpoint usernames/passwords must also be redacted by the shared executor. */
export function sanitizeServerProbeReceipt(receipt: ServerProbeReceipt): ServerProbeReceipt {
schema.parse(receipt)
if (receipt.completedStages > receipt.attemptedStages || receipt.state === "completed" && (receipt.httpStatus !== 200 || receipt.output === undefined || receipt.data === undefined || receipt.attemptedStages < 1 || receipt.completedStages !== receipt.attemptedStages)) throw new Error("Invalid diagnostic receipt")
const clean = (value: unknown, depth = 0): unknown => {
if (depth > 12) throw new Error("Diagnostic receipt depth limit")
if (value === undefined || value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return value
if (typeof value === "string") return text(value)
if (Array.isArray(value)) { if (value.length > 10000) throw new Error("Diagnostic receipt array limit"); return value.map(item => clean(item, depth + 1)) }
if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype || Object.keys(value).length > 2000) throw new Error("Invalid diagnostic receipt data")
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sensitive.test(key) && !/Ref$|Configured$/i.test(key) ? "[redacted]" : clean(item, depth + 1)]))
}
const safe = schema.parse(clean(receipt))
if (Buffer.byteLength(JSON.stringify(safe)) > LIMIT) throw new Error("Diagnostic receipt byte limit")
return safe
}
/** Base64 is transport encoding of already sanitized PUBLIC measurements. It
* is not encryption. Fixed-size pages survive generic MCP output truncation;
* callers must authorize the owned receipt before requesting each page. */
export function serverProbeReceiptPage(receipt: ServerProbeReceipt, page: number) {
if (!Number.isSafeInteger(page) || page < 0) throw new Error("Invalid diagnostic page")
const safe = sanitizeServerProbeReceipt(receipt), content = Buffer.from(JSON.stringify(safe)), totalPages = Math.ceil(content.length / PAGE_BYTES)
if (page >= totalPages) throw new Error("Diagnostic page out of range")
return { receiptId: safe.receiptId, page, totalPages, bytes: content.length, sha256: createHash("sha256").update(content).digest("hex"), encoding: "base64-json-utf8" as const, contentB64: content.subarray(page * PAGE_BYTES, (page + 1) * PAGE_BYTES).toString("base64"), nextPage: page + 1 < totalPages ? page + 1 : null }
}