Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,154 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import type { AuditExportFilters, AuditExportRow, AuditIntegritySummary } from "~/routes/admin/audit-export.helpers.server";
|
||||
import {
|
||||
buildAuditPdfLabels,
|
||||
buildAuditPdfReportInput,
|
||||
renderAuditExportPdfResponse,
|
||||
toAuditPdfEvent,
|
||||
toAuditPdfIntegrity,
|
||||
} from "./pdfRender";
|
||||
|
||||
function makeRow(over: Partial<AuditExportRow> = {}): AuditExportRow {
|
||||
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: "h1",
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
const filters: AuditExportFilters = {
|
||||
from: new Date("2026-05-01T00:00:00.000Z"),
|
||||
to: new Date("2026-05-17T00:00:00.000Z"),
|
||||
regulatoryScope: ["soc2"],
|
||||
actorType: null,
|
||||
outcome: null,
|
||||
tenantId: "tenant_1",
|
||||
};
|
||||
|
||||
const integrity: AuditIntegritySummary = { ok: true, inspected: 1, firstBreakId: null, reason: null };
|
||||
|
||||
describe("toAuditPdfEvent / toAuditPdfIntegrity", () => {
|
||||
it("maps an AuditExportRow into AuditPdfEvent unchanged", () => {
|
||||
const row = makeRow();
|
||||
expect(toAuditPdfEvent(row)).toMatchObject({
|
||||
id: row.id,
|
||||
createdAt: row.createdAt,
|
||||
tenantId: row.tenantId,
|
||||
action: row.action,
|
||||
eventHash: row.eventHash,
|
||||
});
|
||||
});
|
||||
|
||||
it("maps integrity 1:1", () => {
|
||||
expect(toAuditPdfIntegrity(integrity)).toEqual(integrity);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAuditPdfReportInput", () => {
|
||||
it("combines filters + rows + integrity into the renderer input shape", () => {
|
||||
const rows = [makeRow()];
|
||||
const input = buildAuditPdfReportInput({ tenantId: "tenant_1", filters, integrity, rows, generatedBy: "ops-bot" });
|
||||
expect(input.tenantId).toBe("tenant_1");
|
||||
expect(input.from).toBe("2026-05-01T00:00:00.000Z");
|
||||
expect(input.to).toBe("2026-05-17T00:00:00.000Z");
|
||||
expect(input.filterSummary).toContain("regulatoryScope=soc2");
|
||||
expect(input.events).toHaveLength(1);
|
||||
expect(input.integrity.ok).toBe(true);
|
||||
expect(input.generatedBy).toBe("ops-bot");
|
||||
});
|
||||
|
||||
it("passes localized label overrides to the renderer input", () => {
|
||||
const t = ((key: string, args?: Record<string, unknown>) => {
|
||||
if (key === "settings:auditExport.pdf.events") {
|
||||
return `translated events ${args?.count}`;
|
||||
}
|
||||
if (key === "settings:auditExport.pdf.integrity.ok") {
|
||||
return `translated ok ${args?.inspected}`;
|
||||
}
|
||||
if (key === "settings:auditExport.pdf.integrity.broken") {
|
||||
return `translated broken ${args?.firstBreakId}`;
|
||||
}
|
||||
return `translated:${key}`;
|
||||
}) as TFunction;
|
||||
|
||||
const input = buildAuditPdfReportInput({
|
||||
tenantId: "tenant_1",
|
||||
filters,
|
||||
integrity,
|
||||
rows: [makeRow()],
|
||||
labels: buildAuditPdfLabels(t),
|
||||
});
|
||||
|
||||
expect(input.labels?.tenant).toBe("translated:settings:auditExport.pdf.tenant");
|
||||
expect(input.labels?.events?.(3)).toBe("translated events 3");
|
||||
expect(input.labels?.integrityOk?.(1)).toBe("translated ok 1");
|
||||
expect(input.labels?.integrityBroken?.({ inspected: 1, firstBreakId: "audit_1", reason: "hash" })).toBe("translated broken audit_1");
|
||||
expect(input.labels?.columns?.createdAt).toBe("translated:settings:auditExport.pdf.columns.createdAt");
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderAuditExportPdfResponse", () => {
|
||||
it("returns a Response with PDF content-type and chain-status header", async () => {
|
||||
const rows = [makeRow()];
|
||||
const response = await renderAuditExportPdfResponse(
|
||||
{ tenantId: "tenant_1", filters, integrity, rows },
|
||||
{ filenamePrefix: "audit-export-admin" }
|
||||
);
|
||||
expect(response.headers.get("Content-Type")).toBe("application/pdf");
|
||||
expect(response.headers.get("X-Audit-Chain-Status")).toBe("ok");
|
||||
const disposition = response.headers.get("Content-Disposition") ?? "";
|
||||
expect(disposition).toContain("audit-export-admin");
|
||||
expect(disposition).toContain("tenant_1");
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
expect(bytes.length).toBeGreaterThan(0);
|
||||
expect(Buffer.from(bytes.slice(0, 4)).toString("utf8")).toBe("%PDF");
|
||||
});
|
||||
|
||||
it("marks the chain status as broken when integrity.ok=false", async () => {
|
||||
const rows = [makeRow()];
|
||||
const response = await renderAuditExportPdfResponse(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
filters,
|
||||
integrity: { ok: false, inspected: 1, firstBreakId: "audit_1", reason: "hash-mismatch" },
|
||||
rows,
|
||||
},
|
||||
{ filenamePrefix: "audit-export-admin" }
|
||||
);
|
||||
expect(response.headers.get("X-Audit-Chain-Status")).toBe("broken");
|
||||
});
|
||||
|
||||
it("falls back to 'platform' in the filename when tenantId is null", async () => {
|
||||
const rows: AuditExportRow[] = [];
|
||||
const response = await renderAuditExportPdfResponse(
|
||||
{
|
||||
tenantId: null,
|
||||
filters: { ...filters, tenantId: null },
|
||||
integrity: { ok: true, inspected: 0, firstBreakId: null, reason: null },
|
||||
rows,
|
||||
},
|
||||
{ filenamePrefix: "audit-export-admin" }
|
||||
);
|
||||
expect(response.headers.get("Content-Disposition") ?? "").toContain("audit-export-admin-platform-");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Phase 10 Task #67 — Inline PDF helper for the admin/tenant audit-export
|
||||
* routes.
|
||||
*
|
||||
* Wraps `serializeAuditEventsToPdf` from `@toolctrl/exports/audit-pdf`
|
||||
* with the same row + integrity shape the admin route already computes
|
||||
* for the CSV path. Wired into the export route via `?format=pdf`
|
||||
* (the default remains CSV).
|
||||
*
|
||||
* See docs/improvement-plan/10-compliance-polish/compliance-audit-export.md.
|
||||
*/
|
||||
import {
|
||||
AUDIT_PDF_CONTENT_TYPE,
|
||||
AUDIT_PDF_HARD_ROW_LIMIT,
|
||||
serializeAuditEventsToPdf,
|
||||
summarizeAuditPdfFilters,
|
||||
type AuditPdfEvent,
|
||||
type AuditPdfIntegrity,
|
||||
type AuditPdfLabelOverrides,
|
||||
type AuditPdfReportInput,
|
||||
} from "@toolctrl/exports/audit-pdf";
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import type { AuditExportFilters, AuditExportRow, AuditIntegritySummary } from "~/routes/admin/audit-export.helpers.server";
|
||||
|
||||
export { AUDIT_PDF_CONTENT_TYPE, AUDIT_PDF_HARD_ROW_LIMIT };
|
||||
|
||||
/**
|
||||
* Map an in-memory AuditExportRow (from the existing CSV pipeline) to
|
||||
* the AuditPdfEvent shape consumed by @toolctrl/exports/audit-pdf.
|
||||
*
|
||||
* `metadata` is opaque JSON in Prisma — we keep it as-is; the renderer
|
||||
* never inlines metadata into the report body (privacy / page-density
|
||||
* concern).
|
||||
*/
|
||||
export function toAuditPdfEvent(row: AuditExportRow): AuditPdfEvent {
|
||||
return {
|
||||
id: row.id,
|
||||
createdAt: row.createdAt,
|
||||
tenantId: row.tenantId,
|
||||
actorType: row.actorType,
|
||||
actorId: row.actorId,
|
||||
actorEmail: row.actorEmail,
|
||||
actorIp: row.actorIp,
|
||||
actorUserAgent: row.actorUserAgent,
|
||||
action: row.action,
|
||||
targetType: row.targetType,
|
||||
targetId: row.targetId,
|
||||
requestId: row.requestId,
|
||||
sourceModule: row.sourceModule,
|
||||
outcome: row.outcome,
|
||||
dataSensitivity: row.dataSensitivity,
|
||||
regulatoryScope: row.regulatoryScope,
|
||||
metadata: row.metadata,
|
||||
previousHash: row.previousHash,
|
||||
eventHash: row.eventHash,
|
||||
};
|
||||
}
|
||||
|
||||
/** Map our AuditIntegritySummary onto AuditPdfIntegrity (1:1 shape). */
|
||||
export function toAuditPdfIntegrity(integrity: AuditIntegritySummary): AuditPdfIntegrity {
|
||||
return {
|
||||
ok: integrity.ok,
|
||||
inspected: integrity.inspected,
|
||||
firstBreakId: integrity.firstBreakId,
|
||||
reason: integrity.reason,
|
||||
};
|
||||
}
|
||||
|
||||
export type AuditPdfRenderRequest = {
|
||||
tenantId: string | null;
|
||||
filters: AuditExportFilters;
|
||||
integrity: AuditIntegritySummary;
|
||||
rows: ReadonlyArray<AuditExportRow>;
|
||||
generatedBy?: string;
|
||||
generatedAt?: Date;
|
||||
labels?: AuditPdfLabelOverrides;
|
||||
};
|
||||
|
||||
export function buildAuditPdfLabels(t: TFunction): AuditPdfLabelOverrides {
|
||||
return {
|
||||
title: t("settings:auditExport.pdf.title"),
|
||||
tenant: t("settings:auditExport.pdf.tenant"),
|
||||
platformTenant: t("settings:auditExport.pdf.platformTenant"),
|
||||
range: t("settings:auditExport.pdf.range"),
|
||||
openRange: t("settings:auditExport.pdf.openRange"),
|
||||
filters: t("settings:auditExport.pdf.filters"),
|
||||
noFilters: t("settings:auditExport.pdf.noFilters"),
|
||||
generatedBy: t("settings:auditExport.pdf.generatedBy"),
|
||||
generatedAt: t("settings:auditExport.pdf.generatedAt"),
|
||||
hashChainIntegrity: t("settings:auditExport.pdf.hashChainIntegrity"),
|
||||
events: (count) => t("settings:auditExport.pdf.events", { count }),
|
||||
integrityOk: (inspected) => t("settings:auditExport.pdf.integrity.ok", { inspected }),
|
||||
integrityBroken: ({ inspected, firstBreakId, reason }) =>
|
||||
t("settings:auditExport.pdf.integrity.broken", { inspected, firstBreakId, reason }),
|
||||
columns: {
|
||||
createdAt: t("settings:auditExport.pdf.columns.createdAt"),
|
||||
actorType: t("settings:auditExport.pdf.columns.actorType"),
|
||||
actorId: t("settings:auditExport.pdf.columns.actorId"),
|
||||
action: t("settings:auditExport.pdf.columns.action"),
|
||||
targetType: t("settings:auditExport.pdf.columns.targetType"),
|
||||
outcome: t("settings:auditExport.pdf.columns.outcome"),
|
||||
regulatoryScope: t("settings:auditExport.pdf.columns.regulatoryScope"),
|
||||
eventHash: t("settings:auditExport.pdf.columns.eventHash"),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function buildAuditPdfReportInput(req: AuditPdfRenderRequest): AuditPdfReportInput {
|
||||
return {
|
||||
tenantId: req.tenantId,
|
||||
from: req.filters.from?.toISOString() ?? null,
|
||||
to: req.filters.to?.toISOString() ?? null,
|
||||
filterSummary: summarizeAuditPdfFilters({
|
||||
regulatoryScope: req.filters.regulatoryScope,
|
||||
actorType: req.filters.actorType,
|
||||
outcome: req.filters.outcome,
|
||||
}),
|
||||
integrity: toAuditPdfIntegrity(req.integrity),
|
||||
events: req.rows.map(toAuditPdfEvent),
|
||||
...(req.generatedBy ? { generatedBy: req.generatedBy } : {}),
|
||||
...(req.generatedAt ? { generatedAt: req.generatedAt } : {}),
|
||||
...(req.labels ? { labels: req.labels } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the audit-export response as a PDF stream. Returns a
|
||||
* Web-Response with the appropriate Content-Disposition + X-Audit-Chain-Status
|
||||
* headers so the route can return it directly.
|
||||
*/
|
||||
export async function renderAuditExportPdfResponse(
|
||||
req: AuditPdfRenderRequest,
|
||||
options: { filenamePrefix: string }
|
||||
): Promise<Response> {
|
||||
const input = buildAuditPdfReportInput(req);
|
||||
const bytes = await serializeAuditEventsToPdf(input);
|
||||
const filenameSlug = req.tenantId ?? "platform";
|
||||
const fromSlug = req.filters.from ? req.filters.from.toISOString().slice(0, 10) : "all";
|
||||
const toSlug = req.filters.to ? req.filters.to.toISOString().slice(0, 10) : "all";
|
||||
// Convert Uint8Array (Node Buffer slice) to ArrayBuffer for Response body
|
||||
// typing — node's Buffer is fine but Response wants a BodyInit. Slicing
|
||||
// via .buffer keeps the bytes intact.
|
||||
const body = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
"Content-Type": AUDIT_PDF_CONTENT_TYPE,
|
||||
"Content-Disposition": `attachment; filename="${options.filenamePrefix}-${filenameSlug}-${fromSlug}_${toSlug}.pdf"`,
|
||||
"X-Audit-Chain-Status": req.integrity.ok ? "ok" : "broken",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { extractWebActorIp, extractWebActorUserAgent, extractWebRequestId, getWebAuditContext, withAuditContext } from "./withAuditContext.js";
|
||||
|
||||
function makeRequest(headers: Record<string, string>): Request {
|
||||
return new Request("https://example.com/", { headers });
|
||||
}
|
||||
|
||||
describe("extractWebActorIp", () => {
|
||||
it("prefers cf-connecting-ip > x-real-ip > x-forwarded-for first hop", () => {
|
||||
expect(extractWebActorIp(makeRequest({ "cf-connecting-ip": "1.1.1.1", "x-forwarded-for": "2.2.2.2" }))).toBe("1.1.1.1");
|
||||
expect(extractWebActorIp(makeRequest({ "x-real-ip": "2.2.2.2" }))).toBe("2.2.2.2");
|
||||
expect(extractWebActorIp(makeRequest({ "x-forwarded-for": "3.3.3.3, 8.8.8.8" }))).toBe("3.3.3.3");
|
||||
expect(extractWebActorIp(makeRequest({}))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractWebActorUserAgent", () => {
|
||||
it("returns capped trimmed value or null", () => {
|
||||
expect(extractWebActorUserAgent(makeRequest({ "user-agent": " ua " }))).toBe("ua");
|
||||
expect(extractWebActorUserAgent(makeRequest({ "user-agent": "x".repeat(600) })!)?.length).toBe(512);
|
||||
expect(extractWebActorUserAgent(makeRequest({}))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractWebRequestId", () => {
|
||||
it("returns trimmed value or null for oversize/missing", () => {
|
||||
expect(extractWebRequestId(makeRequest({ "x-request-id": "req_1" }))).toBe("req_1");
|
||||
expect(extractWebRequestId(makeRequest({ "x-request-id": "x".repeat(200) }))).toBeNull();
|
||||
expect(extractWebRequestId(makeRequest({}))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("withAuditContext", () => {
|
||||
it("binds the context for the duration of the callback", async () => {
|
||||
expect(getWebAuditContext()).toBeNull();
|
||||
const captured = await withAuditContext({ request: makeRequest({ "cf-connecting-ip": "5.5.5.5", "user-agent": "Test/1.0", "x-request-id": "req_1" }) }, async () => getWebAuditContext());
|
||||
expect(captured).toEqual({ actorIp: "5.5.5.5", actorUserAgent: "Test/1.0", requestId: "req_1" });
|
||||
expect(getWebAuditContext()).toBeNull();
|
||||
});
|
||||
|
||||
it("passes through when request is undefined", async () => {
|
||||
const captured = await withAuditContext({}, async () => getWebAuditContext());
|
||||
expect(captured).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
|
||||
/**
|
||||
* Phase 10 Task #67 — Audit auto-capture (React-Router web).
|
||||
*
|
||||
* The Hono API has its own AsyncLocalStorage-backed audit context (see
|
||||
* apps/api/src/middleware/audit-context.ts). The React-Router runtime
|
||||
* has no global middleware hook for loader/action invocation, so we
|
||||
* expose a thin wrapper that loaders + actions can opt into via
|
||||
* `withAuditContext(args, async () => { ... })`.
|
||||
*
|
||||
* The helper extracts actor IP / user agent / request id from the
|
||||
* inbound Request headers and binds them into a request-scoped store
|
||||
* so any `createAuditEvent` invocation deeper in the call stack can
|
||||
* read them.
|
||||
*/
|
||||
|
||||
export type WebAuditContext = {
|
||||
actorIp: string | null;
|
||||
actorUserAgent: string | null;
|
||||
requestId: string | null;
|
||||
};
|
||||
|
||||
const webAuditContextStore = new AsyncLocalStorage<WebAuditContext>();
|
||||
|
||||
const FORWARDED_HEADERS = ["cf-connecting-ip", "x-real-ip", "x-forwarded-for"] as const;
|
||||
|
||||
export function extractWebActorIp(request: Request): string | null {
|
||||
for (const name of FORWARDED_HEADERS) {
|
||||
const raw = request.headers.get(name);
|
||||
if (typeof raw !== "string") continue;
|
||||
const first = raw.split(",")[0]?.trim();
|
||||
if (first && first.length > 0 && first.length <= 64) return first;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function extractWebActorUserAgent(request: Request): string | null {
|
||||
const raw = request.headers.get("user-agent");
|
||||
if (typeof raw !== "string") return null;
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
return trimmed.length > 512 ? trimmed.slice(0, 512) : trimmed;
|
||||
}
|
||||
|
||||
export function extractWebRequestId(request: Request): string | null {
|
||||
const raw = request.headers.get("x-request-id");
|
||||
if (typeof raw !== "string") return null;
|
||||
const trimmed = raw.trim();
|
||||
return trimmed.length === 0 || trimmed.length > 128 ? null : trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a loader/action body with an audit context bound from the inbound
|
||||
* request. Falls through transparently when no Request is available.
|
||||
*/
|
||||
export async function withAuditContext<T>(args: { request: Request } | { request?: Request }, fn: () => Promise<T>): Promise<T> {
|
||||
const request = (args as { request?: Request }).request;
|
||||
if (!request) return fn();
|
||||
const ctx: WebAuditContext = {
|
||||
actorIp: extractWebActorIp(request),
|
||||
actorUserAgent: extractWebActorUserAgent(request),
|
||||
requestId: extractWebRequestId(request),
|
||||
};
|
||||
return webAuditContextStore.run(ctx, fn);
|
||||
}
|
||||
|
||||
export function getWebAuditContext(): WebAuditContext | null {
|
||||
return webAuditContextStore.getStore() ?? null;
|
||||
}
|
||||
Reference in new issue
Block a user