Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1 @@
export { default, ErrorBoundary, loader } from "../../integrations.$app.$connectionId.syncs.$runId";
@@ -0,0 +1 @@
export { default, ErrorBoundary, loader } from "../../integrations.$app.$connectionId.syncs._index";
@@ -0,0 +1 @@
export { action, default, ErrorBoundary, loader } from "../../integrations.$app._index";
@@ -0,0 +1 @@
export { default, ErrorBoundary, handle, loader } from "../../integrations._index";
@@ -0,0 +1,55 @@
import type { LoaderFunctionArgs } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/modules/api/services/ApiKeyLogService", () => ({
default: {
getSummary: vi.fn(async () => ({ items: [], filterableProperties: [] })),
},
}));
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
getAppConfiguration: vi.fn(async () => ({ app: { features: { tenantApiKeys: true } } })),
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn(async () => undefined) }));
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn(async () => "tenant-1") }));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({
t: (key: string) => (key === "settings.api.errors.tenantApiKeysNotEnabled" ? "API keys are not enabled" : key),
})),
}));
import ApiKeyLogService from "~/modules/api/services/ApiKeyLogService";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { loader } from "./index";
describe("tenant API settings overview route", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
vi.mocked(getAppConfiguration).mockResolvedValue({ app: { features: { tenantApiKeys: true } } } as never);
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
});
it("checks tenant permission and feature gate before loading API key logs", async () => {
const request = new Request("https://app.example.com/acme/settings/api");
const data = await loader({ request, params: { tenant: "acme" }, context: {} } as unknown as LoaderFunctionArgs);
expect(getTenantIdFromUrl).toHaveBeenCalledWith({ tenant: "acme" });
expect(verifyUserHasPermission).toHaveBeenCalledWith(request, "app.settings.apiKeys.view", "tenant-1");
expect(ApiKeyLogService.getSummary).toHaveBeenCalledWith({ request, params: { tenant: "acme" } });
expect(data).toMatchObject({ items: [], filterableProperties: [] });
});
it("returns an i18n key when tenant API keys are disabled", async () => {
vi.mocked(getAppConfiguration).mockResolvedValue({ app: { features: { tenantApiKeys: false } } } as never);
const response = await loader({ request: new Request("https://app.example.com/acme/settings/api"), params: { tenant: "acme" }, context: {} } as never);
expect(response).toBeInstanceOf(Response);
expect((response as Response).status).toBe(400);
await expect((response as Response).json()).resolves.toEqual({ error: "settings.api.errors.tenantApiKeysNotEnabled" });
expect(ApiKeyLogService.getSummary).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,141 @@
import { LoaderFunctionArgs, useLoaderData, useSearchParams } from "react-router";
import { Link, useParams } from "react-router";
import { Fragment } from "react";
import { useTranslation } from "react-i18next";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import ErrorBanner from "~/components/ui/banners/ErrorBanner";
import ServerError from "~/components/ui/errors/ServerError";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import Tabs from "~/components/ui/tabs/Tabs";
import { ApiSummaryPage, GROUP_BY_KEYS, type GroupByKey } from "~/components/screens/api/ApiSummaryPage";
import ApiKeyLogUtils from "~/modules/api/utils/ApiKeyLogUtils";
import { ApiCallSummaryDto } from "~/modules/api/dtos/ApiCallSummaryDto";
import ApiKeyLogService from "~/modules/api/services/ApiKeyLogService";
import UrlUtils from "~/utils/app/UrlUtils";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
type LoaderData =
| { error: string }
| {
items: ApiCallSummaryDto[];
allTenants: { id: string; name: string }[];
filterableProperties: FilterablePropertyDto[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.apiKeys.view", tenantId);
try {
const appConfiguration = await getAppConfiguration({ request });
if (!appConfiguration.app.features.tenantApiKeys) {
return Response.json({ error: "settings.api.errors.tenantApiKeysNotEnabled" }, { status: 400 });
}
const { items, filterableProperties } = await ApiKeyLogService.getSummary({ request, params });
const data: LoaderData = {
items,
allTenants: [],
filterableProperties,
};
return data;
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
return Response.json({ error: "shared.unexpectedError" }, { status: 400 });
}
};
export default function () {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const params = useParams();
const [searchParams, setSearchParams] = useSearchParams();
// Grouping and filtering are resolved in the loader, so the controls write
// query parameters. groupBy repeats, every filter is a single parameter.
const groupBy = ApiKeyLogUtils.getGroupByValues(searchParams).filter((value): value is GroupByKey =>
(GROUP_BY_KEYS as readonly string[]).includes(value)
);
function toggleGroupBy(key: GroupByKey) {
const next = new URLSearchParams(searchParams);
const selected = groupBy.includes(key) ? groupBy.filter((value) => value !== key) : [...groupBy, key];
next.delete("groupBy");
selected.forEach((value) => next.append("groupBy", value));
setSearchParams(next);
}
function setProperty(name: string, value: string | null) {
const next = new URLSearchParams(searchParams);
if (value === null || value === "") next.delete(name);
else next.set(name, value);
setSearchParams(next);
}
/** Row link into the calls tab, carrying this group's values as filters. */
function detailHrefFor(item: ApiCallSummaryDto) {
const target = new URLSearchParams();
groupBy.forEach((key) => {
if (key === "status") target.append("status", item.status?.toString() ?? "null");
else target.append(key, item[key]);
});
return `${UrlUtils.currentTenantUrl(params, "settings/integrations/api/logs")}?${target.toString()}`;
}
return (
<>
{/* AK-SET-01: the Erweiterungen hub owns the page header. */}
<EditPageLayout fullWidth>
{/* Tabs render inside the children so the layout does not emit its own (empty) page heading. */}
<Tabs
tabs={[
{
name: t("shared.overview"),
routePath: UrlUtils.currentTenantUrl(params, "settings/integrations/api"),
},
{
name: t("models.apiCall.plural"),
routePath: UrlUtils.currentTenantUrl(params, "settings/integrations/api/logs"),
},
{
name: t("models.apiKey.plural"),
routePath: UrlUtils.currentTenantUrl(params, "settings/integrations/api/keys"),
},
]}
/>
{"error" in data ? (
<ErrorBanner title={t(data.error)}>
<Link to="." className="underline">
{t("shared.clickHereToTryAgain")}
</Link>
</ErrorBanner>
) : (
<Fragment>
<ApiSummaryPage
items={data.items}
properties={data.filterableProperties}
groupBy={groupBy}
search={searchParams.get("q") ?? ""}
detailHrefFor={detailHrefFor}
actions={{
onSearchChange: (value) => setProperty("q", value),
onToggleProperty: (name, value) => setProperty(name, searchParams.get(name) === value ? null : value),
onToggleGroupBy: toggleGroupBy,
onReset: () => {
const next = new URLSearchParams(searchParams);
next.delete("q");
data.filterableProperties.forEach((property) => next.delete(property.name));
setSearchParams(next);
},
}}
/>
</Fragment>
)}
</EditPageLayout>
</>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
@@ -0,0 +1,49 @@
import { LoaderFunctionArgs, Outlet, useLoaderData, useParams } from "react-router";
import { useTranslation } from "react-i18next";
import ApiKeysTable from "~/components/core/apiKeys/ApiKeysTable";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import Tabs from "~/components/ui/tabs/Tabs";
import UrlUtils from "~/utils/app/UrlUtils";
import { useAppData } from "~/utils/data/useAppData";
import { RedactedApiKeyWithDetails, getApiKeys } from "~/utils/db/apiKeys.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
type LoaderData = {
apiKeys: RedactedApiKeyWithDetails[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.apiKeys.view", tenantId);
const data: LoaderData = {
apiKeys: await getApiKeys(tenantId),
};
return data;
};
export default function ApiKeysRoute() {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const appData = useAppData();
const params = useParams();
return (
<>
{/* AK-SET-01: the Erweiterungen hub owns the page header. */}
<EditPageLayout fullWidth>
{/* Tabs render inside the children so the layout does not emit its own (empty) page heading. */}
<Tabs
tabs={[
{ name: t("shared.overview"), routePath: UrlUtils.currentTenantUrl(params, "settings/integrations/api") },
{ name: t("models.apiCall.plural"), routePath: UrlUtils.currentTenantUrl(params, "settings/integrations/api/logs") },
{ name: t("models.apiKey.plural"), routePath: UrlUtils.currentTenantUrl(params, "settings/integrations/api/keys") },
]}
/>
<ApiKeysTable canCreate={getUserHasPermission(appData, "app.settings.apiKeys.create")} items={data.apiKeys} />
<Outlet />
</EditPageLayout>
</>
);
}
@@ -0,0 +1,213 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ActionFunctionArgs } from "react-router";
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(),
}));
vi.mock("~/utils/services/.server/urlService", () => ({
getTenantIdFromUrl: vi.fn(),
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
verifyUserHasPermission: vi.fn(),
}));
vi.mock("~/utils/session.server", () => ({
getUserInfo: vi.fn(),
validateCSRFToken: vi.fn(),
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
getTenant: vi.fn(),
}));
vi.mock("~/utils/db/users.db.server", () => ({
getUser: vi.fn(),
}));
vi.mock("~/utils/db/apiKeys.db.server", () => ({
countApiKeyLogsForKey: vi.fn(),
deleteApiKey: vi.fn(),
getApiKeys: vi.fn(),
getTenantApiKeyById: vi.fn(),
rotateApiKey: vi.fn(),
updateApiKey: vi.fn(),
}));
vi.mock("~/utils/db/logs.db.server", () => ({
createLog: vi.fn(),
}));
vi.mock("~/modules/events/services/.server/EventsService", () => ({
default: { create: vi.fn() },
}));
vi.mock("~/utils/app/UrlUtils", () => ({
default: { currentTenantUrl: vi.fn((_params: Record<string, string | undefined>, path: string) => `/acme/${path}`) },
}));
vi.mock("~/components/core/apiKeys/ApiKeyCreatedModal", () => ({ default: () => null }));
vi.mock("~/components/core/apiKeys/ApiKeyForm", () => ({ default: () => null }));
vi.mock("~/components/ui/modals/OpenModal", () => ({ default: ({ children }: { children: React.ReactNode }) => children }));
vi.mock("~/utils/data/useAppData", () => ({ useAppData: () => ({ entities: [] }) }));
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn(() => true) }));
import EventsService from "~/modules/events/services/.server/EventsService";
import { getTranslations } from "~/locale/i18next.server";
import { countApiKeyLogsForKey, deleteApiKey, getApiKeys, getTenantApiKeyById, rotateApiKey, updateApiKey } from "~/utils/db/apiKeys.db.server";
import { createLog } from "~/utils/db/logs.db.server";
import { getTenant } from "~/utils/db/tenants.db.server";
import { getUser } from "~/utils/db/users.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { action } from "./$id";
const params = { tenant: "acme", id: "api-key-1" };
const tenant = { id: "tenant-1", name: "Acme", slug: "acme" };
const user = { id: "user-1", email: "ada@example.test" };
const existingApiKey = {
id: "api-key-1",
tenantId: "tenant-1",
alias: "Primary integration",
expires: null,
active: true,
};
const rotatedApiKey = { ...existingApiKey, key: "tc_live_rotated_plaintext_once" };
function createRequest(form: FormData) {
return new Request("https://app.example.test/acme/settings/api/keys/api-key-1", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(form as unknown as Record<string, string>),
});
}
function createForm(actionName: "edit" | "delete" | "rotate" = "edit", overrides: Record<string, string> = {}) {
const form = new FormData();
form.set("action", actionName);
form.set("alias", "Primary integration updated");
form.set("active", "on");
Object.entries(overrides).forEach(([key, value]) => form.set(key, value));
return form;
}
async function callAction(form: FormData) {
return action({
request: createRequest(form),
params,
context: {},
unstable_pattern: "app.$tenant/settings/api/keys/$id",
} as ActionFunctionArgs) as Promise<Response>;
}
async function responseJson(response: Response) {
return response.json() as Promise<Record<string, unknown>>;
}
describe("tenant API key edit route", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user-1" } as never);
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
vi.mocked(getTenant).mockResolvedValue(tenant as never);
vi.mocked(getUser).mockResolvedValue(user as never);
vi.mocked(getTenantApiKeyById).mockResolvedValue(existingApiKey as never);
vi.mocked(getApiKeys).mockResolvedValue([existingApiKey] as never);
vi.mocked(updateApiKey).mockResolvedValue({ ...existingApiKey, alias: "Primary integration updated" } as never);
vi.mocked(rotateApiKey).mockResolvedValue(rotatedApiKey as never);
vi.mocked(deleteApiKey).mockResolvedValue(existingApiKey as never);
vi.mocked(countApiKeyLogsForKey).mockResolvedValue(0 as never);
vi.mocked(EventsService.create).mockResolvedValue(undefined as never);
vi.mocked(createLog).mockResolvedValue({} as never);
});
it("rejects keys outside the tenant scope before update, rotation, or delete", async () => {
vi.mocked(getTenantApiKeyById).mockResolvedValue(null as never);
for (const actionName of ["edit", "rotate", "delete"] as const) {
const response = await callAction(createForm(actionName));
const data = await responseJson(response);
expect(response.status).toBe(400);
expect(data).toEqual({ error: "translated:shared.notFound" });
}
expect(updateApiKey).not.toHaveBeenCalled();
expect(rotateApiKey).not.toHaveBeenCalled();
expect(deleteApiKey).not.toHaveBeenCalled();
});
it("returns one-time plaintext only after successful rotation", async () => {
const response = await callAction(createForm("rotate"));
const data = await responseJson(response);
expect(response.status).toBe(200);
expect(data).toEqual({ apiKey: { key: rotatedApiKey.key, alias: rotatedApiKey.alias } });
expect(rotateApiKey).toHaveBeenCalledWith("api-key-1", "tenant-1");
expect(createLog).toHaveBeenCalledWith(
expect.any(Request),
"tenant-1",
"settings.apiKeys.rotated",
expect.stringContaining('"alias":"Primary integration"')
);
expect(updateApiKey).not.toHaveBeenCalled();
expect(deleteApiKey).not.toHaveBeenCalled();
});
it("checks delete permission only for delete actions", async () => {
await callAction(createForm("edit"));
await callAction(createForm("rotate"));
await callAction(createForm("delete"));
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.apiKeys.update", "tenant-1");
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.apiKeys.delete", "tenant-1");
expect(vi.mocked(verifyUserHasPermission).mock.calls.filter((call) => call[1] === "app.settings.apiKeys.delete")).toHaveLength(1);
});
it("checks delete permission before probing delete usage logs", async () => {
vi.mocked(verifyUserHasPermission).mockImplementation(async (_request, permission) => {
if (permission === "app.settings.apiKeys.delete") {
throw new Response("Forbidden", { status: 403 });
}
return true;
});
await expect(callAction(createForm("delete"))).rejects.toMatchObject({ status: 403 });
expect(countApiKeyLogsForKey).not.toHaveBeenCalled();
expect(deleteApiKey).not.toHaveBeenCalled();
});
it("scopes delete usage-log checks to the current tenant", async () => {
const response = await callAction(createForm("delete"));
expect(response.status).toBe(302);
expect(countApiKeyLogsForKey).toHaveBeenCalledWith("api-key-1", "tenant-1");
expect(deleteApiKey).toHaveBeenCalledWith("api-key-1", "tenant-1");
expect(createLog).toHaveBeenCalledWith(expect.any(Request), "tenant-1", "settings.apiKeys.deleted", "");
});
it("preserves edited details in logs and events", async () => {
const response = await callAction(createForm("edit", { alias: "Primary integration updated" }));
expect(response.status).toBe(302);
expect(updateApiKey).toHaveBeenCalledWith("api-key-1", {
tenantId: "tenant-1",
alias: "Primary integration updated",
expires: null,
active: true,
});
expect(createLog).toHaveBeenCalledWith(
expect.any(Request),
"tenant-1",
"settings.apiKeys.updated",
expect.stringContaining('"alias":"Primary integration updated"')
);
expect(createLog).toHaveBeenCalledTimes(1);
expect(EventsService.create).toHaveBeenCalledWith(
expect.objectContaining({
event: "api_key.updated",
data: expect.objectContaining({
new: expect.objectContaining({ alias: "Primary integration updated", active: true }),
old: expect.objectContaining({ alias: "Primary integration" }),
}),
})
);
});
});
@@ -0,0 +1,225 @@
import { ActionFunction, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
import { useNavigate, useNavigation, useParams, useSubmit } from "react-router";
import { ApiKeyCreatedDialog } from "~/components/screens/api/ApiKeyNewDialog";
import { ApiKeyEditDialog, type ApiKeyEditInput } from "~/components/screens/api/ApiKeyEditDialog";
import { useRootData } from "~/utils/data/useRootData";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { useAppData } from "~/utils/data/useAppData";
import {
RedactedApiKeyWithDetails,
countApiKeyLogsForKey,
deleteApiKey,
getApiKeys,
getTenantApiKeyById,
rotateApiKey,
updateApiKey,
} from "~/utils/db/apiKeys.db.server";
import { createLog } from "~/utils/db/logs.db.server";
import { getUser } from "~/utils/db/users.db.server";
import EventsService from "~/modules/events/services/.server/EventsService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { ApiKeyUpdatedDto } from "~/modules/events/dtos/ApiKeyUpdatedDto";
import { getTenant } from "~/utils/db/tenants.db.server";
import { ApiKeyDeletedDto } from "~/modules/events/dtos/ApiKeyDeletedDto";
type LoaderData = {
item: RedactedApiKeyWithDetails;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.apiKeys.update", tenantId);
const item = await getTenantApiKeyById(params.id ?? "", tenantId);
if (!item) {
return redirect(UrlUtils.currentTenantUrl(params, "settings/integrations/api/keys"));
}
const data: LoaderData = {
item,
};
return data;
};
type ActionData = {
error?: string;
apiKey?: {
key: string;
alias: string;
};
};
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
export const action: ActionFunction = async ({ request, params }) => {
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
const userInfo = await getUserInfo(request);
const currentUser = await getUser(userInfo.userId);
const tenant = await getTenant(tenantId);
if (!tenant || !currentUser) {
return badRequest({ error: t("shared.notFound") });
}
await verifyUserHasPermission(request, "app.settings.apiKeys.update", tenantId);
await validateCSRFToken(request);
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
const existing = await getTenantApiKeyById(params.id ?? "", tenantId);
if (!existing) {
return badRequest({ error: t("shared.notFound") });
}
if (action === "edit") {
let expirationDate: Date | null = null;
let expires = form.get("expires")?.toString();
if (expires) {
expirationDate = new Date(expires);
}
const alias = form.get("alias")?.toString() ?? "";
const existingAlias = await getApiKeys(existing.tenantId);
if (existingAlias.filter((f) => f.id !== existing.id && f.alias === alias).length > 0) {
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
}
const active = Boolean(form.get("active"));
await updateApiKey(params.id ?? "", {
tenantId: tenantId,
alias,
expires: expirationDate,
active,
});
await createLog(request, tenantId, "settings.apiKeys.updated", JSON.stringify({ tenantId, alias, expirationDate, active }));
await EventsService.create({
request,
event: "api_key.updated",
tenantId: tenant.id,
userId: currentUser.id,
data: {
id: existing.id,
new: {
alias: alias,
expires: expirationDate,
active: active,
},
old: {
alias: existing.alias,
expires: existing.expires,
active: existing.active,
},
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
} satisfies ApiKeyUpdatedDto,
});
return redirect(
`${UrlUtils.currentTenantUrl(params, "settings/integrations/api/keys")}?toast=${encodeURIComponent("models.apiKey.toast.saved")}`
);
} else if (action === "rotate") {
const apiKey = await rotateApiKey(existing.id, tenantId);
await createLog(request, tenantId, "settings.apiKeys.rotated", JSON.stringify({ tenantId, alias: existing.alias }));
await EventsService.create({
request,
event: "api_key.updated",
tenantId: tenant.id,
userId: currentUser.id,
data: {
id: existing.id,
new: {
alias: existing.alias,
expires: existing.expires,
active: existing.active,
},
old: {
alias: existing.alias,
expires: existing.expires,
active: existing.active,
},
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
} satisfies ApiKeyUpdatedDto,
});
return Response.json({ apiKey: { key: apiKey.key, alias: apiKey.alias } } satisfies ActionData);
} else if (action === "delete") {
await verifyUserHasPermission(request, "app.settings.apiKeys.delete", tenantId);
const logs = await countApiKeyLogsForKey(params.id ?? "", tenantId);
if (logs > 0) {
return badRequest({ error: t("models.apiKey.errors.cannotDeleteUsed") });
}
await deleteApiKey(params.id ?? "", tenantId);
await createLog(request, tenantId, "settings.apiKeys.deleted", "");
await EventsService.create({
request,
event: "api_key.deleted",
tenantId: tenant.id,
userId: currentUser.id,
data: {
id: existing.id,
alias: existing.alias,
expires: existing.expires,
active: existing.active,
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
} satisfies ApiKeyDeletedDto,
});
return redirect(
`${UrlUtils.currentTenantUrl(params, "settings/integrations/api/keys")}?toast=${encodeURIComponent("models.apiKey.toast.deleted")}`
);
} else {
return badRequest({ error: t("shared.invalidForm") });
}
};
/** Redacted key for the dialog subtitle — the raw secret never reaches the client. */
function redactedKey(item: RedactedApiKeyWithDetails): string {
return [item.keyPrefix, item.keyLastFour ? `••••${item.keyLastFour}` : undefined].filter(Boolean).join("…") || "••••";
}
/** <input type="date"> wants yyyy-mm-dd, the row carries a Date. */
function isoDate(value: Date | string | null): string {
if (!value) return "";
const date = value instanceof Date ? value : new Date(value);
return Number.isNaN(date.getTime()) ? "" : date.toISOString().slice(0, 10);
}
export default function ApiEditKeyRoute() {
const data = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const navigate = useNavigate();
const navigation = useNavigation();
const submit = useSubmit();
const appData = useAppData();
const params = useParams();
const { csrf } = useRootData();
const listPath = UrlUtils.currentTenantUrl(params, "settings/integrations/api/keys");
const closeToList = () => navigate(listPath);
// Rotating answers with the new raw key instead of redirecting, so the edit
// dialog gives way to the one-time reveal.
if (actionData?.apiKey) {
return <ApiKeyCreatedDialog apiKey={actionData.apiKey} action="rotated" onClose={closeToList} />;
}
function post(action: string, fields: Record<string, string> = {}) {
const form = new FormData();
form.set("action", action);
for (const [key, value] of Object.entries(fields)) form.set(key, value);
if (csrf) form.set("csrf", csrf);
submit(form, { method: "post" });
}
return (
<ApiKeyEditDialog
data={{
redactedKey: redactedKey(data.item),
alias: data.item.alias,
expires: isoDate(data.item.expires),
active: data.item.active,
canUpdate: getUserHasPermission(appData, "app.settings.apiKeys.update"),
canDelete: getUserHasPermission(appData, "app.settings.apiKeys.delete"),
canRotate: getUserHasPermission(appData, "app.settings.apiKeys.update"),
}}
submitting={navigation.state === "submitting"}
errorMessage={actionData?.error ?? null}
onSave={(input: ApiKeyEditInput) =>
post("edit", { alias: input.alias, ...(input.expires ? { expires: input.expires } : {}), ...(input.active ? { active: "true" } : {}) })
}
onRotate={() => post("rotate")}
onDelete={() => post("delete")}
onClose={closeToList}
/>
);
}
@@ -0,0 +1,169 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ActionFunctionArgs } from "react-router";
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(),
}));
vi.mock("~/utils/services/.server/urlService", () => ({
getTenantIdFromUrl: vi.fn(),
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
verifyUserHasPermission: vi.fn(),
}));
vi.mock("~/utils/session.server", () => ({
getUserInfo: vi.fn(),
validateCSRFToken: vi.fn(),
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
getTenant: vi.fn(),
}));
vi.mock("~/utils/db/users.db.server", () => ({
getUser: vi.fn(),
}));
vi.mock("~/utils/db/apiKeys.db.server", () => ({
createApiKey: vi.fn(),
getApiKeyByAlias: vi.fn(),
}));
vi.mock("~/utils/db/logs.db.server", () => ({
createLog: vi.fn(),
}));
vi.mock("~/utils/helpers/.server/ApiKeyHelperService", () => ({
getApiKeyEntityPermissions: vi.fn(),
}));
vi.mock("~/modules/events/services/.server/EventsService", () => ({
default: { create: vi.fn() },
}));
vi.mock("~/utils/app/UrlUtils", () => ({
default: { currentTenantUrl: vi.fn((_params: Record<string, string | undefined>, path: string) => `/acme/${path}`) },
}));
vi.mock("~/components/core/apiKeys/ApiKeyCreatedModal", () => ({ default: () => null }));
vi.mock("~/components/core/apiKeys/ApiKeyForm", () => ({ default: () => null }));
vi.mock("~/components/ui/modals/OpenModal", () => ({ default: ({ children }: { children: React.ReactNode }) => children }));
vi.mock("~/utils/data/useAppData", () => ({ useAppData: () => ({ entities: [] }) }));
import EventsService from "~/modules/events/services/.server/EventsService";
import { getTranslations } from "~/locale/i18next.server";
import { createApiKey, getApiKeyByAlias } from "~/utils/db/apiKeys.db.server";
import { createLog } from "~/utils/db/logs.db.server";
import { getTenant } from "~/utils/db/tenants.db.server";
import { getUser } from "~/utils/db/users.db.server";
import { getApiKeyEntityPermissions } from "~/utils/helpers/.server/ApiKeyHelperService";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { action } from "./new";
const params = { tenant: "acme" };
const tenant = { id: "tenant-1", name: "Acme", slug: "acme" };
const user = { id: "user-1", email: "ada@example.test" };
const apiKey = {
id: "api-key-1",
alias: "Primary integration",
key: "tc_live_plaintext_secret_once",
active: true,
};
const entityPermission = { entityId: "entity-1", create: true, read: true, update: false, delete: false };
function createRequest(form: FormData) {
return new Request("https://app.example.test/acme/settings/api/keys/new", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(form as unknown as Record<string, string>),
});
}
function createForm(overrides: Record<string, string> = {}) {
const form = new FormData();
form.set("action", "create");
form.set("alias", "Primary integration");
form.set("active", "on");
form.append("entities[]", JSON.stringify(entityPermission));
Object.entries(overrides).forEach(([key, value]) => form.set(key, value));
return form;
}
async function callAction(form: FormData) {
return action({
request: createRequest(form),
params,
context: {},
unstable_pattern: "app.$tenant/settings/api/keys/new",
} as ActionFunctionArgs) as Promise<Response>;
}
async function responseJson(response: Response) {
return response.json() as Promise<Record<string, unknown>>;
}
describe("tenant API key create route", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getTranslations).mockResolvedValue({
t: (key: string, values?: Record<string, unknown>) =>
key === "models.apiKey.errors.aliasExists" ? `API key with this alias already exists: ${values?.alias}` : `translated:${key}`,
} as never);
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user-1" } as never);
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
vi.mocked(getTenant).mockResolvedValue(tenant as never);
vi.mocked(getUser).mockResolvedValue(user as never);
vi.mocked(getApiKeyByAlias).mockResolvedValue(null as never);
vi.mocked(createApiKey).mockResolvedValue(apiKey as never);
vi.mocked(getApiKeyEntityPermissions).mockResolvedValue([entityPermission] as never);
vi.mocked(EventsService.create).mockResolvedValue(undefined as never);
vi.mocked(createLog).mockResolvedValue({} as never);
});
it("checks create permission before creating a key", async () => {
const response = await callAction(createForm());
expect(response.status).toBe(200);
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.apiKeys.create", "tenant-1");
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(createApiKey).mock.invocationCallOrder[0]);
});
it("returns one-time plaintext only in successful create action JSON", async () => {
const response = await callAction(createForm());
const data = await responseJson(response);
expect(response.status).toBe(200);
expect(data).toEqual({ apiKey: { key: apiKey.key, alias: apiKey.alias } });
expect(createApiKey).toHaveBeenCalledTimes(1);
expect(EventsService.create).toHaveBeenCalledTimes(1);
expect(createLog).toHaveBeenCalledWith(
expect.any(Request),
"tenant-1",
"settings.apiKeys.created",
expect.stringContaining('"alias":"Primary integration"')
);
expect(createLog).toHaveBeenCalledTimes(1);
});
it("rejects duplicate aliases without creating or leaking generated key material", async () => {
vi.mocked(getApiKeyByAlias).mockResolvedValueOnce({ id: "existing-key", alias: "Primary integration" } as never);
const response = await callAction(createForm());
const data = await responseJson(response);
expect(response.status).toBe(400);
expect(data).toEqual({ error: "API key with this alias already exists: Primary integration" });
expect(JSON.stringify(data)).not.toContain(apiKey.key);
expect(createApiKey).not.toHaveBeenCalled();
expect(EventsService.create).not.toHaveBeenCalled();
expect(createLog).not.toHaveBeenCalled();
});
it("rejects invalid actions without creating or leaking generated key material", async () => {
const response = await callAction(createForm({ action: "rotate" }));
const data = await responseJson(response);
expect(response.status).toBe(400);
expect(data).toEqual({ error: "translated:shared.invalidForm" });
expect(JSON.stringify(data)).not.toContain(apiKey.key);
expect(createApiKey).not.toHaveBeenCalled();
expect(EventsService.create).not.toHaveBeenCalled();
expect(createLog).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,123 @@
import { ActionFunction, LoaderFunctionArgs } from "react-router";
import { useActionData, useNavigate, useNavigation, useParams, useSubmit } from "react-router";
import { ApiKeyCreatedDialog, ApiKeyNewDialog, type ApiKeyNewInput } from "~/components/screens/api/ApiKeyNewDialog";
import { useRootData } from "~/utils/data/useRootData";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { createApiKey, getApiKeyByAlias } from "~/utils/db/apiKeys.db.server";
import { createLog } from "~/utils/db/logs.db.server";
import { getUser } from "~/utils/db/users.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import EventsService from "~/modules/events/services/.server/EventsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { ApiKeyCreatedDto } from "~/modules/events/dtos/ApiKeyCreatedDto";
import { getTenant } from "~/utils/db/tenants.db.server";
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.apiKeys.create", tenantId);
return Response.json({});
};
type ActionData = {
error?: string;
apiKey?: {
key: string;
alias: string;
};
};
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
export const action: ActionFunction = async ({ request, params }) => {
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.apiKeys.create", tenantId);
await validateCSRFToken(request);
const userInfo = await getUserInfo(request);
const tenant = await getTenant(tenantId);
const currentUser = await getUser(userInfo.userId);
if (!tenant || !currentUser) {
return badRequest({ error: t("shared.notFound") });
}
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
if (action === "create") {
let expirationDate: Date | null = null;
let expires = form.get("expires")?.toString();
if (expires) {
expirationDate = new Date(expires);
}
const alias = form.get("alias")?.toString() ?? "";
const existingAlias = await getApiKeyByAlias(tenantId, alias);
if (existingAlias) {
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
}
const active = Boolean(form.get("active"));
const apiKey = await createApiKey({
tenantId: tenantId,
createdByUserId: userInfo.userId,
alias,
expires: expirationDate,
active,
});
await EventsService.create({
request,
event: "api_key.created",
tenantId: tenantId,
userId: currentUser.id,
data: {
id: apiKey.id,
alias: apiKey.alias,
expires: expirationDate,
active: active,
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
} satisfies ApiKeyCreatedDto,
});
await createLog(request, tenantId, "settings.apiKeys.created", JSON.stringify({ id: apiKey.id, alias, expirationDate, active }));
return Response.json({ apiKey: { key: apiKey.key, alias: apiKey.alias } } satisfies ActionData);
} else {
return badRequest({ error: t("shared.invalidForm") });
}
};
export default function ApiNewKeyRoute() {
const navigate = useNavigate();
const submit = useSubmit();
const navigation = useNavigation();
const actionData = useActionData<ActionData>();
const params = useParams();
const { csrf } = useRootData();
const listPath = UrlUtils.currentTenantUrl(params, "settings/integrations/api/keys");
const closeToList = () => navigate(listPath);
// The action answers with the raw key instead of redirecting, so the create
// dialog gives way to the one-time reveal rather than closing.
if (actionData?.apiKey) {
return <ApiKeyCreatedDialog apiKey={actionData.apiKey} onClose={closeToList} />;
}
function create(input: ApiKeyNewInput) {
const form = new FormData();
form.set("action", "create");
form.set("alias", input.alias);
if (input.expires) form.set("expires", input.expires);
if (input.active) form.set("active", "true");
if (csrf) form.set("csrf", csrf);
submit(form, { method: "post" });
}
return (
<ApiKeyNewDialog
open
onOpenChange={(next: boolean) => {
if (!next) closeToList();
}}
submitting={navigation.state === "submitting"}
errorMessage={actionData?.error ?? null}
onCreate={create}
/>
);
}
@@ -0,0 +1,93 @@
import { LoaderFunctionArgs, useLoaderData, useSearchParams } 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 EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import Tabs from "~/components/ui/tabs/Tabs";
import { ApiLogsPage } from "~/components/screens/api/ApiLogsPage";
import { ApiKeyLogDto } from "~/modules/api/dtos/ApiKeyLogDto";
import ApiKeyLogService from "~/modules/api/services/ApiKeyLogService";
import UrlUtils from "~/utils/app/UrlUtils";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
type LoaderData = {
items: ApiKeyLogDto[];
filterableProperties: FilterablePropertyDto[];
pagination: PaginationDto;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.apiKeys.view", tenantId);
const { items, filterableProperties, pagination } = await ApiKeyLogService.getDetails({ request, params });
const data: LoaderData = {
items,
filterableProperties,
pagination,
};
return data;
};
export default function AdminApiLogsRoute() {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const params = useParams();
const [searchParams, setSearchParams] = useSearchParams();
// Filtering and paging happen in the loader, so every interaction is written
// back as a query parameter. Any filter change returns to the first page —
// page 4 of the old result set says nothing about the new one.
function patchParams(patch: Record<string, string | null>, { resetPage = true } = {}) {
const next = new URLSearchParams(searchParams);
for (const [key, value] of Object.entries(patch)) {
if (value === null || value === "") next.delete(key);
else next.set(key, value);
}
if (resetPage) next.delete("page");
setSearchParams(next);
}
return (
<>
{/* AK-SET-01: the Erweiterungen hub owns the page header. */}
<EditPageLayout fullWidth>
{/* Tabs render inside the children so the layout does not emit its own (empty) page heading. */}
<Tabs
tabs={[
{
name: t("shared.overview"),
routePath: UrlUtils.currentTenantUrl(params, "settings/integrations/api"),
},
{
name: t("models.apiCall.plural"),
routePath: UrlUtils.currentTenantUrl(params, "settings/integrations/api/logs"),
},
{
name: t("models.apiKey.plural"),
routePath: UrlUtils.currentTenantUrl(params, "settings/integrations/api/keys"),
},
]}
/>
<ApiLogsPage
items={data.items}
properties={data.filterableProperties}
pagination={data.pagination}
search={searchParams.get("q") ?? ""}
actions={{
onSearchChange: (value) => patchParams({ q: value }),
onToggleProperty: (name, value) => patchParams({ [name]: searchParams.get(name) === value ? null : value }),
onReset: () => {
const next = new URLSearchParams(searchParams);
next.delete("q");
next.delete("page");
data.filterableProperties.forEach((property) => next.delete(property.name));
setSearchParams(next);
},
onPage: (page) => patchParams({ page: String(page) }, { resetPage: false }),
}}
/>
</EditPageLayout>
</>
);
}
@@ -0,0 +1,110 @@
// AK-P16a · calendar connection detail route (M25 Block B/F). Owner-only (or
// calendar.admin) view of one connection: selected calendars, status, and the last
// 50 conflicts in Klartext (DoD 4). Disconnect action revokes + soft-deletes. A
// non-owner / missing-permission / unknown-id all render 404 (Bauprinzip A.5.3).
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
import {
buildCalendarConnectionDetailVM,
calendarConflictResolutionKey,
calendarConnectionStatusKey,
type CalendarConnectionDetailVM,
type ConflictLogRow,
type SelectedCalendarRow,
} from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { validateCSRFToken } from "~/utils/session.server";
import { useRootData } from "~/utils/data/useRootData";
import { loadCalendarContext, requireCalendarPermission, requireConnectionOwner, calendarHasPermission, CALENDAR_PERMISSIONS } from "~/modules/calendar/routes/calendarAccess.server";
import { CALENDAR_MODULE_KEY, calendarConnectionDetailPath, calendarConnectionsPath, notFoundResponse } from "~/modules/calendar/routes/calendarRoutePaths";
import { getConnectionForTenant, listConflictsForConnection } from "~/modules/calendar/db/calendar.db.server";
import { disconnectConnection } from "~/modules/calendar/services/CalendarConnectionService.server";
import { CalendarConnectionDetailPage } from "~/components/screens/calendar/CalendarConnectionDetailPage";
import ServerError from "~/components/ui/errors/ServerError";
type LoaderData = { title: string; vm: CalendarConnectionDetailVM; backHref: string };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadCalendarContext({ request, params, requireModule: true });
const tenantSlug = params.tenant ?? "";
const connectionId = params.id ?? "";
try {
requireCalendarPermission(ctx, CALENDAR_PERMISSIONS.connectOwn);
} catch {
throw notFoundResponse();
}
const connection = await getConnectionForTenant(ctx.tenantId, connectionId);
if (!connection) {
throw notFoundResponse();
}
try {
requireConnectionOwner(ctx, connection.userId);
} catch {
throw notFoundResponse();
}
const conflictRows = await listConflictsForConnection(ctx.tenantId, connectionId);
const conflicts: ConflictLogRow[] = conflictRows.map((c) => ({
id: c.id,
resolution: c.resolution,
resolutionKey: calendarConflictResolutionKey(c.resolution),
descriptionText: t(c.descriptionText),
occurredAt: c.createdAt.toISOString(),
}));
const rawCalendars = Array.isArray(connection.selectedCalendars) ? (connection.selectedCalendars as Array<Record<string, unknown>>) : [];
const selectedCalendars: SelectedCalendarRow[] = rawCalendars.map((c) => ({
externalCalendarId: String(c.externalCalendarId ?? c.id ?? ""),
name: String(c.name ?? c.externalCalendarId ?? ""),
isPrimary: Boolean(c.isPrimary),
}));
const vm = buildCalendarConnectionDetailVM({
id: connection.id,
externalAccountEmail: connection.externalAccountEmail,
status: connection.status,
statusKey: calendarConnectionStatusKey(connection.status),
syncDirection: connection.syncDirection,
lastSyncAt: connection.lastSyncAt ? connection.lastSyncAt.toISOString() : null,
lastErrorText: connection.lastErrorText,
selectedCalendars,
conflicts,
canManage: calendarHasPermission(ctx, CALENDAR_PERMISSIONS.connectOwn),
disconnectHref: calendarConnectionDetailPath(tenantSlug, connection.id),
});
return Response.json({ title: `${t("calendar.detail.title")} | ${process.env.APP_NAME}`, vm, backHref: calendarConnectionsPath(tenantSlug) } satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadCalendarContext({ request, params, requireModule: true });
requireCalendarPermission(ctx, CALENDAR_PERMISSIONS.connectOwn);
const connectionId = params.id ?? "";
const connection = await getConnectionForTenant(ctx.tenantId, connectionId);
if (!connection) {
throw notFoundResponse();
}
requireConnectionOwner(ctx, connection.userId);
await validateCSRFToken(request);
const form = await request.formData();
if (form.get("intent") !== "disconnect") {
throw notFoundResponse();
}
await disconnectConnection({ tenantId: ctx.tenantId, connectionId });
return redirect(`${calendarConnectionsPath(params.tenant ?? "")}?toast=${encodeURIComponent("calendar.toast.disconnected")}`);
};
export default function CalendarConnectionDetailRoute() {
const rootData = useRootData();
const { vm, backHref } = useLoaderData<LoaderData>();
return <CalendarConnectionDetailPage vm={vm} csrf={rootData.csrf ?? null} backHref={backHref} />;
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: CALENDAR_MODULE_KEY };
@@ -0,0 +1,101 @@
// AK-P16a · calendar connections settings route (M25 Block B/C). Lists the current
// user's OWN connections (leak-protection, DoD 3) + the Google connect action. The
// connect action redirects to the Google consent screen with a signed state. Module
// off -> locked empty; missing calendar.connect_own -> 404.
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData, useParams } from "react-router";
import {
buildCalendarConnectionListVM,
calendarConnectionStatusKey,
calendarSyncDirectionKey,
type CalendarConnectionRow,
type CalendarConnectionListVM,
} from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { validateCSRFToken } from "~/utils/session.server";
import { useRootData } from "~/utils/data/useRootData";
import { loadCalendarContext, requireCalendarPermission, calendarHasPermission, CALENDAR_PERMISSIONS } from "~/modules/calendar/routes/calendarAccess.server";
import { CALENDAR_MODULE_KEY, calendarConnectionDetailPath, calendarConnectionsPath, notFoundResponse } from "~/modules/calendar/routes/calendarRoutePaths";
import { listConnectionsForUser } from "~/modules/calendar/db/calendar.db.server";
import { buildConnectUrl, CalendarConnectError } from "~/modules/calendar/services/CalendarConnectionService.server";
import { googleCalendarAdapter } from "~/modules/calendar/services/adapters/GoogleCalendarAdapter.server";
import { CalendarConnectionsPage } from "~/components/screens/calendar/CalendarConnectionsPage";
import { integrationsCatalogPath } from "~/utils/integrations/integrationsRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import { useSaveToast, type SaveActionResult } from "~/hooks/use-save-toast";
type LoaderData = { title: string; vm: CalendarConnectionListVM };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadCalendarContext({ request, params });
const tenantSlug = params.tenant ?? "";
const title = `${t("calendar.connections.title")} | ${process.env.APP_NAME}`;
if (!ctx.hasModule) {
return Response.json({ title, vm: buildCalendarConnectionListVM({ rows: [], canConnect: false, isConfigured: false, connectHref: calendarConnectionsPath(tenantSlug) }) } satisfies LoaderData);
}
try {
requireCalendarPermission(ctx, CALENDAR_PERMISSIONS.connectOwn);
} catch {
throw notFoundResponse();
}
const connections = await listConnectionsForUser(ctx.tenantId, ctx.userId);
const rows: CalendarConnectionRow[] = connections.map((c) => ({
id: c.id,
provider: "google",
externalAccountEmail: c.externalAccountEmail,
status: c.status,
statusKey: calendarConnectionStatusKey(c.status),
syncDirection: c.syncDirection,
syncDirectionKey: calendarSyncDirectionKey(c.syncDirection),
lastSyncAt: c.lastSyncAt ? c.lastSyncAt.toISOString() : null,
lastErrorText: c.lastErrorText,
detailHref: calendarConnectionDetailPath(tenantSlug, c.id),
}));
const vm = buildCalendarConnectionListVM({
rows,
canConnect: calendarHasPermission(ctx, CALENDAR_PERMISSIONS.connectOwn),
isConfigured: googleCalendarAdapter.isConfigured(),
connectHref: calendarConnectionsPath(tenantSlug),
});
return Response.json({ title, vm } satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadCalendarContext({ request, params, requireModule: true });
requireCalendarPermission(ctx, CALENDAR_PERMISSIONS.connectOwn);
await validateCSRFToken(request);
const form = await request.formData();
if (form.get("intent") !== "connect") {
throw notFoundResponse();
}
try {
const url = buildConnectUrl({ tenantId: ctx.tenantId, userId: ctx.userId, tenantSlug: params.tenant ?? "" });
return redirect(url);
} catch (error) {
if (error instanceof CalendarConnectError) {
return Response.json({ intent: "connect", error: "calendar.connections.notConfigured" }, { status: 400 });
}
throw error;
}
};
export default function CalendarConnectionsRoute() {
const rootData = useRootData();
const params = useParams();
const { vm } = useLoaderData<LoaderData>();
const actionData = useActionData<SaveActionResult>();
useSaveToast(actionData, { reportSuccess: false });
return <CalendarConnectionsPage embedded vm={vm} csrf={rootData.csrf ?? null} backHref={integrationsCatalogPath(params.tenant ?? "")} />;
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: CALENDAR_MODULE_KEY };
@@ -0,0 +1,145 @@
// VA-P23 · mailbox connect settings route (M09 Block B/D). Lists the current
// user's OWN mailboxes (read_all admins see every tenant mailbox) + the two
// provider connect actions + reconnect/disconnect. Connect redirects to the
// provider consent screen with a signed, provider-pinned state. Module off ->
// locked empty; missing email.read_own -> 404 (A.5.3).
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData, useParams, useSearchParams } from "react-router";
import {
aggregateInitialSync,
buildEmailMailboxListVM,
emailMailboxProviderKey,
emailMailboxStatusKey,
type EmailMailboxListVM,
type EmailMailboxRow,
} from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { validateCSRFToken } from "~/utils/session.server";
import { useRootData } from "~/utils/data/useRootData";
import {
canReadAllMailboxes,
canWriteEmail,
loadEmailInboxContext,
requireEmailRead,
requireMailboxVisibility,
} from "~/modules/emailInbox/routes/emailInboxAccess.server";
import { EMAIL_INBOX_MODULE_KEY, notFoundResponse } from "~/modules/emailInbox/routes/emailInboxRoutePaths";
import { getMailboxForTenant, listMailboxesForTenant, listMailboxesForUser, listSyncCursorsForMailboxes } from "~/modules/emailInbox/db/emailInbox.db.server";
import { MailboxConnectError, buildConnectUrl, configuredEmailProviders, disconnectMailbox } from "~/modules/emailInbox/services/MailboxConnectionService.server";
import type { EmailOAuthProvider } from "~/modules/emailInbox/services/oauthState.server";
import { EmailMailboxSettingsPage } from "~/components/screens/email-inbox/EmailMailboxSettingsPage";
import { integrationsCatalogPath } from "~/utils/integrations/integrationsRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import { useSaveToast } from "~/hooks/use-save-toast";
type LoaderData = { title: string; vm: EmailMailboxListVM };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadEmailInboxContext({ request, params });
const title = `${t("emailInbox.settings.title")} | ${process.env.APP_NAME}`;
if (!ctx.hasModule) {
return Response.json({
title,
vm: buildEmailMailboxListVM({ rows: [], canConnect: false, configuredProviders: { gmail: false, microsoft: false } }),
} satisfies LoaderData);
}
try {
requireEmailRead(ctx);
} catch {
throw notFoundResponse();
}
const mailboxes = canReadAllMailboxes(ctx) ? await listMailboxesForTenant(ctx.tenantId) : await listMailboxesForUser(ctx.tenantId, ctx.userId);
const cursors = await listSyncCursorsForMailboxes(
ctx.tenantId,
mailboxes.map((m) => m.id),
);
const rows: EmailMailboxRow[] = mailboxes.map((mailbox) => ({
id: mailbox.id,
provider: mailbox.provider,
providerKey: emailMailboxProviderKey(mailbox.provider),
emailAddress: mailbox.emailAddress,
displayName: mailbox.displayName,
isDefaultForUser: mailbox.isDefaultForUser,
isOwn: mailbox.ownerUserId === ctx.userId,
status: mailbox.status,
statusKey: emailMailboxStatusKey(mailbox.status),
lastSyncAt: mailbox.lastSyncAt ? mailbox.lastSyncAt.toISOString() : null,
lastErrorText: mailbox.lastErrorText,
initialSync: aggregateInitialSync(cursors.filter((c) => c.mailboxId === mailbox.id)),
}));
const vm = buildEmailMailboxListVM({
rows,
canConnect: canWriteEmail(ctx),
configuredProviders: configuredEmailProviders(),
});
return Response.json({ title, vm } satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadEmailInboxContext({ request, params, requireModule: true });
await validateCSRFToken(request);
const form = await request.formData();
const intent = String(form.get("intent") ?? "");
if (intent === "connect-gmail" || intent === "connect-microsoft") {
try {
requireEmailRead(ctx);
} catch {
throw notFoundResponse();
}
if (!canWriteEmail(ctx)) {
throw notFoundResponse();
}
const provider: EmailOAuthProvider = intent === "connect-gmail" ? "gmail" : "microsoft";
try {
const url = buildConnectUrl({ tenantId: ctx.tenantId, userId: ctx.userId, tenantSlug: params.tenant ?? "", provider });
return redirect(url);
} catch (error) {
if (error instanceof MailboxConnectError) {
return Response.json({ error: "emailInbox.settings.notConfigured" }, { status: 400 });
}
throw error;
}
}
if (intent === "disconnect") {
const mailboxId = String(form.get("mailboxId") ?? "");
const mailbox = mailboxId ? await getMailboxForTenant(ctx.tenantId, mailboxId) : null;
if (!mailbox) {
throw notFoundResponse();
}
// Owner may disconnect their own mailbox; read_all admins may force-disconnect.
requireMailboxVisibility(ctx, mailbox.ownerUserId);
if (mailbox.ownerUserId === ctx.userId && !canWriteEmail(ctx)) {
throw notFoundResponse();
}
await disconnectMailbox({ tenantId: ctx.tenantId, mailboxId });
return Response.json({ ok: true, disconnected: mailboxId, messageKey: "emailInbox.settings.toast.disconnected" });
}
throw notFoundResponse();
};
export default function EmailSettingsRoute() {
const rootData = useRootData();
const params = useParams();
const { vm } = useLoaderData<LoaderData>();
const [searchParams] = useSearchParams();
const actionData = useActionData<{ ok?: boolean; error?: string; messageKey?: string }>();
useSaveToast(actionData);
const flashParam = searchParams.get("email");
const flash = flashParam === "connected" || flashParam === "error" ? flashParam : null;
return <EmailMailboxSettingsPage embedded vm={vm} csrf={rootData.csrf ?? null} flash={flash} backHref={integrationsCatalogPath(params.tenant ?? "")} />;
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: EMAIL_INBOX_MODULE_KEY };
@@ -0,0 +1,462 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
KwpProjectDomainError: class KwpProjectDomainError extends Error {
readonly code: string;
constructor(code: string) {
super(code);
this.code = code;
}
},
runWithRlsContext: vi.fn(),
loadIntegrationsContext: vi.fn(),
requireIntegrationsPermission: vi.fn(),
integrationsHasPermission: vi.fn(),
requireKwpIntegrationModule: vi.fn(),
loadProjectContext: vi.fn(),
requireProjectPermission: vi.fn(),
listConnections: vi.fn(),
listPipelines: vi.fn(),
listProjects: vi.fn(),
getProject: vi.fn(),
searchProjects: vi.fn(),
cacheKwpProjectDetails: vi.fn(),
cacheKwpProjectSearchResults: vi.fn(),
getKwpProjectCatalogSummary: vi.fn(),
revalidateAndRecoverKwpProjectSearch: vi.fn(),
previewKwpProjectImport: vi.fn(),
saveKwpProjectRouting: vi.fn(),
approveKwpProjectContract: vi.fn(),
runKwpProjectContractSentinel: vi.fn(),
importKwpProject: vi.fn(),
unlinkKwpProject: vi.fn(),
restoreAndUnlinkKwpProject: vi.fn(),
validateCSRFToken: vi.fn(),
capabilityFindUnique: vi.fn(),
errorFindFirst: vi.fn(),
bindingFindMany: vi.fn(),
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
runWithRlsContext: mocks.runWithRlsContext,
}));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => ({
kwpCapabilityState: { findUnique: mocks.capabilityFindUnique },
kwpErrorReport: { findFirst: mocks.errorFindFirst },
appEntityBinding: { findMany: mocks.bindingFindMany },
}),
}));
vi.mock("@hivegrid/integrations/kwp-contract-sentinel.server", () => ({
approveKwpProjectContract: mocks.approveKwpProjectContract,
runKwpProjectContractSentinel: mocks.runKwpProjectContractSentinel,
}));
vi.mock("@hivegrid/integrations/kwp-project-domain.server", () => ({
importKwpProject: mocks.importKwpProject,
KwpProjectDomainError: mocks.KwpProjectDomainError,
previewKwpProjectImport: mocks.previewKwpProjectImport,
restoreAndUnlinkKwpProject: mocks.restoreAndUnlinkKwpProject,
saveKwpProjectRouting: mocks.saveKwpProjectRouting,
unlinkKwpProject: mocks.unlinkKwpProject,
}));
vi.mock("@hivegrid/integrations/kwp-project-catalog.server", () => ({
cacheKwpProjectDetails: mocks.cacheKwpProjectDetails,
cacheKwpProjectSearchResults: mocks.cacheKwpProjectSearchResults,
getKwpProjectCatalogSummary: mocks.getKwpProjectCatalogSummary,
searchAndCacheKwpProjects: mocks.searchProjects,
}));
vi.mock("@hivegrid/integrations/kwp-resource-client.server", () => ({
KWP_PROJECT_CAPABILITY: "project-import",
readKwpProjectCapabilityFailureCode: (error: unknown) => {
const code = error && typeof error === "object" && "code" in error
? (error as { code?: unknown }).code
: null;
return code === "auth_scope_missing" || code === "capability_paused" || code === "contract_drift"
? code
: null;
},
revalidateAndRecoverKwpProjectSearch: mocks.revalidateAndRecoverKwpProjectSearch,
}));
vi.mock("~/components/screens/integrations/KwpProjectImportPage", () => ({
KwpProjectImportPage: () => null,
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: () => Promise.resolve({ t: (key: string) => key }),
}));
vi.mock("~/modules/kwp/routes/kwpAccess.server", () => ({
requireKwpIntegrationModule: mocks.requireKwpIntegrationModule,
}));
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf" }) }));
vi.mock("~/utils/integrations/integrationsAccess.server", () => ({
integrationsHasPermission: mocks.integrationsHasPermission,
loadIntegrationsContext: mocks.loadIntegrationsContext,
notFoundResponse: () => new Response(null, { status: 404 }),
requireIntegrationsPermission: mocks.requireIntegrationsPermission,
}));
vi.mock("~/utils/integrations/appsEngineService.server", () => ({
listConnections: mocks.listConnections,
}));
vi.mock("~/utils/integrations/projects/projectService.server", () => ({
getProject: mocks.getProject,
listPipelines: mocks.listPipelines,
listProjects: mocks.listProjects,
}));
vi.mock("~/utils/integrations/projects/projectAccess.server", () => ({
loadProjectContext: mocks.loadProjectContext,
PROJECT_READ_PERMISSIONS: ["projects.read"],
requireProjectPermission: mocks.requireProjectPermission,
}));
vi.mock("~/utils/session.server", () => ({
validateCSRFToken: mocks.validateCSRFToken,
}));
import { action, loader } from "./import";
const integrationsContext = {
tenantId: "tenant-1",
userId: "user-1",
permissions: ["integrations.read", "integrations.connect"],
hasModule: true,
};
const projectContext = {
tenantId: "tenant-1",
userId: "user-1",
permissions: ["projects.read", "projects.write"],
hasModule: true,
};
async function rejectedResponse(promise: Promise<unknown>): Promise<Response> {
try {
await promise;
} catch (error) {
if (error instanceof Response) return error;
throw error;
}
throw new Error("Expected a Response rejection");
}
beforeEach(() => {
vi.clearAllMocks();
mocks.runWithRlsContext.mockImplementation((_context, callback) => callback());
mocks.loadIntegrationsContext.mockResolvedValue(integrationsContext);
mocks.loadProjectContext.mockResolvedValue(projectContext);
mocks.requireIntegrationsPermission.mockImplementation(() => undefined);
mocks.requireKwpIntegrationModule.mockResolvedValue(undefined);
mocks.requireProjectPermission.mockImplementation(() => undefined);
mocks.integrationsHasPermission.mockReturnValue(true);
mocks.listConnections.mockResolvedValue([{
id: "connection-1",
label: "KWP",
connectionStatus: "active",
}]);
mocks.listPipelines.mockResolvedValue([]);
mocks.listProjects.mockResolvedValue([]);
mocks.searchProjects.mockResolvedValue([]);
mocks.cacheKwpProjectDetails.mockResolvedValue(undefined);
mocks.cacheKwpProjectSearchResults.mockResolvedValue(undefined);
mocks.getKwpProjectCatalogSummary.mockResolvedValue({
status: "pending",
discoveredCount: 0,
hydratedCount: 0,
lastDiscoveryAt: null,
lastCompletedAt: null,
});
mocks.revalidateAndRecoverKwpProjectSearch.mockResolvedValue([]);
mocks.previewKwpProjectImport.mockResolvedValue(null);
mocks.runKwpProjectContractSentinel.mockResolvedValue({
status: "paused",
fingerprint: "b".repeat(64),
previousFingerprint: "a".repeat(64),
diff: { added: [], removed: [], changed: [], truncated: false },
});
mocks.capabilityFindUnique.mockResolvedValue(null);
mocks.errorFindFirst.mockResolvedValue(null);
mocks.bindingFindMany.mockResolvedValue([]);
mocks.validateCSRFToken.mockResolvedValue(undefined);
mocks.getProject.mockResolvedValue({
id: "project-1",
projektNummer: "HG-1",
projektname: "Local",
pipelineId: "pipeline-1",
stageId: "stage-1",
startDatum: null,
auftragsvolumen: null,
updatedAt: new Date("2026-07-23T10:00:00.000Z"),
});
mocks.importKwpProject.mockResolvedValue({
projectId: "project-1",
created: false,
bindingId: "binding-1",
});
});
describe("KWP project import route", () => {
it("returns 404 when integrations.read is not available", async () => {
mocks.requireIntegrationsPermission.mockImplementationOnce(() => {
throw new Error("denied");
});
const response = await rejectedResponse(loader({
request: new Request("https://app.example.test/acme/settings/integrations/kwp/import"),
params: { tenant: "acme" },
context: {},
} as never));
expect(response.status).toBe(404);
});
it("does not issue a provider search for fewer than two characters", async () => {
await loader({
request: new Request("https://app.example.test/acme/settings/integrations/kwp/import?q=x"),
params: { tenant: "acme" },
context: {},
} as never);
expect(mocks.searchProjects).not.toHaveBeenCalled();
});
it("renders the paused capability state instead of throwing a 500 after contract drift", async () => {
mocks.searchProjects.mockRejectedValueOnce({ code: "contract_drift" });
mocks.capabilityFindUnique.mockResolvedValueOnce({
status: "paused",
reasonCode: "kwp.project.contract_drift",
revision: 1,
observedFingerprint: null,
});
const data = await loader({
request: new Request("https://app.example.test/acme/settings/integrations/kwp/import?q=20"),
params: { tenant: "acme" },
context: {},
} as never);
expect(data.vm).toMatchObject({
status: "ready",
data: {
results: [],
capability: {
status: "paused",
reasonCode: "kwp.project.contract_drift",
},
},
});
});
it("recovers an uninitialized paused capability and retries the project search once", async () => {
mocks.searchProjects
.mockRejectedValueOnce({ code: "capability_paused" })
.mockResolvedValueOnce([{
externalProjectNumber: "P-100",
name: "Projekt 100",
projectAddressCode: null,
invoiceAddressCode: null,
clientAddressCode: null,
status: 8,
statusLabel: "Erhalten",
}]);
mocks.runKwpProjectContractSentinel.mockResolvedValueOnce({
status: "initialized",
fingerprint: "a".repeat(64),
});
const data = await loader({
request: new Request("https://app.example.test/acme/settings/integrations/kwp/import?q=20"),
params: { tenant: "acme" },
context: {},
} as never);
expect(mocks.runKwpProjectContractSentinel).toHaveBeenCalledWith({
connectionId: "connection-1",
});
expect(mocks.searchProjects).toHaveBeenCalledTimes(2);
expect(data.vm).toMatchObject({
status: "ready",
data: {
results: [{ externalProjectNumber: "P-100", name: "Projekt 100" }],
capability: { status: "active" },
},
});
});
it("revalidates a sticky schema pause when the semantic contract is unchanged", async () => {
mocks.searchProjects.mockRejectedValueOnce({ code: "capability_paused" });
mocks.runKwpProjectContractSentinel.mockResolvedValueOnce({
status: "unchanged",
fingerprint: "a".repeat(64),
});
mocks.revalidateAndRecoverKwpProjectSearch.mockResolvedValueOnce([{
externalProjectNumber: "P-100",
name: "Projekt 100",
projectAddressCode: null,
invoiceAddressCode: null,
clientAddressCode: null,
status: 8,
statusLabel: "Erhalten",
}]);
const data = await loader({
request: new Request("https://app.example.test/acme/settings/integrations/kwp/import?q=20"),
params: { tenant: "acme" },
context: {},
} as never);
expect(mocks.revalidateAndRecoverKwpProjectSearch).toHaveBeenCalledWith({
connectionId: "connection-1",
query: "20",
});
expect(mocks.searchProjects).toHaveBeenCalledTimes(1);
expect(data.vm).toMatchObject({
status: "ready",
data: {
results: [{ externalProjectNumber: "P-100", name: "Projekt 100" }],
capability: { status: "active" },
},
});
});
it("does not hide a non-capability provider failure from the recovery retry", async () => {
const providerFailure = new Error("provider unavailable");
mocks.searchProjects
.mockRejectedValueOnce({ code: "capability_paused" })
.mockRejectedValueOnce(providerFailure);
mocks.runKwpProjectContractSentinel.mockResolvedValueOnce({
status: "initialized",
fingerprint: "a".repeat(64),
});
await expect(loader({
request: new Request("https://app.example.test/acme/settings/integrations/kwp/import?q=20"),
params: { tenant: "acme" },
context: {},
} as never)).rejects.toBe(providerFailure);
});
it("rejects malformed import JSON before domain mutation", async () => {
const form = new FormData();
form.set("csrf", "csrf");
form.set("intent", "import");
form.set("connectionId", "connection-1");
form.set("payload", JSON.stringify({ connectionId: "connection-1", target: { kind: "create" } }));
const response = await rejectedResponse(action({
request: new Request("https://app.example.test/acme/settings/integrations/kwp/import", {
method: "POST",
body: form,
}),
params: { tenant: "acme" },
context: {},
} as never));
expect(response.status).toBe(400);
expect(mocks.importKwpProject).not.toHaveBeenCalled();
});
it("checks normal project visibility before linking an existing project", async () => {
const form = new FormData();
form.set("csrf", "csrf");
form.set("intent", "import");
form.set("connectionId", "connection-1");
form.set("payload", JSON.stringify({
connectionId: "connection-1",
externalProjectNumber: "P-100",
target: {
kind: "link",
projectId: "project-1",
expectedUpdatedAt: "2026-07-23T10:00:00.000Z",
},
addressDecisions: [],
}));
const response = await rejectedResponse(action({
request: new Request("https://app.example.test/acme/settings/integrations/kwp/import", {
method: "POST",
body: form,
}),
params: { tenant: "acme" },
context: {},
} as never));
expect(response.status).toBe(303);
expect(mocks.getProject).toHaveBeenCalledWith({
tenantId: "tenant-1",
projectId: "project-1",
ctx: projectContext,
});
expect(mocks.getProject.mock.invocationCallOrder[0]).toBeLessThan(
mocks.importKwpProject.mock.invocationCallOrder[0]!,
);
});
it("passes three explicit CRM role decisions and one selected person per role", async () => {
const addressDecisions = [
{
role: "project",
addressCode: "ADR-1",
addressContact: { kind: "existing", contactId: "contact-1" },
primaryContact: {
externalContactId: "person-1",
contact: { kind: "create" },
},
},
{
role: "invoice",
addressCode: "ADR-2",
addressContact: { kind: "create" },
primaryContact: null,
},
{
role: "client",
addressCode: "ADR-3",
addressContact: { kind: "existing", contactId: "contact-3" },
primaryContact: null,
},
];
const form = new FormData();
form.set("csrf", "csrf");
form.set("intent", "import");
form.set("connectionId", "connection-1");
form.set("payload", JSON.stringify({
connectionId: "connection-1",
externalProjectNumber: "P-100",
target: { kind: "create" },
addressDecisions,
}));
const response = await rejectedResponse(action({
request: new Request("https://app.example.test/acme/settings/integrations/kwp/import", {
method: "POST",
body: form,
}),
params: { tenant: "acme" },
context: {},
} as never));
expect(response.status).toBe(303);
expect(mocks.importKwpProject).toHaveBeenCalledWith({
connectionId: "connection-1",
externalProjectNumber: "P-100",
actorUserId: "user-1",
target: { kind: "create" },
addressDecisions,
});
});
it("uses the binding revision and project timestamp for an atomic restore", async () => {
const form = new FormData();
form.set("csrf", "csrf");
form.set("intent", "restore");
form.set("connectionId", "connection-1");
form.set("projectId", "project-1");
form.set("expectedBindingRevision", "4");
form.set("expectedProjectUpdatedAt", "2026-07-23T10:00:00.000Z");
const response = await rejectedResponse(action({
request: new Request("https://app.example.test/acme/settings/integrations/kwp/import", {
method: "POST",
body: form,
}),
params: { tenant: "acme" },
context: {},
} as never));
expect(response.status).toBe(303);
expect(mocks.restoreAndUnlinkKwpProject).toHaveBeenCalledWith({
tenantId: "tenant-1",
projectId: "project-1",
expectedBindingRevision: 4,
expectedProjectUpdatedAt: "2026-07-23T10:00:00.000Z",
actorUserId: "user-1",
});
});
});
@@ -0,0 +1,596 @@
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { getDbClient } from "@hivegrid/db/client.server";
import {
approveKwpProjectContract,
runKwpProjectContractSentinel,
} from "@hivegrid/integrations/kwp-contract-sentinel.server";
import {
importKwpProject,
KwpProjectDomainError,
previewKwpProjectImport,
restoreAndUnlinkKwpProject,
saveKwpProjectRouting,
unlinkKwpProject,
} from "@hivegrid/integrations/kwp-project-domain.server";
import {
cacheKwpProjectDetails,
cacheKwpProjectSearchResults,
getKwpProjectCatalogSummary,
searchAndCacheKwpProjects,
} from "@hivegrid/integrations/kwp-project-catalog.server";
import {
KWP_PROJECT_CAPABILITY,
readKwpProjectCapabilityFailureCode,
revalidateAndRecoverKwpProjectSearch,
} from "@hivegrid/integrations/kwp-resource-client.server";
import {
buildKwpProjectImportVM,
type KwpCapabilityVM,
type KwpProjectImportVM,
} from "@hivegrid/view-models";
import {
redirect,
useLoaderData,
useNavigate,
useNavigation,
useSubmit,
type ActionFunctionArgs,
type LoaderFunctionArgs,
type MetaFunction,
} from "react-router";
import { z } from "zod";
import {
KwpProjectImportPage,
type KwpProjectImportActions,
} from "~/components/screens/integrations/KwpProjectImportPage";
import { getTranslations } from "~/locale/i18next.server";
import { requireKwpIntegrationModule } from "~/modules/kwp/routes/kwpAccess.server";
import { useRootData } from "~/utils/data/useRootData";
import {
integrationsHasPermission,
loadIntegrationsContext,
notFoundResponse,
requireIntegrationsPermission,
} from "~/utils/integrations/integrationsAccess.server";
import { listConnections } from "~/utils/integrations/appsEngineService.server";
import {
integrationsAppPath,
kwpProjectImportPath,
} from "~/utils/integrations/integrationsRoutePaths";
import {
getProject,
listPipelines,
listProjects,
} from "~/utils/integrations/projects/projectService.server";
import {
loadProjectContext,
PROJECT_READ_PERMISSIONS,
requireProjectPermission,
} from "~/utils/integrations/projects/projectAccess.server";
import { validateCSRFToken } from "~/utils/session.server";
type LoaderData = {
title: string;
vm: KwpProjectImportVM;
};
function nonEmpty(value: FormDataEntryValue | null): string {
const normalized = typeof value === "string" ? value.trim() : "";
if (!normalized) throw new Response(null, { status: 400 });
return normalized;
}
function parseInteger(value: FormDataEntryValue | null): number {
const parsed = Number(nonEmpty(value));
if (!Number.isSafeInteger(parsed)) throw new Response(null, { status: 400 });
return parsed;
}
function parseKwpStatus(value: FormDataEntryValue | null): 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 {
const parsed = parseInteger(value);
if (parsed < 0 || parsed > 9) throw new Response(null, { status: 400 });
return parsed as 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
}
const idSchema = z.string().trim().min(1).max(200);
const contactDecisionSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("create") }).strict(),
z.object({ kind: z.literal("existing"), contactId: idSchema }).strict(),
]);
const importPayloadSchema = z.object({
connectionId: idSchema,
externalProjectNumber: idSchema,
target: z.discriminatedUnion("kind", [
z.object({ kind: z.literal("create") }).strict(),
z.object({
kind: z.literal("link"),
projectId: idSchema,
expectedUpdatedAt: z.string().datetime({ offset: true }),
}).strict(),
]),
addressDecisions: z.array(z.object({
role: z.enum(["project", "invoice", "client"]),
addressCode: idSchema,
addressContact: contactDecisionSchema,
primaryContact: z.union([
z.null(),
z.object({
externalContactId: idSchema,
contact: contactDecisionSchema,
}).strict(),
]),
}).strict()).max(3),
}).strict();
function parseImportPayload(value: FormDataEntryValue | null) {
try {
const parsed = importPayloadSchema.parse(JSON.parse(nonEmpty(value)));
if (new Set(parsed.addressDecisions.map((row) => row.role)).size !== parsed.addressDecisions.length) {
throw new Error("duplicate role");
}
return parsed;
} catch (error) {
if (error instanceof Response) throw error;
throw new Response(null, { status: 400 });
}
}
function feedbackKey(value: string | null): string | null {
if (!value) return null;
const allowed = new Set([
"imported",
"routingSaved",
"contractApproved",
"address_decision_invalid",
"binding_conflict",
"capability_paused",
"contact_not_found",
"external_project_not_found",
"project_not_found",
"routing_invalid",
"routing_required",
"stale_write",
"unlinked",
"restored",
]);
return allowed.has(value) ? `integrations.kwp.projectImport.feedback.${value}` : null;
}
function readCapabilityDiff(value: unknown): KwpCapabilityVM["diff"] {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const diff = (value as Record<string, unknown>).diff;
if (!diff || typeof diff !== "object" || Array.isArray(diff)) return null;
const row = diff as Record<string, unknown>;
const paths = (field: string) => Array.isArray(row[field])
? row[field]!.filter((item): item is string => typeof item === "string").slice(0, 100)
: [];
return {
added: paths("added"),
removed: paths("removed"),
changed: paths("changed"),
truncated: row.truncated === true,
};
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const ctx = await loadIntegrationsContext({ request, params });
if (!ctx.hasModule) throw notFoundResponse();
try {
requireIntegrationsPermission(ctx, "integrations.read");
await requireKwpIntegrationModule(ctx);
} catch {
throw notFoundResponse();
}
const tenantSlug = params.tenant ?? "";
const url = new URL(request.url);
const query = url.searchParams.get("q")?.trim() ?? "";
const selectedProjectNumber = url.searchParams.get("project")?.trim() ?? "";
const requestedConnectionId = url.searchParams.get("connection")?.trim() ?? "";
const { t } = await getTranslations(request);
return runWithRlsContext({ tenantId: ctx.tenantId, userId: ctx.userId }, async () => {
const connections = (await listConnections(ctx.tenantId, { appId: "kwp" }))
.filter((row) => row.connectionStatus === "active" || row.connectionStatus === "degraded");
const connectionId = connections.some((row) => row.id === requestedConnectionId)
? requestedConnectionId
: connections[0]?.id ?? "";
let results: Awaited<ReturnType<typeof searchAndCacheKwpProjects>> = [];
let preview: Awaited<ReturnType<typeof previewKwpProjectImport>> | null = null;
if (connectionId && query.length >= 2) {
const loadRequestedProjectData = async () => {
const nextResults = await searchAndCacheKwpProjects({ connectionId, query });
const nextPreview = selectedProjectNumber &&
nextResults.some((row) => row.externalProjectNumber === selectedProjectNumber)
? await previewKwpProjectImport({
connectionId,
externalProjectNumber: selectedProjectNumber,
})
: null;
if (nextPreview) {
await cacheKwpProjectDetails({
connectionId,
details: {
externalProjectNumber: nextPreview.project.externalProjectNumber,
name: nextPreview.project.name,
startDate: nextPreview.project.startDate,
orderValue: nextPreview.project.orderValue,
addressCode: null,
addressName: null,
},
});
}
return { nextResults, nextPreview };
};
try {
const loaded = await loadRequestedProjectData();
results = loaded.nextResults;
preview = loaded.nextPreview;
} catch (error) {
const failureCode = readKwpProjectCapabilityFailureCode(error);
if (!failureCode) throw error;
if (failureCode === "capability_paused") {
let sentinelStatus: "initialized" | "unchanged" | null = null;
try {
const sentinel = await runKwpProjectContractSentinel({ connectionId });
sentinelStatus = sentinel.status === "initialized" || sentinel.status === "unchanged"
? sentinel.status
: null;
} catch {
// The original paused state remains the user-facing source of
// truth; maintenance will retry sentinel/provider outages.
}
if (sentinelStatus) {
try {
results = sentinelStatus === "initialized"
? await searchAndCacheKwpProjects({ connectionId, query })
: await revalidateAndRecoverKwpProjectSearch({ connectionId, query });
await cacheKwpProjectSearchResults({ connectionId, results });
preview = selectedProjectNumber &&
results.some((row) => row.externalProjectNumber === selectedProjectNumber)
? await previewKwpProjectImport({
connectionId,
externalProjectNumber: selectedProjectNumber,
})
: null;
} catch (retryError) {
if (!readKwpProjectCapabilityFailureCode(retryError)) throw retryError;
}
}
}
}
}
let projectCtx: Awaited<ReturnType<typeof loadProjectContext>> | null = null;
try {
const loaded = await loadProjectContext({ request, params });
const canReadProject = PROJECT_READ_PERMISSIONS.some((permission) => loaded.permissions.includes(permission));
projectCtx = loaded.hasModule && canReadProject ? loaded : null;
} catch {
projectCtx = null;
}
const [pipelines, localProjects, capability, report, bindings, catalog] = await Promise.all([
projectCtx ? listPipelines({ tenantId: ctx.tenantId, ctx: projectCtx }) : [],
projectCtx ? listProjects({ tenantId: ctx.tenantId, ctx: projectCtx, limit: 200 }) : [],
connectionId
? getDbClient().kwpCapabilityState.findUnique({
where: {
tenantId_dataConnectionId_capability: {
tenantId: ctx.tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
},
},
})
: null,
connectionId
? getDbClient().kwpErrorReport.findFirst({
where: {
tenantId: ctx.tenantId,
dataConnectionId: connectionId,
capability: KWP_PROJECT_CAPABILITY,
resolvedAt: null,
},
orderBy: { createdAt: "desc" },
})
: null,
connectionId && projectCtx
? getDbClient().appEntityBinding.findMany({
where: {
tenantId: ctx.tenantId,
dataConnectionId: connectionId,
externalEntityType: "kwp_project",
localEntityType: "project",
state: { in: ["active", "missing", "quarantined"] },
},
orderBy: { updatedAt: "desc" },
take: 200,
})
: [],
connectionId
? getKwpProjectCatalogSummary({ connectionId })
: {
status: "pending" as const,
discoveredCount: 0,
hydratedCount: 0,
lastDiscoveryAt: null,
lastCompletedAt: null,
},
]);
const visibleBindings = projectCtx
? (await Promise.all(bindings.map(async (binding) => {
try {
const project = await getProject({
tenantId: ctx.tenantId,
projectId: binding.localId,
ctx: projectCtx,
});
return { binding, project };
} catch {
return null;
}
}))).filter((row): row is NonNullable<typeof row> => row !== null)
: [];
const vm = buildKwpProjectImportVM({
tenantSlug,
backHref: integrationsAppPath(tenantSlug, "kwp"),
connectionId,
connections: connections.map((row) => ({ id: row.id, label: row.label })),
query,
results: results.map((row) => ({
externalProjectNumber: row.externalProjectNumber,
name: row.name,
status: row.status,
statusLabel: row.statusLabel,
})),
preview: preview
? {
externalProjectNumber: preview.project.externalProjectNumber,
name: preview.project.name,
status: preview.project.status,
statusLabel: preview.project.statusLabel,
startDate: preview.project.startDate,
orderValue: preview.project.orderValue,
routing: preview.routing,
addresses: preview.addresses.map(({ role, address, candidates }) => ({
role,
addressCode: address.externalAddressCode,
label: [address.firstName, address.name].filter(Boolean).join(" ") || address.externalAddressCode,
addressLabel: [address.street, address.postalCode, address.city].filter(Boolean).join(", "),
email: address.email ?? address.invoiceEmail,
candidates,
people: address.contactPeople.map((person) => ({
externalContactId: person.externalContactId,
label: [person.firstName, person.lastName, person.addition].filter(Boolean).join(" ") || person.externalContactId,
email: person.email,
phone: person.phone ?? person.mobile,
})),
})),
}
: null,
pipelines: pipelines.map((pipeline) => ({
id: pipeline.id,
label: pipeline.name,
stages: pipeline.stages.map((stage) => ({ id: stage.id, label: stage.name })),
})),
localProjects: localProjects.map((project) => ({
id: project.id,
projectNumber: project.projektNummer,
name: project.projektname,
pipelineId: project.pipelineId,
stageId: project.stageId,
startDate: project.startDatum?.toISOString() ?? null,
orderValue: project.auftragsvolumen?.toString() ?? null,
updatedAt: project.updatedAt.toISOString(),
})),
boundProjects: visibleBindings.map(({ binding, project }) => ({
bindingId: binding.id,
projectId: project.id,
externalProjectNumber: binding.externalId,
projectNumber: project.projektNummer,
name: project.projektname,
state: binding.state as "active" | "quarantined" | "missing",
revision: binding.revision,
projectUpdatedAt: project.updatedAt.toISOString(),
canRestore: binding.overwrittenLocalSnapshot !== null,
})),
capability: {
status: capability?.status ?? "active",
reasonCode: capability?.reasonCode ?? null,
revision: capability?.revision ?? 0,
observedFingerprint: capability?.observedFingerprint ?? null,
diff: readCapabilityDiff(report?.redactedDetails),
},
catalog,
canWrite: Boolean(
projectCtx &&
integrationsHasPermission(ctx, "integrations.connect") &&
projectCtx.permissions.includes("projects.write"),
),
feedbackKey: feedbackKey(url.searchParams.get("feedback")),
});
return {
title: `${t("integrations.kwp.projectImport.title")} | ${process.env.APP_NAME}`,
vm,
} satisfies LoaderData;
});
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadIntegrationsContext({ request, params, requireModule: true });
try {
requireIntegrationsPermission(ctx, "integrations.connect");
await requireKwpIntegrationModule(ctx);
} catch {
throw notFoundResponse();
}
const projectCtx = await loadProjectContext({ request, params, requireModule: true });
try {
requireProjectPermission(projectCtx, "projects.write");
} catch {
throw notFoundResponse();
}
const form = await request.formData();
await validateCSRFToken(request, { formData: form });
const intent = nonEmpty(form.get("intent"));
const connectionId = nonEmpty(form.get("connectionId"));
const tenantSlug = params.tenant ?? "";
try {
return await runWithRlsContext({ tenantId: ctx.tenantId, userId: ctx.userId }, async () => {
if (intent === "save-routing") {
await saveKwpProjectRouting({
tenantId: ctx.tenantId,
connectionId,
externalStatus: parseKwpStatus(form.get("externalStatus")),
pipelineId: nonEmpty(form.get("pipelineId")),
stageId: nonEmpty(form.get("stageId")),
expectedRevision: form.get("expectedRevision") === null || form.get("expectedRevision") === ""
? null
: parseInteger(form.get("expectedRevision")),
actorUserId: ctx.userId,
});
const query = new URLSearchParams({
connection: connectionId,
q: nonEmpty(form.get("query")),
project: nonEmpty(form.get("externalProjectNumber")),
feedback: "routingSaved",
});
throw redirect(`${kwpProjectImportPath(tenantSlug)}?${query.toString()}`, 303);
}
if (intent === "unlink" || intent === "restore") {
const projectId = nonEmpty(form.get("projectId"));
const expectedBindingRevision = parseInteger(form.get("expectedBindingRevision"));
await getProject({
tenantId: ctx.tenantId,
projectId,
ctx: projectCtx,
});
if (intent === "restore") {
await restoreAndUnlinkKwpProject({
tenantId: ctx.tenantId,
projectId,
expectedBindingRevision,
expectedProjectUpdatedAt: nonEmpty(form.get("expectedProjectUpdatedAt")),
actorUserId: ctx.userId,
});
} else {
await unlinkKwpProject({
tenantId: ctx.tenantId,
projectId,
expectedBindingRevision,
actorUserId: ctx.userId,
});
}
const query = new URLSearchParams({
connection: connectionId,
feedback: intent === "restore" ? "restored" : "unlinked",
});
throw redirect(`${kwpProjectImportPath(tenantSlug)}?${query.toString()}`, 303);
}
if (intent === "approve-contract") {
await approveKwpProjectContract({
tenantId: ctx.tenantId,
connectionId,
observedFingerprint: nonEmpty(form.get("observedFingerprint")),
expectedRevision: parseInteger(form.get("expectedRevision")),
validationProjectNumber: nonEmpty(form.get("externalProjectNumber")),
actorUserId: ctx.userId,
});
throw redirect(`${kwpProjectImportPath(tenantSlug)}?${new URLSearchParams({
connection: connectionId,
feedback: "contractApproved",
}).toString()}`, 303);
}
if (intent === "import") {
const parsed = parseImportPayload(form.get("payload"));
if (parsed.connectionId !== connectionId) throw new Response(null, { status: 400 });
if (parsed.target.kind === "link") {
await getProject({
tenantId: ctx.tenantId,
projectId: parsed.target.projectId,
ctx: projectCtx,
});
}
const result = await importKwpProject({ ...parsed, connectionId, actorUserId: ctx.userId });
throw redirect(`/${tenantSlug}/projects/${result.projectId}?kwp=imported`, 303);
}
throw new Response(null, { status: 400 });
});
} catch (error) {
if (error instanceof Response) throw error;
if (error instanceof KwpProjectDomainError) {
throw redirect(`${kwpProjectImportPath(tenantSlug)}?${new URLSearchParams({
connection: connectionId,
feedback: error.code,
}).toString()}`, 303);
}
throw error;
}
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function KwpProjectImportRoute() {
const { vm } = useLoaderData<LoaderData>();
const navigate = useNavigate();
const submit = useSubmit();
const navigation = useNavigation();
const { csrf } = useRootData();
const navigateWith = (connectionId: string, query: string, project?: string) => {
const params = new URLSearchParams({ connection: connectionId, q: query.trim() });
if (project) params.set("project", project);
void navigate(`?${params.toString()}`);
};
const post = (intent: string, values: Record<string, string>) => {
const form = new FormData();
form.set("intent", intent);
form.set("csrf", csrf ?? "");
for (const [key, value] of Object.entries(values)) form.set(key, value);
void submit(form, { method: "post" });
};
const actions: KwpProjectImportActions = {
onSearch: (connectionId, query) => navigateWith(connectionId, query),
onSelectProject: (connectionId, query, externalProjectNumber) =>
navigateWith(connectionId, query, externalProjectNumber),
onSaveRouting: (input) => post("save-routing", {
connectionId: input.connectionId,
externalStatus: String(input.externalStatus),
pipelineId: input.pipelineId,
stageId: input.stageId,
expectedRevision: input.expectedRevision === null ? "" : String(input.expectedRevision),
externalProjectNumber: input.externalProjectNumber,
query: input.query,
}),
onImport: (input) => post("import", {
connectionId: input.connectionId,
payload: JSON.stringify(input),
}),
onApproveContract: (input) => post("approve-contract", {
connectionId: input.connectionId,
observedFingerprint: input.observedFingerprint,
expectedRevision: String(input.expectedRevision),
externalProjectNumber: input.externalProjectNumber,
}),
onUnlink: (input) => post("unlink", {
connectionId: input.connectionId,
projectId: input.projectId,
expectedBindingRevision: String(input.expectedBindingRevision),
}),
onRestore: (input) => post("restore", {
connectionId: input.connectionId,
projectId: input.projectId,
expectedBindingRevision: String(input.expectedBindingRevision),
expectedProjectUpdatedAt: input.expectedProjectUpdatedAt,
}),
};
return (
<KwpProjectImportPage
vm={vm}
actions={actions}
submitting={navigation.state !== "idle"}
/>
);
}
@@ -0,0 +1,125 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
const getTenantIdMock = vi.fn().mockResolvedValue("t-1");
const verifyPermissionMock = vi.fn().mockResolvedValue(undefined);
const getUserInfoMock = vi.fn().mockResolvedValue({ userId: "u-1" });
const getPluginForTenantMock = vi.fn();
const auditFindManyMock = vi.fn();
vi.mock("~/utils/services/.server/urlService", () => ({
getTenantIdFromUrl: (...args: unknown[]) => getTenantIdMock(...args),
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
verifyUserHasPermission: (...args: unknown[]) => verifyPermissionMock(...args),
}));
vi.mock("~/utils/session.server", () => ({
getUserInfo: (...args: unknown[]) => getUserInfoMock(...args),
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({
t: (key: string, fallback?: string) => fallback ?? key,
})),
}));
vi.mock("~/modules/plugins/services/.server/PluginLifecycleService", () => ({
getPluginForTenant: (...args: unknown[]) => getPluginForTenantMock(...args),
}));
vi.mock("~/utils/db.server", () => ({
dbRead: {
pluginCapabilityUse: {
findMany: (...args: unknown[]) => auditFindManyMock(...args),
},
},
}));
beforeEach(() => {
getTenantIdMock.mockClear();
verifyPermissionMock.mockReset();
verifyPermissionMock.mockResolvedValue(undefined);
getUserInfoMock.mockReset();
getUserInfoMock.mockResolvedValue({ userId: "u-1" });
getPluginForTenantMock.mockReset();
auditFindManyMock.mockReset();
});
describe("plugin audit route", () => {
test("loader stops before plugin lookup and audit reads when audit permission is denied", async () => {
const denial = new Response("Forbidden", { status: 403 });
verifyPermissionMock.mockRejectedValueOnce(denial);
const { loader } = await import("./plugins.$id.audit.js");
await expect(
loader({
request: new Request("http://localhost/app/t-1/settings/plugins/pl-1/audit"),
params: { tenant: "t-1", id: "pl-1" },
context: {},
})
).rejects.toBe(denial);
expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "t-1");
expect(getPluginForTenantMock).not.toHaveBeenCalled();
expect(auditFindManyMock).not.toHaveBeenCalled();
});
test("loader caps and orders capability filter options deterministically", async () => {
getPluginForTenantMock.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()).toMatchObject({
tenantId: "t-1",
userId: "u-1",
});
return {
id: "pl-row-1",
pluginId: "com.acme.audit",
version: "1.0.0",
};
});
auditFindManyMock
.mockResolvedValueOnce([
{
id: "audit-1",
pluginInvocationId: "inv-1",
capability: "log",
outcome: "success",
errorCode: null,
durationMs: 12,
payloadHash: "hash-1",
timestamp: new Date("2026-05-27T10:00:00.000Z"),
},
])
.mockResolvedValueOnce([{ capability: "secret.read" }, { capability: "http.outbound" }, { capability: "log" }]);
const { loader } = await import("./plugins.$id.audit.js");
const response = await loader({
request: new Request("http://localhost/app/acme/settings/plugins/pl-row-1/audit"),
params: { tenant: "acme", id: "pl-row-1" },
context: {},
});
await expect(response.json()).resolves.toMatchObject({
capabilityOptions: ["http.outbound", "log", "secret.read"],
});
expect(auditFindManyMock).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
select: {
id: true,
pluginInvocationId: true,
capability: true,
outcome: true,
errorCode: true,
durationMs: true,
payloadHash: true,
timestamp: true,
},
})
);
expect(auditFindManyMock).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
distinct: ["capability"],
orderBy: [{ capability: "asc" }, { timestamp: "desc" }],
take: 32,
})
);
});
});
@@ -0,0 +1,343 @@
/**
* Phase 06 #23 — Plugin capability-use audit trail UI (tenant admin).
*
* Lists every PluginCapabilityUse row for a given Plugin row owned by
* the current tenant. Loader uses dbRead (read-replica when configured)
* since the page is read-only and the audit table is the chattiest in
* the plugin subsystem.
*
* Filters: capability name + date range (UTC day boundaries). Pagination
* is cursor-based (`timestamp` desc, `id` tiebreaker) — keyset rather
* than offset to stay cheap as the table grows. Cap at 100 rows / page.
*/
import type { LoaderFunctionArgs } from "react-router";
import { Form, Link, useLoaderData, useSearchParams } from "react-router";
import { useTranslation } from "react-i18next";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { getTranslations } from "~/locale/i18next.server";
import { useLocaleFormatters } from "~/locale/format";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { dbRead } from "~/utils/db.server";
import { getUserInfo } from "~/utils/session.server";
import { getPluginForTenant } from "~/modules/plugins/services/.server/PluginLifecycleService";
const PAGE_SIZE = 50;
const MAX_PAGE_SIZE = 100;
const CAPABILITY_FILTER_OPTION_LIMIT = 32;
type AuditRow = {
id: string;
pluginInvocationId: string;
capability: string;
outcome: string;
errorCode: string | null;
durationMs: number | null;
payloadHash: string | null;
timestamp: string;
};
type LoaderData = {
title: string;
tenantSlug: string;
plugin: {
id: string;
pluginId: string;
version: string;
};
filters: {
capability: string | null;
from: string | null;
to: string | null;
};
rows: ReadonlyArray<AuditRow>;
nextCursor: { ts: string; id: string } | null;
capabilityOptions: ReadonlyArray<string>;
};
export const loader = async (args: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(args.params);
await verifyUserHasPermission(args.request, "app.settings.auditTrails.view", tenantId);
const userInfo = await getUserInfo(args.request);
if (!userInfo.userId) {
throw new Response(null, { status: 404 });
}
return runWithRlsContext({ tenantId, userId: userInfo.userId }, () => loadPluginAudit(args, tenantId));
};
async function loadPluginAudit({ request, params }: LoaderFunctionArgs, tenantId: string) {
const { t } = await getTranslations(request);
const pluginRowId = params.id ?? "";
if (pluginRowId.length === 0) {
throw new Response(t("settings.plugins.errors.notFound"), { status: 404 });
}
const plugin = await getPluginForTenant({ tenantId, pluginRowId });
if (!plugin) {
throw new Response(t("settings.plugins.errors.pluginNotFound"), { status: 404 });
}
const url = new URL(request.url);
const capability = stringOrNull(url.searchParams.get("capability"));
const from = stringOrNull(url.searchParams.get("from"));
const to = stringOrNull(url.searchParams.get("to"));
const cursorTs = stringOrNull(url.searchParams.get("cursorTs"));
const cursorId = stringOrNull(url.searchParams.get("cursorId"));
const where: Record<string, unknown> = {
tenantId,
pluginId: plugin.pluginId,
};
if (capability) {
where.capability = capability;
}
if (from || to) {
const range: Record<string, Date> = {};
if (from) {
const d = parseDate(from);
if (d) range.gte = d;
}
if (to) {
const d = parseDate(to);
if (d) range.lt = addDays(d, 1); // exclusive upper bound
}
if (Object.keys(range).length > 0) {
where.timestamp = range;
}
}
if (cursorTs && cursorId) {
const cursorDate = parseDate(cursorTs) ?? new Date(cursorTs);
if (!Number.isNaN(cursorDate.getTime())) {
// Keyset pagination: (timestamp, id) tuple strictly before cursor.
where.OR = [{ timestamp: { lt: cursorDate } }, { timestamp: cursorDate, id: { lt: cursorId } }];
}
}
// Capability options: distinct capability names seen in the last 30
// days for this plugin. Cheap because of the (tenantId, pluginId,
// timestamp DESC) index — bounded by row count, not table scan.
const since = addDays(new Date(), -30);
const [fetched, distinct] = await Promise.all([
dbRead.pluginCapabilityUse.findMany({
where: where as never,
select: {
id: true,
pluginInvocationId: true,
capability: true,
outcome: true,
errorCode: true,
durationMs: true,
payloadHash: true,
timestamp: true,
},
orderBy: [{ timestamp: "desc" }, { id: "desc" }],
take: Math.min(MAX_PAGE_SIZE, PAGE_SIZE) + 1,
}),
dbRead.pluginCapabilityUse.findMany({
where: { tenantId, pluginId: plugin.pluginId, timestamp: { gte: since } },
select: { capability: true },
distinct: ["capability"],
orderBy: [{ capability: "asc" }, { timestamp: "desc" }],
take: CAPABILITY_FILTER_OPTION_LIMIT,
}),
]);
const rowsPage = fetched.slice(0, PAGE_SIZE);
const nextCursor =
fetched.length > PAGE_SIZE && rowsPage.length > 0
? {
ts: rowsPage[rowsPage.length - 1]!.timestamp.toISOString(),
id: rowsPage[rowsPage.length - 1]!.id,
}
: null;
const data: LoaderData = {
title: `${t("settings.plugins.audit.title")} · ${plugin.pluginId}`,
tenantSlug: params.tenant ?? "",
plugin: { id: plugin.id, pluginId: plugin.pluginId, version: plugin.version },
filters: { capability, from, to },
rows: rowsPage.map((r) => ({
id: r.id,
pluginInvocationId: r.pluginInvocationId,
capability: r.capability,
outcome: r.outcome,
errorCode: r.errorCode ?? null,
durationMs: r.durationMs ?? null,
payloadHash: r.payloadHash ?? null,
timestamp: r.timestamp.toISOString(),
})),
nextCursor,
capabilityOptions: distinct.map((d) => d.capability).sort(),
};
return Response.json(data);
}
function stringOrNull(value: string | null): string | null {
if (!value) return null;
const trimmed = value.trim();
return trimmed.length === 0 ? null : trimmed;
}
function parseDate(input: string): Date | null {
// Accept YYYY-MM-DD and full ISO strings.
const tryYmd = /^\d{4}-\d{2}-\d{2}$/u.test(input) ? `${input}T00:00:00.000Z` : input;
const d = new Date(tryYmd);
if (Number.isNaN(d.getTime())) return null;
return d;
}
function addDays(date: Date, days: number): Date {
const d = new Date(date.getTime());
d.setUTCDate(d.getUTCDate() + days);
return d;
}
export default function PluginAuditTrailRoute() {
const data = useLoaderData<LoaderData>();
const [params] = useSearchParams();
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const nextHref = data.nextCursor
? withParams(params, {
cursorTs: data.nextCursor.ts,
cursorId: data.nextCursor.id,
})
: null;
const outcomeLabel = (outcome: string) => {
if (outcome === "success" || outcome === "denied" || outcome === "error") {
return t(`settings.plugins.audit.outcomes.${outcome}`);
}
return outcome;
};
return (
<div className="space-y-6 p-6">
<header className="space-y-1">
<p className="text-xs text-gray-500">
<Link to={appPath({ tenantSlug: data.tenantSlug, path: "settings/integrations/plugins" })} className="text-blue-600 hover:underline">
{t("settings.plugins.audit.backToPlugins")}
</Link>
</p>
<h1 className="text-xl font-semibold">
{t("settings.plugins.audit.heading")} · {data.plugin.pluginId}
</h1>
<p className="text-sm text-gray-600">{t("settings.plugins.audit.description")}</p>
</header>
<Form method="get" className="flex flex-wrap items-end gap-3 rounded border border-gray-200 bg-white p-4">
<label className="flex flex-col text-xs text-gray-600">
<span className="mb-1">{t("settings.plugins.audit.filters.capability")}</span>
<select
name="capability"
defaultValue={data.filters.capability ?? ""}
onChange={(event) => event.currentTarget.form?.requestSubmit()}
className="rounded border border-gray-300 px-2 py-1 text-sm"
>
<option value="">{t("settings.plugins.audit.filters.all")}</option>
{data.capabilityOptions.map((cap) => (
<option key={cap} value={cap}>
{cap}
</option>
))}
</select>
</label>
<label className="flex flex-col text-xs text-gray-600">
<span className="mb-1">{t("settings.plugins.audit.filters.fromUtc")}</span>
<input
type="date"
name="from"
defaultValue={data.filters.from ?? ""}
onChange={(event) => event.currentTarget.form?.requestSubmit()}
className="rounded border border-gray-300 px-2 py-1 text-sm"
/>
</label>
<label className="flex flex-col text-xs text-gray-600">
<span className="mb-1">{t("settings.plugins.audit.filters.toUtc")}</span>
<input
type="date"
name="to"
defaultValue={data.filters.to ?? ""}
onChange={(event) => event.currentTarget.form?.requestSubmit()}
className="rounded border border-gray-300 px-2 py-1 text-sm"
/>
</label>
<Link to="." className="text-xs text-gray-500 hover:underline">
{t("settings.plugins.audit.filters.reset")}
</Link>
</Form>
{data.rows.length === 0 ? (
<p className="rounded border border-dashed border-gray-300 p-6 text-sm text-gray-600">{t("settings.plugins.audit.empty")}</p>
) : (
<div className="overflow-x-auto rounded border border-gray-200">
<table className="w-full text-left text-sm">
<thead className="bg-gray-50 text-xs tracking-wide text-gray-500 uppercase">
<tr>
<th className="px-3 py-2">{t("settings.plugins.audit.table.timestamp")}</th>
<th className="px-3 py-2">{t("settings.plugins.audit.table.capability")}</th>
<th className="px-3 py-2">{t("settings.plugins.audit.table.outcome")}</th>
<th className="px-3 py-2">{t("settings.plugins.audit.table.duration")}</th>
<th className="px-3 py-2">{t("settings.plugins.audit.table.invocation")}</th>
<th className="px-3 py-2">{t("settings.plugins.audit.table.payloadHash")}</th>
</tr>
</thead>
<tbody>
{data.rows.map((row) => (
<tr key={row.id} className="border-t border-gray-100">
<td className="px-3 py-2 font-mono text-xs text-gray-700">{formatters.date(row.timestamp, { dateStyle: "medium", timeStyle: "medium" })}</td>
<td className="px-3 py-2 font-mono text-xs">{row.capability}</td>
<td className="px-3 py-2 text-xs">
<span
className={
row.outcome === "success"
? "rounded bg-green-100 px-2 py-0.5 text-green-800"
: row.outcome === "denied"
? "rounded bg-amber-100 px-2 py-0.5 text-amber-800"
: "rounded bg-red-100 px-2 py-0.5 text-red-800"
}
>
{outcomeLabel(row.outcome)}
{row.errorCode ? ` · ${row.errorCode}` : ""}
</span>
</td>
<td className="px-3 py-2 text-xs text-gray-600">
{row.durationMs === null
? t("shared.notAvailable")
: t("settings.plugins.audit.durationMs", {
duration: formatters.number(row.durationMs),
})}
</td>
<td className="px-3 py-2 font-mono text-xs text-gray-500" title={row.pluginInvocationId}>
{row.pluginInvocationId.slice(0, 8)}…
</td>
<td className="px-3 py-2 font-mono text-xs text-gray-500" title={row.payloadHash ?? ""}>
{row.payloadHash ? `${row.payloadHash.slice(0, 12)}…` : t("shared.notSet")}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{nextHref ? (
<div className="flex justify-end">
<Link to={`?${nextHref}`} className="rounded border border-gray-300 bg-white px-3 py-1 text-sm hover:bg-gray-50">
{t("settings.plugins.audit.nextPage")}
</Link>
</div>
) : null}
</div>
);
}
function withParams(current: URLSearchParams, next: Record<string, string>): string {
const merged = new URLSearchParams(current);
for (const [k, v] of Object.entries(next)) {
merged.set(k, v);
}
return merged.toString();
}
@@ -0,0 +1,700 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
const getTenantIdMock = vi.fn().mockResolvedValue("tenant-1");
const verifyPermissionMock = vi.fn().mockResolvedValue(undefined);
const loadPluginSettingsPageDataMock = vi.fn();
const setPluginUserSettingMock = vi.fn();
const reportPluginSettingsFrameViolationMock = vi.fn();
const getUserInfoMock = vi.fn();
const validateCSRFTokenMock = vi.fn();
const getUserMock = vi.fn();
const consumeRateLimitMock = vi.fn();
vi.mock("~/utils/services/.server/urlService", () => ({
getTenantIdFromUrl: (...args: unknown[]) => getTenantIdMock(...args),
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
verifyUserHasPermission: (...args: unknown[]) => verifyPermissionMock(...args),
}));
vi.mock("~/utils/session.server", () => ({
getUserInfo: (...args: unknown[]) => getUserInfoMock(...args),
validateCSRFToken: (...args: unknown[]) => validateCSRFTokenMock(...args),
}));
vi.mock("~/utils/db/users.db.server", () => ({
getUser: (...args: unknown[]) => getUserMock(...args),
}));
vi.mock("~/shared-store.server", () => ({
getSharedStore: vi.fn(() => ({ kind: "test-store" })),
}));
vi.mock("~/services/auth/auth-rate-limit-key.server", () => ({
getPseudonymousAuthBucketKey: () => "pseudonymous-plugin-settings",
}));
vi.mock("@hivegrid/shared-store", () => ({
createSlidingWindowRateLimiter: vi.fn(() => ({
consume: (...args: unknown[]) => consumeRateLimitMock(...args),
})),
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({
t: (key: string, vars?: Record<string, unknown>) => (vars ? `${key}:${JSON.stringify(vars)}` : key),
})),
}));
vi.mock("~/modules/plugins/services/.server/PluginSettingsService", () => {
class PluginSettingsServiceError extends Error {
constructor(
public readonly code: string,
message: string
) {
super(message);
}
}
return {
PluginSettingsServiceError,
loadPluginSettingsPageData: (...args: unknown[]) => loadPluginSettingsPageDataMock(...args),
reportPluginSettingsFrameViolation: (...args: unknown[]) => reportPluginSettingsFrameViolationMock(...args),
setPluginUserSetting: (...args: unknown[]) => setPluginUserSettingMock(...args),
};
});
beforeEach(() => {
getTenantIdMock.mockClear();
verifyPermissionMock.mockReset();
verifyPermissionMock.mockResolvedValue(undefined);
loadPluginSettingsPageDataMock.mockReset();
setPluginUserSettingMock.mockReset();
reportPluginSettingsFrameViolationMock.mockReset();
reportPluginSettingsFrameViolationMock.mockResolvedValue(undefined);
getUserInfoMock.mockReset();
getUserInfoMock.mockResolvedValue({ userId: "user-1" });
validateCSRFTokenMock.mockReset();
validateCSRFTokenMock.mockResolvedValue(undefined);
getUserMock.mockReset();
getUserMock.mockResolvedValue({ email: "user@example.com" });
consumeRateLimitMock.mockReset();
consumeRateLimitMock.mockResolvedValue({ allowed: true });
});
describe("plugin settings route", () => {
test("headers add anti-framing policy while preserving server timing", async () => {
const { headers } = await import("./plugins.$id.js");
const responseHeaders = headers({
loaderHeaders: new Headers({ "Server-Timing": "plugin;dur=12" }),
parentHeaders: new Headers(),
actionHeaders: new Headers(),
errorHeaders: undefined,
});
expect(responseHeaders.get("Content-Security-Policy")).toBe(
"default-src 'self'; script-src 'self'; connect-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-src 'self'; child-src 'self'; worker-src 'none'; media-src 'none'; manifest-src 'none'; frame-ancestors 'self'; base-uri 'self'; object-src 'none'; form-action 'self'; navigate-to 'self'"
);
expect(responseHeaders.get("X-Frame-Options")).toBe("SAMEORIGIN");
expect(responseHeaders.get("Server-Timing")).toBe("plugin;dur=12");
});
test("headers deny powerful browser capabilities for embedded plugin settings", async () => {
const { headers } = await import("./plugins.$id.js");
const responseHeaders = headers({
loaderHeaders: new Headers(),
parentHeaders: new Headers(),
actionHeaders: new Headers(),
errorHeaders: undefined,
});
const policy = responseHeaders.get("Permissions-Policy") ?? "";
for (const directive of [
"camera=()",
"microphone=()",
"geolocation=()",
"clipboard-read=()",
"clipboard-write=()",
"display-capture=()",
"fullscreen=()",
"payment=()",
"storage-access=()",
"usb=()",
"web-share=()",
]) {
expect(policy).toContain(directive);
}
expect(policy).not.toContain("*");
expect(policy).not.toContain("self");
});
test("headers retain plugin restrictions while adding the request script nonce", async () => {
const { headers } = await import("./plugins.$id.js");
const nonce = "aBcDeFgHiJkLmNoPqRsTuVwX";
const responseHeaders = headers({
loaderHeaders: new Headers(),
parentHeaders: new Headers({ "x-hivegrid-csp-nonce": nonce }),
actionHeaders: new Headers(),
errorHeaders: undefined,
});
const policy = responseHeaders.get("Content-Security-Policy") ?? "";
expect(policy).toContain(`script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`);
expect(policy).toContain("connect-src 'self'");
expect(policy).toContain("worker-src 'none'");
expect(policy).toContain("media-src 'none'");
expect(policy).toContain("frame-ancestors 'self'");
});
test("loader stops before settings lookup when use permission is denied", async () => {
const denial = new Response("Forbidden", { status: 403 });
verifyPermissionMock.mockRejectedValueOnce(denial);
const { loader } = await import("./plugins.$id.js");
await expect(
loader({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1"),
params: { tenant: "acme", id: "pl-1" },
context: {},
})
).rejects.toBe(denial);
expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.plugins.use", "tenant-1");
expect(loadPluginSettingsPageDataMock).not.toHaveBeenCalled();
});
test("loader returns plugin frame HTML and per-user settings for tenant-scoped plugins", async () => {
loadPluginSettingsPageDataMock.mockResolvedValue({
plugin: { id: "pl-1", pluginId: "com.acme.settings", version: "1.0.0" },
entry: "ui/settings.html",
trustedHtml: "<main>Settings</main>",
settings: { theme: "dark" },
});
const { loader } = await import("./plugins.$id.js");
const response = await loader({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1"),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
await expect(response.json()).resolves.toMatchObject({
plugin: { id: "pl-1", pluginId: "com.acme.settings", version: "1.0.0" },
trustedHtml: "<main>Settings</main>",
settings: { theme: "dark" },
});
expect(loadPluginSettingsPageDataMock).toHaveBeenCalledWith({ tenantId: "tenant-1", pluginRowId: "pl-1", userId: "user-1" });
});
test("loader stops before settings lookup when no authenticated user is available", async () => {
getUserInfoMock.mockResolvedValueOnce({ userId: null });
const { loader } = await import("./plugins.$id.js");
await expect(
loader({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1"),
params: { tenant: "acme", id: "pl-1" },
context: {},
})
).rejects.toMatchObject({ status: 401 });
expect(loadPluginSettingsPageDataMock).not.toHaveBeenCalled();
});
test("loader maps missing settings UI to 404", async () => {
const { PluginSettingsServiceError } = await import("~/modules/plugins/services/.server/PluginSettingsService");
loadPluginSettingsPageDataMock.mockRejectedValue(new PluginSettingsServiceError("settings_ui_unavailable", "no ui"));
const { loader } = await import("./plugins.$id.js");
await expect(
loader({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1"),
params: { tenant: "acme", id: "pl-1" },
context: {},
})
).rejects.toMatchObject({ status: 404 });
});
test("loader maps unsafe and oversized settings UI errors to hardened statuses", async () => {
const { PluginSettingsServiceError } = await import("~/modules/plugins/services/.server/PluginSettingsService");
const { loader } = await import("./plugins.$id.js");
loadPluginSettingsPageDataMock.mockRejectedValueOnce(new PluginSettingsServiceError("settings_ui_entry_unsafe", "unsafe"));
await expect(
loader({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1"),
params: { tenant: "acme", id: "pl-1" },
context: {},
})
).rejects.toMatchObject({ status: 400 });
loadPluginSettingsPageDataMock.mockRejectedValueOnce(new PluginSettingsServiceError("settings_ui_file_too_large", "too large"));
await expect(
loader({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1"),
params: { tenant: "acme", id: "pl-1" },
context: {},
})
).rejects.toMatchObject({ status: 413 });
});
test("action stores one setting through the per-user settings service", async () => {
setPluginUserSettingMock.mockResolvedValue({ key: "theme", value: "light", settings: { theme: "light" } });
const { action } = await import("./plugins.$id.js");
const request = new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: {
"content-type": "application/json",
"cf-connecting-ip": "203.0.113.5",
"x-forwarded-for": "198.51.100.5, 173.245.48.10",
},
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
});
const response = await action({
request,
params: { tenant: "acme", id: "pl-1" },
context: {},
});
await expect(response.json()).resolves.toEqual({ ok: true, key: "theme", value: "light", settings: { theme: "light" } });
expect(verifyPermissionMock).toHaveBeenCalledWith(request, "app.plugins.use", "tenant-1");
expect(validateCSRFTokenMock).toHaveBeenCalledWith(request, { headerOnly: true });
expect(setPluginUserSettingMock).toHaveBeenCalledWith({
tenantId: "tenant-1",
pluginRowId: "pl-1",
userId: "user-1",
key: "theme",
value: "light",
actor: { userId: "user-1", email: "user@example.com", ip: "203.0.113.5" },
});
});
test("action accepts json content types with charset parameters", async () => {
setPluginUserSettingMock.mockResolvedValue({ key: "theme", value: "light", settings: { theme: "light" } });
const { action } = await import("./plugins.$id.js");
const request = new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json; charset=utf-8" },
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
});
const response = await action({
request,
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({ ok: true, key: "theme" });
expect(consumeRateLimitMock).toHaveBeenCalledOnce();
expect(setPluginUserSettingMock).toHaveBeenCalledOnce();
});
test("action reports plugin settings frame violations without persisting settings", async () => {
const { action } = await import("./plugins.$id.js");
const request = new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: {
"content-type": "application/json",
"cf-connecting-ip": "203.0.113.7",
"x-forwarded-for": "198.51.100.7, 173.245.48.10",
},
body: JSON.stringify({ op: "reportFrameViolation", reason: "wrong_origin", csrf: "csrf-token" }),
});
const response = await action({
request,
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual({ ok: true });
expect(verifyPermissionMock).toHaveBeenCalledWith(request, "app.plugins.use", "tenant-1");
expect(validateCSRFTokenMock).toHaveBeenCalledWith(request, { headerOnly: true });
expect(consumeRateLimitMock).toHaveBeenCalledWith("pseudonymous-plugin-settings");
expect(reportPluginSettingsFrameViolationMock).toHaveBeenCalledWith({
tenantId: "tenant-1",
pluginRowId: "pl-1",
reason: "wrong_origin",
actor: { userId: "user-1", email: "user@example.com", ip: "203.0.113.7" },
});
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action rejects invalid plugin settings frame violation reasons before rate limiting", async () => {
const { action } = await import("./plugins.$id.js");
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ op: "reportFrameViolation", reason: "raw-payload", csrf: "csrf-token" }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({
error: "invalid_frame_violation_reason",
message: "settings.plugins.settings.errors.invalid_frame_violation_reason",
});
expect(consumeRateLimitMock).not.toHaveBeenCalled();
expect(reportPluginSettingsFrameViolationMock).not.toHaveBeenCalled();
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action rate limits plugin settings frame violation reports", async () => {
consumeRateLimitMock.mockResolvedValueOnce({ allowed: false });
const { action } = await import("./plugins.$id.js");
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ op: "reportFrameViolation", reason: "wrong_source", csrf: "csrf-token" }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(429);
expect(response.headers.get("Retry-After")).toBe("60");
await expect(response.json()).resolves.toEqual({
error: "rate_limited",
message: 'settings.plugins.settings.errors.rate_limited:{"perMin":120}',
});
expect(reportPluginSettingsFrameViolationMock).not.toHaveBeenCalled();
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action denies setting writes with use permission before CSRF and body parsing", async () => {
const denial = new Response("Forbidden", { status: 403 });
verifyPermissionMock.mockRejectedValueOnce(denial);
const { action } = await import("./plugins.$id.js");
await expect(
action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json" },
body: "{",
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
})
).rejects.toBe(denial);
expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.plugins.use", "tenant-1");
expect(validateCSRFTokenMock).not.toHaveBeenCalled();
expect(getUserInfoMock).not.toHaveBeenCalled();
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action rejects non-json setting writes before parsing or rate limiting", async () => {
const { action } = await import("./plugins.$id.js");
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "text/plain" },
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(415);
await expect(response.json()).resolves.toEqual({
error: "unsupported_media_type",
message: "settings.plugins.settings.errors.unsupported_media_type",
});
expect(validateCSRFTokenMock).not.toHaveBeenCalled();
expect(consumeRateLimitMock).not.toHaveBeenCalled();
expect(getUserMock).not.toHaveBeenCalled();
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action validates op and key before user lookup or setting writes", async () => {
const { action } = await import("./plugins.$id.js");
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ op: "getSetting", key: "theme", csrf: "csrf-token" }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({
error: "missing_fields",
message: "settings.plugins.settings.errors.missing_fields",
});
expect(validateCSRFTokenMock).toHaveBeenCalled();
expect(consumeRateLimitMock).not.toHaveBeenCalled();
expect(getUserMock).not.toHaveBeenCalled();
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action validates setting key and value schema before rate limiting or persistence", async () => {
const { action } = await import("./plugins.$id.js");
const cases = [
{ key: "../theme", value: "dark", error: "settings_key_invalid" },
{ key: "__proto__", value: "polluted", error: "settings_key_invalid" },
{ key: "apiKey", value: "abc", error: "settings_key_secret_like" },
{ key: "authorization", value: "Bearer abc", error: "settings_key_secret_like" },
{ key: "clientSecret", value: "abc", error: "settings_key_secret_like" },
{ key: "theme", value: undefined, error: "settings_value_invalid" },
{ key: "appearance", value: { theme: { accessToken: "must-not-persist" } }, error: "settings_value_invalid" },
{ key: "appearance", value: { headers: { authorization: "Bearer must-not-persist" } }, error: "settings_value_invalid" },
{ key: "blob", value: "x".repeat(33 * 1024), error: "settings_value_too_large" },
];
for (const item of cases) {
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ op: "setSetting", key: item.key, value: item.value, csrf: "csrf-token" }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status, item.error).toBe(400);
await expect(response.json()).resolves.toEqual({
error: item.error,
message: `settings.plugins.settings.errors.${item.error}`,
});
}
expect(validateCSRFTokenMock).toHaveBeenCalledTimes(cases.length);
expect(consumeRateLimitMock).not.toHaveBeenCalled();
expect(getUserMock).not.toHaveBeenCalled();
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action returns 400 for malformed settings JSON", async () => {
const { action } = await import("./plugins.$id.js");
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json" },
body: "{",
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({
error: "invalid_json",
message: "settings.plugins.settings.errors.invalid_json",
});
expect(consumeRateLimitMock).not.toHaveBeenCalled();
expect(getUserMock).not.toHaveBeenCalled();
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action rejects oversized settings JSON before parsing and rate limiting", async () => {
const { action } = await import("./plugins.$id.js");
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json", "content-length": String(81 * 1024) },
body: JSON.stringify({ op: "setSetting", key: "blob", value: "x" }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({
error: "invalid_json",
message: "settings.plugins.settings.errors.invalid_json",
});
expect(consumeRateLimitMock).not.toHaveBeenCalled();
expect(getUserMock).not.toHaveBeenCalled();
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action rejects oversized settings JSON even when content-length is absent", async () => {
const { action } = await import("./plugins.$id.js");
const oversizedValue = "x".repeat(81 * 1024);
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ op: "setSetting", key: "blob", value: oversizedValue }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({
error: "invalid_json",
message: "settings.plugins.settings.errors.invalid_json",
});
expect(consumeRateLimitMock).not.toHaveBeenCalled();
expect(getUserMock).not.toHaveBeenCalled();
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action rate limits per-user plugin setting writes before persistence", async () => {
consumeRateLimitMock.mockResolvedValueOnce({ allowed: false });
const { action } = await import("./plugins.$id.js");
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(429);
expect(response.headers.get("Retry-After")).toBe("60");
await expect(response.json()).resolves.toEqual({
error: "rate_limited",
message: 'settings.plugins.settings.errors.rate_limited:{"perMin":60}',
});
expect(getUserMock).not.toHaveBeenCalled();
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action fails closed in every environment when plugin settings rate limit storage is unavailable", async () => {
consumeRateLimitMock.mockRejectedValueOnce(new Error("redis unavailable"));
setPluginUserSettingMock.mockResolvedValue({ key: "theme", value: "light", settings: { theme: "light" } });
const { action } = await import("./plugins.$id.js");
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(503);
expect(response.headers.get("Retry-After")).toBe("60");
await expect(response.json()).resolves.toEqual({
error: "rate_limit_unavailable",
message: "settings.plugins.settings.errors.rate_limit_unavailable",
});
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action fails closed in production when plugin settings rate limit storage is unavailable", async () => {
const originalNodeEnv = process.env.NODE_ENV;
const originalFailOpen = process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN;
process.env.NODE_ENV = "production";
delete process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN;
consumeRateLimitMock.mockRejectedValueOnce(new Error("redis unavailable"));
const { action } = await import("./plugins.$id.js");
try {
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(503);
expect(response.headers.get("Retry-After")).toBe("60");
await expect(response.json()).resolves.toEqual({
error: "rate_limit_unavailable",
message: "settings.plugins.settings.errors.rate_limit_unavailable",
});
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
} finally {
if (originalNodeEnv === undefined) delete process.env.NODE_ENV;
else process.env.NODE_ENV = originalNodeEnv;
if (originalFailOpen === undefined) delete process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN;
else process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN = originalFailOpen;
}
});
test("action ignores the fail-open escape hatch in production when plugin settings rate limit storage is unavailable", async () => {
const originalNodeEnv = process.env.NODE_ENV;
const originalFailOpen = process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN;
process.env.NODE_ENV = "production";
process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN = "true";
consumeRateLimitMock.mockRejectedValueOnce(new Error("redis unavailable"));
const { action } = await import("./plugins.$id.js");
try {
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(503);
await expect(response.json()).resolves.toEqual({
error: "rate_limit_unavailable",
message: "settings.plugins.settings.errors.rate_limit_unavailable",
});
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
} finally {
if (originalNodeEnv === undefined) delete process.env.NODE_ENV;
else process.env.NODE_ENV = originalNodeEnv;
if (originalFailOpen === undefined) delete process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN;
else process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN = originalFailOpen;
}
});
test("action uses x-real-ip when x-forwarded-for is absent", async () => {
setPluginUserSettingMock.mockResolvedValue({ key: "theme", value: "light", settings: { theme: "light" } });
const { action } = await import("./plugins.$id.js");
await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json", "x-real-ip": "198.51.100.9" },
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(setPluginUserSettingMock).toHaveBeenCalledWith(expect.objectContaining({ actor: expect.objectContaining({ ip: "198.51.100.9" }) }));
});
test("action maps service validation errors to localized JSON responses", async () => {
const { PluginSettingsServiceError } = await import("~/modules/plugins/services/.server/PluginSettingsService");
setPluginUserSettingMock.mockRejectedValue(new PluginSettingsServiceError("settings_value_invalid", "invalid value"));
const { action } = await import("./plugins.$id.js");
const response = await action({
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ op: "setSetting", key: "appearance", value: { theme: "dark" }, csrf: "csrf-token" }),
}),
params: { tenant: "acme", id: "pl-1" },
context: {},
});
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({
error: "settings_value_invalid",
message: "settings.plugins.settings.errors.settings_value_invalid",
});
});
});
@@ -0,0 +1,490 @@
import { useCallback, useMemo, useRef, useState } from "react";
import type { ActionFunctionArgs, HeadersFunction, LoaderFunctionArgs } from "react-router";
import { Link, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import { createSlidingWindowRateLimiter } from "@hivegrid/shared-store";
import { getTranslations } from "~/locale/i18next.server";
import { PluginSettingsFrame } from "~/modules/plugins/components/PluginSettingsFrame";
import {
loadPluginSettingsPageData,
PluginSettingsServiceError,
reportPluginSettingsFrameViolation,
setPluginUserSetting,
type PluginSettingsFrameViolationReason,
type PluginSettingValue,
type PluginUserSettings,
} from "~/modules/plugins/services/.server/PluginSettingsService";
import {
isPluginSettingKeyFormatSafe,
isPluginSettingKeyReserved,
isPluginSettingKeySecretLike,
isPluginSettingValueShapeSafe,
isPluginSettingValueWithinSize,
} from "~/modules/plugins/utils/pluginSettingsValidation";
import { getSharedStore } from "~/shared-store.server";
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { useRootData } from "~/utils/data/useRootData";
import { getUser } from "~/utils/db/users.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { buildDocumentContentSecurityPolicy, getCspNonceFromHeaders } from "~/utils/security/contentSecurityPolicy";
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
import { getPseudonymousAuthBucketKey } from "~/services/auth/auth-rate-limit-key.server";
type LoaderData = {
title: string;
tenantSlug: string;
plugin: {
id: string;
pluginId: string;
version: string;
};
trustedHtml: string;
settings: PluginUserSettings;
};
const SETTINGS_WRITE_RATE_LIMIT_PREFIX = "plugin-settings-write-route:rl";
const SETTINGS_FRAME_VIOLATION_RATE_LIMIT_PREFIX = "plugin-settings-frame-violation-route:rl";
const PLUGIN_SETTINGS_ROUTE_MAX_BODY_BYTES = 80 * 1024;
const PLUGIN_SETTINGS_FRAME_VIOLATION_REPORT_INTERVAL_MS = 60_000;
const PLUGIN_SETTINGS_FRAME_VIOLATION_REASONS = new Set<PluginSettingsFrameViolationReason>([
"wrong_origin",
"wrong_source",
"invalid_payload",
"unexpected_navigation",
]);
const PLUGIN_SETTINGS_ROUTE_CSP = [
"default-src 'self'",
"script-src 'self'",
"connect-src 'self'",
"img-src 'self' data: blob:",
"font-src 'self' data:",
"style-src 'self' 'unsafe-inline'",
"frame-src 'self'",
"child-src 'self'",
"worker-src 'none'",
"media-src 'none'",
"manifest-src 'none'",
"frame-ancestors 'self'",
"base-uri 'self'",
"object-src 'none'",
"form-action 'self'",
"navigate-to 'self'",
].join("; ");
const PLUGIN_SETTINGS_ROUTE_PERMISSION_POLICY = [
"accelerometer=()",
"ambient-light-sensor=()",
"autoplay=()",
"bluetooth=()",
"camera=()",
"clipboard-read=()",
"clipboard-write=()",
"display-capture=()",
"encrypted-media=()",
"fullscreen=()",
"gamepad=()",
"geolocation=()",
"gyroscope=()",
"hid=()",
"identity-credentials-get=()",
"idle-detection=()",
"local-fonts=()",
"magnetometer=()",
"microphone=()",
"midi=()",
"otp-credentials=()",
"payment=()",
"picture-in-picture=()",
"publickey-credentials-get=()",
"screen-wake-lock=()",
"serial=()",
"speaker-selection=()",
"storage-access=()",
"usb=()",
"web-share=()",
"xr-spatial-tracking=()",
].join(", ");
export const headers: HeadersFunction = (args) => {
const responseHeaders = new Headers(serverTimingHeaders(args));
const nonce = getCspNonceFromHeaders(args.loaderHeaders, args.parentHeaders, args.actionHeaders);
responseHeaders.set("Content-Security-Policy", nonce ? buildDocumentContentSecurityPolicy(nonce, PLUGIN_SETTINGS_ROUTE_CSP) : PLUGIN_SETTINGS_ROUTE_CSP);
responseHeaders.set("Permissions-Policy", PLUGIN_SETTINGS_ROUTE_PERMISSION_POLICY);
responseHeaders.set("X-Frame-Options", "SAMEORIGIN");
return responseHeaders;
};
type JsonObjectResult = { ok: true; value: Record<string, unknown> } | { ok: false };
type SettingsWritePayloadError = "settings_key_invalid" | "settings_key_secret_like" | "settings_value_invalid" | "settings_value_too_large";
function hasJsonContentType(request: Request): boolean {
const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
return contentType.split(";", 1)[0]?.trim() === "application/json";
}
async function readJsonObject(request: Request): Promise<JsonObjectResult> {
const contentLength = Number(request.headers.get("content-length") ?? "0");
if (Number.isFinite(contentLength) && contentLength > PLUGIN_SETTINGS_ROUTE_MAX_BODY_BYTES) {
return { ok: false };
}
try {
const text = await readLimitedRequestText(request, PLUGIN_SETTINGS_ROUTE_MAX_BODY_BYTES);
if (text === null) return { ok: false };
const value = JSON.parse(text) as unknown;
if (!value || typeof value !== "object" || Array.isArray(value)) {
return { ok: false };
}
return { ok: true, value: value as Record<string, unknown> };
} catch {
return { ok: false };
}
}
async function readLimitedRequestText(request: Request, maxBytes: number): Promise<string | null> {
if (!request.body) return null;
const reader = request.body.getReader();
const decoder = new TextDecoder();
let bytes = 0;
let text = "";
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
bytes += value.byteLength;
if (bytes > maxBytes) {
await reader.cancel();
return null;
}
text += decoder.decode(value, { stream: true });
}
text += decoder.decode();
return text;
} finally {
reader.releaseLock();
}
}
function resolveSettingsWriteRateLimitPerMin(): number {
const raw = process.env.PLUGIN_SETTINGS_WRITE_RATE_LIMIT_PER_MIN;
if (typeof raw !== "string" || raw.length === 0) return 60;
const parsed = Number.parseInt(raw, 10);
if (!Number.isFinite(parsed) || parsed <= 0) return 60;
return parsed;
}
function resolveFrameViolationRateLimitPerMin(): number {
const raw = process.env.PLUGIN_SETTINGS_FRAME_VIOLATION_RATE_LIMIT_PER_MIN;
if (typeof raw !== "string" || raw.length === 0) return 120;
const parsed = Number.parseInt(raw, 10);
if (!Number.isFinite(parsed) || parsed <= 0) return 120;
return parsed;
}
function getPluginSettingsLoaderErrorStatus(code: PluginSettingsServiceError["code"]): number {
if (code === "settings_ui_file_too_large") return 413;
if (code === "settings_ui_entry_unsafe") return 400;
return 404;
}
function getSettingsWritePayloadError(key: string, value: unknown): SettingsWritePayloadError | null {
if (!isPluginSettingKeyFormatSafe(key) || isPluginSettingKeyReserved(key)) {
return "settings_key_invalid";
}
if (isPluginSettingKeySecretLike(key)) {
return "settings_key_secret_like";
}
if (!isPluginSettingValueShapeSafe(value)) {
return "settings_value_invalid";
}
return isPluginSettingValueWithinSize(value) ? null : "settings_value_too_large";
}
function isPluginSettingsFrameViolationReason(reason: unknown): reason is PluginSettingsFrameViolationReason {
return typeof reason === "string" && PLUGIN_SETTINGS_FRAME_VIOLATION_REASONS.has(reason as PluginSettingsFrameViolationReason);
}
// The settings iframe writes hit this UI route's action through React Router's
// single-fetch endpoint (`<path>.data`), so the action's `Response.json(...)`
// comes back turbo-stream encoded (`text/x-script`) rather than as raw JSON.
// Decode that envelope (`{ data: <actionResult> }`) here; keep the plain-JSON
// branch for any caller that still receives a raw JSON response.
function pluginSettingsActionUrl(): string {
// The component is rendered at the plugin-settings DETAIL route, so the current
// pathname IS that route. A bare `fetch(".")` would resolve to the parent
// plugins-list route (its action does not handle setSetting), so target the
// detail route's single-fetch endpoint explicitly.
return `${window.location.pathname.replace(/\/$/u, "")}.data`;
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.plugins.use", tenantId);
const [{ t }, userInfo] = await Promise.all([getTranslations(request), getUserInfo(request)]);
if (!userInfo.userId) {
throw new Response(t("settings.plugins.settings.errors.unauthorized"), { status: 401 });
}
const pluginRowId = params.id ?? "";
if (pluginRowId.length === 0) {
throw new Response(t("settings.plugins.errors.notFound"), { status: 404 });
}
try {
const settingsPage = await loadPluginSettingsPageData({ tenantId, pluginRowId, userId: userInfo.userId });
const data: LoaderData = {
title: `${t("settings.plugins.settings.title")} · ${settingsPage.plugin.pluginId}`,
tenantSlug: params.tenant ?? "",
plugin: {
id: settingsPage.plugin.id,
pluginId: settingsPage.plugin.pluginId,
version: settingsPage.plugin.version,
},
trustedHtml: settingsPage.trustedHtml,
settings: settingsPage.settings,
};
return Response.json(data);
} catch (error) {
if (error instanceof PluginSettingsServiceError) {
throw new Response(t(`settings.plugins.settings.errors.${error.code}`), { status: getPluginSettingsLoaderErrorStatus(error.code) });
}
throw error;
}
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.plugins.use", tenantId);
const { t } = await getTranslations(request);
const userInfo = await getUserInfo(request);
if (!userInfo.userId) {
return Response.json({ error: "unauthorized", message: t("settings.plugins.settings.errors.unauthorized") }, { status: 401 });
}
const pluginRowId = params.id ?? "";
if (pluginRowId.length === 0) {
return Response.json({ error: "plugin_not_found", message: t("settings.plugins.errors.notFound") }, { status: 404 });
}
if (!hasJsonContentType(request)) {
return Response.json({ error: "unsupported_media_type", message: t("settings.plugins.settings.errors.unsupported_media_type") }, { status: 415 });
}
await validateCSRFToken(request, { headerOnly: true });
const parsed = await readJsonObject(request);
if (!parsed.ok) {
return Response.json({ error: "invalid_json", message: t("settings.plugins.settings.errors.invalid_json") }, { status: 400 });
}
const body = parsed.value as { op?: unknown; key?: unknown; value?: unknown; reason?: unknown };
if (body.op === "reportFrameViolation") {
if (!isPluginSettingsFrameViolationReason(body.reason)) {
return Response.json(
{ error: "invalid_frame_violation_reason", message: t("settings.plugins.settings.errors.invalid_frame_violation_reason") },
{ status: 400 }
);
}
try {
const perMin = resolveFrameViolationRateLimitPerMin();
const limiter = createSlidingWindowRateLimiter({
store: getSharedStore(),
max: perMin,
windowSeconds: 60,
prefix: SETTINGS_FRAME_VIOLATION_RATE_LIMIT_PREFIX,
});
const decision = await limiter.consume(
getPseudonymousAuthBucketKey({
request,
action: "plugin-settings",
identifier: `${tenantId}\0${userInfo.userId}\0${pluginRowId}\0${body.reason}`,
scope: "identifier",
})
);
if (!decision.allowed) {
return Response.json(
{ error: "rate_limited", message: t("settings.plugins.settings.errors.rate_limited", { perMin }) },
{ status: 429, headers: { "Retry-After": "60" } }
);
}
} catch {
return Response.json(
{ error: "rate_limit_unavailable", message: t("settings.plugins.settings.errors.rate_limit_unavailable") },
{ status: 503, headers: { "Retry-After": "60" } }
);
}
try {
const user = await getUser(userInfo.userId);
await reportPluginSettingsFrameViolation({
tenantId,
pluginRowId,
reason: body.reason,
actor: {
userId: userInfo.userId,
email: user?.email ?? null,
ip: getTrustedClientIpOrNull(request),
},
});
return Response.json({ ok: true });
} catch (error) {
if (error instanceof PluginSettingsServiceError) {
const status = error.code === "plugin_not_found" ? 404 : 400;
return Response.json({ error: error.code, message: t(`settings.plugins.settings.errors.${error.code}`) }, { status });
}
throw error;
}
}
if (body.op !== "setSetting" || typeof body.key !== "string") {
return Response.json({ error: "missing_fields", message: t("settings.plugins.settings.errors.missing_fields") }, { status: 400 });
}
const payloadError = getSettingsWritePayloadError(body.key, body.value);
if (payloadError) {
return Response.json({ error: payloadError, message: t(`settings.plugins.settings.errors.${payloadError}`) }, { status: 400 });
}
try {
const perMin = resolveSettingsWriteRateLimitPerMin();
const limiter = createSlidingWindowRateLimiter({
store: getSharedStore(),
max: perMin,
windowSeconds: 60,
prefix: SETTINGS_WRITE_RATE_LIMIT_PREFIX,
});
const decision = await limiter.consume(
getPseudonymousAuthBucketKey({
request,
action: "plugin-settings",
identifier: `${tenantId}\0${userInfo.userId}\0${pluginRowId}`,
scope: "identifier",
})
);
if (!decision.allowed) {
return Response.json(
{ error: "rate_limited", message: t("settings.plugins.settings.errors.rate_limited", { perMin }) },
{ status: 429, headers: { "Retry-After": "60" } }
);
}
} catch {
return Response.json(
{ error: "rate_limit_unavailable", message: t("settings.plugins.settings.errors.rate_limit_unavailable") },
{ status: 503, headers: { "Retry-After": "60" } }
);
}
try {
const user = await getUser(userInfo.userId);
const result = await setPluginUserSetting({
tenantId,
pluginRowId,
userId: userInfo.userId,
key: body.key,
value: body.value as PluginSettingValue,
actor: {
userId: userInfo.userId,
email: user?.email ?? null,
ip: getTrustedClientIpOrNull(request),
},
});
return Response.json({ ok: true, key: result.key, value: result.value, settings: result.settings });
} catch (error) {
if (error instanceof PluginSettingsServiceError) {
const status = error.code === "plugin_not_found" ? 404 : 400;
return Response.json({ error: error.code, message: t(`settings.plugins.settings.errors.${error.code}`) }, { status });
}
throw error;
}
};
export default function TenantPluginSettingsRoute() {
const data = useLoaderData<LoaderData>();
const { csrf } = useRootData();
const { t } = useTranslation();
const [settings, setSettings] = useState<PluginUserSettings>(data.settings);
const frameViolationReportedAtRef = useRef(new Map<PluginSettingsFrameViolationReason, number>());
const frameErrorMessages = useMemo(
() => ({
invalid_payload: t("settings.plugins.settings.frameErrors.invalid_payload"),
settings_unavailable: t("settings.plugins.settings.frameErrors.settings_unavailable"),
settings_update_failed: t("settings.plugins.settings.frameErrors.settings_update_failed"),
}),
[t]
);
const getSetting = useCallback((key: string) => settings[key], [settings]);
const setSetting = useCallback(
async (key: string, value: PluginSettingValue) => {
const fallbackMessage = t("settings.plugins.settings.frameErrors.settings_update_failed");
const response = await fetch(pluginSettingsActionUrl(), {
method: "POST",
headers: {
"content-type": "application/json",
...(csrf ? { "x-csrf-token": csrf } : {}),
},
body: JSON.stringify({ op: "setSetting", key, value, csrf }),
});
// The write reaches this UI route's action through React Router's
// single-fetch endpoint, so the response body is turbo-stream encoded
// rather than the action's raw JSON. The HTTP status is authoritative
// (2xx = persisted, 4xx = rejected with a localized reason), so gate on it
// instead of parsing the body, and reflect the written value locally to
// keep the settings frame state in sync without a reload.
if (!response.ok) {
throw new Error(fallbackMessage);
}
setSettings((current) => ({ ...current, [key]: value ?? null }));
},
[csrf]
);
const reportFrameViolation = useCallback(
(reason: PluginSettingsFrameViolationReason) => {
const now = Date.now();
const lastReportedAt = frameViolationReportedAtRef.current.get(reason) ?? 0;
if (now - lastReportedAt < PLUGIN_SETTINGS_FRAME_VIOLATION_REPORT_INTERVAL_MS) {
return;
}
frameViolationReportedAtRef.current.set(reason, now);
void Promise.resolve(
fetch(pluginSettingsActionUrl(), {
method: "POST",
headers: {
"content-type": "application/json",
...(csrf ? { "x-csrf-token": csrf } : {}),
},
body: JSON.stringify({ op: "reportFrameViolation", reason, csrf }),
})
).catch(() => undefined);
},
[csrf]
);
return (
<div className="space-y-6 p-6" data-ui-id="ui.plugins.settings.page">
<header className="space-y-1">
<p className="text-caption font-caption text-text-neutral-secondary">
<Link
to={appPath({ tenantSlug: data.tenantSlug, path: "settings/integrations/plugins" })}
className="text-text-feedback-link-default hover:text-text-feedback-link-hover hover:underline"
>
{t("settings.plugins.audit.backToPlugins")}
</Link>
</p>
<h1 className="text-xl font-semibold">{t("settings.plugins.settings.heading", { pluginId: data.plugin.pluginId })}</h1>
<p className="text-body-small font-body-small text-text-neutral-secondary">{t("settings.plugins.settings.description")}</p>
</header>
<PluginSettingsFrame
pluginId={data.plugin.pluginId}
title={t("settings.plugins.settings.frameTitle", { pluginId: data.plugin.pluginId })}
trustedHtml={data.trustedHtml}
settings={settings}
errorMessages={frameErrorMessages}
onGetSetting={getSetting}
onSetSetting={setSetting}
onInvalidMessage={reportFrameViolation}
className="min-h-[520px] w-full rounded border border-border-default bg-surface-neutral-primary"
dataUiId="ui.plugins.settings.frame"
/>
</div>
);
}
@@ -0,0 +1,450 @@
import "@testing-library/jest-dom";
import { act, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter, useLoaderData } from "react-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
PLUGIN_SETTINGS_FRAME_CHANNEL_META_NAME,
PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
PLUGIN_SETTINGS_FRAME_SANDBOX,
} from "~/modules/plugins/components/PluginSettingsFrame";
import TenantPluginSettingsRoute from "./plugins.$id";
vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
useLoaderData: vi.fn(),
};
});
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, options?: Record<string, unknown>) => {
if (key === "settings.plugins.audit.backToPlugins") return "Back to plugins";
if (key === "settings.plugins.settings.heading") return `Settings for ${String(options?.pluginId ?? "")}`;
if (key === "settings.plugins.settings.description") return "Manage this plugin's embedded settings.";
if (key === "settings.plugins.settings.frameTitle") return `Settings frame for ${String(options?.pluginId ?? "")}`;
if (key === "settings.plugins.settings.frameErrors.invalid_payload") return "The plugin settings request is invalid.";
if (key === "settings.plugins.settings.frameErrors.settings_unavailable") return "This setting is unavailable.";
if (key === "settings.plugins.settings.frameErrors.settings_update_failed") return "Plugin settings could not be saved.";
return key;
},
}),
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({ csrf: "csrf-token" }),
}));
vi.mock("~/modules/plugins/services/.server/PluginSettingsService", () => ({
PluginSettingsServiceError: class PluginSettingsServiceError extends Error {
constructor(
public readonly code: string,
message: string
) {
super(message);
}
},
loadPluginSettingsHtml: vi.fn(),
loadPluginSettingsPageData: vi.fn(),
}));
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
appPath: ({ tenantSlug, path }: { tenantSlug: string; path: string }) => `/app/${tenantSlug}/${path}`,
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
verifyUserHasPermission: vi.fn(),
}));
vi.mock("~/utils/services/.server/urlService", () => ({
getTenantIdFromUrl: vi.fn(),
}));
function renderSettingsRoute() {
return render(
<MemoryRouter>
<TenantPluginSettingsRoute />
</MemoryRouter>
);
}
function getFrameChannelId(frame: Element) {
const srcDoc = frame.getAttribute("srcdoc") ?? "";
const match = srcDoc.match(new RegExp(`name="${PLUGIN_SETTINGS_FRAME_CHANNEL_META_NAME}" content="([^"]+)"`, "u"));
if (!match?.[1]) throw new Error("plugin settings frame channel missing");
return match[1];
}
describe("tenant plugin settings route UI", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(useLoaderData).mockReturnValue({
title: "Plugin settings",
tenantSlug: "acme",
plugin: {
id: "pl-1",
pluginId: "com.acme.settings",
version: "1.0.0",
},
trustedHtml: "<main><h1>Settings</h1></main>",
settings: { theme: "dark" },
});
});
it("renders the sandboxed settings iframe with route-level navigation", () => {
renderSettingsRoute();
expect(screen.getByRole("link", { name: "Back to plugins" })).toHaveAttribute("href", "/app/acme/settings/integrations/plugins");
expect(screen.getByRole("heading", { name: "Settings for com.acme.settings" })).toBeInTheDocument();
expect(document.querySelector('[data-ui-id="ui.plugins.settings.page"]')).toBeInTheDocument();
const frame = screen.getByTitle("Settings frame for com.acme.settings");
expect(frame).toHaveAttribute("data-ui-id", "ui.plugins.settings.frame");
expect(frame).toHaveAttribute("data-plugin-id", "com.acme.settings");
expect(frame).toHaveAttribute("sandbox", PLUGIN_SETTINGS_FRAME_SANDBOX);
expect(frame).not.toHaveAttribute("src");
expect(frame).toHaveAttribute("srcdoc", expect.stringContaining('http-equiv="Content-Security-Policy"'));
expect(frame).toHaveAttribute("srcdoc", expect.stringContaining("script-src 'nonce-"));
expect(frame).not.toHaveAttribute("srcdoc", expect.stringContaining("script-src 'unsafe-inline'"));
expect(frame).toHaveAttribute("srcdoc", expect.stringContaining(`name="plugin-settings-protocol" content="${PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION}"`));
expect(frame).toHaveAttribute("srcdoc", expect.stringContaining('name="plugin-id" content="com.acme.settings"'));
expect(frame).toHaveAttribute("srcdoc", expect.stringContaining(`name="${PLUGIN_SETTINGS_FRAME_CHANNEL_META_NAME}"`));
});
it("serves loaded settings to the iframe and persists updates through the route action", async () => {
const fetchMock = vi.fn(
async () =>
new Response(JSON.stringify({ ok: true, key: "theme", value: "light", settings: { theme: "light" } }), {
status: 200,
headers: { "content-type": "application/json" },
})
);
vi.stubGlobal("fetch", fetchMock);
renderSettingsRoute();
const frame = screen.getByTitle("Settings frame for com.acme.settings") as HTMLIFrameElement;
const channelId = getFrameChannelId(frame);
const source = frame.contentWindow;
if (!source) throw new Error("iframe contentWindow missing");
const postMessage = vi.spyOn(source, "postMessage").mockImplementation(() => undefined);
act(() => {
window.dispatchEvent(
new MessageEvent("message", {
data: { type: "plugin.settings.get", version: 1, pluginId: "com.acme.settings", channelId, requestId: "get-1", key: "theme" },
origin: "null",
source,
})
);
});
await waitFor(() =>
expect(postMessage).toHaveBeenCalledWith(
{ type: "plugin.settings.result", version: 1, pluginId: "com.acme.settings", channelId, requestId: "get-1", ok: true, key: "theme", value: "dark" },
"*"
)
);
act(() => {
window.dispatchEvent(
new MessageEvent("message", {
data: { type: "plugin.settings.set", version: 1, pluginId: "com.acme.settings", channelId, requestId: "set-1", key: "theme", value: "light" },
origin: "null",
source,
})
);
});
await waitFor(() =>
expect(fetchMock).toHaveBeenCalledWith(".data", {
method: "POST",
headers: { "content-type": "application/json", "x-csrf-token": "csrf-token" },
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
})
);
await waitFor(() =>
expect(postMessage).toHaveBeenCalledWith(
{ type: "plugin.settings.result", version: 1, pluginId: "com.acme.settings", channelId, requestId: "set-1", ok: true, key: "theme", value: "light" },
"*"
)
);
});
it("keeps iframe settings unchanged when route-level persistence fails", async () => {
const fetchMock = vi.fn(
async () =>
new Response(JSON.stringify({ error: "rate_limited", message: "Too many plugin setting updates. Try again in a minute." }), {
status: 429,
headers: { "content-type": "application/json" },
})
);
vi.stubGlobal("fetch", fetchMock);
renderSettingsRoute();
const frame = screen.getByTitle("Settings frame for com.acme.settings") as HTMLIFrameElement;
const channelId = getFrameChannelId(frame);
const source = frame.contentWindow;
if (!source) throw new Error("iframe contentWindow missing");
const postMessage = vi.spyOn(source, "postMessage").mockImplementation(() => undefined);
act(() => {
window.dispatchEvent(
new MessageEvent("message", {
data: { type: "plugin.settings.set", version: 1, pluginId: "com.acme.settings", channelId, requestId: "set-fail", key: "theme", value: "light" },
origin: "null",
source,
})
);
});
await waitFor(() =>
expect(fetchMock).toHaveBeenCalledWith(".data", {
method: "POST",
headers: { "content-type": "application/json", "x-csrf-token": "csrf-token" },
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
})
);
await waitFor(() =>
expect(postMessage).toHaveBeenCalledWith(
{
type: "plugin.settings.result",
version: 1,
pluginId: "com.acme.settings",
channelId,
requestId: "set-fail",
ok: false,
error: "settings_update_failed",
message: "Plugin settings could not be saved.",
},
"*"
)
);
postMessage.mockClear();
act(() => {
window.dispatchEvent(
new MessageEvent("message", {
data: { type: "plugin.settings.get", version: 1, pluginId: "com.acme.settings", channelId, requestId: "get-after-fail", key: "theme" },
origin: "null",
source,
})
);
});
await waitFor(() =>
expect(postMessage).toHaveBeenCalledWith(
{
type: "plugin.settings.result",
version: 1,
pluginId: "com.acme.settings",
channelId,
requestId: "get-after-fail",
ok: true,
key: "theme",
value: "dark",
},
"*"
)
);
});
it("returns bounded iframe error copy when route-level persistence returns non-json", async () => {
const fetchMock = vi.fn(
async () =>
new Response("<!doctype html><title>Bad Gateway</title>", {
status: 502,
headers: { "content-type": "text/html" },
})
);
vi.stubGlobal("fetch", fetchMock);
renderSettingsRoute();
const frame = screen.getByTitle("Settings frame for com.acme.settings") as HTMLIFrameElement;
const channelId = getFrameChannelId(frame);
const source = frame.contentWindow;
if (!source) throw new Error("iframe contentWindow missing");
const postMessage = vi.spyOn(source, "postMessage").mockImplementation(() => undefined);
act(() => {
window.dispatchEvent(
new MessageEvent("message", {
data: { type: "plugin.settings.set", version: 1, pluginId: "com.acme.settings", channelId, requestId: "set-bad-gateway", key: "theme", value: "light" },
origin: "null",
source,
})
);
});
await waitFor(() =>
expect(postMessage).toHaveBeenCalledWith(
{
type: "plugin.settings.result",
version: 1,
pluginId: "com.acme.settings",
channelId,
requestId: "set-bad-gateway",
ok: false,
error: "settings_update_failed",
message: "Plugin settings could not be saved.",
},
"*"
)
);
expect(fetchMock).toHaveBeenCalledOnce();
});
it("rejects forged iframe settings messages and reports frame violations without setting persistence", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
renderSettingsRoute();
const frame = screen.getByTitle("Settings frame for com.acme.settings") as HTMLIFrameElement;
const channelId = getFrameChannelId(frame);
const source = frame.contentWindow;
if (!source) throw new Error("iframe contentWindow missing");
const postMessage = vi.spyOn(source, "postMessage").mockImplementation(() => undefined);
act(() => {
window.dispatchEvent(
new MessageEvent("message", {
data: { type: "plugin.settings.set", version: 1, pluginId: "com.acme.settings", channelId, requestId: "wrong-origin", key: "theme", value: "light" },
origin: "https://evil.example",
source,
})
);
window.dispatchEvent(
new MessageEvent("message", {
data: { type: "plugin.settings.set", version: 1, pluginId: "com.acme.settings", channelId, requestId: "wrong-source", key: "theme", value: "light" },
origin: "null",
source: window,
})
);
window.dispatchEvent(
new MessageEvent("message", {
data: {
type: "plugin.settings.set",
version: 1,
pluginId: "com.acme.settings",
channelId: "stale-channel",
requestId: "wrong-channel",
key: "theme",
value: "light",
},
origin: "null",
source,
})
);
});
await waitFor(() =>
expect(postMessage).toHaveBeenCalledWith(
{
type: "plugin.settings.result",
version: 1,
pluginId: "com.acme.settings",
channelId,
requestId: "wrong-channel",
ok: false,
error: "invalid_payload",
message: "The plugin settings request is invalid.",
},
"*"
)
);
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));
expect(fetchMock.mock.calls.map(([, init]) => JSON.parse(String((init as RequestInit).body)).op)).toEqual([
"reportFrameViolation",
"reportFrameViolation",
"reportFrameViolation",
]);
expect(fetchMock.mock.calls.map(([, init]) => JSON.parse(String((init as RequestInit).body)).reason)).toEqual([
"wrong_origin",
"wrong_source",
"invalid_payload",
]);
expect(postMessage).toHaveBeenCalledTimes(1);
});
it("deduplicates repeated iframe violation reports before they reach the route action", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
renderSettingsRoute();
const frame = screen.getByTitle("Settings frame for com.acme.settings") as HTMLIFrameElement;
const channelId = getFrameChannelId(frame);
const source = frame.contentWindow;
if (!source) throw new Error("iframe contentWindow missing");
act(() => {
for (let index = 0; index < 3; index += 1) {
window.dispatchEvent(
new MessageEvent("message", {
data: { type: "plugin.settings.set", version: 1, pluginId: "com.acme.settings", channelId, requestId: `wrong-origin-${index}`, key: "theme", value: "light" },
origin: "https://evil.example",
source,
})
);
}
});
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
expect(JSON.parse(String((fetchMock.mock.calls[0]?.[1] as RequestInit).body))).toEqual({
op: "reportFrameViolation",
reason: "wrong_origin",
csrf: "csrf-token",
});
});
it("rejects iframe settings messages for another plugin and reports the invalid payload without setting persistence", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
renderSettingsRoute();
const frame = screen.getByTitle("Settings frame for com.acme.settings") as HTMLIFrameElement;
const channelId = getFrameChannelId(frame);
const source = frame.contentWindow;
if (!source) throw new Error("iframe contentWindow missing");
const postMessage = vi.spyOn(source, "postMessage").mockImplementation(() => undefined);
act(() => {
window.dispatchEvent(
new MessageEvent("message", {
data: { type: "plugin.settings.set", version: 1, pluginId: "com.evil.settings", channelId, requestId: "wrong-plugin", key: "theme", value: "light" },
origin: "null",
source,
})
);
});
await waitFor(() =>
expect(postMessage).toHaveBeenCalledWith(
{
type: "plugin.settings.result",
version: 1,
pluginId: "com.acme.settings",
channelId,
requestId: "wrong-plugin",
ok: false,
error: "invalid_payload",
message: "The plugin settings request is invalid.",
},
"*"
)
);
await waitFor(() =>
expect(fetchMock).toHaveBeenCalledWith(".data", {
method: "POST",
headers: { "content-type": "application/json", "x-csrf-token": "csrf-token" },
body: JSON.stringify({ op: "reportFrameViolation", reason: "invalid_payload", csrf: "csrf-token" }),
})
);
});
});
@@ -0,0 +1,393 @@
/**
* Phase 06 #22 — Tenant-Admin plugins UI.
*
* Lists installed plugins for the current tenant with capability consent,
* enable / disable toggles and a manifest preview. The route is deliberately
* scoped (no install dialog, no per-user toggles) — the foundation surfaces
* what plugins exist, links manifest-declared settings UIs, and lets tenant
* admins approve manifest-declared capabilities before flipping the kill-switch.
*
* Permission: `app.plugins.use` can view installed plugins and
* `app.plugins.manage` can grant or revoke capabilities and enable/disable them.
*/
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { getPluginCapabilityMetadata, isPluginCapabilityName, type PluginCapabilityMetadata } from "@hivegrid/plugin-runtime/capabilities";
import { isPluginHookProductionAvailable } from "@hivegrid/plugin-runtime/hooks/registry";
import type { PluginCapability } from "@hivegrid/plugin-runtime/manifest";
import { useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
import {
buildPluginCatalogVM,
pluginCapabilityLabel,
type PluginCapabilityInput,
type PluginCatalogRowInput,
type PluginCatalogVM,
} from "@hivegrid/view-models";
import { PluginCatalogPage, type PluginCapabilityApproval, type PluginCapabilityRevocation } from "~/components/screens/plugins/PluginCatalogPage";
import { getTranslations } from "~/locale/i18next.server";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { useRootData } from "~/utils/data/useRootData";
import { getUserPermission, verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { getUser } from "~/utils/db/users.db.server";
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
import {
PluginLifecycleError,
disablePlugin,
enablePlugin,
grantPluginCapabilities,
isCapabilityGrantScopeSatisfied,
listPluginCapabilityGrants,
listPluginCapabilityGrantsForPlugins,
listPlugins,
revokePluginCapabilities,
type PluginLifecycleActor,
type PluginListItem,
} from "~/modules/plugins/services/.server/PluginLifecycleService";
import { getPluginConsentRequirements, isPluginHookConsentName } from "~/modules/plugins/utils/pluginConsentRequirements";
import { parsePluginCapabilityNameArray, readPluginConsentUrlEncodedFormData } from "~/modules/plugins/utils/capabilityConsentPayload.server";
async function createCapabilityReviewDigest(item: Pick<PluginListItem, "pluginId" | "version" | "manifest">, capabilityNames: ReadonlyArray<string>) {
const { createCapabilityReviewDigest: createDigest } = await import("~/modules/plugins/utils/capabilityReviewDigest");
return createDigest(item, capabilityNames);
}
type SerializedPluginCapabilityMetadata = Pick<PluginCapabilityMetadata, "risk" | "productionAvailable">;
type LoaderData = {
title: string;
vm: PluginCatalogVM;
};
type ActionData = { ok: boolean; message?: string };
const USE_PERMISSION = "app.plugins.use";
const MANAGE_PERMISSION = "app.plugins.manage";
const AUDIT_PERMISSION = "app.settings.auditTrails.view";
/**
* Kept as the route's public capability-label helper (existing consumers/tests);
* the formatting rules themselves live in the AK-UI-05 view-model.
*/
export function formatPluginCapabilityLabel(capability: string, t: (key: string, options?: Record<string, unknown>) => string) {
const label = pluginCapabilityLabel(toCapabilityIdentity(capability));
if (label.fallbackKey) {
return t(label.key, { ...label.params, defaultValue: t(label.fallbackKey, label.params) });
}
return t(label.key, label.params);
}
function toCapabilityIdentity(name: string): { name: string; hookName: string | null; known: boolean } {
return {
name,
hookName: isPluginHookConsentName(name) ? name.slice("hook:".length) : null,
known: isPluginCapabilityName(name),
};
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, USE_PERMISSION, tenantId);
const tenantSlug = params.tenant ?? "";
const [{ t }, info, items] = await Promise.all([getTranslations(request), getUserInfo(request), listPlugins({ tenantId })]);
const [managePermission, auditPermission, rows] = await Promise.all([
info.userId
? getUserPermission({
userId: info.userId,
permissionName: MANAGE_PERMISSION,
tenantId,
})
: Promise.resolve(null),
info.userId
? getUserPermission({
userId: info.userId,
permissionName: AUDIT_PERMISSION,
tenantId,
})
: Promise.resolve(null),
serializePluginItems({ tenantId, tenantSlug, items }),
]);
const data: LoaderData = {
title: `${t("settings.plugins.title")} | ${process.env.APP_NAME}`,
vm: buildPluginCatalogVM({
tenantSlug,
canManage: Boolean(managePermission?.userPermission),
canAudit: Boolean(auditPermission?.userPermission),
rows,
}),
};
return Response.json(data);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, MANAGE_PERMISSION, tenantId);
const { t } = await getTranslations(request);
const parsedForm = await readPluginConsentUrlEncodedFormData(request);
if (!parsedForm.ok) {
return Response.json({ ok: false, message: t("settings.plugins.errors.invalidFormPayload") } satisfies ActionData, { status: 400 });
}
const form = parsedForm.formData;
await validateCSRFToken(request, { formData: form });
const op = form.get("op");
const pluginRowId = form.get("id");
if (typeof pluginRowId !== "string" || pluginRowId.length === 0) {
return Response.json({ ok: false, message: t("settings.plugins.errors.missingPluginId") } satisfies ActionData, { status: 400 });
}
const actor = await resolveActor(request);
try {
if (op === "enable") {
await enablePlugin({ tenantId, pluginRowId, actor });
return Response.json({ ok: true } satisfies ActionData);
}
if (op === "disable") {
await disablePlugin({ tenantId, pluginRowId, actor });
return Response.json({ ok: true } satisfies ActionData);
}
if (op === "revoke") {
const submittedPluginId = form.get("pluginId");
const parsedNames = parsePluginCapabilityNameArray(form.getAll("capabilityNames[]"));
if (typeof submittedPluginId !== "string" || submittedPluginId.length === 0 || !parsedNames.ok) {
return Response.json({ ok: false, message: t("settings.plugins.errors.missingCapabilityRevokeSelection") } satisfies ActionData, { status: 400 });
}
const item = (await listPlugins({ tenantId })).find((row) => row.id === pluginRowId);
if (!item) {
return Response.json({ ok: false, message: t("settings.plugins.errors.pluginNotFound") } satisfies ActionData, { status: 404 });
}
if (item.pluginId !== submittedPluginId) {
return Response.json({ ok: false, message: t("settings.plugins.errors.staleCapabilityReview") } satisfies ActionData, { status: 409 });
}
await revokePluginCapabilities({ tenantId, pluginId: item.pluginId, capabilityNames: parsedNames.capabilityNames, actor });
return Response.json({ ok: true } satisfies ActionData);
}
if (op === "grant" || op === "grantAndEnable") {
const parsedNames = parsePluginCapabilityNameArray(form.getAll("capabilities[]"));
if (!parsedNames.ok) {
return Response.json({ ok: false, message: t("settings.plugins.errors.missingCapabilitySelection") } satisfies ActionData, { status: 400 });
}
const item = (await listPlugins({ tenantId })).find((row) => row.id === pluginRowId);
if (!item) {
return Response.json({ ok: false, message: t("settings.plugins.errors.pluginNotFound") } satisfies ActionData, { status: 404 });
}
if (form.get("capabilitiesReviewed") !== "yes") {
return Response.json({ ok: false, message: t("settings.plugins.errors.missingCapabilityReview") } satisfies ActionData, { status: 400 });
}
const declaredCapabilities = new Map(getPluginConsentRequirements(item.manifest).map((requirement) => [requirement.name, requirement]));
if (parsedNames.capabilityNames.length === 0) {
return Response.json({ ok: false, message: t("settings.plugins.errors.missingCapabilitySelection") } satisfies ActionData, { status: 400 });
}
const existingGrants = await listPluginCapabilityGrants({ tenantId, pluginId: item.pluginId });
const grantByCapability = new Map(existingGrants.map((grant) => [grant.capabilityName, grant]));
const missingCapabilities = getPluginConsentRequirements(item.manifest)
.filter((requirement) => {
const grant = grantByCapability.get(requirement.name);
return !grant || !isCapabilityGrantScopeSatisfied({ declaredScope: requirement.scope ?? null, grantedScopeJson: grant.scopeJson });
})
.map((requirement) => requirement.name);
if (!areCapabilityNameSetsEqual(parsedNames.capabilityNames, missingCapabilities)) {
return Response.json({ ok: false, message: t("settings.plugins.errors.staleCapabilityReview") } satisfies ActionData, { status: 409 });
}
const requestedCapabilities = missingCapabilities;
const submittedDigest = form.get("capabilityReviewDigest");
const expectedDigest = await createCapabilityReviewDigest(item, missingCapabilities);
if (typeof submittedDigest !== "string" || submittedDigest !== expectedDigest) {
return Response.json({ ok: false, message: t("settings.plugins.errors.staleCapabilityReview") } satisfies ActionData, { status: 409 });
}
await grantPluginCapabilities({
tenantId,
pluginId: item.pluginId,
grants: requestedCapabilities.map((name) => ({
capabilityName: name,
scopeJson: declaredCapabilities.get(name)?.scope ?? null,
})),
actor,
capabilityReviewDigest: submittedDigest,
});
if (op === "grantAndEnable") {
await enablePlugin({ tenantId, pluginRowId, actor });
}
return Response.json({ ok: true } satisfies ActionData);
}
return Response.json({ ok: false, message: t("settings.plugins.errors.unknownOperation") } satisfies ActionData, { status: 400 });
} catch (err) {
if (err instanceof PluginLifecycleError) {
return Response.json(
{
ok: false,
message: t(`settings.plugins.errors.lifecycle.${err.code}`),
} satisfies ActionData,
{ status: getPluginLifecycleErrorStatus(err.code) }
);
}
throw err;
}
};
function getPluginLifecycleErrorStatus(code: PluginLifecycleError["code"]): number {
if (
code === "signature_key_not_trusted" ||
code === "signature_key_mismatch" ||
code === "binary_verification_failed" ||
code === "capability_unavailable" ||
code === "production_guard_violation"
) {
return 403;
}
if (code === "not_found" || code === "binary_not_found") {
return 404;
}
if (code === "already_installed" || code === "capability_consent_missing") {
return 409;
}
if (code === "tenant_install_limit_exceeded") {
return 429;
}
return 400;
}
function areCapabilityNameSetsEqual(left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean {
if (left.length !== right.length) return false;
const rightNames = new Set(right);
return left.every((name) => rightNames.has(name));
}
async function serializePluginItems(args: { tenantId: string; tenantSlug: string; items: ReadonlyArray<PluginListItem> }): Promise<PluginCatalogRowInput[]> {
const { createCapabilityReviewDigest: createDigest } = await import("~/modules/plugins/utils/capabilityReviewDigest");
const grants = await listPluginCapabilityGrantsForPlugins({
tenantId: args.tenantId,
pluginIds: args.items.map((row) => row.pluginId),
});
const grantsByPluginId = new Map<string, typeof grants>();
for (const grant of grants) {
const pluginGrants = grantsByPluginId.get(grant.pluginId) ?? [];
pluginGrants.push(grant);
grantsByPluginId.set(grant.pluginId, pluginGrants);
}
return Promise.all(
args.items.map(async (row) => {
const pluginGrants = grantsByPluginId.get(row.pluginId) ?? [];
const grantByCapability = new Map(pluginGrants.map((grant) => [grant.capabilityName, grant]));
const capabilities: PluginCapabilityInput[] = getPluginConsentRequirements(row.manifest).map((capability) => {
const grant = grantByCapability.get(capability.name);
const granted = Boolean(grant) && isCapabilityGrantScopeSatisfied({ declaredScope: capability.scope ?? null, grantedScopeJson: grant?.scopeJson });
const metadata = serializePluginConsentMetadata(capability.name);
const identity = toCapabilityIdentity(capability.name);
return {
name: capability.name,
scope: serializeCapabilityScope(capability.scope ?? null),
granted,
grantedAtIso: grant?.grantedAt.toISOString() ?? null,
hookName: identity.hookName,
known: identity.known,
risk: metadata?.risk ?? null,
productionAvailable: metadata ? metadata.productionAvailable : null,
};
});
const missingCapabilities = capabilities.filter((capability) => !capability.granted).map((capability) => capability.name);
return {
id: row.id,
pluginId: row.pluginId,
version: row.version,
enabled: row.enabled,
installedAtIso: row.installedAt.toISOString(),
capabilities,
missingCapabilities,
capabilityReviewDigest: createDigest(row, missingCapabilities),
hasSettingsUi: Boolean(row.manifest.ui?.settings?.entry),
manifestJson: JSON.stringify(row.manifest, null, 2),
settingsHref: appPath({ tenantSlug: args.tenantSlug, path: `settings/integrations/plugins/${row.id}` }),
auditHref: appPath({ tenantSlug: args.tenantSlug, path: `settings/integrations/plugins/${row.id}/audit` }),
};
})
);
}
/** The declared scope is a plain JSON object — narrow it to the VM's shape. */
function serializeCapabilityScope(scope: PluginCapability["scope"] | null) {
if (!scope) {
return null;
}
return {
allowedHosts: scope.allowedHosts ? [...scope.allowedHosts] : undefined,
keyPattern: scope.keyPattern,
tablePrefix: scope.tablePrefix,
};
}
function serializePluginConsentMetadata(name: string): SerializedPluginCapabilityMetadata | null {
if (isPluginHookConsentName(name)) {
const hookName = name.slice("hook:".length);
return { risk: "medium", productionAvailable: isPluginHookProductionAvailable(hookName) };
}
const metadata = getPluginCapabilityMetadata(name);
return metadata ? { risk: metadata.risk, productionAvailable: metadata.productionAvailable } : null;
}
async function resolveActor(request: Request): Promise<PluginLifecycleActor> {
const info = await getUserInfo(request);
const user = info.userId ? await getUser(info.userId) : null;
const ip = getTrustedClientIpOrNull(request);
return { userId: info.userId ?? null, email: user?.email ?? null, ip };
}
/** AK-UI-05: the route only wires loader/action — the interim screen renders the UI (AD-28). */
export default function TenantPluginsRoute() {
const { vm } = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const rootData = useRootData();
const submit = useSubmit();
const navigation = useNavigation();
/**
* The action still parses url-encoded form data with a CSRF token, exactly as
* the previous <Form> posts did — useSubmit without an encType sends
* application/x-www-form-urlencoded. The field contract is unchanged.
*/
const postOp = (op: string, fields: Record<string, string>, repeated: Record<string, readonly string[]> = {}): void => {
const form = new FormData();
if (rootData.csrf) {
form.set("csrf", rootData.csrf);
}
form.set("op", op);
for (const [name, value] of Object.entries(fields)) {
form.set(name, value);
}
for (const [name, values] of Object.entries(repeated)) {
for (const value of values) {
form.append(name, value);
}
}
void submit(form, { method: "post" });
};
return (
<PluginCatalogPage
embedded
vm={vm}
actionMessage={actionData?.message}
actionOk={actionData?.ok}
submitting={navigation.state !== "idle"}
actions={{
onEnable: (pluginRowId: string) => postOp("enable", { id: pluginRowId }),
onDisable: (pluginRowId: string) => postOp("disable", { id: pluginRowId }),
onApproveCapabilities: (approval: PluginCapabilityApproval) =>
postOp(
approval.op,
{
id: approval.pluginRowId,
capabilityReviewDigest: approval.capabilityReviewDigest,
capabilitiesReviewed: "yes",
},
{ "capabilities[]": approval.capabilityNames }
),
onRevokeCapability: (revocation: PluginCapabilityRevocation) =>
postOp(
"revoke",
{ id: revocation.pluginRowId, pluginId: revocation.pluginId },
{ "capabilityNames[]": [revocation.capabilityName] }
),
}}
/>
);
}
@@ -0,0 +1,633 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter, useActionData, useLoaderData, useSubmit } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { expectNoAxeViolations, runAxe } from "@hivegrid/ui-app/test-setup/axe";
import { buildPluginCatalogVM, type PluginCatalogRowInput } from "@hivegrid/view-models";
import TenantPluginsRoute from "./plugins";
// AK-UI-05: the route wires loader/action, the interim screen renders (AD-28).
// Mutations now travel through useSubmit + FormData instead of hidden <Form>
// inputs — the wire contract (op / id / capabilities[] / csrf / digest) is
// unchanged, so these tests assert on the submitted FormData.
vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
useActionData: vi.fn(),
useLoaderData: vi.fn(),
useSubmit: vi.fn(),
// MemoryRouter is not a data router, so the real hook would throw.
useNavigation: () => ({ state: "idle" }),
};
});
function interpolateTranslation(template: string, options?: Record<string, unknown>) {
return template.replace(/\{\{(\w+)\}\}/g, (_, key: string) => String(options?.[key] ?? `{{${key}}}`));
}
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, options?: Record<string, unknown>) => interpolateTranslation(translations[key] ?? String(options?.defaultValue ?? key), options),
}),
}));
vi.mock("~/locale/format", () => ({
useLocaleFormatters: () => ({
date: (value: string) => `formatted:${value}`,
}),
}));
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
appPath: ({ tenantSlug, path }: { tenantSlug: string; path: string }) => `/app/${tenantSlug}/${path}`,
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({ csrf: "csrf-token" }),
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(),
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
getUserPermission: vi.fn(),
verifyUserHasPermission: 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/db/users.db.server", () => ({
getUser: vi.fn(),
}));
vi.mock("~/modules/plugins/services/.server/PluginLifecycleService", () => ({
PluginLifecycleError: class PluginLifecycleError extends Error {
code: string;
constructor(code: string, message: string) {
super(message);
this.code = code;
}
},
disablePlugin: vi.fn(),
enablePlugin: vi.fn(),
grantPluginCapabilities: vi.fn(),
listPluginCapabilityGrants: vi.fn(),
listPluginCapabilityGrantsForPlugins: vi.fn(),
listPlugins: vi.fn(),
revokePluginCapabilities: vi.fn(),
}));
const translations: Record<string, string> = {
"settings.plugins.title": "Plugins",
"settings.plugins.description": "Installed plugins for acme",
"settings.plugins.empty": "No plugins installed",
"settings.plugins.emptyBody": "Installed plugins appear here.",
"settings.plugins.versionInstalled": "v{{version}} installed {{date}}",
"settings.plugins.capabilities": "Capabilities",
"settings.plugins.capabilityNames.http_outbound": "Outbound HTTP",
"settings.plugins.capabilityNames.log": "Logging",
"settings.plugins.capabilityNames.audit": "Audit logging",
"settings.plugins.capabilityNames.secret_read": "Secret read",
"settings.plugins.consent.allowedHosts": "Allowed hosts: {{hosts}}",
"settings.plugins.consent.approve": "Approve capabilities",
"settings.plugins.consent.approveAndEnable": "Approve and enable",
"settings.plugins.consent.description": "Review and approve missing capability grants before enabling this plugin.",
"settings.plugins.consent.granted": "Approved",
"settings.plugins.consent.grantedAt": "Approved {{date}} for the scope shown above.",
"settings.plugins.consent.hookLabel": "Hook: {{hook}}",
"settings.plugins.consent.keyPattern": "Key pattern: {{pattern}}",
"settings.plugins.consent.missing": "Approval required",
"settings.plugins.consent.noScope": "No additional scope.",
"settings.plugins.consent.none": "This plugin declares no capabilities.",
"settings.plugins.consent.reviewCapabilities": "Review capabilities",
"settings.plugins.consent.reviewDescription": "Version {{version}} is requesting these additional host capabilities.",
"settings.plugins.consent.reviewFormLabel": "Capability review for {{pluginId}}",
"settings.plugins.consent.reviewTitle": "Review {{pluginId}} capabilities",
"settings.plugins.consent.reviewCapability": "I reviewed {{capability}}.",
"settings.plugins.consent.risk.low": "Low risk",
"settings.plugins.consent.risk.medium": "Medium risk",
"settings.plugins.consent.risk.high": "High risk",
"settings.plugins.consent.risk.critical": "Critical risk",
"settings.plugins.consent.available": "Available in this runtime",
"settings.plugins.consent.unavailable": "Not available in this runtime",
"settings.plugins.consent.unavailableDescription":
"This host binding is not production-available yet. It cannot be approved until the operator enables a reviewed implementation.",
"settings.plugins.consent.revoke": "Revoke approval",
"settings.plugins.consent.revokeDisables": "Revoking approval disables this plugin.",
"settings.plugins.consent.tablePrefix": "Table prefix: {{prefix}}",
"settings.plugins.revokeDialog.title": "Revoke this approval?",
"settings.plugins.revokeDialog.body": "{{capability}} will be revoked for {{pluginId}}. This disables the plugin.",
"settings.plugins.revokeDialog.confirm": "Revoke and disable",
"settings.plugins.revokeDialog.cancel": "Cancel",
"shared.deny": "Deny",
"settings.plugins.viewManifest": "View manifest",
"settings.plugins.hideManifest": "Hide manifest",
"settings.plugins.openSettings": "Open settings",
"settings.plugins.viewAudit": "View audit",
"shared.disable": "Disable",
"shared.disabled": "Disabled",
"shared.enable": "Enable",
"shared.enabled": "Enabled",
};
const pluginRow: PluginCatalogRowInput = {
id: "pl-1",
pluginId: "com.acme.outbound",
version: "1.2.3",
enabled: true,
installedAtIso: "2026-05-01T12:00:00.000Z",
capabilities: [
{
name: "http.outbound",
scope: { allowedHosts: ["api.example.com"] },
granted: true,
grantedAtIso: "2026-05-01T12:10:00.000Z",
hookName: null,
known: true,
risk: "high",
productionAvailable: false,
},
],
missingCapabilities: [],
capabilityReviewDigest: "review-digest",
hasSettingsUi: true,
manifestJson: JSON.stringify({ id: "com.acme.outbound", capabilities: [{ name: "http.outbound" }] }, null, 2),
settingsHref: "/app/acme/settings/plugins/pl-1",
auditHref: "/app/acme/settings/plugins/pl-1/audit",
};
let submitSpy: ReturnType<typeof vi.fn>;
function setLoaderData(canManage: boolean, row: PluginCatalogRowInput = pluginRow, canAudit = false) {
vi.mocked(useLoaderData).mockReturnValue({
title: "Plugins",
vm: buildPluginCatalogVM({ tenantSlug: "acme", canManage, canAudit, rows: [row] }),
});
vi.mocked(useActionData).mockReturnValue(undefined);
}
/** Reads the FormData handed to useSubmit by the route wiring. */
function submittedForm(): FormData {
expect(submitSpy).toHaveBeenCalledTimes(1);
const [form, options] = submitSpy.mock.calls[0] as [FormData, { method: string; encType?: string }];
expect(options.method).toBe("post");
// No encType → react-router posts application/x-www-form-urlencoded, which is
// what readPluginConsentUrlEncodedFormData on the server expects.
expect(options.encType).toBeUndefined();
return form;
}
function renderPluginsRoute() {
return render(
<MemoryRouter>
<TenantPluginsRoute />
</MemoryRouter>
);
}
describe("tenant plugin settings UI", () => {
beforeEach(() => {
vi.clearAllMocks();
submitSpy = vi.fn();
vi.mocked(useSubmit).mockReturnValue(submitSpy as unknown as ReturnType<typeof useSubmit>);
setLoaderData(false);
});
it("hides mutation controls from read-only plugin users and exposes manifest state", () => {
renderPluginsRoute();
// AK-SET-01: the page <h1> now belongs to the Erweiterungen hub; this tab
// renders its description and content only.
expect(screen.queryByRole("heading", { name: "Plugins" })).not.toBeInTheDocument();
expect(screen.getByText("com.acme.outbound")).toBeInTheDocument();
expect(screen.getByText(/Outbound HTTP/u)).toBeInTheDocument();
expect(screen.getByText("Approved")).toBeInTheDocument();
expect(screen.getByText("Approved formatted:2026-05-01T12:10:00.000Z for the scope shown above.")).toBeInTheDocument();
expect(document.querySelector('[data-ui-id="ui.plugins.capability.grantMeta"]')).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Disable" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Enable" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Review capabilities" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Revoke approval" })).not.toBeInTheDocument();
expect(document.querySelector('[data-ui-id="ui.plugins.list"]')).toBeInTheDocument();
expect(document.querySelector('[data-ui-id="ui.plugins.item"][data-plugin-row-id="pl-1"][data-plugin-id="com.acme.outbound"]')).toBeInTheDocument();
const settingsLink = screen.getByRole("link", { name: "Open settings" });
expect(settingsLink).toHaveAttribute("href", "/app/acme/settings/plugins/pl-1");
expect(settingsLink).toHaveAttribute("data-ui-id", "ui.plugins.settings.open");
expect(screen.queryByRole("link", { name: "View audit" })).not.toBeInTheDocument();
const manifestToggle = screen.getByRole("button", { name: "View manifest" });
expect(manifestToggle).toHaveAttribute("aria-expanded", "false");
expect(manifestToggle).toHaveAttribute("data-ui-id", "ui.plugins.manifest.toggle");
fireEvent.click(manifestToggle);
expect(screen.getByRole("button", { name: "Hide manifest" })).toHaveAttribute("aria-expanded", "true");
expect(screen.getByText(/http\.outbound/u)).toBeInTheDocument();
expect(document.querySelector('[data-ui-id="ui.plugins.manifest.panel"]')).toBeInTheDocument();
});
it("submits the disable op for plugin managers", () => {
setLoaderData(true);
renderPluginsRoute();
const disableButton = screen.getByRole("button", { name: "Disable" });
expect(disableButton).toHaveAttribute("data-ui-id", "ui.plugins.lifecycle.button");
fireEvent.click(disableButton);
const form = submittedForm();
expect(form.get("op")).toBe("disable");
expect(form.get("id")).toBe("pl-1");
expect(form.get("csrf")).toBe("csrf-token");
});
it("shows plugin audit links only when the user has audit permission", () => {
setLoaderData(false, pluginRow, true);
renderPluginsRoute();
const auditLink = screen.getByRole("link", { name: "View audit" });
expect(auditLink).toHaveAttribute("href", "/app/acme/settings/plugins/pl-1/audit");
expect(auditLink).toHaveAttribute("data-ui-id", "ui.plugins.audit.open");
expect(screen.queryByRole("button", { name: "Disable" })).not.toBeInTheDocument();
});
it("confirms a capability revoke in a real ~/ui dialog before submitting", () => {
setLoaderData(true);
renderPluginsRoute();
const revokeTrigger = screen.getByRole("button", { name: "Revoke approval" });
expect(revokeTrigger).toHaveAttribute("data-ui-id", "ui.plugins.capability.revoke.button");
expect(screen.getByText("Revoking approval disables this plugin.")).toBeInTheDocument();
// The destructive action is gated behind a confirmation dialog.
expect(screen.queryByRole("button", { name: "Revoke and disable" })).not.toBeInTheDocument();
fireEvent.click(revokeTrigger);
expect(document.querySelector('[data-ui-id="ui.plugins.capability.revoke.form"]')).toBeInTheDocument();
expect(screen.getByText("Outbound HTTP will be revoked for com.acme.outbound. This disables the plugin.")).toBeInTheDocument();
expect(submitSpy).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Revoke and disable" }));
const form = submittedForm();
expect(form.get("op")).toBe("revoke");
expect(form.get("id")).toBe("pl-1");
expect(form.get("pluginId")).toBe("com.acme.outbound");
expect(form.getAll("capabilityNames[]")).toEqual(["http.outbound"]);
expect(form.get("csrf")).toBe("csrf-token");
});
it("guides managers through capability review before enabling", () => {
setLoaderData(true, {
...pluginRow,
enabled: false,
capabilities: [
{ name: "log", scope: null, granted: false, grantedAtIso: null, hookName: null, known: true, risk: "low", productionAvailable: true },
],
missingCapabilities: ["log"],
});
renderPluginsRoute();
expect(screen.getByText("Approval required")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Enable" })).not.toBeInTheDocument();
const reviewToggle = screen.getByRole("button", { name: "Review capabilities" });
expect(reviewToggle).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.toggle");
expect(screen.queryByRole("button", { name: "Approve and enable" })).not.toBeInTheDocument();
fireEvent.click(reviewToggle);
const dialog = document.querySelector('[data-ui-id="ui.plugins.capabilityReview.form"]');
expect(dialog).toBeInTheDocument();
expect(dialog).toHaveAttribute("aria-label", "Capability review for com.acme.outbound");
expect(screen.getByText("Review com.acme.outbound capabilities")).toBeInTheDocument();
expect(screen.getByText("Version 1.2.3 is requesting these additional host capabilities.")).toBeInTheDocument();
// The scope shows both on the plugin card and inside the review dialog.
expect(screen.getAllByText("No additional scope.")).toHaveLength(2);
expect(screen.getByText("log")).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.grantName");
expect(document.querySelector('[data-ui-id="ui.plugins.capabilityReview.risk"]')).toHaveTextContent("Low risk");
expect(document.querySelector('[data-ui-id="ui.plugins.capabilityReview.availability"]')).toHaveTextContent("Available in this runtime");
const approveButton = screen.getByRole("button", { name: "Approve and enable" });
expect(approveButton).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.button");
expect(approveButton).toBeDisabled();
const reviewCheckbox = screen.getByRole("checkbox", { name: "I reviewed Logging." });
expect(reviewCheckbox).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.checkbox");
fireEvent.click(reviewCheckbox);
expect(approveButton).toBeEnabled();
fireEvent.click(approveButton);
const form = submittedForm();
expect(form.get("op")).toBe("grantAndEnable");
expect(form.get("id")).toBe("pl-1");
expect(form.getAll("capabilities[]")).toEqual(["log"]);
expect(form.get("capabilitiesReviewed")).toBe("yes");
expect(form.get("capabilityReviewDigest")).toBe("review-digest");
expect(form.get("csrf")).toBe("csrf-token");
});
it("drops the reviewed ticks when the manager denies the review", () => {
setLoaderData(true, {
...pluginRow,
enabled: false,
capabilities: [
{ name: "log", scope: null, granted: false, grantedAtIso: null, hookName: null, known: true, risk: "low", productionAvailable: true },
],
missingCapabilities: ["log"],
});
renderPluginsRoute();
fireEvent.click(screen.getByRole("button", { name: "Review capabilities" }));
fireEvent.click(screen.getByRole("checkbox", { name: "I reviewed Logging." }));
expect(screen.getByRole("button", { name: "Approve and enable" })).toBeEnabled();
const denyButton = screen.getByRole("button", { name: "Deny" });
expect(denyButton).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.deny");
fireEvent.click(denyButton);
expect(submitSpy).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Review capabilities" }));
expect(screen.getByRole("checkbox", { name: "I reviewed Logging." })).not.toBeChecked();
expect(screen.getByRole("button", { name: "Approve and enable" })).toBeDisabled();
});
it("keeps approval disabled until every missing capability is reviewed", () => {
setLoaderData(true, {
...pluginRow,
enabled: false,
capabilities: [
{ name: "log", scope: null, granted: false, grantedAtIso: null, hookName: null, known: true, risk: "low", productionAvailable: true },
{ name: "audit", scope: null, granted: false, grantedAtIso: null, hookName: null, known: true, risk: "medium", productionAvailable: true },
],
missingCapabilities: ["log", "audit"],
});
renderPluginsRoute();
fireEvent.click(screen.getByRole("button", { name: "Review capabilities" }));
const approveButton = screen.getByRole("button", { name: "Approve and enable" });
expect(approveButton).toBeDisabled();
fireEvent.click(screen.getByRole("checkbox", { name: "I reviewed Logging." }));
expect(approveButton).toBeDisabled();
fireEvent.click(screen.getByRole("checkbox", { name: "I reviewed Audit logging." }));
expect(approveButton).toBeEnabled();
fireEvent.click(approveButton);
expect(submittedForm().getAll("capabilities[]")).toEqual(["log", "audit"]);
});
it("requires explicit review before enabling hook-only plugins", () => {
setLoaderData(true, {
...pluginRow,
pluginId: "com.acme.workflow-hook",
enabled: false,
capabilities: [
{
name: "hook:workflow.executed",
scope: null,
granted: false,
grantedAtIso: null,
hookName: "workflow.executed",
known: false,
risk: "medium",
productionAvailable: true,
},
],
missingCapabilities: ["hook:workflow.executed"],
manifestJson: JSON.stringify({ id: "com.acme.workflow-hook", hooks: [{ name: "workflow.executed", export: "onWorkflowExecuted" }] }, null, 2),
hasSettingsUi: false,
});
renderPluginsRoute();
expect(screen.getByText("Hook: workflow.executed")).toBeInTheDocument();
expect(screen.getByText("Approval required")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Enable" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Review capabilities" }));
const approveButton = screen.getByRole("button", { name: "Approve and enable" });
expect(approveButton).toBeDisabled();
const reviewCheckbox = screen.getByRole("checkbox", { name: "I reviewed Hook: workflow.executed." });
expect(screen.getByText("Medium risk")).toBeInTheDocument();
expect(screen.getByText("Available in this runtime")).toBeInTheDocument();
fireEvent.click(reviewCheckbox);
expect(approveButton).toBeEnabled();
fireEvent.click(approveButton);
const form = submittedForm();
expect(form.get("op")).toBe("grantAndEnable");
expect(form.getAll("capabilities[]")).toEqual(["hook:workflow.executed"]);
expect(form.get("capabilitiesReviewed")).toBe("yes");
});
it("resets reviewed capability state when the review digest changes", () => {
const rowWithMissingCapability: PluginCatalogRowInput = {
...pluginRow,
enabled: false,
capabilities: [
{ name: "log", scope: null, granted: false, grantedAtIso: null, hookName: null, known: true, risk: "low", productionAvailable: true },
],
missingCapabilities: ["log"],
};
setLoaderData(true, rowWithMissingCapability);
const view = renderPluginsRoute();
fireEvent.click(screen.getByRole("button", { name: "Review capabilities" }));
fireEvent.click(screen.getByRole("checkbox", { name: "I reviewed Logging." }));
expect(screen.getByRole("button", { name: "Approve and enable" })).toBeEnabled();
// A changed digest means the manifest/grant set moved underneath the manager:
// every tick they already made is void (the server rejects a stale digest).
setLoaderData(true, { ...rowWithMissingCapability, capabilityReviewDigest: "changed-review-digest" });
view.rerender(
<MemoryRouter>
<TenantPluginsRoute />
</MemoryRouter>
);
expect(screen.getByRole("checkbox", { name: "I reviewed Logging." })).not.toBeChecked();
const approveButton = screen.getByRole("button", { name: "Approve and enable" });
expect(approveButton).toBeDisabled();
fireEvent.click(screen.getByRole("checkbox", { name: "I reviewed Logging." }));
fireEvent.click(approveButton);
expect(submittedForm().get("capabilityReviewDigest")).toBe("changed-review-digest");
});
it("blocks approval for unavailable host bindings before submit", () => {
setLoaderData(true, {
...pluginRow,
enabled: false,
capabilities: [
{
name: "http.outbound",
scope: { allowedHosts: ["api.example.com"] },
granted: false,
grantedAtIso: null,
hookName: null,
known: true,
risk: "high",
productionAvailable: false,
},
],
missingCapabilities: ["http.outbound"],
});
renderPluginsRoute();
fireEvent.click(screen.getByRole("button", { name: "Review capabilities" }));
expect(document.querySelector('[data-ui-id="ui.plugins.capabilityReview.risk"]')).toHaveTextContent("High risk");
expect(document.querySelector('[data-ui-id="ui.plugins.capabilityReview.availability"]')).toHaveTextContent("Not available in this runtime");
expect(
screen.getByText("This host binding is not production-available yet. It cannot be approved until the operator enables a reviewed implementation.")
).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.unavailableReason");
expect(screen.getByRole("checkbox", { name: "I reviewed Outbound HTTP." })).toBeDisabled();
expect(screen.getByRole("button", { name: "Approve and enable" })).toBeDisabled();
expect(screen.getAllByText("Allowed hosts: api.example.com").length).toBeGreaterThan(0);
});
it("keeps capability-free plugins enable-able without consent controls", () => {
setLoaderData(true, { ...pluginRow, enabled: false, capabilities: [], missingCapabilities: [] });
renderPluginsRoute();
expect(screen.getByText("This plugin declares no capabilities.")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Review capabilities" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Approve and enable" })).not.toBeInTheDocument();
expect(screen.queryByRole("link", { name: "Open settings" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Enable" }));
const form = submittedForm();
expect(form.get("op")).toBe("enable");
expect(form.get("id")).toBe("pl-1");
});
it("renders the empty state when no plugins are installed", () => {
vi.mocked(useLoaderData).mockReturnValue({
title: "Plugins",
vm: buildPluginCatalogVM({ tenantSlug: "acme", canManage: true, canAudit: true, rows: [] }),
});
vi.mocked(useActionData).mockReturnValue(undefined);
renderPluginsRoute();
expect(document.querySelector('[data-ui-id="ui.plugins.empty"]')).toBeInTheDocument();
expect(screen.getByText("No plugins installed")).toBeInTheDocument();
expect(screen.getByText("Installed plugins appear here.")).toBeInTheDocument();
expect(document.querySelector('[data-ui-id="ui.plugins.list"]')).not.toBeInTheDocument();
});
it("keeps the review dialog open and usable when the server rejects a stale digest", () => {
setLoaderData(true, {
...pluginRow,
enabled: false,
capabilities: [
{ name: "log", scope: null, granted: false, grantedAtIso: null, hookName: null, known: true, risk: "low", productionAvailable: true },
],
missingCapabilities: ["log"],
});
vi.mocked(useActionData).mockReturnValue({ ok: false, message: "Capability review is stale." });
renderPluginsRoute();
fireEvent.click(screen.getByRole("button", { name: "Review capabilities" }));
fireEvent.click(screen.getByRole("checkbox", { name: "I reviewed Logging." }));
// A rejected grant must not tear the dialog down — the manager has to be able
// to read the error and retry from where they stand.
const dialog = document.querySelector('[data-ui-id="ui.plugins.capabilityReview.form"]');
expect(dialog).toBeInTheDocument();
expect(document.querySelector('[data-ui-id="ui.plugins.capabilityReview.error"]')).toBeInTheDocument();
expect(screen.getAllByText("Capability review is stale.").length).toBeGreaterThan(0);
expect(screen.getByRole("button", { name: "Approve and enable" })).toBeEnabled();
});
it("marks the review trigger as a dialog opener for assistive tech", () => {
setLoaderData(true, {
...pluginRow,
enabled: false,
capabilities: [
{ name: "log", scope: null, granted: false, grantedAtIso: null, hookName: null, known: true, risk: "low", productionAvailable: true },
],
missingCapabilities: ["log"],
});
renderPluginsRoute();
const reviewToggle = screen.getByRole("button", { name: "Review capabilities" });
expect(reviewToggle).toHaveAttribute("aria-haspopup", "dialog");
expect(reviewToggle).toHaveAttribute("aria-expanded", "false");
fireEvent.click(reviewToggle);
// Once the modal is up, Radix marks the page behind it aria-hidden, so the
// trigger is no longer reachable by role — query it directly.
expect(document.querySelector('[data-ui-id="ui.plugins.capabilityReview.toggle"]')).toHaveAttribute("aria-expanded", "true");
});
it("surfaces a failed action as a plain-text error alert", () => {
setLoaderData(true);
vi.mocked(useActionData).mockReturnValue({ ok: false, message: "This plugin no longer exists." });
renderPluginsRoute();
const alert = document.querySelector('[data-ui-id="ui.plugins.actionError"]');
expect(alert).toBeInTheDocument();
expect(screen.getByText("This plugin no longer exists.")).toBeInTheDocument();
});
it("has no axe violations for the read-only plugin list", async () => {
await expectNoAxeViolations(
<MemoryRouter>
<TenantPluginsRoute />
</MemoryRouter>
);
});
it("has no axe violations for plugin manager revoke controls", async () => {
setLoaderData(true);
await expectNoAxeViolations(
<MemoryRouter>
<TenantPluginsRoute />
</MemoryRouter>
);
});
it("has no axe violations for the expanded capability review dialog", async () => {
setLoaderData(true, {
...pluginRow,
enabled: false,
capabilities: [
{
name: "http.outbound",
scope: { allowedHosts: ["api.example.com"] },
granted: false,
grantedAtIso: null,
hookName: null,
known: true,
risk: "high",
productionAvailable: false,
},
],
missingCapabilities: ["http.outbound"],
});
const { baseElement } = renderPluginsRoute();
fireEvent.click(screen.getByRole("button", { name: "Review capabilities" }));
expect(document.querySelector('[data-ui-id="ui.plugins.capabilityReview.form"]')).toBeInTheDocument();
expect((await runAxe(baseElement)).violations).toEqual([]);
});
});
@@ -0,0 +1,238 @@
import { CatalogError } from "@hivegrid/foundation";
import type { TelephonySettingsVM } from "@hivegrid/view-models";
import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, useFetcher, useLoaderData, useNavigation, useParams, useSubmit } from "react-router";
import { TelephonySettingsPage } from "~/components/screens/telephony/TelephonySettingsPage";
import ServerError from "~/components/ui/errors/ServerError";
import { useSaveToast } from "~/hooks/use-save-toast";
import { getTranslations } from "~/locale/i18next.server";
import {
loadTelephonyContext,
requireTelephonyPermission,
TELEPHONY_PERMISSIONS,
} from "~/modules/telephony/routes/telephonyAccess.server";
import { TELEPHONY_MODULE_KEY } from "~/modules/telephony/routes/telephonyRoutePaths";
import {
checkTelephonyConnection,
disconnectTelephonyConnection,
loadTelephonySettings,
saveTelephonyUserBinding,
TelephonyServiceError,
} from "~/modules/telephony/services/TelephonyService.server";
import {
connectHalloPetra,
HalloPetraConnectError,
} from "~/modules/telephony/services/HalloPetraConnectionService.server";
import { appendCSRFToken } from "~/utils/csrf";
import { integrationsCatalogPath } from "~/utils/integrations/integrationsRoutePaths";
import { validateCSRFToken } from "~/utils/session.server";
type LoaderData = {
readonly title: string;
readonly vm: TelephonySettingsVM;
readonly callbackResult: ActionData | null;
};
type ActionData = {
readonly intent?: string;
readonly ok?: true;
readonly messageKey?: string;
readonly error?: string;
readonly hallopetraSetup?: {
readonly webhookUrl: string;
readonly webhookSecret: string;
};
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const [{ t }, ctx] = await Promise.all([getTranslations(request), loadRequiredTelephonyContext({ request, params })]);
const vm = await loadTelephonySettings(ctx, params.tenant ?? "");
return Response.json({
title: `${t("telephony.settings.title")} | ${process.env.APP_NAME}`,
vm,
callbackResult: aircallCallbackResult(request.url),
} satisfies LoaderData);
};
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
export const action = async ({ request, params }: ActionFunctionArgs) => {
const form = await request.formData();
await validateCSRFToken(request, { formData: form });
const ctx = await loadRequiredTelephonyContext({ request, params });
const intent = String(form.get("intent") ?? "");
if (intent === "connectHallopetra" || intent === "reconnectHallopetra") {
try {
requireTelephonyPermission(ctx, TELEPHONY_PERMISSIONS.manage);
const result = await connectHalloPetra({
tenantId: ctx.tenantId,
userId: ctx.userId,
apiKey: String(form.get("apiKey") ?? ""),
});
return Response.json({
intent,
ok: true,
messageKey:
intent === "reconnectHallopetra"
? "telephony.settings.feedback.reconnected"
: "telephony.settings.feedback.connected",
hallopetraSetup: { webhookUrl: result.webhookUrl, webhookSecret: result.webhookSecret },
} satisfies ActionData);
} catch (error) {
return telephonyActionErrorResponse(error, intent);
}
}
const connectionId = String(form.get("connectionId") ?? "").trim();
if (!connectionId) return invalidRequestResponse(intent);
try {
if (intent === "healthCheck") {
await checkTelephonyConnection(ctx, params.tenant ?? "", connectionId);
return Response.json({
intent,
ok: true,
messageKey: "telephony.settings.feedback.healthChecked",
} satisfies ActionData);
}
if (intent === "saveBinding") {
const providerUserId = String(form.get("providerUserId") ?? "").trim();
if (!providerUserId) return invalidRequestResponse(intent);
await saveTelephonyUserBinding(ctx, {
dataConnectionId: connectionId,
providerUserId,
tenantUserId: String(form.get("tenantUserId") ?? "").trim() || null,
});
return Response.json({
intent,
ok: true,
messageKey: "telephony.settings.feedback.bindingSaved",
} satisfies ActionData);
}
if (intent === "disconnect") {
await disconnectTelephonyConnection(ctx, connectionId);
return Response.json({
intent,
ok: true,
messageKey: "telephony.settings.feedback.disconnected",
} satisfies ActionData);
}
return invalidRequestResponse(intent);
} catch (error) {
return telephonyActionErrorResponse(error, intent);
}
};
export default function TelephonySettingsRoute(): React.JSX.Element {
const { vm, callbackResult } = useLoaderData<LoaderData>();
const params = useParams();
const fetcher = useFetcher<ActionData>();
const navigation = useNavigation();
const navigationSubmit = useSubmit();
const actionVm: TelephonySettingsVM = fetcher.data?.error
? {
status: "error",
data: vm.status === "ready" ? vm.data : undefined,
error: { messageKey: fetcher.data.error },
}
: vm;
// Action errors are already rendered as the page's error state. OAuth
// callback failures have no inline surface, so those still use the toast.
useSaveToast(fetcher.data?.ok ? fetcher.data : fetcher.data?.error ? undefined : callbackResult);
const submit = (fields: Record<string, string>) => {
const form = new FormData();
for (const [key, value] of Object.entries(fields)) form.set(key, value);
fetcher.submit(appendCSRFToken(form), { method: "post" });
};
const connectionId = vm.status === "ready" ? vm.data.connection?.id : null;
const busy = fetcher.state !== "idle" || navigation.state !== "idle";
return (
<TelephonySettingsPage
embedded
vm={actionVm}
busy={busy}
hallopetraSetup={fetcher.data?.hallopetraSetup ?? null}
backHref={integrationsCatalogPath(params.tenant ?? "")}
actions={{
onConnect: (connectHref) => {
const form = new FormData();
form.set("intent", "connect");
navigationSubmit(appendCSRFToken(form), { method: "post", action: connectHref });
},
onHealthCheck: (id) => submit({ intent: "healthCheck", connectionId: id }),
onConnectHalloPetra: (apiKey) =>
submit({ intent: connectionId ? "reconnectHallopetra" : "connectHallopetra", apiKey }),
onBindingChange: (providerUserId, tenantUserId) => {
if (!connectionId) return;
submit({
intent: "saveBinding",
connectionId,
providerUserId,
tenantUserId: tenantUserId ?? "",
});
},
onDisconnect: (id) => submit({ intent: "disconnect", connectionId: id }),
onRetry: () => window.location.reload(),
}}
/>
);
}
function invalidRequestResponse(intent?: string): Response {
return Response.json({ intent, error: "telephony.errors.invalidRequest" } satisfies ActionData, { status: 400 });
}
async function loadRequiredTelephonyContext({
request,
params,
}: Pick<Parameters<typeof loadTelephonyContext>[0], "request" | "params">) {
try {
return await loadTelephonyContext({ request, params, requireModule: true });
} catch (error) {
if (error instanceof Response) throw error;
if (error instanceof CatalogError) throw new Response(null, { status: error.status });
throw error;
}
}
function telephonyActionErrorResponse(error: unknown, intent: string): Response {
if (error instanceof Response) return error;
if (error instanceof CatalogError) {
return Response.json({ intent, error: error.i18nKey } satisfies ActionData, { status: error.status });
}
if (error instanceof TelephonyServiceError) {
return Response.json({ intent, error: error.messageKey } satisfies ActionData, { status: 400 });
}
if (error instanceof HalloPetraConnectError) {
const messageKey = {
not_configured: "telephony.settings.hallopetra.errors.notConfigured",
invalid_key: "telephony.settings.hallopetra.errors.invalidKey",
provider_conflict: "telephony.settings.hallopetra.errors.providerConflict",
slot_conflict: "telephony.settings.hallopetra.errors.slotConflict",
persistence_failed: "telephony.settings.hallopetra.errors.persistenceFailed",
}[error.code];
return Response.json({ intent, error: messageKey } satisfies ActionData, { status: 400 });
}
throw error;
}
function aircallCallbackResult(requestUrl: string): ActionData | null {
const outcome = new URL(requestUrl).searchParams.get("aircall");
if (outcome === "connected") {
return { intent: "connect", ok: true, messageKey: "telephony.settings.feedback.connected" };
}
if (outcome === "error") {
return { intent: "connect", error: "telephony.settings.feedback.connectionFailed" };
}
return null;
}
export function ErrorBoundary(): React.JSX.Element {
return <ServerError />;
}
export const handle = {
moduleKey: TELEPHONY_MODULE_KEY,
breadcrumbKey: "telephony.settings.title",
};