Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/app.$tenant/notifications.test.tsx
T

483 lines
19 KiB
TypeScript

import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import React from "react";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { MemoryRouter } from "react-router";
const baseEnv = {
API_ACCESS_TOKEN: "test-api-access-token-placeholder",
APP_NAME: "HiveGrid Test",
CRYPTO_SECRET: "test-crypto-secret-placeholder",
DATABASE_URL: "file:./test.db?connection_limit=1&connect_timeout=30",
JWT_SECRET: "test-jwt-secret-placeholder",
SESSION_SECRET: "test-session-secret-placeholder",
};
const originalEnv = new Map(Object.keys(baseEnv).map((key) => [key, process.env[key]]));
function applyBaseEnv() {
for (const [key, value] of Object.entries(baseEnv)) {
process.env[key] = value;
}
}
function restoreOriginalEnv() {
for (const [key, value] of originalEnv) {
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
}
let routeLoaderData: unknown;
let NotificationsRoute: typeof import("./notifications").default;
let action: typeof import("./notifications").action;
let loader: typeof import("./notifications").loader;
let streamLoader: typeof import("./notifications/stream").loader;
let getNotificationDeliveryDiagnostics: typeof import("@hivegrid/db/notifications.server").getNotificationDeliveryDiagnostics;
let markInAppNotificationDeliveryRead: typeof import("@hivegrid/db/notifications.server").markInAppNotificationDeliveryRead;
let requireAuth: typeof import("~/utils/loaders.middleware").requireAuth;
let getTenantIdFromUrl: typeof import("~/utils/services/.server/urlService").getTenantIdFromUrl;
let getUserInfo: typeof import("~/utils/session.server").getUserInfo;
let validateCSRFToken: typeof import("~/utils/session.server").validateCSRFToken;
let getAbsoluteApiUrl: typeof import("~/utils/url.server").getAbsoluteApiUrl;
let getTranslations: typeof import("~/locale/i18next.server").getTranslations;
vi.mock("@hivegrid/db/notifications.server", () => ({
getNotificationDeliveryDiagnostics: vi.fn(),
markInAppNotificationDeliveryRead: vi.fn(),
markAllInAppNotificationDeliveriesRead: vi.fn(),
redactNotificationDiagnosticText: (value: string) =>
value
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [redacted]")
.replace(/\b(token|secret|api[-_]?key|apikey|password|code)\s*[:=]\s*[^&\s;,)"']+/gi, "$1=[redacted]"),
}));
vi.mock("~/utils/loaders.middleware", () => ({
requireAuth: vi.fn(),
}));
vi.mock("~/utils/services/.server/urlService", () => ({
getTenantIdFromUrl: vi.fn(),
}));
vi.mock("~/utils/session.server", () => ({
getUserInfo: vi.fn(),
validateCSRFToken: vi.fn(),
}));
vi.mock("~/utils/url.server", () => ({
getAbsoluteApiUrl: vi.fn(() => "https://api.example.com/v1/notifications/stream"),
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({
t: (key: string) =>
({
"notifications.errors.invalidAction": "Invalid notification action.",
"notifications.errors.deliveryRequired": "Notification delivery is required.",
"notifications.errors.streamTenantSessionRequired": "Notification stream requires an authenticated tenant session.",
"notifications.errors.streamServiceTokenMissing": "Notification stream service token is not configured.",
})[key] ?? key,
})),
}));
vi.mock("~/utils/app/UrlUtils", () => ({
default: {
getModulePath: vi.fn(() => "/acme/notifications/stream"),
},
}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, options?: Record<string, string>) =>
({
"notifications.title": "Notifications",
"notifications.description": "Review in-app notification delivery status, retry diagnostics, and read timestamps for your account.",
"notifications.center.title": "Notification center",
"notifications.center.empty": "No in-app notifications yet.",
"notifications.center.categories.team": "Team",
"notifications.center.channels.in_app": "In-app",
"notifications.center.diagnostics": "Delivery diagnostics for in-app notifications.",
"notifications.center.fields.attempts": "Attempts",
"notifications.center.fields.read": "Read",
"notifications.center.fields.sent": "Sent",
"notifications.center.fields.updated": "Updated",
"notifications.center.lastError": "Last error:",
"notifications.center.listLabel": "In-app notification deliveries",
"notifications.center.markRead": "Mark as read",
"notifications.center.markReadLabel": `Mark ${options?.message ?? ""} as read`,
"notifications.center.realtime.unavailable": "Realtime updates unavailable.",
"notifications.center.statuses.failed": "Failed",
"notifications.center.timestamps.notRecorded": "Not recorded",
"notifications.center.unknownMessage": "Notification delivery",
"team.invite.created": "Team invite created",
})[key] ?? key,
i18n: {
exists: (key: string) =>
[
"notifications.title",
"notifications.description",
"notifications.center.title",
"notifications.center.empty",
"notifications.center.categories.team",
"notifications.center.channels.in_app",
"notifications.center.statuses.failed",
"team.invite.created",
].includes(key),
},
}),
}));
vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
useLoaderData: () => routeLoaderData,
useFetcher: () => ({ submit: vi.fn(), data: undefined, state: "idle" }),
};
});
vi.mock("~/components/ui/errors/ServerError", () => ({
default: () => null,
}));
const request = new Request("https://example.com/acme/notifications");
const params = { tenant: "acme" };
const createdAt = new Date("2026-05-01T10:00:00.000Z");
const updatedAt = new Date("2026-05-01T10:05:00.000Z");
const sentAt = new Date("2026-05-01T10:01:00.000Z");
function routeArgs(customRequest: Request = request) {
return { request: customRequest, params, context: {}, unstable_pattern: "app.$tenant/notifications" };
}
function postFormRequest(formData: FormData) {
return new Request("https://example.com/acme/notifications", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(formData as unknown as Record<string, string>),
});
}
describe("app tenant notifications route", () => {
beforeAll(async () => {
applyBaseEnv();
const notificationsDb = await import("@hivegrid/db/notifications.server");
const loadersMiddleware = await import("~/utils/loaders.middleware");
const urlService = await import("~/utils/services/.server/urlService");
const sessionServer = await import("~/utils/session.server");
const urlServer = await import("~/utils/url.server");
const i18nextServer = await import("~/locale/i18next.server");
const route = await import("./notifications");
const streamRoute = await import("./notifications/stream");
getNotificationDeliveryDiagnostics = notificationsDb.getNotificationDeliveryDiagnostics;
markInAppNotificationDeliveryRead = notificationsDb.markInAppNotificationDeliveryRead;
requireAuth = loadersMiddleware.requireAuth;
getTenantIdFromUrl = urlService.getTenantIdFromUrl;
getUserInfo = sessionServer.getUserInfo;
validateCSRFToken = sessionServer.validateCSRFToken;
getAbsoluteApiUrl = urlServer.getAbsoluteApiUrl;
getTranslations = i18nextServer.getTranslations;
NotificationsRoute = route.default;
action = route.action;
loader = route.loader;
streamLoader = streamRoute.loader;
}, 60_000);
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1");
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user_1", csrf: "csrf-token" } as never);
vi.mocked(getNotificationDeliveryDiagnostics).mockResolvedValue([]);
routeLoaderData = {
vm: { status: "ready", data: { items: [], totalCount: 0, unreadCount: 0, emptyHeadlineKey: "notifications.center.empty", emptyBodyKey: "notifications.center.emptyHelper", unreadEmptyKey: "notifications.center.unreadEmpty", streamAvailable: true } },
streamUrl: "/acme/notifications/stream",
};
vi.stubEnv("API_ACCESS_TOKEN", "service-secret");
});
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
process.env.API_ACCESS_TOKEN = baseEnv.API_ACCESS_TOKEN;
});
afterAll(() => {
restoreOriginalEnv();
});
it("delegates authentication and loads only scoped in-app deliveries capped newest-first", async () => {
vi.mocked(getNotificationDeliveryDiagnostics).mockResolvedValue([
{
id: "delivery_1",
tenantId: "tenant_1",
userId: "user_1",
messageKey: "billing.invoice.paid",
category: "billing",
channel: "IN_APP",
status: "SENT",
attemptsMade: 2,
providerMessageId: "provider_secret_123",
payloadMetadata: { token: "tok_secret", payload: "hidden" },
lastError: "token=tok_secret Authorization: Bearer abc123",
createdAt,
updatedAt,
sentAt,
readAt: null,
},
{
id: "delivery_skipped",
tenantId: "tenant_1",
userId: "user_1",
messageKey: "billing.invoice.skipped",
category: "billing",
channel: "IN_APP",
status: "SKIPPED",
attemptsMade: 0,
lastError: "preference_disabled",
createdAt,
updatedAt,
sentAt: null,
readAt: null,
},
] as never);
const response = (await loader(routeArgs())) as Response;
const body = await response.json();
expect(requireAuth).toHaveBeenCalledWith({ request, params });
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
expect(getUserInfo).toHaveBeenCalledWith(request);
expect(getNotificationDeliveryDiagnostics).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
statuses: ["SENT", "READ"],
take: 50,
});
expect(body.vm.status).toBe("ready");
expect(body.vm.data.items).toHaveLength(1);
expect(body.vm.data.items[0]).toMatchObject({
id: "delivery_1",
messageKey: "billing.invoice.paid",
category: "billing",
categoryKey: "notifications.center.categories.billing",
channel: "IN_APP",
status: "SENT",
isRead: false,
attemptsMade: 2,
lastErrorRedacted: "token=[redacted] Authorization: Bearer [redacted]",
createdAtIso: "2026-05-01T10:00:00.000Z",
updatedAtIso: "2026-05-01T10:05:00.000Z",
sentAtIso: "2026-05-01T10:01:00.000Z",
readAtIso: null,
deeplinkHref: null,
});
expect(body.vm.data.unreadCount).toBe(1);
expect(body.csrf).toBe("csrf-token");
expect(body.streamUrl).toBe("/acme/notifications/stream");
expect(JSON.stringify(body)).not.toContain("provider_secret_123");
expect(JSON.stringify(body)).not.toContain("payloadMetadata");
expect(JSON.stringify(body)).not.toContain("billing.invoice.skipped");
expect(JSON.stringify(body)).not.toContain("preference_disabled");
expect(JSON.stringify(body)).not.toContain("hidden");
expect(JSON.stringify(body)).not.toContain("tok_secret");
expect(JSON.stringify(body)).not.toContain("abc123");
});
it("derives a validated app-relative deeplink from payloadMetadata", async () => {
vi.mocked(getNotificationDeliveryDiagnostics).mockResolvedValue([
{
id: "delivery_deeplink",
tenantId: "tenant_1",
userId: "user_1",
messageKey: "team.invite.created",
category: "team",
channel: "IN_APP",
status: "SENT",
attemptsMade: 1,
payloadMetadata: { deeplink: "/acme/settings/members" },
createdAt,
updatedAt,
sentAt,
readAt: null,
},
{
id: "delivery_evil",
tenantId: "tenant_1",
userId: "user_1",
messageKey: "team.invite.created",
category: "team",
channel: "IN_APP",
status: "SENT",
attemptsMade: 1,
payloadMetadata: { deeplink: "https://evil.example/phish" },
createdAt,
updatedAt,
sentAt,
readAt: null,
},
] as never);
const response = (await loader(routeArgs())) as Response;
const body = await response.json();
const byId = Object.fromEntries(body.vm.data.items.map((item: { id: string; deeplinkHref: string | null }) => [item.id, item.deeplinkHref]));
expect(byId.delivery_deeplink).toBe("/acme/settings/members");
expect(byId.delivery_evil).toBeNull();
expect(JSON.stringify(body)).not.toContain("evil.example");
});
it("returns 400 for invalid form actions without updating a delivery", async () => {
const formData = new FormData();
formData.set("action", "delete");
formData.set("deliveryId", "delivery_1");
const response = (await action(routeArgs(postFormRequest(formData)))) as Response;
const body = await response.json();
expect(response.status).toBe(400);
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
expect(body).toEqual({ intent: "delete", error: "notifications.errors.invalidAction" });
expect(markInAppNotificationDeliveryRead).not.toHaveBeenCalled();
});
it("returns 400 when mark-read omits a non-empty delivery id", async () => {
const formData = new FormData();
formData.set("action", "mark-read");
formData.set("deliveryId", " ");
const response = (await action(routeArgs(postFormRequest(formData)))) as Response;
const body = await response.json();
expect(response.status).toBe(400);
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
expect(body).toEqual({ intent: "mark-read", error: "notifications.errors.deliveryRequired" });
expect(markInAppNotificationDeliveryRead).not.toHaveBeenCalled();
});
it("marks the selected delivery as read after resolving the current scoped user", async () => {
const formData = new FormData();
formData.set("action", "mark-read");
formData.set("deliveryId", "delivery_1");
const response = (await action(routeArgs(postFormRequest(formData)))) as Response;
const body = await response.json();
expect(requireAuth).toHaveBeenCalledWith({ request: expect.any(Request), params });
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
expect(getUserInfo).toHaveBeenCalledWith(expect.any(Request));
expect(markInAppNotificationDeliveryRead).toHaveBeenCalledWith({
id: "delivery_1",
tenantId: "tenant_1",
userId: "user_1",
readAt: expect.any(Date),
});
expect(body).toEqual({ intent: "mark-read", ok: true });
});
it("renders page copy, tabs, bounce plain-text and mark-read through the interim screen", async () => {
const { buildNotificationCenterVM } = await import("@hivegrid/view-models");
routeLoaderData = {
streamUrl: "/acme/notifications/stream",
csrf: "csrf-token",
vm: buildNotificationCenterVM({
streamAvailable: true,
items: [
{
id: "delivery_1",
messageKey: "team.invite.created",
category: "team",
channel: "IN_APP",
status: "FAILED",
attemptsMade: 3,
lastError: "provider_id=provider_secret_123 token=tok_secret rate limit",
createdAtIso: "2026-05-01T10:00:00.000Z",
updatedAtIso: "2026-05-01T10:05:00.000Z",
sentAtIso: null,
readAtIso: null,
payloadMetadata: { deeplink: "/acme/settings/members" },
},
],
}),
};
const { container } = render(
<MemoryRouter>
<NotificationsRoute />
</MemoryRouter>
);
expect(container.querySelector('[data-ui-id="ui.notifications.center"]')).toBeInTheDocument();
expect(screen.getByText("Notification center")).toBeInTheDocument();
expect(screen.getByText("Delivery diagnostics for in-app notifications.")).toBeInTheDocument();
expect(screen.getByText("Team invite created")).toBeInTheDocument();
expect(screen.getByText("Failed")).toBeInTheDocument();
// Deeplink renders as an app-relative link on the item title.
expect(container.querySelector('[data-ui-id="ui.notifications.center.deeplink"]')).toHaveAttribute("href", "/acme/settings/members");
// Bounce plain-text (M002) is shown; the raw redacted detail never leaks secrets.
expect(container.querySelector('[data-ui-id="ui.notifications.center.bounce"]')).toBeInTheDocument();
expect(screen.getByLabelText("Mark Team invite created as read")).toBeInTheDocument();
expect(container.querySelector('[data-ui-id="ui.notifications.center.tabs"]')).toBeInTheDocument();
expect(container.querySelector('[data-ui-id="ui.notifications.center.bulkClear"]')).toBeInTheDocument();
expect(screen.queryByText("provider_secret_123")).not.toBeInTheDocument();
expect(screen.queryByText("tok_secret")).not.toBeInTheDocument();
});
it("proxies the notification stream through a tenant-authenticated same-origin route", async () => {
const stream = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode('event: notification.snapshot\ndata: {"items":[]}\n\n'));
controller.close();
},
});
const fetchMock = vi.fn().mockResolvedValue(
new Response(stream, {
headers: {
"content-type": "text/event-stream; charset=utf-8",
"cache-control": "no-cache",
"x-request-id": "req_stream",
},
})
);
vi.stubGlobal("fetch", fetchMock);
const response = await streamLoader(
routeArgs(new Request("https://app.example.test/acme/notifications/stream?afterCursor=cursor_1", { headers: { "x-request-id": "req_web" } }))
);
expect(requireAuth).toHaveBeenCalledWith({ request: expect.any(Request), params });
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
expect(getUserInfo).toHaveBeenCalledWith(expect.any(Request));
expect(getAbsoluteApiUrl).toHaveBeenCalledWith(expect.any(Request), "/v1/notifications/stream");
expect(fetchMock).toHaveBeenCalledTimes(1);
const [proxiedUrl, proxiedInit] = fetchMock.mock.calls[0];
expect(proxiedUrl.toString()).toBe("https://api.example.com/v1/notifications/stream?afterCursor=cursor_1");
expect(proxiedInit).toEqual({
headers: {
authorization: "Bearer service-secret",
"x-hivegrid-tenant-id": "tenant_1",
"x-hivegrid-user-id": "user_1",
"x-request-id": "req_web",
},
});
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("text/event-stream; charset=utf-8");
expect(response.headers.get("x-request-id")).toBe("req_stream");
});
it("localizes notification stream tenant-session failures", async () => {
vi.mocked(getTenantIdFromUrl).mockResolvedValue("");
const response = await streamLoader(routeArgs(new Request("https://app.example.test/acme/notifications/stream")));
const body = await response.json();
expect(response.status).toBe(401);
expect(body).toEqual({ error: "Notification stream requires an authenticated tenant session." });
expect(getTranslations).toHaveBeenCalledWith(expect.any(Request));
});
});