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: "ToolCTRL 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("@toolctrl/db/notifications.server").getNotificationDeliveryDiagnostics; let markInAppNotificationDeliveryRead: typeof import("@toolctrl/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("@toolctrl/db/notifications.server", () => ({ getNotificationDeliveryDiagnostics: vi.fn(), markInAppNotificationDeliveryRead: 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) => ({ "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("react-router"); return { ...actual, useLoaderData: () => routeLoaderData, }; }); 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), }); } describe("app tenant notifications route", () => { beforeAll(async () => { applyBaseEnv(); const notificationsDb = await import("@toolctrl/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; }); 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 = { items: [], 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.items).toEqual([ { id: "delivery_1", messageKey: "billing.invoice.paid", category: "billing", channel: "IN_APP", status: "SENT", attemptsMade: 2, lastError: "token=[redacted] Authorization: Bearer [redacted]", createdAt: "2026-05-01T10:00:00.000Z", updatedAt: "2026-05-01T10:05:00.000Z", sentAt: "2026-05-01T10:01:00.000Z", readAt: null, }, ]); 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("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(getTranslations).toHaveBeenCalledWith(expect.any(Request)); expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request)); expect(body.error).toBe("Invalid notification action."); 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(getTranslations).toHaveBeenCalledWith(expect.any(Request)); expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request)); expect(body.error).toBe("Notification delivery is required."); 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({ ok: true }); }); it("renders page copy, empty state, and notification diagnostics through the center component", () => { routeLoaderData = { streamUrl: "/acme/notifications/stream", csrf: "csrf-token", 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", createdAt: "2026-05-01T10:00:00.000Z", updatedAt: "2026-05-01T10:05:00.000Z", sentAt: null, readAt: null, }, ], }; render( ); expect(screen.getByRole("heading", { name: "Notifications" })).toBeInTheDocument(); expect(screen.getByText("Review in-app notification delivery status, retry diagnostics, and read timestamps for your account.")).toBeInTheDocument(); expect(screen.getByRole("heading", { name: "Notification center" })).toBeInTheDocument(); expect(screen.getByText("Team invite created")).toBeInTheDocument(); expect(screen.getByText("Failed")).toBeInTheDocument(); expect(screen.getByText("3")).toBeInTheDocument(); expect(screen.getByLabelText("Mark Team invite created as read")).toBeInTheDocument(); expect(screen.getByDisplayValue("csrf-token")).toHaveAttribute("name", "csrf"); 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-toolctrl-tenant-id": "tenant_1", "x-toolctrl-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)); }); });