Files
HiveGrid-Wireframes/hivegrid-cloud/apps/web/app/routes/app.$tenant/settings/plugins.$id.audit.tsx
T

341 lines
13 KiB
TypeScript

/**
* 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 { 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";
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 ({ 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();
}