Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+18
@@ -0,0 +1,18 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const sourcePath = path.resolve(process.cwd(), "packages/view-models/src/audit/audit-export.vm.ts");
|
||||
|
||||
describe("tenant audit export i18n", () => {
|
||||
it("uses semantic keys for filter option labels", () => {
|
||||
const source = fs.readFileSync(sourcePath, "utf8");
|
||||
|
||||
expect(source).toContain("auditExport.scopes.soc2");
|
||||
expect(source).toContain("auditExport.actorTypes.apiKey");
|
||||
expect(source).not.toContain(">soc2<");
|
||||
expect(source).not.toContain(">gdpr<");
|
||||
expect(source).not.toContain(">api_key<");
|
||||
});
|
||||
});
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "./audit-export";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
getUserInfo: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/rls-context.server", () => ({
|
||||
runWithRlsContext: vi.fn((_context, callback) => callback()),
|
||||
}));
|
||||
|
||||
const params = { tenant: "acme" };
|
||||
const findMany = vi.fn();
|
||||
|
||||
function callLoader(url: string) {
|
||||
const request = new Request(url);
|
||||
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/compliance/audit-export" } as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
describe("tenant audit export route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user-1" } as never);
|
||||
findMany.mockResolvedValue([]);
|
||||
vi.mocked(getDbClient).mockReturnValue({ auditEvent: { findMany } } as never);
|
||||
});
|
||||
|
||||
it("checks tenant audit-trail permission before returning export defaults", async () => {
|
||||
const response = (await callLoader("https://app.example.test/acme/settings/compliance/audit-export")) as Response;
|
||||
const data = await response.json();
|
||||
|
||||
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
|
||||
expect(findMany).not.toHaveBeenCalled();
|
||||
expect(data).toMatchObject({
|
||||
title: "translated:models.log.plural | HiveGrid",
|
||||
tenantSlug: "acme",
|
||||
// AK-SET-01: the filter defaults live in the shared AuditExportVM now.
|
||||
vm: { status: "ready", data: { maxRows: expect.any(Number) } },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps CSV export tenant-scoped and permission-gated", async () => {
|
||||
const response = (await callLoader(
|
||||
"https://app.example.test/acme/settings/compliance/audit-export?export=csv&tenantId=other-tenant&from=2026-05-01&to=2026-05-31",
|
||||
)) as Response;
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(findMany.mock.invocationCallOrder[0]);
|
||||
expect(findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({ tenantId: "tenant-1" }),
|
||||
orderBy: { createdAt: "asc" },
|
||||
}),
|
||||
);
|
||||
expect(JSON.stringify(findMany.mock.calls[0]?.[0])).not.toContain("other-tenant");
|
||||
expect(runWithRlsContext).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: "user-1" }, expect.any(Function));
|
||||
expect(response.headers.get("Content-Type")).toBe("text/csv; charset=utf-8");
|
||||
expect(response.headers.get("Content-Disposition")).toContain("audit-export-tenant-1-2026-05-01_2026-05-31.csv");
|
||||
});
|
||||
|
||||
it("drops UI all-filter sentinels before building the tenant query", async () => {
|
||||
await callLoader(
|
||||
"https://app.example.test/acme/settings/compliance/audit-export?export=csv&actorType=__all__&outcome=__all__®ulatoryScope=__all__",
|
||||
);
|
||||
|
||||
expect(findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { tenantId: "tenant-1" } }),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects export reads without touching audit rows when permission is missing", async () => {
|
||||
const rejection = new Response("Forbidden", { status: 403 });
|
||||
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
|
||||
|
||||
await expect(callLoader("https://app.example.test/acme/settings/compliance/audit-export?export=csv")).rejects.toBe(rejection);
|
||||
|
||||
expect(findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Phase 10 Task #67 — Tenant Compliance-Audit-Export.
|
||||
*
|
||||
* Per-tenant self-service variant of the admin audit-export. Identical
|
||||
* filter surface but tenantId-locked: a tenant admin can only see their
|
||||
* own AuditEvent rows. Used for SOC2-Type-II evidence collection by
|
||||
* tenants who need to deliver their own privileged-action report.
|
||||
*/
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { useLoaderData } from "react-router";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
import { loadAuditVerificationContext } from "@hivegrid/db/audit-chain-checkpoint.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { buildAuditExportVM, type AuditExportVM } from "@hivegrid/view-models";
|
||||
import { AuditExportPage } from "~/components/screens/audit/AuditExportPage";
|
||||
import {
|
||||
AUDIT_EXPORT_MAX_ROWS,
|
||||
buildAuditExportWhere,
|
||||
computeAuditIntegritySummary,
|
||||
hasAuditExportPrefixFilters,
|
||||
parseAuditExportFilters,
|
||||
renderAuditExportCsv,
|
||||
stripAuditExportFilterSentinels,
|
||||
type AuditExportRow,
|
||||
} from "~/routes/admin/audit-export.helpers.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
tenantSlug: string;
|
||||
vm: AuditExportVM;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
|
||||
const url = stripAuditExportFilterSentinels(new URL(request.url));
|
||||
if (url.searchParams.get("export") === "csv") {
|
||||
return streamTenantAuditExport(tenantId, userInfo.userId, url);
|
||||
}
|
||||
if (url.searchParams.get("export") === "pdf" || url.searchParams.get("format") === "pdf") {
|
||||
return streamTenantAuditPdfExport(tenantId, userInfo.userId, url, t);
|
||||
}
|
||||
const today = new Date();
|
||||
const fromDate = new Date(today);
|
||||
fromDate.setDate(fromDate.getDate() - 30);
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.log.plural")} | ${process.env.APP_NAME}`,
|
||||
tenantSlug: params.tenant ?? "",
|
||||
vm: buildAuditExportVM({
|
||||
defaultFrom: fromDate.toISOString().slice(0, 10),
|
||||
defaultTo: today.toISOString().slice(0, 10),
|
||||
maxRows: AUDIT_EXPORT_MAX_ROWS,
|
||||
}),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
async function loadTenantAuditExportRows(tenantId: string, userId: string, url: URL) {
|
||||
// Force tenantId scope onto the URL filters so a request that tries to
|
||||
// smuggle a different tenantId via query string is silently ignored.
|
||||
const filters = { ...parseAuditExportFilters(url), tenantId };
|
||||
const db = getDbClient();
|
||||
return runWithRlsContext({ tenantId, userId }, async () => {
|
||||
const rows = (await db.auditEvent.findMany({
|
||||
where: buildAuditExportWhere(filters),
|
||||
orderBy: { createdAt: "asc" },
|
||||
take: AUDIT_EXPORT_MAX_ROWS,
|
||||
})) as unknown as AuditExportRow[];
|
||||
const verification = await loadAuditVerificationContext(db as never, rows, {
|
||||
allowPartialPrefix: hasAuditExportPrefixFilters(filters),
|
||||
});
|
||||
return { filters, rows, verification };
|
||||
});
|
||||
}
|
||||
|
||||
async function streamTenantAuditExport(tenantId: string, userId: string, url: URL): Promise<Response> {
|
||||
const { rows, verification } = await loadTenantAuditExportRows(tenantId, userId, url);
|
||||
const integrity = computeAuditIntegritySummary(rows, verification);
|
||||
const csv = renderAuditExportCsv(rows, integrity);
|
||||
return new Response(csv, {
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": `attachment; filename="audit-export-${tenantId}-${url.searchParams.get("from") ?? "all"}_${url.searchParams.get("to") ?? "all"}.csv"`,
|
||||
"X-Audit-Chain-Status": integrity.ok ? "ok" : "broken",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function streamTenantAuditPdfExport(
|
||||
tenantId: string,
|
||||
userId: string,
|
||||
url: URL,
|
||||
t: Awaited<ReturnType<typeof getTranslations>>["t"]
|
||||
): Promise<Response> {
|
||||
const { buildAuditPdfLabels, renderAuditExportPdfResponse } = await import("~/utils/audit/pdfRender");
|
||||
const { filters, rows, verification } = await loadTenantAuditExportRows(tenantId, userId, url);
|
||||
const integrity = computeAuditIntegritySummary(rows, verification);
|
||||
return renderAuditExportPdfResponse(
|
||||
{
|
||||
tenantId,
|
||||
filters,
|
||||
integrity,
|
||||
rows,
|
||||
labels: buildAuditPdfLabels(t),
|
||||
},
|
||||
{ filenamePrefix: "audit-export" }
|
||||
);
|
||||
}
|
||||
|
||||
export default function TenantAuditExportRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return <AuditExportPage vm={data.vm} result={null} scope="tenant" tenantSlug={data.tenantSlug} embedded />;
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
// AK-P21 — AVV (data processing agreement) page. Gate: privacy.avv.read;
|
||||
// accepting additionally requires privacy.avv.accept. The current contract
|
||||
// version is configuration (AVV_CURRENT_VERSION, default 1.0); the PDF
|
||||
// download stays interim-disabled until an AVV source PDF ships (tracked in
|
||||
// the ticket doc as open follow-up).
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { useEffect } from "react";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useActionData, useLoaderData, useNavigation, useParams, useRevalidator, useSubmit } from "react-router";
|
||||
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { acceptAvv, listAvvAcceptances } from "@hivegrid/db/privacy-gdpr.server";
|
||||
import { buildAvvVM, type AvvVM } from "@hivegrid/view-models";
|
||||
|
||||
import { AvvPage } from "~/components/screens/privacy/AvvPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
|
||||
const CURRENT_AVV_VERSION = process.env.AVV_CURRENT_VERSION?.trim() || "1.0";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: AvvVM;
|
||||
};
|
||||
|
||||
type ActionData = { ok: true; message: string } | { ok: false; error: string };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "privacy.avv.read", tenantId);
|
||||
|
||||
const acceptances = await listAvvAcceptances({ tenantId });
|
||||
const vm = buildAvvVM({
|
||||
currentVersion: CURRENT_AVV_VERSION,
|
||||
// No AVV source PDF ships in the repo yet — download stays interim-disabled.
|
||||
pdfAvailable: false,
|
||||
acceptances: acceptances.map((acceptance) => ({
|
||||
id: acceptance.id,
|
||||
avvVersion: acceptance.avvVersion,
|
||||
signerName: acceptance.signerName,
|
||||
signerRole: acceptance.signerRole,
|
||||
pdfFileId: acceptance.pdfFileId,
|
||||
createdAt: acceptance.createdAt.toISOString(),
|
||||
})),
|
||||
});
|
||||
|
||||
const data: LoaderData = { title: `${t("settings.privacy.avv.title")} | ${process.env.APP_NAME}`, vm };
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "privacy.avv.accept", tenantId);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
const signerName = String(form.get("signerName") ?? "").trim();
|
||||
const signerRole = String(form.get("signerRole") ?? "").trim();
|
||||
|
||||
if (intent !== "accept" || !signerName) {
|
||||
return Response.json({ ok: false, error: t("settings.privacy.errors.unknownIntent", { intent }) } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
const acceptance = await acceptAvv({
|
||||
tenantId,
|
||||
acceptedByUserId: userInfo.userId,
|
||||
avvVersion: CURRENT_AVV_VERSION,
|
||||
signerName,
|
||||
signerRole: signerRole || null,
|
||||
acceptedIp: getTrustedClientIpOrNull(request),
|
||||
acceptedUserAgent: request.headers.get("user-agent"),
|
||||
});
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "user",
|
||||
action: "ACCEPT_AVV",
|
||||
targetType: "Tenant",
|
||||
targetId: tenantId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId: randomUUID(), avvVersion: CURRENT_AVV_VERSION, acceptanceId: acceptance.id, source: "privacy-avv-page" },
|
||||
});
|
||||
return Response.json({ ok: true, message: t("settings.privacy.avv.messages.accepted", { version: CURRENT_AVV_VERSION }) } satisfies ActionData);
|
||||
};
|
||||
|
||||
export default function PrivacyAvvRoute() {
|
||||
// AK-P21 DoD B9 — breadcrumb target injected into the screen so the screen
|
||||
// itself stays free of router data access.
|
||||
const routeParams = useParams();
|
||||
const hubHref = appPath({ tenantSlug: routeParams.tenant ?? "", path: "settings/compliance", mode: "host-aware" });
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const revalidator = useRevalidator();
|
||||
const navigation = useNavigation();
|
||||
const { csrf } = useRootData();
|
||||
|
||||
useEffect(() => {
|
||||
if (!actionData) return;
|
||||
if (actionData.ok) toast.success(actionData.message);
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<AvvPage
|
||||
embedded
|
||||
hubHref={hubHref}
|
||||
vm={vm}
|
||||
submitting={navigation.state === "submitting"}
|
||||
errorKey={actionData && !actionData.ok ? actionData.error : null}
|
||||
actions={{
|
||||
onAccept(fields) {
|
||||
const form = new FormData();
|
||||
form.set("intent", "accept");
|
||||
form.set("csrf", csrf ?? "");
|
||||
form.set("signerName", fields.signerName);
|
||||
form.set("signerRole", fields.signerRole);
|
||||
void submit(form, { method: "post" });
|
||||
},
|
||||
onRetry() {
|
||||
revalidator.revalidate();
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loadChatContext: vi.fn(),
|
||||
readSession: vi.fn(),
|
||||
loadChannel: vi.fn(),
|
||||
archiveChannel: vi.fn(),
|
||||
setMemberRole: vi.fn(),
|
||||
removeMember: vi.fn(),
|
||||
validateCsrf: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
|
||||
vi.mock("~/modules/chat/routes/chatAccess.server", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("~/modules/chat/routes/chatAccess.server")>();
|
||||
return { ...actual, loadChatContext: mocks.loadChatContext };
|
||||
});
|
||||
vi.mock("~/modules/chat/services/chatAuditSession.server", () => ({ readChatAuditSession: mocks.readSession }));
|
||||
vi.mock("~/modules/chat/services/ChatAuditService.server", () => ({
|
||||
loadChatAuditChannel: mocks.loadChannel,
|
||||
archiveChatAuditChannel: mocks.archiveChannel,
|
||||
setChatAuditMemberRole: mocks.setMemberRole,
|
||||
removeChatAuditMember: mocks.removeMember,
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCsrf }));
|
||||
vi.mock("~/components/screens/chat/ChatAuditAdministrationPanel", () => ({ ChatAuditAdministrationPanel: () => null }));
|
||||
vi.mock("~/components/screens/chat/ChatChannelDetailPage", () => ({ ChatChannelDetailPage: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
|
||||
import { action, loader } from "./chat.$id";
|
||||
|
||||
const context = {
|
||||
tenantId: "tenant-1",
|
||||
userId: "admin-1",
|
||||
tenantUserId: "tenant-user-1",
|
||||
permissions: ["chat.read_all_channels"],
|
||||
hasModule: true as const,
|
||||
};
|
||||
const session = {
|
||||
id: "session-1",
|
||||
tenantId: "tenant-1",
|
||||
userId: "admin-1",
|
||||
reason: "Supportfall",
|
||||
issuedAt: 1,
|
||||
expiresAt: 2,
|
||||
};
|
||||
|
||||
describe("AK-P15b chat audit detail route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.loadChatContext.mockResolvedValue(context);
|
||||
mocks.readSession.mockResolvedValue(session);
|
||||
mocks.loadChannel.mockResolvedValue({
|
||||
vm: { status: "ready", data: { header: { title: "Anna · Ben" } } },
|
||||
administrationVm: { status: "ready", data: { channel: { id: "dm-1" }, canAdminister: true, members: [] } },
|
||||
authors: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fails closed with 404 when the reason session is absent or expired", async () => {
|
||||
mocks.readSession.mockResolvedValueOnce(null);
|
||||
await expect(loader(args())).rejects.toMatchObject({ status: 404 });
|
||||
expect(mocks.loadChannel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("opens the channel through the audited read-only service", async () => {
|
||||
const response = await loader(args());
|
||||
expect(mocks.loadChannel).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
context,
|
||||
tenantSlug: "demo",
|
||||
chatId: "dm-1",
|
||||
session,
|
||||
requestId: expect.any(String),
|
||||
})
|
||||
);
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it("requires the active reason session and CSRF before force-member and cleanup actions", async () => {
|
||||
const roleResponse = await action(args(post({ intent: "set-role", memberUserId: "member-a", roleInChat: "admin" })));
|
||||
expect(mocks.validateCsrf).toHaveBeenCalledOnce();
|
||||
expect(mocks.setMemberRole).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ context, chatId: "dm-1", memberUserId: "member-a", roleInChat: "admin", session })
|
||||
);
|
||||
expect(roleResponse.status).toBe(302);
|
||||
|
||||
await action(args(post({ intent: "remove-member", memberUserId: "member-a" })));
|
||||
expect(mocks.removeMember).toHaveBeenCalledWith(expect.objectContaining({ chatId: "dm-1", memberUserId: "member-a", session }));
|
||||
|
||||
await action(args(post({ intent: "archive" })));
|
||||
expect(mocks.archiveChannel).toHaveBeenCalledWith(expect.objectContaining({ chatId: "dm-1", session }));
|
||||
|
||||
mocks.readSession.mockResolvedValueOnce(null);
|
||||
await expect(
|
||||
action(args(post({ intent: "archive" })))
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
});
|
||||
|
||||
function args(request = new Request("http://app.localhost/demo/settings/compliance/chat/dm-1")) {
|
||||
return {
|
||||
request,
|
||||
params: { tenant: "demo", id: "dm-1" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/settings/compliance/chat.$id",
|
||||
};
|
||||
}
|
||||
|
||||
function post(values: Record<string, string>): Request {
|
||||
return new Request("http://app.localhost/demo/settings/compliance/chat/dm-1", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(values),
|
||||
});
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
import {
|
||||
type ActionFunctionArgs,
|
||||
type LoaderFunctionArgs,
|
||||
type MetaFunction,
|
||||
redirect,
|
||||
useActionData,
|
||||
useLoaderData,
|
||||
useNavigate,
|
||||
useNavigation,
|
||||
useSubmit,
|
||||
} from "react-router";
|
||||
import type { ChatAuditAdministrationVM, ChatChannelDetailVM, ChatResolvedAuthorVM } from "@hivegrid/view-models";
|
||||
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
|
||||
import { ChatAuditAdministrationPanel } from "~/components/screens/chat/ChatAuditAdministrationPanel";
|
||||
import { ChatChannelDetailPage } from "~/components/screens/chat/ChatChannelDetailPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadChatContext, requireChatPermission } from "~/modules/chat/routes/chatAccess.server";
|
||||
import { CHAT_MODULE_KEY, chatAuditPath } from "~/modules/chat/routes/chatRoutePaths";
|
||||
import { archiveChatAuditChannel, loadChatAuditChannel, removeChatAuditMember, setChatAuditMemberRole } from "~/modules/chat/services/ChatAuditService.server";
|
||||
import { readChatAuditSession } from "~/modules/chat/services/chatAuditSession.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = Readonly<{
|
||||
title: string;
|
||||
tenantSlug: string;
|
||||
chatId: string;
|
||||
vm: ChatChannelDetailVM;
|
||||
administrationVm: ChatAuditAdministrationVM;
|
||||
authors: readonly ChatResolvedAuthorVM[];
|
||||
}>;
|
||||
|
||||
type ActionData = Readonly<{ errorKey: string }>;
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const [{ t }, loadedContext] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]);
|
||||
const context = requireChatPermission(loadedContext, CHAT_PERMISSIONS.readAllChannels);
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const chatId = params.id?.trim() ?? "";
|
||||
if (!chatId) throw new CatalogError(foundationErrors.notFound);
|
||||
const session = await readChatAuditSession({ request, tenantId: context.tenantId, userId: context.userId });
|
||||
if (!session) throw new CatalogError(foundationErrors.notFound, { chat: "audit-session-required" });
|
||||
const beforeMessageCursor = new URL(request.url).searchParams.get("before");
|
||||
|
||||
const result = await loadChatAuditChannel({
|
||||
context,
|
||||
tenantSlug,
|
||||
chatId,
|
||||
session,
|
||||
requestId: crypto.randomUUID(),
|
||||
...(beforeMessageCursor ? { beforeMessageCursor } : {}),
|
||||
labels: {
|
||||
directMessage: t("chat.channel.fallback.directMessage"),
|
||||
unnamedGroup: t("chat.channel.fallback.group"),
|
||||
unnamedProject: t("chat.channel.fallback.project"),
|
||||
unknownUser: t("chat.participant.unknown"),
|
||||
unknownMention: t("chat.mention.unknown"),
|
||||
},
|
||||
});
|
||||
const channelTitle = result.vm.status === "ready" ? result.vm.data.header.title : t("chat.titleFallback");
|
||||
return Response.json({
|
||||
title: `${channelTitle} | ${process.env.APP_NAME}`,
|
||||
tenantSlug,
|
||||
chatId,
|
||||
...result,
|
||||
} satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
|
||||
const loadedContext = await loadChatContext({ request, params });
|
||||
const context = requireChatPermission(loadedContext, CHAT_PERMISSIONS.readAllChannels);
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const chatId = params.id?.trim() ?? "";
|
||||
if (!chatId) throw new CatalogError(foundationErrors.notFound);
|
||||
const session = await readChatAuditSession({ request, tenantId: context.tenantId, userId: context.userId });
|
||||
if (!session) throw new CatalogError(foundationErrors.notFound, { chat: "audit-session-required" });
|
||||
const formData = await request.formData();
|
||||
await validateCSRFToken(request, { formData });
|
||||
const intent = formData.get("intent")?.toString();
|
||||
const requestId = crypto.randomUUID();
|
||||
let messageKey: string;
|
||||
|
||||
if (intent === "archive") {
|
||||
await archiveChatAuditChannel({ context, chatId, session, requestId });
|
||||
messageKey = "chat.audit.toast.channelArchived";
|
||||
} else if (intent === "set-role") {
|
||||
const memberUserId = formData.get("memberUserId")?.toString().trim() ?? "";
|
||||
const roleInChat = formData.get("roleInChat")?.toString();
|
||||
if (!memberUserId || (roleInChat !== "admin" && roleInChat !== "member")) return invalidInput();
|
||||
await setChatAuditMemberRole({ context, chatId, memberUserId, roleInChat, session, requestId });
|
||||
messageKey = "chat.audit.toast.memberRoleChanged";
|
||||
} else if (intent === "remove-member") {
|
||||
const memberUserId = formData.get("memberUserId")?.toString().trim() ?? "";
|
||||
if (!memberUserId) return invalidInput();
|
||||
await removeChatAuditMember({ context, chatId, memberUserId, session, requestId });
|
||||
messageKey = "chat.audit.toast.memberRemoved";
|
||||
} else {
|
||||
return invalidInput();
|
||||
}
|
||||
|
||||
return redirect(`${chatAuditPath(tenantSlug)}/${encodeURIComponent(chatId)}?toast=${encodeURIComponent(messageKey)}`);
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
||||
|
||||
export default function ChatAuditChannelRoute(): React.JSX.Element {
|
||||
const { tenantSlug, chatId, vm, administrationVm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const { csrf } = useRootData();
|
||||
const noOp = () => undefined;
|
||||
const busy = navigation.state === "submitting";
|
||||
|
||||
function submitAction(intent: "archive" | "set-role" | "remove-member", values?: Record<string, string>): void {
|
||||
const formData = new FormData();
|
||||
formData.set("csrf", csrf ?? "");
|
||||
formData.set("intent", intent);
|
||||
for (const [key, value] of Object.entries(values ?? {})) formData.set(key, value);
|
||||
void submit(formData, { method: "post" });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col">
|
||||
<ChatAuditAdministrationPanel
|
||||
vm={administrationVm}
|
||||
busy={busy}
|
||||
actionErrorKey={actionData?.errorKey}
|
||||
actions={{
|
||||
onArchive: () => submitAction("archive"),
|
||||
onChangeMemberRole: (memberUserId, roleInChat) => submitAction("set-role", { memberUserId, roleInChat }),
|
||||
onRemoveMember: (memberUserId) => submitAction("remove-member", { memberUserId }),
|
||||
}}
|
||||
/>
|
||||
<ChatChannelDetailPage
|
||||
vm={vm}
|
||||
draft=""
|
||||
sending={false}
|
||||
actions={{
|
||||
onBack: () => void navigate(chatAuditPath(tenantSlug)),
|
||||
onOpenSettings: noOp,
|
||||
onDraftChange: noOp,
|
||||
onSend: noOp,
|
||||
onRetryMessage: noOp,
|
||||
onDiscardMessage: noOp,
|
||||
onMessageVisibilityChange: noOp,
|
||||
onRetryConnection: noOp,
|
||||
onLoadOlder: (cursor) => void navigate(`${chatAuditPath(tenantSlug)}/${encodeURIComponent(chatId)}?before=${encodeURIComponent(cursor)}`),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function invalidInput(): Response {
|
||||
return Response.json({ errorKey: "chat.errors.invalidInput" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
export function ErrorBoundary(): React.JSX.Element {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = {
|
||||
moduleKey: CHAT_MODULE_KEY,
|
||||
breadcrumbKey: "chat.audit.channelTitle",
|
||||
};
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loadChatContext: vi.fn(),
|
||||
loadOverview: vi.fn(),
|
||||
startSession: vi.fn(),
|
||||
archiveChannel: vi.fn(),
|
||||
readSession: vi.fn(),
|
||||
beginSession: vi.fn(),
|
||||
clearSession: vi.fn(),
|
||||
validateCSRF: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
|
||||
vi.mock("~/modules/chat/routes/chatAccess.server", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("~/modules/chat/routes/chatAccess.server")>();
|
||||
return { ...actual, loadChatContext: mocks.loadChatContext };
|
||||
});
|
||||
vi.mock("~/modules/chat/services/ChatAuditService.server", () => ({
|
||||
loadChatAuditOverview: mocks.loadOverview,
|
||||
startChatAuditSession: mocks.startSession,
|
||||
archiveChatAuditChannel: mocks.archiveChannel,
|
||||
}));
|
||||
vi.mock("~/modules/chat/services/chatAuditSession.server", () => ({
|
||||
readChatAuditSession: mocks.readSession,
|
||||
beginChatAuditSession: mocks.beginSession,
|
||||
clearChatAuditSession: mocks.clearSession,
|
||||
normalizeChatAuditReason: (value: unknown) => (typeof value === "string" && value.trim() ? value.trim() : null),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCSRF }));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf-1" }) }));
|
||||
vi.mock("~/components/screens/chat/ChatAuditOverviewPage", () => ({ ChatAuditOverviewPage: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
|
||||
import { action, loader } from "./chat";
|
||||
|
||||
const context = {
|
||||
tenantId: "tenant-1",
|
||||
userId: "admin-1",
|
||||
tenantUserId: "tenant-user-1",
|
||||
permissions: ["chat.read_all_channels"],
|
||||
hasModule: true as const,
|
||||
};
|
||||
const auditSession = {
|
||||
id: "session-1",
|
||||
tenantId: "tenant-1",
|
||||
userId: "admin-1",
|
||||
reason: "Kundenreklamation prüfen",
|
||||
issuedAt: Date.parse("2026-07-16T10:00:00.000Z"),
|
||||
expiresAt: Date.parse("2026-07-16T10:15:00.000Z"),
|
||||
};
|
||||
|
||||
describe("AK-P15b chat audit overview route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.loadChatContext.mockResolvedValue(context);
|
||||
mocks.readSession.mockResolvedValue(null);
|
||||
mocks.loadOverview.mockResolvedValue({ status: "ready", data: { session: null, channels: [] } });
|
||||
mocks.beginSession.mockResolvedValue({ session: auditSession, cookie: "hivegrid_chat_audit=signed; Path=/; HttpOnly" });
|
||||
mocks.clearSession.mockResolvedValue("hivegrid_chat_audit=; Max-Age=0");
|
||||
});
|
||||
|
||||
it("returns a 404-equivalent CatalogError without read_all_channels", async () => {
|
||||
mocks.loadChatContext.mockResolvedValueOnce({ ...context, permissions: ["chat.admin"] });
|
||||
await expect(loader(args(new Request("http://app.localhost/demo/settings/compliance/chat")))).rejects.toMatchObject({ status: 404 });
|
||||
expect(mocks.loadOverview).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not expose channels before a signed reason session exists", async () => {
|
||||
const response = await loader(args(new Request("http://app.localhost/demo/settings/compliance/chat")));
|
||||
expect(mocks.readSession).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant-1", userId: "admin-1" }));
|
||||
expect(mocks.loadOverview).toHaveBeenCalledWith(expect.objectContaining({ context, session: null }));
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it("rejects a missing justification after CSRF validation", async () => {
|
||||
const request = post({ intent: "start", reason: " ", csrf: "csrf-1" });
|
||||
const response = await action(args(request));
|
||||
expect(mocks.validateCSRF).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.validateCSRF.mock.calls[0]?.[0]).toBe(request);
|
||||
expect(mocks.validateCSRF.mock.calls[0]?.[1]).toHaveProperty("formData");
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ errorKey: "chat.audit.errors.reasonRequired" });
|
||||
expect(mocks.beginSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("audits the reason before issuing the short-lived session cookie", async () => {
|
||||
const response = await action(args(post({ intent: "start", reason: "Kundenreklamation prüfen", csrf: "csrf-1" })));
|
||||
expect(mocks.beginSession).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: "admin-1", reason: "Kundenreklamation prüfen" });
|
||||
expect(mocks.startSession).toHaveBeenCalledWith({ context, session: auditSession, requestId: expect.any(String) });
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("set-cookie")).toContain("hivegrid_chat_audit=signed");
|
||||
});
|
||||
|
||||
it("requires the signed reason session before an overview cleanup archive", async () => {
|
||||
const adminContext = { ...context, permissions: ["chat.read_own_channels", "chat.read_all_channels", "chat.admin"] };
|
||||
mocks.loadChatContext.mockResolvedValue(adminContext);
|
||||
mocks.readSession.mockResolvedValue(auditSession);
|
||||
const response = await action(args(post({ intent: "archive", chatId: "group-a", csrf: "csrf-1" })));
|
||||
expect(mocks.archiveChannel).toHaveBeenCalledWith({
|
||||
context: adminContext,
|
||||
chatId: "group-a",
|
||||
session: auditSession,
|
||||
requestId: expect.any(String),
|
||||
});
|
||||
expect(response.status).toBe(302);
|
||||
|
||||
mocks.readSession.mockResolvedValueOnce(null);
|
||||
await expect(action(args(post({ intent: "archive", chatId: "group-a", csrf: "csrf-1" })))).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
});
|
||||
|
||||
function args(request: Request) {
|
||||
return {
|
||||
request,
|
||||
params: { tenant: "demo" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/settings/compliance/chat",
|
||||
};
|
||||
}
|
||||
|
||||
function post(values: Record<string, string>): Request {
|
||||
return new Request("http://app.localhost/demo/settings/compliance/chat", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(values),
|
||||
});
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import {
|
||||
type ActionFunctionArgs,
|
||||
type LoaderFunctionArgs,
|
||||
type MetaFunction,
|
||||
redirect,
|
||||
useActionData,
|
||||
useLoaderData,
|
||||
useNavigate,
|
||||
useNavigation,
|
||||
useSubmit,
|
||||
} from "react-router";
|
||||
import type { ChatAuditOverviewVM } from "@hivegrid/view-models";
|
||||
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
|
||||
import { ChatAuditOverviewPage } from "~/components/screens/chat/ChatAuditOverviewPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadChatContext, requireChatPermission } from "~/modules/chat/routes/chatAccess.server";
|
||||
import { CHAT_MODULE_KEY, chatAuditPath } from "~/modules/chat/routes/chatRoutePaths";
|
||||
import { archiveChatAuditChannel, loadChatAuditOverview, startChatAuditSession } from "~/modules/chat/services/ChatAuditService.server";
|
||||
import { beginChatAuditSession, clearChatAuditSession, normalizeChatAuditReason, readChatAuditSession } from "~/modules/chat/services/chatAuditSession.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = Readonly<{
|
||||
title: string;
|
||||
tenantSlug: string;
|
||||
vm: ChatAuditOverviewVM;
|
||||
}>;
|
||||
|
||||
type ActionData = Readonly<{ errorKey: string }>;
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const [{ t }, loadedContext] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]);
|
||||
const context = requireChatPermission(loadedContext, CHAT_PERMISSIONS.readAllChannels);
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const session = await readChatAuditSession({ request, tenantId: context.tenantId, userId: context.userId });
|
||||
const vm = await loadChatAuditOverview({
|
||||
context,
|
||||
tenantSlug,
|
||||
session,
|
||||
requestId: crypto.randomUUID(),
|
||||
labels: {
|
||||
directMessage: t("chat.channel.fallback.directMessage"),
|
||||
unnamedGroup: t("chat.channel.fallback.group"),
|
||||
unnamedProject: t("chat.channel.fallback.project"),
|
||||
},
|
||||
});
|
||||
return Response.json({ title: `${t("chat.audit.title")} | ${process.env.APP_NAME}`, tenantSlug, vm } satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
|
||||
const loadedContext = await loadChatContext({ request, params });
|
||||
const context = requireChatPermission(loadedContext, CHAT_PERMISSIONS.readAllChannels);
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const formData = await request.formData();
|
||||
await validateCSRFToken(request, { formData });
|
||||
const intent = formData.get("intent")?.toString();
|
||||
|
||||
if (intent === "end") {
|
||||
return redirect(`${chatAuditPath(tenantSlug)}?toast=${encodeURIComponent("chat.audit.toast.sessionEnded")}`, {
|
||||
headers: { "Set-Cookie": await clearChatAuditSession() },
|
||||
});
|
||||
}
|
||||
if (intent === "archive") {
|
||||
const session = await readChatAuditSession({ request, tenantId: context.tenantId, userId: context.userId });
|
||||
if (!session) throw new CatalogError(foundationErrors.notFound, { chat: "audit-session-required" });
|
||||
const chatId = formData.get("chatId")?.toString().trim() ?? "";
|
||||
if (!chatId) return invalidInput("chat.errors.invalidInput");
|
||||
await archiveChatAuditChannel({ context, chatId, session, requestId: crypto.randomUUID() });
|
||||
return redirect(`${chatAuditPath(tenantSlug)}?toast=${encodeURIComponent("chat.audit.toast.channelArchived")}`);
|
||||
}
|
||||
if (intent !== "start") return invalidInput("chat.errors.invalidInput");
|
||||
|
||||
const reason = normalizeChatAuditReason(formData.get("reason"));
|
||||
if (!reason) return invalidInput("chat.audit.errors.reasonRequired");
|
||||
const issued = await beginChatAuditSession({ tenantId: context.tenantId, userId: context.userId, reason });
|
||||
await startChatAuditSession({ context, session: issued.session, requestId: crypto.randomUUID() });
|
||||
return redirect(`${chatAuditPath(tenantSlug)}?toast=${encodeURIComponent("chat.audit.toast.sessionStarted")}`, { headers: { "Set-Cookie": issued.cookie } });
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
||||
|
||||
export default function ChatAuditOverviewRoute(): React.JSX.Element {
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const navigate = useNavigate();
|
||||
const { csrf } = useRootData();
|
||||
const busy = navigation.state === "submitting";
|
||||
|
||||
function submitIntent(intent: "start" | "end" | "archive", options?: { reason?: string; chatId?: string }): void {
|
||||
const formData = new FormData();
|
||||
formData.set("csrf", csrf ?? "");
|
||||
formData.set("intent", intent);
|
||||
if (options?.reason !== undefined) formData.set("reason", options.reason);
|
||||
if (options?.chatId !== undefined) formData.set("chatId", options.chatId);
|
||||
void submit(formData, { method: "post" });
|
||||
}
|
||||
|
||||
return (
|
||||
<ChatAuditOverviewPage
|
||||
embedded
|
||||
vm={vm}
|
||||
busy={busy}
|
||||
actionErrorKey={actionData?.errorKey}
|
||||
actions={{
|
||||
onStartSession: (reason) => submitIntent("start", { reason }),
|
||||
onEndSession: () => submitIntent("end"),
|
||||
onOpenChannel: (href) => void navigate(href),
|
||||
onArchiveChannel: (chatId) => submitIntent("archive", { chatId }),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function invalidInput(errorKey: string): Response {
|
||||
return Response.json({ errorKey } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
export function ErrorBoundary(): React.JSX.Element {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = {
|
||||
moduleKey: CHAT_MODULE_KEY,
|
||||
breadcrumbKey: "chat.audit.title",
|
||||
};
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
// AK-P21 — GDPR export job list (tenant admins see all tenant jobs and may
|
||||
// start the tenant-full export; every user may start their own self export
|
||||
// within the 3/24h rate limit). The download button targets the signed-URL
|
||||
// resource route privacy.export.$jobId.download.
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { useEffect } from "react";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useActionData, useLoaderData, useLocation, useNavigation, useParams, useRevalidator, useSubmit } from "react-router";
|
||||
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
import {
|
||||
createGdprExportJob,
|
||||
GDPR_EXPORT_URL_TTL_HOURS,
|
||||
GDPR_USER_SELF_EXPORT_LIMIT_PER_24H,
|
||||
listGdprExportJobs,
|
||||
} from "@hivegrid/db/privacy-gdpr.server";
|
||||
import { buildGdprExportJobsVM, type GdprExportJobsVM } from "@hivegrid/view-models";
|
||||
|
||||
import { GdprExportJobsPage } from "~/components/screens/privacy/GdprExportJobsPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { enqueueGdprExport } from "~/utils/privacy/gdprExportQueue.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import type { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: GdprExportJobsVM;
|
||||
};
|
||||
|
||||
type ActionData = { ok: true; message: string } | { ok: false; error: string };
|
||||
|
||||
async function hasPermission(request: Request, permission: DefaultPermission, tenantId: string): Promise<boolean> {
|
||||
try {
|
||||
await verifyUserHasPermission(request, permission, tenantId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof Response && ((error.status >= 300 && error.status < 400) || error.status === 403 || error.status === 404)) return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const db = getDbClient();
|
||||
|
||||
const tenantExportAllowed = await hasPermission(request, "privacy.tenant_export", tenantId);
|
||||
const now = new Date();
|
||||
const [jobs, userSelfCountLast24h, tenantFullActiveCount] = await Promise.all([
|
||||
// Tenant admins see the whole tenant register; everyone else only their own jobs.
|
||||
listGdprExportJobs(tenantExportAllowed ? { tenantId, take: 50 } : { tenantId, requestedByUserId: userInfo.userId, take: 50 }),
|
||||
db.gdprExportJob.count({
|
||||
where: { tenantId, scope: "user_self", targetUserId: userInfo.userId, createdAt: { gte: new Date(now.getTime() - 24 * 60 * 60 * 1_000) } },
|
||||
}),
|
||||
db.gdprExportJob.count({ where: { tenantId, scope: "tenant_full", status: { in: ["queued", "processing"] } } }),
|
||||
]);
|
||||
|
||||
const vm = buildGdprExportJobsVM({
|
||||
now: now.toISOString(),
|
||||
jobs: jobs.map((job) => ({
|
||||
id: job.id,
|
||||
scope: job.scope,
|
||||
status: job.status,
|
||||
progressPercent: job.progressPercent,
|
||||
resultSizeBytes: job.resultSizeBytes,
|
||||
resultExpiresAt: job.resultExpiresAt ? job.resultExpiresAt.toISOString() : null,
|
||||
downloadCount: job.downloadCount,
|
||||
createdAt: job.createdAt.toISOString(),
|
||||
})),
|
||||
userSelfCountLast24h,
|
||||
tenantFullActive: tenantFullActiveCount > 0,
|
||||
tenantExportAllowed,
|
||||
userSelfLimitPer24h: GDPR_USER_SELF_EXPORT_LIMIT_PER_24H,
|
||||
downloadTtlHours: GDPR_EXPORT_URL_TTL_HOURS,
|
||||
});
|
||||
|
||||
const data: LoaderData = { title: `${t("settings.privacy.exportJobs.title")} | ${process.env.APP_NAME}`, vm };
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
const scope = String(form.get("scope") ?? "");
|
||||
|
||||
if (intent !== "start" || (scope !== "user_self" && scope !== "tenant_full")) {
|
||||
return Response.json({ ok: false, error: t("settings.privacy.errors.unknownIntent", { intent }) } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
if (scope === "tenant_full") {
|
||||
await verifyUserHasPermission(request, "privacy.tenant_export", tenantId);
|
||||
}
|
||||
|
||||
const requestId = randomUUID();
|
||||
try {
|
||||
const exportJob = await createGdprExportJob({
|
||||
tenantId,
|
||||
requestedByUserId: userInfo.userId,
|
||||
targetUserId: scope === "user_self" ? userInfo.userId : null,
|
||||
scope,
|
||||
});
|
||||
const enqueueResult = await enqueueGdprExport({
|
||||
exportJobId: exportJob.id,
|
||||
tenantId,
|
||||
requestedByUserId: userInfo.userId,
|
||||
targetUserId: scope === "user_self" ? userInfo.userId : null,
|
||||
scope,
|
||||
requestId,
|
||||
});
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "user",
|
||||
action: scope === "tenant_full" ? "REQUEST_TENANT_DATA_EXPORT" : "REQUEST_PERSONAL_DATA_EXPORT",
|
||||
targetType: scope === "tenant_full" ? "Tenant" : "User",
|
||||
targetId: scope === "tenant_full" ? tenantId : userInfo.userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "start", source: "privacy-export-page", scope, gdprExportJobId: exportJob.id, enqueueResult },
|
||||
});
|
||||
return Response.json({ ok: true, message: t("settings.privacy.messages.exportRequested") } satisfies ActionData);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "";
|
||||
if (message.includes("limit reached")) {
|
||||
return Response.json(
|
||||
{ ok: false, error: t("settings.privacy.exportJobs.rateLimit.description", { limit: GDPR_USER_SELF_EXPORT_LIMIT_PER_24H }) } satisfies ActionData,
|
||||
{ status: 429 }
|
||||
);
|
||||
}
|
||||
if (message.includes("already active")) {
|
||||
return Response.json({ ok: false, error: t("settings.privacy.exportJobs.tenantActive.description") } satisfies ActionData, { status: 409 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export default function PrivacyExportRoute() {
|
||||
// AK-P21 DoD B9 — breadcrumb target injected into the screen so the screen
|
||||
// itself stays free of router data access.
|
||||
const routeParams = useParams();
|
||||
const hubHref = appPath({ tenantSlug: routeParams.tenant ?? "", path: "settings/compliance", mode: "host-aware" });
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const revalidator = useRevalidator();
|
||||
const navigation = useNavigation();
|
||||
const location = useLocation();
|
||||
const { csrf } = useRootData();
|
||||
|
||||
useEffect(() => {
|
||||
if (!actionData) return;
|
||||
if (actionData.ok) toast.success(actionData.message);
|
||||
else toast.error(actionData.error);
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<GdprExportJobsPage
|
||||
embedded
|
||||
hubHref={hubHref}
|
||||
vm={vm}
|
||||
submitting={navigation.state === "submitting"}
|
||||
actions={{
|
||||
onStart(scope) {
|
||||
const form = new FormData();
|
||||
form.set("intent", "start");
|
||||
form.set("scope", scope);
|
||||
form.set("csrf", csrf ?? "");
|
||||
void submit(form, { method: "post" });
|
||||
},
|
||||
onDownload(jobId) {
|
||||
window.location.assign(`${location.pathname.replace(/\/$/, "")}/${jobId}/download`);
|
||||
},
|
||||
onRetry() {
|
||||
revalidator.revalidate();
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "../logs/events-export";
|
||||
import { getEvents, serializeEventsCsv } from "~/modules/events/db/events.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
|
||||
vi.mock("~/modules/events/db/events.db.server", () => ({
|
||||
getEvents: vi.fn(),
|
||||
serializeEventsCsv: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
const params = { tenant: "acme" };
|
||||
const events = [{ id: "event-1", name: "account.created" }];
|
||||
|
||||
function callLoader(url: string) {
|
||||
const request = new Request(url);
|
||||
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/logs/events-export" } as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
describe("tenant settings events CSV export route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getEvents).mockResolvedValue({ items: events, pagination: { page: 1, pageSize: 500, totalItems: 1, totalPages: 1 } } as never);
|
||||
vi.mocked(serializeEventsCsv).mockReturnValue("csv-body\n");
|
||||
});
|
||||
|
||||
it("exports CSV with the same tenant filters and a capped export window", async () => {
|
||||
const response = await callLoader("https://app.example.test/acme/settings/logs/events-export?q=account&name=account.created&page=9&pageSize=5");
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getEvents).mock.invocationCallOrder[0]);
|
||||
expect(getEvents).toHaveBeenCalledWith(
|
||||
{
|
||||
current: { page: 1, pageSize: 500 },
|
||||
filters: expect.objectContaining({
|
||||
query: "account",
|
||||
properties: expect.arrayContaining([expect.objectContaining({ name: "name", value: "account.created" })]),
|
||||
}),
|
||||
},
|
||||
"tenant-1",
|
||||
);
|
||||
expect(serializeEventsCsv).toHaveBeenCalledWith(events);
|
||||
expect(response.headers.get("Content-Type")).toBe("text/csv; charset=utf-8");
|
||||
expect(response.headers.get("Content-Disposition")).toBe('attachment; filename="tenant-events.csv"');
|
||||
expect(await response.text()).toBe("csv-body\n");
|
||||
});
|
||||
|
||||
it("rejects CSV reads without permission before helper calls", async () => {
|
||||
const rejection = new Response("Forbidden", { status: 403 });
|
||||
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
|
||||
|
||||
await expect(callLoader("https://app.example.test/acme/settings/logs/events-export")).rejects.toBe(rejection);
|
||||
|
||||
expect(getEvents).not.toHaveBeenCalled();
|
||||
expect(serializeEventsCsv).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "./events.$id";
|
||||
import { getEvent } from "~/modules/events/db/events.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
Link: () => null,
|
||||
useLoaderData: () => ({}),
|
||||
useParams: () => ({ tenant: "acme", id: "event-1" }),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/modules/events/components/EventDetails", () => ({ default: () => null }));
|
||||
|
||||
vi.mock("~/modules/events/db/events.db.server", () => ({
|
||||
getEvent: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
const params = { tenant: "acme", id: "event-1" };
|
||||
const event = {
|
||||
id: "event-1",
|
||||
tenantId: "tenant-1",
|
||||
userId: "user-1",
|
||||
name: "account.created",
|
||||
data: "{}",
|
||||
description: null,
|
||||
createdAt: new Date("2026-05-08T10:00:00.000Z"),
|
||||
tenant: { id: "tenant-1", name: "Acme", slug: "acme" },
|
||||
user: { id: "user-1", email: "ada@example.test" },
|
||||
};
|
||||
|
||||
function callLoader(routeParams = params) {
|
||||
const request = new Request("https://app.example.test/acme/settings/compliance/events/event-1");
|
||||
return loader({ request, params: routeParams, context: {}, unstable_pattern: "app.$tenant/settings/compliance/events.$id" } as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
describe("tenant settings event detail route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getEvent).mockResolvedValue(event as never);
|
||||
});
|
||||
|
||||
it("checks tenant-scoped audit-trail permission before reading the requested event", async () => {
|
||||
const data = await callLoader();
|
||||
|
||||
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getEvent).mock.invocationCallOrder[0]);
|
||||
expect(getEvent).toHaveBeenCalledWith("event-1", "tenant-1");
|
||||
expect(data).toEqual({ item: event });
|
||||
});
|
||||
|
||||
it("rejects event detail reads without permission before downstream helper calls", async () => {
|
||||
const rejection = new Response("Forbidden", { status: 403 });
|
||||
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
|
||||
|
||||
await expect(callLoader()).rejects.toBe(rejection);
|
||||
|
||||
expect(getEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("redirects missing events to the tenant events path after permission", async () => {
|
||||
vi.mocked(getEvent).mockResolvedValue(null as never);
|
||||
|
||||
await expect(callLoader()).rejects.toMatchObject({
|
||||
status: 302,
|
||||
headers: expect.objectContaining({}),
|
||||
});
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getEvent).mock.invocationCallOrder[0]);
|
||||
expect(getEvent).toHaveBeenCalledWith("event-1", "tenant-1");
|
||||
|
||||
try {
|
||||
await callLoader();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(Response);
|
||||
expect((error as Response).headers.get("Location")).toBe("/acme/settings/compliance/events");
|
||||
}
|
||||
});
|
||||
|
||||
it("uses an empty id after permission when the route id param is absent", async () => {
|
||||
const data = await callLoader({ tenant: "acme", id: undefined as unknown as string });
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
|
||||
expect(getEvent).toHaveBeenCalledWith("", "tenant-1");
|
||||
expect(data).toEqual({ item: event });
|
||||
});
|
||||
});
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import { LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EventDetails from "~/modules/events/components/EventDetails";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { EventWithDetails, getEvent } from "~/modules/events/db/events.db.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import EventUtils from "~/modules/events/utils/EventUtils";
|
||||
|
||||
type LoaderData = {
|
||||
item: EventWithDetails;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
|
||||
const item = await getEvent(params.id ?? "", tenantId);
|
||||
if (!item) {
|
||||
throw redirect(UrlUtils.currentTenantUrl(params, "settings/compliance/events"));
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function AppEventDetailsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.event.object")}
|
||||
withHome={false}
|
||||
menu={[
|
||||
{
|
||||
title: t("models.event.plural"),
|
||||
routePath: UrlUtils.currentTenantUrl(params, "settings/compliance/events"),
|
||||
},
|
||||
{
|
||||
title: EventUtils.parseName(data.item.name, t),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<EventDetails item={data.item} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "./events";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getEvents } from "~/modules/events/db/events.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUsersByTenant } from "~/utils/db/users.db.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
Link: () => null,
|
||||
useLoaderData: () => ({}),
|
||||
useParams: () => ({ tenant: "acme" }),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/components/ui/input/InputFilters", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/tabs/Tabs", () => ({ default: () => null }));
|
||||
vi.mock("~/modules/events/components/EventsTable", () => ({ default: () => null }));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/events/db/events.db.server", () => ({
|
||||
getEvents: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/activity/TenantActivityLogToolbar", () => ({ default: () => null }));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/users.db.server", () => ({
|
||||
getUsersByTenant: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
const params = { tenant: "acme" };
|
||||
const users = [
|
||||
{ id: "user-1", email: "ada@example.test" },
|
||||
{ id: "user-2", email: "grace@example.test" },
|
||||
];
|
||||
const events = [
|
||||
{
|
||||
id: "event-1",
|
||||
tenantId: "tenant-1",
|
||||
userId: "user-1",
|
||||
name: "account.created",
|
||||
data: "{}",
|
||||
description: null,
|
||||
createdAt: new Date("2026-05-08T10:00:00.000Z"),
|
||||
tenant: { id: "tenant-1", name: "Acme", slug: "acme" },
|
||||
user: { id: "user-1", email: "ada@example.test" },
|
||||
},
|
||||
];
|
||||
|
||||
function callLoader(url: string) {
|
||||
const request = new Request(url);
|
||||
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/compliance/events" } as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
describe("tenant settings event list route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({
|
||||
t: (key: string, values?: Record<string, string>) =>
|
||||
key === "settings.logs.events.filters.eventOption" && values
|
||||
? `formatted:${values.eventValue} -> ${values.eventLabel}`
|
||||
: `translated:${key}`,
|
||||
} as never);
|
||||
vi.mocked(getUsersByTenant).mockResolvedValue(users as never);
|
||||
vi.mocked(getEvents).mockResolvedValue({
|
||||
items: events,
|
||||
pagination: { page: 2, pageSize: 25, totalItems: 1, totalPages: 1 },
|
||||
} as never);
|
||||
});
|
||||
|
||||
it("checks tenant-scoped audit-trail permission before user and event helpers", async () => {
|
||||
const data = await callLoader(
|
||||
"https://app.example.test/acme/settings/compliance/events?q=account&name=account.created&data=secret&userId=user-1&page=2&pageSize=25",
|
||||
);
|
||||
|
||||
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getUsersByTenant).mock.invocationCallOrder[0]);
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getEvents).mock.invocationCallOrder[0]);
|
||||
expect(getUsersByTenant).toHaveBeenCalledWith("tenant-1");
|
||||
expect(getEvents).toHaveBeenCalledWith(
|
||||
{
|
||||
current: expect.objectContaining({ page: 2, pageSize: 25 }),
|
||||
filters: expect.objectContaining({
|
||||
query: "account",
|
||||
properties: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "name", value: "account.created" }),
|
||||
expect.objectContaining({ name: "data", value: "secret" }),
|
||||
expect.objectContaining({ name: "userId", value: "user-1" }),
|
||||
]),
|
||||
}),
|
||||
},
|
||||
"tenant-1",
|
||||
);
|
||||
expect(data).toMatchObject({
|
||||
title: "translated:models.event.plural | HiveGrid",
|
||||
items: events,
|
||||
pagination: { page: 2, pageSize: 25, totalItems: 1, totalPages: 1 },
|
||||
});
|
||||
expect(data.filterableProperties).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "name",
|
||||
options: expect.arrayContaining([expect.objectContaining({ value: "account.created", name: "formatted:account.created -> translated:events.names.account_created" })]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects event list reads without permission before downstream helper calls", async () => {
|
||||
const rejection = new Response("Forbidden", { status: 403 });
|
||||
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
|
||||
|
||||
await expect(callLoader("https://app.example.test/acme/settings/compliance/events?name=account.created")).rejects.toBe(rejection);
|
||||
|
||||
expect(getUsersByTenant).not.toHaveBeenCalled();
|
||||
expect(getEvents).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { ApplicationEvents, getApplicationEventNameKey } from "~/modules/events/types/ApplicationEvent";
|
||||
import EventsTable from "~/modules/events/components/EventsTable";
|
||||
import TenantActivityLogToolbar from "~/components/activity/TenantActivityLogToolbar";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { PageIntro } from "~/components/screens/shared/PageShell";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { EventWithAttempts, getEvents } from "~/modules/events/db/events.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUsersByTenant } from "~/utils/db/users.db.server";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: EventWithAttempts[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const current = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "name",
|
||||
title: "settings.logs.events.filters.event",
|
||||
options: ApplicationEvents.filter((f) => !f.adminOnly || !params.tenant).map((item) => {
|
||||
return {
|
||||
value: item.value,
|
||||
name: t("settings.logs.events.filters.eventOption", { eventValue: item.value, eventLabel: t(getApplicationEventNameKey(item.value)) }),
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "data",
|
||||
title: "settings.logs.events.filters.data",
|
||||
},
|
||||
{
|
||||
name: "userId",
|
||||
title: "models.user.object",
|
||||
options: (await getUsersByTenant(tenantId)).map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.email,
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const { items, pagination } = await getEvents({ current, filters }, tenantId);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.event.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
pagination,
|
||||
filterableProperties,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function AppEventsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout fullWidth>
|
||||
{/* AK-SET-01: the Compliance hub owns the page header. */}
|
||||
<PageIntro uiId="ui.settings.logs.intro">{t("settings.logs.subtitle")}</PageIntro>
|
||||
<div data-ui-id="ui.settings.logs.events.page" className="space-y-2">
|
||||
<div className="flex justify-between gap-2">
|
||||
<div data-ui-id="ui.settings.logs.tabs" className="grow">
|
||||
<Tabs
|
||||
tabs={[
|
||||
{
|
||||
name: t("models.log.plural"),
|
||||
routePath: UrlUtils.currentTenantUrl(params, "settings/compliance"),
|
||||
},
|
||||
{
|
||||
name: t("models.event.plural"),
|
||||
routePath: UrlUtils.currentTenantUrl(params, "settings/compliance/events"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div data-ui-id="ui.settings.logs.filters">
|
||||
<TenantActivityLogToolbar filters={data.filterableProperties} exportTo={UrlUtils.currentTenantUrl(params, "settings/logs/events-export")} />
|
||||
</div>
|
||||
</div>
|
||||
<div data-ui-id="ui.settings.logs.events.table">
|
||||
<EventsTable items={data.items} pagination={data.pagination} />
|
||||
</div>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "./index";
|
||||
import { getTenantAuditLogList } from "@hivegrid/db/logs.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
Link: () => null,
|
||||
useLoaderData: () => ({}),
|
||||
useParams: () => ({ tenant: "acme" }),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/components/activity/TenantActivityLogToolbar", () => ({ default: () => null }));
|
||||
vi.mock("~/components/app/events/LogsTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/tabs/Tabs", () => ({ default: () => null }));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/logs.server", () => ({
|
||||
getTenantAuditLogList: vi.fn(),
|
||||
}));
|
||||
|
||||
const params = { tenant: "acme" };
|
||||
const auditRows = [
|
||||
{
|
||||
id: "log-1",
|
||||
createdAt: new Date("2026-05-08T10:00:00.000Z"),
|
||||
tenantId: "tenant-1",
|
||||
userId: "user-1",
|
||||
apiKeyId: null,
|
||||
action: "create",
|
||||
url: "/acme/contacts",
|
||||
details: "redacted details",
|
||||
rowId: null,
|
||||
commentId: null,
|
||||
tenant: { id: "tenant-1", name: "Acme", slug: "acme" },
|
||||
user: { id: "user-1", email: "admin@example.test", firstName: "Ada", lastName: "Admin" },
|
||||
apiKey: null,
|
||||
comment: null,
|
||||
},
|
||||
];
|
||||
|
||||
function callLoader(url: string) {
|
||||
const request = new Request(url);
|
||||
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/compliance" } as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
function readTenantLogsRoute() {
|
||||
return readRepoFile("apps/web/app/routes/app.$tenant/settings/compliance/index.tsx");
|
||||
}
|
||||
|
||||
describe("tenant settings logs route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
vi.mocked(getTenantAuditLogList).mockResolvedValue({ rows: auditRows, total: 1, take: 25, skip: 25 } as never);
|
||||
});
|
||||
|
||||
it("checks permission before reading the tenant-scoped filtered table data", async () => {
|
||||
const data = await callLoader(
|
||||
"https://app.example.test/acme/settings/compliance?q=contact&action=create&url=%2Fcontacts&tenantId=other-tenant&userId=user-1&createdAtFrom=2026-05-01&createdAtTo=2026-05-08&page=2&pageSize=25",
|
||||
);
|
||||
|
||||
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getTenantAuditLogList).mock.invocationCallOrder[0]);
|
||||
expect(getTenantAuditLogList).toHaveBeenCalledWith("tenant-1", {
|
||||
q: "contact",
|
||||
action: "create",
|
||||
url: "/contacts",
|
||||
userId: "user-1",
|
||||
createdAtFrom: "2026-05-01",
|
||||
createdAtTo: "2026-05-08",
|
||||
take: 25,
|
||||
skip: 25,
|
||||
});
|
||||
expect(JSON.stringify(vi.mocked(getTenantAuditLogList).mock.calls[0]?.[1])).not.toContain("other-tenant");
|
||||
expect(data).toMatchObject({
|
||||
title: "translated:models.log.plural | HiveGrid",
|
||||
items: auditRows,
|
||||
pagination: { page: 2, pageSize: 25, totalItems: 1, totalPages: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects table reads without permission before helper calls", async () => {
|
||||
const rejection = new Response("Forbidden", { status: 403 });
|
||||
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
|
||||
|
||||
await expect(callLoader("https://app.example.test/acme/settings/compliance")).rejects.toBe(rejection);
|
||||
|
||||
expect(getTenantAuditLogList).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not crash on malformed numeric and date filters", async () => {
|
||||
vi.mocked(getTenantAuditLogList).mockResolvedValue({ rows: [], total: 0, take: 10, skip: 0 } as never);
|
||||
|
||||
const data = await callLoader("https://app.example.test/acme/settings/compliance?page=abc&pageSize=-5&createdAtFrom=not-a-date&createdAtTo=also-bad");
|
||||
|
||||
expect(getTenantAuditLogList).toHaveBeenCalledWith("tenant-1", {
|
||||
q: null,
|
||||
action: null,
|
||||
url: null,
|
||||
userId: null,
|
||||
createdAtFrom: "not-a-date",
|
||||
createdAtTo: "also-bad",
|
||||
take: 10,
|
||||
skip: 0,
|
||||
});
|
||||
expect(data).toMatchObject({ pagination: { page: 1, pageSize: 10, totalItems: 0, totalPages: 0 } });
|
||||
});
|
||||
|
||||
it("uses the package audit-log boundary instead of the legacy app DB helper", () => {
|
||||
const source = readTenantLogsRoute();
|
||||
|
||||
expect(source).toContain('from "@hivegrid/db/logs.server"');
|
||||
expect(source).toContain("getTenantAuditLogList");
|
||||
expect(source).toContain("TenantActivityLogToolbar");
|
||||
expect(source).not.toContain("getLogs");
|
||||
expect(source).not.toContain('from "~/utils/db/logs.db.server"');
|
||||
});
|
||||
});
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
import type { AdminAuditLogRow } from "@hivegrid/db/logs.server";
|
||||
import { getTenantAuditLogList } from "@hivegrid/db/logs.server";
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import TenantActivityLogToolbar from "~/components/activity/TenantActivityLogToolbar";
|
||||
import LogsTable from "~/components/app/events/LogsTable";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { PageIntro } from "~/components/screens/shared/PageShell";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
import { getTenantAuditLogFiltersFromUrl } from "./logs-export.helpers.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: AdminAuditLogRow[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const filterableProperties = getAuditLogFilterableProperties();
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const auditLogFilters = getTenantAuditLogFiltersFromUrl(urlSearchParams);
|
||||
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const pageSize = normalizePositiveInteger(currentPagination.pageSize, 10);
|
||||
const page = normalizePositiveInteger(currentPagination.page, 1);
|
||||
const { rows, total, take } = await getTenantAuditLogList(tenantId, {
|
||||
...auditLogFilters,
|
||||
take: pageSize,
|
||||
skip: pageSize * (page - 1),
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.log.plural")} | ${process.env.APP_NAME}`,
|
||||
items: rows,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize: take,
|
||||
totalItems: total,
|
||||
totalPages: Math.ceil(total / take),
|
||||
sortedBy: currentPagination.sortedBy,
|
||||
query: currentPagination.query,
|
||||
},
|
||||
filterableProperties: filters.properties,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
function getAuditLogFilterableProperties(): FilterablePropertyDto[] {
|
||||
return [
|
||||
{
|
||||
name: "action",
|
||||
title: "models.log.action",
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
title: "models.log.url",
|
||||
},
|
||||
{
|
||||
name: "userId",
|
||||
title: "shared.createdBy",
|
||||
},
|
||||
{
|
||||
name: "createdAtFrom",
|
||||
title: "shared.createdAt",
|
||||
},
|
||||
{
|
||||
name: "createdAtTo",
|
||||
title: "shared.createdAt",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function normalizePositiveInteger(value: number | null | undefined, fallback: number): number {
|
||||
if (!Number.isFinite(value) || !value || value < 1) return fallback;
|
||||
return Math.trunc(value);
|
||||
}
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function Events() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout fullWidth>
|
||||
{/* AK-SET-01: the Compliance hub owns the page header. */}
|
||||
<PageIntro uiId="ui.settings.logs.intro">{t("settings.logs.subtitle")}</PageIntro>
|
||||
<div data-ui-id="ui.settings.logs.page" className="space-y-2">
|
||||
<div className="flex justify-between gap-2">
|
||||
<div data-ui-id="ui.settings.logs.tabs" className="grow">
|
||||
<Tabs
|
||||
tabs={[
|
||||
{
|
||||
name: t("models.log.plural"),
|
||||
routePath: UrlUtils.currentTenantUrl(params, "settings/compliance"),
|
||||
},
|
||||
{
|
||||
name: t("models.event.plural"),
|
||||
routePath: UrlUtils.currentTenantUrl(params, "settings/compliance/events"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div data-ui-id="ui.settings.logs.filters">
|
||||
<TenantActivityLogToolbar filters={data.filterableProperties} exportTo={UrlUtils.currentTenantUrl(params, "settings/logs/export")} />
|
||||
</div>
|
||||
</div>
|
||||
<div data-ui-id="ui.settings.logs.table">
|
||||
<LogsTable withTenant={false} items={data.items} pagination={data.pagination} />
|
||||
</div>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
// Shared between the tenant Protokolle/Ereignisse list routes and their CSV
|
||||
// export resource routes. Exports must live in resource routes (no component):
|
||||
// returning a raw Response from a UI route's loader breaks under React Router 7.
|
||||
import type { AdminAuditLogFilters } from "@hivegrid/db/logs.server";
|
||||
|
||||
export const CSV_EXPORT_TAKE = 500;
|
||||
|
||||
export function getTenantAuditLogFiltersFromUrl(urlSearchParams: URLSearchParams): AdminAuditLogFilters {
|
||||
return {
|
||||
q: urlSearchParams.get("q"),
|
||||
action: urlSearchParams.get("action"),
|
||||
url: urlSearchParams.get("url"),
|
||||
userId: urlSearchParams.get("userId"),
|
||||
createdAtFrom: urlSearchParams.get("createdAtFrom"),
|
||||
createdAtTo: urlSearchParams.get("createdAtTo"),
|
||||
};
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "../logs/export";
|
||||
import { getTenantAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
|
||||
vi.mock("@hivegrid/db/logs.server", () => ({
|
||||
getTenantAuditLogList: vi.fn(),
|
||||
serializeAdminAuditLogsCsv: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
const params = { tenant: "acme" };
|
||||
const auditRows = [{ id: "log-1" }];
|
||||
|
||||
function callLoader(url: string) {
|
||||
const request = new Request(url);
|
||||
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/logs/export" } as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
describe("tenant settings logs CSV export route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTenantAuditLogList).mockResolvedValue({ rows: auditRows, total: 1, take: 500, skip: 0 } as never);
|
||||
vi.mocked(serializeAdminAuditLogsCsv).mockReturnValue("csv-body\n");
|
||||
});
|
||||
|
||||
it("exports CSV with the same tenant filters and a capped export window", async () => {
|
||||
const response = await callLoader(
|
||||
"https://app.example.test/acme/settings/logs/export?q=login&action=auth&url=%2Flogin&tenantId=other-tenant&userId=user-2&createdAtFrom=bad-date&createdAtTo=2026-05-08&page=9&pageSize=5",
|
||||
);
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getTenantAuditLogList).mock.invocationCallOrder[0]);
|
||||
expect(getTenantAuditLogList).toHaveBeenCalledWith("tenant-1", {
|
||||
q: "login",
|
||||
action: "auth",
|
||||
url: "/login",
|
||||
userId: "user-2",
|
||||
createdAtFrom: "bad-date",
|
||||
createdAtTo: "2026-05-08",
|
||||
take: 500,
|
||||
skip: 0,
|
||||
});
|
||||
expect(JSON.stringify(vi.mocked(getTenantAuditLogList).mock.calls[0]?.[1])).not.toContain("other-tenant");
|
||||
expect(serializeAdminAuditLogsCsv).toHaveBeenCalledWith(auditRows);
|
||||
expect(response.headers.get("Content-Type")).toBe("text/csv; charset=utf-8");
|
||||
expect(response.headers.get("Content-Disposition")).toBe('attachment; filename="tenant-audit-logs.csv"');
|
||||
expect(await response.text()).toBe("csv-body\n");
|
||||
});
|
||||
|
||||
it("rejects CSV reads without permission before helper calls", async () => {
|
||||
const rejection = new Response("Forbidden", { status: 403 });
|
||||
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
|
||||
|
||||
await expect(callLoader("https://app.example.test/acme/settings/logs/export")).rejects.toBe(rejection);
|
||||
|
||||
expect(getTenantAuditLogList).not.toHaveBeenCalled();
|
||||
expect(serializeAdminAuditLogsCsv).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// AK-P21 — subprocessor register (global rows, tenant-visible). Gate:
|
||||
// privacy.subprocessors.read (denied ⇒ 404 via PermissionsService).
|
||||
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { useLoaderData, useParams, useRevalidator } from "react-router";
|
||||
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
import { listActiveSubprocessors } from "@hivegrid/db/privacy-gdpr.server";
|
||||
import { buildSubprocessorsVM, type SubprocessorsVM } from "@hivegrid/view-models";
|
||||
|
||||
import { SubprocessorsPage } from "~/components/screens/privacy/SubprocessorsPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: SubprocessorsVM;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "privacy.subprocessors.read", tenantId);
|
||||
|
||||
const subprocessors = await listActiveSubprocessors();
|
||||
const vm = buildSubprocessorsVM({
|
||||
subprocessors: subprocessors.map((subprocessor) => ({
|
||||
id: subprocessor.id,
|
||||
name: subprocessor.name,
|
||||
purposeText: subprocessor.purposeText,
|
||||
country: subprocessor.country,
|
||||
isEuEea: subprocessor.isEuEea,
|
||||
dataCategories: subprocessor.dataCategories,
|
||||
dpaUrl: subprocessor.dpaUrl,
|
||||
activeSince: subprocessor.activeSince ? subprocessor.activeSince.toISOString() : null,
|
||||
})),
|
||||
});
|
||||
|
||||
const data: LoaderData = { title: `${t("settings.privacy.subprocessors.title")} | ${process.env.APP_NAME}`, vm };
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
|
||||
|
||||
export default function PrivacySubprocessorsRoute() {
|
||||
// AK-P21 DoD B9 — breadcrumb target injected into the screen so the screen
|
||||
// itself stays free of router data access.
|
||||
const routeParams = useParams();
|
||||
const hubHref = appPath({ tenantSlug: routeParams.tenant ?? "", path: "settings/compliance", mode: "host-aware" });
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const revalidator = useRevalidator();
|
||||
|
||||
return (
|
||||
<SubprocessorsPage
|
||||
embedded
|
||||
hubHref={hubHref}
|
||||
vm={vm}
|
||||
actions={{
|
||||
onRetry() {
|
||||
revalidator.revalidate();
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
// AK-P21 — tenant deletion area. Gate: privacy.tenant_deletion (denied ⇒ 404
|
||||
// via PermissionsService). The wizard re-authenticates with password (+ TOTP
|
||||
// when enabled) and requires the tenant slug as the confirm phrase; the
|
||||
// service re-checks the phrase server-side. Cancelling is possible during the
|
||||
// whole 30-day grace window. The hard-delete cron itself is a tracked
|
||||
// follow-up outside this route (see ticket doc AK-P21).
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { useEffect } from "react";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useActionData, useLoaderData, useLocation, useNavigate, useNavigation, useParams, useRevalidator, useSubmit } from "react-router";
|
||||
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
import {
|
||||
cancelTenantDeletionRequest,
|
||||
createTenantDeletionRequest,
|
||||
GDPR_TENANT_DELETION_GRACE_DAYS,
|
||||
} from "@hivegrid/db/privacy-gdpr.server";
|
||||
import { buildTenantDeletionVM, type TenantDeletionVM } from "@hivegrid/view-models";
|
||||
|
||||
import { TenantDeletionPage } from "~/components/screens/privacy/TenantDeletionPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { getActiveTotpSecretEncrypted } from "~/utils/db/users.db.server";
|
||||
import { verifyTotpCode } from "~/services/auth/totp.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: TenantDeletionVM;
|
||||
};
|
||||
|
||||
type ActionData = { ok: true; message: string } | { ok: false; error: string };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "privacy.tenant_deletion", tenantId);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const db = getDbClient();
|
||||
|
||||
const [latestRequest, totpSecret] = await Promise.all([
|
||||
db.tenantDeletionRequest.findFirst({
|
||||
where: { tenantId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: { id: true, status: true, reason: true, reasonText: true, gracePeriodEndsAt: true, createdAt: true },
|
||||
}),
|
||||
getActiveTotpSecretEncrypted(userInfo.userId),
|
||||
]);
|
||||
|
||||
const vm = buildTenantDeletionVM({
|
||||
now: new Date().toISOString(),
|
||||
tenantSlug: params.tenant ?? "",
|
||||
graceDays: GDPR_TENANT_DELETION_GRACE_DAYS,
|
||||
requiresOtp: totpSecret !== null,
|
||||
request: latestRequest
|
||||
? {
|
||||
id: latestRequest.id,
|
||||
status: latestRequest.status,
|
||||
reason: latestRequest.reason,
|
||||
reasonText: latestRequest.reasonText,
|
||||
gracePeriodEndsAt: latestRequest.gracePeriodEndsAt.toISOString(),
|
||||
createdAt: latestRequest.createdAt.toISOString(),
|
||||
}
|
||||
: null,
|
||||
});
|
||||
|
||||
const data: LoaderData = { title: `${t("settings.privacy.deletion.title")} | ${process.env.APP_NAME}`, vm };
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "privacy.tenant_deletion", tenantId);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const db = getDbClient();
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
const requestId = randomUUID();
|
||||
|
||||
const badRequest = (error: string, status = 400) => Response.json({ ok: false, error } satisfies ActionData, { status });
|
||||
|
||||
if (intent === "cancel") {
|
||||
const deletionRequestId = String(form.get("requestId") ?? "").trim();
|
||||
if (!deletionRequestId) return badRequest(t("settings.privacy.errors.unknownIntent", { intent }));
|
||||
try {
|
||||
await cancelTenantDeletionRequest({ id: deletionRequestId, tenantId, cancelledByUserId: userInfo.userId });
|
||||
} catch {
|
||||
return badRequest(t("settings.privacy.deletion.errors.cancelFailed"), 409);
|
||||
}
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "user",
|
||||
action: "CANCEL_TENANT_DELETION",
|
||||
targetType: "Tenant",
|
||||
targetId: tenantId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, deletionRequestId, source: "privacy-deletion-page" },
|
||||
});
|
||||
return Response.json({ ok: true, message: t("settings.privacy.deletion.messages.cancelled") } satisfies ActionData);
|
||||
}
|
||||
|
||||
if (intent === "request") {
|
||||
const password = String(form.get("password") ?? "");
|
||||
const otpCode = String(form.get("otpCode") ?? "").trim();
|
||||
const slugConfirm = String(form.get("slugConfirm") ?? "");
|
||||
const reasonText = String(form.get("reasonText") ?? "").trim();
|
||||
|
||||
// Re-authenticate: password always; TOTP when the user has it enabled.
|
||||
const user = await db.user.findUnique({ where: { id: userInfo.userId }, select: { passwordHash: true } });
|
||||
const { valid: passwordValid } = await verifyPassword(password, user?.passwordHash ?? null);
|
||||
if (!passwordValid) {
|
||||
return badRequest(t("settings.privacy.deletion.errors.verifyFailed"), 403);
|
||||
}
|
||||
const totpSecret = await getActiveTotpSecretEncrypted(userInfo.userId);
|
||||
if (totpSecret && !verifyTotpCode(totpSecret, otpCode)) {
|
||||
return badRequest(t("settings.privacy.deletion.errors.verifyFailed"), 403);
|
||||
}
|
||||
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (!tenant) return badRequest(t("shared.unexpectedError"), 404);
|
||||
if (slugConfirm !== tenant.slug) {
|
||||
return badRequest(t("settings.privacy.deletion.wizard.confirm.slugMismatch"));
|
||||
}
|
||||
|
||||
try {
|
||||
const deletionRequest = await createTenantDeletionRequest({
|
||||
tenantId,
|
||||
requestedByUserId: userInfo.userId,
|
||||
tenantSlug: tenant.slug,
|
||||
slugConfirmPhrase: slugConfirm,
|
||||
reason: "voluntary",
|
||||
reasonText: reasonText || null,
|
||||
});
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "user",
|
||||
action: "REQUEST_TENANT_DELETION",
|
||||
targetType: "Tenant",
|
||||
targetId: tenantId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, deletionRequestId: deletionRequest.id, gracePeriodEndsAt: deletionRequest.gracePeriodEndsAt.toISOString(), source: "privacy-deletion-page" },
|
||||
});
|
||||
return Response.json({ ok: true, message: t("settings.privacy.deletion.messages.requested", { days: GDPR_TENANT_DELETION_GRACE_DAYS }) } satisfies ActionData);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "";
|
||||
if (message.includes("already active")) {
|
||||
return badRequest(t("settings.privacy.deletion.errors.alreadyActive"), 409);
|
||||
}
|
||||
if (message.includes("confirmation phrase")) {
|
||||
return badRequest(t("settings.privacy.deletion.wizard.confirm.slugMismatch"));
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return badRequest(t("settings.privacy.errors.unknownIntent", { intent }));
|
||||
};
|
||||
|
||||
export default function PrivacyDeletionRoute() {
|
||||
// AK-P21 DoD B9 — breadcrumb target injected into the screen so the screen
|
||||
// itself stays free of router data access.
|
||||
const routeParams = useParams();
|
||||
const hubHref = appPath({ tenantSlug: routeParams.tenant ?? "", path: "settings/compliance", mode: "host-aware" });
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const revalidator = useRevalidator();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { csrf } = useRootData();
|
||||
|
||||
useEffect(() => {
|
||||
if (!actionData) return;
|
||||
if (actionData.ok) toast.success(actionData.message);
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<TenantDeletionPage
|
||||
embedded
|
||||
hubHref={hubHref}
|
||||
vm={vm}
|
||||
submitting={navigation.state === "submitting"}
|
||||
errorKey={actionData && !actionData.ok ? actionData.error : null}
|
||||
actions={{
|
||||
onRequest(fields) {
|
||||
const form = new FormData();
|
||||
form.set("intent", "request");
|
||||
form.set("csrf", csrf ?? "");
|
||||
form.set("password", fields.password);
|
||||
form.set("otpCode", fields.otpCode);
|
||||
form.set("slugConfirm", fields.slugConfirm);
|
||||
form.set("reasonText", fields.reasonText);
|
||||
void submit(form, { method: "post" });
|
||||
},
|
||||
onCancelRequest(requestId) {
|
||||
const form = new FormData();
|
||||
form.set("intent", "cancel");
|
||||
form.set("csrf", csrf ?? "");
|
||||
form.set("requestId", requestId);
|
||||
void submit(form, { method: "post" });
|
||||
},
|
||||
onOpenExport() {
|
||||
void navigate(location.pathname.replace(/\/deletion\/?$/, "/export"));
|
||||
},
|
||||
onRetry() {
|
||||
revalidator.revalidate();
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user