/** * Compliance-Audit PDF report renderer. * * Renders an AuditEvent slice into a tamper-evident PDF report suitable * for SOC2 / HIPAA / GDPR auditor evidence packs. The first page is a * cover page with tenant + range + filter summary + verifyAuditChain * integrity outcome; following pages list events as a tabular log. * * The renderer is host-agnostic and async — both the operator CLI * (`hivegrid audit export-pdf …`) and the admin web export route use * it via `serializeAuditEventsToPdf` / `serializeAuditEventsToPdfStream`. * * See docs/improvement-plan/10-compliance-polish/compliance-audit-export.md. */ import type { Writable } from "node:stream"; import React from "react"; import { Document, Page, StyleSheet, Text, View, renderToBuffer, renderToStream } from "@react-pdf/renderer"; import { PDF_STREAM_HARD_ROW_LIMIT, ExportPdfRowLimitExceededError } from "./pdf/index.js"; export const AUDIT_PDF_CONTENT_TYPE = "application/pdf" as const; export const AUDIT_PDF_HARD_ROW_LIMIT = PDF_STREAM_HARD_ROW_LIMIT; export type AuditPdfEvent = { id: string; createdAt: Date | string; 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: ReadonlyArray; metadata: unknown; previousHash: string | null; eventHash: string | null; }; export type AuditPdfIntegrity = { ok: boolean; inspected: number; firstBreakId: string | null; reason: string | null; }; export type AuditPdfReportInput = { /** Tenant identifier; null = platform-wide. */ tenantId: string | null; /** ISO-8601 lower bound used by the export query. */ from: string | null; /** ISO-8601 upper bound used by the export query. */ to: string | null; /** Free-text filter summary (regulatoryScope/actorType/outcome). */ filterSummary: string; /** Pre-computed verifyAuditChain integrity result. */ integrity: AuditPdfIntegrity; /** Events in chronological order. */ events: ReadonlyArray; /** Operator-facing report title (defaults to "Audit-Compliance Report"). */ title?: string; /** Human display name of the operator who generated the report. */ generatedBy?: string; /** Timestamp of report generation; defaults to new Date(). */ generatedAt?: Date; /** Visible report labels; pass localized labels from the caller when needed. */ labels?: AuditPdfLabelOverrides; }; type AuditPdfColumnKey = "createdAt" | "actorType" | "actorId" | "action" | "targetType" | "outcome" | "regulatoryScope" | "eventHash"; export type AuditPdfLabels = { title: string; tenant: string; platformTenant: string; range: string; openRange: string; filters: string; noFilters: string; generatedBy: string; generatedAt: string; hashChainIntegrity: string; events: (count: number) => string; integrityOk: (inspected: number) => string; integrityBroken: (args: { inspected: number; firstBreakId: string; reason: string }) => string; columns: Record; }; export type AuditPdfLabelOverrides = Partial> & { columns?: Partial; }; const labelText = (value: string) => value; const DEFAULT_AUDIT_PDF_LABELS: AuditPdfLabels = { title: labelText("Audit compliance report"), tenant: "Tenant", platformTenant: "platform", range: "Range", openRange: "open", filters: "Filters", noFilters: "none", generatedBy: "Generated by", generatedAt: "Generated at", hashChainIntegrity: "Hash-chain integrity", events: (count) => `Events (${count})`, integrityOk: (inspected) => `verifyAuditChain OK - inspected ${inspected} events.`, integrityBroken: ({ inspected, firstBreakId, reason }) => `verifyAuditChain BROKEN - inspected ${inspected} events. First-break id=${firstBreakId} reason=${reason}.`, columns: { createdAt: "Time", actorType: "Actor", actorId: "Actor ID", action: "Action", targetType: "Target", outcome: "Outcome", regulatoryScope: "Scope", eventHash: "Hash", }, }; const styles = StyleSheet.create({ page: { padding: 32, fontSize: 9, fontFamily: "Helvetica" }, title: { fontSize: 18, fontWeight: 700, marginBottom: 12 }, subtitle: { fontSize: 12, fontWeight: 700, marginTop: 12, marginBottom: 6 }, meta: { marginBottom: 4 }, integrityOk: { color: "#047857", fontWeight: 700 }, integrityBroken: { color: "#b91c1c", fontWeight: 700 }, table: { display: "flex", flexDirection: "column", width: "100%", borderTopWidth: 1, borderLeftWidth: 1, borderColor: "#d1d5db", marginTop: 8, }, row: { display: "flex", flexDirection: "row" }, headerCell: { flexGrow: 1, flexBasis: 0, padding: 4, fontWeight: 700, backgroundColor: "#f3f4f6", borderRightWidth: 1, borderBottomWidth: 1, borderColor: "#d1d5db", }, cell: { flexGrow: 1, flexBasis: 0, padding: 4, borderRightWidth: 1, borderBottomWidth: 1, borderColor: "#d1d5db", }, }); const COLUMNS: ReadonlyArray<{ key: AuditPdfColumnKey; render?: (event: AuditPdfEvent) => string }> = [ { key: "createdAt", render: (e) => (e.createdAt instanceof Date ? e.createdAt.toISOString() : String(e.createdAt)) }, { key: "actorType" }, { key: "actorId", render: (e) => e.actorId ?? "-" }, { key: "action" }, { key: "targetType", render: (e) => `${e.targetType ?? "-"}/${e.targetId ?? "-"}` }, { key: "outcome" }, { key: "regulatoryScope", render: (e) => e.regulatoryScope.join(",") || "-" }, { key: "eventHash", render: (e) => (e.eventHash ? e.eventHash.slice(0, 16) : "-") }, ]; function resolveAuditPdfLabels(input?: AuditPdfLabelOverrides): AuditPdfLabels { return { ...DEFAULT_AUDIT_PDF_LABELS, ...input, columns: { ...DEFAULT_AUDIT_PDF_LABELS.columns, ...input?.columns, }, }; } function buildIntegrityLine(integrity: AuditPdfIntegrity, labels: AuditPdfLabels): string { if (integrity.ok) { return labels.integrityOk(integrity.inspected); } return labels.integrityBroken({ inspected: integrity.inspected, firstBreakId: integrity.firstBreakId ?? "?", reason: integrity.reason ?? "unknown", }); } export function buildAuditPdfDocument(input: AuditPdfReportInput): ReturnType { const labels = resolveAuditPdfLabels(input.labels); const generatedAt = (input.generatedAt ?? new Date()).toISOString(); const integrityStyle = input.integrity.ok ? styles.integrityOk : styles.integrityBroken; const eventRows = input.events.map((event, index) => React.createElement( View, { key: `row-${event.id}-${index}`, style: styles.row }, ...COLUMNS.map((col) => { const raw = col.render ? col.render(event) : (event[col.key] as unknown); const text = raw === null || raw === undefined ? "-" : String(raw); return React.createElement(Text, { key: `${event.id}-${col.key}`, style: styles.cell }, text); }) ) ); return React.createElement( Document, { title: input.title ?? labels.title }, React.createElement( Page, { size: "A4", style: styles.page }, React.createElement(Text, { style: styles.title }, input.title ?? labels.title), React.createElement(Text, { style: styles.meta }, `${labels.tenant}: ${input.tenantId ?? `(${labels.platformTenant})`}`), React.createElement(Text, { style: styles.meta }, `${labels.range}: ${input.from ?? `(${labels.openRange})`} ... ${input.to ?? `(${labels.openRange})`}`), React.createElement(Text, { style: styles.meta }, `${labels.filters}: ${input.filterSummary || labels.noFilters}`), input.generatedBy ? React.createElement(Text, { style: styles.meta }, `${labels.generatedBy}: ${input.generatedBy}`) : null, React.createElement(Text, { style: styles.meta }, `${labels.generatedAt}: ${generatedAt}`), React.createElement(Text, { style: styles.subtitle }, labels.hashChainIntegrity), React.createElement(Text, { style: integrityStyle }, buildIntegrityLine(input.integrity, labels)), React.createElement(Text, { style: styles.subtitle }, labels.events(input.events.length)), React.createElement( View, { style: styles.table }, React.createElement( View, { style: styles.row }, ...COLUMNS.map((col) => React.createElement(Text, { key: `head-${col.key}`, style: styles.headerCell }, labels.columns[col.key]) ) ), ...eventRows ) ) ); } export async function serializeAuditEventsToPdf(input: AuditPdfReportInput): Promise { if (input.events.length > AUDIT_PDF_HARD_ROW_LIMIT) { throw new ExportPdfRowLimitExceededError(input.events.length); } const doc = buildAuditPdfDocument(input); return new Uint8Array(await renderToBuffer(doc)); } export async function serializeAuditEventsToPdfStream(writeStream: Writable, input: AuditPdfReportInput): Promise<{ rowCount: number }> { if (input.events.length > AUDIT_PDF_HARD_ROW_LIMIT) { throw new ExportPdfRowLimitExceededError(input.events.length); } const doc = buildAuditPdfDocument(input); const readable = await renderToStream(doc); await new Promise((resolve, reject) => { readable.on("error", reject); writeStream.on("error", reject); readable.on("end", () => resolve()); readable.pipe(writeStream, { end: false }); }); return { rowCount: input.events.length }; } /** * Format the active filters into a compact one-liner suitable for the * cover-page metadata. Shared between CLI and web call-sites so the * report self-describes the operator inputs identically. */ export function summarizeAuditPdfFilters(filters: { regulatoryScope?: ReadonlyArray; actorType?: string | null; outcome?: string | null; }): string { const parts: string[] = []; if (filters.regulatoryScope && filters.regulatoryScope.length > 0) { parts.push(`regulatoryScope=${filters.regulatoryScope.join("|")}`); } if (filters.actorType) parts.push(`actorType=${filters.actorType}`); if (filters.outcome) parts.push(`outcome=${filters.outcome}`); return parts.join(" "); }