import { PassThrough } from "node:stream"; import { describe, expect, it } from "vitest"; import { AUDIT_PDF_HARD_ROW_LIMIT, buildAuditPdfDocument, serializeAuditEventsToPdfStream, type AuditPdfEvent, type AuditPdfReportInput, } from "./audit-pdf.js"; import { ExportPdfRowLimitExceededError } from "./pdf/index.js"; function makeEvent(over: Partial = {}): AuditPdfEvent { return { id: "audit_1", createdAt: new Date("2026-05-17T00:00:00.000Z"), tenantId: "tenant_1", actorType: "user", actorId: "user_1", actorEmail: null, actorIp: null, actorUserAgent: null, action: "widget.created", targetType: "widget", targetId: "widget_1", requestId: null, sourceModule: "crm", outcome: "success", dataSensitivity: "internal", regulatoryScope: ["soc2"], metadata: null, previousHash: null, eventHash: "deadbeef0123456789abcdef0123456789abcdef0123456789abcdef01234567", ...over, }; } function makeInput(over: Partial = {}): AuditPdfReportInput { return { tenantId: "tenant_1", from: "2026-05-01", to: "2026-05-17", filterSummary: "regulatoryScope=soc2", integrity: { ok: true, inspected: 1, firstBreakId: null, reason: null }, events: [makeEvent()], generatedAt: new Date("2026-05-17T12:34:56.000Z"), generatedBy: "ops-bot", ...over, }; } function collectText(node: unknown): string { if (typeof node === "string" || typeof node === "number") { return String(node); } if (!node || typeof node !== "object") { return ""; } const children = (node as { props?: { children?: unknown } }).props?.children; if (Array.isArray(children)) { return children.map(collectText).join(" "); } return collectText(children); } describe("buildAuditPdfDocument — broken integrity and null-heavy events", () => { it("renders a broken hash-chain line with the offending id and reason", () => { const doc = buildAuditPdfDocument( makeInput({ integrity: { ok: false, inspected: 9, firstBreakId: "audit_7", reason: "hash mismatch" }, }), ); const text = collectText(doc); expect(text).toContain("verifyAuditChain BROKEN"); expect(text).toContain("inspected 9 events"); expect(text).toContain("id=audit_7"); expect(text).toContain("reason=hash mismatch"); }); it("falls back to placeholders when the break id and reason are null", () => { const doc = buildAuditPdfDocument( makeInput({ integrity: { ok: false, inspected: 3, firstBreakId: null, reason: null }, }), ); const text = collectText(doc); expect(text).toContain("id=?"); expect(text).toContain("reason=unknown"); }); it("renders placeholder dashes and platform/open metadata for sparse inputs", () => { const doc = buildAuditPdfDocument({ tenantId: null, from: null, to: null, filterSummary: "", integrity: { ok: true, inspected: 0, firstBreakId: null, reason: null }, events: [ makeEvent({ createdAt: "2026-05-17T00:00:00.000Z", // string branch, not a Date actorId: null, targetType: null, targetId: null, regulatoryScope: [], eventHash: null, }), ], // generatedBy intentionally omitted, generatedAt defaults to now }); const text = collectText(doc); // tenant null -> "(platform)", range null -> "(open)", empty filter -> "none" expect(text).toContain("(platform)"); expect(text).toContain("(open)"); expect(text).toContain("none"); // regulatoryScope [] and eventHash null both collapse to "-" expect(text).toContain("-"); }); }); describe("serializeAuditEventsToPdfStream", () => { it("pipes a real PDF byte stream into the sink and reports the row count", async () => { const sink = new PassThrough(); const chunks: Buffer[] = []; sink.on("data", (chunk: Buffer) => chunks.push(chunk)); const result = await serializeAuditEventsToPdfStream(sink, makeInput({ events: [makeEvent(), makeEvent({ id: "audit_2" })] })); expect(result).toEqual({ rowCount: 2 }); const buffer = Buffer.concat(chunks); expect(buffer.byteLength).toBeGreaterThan(100); expect(buffer.slice(0, 4).toString("utf8")).toBe("%PDF"); }); it("rejects when the event count exceeds the hard cap before rendering", async () => { const sink = new PassThrough(); sink.on("data", () => undefined); const tooMany: AuditPdfEvent[] = Array.from({ length: AUDIT_PDF_HARD_ROW_LIMIT + 1 }, (_, i) => makeEvent({ id: `e_${i}` }), ); await expect( serializeAuditEventsToPdfStream(sink, makeInput({ events: tooMany })), ).rejects.toBeInstanceOf(ExportPdfRowLimitExceededError); }); });