/** * 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; nextCursor: { ts: string; id: string } | null; capabilityOptions: ReadonlyArray; }; 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 = { tenantId, pluginId: plugin.pluginId, }; if (capability) { where.capability = capability; } if (from || to) { const range: Record = {}; 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(); 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 (

{t("settings.plugins.audit.backToPlugins")}

{t("settings.plugins.audit.heading")} · {data.plugin.pluginId}

{t("settings.plugins.audit.description")}

{t("settings.plugins.audit.filters.reset")}
{data.rows.length === 0 ? (

{t("settings.plugins.audit.empty")}

) : (
{data.rows.map((row) => ( ))}
{t("settings.plugins.audit.table.timestamp")} {t("settings.plugins.audit.table.capability")} {t("settings.plugins.audit.table.outcome")} {t("settings.plugins.audit.table.duration")} {t("settings.plugins.audit.table.invocation")} {t("settings.plugins.audit.table.payloadHash")}
{formatters.date(row.timestamp, { dateStyle: "medium", timeStyle: "medium" })} {row.capability} {outcomeLabel(row.outcome)} {row.errorCode ? ` · ${row.errorCode}` : ""} {row.durationMs === null ? t("shared.notAvailable") : t("settings.plugins.audit.durationMs", { duration: formatters.number(row.durationMs), })} {row.pluginInvocationId.slice(0, 8)}… {row.payloadHash ? `${row.payloadHash.slice(0, 12)}…` : t("shared.notSet")}
)} {nextHref ? (
{t("settings.plugins.audit.nextPage")}
) : null}
); } function withParams(current: URLSearchParams, next: Record): string { const merged = new URLSearchParams(current); for (const [k, v] of Object.entries(next)) { merged.set(k, v); } return merged.toString(); }