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

@@ -1,269 +1,8 @@
import { useTranslation } from "react-i18next";
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
import { useActionData, useSubmit } from "react-router";
import { useAppData } from "~/utils/data/useAppData";
import { getTranslations } from "~/locale/i18next.server";
import { getTenant, getTenantBySlug, updateTenant, type TenantWithDetails } from "~/utils/db/tenants.db.server";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import UpdateTenantDetailsForm from "~/components/core/tenants/UpdateTenantDetailsForm";
import { createLog } from "~/utils/db/logs.db.server";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
import { useEffect, useRef } from "react";
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
import { deleteAndCancelTenant, isReservedTenantSlug, normalizeTenantSlug } from "~/utils/services/tenantService";
import EventsService from "~/modules/events/services/.server/EventsService";
import { getUser } from "~/utils/db/users.db.server";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { getActiveTenantSubscriptions } from "~/utils/services/.server/subscriptionService";
import { storeFile } from "~/utils/integrations/storageService";
import { auditRejectedUpload } from "~/utils/integrations/storageAudit.server";
import { getTenantTypeOptions } from "~/utils/db/tenants/tenantTypes.db.server";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import SettingSection from "~/components/ui/sections/SettingSection";
import { AccountUpdatedDto } from "~/modules/events/dtos/AccountUpdatedDto";
import { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
import toast from "react-hot-toast";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { useRootData } from "~/utils/data/useRootData";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
// AK-SET-01 — legacy `settings/account` is now the Allgemein tab of the Workspace hub.
import { legacySettingsRedirectLoader } from "./legacy-redirects.server";
type LoaderData = {
title: string;
tenant: TenantWithDetails;
tenantTypes: Awaited<ReturnType<typeof getTenantTypeOptions>>;
};
export const loader = legacySettingsRedirectLoader("settings/workspace");
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.account.view", tenantId);
const { t } = await getTranslations(request);
const [tenant, tenantTypes] = await Promise.all([getTenant(tenantId), getTenantTypeOptions()]);
if (!tenant) {
throw Error(t("shared.notFound"));
}
const data: LoaderData = {
title: `${t("models.tenant.object")} | ${process.env.APP_NAME}`,
tenant,
tenantTypes,
};
return data;
};
type ActionData = {
updateDetailsError?: string;
deleteError?: string;
success?: string;
};
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
export const action: ActionFunction = async ({ request, params }) => {
const { t } = await getTranslations(request);
await validateCSRFToken(request);
const userInfo = await getUserInfo(request);
const currentUser = await getUser(userInfo.userId);
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
const tenant = await getTenant(tenantId);
if (!tenant || !currentUser) {
return redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
}
if (action === "edit") {
const name = form.get("name")?.toString() ?? "";
const slug = normalizeTenantSlug(form.get("slug")?.toString() ?? "");
const icon = form.get("icon")?.toString() ?? "";
if ((name?.length ?? 0) < 1) {
return badRequest({
updateDetailsError: t("settings.tenant.errors.nameRequired"),
});
}
if (!slug || slug.length < 1) {
return badRequest({ updateDetailsError: t("settings.tenant.errors.slugRequired") });
}
if (isReservedTenantSlug(slug)) {
return badRequest({
updateDetailsError: t("settings.tenant.errors.reservedSlug", { slug }),
});
}
if (slug.includes(" ")) {
return badRequest({
updateDetailsError: t("settings.tenant.errors.slugWhitespace"),
});
}
const existing = await getTenant(tenantId);
if (!existing) {
return badRequest({ updateDetailsError: t("settings.tenant.errors.notFound") });
}
await createLog(request, tenantId, "settings.tenant.updateDetails", JSON.stringify({ name, slug }));
if (existing?.slug !== slug) {
const existingSlug = await getTenantBySlug(slug);
if (existingSlug) {
return badRequest({
updateDetailsError: t("settings.tenant.errors.slugTaken"),
});
}
let iconStored = icon
? await storeFile({
bucket: "accounts-icons",
content: icon,
id: tenantId,
scan: { context: "avatar", enqueuePostScan: true, onReject: auditRejectedUpload(request, "tenant.account.icon"), filename: `${tenantId}.icon` },
})
: icon;
await updateTenant(existing, { name, icon: iconStored, slug });
await EventsService.create({
request,
event: "account.updated",
tenantId: tenant.id,
userId: currentUser.id,
data: {
id: tenant.id,
new: { name, slug },
old: { name: tenant.name, slug: tenant.slug },
user: { id: currentUser.id ?? "", email: currentUser.email },
} satisfies AccountUpdatedDto,
});
return redirect(appPath({ tenantSlug: slug, path: "settings/account", mode: "host-aware" }));
} else {
let iconStored = icon
? await storeFile({
bucket: "accounts-icons",
content: icon,
id: tenantId,
scan: { context: "avatar", enqueuePostScan: true, onReject: auditRejectedUpload(request, "tenant.account.icon"), filename: `${tenantId}.icon` },
})
: icon;
await updateTenant(existing, { name, icon: iconStored, slug });
await EventsService.create({
request,
event: "account.updated",
tenantId: tenant.id,
userId: currentUser.id,
data: {
id: tenant.id,
new: { name, slug },
old: { name: tenant.name, slug: tenant.slug },
user: { id: currentUser.id, email: currentUser.email },
} satisfies AccountUpdatedDto,
});
const actionData: ActionData = {
success: t("settings.tenant.updated"),
};
return Response.json(actionData);
}
} else if (action === "delete") {
await verifyUserHasPermission(request, "app.settings.account.delete", tenantId);
const activeSubscriptions = await getActiveTenantSubscriptions(tenantId);
if (activeSubscriptions && activeSubscriptions.products.find((f) => !f.cancelledAt)) {
return badRequest({
deleteError: t("settings.tenant.errors.cannotDeleteWithActiveSubscriptions"),
});
}
await EventsService.create({
request,
event: "account.deleted",
tenantId: null,
userId: currentUser.id,
data: {
tenant: { id: tenant.id, name: tenant.name },
user: { id: currentUser.id, email: currentUser.email },
} satisfies AccountDeletedDto,
});
await deleteAndCancelTenant({ tenantId, userId: userInfo.userId, t });
return redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
} else {
return badRequest({ updateDetailsError: t("shared.invalidForm") });
}
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function TenantRoute() {
const data = useLoaderData<LoaderData>();
const appData = useAppData();
const actionData = useActionData<ActionData>();
const { t } = useTranslation();
const submit = useSubmit();
const rootData = useRootData();
const confirmDelete = useRef<RefConfirmModal>(null);
useEffect(() => {
if (actionData?.success) {
toast.success(actionData.success);
} else if (actionData?.updateDetailsError) {
toast.error(actionData.updateDetailsError);
} else if (actionData?.deleteError) {
toast.error(actionData.deleteError);
}
}, [actionData]);
function deleteAccount() {
confirmDelete.current?.show(t("settings.danger.confirmDeleteTenant"), t("shared.confirm"), t("shared.cancel"), t("shared.warningCannotUndo"));
}
function confirmDeleteTenant() {
const form = new FormData();
form.set("action", "delete");
if (rootData.csrf) {
form.set("csrf", rootData.csrf);
}
submit(form, { method: "post" });
}
return (
<EditPageLayout>
<SettingSection title={t("settings.tenant.general")} description={t("settings.tenant.generalDescription")}>
<UpdateTenantDetailsForm
disabled={!getUserHasPermission(appData, "app.settings.account.update")}
tenant={data.tenant}
tenantTypes={data.tenantTypes}
options={{
canChangeType: false,
}}
/>
</SettingSection>
{/*Separator */}
<div className="block">
<div className="py-5">
<div className="border-border border-t"></div>
</div>
</div>
{/*Danger */}
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")} tone="danger">
<div className="mt-12 md:col-span-2 md:mt-0">
<div>
<input hidden type="text" name="action" value="deleteAccount" readOnly />
<div className="">
<div className="">
<div className="">
<ButtonPrimary
disabled={!getUserHasPermission(appData, "app.settings.account.delete")}
destructive={true}
onClick={deleteAccount}
dataUiId="ui.settings.account.delete"
>
{t("settings.danger.deleteWorkspace")}
</ButtonPrimary>
</div>
</div>
</div>
</div>
</div>
</SettingSection>
<ConfirmModal ref={confirmDelete} onYes={confirmDeleteTenant} />
</EditPageLayout>
);
export default function LegacyAccountRedirect() {
return null;
}
@@ -1,88 +1,8 @@
import { LoaderFunctionArgs, useLoaderData } 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 ApiKeyLogsSummary from "~/modules/api/components/ApiKeyLogsSummary";
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";
// AK-SET-01 — legacy `settings/api` is now a tab of the Erweiterungen hub.
import { legacySettingsRedirectLoader } from "../legacy-redirects.server";
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 const loader = legacySettingsRedirectLoader("settings/integrations/api");
export default function () {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const params = useParams();
return (
<EditPageLayout
tabs={[
{
name: t("shared.overview"),
routePath: UrlUtils.getModulePath(params, "api"),
},
{
name: t("models.apiCall.plural"),
routePath: UrlUtils.getModulePath(params, "api/logs"),
},
{
name: t("models.apiKey.plural"),
routePath: UrlUtils.getModulePath(params, "api/keys"),
},
{
name: t("docs.title"),
routePath: UrlUtils.getModulePath(params, "api/docs"),
},
]}
>
{"error" in data ? (
<ErrorBanner title={t(data.error)}>
<Link to="." className="underline">
{t("shared.clickHereToTryAgain")}
</Link>
</ErrorBanner>
) : (
<Fragment>
<ApiKeyLogsSummary data={data} />
</Fragment>
)}
</EditPageLayout>
);
}
export function ErrorBoundary() {
return <ServerError />;
export default function LegacyApiRedirect() {
return null;
}
@@ -1,47 +1,8 @@
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 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";
// AK-SET-01 — legacy `settings/api/keys`.
import { legacySettingsRedirectLoader } from "../legacy-redirects.server";
type LoaderData = {
apiKeys: RedactedApiKeyWithDetails[];
};
export const loader = legacySettingsRedirectLoader("settings/integrations/api/keys");
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 (
<EditPageLayout
tabs={[
{ name: t("shared.overview"), routePath: UrlUtils.getModulePath(params, "api") },
{ name: t("models.apiCall.plural"), routePath: UrlUtils.getModulePath(params, "api/logs") },
{ name: t("models.apiKey.plural"), routePath: UrlUtils.getModulePath(params, "api/keys") },
{ name: t("docs.title"), routePath: UrlUtils.getModulePath(params, "api/docs") },
]}
>
<ApiKeysTable
canCreate={getUserHasPermission(appData, "app.settings.apiKeys.create")}
items={data.apiKeys}
/>
<Outlet />
</EditPageLayout>
);
export default function LegacyApiKeysRedirect() {
return null;
}
@@ -1,182 +1,10 @@
import { ActionFunction, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
import { useNavigate, useParams } from "react-router";
import ApiKeyCreatedModal from "~/components/core/apiKeys/ApiKeyCreatedModal";
import ApiKeyForm from "~/components/core/apiKeys/ApiKeyForm";
import OpenModal from "~/components/ui/modals/OpenModal";
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";
// AK-SET-01 — legacy API key detail path; the id has to survive the redirect.
import type { LoaderFunctionArgs } from "react-router";
import { legacySettingsRedirect } from "../../legacy-redirects.server";
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/api/keys"));
}
const data: LoaderData = {
item,
};
return data;
};
export const loader = ({ request, params }: LoaderFunctionArgs) =>
legacySettingsRedirect({ request, params }, `settings/integrations/api/keys/${encodeURIComponent(params.id ?? "")}`);
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/api/keys"));
} 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/api/keys"));
} else {
return badRequest({ error: t("shared.invalidForm") });
}
};
export default function ApiEditKeyRoute() {
const data = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const navigate = useNavigate();
const appData = useAppData();
const params = useParams();
return (
<>
<OpenModal className="sm:max-w-xl" onClose={() => navigate(UrlUtils.currentTenantUrl(params, "settings/api/keys"))}>
<ApiKeyForm
item={data.item}
canUpdate={getUserHasPermission(appData, "app.settings.apiKeys.update")}
canDelete={getUserHasPermission(appData, "app.settings.apiKeys.delete")}
canRotate={getUserHasPermission(appData, "app.settings.apiKeys.update")}
/>
{actionData?.apiKey !== undefined && (
<ApiKeyCreatedModal apiKey={actionData?.apiKey} redirectTo={UrlUtils.currentTenantUrl(params, "settings/api/keys")} action="rotated" />
)}
</OpenModal>
</>
);
export default function LegacyApiKeyDetailRedirect() {
return null;
}
@@ -1,100 +1,8 @@
import { ActionFunction, LoaderFunctionArgs } from "react-router";
import { useActionData, useNavigate, useParams } from "react-router";
import ApiKeyCreatedModal from "~/components/core/apiKeys/ApiKeyCreatedModal";
import ApiKeyForm from "~/components/core/apiKeys/ApiKeyForm";
import OpenModal from "~/components/ui/modals/OpenModal";
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";
// AK-SET-01 — legacy `settings/api/keys/new`.
import { legacySettingsRedirectLoader } from "../../legacy-redirects.server";
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.apiKeys.create", tenantId);
return Response.json({});
};
export const loader = legacySettingsRedirectLoader("settings/integrations/api/keys/new");
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 actionData = useActionData<ActionData>();
const params = useParams();
return (
<>
<OpenModal className="sm:max-w-xl" onClose={() => navigate(UrlUtils.currentTenantUrl(params, "settings/api/keys"))}>
<ApiKeyForm />
{actionData?.apiKey !== undefined && (
<ApiKeyCreatedModal apiKey={actionData?.apiKey} redirectTo={UrlUtils.currentTenantUrl(params, "settings/api/keys")} />
)}
</OpenModal>
</>
);
export default function LegacyNewApiKeyRedirect() {
return null;
}
@@ -1,59 +1,8 @@
import { LoaderFunctionArgs, useLoaderData } 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 ApiKeyLogsDetails from "~/modules/api/components/ApiKeyLogsDetails";
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";
// AK-SET-01 — legacy `settings/api/logs`.
import { legacySettingsRedirectLoader } from "../legacy-redirects.server";
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 const loader = legacySettingsRedirectLoader("settings/integrations/api/logs");
export default function AdminApiLogsRoute() {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const params = useParams();
return (
<EditPageLayout
tabs={[
{
name: t("shared.overview"),
routePath: UrlUtils.getModulePath(params, "api"),
},
{
name: t("models.apiCall.plural"),
routePath: UrlUtils.getModulePath(params, "api/logs"),
},
{
name: t("models.apiKey.plural"),
routePath: UrlUtils.getModulePath(params, "api/keys"),
},
{
name: t("docs.title"),
routePath: UrlUtils.getModulePath(params, "api/docs"),
},
]}
>
<ApiKeyLogsDetails data={data} />
</EditPageLayout>
);
export default function LegacyApiLogsRedirect() {
return null;
}
@@ -1,167 +1,8 @@
/**
* Phase 10 Task #67 — Tenant Compliance-Audit-Export.
*
* Per-tenant self-service variant of the admin audit-export. Identical
* filter surface but tenantId-locked: a tenant admin can only see their
* own AuditEvent rows. Used for SOC2-Type-II evidence collection by
* tenants who need to deliver their own privileged-action report.
*/
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import { getDbClient } from "@hivegrid/db/client.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getTranslations } from "~/locale/i18next.server";
import { useLocaleFormatters } from "~/locale/format";
import { AUDIT_EXPORT_MAX_ROWS, buildAuditExportWhere, computeAuditIntegritySummary, parseAuditExportFilters, renderAuditExportCsv, type AuditExportRow } from "~/routes/admin/audit-export.helpers.server";
import { buildAuditPdfLabels, renderAuditExportPdfResponse } from "~/utils/audit/pdfRender";
// AK-SET-01 — legacy `settings/audit-export` is now a tab of the Compliance-Hub.
import { legacySettingsRedirectLoader } from "./legacy-redirects.server";
type LoaderData = {
title: string;
tenantSlug: string;
defaultFrom: string;
defaultTo: string;
maxRows: number;
};
export const loader = legacySettingsRedirectLoader("settings/compliance/audit-export");
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
const { t } = await getTranslations(request);
const url = new URL(request.url);
if (url.searchParams.get("export") === "csv") {
return streamTenantAuditExport(tenantId, url);
}
if (url.searchParams.get("export") === "pdf" || url.searchParams.get("format") === "pdf") {
return streamTenantAuditPdfExport(tenantId, url, t);
}
const today = new Date();
const fromDate = new Date(today);
fromDate.setDate(fromDate.getDate() - 30);
const data: LoaderData = {
title: `${t("models.log.plural")} | ${process.env.APP_NAME}`,
tenantSlug: params.tenant ?? "",
defaultFrom: fromDate.toISOString().slice(0, 10),
defaultTo: today.toISOString().slice(0, 10),
maxRows: AUDIT_EXPORT_MAX_ROWS,
};
return Response.json(data);
};
async function streamTenantAuditExport(tenantId: string, url: URL): Promise<Response> {
// Force tenantId scope onto the URL filters so a request that tries to
// smuggle a different tenantId via query string is silently ignored.
const filters = { ...parseAuditExportFilters(url), tenantId };
const db = getDbClient();
const rows = (await db.auditEvent.findMany({
where: buildAuditExportWhere(filters),
orderBy: { createdAt: "asc" },
take: AUDIT_EXPORT_MAX_ROWS,
})) as unknown as AuditExportRow[];
const integrity = computeAuditIntegritySummary(rows);
const csv = renderAuditExportCsv(rows, integrity);
return new Response(csv, {
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": `attachment; filename="audit-export-${tenantId}-${url.searchParams.get("from") ?? "all"}_${url.searchParams.get("to") ?? "all"}.csv"`,
"X-Audit-Chain-Status": integrity.ok ? "ok" : "broken",
},
});
}
async function streamTenantAuditPdfExport(tenantId: string, url: URL, t: Awaited<ReturnType<typeof getTranslations>>["t"]): Promise<Response> {
const filters = { ...parseAuditExportFilters(url), tenantId };
const db = getDbClient();
const rows = (await db.auditEvent.findMany({
where: buildAuditExportWhere(filters),
orderBy: { createdAt: "asc" },
take: AUDIT_EXPORT_MAX_ROWS,
})) as unknown as AuditExportRow[];
const integrity = computeAuditIntegritySummary(rows);
return renderAuditExportPdfResponse(
{
tenantId,
filters,
integrity,
rows,
labels: buildAuditPdfLabels(t),
},
{ filenamePrefix: "audit-export" }
);
}
export default function TenantAuditExportRoute() {
const data = useLoaderData<LoaderData>();
const { t } = useTranslation(["settings", "translations"]);
const formatters = useLocaleFormatters();
return (
<div data-ui-id="ui.settings.auditExport.page" className="space-y-6 p-6">
<header>
<h1 className="text-xl font-semibold">{t("translations:models.log.plural")}</h1>
<p className="text-sm text-gray-500">
{t(
"auditExport.description",
{ tenantSlug: data.tenantSlug, maxRows: formatters.number(data.maxRows) },
)}
</p>
</header>
<form data-ui-id="ui.settings.auditExport.form" method="get" className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3" action="">
<input type="hidden" name="export" value="csv" />
<label className="text-sm">
<span className="block">{t("auditExport.filters.fromUtc")}</span>
<input data-ui-id="ui.settings.auditExport.from" type="date" name="from" defaultValue={data.defaultFrom} className="mt-1 w-full rounded border px-2 py-1" />
</label>
<label className="text-sm">
<span className="block">{t("auditExport.filters.toUtc")}</span>
<input data-ui-id="ui.settings.auditExport.to" type="date" name="to" defaultValue={data.defaultTo} className="mt-1 w-full rounded border px-2 py-1" />
</label>
<label className="text-sm">
<span className="block">{t("auditExport.filters.regulatoryScope")}</span>
<select data-ui-id="ui.settings.auditExport.regulatoryScope" name="regulatoryScope" className="mt-1 w-full rounded border px-2 py-1" defaultValue="">
<option value="">{t("auditExport.filters.any")}</option>
<option value="soc2">{t("auditExport.scopes.soc2")}</option>
<option value="gdpr">{t("auditExport.scopes.gdpr")}</option>
<option value="hipaa">{t("auditExport.scopes.hipaa")}</option>
<option value="pci">{t("auditExport.scopes.pci")}</option>
</select>
</label>
<label className="text-sm">
<span className="block">{t("auditExport.filters.actorType")}</span>
<select data-ui-id="ui.settings.auditExport.actorType" name="actorType" className="mt-1 w-full rounded border px-2 py-1" defaultValue="">
<option value="">{t("auditExport.filters.any")}</option>
<option value="user">{t("auditExport.actorTypes.user")}</option>
<option value="admin">{t("auditExport.actorTypes.admin")}</option>
<option value="api_key">{t("auditExport.actorTypes.apiKey")}</option>
<option value="system">{t("auditExport.actorTypes.system")}</option>
<option value="plugin">{t("auditExport.actorTypes.plugin")}</option>
</select>
</label>
<label className="text-sm">
<span className="block">{t("auditExport.filters.outcome")}</span>
<select data-ui-id="ui.settings.auditExport.outcome" name="outcome" className="mt-1 w-full rounded border px-2 py-1" defaultValue="">
<option value="">{t("auditExport.filters.any")}</option>
<option value="success">{t("auditExport.outcomes.success")}</option>
<option value="failure">{t("auditExport.outcomes.failure")}</option>
<option value="blocked">{t("auditExport.outcomes.blocked")}</option>
</select>
</label>
<div className="sm:col-span-2 lg:col-span-3 flex flex-wrap gap-3">
<button data-ui-id="ui.settings.auditExport.downloadCsv" type="submit" className="rounded bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-500">
{t("auditExport.downloadCsv")}
</button>
<button
type="submit"
name="export"
value="pdf"
data-ui-id="ui.settings.auditExport.downloadPdf"
className="rounded border border-blue-600 bg-white px-4 py-2 text-sm font-medium text-blue-600 hover:bg-blue-50"
>
{t("auditExport.downloadPdf")}
</button>
</div>
</form>
</div>
);
export default function LegacyAuditExportRedirect() {
return null;
}
@@ -0,0 +1,67 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
let subscriptionActivationRequired = false;
vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
Outlet: () => <div data-testid="billing-outlet" />,
useLoaderData: () => ({
tabs: [{ id: "plan", labelKey: "billing.plan", href: "/acme/settings/billing", exact: true }],
}),
useLocation: () => ({ pathname: "/acme/settings/billing" }),
};
});
vi.mock("~/utils/data/useAppData", () => ({
useAppData: () => ({
mySubscription: null,
subscriptionActivationRequired,
}),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({
appConfiguration: { subscription: { required: false } },
}),
}));
vi.mock("~/components/screens/settings/SettingsHubShell", () => ({
SettingsHubShell: ({ children }: { children: React.ReactNode }) => <div data-testid="billing-hub">{children}</div>,
}));
vi.mock("@hivegrid/view-models", () => ({
buildSettingsHubVM: () => ({ hubId: "billing" }),
}));
vi.mock("@subframe/core", () => ({
FeatherCreditCard: () => null,
}));
import BillingHubRoute from "./billing";
describe("billing settings shell", () => {
beforeEach(() => {
subscriptionActivationRequired = false;
});
it("renders the regular billing hub for an active workspace", () => {
render(<BillingHubRoute />);
expect(screen.getByTestId("billing-hub")).toBeInTheDocument();
expect(screen.getByTestId("billing-outlet")).toBeInTheDocument();
});
it("removes billing tabs when the persisted signup selection requires activation", () => {
subscriptionActivationRequired = true;
render(<BillingHubRoute />);
expect(screen.queryByTestId("billing-hub")).not.toBeInTheDocument();
expect(screen.getByTestId("billing-outlet")).toBeInTheDocument();
});
});
@@ -0,0 +1,89 @@
// AK-SET-01 Hub D — "Abrechnung" bundles the former subscription, usage and
// billing rail entries into one hub with a tab bar. Layout route only: the
// loader decides which tabs the user may see, every tab keeps its own URL and
// its own loader.
import { Outlet, useLoaderData, useLocation, type LoaderFunctionArgs, type MetaFunction } from "react-router";
import { FeatherCreditCard } from "@subframe/core";
import { buildSettingsHubVM, type SettingsHubTabInput } from "@hivegrid/view-models";
import { SettingsHubShell } from "~/components/screens/settings/SettingsHubShell";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { useAppData } from "~/utils/data/useAppData";
import { useRootData } from "~/utils/data/useRootData";
import { requiresTenantSubscriptionActivation } from "~/utils/app/SubscriptionAccess";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { hasSettingsPermission, settingsHubBaseRedirect, settingsHubNotFound } from "./hub-access.server";
type LoaderData = {
title: string;
tabs: SettingsHubTabInput[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
const [{ t }, canViewSubscription, canViewInvoices] = await Promise.all([
getTranslations(request),
hasSettingsPermission(request, "app.settings.subscription.view", tenantId),
hasSettingsPermission(request, "app.settings.subscription.invoices.view", tenantId),
]);
const tabs: SettingsHubTabInput[] = [];
if (canViewSubscription) {
tabs.push({
id: "plan",
labelKey: "billing:selfServiceSubscription.management.tabs.overview",
href: UrlUtils.currentTenantUrl(params, "settings/billing"),
// The hub index href is a prefix of every sibling — without this the plan
// tab would stay lit on the usage and invoices routes.
exact: true,
});
tabs.push({ id: "usage", labelKey: "billing:usage.title", href: UrlUtils.currentTenantUrl(params, "settings/billing/usage") });
}
if (canViewInvoices) {
tabs.push({
id: "invoices",
labelKey: "app.subscription.invoices.title",
href: UrlUtils.currentTenantUrl(params, "settings/billing/invoices"),
});
}
// A hub without a single reachable tab must not render an empty frame —
// permission denied shows 404, never 403 (Bauprinzip A.5.3).
if (tabs.length === 0) throw settingsHubNotFound();
const baseRedirect = settingsHubBaseRedirect(request, UrlUtils.currentTenantUrl(params, "settings/billing"), tabs);
if (baseRedirect) throw baseRedirect;
return { title: `${t("settings.hubs.billing.title")} | ${process.env.APP_NAME}`, tabs } satisfies LoaderData;
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function BillingHubRoute() {
const { tabs } = useLoaderData<LoaderData>();
const location = useLocation();
const appData = useAppData();
const { appConfiguration } = useRootData();
const subscriptionActivationMode =
appData.subscriptionActivationRequired ??
requiresTenantSubscriptionActivation(appConfiguration.subscription.required, appData.mySubscription);
if (subscriptionActivationMode) {
return <Outlet />;
}
const vm = buildSettingsHubVM({
hubId: "billing",
titleKey: "settings.hubs.billing.title",
subtitleKey: "settings.hubs.billing.subtitle",
tabs,
currentPath: location.pathname,
});
return (
<SettingsHubShell vm={vm} icon={<FeatherCreditCard />}>
<Outlet />
</SettingsHubShell>
);
}
@@ -0,0 +1,664 @@
import { useEffect, useRef } from "react";
import { ActionFunction, LoaderFunctionArgs, redirect, useActionData, useFetcher, useLoaderData, useNavigate, useRevalidator, useSubmit } from "react-router";
import { toast } from "sonner";
import {
buildSeatUsageVM,
buildSelfServiceSubscriptionManagementPolicyVM,
buildSelfServiceSubscriptionPageVM,
buildSubscriptionOverviewVM,
type SelfServiceSubscriptionPageVM,
type SelfServiceCheckoutPaymentMethodsVM,
type SelfServiceSubscriptionPricePreviewVM,
type SubscriptionOverviewEntitlementInput,
type SubscriptionOverviewProductInput,
type SubscriptionOverviewVM,
} from "@hivegrid/view-models";
import { defaultBrandLinks } from "@hivegrid/brand";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { computeSeatUsage, getSeatPackage, resolveSeatPackageId } from "@hivegrid/entitlements";
import {
SelfServiceSubscriptionPage,
type SelfServiceSubscriptionPlanAdvice,
type SelfServiceSubscriptionSelection,
} from "~/components/screens/billing/SelfServiceSubscriptionPage";
import { getTranslations } from "~/locale/i18next.server";
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
import { getTenant } from "~/utils/db/tenants.db.server";
import { getUser } from "~/utils/db/users.db.server";
import { getRegistrationBillingPreference } from "~/utils/db/registration.db.server";
import { getTenantSubscription } from "~/utils/db/tenantSubscriptions.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { apiUrl, appPath } from "~/utils/app/CanonicalUrlUtils";
import { absolutePublicAppPath } from "~/utils/app/CrossHostUrls";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { cancelTenantSubscription, getPlanFeaturesUsage } from "~/utils/services/.server/subscriptionService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { useRootData } from "~/utils/data/useRootData";
import { useAppData } from "~/utils/data/useAppData";
import { requiresTenantSubscriptionActivation } from "~/utils/app/SubscriptionAccess";
import { getSubscriptionFeatureTitleKey } from "~/utils/app/SubscriptionFeatureText";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
import type { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import { createSelfServiceCheckout, SelfServiceCheckoutError } from "~/services/billing/self-service-checkout.server";
import { loadTenantRegistrationBillingPreference } from "~/services/billing/registration-billing-preference.server";
import { loadRegistrationPlanSelection } from "~/services/billing/registration-plan-selection.server";
import { createProductAcquisition, productAcquisitionReturnIdPlaceholder, ProductAcquisitionError } from "~/services/billing/product-acquisition.server";
import { loadCheckoutPaymentMethods } from "~/services/billing/payment-methods.server";
import { reserveRecurringProductCheckoutLedger } from "~/services/billing/recurring-checkout-policy.server";
import {
previewSelfServiceSubscription,
resolveCurrentRecurringGrossTotalCents,
resolveOtherActiveRecurringGrossTotalCents,
resolveSelfServicePreferredSelection,
SELF_SERVICE_SUBSCRIPTION_EFFECTIVE_AT_POLICY,
SelfServiceSubscriptionValidationError,
loadSelfServiceSubscriptionServerContext,
} from "~/services/billing/self-service-subscription.server";
export { serverTimingHeaders as headers };
type LoaderData = {
title: string;
vm: SelfServiceSubscriptionPageVM;
initialPlanAdvice: SelfServiceSubscriptionPlanAdvice | null;
initialEmailMarketingAddOnCode: string | null;
};
export function readRegistrationSeatPreference(searchParams: URLSearchParams): {
officeSeatQuantity: number;
fieldSeatQuantity: number;
} | null {
const officeRaw = searchParams.get("office_seats")?.trim() ?? "";
const fieldRaw = searchParams.get("field_seats")?.trim() ?? "";
if (!officeRaw && !fieldRaw) return null;
if (!/^\d{1,5}$/u.test(officeRaw) || !/^\d{1,5}$/u.test(fieldRaw)) return null;
const officeSeatQuantity = Number(officeRaw);
const fieldSeatQuantity = Number(fieldRaw);
if (officeSeatQuantity < 1 || officeSeatQuantity > 10_000 || fieldSeatQuantity < 0 || fieldSeatQuantity > 10_000) return null;
return { officeSeatQuantity, fieldSeatQuantity };
}
export function customerPortalSettingsPath(tenantSlug: string): string {
return appPath({ tenantSlug, path: "settings/customer-portal", mode: "host-aware" });
}
type ActionData = {
error?: string;
success?: string;
preview?: SelfServiceSubscriptionPricePreviewVM;
paymentMethods?: SelfServiceCheckoutPaymentMethodsVM;
planAdvice?: SelfServiceSubscriptionPlanAdvice;
emailMarketingPreview?: {
addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number];
paymentMethods: SelfServiceCheckoutPaymentMethodsVM;
};
};
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
async function hasPermission(request: Request, permission: DefaultPermission, tenantId: string): Promise<boolean> {
try {
await verifyUserHasPermission(request, permission, tenantId);
return true;
} catch (error) {
if (error instanceof Response && ((error.status >= 300 && error.status < 400) || error.status === 403 || error.status === 404)) return false;
throw error;
}
}
function toIso(value: Date | string | null | undefined): string | null {
if (!value) return null;
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "app.$tenant.settings.subscription");
const { t } = await getTranslations(request);
const tenantId = await time(getTenantIdFromUrl(params), "getTenantIdFromUrl");
await time(verifyUserHasPermission(request, "app.settings.subscription.view", tenantId), "verifyUserHasPermission");
const userInfo = await time(getUserInfo(request), "getUserInfo");
const [user, tenant] = await runWithRlsContext({ tenantId, userId: userInfo.userId }, () =>
Promise.all([time(getUser(userInfo.userId), "getUser"), time(getTenant(tenantId), "getTenant")])
);
if (!user) return badRequest({ error: t("shared.invalidUser") });
if (!tenant) return badRequest({ error: t("settings.subscription.errors.invalidTenant", { tenantId }) });
const title = `${t("billing:selfServiceSubscription.title")} | ${process.env.APP_NAME}`;
const contactHref = `${defaultBrandLinks.siteUrl}/kontakt`;
const [canUpdate, canDelete, selfServiceContext] = await Promise.all([
time(hasPermission(request, "app.settings.subscription.update", tenantId), "verifySubscriptionUpdatePermission"),
time(hasPermission(request, "app.settings.subscription.delete", tenantId), "verifySubscriptionDeletePermission"),
time(loadSelfServiceSubscriptionServerContext(tenantId), "loadSelfServiceSubscriptionServerContext"),
]);
const { tenantSubscription, billingState, catalog, minimumSeatQuantity, seatCounts, storageAddOns, emailMarketingAddOns, usage, currentSelection } =
selfServiceContext;
const searchParams = new URL(request.url).searchParams;
const requestedSelection = resolveSelfServicePreferredSelection(catalog, searchParams.get("selected_price"), readRegistrationSeatPreference(searchParams));
const registrationPreference = tenantSubscription
? null
: await runWithRlsContext({ tenantId, userId: userInfo.userId }, async () => {
const tenantPreference = await time(loadTenantRegistrationBillingPreference(tenantId), "loadTenantRegistrationBillingPreference");
if (tenantPreference) return tenantPreference;
// Rolling compatibility for accounts completed through the email-
// verification path before tenant-scoped preference persistence.
return await time(getRegistrationBillingPreference(tenantId, userInfo.userId), "getRegistrationBillingPreference");
});
const persistedSelection = registrationPreference
? resolveSelfServicePreferredSelection(catalog, registrationPreference.selectedSubscriptionPriceId, {
officeSeatQuantity: registrationPreference.selectedOfficeSeatQuantity,
fieldSeatQuantity: registrationPreference.selectedFieldSeatQuantity,
})
: null;
const preferredSelection = tenantSubscription ? null : (requestedSelection ?? persistedSelection);
const initialPlanAdvice = tenantSubscription
? null
: await time(
loadRegistrationPlanSelection(null, {
officeSeatQuantity: Math.max(1, preferredSelection?.officeSeatQuantity ?? seatCounts.office),
fieldSeatQuantity: Math.max(0, preferredSelection?.fieldSeatQuantity ?? seatCounts.field),
}),
"loadRegistrationPlanSelection"
);
let overview: SubscriptionOverviewVM;
if (!tenantSubscription) {
overview = buildSubscriptionOverviewVM({
hasSubscription: false,
status: null,
seatUsage: { status: "empty" },
products: [],
entitlements: [],
canCancel: false,
contactHref,
});
} else {
const features = await runWithRlsContext({ tenantId, userId: userInfo.userId }, () =>
time(getPlanFeaturesUsage(tenantId, tenantSubscription), "subscription[getPlanFeaturesUsage]")
);
const seatPackageId = resolveSeatPackageId(
billingState.planCode,
currentSelection?.planCode,
...tenantSubscription.products.flatMap((product) => [product.planCode, product.subscriptionProduct?.title, product.subscriptionProduct?.code])
);
const seatPackage = seatPackageId ? getSeatPackage(seatPackageId) : undefined;
const seatUsageProjection = seatPackage ? computeSeatUsage({ package: seatPackage, officeUsed: seatCounts.office, fieldUsed: seatCounts.field }) : null;
const seatUsage = buildSeatUsageVM({ packageId: seatPackageId, usage: seatUsageProjection, counts: seatCounts });
const products: SubscriptionOverviewProductInput[] = tenantSubscription.products.map((product) => {
const productPackageId = resolveSeatPackageId(product.planCode, product.subscriptionProduct.code, product.subscriptionProduct.title);
return {
id: product.id,
titleKey: productPackageId ? `settings.subscription.checkout.plans.packages.${productPackageId}.title` : product.subscriptionProduct.title,
code: product.planCode ?? product.subscriptionProduct.code,
kind: product.subscriptionProduct.kind,
acquisition: product.acquisition
? {
productKind: product.acquisition.productKind,
status: product.acquisition.status,
lagoSubscriptionId: product.acquisition.lagoSubscriptionId,
}
: null,
quantity: product.quantity ?? product.seatQuantity,
cancelledAt: toIso(product.cancelledAt),
endsAt: toIso(product.endsAt),
currentPeriodStart: toIso(product.currentPeriodStart),
currentPeriodEnd: toIso(product.currentPeriodEnd),
prices: product.prices
.filter((price) => !price.isMetered && price.subscriptionPrice)
.map((price) => ({
amount: price.subscriptionPrice ? Number(price.subscriptionPrice.price) : null,
currency: price.subscriptionPrice?.currency ?? null,
billingPeriod: price.subscriptionPrice?.billingPeriod ?? null,
quantity: price.quantity,
})),
};
});
const entitlements: SubscriptionOverviewEntitlementInput[] = features.map((feature) => ({
code: feature.name,
titleKey: getSubscriptionFeatureTitleKey(feature),
enabled: feature.enabled,
value: feature.value,
used: feature.used,
remaining: feature.remaining,
}));
overview = buildSubscriptionOverviewVM({
hasSubscription: true,
status: billingState.status,
trialEndsAt: toIso(billingState.trialEndsAt),
planCode: billingState.planCode,
seatUsage,
products,
entitlements,
canCancel: canUpdate && canDelete,
contactHref,
});
}
const managementPolicy = buildSelfServiceSubscriptionManagementPolicyVM({
planOrder: catalog.plans.map((plan) => plan.code),
effectiveAtByChangeKind: SELF_SERVICE_SUBSCRIPTION_EFFECTIVE_AT_POLICY,
});
const vm = buildSelfServiceSubscriptionPageVM({
overview,
catalog,
managementPolicy,
minimumSeatQuantity,
minimumSeatQuantities: seatCounts,
storageAddOns,
emailMarketingAddOns,
usage,
canManage: canUpdate,
billingHref: appPath({ tenantSlug: tenant.slug, path: "settings/billing", mode: "host-aware" }),
currentSelection,
preferredSelection,
});
const requestedEmailMarketingAddOnCode = searchParams.get("email_add_on")?.trim() ?? "";
const initialEmailMarketingAddOnCode = emailMarketingAddOns.find((addOn) => addOn.code === requestedEmailMarketingAddOnCode && !addOn.active)?.code ?? null;
return Response.json({ title, vm, initialPlanAdvice, initialEmailMarketingAddOnCode } satisfies LoaderData, { headers: getServerTimingHeader() });
};
function readPlanAdviceSeatQuantities(form: FormData): {
officeSeatQuantity: number;
fieldSeatQuantity: number;
} {
const officeRaw = form.get("office-seat-quantity")?.toString().trim() ?? "";
const fieldRaw = form.get("field-seat-quantity")?.toString().trim() ?? "";
if (!/^\d{1,5}$/u.test(officeRaw) || !/^\d{1,5}$/u.test(fieldRaw)) {
throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_INVALID");
}
const officeSeatQuantity = Number(officeRaw);
const fieldSeatQuantity = Number(fieldRaw);
if (officeSeatQuantity < 1 || officeSeatQuantity > 10_000 || fieldSeatQuantity < 0 || fieldSeatQuantity > 10_000) {
throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_INVALID");
}
return { officeSeatQuantity, fieldSeatQuantity };
}
function readSelection(form: FormData): SelfServiceSubscriptionSelection {
const productId = form.get("product-id")?.toString().trim() ?? "";
const priceId = form.get("price-id")?.toString().trim() ?? "";
const billingPeriodRaw = form.get("billing-period")?.toString().trim() ?? "";
const billingPeriod = Number(billingPeriodRaw);
const currency = form.get("currency")?.toString().trim() ?? "";
const officeSeatQuantityRaw = form.get("office-seat-quantity")?.toString().trim() ?? "";
const fieldSeatQuantityRaw = form.get("field-seat-quantity")?.toString().trim() ?? "";
const legacySeatQuantityRaw = form.get("seat-quantity")?.toString().trim() ?? "";
const usingLegacySeatQuantity = !officeSeatQuantityRaw && !fieldSeatQuantityRaw && Boolean(legacySeatQuantityRaw);
const officeSeatQuantity = Number(usingLegacySeatQuantity ? legacySeatQuantityRaw : officeSeatQuantityRaw);
const fieldSeatQuantity = Number(usingLegacySeatQuantity ? "0" : fieldSeatQuantityRaw);
const storageAddOnCodes = form
.getAll("storage-add-on-code")
.map((value) => value.toString().trim())
.filter(Boolean);
if (!productId) throw new SelfServiceSubscriptionValidationError("PLAN_NOT_FOUND");
if (!priceId) throw new SelfServiceSubscriptionValidationError("PRICE_NOT_FOUND");
if (!billingPeriodRaw || !Number.isSafeInteger(billingPeriod) || billingPeriod < 0 || !currency) {
throw new SelfServiceSubscriptionValidationError("PRICE_NOT_FOUND");
}
if (
(!usingLegacySeatQuantity && (!officeSeatQuantityRaw || !fieldSeatQuantityRaw)) ||
!Number.isSafeInteger(officeSeatQuantity) ||
!Number.isSafeInteger(fieldSeatQuantity) ||
officeSeatQuantity < 0 ||
fieldSeatQuantity < 0 ||
officeSeatQuantity + fieldSeatQuantity < 1
) {
throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_INVALID");
}
return { productId, priceId, billingPeriod, currency, officeSeatQuantity, fieldSeatQuantity, storageAddOnCodes };
}
function selectionForm(intent: "preview" | "checkout", selection: SelfServiceSubscriptionSelection, csrf: string): FormData {
const form = new FormData();
form.set("intent", intent);
form.set("csrf", csrf);
form.set("product-id", selection.productId);
form.set("price-id", selection.priceId);
form.set("billing-period", String(selection.billingPeriod));
form.set("currency", selection.currency);
form.set("office-seat-quantity", String(selection.officeSeatQuantity));
form.set("field-seat-quantity", String(selection.fieldSeatQuantity));
for (const code of selection.storageAddOnCodes) form.append("storage-add-on-code", code);
if (selection.emailMarketingAddOnCode) form.set("email-marketing-add-on-code", selection.emailMarketingAddOnCode);
return form;
}
export const action: ActionFunction = async ({ request, params }) => {
const { t, locale } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.subscription.update", tenantId);
const userInfo = await getUserInfo(request);
await validateCSRFToken(request);
const form = await request.formData();
const intent = form.get("intent")?.toString() || form.get("action")?.toString();
try {
if (intent === "plan-advice") {
const seatQuantities = readPlanAdviceSeatQuantities(form);
const planAdvice = await loadRegistrationPlanSelection(null, seatQuantities);
return Response.json({ planAdvice } satisfies ActionData);
}
if (intent === "preview") {
const selection = readSelection(form);
const preview = await previewSelfServiceSubscription(tenantId, {
productId: selection.productId,
priceId: selection.priceId,
officeSeatQuantity: selection.officeSeatQuantity,
fieldSeatQuantity: selection.fieldSeatQuantity,
storageAddOnCodes: selection.storageAddOnCodes,
});
const tenantSubscription = await runWithRlsContext({ tenantId, userId: userInfo.userId }, () => getTenantSubscription(tenantId));
const otherRecurringGrossTotalCents = resolveOtherActiveRecurringGrossTotalCents(tenantSubscription);
const paymentPolicyAmountCents =
otherRecurringGrossTotalCents === null || !Number.isSafeInteger(preview.recurringGrossTotalCents + otherRecurringGrossTotalCents)
? null
: preview.recurringGrossTotalCents + otherRecurringGrossTotalCents;
if (paymentPolicyAmountCents === null) throw new ProductAcquisitionError("PAYMENT_METHOD_UNAVAILABLE");
const paymentMethods = await loadCheckoutPaymentMethods({
amountCents: (preview.changeKind === "new" && preview.trialDays > 0) || preview.effectiveAt === "period_end" ? 0 : preview.recurringGrossTotalCents,
policyAmountCents: paymentPolicyAmountCents,
currency: preview.selectedPrice.currency,
sequenceType: "first",
locale: locale ?? "de",
requirement: "any",
});
return Response.json({ preview, paymentMethods } satisfies ActionData);
}
if (intent === "checkout") {
const selection = readSelection(form);
const requestedEmailMarketingAddOnCode = form.get("email-marketing-add-on-code")?.toString().trim() ?? "";
const emailMarketingAddOnCode = requestedEmailMarketingAddOnCode
? (await loadSelfServiceSubscriptionServerContext(tenantId)).emailMarketingAddOns.find(
(addOn) => addOn.code === requestedEmailMarketingAddOnCode && !addOn.active
)?.code
: null;
if (requestedEmailMarketingAddOnCode && !emailMarketingAddOnCode) {
return badRequest({ error: t("billing:selfServiceSubscription.emailMarketing.errors.selectionUnavailable") });
}
const [user, tenant] = await runWithRlsContext({ tenantId, userId: userInfo.userId }, () => Promise.all([getUser(userInfo.userId), getTenant(tenantId)]));
if (!user) return badRequest({ error: t("shared.invalidUser") });
if (!tenant) return badRequest({ error: t("settings.subscription.errors.invalidTenant", { tenantId }) });
const checkout = await createSelfServiceCheckout({
request,
checkoutRequestKey: form.get("checkout-request-key")?.toString() ?? "",
tenantId,
tenantSlug: tenant.slug,
tenantName: tenant.name,
userId: user.id,
userEmail: user.email,
userName: [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email,
productId: selection.productId,
priceId: selection.priceId,
billingPeriod: selection.billingPeriod,
currency: selection.currency,
officeSeatQuantity: selection.officeSeatQuantity,
fieldSeatQuantity: selection.fieldSeatQuantity,
storageAddOnCodes: selection.storageAddOnCodes,
paymentMethod: form.get("payment-method")?.toString() ?? null,
paymentLocale: locale ?? "de",
postActivationEmailMarketingAddOnCode: emailMarketingAddOnCode,
});
throw redirect(checkout.checkoutUrl);
}
if (intent === "email-marketing-preview" || intent === "email-marketing-checkout") {
const productId = form.get("product-id")?.toString().trim() ?? "";
const priceId = form.get("price-id")?.toString().trim() ?? "";
const context = await loadSelfServiceSubscriptionServerContext(tenantId);
const selected = context.emailMarketingAddOns.find((addOn) => addOn.productId === productId && addOn.priceId === priceId && !addOn.active);
if (!selected) {
return badRequest({ error: t("billing:selfServiceSubscription.emailMarketing.errors.selectionUnavailable") });
}
if (intent === "email-marketing-preview") {
const currentRecurringGrossTotalCents = resolveCurrentRecurringGrossTotalCents(context, {
excludedProductCodes: context.emailMarketingAddOns.map((addOn) => addOn.code),
});
const paymentPolicyAmountCents =
currentRecurringGrossTotalCents === null || !Number.isSafeInteger(currentRecurringGrossTotalCents + selected.grossAmountCents)
? null
: currentRecurringGrossTotalCents + selected.grossAmountCents;
if (paymentPolicyAmountCents === null) {
throw new ProductAcquisitionError("PAYMENT_METHOD_UNAVAILABLE");
}
const paymentMethods = await loadCheckoutPaymentMethods({
amountCents: selected.grossAmountCents,
policyAmountCents: paymentPolicyAmountCents,
currency: selected.currency,
sequenceType: "first",
locale: locale ?? "de",
});
return Response.json({ emailMarketingPreview: { addOn: selected, paymentMethods } } satisfies ActionData);
}
const [user, tenant] = await runWithRlsContext({ tenantId, userId: userInfo.userId }, () => Promise.all([getUser(userInfo.userId), getTenant(tenantId)]));
if (!user) return badRequest({ error: t("shared.invalidUser") });
if (!tenant) return badRequest({ error: t("settings.subscription.errors.invalidTenant", { tenantId }) });
const config = loadRequiredWebConfig();
const acquisitionInput = {
tenantId,
tenantName: tenant.name,
userId: user.id,
userEmail: user.email,
userName: [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email,
productId: selected.productId,
priceId: selected.priceId,
scopeKey: "tenant",
redirectUrl: absolutePublicAppPath(
config.routing,
`/subscribe/${encodeURIComponent(tenant.slug)}/product/${productAcquisitionReturnIdPlaceholder}/success`
),
webhookUrl: apiUrl({
rootDomain: config.routing.apiHost,
protocol: config.routing.protocol,
path: "billing/mollie/webhooks",
version: "v1",
mode: "host-aware",
}),
paymentMethod: form.get("payment-method")?.toString() ?? null,
paymentLocale: locale ?? "de",
};
const locked = await reserveRecurringProductCheckoutLedger(acquisitionInput, {
replacedProductCodes: context.emailMarketingAddOns.map((addOn) => addOn.code),
});
const checkout = await createProductAcquisition({
...acquisitionInput,
paymentPolicyAmountCents: locked.paymentPolicyAmountCents,
});
if (!checkout.checkoutUrl) throw new ProductAcquisitionError("CHECKOUT_URL_MISSING");
throw redirect(checkout.checkoutUrl);
}
if (intent === "cancel") {
await verifyUserHasPermission(request, "app.settings.subscription.delete", tenantId);
const tenantSubscriptionProductId = form.get("tenant-subscription-product-id")?.toString() ?? "";
await runWithRlsContext({ tenantId, userId: userInfo.userId }, () =>
cancelTenantSubscription(tenantSubscriptionProductId, { t, tenantId, userId: userInfo.userId })
);
return Response.json({ success: t("settings.subscription.success.cancelled") });
}
return badRequest({ error: t("billing:selfServiceSubscription.errors.unsupportedAction") });
} catch (error) {
if (error instanceof Response) throw error;
if (error instanceof ProductAcquisitionError) {
const providerUnavailable = error.code === "PROVIDER_CONFIGURATION_MISSING" || error.code === "PROVIDER_FAILED";
const paymentMethodError = error.code === "PAYMENT_METHOD_INVALID" || error.code === "PAYMENT_METHOD_UNAVAILABLE";
return Response.json(
{
error: t(
providerUnavailable
? "customerPortal.domain.errors.checkoutUnavailable"
: paymentMethodError
? `billing:selfServiceSubscription.errors.${error.code}`
: "shared.unexpectedError"
),
},
{ status: providerUnavailable ? 503 : 409 }
);
}
if (error instanceof SelfServiceSubscriptionValidationError || error instanceof SelfServiceCheckoutError) {
return badRequest({ error: t(error.i18nKey) });
}
// eslint-disable-next-line no-console
console.error(error);
return badRequest({ error: t("shared.unexpectedError") });
}
};
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
export default function SubscriptionRoute() {
const { vm, initialPlanAdvice, initialEmailMarketingAddOnCode } = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const planAdviceFetcher = useFetcher<ActionData>();
const previewFetcher = useFetcher<ActionData>();
const emailMarketingPreviewFetcher = useFetcher<ActionData>();
const submit = useSubmit();
const navigate = useNavigate();
const revalidator = useRevalidator();
const { csrf, appConfiguration } = useRootData();
const appData = useAppData();
const activationMode =
appData.subscriptionActivationRequired ?? requiresTenantSubscriptionActivation(appConfiguration.subscription.required, appData.mySubscription);
const planAdviceResolver = useRef<{
resolve: (result: SelfServiceSubscriptionPlanAdvice) => void;
reject: (error: Error) => void;
} | null>(null);
const previewResolver = useRef<{
resolve: (result: { preview: SelfServiceSubscriptionPricePreviewVM; paymentMethods: SelfServiceCheckoutPaymentMethodsVM }) => void;
reject: (error: Error) => void;
} | null>(null);
const emailMarketingPreviewResolver = useRef<{
resolve: (result: { addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number]; paymentMethods: SelfServiceCheckoutPaymentMethodsVM }) => void;
reject: (error: Error) => void;
} | null>(null);
useEffect(() => {
if (actionData?.error) toast.error(actionData.error);
else if (actionData?.success) toast.success(actionData.success);
}, [actionData]);
useEffect(() => {
if (planAdviceFetcher.state !== "idle" || !planAdviceResolver.current) return;
const resolver = planAdviceResolver.current;
planAdviceResolver.current = null;
if (planAdviceFetcher.data?.planAdvice) resolver.resolve(planAdviceFetcher.data.planAdvice);
else resolver.reject(new Error(planAdviceFetcher.data?.error ?? "Plan advice unavailable"));
}, [planAdviceFetcher.data, planAdviceFetcher.state]);
useEffect(() => {
if (previewFetcher.state !== "idle" || !previewResolver.current) return;
const resolver = previewResolver.current;
previewResolver.current = null;
if (previewFetcher.data?.preview && previewFetcher.data.paymentMethods) {
resolver.resolve({ preview: previewFetcher.data.preview, paymentMethods: previewFetcher.data.paymentMethods });
} else resolver.reject(new Error(previewFetcher.data?.error ?? "Preview unavailable"));
}, [previewFetcher.data, previewFetcher.state]);
useEffect(() => {
if (emailMarketingPreviewFetcher.state !== "idle" || !emailMarketingPreviewResolver.current) return;
const resolver = emailMarketingPreviewResolver.current;
emailMarketingPreviewResolver.current = null;
if (emailMarketingPreviewFetcher.data?.emailMarketingPreview) {
resolver.resolve(emailMarketingPreviewFetcher.data.emailMarketingPreview);
} else {
resolver.reject(new Error(emailMarketingPreviewFetcher.data?.error ?? "Email marketing preview unavailable"));
}
}, [emailMarketingPreviewFetcher.data, emailMarketingPreviewFetcher.state]);
useEffect(
() => () => {
planAdviceResolver.current?.reject(new Error("Plan advice cancelled"));
planAdviceResolver.current = null;
previewResolver.current?.reject(new Error("Preview cancelled"));
previewResolver.current = null;
emailMarketingPreviewResolver.current?.reject(new Error("Email marketing preview cancelled"));
emailMarketingPreviewResolver.current = null;
},
[]
);
return (
<SelfServiceSubscriptionPage
embedded
activationMode={activationMode}
initialPlanAdvice={initialPlanAdvice}
initialEmailMarketingAddOnCode={initialEmailMarketingAddOnCode}
vm={vm}
actions={{
onPlanAdvice(seatQuantities) {
planAdviceResolver.current?.reject(new Error("Plan advice superseded"));
return new Promise<SelfServiceSubscriptionPlanAdvice>((resolve, reject) => {
planAdviceResolver.current = { resolve, reject };
const form = new FormData();
form.set("intent", "plan-advice");
form.set("csrf", csrf ?? "");
form.set("office-seat-quantity", String(seatQuantities.officeSeatQuantity));
form.set("field-seat-quantity", String(seatQuantities.fieldSeatQuantity));
void planAdviceFetcher.submit(form, { method: "post" });
});
},
onRetry() {
revalidator.revalidate();
},
onOpenBilling() {
void navigate(vm.billingHref);
},
onOpenCustomerPortal: getUserHasPermission(appData, "portal.admin")
? () => {
void navigate(customerPortalSettingsPath(appData.currentTenant.slug));
}
: undefined,
onPreview(selection) {
previewResolver.current?.reject(new Error("Preview superseded"));
return new Promise<{ preview: SelfServiceSubscriptionPricePreviewVM; paymentMethods: SelfServiceCheckoutPaymentMethodsVM }>((resolve, reject) => {
previewResolver.current = { resolve, reject };
void previewFetcher.submit(selectionForm("preview", selection, csrf ?? ""), { method: "post" });
});
},
onCheckout(selection, paymentMethod, checkoutRequestKey) {
const form = selectionForm("checkout", selection, csrf ?? "");
if (paymentMethod) form.set("payment-method", paymentMethod);
form.set("checkout-request-key", checkoutRequestKey);
return submit(form, { method: "post" });
},
onCancel(productId) {
const form = new FormData();
form.set("intent", "cancel");
form.set("csrf", csrf ?? "");
form.set("tenant-subscription-product-id", productId);
return submit(form, { method: "post" });
},
onEmailMarketingPreview(addOn) {
emailMarketingPreviewResolver.current?.reject(new Error("Email marketing preview superseded"));
return new Promise<{
addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number];
paymentMethods: SelfServiceCheckoutPaymentMethodsVM;
}>((resolve, reject) => {
emailMarketingPreviewResolver.current = { resolve, reject };
const form = new FormData();
form.set("intent", "email-marketing-preview");
form.set("csrf", csrf ?? "");
form.set("product-id", addOn.productId);
form.set("price-id", addOn.priceId);
void emailMarketingPreviewFetcher.submit(form, { method: "post" });
});
},
onEmailMarketingCheckout(addOn, paymentMethod) {
const form = new FormData();
form.set("intent", "email-marketing-checkout");
form.set("csrf", csrf ?? "");
form.set("product-id", addOn.productId);
form.set("price-id", addOn.priceId);
if (paymentMethod) form.set("payment-method", paymentMethod);
return submit(form, { method: "post" });
},
}}
/>
);
}
@@ -0,0 +1,88 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { LoaderFunctionArgs } from "react-router";
const mocks = vi.hoisted(() => ({
getTranslations: vi.fn(),
getTenantIdFromUrl: vi.fn(),
verifyUserHasPermission: vi.fn(),
getUserInfo: vi.fn(),
tenantHasModule: vi.fn(),
getTenant: vi.fn(),
getTenantSubscription: vi.fn(),
listCustomerBillingInvoices: vi.fn(),
}));
vi.mock("~/components/screens/billing/BillingPaymentPage", () => ({ BillingPaymentPage: () => null }));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: (...args: unknown[]) => mocks.getTenantIdFromUrl(...args) }));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: (...args: unknown[]) => mocks.verifyUserHasPermission(...args) }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: (...args: unknown[]) => mocks.getUserInfo(...args) }));
vi.mock("~/utils/connector/tenantConnector.server", () => ({ tenantHasModule: (...args: unknown[]) => mocks.tenantHasModule(...args) }));
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenant: (...args: unknown[]) => mocks.getTenant(...args) }));
vi.mock("~/utils/db/tenantSubscriptions.db.server", () => ({ getTenantSubscription: (...args: unknown[]) => mocks.getTenantSubscription(...args) }));
vi.mock("~/services/billing/customer-invoices.server", () => ({
CustomerBillingInvoiceError: class CustomerBillingInvoiceError extends Error {
readonly i18nKey = "settings.subscription.errors.INVOICE_LIST_UNAVAILABLE";
},
listCustomerBillingInvoices: (...args: unknown[]) => mocks.listCustomerBillingInvoices(...args),
}));
import { loader } from "./invoices";
async function callLoader() {
return loader({
request: new Request("https://app.example.test/acme/settings/billing"),
params: { tenant: "acme" },
context: {},
unstable_pattern: "app.$tenant/settings/billing",
} as LoaderFunctionArgs);
}
describe("tenant billing payment route", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
mocks.getTenantIdFromUrl.mockResolvedValue("tenant_1");
mocks.verifyUserHasPermission.mockResolvedValue(undefined);
mocks.getUserInfo.mockResolvedValue({ userId: "user_1" });
mocks.tenantHasModule.mockResolvedValue(true);
mocks.getTenant.mockResolvedValue({ id: "tenant_1", slug: "acme" });
mocks.getTenantSubscription.mockResolvedValue({ lastPaymentExternalId: "tr_123" });
mocks.listCustomerBillingInvoices.mockResolvedValue([
{
id: "invoice_1",
number: "LAG-001",
issuingDate: "2026-07-10",
amountCents: 4_900,
currency: "EUR",
status: "finalized",
paymentStatus: "succeeded",
invoiceType: "subscription",
downloadHref: "/acme/settings/subscription/invoices/invoice_1/download",
},
]);
});
it("requires invoice permission and builds Lago/Mollie payment state", async () => {
const data = await callLoader();
expect(mocks.verifyUserHasPermission).toHaveBeenCalledTimes(1);
expect(mocks.verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.subscription.invoices.view", "tenant_1");
expect(mocks.verifyUserHasPermission).not.toHaveBeenCalledWith(expect.any(Request), "app.settings.subscription.view", expect.any(String));
expect(mocks.listCustomerBillingInvoices).toHaveBeenCalledWith({ tenantId: "tenant_1", tenantSlug: "acme" });
expect(data.vm).toMatchObject({
status: "ready",
data: { latestPaymentStatus: "succeeded", hasMollieReference: true },
});
expect(data.vm.status === "ready" ? data.vm.data.invoices[0]?.downloadHref : null).toBe("/acme/settings/subscription/invoices/invoice_1/download");
});
it("returns a localized VM error when Lago cannot list invoices", async () => {
mocks.listCustomerBillingInvoices.mockRejectedValueOnce(new Error("upstream unavailable"));
const data = await callLoader();
expect(data.vm).toEqual({
status: "error",
error: { messageKey: "settings.subscription.errors.INVOICE_LIST_UNAVAILABLE", code: "INVOICE_LIST_UNAVAILABLE" },
});
});
});
@@ -0,0 +1,56 @@
import { LoaderFunctionArgs, redirect, useLoaderData, useRevalidator } from "react-router";
import { buildBillingPaymentVM, type BillingPaymentVM } from "@hivegrid/view-models";
import { BillingPaymentPage } from "~/components/screens/billing/BillingPaymentPage";
import { getTranslations } from "~/locale/i18next.server";
import { CustomerBillingInvoiceError, listCustomerBillingInvoices } from "~/services/billing/customer-invoices.server";
import { appTenantPlanRequiredPath } from "~/utils/app/AppTenantStatusPaths";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { getTenantSubscription } from "~/utils/db/tenantSubscriptions.db.server";
import { getTenant } from "~/utils/db/tenants.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { BILLING_MODULE_KEY } from "~/utils/services/.server/billingStatusService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
type LoaderData = { title: string; vm: BillingPaymentVM };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.subscription.invoices.view", tenantId);
const userInfo = await getUserInfo(request);
const hasBillingModule = await tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: BILLING_MODULE_KEY });
if (!hasBillingModule) throw redirect(appTenantPlanRequiredPath(params));
const [{ t }, tenant, subscription] = await Promise.all([getTranslations(request), getTenant(tenantId), getTenantSubscription(tenantId)]);
if (!tenant) throw new Response(t("settings.subscription.errors.invalidTenant", { tenantId }), { status: 404 });
const invoiceResult = await listCustomerBillingInvoices({ tenantId, tenantSlug: tenant.slug })
.then((invoices) => ({ invoices, errorKey: null }))
.catch((error) => ({
invoices: [],
errorKey: error instanceof CustomerBillingInvoiceError ? error.i18nKey : "settings.subscription.errors.INVOICE_LIST_UNAVAILABLE",
}));
const vm = buildBillingPaymentVM({
invoices: invoiceResult.invoices,
lastPaymentExternalId: subscription?.lastPaymentExternalId,
errorKey: invoiceResult.errorKey,
});
return { title: `${t("billing:billingPayment.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData;
};
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
export default function BillingPaymentRoute() {
const { vm } = useLoaderData<LoaderData>();
const revalidator = useRevalidator();
return (
<BillingPaymentPage
vm={vm}
embedded
actions={{
onDownloadInvoice: (href) => window.open(href, "_blank", "noopener,noreferrer"),
onRetry: () => revalidator.revalidate(),
}}
/>
);
}
@@ -0,0 +1,106 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { LoaderFunctionArgs } from "react-router";
const mocks = vi.hoisted(() => ({
getTranslations: vi.fn(),
getTenantIdFromUrl: vi.fn(),
verifyUserHasPermission: vi.fn(),
getUserInfo: vi.fn(),
tenantHasModule: vi.fn(),
getBillingUsageSummary: vi.fn(),
}));
vi.mock("~/components/screens/billing/BillingUsagePage", () => ({ BillingUsagePage: () => null }));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: (...args: unknown[]) => mocks.getTenantIdFromUrl(...args) }));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: (...args: unknown[]) => mocks.verifyUserHasPermission(...args) }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: (...args: unknown[]) => mocks.getUserInfo(...args) }));
vi.mock("~/utils/connector/tenantConnector.server", () => ({ tenantHasModule: (...args: unknown[]) => mocks.tenantHasModule(...args) }));
vi.mock("~/utils/services/.server/billingStatusService", () => ({
BILLING_MODULE_KEY: "billing",
getBillingUsageSummary: (...args: unknown[]) => mocks.getBillingUsageSummary(...args),
}));
import { loader } from "./usage";
function callLoader() {
return loader({
request: new Request("https://app.example.test/acme/settings/billing/usage"),
params: { tenant: "acme" },
context: {},
unstable_pattern: "app.$tenant/settings/billing/usage",
} as LoaderFunctionArgs);
}
describe("tenant billing usage route", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
mocks.getTenantIdFromUrl.mockResolvedValue("tenant_1");
mocks.verifyUserHasPermission.mockResolvedValue(undefined);
mocks.getUserInfo.mockResolvedValue({ userId: "user_1" });
mocks.tenantHasModule.mockResolvedValue(true);
mocks.getBillingUsageSummary.mockResolvedValue({
periodStart: new Date("2026-08-01T00:00:00.000Z"),
periodEnd: new Date("2026-09-01T00:00:00.000Z"),
storageUnavailableReason: null,
metrics: [
{
metricCode: "storage_bytes",
quantity: 75,
quota: 350 * 1024 ** 3,
remaining: 350 * 1024 ** 3 - 75,
exceeded: false,
percentUsed: 0,
},
],
});
});
it("renders the canonical storage allowance from the RLS-bound usage projection", async () => {
const data = await callLoader();
expect(mocks.verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.subscription.view", "tenant_1");
expect(data.vm).toMatchObject({
status: "ready",
data: { metrics: [expect.objectContaining({ metricCode: "storage_bytes", quantity: 75, quota: 350 * 1024 ** 3 })] },
});
});
it("keeps healthy counters visible without claiming unlimited storage when capacity is unavailable", async () => {
mocks.getBillingUsageSummary.mockResolvedValueOnce({
periodStart: new Date("2026-08-01T00:00:00.000Z"),
periodEnd: new Date("2026-09-01T00:00:00.000Z"),
storageUnavailableReason: "plan_unknown",
metrics: [
{
metricCode: "automation_runs",
quantity: 12,
quota: 100,
remaining: 88,
exceeded: false,
percentUsed: 12,
},
{
metricCode: "storage_bytes",
quantity: 0,
quota: null,
remaining: null,
exceeded: false,
percentUsed: null,
},
],
});
const data = await callLoader();
expect(data.vm).toMatchObject({
status: "ready",
data: {
unavailableMetrics: ["storage_bytes"],
metrics: [expect.objectContaining({ metricCode: "automation_runs", quantity: 12 })],
},
});
});
});
@@ -0,0 +1,37 @@
import { LoaderFunctionArgs, redirect, useLoaderData, useRevalidator } from "react-router";
import { buildBillingUsageVM, type BillingUsageVM } from "@hivegrid/view-models";
import { BillingUsagePage } from "~/components/screens/billing/BillingUsagePage";
import { getTranslations } from "~/locale/i18next.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { appTenantPlanRequiredPath } from "~/utils/app/AppTenantStatusPaths";
import { BILLING_MODULE_KEY, getBillingUsageSummary } from "~/utils/services/.server/billingStatusService";
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
type LoaderData = { title: string; vm: BillingUsageVM };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.subscription.view", tenantId);
const userInfo = await getUserInfo(request);
const hasBillingModule = await tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: BILLING_MODULE_KEY });
if (!hasBillingModule) throw redirect(appTenantPlanRequiredPath(params));
const [{ t }, summary] = await Promise.all([getTranslations(request), getBillingUsageSummary(tenantId)]);
const vm: BillingUsageVM = buildBillingUsageVM({
periodStart: summary.periodStart.toISOString(),
periodEnd: summary.periodEnd.toISOString(),
metrics: summary.metrics,
unavailableMetricCodes: summary.storageUnavailableReason ? ["storage_bytes"] : [],
});
return { title: `${t("billing:usage.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData;
};
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
export default function BillingUsageRoute() {
const { vm } = useLoaderData<LoaderData>();
const revalidator = useRevalidator();
return <BillingUsagePage vm={vm} embedded actions={{ onRetry: () => revalidator.revalidate() }} />;
}
@@ -0,0 +1,128 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadChatContext: vi.fn(),
readSession: vi.fn(),
loadAttachment: vi.fn(),
assertTenantKey: vi.fn(),
createDownloadUrl: vi.fn(),
}));
vi.mock("~/modules/chat/routes/chatAccess.server", async (importOriginal) => {
const actual = await importOriginal<typeof import("~/modules/chat/routes/chatAccess.server")>();
return { ...actual, loadChatContext: mocks.loadChatContext };
});
vi.mock("~/modules/chat/services/chatAuditSession.server", () => ({ readChatAuditSession: mocks.readSession }));
vi.mock("~/modules/chat/services/ChatAuditService.server", () => ({ loadChatAuditAttachment: mocks.loadAttachment }));
vi.mock("@hivegrid/storage", () => ({ assertFileKeyBelongsToTenant: mocks.assertTenantKey }));
vi.mock("~/utils/integrations/mediaSigning.server", () => ({ createMediaDownloadUrl: mocks.createDownloadUrl }));
import { loader } from "./audit.$id.attachments.$fileId.$variant";
const context = {
tenantId: "tenant-1",
userId: "admin-1",
tenantUserId: "tenant-user-1",
permissions: ["chat.read_all_channels"],
hasModule: true as const,
};
const session = {
id: "session-1",
tenantId: "tenant-1",
userId: "admin-1",
reason: "Supportfall",
issuedAt: new Date("2026-07-16T10:00:00.000Z").getTime(),
expiresAt: new Date("2026-07-16T10:02:00.000Z").getTime(),
};
describe("chat audit attachment media route", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-07-16T10:00:00.000Z"));
mocks.loadChatContext.mockResolvedValue(context);
mocks.readSession.mockResolvedValue(session);
mocks.loadAttachment.mockResolvedValue({
fileId: "file-1",
messageId: "message-1",
displayName: "beleg.pdf",
storageKey: "tenants/tenant-1/files/file-1",
});
mocks.createDownloadUrl.mockResolvedValue("https://storage.test/signed");
});
afterEach(() => {
vi.useRealTimers();
});
it("returns 404 without a reason-bound audit session", async () => {
mocks.readSession.mockResolvedValue(null);
const response = await loader(args());
expect(response.status).toBe(404);
expect(mocks.loadAttachment).not.toHaveBeenCalled();
});
it("logs the audit-bound read before signing and redirecting", async () => {
const response = await loader(args());
expect(mocks.loadAttachment).toHaveBeenCalledWith(
expect.objectContaining({
context,
chatId: "chat-1",
fileId: "file-1",
variant: "original",
session,
requestId: expect.any(String),
})
);
expect(mocks.assertTenantKey).toHaveBeenCalledWith("tenant-1", "tenants/tenant-1/files/file-1", "download");
expect(mocks.createDownloadUrl).toHaveBeenCalledWith({
key: "tenants/tenant-1/files/file-1",
filename: "beleg.pdf",
ttlSeconds: 60,
});
expect(response.status).toBe(302);
expect(response.headers.get("location")).toBe("https://storage.test/signed");
});
it("caps the signed URL to the remaining whole audit-session lifetime", async () => {
mocks.readSession.mockResolvedValue({ ...session, expiresAt: Date.now() + 20_900 });
const response = await loader(args());
expect(response.status).toBe(302);
expect(mocks.createDownloadUrl).toHaveBeenCalledWith(expect.objectContaining({ ttlSeconds: 20 }));
});
it("does not audit or sign when less than one whole session second remains", async () => {
mocks.readSession.mockResolvedValue({ ...session, expiresAt: Date.now() + 999 });
const response = await loader(args());
expect(response.status).toBe(404);
expect(mocks.loadAttachment).not.toHaveBeenCalled();
expect(mocks.createDownloadUrl).not.toHaveBeenCalled();
});
it("fails closed for missing variants and tenant-key mismatches", async () => {
const invalidVariant = await loader(args({ variant: "raw" }));
expect(invalidVariant.status).toBe(404);
mocks.assertTenantKey.mockImplementationOnce(() => {
throw new Error("foreign key");
});
const foreignKey = await loader(args());
expect(foreignKey.status).toBe(404);
});
});
function args(overrides: Partial<Record<"tenant" | "id" | "fileId" | "variant", string>> = {}) {
return {
request: new Request("http://app.localhost/demo/settings/chat/audit/chat-1/attachments/file-1/original"),
params: { tenant: "demo", id: "chat-1", fileId: "file-1", variant: "original", ...overrides },
context: {},
unstable_pattern: "app.$tenant/settings/chat/audit.$id.attachments.$fileId.$variant",
};
}
@@ -0,0 +1,61 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import type { ChatAuditAttachmentVariant } from "@hivegrid/chat/audit.server";
import { assertFileKeyBelongsToTenant } from "@hivegrid/storage";
import type { LoaderFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { loadChatContext, requireChatPermission } from "~/modules/chat/routes/chatAccess.server";
import { loadChatAuditAttachment } from "~/modules/chat/services/ChatAuditService.server";
import { readChatAuditSession } from "~/modules/chat/services/chatAuditSession.server";
import { createMediaDownloadUrl } from "~/utils/integrations/mediaSigning.server";
const CHAT_AUDIT_SIGNED_URL_MAX_TTL_SECONDS = 60;
function notFound(): Response {
return new Response("Not Found", { status: 404 });
}
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
const chatId = params.id?.trim() ?? "";
const fileId = params.fileId?.trim() ?? "";
const variant = parseVariant(params.variant);
if (!chatId || !fileId || !variant) return notFound();
try {
const loadedContext = await loadChatContext({ request, params });
const context = requireChatPermission(loadedContext, CHAT_PERMISSIONS.readAllChannels);
const session = await readChatAuditSession({ request, tenantId: context.tenantId, userId: context.userId });
if (!session) return notFound();
const ttlSeconds = auditDownloadTtlSeconds(session.expiresAt);
if (ttlSeconds === null) return notFound();
const file = await loadChatAuditAttachment({
context,
chatId,
fileId,
variant,
session,
requestId: crypto.randomUUID(),
});
assertFileKeyBelongsToTenant(context.tenantId, file.storageKey, "download");
const url = await createMediaDownloadUrl({
key: file.storageKey,
filename: variant === "original" ? file.displayName : undefined,
ttlSeconds,
});
return redirect(url, 302);
} catch {
return notFound();
}
}
function auditDownloadTtlSeconds(expiresAt: number): number | null {
const remainingWholeSeconds = Math.floor((expiresAt - Date.now()) / 1_000);
if (remainingWholeSeconds < 1) return null;
return Math.min(CHAT_AUDIT_SIGNED_URL_MAX_TTL_SECONDS, remainingWholeSeconds);
}
function parseVariant(value: string | undefined): ChatAuditAttachmentVariant | null {
return value === "original" || value === "preview" || value === "thumb" ? value : null;
}
@@ -0,0 +1,11 @@
// AK-SET-01 — legacy chat-audit detail path. The attachment route below it keeps
// its own published URL and is unaffected by this redirect (flat sibling).
import type { LoaderFunctionArgs } from "react-router";
import { legacySettingsRedirect } from "../legacy-redirects.server";
export const loader = ({ request, params }: LoaderFunctionArgs) =>
legacySettingsRedirect({ request, params }, `settings/compliance/chat/${encodeURIComponent(params.id ?? "")}`);
export default function LegacyChatAuditDetailRedirect() {
return null;
}
@@ -0,0 +1,8 @@
// AK-SET-01 — legacy `settings/chat/audit` is now a tab of the Compliance-Hub.
import { legacySettingsRedirectLoader } from "../legacy-redirects.server";
export const loader = legacySettingsRedirectLoader("settings/compliance/chat");
export default function LegacyChatAuditRedirect() {
return null;
}
@@ -0,0 +1,96 @@
// AK-SET-01 Hub F — "Compliance & Protokolle" bundles the audit log, the audit
// export, the chat audit and the tenant-wide privacy administration. Layout
// route only.
//
// This hub is what finally makes the audit export reachable from navigation;
// before, it existed only as a deep link.
import { Outlet, useLoaderData, useLocation, type LoaderFunctionArgs, type MetaFunction } from "react-router";
import { FeatherClipboardList } from "@subframe/core";
import { buildSettingsHubVM, type SettingsHubTabInput } from "@hivegrid/view-models";
import { SettingsHubShell } from "~/components/screens/settings/SettingsHubShell";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { CHAT_MODULE_KEY } from "~/modules/chat/routes/chatRoutePaths";
import { hasSettingsPermission, settingsHubBaseRedirect, settingsHubNotFound } from "./hub-access.server";
type LoaderData = {
title: string;
tabs: SettingsHubTabInput[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
const [{ t }, userInfo, canViewAudit, canReadChat, canExportTenant, canReadAvv, canReadSubprocessors, canDeleteTenant] = await Promise.all([
getTranslations(request),
getUserInfo(request),
hasSettingsPermission(request, "app.settings.auditTrails.view", tenantId),
hasSettingsPermission(request, "chat.read_all_channels", tenantId),
hasSettingsPermission(request, "privacy.tenant_export", tenantId),
hasSettingsPermission(request, "privacy.avv.read", tenantId),
hasSettingsPermission(request, "privacy.subprocessors.read", tenantId),
hasSettingsPermission(request, "privacy.tenant_deletion", tenantId),
]);
const chatEnabled = canReadChat && (await tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: CHAT_MODULE_KEY }));
const tabs: SettingsHubTabInput[] = [];
if (canViewAudit) {
// The hub index href is a prefix of every sibling — without this the log
// tab would stay lit everywhere.
tabs.push({ id: "log", labelKey: "settings.hubs.compliance.tabs.log", href: UrlUtils.currentTenantUrl(params, "settings/compliance"), exact: true });
tabs.push({ id: "auditExport", labelKey: "settings.hubs.compliance.tabs.auditExport", href: UrlUtils.currentTenantUrl(params, "settings/compliance/audit-export") });
}
if (chatEnabled) {
tabs.push({ id: "chat", labelKey: "settings.hubs.compliance.tabs.chat", href: UrlUtils.currentTenantUrl(params, "settings/compliance/chat") });
}
if (canExportTenant) {
tabs.push({ id: "dataExport", labelKey: "settings.hubs.compliance.tabs.dataExport", href: UrlUtils.currentTenantUrl(params, "settings/compliance/data-export") });
}
if (canReadAvv) {
tabs.push({ id: "avv", labelKey: "settings.hubs.compliance.tabs.avv", href: UrlUtils.currentTenantUrl(params, "settings/compliance/avv") });
}
if (canReadSubprocessors) {
tabs.push({
id: "subprocessors",
labelKey: "settings.hubs.compliance.tabs.subprocessors",
href: UrlUtils.currentTenantUrl(params, "settings/compliance/subprocessors"),
});
}
if (canDeleteTenant) {
tabs.push({
id: "tenantDeletion",
labelKey: "settings.hubs.compliance.tabs.tenantDeletion",
href: UrlUtils.currentTenantUrl(params, "settings/compliance/tenant-deletion"),
});
}
if (tabs.length === 0) throw settingsHubNotFound();
const baseRedirect = settingsHubBaseRedirect(request, UrlUtils.currentTenantUrl(params, "settings/compliance"), tabs);
if (baseRedirect) throw baseRedirect;
return { title: `${t("settings.hubs.compliance.title")} | ${process.env.APP_NAME}`, tabs } satisfies LoaderData;
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function ComplianceHubRoute() {
const { tabs } = useLoaderData<LoaderData>();
const location = useLocation();
const vm = buildSettingsHubVM({
hubId: "compliance",
titleKey: "settings.hubs.compliance.title",
subtitleKey: "settings.hubs.compliance.subtitle",
tabs,
currentPath: location.pathname,
});
return (
<SettingsHubShell vm={vm} icon={<FeatherClipboardList />}>
<Outlet />
</SettingsHubShell>
);
}
@@ -3,7 +3,7 @@ import path from "node:path";
import { describe, expect, it } from "vitest";
const sourcePath = path.resolve(process.cwd(), "apps/web/app/routes/app.$tenant/settings/audit-export.tsx");
const sourcePath = path.resolve(process.cwd(), "packages/view-models/src/audit/audit-export.vm.ts");
describe("tenant audit export i18n", () => {
it("uses semantic keys for filter option labels", () => {
@@ -6,6 +6,8 @@ import { getDbClient } from "@hivegrid/db/client.server";
import { getTranslations } from "~/locale/i18next.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: vi.fn(),
@@ -23,12 +25,20 @@ vi.mock("~/utils/services/.server/urlService", () => ({
getTenantIdFromUrl: vi.fn(),
}));
vi.mock("~/utils/session.server", () => ({
getUserInfo: vi.fn(),
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
runWithRlsContext: vi.fn((_context, callback) => callback()),
}));
const params = { tenant: "acme" };
const findMany = vi.fn();
function callLoader(url: string) {
const request = new Request(url);
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/audit-export" } as LoaderFunctionArgs);
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/compliance/audit-export" } as LoaderFunctionArgs);
}
describe("tenant audit export route", () => {
@@ -38,12 +48,13 @@ describe("tenant audit export route", () => {
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user-1" } as never);
findMany.mockResolvedValue([]);
vi.mocked(getDbClient).mockReturnValue({ auditEvent: { findMany } } as never);
});
it("checks tenant audit-trail permission before returning export defaults", async () => {
const response = (await callLoader("https://app.example.test/acme/settings/audit-export")) as Response;
const response = (await callLoader("https://app.example.test/acme/settings/compliance/audit-export")) as Response;
const data = await response.json();
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
@@ -52,13 +63,14 @@ describe("tenant audit export route", () => {
expect(data).toMatchObject({
title: "translated:models.log.plural | HiveGrid",
tenantSlug: "acme",
maxRows: expect.any(Number),
// AK-SET-01: the filter defaults live in the shared AuditExportVM now.
vm: { status: "ready", data: { maxRows: expect.any(Number) } },
});
});
it("keeps CSV export tenant-scoped and permission-gated", async () => {
const response = (await callLoader(
"https://app.example.test/acme/settings/audit-export?export=csv&tenantId=other-tenant&from=2026-05-01&to=2026-05-31",
"https://app.example.test/acme/settings/compliance/audit-export?export=csv&tenantId=other-tenant&from=2026-05-01&to=2026-05-31",
)) as Response;
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
@@ -70,15 +82,26 @@ describe("tenant audit export route", () => {
}),
);
expect(JSON.stringify(findMany.mock.calls[0]?.[0])).not.toContain("other-tenant");
expect(runWithRlsContext).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: "user-1" }, expect.any(Function));
expect(response.headers.get("Content-Type")).toBe("text/csv; charset=utf-8");
expect(response.headers.get("Content-Disposition")).toContain("audit-export-tenant-1-2026-05-01_2026-05-31.csv");
});
it("drops UI all-filter sentinels before building the tenant query", async () => {
await callLoader(
"https://app.example.test/acme/settings/compliance/audit-export?export=csv&actorType=__all__&outcome=__all__&regulatoryScope=__all__",
);
expect(findMany).toHaveBeenCalledWith(
expect.objectContaining({ where: { tenantId: "tenant-1" } }),
);
});
it("rejects export reads without touching audit rows when permission is missing", async () => {
const rejection = new Response("Forbidden", { status: 403 });
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
await expect(callLoader("https://app.example.test/acme/settings/audit-export?export=csv")).rejects.toBe(rejection);
await expect(callLoader("https://app.example.test/acme/settings/compliance/audit-export?export=csv")).rejects.toBe(rejection);
expect(findMany).not.toHaveBeenCalled();
});
@@ -0,0 +1,120 @@
/**
* Phase 10 Task #67 — Tenant Compliance-Audit-Export.
*
* Per-tenant self-service variant of the admin audit-export. Identical
* filter surface but tenantId-locked: a tenant admin can only see their
* own AuditEvent rows. Used for SOC2-Type-II evidence collection by
* tenants who need to deliver their own privileged-action report.
*/
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import { getDbClient } from "@hivegrid/db/client.server";
import { loadAuditVerificationContext } from "@hivegrid/db/audit-chain-checkpoint.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getTranslations } from "~/locale/i18next.server";
import { getUserInfo } from "~/utils/session.server";
import { buildAuditExportVM, type AuditExportVM } from "@hivegrid/view-models";
import { AuditExportPage } from "~/components/screens/audit/AuditExportPage";
import {
AUDIT_EXPORT_MAX_ROWS,
buildAuditExportWhere,
computeAuditIntegritySummary,
hasAuditExportPrefixFilters,
parseAuditExportFilters,
renderAuditExportCsv,
stripAuditExportFilterSentinels,
type AuditExportRow,
} from "~/routes/admin/audit-export.helpers.server";
type LoaderData = {
title: string;
tenantSlug: string;
vm: AuditExportVM;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
const { t } = await getTranslations(request);
const userInfo = await getUserInfo(request);
const url = stripAuditExportFilterSentinels(new URL(request.url));
if (url.searchParams.get("export") === "csv") {
return streamTenantAuditExport(tenantId, userInfo.userId, url);
}
if (url.searchParams.get("export") === "pdf" || url.searchParams.get("format") === "pdf") {
return streamTenantAuditPdfExport(tenantId, userInfo.userId, url, t);
}
const today = new Date();
const fromDate = new Date(today);
fromDate.setDate(fromDate.getDate() - 30);
const data: LoaderData = {
title: `${t("models.log.plural")} | ${process.env.APP_NAME}`,
tenantSlug: params.tenant ?? "",
vm: buildAuditExportVM({
defaultFrom: fromDate.toISOString().slice(0, 10),
defaultTo: today.toISOString().slice(0, 10),
maxRows: AUDIT_EXPORT_MAX_ROWS,
}),
};
return Response.json(data);
};
async function loadTenantAuditExportRows(tenantId: string, userId: string, url: URL) {
// Force tenantId scope onto the URL filters so a request that tries to
// smuggle a different tenantId via query string is silently ignored.
const filters = { ...parseAuditExportFilters(url), tenantId };
const db = getDbClient();
return runWithRlsContext({ tenantId, userId }, async () => {
const rows = (await db.auditEvent.findMany({
where: buildAuditExportWhere(filters),
orderBy: { createdAt: "asc" },
take: AUDIT_EXPORT_MAX_ROWS,
})) as unknown as AuditExportRow[];
const verification = await loadAuditVerificationContext(db as never, rows, {
allowPartialPrefix: hasAuditExportPrefixFilters(filters),
});
return { filters, rows, verification };
});
}
async function streamTenantAuditExport(tenantId: string, userId: string, url: URL): Promise<Response> {
const { rows, verification } = await loadTenantAuditExportRows(tenantId, userId, url);
const integrity = computeAuditIntegritySummary(rows, verification);
const csv = renderAuditExportCsv(rows, integrity);
return new Response(csv, {
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": `attachment; filename="audit-export-${tenantId}-${url.searchParams.get("from") ?? "all"}_${url.searchParams.get("to") ?? "all"}.csv"`,
"X-Audit-Chain-Status": integrity.ok ? "ok" : "broken",
},
});
}
async function streamTenantAuditPdfExport(
tenantId: string,
userId: string,
url: URL,
t: Awaited<ReturnType<typeof getTranslations>>["t"]
): Promise<Response> {
const { buildAuditPdfLabels, renderAuditExportPdfResponse } = await import("~/utils/audit/pdfRender");
const { filters, rows, verification } = await loadTenantAuditExportRows(tenantId, userId, url);
const integrity = computeAuditIntegritySummary(rows, verification);
return renderAuditExportPdfResponse(
{
tenantId,
filters,
integrity,
rows,
labels: buildAuditPdfLabels(t),
},
{ filenamePrefix: "audit-export" }
);
}
export default function TenantAuditExportRoute() {
const data = useLoaderData<LoaderData>();
return <AuditExportPage vm={data.vm} result={null} scope="tenant" tenantSlug={data.tenantSlug} embedded />;
}
@@ -0,0 +1,144 @@
// AK-P21 — AVV (data processing agreement) page. Gate: privacy.avv.read;
// accepting additionally requires privacy.avv.accept. The current contract
// version is configuration (AVV_CURRENT_VERSION, default 1.0); the PDF
// download stays interim-disabled until an AVV source PDF ships (tracked in
// the ticket doc as open follow-up).
import { randomUUID } from "node:crypto";
import { useEffect } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useActionData, useLoaderData, useNavigation, useParams, useRevalidator, useSubmit } from "react-router";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { toast } from "sonner";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { acceptAvv, listAvvAcceptances } from "@hivegrid/db/privacy-gdpr.server";
import { buildAvvVM, type AvvVM } from "@hivegrid/view-models";
import { AvvPage } from "~/components/screens/privacy/AvvPage";
import { getTranslations } from "~/locale/i18next.server";
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
import { requireAuth } from "~/utils/loaders.middleware";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { useRootData } from "~/utils/data/useRootData";
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
const CURRENT_AVV_VERSION = process.env.AVV_CURRENT_VERSION?.trim() || "1.0";
type LoaderData = {
title: string;
vm: AvvVM;
};
type ActionData = { ok: true; message: string } | { ok: false; error: string };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "privacy.avv.read", tenantId);
const acceptances = await listAvvAcceptances({ tenantId });
const vm = buildAvvVM({
currentVersion: CURRENT_AVV_VERSION,
// No AVV source PDF ships in the repo yet — download stays interim-disabled.
pdfAvailable: false,
acceptances: acceptances.map((acceptance) => ({
id: acceptance.id,
avvVersion: acceptance.avvVersion,
signerName: acceptance.signerName,
signerRole: acceptance.signerRole,
pdfFileId: acceptance.pdfFileId,
createdAt: acceptance.createdAt.toISOString(),
})),
});
const data: LoaderData = { title: `${t("settings.privacy.avv.title")} | ${process.env.APP_NAME}`, vm };
return Response.json(data);
};
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
export const action = async ({ request, params }: ActionFunctionArgs) => {
await requireAuth({ request, params });
await validateCSRFToken(request);
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "privacy.avv.accept", tenantId);
const userInfo = await getUserInfo(request);
const form = await request.formData();
const intent = String(form.get("intent") ?? "");
const signerName = String(form.get("signerName") ?? "").trim();
const signerRole = String(form.get("signerRole") ?? "").trim();
if (intent !== "accept" || !signerName) {
return Response.json({ ok: false, error: t("settings.privacy.errors.unknownIntent", { intent }) } satisfies ActionData, { status: 400 });
}
const acceptance = await acceptAvv({
tenantId,
acceptedByUserId: userInfo.userId,
avvVersion: CURRENT_AVV_VERSION,
signerName,
signerRole: signerRole || null,
acceptedIp: getTrustedClientIpOrNull(request),
acceptedUserAgent: request.headers.get("user-agent"),
});
await createAuditEvent({
tenantId,
actorId: userInfo.userId,
actorType: "user",
action: "ACCEPT_AVV",
targetType: "Tenant",
targetId: tenantId,
regulatoryScope: ["gdpr"],
dataSensitivity: "pii",
outcome: "success",
metadata: { requestId: randomUUID(), avvVersion: CURRENT_AVV_VERSION, acceptanceId: acceptance.id, source: "privacy-avv-page" },
});
return Response.json({ ok: true, message: t("settings.privacy.avv.messages.accepted", { version: CURRENT_AVV_VERSION }) } satisfies ActionData);
};
export default function PrivacyAvvRoute() {
// AK-P21 DoD B9 — breadcrumb target injected into the screen so the screen
// itself stays free of router data access.
const routeParams = useParams();
const hubHref = appPath({ tenantSlug: routeParams.tenant ?? "", path: "settings/compliance", mode: "host-aware" });
const { vm } = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const submit = useSubmit();
const revalidator = useRevalidator();
const navigation = useNavigation();
const { csrf } = useRootData();
useEffect(() => {
if (!actionData) return;
if (actionData.ok) toast.success(actionData.message);
}, [actionData]);
return (
<AvvPage
embedded
hubHref={hubHref}
vm={vm}
submitting={navigation.state === "submitting"}
errorKey={actionData && !actionData.ok ? actionData.error : null}
actions={{
onAccept(fields) {
const form = new FormData();
form.set("intent", "accept");
form.set("csrf", csrf ?? "");
form.set("signerName", fields.signerName);
form.set("signerRole", fields.signerRole);
void submit(form, { method: "post" });
},
onRetry() {
revalidator.revalidate();
},
}}
/>
);
}
@@ -0,0 +1,116 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadChatContext: vi.fn(),
readSession: vi.fn(),
loadChannel: vi.fn(),
archiveChannel: vi.fn(),
setMemberRole: vi.fn(),
removeMember: vi.fn(),
validateCsrf: vi.fn(),
}));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
vi.mock("~/modules/chat/routes/chatAccess.server", async (importOriginal) => {
const actual = await importOriginal<typeof import("~/modules/chat/routes/chatAccess.server")>();
return { ...actual, loadChatContext: mocks.loadChatContext };
});
vi.mock("~/modules/chat/services/chatAuditSession.server", () => ({ readChatAuditSession: mocks.readSession }));
vi.mock("~/modules/chat/services/ChatAuditService.server", () => ({
loadChatAuditChannel: mocks.loadChannel,
archiveChatAuditChannel: mocks.archiveChannel,
setChatAuditMemberRole: mocks.setMemberRole,
removeChatAuditMember: mocks.removeMember,
}));
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCsrf }));
vi.mock("~/components/screens/chat/ChatAuditAdministrationPanel", () => ({ ChatAuditAdministrationPanel: () => null }));
vi.mock("~/components/screens/chat/ChatChannelDetailPage", () => ({ ChatChannelDetailPage: () => null }));
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
import { action, loader } from "./chat.$id";
const context = {
tenantId: "tenant-1",
userId: "admin-1",
tenantUserId: "tenant-user-1",
permissions: ["chat.read_all_channels"],
hasModule: true as const,
};
const session = {
id: "session-1",
tenantId: "tenant-1",
userId: "admin-1",
reason: "Supportfall",
issuedAt: 1,
expiresAt: 2,
};
describe("AK-P15b chat audit detail route", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.loadChatContext.mockResolvedValue(context);
mocks.readSession.mockResolvedValue(session);
mocks.loadChannel.mockResolvedValue({
vm: { status: "ready", data: { header: { title: "Anna · Ben" } } },
administrationVm: { status: "ready", data: { channel: { id: "dm-1" }, canAdminister: true, members: [] } },
authors: [],
});
});
it("fails closed with 404 when the reason session is absent or expired", async () => {
mocks.readSession.mockResolvedValueOnce(null);
await expect(loader(args())).rejects.toMatchObject({ status: 404 });
expect(mocks.loadChannel).not.toHaveBeenCalled();
});
it("opens the channel through the audited read-only service", async () => {
const response = await loader(args());
expect(mocks.loadChannel).toHaveBeenCalledWith(
expect.objectContaining({
context,
tenantSlug: "demo",
chatId: "dm-1",
session,
requestId: expect.any(String),
})
);
expect(response.status).toBe(200);
});
it("requires the active reason session and CSRF before force-member and cleanup actions", async () => {
const roleResponse = await action(args(post({ intent: "set-role", memberUserId: "member-a", roleInChat: "admin" })));
expect(mocks.validateCsrf).toHaveBeenCalledOnce();
expect(mocks.setMemberRole).toHaveBeenCalledWith(
expect.objectContaining({ context, chatId: "dm-1", memberUserId: "member-a", roleInChat: "admin", session })
);
expect(roleResponse.status).toBe(302);
await action(args(post({ intent: "remove-member", memberUserId: "member-a" })));
expect(mocks.removeMember).toHaveBeenCalledWith(expect.objectContaining({ chatId: "dm-1", memberUserId: "member-a", session }));
await action(args(post({ intent: "archive" })));
expect(mocks.archiveChannel).toHaveBeenCalledWith(expect.objectContaining({ chatId: "dm-1", session }));
mocks.readSession.mockResolvedValueOnce(null);
await expect(
action(args(post({ intent: "archive" })))
).rejects.toMatchObject({ status: 404 });
});
});
function args(request = new Request("http://app.localhost/demo/settings/compliance/chat/dm-1")) {
return {
request,
params: { tenant: "demo", id: "dm-1" },
context: {},
unstable_pattern: "app.$tenant/settings/compliance/chat.$id",
};
}
function post(values: Record<string, string>): Request {
return new Request("http://app.localhost/demo/settings/compliance/chat/dm-1", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(values),
});
}
@@ -0,0 +1,170 @@
import {
type ActionFunctionArgs,
type LoaderFunctionArgs,
type MetaFunction,
redirect,
useActionData,
useLoaderData,
useNavigate,
useNavigation,
useSubmit,
} from "react-router";
import type { ChatAuditAdministrationVM, ChatChannelDetailVM, ChatResolvedAuthorVM } from "@hivegrid/view-models";
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { ChatAuditAdministrationPanel } from "~/components/screens/chat/ChatAuditAdministrationPanel";
import { ChatChannelDetailPage } from "~/components/screens/chat/ChatChannelDetailPage";
import ServerError from "~/components/ui/errors/ServerError";
import { getTranslations } from "~/locale/i18next.server";
import { loadChatContext, requireChatPermission } from "~/modules/chat/routes/chatAccess.server";
import { CHAT_MODULE_KEY, chatAuditPath } from "~/modules/chat/routes/chatRoutePaths";
import { archiveChatAuditChannel, loadChatAuditChannel, removeChatAuditMember, setChatAuditMemberRole } from "~/modules/chat/services/ChatAuditService.server";
import { readChatAuditSession } from "~/modules/chat/services/chatAuditSession.server";
import { useRootData } from "~/utils/data/useRootData";
import { validateCSRFToken } from "~/utils/session.server";
type LoaderData = Readonly<{
title: string;
tenantSlug: string;
chatId: string;
vm: ChatChannelDetailVM;
administrationVm: ChatAuditAdministrationVM;
authors: readonly ChatResolvedAuthorVM[];
}>;
type ActionData = Readonly<{ errorKey: string }>;
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
const [{ t }, loadedContext] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]);
const context = requireChatPermission(loadedContext, CHAT_PERMISSIONS.readAllChannels);
const tenantSlug = params.tenant ?? "";
const chatId = params.id?.trim() ?? "";
if (!chatId) throw new CatalogError(foundationErrors.notFound);
const session = await readChatAuditSession({ request, tenantId: context.tenantId, userId: context.userId });
if (!session) throw new CatalogError(foundationErrors.notFound, { chat: "audit-session-required" });
const beforeMessageCursor = new URL(request.url).searchParams.get("before");
const result = await loadChatAuditChannel({
context,
tenantSlug,
chatId,
session,
requestId: crypto.randomUUID(),
...(beforeMessageCursor ? { beforeMessageCursor } : {}),
labels: {
directMessage: t("chat.channel.fallback.directMessage"),
unnamedGroup: t("chat.channel.fallback.group"),
unnamedProject: t("chat.channel.fallback.project"),
unknownUser: t("chat.participant.unknown"),
unknownMention: t("chat.mention.unknown"),
},
});
const channelTitle = result.vm.status === "ready" ? result.vm.data.header.title : t("chat.titleFallback");
return Response.json({
title: `${channelTitle} | ${process.env.APP_NAME}`,
tenantSlug,
chatId,
...result,
} satisfies LoaderData);
}
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
const loadedContext = await loadChatContext({ request, params });
const context = requireChatPermission(loadedContext, CHAT_PERMISSIONS.readAllChannels);
const tenantSlug = params.tenant ?? "";
const chatId = params.id?.trim() ?? "";
if (!chatId) throw new CatalogError(foundationErrors.notFound);
const session = await readChatAuditSession({ request, tenantId: context.tenantId, userId: context.userId });
if (!session) throw new CatalogError(foundationErrors.notFound, { chat: "audit-session-required" });
const formData = await request.formData();
await validateCSRFToken(request, { formData });
const intent = formData.get("intent")?.toString();
const requestId = crypto.randomUUID();
let messageKey: string;
if (intent === "archive") {
await archiveChatAuditChannel({ context, chatId, session, requestId });
messageKey = "chat.audit.toast.channelArchived";
} else if (intent === "set-role") {
const memberUserId = formData.get("memberUserId")?.toString().trim() ?? "";
const roleInChat = formData.get("roleInChat")?.toString();
if (!memberUserId || (roleInChat !== "admin" && roleInChat !== "member")) return invalidInput();
await setChatAuditMemberRole({ context, chatId, memberUserId, roleInChat, session, requestId });
messageKey = "chat.audit.toast.memberRoleChanged";
} else if (intent === "remove-member") {
const memberUserId = formData.get("memberUserId")?.toString().trim() ?? "";
if (!memberUserId) return invalidInput();
await removeChatAuditMember({ context, chatId, memberUserId, session, requestId });
messageKey = "chat.audit.toast.memberRemoved";
} else {
return invalidInput();
}
return redirect(`${chatAuditPath(tenantSlug)}/${encodeURIComponent(chatId)}?toast=${encodeURIComponent(messageKey)}`);
}
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
export default function ChatAuditChannelRoute(): React.JSX.Element {
const { tenantSlug, chatId, vm, administrationVm } = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const navigate = useNavigate();
const navigation = useNavigation();
const submit = useSubmit();
const { csrf } = useRootData();
const noOp = () => undefined;
const busy = navigation.state === "submitting";
function submitAction(intent: "archive" | "set-role" | "remove-member", values?: Record<string, string>): void {
const formData = new FormData();
formData.set("csrf", csrf ?? "");
formData.set("intent", intent);
for (const [key, value] of Object.entries(values ?? {})) formData.set(key, value);
void submit(formData, { method: "post" });
}
return (
<div className="flex w-full flex-col">
<ChatAuditAdministrationPanel
vm={administrationVm}
busy={busy}
actionErrorKey={actionData?.errorKey}
actions={{
onArchive: () => submitAction("archive"),
onChangeMemberRole: (memberUserId, roleInChat) => submitAction("set-role", { memberUserId, roleInChat }),
onRemoveMember: (memberUserId) => submitAction("remove-member", { memberUserId }),
}}
/>
<ChatChannelDetailPage
vm={vm}
draft=""
sending={false}
actions={{
onBack: () => void navigate(chatAuditPath(tenantSlug)),
onOpenSettings: noOp,
onDraftChange: noOp,
onSend: noOp,
onRetryMessage: noOp,
onDiscardMessage: noOp,
onMessageVisibilityChange: noOp,
onRetryConnection: noOp,
onLoadOlder: (cursor) => void navigate(`${chatAuditPath(tenantSlug)}/${encodeURIComponent(chatId)}?before=${encodeURIComponent(cursor)}`),
}}
/>
</div>
);
}
function invalidInput(): Response {
return Response.json({ errorKey: "chat.errors.invalidInput" } satisfies ActionData, { status: 400 });
}
export function ErrorBoundary(): React.JSX.Element {
return <ServerError />;
}
export const handle = {
moduleKey: CHAT_MODULE_KEY,
breadcrumbKey: "chat.audit.channelTitle",
};
@@ -0,0 +1,128 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadChatContext: vi.fn(),
loadOverview: vi.fn(),
startSession: vi.fn(),
archiveChannel: vi.fn(),
readSession: vi.fn(),
beginSession: vi.fn(),
clearSession: vi.fn(),
validateCSRF: vi.fn(),
}));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
vi.mock("~/modules/chat/routes/chatAccess.server", async (importOriginal) => {
const actual = await importOriginal<typeof import("~/modules/chat/routes/chatAccess.server")>();
return { ...actual, loadChatContext: mocks.loadChatContext };
});
vi.mock("~/modules/chat/services/ChatAuditService.server", () => ({
loadChatAuditOverview: mocks.loadOverview,
startChatAuditSession: mocks.startSession,
archiveChatAuditChannel: mocks.archiveChannel,
}));
vi.mock("~/modules/chat/services/chatAuditSession.server", () => ({
readChatAuditSession: mocks.readSession,
beginChatAuditSession: mocks.beginSession,
clearChatAuditSession: mocks.clearSession,
normalizeChatAuditReason: (value: unknown) => (typeof value === "string" && value.trim() ? value.trim() : null),
}));
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCSRF }));
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf-1" }) }));
vi.mock("~/components/screens/chat/ChatAuditOverviewPage", () => ({ ChatAuditOverviewPage: () => null }));
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
import { action, loader } from "./chat";
const context = {
tenantId: "tenant-1",
userId: "admin-1",
tenantUserId: "tenant-user-1",
permissions: ["chat.read_all_channels"],
hasModule: true as const,
};
const auditSession = {
id: "session-1",
tenantId: "tenant-1",
userId: "admin-1",
reason: "Kundenreklamation prüfen",
issuedAt: Date.parse("2026-07-16T10:00:00.000Z"),
expiresAt: Date.parse("2026-07-16T10:15:00.000Z"),
};
describe("AK-P15b chat audit overview route", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.loadChatContext.mockResolvedValue(context);
mocks.readSession.mockResolvedValue(null);
mocks.loadOverview.mockResolvedValue({ status: "ready", data: { session: null, channels: [] } });
mocks.beginSession.mockResolvedValue({ session: auditSession, cookie: "hivegrid_chat_audit=signed; Path=/; HttpOnly" });
mocks.clearSession.mockResolvedValue("hivegrid_chat_audit=; Max-Age=0");
});
it("returns a 404-equivalent CatalogError without read_all_channels", async () => {
mocks.loadChatContext.mockResolvedValueOnce({ ...context, permissions: ["chat.admin"] });
await expect(loader(args(new Request("http://app.localhost/demo/settings/compliance/chat")))).rejects.toMatchObject({ status: 404 });
expect(mocks.loadOverview).not.toHaveBeenCalled();
});
it("does not expose channels before a signed reason session exists", async () => {
const response = await loader(args(new Request("http://app.localhost/demo/settings/compliance/chat")));
expect(mocks.readSession).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant-1", userId: "admin-1" }));
expect(mocks.loadOverview).toHaveBeenCalledWith(expect.objectContaining({ context, session: null }));
expect(response.status).toBe(200);
});
it("rejects a missing justification after CSRF validation", async () => {
const request = post({ intent: "start", reason: " ", csrf: "csrf-1" });
const response = await action(args(request));
expect(mocks.validateCSRF).toHaveBeenCalledTimes(1);
expect(mocks.validateCSRF.mock.calls[0]?.[0]).toBe(request);
expect(mocks.validateCSRF.mock.calls[0]?.[1]).toHaveProperty("formData");
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({ errorKey: "chat.audit.errors.reasonRequired" });
expect(mocks.beginSession).not.toHaveBeenCalled();
});
it("audits the reason before issuing the short-lived session cookie", async () => {
const response = await action(args(post({ intent: "start", reason: "Kundenreklamation prüfen", csrf: "csrf-1" })));
expect(mocks.beginSession).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: "admin-1", reason: "Kundenreklamation prüfen" });
expect(mocks.startSession).toHaveBeenCalledWith({ context, session: auditSession, requestId: expect.any(String) });
expect(response.status).toBe(302);
expect(response.headers.get("set-cookie")).toContain("hivegrid_chat_audit=signed");
});
it("requires the signed reason session before an overview cleanup archive", async () => {
const adminContext = { ...context, permissions: ["chat.read_own_channels", "chat.read_all_channels", "chat.admin"] };
mocks.loadChatContext.mockResolvedValue(adminContext);
mocks.readSession.mockResolvedValue(auditSession);
const response = await action(args(post({ intent: "archive", chatId: "group-a", csrf: "csrf-1" })));
expect(mocks.archiveChannel).toHaveBeenCalledWith({
context: adminContext,
chatId: "group-a",
session: auditSession,
requestId: expect.any(String),
});
expect(response.status).toBe(302);
mocks.readSession.mockResolvedValueOnce(null);
await expect(action(args(post({ intent: "archive", chatId: "group-a", csrf: "csrf-1" })))).rejects.toMatchObject({ status: 404 });
});
});
function args(request: Request) {
return {
request,
params: { tenant: "demo" },
context: {},
unstable_pattern: "app.$tenant/settings/compliance/chat",
};
}
function post(values: Record<string, string>): Request {
return new Request("http://app.localhost/demo/settings/compliance/chat", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(values),
});
}
@@ -0,0 +1,130 @@
import {
type ActionFunctionArgs,
type LoaderFunctionArgs,
type MetaFunction,
redirect,
useActionData,
useLoaderData,
useNavigate,
useNavigation,
useSubmit,
} from "react-router";
import type { ChatAuditOverviewVM } from "@hivegrid/view-models";
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { ChatAuditOverviewPage } from "~/components/screens/chat/ChatAuditOverviewPage";
import ServerError from "~/components/ui/errors/ServerError";
import { getTranslations } from "~/locale/i18next.server";
import { loadChatContext, requireChatPermission } from "~/modules/chat/routes/chatAccess.server";
import { CHAT_MODULE_KEY, chatAuditPath } from "~/modules/chat/routes/chatRoutePaths";
import { archiveChatAuditChannel, loadChatAuditOverview, startChatAuditSession } from "~/modules/chat/services/ChatAuditService.server";
import { beginChatAuditSession, clearChatAuditSession, normalizeChatAuditReason, readChatAuditSession } from "~/modules/chat/services/chatAuditSession.server";
import { useRootData } from "~/utils/data/useRootData";
import { validateCSRFToken } from "~/utils/session.server";
type LoaderData = Readonly<{
title: string;
tenantSlug: string;
vm: ChatAuditOverviewVM;
}>;
type ActionData = Readonly<{ errorKey: string }>;
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
const [{ t }, loadedContext] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]);
const context = requireChatPermission(loadedContext, CHAT_PERMISSIONS.readAllChannels);
const tenantSlug = params.tenant ?? "";
const session = await readChatAuditSession({ request, tenantId: context.tenantId, userId: context.userId });
const vm = await loadChatAuditOverview({
context,
tenantSlug,
session,
requestId: crypto.randomUUID(),
labels: {
directMessage: t("chat.channel.fallback.directMessage"),
unnamedGroup: t("chat.channel.fallback.group"),
unnamedProject: t("chat.channel.fallback.project"),
},
});
return Response.json({ title: `${t("chat.audit.title")} | ${process.env.APP_NAME}`, tenantSlug, vm } satisfies LoaderData);
}
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
const loadedContext = await loadChatContext({ request, params });
const context = requireChatPermission(loadedContext, CHAT_PERMISSIONS.readAllChannels);
const tenantSlug = params.tenant ?? "";
const formData = await request.formData();
await validateCSRFToken(request, { formData });
const intent = formData.get("intent")?.toString();
if (intent === "end") {
return redirect(`${chatAuditPath(tenantSlug)}?toast=${encodeURIComponent("chat.audit.toast.sessionEnded")}`, {
headers: { "Set-Cookie": await clearChatAuditSession() },
});
}
if (intent === "archive") {
const session = await readChatAuditSession({ request, tenantId: context.tenantId, userId: context.userId });
if (!session) throw new CatalogError(foundationErrors.notFound, { chat: "audit-session-required" });
const chatId = formData.get("chatId")?.toString().trim() ?? "";
if (!chatId) return invalidInput("chat.errors.invalidInput");
await archiveChatAuditChannel({ context, chatId, session, requestId: crypto.randomUUID() });
return redirect(`${chatAuditPath(tenantSlug)}?toast=${encodeURIComponent("chat.audit.toast.channelArchived")}`);
}
if (intent !== "start") return invalidInput("chat.errors.invalidInput");
const reason = normalizeChatAuditReason(formData.get("reason"));
if (!reason) return invalidInput("chat.audit.errors.reasonRequired");
const issued = await beginChatAuditSession({ tenantId: context.tenantId, userId: context.userId, reason });
await startChatAuditSession({ context, session: issued.session, requestId: crypto.randomUUID() });
return redirect(`${chatAuditPath(tenantSlug)}?toast=${encodeURIComponent("chat.audit.toast.sessionStarted")}`, { headers: { "Set-Cookie": issued.cookie } });
}
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
export default function ChatAuditOverviewRoute(): React.JSX.Element {
const { vm } = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const navigation = useNavigation();
const submit = useSubmit();
const navigate = useNavigate();
const { csrf } = useRootData();
const busy = navigation.state === "submitting";
function submitIntent(intent: "start" | "end" | "archive", options?: { reason?: string; chatId?: string }): void {
const formData = new FormData();
formData.set("csrf", csrf ?? "");
formData.set("intent", intent);
if (options?.reason !== undefined) formData.set("reason", options.reason);
if (options?.chatId !== undefined) formData.set("chatId", options.chatId);
void submit(formData, { method: "post" });
}
return (
<ChatAuditOverviewPage
embedded
vm={vm}
busy={busy}
actionErrorKey={actionData?.errorKey}
actions={{
onStartSession: (reason) => submitIntent("start", { reason }),
onEndSession: () => submitIntent("end"),
onOpenChannel: (href) => void navigate(href),
onArchiveChannel: (chatId) => submitIntent("archive", { chatId }),
}}
/>
);
}
function invalidInput(errorKey: string): Response {
return Response.json({ errorKey } satisfies ActionData, { status: 400 });
}
export function ErrorBoundary(): React.JSX.Element {
return <ServerError />;
}
export const handle = {
moduleKey: CHAT_MODULE_KEY,
breadcrumbKey: "chat.audit.title",
};
@@ -0,0 +1,198 @@
// AK-P21 — GDPR export job list (tenant admins see all tenant jobs and may
// start the tenant-full export; every user may start their own self export
// within the 3/24h rate limit). The download button targets the signed-URL
// resource route privacy.export.$jobId.download.
import { randomUUID } from "node:crypto";
import { useEffect } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useActionData, useLoaderData, useLocation, useNavigation, useParams, useRevalidator, useSubmit } from "react-router";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { toast } from "sonner";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { getDbClient } from "@hivegrid/db/client.server";
import {
createGdprExportJob,
GDPR_EXPORT_URL_TTL_HOURS,
GDPR_USER_SELF_EXPORT_LIMIT_PER_24H,
listGdprExportJobs,
} from "@hivegrid/db/privacy-gdpr.server";
import { buildGdprExportJobsVM, type GdprExportJobsVM } from "@hivegrid/view-models";
import { GdprExportJobsPage } from "~/components/screens/privacy/GdprExportJobsPage";
import { getTranslations } from "~/locale/i18next.server";
import { requireAuth } from "~/utils/loaders.middleware";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { enqueueGdprExport } from "~/utils/privacy/gdprExportQueue.server";
import { useRootData } from "~/utils/data/useRootData";
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
import type { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
type LoaderData = {
title: string;
vm: GdprExportJobsVM;
};
type ActionData = { ok: true; message: string } | { ok: false; error: string };
async function hasPermission(request: Request, permission: DefaultPermission, tenantId: string): Promise<boolean> {
try {
await verifyUserHasPermission(request, permission, tenantId);
return true;
} catch (error) {
if (error instanceof Response && ((error.status >= 300 && error.status < 400) || error.status === 403 || error.status === 404)) return false;
throw error;
}
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
const userInfo = await getUserInfo(request);
const db = getDbClient();
const tenantExportAllowed = await hasPermission(request, "privacy.tenant_export", tenantId);
const now = new Date();
const [jobs, userSelfCountLast24h, tenantFullActiveCount] = await Promise.all([
// Tenant admins see the whole tenant register; everyone else only their own jobs.
listGdprExportJobs(tenantExportAllowed ? { tenantId, take: 50 } : { tenantId, requestedByUserId: userInfo.userId, take: 50 }),
db.gdprExportJob.count({
where: { tenantId, scope: "user_self", targetUserId: userInfo.userId, createdAt: { gte: new Date(now.getTime() - 24 * 60 * 60 * 1_000) } },
}),
db.gdprExportJob.count({ where: { tenantId, scope: "tenant_full", status: { in: ["queued", "processing"] } } }),
]);
const vm = buildGdprExportJobsVM({
now: now.toISOString(),
jobs: jobs.map((job) => ({
id: job.id,
scope: job.scope,
status: job.status,
progressPercent: job.progressPercent,
resultSizeBytes: job.resultSizeBytes,
resultExpiresAt: job.resultExpiresAt ? job.resultExpiresAt.toISOString() : null,
downloadCount: job.downloadCount,
createdAt: job.createdAt.toISOString(),
})),
userSelfCountLast24h,
tenantFullActive: tenantFullActiveCount > 0,
tenantExportAllowed,
userSelfLimitPer24h: GDPR_USER_SELF_EXPORT_LIMIT_PER_24H,
downloadTtlHours: GDPR_EXPORT_URL_TTL_HOURS,
});
const data: LoaderData = { title: `${t("settings.privacy.exportJobs.title")} | ${process.env.APP_NAME}`, vm };
return Response.json(data);
};
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
export const action = async ({ request, params }: ActionFunctionArgs) => {
await requireAuth({ request, params });
await validateCSRFToken(request);
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
const userInfo = await getUserInfo(request);
const form = await request.formData();
const intent = String(form.get("intent") ?? "");
const scope = String(form.get("scope") ?? "");
if (intent !== "start" || (scope !== "user_self" && scope !== "tenant_full")) {
return Response.json({ ok: false, error: t("settings.privacy.errors.unknownIntent", { intent }) } satisfies ActionData, { status: 400 });
}
if (scope === "tenant_full") {
await verifyUserHasPermission(request, "privacy.tenant_export", tenantId);
}
const requestId = randomUUID();
try {
const exportJob = await createGdprExportJob({
tenantId,
requestedByUserId: userInfo.userId,
targetUserId: scope === "user_self" ? userInfo.userId : null,
scope,
});
const enqueueResult = await enqueueGdprExport({
exportJobId: exportJob.id,
tenantId,
requestedByUserId: userInfo.userId,
targetUserId: scope === "user_self" ? userInfo.userId : null,
scope,
requestId,
});
await createAuditEvent({
tenantId,
actorId: userInfo.userId,
actorType: "user",
action: scope === "tenant_full" ? "REQUEST_TENANT_DATA_EXPORT" : "REQUEST_PERSONAL_DATA_EXPORT",
targetType: scope === "tenant_full" ? "Tenant" : "User",
targetId: scope === "tenant_full" ? tenantId : userInfo.userId,
regulatoryScope: ["gdpr"],
dataSensitivity: "pii",
outcome: "success",
metadata: { requestId, intent: "start", source: "privacy-export-page", scope, gdprExportJobId: exportJob.id, enqueueResult },
});
return Response.json({ ok: true, message: t("settings.privacy.messages.exportRequested") } satisfies ActionData);
} catch (error) {
const message = error instanceof Error ? error.message : "";
if (message.includes("limit reached")) {
return Response.json(
{ ok: false, error: t("settings.privacy.exportJobs.rateLimit.description", { limit: GDPR_USER_SELF_EXPORT_LIMIT_PER_24H }) } satisfies ActionData,
{ status: 429 }
);
}
if (message.includes("already active")) {
return Response.json({ ok: false, error: t("settings.privacy.exportJobs.tenantActive.description") } satisfies ActionData, { status: 409 });
}
throw error;
}
};
export default function PrivacyExportRoute() {
// AK-P21 DoD B9 — breadcrumb target injected into the screen so the screen
// itself stays free of router data access.
const routeParams = useParams();
const hubHref = appPath({ tenantSlug: routeParams.tenant ?? "", path: "settings/compliance", mode: "host-aware" });
const { vm } = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const submit = useSubmit();
const revalidator = useRevalidator();
const navigation = useNavigation();
const location = useLocation();
const { csrf } = useRootData();
useEffect(() => {
if (!actionData) return;
if (actionData.ok) toast.success(actionData.message);
else toast.error(actionData.error);
}, [actionData]);
return (
<GdprExportJobsPage
embedded
hubHref={hubHref}
vm={vm}
submitting={navigation.state === "submitting"}
actions={{
onStart(scope) {
const form = new FormData();
form.set("intent", "start");
form.set("scope", scope);
form.set("csrf", csrf ?? "");
void submit(form, { method: "post" });
},
onDownload(jobId) {
window.location.assign(`${location.pathname.replace(/\/$/, "")}/${jobId}/download`);
},
onRetry() {
revalidator.revalidate();
},
}}
/>
);
}
@@ -0,0 +1,69 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { LoaderFunctionArgs } from "react-router";
import { loader } from "../logs/events-export";
import { getEvents, serializeEventsCsv } from "~/modules/events/db/events.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
vi.mock("~/modules/events/db/events.db.server", () => ({
getEvents: vi.fn(),
serializeEventsCsv: vi.fn(),
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
verifyUserHasPermission: vi.fn(),
}));
vi.mock("~/utils/services/.server/urlService", () => ({
getTenantIdFromUrl: vi.fn(),
}));
const params = { tenant: "acme" };
const events = [{ id: "event-1", name: "account.created" }];
function callLoader(url: string) {
const request = new Request(url);
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/logs/events-export" } as LoaderFunctionArgs);
}
describe("tenant settings events CSV export route", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
vi.mocked(getEvents).mockResolvedValue({ items: events, pagination: { page: 1, pageSize: 500, totalItems: 1, totalPages: 1 } } as never);
vi.mocked(serializeEventsCsv).mockReturnValue("csv-body\n");
});
it("exports CSV with the same tenant filters and a capped export window", async () => {
const response = await callLoader("https://app.example.test/acme/settings/logs/events-export?q=account&name=account.created&page=9&pageSize=5");
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getEvents).mock.invocationCallOrder[0]);
expect(getEvents).toHaveBeenCalledWith(
{
current: { page: 1, pageSize: 500 },
filters: expect.objectContaining({
query: "account",
properties: expect.arrayContaining([expect.objectContaining({ name: "name", value: "account.created" })]),
}),
},
"tenant-1",
);
expect(serializeEventsCsv).toHaveBeenCalledWith(events);
expect(response.headers.get("Content-Type")).toBe("text/csv; charset=utf-8");
expect(response.headers.get("Content-Disposition")).toBe('attachment; filename="tenant-events.csv"');
expect(await response.text()).toBe("csv-body\n");
});
it("rejects CSV reads without permission before helper calls", async () => {
const rejection = new Response("Forbidden", { status: 403 });
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
await expect(callLoader("https://app.example.test/acme/settings/logs/events-export")).rejects.toBe(rejection);
expect(getEvents).not.toHaveBeenCalled();
expect(serializeEventsCsv).not.toHaveBeenCalled();
});
});
@@ -49,8 +49,8 @@ const event = {
};
function callLoader(routeParams = params) {
const request = new Request("https://app.example.test/acme/settings/logs/events/event-1");
return loader({ request, params: routeParams, context: {}, unstable_pattern: "app.$tenant/settings/logs/events.$id" } as LoaderFunctionArgs);
const request = new Request("https://app.example.test/acme/settings/compliance/events/event-1");
return loader({ request, params: routeParams, context: {}, unstable_pattern: "app.$tenant/settings/compliance/events.$id" } as LoaderFunctionArgs);
}
describe("tenant settings event detail route", () => {
@@ -96,7 +96,7 @@ describe("tenant settings event detail route", () => {
await callLoader();
} catch (error) {
expect(error).toBeInstanceOf(Response);
expect((error as Response).headers.get("Location")).toBe("/acme/settings/logs/events");
expect((error as Response).headers.get("Location")).toBe("/acme/settings/compliance/events");
}
});
@@ -0,0 +1,50 @@
import { LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
import { useParams } from "react-router";
import { useTranslation } from "react-i18next";
import EventDetails from "~/modules/events/components/EventDetails";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import UrlUtils from "~/utils/app/UrlUtils";
import { EventWithDetails, getEvent } from "~/modules/events/db/events.db.server";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import EventUtils from "~/modules/events/utils/EventUtils";
type LoaderData = {
item: EventWithDetails;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
const item = await getEvent(params.id ?? "", tenantId);
if (!item) {
throw redirect(UrlUtils.currentTenantUrl(params, "settings/compliance/events"));
}
const data: LoaderData = {
item,
};
return data;
};
export default function AppEventDetailsRoute() {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const params = useParams();
return (
<EditPageLayout
title={t("models.event.object")}
withHome={false}
menu={[
{
title: t("models.event.plural"),
routePath: UrlUtils.currentTenantUrl(params, "settings/compliance/events"),
},
{
title: EventUtils.parseName(data.item.name, t),
},
]}
>
<EventDetails item={data.item} />
</EditPageLayout>
);
}
@@ -35,6 +35,8 @@ vi.mock("~/modules/events/db/events.db.server", () => ({
getEvents: vi.fn(),
}));
vi.mock("~/components/activity/TenantActivityLogToolbar", () => ({ default: () => null }));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
verifyUserHasPermission: vi.fn(),
}));
@@ -68,7 +70,7 @@ const events = [
function callLoader(url: string) {
const request = new Request(url);
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/logs/events" } as LoaderFunctionArgs);
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/compliance/events" } as LoaderFunctionArgs);
}
describe("tenant settings event list route", () => {
@@ -92,7 +94,7 @@ describe("tenant settings event list route", () => {
it("checks tenant-scoped audit-trail permission before user and event helpers", async () => {
const data = await callLoader(
"https://app.example.test/acme/settings/logs/events?q=account&name=account.created&data=secret&userId=user-1&page=2&pageSize=25",
"https://app.example.test/acme/settings/compliance/events?q=account&name=account.created&data=secret&userId=user-1&page=2&pageSize=25",
);
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
@@ -133,7 +135,7 @@ describe("tenant settings event list route", () => {
const rejection = new Response("Forbidden", { status: 403 });
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
await expect(callLoader("https://app.example.test/acme/settings/logs/events?name=account.created")).rejects.toBe(rejection);
await expect(callLoader("https://app.example.test/acme/settings/compliance/events?name=account.created")).rejects.toBe(rejection);
expect(getUsersByTenant).not.toHaveBeenCalled();
expect(getEvents).not.toHaveBeenCalled();
@@ -0,0 +1,109 @@
import { LoaderFunctionArgs, useLoaderData } 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 { ApplicationEvents, getApplicationEventNameKey } from "~/modules/events/types/ApplicationEvent";
import EventsTable from "~/modules/events/components/EventsTable";
import TenantActivityLogToolbar from "~/components/activity/TenantActivityLogToolbar";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import { PageIntro } from "~/components/screens/shared/PageShell";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { EventWithAttempts, getEvents } from "~/modules/events/db/events.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUsersByTenant } from "~/utils/db/users.db.server";
import Tabs from "~/components/ui/tabs/Tabs";
type LoaderData = {
title: string;
items: EventWithAttempts[];
pagination: PaginationDto;
filterableProperties: FilterablePropertyDto[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
const { t } = await getTranslations(request);
const urlSearchParams = new URL(request.url).searchParams;
const current = getPaginationFromCurrentUrl(urlSearchParams);
const filterableProperties: FilterablePropertyDto[] = [
{
name: "name",
title: "settings.logs.events.filters.event",
options: ApplicationEvents.filter((f) => !f.adminOnly || !params.tenant).map((item) => {
return {
value: item.value,
name: t("settings.logs.events.filters.eventOption", { eventValue: item.value, eventLabel: t(getApplicationEventNameKey(item.value)) }),
};
}),
},
{
name: "data",
title: "settings.logs.events.filters.data",
},
{
name: "userId",
title: "models.user.object",
options: (await getUsersByTenant(tenantId)).map((item) => {
return {
value: item.id,
name: item.email,
};
}),
},
];
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
const { items, pagination } = await getEvents({ current, filters }, tenantId);
const data: LoaderData = {
title: `${t("models.event.plural")} | ${process.env.APP_NAME}`,
items,
pagination,
filterableProperties,
};
return data;
};
export default function AppEventsRoute() {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const params = useParams();
return (
<>
<EditPageLayout fullWidth>
{/* AK-SET-01: the Compliance hub owns the page header. */}
<PageIntro uiId="ui.settings.logs.intro">{t("settings.logs.subtitle")}</PageIntro>
<div data-ui-id="ui.settings.logs.events.page" className="space-y-2">
<div className="flex justify-between gap-2">
<div data-ui-id="ui.settings.logs.tabs" className="grow">
<Tabs
tabs={[
{
name: t("models.log.plural"),
routePath: UrlUtils.currentTenantUrl(params, "settings/compliance"),
},
{
name: t("models.event.plural"),
routePath: UrlUtils.currentTenantUrl(params, "settings/compliance/events"),
},
]}
/>
</div>
<div data-ui-id="ui.settings.logs.filters">
<TenantActivityLogToolbar filters={data.filterableProperties} exportTo={UrlUtils.currentTenantUrl(params, "settings/logs/events-export")} />
</div>
</div>
<div data-ui-id="ui.settings.logs.events.table">
<EventsTable items={data.items} pagination={data.pagination} />
</div>
</div>
</EditPageLayout>
</>
);
}
@@ -2,7 +2,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { LoaderFunctionArgs } from "react-router";
import { loader } from "./index";
import { getTenantAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
import { getTenantAuditLogList } from "@hivegrid/db/logs.server";
import { getTranslations } from "~/locale/i18next.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
@@ -41,7 +41,6 @@ vi.mock("~/utils/services/.server/urlService", () => ({
vi.mock("@hivegrid/db/logs.server", () => ({
getTenantAuditLogList: vi.fn(),
serializeAdminAuditLogsCsv: vi.fn(),
}));
const params = { tenant: "acme" };
@@ -66,11 +65,11 @@ const auditRows = [
function callLoader(url: string) {
const request = new Request(url);
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/logs" } as LoaderFunctionArgs);
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/compliance" } as LoaderFunctionArgs);
}
function readTenantLogsRoute() {
return readRepoFile("apps/web/app/routes/app.$tenant/settings/logs/index.tsx");
return readRepoFile("apps/web/app/routes/app.$tenant/settings/compliance/index.tsx");
}
describe("tenant settings logs route", () => {
@@ -81,12 +80,11 @@ describe("tenant settings logs route", () => {
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
vi.mocked(getTenantAuditLogList).mockResolvedValue({ rows: auditRows, total: 1, take: 25, skip: 25 } as never);
vi.mocked(serializeAdminAuditLogsCsv).mockReturnValue("csv-body\n");
});
it("checks permission before reading the tenant-scoped filtered table data", async () => {
const data = await callLoader(
"https://app.example.test/acme/settings/logs?q=contact&action=create&url=%2Fcontacts&tenantId=other-tenant&userId=user-1&createdAtFrom=2026-05-01&createdAtTo=2026-05-08&page=2&pageSize=25",
"https://app.example.test/acme/settings/compliance?q=contact&action=create&url=%2Fcontacts&tenantId=other-tenant&userId=user-1&createdAtFrom=2026-05-01&createdAtTo=2026-05-08&page=2&pageSize=25",
);
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
@@ -110,44 +108,19 @@ describe("tenant settings logs route", () => {
});
});
it("exports CSV with the same tenant filters and a capped export window", async () => {
const response = (await callLoader(
"https://app.example.test/acme/settings/logs?export=csv&q=login&action=auth&url=%2Flogin&tenantId=other-tenant&userId=user-2&createdAtFrom=bad-date&createdAtTo=2026-05-08&page=9&pageSize=5",
)) as Response;
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getTenantAuditLogList).mock.invocationCallOrder[0]);
expect(getTenantAuditLogList).toHaveBeenCalledWith("tenant-1", {
q: "login",
action: "auth",
url: "/login",
userId: "user-2",
createdAtFrom: "bad-date",
createdAtTo: "2026-05-08",
take: 500,
skip: 0,
});
expect(JSON.stringify(vi.mocked(getTenantAuditLogList).mock.calls[0]?.[1])).not.toContain("other-tenant");
expect(serializeAdminAuditLogsCsv).toHaveBeenCalledWith(auditRows);
expect(response.headers.get("Content-Type")).toBe("text/csv; charset=utf-8");
expect(response.headers.get("Content-Disposition")).toBe('attachment; filename="tenant-audit-logs.csv"');
expect(await response.text()).toBe("csv-body\n");
});
it("rejects table and CSV reads without permission before helper calls", async () => {
it("rejects table reads without permission before helper calls", async () => {
const rejection = new Response("Forbidden", { status: 403 });
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
await expect(callLoader("https://app.example.test/acme/settings/logs?export=csv")).rejects.toBe(rejection);
await expect(callLoader("https://app.example.test/acme/settings/compliance")).rejects.toBe(rejection);
expect(getTenantAuditLogList).not.toHaveBeenCalled();
expect(serializeAdminAuditLogsCsv).not.toHaveBeenCalled();
});
it("does not crash on malformed numeric and date filters", async () => {
vi.mocked(getTenantAuditLogList).mockResolvedValue({ rows: [], total: 0, take: 10, skip: 0 } as never);
const data = await callLoader("https://app.example.test/acme/settings/logs?page=abc&pageSize=-5&createdAtFrom=not-a-date&createdAtTo=also-bad");
const data = await callLoader("https://app.example.test/acme/settings/compliance?page=abc&pageSize=-5&createdAtFrom=not-a-date&createdAtTo=also-bad");
expect(getTenantAuditLogList).toHaveBeenCalledWith("tenant-1", {
q: null,
@@ -167,7 +140,6 @@ describe("tenant settings logs route", () => {
expect(source).toContain('from "@hivegrid/db/logs.server"');
expect(source).toContain("getTenantAuditLogList");
expect(source).toContain("serializeAdminAuditLogsCsv");
expect(source).toContain("TenantActivityLogToolbar");
expect(source).not.toContain("getLogs");
expect(source).not.toContain('from "~/utils/db/logs.db.server"');
@@ -0,0 +1,131 @@
import type { AdminAuditLogRow } from "@hivegrid/db/logs.server";
import { getTenantAuditLogList } from "@hivegrid/db/logs.server";
import { LoaderFunctionArgs, MetaFunction, useLoaderData } 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 TenantActivityLogToolbar from "~/components/activity/TenantActivityLogToolbar";
import LogsTable from "~/components/app/events/LogsTable";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import { PageIntro } from "~/components/screens/shared/PageShell";
import UrlUtils from "~/utils/app/UrlUtils";
import { getTranslations } from "~/locale/i18next.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import Tabs from "~/components/ui/tabs/Tabs";
import { getTenantAuditLogFiltersFromUrl } from "./logs-export.helpers.server";
type LoaderData = {
title: string;
items: AdminAuditLogRow[];
pagination: PaginationDto;
filterableProperties: FilterablePropertyDto[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
const { t } = await getTranslations(request);
const filterableProperties = getAuditLogFilterableProperties();
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
const urlSearchParams = new URL(request.url).searchParams;
const auditLogFilters = getTenantAuditLogFiltersFromUrl(urlSearchParams);
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
const pageSize = normalizePositiveInteger(currentPagination.pageSize, 10);
const page = normalizePositiveInteger(currentPagination.page, 1);
const { rows, total, take } = await getTenantAuditLogList(tenantId, {
...auditLogFilters,
take: pageSize,
skip: pageSize * (page - 1),
});
const data: LoaderData = {
title: `${t("models.log.plural")} | ${process.env.APP_NAME}`,
items: rows,
pagination: {
page,
pageSize: take,
totalItems: total,
totalPages: Math.ceil(total / take),
sortedBy: currentPagination.sortedBy,
query: currentPagination.query,
},
filterableProperties: filters.properties,
};
return data;
};
function getAuditLogFilterableProperties(): FilterablePropertyDto[] {
return [
{
name: "action",
title: "models.log.action",
},
{
name: "url",
title: "models.log.url",
},
{
name: "userId",
title: "shared.createdBy",
},
{
name: "createdAtFrom",
title: "shared.createdAt",
},
{
name: "createdAtTo",
title: "shared.createdAt",
},
];
}
function normalizePositiveInteger(value: number | null | undefined, fallback: number): number {
if (!Number.isFinite(value) || !value || value < 1) return fallback;
return Math.trunc(value);
}
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function Events() {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const params = useParams();
return (
<>
<EditPageLayout fullWidth>
{/* AK-SET-01: the Compliance hub owns the page header. */}
<PageIntro uiId="ui.settings.logs.intro">{t("settings.logs.subtitle")}</PageIntro>
<div data-ui-id="ui.settings.logs.page" className="space-y-2">
<div className="flex justify-between gap-2">
<div data-ui-id="ui.settings.logs.tabs" className="grow">
<Tabs
tabs={[
{
name: t("models.log.plural"),
routePath: UrlUtils.currentTenantUrl(params, "settings/compliance"),
},
{
name: t("models.event.plural"),
routePath: UrlUtils.currentTenantUrl(params, "settings/compliance/events"),
},
]}
/>
</div>
<div data-ui-id="ui.settings.logs.filters">
<TenantActivityLogToolbar filters={data.filterableProperties} exportTo={UrlUtils.currentTenantUrl(params, "settings/logs/export")} />
</div>
</div>
<div data-ui-id="ui.settings.logs.table">
<LogsTable withTenant={false} items={data.items} pagination={data.pagination} />
</div>
</div>
</EditPageLayout>
</>
);
}
@@ -0,0 +1,17 @@
// Shared between the tenant Protokolle/Ereignisse list routes and their CSV
// export resource routes. Exports must live in resource routes (no component):
// returning a raw Response from a UI route's loader breaks under React Router 7.
import type { AdminAuditLogFilters } from "@hivegrid/db/logs.server";
export const CSV_EXPORT_TAKE = 500;
export function getTenantAuditLogFiltersFromUrl(urlSearchParams: URLSearchParams): AdminAuditLogFilters {
return {
q: urlSearchParams.get("q"),
action: urlSearchParams.get("action"),
url: urlSearchParams.get("url"),
userId: urlSearchParams.get("userId"),
createdAtFrom: urlSearchParams.get("createdAtFrom"),
createdAtTo: urlSearchParams.get("createdAtTo"),
};
}
@@ -0,0 +1,72 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { LoaderFunctionArgs } from "react-router";
import { loader } from "../logs/export";
import { getTenantAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
vi.mock("@hivegrid/db/logs.server", () => ({
getTenantAuditLogList: vi.fn(),
serializeAdminAuditLogsCsv: vi.fn(),
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
verifyUserHasPermission: vi.fn(),
}));
vi.mock("~/utils/services/.server/urlService", () => ({
getTenantIdFromUrl: vi.fn(),
}));
const params = { tenant: "acme" };
const auditRows = [{ id: "log-1" }];
function callLoader(url: string) {
const request = new Request(url);
return loader({ request, params, context: {}, unstable_pattern: "app.$tenant/settings/logs/export" } as LoaderFunctionArgs);
}
describe("tenant settings logs CSV export route", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
vi.mocked(getTenantAuditLogList).mockResolvedValue({ rows: auditRows, total: 1, take: 500, skip: 0 } as never);
vi.mocked(serializeAdminAuditLogsCsv).mockReturnValue("csv-body\n");
});
it("exports CSV with the same tenant filters and a capped export window", async () => {
const response = await callLoader(
"https://app.example.test/acme/settings/logs/export?q=login&action=auth&url=%2Flogin&tenantId=other-tenant&userId=user-2&createdAtFrom=bad-date&createdAtTo=2026-05-08&page=9&pageSize=5",
);
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getTenantAuditLogList).mock.invocationCallOrder[0]);
expect(getTenantAuditLogList).toHaveBeenCalledWith("tenant-1", {
q: "login",
action: "auth",
url: "/login",
userId: "user-2",
createdAtFrom: "bad-date",
createdAtTo: "2026-05-08",
take: 500,
skip: 0,
});
expect(JSON.stringify(vi.mocked(getTenantAuditLogList).mock.calls[0]?.[1])).not.toContain("other-tenant");
expect(serializeAdminAuditLogsCsv).toHaveBeenCalledWith(auditRows);
expect(response.headers.get("Content-Type")).toBe("text/csv; charset=utf-8");
expect(response.headers.get("Content-Disposition")).toBe('attachment; filename="tenant-audit-logs.csv"');
expect(await response.text()).toBe("csv-body\n");
});
it("rejects CSV reads without permission before helper calls", async () => {
const rejection = new Response("Forbidden", { status: 403 });
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
await expect(callLoader("https://app.example.test/acme/settings/logs/export")).rejects.toBe(rejection);
expect(getTenantAuditLogList).not.toHaveBeenCalled();
expect(serializeAdminAuditLogsCsv).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,70 @@
// AK-P21 — subprocessor register (global rows, tenant-visible). Gate:
// privacy.subprocessors.read (denied ⇒ 404 via PermissionsService).
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData, useParams, useRevalidator } from "react-router";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { listActiveSubprocessors } from "@hivegrid/db/privacy-gdpr.server";
import { buildSubprocessorsVM, type SubprocessorsVM } from "@hivegrid/view-models";
import { SubprocessorsPage } from "~/components/screens/privacy/SubprocessorsPage";
import { getTranslations } from "~/locale/i18next.server";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
type LoaderData = {
title: string;
vm: SubprocessorsVM;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "privacy.subprocessors.read", tenantId);
const subprocessors = await listActiveSubprocessors();
const vm = buildSubprocessorsVM({
subprocessors: subprocessors.map((subprocessor) => ({
id: subprocessor.id,
name: subprocessor.name,
purposeText: subprocessor.purposeText,
country: subprocessor.country,
isEuEea: subprocessor.isEuEea,
dataCategories: subprocessor.dataCategories,
dpaUrl: subprocessor.dpaUrl,
activeSince: subprocessor.activeSince ? subprocessor.activeSince.toISOString() : null,
})),
});
const data: LoaderData = { title: `${t("settings.privacy.subprocessors.title")} | ${process.env.APP_NAME}`, vm };
return Response.json(data);
};
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
export default function PrivacySubprocessorsRoute() {
// AK-P21 DoD B9 — breadcrumb target injected into the screen so the screen
// itself stays free of router data access.
const routeParams = useParams();
const hubHref = appPath({ tenantSlug: routeParams.tenant ?? "", path: "settings/compliance", mode: "host-aware" });
const { vm } = useLoaderData<LoaderData>();
const revalidator = useRevalidator();
return (
<SubprocessorsPage
embedded
hubHref={hubHref}
vm={vm}
actions={{
onRetry() {
revalidator.revalidate();
},
}}
/>
);
}
@@ -0,0 +1,235 @@
// AK-P21 — tenant deletion area. Gate: privacy.tenant_deletion (denied ⇒ 404
// via PermissionsService). The wizard re-authenticates with password (+ TOTP
// when enabled) and requires the tenant slug as the confirm phrase; the
// service re-checks the phrase server-side. Cancelling is possible during the
// whole 30-day grace window. The hard-delete cron itself is a tracked
// follow-up outside this route (see ticket doc AK-P21).
import { randomUUID } from "node:crypto";
import { useEffect } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useActionData, useLoaderData, useLocation, useNavigate, useNavigation, useParams, useRevalidator, useSubmit } from "react-router";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { toast } from "sonner";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { getDbClient } from "@hivegrid/db/client.server";
import {
cancelTenantDeletionRequest,
createTenantDeletionRequest,
GDPR_TENANT_DELETION_GRACE_DAYS,
} from "@hivegrid/db/privacy-gdpr.server";
import { buildTenantDeletionVM, type TenantDeletionVM } from "@hivegrid/view-models";
import { TenantDeletionPage } from "~/components/screens/privacy/TenantDeletionPage";
import { getTranslations } from "~/locale/i18next.server";
import { requireAuth } from "~/utils/loaders.middleware";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { verifyPassword } from "~/utils/auth/passwordHasher.server";
import { getActiveTotpSecretEncrypted } from "~/utils/db/users.db.server";
import { verifyTotpCode } from "~/services/auth/totp.server";
import { getTenant } from "~/utils/db/tenants.db.server";
import { useRootData } from "~/utils/data/useRootData";
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
type LoaderData = {
title: string;
vm: TenantDeletionVM;
};
type ActionData = { ok: true; message: string } | { ok: false; error: string };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "privacy.tenant_deletion", tenantId);
const userInfo = await getUserInfo(request);
const db = getDbClient();
const [latestRequest, totpSecret] = await Promise.all([
db.tenantDeletionRequest.findFirst({
where: { tenantId },
orderBy: { createdAt: "desc" },
select: { id: true, status: true, reason: true, reasonText: true, gracePeriodEndsAt: true, createdAt: true },
}),
getActiveTotpSecretEncrypted(userInfo.userId),
]);
const vm = buildTenantDeletionVM({
now: new Date().toISOString(),
tenantSlug: params.tenant ?? "",
graceDays: GDPR_TENANT_DELETION_GRACE_DAYS,
requiresOtp: totpSecret !== null,
request: latestRequest
? {
id: latestRequest.id,
status: latestRequest.status,
reason: latestRequest.reason,
reasonText: latestRequest.reasonText,
gracePeriodEndsAt: latestRequest.gracePeriodEndsAt.toISOString(),
createdAt: latestRequest.createdAt.toISOString(),
}
: null,
});
const data: LoaderData = { title: `${t("settings.privacy.deletion.title")} | ${process.env.APP_NAME}`, vm };
return Response.json(data);
};
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
export const action = async ({ request, params }: ActionFunctionArgs) => {
await requireAuth({ request, params });
await validateCSRFToken(request);
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "privacy.tenant_deletion", tenantId);
const userInfo = await getUserInfo(request);
const db = getDbClient();
const form = await request.formData();
const intent = String(form.get("intent") ?? "");
const requestId = randomUUID();
const badRequest = (error: string, status = 400) => Response.json({ ok: false, error } satisfies ActionData, { status });
if (intent === "cancel") {
const deletionRequestId = String(form.get("requestId") ?? "").trim();
if (!deletionRequestId) return badRequest(t("settings.privacy.errors.unknownIntent", { intent }));
try {
await cancelTenantDeletionRequest({ id: deletionRequestId, tenantId, cancelledByUserId: userInfo.userId });
} catch {
return badRequest(t("settings.privacy.deletion.errors.cancelFailed"), 409);
}
await createAuditEvent({
tenantId,
actorId: userInfo.userId,
actorType: "user",
action: "CANCEL_TENANT_DELETION",
targetType: "Tenant",
targetId: tenantId,
regulatoryScope: ["gdpr"],
dataSensitivity: "pii",
outcome: "success",
metadata: { requestId, deletionRequestId, source: "privacy-deletion-page" },
});
return Response.json({ ok: true, message: t("settings.privacy.deletion.messages.cancelled") } satisfies ActionData);
}
if (intent === "request") {
const password = String(form.get("password") ?? "");
const otpCode = String(form.get("otpCode") ?? "").trim();
const slugConfirm = String(form.get("slugConfirm") ?? "");
const reasonText = String(form.get("reasonText") ?? "").trim();
// Re-authenticate: password always; TOTP when the user has it enabled.
const user = await db.user.findUnique({ where: { id: userInfo.userId }, select: { passwordHash: true } });
const { valid: passwordValid } = await verifyPassword(password, user?.passwordHash ?? null);
if (!passwordValid) {
return badRequest(t("settings.privacy.deletion.errors.verifyFailed"), 403);
}
const totpSecret = await getActiveTotpSecretEncrypted(userInfo.userId);
if (totpSecret && !verifyTotpCode(totpSecret, otpCode)) {
return badRequest(t("settings.privacy.deletion.errors.verifyFailed"), 403);
}
const tenant = await getTenant(tenantId);
if (!tenant) return badRequest(t("shared.unexpectedError"), 404);
if (slugConfirm !== tenant.slug) {
return badRequest(t("settings.privacy.deletion.wizard.confirm.slugMismatch"));
}
try {
const deletionRequest = await createTenantDeletionRequest({
tenantId,
requestedByUserId: userInfo.userId,
tenantSlug: tenant.slug,
slugConfirmPhrase: slugConfirm,
reason: "voluntary",
reasonText: reasonText || null,
});
await createAuditEvent({
tenantId,
actorId: userInfo.userId,
actorType: "user",
action: "REQUEST_TENANT_DELETION",
targetType: "Tenant",
targetId: tenantId,
regulatoryScope: ["gdpr"],
dataSensitivity: "pii",
outcome: "success",
metadata: { requestId, deletionRequestId: deletionRequest.id, gracePeriodEndsAt: deletionRequest.gracePeriodEndsAt.toISOString(), source: "privacy-deletion-page" },
});
return Response.json({ ok: true, message: t("settings.privacy.deletion.messages.requested", { days: GDPR_TENANT_DELETION_GRACE_DAYS }) } satisfies ActionData);
} catch (error) {
const message = error instanceof Error ? error.message : "";
if (message.includes("already active")) {
return badRequest(t("settings.privacy.deletion.errors.alreadyActive"), 409);
}
if (message.includes("confirmation phrase")) {
return badRequest(t("settings.privacy.deletion.wizard.confirm.slugMismatch"));
}
throw error;
}
}
return badRequest(t("settings.privacy.errors.unknownIntent", { intent }));
};
export default function PrivacyDeletionRoute() {
// AK-P21 DoD B9 — breadcrumb target injected into the screen so the screen
// itself stays free of router data access.
const routeParams = useParams();
const hubHref = appPath({ tenantSlug: routeParams.tenant ?? "", path: "settings/compliance", mode: "host-aware" });
const { vm } = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const submit = useSubmit();
const revalidator = useRevalidator();
const navigation = useNavigation();
const navigate = useNavigate();
const location = useLocation();
const { csrf } = useRootData();
useEffect(() => {
if (!actionData) return;
if (actionData.ok) toast.success(actionData.message);
}, [actionData]);
return (
<TenantDeletionPage
embedded
hubHref={hubHref}
vm={vm}
submitting={navigation.state === "submitting"}
errorKey={actionData && !actionData.ok ? actionData.error : null}
actions={{
onRequest(fields) {
const form = new FormData();
form.set("intent", "request");
form.set("csrf", csrf ?? "");
form.set("password", fields.password);
form.set("otpCode", fields.otpCode);
form.set("slugConfirm", fields.slugConfirm);
form.set("reasonText", fields.reasonText);
void submit(form, { method: "post" });
},
onCancelRequest(requestId) {
const form = new FormData();
form.set("intent", "cancel");
form.set("csrf", csrf ?? "");
form.set("requestId", requestId);
void submit(form, { method: "post" });
},
onOpenExport() {
void navigate(location.pathname.replace(/\/deletion\/?$/, "/export"));
},
onRetry() {
revalidator.revalidate();
},
}}
/>
);
}
@@ -1,11 +1,14 @@
import { LoaderFunctionArgs, redirect } from "react-router";
import { LoaderFunctionArgs } from "react-router";
import UrlUtils from "~/utils/app/UrlUtils";
import { requireAuth } from "~/utils/loaders.middleware";
import { legacySettingsRedirect } from "./legacy-redirects.server";
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
return redirect(UrlUtils.currentTenantUrl(params, "settings/subscription"));
// AK-SET-01: retargeted straight at the hub — pointing at the old
// `settings/subscription` would now cost a second hop. Routed through the
// shared helper so the query string survives like on every other legacy path.
return legacySettingsRedirect({ request, params }, "settings/billing");
};
export default function RemovedCreditsRoute() {
@@ -0,0 +1,77 @@
// AK-SET-01 — Customer-Portal keeps its own rail entry but gains the same tab
// bar as the six settings hubs, so the mail templates no longer need a second
// entry beside it. Layout route only.
import { Outlet, useLoaderData, useLocation, type LoaderFunctionArgs, type MetaFunction } from "react-router";
import { FeatherMail } from "@subframe/core";
import { buildSettingsHubVM, type SettingsHubTabInput } from "@hivegrid/view-models";
import { SettingsHubShell } from "~/components/screens/settings/SettingsHubShell";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { isPortalCustomDomainRuntimeEnabled } from "~/services/customer-portal/portal-custom-domain-runtime.server";
import { hasSettingsPermission, settingsHubBaseRedirect, settingsHubNotFound } from "./hub-access.server";
type LoaderData = {
title: string;
tabs: SettingsHubTabInput[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
const [{ t }, canReadPortal, canAdminPortal] = await Promise.all([
getTranslations(request),
hasSettingsPermission(request, "portal.read", tenantId),
hasSettingsPermission(request, "portal.admin", tenantId),
]);
if (!canReadPortal && !canAdminPortal) throw settingsHubNotFound();
const tabs: SettingsHubTabInput[] = [];
if (canReadPortal) {
// The hub index href is a prefix of every sibling.
tabs.push({ id: "settings", labelKey: "customerPortal.admin.title", href: UrlUtils.currentTenantUrl(params, "settings/customer-portal"), exact: true });
}
// The domain tab follows the same runtime gate the settings screen uses for
// its "open domain" action — no tab into a disabled surface.
if (canAdminPortal && isPortalCustomDomainRuntimeEnabled()) {
tabs.push({
id: "domain",
labelKey: "customerPortal.domain.title",
href: UrlUtils.currentTenantUrl(params, "settings/customer-portal/domain"),
});
}
if (canAdminPortal) {
tabs.push({
id: "emailTemplates",
labelKey: "customerPortal.emailTemplates.title",
href: UrlUtils.currentTenantUrl(params, "settings/customer-portal/email-templates"),
});
}
const baseRedirect = settingsHubBaseRedirect(request, UrlUtils.currentTenantUrl(params, "settings/customer-portal"), tabs);
if (baseRedirect) throw baseRedirect;
return { title: `${t("customerPortal.admin.title")} | ${process.env.APP_NAME}`, tabs } satisfies LoaderData;
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function CustomerPortalHubRoute() {
const { tabs } = useLoaderData<LoaderData>();
const location = useLocation();
const vm = buildSettingsHubVM({
hubId: "customerPortal",
titleKey: "customerPortal.admin.title",
subtitleKey: "customerPortal.admin.subtitle",
tabs,
currentPath: location.pathname,
});
return (
<SettingsHubShell vm={vm} icon={<FeatherMail />}>
<Outlet />
</SettingsHubShell>
);
}
@@ -0,0 +1,569 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
const routeDir = path.dirname(fileURLToPath(import.meta.url));
const mocks = vi.hoisted(() => {
class PortalDomainError extends Error {
constructor(
readonly code: string,
readonly status = 400
) {
super(code);
}
}
class PortalDomainCommercialError extends Error {
constructor(readonly code: string) {
super(code);
}
}
class ProductAcquisitionError extends Error {
constructor(readonly code: string) {
super(code);
}
}
return {
PortalDomainError,
PortalDomainCommercialError,
ProductAcquisitionError,
translations: vi.fn(),
requireContext: vi.fn(),
billingState: vi.fn(),
loadVm: vi.fn(),
validateCsrf: vi.fn(),
rateLimit: vi.fn(),
checkoutCatalog: vi.fn(),
eligibility: vi.fn(),
startMonthly: vi.fn(),
cancelRecurring: vi.fn(),
startSetup: vi.fn(),
claim: vi.fn(),
reissue: vi.fn(),
reconcile: vi.fn(),
verify: vi.fn(),
retry: vi.fn(),
remove: vi.fn(),
switchClaim: vi.fn(),
activateSwitch: vi.fn(),
getUser: vi.fn(),
getTenant: vi.fn(),
absolutePublicPath: vi.fn(),
apiUrl: vi.fn(),
runtimeEnabled: vi.fn(),
};
});
vi.mock("@hivegrid/config", () => ({
loadRequiredWebConfig: () => ({
appName: "HiveGrid",
cryptoSecret: "test-domain-admin-secret-at-least-32-bytes",
routing: {
protocol: "https",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
portalAppHost: "portal.example.test",
appBaseDomain: "example.test",
},
}),
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({ runWithRlsContext: (_ctx: unknown, operation: () => unknown) => operation() }));
vi.mock("~/components/screens/customer-portal/PortalDomainAdminInterimPage", () => ({ PortalDomainAdminInterimPage: () => null }));
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: mocks.translations }));
vi.mock("~/services/billing/product-acquisition.server", () => ({
ProductAcquisitionError: mocks.ProductAcquisitionError,
productAcquisitionReturnIdPlaceholder: "__hivegrid_acquisition_id__",
cancelRecurringProductAcquisition: mocks.cancelRecurring,
}));
vi.mock("~/services/customer-portal/portal-admin-context.server", () => ({ requirePortalAdminWorkspaceContext: mocks.requireContext }));
vi.mock("~/services/customer-portal/portal-custom-domain-runtime.server", () => ({
isPortalCustomDomainRuntimeEnabled: mocks.runtimeEnabled,
}));
vi.mock("~/services/customer-portal/portal-domain-admin-rate-limit.server", () => ({
portalDomainAdminRateLimitActions: [
"buy-portal",
"cancel-portal",
"claim-domain",
"buy-domain-setup",
"reissue-proof",
"verify-dns",
"retry-domain",
"remove-domain",
"switch-domain",
"activate-switch",
],
checkPortalDomainAdminRateLimit: mocks.rateLimit,
}));
vi.mock("~/services/customer-portal/portal-domain-commercial.server", () => ({
PortalDomainCommercialError: mocks.PortalDomainCommercialError,
getCustomerPortalCommercialEligibility: mocks.eligibility,
getCustomerPortalCheckoutCatalog: mocks.checkoutCatalog,
startCustomerPortalMonthlyCheckout: mocks.startMonthly,
startPortalDomainSetupCheckout: mocks.startSetup,
}));
vi.mock("~/services/customer-portal/portal-domain.server", () => ({
PortalDomainError: mocks.PortalDomainError,
loadPortalDomainAdminVM: mocks.loadVm,
claimPortalCustomDomain: mocks.claim,
reissuePortalDomainProof: mocks.reissue,
reconcilePortalDomainEntitlement: mocks.reconcile,
verifyPortalCustomDomainDns: mocks.verify,
retryPortalCustomDomain: mocks.retry,
removePortalCustomDomain: mocks.remove,
switchPortalCustomDomainClaim: mocks.switchClaim,
activatePortalDomainSwitch: mocks.activateSwitch,
}));
vi.mock("~/utils/app/CrossHostUrls", () => ({ absolutePublicAppPath: mocks.absolutePublicPath }));
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({ apiUrl: mocks.apiUrl }));
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenant: mocks.getTenant }));
vi.mock("~/utils/db/users.db.server", () => ({ getUser: mocks.getUser }));
vi.mock("~/utils/services/.server/billingStatusService", () => ({ getTenantBillingReadOnlyState: mocks.billingState }));
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCsrf }));
import { action, loader } from "./domain";
const context = { tenantId: "tenant-a1", tenantSlug: "acme", userId: "user-admin-a", permissions: ["portal.admin"] };
const readyVm = {
status: "ready",
data: {
readOnly: false,
standardPortalUrl: "https://portal.example.test/acme",
portalEntitled: true,
portalEntitlementSource: "base_plan",
monthlyAddOn: { required: false, active: true, amountCents: 1999, currency: "EUR" },
domainSetup: { required: true, active: false, includedByContract: false, amountCents: 29999, currency: "EUR", scopeKey: "portal-domain:claim-current" },
domain: {
claimId: "claim-current",
hostname: "portal.acme.test",
status: "active",
generation: 1,
customPortalUrl: "https://portal.acme.test",
txtRecordName: "_hivegrid-portal.portal.acme.test",
txtRecordValue: null,
cnameRecordName: "portal.acme.test",
cnameRecordValue: "portal.hivegrid.de",
txtVerified: false,
cnameVerified: false,
nextRetryAt: null,
nextRevalidationAt: null,
certificateExpiresAt: null,
cooldownUntil: null,
failureMessageKey: null,
killSwitchEnabled: false,
},
pendingSwitch: null,
actions: {
canBuyPortal: false,
canCancelPortal: false,
canClaimDomain: false,
canBuyDomainSetup: false,
canReissueProof: false,
canVerifyDns: false,
canRetry: false,
canRemove: true,
canSwitch: true,
canActivateSwitch: false,
},
timeline: [],
},
} as const;
function serverBuiltVm(input: unknown) {
const request = input as {
readonly frozen?: boolean;
readonly transientClaimProof?: { readonly claimId: string; readonly txtRecordValue: string } | null;
};
const proof = request.transientClaimProof;
const frozen = request.frozen ?? false;
const actions = frozen ? Object.fromEntries(Object.keys(readyVm.data.actions).map((key) => [key, false])) : readyVm.data.actions;
if (proof?.claimId === "claim-switch") {
return {
...readyVm,
data: {
...readyVm.data,
readOnly: frozen,
actions,
pendingSwitch: {
claimId: proof.claimId,
hostname: "portal-new.acme.test",
status: "awaiting_payment",
billingScopeKey: "portal-domain:claim-switch",
txtRecordName: "_hivegrid-portal.portal-new.acme.test",
txtRecordValue: proof.txtRecordValue,
cnameRecordName: "portal-new.acme.test",
cnameRecordValue: "portal.hivegrid.de",
txtVerified: false,
cnameVerified: false,
verificationExpiresAt: "2026-07-18T00:00:00.000Z",
},
},
};
}
return {
...readyVm,
data: {
...readyVm.data,
readOnly: frozen,
actions,
domain: proof ? { ...readyVm.data.domain, claimId: proof.claimId, txtRecordValue: proof.txtRecordValue } : readyVm.data.domain,
},
};
}
function args(request: Request) {
return { request, params: { tenant: "acme" }, context: {} } as never;
}
function post(intent: string, values: Readonly<Record<string, string>> = {}): Request {
const body = new URLSearchParams({ intent, csrf: "csrf-token", ...values });
return new Request("https://app.example.test/acme/settings/customer-portal/domain", { method: "POST", body });
}
describe("customer portal domain admin route", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.translations.mockResolvedValue({ t: (key: string) => key });
mocks.requireContext.mockResolvedValue(context);
mocks.runtimeEnabled.mockReturnValue(true);
mocks.billingState.mockResolvedValue({ readOnly: false, status: "active" });
mocks.loadVm.mockImplementation(async (input) => serverBuiltVm(input));
mocks.validateCsrf.mockResolvedValue(undefined);
mocks.rateLimit.mockResolvedValue({ allowed: true });
mocks.checkoutCatalog.mockResolvedValue({
monthlyAddOn: { productId: "product-monthly", priceId: "price-monthly", amountCents: 2499, currency: "EUR" },
customDomainSetup: { productId: "product-setup", priceId: "price-setup", amountCents: 34999, currency: "EUR" },
});
mocks.eligibility.mockResolvedValue({
portalSource: "recurring_add_on",
monthlyAddOnSubscriptionProductId: "tenant-product-portal",
});
mocks.getUser.mockResolvedValue({ id: "user-admin-a", email: "ada@example.test", firstName: "Ada", lastName: "Admin" });
mocks.getTenant.mockResolvedValue({ id: "tenant-a1", slug: "acme", name: "Acme GmbH" });
mocks.absolutePublicPath.mockImplementation((_routing: unknown, target: string) => `https://app.example.test${target}`);
mocks.apiUrl.mockReturnValue("https://api.example.test/v1/billing/mollie/webhooks");
mocks.claim.mockResolvedValue({
claimId: "claim-new",
replayed: false,
verification: { txtRecordValue: "hivegrid-proof-once" },
});
mocks.switchClaim.mockResolvedValue({
claimId: "claim-switch",
replayed: false,
verification: { txtRecordValue: "hivegrid-switch-proof-once" },
});
mocks.reissue.mockResolvedValue({
claimId: "claim-current",
txtRecordValue: "hivegrid-proof-reissued",
expiresAt: "2026-07-18T00:00:00.000Z",
});
mocks.verify.mockResolvedValue({ txtVerified: true, cnameVerified: true, provisioning: true });
mocks.reconcile.mockResolvedValue({ active: false, pendingSwitch: false });
mocks.startMonthly.mockResolvedValue({ checkoutUrl: "https://checkout.example.test/monthly" });
mocks.cancelRecurring.mockResolvedValue({ id: "acq-monthly", status: "cancelled", replayed: false });
mocks.startSetup.mockResolvedValue({ checkoutUrl: "https://checkout.example.test/setup" });
});
it("404-gates the loader with portal.admin and uses the canonical HTTPS portal origin", async () => {
const request = new Request("https://app.example.test/acme/settings/customer-portal/domain");
const response = await loader(args(request));
expect(mocks.requireContext).toHaveBeenCalledWith(request, { tenant: "acme" }, "portal.admin");
expect(mocks.loadVm).toHaveBeenCalledWith({
tenantId: "tenant-a1",
standardPortalOrigin: "https://portal.example.test",
frozen: false,
});
expect(mocks.reconcile).not.toHaveBeenCalled();
await expect(response.json()).resolves.toMatchObject({
vm: {
status: "ready",
data: {
monthlyAddOn: { amountCents: 2499, currency: "EUR" },
domainSetup: { amountCents: 34999, currency: "EUR" },
},
},
});
});
it("fails closed instead of rendering fallback prices when the checkout catalog is unavailable", async () => {
mocks.checkoutCatalog.mockRejectedValueOnce(new mocks.PortalDomainCommercialError("PRODUCT_NOT_FOUND"));
const response = await loader(args(new Request("https://app.example.test/acme/settings/customer-portal/domain")));
await expect(response.json()).resolves.toMatchObject({
vm: { status: "error", error: { messageKey: "customerPortal.domain.errors.productUnavailable" } },
});
});
it("preserves the permission service's non-disclosing 404", async () => {
mocks.requireContext.mockRejectedValueOnce(new Response(null, { status: 404 }));
await expect(loader(args(new Request("https://app.example.test/acme/settings/customer-portal/domain")))).rejects.toMatchObject({ status: 404 });
expect(mocks.loadVm).not.toHaveBeenCalled();
});
it("returns 404 for a disabled runtime only after the loader permission gate", async () => {
mocks.runtimeEnabled.mockReturnValueOnce(false);
const request = new Request("https://app.example.test/acme/settings/customer-portal/domain");
await expect(loader(args(request))).rejects.toMatchObject({ status: 404 });
expect(mocks.requireContext).toHaveBeenCalledWith(request, { tenant: "acme" }, "portal.admin");
expect(mocks.runtimeEnabled).toHaveBeenCalledOnce();
expect(mocks.translations).not.toHaveBeenCalled();
expect(mocks.loadVm).not.toHaveBeenCalled();
});
it("returns the permission service's 404 before CSRF or intent validation on mutations", async () => {
const denied = new Response(null, { status: 404 });
mocks.requireContext.mockRejectedValueOnce(denied);
const request = post("invented-domain-operation");
await expect(action(args(request))).rejects.toBe(denied);
expect(mocks.validateCsrf).not.toHaveBeenCalled();
expect(mocks.rateLimit).not.toHaveBeenCalled();
});
it("returns 404 for a disabled runtime after mutation permission and before request validation", async () => {
mocks.runtimeEnabled.mockReturnValueOnce(false);
const request = post("claim-domain", {
hostname: "portal.acme.test",
idempotencyKey: "portal-domain:stable-claim-key",
});
await expect(action(args(request))).rejects.toMatchObject({ status: 404 });
expect(mocks.requireContext).toHaveBeenCalledWith(request, { tenant: "acme" }, "portal.admin");
expect(mocks.runtimeEnabled).toHaveBeenCalledOnce();
expect(mocks.validateCsrf).not.toHaveBeenCalled();
expect(mocks.rateLimit).not.toHaveBeenCalled();
expect(mocks.claim).not.toHaveBeenCalled();
});
it("validates CSRF, permission and the shared fail-closed limiter before claiming", async () => {
const request = post("claim-domain", {
hostname: "portal.acme.test",
idempotencyKey: "portal-domain:stable-claim-key",
});
const response = await action(args(request));
expect(response.status).toBe(201);
expect(mocks.validateCsrf).toHaveBeenCalledWith(request, { formData: expect.objectContaining({ get: expect.any(Function) }) });
expect(mocks.requireContext).toHaveBeenCalledWith(request, { tenant: "acme" }, "portal.admin");
expect(mocks.requireContext.mock.invocationCallOrder[0]).toBeLessThan(mocks.validateCsrf.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER);
expect(mocks.rateLimit).toHaveBeenCalledWith({
tenantId: "tenant-a1",
userId: "user-admin-a",
action: "claim-domain",
secret: "test-domain-admin-secret-at-least-32-bytes",
});
expect(mocks.claim).toHaveBeenCalledWith({
tenantId: "tenant-a1",
actorUserId: "user-admin-a",
hostname: "portal.acme.test",
idempotencyKey: "portal-domain:stable-claim-key",
});
const data = await response.json();
expect(data).toMatchObject({
ok: true,
vm: { status: "ready", data: { domain: { claimId: "claim-new", txtRecordValue: "hivegrid-proof-once" } } },
});
expect(data).not.toHaveProperty("claimId");
expect(data).not.toHaveProperty("transientTxtRecordValue");
expect(mocks.loadVm).toHaveBeenLastCalledWith({
tenantId: "tenant-a1",
standardPortalOrigin: "https://portal.example.test",
frozen: false,
transientClaimProof: { claimId: "claim-new", txtRecordValue: "hivegrid-proof-once" },
});
});
it("denies a mutation when the distributed rate limiter is unavailable or exhausted", async () => {
mocks.rateLimit.mockResolvedValueOnce({ allowed: false, retryAfterSeconds: 900 });
const response = await action(args(post("retry-domain")));
expect(response.status).toBe(429);
expect(response.headers.get("Retry-After")).toBe("900");
expect(mocks.retry).not.toHaveBeenCalled();
});
it("rejects unknown intents before reserving a shared-store bucket", async () => {
const response = await action(args(post("invented-domain-operation")));
expect(response.status).toBe(400);
expect(mocks.rateLimit).not.toHaveBeenCalled();
await expect(response.json()).resolves.toMatchObject({
errorKey: "customerPortal.domain.errors.invalidInput",
vm: { status: "ready" },
});
});
it("keeps frozen billing tenants read-only on the server", async () => {
mocks.billingState.mockResolvedValueOnce({ readOnly: true, status: "frozen" });
const response = await action(args(post("remove-domain")));
expect(response.status).toBe(423);
expect(mocks.remove).not.toHaveBeenCalled();
await expect(response.json()).resolves.toMatchObject({
errorKey: "customerPortal.domain.errors.readOnly",
vm: { status: "ready", data: { readOnly: true } },
});
expect(mocks.loadVm).toHaveBeenLastCalledWith(expect.objectContaining({ frozen: true }));
});
it("starts catalog-bound monthly and claim-bound one-off checkouts", async () => {
const monthly = await action(args(post("buy-portal")));
expect(monthly.status).toBe(302);
expect(monthly.headers.get("Location")).toBe("https://checkout.example.test/monthly");
expect(mocks.startMonthly).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: "tenant-a1",
tenantName: "Acme GmbH",
userEmail: "ada@example.test",
productId: "product-monthly",
priceId: "price-monthly",
redirectUrl: "https://app.example.test/subscribe/acme/product/__hivegrid_acquisition_id__/success?return=customer-portal-domain",
webhookUrl: "https://api.example.test/v1/billing/mollie/webhooks",
})
);
const setup = await action(args(post("buy-domain-setup", { claimId: "claim-switch" })));
expect(setup.status).toBe(302);
expect(setup.headers.get("Location")).toBe("https://checkout.example.test/setup");
expect(mocks.startSetup).toHaveBeenCalledWith(
expect.objectContaining({
claimId: "claim-switch",
productId: "product-setup",
priceId: "price-setup",
})
);
});
it("delegates fail-closed recurring price reservation to the checkout service", async () => {
const response = await action(args(post("buy-portal")));
expect(response.status).toBe(302);
expect(mocks.startMonthly).toHaveBeenCalledOnce();
});
it("cancels only the tenant-owned recurring portal product through the provider-first service", async () => {
const response = await action(args(post("cancel-portal", { tenantSubscriptionProductId: "forged-other-add-on" })));
expect(response.status).toBe(200);
expect(mocks.eligibility).toHaveBeenCalledWith({ tenantId: "tenant-a1" });
expect(mocks.cancelRecurring).toHaveBeenCalledWith({
tenantId: "tenant-a1",
actorUserId: "user-admin-a",
tenantSubscriptionProductId: "tenant-product-portal",
eventData: {
user: { id: "user-admin-a", email: "ada@example.test" },
tenant: { id: "tenant-a1", name: "Acme GmbH" },
},
});
await expect(response.json()).resolves.toMatchObject({
ok: true,
messageKey: "customerPortal.domain.messages.portalCancelled",
});
});
it("wires proof recovery, verify, retry, removal, and switch activation intents", async () => {
const reissueResponse = await action(args(post("reissue-proof", { claimId: "claim-current" })));
await action(args(post("verify-dns", { claimId: "claim-switch" })));
await action(args(post("retry-domain")));
await action(args(post("remove-domain", { reason: "planned switch" })));
const switchResponse = await action(
args(
post("switch-domain", {
hostname: "portal-new.acme.test",
idempotencyKey: "portal-domain:stable-switch-key",
})
)
);
await action(args(post("activate-switch", { claimId: "claim-switch" })));
expect(mocks.reissue).toHaveBeenCalledWith({ tenantId: "tenant-a1", actorUserId: "user-admin-a", claimId: "claim-current" });
expect(mocks.reconcile).toHaveBeenCalledWith({ tenantId: "tenant-a1", actorUserId: "user-admin-a", claimId: "claim-switch" });
expect(mocks.verify).toHaveBeenCalledWith({ tenantId: "tenant-a1", actorUserId: "user-admin-a", claimId: "claim-switch" });
expect(mocks.reconcile.mock.invocationCallOrder[0]).toBeLessThan(mocks.verify.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER);
expect(mocks.retry).toHaveBeenCalledWith({ tenantId: "tenant-a1", actorUserId: "user-admin-a" });
expect(mocks.remove).toHaveBeenCalledWith({ tenantId: "tenant-a1", actorUserId: "user-admin-a", reason: "planned switch" });
expect(mocks.switchClaim).toHaveBeenCalledWith(expect.objectContaining({ hostname: "portal-new.acme.test" }));
expect(mocks.activateSwitch).toHaveBeenCalledWith({ tenantId: "tenant-a1", actorUserId: "user-admin-a", claimId: "claim-switch" });
await expect(reissueResponse.json()).resolves.toMatchObject({
ok: true,
messageKey: "customerPortal.domain.messages.proofReissued",
vm: { status: "ready", data: { domain: { claimId: "claim-current", txtRecordValue: "hivegrid-proof-reissued" } } },
});
const switchData = await switchResponse.json();
expect(switchData).toMatchObject({
vm: {
status: "ready",
data: { pendingSwitch: { claimId: "claim-switch", txtRecordValue: "hivegrid-switch-proof-once" } },
},
});
expect(switchData).not.toHaveProperty("transientTxtRecordValue");
});
it("does not expose the operator kill switch from the tenant route", async () => {
const response = await action(args(post("set-kill-switch", { enabled: "true", reason: "security incident" })));
expect(response.status).toBe(400);
expect(mocks.rateLimit).not.toHaveBeenCalled();
await expect(response.json()).resolves.toMatchObject({ errorKey: "customerPortal.domain.errors.invalidInput" });
});
it("returns a renewed expired TXT proof only to the authenticated admin action", async () => {
mocks.verify.mockResolvedValueOnce({
txtVerified: false,
cnameVerified: false,
provisioning: false,
renewedProof: {
claimId: "claim-current",
txtRecordValue: "hivegrid-portal-verification=fresh-proof",
expiresAt: "2026-07-18T10:00:00.000Z",
},
});
const response = await action(args(post("verify-dns", { claimId: "claim-current" })));
expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({
ok: true,
messageKey: "customerPortal.domain.messages.proofRenewed",
vm: {
status: "ready",
data: { domain: { claimId: "claim-current", txtRecordValue: "hivegrid-portal-verification=fresh-proof" } },
},
});
});
it("maps domain, catalog and provider failures to user-facing keys", async () => {
mocks.claim.mockRejectedValueOnce(new mocks.PortalDomainError("HOSTNAME_UNAVAILABLE", 409));
const unavailable = await action(args(post("claim-domain", { hostname: "portal.acme.test", idempotencyKey: "portal-domain:claim-a" })));
expect(unavailable.status).toBe(409);
await expect(unavailable.json()).resolves.toMatchObject({
errorKey: "customerPortal.domain.errors.hostnameUnavailable",
vm: { status: "ready" },
});
mocks.checkoutCatalog.mockRejectedValueOnce(new mocks.PortalDomainCommercialError("CHECKOUT_CATALOG_DRIFT"));
const drift = await action(args(post("buy-portal")));
expect(drift.status).toBe(409);
await expect(drift.json()).resolves.toMatchObject({
errorKey: "customerPortal.domain.errors.checkoutCatalogDrift",
vm: { status: "ready" },
});
});
it("renders only loader/action VMs and never recomputes or stores a TXT proof on the client", () => {
const source = readFileSync(path.join(routeDir, "domain.tsx"), "utf8");
expect(source).toContain("const screenVm = fetcher.data?.vm ?? vm;");
expect(source).toContain("transientClaimProof: result.transientClaimProof ?? null");
expect(source).not.toContain("mergeTransientClaimProof");
expect(source).not.toContain("setTransientProof");
expect(source).not.toContain("useMemo(");
expect(source).not.toContain("useEffect(");
});
});
@@ -0,0 +1,519 @@
import { useRef } from "react";
import { redirect, type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, useFetcher, useLoaderData } from "react-router";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import {
bindPortalDomainCheckoutCatalog,
type PortalDomainAdminActions,
type PortalDomainAdminVM,
} from "@hivegrid/view-models";
import { PortalDomainAdminInterimPage } from "~/components/screens/customer-portal/PortalDomainAdminInterimPage";
import ServerError from "~/components/ui/errors/ServerError";
import { getTranslations } from "~/locale/i18next.server";
import {
cancelRecurringProductAcquisition,
productAcquisitionReturnIdPlaceholder,
ProductAcquisitionError,
} from "~/services/billing/product-acquisition.server";
import { requirePortalAdminWorkspaceContext } from "~/services/customer-portal/portal-admin-context.server";
import { isPortalCustomDomainRuntimeEnabled } from "~/services/customer-portal/portal-custom-domain-runtime.server";
import {
checkPortalDomainAdminRateLimit,
portalDomainAdminRateLimitActions,
type PortalDomainAdminRateLimitAction,
} from "~/services/customer-portal/portal-domain-admin-rate-limit.server";
import {
getCustomerPortalCommercialEligibility,
getCustomerPortalCheckoutCatalog,
PortalDomainCommercialError,
startCustomerPortalMonthlyCheckout,
startPortalDomainSetupCheckout,
} from "~/services/customer-portal/portal-domain-commercial.server";
import {
activatePortalDomainSwitch,
claimPortalCustomDomain,
loadPortalDomainAdminVM,
PortalDomainError,
reconcilePortalDomainEntitlement,
reissuePortalDomainProof,
removePortalCustomDomain,
retryPortalCustomDomain,
switchPortalCustomDomainClaim,
verifyPortalCustomDomainDns,
} from "~/services/customer-portal/portal-domain.server";
import { absolutePublicAppPath } from "~/utils/app/CrossHostUrls";
import { apiUrl } from "~/utils/app/CanonicalUrlUtils";
import { appendCSRFToken } from "~/utils/csrf";
import { getTenant } from "~/utils/db/tenants.db.server";
import { getUser } from "~/utils/db/users.db.server";
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
import { validateCSRFToken } from "~/utils/session.server";
export type PortalDomainAdminActionData = {
readonly vm: PortalDomainAdminVM;
readonly ok?: true;
readonly messageKey?: string;
readonly errorKey?: string;
readonly retryAfterSeconds?: number;
};
type LoaderData = {
readonly title: string;
readonly vm: PortalDomainAdminVM;
};
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
const ctx = await requirePortalAdminWorkspaceContext(request, params, "portal.admin");
requirePortalCustomDomainRuntime();
const { t } = await getTranslations(request);
const [billing, config] = await Promise.all([getTenantBillingReadOnlyState(ctx.tenantId), Promise.resolve(loadRequiredWebConfig())]);
const standardPortalOrigin = `https://${config.routing.portalAppHost}`;
const vm = await loadCatalogBoundPortalDomainAdminVM({
tenantId: ctx.tenantId,
standardPortalOrigin,
frozen: billing.readOnly,
});
return Response.json({ title: `${t("customerPortal.domain.title")} | ${config.appName}`, vm } satisfies LoaderData);
}
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
// Preserve the non-disclosing permission contract before any mutation-specific
// validation can reveal that this route exists to an unauthorized member.
const ctx = await requirePortalAdminWorkspaceContext(request, params, "portal.admin");
requirePortalCustomDomainRuntime();
const form = await request.formData();
await validateCSRFToken(request, { formData: form });
let intent: PortalDomainAdminRateLimitAction;
try {
intent = domainIntent(form);
} catch {
return domainActionResponse(ctx, loadRequiredWebConfig(), {
errorKey: "customerPortal.domain.errors.invalidInput",
status: 400,
});
}
const config = loadRequiredWebConfig();
const rateLimit = await checkPortalDomainAdminRateLimit({
tenantId: ctx.tenantId,
userId: ctx.userId,
action: intent,
secret: config.cryptoSecret ?? "",
});
if (!rateLimit.allowed) {
return domainActionResponse(ctx, config, {
errorKey: "customerPortal.domain.errors.rateLimited",
retryAfterSeconds: rateLimit.retryAfterSeconds,
status: 429,
headers: { "Retry-After": String(rateLimit.retryAfterSeconds) },
});
}
const billing = await getTenantBillingReadOnlyState(ctx.tenantId);
if (billing.readOnly) {
return domainActionResponse(ctx, config, {
errorKey: "customerPortal.domain.errors.readOnly",
frozen: true,
status: 423,
});
}
try {
if (intent === "buy-portal") {
const [catalog, checkoutContext] = await Promise.all([
getCustomerPortalCheckoutCatalog({ tenantId: ctx.tenantId }),
loadCheckoutContext(ctx),
]);
const checkout = await startCustomerPortalMonthlyCheckout({
...checkoutContext,
productId: catalog.monthlyAddOn.productId,
priceId: catalog.monthlyAddOn.priceId,
...checkoutUrls(config, ctx.tenantSlug),
});
return checkoutRedirect(checkout.checkoutUrl);
}
if (intent === "cancel-portal") {
const [cancellationContext, eligibility] = await Promise.all([
loadCheckoutContext(ctx),
getCustomerPortalCommercialEligibility({ tenantId: ctx.tenantId }),
]);
if (eligibility.portalSource !== "recurring_add_on" || !eligibility.monthlyAddOnSubscriptionProductId) {
throw new PortalDomainCommercialError("PORTAL_ENTITLEMENT_REQUIRED");
}
await cancelRecurringProductAcquisition({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
tenantSubscriptionProductId: eligibility.monthlyAddOnSubscriptionProductId,
eventData: {
user: { id: ctx.userId, email: cancellationContext.userEmail },
tenant: { id: ctx.tenantId, name: cancellationContext.tenantName },
},
});
return domainActionResponse(ctx, config, {
ok: true,
messageKey: "customerPortal.domain.messages.portalCancelled",
});
}
if (intent === "claim-domain") {
const result = await claimPortalCustomDomain({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
hostname: required(form, "hostname"),
idempotencyKey: required(form, "idempotencyKey"),
});
return domainActionResponse(ctx, config, {
ok: true,
messageKey: "customerPortal.domain.messages.claimed",
transientClaimProof: { claimId: result.claimId, txtRecordValue: result.verification.txtRecordValue },
status: result.replayed ? 200 : 201,
});
}
if (intent === "buy-domain-setup") {
const claimId = required(form, "claimId");
const [catalog, checkoutContext] = await Promise.all([getCustomerPortalCheckoutCatalog({ tenantId: ctx.tenantId }), loadCheckoutContext(ctx)]);
const checkout = await startPortalDomainSetupCheckout({
...checkoutContext,
claimId,
productId: catalog.customDomainSetup.productId,
priceId: catalog.customDomainSetup.priceId,
...checkoutUrls(config, ctx.tenantSlug),
});
return checkoutRedirect(checkout.checkoutUrl);
}
if (intent === "reissue-proof") {
const result = await reissuePortalDomainProof({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
claimId: required(form, "claimId"),
});
return domainActionResponse(ctx, config, {
ok: true,
messageKey: "customerPortal.domain.messages.proofReissued",
transientClaimProof: { claimId: result.claimId, txtRecordValue: result.txtRecordValue },
});
}
if (intent === "verify-dns") {
const claimId = required(form, "claimId");
await reconcilePortalDomainEntitlement({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
claimId,
});
const result = await verifyPortalCustomDomainDns({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
claimId,
});
if (result.renewedProof) {
return domainActionResponse(ctx, config, {
ok: true,
messageKey: "customerPortal.domain.messages.proofRenewed",
transientClaimProof: {
claimId: result.renewedProof.claimId,
txtRecordValue: result.renewedProof.txtRecordValue,
},
});
}
return domainActionResponse(ctx, config, {
ok: true,
messageKey: result.txtVerified && result.cnameVerified ? "customerPortal.domain.messages.dnsVerified" : "customerPortal.domain.messages.dnsPending",
});
}
if (intent === "retry-domain") {
await retryPortalCustomDomain({ tenantId: ctx.tenantId, actorUserId: ctx.userId });
return domainActionResponse(ctx, config, { ok: true, messageKey: "customerPortal.domain.messages.retryRequested", status: 202 });
}
if (intent === "remove-domain") {
await removePortalCustomDomain({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
reason: optional(form, "reason") ?? undefined,
});
return domainActionResponse(ctx, config, { ok: true, messageKey: "customerPortal.domain.messages.removalRequested", status: 202 });
}
if (intent === "switch-domain") {
const result = await switchPortalCustomDomainClaim({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
hostname: required(form, "hostname"),
idempotencyKey: required(form, "idempotencyKey"),
});
return domainActionResponse(ctx, config, {
ok: true,
messageKey: "customerPortal.domain.messages.switchClaimed",
transientClaimProof: { claimId: result.claimId, txtRecordValue: result.verification.txtRecordValue },
status: result.replayed ? 200 : 201,
});
}
if (intent === "activate-switch") {
await activatePortalDomainSwitch({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
claimId: required(form, "claimId"),
});
return domainActionResponse(ctx, config, { ok: true, messageKey: "customerPortal.domain.messages.switchActivated", status: 202 });
}
throw new PortalDomainError("IDEMPOTENCY_KEY_INVALID", 400);
} catch (error) {
if (error instanceof Response) throw error;
const mapped = mapDomainActionError(error);
if (mapped) return domainActionResponse(ctx, config, { errorKey: mapped.errorKey, status: mapped.status });
throw error;
}
}
function requirePortalCustomDomainRuntime(): void {
if (!isPortalCustomDomainRuntimeEnabled()) throw new Response(null, { status: 404 });
}
export default function PortalDomainAdminRoute(): React.JSX.Element {
const { vm } = useLoaderData<LoaderData>();
const fetcher = useFetcher<PortalDomainAdminActionData>();
const idempotencyKeys = useRef(new Map<string, string>());
const screenVm = fetcher.data?.vm ?? vm;
const submit = (intent: PortalDomainAdminRateLimitAction, values: Readonly<Record<string, string | boolean>> = {}) => {
const form = new FormData();
form.set("intent", intent);
for (const [key, value] of Object.entries(values)) form.set(key, String(value));
fetcher.submit(appendCSRFToken(form), { method: "post" });
};
const claimId = screenVm.status === "ready" ? (screenVm.data.pendingSwitch?.claimId ?? screenVm.data.domain?.claimId ?? "") : "";
const idempotencyKey = (mode: "claim" | "switch", hostname: string): string => {
const mapKey = `${mode}:${hostname.trim().toLowerCase()}`;
const existing = idempotencyKeys.current.get(mapKey);
if (existing) return existing;
const created = `portal-domain:${globalThis.crypto.randomUUID()}`;
idempotencyKeys.current.set(mapKey, created);
return created;
};
const actions: PortalDomainAdminActions = {
onBuyPortal: () => submit("buy-portal"),
onCancelPortal: () => submit("cancel-portal"),
onClaimDomain: (hostname) => submit("claim-domain", { hostname, idempotencyKey: idempotencyKey("claim", hostname) }),
onBuyDomainSetup: () => submit("buy-domain-setup", { claimId }),
onReissueProof: () => submit("reissue-proof", { claimId }),
onVerifyDns: () => submit("verify-dns", { claimId }),
onRetry: () => submit("retry-domain"),
onRemove: () => submit("remove-domain"),
onSwitch: (hostname) => submit("switch-domain", { hostname, idempotencyKey: idempotencyKey("switch", hostname) }),
onActivateSwitch: (pendingClaimId) => submit("activate-switch", { claimId: pendingClaimId }),
};
return (
<PortalDomainAdminInterimPage
vm={screenVm}
actions={actions}
embedded
busy={fetcher.state !== "idle"}
messageKey={fetcher.data?.ok ? (fetcher.data.messageKey ?? null) : null}
errorKey={fetcher.data?.errorKey ?? null}
/>
);
}
async function loadCheckoutContext(ctx: { readonly tenantId: string; readonly userId: string }): Promise<{
readonly tenantId: string;
readonly tenantName: string;
readonly userId: string;
readonly userEmail: string;
readonly userName: string;
}> {
const [user, tenant] = await runWithRlsContext({ tenantId: ctx.tenantId, userId: ctx.userId }, () =>
Promise.all([getUser(ctx.userId), getTenant(ctx.tenantId)])
);
if (!user || !tenant) throw new PortalDomainError("PORTAL_NOT_FOUND", 404);
return {
tenantId: ctx.tenantId,
tenantName: tenant.name,
userId: user.id,
userEmail: user.email,
userName: [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email,
};
}
function checkoutUrls(
config: ReturnType<typeof loadRequiredWebConfig>,
tenantSlug: string
): {
readonly redirectUrl: string;
readonly webhookUrl: string;
} {
return {
redirectUrl: absolutePublicAppPath(
config.routing,
`/subscribe/${encodeURIComponent(tenantSlug)}/product/${productAcquisitionReturnIdPlaceholder}/success?return=customer-portal-domain`
),
webhookUrl: apiUrl({
rootDomain: config.routing.apiHost,
protocol: config.routing.protocol,
path: "billing/mollie/webhooks",
version: "v1",
mode: "host-aware",
}),
};
}
function checkoutRedirect(checkoutUrl: string | null): Response {
if (!checkoutUrl) throw new ProductAcquisitionError("CHECKOUT_URL_MISSING");
return redirect(checkoutUrl);
}
function domainIntent(form: FormData): PortalDomainAdminRateLimitAction {
const intent = required(form, "intent");
if (!portalDomainAdminRateLimitActions.includes(intent as PortalDomainAdminRateLimitAction)) {
throw new PortalDomainError("IDEMPOTENCY_KEY_INVALID", 400);
}
return intent as PortalDomainAdminRateLimitAction;
}
async function domainActionResponse(
ctx: { readonly tenantId: string },
config: ReturnType<typeof loadRequiredWebConfig>,
result: {
readonly ok?: true;
readonly messageKey?: string;
readonly errorKey?: string;
readonly retryAfterSeconds?: number;
readonly transientClaimProof?: { readonly claimId: string; readonly txtRecordValue: string };
readonly frozen?: boolean;
readonly status?: number;
readonly headers?: HeadersInit;
}
): Promise<Response> {
const frozen = result.frozen ?? (await getTenantBillingReadOnlyState(ctx.tenantId)).readOnly;
const vm = await loadCatalogBoundPortalDomainAdminVM({
tenantId: ctx.tenantId,
standardPortalOrigin: `https://${config.routing.portalAppHost}`,
frozen,
transientClaimProof: result.transientClaimProof ?? null,
});
return Response.json(
{
vm,
...(result.ok ? { ok: true as const } : {}),
...(result.messageKey ? { messageKey: result.messageKey } : {}),
...(result.errorKey ? { errorKey: result.errorKey } : {}),
...(result.retryAfterSeconds === undefined ? {} : { retryAfterSeconds: result.retryAfterSeconds }),
} satisfies PortalDomainAdminActionData,
{ status: result.status ?? 200, headers: result.headers }
);
}
async function loadCatalogBoundPortalDomainAdminVM(input: {
readonly tenantId: string;
readonly standardPortalOrigin: string;
readonly frozen: boolean;
readonly transientClaimProof?: { readonly claimId: string; readonly txtRecordValue: string } | null;
}): Promise<PortalDomainAdminVM> {
const [vm, catalog] = await Promise.all([
loadPortalDomainAdminVM(input),
loadPortalDomainCheckoutCatalog(input.tenantId),
]);
return bindPortalDomainCheckoutCatalog(vm, catalog);
}
async function loadPortalDomainCheckoutCatalog(
tenantId: string,
): Promise<Awaited<ReturnType<typeof getCustomerPortalCheckoutCatalog>> | null> {
try {
return await getCustomerPortalCheckoutCatalog({ tenantId });
} catch (error) {
if (error instanceof PortalDomainCommercialError) return null;
throw error;
}
}
function required(form: FormData, key: string): string {
const value = form.get(key);
if (typeof value !== "string" || !value.trim()) throw new PortalDomainError("IDEMPOTENCY_KEY_INVALID", 400);
return value.trim();
}
function optional(form: FormData, key: string): string | null {
const value = form.get(key);
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function mapDomainActionError(error: unknown): { readonly errorKey: string; readonly status: number } | null {
if (error instanceof PortalDomainError) {
return { errorKey: portalDomainErrorKey[error.code], status: error.status };
}
if (error instanceof PortalDomainCommercialError) {
return { errorKey: commercialErrorKey[error.code], status: error.code === "CLAIM_NOT_FOUND" ? 404 : 409 };
}
if (error instanceof ProductAcquisitionError) {
return {
errorKey: acquisitionErrorKey[error.code],
status: error.code === "PROVIDER_CONFIGURATION_MISSING" || error.code === "PROVIDER_FAILED" ? 503 : 409,
};
}
return null;
}
const portalDomainErrorKey: Record<PortalDomainError["code"], string> = {
PORTAL_NOT_FOUND: "customerPortal.domain.errors.notFound",
PORTAL_NOT_PUBLISHED: "customerPortal.domain.errors.portalNotPublished",
PORTAL_ENTITLEMENT_REQUIRED: "customerPortal.domain.errors.entitlementRequired",
DOMAIN_SETUP_PAYMENT_REQUIRED: "customerPortal.domain.errors.setupPaymentRequired",
HOSTNAME_UNAVAILABLE: "customerPortal.domain.errors.hostnameUnavailable",
DOMAIN_ALREADY_CONFIGURED: "customerPortal.domain.errors.domainAlreadyConfigured",
CLAIM_NOT_FOUND: "customerPortal.domain.errors.claimNotFound",
DOMAIN_NOT_FOUND: "customerPortal.domain.errors.domainNotFound",
DNS_PROOF_INCOMPLETE: "customerPortal.domain.errors.dnsProofIncomplete",
DNS_LOOKUP_FAILED: "customerPortal.domain.errors.dnsLookupFailed",
DOMAIN_BUSY: "customerPortal.domain.errors.domainBusy",
DOMAIN_SWITCH_NOT_READY: "customerPortal.domain.errors.switchNotReady",
KILL_SWITCH_ENABLED: "customerPortal.domain.errors.killSwitchEnabled",
IDEMPOTENCY_KEY_INVALID: "customerPortal.domain.errors.invalidInput",
DOMAIN_PROOF_CONFIGURATION_INVALID: "customerPortal.domain.errors.proofConfigurationInvalid",
};
const commercialErrorKey: Record<PortalDomainCommercialError["code"], string> = {
PORTAL_ENTITLEMENT_REQUIRED: "customerPortal.domain.errors.entitlementRequired",
CLAIM_NOT_FOUND: "customerPortal.domain.errors.claimNotFound",
OWNERSHIP_PROOF_REQUIRED: "customerPortal.domain.errors.ownershipProofRequired",
PRODUCT_NOT_FOUND: "customerPortal.domain.errors.productUnavailable",
PRODUCT_CODE_MISMATCH: "customerPortal.domain.errors.productUnavailable",
CONTRACT_SETUP_ALREADY_CONSUMED: "customerPortal.domain.errors.contractSetupConsumed",
CHECKOUT_CATALOG_DRIFT: "customerPortal.domain.errors.checkoutCatalogDrift",
};
const acquisitionErrorKey: Record<ProductAcquisitionError["code"], string> = {
PROVIDER_CONFIGURATION_MISSING: "customerPortal.domain.errors.checkoutUnavailable",
PRODUCT_NOT_FOUND: "customerPortal.domain.errors.productUnavailable",
PRODUCT_NOT_PURCHASABLE: "customerPortal.domain.errors.productUnavailable",
PRODUCT_KIND_INVALID: "customerPortal.domain.errors.productUnavailable",
PRICE_NOT_FOUND: "customerPortal.domain.errors.productUnavailable",
PRICE_KIND_INVALID: "customerPortal.domain.errors.productUnavailable",
BASE_SUBSCRIPTION_REQUIRED: "customerPortal.domain.errors.baseSubscriptionRequired",
SCOPE_KEY_INVALID: "customerPortal.domain.errors.invalidInput",
IDEMPOTENCY_CONFLICT: "customerPortal.domain.errors.checkoutConflict",
PROVIDER_FAILED: "customerPortal.domain.errors.checkoutUnavailable",
CHECKOUT_URL_MISSING: "customerPortal.domain.errors.checkoutUnavailable",
ACQUISITION_NOT_FOUND: "customerPortal.domain.errors.checkoutConflict",
PAYMENT_NOT_FOUND: "customerPortal.domain.errors.checkoutConflict",
PAYMENT_EXPIRY_MISSING: "customerPortal.domain.errors.checkoutUnavailable",
PAYMENT_METADATA_MISMATCH: "customerPortal.domain.errors.checkoutConflict",
PAYMENT_METHOD_INVALID: "customerPortal.domain.errors.invalidInput",
PAYMENT_METHOD_UNAVAILABLE: "customerPortal.domain.errors.checkoutUnavailable",
RESERVATION_EXPIRED: "customerPortal.domain.errors.checkoutConflict",
CONTRACT_REFERENCE_REQUIRED: "customerPortal.domain.errors.checkoutConflict",
};
export function ErrorBoundary(): React.JSX.Element {
return <ServerError />;
}
export const handle = { breadcrumbKey: "customerPortal.domain.title" };
@@ -0,0 +1,43 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
const repoRoot = process.cwd();
const routePath = "apps/web/app/routes/app.$tenant/settings/customer-portal/email-templates.tsx";
const screenPath = "apps/web/app/components/screens/customer-portal/CustomerPortalInterimPages.tsx";
// AK-SET-01: reachability moved from the settings rail into the portal hub's
// tab bar, so the contract checks the hub layout instead.
const settingsPath = "apps/web/app/routes/app.$tenant/settings/customer-portal.tsx";
function translations(locale: "de" | "en") {
const value = JSON.parse(fs.readFileSync(path.join(repoRoot, "apps/web/public/locales", locale, "translations.json"), "utf8")) as {
customerPortal: { emailTemplates: Record<string, unknown> };
};
return value.customerPortal.emailTemplates;
}
describe("customer portal email template settings i18n contract", () => {
it("keeps the German and English template dictionaries in parity", () => {
expect(Object.keys(translations("de")).sort()).toEqual(Object.keys(translations("en")).sort());
});
it("uses semantic keys for route title, navigation, breadcrumb, and screen chrome", () => {
const source = [routePath, screenPath, settingsPath].map((file) => fs.readFileSync(path.join(repoRoot, file), "utf8")).join("\n");
for (const key of [
"customerPortal.emailTemplates.title",
"customerPortal.emailTemplates.subtitle",
"customerPortal.emailTemplates.variables.title",
"customerPortal.emailTemplates.subject",
"customerPortal.emailTemplates.body",
"customerPortal.emailTemplates.preview.title",
"customerPortal.emailTemplates.save",
"customerPortal.emailTemplates.empty.title",
"customerPortal.emailTemplates.empty.body",
]) {
expect(source).toContain(key);
}
expect(source).toContain('breadcrumbKey: "customerPortal.emailTemplates.title"');
expect(source).toContain('"settings/customer-portal/email-templates"');
});
});
@@ -0,0 +1,141 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
requireContext: vi.fn(),
getTranslations: vi.fn(),
validateCSRF: vi.fn(),
loadAdmin: vi.fn(),
saveTemplate: vi.fn(),
}));
vi.mock("~/utils/session.server", () => ({
validateCSRFToken: (...args: unknown[]) => mocks.validateCSRF(...args),
}));
vi.mock("~/services/customer-portal/portal-admin-context.server", () => ({
requirePortalAdminWorkspaceContext: (...args: unknown[]) => mocks.requireContext(...args),
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: (...args: unknown[]) => mocks.getTranslations(...args),
}));
vi.mock("~/services/customer-portal/portal-email-template-admin.server", () => ({
PortalEmailTemplateAdminError: class PortalEmailTemplateAdminError extends Error {
status = 400;
messageKey = "customerPortal.states.error.body";
},
loadPortalEmailTemplateAdmin: (...args: unknown[]) => mocks.loadAdmin(...args),
savePortalEmailTemplate: (...args: unknown[]) => mocks.saveTemplate(...args),
}));
vi.mock("~/components/screens/customer-portal/CustomerPortalInterimPages", () => ({
PortalEmailTemplateEditorPage: () => null,
}));
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
import { action, handle, loader } from "./email-templates";
const routeParams = { tenant: "acme" };
function loaderArgs(request = new Request("https://app.example.test/acme/settings/customer-portal/email-templates")) {
return { request, params: routeParams, context: {}, unstable_pattern: "app.$tenant/settings/customer-portal/email-templates" } as never;
}
function actionRequest(fields: Record<string, string>) {
return new Request("https://app.example.test/acme/settings/customer-portal/email-templates", {
method: "POST",
body: new URLSearchParams(fields),
});
}
describe("customer portal email template settings route", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.requireContext.mockResolvedValue({ tenantId: "tenant_1", userId: "user_1", permissions: ["portal.admin"], tenantSlug: "acme" });
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key, locale: "de" });
mocks.loadAdmin.mockResolvedValue({
portalId: "portal_1",
frozen: false,
stages: [{ id: "stage_1", label: "Angebot", visible: true }],
templates: [{ id: "template_1", stageId: "stage_1", subject: "Status", body: "Hallo", active: true }],
});
mocks.saveTemplate.mockResolvedValue({ template: { id: "template_1" } });
});
it("builds and returns the admin VM for a permitted workspace admin", async () => {
const response = await loader(loaderArgs());
const data = (await response.json()) as { title: string; vm: { status: string; data: { canManage: boolean } } };
expect(response.status).toBe(200);
expect(data.title).toContain("customerPortal.emailTemplates.title");
expect(data.vm).toMatchObject({ status: "ready", data: { canManage: true } });
expect(mocks.loadAdmin).toHaveBeenCalledWith({ tenantId: "tenant_1", locale: "de" });
});
it("returns 404 and skips tenant data when the read permission is missing", async () => {
mocks.requireContext.mockRejectedValue(new Response(null, { status: 404 }));
await expect(loader(loaderArgs())).rejects.toMatchObject({ status: 404 });
expect(mocks.loadAdmin).not.toHaveBeenCalled();
});
it("returns 404 for a user without an active workspace membership", async () => {
mocks.requireContext.mockRejectedValue(new Response(null, { status: 404 }));
await expect(loader(loaderArgs())).rejects.toMatchObject({ status: 404 });
expect(mocks.loadAdmin).not.toHaveBeenCalled();
});
it("saves a localized stage template after permission and CSRF checks", async () => {
const request = actionRequest({
intent: "save-template",
stageId: "stage_1",
subject: "Neuer Status",
body: "Hallo Kunde",
active: "true",
csrf: "csrf-token",
});
const response = await action(loaderArgs(request));
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual({
intent: "save-template",
ok: true,
stageId: "stage_1",
messageKey: "customerPortal.emailTemplates.feedback.saved",
});
expect(mocks.validateCSRF).toHaveBeenCalledWith(request, { formData: expect.anything() });
expect(mocks.validateCSRF.mock.calls[0]?.[1].formData.get("csrf")).toBe("csrf-token");
expect(mocks.saveTemplate).toHaveBeenCalledWith({
tenantId: "tenant_1",
actorUserId: "user_1",
stageId: "stage_1",
locale: "de",
subject: "Neuer Status",
body: "Hallo Kunde",
active: true,
});
});
it("returns 404 before CSRF or mutation when update permission is missing", async () => {
mocks.requireContext.mockRejectedValue(new Response(null, { status: 404 }));
const request = actionRequest({ intent: "save-template", stageId: "stage_1", subject: "Status", body: "Hallo", active: "true" });
await expect(action(loaderArgs(request))).rejects.toMatchObject({ status: 404 });
expect(mocks.validateCSRF).not.toHaveBeenCalled();
expect(mocks.saveTemplate).not.toHaveBeenCalled();
});
it("rejects malformed save payloads without calling the domain service", async () => {
const request = actionRequest({ intent: "save-template", stageId: "stage_1", subject: "Status", body: "Hallo", active: "yes" });
const response = await action(loaderArgs(request));
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({
intent: "save-template",
error: "customerPortal.states.error.body",
});
expect(mocks.saveTemplate).not.toHaveBeenCalled();
});
it("publishes the semantic breadcrumb key", () => {
expect(handle).toEqual({ breadcrumbKey: "customerPortal.emailTemplates.title" });
});
});
@@ -0,0 +1,138 @@
import { CatalogError } from "@hivegrid/foundation";
import { buildPortalEmailTemplateAdminVM, type PortalEmailTemplateAdminVM } from "@hivegrid/view-models";
import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, useFetcher, useLoaderData, useRevalidator } from "react-router";
import { PortalEmailTemplateEditorPage, type PortalEmailTemplateDraft } from "~/components/screens/customer-portal/CustomerPortalInterimPages";
import ServerError from "~/components/ui/errors/ServerError";
import { useSaveToast } from "~/hooks/use-save-toast";
import { getTranslations } from "~/locale/i18next.server";
import {
loadPortalEmailTemplateAdmin,
PortalEmailTemplateAdminError,
savePortalEmailTemplate,
} from "~/services/customer-portal/portal-email-template-admin.server";
import { requirePortalAdminWorkspaceContext } from "~/services/customer-portal/portal-admin-context.server";
import { appendCSRFToken } from "~/utils/csrf";
import { validateCSRFToken } from "~/utils/session.server";
const VIEW_PERMISSION = "portal.admin";
const MANAGE_PERMISSION = "portal.admin";
type LoaderData = {
readonly title: string;
readonly vm: PortalEmailTemplateAdminVM;
};
type ActionData = {
readonly intent?: string;
readonly ok?: true;
readonly messageKey?: string;
readonly stageId?: string;
readonly error?: string;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const [{ t, locale }, ctx] = await Promise.all([getTranslations(request), requirePortalAdminWorkspaceContext(request, params, VIEW_PERMISSION)]);
const data = await loadPortalEmailTemplateAdmin({ tenantId: ctx.tenantId, locale });
const vm = buildPortalEmailTemplateAdminVM({
canManage: ctx.permissions.includes(MANAGE_PERMISSION),
frozen: data.frozen,
preview: {
customerName: t("customerPortal.emailTemplates.preview.customerName"),
projectName: t("customerPortal.emailTemplates.preview.projectName"),
projectNumber: t("customerPortal.emailTemplates.preview.projectNumber"),
portalUrl: t("customerPortal.emailTemplates.preview.portalUrl"),
},
stages: data.stages,
templates: data.templates,
});
return Response.json({
title: `${t("customerPortal.emailTemplates.title")} | ${process.env.APP_NAME}`,
vm,
} satisfies LoaderData);
};
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await requirePortalAdminWorkspaceContext(request, params, MANAGE_PERMISSION);
const formData = await request.formData();
await validateCSRFToken(request, { formData });
const { locale } = await getTranslations(request);
const intent = formValue(formData, "intent");
const stageId = formValue(formData, "stageId");
const subject = formValue(formData, "subject");
const body = formValue(formData, "body");
const activeValue = formValue(formData, "active");
if (intent !== "save-template" || !stageId || subject === null || body === null || (activeValue !== "true" && activeValue !== "false")) {
return invalidRequestResponse(intent ?? undefined);
}
try {
await savePortalEmailTemplate({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
stageId,
locale,
subject,
body,
active: activeValue === "true",
});
return Response.json({
intent,
ok: true,
stageId,
messageKey: "customerPortal.emailTemplates.feedback.saved",
} satisfies ActionData);
} catch (error) {
return actionErrorResponse(error, intent);
}
};
export default function PortalEmailTemplateSettingsRoute(): React.JSX.Element {
const { vm } = useLoaderData<LoaderData>();
const fetcher = useFetcher<ActionData>();
const revalidator = useRevalidator();
const savingStageId = fetcher.state === "idle" ? null : String(fetcher.formData?.get("stageId") ?? "") || null;
useSaveToast(fetcher.data);
const onSave = (draft: PortalEmailTemplateDraft) => {
const formData = new FormData();
formData.set("intent", "save-template");
formData.set("stageId", draft.stageId);
formData.set("subject", draft.subject);
formData.set("body", draft.body);
formData.set("active", String(draft.active));
fetcher.submit(appendCSRFToken(formData), { method: "post" });
};
return <PortalEmailTemplateEditorPage vm={vm} savingStageId={savingStageId} embedded actions={{ onSave, onRetry: () => revalidator.revalidate() }} />;
}
function formValue(formData: FormData, key: string): string | null {
const value = formData.get(key);
return typeof value === "string" ? value.trim() : null;
}
function invalidRequestResponse(intent?: string): Response {
return Response.json({ intent, error: "customerPortal.states.error.body" } satisfies ActionData, { status: 400 });
}
function actionErrorResponse(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 PortalEmailTemplateAdminError) {
return Response.json({ intent, error: error.messageKey } satisfies ActionData, { status: error.status });
}
throw error;
}
export function ErrorBoundary(): React.JSX.Element {
return <ServerError />;
}
export const handle = {
breadcrumbKey: "customerPortal.emailTemplates.title",
};
@@ -0,0 +1,373 @@
import { render, screen } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => {
class PortalAdminError extends Error {
constructor(
readonly messageKey: string,
readonly status: number
) {
super(messageKey);
}
}
return {
PortalAdminError,
getTranslations: vi.fn(),
requireContext: vi.fn(),
requireMembership: vi.fn(),
requirePermission: vi.fn(),
loadSnapshot: vi.fn(),
saveConfiguration: vi.fn(),
saveBranding: vi.fn(),
saveStage: vi.fn(),
saveAutoRelease: vi.fn(),
inviteUser: vi.fn(),
resendInvitation: vi.fn(),
setAccess: vi.fn(),
disableUser: vi.fn(),
updateInbox: vi.fn(),
validateCsrf: vi.fn(),
runtimeEnabled: vi.fn(),
recordInvitationFailure: vi.fn(),
};
});
vi.mock("~/components/screens/customer-portal/CustomerPortalInterimPages", () => ({
PortalAdminPage: () => null,
}));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: mocks.getTranslations }));
vi.mock("~/services/customer-portal/portal-admin-context.server", () => ({
requirePortalAdminWorkspaceContext: mocks.requireContext,
requirePortalAdminWorkspaceMembership: mocks.requireMembership,
requirePortalAdminWorkspacePermission: mocks.requirePermission,
}));
vi.mock("~/services/customer-portal/portal-admin.server", () => ({
PortalAdminError: mocks.PortalAdminError,
loadPortalAdminSnapshot: mocks.loadSnapshot,
savePortalConfiguration: mocks.saveConfiguration,
savePortalBranding: mocks.saveBranding,
setPortalStageVisibility: mocks.saveStage,
setPortalDocumentAutoReleaseRule: mocks.saveAutoRelease,
invitePortalUser: mocks.inviteUser,
resendPortalUserInvitation: mocks.resendInvitation,
setPortalProjectAccess: mocks.setAccess,
disablePortalUser: mocks.disableUser,
updatePortalInbox: mocks.updateInbox,
}));
vi.mock("~/services/customer-portal/portal-custom-domain-runtime.server", () => ({
isPortalCustomDomainRuntimeEnabled: mocks.runtimeEnabled,
}));
vi.mock("~/services/customer-portal/portal-invitation.server", async (importOriginal) => {
const original = await importOriginal<typeof import("~/services/customer-portal/portal-invitation.server")>();
return { ...original, recordPortalInvitationFailure: mocks.recordInvitationFailure };
});
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCsrf }));
import CustomerPortalAdminRoute, { action, loader } from "./index";
const context = {
tenantId: "tenant-a",
tenantSlug: "acme",
userId: "user-a",
permissions: [
"portal.read",
"portal.manage_users",
"portal.manage_access",
"portal.delete_user",
"portal.activity.read",
"portal.activity.manage",
"portal.admin",
],
};
const snapshot = {
frozen: false,
configuration: {
published: true,
lifecycleMode: "project",
projectAutoCloseMonths: 12,
inactivityDisableMonths: 24,
uploadMaxFiles: 10,
uploadMaxFileSizeBytes: 50 * 1024 * 1024,
enabledProjectTypes: ["installation"],
statusEmailsEnabled: true,
imprintUrl: "https://example.test/impressum",
privacyUrl: "https://example.test/datenschutz",
termsUrl: "https://example.test/agb",
legalLinksComplete: true,
visibleStageCount: 1,
autoReleaseRuleCount: 1,
emailTemplateHref: "/acme/settings/customer-portal/email-templates",
},
stages: [{ stageId: "stage-a", stageLabel: "Montage", visible: true, customerLabel: "Montage vor Ort" }],
autoReleaseRules: [{ id: "rule-a", projectType: "installation", documentType: "invoice", enabled: true }],
projectOptions: [{ id: "project-a", label: "P-1001 · Heizung", projectType: "installation" }],
users: [
{
id: "portal-subcontractor",
kind: "subcontractor",
name: "Sven Subunternehmen",
email: "sven@example.test",
status: "active",
canResendInvitation: false,
projectCount: 1,
lastActivityAt: "2026-07-16T09:00:00.000Z",
},
],
accessRows: [],
inbox: [
{
id: "inbox-upload",
kind: "upload",
status: "open",
priority: 300,
titleKey: "customerPortal.admin.inbox.kinds.upload",
portalUserLabel: "Karla Kunde",
projectLabel: "P-1001 · Heizung",
bundledCount: 2,
occurredAt: "2026-07-16T09:00:00.000Z",
expiresAt: "2099-07-23T09:00:00.000Z",
ownerLabel: null,
},
],
};
function args(request: Request) {
return { request, params: { tenant: "acme" }, context: {} } as never;
}
function post(values: Readonly<Record<string, string>>): Request {
return new Request("https://app.example.test/acme/settings/customer-portal", {
method: "POST",
body: new URLSearchParams(values),
});
}
describe("workspace customer portal administration route", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
mocks.requireContext.mockResolvedValue(context);
mocks.requireMembership.mockResolvedValue(context);
mocks.requirePermission.mockImplementation((membership) => membership);
mocks.loadSnapshot.mockResolvedValue(snapshot);
mocks.validateCsrf.mockResolvedValue(undefined);
mocks.saveConfiguration.mockResolvedValue(undefined);
mocks.saveBranding.mockResolvedValue(undefined);
mocks.runtimeEnabled.mockReturnValue(true);
mocks.recordInvitationFailure.mockResolvedValue(undefined);
});
it("renders nested customer-portal child routes through the parent outlet", () => {
render(
<MemoryRouter initialEntries={["/acme/settings/customer-portal/domain"]}>
<Routes>
<Route path="/:tenant/settings/customer-portal" element={<CustomerPortalAdminRoute />}>
<Route path="domain" element={<span data-testid="portal-domain-child">domain child</span>} />
</Route>
</Routes>
</MemoryRouter>
);
expect(screen.getByTestId("portal-domain-child").textContent).toBe("domain child");
});
it("builds the admin VM with subcontractor, access, configuration and persistent inbox data", async () => {
const response = await loader(args(new Request("https://app.example.test/acme/settings/customer-portal")));
const data = (await response.json()) as {
vm: { status: string; data: { users: Array<{ kind: string }>; inbox: Array<{ kind: string }>; configuration: { published: boolean } } };
};
expect(mocks.requireContext).toHaveBeenCalledWith(expect.any(Request), { tenant: "acme" }, "portal.read");
expect(data.vm.status).toBe("ready");
expect(data.vm.data.users[0]?.kind).toBe("subcontractor");
expect(data.vm.data.inbox[0]?.kind).toBe("upload");
expect(data.vm.data.configuration.published).toBe(true);
expect((data as typeof data & { customDomainRuntimeEnabled: boolean }).customDomainRuntimeEnabled).toBe(true);
});
it("keeps the custom-domain admin link out of loader data when its runtime is disabled", async () => {
mocks.runtimeEnabled.mockReturnValueOnce(false);
const response = await loader(args(new Request("https://app.example.test/acme/settings/customer-portal")));
const data = (await response.json()) as { customDomainRuntimeEnabled: boolean };
expect(data.customDomainRuntimeEnabled).toBe(false);
expect(mocks.runtimeEnabled).toHaveBeenCalledOnce();
});
it("does not serialize protected portal-user or activity data for a read-only role", async () => {
mocks.requireContext.mockResolvedValueOnce({ ...context, permissions: ["portal.read"] });
const response = await loader(args(new Request("https://app.example.test/acme/settings/customer-portal")));
const payload = (await response.json()) as {
vm: { status: string; data: { users: unknown[]; accessRows: unknown[]; projectOptions: unknown[]; inbox: unknown[] } };
};
expect(payload.vm).toMatchObject({
status: "ready",
data: { users: [], accessRows: [], projectOptions: [], inbox: [] },
});
expect(JSON.stringify(payload)).not.toContain("sven@example.test");
expect(JSON.stringify(payload)).not.toContain("Karla Kunde");
});
it("requires portal.admin and forwards the complete activation-gated configuration", async () => {
const request = post({
intent: "save-configuration",
lifecycleMode: "project",
projectAutoCloseMonths: "12",
inactivityDisableMonths: "24",
enabledProjectTypes: "installation,maintenance",
uploadMaxFiles: "10",
uploadMaxFileSizeBytes: String(50 * 1024 * 1024),
statusEmailsEnabled: "true",
imprintUrl: "https://example.test/impressum",
privacyUrl: "https://example.test/datenschutz",
termsUrl: "https://example.test/agb",
publish: "true",
});
const response = await action(args(request));
expect(response.status).toBe(200);
expect(mocks.validateCsrf).toHaveBeenCalledWith(request, {
formData: expect.objectContaining({ get: expect.any(Function) }),
});
expect(mocks.requireMembership).toHaveBeenCalledWith(request, { tenant: "acme" });
expect(mocks.requirePermission).toHaveBeenCalledWith(context, "portal.admin");
expect(mocks.saveConfiguration).toHaveBeenCalledWith({
tenantId: "tenant-a",
actorUserId: "user-a",
lifecycleMode: "project",
projectAutoCloseMonths: 12,
inactivityDisableMonths: 24,
enabledProjectTypes: ["installation", "maintenance"],
uploadMaxFiles: 10,
uploadMaxFileSizeBytes: 50 * 1024 * 1024,
statusEmailsEnabled: true,
imprintUrl: "https://example.test/impressum",
privacyUrl: "https://example.test/datenschutz",
termsUrl: "https://example.test/agb",
publish: true,
});
});
it("keeps the main-branch branding upload action after the settings-hub split", async () => {
const request = post({
intent: "save-branding",
remove: "false",
content: "data:image/png;base64,AAAA",
declaredMimeType: "image/png",
filename: "logo.png",
});
const response = await action(args(request));
expect(response.status).toBe(200);
expect(mocks.requirePermission).toHaveBeenCalledWith(context, "portal.admin");
expect(mocks.saveBranding).toHaveBeenCalledWith({
tenantId: "tenant-a",
actorUserId: "user-a",
logo: {
content: "data:image/png;base64,AAAA",
declaredMimeType: "image/png",
filename: "logo.png",
},
});
});
it("returns membership failures before CSRF or intent validation", async () => {
const notFound = new Response(null, { status: 404 });
mocks.requireMembership.mockRejectedValueOnce(notFound);
const request = post({});
await expect(action(args(request))).rejects.toBe(notFound);
expect(mocks.requirePermission).not.toHaveBeenCalled();
expect(mocks.validateCsrf).not.toHaveBeenCalled();
expect(mocks.saveConfiguration).not.toHaveBeenCalled();
});
it("requires valid CSRF before auditing a narrow custom-role permission denial", async () => {
const customRoleContext = { ...context, permissions: ["portal.manage_users"] };
const notFound = new Response(null, { status: 404 });
mocks.requireMembership.mockResolvedValueOnce(customRoleContext);
mocks.requirePermission.mockImplementationOnce(() => {
throw notFound;
});
const request = post({ intent: "invite-user" });
await expect(action(args(request))).rejects.toBe(notFound);
expect(mocks.requirePermission).toHaveBeenCalledWith(customRoleContext, "portal.manage_users");
expect(mocks.recordInvitationFailure).toHaveBeenCalledWith({
tenantId: "tenant-a",
actorUserId: "user-a",
operation: "admin_invite",
reason: "permission_denied",
outcome: "blocked",
});
expect(mocks.validateCsrf).toHaveBeenCalledWith(request, {
formData: expect.objectContaining({ get: expect.any(Function) }),
});
expect(mocks.inviteUser).not.toHaveBeenCalled();
});
it("preserves permission 404 without an audit mutation when CSRF is invalid", async () => {
const notFound = new Response(null, { status: 404 });
mocks.requirePermission.mockImplementationOnce(() => {
throw notFound;
});
mocks.validateCsrf.mockRejectedValueOnce(new Error("invalid csrf"));
const request = post({ intent: "invite-user" });
await expect(action(args(request))).rejects.toBe(notFound);
expect(mocks.validateCsrf).toHaveBeenCalledWith(request, {
formData: expect.objectContaining({ get: expect.any(Function) }),
});
expect(mocks.recordInvitationFailure).not.toHaveBeenCalled();
expect(mocks.inviteUser).not.toHaveBeenCalled();
});
it("audits a resend permission denial without serializing the requested portal-user id", async () => {
const notFound = new Response(null, { status: 404 });
mocks.requirePermission.mockImplementationOnce(() => {
throw notFound;
});
const request = post({ intent: "resend-invite", portalUserId: "portal-user-guessed" });
await expect(action(args(request))).rejects.toBe(notFound);
expect(mocks.recordInvitationFailure).toHaveBeenCalledWith({
tenantId: "tenant-a",
actorUserId: "user-a",
operation: "resend_invite",
reason: "permission_denied",
outcome: "blocked",
});
expect(JSON.stringify(mocks.recordInvitationFailure.mock.calls)).not.toContain("portal-user-guessed");
expect(mocks.validateCsrf).toHaveBeenCalledWith(request, {
formData: expect.objectContaining({ get: expect.any(Function) }),
});
expect(mocks.resendInvitation).not.toHaveBeenCalled();
});
it("resends an invitation only through the explicit manage-users intent", async () => {
const request = post({ intent: "resend-invite", portalUserId: "portal-user-invited" });
const response = await action(args(request));
expect(response.status).toBe(200);
expect(mocks.requirePermission).toHaveBeenCalledWith(context, "portal.manage_users");
expect(mocks.validateCsrf).toHaveBeenCalledWith(request, { formData: expect.objectContaining({ get: expect.any(Function) }) });
expect(mocks.resendInvitation).toHaveBeenCalledWith({
tenantId: "tenant-a",
actorUserId: "user-a",
portalUserId: "portal-user-invited",
});
expect(mocks.inviteUser).not.toHaveBeenCalled();
await expect(response.json()).resolves.toEqual({ ok: true, messageKey: "customerPortal.invitation.sent" });
});
});
@@ -0,0 +1,373 @@
import { CatalogError } from "@hivegrid/foundation";
import { buildPortalAdminVM, type PortalAdminVM } from "@hivegrid/view-models";
import {
type ActionFunctionArgs,
type LoaderFunctionArgs,
type MetaFunction,
useFetcher,
useLoaderData,
useNavigate,
useOutlet,
useParams,
} from "react-router";
import {
PortalAdminPage,
type PortalAdminBrandingDraft,
type PortalAdminConfigurationDraft,
type PortalAdminPageActions,
} from "~/components/screens/customer-portal/CustomerPortalInterimPages";
import ServerError from "~/components/ui/errors/ServerError";
import { getTranslations } from "~/locale/i18next.server";
import {
disablePortalUser,
invitePortalUser,
loadPortalAdminSnapshot,
PortalAdminError,
resendPortalUserInvitation,
savePortalBranding,
savePortalConfiguration,
setPortalDocumentAutoReleaseRule,
setPortalProjectAccess,
setPortalStageVisibility,
updatePortalInbox,
} from "~/services/customer-portal/portal-admin.server";
import {
requirePortalAdminWorkspaceContext,
requirePortalAdminWorkspaceMembership,
requirePortalAdminWorkspacePermission,
type PortalAdminWorkspaceContext,
} from "~/services/customer-portal/portal-admin-context.server";
import { PortalBrandingValidationError } from "~/services/customer-portal/portal-branding.server";
import { isPortalCustomDomainRuntimeEnabled } from "~/services/customer-portal/portal-custom-domain-runtime.server";
import { recordPortalInvitationFailure, type PortalInvitationOperation } from "~/services/customer-portal/portal-invitation.server";
import { appendCSRFToken } from "~/utils/csrf";
import { StorageScanRejectedError, UploadContentReadError } from "~/utils/integrations/storageService";
import { validateCSRFToken } from "~/utils/session.server";
type LoaderData = { readonly title: string; readonly vm: PortalAdminVM; readonly customDomainRuntimeEnabled: boolean };
type ActionData = { readonly ok?: true; readonly messageKey?: string; readonly errorKey?: string };
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
const [{ t }, ctx] = await Promise.all([getTranslations(request), requirePortalAdminWorkspaceContext(request, params, "portal.read")]);
const snapshot = await loadPortalAdminSnapshot({ tenantId: ctx.tenantId, tenantSlug: ctx.tenantSlug });
const vm = buildPortalAdminVM({
frozen: snapshot.frozen,
permissions: {
canRead: ctx.permissions.includes("portal.read"),
canManageUsers: ctx.permissions.includes("portal.manage_users"),
canManageAccess: ctx.permissions.includes("portal.manage_access"),
canDeleteUsers: ctx.permissions.includes("portal.delete_user"),
canReadActivity: ctx.permissions.includes("portal.activity.read"),
canManageActivity: ctx.permissions.includes("portal.activity.manage"),
canAdminister: ctx.permissions.includes("portal.admin"),
},
configuration: snapshot.configuration,
stages: snapshot.stages,
autoReleaseRules: snapshot.autoReleaseRules,
projectOptions: snapshot.projectOptions,
users: snapshot.users,
accessRows: snapshot.accessRows,
inbox: snapshot.inbox,
});
return Response.json({
title: `${t("customerPortal.admin.title")} | ${process.env.APP_NAME}`,
vm,
customDomainRuntimeEnabled: isPortalCustomDomainRuntimeEnabled(),
} satisfies LoaderData);
}
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
const membership = await requirePortalAdminWorkspaceMembership(request, params);
const form = await request.formData();
const intent = rawIntent(form);
const permission = permissionForIntent(intent);
const ctx = await requireActionPermission(membership, permission, intent, request, form);
await validateCSRFToken(request, { formData: form });
try {
if (!isKnownIntent(intent)) throw invalid();
if (intent === "save-configuration") {
await savePortalConfiguration({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
lifecycleMode: enumValue(form, "lifecycleMode", ["customer", "project"]),
projectAutoCloseMonths: integer(form, "projectAutoCloseMonths"),
inactivityDisableMonths: integer(form, "inactivityDisableMonths"),
enabledProjectTypes: list(form, "enabledProjectTypes"),
uploadMaxFiles: integer(form, "uploadMaxFiles"),
uploadMaxFileSizeBytes: integer(form, "uploadMaxFileSizeBytes"),
statusEmailsEnabled: booleanValue(form, "statusEmailsEnabled"),
imprintUrl: optional(form, "imprintUrl"),
privacyUrl: optional(form, "privacyUrl"),
termsUrl: optional(form, "termsUrl"),
publish: booleanValue(form, "publish"),
});
} else if (intent === "save-branding") {
const remove = booleanValue(form, "remove");
await savePortalBranding({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
logo: remove
? null
: {
content: required(form, "content"),
declaredMimeType: required(form, "declaredMimeType"),
filename: required(form, "filename"),
},
});
} else if (intent === "save-stage") {
await setPortalStageVisibility({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
stageId: required(form, "stageId"),
visible: booleanValue(form, "visible"),
customerLabel: optional(form, "customerLabel"),
});
} else if (intent === "save-auto-release") {
await setPortalDocumentAutoReleaseRule({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
projectType: optional(form, "projectType"),
documentType: required(form, "documentType"),
enabled: booleanValue(form, "enabled"),
});
} else if (intent === "invite-user") {
await invitePortalUser({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
email: required(form, "email"),
firstName: required(form, "firstName"),
lastName: required(form, "lastName"),
kind: enumValue(form, "kind", ["customer", "subcontractor"]),
});
} else if (intent === "resend-invite") {
await resendPortalUserInvitation({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
portalUserId: required(form, "portalUserId"),
});
} else if (intent === "set-access") {
const validUntilValue = optional(form, "validUntil");
const validUntil = validUntilValue ? new Date(`${validUntilValue}T23:59:59.999Z`) : null;
if (validUntil && !Number.isFinite(validUntil.getTime())) throw invalid();
await setPortalProjectAccess({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
portalUserId: required(form, "portalUserId"),
projectId: required(form, "projectId"),
active: booleanValue(form, "active"),
canUpload: booleanValue(form, "canUpload"),
validUntil,
companyName: optional(form, "companyName"),
roleLabel: optional(form, "roleLabel"),
visibleStageIds: list(form, "visibleStageIds"),
visibleDocumentTypes: list(form, "visibleDocumentTypes"),
canSeeOtherSubcontractors: booleanValue(form, "canSeeOtherSubcontractors"),
});
} else if (intent === "disable-user") {
await disablePortalUser({ tenantId: ctx.tenantId, actorUserId: ctx.userId, portalUserId: required(form, "portalUserId") });
} else if (intent === "update-inbox") {
await updatePortalInbox({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
itemId: required(form, "itemId"),
status: enumValue(form, "status", ["open", "in_progress", "resolved", "dismissed"]),
});
} else {
throw invalid();
}
return Response.json({
ok: true,
messageKey: intent === "invite-user" || intent === "resend-invite" ? "customerPortal.invitation.sent" : "customerPortal.admin.messages.saved",
} satisfies ActionData);
} catch (error) {
if (error instanceof PortalBrandingValidationError) {
return Response.json({ errorKey: "customerPortal.admin.branding.errors.invalid" } satisfies ActionData, { status: 400 });
}
if (error instanceof UploadContentReadError) {
return Response.json(
{
errorKey:
error.code === "too_large"
? "customerPortal.admin.branding.errors.tooLarge"
: "customerPortal.admin.branding.errors.uploadFailed",
} satisfies ActionData,
{ status: 400 }
);
}
if (error instanceof StorageScanRejectedError) {
return Response.json({ errorKey: "customerPortal.admin.branding.errors.uploadFailed" } satisfies ActionData, { status: 400 });
}
if (error instanceof PortalAdminError) return Response.json({ errorKey: error.messageKey } satisfies ActionData, { status: error.status });
if (error instanceof Response) throw error;
if (error instanceof CatalogError) return Response.json({ errorKey: error.i18nKey } satisfies ActionData, { status: error.status });
throw error;
}
}
async function requireActionPermission(
membership: PortalAdminWorkspaceContext,
permission: string,
intent: string,
request: Request,
formData: FormData
): Promise<PortalAdminWorkspaceContext> {
try {
return requirePortalAdminWorkspacePermission(membership, permission);
} catch (error) {
const operation = invitationOperationForIntent(intent);
if (operation && error instanceof Response && error.status === 404) {
// Permission stays indistinguishable as 404, while cross-site requests
// without a valid CSRF proof must not be able to append audit rows.
try {
await validateCSRFToken(request, { formData });
} catch {
throw error;
}
await recordPortalInvitationFailure({
tenantId: membership.tenantId,
actorUserId: membership.userId,
operation,
reason: "permission_denied",
outcome: "blocked",
});
}
throw error;
}
}
function invitationOperationForIntent(intent: string): PortalInvitationOperation | null {
if (intent === "invite-user") return "admin_invite";
if (intent === "resend-invite") return "resend_invite";
return null;
}
export default function CustomerPortalAdminRoute(): React.JSX.Element {
const outlet = useOutlet();
return outlet ?? <CustomerPortalAdminIndexRoute />;
}
function CustomerPortalAdminIndexRoute(): React.JSX.Element {
const { vm, customDomainRuntimeEnabled } = useLoaderData<LoaderData>();
const fetcher = useFetcher<ActionData>();
const navigate = useNavigate();
const params = useParams();
const submit = (intent: string, values: Readonly<Record<string, string | number | boolean>>) => {
const form = new FormData();
form.set("intent", intent);
for (const [key, value] of Object.entries(values)) form.set(key, String(value));
fetcher.submit(appendCSRFToken(form), { method: "post" });
};
const actions: PortalAdminPageActions = {
onSaveConfiguration: (draft: PortalAdminConfigurationDraft) =>
submit("save-configuration", { ...draft, enabledProjectTypes: draft.enabledProjectTypes.join(",") }),
onSaveBranding: (logo: PortalAdminBrandingDraft | null) =>
submit(
"save-branding",
logo
? { remove: false, content: logo.content, declaredMimeType: logo.declaredMimeType, filename: logo.filename }
: { remove: true }
),
onSaveStage: (input) => submit("save-stage", input),
onSaveAutoRelease: (input) => submit("save-auto-release", input),
onInviteUser: (input) => submit("invite-user", input),
onResendInvitation: (portalUserId) => submit("resend-invite", { portalUserId }),
onSetAccess: (input) =>
submit("set-access", {
...input,
visibleStageIds: input.visibleStageIds.join(","),
visibleDocumentTypes: input.visibleDocumentTypes.join(","),
}),
onDisableUser: (portalUserId) => submit("disable-user", { portalUserId }),
onUpdateInbox: (input) => submit("update-inbox", input),
onOpenEmailTemplates: (href) => navigate(href),
onOpenInbox: () => navigate(`/${encodeURIComponent(params.tenant ?? "")}/customer-portal/inbox`),
onOpenDomain: customDomainRuntimeEnabled ? () => navigate(`/${encodeURIComponent(params.tenant ?? "")}/settings/customer-portal/domain`) : undefined,
};
return (
<PortalAdminPage
vm={vm}
embedded
busy={fetcher.state !== "idle"}
messageKey={fetcher.data?.ok ? fetcher.data.messageKey : null}
errorKey={fetcher.data?.errorKey ?? null}
actions={actions}
/>
);
}
function permissionForIntent(intent: string): string {
if (intent === "invite-user" || intent === "resend-invite" || intent === "disable-user") return "portal.manage_users";
if (intent === "set-access") return "portal.manage_access";
if (intent === "update-inbox") return "portal.activity.manage";
return "portal.admin";
}
function rawIntent(form: FormData): string {
const value = form.get("intent");
return typeof value === "string" ? value.trim() : "";
}
function isKnownIntent(intent: string): boolean {
return [
"save-configuration",
"save-branding",
"save-stage",
"save-auto-release",
"invite-user",
"resend-invite",
"set-access",
"disable-user",
"update-inbox",
].includes(intent);
}
function required(form: FormData, key: string): string {
const value = form.get(key);
if (typeof value !== "string" || !value.trim()) throw invalid();
return value.trim();
}
function optional(form: FormData, key: string): string | null {
const value = form.get(key);
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function list(form: FormData, key: string): string[] {
const value = form.get(key);
return typeof value === "string"
? value
.split(",")
.map((item) => item.trim())
.filter(Boolean)
: [];
}
function integer(form: FormData, key: string): number {
const value = Number(required(form, key));
if (!Number.isSafeInteger(value)) throw invalid();
return value;
}
function booleanValue(form: FormData, key: string): boolean {
const value = required(form, key);
if (value !== "true" && value !== "false") throw invalid();
return value === "true";
}
function enumValue<const T extends string>(form: FormData, key: string, values: readonly T[]): T {
const value = required(form, key);
if (!values.includes(value as T)) throw invalid();
return value as T;
}
function invalid(): PortalAdminError {
return new PortalAdminError("customerPortal.admin.errors.invalidInput", 400);
}
export function ErrorBoundary(): React.JSX.Element {
return <ServerError />;
}
export const handle = { breadcrumbKey: "customerPortal.admin.title" };
@@ -1,140 +1,8 @@
import { useEffect, useRef, useState } from "react";
import { LoaderFunctionArgs, MetaFunction, useFetcher, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import { Outlet, useParams } from "react-router";
import toast from "react-hot-toast";
import { buildGroupsDetailVM } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { getUserPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getAllGroups, getMyGroups, GroupWithDetails } from "~/utils/db/permissions/groups.db.server";
import { getTenantUsers } from "~/utils/db/tenants.db.server";
import { getUserInfo } from "~/utils/session.server";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import GroupsListView from "~/modules/users/components/GroupsListView";
import { GroupMembersDialog, type GroupMembersActions } from "~/components/screens/users/GroupMembersDialog";
import UrlUtils from "~/utils/app/UrlUtils";
import { useRootData } from "~/utils/data/useRootData";
import { useAppData } from "~/utils/data/useAppData";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import InfoBanner from "~/components/ui/banners/InfoBanner";
import { requireAuth } from "~/utils/loaders.middleware";
// AK-SET-01 — legacy `settings/groups` is now a tab of the Team-Hub.
import { legacySettingsRedirectLoader } from "./legacy-redirects.server";
// R-P2b — groups bulk add/remove (interim UI per AD-28, David parked groups
// for RBAC V2): the list gains a "manage members" row action opening the bulk
// dialog, which posts bulk-add/bulk-remove to the existing groups/$id action.
export const loader = legacySettingsRedirectLoader("settings/team/groups");
type TenantUserRow = { userId: string; firstName: string | null; lastName: string | null; email: string };
type LoaderData = {
title: string;
items: GroupWithDetails[];
tenantUsers: TenantUserRow[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
const userInfo = await getUserInfo(request);
const { permission, userPermission } = await getUserPermission({
userId: userInfo.userId,
permissionName: "app.settings.groups.full",
tenantId: tenantId,
});
let items: GroupWithDetails[];
if (!permission || userPermission) {
items = await getAllGroups(tenantId);
} else {
items = await getMyGroups(userInfo.userId, tenantId);
}
// Bulk-add candidates: active tenant members (minimal fields only).
const tenantUsers = (await getTenantUsers(tenantId)).map((member) => ({
userId: member.userId,
firstName: member.user.firstName,
lastName: member.user.lastName,
email: member.user.email,
}));
const data: LoaderData = {
title: `${t("models.group.plural")} | ${process.env.APP_NAME}`,
items,
tenantUsers,
};
return data;
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
type MutationResponse = { error?: string; success?: string };
export default function GroupsRoute() {
const data = useLoaderData<LoaderData>();
const rootData = useRootData();
const appData = useAppData();
const params = useParams();
const { t } = useTranslation();
const fetcher = useFetcher<MutationResponse>();
const [openGroupId, setOpenGroupId] = useState<string | null>(null);
const hadSubmission = useRef(false);
const canManage = getUserHasPermission(appData, "app.settings.groups.full");
const submitting = fetcher.state !== "idle";
useEffect(() => {
if (fetcher.state !== "idle") {
hadSubmission.current = true;
return;
}
if (hadSubmission.current) {
hadSubmission.current = false;
if (fetcher.data?.error) toast.error(fetcher.data.error);
else if (fetcher.data?.success) toast.success(fetcher.data.success);
}
}, [fetcher.state, fetcher.data]);
const openGroup = openGroupId ? (data.items.find((group) => group.id === openGroupId) ?? null) : null;
const groupVM = openGroup
? buildGroupsDetailVM({
group: { id: openGroup.id, name: openGroup.name, description: openGroup.description },
memberUsers: openGroup.users.map((entry) => ({
userId: entry.user.id,
firstName: entry.user.firstName,
lastName: entry.user.lastName,
email: entry.user.email,
})),
tenantUsers: data.tenantUsers,
canManage,
})
: null;
function postBulk(intent: "bulk-add" | "bulk-remove", userIds: string[]) {
if (!openGroupId) return;
const formData = new FormData();
if (rootData.csrf) formData.set("csrf", rootData.csrf);
formData.set("action", intent);
for (const userId of userIds) {
formData.append("user-ids", userId);
}
fetcher.submit(formData, { method: "post", action: UrlUtils.currentTenantUrl(params, `settings/groups/${openGroupId}`) });
}
const bulkActions: GroupMembersActions = {
onAdd: (userIds) => postBulk("bulk-add", userIds),
onRemove: (userIds) => postBulk("bulk-remove", userIds),
};
return (
<EditPageLayout>
{rootData.featureFlags?.includes("row-groups") ? (
<GroupsListView items={data.items} canManage={canManage} onManageMembers={canManage ? setOpenGroupId : undefined} />
) : (
<InfoBanner title={t("settings.groups.disabled.title")} text={t("settings.groups.disabled.description")} />
)}
{groupVM ? <GroupMembersDialog vm={groupVM} actions={bulkActions} submitting={submitting} onClose={() => setOpenGroupId(null)} /> : null}
<Outlet />
</EditPageLayout>
);
export default function LegacyGroupsRedirect() {
return null;
}
@@ -1,151 +1,10 @@
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router";
import GroupForm from "~/components/core/roles/GroupForm";
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { useAppData } from "~/utils/data/useAppData";
import { createLog } from "~/utils/db/logs.db.server";
import { addUsersToGroup, deleteGroup, getGroup, GroupWithDetails, removeUsersFromGroup, updateGroup } from "~/utils/db/permissions/groups.db.server";
import { replaceGroupUsers } from "~/utils/db/permissions/userGroups.db.server";
import { getTenantUsers, TenantUserWithUser } from "~/utils/db/tenants.db.server";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { getUserPermission } from "~/utils/helpers/.server/PermissionsService";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { validateCSRFToken } from "~/utils/session.server";
// AK-SET-01 — legacy group detail path; the id has to survive the redirect.
import type { LoaderFunctionArgs } from "react-router";
import { legacySettingsRedirect } from "../legacy-redirects.server";
type LoaderData = {
title: string;
item: GroupWithDetails;
tenantUsers: TenantUserWithUser[];
};
export const loader = ({ request, params }: LoaderFunctionArgs) =>
legacySettingsRedirect({ request, params }, `settings/team/groups/${encodeURIComponent(params.id ?? "")}`);
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const userInfo = await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
const item = await getGroup(params.id ?? "", tenantId);
if (!item) {
throw redirect(UrlUtils.currentTenantUrl(params, "settings/members"));
}
const { userPermission: canManageGroups } = await getUserPermission({
userId: userInfo.userId,
tenantId,
permissionName: "app.settings.groups.full",
});
if (!canManageGroups && item.createdByUserId !== userInfo.userId) {
throw Response.json({ error: t("models.group.errors.manageForbidden") }, { status: 403 });
}
const data: LoaderData = {
title: `${item.name} | ${t("models.group.object")} | ${process.env.APP_NAME}`,
item,
tenantUsers: await getTenantUsers(tenantId),
};
return data;
};
type ActionData = {
error?: string;
};
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
export const action: ActionFunction = async ({ request, params }) => {
const userInfo = await requireAuth({ request, params });
await validateCSRFToken(request);
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
const existing = await getGroup(params.id ?? "", tenantId);
if (!existing) {
throw redirect(UrlUtils.currentTenantUrl(params, "settings/members"));
}
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
const { userPermission: canManageGroups } = await getUserPermission({
userId: userInfo.userId,
tenantId,
permissionName: "app.settings.groups.full",
});
if (!canManageGroups && existing.createdByUserId !== userInfo.userId) {
throw Response.json({ error: t("models.group.errors.manageForbidden") }, { status: 403 });
}
if (action === "edit") {
const data = {
tenantId: tenantId,
name: form.get("name")?.toString() ?? "",
description: form.get("description")?.toString() ?? "",
color: Number(form.get("color")),
};
const updated = await updateGroup(existing.id, data, tenantId);
if ("count" in updated && updated.count !== 1) {
return badRequest({ error: t("shared.notFound") });
}
const userIds = form.getAll("users[]").map((f) => f.toString());
const selectedUserIds = new Set(userIds);
const tenantUsers = await getTenantUsers(tenantId);
const users = tenantUsers.filter((tenantUser) => selectedUserIds.has(tenantUser.userId)).map((tenantUser) => tenantUser.user);
if (users.length !== userIds.length) {
return badRequest({ error: t("shared.invalidForm") });
}
await replaceGroupUsers(
existing.id,
tenantId,
users.map((user) => user.id)
);
await createLog(request, tenantId, "settings.groups.updated", `${existing.name}: ${JSON.stringify({ ...data, users: users.map((f) => f.email) })}`);
} else if (action === "bulk-add" || action === "bulk-remove") {
// R-P2b — bulk member ops for the interim group members dialog (AD-28).
// Only tenant members are accepted; the ops themselves are idempotent.
const userIds = form.getAll("user-ids").map((value) => value.toString());
const tenantUserIds = new Set((await getTenantUsers(tenantId)).map((tenantUser) => tenantUser.userId));
if (userIds.length === 0 || !userIds.every((userId) => tenantUserIds.has(userId))) {
return badRequest({ error: t("shared.invalidForm") });
}
if (action === "bulk-add") {
await addUsersToGroup(existing.id, userIds);
await createLog(request, tenantId, "settings.groups.membersAdded", `${existing.name}: +${userIds.length}`);
return Response.json({ success: t("settings.members.groups.bulk.added", { count: userIds.length }) });
}
await removeUsersFromGroup(existing.id, userIds);
await createLog(request, tenantId, "settings.groups.membersRemoved", `${existing.name}: -${userIds.length}`);
return Response.json({ success: t("settings.members.groups.bulk.removed", { count: userIds.length }) });
} else if (action === "delete") {
const deleted = await deleteGroup(existing.id, tenantId);
if ("count" in deleted && deleted.count !== 1) {
return badRequest({ error: t("shared.notFound") });
}
await createLog(request, tenantId, "settings.groups.deleted", `${existing.name}`);
} else {
return badRequest({ error: t("shared.invalidForm") });
}
return redirect(UrlUtils.currentTenantUrl(params, "settings/members"));
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function AdminEditGroupRoute() {
const data = useLoaderData<LoaderData>();
const appData = useAppData();
const navigate = useNavigate();
const params = useParams();
const { t } = useTranslation();
return (
<SlideOverWideEmpty
title={t("settings.members.groups.editTitle")}
open={true}
className="sm:max-w-sm"
onClose={() => navigate(UrlUtils.currentTenantUrl(params, "settings/members"))}
>
<GroupForm
allUsers={data.tenantUsers}
item={data.item}
canUpdate={getUserHasPermission(appData, "app.settings.groups.full") || data.item.createdByUserId === appData.user.id}
canDelete={getUserHasPermission(appData, "app.settings.groups.full") || data.item.createdByUserId === appData.user.id}
/>
</SlideOverWideEmpty>
);
export default function LegacyGroupDetailRedirect() {
return null;
}
@@ -1,93 +1,8 @@
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router";
import GroupForm from "~/components/core/roles/GroupForm";
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { createLog } from "~/utils/db/logs.db.server";
import { createGroup } from "~/utils/db/permissions/groups.db.server";
import { createUserGroups } from "~/utils/db/permissions/userGroups.db.server";
import { getTenantUsers, TenantUserWithUser } from "~/utils/db/tenants.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
// AK-SET-01 — legacy `settings/groups/new`.
import { legacySettingsRedirectLoader } from "../legacy-redirects.server";
type LoaderData = {
tenantUsers: TenantUserWithUser[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.groups.full", tenantId);
const data: LoaderData = {
tenantUsers: await getTenantUsers(tenantId),
};
return data;
};
export const loader = legacySettingsRedirectLoader("settings/team/groups/new");
type ActionData = {
error?: string;
};
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
export const action: ActionFunction = async ({ request, params }) => {
await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.groups.full", tenantId);
await validateCSRFToken(request);
const userInfo = await getUserInfo(request);
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
if (action === "create") {
const data = {
createdByUserId: userInfo.userId,
tenantId: tenantId,
name: form.get("name")?.toString() ?? "",
description: form.get("description")?.toString() ?? "",
color: Number(form.get("color")),
};
const group = await createGroup(data);
const userIds = form.getAll("users[]").map((f) => f.toString());
const tenantUsers = await getTenantUsers(tenantId);
const users = tenantUsers.filter((tenantUser) => userIds.includes(tenantUser.userId)).map((tenantUser) => tenantUser.user);
if (users.length !== userIds.length) {
return badRequest({ error: t("shared.invalidForm") });
}
await createUserGroups(
group.id,
users.map((user) => user.id)
);
await createLog(
request,
tenantId,
"settings.groups.created",
`${JSON.stringify({
...data,
users: users.map((f) => f.email),
})}`
);
return redirect(UrlUtils.currentTenantUrl(params, "settings/members"));
} else {
return badRequest({ error: t("shared.invalidForm") });
}
};
export default function NewGroupRoute() {
const navigate = useNavigate();
const params = useParams();
const data = useLoaderData<LoaderData>();
const { t } = useTranslation();
return (
<SlideOverWideEmpty
title={t("settings.members.groups.createTitle")}
open={true}
className="sm:max-w-sm"
onClose={() => navigate(UrlUtils.currentTenantUrl(params, "settings/members"))}
>
<GroupForm allUsers={data.tenantUsers} />
</SlideOverWideEmpty>
);
export default function LegacyNewGroupRedirect() {
return null;
}
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { settingsHubBaseRedirect } from "./hub-access.server";
describe("settings hub base redirects", () => {
it("redirects a base URL to the first reachable tab and keeps its query", () => {
const response = settingsHubBaseRedirect(
new Request("https://app.example.test/acme/settings/team?from=rail"),
"/acme/settings/team",
[{ href: "/acme/settings/team/roles" }]
);
expect(response?.status).toBe(302);
expect(response?.headers.get("Location")).toBe("/acme/settings/team/roles?from=rail");
});
it("does not redirect when the base route is itself reachable", () => {
expect(
settingsHubBaseRedirect(new Request("https://app.example.test/acme/settings/team"), "/acme/settings/team", [
{ href: "/acme/settings/team" },
{ href: "/acme/settings/team/roles" },
])
).toBeNull();
});
it("does not interfere with a child route", () => {
expect(
settingsHubBaseRedirect(new Request("https://app.example.test/acme/settings/team/roles"), "/acme/settings/team", [
{ href: "/acme/settings/team/roles" },
])
).toBeNull();
});
});
@@ -0,0 +1,49 @@
import type { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
/**
* AK-SET-01 · shared loader guards for the settings hubs.
*
* A hub bundles tabs with different permissions, so it needs to ask "may this
* user see this tab?" without the answer aborting the whole request.
*/
/**
* Permission probe that reports instead of throwing.
*
* `verifyUserHasPermission` throws a redirect/404 Response on denial, which is
* right for a leaf route but wrong for a hub: one denied tab must not take the
* remaining tabs down with it. Anything that is not a denial still propagates.
*/
export async function hasSettingsPermission(request: Request, permission: DefaultPermission, tenantId: string): Promise<boolean> {
try {
await verifyUserHasPermission(request, permission, tenantId);
return true;
} catch (error) {
if (error instanceof Response && ((error.status >= 300 && error.status < 400) || error.status === 403 || error.status === 404)) return false;
throw error;
}
}
/**
* A hub with no reachable tab renders nothing useful, so it must not render at
* all. 404 rather than 403 — a user may not learn that the area exists
* (Bauprinzip A.5.3).
*/
export function settingsHubNotFound(): Response {
return new Response("Not Found", { status: 404 });
}
/** Redirect a hub base URL to the first tab the current user can actually open. */
export function settingsHubBaseRedirect(request: Request, baseHref: string, tabs: ReadonlyArray<{ href: string }>): Response | null {
const url = new URL(request.url);
const normalize = (value: string) => value.replace(/\/+$/, "") || "/";
if (normalize(url.pathname) !== normalize(baseHref)) return null;
const firstHref = tabs[0]?.href;
if (!firstHref || normalize(firstHref) === normalize(baseHref)) return null;
return new Response(null, {
status: 302,
headers: { Location: `${firstHref}${url.search}${url.hash}` },
});
}
@@ -0,0 +1,100 @@
// AK-SET-01 Hub E — "Erweiterungen" bundles the integration catalog, mailboxes,
// calendars, telephony, plugins and API keys. Was already the layout route for
// the integrations area; it now also contributes the tab bar and stays the
// "Erweiterungen" breadcrumb level (useBreadcrumbTrail reads loader titles per
// match).
import { Outlet, useLoaderData, useLocation, type LoaderFunctionArgs, type MetaFunction } from "react-router";
import { FeatherPlug } from "@subframe/core";
import { buildSettingsHubVM, type SettingsHubTabInput } from "@hivegrid/view-models";
import { SettingsHubShell } from "~/components/screens/settings/SettingsHubShell";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { EMAIL_INBOX_MODULE_KEY } from "~/modules/emailInbox/routes/emailInboxRoutePaths";
import { INTEGRATIONS_MODULE_KEY } from "~/utils/integrations/integrationsRoutePaths";
import { TELEPHONY_MODULE_KEY } from "~/modules/telephony/routes/telephonyRoutePaths";
import { hasSettingsPermission, settingsHubBaseRedirect, settingsHubNotFound } from "./hub-access.server";
type LoaderData = {
title: string;
tabs: SettingsHubTabInput[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
const [{ t }, userInfo, canReadIntegrations, canReadOwnEmail, canReadAllEmail, canConnectOwnCalendar, canAdminCalendar, canManageTelephony, canUsePlugins, canViewApiKeys] = await Promise.all([
getTranslations(request),
getUserInfo(request),
hasSettingsPermission(request, "integrations.read", tenantId),
hasSettingsPermission(request, "email.read_own", tenantId),
hasSettingsPermission(request, "email.read_all", tenantId),
hasSettingsPermission(request, "calendar.connect_own", tenantId),
hasSettingsPermission(request, "calendar.admin", tenantId),
hasSettingsPermission(request, "telephony.manage", tenantId),
hasSettingsPermission(request, "app.plugins.use", tenantId),
hasSettingsPermission(request, "app.settings.apiKeys.view", tenantId),
]);
const [integrationsEnabled, emailEnabled, telephonyEnabled, apiEnabled, appConfiguration] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: INTEGRATIONS_MODULE_KEY }),
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: EMAIL_INBOX_MODULE_KEY }),
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: TELEPHONY_MODULE_KEY }),
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: "api" }),
getAppConfiguration({ request }),
]);
const tabs: SettingsHubTabInput[] = [];
if (canReadIntegrations && integrationsEnabled) {
// The hub index href is a prefix of every sibling, but longest-prefix
// matching in buildSettingsHubVM keeps sibling tabs winning on their own
// routes — so the catalog tab stays lit on app detail pages
// (…/integrations/<app>) without swallowing email/calendar/… tabs.
tabs.push({ id: "catalog", labelKey: "integrations.nav.title", href: UrlUtils.currentTenantUrl(params, "settings/integrations") });
}
if (emailEnabled && (canReadOwnEmail || canReadAllEmail)) {
tabs.push({ id: "email", labelKey: "emailInbox.settings.title", href: UrlUtils.currentTenantUrl(params, "settings/integrations/email") });
}
if (integrationsEnabled && (canConnectOwnCalendar || canAdminCalendar)) {
tabs.push({ id: "calendar", labelKey: "calendar.connections.title", href: UrlUtils.currentTenantUrl(params, "settings/integrations/calendar") });
}
if (telephonyEnabled && canManageTelephony) {
tabs.push({ id: "telephony", labelKey: "telephony.nav.title", href: UrlUtils.currentTenantUrl(params, "settings/integrations/telephony") });
}
if (canUsePlugins) {
tabs.push({ id: "plugins", labelKey: "settings.plugins.title", href: UrlUtils.currentTenantUrl(params, "settings/integrations/plugins") });
}
if (apiEnabled && appConfiguration.app.features.tenantApiKeys && canViewApiKeys) {
tabs.push({ id: "api", labelKey: "models.apiKey.plural", href: UrlUtils.currentTenantUrl(params, "settings/integrations/api") });
}
if (tabs.length === 0) throw settingsHubNotFound();
const baseRedirect = settingsHubBaseRedirect(request, UrlUtils.currentTenantUrl(params, "settings/integrations"), tabs);
if (baseRedirect) throw baseRedirect;
return { title: `${t("settings.hubs.integrations.title")} | ${process.env.APP_NAME}`, tabs } satisfies LoaderData;
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function IntegrationsHubRoute() {
const { tabs } = useLoaderData<LoaderData>();
const location = useLocation();
const vm = buildSettingsHubVM({
hubId: "integrations",
titleKey: "settings.hubs.integrations.title",
subtitleKey: "settings.hubs.integrations.subtitle",
tabs,
currentPath: location.pathname,
});
return (
<SettingsHubShell vm={vm} icon={<FeatherPlug />}>
<Outlet />
</SettingsHubShell>
);
}
@@ -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,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,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,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"}
/>
);
}
@@ -1,7 +1,9 @@
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();
@@ -11,6 +13,9 @@ vi.mock("~/utils/services/.server/urlService", () => ({
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,
@@ -31,6 +36,8 @@ beforeEach(() => {
getTenantIdMock.mockClear();
verifyPermissionMock.mockReset();
verifyPermissionMock.mockResolvedValue(undefined);
getUserInfoMock.mockReset();
getUserInfoMock.mockResolvedValue({ userId: "u-1" });
getPluginForTenantMock.mockReset();
auditFindManyMock.mockReset();
});
@@ -55,10 +62,16 @@ describe("plugin audit route", () => {
});
test("loader caps and orders capability filter options deterministically", async () => {
getPluginForTenantMock.mockResolvedValue({
id: "pl-row-1",
pluginId: "com.acme.audit",
version: "1.0.0",
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([
@@ -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();
}
@@ -26,6 +26,9 @@ vi.mock("~/utils/db/users.db.server", () => ({
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),
@@ -119,6 +122,25 @@ describe("plugin settings route", () => {
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);
@@ -216,7 +238,11 @@ describe("plugin settings route", () => {
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", "x-forwarded-for": "203.0.113.5" },
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" }),
});
@@ -264,7 +290,11 @@ describe("plugin settings route", () => {
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", "x-forwarded-for": "203.0.113.7" },
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" }),
});
@@ -278,7 +308,7 @@ describe("plugin settings route", () => {
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("tenant:tenant-1:user:user-1:plugin:pl-1:reason:wrong_origin");
expect(consumeRateLimitMock).toHaveBeenCalledWith("pseudonymous-plugin-settings");
expect(reportPluginSettingsFrameViolationMock).toHaveBeenCalledWith({
tenantId: "tenant-1",
pluginRowId: "pl-1",
@@ -538,10 +568,9 @@ describe("plugin settings route", () => {
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
});
test("action fails open when plugin settings rate limit storage is unavailable", async () => {
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 warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
const { action } = await import("./plugins.$id.js");
const response = await action({
@@ -554,11 +583,13 @@ describe("plugin settings route", () => {
context: {},
});
expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({ ok: true, key: "theme" });
expect(setPluginUserSettingMock).toHaveBeenCalledOnce();
expect(warn).toHaveBeenCalledWith("[plugin-settings] rate-limit infra failure; allowing settings write:", "redis unavailable");
warn.mockRestore();
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 () => {
@@ -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>
);
}
@@ -104,7 +104,7 @@ describe("tenant plugin settings route UI", () => {
it("renders the sandboxed settings iframe with route-level navigation", () => {
renderSettingsRoute();
expect(screen.getByRole("link", { name: "Back to plugins" })).toHaveAttribute("href", "/app/acme/settings/plugins");
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();
@@ -139,21 +139,24 @@ describe("plugins settings route", () => {
context: {},
});
const data = await (response as Response).json();
expect(data.items).toHaveLength(1);
expect(data.items[0].capabilities).toEqual([
{
// AK-UI-05: the loader now serializes a PluginCatalogVM (AD-28 interim screen).
expect(data.vm.status).toBe("ready");
expect(data.vm.data.rows).toHaveLength(1);
expect(data.vm.data.rows[0].capabilities).toEqual([
expect.objectContaining({
name: "log",
scope: null,
granted: true,
grantedAt: "2026-01-02T00:00:00.000Z",
grantedScopeJson: null,
metadata: { risk: "low", productionAvailable: true },
},
grantedAtIso: "2026-01-02T00:00:00.000Z",
scopeParts: [],
risk: "low",
productionAvailable: true,
approvable: true,
}),
]);
expect(data.items[0].missingCapabilities).toEqual([]);
expect(data.items[0].capabilityReviewDigest).toBeTruthy();
expect(data.canManage).toBe(true);
expect(data.canAudit).toBe(true);
expect(data.vm.data.rows[0].missingCapabilities).toEqual([]);
expect(data.vm.data.rows[0].capabilityReviewDigest).toBeTruthy();
expect(data.vm.data.canManage).toBe(true);
expect(data.vm.data.rows[0].auditHref).toBeTruthy();
expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.plugins.use", "t-1");
expect(getUserPermissionMock).toHaveBeenCalledWith({ userId: "u-1", permissionName: "app.plugins.manage", tenantId: "t-1" });
expect(getUserPermissionMock).toHaveBeenCalledWith({ userId: "u-1", permissionName: "app.settings.auditTrails.view", tenantId: "t-1" });
@@ -361,18 +364,20 @@ describe("plugins settings route", () => {
});
const data = await (response as Response).json();
expect(data.items[0].capabilities).toEqual([
{
expect(data.vm.data.rows[0].capabilities).toEqual([
expect.objectContaining({
name: "hook:workflow.executed",
scope: null,
granted: false,
grantedAt: null,
grantedScopeJson: null,
metadata: { risk: "medium", productionAvailable: true },
},
grantedAtIso: null,
scopeParts: [],
risk: "medium",
productionAvailable: true,
// Hook consent names render as "Hook: <name>", not as a capabilityNames key.
label: { key: "settings.plugins.consent.hookLabel", params: { hook: "workflow.executed" } },
}),
]);
expect(data.items[0].missingCapabilities).toEqual(["hook:workflow.executed"]);
expect(data.items[0].capabilityReviewDigest).toBe(await getCapabilityReviewDigest(plugin, ["hook:workflow.executed"]));
expect(data.vm.data.rows[0].missingCapabilities).toEqual(["hook:workflow.executed"]);
expect(data.vm.data.rows[0].capabilityReviewDigest).toBe(await getCapabilityReviewDigest(plugin, ["hook:workflow.executed"]));
});
test("action grants hook consent before enabling hook-only plugins", async () => {
@@ -814,8 +819,9 @@ describe("plugins settings route", () => {
context: {},
});
const data = await (response as Response).json();
expect(data.canManage).toBe(false);
expect(data.canAudit).toBe(false);
expect(data.vm.data.canManage).toBe(false);
// No audit permission means no plugin row ever exposes an audit link.
expect(data.vm.data.rows.every((row: { auditHref: string | null }) => row.auditHref === null)).toBe(true);
});
test("action disables plugins via form data", async () => {
@@ -830,7 +836,8 @@ describe("plugins settings route", () => {
body: new URLSearchParams(Array.from(form.entries()) as [string, string][]),
headers: {
"content-type": "application/x-www-form-urlencoded",
"x-forwarded-for": "203.0.113.10, 198.51.100.2",
"cf-connecting-ip": "203.0.113.10",
"x-forwarded-for": "198.51.100.2, 173.245.48.10",
},
}),
params: { tenant: "t-1" },
@@ -868,7 +875,8 @@ describe("plugins settings route", () => {
body: new URLSearchParams(Array.from(form.entries()) as [string, string][]),
headers: {
"content-type": "application/x-www-form-urlencoded",
"x-forwarded-for": "203.0.113.10, 198.51.100.2",
"cf-connecting-ip": "203.0.113.10",
"x-forwarded-for": "198.51.100.2, 173.245.48.10",
},
}),
params: { tenant: "t-1" },
@@ -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] }
),
}}
/>
);
}
@@ -1,19 +1,26 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import type { FormHTMLAttributes, ReactNode } from "react";
import { MemoryRouter, useActionData, useLoaderData } from "react-router";
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,
Form: ({ children, ...props }: { children: ReactNode } & FormHTMLAttributes<HTMLFormElement>) => <form {...props}>{children}</form>,
useActionData: vi.fn(),
useLoaderData: vi.fn(),
useSubmit: vi.fn(),
// MemoryRouter is not a data router, so the real hook would throw.
useNavigation: () => ({ state: "idle" }),
};
});
@@ -84,6 +91,8 @@ vi.mock("~/modules/plugins/services/.server/PluginLifecycleService", () => ({
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",
@@ -106,17 +115,21 @@ const translations: Record<string, string> = {
"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.reviewedCapabilities": "I reviewed the requested plugin capabilities.",
"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.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",
@@ -128,39 +141,53 @@ const translations: Record<string, string> = {
"shared.enabled": "Enabled",
};
const pluginItem = {
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,
grantedAt: "2026-05-01T12:10:00.000Z",
grantedScopeJson: { allowedHosts: ["api.example.com"] },
metadata: { risk: "high", productionAvailable: false },
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),
installedAt: "2026-05-01T12:00:00.000Z",
settingsHref: "/app/acme/settings/plugins/pl-1",
auditHref: "/app/acme/settings/plugins/pl-1/audit",
};
function setLoaderData(canManage: boolean, item = pluginItem, canAudit = false) {
let submitSpy: ReturnType<typeof vi.fn>;
function setLoaderData(canManage: boolean, row: PluginCatalogRowInput = pluginRow, canAudit = false) {
vi.mocked(useLoaderData).mockReturnValue({
title: "Plugins",
tenantSlug: "acme",
canManage,
canAudit,
items: [item],
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>
@@ -172,13 +199,17 @@ function renderPluginsRoute() {
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", async () => {
it("hides mutation controls from read-only plugin users and exposes manifest state", () => {
renderPluginsRoute();
expect(screen.getByRole("heading", { name: "Plugins" })).toBeInTheDocument();
// 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();
@@ -186,7 +217,7 @@ describe("tenant plugin settings UI", () => {
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: "Approve capabilities" })).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();
@@ -206,19 +237,22 @@ describe("tenant plugin settings UI", () => {
expect(document.querySelector('[data-ui-id="ui.plugins.manifest.panel"]')).toBeInTheDocument();
});
it("shows the disable mutation control to plugin managers", () => {
it("submits the disable op for plugin managers", () => {
setLoaderData(true);
renderPluginsRoute();
expect(screen.getByRole("button", { name: "Disable" })).toHaveAttribute("data-ui-id", "ui.plugins.lifecycle.button");
expect(document.querySelector('[data-ui-id="ui.plugins.lifecycle.form"]')).toBeInTheDocument();
expect(document.querySelector('input[name="id"]')).toHaveAttribute("value", "pl-1");
expect(document.querySelector('input[name="op"]')).toHaveAttribute("value", "disable");
expect(document.querySelector('input[name="csrf"]')).toHaveAttribute("value", "csrf-token");
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, pluginItem, true);
setLoaderData(false, pluginRow, true);
renderPluginsRoute();
const auditLink = screen.getByRole("link", { name: "View audit" });
@@ -227,30 +261,38 @@ describe("tenant plugin settings UI", () => {
expect(screen.queryByRole("button", { name: "Disable" })).not.toBeInTheDocument();
});
it("shows revoke controls for granted capabilities to plugin managers", () => {
it("confirms a capability revoke in a real ~/ui dialog before submitting", () => {
setLoaderData(true);
renderPluginsRoute();
expect(screen.getByRole("button", { name: "Revoke approval" })).toHaveAttribute("data-ui-id", "ui.plugins.capability.revoke.button");
expect(document.querySelector('[data-ui-id="ui.plugins.capability.revoke.form"]')).toBeInTheDocument();
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();
expect(document.querySelector('input[name="pluginId"]')).toHaveAttribute("value", "com.acme.outbound");
expect(document.querySelector('input[name="capabilityNames[]"]')).toHaveAttribute("value", "http.outbound");
// 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, {
...pluginItem,
...pluginRow,
enabled: false,
capabilities: [
{
name: "log",
scope: null,
granted: false,
grantedAt: null,
grantedScopeJson: null,
metadata: { risk: "low", productionAvailable: true },
},
{ name: "log", scope: null, granted: false, grantedAtIso: null, hookName: null, known: true, risk: "low", productionAvailable: true },
],
missingCapabilities: ["log"],
});
@@ -259,63 +301,75 @@ describe("tenant plugin settings UI", () => {
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("aria-expanded", "false");
expect(reviewToggle).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.toggle");
expect(screen.queryByRole("button", { name: "Approve and enable" })).not.toBeInTheDocument();
fireEvent.click(reviewToggle);
expect(reviewToggle).toHaveAttribute("aria-expanded", "true");
expect(screen.getByRole("form", { name: "Capability review for com.acme.outbound" })).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.form");
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(screen.getByText("Low risk")).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.risk");
expect(screen.getByText("Available in this runtime")).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.availability");
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.getByLabelText("I reviewed Logging.");
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();
expect(document.querySelector('input[name="op"]')).toHaveAttribute("value", "grantAndEnable");
expect(document.querySelector('input[name="capabilities[]"]')).toHaveAttribute("value", "log");
expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "yes");
expect(document.querySelector('input[name="capabilityReviewDigest"]')).toHaveAttribute("value", "review-digest");
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(screen.queryByRole("form", { name: "Capability review for com.acme.outbound" })).not.toBeInTheDocument();
expect(submitSpy).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Review capabilities" }));
expect(screen.getByLabelText("I reviewed Logging.")).not.toBeChecked();
expect(screen.getByRole("checkbox", { name: "I reviewed Logging." })).not.toBeChecked();
expect(screen.getByRole("button", { name: "Approve and enable" })).toBeDisabled();
expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "no");
});
it("keeps approval disabled until every missing capability is reviewed", () => {
setLoaderData(true, {
...pluginItem,
...pluginRow,
enabled: false,
capabilities: [
{
name: "log",
scope: null,
granted: false,
grantedAt: null,
grantedScopeJson: null,
metadata: { risk: "low", productionAvailable: true },
},
{
name: "audit",
scope: null,
granted: false,
grantedAt: null,
grantedScopeJson: null,
metadata: { risk: "medium", productionAvailable: true },
},
{ 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"],
});
@@ -325,18 +379,19 @@ describe("tenant plugin settings UI", () => {
const approveButton = screen.getByRole("button", { name: "Approve and enable" });
expect(approveButton).toBeDisabled();
fireEvent.click(screen.getByLabelText("I reviewed Logging."));
fireEvent.click(screen.getByRole("checkbox", { name: "I reviewed Logging." }));
expect(approveButton).toBeDisabled();
expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "no");
fireEvent.click(screen.getByLabelText("I reviewed Audit logging."));
fireEvent.click(screen.getByRole("checkbox", { name: "I reviewed Audit logging." }));
expect(approveButton).toBeEnabled();
expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "yes");
fireEvent.click(approveButton);
expect(submittedForm().getAll("capabilities[]")).toEqual(["log", "audit"]);
});
it("requires explicit review before enabling hook-only plugins", () => {
setLoaderData(true, {
...pluginItem,
...pluginRow,
pluginId: "com.acme.workflow-hook",
enabled: false,
capabilities: [
@@ -344,9 +399,11 @@ describe("tenant plugin settings UI", () => {
name: "hook:workflow.executed",
scope: null,
granted: false,
grantedAt: null,
grantedScopeJson: null,
metadata: { risk: "medium", productionAvailable: true },
grantedAtIso: null,
hookName: "workflow.executed",
known: false,
risk: "medium",
productionAvailable: true,
},
],
missingCapabilities: ["hook:workflow.executed"],
@@ -363,82 +420,69 @@ describe("tenant plugin settings UI", () => {
const approveButton = screen.getByRole("button", { name: "Approve and enable" });
expect(approveButton).toBeDisabled();
const reviewCheckbox = screen.getByLabelText("I reviewed Hook: workflow.executed.");
expect(reviewCheckbox).toHaveAttribute("value", "hook:workflow.executed");
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();
expect(screen.getAllByText("No additional scope.")).toHaveLength(2);
fireEvent.click(reviewCheckbox);
expect(approveButton).toBeEnabled();
expect(document.querySelector('input[name="op"]')).toHaveAttribute("value", "grantAndEnable");
expect(document.querySelector('input[name="capabilities[]"]')).toHaveAttribute("value", "hook:workflow.executed");
expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "yes");
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 itemWithMissingCapability = {
...pluginItem,
const rowWithMissingCapability: PluginCatalogRowInput = {
...pluginRow,
enabled: false,
capabilities: [
{
name: "log",
scope: null,
granted: false,
grantedAt: null,
grantedScopeJson: null,
metadata: { risk: "low", productionAvailable: true },
},
{ name: "log", scope: null, granted: false, grantedAtIso: null, hookName: null, known: true, risk: "low", productionAvailable: true },
],
missingCapabilities: ["log"],
};
setLoaderData(true, itemWithMissingCapability);
setLoaderData(true, rowWithMissingCapability);
const view = renderPluginsRoute();
fireEvent.click(screen.getByRole("button", { name: "Review capabilities" }));
fireEvent.click(screen.getByLabelText("I reviewed Logging."));
fireEvent.click(screen.getByRole("checkbox", { name: "I reviewed Logging." }));
expect(screen.getByRole("button", { name: "Approve and enable" })).toBeEnabled();
setLoaderData(true, {
...itemWithMissingCapability,
capabilityReviewDigest: "changed-review-digest",
capabilities: [
{
name: "log",
scope: null,
granted: false,
grantedAt: null,
grantedScopeJson: null,
metadata: { risk: "low", productionAvailable: true },
},
],
});
// 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.getByLabelText("I reviewed Logging.")).not.toBeChecked();
expect(screen.getByRole("button", { name: "Approve and enable" })).toBeDisabled();
expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "no");
expect(document.querySelector('input[name="capabilityReviewDigest"]')).toHaveAttribute("value", "changed-review-digest");
expect(screen.getAllByText("No additional scope.")).toHaveLength(2);
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, {
...pluginItem,
...pluginRow,
enabled: false,
capabilities: [
{
name: "http.outbound",
scope: { allowedHosts: ["api.example.com"] },
granted: false,
grantedAt: null,
grantedScopeJson: null,
metadata: { risk: "high", productionAvailable: false },
grantedAtIso: null,
hookName: null,
known: true,
risk: "high",
productionAvailable: false,
},
],
missingCapabilities: ["http.outbound"],
@@ -447,30 +491,100 @@ describe("tenant plugin settings UI", () => {
fireEvent.click(screen.getByRole("button", { name: "Review capabilities" }));
expect(screen.getByText("High risk")).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.risk");
expect(screen.getByText("Not available in this runtime")).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.availability");
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.getByLabelText("I reviewed Outbound HTTP.")).toBeDisabled();
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(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "no");
expect(screen.getAllByText("Allowed hosts: api.example.com").length).toBeGreaterThan(0);
});
it("keeps capability-free plugins enable-able without consent controls", () => {
setLoaderData(true, {
...pluginItem,
enabled: false,
capabilities: [],
missingCapabilities: [],
});
setLoaderData(true, { ...pluginRow, enabled: false, capabilities: [], missingCapabilities: [] });
renderPluginsRoute();
expect(screen.getByText("This plugin declares no capabilities.")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Enable" })).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 () => {
@@ -491,27 +605,29 @@ describe("tenant plugin settings UI", () => {
);
});
it("has no axe violations for expanded capability review controls", async () => {
it("has no axe violations for the expanded capability review dialog", async () => {
setLoaderData(true, {
...pluginItem,
...pluginRow,
enabled: false,
capabilities: [
{
name: "http.outbound",
scope: { allowedHosts: ["api.example.com"] },
granted: false,
grantedAt: null,
grantedScopeJson: null,
metadata: { risk: "high", productionAvailable: false },
grantedAtIso: null,
hookName: null,
known: true,
risk: "high",
productionAvailable: false,
},
],
missingCapabilities: ["http.outbound"],
});
const { container } = renderPluginsRoute();
const { baseElement } = renderPluginsRoute();
fireEvent.click(screen.getByRole("button", { name: "Review capabilities" }));
expect(screen.getByRole("form", { name: "Capability review for com.acme.outbound" })).toBeInTheDocument();
expect((await runAxe(container)).violations).toEqual([]);
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",
};
@@ -0,0 +1,29 @@
import { redirect, type LoaderFunctionArgs } from "react-router";
import UrlUtils from "~/utils/app/UrlUtils";
/**
* AK-SET-01 · one-hop redirects from the pre-hub settings URLs.
*
* Follows the pattern already used for the legacy `/:tenant/api/*` routes: the
* old route keeps a loader that answers 302 and nothing else.
*
* Two rules the contract test enforces:
* - the query string survives, because callers such as
* SubscriptionUrlUtils.subscriptionRequiredCheckoutPath rely on
* `?subscription_required=1` reaching the target;
* - the target is never itself a redirect, so no URL costs two hops.
*/
export function legacySettingsRedirect({ request, params }: Pick<LoaderFunctionArgs, "request" | "params">, target: string): Response {
const { search, hash } = new URL(request.url);
return redirect(`${UrlUtils.currentTenantUrl(params, target)}${search}${hash}`);
}
/**
* Convenience for a route file whose only job is the redirect:
*
* export const loader = legacySettingsRedirectLoader("settings/billing");
*/
export function legacySettingsRedirectLoader(target: string) {
return ({ request, params }: LoaderFunctionArgs) => legacySettingsRedirect({ request, params }, target);
}
@@ -0,0 +1,90 @@
import type { LoaderFunctionArgs } from "react-router";
import { describe, expect, it, vi } from "vitest";
vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: vi.fn().mockResolvedValue(undefined) }));
type RedirectModule = {
loader: (args: LoaderFunctionArgs) => Response | Promise<Response>;
};
type RedirectContract = {
name: string;
load: () => Promise<RedirectModule>;
from: string;
to: string;
params?: Record<string, string>;
};
const REDIRECTS: ReadonlyArray<RedirectContract> = [
{ name: "settings/usage", load: () => import("./usage"), from: "/acme/settings/usage", to: "/acme/settings/billing/usage" },
{ name: "settings/subscription", load: () => import("./subscription/index"), from: "/acme/settings/subscription", to: "/acme/settings/billing" },
{ name: "settings/credits", load: () => import("./credits"), from: "/acme/settings/credits", to: "/acme/settings/billing" },
{ name: "settings/account", load: () => import("./account"), from: "/acme/settings/account", to: "/acme/settings/workspace" },
{ name: "settings/policies", load: () => import("./policies"), from: "/acme/settings/policies", to: "/acme/settings/workspace/policies" },
{ name: "settings/onboarding/demo-data", load: () => import("./onboarding/demo-data"), from: "/acme/settings/onboarding/demo-data", to: "/acme/settings/workspace/demo-data" },
{ name: "settings/security", load: () => import("./security"), from: "/acme/settings/security", to: "/acme/settings/profile/security" },
{ name: "settings/notifications", load: () => import("./notifications"), from: "/acme/settings/notifications", to: "/acme/settings/profile/notifications" },
{ name: "settings/privacy", load: () => import("./privacy"), from: "/acme/settings/privacy", to: "/acme/settings/profile/data" },
{ name: "settings/privacy/export", load: () => import("./privacy.export"), from: "/acme/settings/privacy/export", to: "/acme/settings/compliance/data-export" },
{ name: "settings/privacy/avv", load: () => import("./privacy.avv"), from: "/acme/settings/privacy/avv", to: "/acme/settings/compliance/avv" },
{ name: "settings/privacy/subprocessors", load: () => import("./privacy.subprocessors"), from: "/acme/settings/privacy/subprocessors", to: "/acme/settings/compliance/subprocessors" },
{ name: "settings/privacy/deletion", load: () => import("./privacy.deletion"), from: "/acme/settings/privacy/deletion", to: "/acme/settings/compliance/tenant-deletion" },
{ name: "settings/members", load: () => import("./members"), from: "/acme/settings/members", to: "/acme/settings/team" },
{ name: "settings/members/new", load: () => import("./members/new"), from: "/acme/settings/members/new", to: "/acme/settings/team/members/new" },
{ name: "settings/members/edit/:id", load: () => import("./members/edit.$id"), from: "/acme/settings/members/edit/user-1", to: "/acme/settings/team/members/edit/user-1", params: { id: "user-1" } },
{ name: "settings/members/groups/new", load: () => import("./members/groups/new"), from: "/acme/settings/members/groups/new", to: "/acme/settings/team/members/groups/new" },
{ name: "settings/members/groups/:id", load: () => import("./members/groups/$id"), from: "/acme/settings/members/groups/group-1", to: "/acme/settings/team/members/groups/group-1", params: { id: "group-1" } },
{ name: "settings/groups", load: () => import("./groups"), from: "/acme/settings/groups", to: "/acme/settings/team/groups" },
{ name: "settings/groups/new", load: () => import("./groups/new"), from: "/acme/settings/groups/new", to: "/acme/settings/team/groups/new" },
{ name: "settings/groups/:id", load: () => import("./groups/$id"), from: "/acme/settings/groups/group-1", to: "/acme/settings/team/groups/group-1", params: { id: "group-1" } },
{ name: "settings/roles-and-permissions", load: () => import("./roles-and-permissions/index"), from: "/acme/settings/roles-and-permissions", to: "/acme/settings/team/roles" },
{ name: "settings/roles-and-permissions/roles", load: () => import("./roles-and-permissions/roles"), from: "/acme/settings/roles-and-permissions/roles", to: "/acme/settings/team/roles" },
{ name: "settings/roles-and-permissions/roles/new", load: () => import("./roles-and-permissions/roles/new"), from: "/acme/settings/roles-and-permissions/roles/new", to: "/acme/settings/team/roles/new" },
{ name: "settings/roles-and-permissions/roles/:id", load: () => import("./roles-and-permissions/roles/$id"), from: "/acme/settings/roles-and-permissions/roles/role-1", to: "/acme/settings/team/roles/role-1", params: { id: "role-1" } },
{ name: "settings/roles-and-permissions/permissions", load: () => import("./roles-and-permissions/permissions"), from: "/acme/settings/roles-and-permissions/permissions", to: "/acme/settings/team/roles" },
{ name: "settings/roles-and-permissions/users", load: () => import("./roles-and-permissions/users"), from: "/acme/settings/roles-and-permissions/users", to: "/acme/settings/team" },
{ name: "settings/logs", load: () => import("./logs/index"), from: "/acme/settings/logs", to: "/acme/settings/compliance" },
{ name: "settings/logs/events", load: () => import("./logs/events"), from: "/acme/settings/logs/events", to: "/acme/settings/compliance/events" },
{ name: "settings/logs/events/:id", load: () => import("./logs/events.$id"), from: "/acme/settings/logs/events/event-1", to: "/acme/settings/compliance/events/event-1", params: { id: "event-1" } },
{ name: "settings/audit-export", load: () => import("./audit-export"), from: "/acme/settings/audit-export", to: "/acme/settings/compliance/audit-export" },
{ name: "settings/chat/audit", load: () => import("./chat/audit"), from: "/acme/settings/chat/audit", to: "/acme/settings/compliance/chat" },
{ name: "settings/chat/audit/:id", load: () => import("./chat/audit.$id"), from: "/acme/settings/chat/audit/chat-1", to: "/acme/settings/compliance/chat/chat-1", params: { id: "chat-1" } },
{ name: "settings/plugins", load: () => import("./plugins"), from: "/acme/settings/plugins", to: "/acme/settings/integrations/plugins" },
{ name: "settings/plugins/:id", load: () => import("./plugins.$id"), from: "/acme/settings/plugins/plugin-1", to: "/acme/settings/integrations/plugins/plugin-1", params: { id: "plugin-1" } },
{ name: "settings/plugins/:id/audit", load: () => import("./plugins.$id.audit"), from: "/acme/settings/plugins/plugin-1/audit", to: "/acme/settings/integrations/plugins/plugin-1/audit", params: { id: "plugin-1" } },
{ name: "settings/api", load: () => import("./api/index"), from: "/acme/settings/api", to: "/acme/settings/integrations/api" },
{ name: "settings/api/logs", load: () => import("./api/logs"), from: "/acme/settings/api/logs", to: "/acme/settings/integrations/api/logs" },
{ name: "settings/api/keys", load: () => import("./api/keys"), from: "/acme/settings/api/keys", to: "/acme/settings/integrations/api/keys" },
{ name: "settings/api/keys/new", load: () => import("./api/keys/new"), from: "/acme/settings/api/keys/new", to: "/acme/settings/integrations/api/keys/new" },
{ name: "settings/api/keys/:id", load: () => import("./api/keys/$id"), from: "/acme/settings/api/keys/key-1", to: "/acme/settings/integrations/api/keys/key-1", params: { id: "key-1" } },
];
async function callLoader(entry: RedirectContract, suffix = "") {
const { loader } = await entry.load();
return loader({
request: new Request(`https://app.example.test${entry.from}${suffix}`),
params: { tenant: "acme", ...entry.params },
context: {},
unstable_pattern: entry.name,
} as unknown as LoaderFunctionArgs);
}
describe("legacy settings redirects", () => {
it.each(REDIRECTS)("$name answers 302 to its canonical hub target", async (entry) => {
const response = await callLoader(entry);
expect(response.status).toBe(302);
expect(response.headers.get("Location")).toBe(entry.to);
});
it.each(REDIRECTS)("$name keeps the query string", async (entry) => {
const response = await callLoader(entry, "?subscription_required=1&page=2");
expect(response.headers.get("Location")).toBe(`${entry.to}?subscription_required=1&page=2`);
});
it("covers every visual redirect route and never chains one redirect into another", () => {
expect(REDIRECTS).toHaveLength(41);
const targets = REDIRECTS.map((entry) => entry.to);
const sources = REDIRECTS.map((entry) => entry.from);
expect(targets.filter((target) => sources.includes(target))).toEqual([]);
});
});
@@ -0,0 +1,29 @@
// Published tenant events CSV resource route. It stays on the old URL while
// the visual events page lives in the Compliance hub.
import type { LoaderFunctionArgs } from "react-router";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import { getEvents, serializeEventsCsv } from "~/modules/events/db/events.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getFiltersFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { CSV_EXPORT_TAKE } from "../compliance/logs-export.helpers.server";
const filterableProperties: FilterablePropertyDto[] = [
{ name: "name", title: "settings.logs.events.filters.event" },
{ name: "data", title: "settings.logs.events.filters.data" },
{ name: "userId", title: "models.user.object" },
];
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
const { items } = await getEvents({ current: { page: 1, pageSize: CSV_EXPORT_TAKE }, filters }, tenantId);
return new Response(serializeEventsCsv(items), {
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": 'attachment; filename="tenant-events.csv"',
},
});
};
@@ -1,50 +1,10 @@
import { LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
import { useParams } from "react-router";
import { useTranslation } from "react-i18next";
import EventDetails from "~/modules/events/components/EventDetails";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import UrlUtils from "~/utils/app/UrlUtils";
import { EventWithDetails, getEvent } from "~/modules/events/db/events.db.server";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import EventUtils from "~/modules/events/utils/EventUtils";
// AK-SET-01 — legacy log-event detail path; the id has to survive the redirect.
import type { LoaderFunctionArgs } from "react-router";
import { legacySettingsRedirect } from "../legacy-redirects.server";
type LoaderData = {
item: EventWithDetails;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
const item = await getEvent(params.id ?? "", tenantId);
if (!item) {
throw redirect(UrlUtils.getModulePath(params, "logs/events"));
}
export const loader = ({ request, params }: LoaderFunctionArgs) =>
legacySettingsRedirect({ request, params }, `settings/compliance/events/${encodeURIComponent(params.id ?? "")}`);
const data: LoaderData = {
item,
};
return data;
};
export default function AppEventDetailsRoute() {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const params = useParams();
return (
<EditPageLayout
title={t("models.event.object")}
withHome={false}
menu={[
{
title: t("models.event.plural"),
routePath: UrlUtils.getModulePath(params, "logs/events"),
},
{
title: EventUtils.parseName(data.item.name, t),
},
]}
>
<EventDetails item={data.item} />
</EditPageLayout>
);
export default function LegacyLogEventDetailRedirect() {
return null;
}
@@ -1,104 +1,8 @@
import { LoaderFunctionArgs, useLoaderData } 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 { ApplicationEvents, getApplicationEventNameKey } from "~/modules/events/types/ApplicationEvent";
import EventsTable from "~/modules/events/components/EventsTable";
import InputFilters from "~/components/ui/input/InputFilters";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { EventWithAttempts, getEvents } from "~/modules/events/db/events.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUsersByTenant } from "~/utils/db/users.db.server";
import Tabs from "~/components/ui/tabs/Tabs";
// AK-SET-01 — legacy `settings/logs/events`.
import { legacySettingsRedirectLoader } from "../legacy-redirects.server";
type LoaderData = {
title: string;
items: EventWithAttempts[];
pagination: PaginationDto;
filterableProperties: FilterablePropertyDto[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
const { t } = await getTranslations(request);
export const loader = legacySettingsRedirectLoader("settings/compliance/events");
const urlSearchParams = new URL(request.url).searchParams;
const current = getPaginationFromCurrentUrl(urlSearchParams);
const filterableProperties: FilterablePropertyDto[] = [
{
name: "name",
title: "settings.logs.events.filters.event",
options: ApplicationEvents.filter((f) => !f.adminOnly || !params.tenant).map((item) => {
return {
value: item.value,
name: t("settings.logs.events.filters.eventOption", { eventValue: item.value, eventLabel: t(getApplicationEventNameKey(item.value)) }),
};
}),
},
{
name: "data",
title: "settings.logs.events.filters.data",
},
{
name: "userId",
title: "models.user.object",
options: (await getUsersByTenant(tenantId)).map((item) => {
return {
value: item.id,
name: item.email,
};
}),
},
];
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
const { items, pagination } = await getEvents({ current, filters }, tenantId);
const data: LoaderData = {
title: `${t("models.event.plural")} | ${process.env.APP_NAME}`,
items,
pagination,
filterableProperties,
};
return data;
};
export default function AppEventsRoute() {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const params = useParams();
return (
<EditPageLayout>
<div data-ui-id="ui.settings.logs.events.page" className="space-y-2">
<div className="flex justify-between gap-2">
<div data-ui-id="ui.settings.logs.tabs" className="grow">
<Tabs
tabs={[
{
name: t("models.log.plural"),
routePath: UrlUtils.getModulePath(params, "logs"),
},
{
name: t("models.event.plural"),
routePath: UrlUtils.getModulePath(params, "logs/events"),
},
]}
/>
</div>
<div data-ui-id="ui.settings.logs.filters">
<InputFilters size="sm" filters={data.filterableProperties} />
</div>
</div>
<div data-ui-id="ui.settings.logs.events.table">
<EventsTable items={data.items} pagination={data.pagination} />
</div>
</div>
</EditPageLayout>
);
export default function LegacyLogEventsRedirect() {
return null;
}
@@ -0,0 +1,21 @@
// Published tenant audit-log CSV resource route. Its URL deliberately stays
// under settings/logs after the visual page moved into the Compliance hub.
import type { LoaderFunctionArgs } from "react-router";
import { getTenantAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { CSV_EXPORT_TAKE, getTenantAuditLogFiltersFromUrl } from "../compliance/logs-export.helpers.server";
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
const filters = getTenantAuditLogFiltersFromUrl(new URL(request.url).searchParams);
const { rows } = await getTenantAuditLogList(tenantId, { ...filters, take: CSV_EXPORT_TAKE, skip: 0 });
return new Response(serializeAdminAuditLogsCsv(rows), {
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": 'attachment; filename="tenant-audit-logs.csv"',
},
});
};
@@ -1,150 +1,8 @@
import type { AdminAuditLogFilters, AdminAuditLogRow } from "@hivegrid/db/logs.server";
import { getTenantAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
import { LoaderFunctionArgs, MetaFunction, useLoaderData } 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 TenantActivityLogToolbar from "~/components/activity/TenantActivityLogToolbar";
import LogsTable from "~/components/app/events/LogsTable";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import UrlUtils from "~/utils/app/UrlUtils";
import { getTranslations } from "~/locale/i18next.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import Tabs from "~/components/ui/tabs/Tabs";
// AK-SET-01 — legacy `settings/logs` is now the Audit-Log tab of the Compliance-Hub.
import { legacySettingsRedirectLoader } from "../legacy-redirects.server";
const CSV_EXPORT_TAKE = 500;
export const loader = legacySettingsRedirectLoader("settings/compliance");
type LoaderData = {
title: string;
items: AdminAuditLogRow[];
pagination: PaginationDto;
filterableProperties: FilterablePropertyDto[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
const { t } = await getTranslations(request);
const filterableProperties = getAuditLogFilterableProperties();
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
const urlSearchParams = new URL(request.url).searchParams;
const auditLogFilters = getAuditLogFiltersFromUrl(urlSearchParams);
if (urlSearchParams.get("export") === "csv") {
const { rows } = await getTenantAuditLogList(tenantId, { ...auditLogFilters, take: CSV_EXPORT_TAKE, skip: 0 });
return new Response(serializeAdminAuditLogsCsv(rows), {
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": 'attachment; filename="tenant-audit-logs.csv"',
},
});
}
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
const pageSize = normalizePositiveInteger(currentPagination.pageSize, 10);
const page = normalizePositiveInteger(currentPagination.page, 1);
const { rows, total, take } = await getTenantAuditLogList(tenantId, {
...auditLogFilters,
take: pageSize,
skip: pageSize * (page - 1),
});
const data: LoaderData = {
title: `${t("models.log.plural")} | ${process.env.APP_NAME}`,
items: rows,
pagination: {
page,
pageSize: take,
totalItems: total,
totalPages: Math.ceil(total / take),
sortedBy: currentPagination.sortedBy,
query: currentPagination.query,
},
filterableProperties: filters.properties,
};
return data;
};
function getAuditLogFilterableProperties(): FilterablePropertyDto[] {
return [
{
name: "action",
title: "models.log.action",
},
{
name: "url",
title: "models.log.url",
},
{
name: "userId",
title: "shared.createdBy",
},
{
name: "createdAtFrom",
title: "shared.createdAt",
},
{
name: "createdAtTo",
title: "shared.createdAt",
},
];
}
function getAuditLogFiltersFromUrl(urlSearchParams: URLSearchParams): AdminAuditLogFilters {
return {
q: urlSearchParams.get("q"),
action: urlSearchParams.get("action"),
url: urlSearchParams.get("url"),
userId: urlSearchParams.get("userId"),
createdAtFrom: urlSearchParams.get("createdAtFrom"),
createdAtTo: urlSearchParams.get("createdAtTo"),
};
}
function normalizePositiveInteger(value: number | null | undefined, fallback: number): number {
if (!Number.isFinite(value) || !value || value < 1) return fallback;
return Math.trunc(value);
}
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function Events() {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const params = useParams();
return (
<EditPageLayout
// title={t("models.log.plural")}
>
<div data-ui-id="ui.settings.logs.page" className="space-y-2">
<div className="flex justify-between gap-2">
<div data-ui-id="ui.settings.logs.tabs" className="grow">
<Tabs
tabs={[
{
name: t("models.log.plural"),
routePath: UrlUtils.getModulePath(params, "logs"),
},
{
name: t("models.event.plural"),
routePath: UrlUtils.getModulePath(params, "logs/events"),
},
]}
/>
</div>
<div data-ui-id="ui.settings.logs.filters">
<TenantActivityLogToolbar filters={data.filterableProperties} />
</div>
</div>
<div data-ui-id="ui.settings.logs.table">
<LogsTable withTenant={false} items={data.items} pagination={data.pagination} />
</div>
</div>
</EditPageLayout>
);
export default function LegacyLogsRedirect() {
return null;
}
@@ -1,341 +1,8 @@
import { useEffect } from "react";
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData } from "react-router";
import { useNavigate, useNavigation, useOutlet, useParams, useSubmit } from "react-router";
import { useTranslation } from "react-i18next";
import toast from "react-hot-toast";
import { buildMembersListVM, type MembersListVM, type MemberStatus } from "@hivegrid/view-models";
import { getTenant, getTenantMember, getTenantUsers } from "~/utils/db/tenants.db.server";
import { deleteUserInvitation, getUserInvitation, getUserInvitations } from "~/utils/db/tenantUserInvitations.db.server";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserPermission, verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantAssignableAppRole, getTenantAssignableAppRoles } from "~/utils/db/permissions/roles.db.server";
import { getEnabledTotpUserIds, getUser, getUserTotpStatus } from "~/utils/db/users.db.server";
import { createAdminLog } from "~/utils/db/logs.db.server";
import { createUserRole, deleteUserRole } from "~/utils/db/permissions/userRoles.db.server";
import { createImpersonationStartedAt, createUserSession, getUserInfo, getUserSession, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
import { deactivateTenantUser, reactivateTenantUser } from "~/utils/services/tenantUserLifecycle.server";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import { MembersPage, type MembersActions } from "~/components/screens/users/MembersPage";
import { Dialog } from "~/ui/components/Dialog";
import { DefaultAppRoles } from "~/application/dtos/shared/DefaultAppRoles";
import { useRootData } from "~/utils/data/useRootData";
import EventsService from "~/modules/events/services/.server/EventsService";
import { RoleAssignedDto } from "~/modules/events/dtos/RoleAssignedDto";
import { RoleUnassignedDto } from "~/modules/events/dtos/RoleUnassignedDto";
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { absoluteAdminPath, absoluteAppPath } from "~/utils/app/CrossHostUrls";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
// AK-SET-01 — legacy `settings/members` is now the Mitglieder tab of the Team-Hub.
import { legacySettingsRedirectLoader } from "./legacy-redirects.server";
type LoaderData = {
title: string;
vm: MembersListVM;
canViewRoles: boolean;
};
export const loader = legacySettingsRedirectLoader("settings/team");
function toMemberStatus(status: TenantUserStatus): MemberStatus {
if (status === TenantUserStatus.ACTIVE) return "active";
if (status === TenantUserStatus.INACTIVE) return "inactive";
return "invited";
}
async function hasPermission(userId: string, permissionName: string, tenantId: string): Promise<boolean> {
const { permission, userPermission } = await getUserPermission({ userId, permissionName, tenantId });
return !permission || Boolean(userPermission);
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
const userInfo = await getUserInfo(request);
await verifyUserHasPermission(request, "app.settings.members.view", tenantId);
// Deactivated members stay visible with status "Deaktiviert" (David's S01/M03).
const [users, pendingInvitations, roles, canInvite, canEditRoles, canManageMembers, canViewRoles] = await Promise.all([
getTenantUsers(tenantId, { includeInactive: true }),
getUserInvitations(tenantId),
// Assignable defaults + the tenant's own custom/SHK roles (D01 dropdown).
getTenantAssignableAppRoles(tenantId),
hasPermission(userInfo.userId, "app.settings.members.create", tenantId),
hasPermission(userInfo.userId, "app.settings.roles.set", tenantId),
hasPermission(userInfo.userId, "app.settings.members.update", tenantId),
hasPermission(userInfo.userId, "app.settings.roles.view", tenantId),
]);
const mfaEnabledUserIds = new Set(await getEnabledTotpUserIds(users.map((member) => member.user.id)));
const vm = buildMembersListVM({
rows: users.map((member) => ({
tenantUserId: member.id,
userId: member.userId,
firstName: member.user.firstName,
lastName: member.user.lastName,
email: member.user.email,
phone: member.user.phone,
status: toMemberStatus(member.status),
mfaEnabled: mfaEnabledUserIds.has(member.user.id),
roles: member.user.roles
.filter((userRole) => userRole.tenantId === tenantId)
.map((userRole) => ({ id: userRole.role.id, name: userRole.role.name, description: userRole.role.description })),
})),
pendingInvitations: pendingInvitations.map((invitation) => ({
id: invitation.id,
email: invitation.email,
name: [invitation.firstName, invitation.lastName].filter(Boolean).join(" "),
createdAtIso: null,
})),
assignableRoles: roles.map((role) => ({ id: role.id, name: role.name, description: role.description })),
currentUserId: userInfo.userId,
canInvite,
canEditRoles,
canManageMembers,
});
const data: LoaderData = {
title: `${t("settings.members.title")} | ${process.env.APP_NAME}`,
vm,
canViewRoles,
};
return data;
};
type ActionData = {
success?: string;
error?: string;
/** Machine-readable guard code — "last-admin" opens the V01 blocker dialog. */
code?: 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.members.update", tenantId);
await validateCSRFToken(request);
const userInfo = await getUserInfo(request);
const form = await request.formData();
const action = form.get("action")?.toString();
const fromUser = await getUser(userInfo.userId);
if (!fromUser) {
return badRequest({ error: t("settings.members.errors.invalidUser") });
}
if (action === "delete-invitation") {
await verifyUserHasPermission(request, "app.settings.members.delete", tenantId);
const invitationId = form.get("invitation-id")?.toString() ?? "";
const invitation = await getUserInvitation(invitationId, tenantId);
if (!invitation) {
return badRequest({
error: t("settings.members.errors.invitationNotFound"),
});
}
await deleteUserInvitation(invitation.id, tenantId);
return Response.json({ success: t("settings.members.success.invitationDeleted") });
}
if (action === "deactivate" || action === "reactivate") {
// R-P2b user lifecycle (M03/V01): soft-deactivation via the lifecycle service.
// Reassign-on-deactivate stays Backlog/V2 (David) — the service keeps the option.
const userId = form.get("user-id")?.toString() ?? "";
const tenant = await getTenant(tenantId);
const tenantMember = await getTenantMember(userId, tenantId);
if (!tenant || !tenantMember) {
return badRequest({ error: t("shared.invalidForm") });
}
if (action === "deactivate") {
const result = await deactivateTenantUser({ tenantId, targetUserId: userId });
if (!result.ok) {
if (result.reason === "last-admin") {
return badRequest({ error: t("settings.members.errors.lastAdminBody"), code: "last-admin" });
}
return badRequest({ error: t("shared.invalidForm") });
}
createAdminLog(request, "settings.members.deactivated", `[${tenant.name}] ${tenantMember.user.email}`);
return Response.json({ success: t("settings.members.success.deactivated") });
}
const result = await reactivateTenantUser({ tenantId, targetUserId: userId });
if (!result.ok) {
return badRequest({ error: t("shared.invalidForm") });
}
createAdminLog(request, "settings.members.reactivated", `[${tenant.name}] ${tenantMember.user.email}`);
return Response.json({ success: t("settings.members.success.reactivated") });
}
if (action === "edit") {
await verifyUserHasPermission(request, "app.settings.roles.set", tenantId);
const userId = form.get("user-id")?.toString() ?? "";
const roleId = form.get("role-id")?.toString() ?? "";
const add = form.get("add") === "true";
const tenant = await getTenant(tenantId);
const tenantMember = await getTenantMember(userId, tenantId);
const user = tenantMember?.user ?? null;
const role = await getTenantAssignableAppRole(roleId, tenantId);
if (!tenantMember || !user || !role || role.type !== "app" || !tenant) {
return badRequest({ error: t("shared.invalidForm") });
}
if (role?.name === DefaultAppRoles.SuperUser) {
const allMembers = await getTenantUsers(tenantId);
const activeMembers = allMembers.filter((member) => member.status === TenantUserStatus.ACTIVE);
const superAdmins = activeMembers.filter((m) => m.user.roles.some((r) => r.tenantId === tenantId && r.role.name === DefaultAppRoles.SuperUser));
if (superAdmins.length === 1 && !add) {
// Same guard family as deactivation: the workspace must keep an admin (V01).
return badRequest({
error: t("settings.members.errors.atLeastOneSuperAdmin"),
code: "last-admin",
});
}
if (userId === userInfo.userId) {
return badRequest({
error: t("settings.members.errors.cannotRemoveOwnSuperAdminRole"),
});
}
}
if (add) {
await createUserRole(userId, roleId, tenantId);
if (fromUser && user && role) {
await EventsService.create({
request,
event: "role.assigned",
tenantId,
userId: fromUser.id,
data: {
fromUser: { id: fromUser.id, email: fromUser.email },
toUser: { id: user.id, email: user.email },
role: { id: role.id, name: role.name, description: role.description },
} satisfies RoleAssignedDto,
});
}
createAdminLog(request, "settings.memberRoles.created", `[${tenant?.name}] ${user?.email} - ${role?.name}`);
} else {
await EventsService.create({
request,
event: "role.unassigned",
tenantId: tenant?.id ?? null,
userId: fromUser.id,
data: {
fromUser: { id: fromUser.id, email: fromUser.email },
toUser: { id: user.id, email: user.email },
role: { id: role.id, name: role.name, description: role.description },
} satisfies RoleUnassignedDto,
});
await deleteUserRole(userId, roleId, tenantId);
createAdminLog(request, "settings.memberRoles.deleted", `[${tenant?.name}] ${user?.email} - ${role?.name}`);
}
return Response.json({});
} else if (action === "impersonate") {
await verifyUserHasPermission(request, "app.settings.members.impersonate", tenantId);
const session = await getUserSession(request);
const mfaEnforcement = enforceAdminMfa({
requestUrl: request.url,
userId: fromUser.id,
isAdmin: Boolean(fromUser.admin),
totpStatus: await getUserTotpStatus(fromUser.id),
stepUp: checkMfaStepUpState(session, fromUser.id),
redirectMode: "host-aware",
appFallbackPath: appPath({ tenantSlug: params.tenant ?? "", path: "settings/members", mode: "host-aware" }),
});
if (!mfaEnforcement.allowed) {
const routing = loadRequiredWebConfig().routing;
if (mfaEnforcement.reason === "missing-admin" || mfaEnforcement.reason === "missing-user") {
throw redirect(absoluteAppPath(routing, params.tenant ?? "", "settings/members"));
}
throw redirect(absoluteAdminPath(routing, mfaEnforcement.redirectTo));
}
const userId = form.get("user-id")?.toString();
const tenantMember = await getTenantMember(userId, tenantId);
const user = tenantMember ? await getUser(userId) : null;
if (!tenantMember || !user) {
return badRequest({ error: t("shared.notFound") });
}
if (user.admin) {
return badRequest({ error: t("settings.members.errors.cannotImpersonateSuperAdmin") });
}
const userSession = await setLoggedUser(user);
if (!userSession) {
return badRequest({ error: t("shared.notFound") });
}
const tenant = await getTenant(tenantId);
return createUserSession(
{
...userInfo,
...userSession,
impersonatingFromUserId: userInfo.userId,
impersonatingStartedAt: createImpersonationStartedAt(),
},
tenant ? appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" }) : "/"
);
} else {
return badRequest({ error: t("shared.invalidForm") });
}
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function MembersSettingsRoute() {
const { t } = useTranslation();
const params = useParams();
const data = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const rootData = useRootData();
const navigate = useNavigate();
const navigation = useNavigation();
const outlet = useOutlet();
const submit = useSubmit();
const submitting = navigation.state === "submitting";
const lastAdminBlocked = actionData?.code === "last-admin";
useEffect(() => {
if (actionData?.success) {
toast.success(actionData.success);
} else if (actionData?.error && actionData.code !== "last-admin") {
toast.error(actionData.error);
}
}, [actionData]);
function post(fields: Record<string, string>) {
const formData = new FormData();
if (rootData.csrf) formData.set("csrf", rootData.csrf);
for (const [name, value] of Object.entries(fields)) {
formData.set(name, value);
}
submit(formData, { method: "post" });
}
const actions: MembersActions = {
onToggleRole: ({ userId, roleId, add }) => post({ action: "edit", "user-id": userId, "role-id": roleId, add: String(add) }),
onDeactivate: ({ userId }) => post({ action: "deactivate", "user-id": userId }),
onReactivate: ({ userId }) => post({ action: "reactivate", "user-id": userId }),
onDeleteInvitation: ({ invitationId }) => post({ action: "delete-invitation", "invitation-id": invitationId }),
onInvite: () => navigate(UrlUtils.currentTenantUrl(params, "settings/members/new")),
};
return (
<EditPageLayout>
<MembersPage
vm={data.vm}
actions={actions}
rolesTabHref={data.canViewRoles ? UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions/roles") : null}
editRouteFor={(tenantUserId) => UrlUtils.currentTenantUrl(params, `settings/members/edit/${tenantUserId}`)}
submitting={submitting}
lastAdminBlocked={lastAdminBlocked}
/>
{/* Child routes (M01 invite, member edit, group forms) render in a real Dialog (S 560). */}
<Dialog
open={!!outlet}
onOpenChange={(open: boolean) => {
if (!open) navigate(".", { replace: true });
}}
>
<Dialog.Content className="w-[560px] max-w-[90vw] p-6" aria-label={t("settings.members.form.newTitle")}>
<div className="w-full">{outlet}</div>
</Dialog.Content>
</Dialog>
</EditPageLayout>
);
export default function LegacyMembersRedirect() {
return null;
}
@@ -1,308 +1,10 @@
import { useTranslation } from "react-i18next";
import { useEffect, useRef } from "react";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
import SuccessModal, { RefSuccessModal } from "~/components/ui/modals/SuccessModal";
import { useEscapeKeypress } from "~/utils/shared/KeypressUtils";
import type { TenantUser, User } from "@hivegrid/db/prisma-browser";
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
import { Form, useActionData, useParams, useSubmit, useNavigation, useNavigate } from "react-router";
import { deleteTenantUser, getTenantUser, getTenantUsers } from "~/utils/db/tenants.db.server";
import { getTranslations } from "~/locale/i18next.server";
import clsx from "clsx";
import { useAppData } from "~/utils/data/useAppData";
import UrlUtils from "~/utils/app/UrlUtils";
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
import InputText from "~/components/ui/input/InputText";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { useRootData } from "~/utils/data/useRootData";
import { DefaultAppRoles } from "~/application/dtos/shared/DefaultAppRoles";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
// AK-SET-01 — legacy member edit path; the id has to survive the redirect.
import type { LoaderFunctionArgs } from "react-router";
import { legacySettingsRedirect } from "../legacy-redirects.server";
type LoaderData = {
metatags: MetaTagsDto;
member: (TenantUser & { user: User }) | null;
};
export const loader = ({ request, params }: LoaderFunctionArgs) =>
legacySettingsRedirect({ request, params }, `settings/team/members/edit/${encodeURIComponent(params.id ?? "")}`);
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.members.update", tenantId);
const { t } = await getTranslations(request);
const member = await getTenantUser(params.id, tenantId);
const data: LoaderData = {
metatags: [{ title: `${t("settings.members.actions.edit")} | ${process.env.APP_NAME}` }],
member,
};
return data;
};
type ActionData = {
error?: string;
success?: string;
fields?: {
email: string;
firstName: string;
lastName: string;
role: number;
};
};
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
export const action: ActionFunction = async ({ request, params }) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.members.update", tenantId);
await validateCSRFToken(request);
const { t } = await getTranslations(request);
const userInfo = await getUserInfo(request);
// const tenantId = await getTenantIdFromUrl(params);
const { id } = params;
if (!id) {
return badRequest({
error: t("shared.notFound"),
});
}
const form = await request.formData();
const action = form.get("action")?.toString();
// const email = form.get("email")?.toString().toLowerCase().trim();
// const firstName = form.get("firstName")?.toString() ?? "";
// const lastName = Number(form.get("lastName")) ?? "";
// const tenantUsers = await getTenantUsers(tenantId);
// const owners = tenantUsers?.filter((f) => f.type === TenantUserType.OWNER);
// if (owners?.length === 1 && owners?.find((f) => f.user.email === email) && type !== TenantUserType.OWNER) {
// return badRequest({
// error: t("api.errors.cannotBeWithoutOwner"),
// });
// }
if (action === "edit") {
const tenantUser = await getTenantUser(id, tenantId);
if (!tenantUser) {
return badRequest({
error: t("shared.notFound"),
});
}
return redirect(UrlUtils.currentTenantUrl(params, "settings/members"));
} else if (action === "delete") {
await verifyUserHasPermission(request, "app.settings.members.delete", tenantId);
const tenantUser = await getTenantUser(id, tenantId);
if (!tenantUser) {
return badRequest({
error: t("shared.notFound"),
});
}
if (tenantUser.userId === userInfo.userId) {
return badRequest({
error: t("settings.members.errors.cannotRemoveSelf"),
});
}
const allMembers = await getTenantUsers(tenantId);
const targetMember = allMembers.find((member) => member.id === tenantUser.id);
const targetIsSuperUser = targetMember?.user.roles.some((role) => role.tenantId === tenantId && role.role.name === DefaultAppRoles.SuperUser) ?? false;
if (targetIsSuperUser) {
const activeMembers = allMembers.filter((member) => member.status === TenantUserStatus.ACTIVE);
const superUsers = activeMembers.filter((member) =>
member.user.roles.some((role) => role.tenantId === tenantId && role.role.name === DefaultAppRoles.SuperUser)
);
if (superUsers.length <= 1) {
return badRequest({
error: t("settings.members.errors.atLeastOneSuperAdmin"),
});
}
}
try {
const deleted = await deleteTenantUser(id, tenantId);
if ("count" in deleted && deleted.count !== 1) {
return badRequest({
error: t("shared.notFound"),
});
}
} catch (e: any) {
return badRequest({
error: e.toString(),
});
}
return redirect(UrlUtils.currentTenantUrl(params, "settings/members"));
}
};
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags ?? [];
interface Props {
maxSize?: string;
}
export default function EditMemberRoute({ maxSize = "sm:max-w-lg" }: Props) {
const params = useParams();
const data = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const appData = useAppData();
const rootData = useRootData();
const { t } = useTranslation();
const navigate = useNavigate();
const submit = useSubmit();
const navigation = useNavigation();
const loading = navigation.state === "submitting";
const errorModal = useRef<RefErrorModal>(null);
const successModal = useRef<RefSuccessModal>(null);
const confirmRemove = useRef<RefConfirmModal>(null);
// const [item, setItem] = useState<TenantUserDto | null>(null);
// const [loading, setLoading] = useState(false);
// const [email, setEmail] = useState("");
// const [firstName, setFirstName] = useState("");
// const [lastName, setLastName] = useState("");
// const [phone, setPhone] = useState("");
useEffect(() => {
if (actionData?.error) {
errorModal.current?.show(actionData.error);
}
if (actionData?.success) {
successModal.current?.show(t("shared.success"), actionData.success);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [actionData]);
function close() {
navigate(UrlUtils.currentTenantUrl(params, "settings/members"));
}
function remove() {
if (!data.member) {
return;
}
confirmRemove.current?.show(
t("shared.confirmRemove"),
t("shared.remove"),
t("shared.cancel"),
t("settings.members.actions.removeConfirm", { email: data.member?.user.email })
);
}
function yesRemove() {
if (appData.currentRole === TenantUserType.MEMBER) {
errorModal.current?.show(t("account.tenant.onlyAdmin"));
} else {
const form = new FormData();
form.set("action", "delete");
if (rootData.csrf) {
form.set("csrf", rootData.csrf);
}
submit(form, {
method: "post",
});
}
}
useEscapeKeypress(close);
return (
<div>
{(() => {
if (!data.member) {
return <div>{t("shared.notFound")}</div>;
} else if (data.member) {
return (
<Form method="post" className="space-y-4">
<input hidden type="text" name="action" value="edit" readOnly />
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
<div className="grid grid-cols-2 gap-2">
{/*Email */}
<InputText
className="col-span-2"
disabled={!getUserHasPermission(appData, "app.settings.members.update")}
name="email"
title={t("models.user.email")}
autoComplete="off"
readOnly
defaultValue={data.member?.user.email || actionData?.fields?.email}
/>
{/*Email: End */}
{/*User First Name */}
<InputText
type="text"
disabled={!getUserHasPermission(appData, "app.settings.members.update")}
name="first-name"
title={t("models.user.firstName")}
autoComplete="off"
readOnly
defaultValue={data.member?.user.firstName || actionData?.fields?.firstName}
/>
{/*User First Name: End */}
{/*User Last Name */}
<InputText
disabled={!getUserHasPermission(appData, "app.settings.members.update")}
type="text"
title={t("models.user.lastName")}
name="last-name"
autoComplete="off"
readOnly
defaultValue={data.member?.user.lastName || actionData?.fields?.lastName}
/>
{/*User Last Name: End */}
</div>
<div className="mt-4 flex items-center justify-between">
{(() => {
if (loading) {
return (
<div className="text-theme-700 text-sm">
<div>{t("shared.loading")}...</div>
</div>
);
} else {
return (
<div>
<ButtonSecondary
destructive
disabled={!getUserHasPermission(appData, "app.settings.members.delete")}
onClick={remove}
isLoading={loading}
>
<div>{t("shared.remove")}</div>
</ButtonSecondary>
</div>
);
}
})()}
<div className="flex items-center space-x-2">
<ButtonSecondary
disabled={loading}
className={clsx(
"focus:ring-ring hover:bg-secondary border-border bg-background text-foreground/80 inline-flex items-center space-x-2 border px-3 py-2 font-medium shadow-2xs focus:outline-hidden focus:ring-2 focus:ring-offset-2 sm:rounded-md sm:text-sm",
loading && "bg-secondary/90 cursor-not-allowed"
)}
type="button"
onClick={close}
>
<div>{t("shared.cancel")}</div>
</ButtonSecondary>
{/* <ButtonPrimary disabled={loading || !getUserHasPermission( appData,"app.settings.members.update")} type="submit">
<div>{t("shared.save")}</div>
</ButtonPrimary> */}
</div>
</div>
</Form>
);
} else {
return <div></div>;
}
})()}
<ConfirmModal ref={confirmRemove} onYes={yesRemove} />
<ErrorModal ref={errorModal} />
<SuccessModal ref={successModal} onClosed={close} />
</div>
);
export default function LegacyEditMemberRedirect() {
return null;
}
@@ -1,135 +1,10 @@
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router";
import GroupForm from "~/components/core/roles/GroupForm";
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { useAppData } from "~/utils/data/useAppData";
import { createLog } from "~/utils/db/logs.db.server";
import { deleteGroup, getGroup, GroupWithDetails, updateGroup } from "~/utils/db/permissions/groups.db.server";
import { createUserGroup, deleteGroupUsers } from "~/utils/db/permissions/userGroups.db.server";
import { getTenantUsers, TenantUserWithUser } from "~/utils/db/tenants.db.server";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { getUserPermission } from "~/utils/helpers/.server/PermissionsService";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { validateCSRFToken } from "~/utils/session.server";
// AK-SET-01 — legacy member-group detail path; the id has to survive the redirect.
import type { LoaderFunctionArgs } from "react-router";
import { legacySettingsRedirect } from "../../legacy-redirects.server";
type LoaderData = {
title: string;
item: GroupWithDetails;
tenantUsers: TenantUserWithUser[];
};
export const loader = ({ request, params }: LoaderFunctionArgs) =>
legacySettingsRedirect({ request, params }, `settings/team/members/groups/${encodeURIComponent(params.id ?? "")}`);
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const userInfo = await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
const item = await getGroup(params.id ?? "", tenantId);
if (!item) {
throw redirect(UrlUtils.currentTenantUrl(params, "settings/members"));
}
const { userPermission: canManageGroups } = await getUserPermission({
userId: userInfo.userId,
tenantId,
permissionName: "app.settings.groups.full",
});
if (!canManageGroups && item.createdByUserId !== userInfo.userId) {
throw Response.json({ error: t("models.group.errors.manageForbidden") }, { status: 403 });
}
const data: LoaderData = {
title: `${item.name} | ${t("models.group.object")} | ${process.env.APP_NAME}`,
item,
tenantUsers: await getTenantUsers(tenantId),
};
return data;
};
type ActionData = {
error?: string;
};
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
export const action: ActionFunction = async ({ request, params }) => {
const userInfo = await requireAuth({ request, params });
await validateCSRFToken(request);
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
const existing = await getGroup(params.id ?? "", tenantId);
if (!existing) {
throw redirect(UrlUtils.currentTenantUrl(params, "settings/members"));
}
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
const { userPermission: canManageGroups } = await getUserPermission({
userId: userInfo.userId,
tenantId,
permissionName: "app.settings.groups.full",
});
if (!canManageGroups && existing.createdByUserId !== userInfo.userId) {
throw Response.json({ error: t("models.group.errors.manageForbidden") }, { status: 403 });
}
if (action === "edit") {
const data = {
tenantId: tenantId,
name: form.get("name")?.toString() ?? "",
description: form.get("description")?.toString() ?? "",
color: Number(form.get("color")),
};
const updated = await updateGroup(existing.id, data, tenantId);
if ("count" in updated && updated.count !== 1) {
return badRequest({ error: t("shared.notFound") });
}
await deleteGroupUsers(existing.id, tenantId);
const userIds = form.getAll("users[]").map((f) => f.toString());
const tenantUsers = await getTenantUsers(tenantId);
const users = tenantUsers.filter((tenantUser) => userIds.includes(tenantUser.userId)).map((tenantUser) => tenantUser.user);
if (users.length !== userIds.length) {
return badRequest({ error: t("shared.invalidForm") });
}
await Promise.all(
users.map(async (user) => {
return await createUserGroup(user.id, existing.id);
})
);
await createLog(request, tenantId, "settings.groups.updated", `${existing.name}: ${JSON.stringify({ ...data, users: users.map((f) => f.email) })}`);
} else if (action === "delete") {
const deleted = await deleteGroup(existing.id, tenantId);
if ("count" in deleted && deleted.count !== 1) {
return badRequest({ error: t("shared.notFound") });
}
await createLog(request, tenantId, "settings.groups.deleted", `${existing.name}`);
} else {
return badRequest({ error: t("shared.invalidForm") });
}
return redirect(UrlUtils.currentTenantUrl(params, "settings/members"));
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function AdminEditGroupRoute() {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const appData = useAppData();
const navigate = useNavigate();
const params = useParams();
return (
<SlideOverWideEmpty
title={t("settings.members.groups.editTitle")}
open={true}
className="sm:max-w-sm"
onClose={() => navigate(UrlUtils.currentTenantUrl(params, "settings/members"))}
>
<GroupForm
allUsers={data.tenantUsers}
item={data.item}
canUpdate={getUserHasPermission(appData, "app.settings.groups.full") || data.item.createdByUserId === appData.user.id}
canDelete={getUserHasPermission(appData, "app.settings.groups.full") || data.item.createdByUserId === appData.user.id}
/>
</SlideOverWideEmpty>
);
export default function LegacyMemberGroupDetailRedirect() {
return null;
}
@@ -1,95 +1,8 @@
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router";
import GroupForm from "~/components/core/roles/GroupForm";
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { createLog } from "~/utils/db/logs.db.server";
import { createGroup } from "~/utils/db/permissions/groups.db.server";
import { createUserGroup } from "~/utils/db/permissions/userGroups.db.server";
import { getTenantUsers, TenantUserWithUser } from "~/utils/db/tenants.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
// AK-SET-01 — legacy `settings/members/groups/new`.
import { legacySettingsRedirectLoader } from "../../legacy-redirects.server";
type LoaderData = {
tenantUsers: TenantUserWithUser[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.groups.full", tenantId);
const data: LoaderData = {
tenantUsers: await getTenantUsers(tenantId),
};
return data;
};
export const loader = legacySettingsRedirectLoader("settings/team/members/groups/new");
type ActionData = {
error?: string;
};
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
export const action: ActionFunction = async ({ request, params }) => {
await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.groups.full", tenantId);
await validateCSRFToken(request);
const userInfo = await getUserInfo(request);
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
if (action === "create") {
const data = {
createdByUserId: userInfo.userId,
tenantId: tenantId,
name: form.get("name")?.toString() ?? "",
description: form.get("description")?.toString() ?? "",
color: Number(form.get("color")),
};
const group = await createGroup(data);
const userIds = form.getAll("users[]").map((f) => f.toString());
const selectedUserIds = new Set(userIds);
const tenantUsers = await getTenantUsers(tenantId);
const users = tenantUsers.filter((tenantUser) => selectedUserIds.has(tenantUser.userId)).map((tenantUser) => tenantUser.user);
if (users.length !== userIds.length) {
return badRequest({ error: t("shared.invalidForm") });
}
await Promise.all(
users.map(async (user) => {
return await createUserGroup(user.id, group.id);
})
);
await createLog(
request,
tenantId,
"settings.groups.created",
`${JSON.stringify({
...data,
users: users.map((f) => f.email),
})}`
);
return redirect(UrlUtils.currentTenantUrl(params, "settings/members"));
} else {
return badRequest({ error: t("shared.invalidForm") });
}
};
export default function NewGroupRoute() {
const { t } = useTranslation();
const navigate = useNavigate();
const params = useParams();
const data = useLoaderData<LoaderData>();
return (
<SlideOverWideEmpty
title={t("settings.members.groups.createTitle")}
open={true}
className="sm:max-w-sm"
onClose={() => navigate(UrlUtils.currentTenantUrl(params, "settings/members"))}
>
<GroupForm allUsers={data.tenantUsers} />
</SlideOverWideEmpty>
);
export default function LegacyNewMemberGroupRedirect() {
return null;
}
@@ -1,178 +1,8 @@
import { ActionFunction, LoaderFunctionArgs, redirect, MetaFunction, useLoaderData, useNavigate, useParams } from "react-router";
import { getTranslations } from "~/locale/i18next.server";
import { getTenant, getTenantMember } from "~/utils/db/tenants.db.server";
import { getUser, getUserByEmail } from "~/utils/db/users.db.server";
import { createWorkspaceInvite, WorkspaceInviteError } from "@hivegrid/db/workspace-invites.server";
import { getDbClient } from "@hivegrid/db/client.server";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import CheckPlanFeatureLimit from "~/components/core/settings/subscription/CheckPlanFeatureLimit";
import { InviteMemberForm } from "~/components/screens/users/InviteMemberForm";
import UrlUtils from "~/utils/app/UrlUtils";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { getPlanFeatureUsage } from "~/utils/services/.server/subscriptionService";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { getAbsoluteUrl } from "~/utils/url.server";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import ServerError from "~/components/ui/errors/ServerError";
import EventsService from "~/modules/events/services/.server/EventsService";
import { MemberInvitationCreatedDto } from "~/modules/events/dtos/MemberInvitationCreatedDto";
import { getUserInfo } from "~/utils/session.server";
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
import { getMailTranslator } from "~/locale/mail-translator.server";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { validateCSRFToken } from "~/utils/session.server";
// AK-SET-01 — legacy `settings/members/new`.
import { legacySettingsRedirectLoader } from "../legacy-redirects.server";
export type NewMemberLoaderData = {
title: string;
featurePlanUsage: PlanFeatureUsageDto | undefined;
};
export const loader = legacySettingsRedirectLoader("settings/team/members/new");
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.members.create", tenantId);
const featurePlanUsage = await getPlanFeatureUsage(tenantId, DefaultFeatures.Users);
const data: NewMemberLoaderData = {
title: `${t("settings.members.actions.new")} | ${process.env.APP_NAME}`,
featurePlanUsage,
};
return data;
};
export type NewMemberActionData = {
error?: string;
success?: string;
fields?: {
email: string;
firstName: string;
lastName: string;
role: number;
};
};
export const action: ActionFunction = async ({ request, params }) => {
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
await validateCSRFToken(request);
await verifyUserHasPermission(request, "app.settings.members.create", tenantId);
const { userId } = await getUserInfo(request);
const fromUser = await getUser(userId);
const tenant = await getTenant(tenantId);
if (!tenant || !fromUser) {
return Response.json({ error: t("settings.members.errors.tenantOrUserNotFound") });
}
const form = await request.formData();
const email = form.get("email")?.toString().toLowerCase().trim() ?? "";
const firstName = form.get("first-name")?.toString() ?? "";
const lastName = form.get("last-name")?.toString() ?? "";
const sendInvitationEmail = Boolean(form.get("send-invitation-email"));
try {
const user = await getUserByEmail(email);
if (user) {
const tenantUser = await getTenantMember(user.id, tenantId);
if (tenantUser) {
return Response.json({ error: t("settings.members.errors.userAlreadyInOrganization") });
}
}
const mailTranslator = sendInvitationEmail ? await getMailTranslator(fromUser.locale) : null;
const appConfiguration = sendInvitationEmail ? await getAppConfiguration({ request }) : null;
const db = getDbClient();
const invitation = await db.$transaction(async (tx) => {
const created = await createWorkspaceInvite(
{
tenantId,
email,
firstName,
lastName,
type: TenantUserType.MEMBER,
fromUserId: fromUser?.id ?? null,
// DoD "Einladung 48h": kein expliziter Wert mehr -> createWorkspaceInvite setzt den
// 48h-Default (WORKSPACE_INVITE_TTL_MS) als Single Source of Truth.
},
tx
);
if (sendInvitationEmail && mailTranslator && appConfiguration) {
const rendered = EmailTemplates.USER_INVITATION_EMAIL.parse({
appConfiguration,
data: {
name: firstName,
invite_sender_name: fromUser.firstName,
invite_sender_organization: tenant.name,
action_url: getAbsoluteUrl(request, `/invitation/${created.token}`),
},
t: mailTranslator.t,
locale: mailTranslator.locale,
});
await publishOutboxEvent(tx as OutboxPublisherTransaction, {
tenantId: tenant.id,
type: "mail.transactional.send",
dispatchKey: `mail:workspace-invite:${created.id}`,
payload: {
tenantId: tenant.id,
to: [email],
subject: rendered.subject,
html: rendered.body,
priorityOverride: "critical",
metadata: {
source: "workspace-invitation",
alias: "user-invitation",
invitationId: created.id,
},
} satisfies Prisma.InputJsonValue,
});
}
return created;
});
await EventsService.create({
request,
event: "member.invitation.created",
tenantId: tenant.id,
userId: fromUser.id,
data: {
user: { email: invitation.email, firstName: invitation.firstName, lastName: invitation.lastName, type: TenantUserType[invitation.type] },
tenant: { id: tenant.id, name: tenant.name },
fromUser: { id: fromUser!.id, email: fromUser!.email },
} satisfies MemberInvitationCreatedDto,
});
return redirect(appPath({ tenantSlug: params.tenant ?? "", path: "settings/members", mode: "host-aware" }));
} catch (error: any) {
if (error instanceof WorkspaceInviteError && error.code === "duplicate_active_invite") {
return Response.json({ error: t("settings.members.errors.invitationAlreadyExists") }, { status: 400 });
}
// eslint-disable-next-line no-console
console.error(error);
return Response.json({ error: t("settings.members.errors.createInvitationFailed") }, { status: 400 });
}
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function NewMemberRoute() {
// D-P2 M01 "Mitarbeiter einladen": David-style form, rendered inside the
// members route's Dialog outlet (real Dialog instead of the old slide-over).
const data = useLoaderData<NewMemberLoaderData>();
const navigate = useNavigate();
const params = useParams();
return (
<CheckPlanFeatureLimit item={data.featurePlanUsage}>
<InviteMemberForm onClose={() => navigate(UrlUtils.currentTenantUrl(params, "settings/members"), { replace: true })} />
</CheckPlanFeatureLimit>
);
}
export function ErrorBoundary() {
return <ServerError />;
export default function LegacyNewMemberRedirect() {
return null;
}
@@ -1,139 +1,8 @@
// AK-P3 — Notification-Settings route (`/app/:tenant/settings/notifications`).
// The category registry + default-inheritance merge live in the pure
// notification-settings VM (@hivegrid/view-models); the loader builds the VM
// once and the route injects it plus fetcher-backed action callbacks into the
// interim <NotificationSettingsPage /> screen (AD-28).
// AK-SET-01 — legacy `settings/notifications` is now a tab of the Mein-Konto hub.
import { legacySettingsRedirectLoader } from "./legacy-redirects.server";
import { ActionFunctionArgs, LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { upsertUserNotificationPreference, getUserNotificationPreferences } from "@hivegrid/db/notifications.server";
import {
buildNotificationSettingsVM,
isAllowedNotificationCategory,
isAllowedNotificationChannel,
NOTIFICATION_SETTING_CATEGORIES,
type NotificationPreferenceInput,
type NotificationSettingsVM,
} from "@hivegrid/view-models";
import { NotificationSettingsPage } from "~/components/screens/notifications/NotificationSettingsPage";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { useRootData } from "~/utils/data/useRootData";
import { getTranslations } from "~/locale/i18next.server";
export const loader = legacySettingsRedirectLoader("settings/profile/notifications");
type LoaderData = {
vm: NotificationSettingsVM;
};
type ActionData = {
ok?: true;
error?: string;
};
function getRequiredFormValue(formData: FormData, key: string): string | null {
const value = formData.get(key);
if (typeof value !== "string") {
return null;
}
const normalized = value.trim();
return normalized.length > 0 ? normalized : null;
}
function isCheckboxOn(formData: FormData, key: string): boolean {
const value = formData.get(key);
return value === "on" || value === "true";
}
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const tenantId = await getTenantIdFromUrl(params);
const userInfo = await getUserInfo(request);
const records = (await getUserNotificationPreferences({ tenantId, userId: userInfo.userId })) as NotificationPreferenceInput[];
const data: LoaderData = { vm: buildNotificationSettingsVM(records) };
return Response.json(data);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
await requireAuth({ request, params });
const { t } = await getTranslations(request);
await validateCSRFToken(request);
const tenantId = await getTenantIdFromUrl(params);
const userInfo = await getUserInfo(request);
const formData = await request.formData();
const actionName = getRequiredFormValue(formData, "action");
// Master "turn all emails off" switch: write the EMAIL preference for every
// known category so explicit per-category overrides cannot leak emails back in.
if (actionName === "set-email-master") {
const emailsEnabled = !isCheckboxOn(formData, "disableAllEmails");
for (const category of NOTIFICATION_SETTING_CATEGORIES) {
await upsertUserNotificationPreference({
tenantId,
userId: userInfo.userId,
channel: "EMAIL",
category,
enabled: emailsEnabled,
});
}
return Response.json({ ok: true });
}
if (actionName !== "update-preference") {
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceAction") });
}
const category = getRequiredFormValue(formData, "category")?.toLowerCase() ?? "";
const channel = getRequiredFormValue(formData, "channel")?.replace(/-/g, "_").toUpperCase() ?? "";
if (!isAllowedNotificationCategory(category)) {
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceCategory") });
}
if (!isAllowedNotificationChannel(channel)) {
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceChannel") });
}
await upsertUserNotificationPreference({
tenantId,
userId: userInfo.userId,
channel,
category,
enabled: isCheckboxOn(formData, "enabled"),
});
return Response.json({ ok: true });
};
export default function WorkspaceNotificationSettingsRoute() {
const data = useLoaderData<LoaderData>();
const rootData = useRootData();
const fetcher = useFetcher<ActionData>();
const saveState = fetcher.data ? { ok: fetcher.data.ok === true, errorText: fetcher.data.error } : null;
function submit(form: Record<string, string>) {
fetcher.submit({ ...form, ...(rootData.csrf ? { csrf: rootData.csrf } : {}) }, { method: "post" });
}
return (
<main className="relative z-0 flex-1 pb-8">
<NotificationSettingsPage
vm={data.vm}
saveState={saveState}
actions={{
onTogglePreference: ({ category, channel, enabled }) =>
submit({ action: "update-preference", category, channel, enabled: enabled ? "true" : "false" }),
onSetEmailMaster: (disableAllEmails) =>
submit({ action: "set-email-master", ...(disableAllEmails ? { disableAllEmails: "true" } : {}) }),
}}
/>
</main>
);
export default function LegacyNotificationsRedirect() {
return null;
}
@@ -1,72 +1,8 @@
import { ActionFunctionArgs, Form, LoaderFunctionArgs, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
// AK-SET-01 — legacy `settings/onboarding/demo-data` is now a tab of the Workspace hub.
import { legacySettingsRedirectLoader } from "../legacy-redirects.server";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import SettingSection from "~/components/ui/sections/SettingSection";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { deleteShkDemoData, getDemoDataStatus, provisionShkDemoData } from "~/utils/services/.server/akP20OnboardingService";
import { useRootData } from "~/utils/data/useRootData";
export const loader = legacySettingsRedirectLoader("settings/workspace/demo-data");
type LoaderData = {
provisioning: Awaited<ReturnType<typeof getDemoDataStatus>>;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.onboarding.demoData.manage", tenantId);
return { provisioning: await getDemoDataStatus(tenantId) } satisfies LoaderData;
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.onboarding.demoData.manage", tenantId);
await validateCSRFToken(request);
const userInfo = await getUserInfo(request);
const form = await request.formData();
const action = form.get("action")?.toString();
if (action === "create-demo-data") {
await provisionShkDemoData({ tenantId, userId: userInfo.userId });
return Response.json({ ok: true });
}
if (action === "delete-demo-data") {
await deleteShkDemoData({ tenantId, provisioningId: form.get("provisioningId")?.toString() ?? "" });
return Response.json({ ok: true });
}
return Response.json({ error: "shared.invalidAction" }, { status: 400 });
};
export default function DemoDataSettingsRoute() {
const { t } = useTranslation();
const { csrf } = useRootData();
const data = useLoaderData<LoaderData>();
const hasDemoData = Boolean(data.provisioning);
return (
<EditPageLayout title={t("onboarding.demoData.title")}>
<SettingSection title={t("onboarding.demoData.title")} description={t("onboarding.demoData.description")}>
<Form method="post" className="flex flex-wrap gap-3">
<input type="hidden" name="csrf" value={csrf ?? ""} />
{hasDemoData ? (
<>
<input type="hidden" name="action" value="delete-demo-data" />
<input type="hidden" name="provisioningId" value={data.provisioning?.id ?? ""} />
<button type="submit" className="bg-destructive text-destructive-foreground rounded-md px-3 py-2 text-sm font-medium">
{t("onboarding.demoData.delete")}
</button>
</>
) : (
<>
<input type="hidden" name="action" value="create-demo-data" />
<button type="submit" className="bg-primary text-primary-foreground rounded-md px-3 py-2 text-sm font-medium">
{t("onboarding.demoData.create")}
</button>
</>
)}
</Form>
</SettingSection>
</EditPageLayout>
);
export default function LegacyDemoDataRedirect() {
return null;
}
@@ -1,340 +1,10 @@
/**
* 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.
*/
// AK-SET-01 — legacy plugin audit path; the id has to survive the redirect.
import type { LoaderFunctionArgs } from "react-router";
import { Form, Link, useLoaderData, useSearchParams } from "react-router";
import { useTranslation } from "react-i18next";
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 { getPluginForTenant } from "~/modules/plugins/services/.server/PluginLifecycleService";
import { legacySettingsRedirect } from "./legacy-redirects.server";
const PAGE_SIZE = 50;
const MAX_PAGE_SIZE = 100;
const CAPABILITY_FILTER_OPTION_LIMIT = 32;
export const loader = ({ request, params }: LoaderFunctionArgs) =>
legacySettingsRedirect({ request, params }, `settings/integrations/plugins/${encodeURIComponent(params.id ?? "")}/audit`);
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 ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.auditTrails.view", tenantId);
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/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-500">
{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 ?? ""}
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 ?? ""}
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 ?? ""}
className="rounded border border-gray-300 px-2 py-1 text-sm"
/>
</label>
<button type="submit" className="rounded border border-gray-300 bg-white px-3 py-1 text-sm hover:bg-gray-50">
{t("settings.plugins.audit.filters.submit")}
</button>
<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-500">
{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 uppercase tracking-wide text-gray-500">
<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();
export default function LegacyPluginAuditRedirect() {
return null;
}
@@ -1,481 +1,10 @@
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";
// AK-SET-01 — legacy plugin detail path; the id has to survive the redirect.
import type { LoaderFunctionArgs } from "react-router";
import { legacySettingsRedirect } from "./legacy-redirects.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 loader = ({ request, params }: LoaderFunctionArgs) =>
legacySettingsRedirect({ request, params }, `settings/integrations/plugins/${encodeURIComponent(params.id ?? "")}`);
export const headers: HeadersFunction = (args) => {
const responseHeaders = new Headers(serverTimingHeaders(args));
responseHeaders.set("Content-Security-Policy", PLUGIN_SETTINGS_ROUTE_CSP);
responseHeaders.set("Permissions-Policy", PLUGIN_SETTINGS_ROUTE_PERMISSION_POLICY);
responseHeaders.set("X-Frame-Options", "SAMEORIGIN");
return responseHeaders;
};
function shouldFailClosedOnRateLimitInfraFailure(): boolean {
return process.env.NODE_ENV === "production";
}
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(`tenant:${tenantId}:user:${userInfo.userId}:plugin:${pluginRowId}:reason:${body.reason}`);
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 (error) {
if (shouldFailClosedOnRateLimitInfraFailure()) {
return Response.json(
{ error: "rate_limit_unavailable", message: t("settings.plugins.settings.errors.rate_limit_unavailable") },
{ status: 503, headers: { "Retry-After": "60" } }
);
}
// eslint-disable-next-line no-console
console.warn("[plugin-settings] frame-violation rate-limit infra failure; allowing audit report:", error instanceof Error ? error.message : String(error));
}
try {
const user = await getUser(userInfo.userId);
await reportPluginSettingsFrameViolation({
tenantId,
pluginRowId,
reason: body.reason,
actor: {
userId: userInfo.userId,
email: user?.email ?? null,
ip: request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? request.headers.get("x-real-ip") ?? null,
},
});
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(`tenant:${tenantId}:user:${userInfo.userId}:plugin:${pluginRowId}`);
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 (error) {
if (shouldFailClosedOnRateLimitInfraFailure()) {
return Response.json(
{ error: "rate_limit_unavailable", message: t("settings.plugins.settings.errors.rate_limit_unavailable") },
{ status: 503, headers: { "Retry-After": "60" } }
);
}
// Failing open keeps legitimate plugin settings usable outside
// production during a transient shared-store outage; the service still
// enforces key and value safety before any write reaches the database.
// eslint-disable-next-line no-console
console.warn("[plugin-settings] rate-limit infra failure; allowing settings write:", error instanceof Error ? error.message : String(error));
}
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: request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? request.headers.get("x-real-ip") ?? null,
},
});
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-xs text-gray-500">
<Link to={appPath({ tenantSlug: data.tenantSlug, path: "settings/plugins" })} className="text-blue-600 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-sm text-gray-500">{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-gray-200 bg-white"
dataUiId="ui.plugins.settings.frame"
/>
</div>
);
export default function LegacyPluginDetailRedirect() {
return null;
}
@@ -1,672 +1,8 @@
/**
* 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.
*/
// AK-SET-01 — legacy `settings/plugins` is now a tab of the Erweiterungen hub.
import { legacySettingsRedirectLoader } from "./legacy-redirects.server";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import {
getPluginCapabilityMetadata,
isPluginCapabilityName,
type PluginCapabilityMetadata,
type PluginCapabilityRisk,
} from "@hivegrid/plugin-runtime/capabilities";
import { isPluginHookProductionAvailable } from "@hivegrid/plugin-runtime/hooks/registry";
import type { PluginCapability } from "@hivegrid/plugin-runtime/manifest";
import { Form, Link, useActionData, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import { useState } from "react";
import { getTranslations } from "~/locale/i18next.server";
import { useLocaleFormatters } from "~/locale/format";
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 {
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";
export const loader = legacySettingsRedirectLoader("settings/integrations/plugins");
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 SerializedPluginCapability = {
name: string;
scope: PluginCapability["scope"] | null;
granted: boolean;
grantedAt: string | null;
grantedScopeJson: unknown;
metadata: SerializedPluginCapabilityMetadata | null;
};
type SerializedPluginCapabilityMetadata = Pick<PluginCapabilityMetadata, "risk" | "productionAvailable">;
type SerializedPluginItem = {
id: string;
pluginId: string;
version: string;
enabled: boolean;
capabilities: ReadonlyArray<SerializedPluginCapability>;
missingCapabilities: ReadonlyArray<string>;
capabilityReviewDigest: string;
hasSettingsUi: boolean;
manifestJson: string;
installedAt: string;
};
type LoaderData = {
title: string;
tenantSlug: string;
canManage: boolean;
canAudit: boolean;
items: ReadonlyArray<SerializedPluginItem>;
};
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";
export function formatPluginCapabilityLabel(capability: string, t: (key: string, options?: Record<string, unknown>) => string) {
if (isPluginHookConsentName(capability)) {
return t("settings.plugins.consent.hookLabel", { hook: capability.slice("hook:".length) });
}
if (isPluginCapabilityName(capability)) {
return t(`settings.plugins.capabilityNames.${capability.replaceAll(".", "_")}`);
}
return t(`settings.plugins.capabilityNames.${capability.replaceAll(".", "_")}`, {
defaultValue: t("settings.plugins.capabilityNames.unknown", { capability }),
});
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, USE_PERMISSION, tenantId);
const [{ t }, info, items] = await Promise.all([getTranslations(request), getUserInfo(request), listPlugins({ tenantId })]);
const [managePermission, auditPermission, serializedItems] = 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, items }),
]);
const data: LoaderData = {
title: `${t("settings.plugins.title")} | ${process.env.APP_NAME}`,
tenantSlug: params.tenant ?? "",
canManage: Boolean(managePermission?.userPermission),
canAudit: Boolean(auditPermission?.userPermission),
items: serializedItems,
};
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; items: ReadonlyArray<PluginListItem> }): Promise<SerializedPluginItem[]> {
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 = getPluginConsentRequirements(row.manifest).map((capability) => {
const grant = grantByCapability.get(capability.name);
const granted = Boolean(grant) && isCapabilityGrantScopeSatisfied({ declaredScope: capability.scope ?? null, grantedScopeJson: grant?.scopeJson });
return {
name: capability.name,
scope: capability.scope ?? null,
granted,
grantedAt: grant?.grantedAt.toISOString() ?? null,
grantedScopeJson: grant?.scopeJson ?? null,
metadata: serializePluginConsentMetadata(capability.name),
};
});
const missingCapabilities = capabilities.filter((capability) => !capability.granted).map((capability) => capability.name);
return {
id: row.id,
pluginId: row.pluginId,
version: row.version,
enabled: row.enabled,
capabilities,
missingCapabilities,
capabilityReviewDigest: createDigest(row, missingCapabilities),
hasSettingsUi: Boolean(row.manifest.ui?.settings?.entry),
manifestJson: JSON.stringify(row.manifest, null, 2),
installedAt: row.installedAt.toISOString(),
};
})
);
}
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 = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? request.headers.get("x-real-ip") ?? null;
return { userId: info.userId ?? null, email: user?.email ?? null, ip };
}
export default function TenantPluginsRoute() {
const data = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const { t } = useTranslation();
const rootData = useRootData();
const formatters = useLocaleFormatters();
const [expanded, setExpanded] = useState<string | null>(null);
const [reviewingCapabilities, setReviewingCapabilities] = useState<string | null>(null);
const [reviewedCapabilities, setReviewedCapabilities] = useState<ReadonlySet<string>>(() => new Set());
const getCapabilityReviewKey = (item: SerializedPluginItem, capabilityName: string) => `${item.id}:${item.capabilityReviewDigest}:${capabilityName}`;
const denyCapabilityReview = (item: SerializedPluginItem) => {
setReviewedCapabilities((current) => {
const next = new Set(current);
for (const capabilityName of item.missingCapabilities) {
next.delete(getCapabilityReviewKey(item, capabilityName));
}
return next;
});
setReviewingCapabilities(null);
};
return (
<div className="space-y-6 p-6" data-ui-id="ui.plugins.page">
<header>
<h1 className="text-heading- font-heading- text-text-neutral-primary">{t("settings.plugins.title")}</h1>
<p className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{t("settings.plugins.description", { tenantSlug: data.tenantSlug })}</p>
</header>
{actionData?.message ? (
<div
role="alert"
className={`rounded border px-3 py-2 text-sm ${actionData.ok ? "border-green-300 bg-green-50 text-green-800" : "border-red-300 bg-red-50 text-red-800"}`}
>
{actionData.message}
</div>
) : null}
{data.items.length === 0 ? (
<p className="rounded border border-dashed border-gray-300 p-6 text-sm text-gray-500">{t("settings.plugins.empty")}</p>
) : (
<ul className="space-y-3" data-ui-id="ui.plugins.list">
{data.items.map((item) => {
const missingCapabilityNames = new Set(item.missingCapabilities);
const capabilitiesToReview = item.capabilities.filter((capability) => missingCapabilityNames.has(capability.name));
const unavailableCapabilitiesToReview = capabilitiesToReview.filter((capability) => capability.metadata?.productionAvailable === false);
const reviewComplete =
unavailableCapabilitiesToReview.length === 0 &&
item.missingCapabilities.every((capabilityName) => reviewedCapabilities.has(getCapabilityReviewKey(item, capabilityName)));
return (
<li
key={item.id}
className="rounded border border-gray-200 bg-white p-4 shadow-sm"
data-ui-id="ui.plugins.item"
data-plugin-row-id={item.id}
data-plugin-id={item.pluginId}
>
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 className="text-base font-medium">{item.pluginId}</h2>
<p className="text-xs text-gray-500">
{t("settings.plugins.versionInstalled", {
version: item.version,
date: formatters.date(item.installedAt, { dateStyle: "medium", timeStyle: "short" }),
})}
</p>
</div>
<div className="flex items-center gap-3">
<span
className={`rounded-full px-2 py-0.5 text-xs font-medium ${item.enabled ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-700"}`}
>
{item.enabled ? t("shared.enabled") : t("shared.disabled")}
</span>
{data.canManage ? (
item.enabled ? (
<Form method="post" className="inline" data-ui-id="ui.plugins.lifecycle.form">
{rootData.csrf ? <input type="hidden" name="csrf" value={rootData.csrf} /> : null}
<input type="hidden" name="id" value={item.id} />
<input type="hidden" name="op" value="disable" />
<button
type="submit"
className="rounded border border-gray-300 bg-white px-3 py-1 text-sm hover:bg-gray-50"
data-ui-id="ui.plugins.lifecycle.button"
>
{t("shared.disable")}
</button>
</Form>
) : item.missingCapabilities.length > 0 ? null : (
<Form method="post" className="inline" data-ui-id="ui.plugins.lifecycle.form">
{rootData.csrf ? <input type="hidden" name="csrf" value={rootData.csrf} /> : null}
<input type="hidden" name="id" value={item.id} />
<input type="hidden" name="op" value="enable" />
<button
type="submit"
className="rounded border border-gray-300 bg-white px-3 py-1 text-sm hover:bg-gray-50"
data-ui-id="ui.plugins.lifecycle.button"
>
{t("shared.enable")}
</button>
</Form>
)
) : null}
</div>
</div>
<div className="mt-3 space-y-2">
<p className="text-xs font-medium text-gray-500 uppercase">{t("settings.plugins.capabilities")}</p>
{item.capabilities.length === 0 ? (
<p className="text-xs text-gray-500">{t("settings.plugins.consent.none")}</p>
) : (
<ul className="space-y-2">
{item.capabilities.map((capability) => (
<li key={capability.name} className="rounded border border-gray-100 bg-gray-50 px-3 py-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-sm font-medium text-gray-900">{formatPluginCapabilityLabel(capability.name, t)}</span>
<span
className={`rounded-full px-2 py-0.5 text-xs font-medium ${capability.granted ? "bg-green-100 text-green-800" : "bg-amber-100 text-amber-800"}`}
>
{capability.granted ? t("settings.plugins.consent.granted") : t("settings.plugins.consent.missing")}
</span>
</div>
<p className="mt-1 text-xs text-gray-500">{formatPluginCapabilityScope(capability.scope, t)}</p>
{capability.granted && capability.grantedAt ? (
<p className="mt-1 text-xs text-gray-500" data-ui-id="ui.plugins.capability.grantMeta">
{t("settings.plugins.consent.grantedAt", {
date: formatters.date(capability.grantedAt, { dateStyle: "medium", timeStyle: "short" }),
})}
</p>
) : null}
{data.canManage && capability.granted ? (
<Form method="post" className="mt-2" data-ui-id="ui.plugins.capability.revoke.form">
{rootData.csrf ? <input type="hidden" name="csrf" value={rootData.csrf} /> : null}
<input type="hidden" name="id" value={item.id} />
<input type="hidden" name="pluginId" value={item.pluginId} />
<input type="hidden" name="op" value="revoke" />
<input type="hidden" name="capabilityNames[]" value={capability.name} />
<button
type="submit"
className="text-xs font-medium text-red-700 hover:underline"
data-ui-id="ui.plugins.capability.revoke.button"
>
{t("settings.plugins.consent.revoke")}
</button>
<span className="ml-2 text-xs text-gray-500">{t("settings.plugins.consent.revokeDisables")}</span>
</Form>
) : null}
</li>
))}
</ul>
)}
{data.canManage && item.missingCapabilities.length > 0 ? (
<div className="rounded border border-amber-200 bg-amber-50 p-3">
<button
type="button"
aria-expanded={reviewingCapabilities === item.id}
aria-controls={`plugin-capability-review-${item.id}`}
onClick={() => setReviewingCapabilities(reviewingCapabilities === item.id ? null : item.id)}
className="rounded border border-amber-300 bg-white px-3 py-1 text-sm font-medium text-amber-900 hover:bg-amber-100"
data-ui-id="ui.plugins.capabilityReview.toggle"
>
{t("settings.plugins.consent.reviewCapabilities")}
</button>
<span className="ml-3 text-xs text-gray-500">{t("settings.plugins.consent.description")}</span>
{reviewingCapabilities === item.id ? (
<Form
method="post"
id={`plugin-capability-review-${item.id}`}
className="mt-3 space-y-3"
aria-label={t("settings.plugins.consent.reviewFormLabel", { pluginId: item.pluginId })}
data-ui-id="ui.plugins.capabilityReview.form"
>
{rootData.csrf ? <input type="hidden" name="csrf" value={rootData.csrf} /> : null}
<input type="hidden" name="id" value={item.id} />
<input type="hidden" name="op" value={item.enabled ? "grant" : "grantAndEnable"} />
<input type="hidden" name="capabilityReviewDigest" value={item.capabilityReviewDigest} />
<div>
<p className="text-sm font-medium text-amber-950">{t("settings.plugins.consent.reviewTitle", { pluginId: item.pluginId })}</p>
<p className="mt-1 text-xs text-amber-900">{t("settings.plugins.consent.reviewDescription", { version: item.version })}</p>
</div>
<ul className="space-y-2">
{capabilitiesToReview.map((capability) => {
const reviewKey = getCapabilityReviewKey(item, capability.name);
const label = formatPluginCapabilityLabel(capability.name, t);
const unavailable = capability.metadata?.productionAvailable === false;
return (
<li key={capability.name} className="rounded border border-amber-200 bg-white px-3 py-2">
<label className="flex items-start gap-2">
<input
type="checkbox"
name="capabilities[]"
value={capability.name}
disabled={unavailable}
checked={reviewedCapabilities.has(reviewKey)}
onChange={(event) => {
const isChecked = event.currentTarget.checked;
setReviewedCapabilities((current) => {
const next = new Set(current);
if (isChecked) {
next.add(reviewKey);
} else {
next.delete(reviewKey);
}
return next;
});
}}
className="mt-0.5 h-3.5 w-3.5 rounded border-gray-300 disabled:cursor-not-allowed disabled:opacity-50"
data-ui-id="ui.plugins.capabilityReview.checkbox"
/>
<span className="text-sm font-medium text-gray-900">
{t("settings.plugins.consent.reviewCapability", { capability: label })}
</span>
</label>
{capability.metadata ? (
<div className="mt-2 flex flex-wrap gap-2">
<span
className={`rounded-full px-2 py-0.5 text-xs font-medium ${getPluginCapabilityRiskClassName(capability.metadata.risk)}`}
data-ui-id="ui.plugins.capabilityReview.risk"
>
{t(`settings.plugins.consent.risk.${capability.metadata.risk}`)}
</span>
<span
className={`rounded-full px-2 py-0.5 text-xs font-medium ${
capability.metadata.productionAvailable ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800"
}`}
data-ui-id="ui.plugins.capabilityReview.availability"
>
{capability.metadata.productionAvailable
? t("settings.plugins.consent.available")
: t("settings.plugins.consent.unavailable")}
</span>
</div>
) : null}
{unavailable ? (
<p className="mt-2 text-xs text-red-700" data-ui-id="ui.plugins.capabilityReview.unavailableReason">
{t("settings.plugins.consent.unavailableDescription")}
</p>
) : null}
<p className="mt-1 text-xs text-gray-500">{formatPluginCapabilityScope(capability.scope, t)}</p>
<code
className="mt-2 inline-flex rounded border border-gray-200 bg-gray-50 px-1.5 py-0.5 text-xs text-gray-700"
data-ui-id="ui.plugins.capabilityReview.grantName"
>
{capability.name}
</code>
</li>
);
})}
</ul>
<input type="hidden" name="capabilitiesReviewed" value={reviewComplete ? "yes" : "no"} />
<div className="flex flex-wrap items-center gap-2">
<button
type="submit"
disabled={!reviewComplete}
className="rounded border border-amber-300 bg-amber-100 px-3 py-1 text-sm font-medium text-amber-950 hover:bg-amber-200 disabled:cursor-not-allowed disabled:opacity-50"
data-ui-id="ui.plugins.capabilityReview.button"
>
{item.enabled ? t("settings.plugins.consent.approve") : t("settings.plugins.consent.approveAndEnable")}
</button>
<button
type="button"
onClick={() => denyCapabilityReview(item)}
className="rounded border border-gray-300 bg-white px-3 py-1 text-sm font-medium text-gray-700 hover:bg-gray-50"
data-ui-id="ui.plugins.capabilityReview.deny"
>
{t("shared.deny")}
</button>
</div>
</Form>
) : null}
</div>
) : null}
</div>
<button
type="button"
aria-expanded={expanded === item.id}
aria-controls={`plugin-manifest-${item.id}`}
onClick={() => setExpanded(expanded === item.id ? null : item.id)}
className="mt-2 text-xs text-blue-600 hover:underline"
data-ui-id="ui.plugins.manifest.toggle"
>
{expanded === item.id ? t("settings.plugins.hideManifest") : t("settings.plugins.viewManifest")}
</button>
{item.enabled && item.hasSettingsUi ? (
<Link
to={appPath({ tenantSlug: data.tenantSlug, path: `settings/plugins/${item.id}` })}
className="ml-4 text-xs font-medium text-blue-600 hover:underline"
data-ui-id="ui.plugins.settings.open"
>
{t("settings.plugins.openSettings")}
</Link>
) : null}
{data.canAudit ? (
<Link
to={appPath({ tenantSlug: data.tenantSlug, path: `settings/plugins/${item.id}/audit` })}
className="ml-4 text-xs font-medium text-blue-600 hover:underline"
data-ui-id="ui.plugins.audit.open"
>
{t("settings.plugins.viewAudit")}
</Link>
) : null}
{expanded === item.id ? (
<pre
id={`plugin-manifest-${item.id}`}
// Scrollable regions must be keyboard-focusable (axe
// scrollable-region-focusable) so keyboard users can scroll the
// manifest content.
tabIndex={0}
className="mt-2 overflow-auto rounded bg-gray-50 p-3 text-xs text-gray-800"
data-ui-id="ui.plugins.manifest.panel"
>
{item.manifestJson}
</pre>
) : null}
</li>
);
})}
</ul>
)}
</div>
);
}
function getPluginCapabilityRiskClassName(risk: PluginCapabilityRisk): string {
switch (risk) {
case "low":
return "bg-green-100 text-green-800";
case "medium":
return "bg-blue-100 text-blue-800";
case "high":
return "bg-amber-100 text-amber-800";
case "critical":
return "bg-red-100 text-red-800";
}
}
function formatPluginCapabilityScope(scope: PluginCapability["scope"] | null, t: (key: string, options?: Record<string, unknown>) => string) {
if (!scope) {
return t("settings.plugins.consent.noScope");
}
const parts = [
scope.allowedHosts?.length ? t("settings.plugins.consent.allowedHosts", { hosts: scope.allowedHosts.join(", ") }) : null,
scope.keyPattern ? t("settings.plugins.consent.keyPattern", { pattern: scope.keyPattern }) : null,
scope.tablePrefix ? t("settings.plugins.consent.tablePrefix", { prefix: scope.tablePrefix }) : null,
].filter(Boolean);
return parts.length > 0 ? parts.join(" / ") : t("settings.plugins.consent.noScope");
export default function LegacyPluginsRedirect() {
return null;
}
@@ -1,100 +1,8 @@
import { LoaderFunctionArgs, MetaFunction, useLoaderData, useParams } from "react-router";
import { useTranslation } from "react-i18next";
import UrlUtils from "~/utils/app/UrlUtils";
import { getTranslations } from "~/locale/i18next.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
// AK-SET-01 — legacy `settings/policies` is now a tab of the Workspace hub.
import { legacySettingsRedirectLoader } from "./legacy-redirects.server";
type PolicyLink = {
labelKey: string;
path: string;
};
export const loader = legacySettingsRedirectLoader("settings/workspace/policies");
type PolicySection = {
id: string;
links: PolicyLink[];
};
type LoaderData = {
title: string;
workspaceSlug: string;
};
const POLICY_SECTIONS: PolicySection[] = [
{
id: "membership",
links: [{ labelKey: "settings.policies.sections.membership.links.members", path: "settings/members" }],
},
{
id: "roles",
links: [{ labelKey: "settings.policies.sections.roles.links.roles", path: "settings/roles-and-permissions" }],
},
{
id: "billing",
links: [{ labelKey: "settings.policies.sections.billing.links.billing", path: "settings/subscription" }],
},
{
id: "notifications",
links: [{ labelKey: "settings.policies.sections.notifications.links.notifications", path: "settings/notifications" }],
},
{
id: "audit",
links: [{ labelKey: "settings.policies.sections.audit.links.audit", path: "settings/logs" }],
},
{
id: "api",
links: [{ labelKey: "settings.policies.sections.api.links.api", path: "settings/api" }],
},
];
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdFromUrl(params);
await verifyUserHasPermission(request, "app.settings.account.view", tenantId);
const { t } = await getTranslations(request);
const data: LoaderData = {
title: `${t("settings.policies.title")} | ${process.env.APP_NAME}`,
workspaceSlug: params.tenant ?? "",
};
return data;
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function WorkspacePoliciesRoute() {
const data = useLoaderData<LoaderData>();
const params = useParams();
const { t } = useTranslation();
return (
<main data-ui-id="ui.settings.policies.page" className="mx-auto grid max-w-4xl gap-6 px-4 py-5 sm:px-8">
<div className="space-y-2">
<p className="text-sm font-medium text-primary">{t("settings.policies.eyebrow")}</p>
<h1 className="text-2xl font-semibold text-foreground">{t("settings.policies.heading")}</h1>
<p className="max-w-3xl text-sm text-muted-foreground">{t("settings.policies.description")}</p>
</div>
<div className="rounded-lg border bg-card p-4 text-sm text-muted-foreground">
<span className="font-medium text-foreground">{t("settings.policies.resolvedWorkspace")}</span> {data.workspaceSlug}
</div>
<div className="grid gap-4 md:grid-cols-2">
{POLICY_SECTIONS.map((section) => (
<section key={section.id} data-ui-id={`ui.settings.policies.section.${section.id}`} className="rounded-lg border bg-card p-5 shadow-sm">
<div className="space-y-2">
<h2 className="text-base font-semibold text-foreground">{t(`settings.policies.sections.${section.id}.heading`)}</h2>
<p className="text-sm leading-6 text-muted-foreground">{t(`settings.policies.sections.${section.id}.body`)}</p>
</div>
<div className="mt-4 flex flex-wrap gap-2">
{section.links.map((link) => (
<a key={link.path} href={UrlUtils.currentTenantUrl(params, link.path)} className="text-sm font-medium text-primary underline-offset-2 hover:underline">
{t(link.labelKey)}
</a>
))}
</div>
</section>
))}
</div>
</main>
);
export default function LegacyPoliciesRedirect() {
return null;
}
@@ -0,0 +1,8 @@
// AK-SET-01 — legacy `settings/privacy/avv` is now a Compliance-Hub tab.
import { legacySettingsRedirectLoader } from "./legacy-redirects.server";
export const loader = legacySettingsRedirectLoader("settings/compliance/avv");
export default function LegacyPrivacyRedirect_avv() {
return null;
}
Loaded 100 of 5955 files, more files were not shown because too many files have changed in this diff. Show more