/** * Pure helpers for the audit-export route. Extracted so unit tests can * import them without dragging in the route module's server-only deps * (PrismaClient, getDbClient, session secret env vars). */ import { verifyAuditChain } from "@hivegrid/db/audit-hash"; import { auditChainKey, type AuditVerificationContext } from "@hivegrid/db/audit-chain-checkpoint.server"; import { neutralizeSpreadsheetFormula } from "@hivegrid/foundation/spreadsheet-safety"; const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/; const FILTER_ALL = "__all__"; export const AUDIT_EXPORT_MAX_ROWS = 50_000; export const AUDIT_EXPORT_CSV_COLUMNS = [ "id", "createdAt", "tenantId", "actorType", "actorId", "actorEmail", "actorIp", "actorUserAgent", "action", "targetType", "targetId", "requestId", "sourceModule", "outcome", "dataSensitivity", "regulatoryScope", "metadata", "previousHash", "eventHash", ] as const; export type AuditExportFilters = { from: Date | null; to: Date | null; regulatoryScope: string[]; actorType: string | null; outcome: string | null; tenantId: string | null; }; export type AuditExportRow = { id: string; createdAt: Date; tenantId: string | null; actorType: string; actorId: string | null; actorEmail: string | null; actorIp: string | null; actorUserAgent: string | null; action: string; targetType: string | null; targetId: string | null; requestId: string | null; sourceModule: string | null; outcome: string; dataSensitivity: string; regulatoryScope: string[]; metadata: unknown; previousHash: string | null; eventHash: string | null; }; export type AuditIntegritySummary = { ok: boolean; inspected: number; firstBreakId: string | null; reason: string | null; }; export function stripAuditExportFilterSentinels(url: URL): URL { const cleaned = new URL(url.toString()); for (const key of Array.from(cleaned.searchParams.keys())) { const values = cleaned.searchParams.getAll(key).filter((value) => value.trim() !== FILTER_ALL); cleaned.searchParams.delete(key); for (const value of values) cleaned.searchParams.append(key, value); } return cleaned; } export function parseAuditExportFilters(url: URL): AuditExportFilters { return { from: parseIsoDate(url.searchParams.get("from")), to: parseIsoDate(url.searchParams.get("to")), regulatoryScope: url.searchParams.getAll("regulatoryScope").map((s) => s.trim().toLowerCase()).filter(Boolean), actorType: url.searchParams.get("actorType")?.trim() || null, outcome: url.searchParams.get("outcome")?.trim() || null, tenantId: url.searchParams.get("tenantId")?.trim() || null, }; } function parseIsoDate(raw: string | null): Date | null { if (!raw || !ISO_DATE.test(raw)) return null; const d = new Date(`${raw}T00:00:00.000Z`); return Number.isNaN(d.getTime()) ? null : d; } export function buildAuditExportWhere(filters: AuditExportFilters): Record { const where: Record = {}; if (filters.tenantId) where.tenantId = filters.tenantId; if (filters.actorType) where.actorType = filters.actorType; if (filters.outcome) where.outcome = filters.outcome; if (filters.regulatoryScope.length > 0) where.regulatoryScope = { hasSome: filters.regulatoryScope }; if (filters.from || filters.to) { const range: Record = {}; if (filters.from) range.gte = filters.from; if (filters.to) { const upper = new Date(filters.to); upper.setUTCDate(upper.getUTCDate() + 1); range.lt = upper; } where.createdAt = range; } return where; } export function hasAuditExportPrefixFilters(filters: AuditExportFilters): boolean { return Boolean( filters.from || filters.actorType || filters.outcome || filters.regulatoryScope.length > 0, ); } export function computeAuditIntegritySummary( rows: ReadonlyArray, context?: AuditVerificationContext, ): AuditIntegritySummary { const chains = new Map(); for (const row of rows) { const key = row.tenantId ?? "__platform__"; const list = chains.get(key) ?? []; list.push(row); chains.set(key, list); } let inspected = 0; for (const [key, list] of chains) { list.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id)); const chainKey = auditChainKey(key === "__platform__" ? null : key); if (context?.invalidCheckpointChains.has(chainKey)) { return { ok: false, inspected, firstBreakId: list[0]?.id ?? null, reason: "checkpoint-authentication-failed" }; } const result = verifyAuditChain( list.map((row) => ({ ...row, createdAt: row.createdAt.toISOString() })), { initialPreviousHash: context?.initialPreviousHashes.get(chainKey) ?? null }, ); inspected += result.inspected; if (!result.ok) { return { ok: false, inspected, firstBreakId: result.firstBreak?.eventId ?? null, reason: result.firstBreak?.reason ?? "unknown", }; } } return { ok: true, inspected, firstBreakId: null, reason: null }; } export function renderAuditExportCsv(rows: ReadonlyArray, integrity: AuditIntegritySummary): string { const lines: string[] = []; lines.push(`# verifyAuditChain: ok=${integrity.ok} inspected=${integrity.inspected} firstBreakId=${integrity.firstBreakId ?? "-"} reason=${integrity.reason ?? "-"}`); lines.push(AUDIT_EXPORT_CSV_COLUMNS.join(",")); for (const row of rows) { lines.push( AUDIT_EXPORT_CSV_COLUMNS.map((col) => { const value = (row as unknown as Record)[col]; return csvCell(value); }).join(",") ); } return `${lines.join("\n")}\n`; } /** * NDJSON rendering (AK-P3 DoD 3): one JSON object per line. The first line is a * `{"_integrity": ...}` record mirroring the CSV integrity header so a streamed * export still carries the chain-verification evidence. */ export function renderAuditExportNdjson(rows: ReadonlyArray, integrity: AuditIntegritySummary): string { const lines: string[] = []; lines.push(JSON.stringify({ _integrity: integrity })); for (const row of rows) { const record: Record = {}; for (const col of AUDIT_EXPORT_CSV_COLUMNS) { const value = (row as unknown as Record)[col]; record[col] = value instanceof Date ? value.toISOString() : value; } lines.push(JSON.stringify(record)); } return `${lines.join("\n")}\n`; } export function csvCell(value: unknown): string { if (value === null || value === undefined) return ""; if (Array.isArray(value)) return csvCell(value.join("|")); if (value instanceof Date) return value.toISOString(); if (typeof value === "object") return csvCell(JSON.stringify(value)); const safeValue = neutralizeSpreadsheetFormula(String(value)); if (/[",\n\r]/.test(safeValue)) return `"${safeValue.replace(/"/g, '""')}"`; return safeValue; }