Files
archie/ui/src/audit/audit.ts
T

443 lines
14 KiB
TypeScript

import type { LocationQuery } from "vue-router";
import type { QueryParams } from "@/lib/api";
import { formatValue, type Change } from "@/lib/changes";
/** One actor as the audit feed reports it. */
export interface AuditActor {
id: string;
name?: string;
kind?: string;
principal_id?: string;
}
/** The thing the event happened to; `href` is a same-origin dashboard route. */
export interface AuditTarget {
kind: string;
id: string;
label?: string;
href?: string;
}
export interface AuditField {
field: string;
old?: unknown;
new?: unknown;
}
/** Per-event context. A settings change carries `fields`; a runtime event
* carries `data`. */
export interface AuditDetail {
fields?: AuditField[];
data?: Record<string, unknown> | null;
version?: number;
request_id?: string;
source?: string;
table?: string;
}
export type AuditCategory = "settings" | "access" | "identity" | "runtime";
export type AuditSeverity = "info" | "warning" | "critical";
export type AuditOutcome = "success" | "denied" | "failure";
export interface AuditRecord {
/** Composite and opaque, e.g. "1:42". */
id: string;
at: string;
category: AuditCategory;
action: string;
kind: string;
severity: AuditSeverity;
outcome: AuditOutcome;
actor: AuditActor;
target: AuditTarget;
summary: string;
detail?: AuditDetail;
}
/** One settings kind the feed can name, with its catalog title. */
export interface SettingsKind {
kind: string;
title: string;
}
/** The server's closed vocabularies, so the UI never invents one. */
export interface AuditFacets {
categories: string[];
severities: string[];
outcomes: string[];
target_kinds: string[];
settings_kinds: SettingsKind[];
}
export interface AuditResponse {
records: AuditRecord[];
next_cursor?: string | null;
has_more: boolean;
facets?: AuditFacets;
}
export function emptyFacets(): AuditFacets {
return {
categories: [],
severities: [],
outcomes: [],
target_kinds: [],
settings_kinds: [],
};
}
/** The filter state carried in the URL. */
export interface AuditQuery {
q?: string;
categories: string[];
kinds: string[];
actions: string[];
actor?: string;
target_kind?: string;
target_id?: string;
severity?: string;
outcome?: string;
/** 24h, 7d, 30d or any. Absent means the default 30 days. */
since?: string;
/** Custom range, in datetime-local form. */
from?: string;
to?: string;
}
const PRESET_MS: Record<string, number> = {
"24h": 86_400_000,
"7d": 604_800_000,
"30d": 2_592_000_000,
};
/** The default window: what the time select shows when the URL is bare. */
export const DEFAULT_SINCE = "30d";
function text(value: LocationQuery[string] | undefined): string | undefined {
const first = Array.isArray(value) ? value[0] : value;
const trimmed = first == null ? "" : String(first).trim();
return trimmed || undefined;
}
function list(value: LocationQuery[string] | undefined): string[] {
if (value == null) return [];
const raw = Array.isArray(value) ? value : [value];
return raw
.flatMap((item) => String(item).split(","))
.map((item) => item.trim())
.filter(Boolean);
}
/** Reads the URL into a query. `section` is the pre-Audit deep-link name for
* the resource-kind filter, and still wins when `kind` is absent. */
export function queryFromRoute(query: LocationQuery): AuditQuery {
const kinds = list(query.kind);
return {
q: text(query.q),
categories: list(query.categories),
kinds: kinds.length ? kinds : list(query.section),
actions: list(query.actions),
actor: text(query.actor),
target_kind: text(query.target_kind),
target_id: text(query.target_id),
severity: text(query.severity),
outcome: text(query.outcome),
since: text(query.since),
from: text(query.from),
to: text(query.to),
};
}
/** Writes a query back as URL values: arrays are comma-joined so a shared or
* bookmarked URL stays readable. */
export function routeQueryFor(query: AuditQuery): Record<string, string> {
const out: Record<string, string> = {};
const put = (key: string, value: string | undefined) => {
if (value) out[key] = value;
};
put("q", query.q?.trim());
put("categories", query.categories.join(","));
put("actions", query.actions.join(","));
put("kind", query.kinds.join(","));
put("actor", query.actor?.trim());
put("target_kind", query.target_kind);
put("target_id", query.target_id?.trim());
put("severity", query.severity);
put("outcome", query.outcome);
put("since", query.since);
put("from", query.from);
put("to", query.to);
return out;
}
function instant(value: string | undefined): string | undefined {
if (!value) return undefined;
const date = new Date(value);
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
}
/** Resolves the explicit window once per load. The cursor is bound to these
* exact bounds, so pagination must not recompute them. */
export function timeBounds(
query: AuditQuery,
now = Date.now(),
): { from?: string; to?: string } {
const from = instant(query.from);
const to = instant(query.to);
if (from || to) return { from, to };
if (query.since === "any") return {};
const ms = PRESET_MS[query.since ?? DEFAULT_SINCE] ?? PRESET_MS[DEFAULT_SINCE];
return { from: new Date(now - ms).toISOString() };
}
/** The server filter for one page. Arrays become repeated parameters. */
export function apiParams(query: AuditQuery, now = Date.now()): QueryParams {
const { from, to } = timeBounds(query, now);
return {
q: query.q?.trim() || undefined,
categories: query.categories.length ? query.categories : undefined,
actions: query.actions.length ? query.actions : undefined,
kind: query.kinds.length ? query.kinds : undefined,
actor: query.actor?.trim() || undefined,
target_kind: query.target_kind,
target_id: query.target_id?.trim() || undefined,
severity: query.severity,
outcome: query.outcome,
from,
to,
};
}
export function hasFilters(query: AuditQuery): boolean {
return !!(
query.q ||
query.categories.length ||
query.kinds.length ||
query.actions.length ||
query.actor ||
query.target_kind ||
query.target_id ||
query.severity ||
query.outcome ||
query.from ||
query.to
);
}
/** What the table says when the server returned no rows. An empty feed and a
* filter that matched nothing must not read the same. */
export function emptyMessage(query: AuditQuery): string {
if (hasFilters(query)) return "No records match these filters.";
if (query.since === "any") return "No audit records yet.";
if (query.from || query.to) return "No records in this range.";
const window = query.since === "24h" ? "24 hours" : query.since === "7d" ? "7 days" : "30 days";
return `No records in the last ${window}.`;
}
export function presetLabel(query: AuditQuery): string {
if (query.from || query.to) return "Custom range";
switch (query.since) {
case "any":
return "Any time";
case "24h":
return "Last 24 hours";
case "7d":
return "Last 7 days";
default:
return "Last 30 days";
}
}
export interface AuditChip {
key: "kind" | "action" | "actor" | "severity" | "target_kind" | "target_id" | "from" | "to";
value: string;
text: string;
}
/** A server value read as a label: "access_policies" -> "Access policies". */
export function valueLabel(value: string): string {
const words = value.replaceAll("_", " ").replaceAll("-", " ");
return words ? words.charAt(0).toUpperCase() + words.slice(1) : value;
}
function settingsKindLabel(options: SettingsKind[], value: string): string {
return options.find((option) => option.kind === value)?.title ?? value;
}
function localTime(value: string): string {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
}
/** The advanced and deep-link filters as removable chips. */
export function filterChips(query: AuditQuery, facets: AuditFacets): AuditChip[] {
return [
...query.kinds.map((value) => ({
key: "kind" as const,
value,
text: `Kind: ${settingsKindLabel(facets.settings_kinds, value)}`,
})),
...query.actions.map((value) => ({
key: "action" as const,
value,
text: `Action: ${value}`,
})),
...(query.actor ? [{ key: "actor" as const, value: query.actor, text: `Actor: ${query.actor}` }] : []),
...(query.severity
? [
{
key: "severity" as const,
value: query.severity,
text: `Severity: ${valueLabel(query.severity)}`,
},
]
: []),
...(query.target_kind
? [
{
key: "target_kind" as const,
value: query.target_kind,
text: `Target kind: ${valueLabel(query.target_kind)}`,
},
]
: []),
...(query.target_id
? [{ key: "target_id" as const, value: query.target_id, text: `Target: ${query.target_id}` }]
: []),
...(query.from ? [{ key: "from" as const, value: query.from, text: `From: ${localTime(query.from)}` }] : []),
...(query.to ? [{ key: "to" as const, value: query.to, text: `To: ${localTime(query.to)}` }] : []),
];
}
export type AuditBadgeVariant = "danger" | "warn" | "info";
/** A textual badge carries severity; colour alone never does. */
export function badgeFor(record: AuditRecord): { label: string; variant: AuditBadgeVariant } | null {
if (record.outcome === "denied") return { label: "Denied", variant: "danger" };
if (record.outcome === "failure") return { label: "Failed", variant: "danger" };
if (record.severity === "critical") return { label: "Critical", variant: "danger" };
if (record.severity === "warning") return { label: "Warning", variant: "warn" };
return null;
}
/** One leaf per changed field, in the shape ChangeList renders. */
export function changesFromFields(detail?: AuditDetail): Change[] {
return (detail?.fields ?? []).map((field, index) => ({
path: field.field || `field ${index + 1}`,
before: field.old,
after: field.new,
}));
}
export interface AuditMetadataRow {
key: string;
label: string;
value?: string;
mono?: boolean;
}
function humanise(field: string): string {
return field.replaceAll("_", " ").replaceAll("-", " ");
}
/** Label/value rows for a runtime event: its target, its data and how it was
* recorded. A settings change shows its diff instead. */
export function metadataRows(record: AuditRecord): AuditMetadataRow[] {
const detail = record.detail ?? {};
const rows: AuditMetadataRow[] = [];
if (!detail.fields?.length) {
rows.push({
key: "target",
label: "Target",
value: record.target?.label || record.target?.id || "",
});
}
if (detail.data && typeof detail.data === "object" && !Array.isArray(detail.data)) {
for (const [key, value] of Object.entries(detail.data as Record<string, unknown>)) {
rows.push({
key: `data.${key}`,
label: humanise(key),
value: formatValue(value),
mono: typeof value !== "string",
});
}
} else if (detail.data != null) {
rows.push({ key: "data", label: "Data", value: formatValue(detail.data), mono: true });
}
if (detail.table) rows.push({ key: "table", label: "Table", value: detail.table, mono: true });
if (detail.source) rows.push({ key: "source", label: "Source", value: detail.source, mono: true });
if (detail.version != null)
rows.push({ key: "version", label: "Version", value: String(detail.version), mono: true });
if (detail.request_id)
rows.push({ key: "request", label: "Request", value: detail.request_id, mono: true });
return rows;
}
export function recordKey(record: AuditRecord): string {
return record.id;
}
/** The target's own id when it adds anything beyond the label: the settings
* resource kind, a record key, or a task id. */
export function targetDetail(target?: AuditTarget): string {
if (!target?.id) return "";
return target.id === target.label ? "" : target.id;
}
/** Keeps the first occurrence, so a live page and an older page cannot show
* the same event twice. */
export function dedupeRecords(records: AuditRecord[]): AuditRecord[] {
const seen = new Set<string>();
return records.filter((record) => {
const key = recordKey(record);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
/** Saved views live in this browser, keyed by the signed-in identity. */
export interface SavedAuditView {
name: string;
query: Record<string, string>;
}
export function savedViewsKey(identityId: string): string {
return `archie.audit.views.${identityId}`;
}
export function readSavedViews(identityId: string): SavedAuditView[] {
if (!identityId) return [];
try {
const raw = localStorage.getItem(savedViewsKey(identityId));
if (!raw) return [];
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed.flatMap((entry): SavedAuditView[] => {
if (!entry || typeof entry !== "object") return [];
const candidate = entry as { name?: unknown; query?: unknown };
if (typeof candidate.name !== "string" || !candidate.name.trim()) return [];
if (!candidate.query || typeof candidate.query !== "object") return [];
const query = Object.fromEntries(
Object.entries(candidate.query as Record<string, unknown>).map(([key, value]) => [
key,
String(value),
]),
);
return [{ name: candidate.name, query }];
});
} catch {
return [];
}
}
export function writeSavedViews(identityId: string, views: SavedAuditView[]): void {
if (!identityId) return;
try {
localStorage.setItem(savedViewsKey(identityId), JSON.stringify(views));
} catch {
// The view still applies for this page; only persistence is lost.
}
}