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

679 lines
27 KiB
TypeScript

import { act, render, screen } from "@testing-library/react";
import { MemoryRouter, Route, Routes, useLocation, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/components/app/AppLayout", () => ({
default: vi.fn(({ children }: { children: React.ReactNode }) => <div data-ui-id="ui.test.appLayout">{children}</div>),
}));
vi.mock("~/components/screens/billing/SubscriptionStatusBanner", () => ({ SubscriptionStatusBanner: vi.fn(() => null) }));
vi.mock("~/application/sidebar/AppSidebar", () => ({ AppSidebar: vi.fn(() => []) }));
vi.mock("~/utils/data/useAppData", () => ({ useAppData: vi.fn() }));
vi.mock("~/utils/data/.server/appData", () => ({ loadAppData: vi.fn() }));
vi.mock("~/services/billing/registration-billing-preference.server", () => ({ loadTenantRegistrationBillingPreference: vi.fn() }));
vi.mock("@hivegrid/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", () => ({ 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", () => ({ getTrustedClientIpOrNull: vi.fn() }));
vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({
createMetrics: vi.fn(async () => ({
time: async <T,>(value: T | Promise<T>) => value,
getServerTimingHeader: () => ({ "Server-Timing": "test" }),
})),
}));
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({ serverTimingHeaders: vi.fn() }));
vi.mock("~/lib/metrics/ssr", () => ({ withMetrics: (_name: string, handler: unknown) => handler }));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
vi.mock("~/modules/helpDesk/services/Feedback.server", async (importOriginal) => ({
...(await importOriginal<typeof import("~/modules/helpDesk/services/Feedback.server")>()),
default: { send: vi.fn() },
}));
vi.mock("~/modules/helpDesk/services/SupportTickets.server", () => ({ default: { createInline: vi.fn() } }));
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" } }) }));
vi.mock("~/utils/services/.server/billingStatusService", () => ({
getTenantBillingReadOnlyState: vi.fn(async () => ({ readOnly: false, status: null })),
}));
vi.mock("@hivegrid/config", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/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 "@hivegrid/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 { SubscriptionStatusBanner } from "~/components/screens/billing/SubscriptionStatusBanner";
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 { loadTenantRegistrationBillingPreference } from "~/services/billing/registration-billing-preference.server";
import { useAppData } from "~/utils/data/useAppData";
import { useRootData } from "~/utils/data/useRootData";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
import { getUserInfo } from "~/utils/session.server";
import { requireAuth } from "~/utils/loaders.middleware";
import FeedbackServer from "~/modules/helpDesk/services/Feedback.server";
import { FeedbackUserError } from "~/modules/helpDesk/services/Feedback.server";
import SupportTicketsServer from "~/modules/helpDesk/services/SupportTickets.server";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import AppLayout from "~/components/app/AppLayout";
import AppTenantRoute, { action, appTenantPlanRequiredPath, loader, middleware } 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: [] },
billingBanner: { status: "empty" as const },
};
function subscriptionProduct(kind = "base_plan") {
return {
cancelledAt: null,
currentPeriodStart: new Date("2026-08-01T00:00:00.000Z"),
endsAt: null,
subscriptionProduct: {
kind,
features: [
{
order: 0,
title: "API access",
name: DefaultFeatures.API,
type: SubscriptionFeatureLimitType.INCLUDED,
value: 0,
accumulate: false,
},
],
},
};
}
function activeSubscription(products = [subscriptionProduct()]) {
return {
status: "active",
trialStartsAt: null,
trialEndsAt: null,
pastDueSince: null,
frozenAt: null,
cancelledAt: null,
products,
};
}
function trialSubscription(trialEndsAt: Date) {
return {
status: "trial",
trialStartsAt: new Date("2026-08-01T00:00:00.000Z"),
trialEndsAt,
pastDueSince: null,
frozenAt: null,
cancelledAt: null,
products: [],
};
}
function shellAppData(permissions: string[] = ["app.settings.subscription.view"]) {
return {
...baseData,
currentTenant: { ...baseData.currentTenant, theme: null, themeConfig: null },
mySubscription: activeSubscription(),
billingBanner: {
status: "ready" as const,
data: {
status: "frozen" as const,
tone: "danger" as const,
titleKey: "settings.subscription.banner.frozen.title",
descriptionKey: "settings.subscription.banner.frozen.description",
trialDaysRemaining: null,
readOnly: true,
},
},
productAccess: {},
permissions,
};
}
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<unknown>) {
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(loadTenantRegistrationBillingPreference).mockResolvedValue(null);
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(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: trialSubscription(new Date("2099-08-10T00:00:00.000Z")),
} 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,
isOperatorAdmin: false,
});
});
it("denies expired trial access with a stable non-secret redirect reason", async () => {
vi.mocked(loadAppData).mockResolvedValue({
...baseData,
mySubscription: trialSubscription(new Date("2020-08-03T12:00:00.000Z")),
} 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 a signup-selected tenant in activation when subscriptions are globally optional", async () => {
vi.mocked(getAppConfiguration).mockResolvedValue({ subscription: { required: false } } as never);
vi.mocked(loadTenantRegistrationBillingPreference).mockResolvedValue({
selectedSubscriptionPriceId: "price_swarm_monthly",
selectedOfficeSeatQuantity: 5,
selectedFieldSeatQuantity: 15,
});
await expectSubscriptionRedirect(callLoader("/acme/contacts"));
const response = await callLoader("/acme/settings/billing?subscription_required=1");
expect(response).toBeInstanceOf(Response);
expect(await (response as Response).json()).toMatchObject({ subscriptionActivationRequired: true });
});
it("allows only the exact billing activation path without subscription access", async () => {
vi.mocked(loadAppData).mockResolvedValue({
...baseData,
mySubscription: trialSubscription(new Date("2020-08-03T12:00:00.000Z")),
} as never);
const response = await callLoader("/acme/settings/billing");
expect(response).toBeInstanceOf(Response);
expect((response as Response).status).toBe(200);
expect(getAppConfiguration).toHaveBeenCalledOnce();
});
it("denies every other settings path without subscription access", async () => {
vi.mocked(loadAppData).mockResolvedValue({
...baseData,
mySubscription: trialSubscription(new Date("2020-08-03T12:00:00.000Z")),
} as never);
await expectSubscriptionRedirect(callLoader("/acme/settings/profile"));
await expectSubscriptionRedirect(callLoader("/acme/settings/billing/usage"));
});
it("allows subscribed tenants through the entitlement adapter", async () => {
vi.mocked(loadAppData).mockResolvedValue({ ...baseData, mySubscription: activeSubscription() } as never);
const response = await callLoader();
expect(response).toBeInstanceOf(Response);
expect((response as Response).status).toBe(200);
});
it.each(["past_due", "cancelled", "frozen"])("denies a %s subscription even when a base-plan product remains attached", async (status) => {
vi.mocked(loadAppData).mockResolvedValue({
...baseData,
mySubscription: { ...activeSubscription(), status },
} as never);
await expectSubscriptionRedirect(callLoader());
});
it("denies an active add-on-only subscription", async () => {
vi.mocked(loadAppData).mockResolvedValue({
...baseData,
mySubscription: activeSubscription([subscriptionProduct("recurring_add_on")]),
} as never);
await expectSubscriptionRedirect(callLoader());
});
it("returns the server-built billing banner in the app loader payload", async () => {
const billingBanner = {
status: "ready" as const,
data: {
status: "past_due" as const,
tone: "warning" as const,
titleKey: "settings.subscription.banner.pastDue.title",
descriptionKey: "settings.subscription.banner.pastDue.description",
trialDaysRemaining: null,
readOnly: true,
},
};
vi.mocked(loadAppData).mockResolvedValue({
...baseData,
mySubscription: activeSubscription(),
billingBanner,
} as never);
const response = (await callLoader()) as Response;
await expect(response.json()).resolves.toMatchObject({ billingBanner });
});
it("encodes deactivated tenant redirects as a single route segment", async () => {
vi.mocked(loadAppData).mockResolvedValue({
...baseData,
currentTenant: { ...baseData.currentTenant, deactivatedReason: "billing" },
mySubscription: activeSubscription(),
} 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("does not let AdminUser identity bypass 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);
await expect(callLoader()).rejects.toBeInstanceOf(Response);
expect(getTenantMembershipByIds).toHaveBeenCalledWith("tenant_1", "user_1");
expect(ensureTenantUserAppRoles).not.toHaveBeenCalled();
expect(loadAppData).not.toHaveBeenCalled();
});
it("does not let a platform SuperAdmin bypass tenant membership", async () => {
vi.mocked(getTenantMembershipByIds).mockResolvedValueOnce(null as never);
vi.mocked(loadAppData).mockResolvedValue({ ...baseData, mySubscription: { products: [subscriptionProduct()] } } as never);
await expect(callLoader()).rejects.toBeInstanceOf(Response);
expect(ensureTenantUserAppRoles).not.toHaveBeenCalled();
expect(updateAuthUserDefaultTenantId).not.toHaveBeenCalled();
expect(loadAppData).not.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 RLS middleware", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1");
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user_1" } as never);
vi.mocked(getTenantMembershipByIds).mockResolvedValue(tenantMembership as never);
});
it("binds the verified tenant before any child loader executes", async () => {
const next = vi.fn(async () => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1" });
return new Response("ok");
});
const response = await middleware[0]!(
{ request: new Request("https://app.example.test/acme/dashboard"), params: tenantParams } as never,
next,
);
expect(response).toBeInstanceOf(Response);
expect(next).toHaveBeenCalledOnce();
expect(getRlsExecutionContext()).toBeNull();
});
it("stops the middleware chain for a foreign tenant", async () => {
vi.mocked(getTenantMembershipByIds).mockResolvedValue(null);
const next = vi.fn(async () => new Response("should not run"));
await expect(
middleware[0]!(
{ request: new Request("https://app.example.test/foreign/dashboard"), params: { tenant: "foreign" } } as never,
next,
),
).rejects.toMatchObject({ status: 302 });
expect(next).not.toHaveBeenCalled();
});
});
function LocationProbe() {
return <span data-testid="location-probe">{useLocation().pathname}</span>;
}
function renderShellRoute(initialEntry = "/acme/dashboard") {
return render(
<MemoryRouter initialEntries={[initialEntry]}>
<LocationProbe />
<Routes>
<Route path="/:tenant/*" element={<AppTenantRoute />} />
</Routes>
</MemoryRouter>
);
}
describe("app.$tenant billing shell banner", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(useAppData).mockReturnValue(shellAppData() as never);
vi.mocked(useRootData).mockReturnValue({
appConfiguration: { subscription: { required: false } },
routing: {},
} as never);
});
it("injects canonical tenant subscription navigation into the shell component", () => {
renderShellRoute();
const bannerProps = vi.mocked(SubscriptionStatusBanner).mock.calls.at(-1)?.[0];
expect(bannerProps?.vm).toMatchObject({ status: "ready", data: { status: "frozen" } });
expect(bannerProps?.actions.onOpenSubscription).toEqual(expect.any(Function));
act(() => bannerProps?.actions.onOpenSubscription?.());
expect(screen.getByTestId("location-probe").textContent).toBe("/acme/settings/billing");
});
it("keeps the banner but omits its navigation action without view permission", () => {
vi.mocked(useAppData).mockReturnValue(shellAppData([]) as never);
renderShellRoute();
const bannerProps = vi.mocked(SubscriptionStatusBanner).mock.calls.at(-1)?.[0];
expect(bannerProps?.vm).toMatchObject({ status: "ready", data: { status: "frozen" } });
expect(bannerProps?.actions.onOpenSubscription).toBeUndefined();
});
it("renders first activation without the workspace layout or subscription banner", () => {
vi.mocked(useAppData).mockReturnValue({
...shellAppData(),
mySubscription: { status: "past_due", trialStartsAt: null, trialEndsAt: null, products: [] },
} as never);
vi.mocked(useRootData).mockReturnValue({
appConfiguration: { subscription: { required: true } },
routing: {},
} as never);
const { container } = renderShellRoute("/acme/settings/billing");
expect(container.querySelector('[data-ui-id="ui.billing.activation.shell"]')).not.toBeNull();
expect(AppLayout).not.toHaveBeenCalled();
expect(SubscriptionStatusBanner).not.toHaveBeenCalled();
});
it("renders persisted signup activation without relying on the global subscription flag", () => {
vi.mocked(useAppData).mockReturnValue({
...shellAppData(),
mySubscription: { status: "past_due", trialStartsAt: null, trialEndsAt: null, products: [] },
subscriptionActivationRequired: true,
} as never);
vi.mocked(useRootData).mockReturnValue({
appConfiguration: { subscription: { required: false } },
routing: {},
} as never);
const { container } = renderShellRoute("/acme/settings/billing?subscription_required=1");
expect(container.querySelector('[data-ui-id="ui.billing.activation.shell"]')).not.toBeNull();
expect(AppLayout).not.toHaveBeenCalled();
expect(SubscriptionStatusBanner).not.toHaveBeenCalled();
});
it("renders the paid welcome route as a focused setup surface without the workspace layout", () => {
const { container } = renderShellRoute("/acme/onboarding/welcome");
expect(container.querySelector('[data-ui-id="ui.onboarding.welcome.shell"]')).not.toBeNull();
expect(AppLayout).not.toHaveBeenCalled();
expect(SubscriptionStatusBanner).not.toHaveBeenCalled();
});
});
describe("app.$tenant feedback action", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1");
vi.mocked(getTenantBillingReadOnlyState).mockResolvedValue({ readOnly: false, status: null });
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.toString(),
}),
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" }));
});
it("blocks tenant feedback mutations while billing is read-only", async () => {
vi.mocked(getTenantBillingReadOnlyState).mockResolvedValue({ readOnly: true, status: "frozen" });
const formData = new URLSearchParams();
formData.set("action", "add-feedback");
formData.set("message", "Tenant-scoped feedback");
formData.set("fromUrl", "/acme/dashboard");
const response = await action({
request: new Request("https://app.example.test/acme", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: formData.toString(),
}),
params: tenantParams,
context: {},
unstable_pattern: "app.$tenant",
} as ActionFunctionArgs);
expect(response).toBeInstanceOf(Response);
expect((response as Response).status).toBe(423);
await expect((response as Response).json()).resolves.toEqual({ error: "billing:status.readOnly" });
expect(FeedbackServer.send).not.toHaveBeenCalled();
});
it("keeps expected rate-limit feedback actionable", async () => {
vi.mocked(FeedbackServer.send).mockRejectedValueOnce(new FeedbackUserError("feedback.limitReached", 429));
const formData = new URLSearchParams({
action: "add-feedback",
message: "Tenant-scoped feedback",
fromUrl: "/acme/dashboard",
});
const response = (await action({
request: new Request("https://app.example.test/acme", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: formData.toString(),
}),
params: tenantParams,
context: {},
unstable_pattern: "app.$tenant",
} as ActionFunctionArgs)) as Response;
expect(response.status).toBe(429);
await expect(response.json()).resolves.toEqual({ error: "feedback.limitReached" });
});
it("does not disclose unexpected feedback service errors", async () => {
vi.mocked(FeedbackServer.send).mockRejectedValueOnce(new Error("database password rejected at internal-host"));
const formData = new URLSearchParams({
action: "add-feedback",
message: "Tenant-scoped feedback",
fromUrl: "/acme/dashboard",
});
const response = (await action({
request: new Request("https://app.example.test/acme", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: formData.toString(),
}),
params: tenantParams,
context: {},
unstable_pattern: "app.$tenant",
} as ActionFunctionArgs)) as Response;
expect(response.status).toBe(503);
await expect(response.json()).resolves.toEqual({ error: "feedback.unavailable" });
});
it("validates support text and hides unexpected support service errors", async () => {
const emptyForm = new URLSearchParams({ action: "create-support-ticket", message: " " });
const emptyResponse = (await action({
request: new Request("https://app.example.test/acme", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: emptyForm.toString(),
}),
params: tenantParams,
context: {},
unstable_pattern: "app.$tenant",
} as ActionFunctionArgs)) as Response;
expect(emptyResponse.status).toBe(400);
await expect(emptyResponse.json()).resolves.toEqual({ error: "feedback.messageRequired" });
expect(SupportTicketsServer.createInline).not.toHaveBeenCalled();
vi.mocked(SupportTicketsServer.createInline).mockRejectedValueOnce(new Error("queue token leaked"));
const validForm = new URLSearchParams({ action: "create-support-ticket", message: "Bitte helfen" });
const failureResponse = (await action({
request: new Request("https://app.example.test/acme", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: validForm.toString(),
}),
params: tenantParams,
context: {},
unstable_pattern: "app.$tenant",
} as ActionFunctionArgs)) as Response;
expect(failureResponse.status).toBe(503);
await expect(failureResponse.json()).resolves.toEqual({ error: "feedback.unavailable" });
});
});