import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; import { beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("~/components/app/AppLayout", () => ({ default: ({ children }: { children: React.ReactNode }) => children })); vi.mock("~/utils/data/useAppData", () => ({ useAppData: vi.fn() })); vi.mock("~/utils/data/.server/appData", () => ({ loadAppData: vi.fn() })); vi.mock("@toolctrl/db/auth-boundary.server", () => ({ getAuthUserWithoutPasswordById: vi.fn(), getTenantMembershipByIds: vi.fn(), updateAuthUserDefaultTenantId: 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/loaders.middleware", () => ({ getIsSuperAdminByUserId: vi.fn(), requireAuth: vi.fn() })); vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({ ensureTenantUserAppRoles: vi.fn() })); vi.mock("~/utils/db/appConfiguration.db.server", () => ({ getAppConfiguration: vi.fn() })); vi.mock("~/utils/data/useRootData", () => ({ useRootData: vi.fn() })); vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null })); vi.mock("~/utils/db/tenants/tenantIpAddress.db.server", () => ({ createUniqueTenantIpAddress: vi.fn() })); vi.mock("~/utils/server/IpUtils", () => ({ getClientIPAddress: vi.fn() })); vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({ createMetrics: vi.fn(async () => ({ time: async (value: T | Promise) => value, getServerTimingHeader: () => ({ "Server-Timing": "test" }), })), })); vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({ serverTimingHeaders: vi.fn() })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) })); vi.mock("~/modules/helpDesk/services/Feedback.server", () => ({ default: { send: vi.fn() } })); vi.mock("~/stores/themePreviewStore", () => ({ useThemePreviewStore: vi.fn() })); vi.mock("~/utils/theme/ThemeConfig", () => ({ getThemeStyle: vi.fn(), parseThemeConfig: vi.fn() })); vi.mock("@toolctrl/config", async () => { const actual = await vi.importActual("@toolctrl/config"); return { ...actual, loadRequiredWebConfig: () => ({ routing: { protocol: "https", webAppHost: "app.example.test", adminAppHost: "admin.example.test", apiHost: "api.example.test", appBaseDomain: "example.test", }, }), }; }); import { getAuthUserWithoutPasswordById, getTenantMembershipByIds, updateAuthUserDefaultTenantId } from "@toolctrl/db/auth-boundary.server"; import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures"; import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType"; import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server"; import { ensureTenantUserAppRoles } from "~/utils/db/permissions/userRoles.db.server"; import { createUniqueTenantIpAddress } from "~/utils/db/tenants/tenantIpAddress.db.server"; import { loadAppData } from "~/utils/data/.server/appData"; import { getTenantIdFromUrl } from "~/utils/services/.server/urlService"; import { getUserInfo } from "~/utils/session.server"; import { getIsSuperAdminByUserId, requireAuth } from "~/utils/loaders.middleware"; import FeedbackServer from "~/modules/helpDesk/services/Feedback.server"; import { action, appTenantPlanRequiredPath, loader } from "./app.$tenant"; const tenantParams = { tenant: "acme" }; const adminUser = { id: "user_1", admin: true, defaultTenantId: "tenant_1" }; const tenantMembership = { tenantId: "tenant_1", userId: "user_1", type: 0 }; const baseData = { currentTenant: { id: "tenant_1", slug: "acme", deactivatedReason: null }, mySubscription: { products: [] }, }; function subscriptionProduct() { return { features: [ { order: 0, title: "API access", name: DefaultFeatures.API, type: SubscriptionFeatureLimitType.INCLUDED, value: 0, accumulate: false, }, ], }; } async function callLoader(pathname = "/acme/dashboard") { return loader({ request: new Request(`https://app.example.test${pathname}`), params: tenantParams, context: {}, unstable_pattern: "app.$tenant" } as LoaderFunctionArgs); } async function expectSubscriptionRedirect(promise: Promise) { try { await promise; throw new Error("Expected subscription redirect"); } catch (error) { const response = error as Response; expect(response.status).toBe(302); expect(response.headers.get("Location")).toBe(appTenantPlanRequiredPath(tenantParams)); expect(response.headers.get("Location")).not.toMatch(/\/app\/acme|tenant_1|user_1|customer|subscription id|secret|sk_/i); } } describe("app.$tenant subscription entitlement guard", () => { beforeEach(() => { vi.clearAllMocks(); vi.mocked(loadAppData).mockResolvedValue(baseData as never); vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1"); vi.mocked(getUserInfo).mockResolvedValue({ userId: "user_1" } as never); vi.mocked(requireAuth).mockResolvedValue({ userId: "user_1" } as never); vi.mocked(getAuthUserWithoutPasswordById).mockResolvedValue(adminUser as never); vi.mocked(getTenantMembershipByIds).mockResolvedValue(tenantMembership as never); vi.mocked(getIsSuperAdminByUserId).mockResolvedValue(false); vi.mocked(ensureTenantUserAppRoles).mockResolvedValue({ created: 0, roleCount: 1 }); vi.mocked(updateAuthUserDefaultTenantId).mockResolvedValue(undefined as never); vi.mocked(createUniqueTenantIpAddress).mockResolvedValue(undefined as never); vi.mocked(getAppConfiguration).mockResolvedValue({ subscription: { required: true } } as never); }); it("allows trial-active tenants without subscription products", async () => { vi.mocked(loadAppData).mockResolvedValue({ ...baseData, mySubscription: { products: [], trial: { active: true, period: "trial-day-7" } }, } as never); const response = await callLoader(); expect(response).toBeInstanceOf(Response); expect((response as Response).status).toBe(200); expect(ensureTenantUserAppRoles).toHaveBeenCalledWith({ userId: "user_1", tenantId: "tenant_1", tenantUserType: tenantMembership.type, }); expect(loadAppData).toHaveBeenCalledWith({ request: expect.any(Request), params: tenantParams, t: expect.any(Function), time: expect.any(Function), tenantId: "tenant_1", userInfo: { userId: "user_1" }, user: adminUser, }); }); it("denies expired trial access with a stable non-secret redirect reason", async () => { vi.mocked(loadAppData).mockResolvedValue({ ...baseData, mySubscription: { products: [], trial: { active: false, period: "trial-ended" } }, } as never); await expectSubscriptionRedirect(callLoader()); const redirectTarget = appTenantPlanRequiredPath(tenantParams); expect(redirectTarget).toBe("/plan-required/acme"); expect(redirectTarget).not.toMatch(/\/app\/acme|tenant_1|user_1|customer|subscription id|secret|sk_/i); }); it("denies access when subscription products and trial state are missing", async () => { vi.mocked(loadAppData).mockResolvedValue({ ...baseData, mySubscription: { products: [] } } as never); await expectSubscriptionRedirect(callLoader()); }); it("keeps settings paths exempt from subscription redirects", async () => { vi.mocked(loadAppData).mockResolvedValue({ ...baseData, mySubscription: { products: [], trial: { active: false, period: "trial-ended" } }, } as never); const response = await callLoader("/acme/settings/subscription"); expect(response).toBeInstanceOf(Response); expect((response as Response).status).toBe(200); expect(getAppConfiguration).not.toHaveBeenCalled(); }); it("allows subscribed tenants through the entitlement adapter", async () => { vi.mocked(loadAppData).mockResolvedValue({ ...baseData, mySubscription: { products: [subscriptionProduct()] } } as never); const response = await callLoader(); expect(response).toBeInstanceOf(Response); expect((response as Response).status).toBe(200); }); it("encodes deactivated tenant redirects as a single route segment", async () => { vi.mocked(loadAppData).mockResolvedValue({ ...baseData, currentTenant: { ...baseData.currentTenant, deactivatedReason: "billing" }, mySubscription: { products: [subscriptionProduct()] }, } as never); try { await loader({ request: new Request("https://app.example.test/acme%2Fwest/dashboard"), params: { tenant: "acme/west" }, context: {}, unstable_pattern: "app.$tenant", } as LoaderFunctionArgs); throw new Error("Expected deactivated redirect"); } catch (error) { expect(error).toBeInstanceOf(Response); expect((error as Response).status).toBe(302); expect((error as Response).headers.get("Location")).toBe("/deactivated/acme%2Fwest"); } }); it("redirects non-members before loading tenant app data", async () => { vi.mocked(getAuthUserWithoutPasswordById).mockResolvedValue({ ...adminUser, admin: null } as never); vi.mocked(getTenantMembershipByIds).mockResolvedValueOnce(null as never); try { await callLoader(); throw new Error("Expected membership redirect"); } catch (error) { expect(error).toBeInstanceOf(Response); expect((error as Response).status).toBe(302); } expect(getTenantMembershipByIds).toHaveBeenCalledWith("tenant_1", "user_1"); expect(ensureTenantUserAppRoles).not.toHaveBeenCalled(); expect(loadAppData).not.toHaveBeenCalled(); }); it("allows operator admins to load tenant app data without tenant membership", async () => { vi.mocked(getAuthUserWithoutPasswordById).mockResolvedValue({ ...adminUser, admin: true } as never); vi.mocked(getTenantMembershipByIds).mockResolvedValueOnce(null as never); vi.mocked(loadAppData).mockResolvedValue({ ...baseData, mySubscription: { products: [subscriptionProduct()] } } as never); const response = await callLoader(); expect(response).toBeInstanceOf(Response); expect((response as Response).status).toBe(200); expect(getTenantMembershipByIds).toHaveBeenCalledWith("tenant_1", "user_1"); expect(ensureTenantUserAppRoles).not.toHaveBeenCalled(); expect(updateAuthUserDefaultTenantId).not.toHaveBeenCalled(); expect(loadAppData).toHaveBeenCalled(); }); it("preserves unauthenticated deep links when redirecting to login", async () => { vi.mocked(getUserInfo).mockResolvedValueOnce({ userId: null } as never); try { await callLoader("/acme/g/sales/contacts/row_1?tab=activity"); throw new Error("Expected login redirect"); } catch (error) { expect(error).toBeInstanceOf(Response); expect((error as Response).status).toBe(302); expect((error as Response).headers.get("Location")).toBe("/login?redirectTo=%2Facme%2Fg%2Fsales%2Fcontacts%2Frow_1%3Ftab%3Dactivity"); } expect(getAuthUserWithoutPasswordById).not.toHaveBeenCalled(); expect(getTenantIdFromUrl).not.toHaveBeenCalled(); expect(loadAppData).not.toHaveBeenCalled(); }); }); describe("app.$tenant feedback action", () => { beforeEach(() => { vi.clearAllMocks(); vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1"); vi.mocked(requireAuth).mockResolvedValue({ userId: "user_1" } as never); }); it("derives feedback tenant from the route and ignores submitted tenant ids", async () => { const formData = new URLSearchParams(); formData.set("action", "add-feedback"); formData.set("message", "Tenant-scoped feedback"); formData.set("fromUrl", "/acme/dashboard"); formData.set("tenantId", "tenant_other"); const response = await action({ request: new Request("https://app.example.test/acme", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: formData, }), params: tenantParams, context: {}, unstable_pattern: "app.$tenant", } as ActionFunctionArgs); expect(response).toBeInstanceOf(Response); expect((response as Response).status).toBe(200); expect(requireAuth).toHaveBeenCalledWith({ request: expect.any(Request), params: tenantParams }); expect(getTenantIdFromUrl).toHaveBeenCalledWith(tenantParams); expect(FeedbackServer.send).toHaveBeenCalledWith( expect.objectContaining({ tenantId: "tenant_1", userId: "user_1", message: "Tenant-scoped feedback", fromUrl: "/acme/dashboard", }) ); expect(FeedbackServer.send).not.toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_other" })); }); });