499 lines
20 KiB
TypeScript
499 lines
20 KiB
TypeScript
import {
|
|
buildTenantSecurityVM,
|
|
type TenantSecurityMetric,
|
|
type TenantSecurityData,
|
|
type TenantSecurityRisk,
|
|
type TenantSecuritySessionRow,
|
|
type TenantSecurityTone,
|
|
type TenantSecurityTrustedDeviceRow,
|
|
} from "@hivegrid/view-models";
|
|
import { AlertTriangle, ArrowLeft, KeyRound, LinkIcon, MonitorSmartphone, ShieldCheck, ShieldX, UserRoundCheck } from "lucide-react";
|
|
import type React from "react";
|
|
import { Form, Link, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData, useNavigation, type ActionFunctionArgs } from "react-router";
|
|
import { useTranslation } from "react-i18next";
|
|
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
|
import { Badge, type BadgeColor } from "~/components/ui/badge";
|
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { useLocaleFormatters } from "~/locale/format";
|
|
import { getUser } from "~/utils/db/users.db.server";
|
|
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
|
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
|
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
|
import { useRootData } from "~/utils/data/useRootData";
|
|
import {
|
|
forgetTenantTrustedDevice,
|
|
getTenantSecuritySnapshot,
|
|
revokeTenantUserSession,
|
|
TenantSecurityError,
|
|
} from "~/services/admin/tenant-security.server";
|
|
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
|
|
type LoaderData = {
|
|
title: string;
|
|
vm: ReturnType<typeof buildTenantSecurityVM>;
|
|
};
|
|
|
|
type ActionData = {
|
|
success?: string;
|
|
error?: string;
|
|
};
|
|
|
|
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
await verifyUserHasPermission(request, "admin.account.view");
|
|
const { t } = await getTranslations(request);
|
|
const tenantId = params.id;
|
|
if (!tenantId) {
|
|
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
|
}
|
|
|
|
try {
|
|
const snapshot = await runWithRlsContext({ tenantId }, () => getTenantSecuritySnapshot(tenantId));
|
|
return {
|
|
title: `${t("admin.tenantSecurity.title")} | ${process.env.APP_NAME}`,
|
|
vm: buildTenantSecurityVM(snapshot),
|
|
} satisfies LoaderData;
|
|
} catch (error) {
|
|
if (error instanceof TenantSecurityError && error.code === "TENANT_NOT_FOUND") {
|
|
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
|
}
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
function badRequest(data: ActionData) {
|
|
return Response.json(data, { status: 400 });
|
|
}
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
await verifyUserHasPermission(request, "admin.account.settings.update");
|
|
const { t } = await getTranslations(request);
|
|
await validateCSRFToken(request);
|
|
const form = await request.formData();
|
|
const userInfo = await getUserInfo(request);
|
|
const actor = await getUser(userInfo.userId);
|
|
const action = form.get("action")?.toString() ?? "";
|
|
const reason = form.get("reason")?.toString() ?? "";
|
|
const tenantId = params.id ?? "";
|
|
|
|
try {
|
|
if (action === "revoke-session") {
|
|
await runWithRlsContext({ tenantId }, () =>
|
|
revokeTenantUserSession({
|
|
tenantId,
|
|
sessionId: form.get("sessionId")?.toString() ?? "",
|
|
reason,
|
|
actorUserId: userInfo.userId,
|
|
actorEmail: actor?.email ?? null,
|
|
request,
|
|
})
|
|
);
|
|
return Response.json({ success: t("admin.tenantSecurity.actions.sessionRevoked") } satisfies ActionData);
|
|
}
|
|
if (action === "forget-device") {
|
|
await runWithRlsContext({ tenantId }, () =>
|
|
forgetTenantTrustedDevice({
|
|
tenantId,
|
|
trustedDeviceId: form.get("trustedDeviceId")?.toString() ?? "",
|
|
reason,
|
|
actorUserId: userInfo.userId,
|
|
actorEmail: actor?.email ?? null,
|
|
request,
|
|
})
|
|
);
|
|
return Response.json({ success: t("admin.tenantSecurity.actions.deviceForgotten") } satisfies ActionData);
|
|
}
|
|
return badRequest({ error: t("shared.invalidForm") });
|
|
} catch (error) {
|
|
if (error && typeof error === "object" && "i18nKey" in error && typeof error.i18nKey === "string") {
|
|
return badRequest({ error: t(error.i18nKey) });
|
|
}
|
|
if (error instanceof TenantSecurityError) {
|
|
return badRequest({ error: t(`admin.tenantSecurity.errors.${error.code}`) });
|
|
}
|
|
return badRequest({ error: t("admin.tenantSecurity.errors.actionFailed") });
|
|
}
|
|
};
|
|
|
|
export default function TenantSecurityRoute() {
|
|
const { t } = useTranslation();
|
|
const data = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<ActionData>();
|
|
const navigation = useNavigation();
|
|
const loading = navigation.state === "submitting";
|
|
|
|
return (
|
|
<EditPageLayout title={t("admin.tenantSecurity.title")} fullWidth>
|
|
{data.vm.status === "ready" ? (
|
|
<TenantSecurityPage data={data.vm.data} actionData={actionData} loading={loading} />
|
|
) : (
|
|
<div className="border-border bg-background rounded-md border p-6">
|
|
<div className="font-medium">{t("admin.tenantSecurity.empty.title")}</div>
|
|
<div className="text-muted-foreground mt-1 text-sm">{t("admin.tenantSecurity.empty.body")}</div>
|
|
</div>
|
|
)}
|
|
</EditPageLayout>
|
|
);
|
|
}
|
|
|
|
function TenantSecurityPage({
|
|
data,
|
|
actionData,
|
|
loading,
|
|
}: {
|
|
data: TenantSecurityData;
|
|
actionData: ActionData | undefined;
|
|
loading: boolean;
|
|
}) {
|
|
const { t } = useTranslation();
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
<div className="border-border bg-surface-neutral-primary rounded-md border p-4">
|
|
<div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
|
|
<div className="min-w-0">
|
|
<Link to={adminPath(`accounts/${data.tenant.id}`, { mode: "host-aware" })} className="text-primary inline-flex items-center gap-1 text-sm font-medium hover:underline">
|
|
<ArrowLeft className="size-4" aria-hidden="true" />
|
|
{t("admin.tenantSecurity.backToTenant")}
|
|
</Link>
|
|
<div className="text-muted-foreground mt-2 text-sm">
|
|
{t("admin.tenantSecurity.description", { tenant: data.tenant.name, slug: data.tenant.slug })}
|
|
</div>
|
|
</div>
|
|
<Badge color={riskBadgeColor(data.risk)} withColorDot>
|
|
{t(data.riskLabelKey)}
|
|
</Badge>
|
|
</div>
|
|
<div className="text-muted-foreground mt-3 text-sm">{t(data.riskDetailKey)}</div>
|
|
{actionData?.success ? <div className="mt-3 rounded-md bg-green-50 px-3 py-2 text-sm text-green-800">{actionData.success}</div> : null}
|
|
{actionData?.error ? <div className="mt-3 rounded-md bg-red-50 px-3 py-2 text-sm text-red-800">{actionData.error}</div> : null}
|
|
</div>
|
|
|
|
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
|
|
{data.metrics.map((metric) => (
|
|
<MetricCard key={metric.id} metric={metric} />
|
|
))}
|
|
</div>
|
|
|
|
{data.issues.length > 0 ? (
|
|
<Card className="gap-4 rounded-lg border-yellow-200 bg-yellow-50 py-5">
|
|
<CardHeader>
|
|
<CardTitle className="flex items-center gap-2 text-base text-yellow-950">
|
|
<AlertTriangle className="size-5" aria-hidden="true" />
|
|
{t("admin.tenantSecurity.issues.title")}
|
|
</CardTitle>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<ul className="grid gap-2 text-sm text-yellow-900 md:grid-cols-2">
|
|
{data.issues.map((issue) => (
|
|
<li key={issue}>{t(issue)}</li>
|
|
))}
|
|
</ul>
|
|
</CardContent>
|
|
</Card>
|
|
) : null}
|
|
|
|
<Card className="gap-4 rounded-lg py-5">
|
|
<CardHeader>
|
|
<CardTitle>{t("admin.tenantSecurity.users.title")}</CardTitle>
|
|
<CardDescription>{t("admin.tenantSecurity.users.description")}</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full min-w-[760px] text-sm">
|
|
<thead className="text-muted-foreground border-b text-left">
|
|
<tr>
|
|
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.user")}</th>
|
|
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.status")}</th>
|
|
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.mfa")}</th>
|
|
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.recovery")}</th>
|
|
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.risk")}</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody className="divide-y">
|
|
{data.users.map((user) => (
|
|
<tr key={user.id}>
|
|
<td className="py-3 pr-4">
|
|
<div className="font-medium">{user.name}</div>
|
|
<div className="text-muted-foreground">{user.email}</div>
|
|
</td>
|
|
<td className="py-3 pr-4">{t(user.statusLabelKey)}</td>
|
|
<td className="py-3 pr-4">{t(user.mfaLabelKey)}</td>
|
|
<td className="py-3 pr-4">{user.recoveryCodesConfigured ? t("shared.yes") : t("shared.no")}</td>
|
|
<td className="py-3 pr-4">
|
|
<Badge color={riskBadgeColor(user.risk)} withColorDot>
|
|
{t(user.riskLabelKey)}
|
|
</Badge>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<div className="grid gap-4 xl:grid-cols-2">
|
|
<SessionsCard rows={data.sessions} loading={loading} />
|
|
<TrustedDevicesCard rows={data.trustedDevices} loading={loading} />
|
|
</div>
|
|
|
|
<div className="grid gap-4 xl:grid-cols-2">
|
|
<Card className="gap-4 rounded-lg py-5">
|
|
<CardHeader>
|
|
<CardTitle>{t("admin.tenantSecurity.magicLinks.title")}</CardTitle>
|
|
<CardDescription>{t("admin.tenantSecurity.magicLinks.description")}</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<CompactRows
|
|
emptyKey="admin.tenantSecurity.magicLinks.empty"
|
|
rows={data.magicLinks.map((link) => ({
|
|
id: link.id,
|
|
title: link.userEmail,
|
|
detail: `${t(link.statusLabelKey)} · ${link.expiresAt}`,
|
|
tone: link.tone,
|
|
}))}
|
|
/>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card className="gap-4 rounded-lg py-5">
|
|
<CardHeader>
|
|
<CardTitle>{t("admin.tenantSecurity.ipLogs.title")}</CardTitle>
|
|
<CardDescription>{t("admin.tenantSecurity.ipLogs.description")}</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<CompactRows
|
|
emptyKey="admin.tenantSecurity.ipLogs.empty"
|
|
rows={data.ipLogs.map((log) => ({
|
|
id: log.id,
|
|
title: `${log.maskedIp} · ${log.actorLabel}`,
|
|
detail: `${log.fromUrl} · ${log.createdAt}`,
|
|
tone: "neutral",
|
|
}))}
|
|
/>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
|
|
<Card className="gap-4 rounded-lg py-5">
|
|
<CardHeader>
|
|
<CardTitle>{t("admin.tenantSecurity.audit.title")}</CardTitle>
|
|
<CardDescription>{t("admin.tenantSecurity.audit.description")}</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<CompactRows
|
|
emptyKey="admin.tenantSecurity.audit.empty"
|
|
rows={data.auditEvents.map((event) => ({
|
|
id: event.id,
|
|
title: event.displaySummary,
|
|
detail: `${event.actorEmail ?? event.actorId ?? "system"} · ${event.createdAt}`,
|
|
tone: event.tone,
|
|
}))}
|
|
/>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function MetricCard({ metric }: { metric: TenantSecurityMetric }) {
|
|
const { t } = useTranslation();
|
|
return (
|
|
<Card className="gap-4 rounded-lg py-5">
|
|
<CardHeader>
|
|
<div className="flex items-start justify-between gap-3">
|
|
<div className="min-w-0">
|
|
<CardTitle className="text-sm leading-5">{t(metric.labelKey)}</CardTitle>
|
|
<CardDescription className="mt-1 leading-5">{t(metric.detailKey)}</CardDescription>
|
|
</div>
|
|
<div className={`flex size-10 shrink-0 items-center justify-center rounded-md border ${toneIconClasses(metric.tone)}`}>{metricIcon(metric.id)}</div>
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<div className="text-2xl font-semibold leading-7">{metric.value}</div>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
function SessionsCard({ rows, loading }: { rows: readonly TenantSecuritySessionRow[]; loading: boolean }) {
|
|
const { t } = useTranslation();
|
|
const format = useLocaleFormatters();
|
|
return (
|
|
<Card className="gap-4 rounded-lg py-5">
|
|
<CardHeader>
|
|
<CardTitle>{t("admin.tenantSecurity.sessions.title")}</CardTitle>
|
|
<CardDescription>{t("admin.tenantSecurity.sessions.description")}</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<div className="space-y-3">
|
|
{rows.length === 0 ? <div className="text-muted-foreground text-sm">{t("admin.tenantSecurity.sessions.empty")}</div> : null}
|
|
{rows.map((session) => (
|
|
<div key={session.id} className="rounded-md border p-3">
|
|
<div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
|
<div className="min-w-0">
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<div className="font-medium">{session.displayDevice}</div>
|
|
<Badge color={toneBadgeColor(session.tone)} withColorDot>
|
|
{t(session.statusLabelKey)}
|
|
</Badge>
|
|
</div>
|
|
<div className="text-muted-foreground mt-1 text-sm">{session.userEmail}</div>
|
|
<div className="text-muted-foreground mt-1 text-xs">
|
|
{t("admin.tenantSecurity.sessions.lastSeen", { value: format.dateTime(session.lastSeenAt) })}
|
|
</div>
|
|
</div>
|
|
{session.status === "active" || session.status === "trusted" ? (
|
|
<SecurityActionForm action="revoke-session" idName="sessionId" idValue={session.id} buttonKey="admin.tenantSecurity.actions.revokeSession" loading={loading} />
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
function TrustedDevicesCard({ rows, loading }: { rows: readonly TenantSecurityTrustedDeviceRow[]; loading: boolean }) {
|
|
const { t } = useTranslation();
|
|
const format = useLocaleFormatters();
|
|
return (
|
|
<Card className="gap-4 rounded-lg py-5">
|
|
<CardHeader>
|
|
<CardTitle>{t("admin.tenantSecurity.devices.title")}</CardTitle>
|
|
<CardDescription>{t("admin.tenantSecurity.devices.description")}</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<div className="space-y-3">
|
|
{rows.length === 0 ? <div className="text-muted-foreground text-sm">{t("admin.tenantSecurity.devices.empty")}</div> : null}
|
|
{rows.map((device) => (
|
|
<div key={device.id} className="rounded-md border p-3">
|
|
<div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
|
<div className="min-w-0">
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<div className="font-medium">{device.displayDevice}</div>
|
|
<Badge color={toneBadgeColor(device.tone)} withColorDot>
|
|
{t(device.statusLabelKey)}
|
|
</Badge>
|
|
</div>
|
|
<div className="text-muted-foreground mt-1 text-sm">{device.userEmail}</div>
|
|
<div className="text-muted-foreground mt-1 text-xs">
|
|
{t("admin.tenantSecurity.devices.lastUsed", { value: format.dateTime(device.lastUsedAt) })}
|
|
</div>
|
|
</div>
|
|
{device.status === "active" ? (
|
|
<SecurityActionForm action="forget-device" idName="trustedDeviceId" idValue={device.id} buttonKey="admin.tenantSecurity.actions.forgetDevice" loading={loading} />
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
function SecurityActionForm({
|
|
action,
|
|
idName,
|
|
idValue,
|
|
buttonKey,
|
|
loading,
|
|
}: {
|
|
action: string;
|
|
idName: string;
|
|
idValue: string;
|
|
buttonKey: string;
|
|
loading: boolean;
|
|
}) {
|
|
const { t } = useTranslation();
|
|
const rootData = useRootData();
|
|
return (
|
|
<Form method="post" className="flex w-full flex-col gap-2 md:w-72">
|
|
<input type="hidden" name="action" value={action} />
|
|
<input type="hidden" name={idName} value={idValue} />
|
|
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} />
|
|
<input
|
|
name="reason"
|
|
required
|
|
minLength={5}
|
|
placeholder={t("admin.tenantSecurity.actions.reasonPlaceholder")}
|
|
className="border-border bg-background h-9 rounded-md border px-3 text-sm focus-visible:outline-none focus-visible:shadow-focus"
|
|
/>
|
|
<ButtonSecondary disabled={loading} type="submit">
|
|
{t(buttonKey)}
|
|
</ButtonSecondary>
|
|
</Form>
|
|
);
|
|
}
|
|
|
|
function CompactRows({
|
|
rows,
|
|
emptyKey,
|
|
}: {
|
|
rows: readonly { readonly id: string; readonly title: string; readonly detail: string; readonly tone: TenantSecurityTone }[];
|
|
emptyKey: string;
|
|
}) {
|
|
const { t } = useTranslation();
|
|
if (rows.length === 0) return <div className="text-muted-foreground text-sm">{t(emptyKey)}</div>;
|
|
return (
|
|
<div className="space-y-2">
|
|
{rows.map((row) => (
|
|
<div key={row.id} className="flex items-start justify-between gap-3 rounded-md border p-3 text-sm">
|
|
<div className="min-w-0">
|
|
<div className="truncate font-medium">{row.title}</div>
|
|
<div className="text-muted-foreground mt-1 truncate">{row.detail}</div>
|
|
</div>
|
|
<span className={`mt-1 size-2 shrink-0 rounded-full ${toneDotClass(row.tone)}`} />
|
|
</div>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function metricIcon(id: string): React.ReactNode {
|
|
if (id === "mfa") return <ShieldCheck className="size-5" aria-hidden="true" />;
|
|
if (id === "sessions") return <MonitorSmartphone className="size-5" aria-hidden="true" />;
|
|
if (id === "devices") return <KeyRound className="size-5" aria-hidden="true" />;
|
|
if (id === "magicLinks") return <LinkIcon className="size-5" aria-hidden="true" />;
|
|
if (id === "loginFailures") return <ShieldX className="size-5" aria-hidden="true" />;
|
|
return <UserRoundCheck className="size-5" aria-hidden="true" />;
|
|
}
|
|
|
|
function riskBadgeColor(risk: TenantSecurityRisk): BadgeColor {
|
|
if (risk === "high") return "red";
|
|
if (risk === "medium") return "yellow";
|
|
return "green";
|
|
}
|
|
|
|
function toneBadgeColor(tone: TenantSecurityTone): BadgeColor {
|
|
if (tone === "danger") return "red";
|
|
if (tone === "warning") return "yellow";
|
|
if (tone === "success") return "green";
|
|
return "gray";
|
|
}
|
|
|
|
function toneIconClasses(tone: TenantSecurityTone): string {
|
|
if (tone === "danger") return "border-red-200 bg-red-50 text-red-700";
|
|
if (tone === "warning") return "border-yellow-200 bg-yellow-50 text-yellow-700";
|
|
if (tone === "success") return "border-green-200 bg-green-50 text-green-700";
|
|
return "border-border bg-surface-neutral-primary text-muted-foreground";
|
|
}
|
|
|
|
function toneDotClass(tone: TenantSecurityTone): string {
|
|
if (tone === "danger") return "bg-red-500";
|
|
if (tone === "warning") return "bg-yellow-500";
|
|
if (tone === "success") return "bg-green-500";
|
|
return "bg-gray-300";
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|