feat(ui): unified audit page with server filters and live tail

This commit is contained in:
sam committed 2026-10-25 22:09:25 +11:00
1 parent 2caab17461
commit 2ce773f5a5
19 files changed
+1519 -424

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
<script setup lang="ts">
import { computed } from "vue";
import { Undo2 } from "@lucide/vue";
import ChangeList from "@/components/ChangeList.vue";
import { Button } from "@/components/ui/button";
import { MetadataList } from "@/components/ui/metadata-list";
import {
changesFromFields,
metadataRows,
type AuditRecord,
} from "./audit";
const props = defineProps<{ record: AuditRecord; canRevert?: boolean }>();
defineEmits<{ revert: [] }>();
const changes = computed(() => changesFromFields(props.record.detail));
const rows = computed(() => metadataRows(props.record));
</script>
<template>
<div class="space-y-3 py-1">
<ChangeList v-if="changes.length" :changes="changes" :revertable="false" />
<MetadataList v-if="rows.length" :rows="rows">
<template #value="{ row }">
<RouterLink
v-if="row.key === 'target' && record.target?.href"
:to="record.target.href"
class="hover:underline"
>{{ row.value }}</RouterLink>
<template v-else>{{ row.value }}</template>
</template>
</MetadataList>
<div v-if="props.canRevert">
<Button variant="outline" size="sm" @click="$emit('revert')"><Undo2 data-icon="inline-start" />Revert</Button>
</div>
</div>
</template>
+36
View File
@@ -0,0 +1,36 @@
<script setup lang="ts">
import { Download } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { api, type QueryParams } from "@/lib/api";
/** Export is a browser download: the anchor navigates, so the server owns the
* filename and streams the body to disk. */
const props = defineProps<{ params: QueryParams }>();
function url(format: "csv" | "json"): string {
return api.auditExportURL(format, props.params);
}
</script>
<template>
<DropdownMenu>
<DropdownMenuTrigger as-child>
<Button variant="outline" size="sm"><Download data-icon="inline-start" />Export</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem as-child>
<a :href="url('csv')" download aria-label="Export as CSV">CSV</a>
</DropdownMenuItem>
<DropdownMenuItem as-child>
<a :href="url('json')" download aria-label="Export as JSON">JSON</a>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</template>
+244
View File
@@ -0,0 +1,244 @@
<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from "vue";
import { ListFilter, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Toggle } from "@/components/ui/toggle";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import {
filterChips,
presetLabel,
valueLabel,
type AuditChip,
type AuditFacets,
type AuditQuery,
} from "./audit";
const props = defineProps<{ query: AuditQuery; facets: AuditFacets }>();
const emit = defineEmits<{ change: [patch: Partial<AuditQuery>] }>();
const advancedOpen = ref(false);
// Search is typed, so it settles before it reaches the URL and the server.
const search = ref(props.query.q ?? "");
let searchTimer: ReturnType<typeof setTimeout> | undefined;
watch(
() => props.query.q,
(value) => {
const next = value ?? "";
if (next !== search.value) search.value = next;
},
);
watch(search, (value) => {
clearTimeout(searchTimer);
const next = value.trim();
if (next === (props.query.q ?? "")) return;
searchTimer = setTimeout(() => emit("change", { q: next || undefined }), 300);
});
onUnmounted(() => clearTimeout(searchTimer));
const actor = ref(props.query.actor ?? "");
const action = ref(props.query.actions[0] ?? "");
const targetId = ref(props.query.target_id ?? "");
const from = ref(props.query.from ?? "");
const to = ref(props.query.to ?? "");
watch(() => props.query.actor, (value) => (actor.value = value ?? ""));
watch(() => props.query.actions.join(","), () => (action.value = props.query.actions[0] ?? ""));
watch(() => props.query.target_id, (value) => (targetId.value = value ?? ""));
watch(() => props.query.from, (value) => (from.value = value ?? ""));
watch(() => props.query.to, (value) => (to.value = value ?? ""));
const preset = computed(() =>
props.query.from || props.query.to ? "custom" : props.query.since || "30d",
);
function setPreset(value: unknown) {
if (typeof value !== "string" || value === "custom") return;
emit("change", {
since: value === "30d" ? undefined : value,
from: undefined,
to: undefined,
});
}
function setCategories(value: unknown) {
emit("change", { categories: Array.isArray(value) ? value.map(String) : [] });
}
function setDenied(value: boolean) {
emit("change", { outcome: value ? "denied" : undefined });
}
function commitActor() {
emit("change", { actor: actor.value.trim() || undefined });
}
function commitAction() {
const value = action.value.trim();
emit("change", { actions: value ? [value] : [] });
}
function commitTargetId() {
emit("change", { target_id: targetId.value.trim() || undefined });
}
function commitFrom() {
emit("change", { from: from.value || undefined, since: undefined });
}
function commitTo() {
emit("change", { to: to.value || undefined, since: undefined });
}
const chips = computed(() => filterChips(props.query, props.facets));
const advancedCount = computed(
() =>
props.query.actions.length +
(props.query.actor ? 1 : 0) +
(props.query.severity ? 1 : 0) +
(props.query.target_kind ? 1 : 0) +
(props.query.target_id ? 1 : 0) +
(props.query.from ? 1 : 0) +
(props.query.to ? 1 : 0),
);
function removeChip(chip: AuditChip) {
if (chip.key === "kind") {
emit("change", { kinds: props.query.kinds.filter((kind) => kind !== chip.value) });
return;
}
if (chip.key === "action") {
emit("change", { actions: props.query.actions.filter((entry) => entry !== chip.value) });
return;
}
const patch: Partial<AuditQuery> = {};
patch[chip.key] = undefined;
emit("change", patch);
}
</script>
<template>
<div class="mb-3">
<div class="flex flex-wrap items-center gap-2">
<Input
v-model="search"
type="search"
aria-label="Search events"
placeholder="Search"
class="w-full sm:max-w-56"
/>
<ToggleGroup
v-if="props.facets.categories.length"
type="multiple"
variant="outline"
size="sm"
:model-value="props.query.categories"
aria-label="Categories"
class="max-w-full flex-wrap"
@update:model-value="setCategories"
>
<ToggleGroupItem
v-for="option in props.facets.categories"
:key="option"
:value="option"
>{{ valueLabel(option) }}</ToggleGroupItem>
</ToggleGroup>
<Select :model-value="preset" @update:model-value="setPreset">
<SelectTrigger class="w-36" aria-label="Time range"><SelectValue>{{ presetLabel(props.query) }}</SelectValue></SelectTrigger>
<SelectContent>
<SelectItem value="any">Any time</SelectItem>
<SelectItem value="24h">Last 24 hours</SelectItem>
<SelectItem value="7d">Last 7 days</SelectItem>
<SelectItem value="30d">Last 30 days</SelectItem>
</SelectContent>
</Select>
<Toggle
variant="outline"
size="sm"
:pressed="props.query.outcome === 'denied'"
@update:pressed="setDenied"
>Denied</Toggle>
<Popover v-model:open="advancedOpen">
<PopoverTrigger as-child>
<Button variant="outline" size="sm" aria-label="Filters">
<ListFilter data-icon="inline-start" />Filters<Badge v-if="advancedCount" variant="secondary" class="ml-1">{{ advancedCount }}</Badge>
</Button>
</PopoverTrigger>
<PopoverContent align="start" class="w-96 max-w-[calc(100vw-2rem)]">
<div class="grid gap-3">
<div class="grid gap-1.5">
<Label for="audit-actor">Actor</Label>
<Input id="audit-actor" v-model="actor" @change="commitActor" @keydown.enter="commitActor" />
</div>
<div class="grid gap-1.5">
<Label for="audit-action">Action</Label>
<Input id="audit-action" v-model="action" @change="commitAction" @keydown.enter="commitAction" />
</div>
<div class="grid gap-1.5">
<Label for="audit-severity">Severity</Label>
<Select
:model-value="props.query.severity || 'any'"
@update:model-value="(value) => emit('change', { severity: value === 'any' || !value ? undefined : String(value) })"
>
<SelectTrigger id="audit-severity" class="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="any">Any severity</SelectItem>
<SelectItem v-for="option in props.facets.severities" :key="option" :value="option">{{ valueLabel(option) }}</SelectItem>
</SelectContent>
</Select>
</div>
<div class="grid gap-1.5">
<Label for="audit-target-kind">Target kind</Label>
<Select
:model-value="props.query.target_kind || 'any'"
@update:model-value="(value) => emit('change', { target_kind: value === 'any' || !value ? undefined : String(value) })"
>
<SelectTrigger id="audit-target-kind" class="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="any">Any target kind</SelectItem>
<SelectItem v-for="option in props.facets.target_kinds" :key="option" :value="option">{{ valueLabel(option) }}</SelectItem>
</SelectContent>
</Select>
</div>
<div class="grid gap-1.5">
<Label for="audit-target-id">Target</Label>
<Input id="audit-target-id" v-model="targetId" @change="commitTargetId" @keydown.enter="commitTargetId" />
</div>
<div class="grid grid-cols-2 gap-2">
<div class="grid gap-1.5">
<Label for="audit-from">From</Label>
<Input id="audit-from" v-model="from" type="datetime-local" @change="commitFrom" />
</div>
<div class="grid gap-1.5">
<Label for="audit-to">To</Label>
<Input id="audit-to" v-model="to" type="datetime-local" @change="commitTo" />
</div>
</div>
</div>
</PopoverContent>
</Popover>
</div>
<ul v-if="chips.length" class="mt-2 flex flex-wrap gap-1.5" aria-label="Active filters">
<li v-for="chip in chips" :key="`${chip.key}:${chip.value}`">
<Button
variant="secondary"
size="sm"
:aria-label="`Remove ${chip.text}`"
@click="removeChip(chip)"
>{{ chip.text }}<X data-icon="inline-end" /></Button>
</li>
</ul>
</div>
</template>
+470
View File
@@ -0,0 +1,470 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { useAccountsStore } from "@/accounts/accounts";
import PageHeader from "@/base/PageHeader.vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { Empty, EmptyContent, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { MoreMenu } from "@/components/ui/more-menu";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Section } from "@/components/ui/section";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import { Timestamp } from "@/components/ui/timestamp";
import { useSessionStore } from "@/stores/session";
import { useSettingsStore } from "@/stores/settings";
import AuditDetail from "./AuditDetail.vue";
import AuditExportMenu from "./AuditExportMenu.vue";
import AuditFilters from "./AuditFilters.vue";
import {
apiParams,
badgeFor,
dedupeRecords,
emptyMessage,
hasFilters,
queryFromRoute,
readSavedViews,
recordKey,
routeQueryFor,
targetDetail,
writeSavedViews,
type AuditQuery,
type AuditRecord,
type SavedAuditView,
} from "./audit";
import { useAuditStore } from "./store";
const audit = useAuditStore();
const settings = useSettingsStore();
const session = useSessionStore();
const accounts = useAccountsStore();
const route = useRoute();
const router = useRouter();
const { records, facets, loading, loadingMore, error, moreError, hasMore } = storeToRefs(audit);
const query = computed(() => queryFromRoute(route.query));
const queryKey = computed(() => JSON.stringify(query.value));
const exportParams = computed(() => apiParams(query.value));
const columns: DataTableColumn<AuditRecord>[] = [
{ id: "event", label: "Event", fixed: true, class: "whitespace-normal" },
{ id: "target", label: "Target", fixed: true, class: "hidden sm:table-cell" },
{ id: "actor", label: "Actor", fixed: true, class: "hidden sm:table-cell" },
{ id: "when", label: "When", fixed: true, class: "hidden sm:table-cell" },
];
const status = ref("");
const liveError = ref("");
const pending = ref<AuditRecord[]>([]);
let liveTimer: ReturnType<typeof setTimeout> | undefined;
let liveBusy = false;
let liveAgain = false;
function reload(): void {
void audit.load(query.value);
}
function loadMore(): void {
void audit.loadMore();
}
onMounted(() => {
void settings.load();
if (!accounts.status) void accounts.load();
});
const stopLive = session.subscribe("audit-head", () => {
clearTimeout(liveTimer);
liveTimer = setTimeout(() => void pullLive(), 400);
});
onUnmounted(() => {
clearTimeout(liveTimer);
stopLive();
});
// A head token means something was written. Page one is re-read with the same
// filters; rows the operator has not scrolled past prepend, the rest wait.
async function pullLive(): Promise<void> {
if (liveBusy) {
liveAgain = true;
return;
}
if (loading.value || error.value) return;
liveBusy = true;
try {
const incoming = await audit.refresh();
liveError.value = "";
if (!incoming.length) return;
if (window.scrollY > 80) {
pending.value = dedupeRecords([...incoming, ...pending.value]);
status.value = `${pending.value.length} new ${pending.value.length === 1 ? "event" : "events"}`;
} else {
audit.prepend(incoming);
status.value = `${incoming.length} new ${incoming.length === 1 ? "event" : "events"}`;
}
} catch (err) {
liveError.value = String((err as Error)?.message || err || "Audit could not refresh.");
status.value = "Audit could not refresh.";
} finally {
liveBusy = false;
if (liveAgain) {
liveAgain = false;
void pullLive();
}
}
}
function showPending(): void {
const count = pending.value.length;
if (!count) return;
audit.prepend(pending.value);
pending.value = [];
status.value = `${count} new ${count === 1 ? "event" : "events"}`;
window.scrollTo({ top: 0 });
}
function changeFilters(patch: Partial<AuditQuery>): void {
const next: AuditQuery = { ...query.value, ...patch };
const keys = Object.keys(patch);
const location = { query: routeQueryFor(next), hash: route.hash };
if (keys.length === 1 && keys[0] === "q") void router.replace(location);
else void router.push(location);
}
function clearFilters(): void {
void router.push({ query: {}, hash: route.hash });
}
// Saved views are this browser's, keyed by the signed-in identity.
const views = ref<SavedAuditView[]>([]);
const identityId = computed(() => accounts.status?.user?.id ?? "");
watch(identityId, (id) => (views.value = readSavedViews(id)), { immediate: true });
const activeView = computed(() => {
const current = queryKey.value;
return views.value.find((view) => JSON.stringify(queryFromRoute(view.query)) === current) ?? null;
});
const ALL_VIEWS = "__all";
const selectedView = computed(() => activeView.value?.name ?? ALL_VIEWS);
function selectView(value: unknown): void {
if (typeof value !== "string") return;
if (value === ALL_VIEWS) {
clearFilters();
return;
}
const view = views.value.find((entry) => entry.name === value);
if (view) void router.push({ query: view.query, hash: route.hash });
}
const saveOpen = ref(false);
const viewName = ref("");
function openSaveView(): void {
viewName.value = activeView.value?.name ?? "";
saveOpen.value = true;
}
function saveView(): void {
const name = viewName.value.trim();
if (!name || !identityId.value) return;
views.value = [
...views.value.filter((view) => view.name !== name),
{ name, query: routeQueryFor(query.value) },
].sort((a, b) => a.name.localeCompare(b.name));
writeSavedViews(identityId.value, views.value);
saveOpen.value = false;
}
function deleteView(): void {
const view = activeView.value;
if (!view || !identityId.value) return;
views.value = views.value.filter((entry) => entry.name !== view.name);
writeSavedViews(identityId.value, views.value);
}
// Revert restores the revision before the audited write. The settings store
// owns the draft, so the existing review sheet and save path do the write.
const revertOpen = ref(false);
const revertTarget = ref<{ record: AuditRecord; kind: string } | null>(null);
const revertError = ref("");
const reverting = ref(false);
watch(
queryKey,
() => {
pending.value = [];
revertError.value = "";
void audit.load(query.value);
},
{ immediate: true },
);
function resourceKind(record: AuditRecord): string {
const kind = record.target?.id;
if (!kind) return "";
return settings.genericResources.some((resource) => resource.kind === kind) ? kind : "";
}
function canRevert(record: AuditRecord): boolean {
return (record.detail?.version ?? 0) > 1 && !!resourceKind(record);
}
const revertUnsaved = computed(() => {
const target = revertTarget.value;
return !!target && settings.changesFor(target.kind).length > 0;
});
function askRevert(record: AuditRecord): void {
const kind = resourceKind(record);
if (!kind) return;
revertError.value = "";
revertTarget.value = { record, kind };
revertOpen.value = true;
}
async function confirmRevert(): Promise<void> {
const target = revertTarget.value;
if (!target || reverting.value) return;
const version = target.record.detail?.version ?? 0;
reverting.value = true;
revertError.value = "";
try {
await settings.loadResource(target.kind);
if (!settings.stateFor(target.kind).resource) {
revertError.value = "That resource could not be loaded.";
return;
}
const previous = (await settings.history(target.kind)).find(
(revision) => revision.version === version - 1,
);
if (!previous) {
revertError.value = "That earlier version is no longer available.";
return;
}
settings.stageRestore(target.kind, previous.value);
} catch (err) {
revertError.value = String((err as Error)?.message || err);
} finally {
reverting.value = false;
revertTarget.value = null;
}
}
// Retention is one instance-only control-plane resource, saved through the
// same versioned replace the settings pages use.
const RETENTION_KIND = "audit-retention";
const retentionOpen = ref(false);
const retentionHours = ref("0");
const retentionError = ref("");
const retentionSaving = ref(false);
const retentionState = settings.stateFor(RETENTION_KIND);
function hoursFrom(value: unknown): number {
if (typeof value === "number") return value;
if (typeof value !== "string") return 0;
const match = value.match(/^(\d+(?:\.\d+)?)h$/);
return match ? Number(match[1]) : 0;
}
async function openRetention(): Promise<void> {
retentionOpen.value = true;
retentionError.value = "";
await settings.loadResource(RETENTION_KIND);
const resource = retentionState.resource;
if (resource) {
const value = resource.value as { runtime_event_retention?: unknown } | undefined;
retentionHours.value = String(hoursFrom(value?.runtime_event_retention));
}
}
async function saveRetention(): Promise<void> {
if (retentionSaving.value) return;
const hours = Number(retentionHours.value);
if (!Number.isFinite(hours) || hours < 0) {
retentionError.value = "Enter a number of hours.";
return;
}
const state = retentionState;
if (!state.resource) {
retentionError.value = "Retention settings are unavailable.";
return;
}
retentionSaving.value = true;
retentionError.value = "";
const saved = await settings.replace(
RETENTION_KIND,
{ runtime_event_retention: `${hours}h` },
state.resource.version,
);
retentionSaving.value = false;
if (saved) retentionOpen.value = false;
else retentionError.value = state.error || "Retention could not be saved.";
}
</script>
<template>
<div>
<PageHeader title="Audit">
<Select v-if="views.length" :model-value="selectedView" @update:model-value="selectView">
<SelectTrigger class="w-40" aria-label="Saved view"><SelectValue>{{ activeView?.name || "All events" }}</SelectValue></SelectTrigger>
<SelectContent>
<SelectItem :value="ALL_VIEWS">All events</SelectItem>
<SelectItem v-for="view in views" :key="view.name" :value="view.name">{{ view.name }}</SelectItem>
</SelectContent>
</Select>
<AuditExportMenu :params="exportParams" />
<MoreMenu label="Audit actions">
<DropdownMenuItem :disabled="!identityId" @click="openSaveView">Save view…</DropdownMenuItem>
<DropdownMenuItem v-if="activeView" variant="destructive" @click="deleteView">Delete view</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem @click="openRetention">Retention</DropdownMenuItem>
</MoreMenu>
</PageHeader>
<AuditFilters :query="query" :facets="facets" @change="changeFilters" />
<p v-if="revertError" class="mb-3 text-sm text-danger" role="alert">{{ revertError }}</p>
<p v-if="liveError" class="mb-3 text-sm text-danger" role="alert">{{ liveError }}</p>
<div class="relative">
<div v-if="pending.length" class="sticky top-2 z-20 mb-2 flex justify-center">
<Button size="sm" @click="showPending">{{ pending.length }} new {{ pending.length === 1 ? "event" : "events" }}</Button>
</div>
<div v-if="loading" class="space-y-2" role="status" aria-label="Loading audit">
<Skeleton v-for="n in 6" :key="n" class="h-10 w-full" />
</div>
<div v-else-if="error" class="rounded-xl border border-border bg-card p-6" role="alert">
<p class="text-sm text-danger">{{ error }}</p>
<Button class="mt-3" variant="outline" size="sm" @click="reload">Retry</Button>
</div>
<Section v-else>
<DataTable :key="queryKey" :columns="columns" :rows="records" :row-key="recordKey" storage-key="audit">
<template #cell-event="{ row }">
<div class="min-w-0">
<div class="flex flex-wrap items-start gap-2">
<span class="min-w-0 break-words">{{ row.summary || `${row.category} ${row.action}` }}</span>
<Badge v-if="badgeFor(row)" :variant="badgeFor(row)!.variant">{{ badgeFor(row)!.label }}</Badge>
</div>
<p class="mt-0.5 text-xs text-fg-subtle sm:hidden">
<RouterLink v-if="row.target?.href" :to="row.target.href" class="hover:underline" @click.stop>{{ row.target.label || row.target.id }}</RouterLink>
<span v-else>{{ row.target?.label || row.target?.id }}</span>
·
<span>{{ row.actor.name || row.actor.id }}</span>
·
<Timestamp :at="row.at" />
</p>
</div>
</template>
<template #cell-target="{ row }">
<RouterLink v-if="row.target?.href" :to="row.target.href" class="hover:underline" @click.stop>{{ row.target.label || row.target.id }}</RouterLink>
<span v-else>{{ row.target?.label || row.target?.id }}</span>
<span class="block text-xs text-fg-subtle">{{ targetDetail(row.target) }}</span>
</template>
<template #cell-actor="{ row }">
<span>{{ row.actor.name || row.actor.id }}</span>
<span class="block text-xs text-fg-subtle">{{ row.actor.kind }}</span>
</template>
<template #cell-when="{ row }"><Timestamp :at="row.at" /></template>
<template #detail="{ row }">
<AuditDetail :record="row" :can-revert="canRevert(row)" @revert="askRevert(row)" />
</template>
<template #empty>
<Empty>
<EmptyHeader>
<EmptyTitle>{{ emptyMessage(query) }}</EmptyTitle>
</EmptyHeader>
<EmptyContent v-if="hasFilters(query)">
<Button variant="outline" size="sm" @click="clearFilters">Clear filters</Button>
</EmptyContent>
</Empty>
</template>
</DataTable>
<div v-if="hasMore" class="mt-3 flex justify-center">
<Button variant="outline" size="sm" :disabled="loadingMore" @click="loadMore"><Spinner v-if="loadingMore" data-icon="inline-start" />Load older</Button>
</div>
<p v-if="moreError" class="mt-2 text-sm text-danger" role="alert">{{ moreError }}</p>
</Section>
</div>
<p class="sr-only" role="status">{{ status }}</p>
<AlertDialog :open="revertOpen" @update:open="(open) => (revertOpen = open)">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Revert this change?</AlertDialogTitle>
<AlertDialogDescription v-if="revertUnsaved">Unsaved changes to this resource will be replaced.</AlertDialogDescription>
<AlertDialogDescription v-else>The previous version opens for review before saving.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction :disabled="reverting" @click="confirmRevert">Revert</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Dialog v-model:open="saveOpen">
<DialogContent>
<DialogHeader>
<DialogTitle>Save view</DialogTitle>
</DialogHeader>
<div class="grid gap-1.5">
<Label for="audit-view-name">Name</Label>
<Input id="audit-view-name" v-model="viewName" @keydown.enter="saveView" />
</div>
<DialogFooter>
<Button variant="ghost" @click="saveOpen = false">Cancel</Button>
<Button :disabled="!viewName.trim() || !identityId" @click="saveView">Save</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog v-model:open="retentionOpen">
<DialogContent>
<DialogHeader>
<DialogTitle>Audit retention</DialogTitle>
<DialogDescription>Older runtime events are deleted hourly. Settings, access and identity records are kept.</DialogDescription>
</DialogHeader>
<div class="grid gap-1.5">
<Label for="audit-retention-hours">Runtime event retention (hours)</Label>
<Input id="audit-retention-hours" v-model="retentionHours" type="number" min="0" step="1" class="w-32" />
<p class="text-xs text-fg-subtle">0 keeps them forever.</p>
</div>
<p v-if="retentionError || retentionState.error" class="text-sm text-danger" role="alert">{{ retentionError || retentionState.error }}</p>
<DialogFooter>
<Button variant="ghost" @click="retentionOpen = false">Cancel</Button>
<Button :disabled="retentionSaving || retentionState.loading || !retentionState.resource" @click="saveRetention"><Spinner v-if="retentionSaving" data-icon="inline-start" />Save</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</template>
+442
View File
@@ -0,0 +1,442 @@
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.
}
}
+142
View File
@@ -0,0 +1,142 @@
import { defineStore } from "pinia";
import { ref } from "vue";
import { ApiError, api, type QueryParams } from "@/lib/api";
import {
apiParams,
dedupeRecords,
emptyFacets,
recordKey,
type AuditFacets,
type AuditQuery,
type AuditRecord,
type AuditResponse,
} from "./audit";
const PAGE_SIZE = 100;
function failure(err: unknown): string {
if (err instanceof ApiError && err.status === 503) return "Audit is unavailable.";
const message = err instanceof Error && err.message ? err.message : String(err);
return message || "Audit could not be loaded.";
}
/** The server's vocabularies arrive with the first page; a later page that
* omits one must not blank the filters the operator is using. */
function facetsFrom(next: AuditFacets | undefined, current: AuditFacets): AuditFacets {
if (!next) return current;
const pick = <T,>(incoming: T[] | undefined, previous: T[]): T[] =>
incoming?.length ? incoming : previous;
return {
categories: pick(next.categories, current.categories),
severities: pick(next.severities, current.severities),
outcomes: pick(next.outcomes, current.outcomes),
target_kinds: pick(next.target_kinds, current.target_kinds),
settings_kinds: pick(next.settings_kinds, current.settings_kinds),
};
}
/** One loaded audit feed. Filters live in the URL; this store owns only the
* pages fetched for the current filter. */
export const useAuditStore = defineStore("audit", () => {
const records = ref<AuditRecord[]>([]);
const facets = ref<AuditFacets>(emptyFacets());
const loading = ref(false);
const loadingMore = ref(false);
const error = ref("");
const moreError = ref("");
const nextCursor = ref<string | null>(null);
const hasMore = ref(false);
let generation = 0;
let pages = 1;
// Resolved once per filter load: the cursor is bound to these exact bounds.
let params: QueryParams = {};
async function load(query: AuditQuery): Promise<void> {
const token = ++generation;
params = apiParams(query);
loading.value = true;
loadingMore.value = false;
error.value = "";
moreError.value = "";
records.value = [];
nextCursor.value = null;
hasMore.value = false;
pages = 1;
try {
const response = await api.audit<AuditResponse>({ ...params, limit: PAGE_SIZE });
if (token !== generation) return;
records.value = dedupeRecords(response.records ?? []);
facets.value = facetsFrom(response.facets, facets.value);
nextCursor.value = response.next_cursor || null;
hasMore.value = !!response.has_more;
} catch (err) {
if (token !== generation) return;
error.value = failure(err);
} finally {
if (token === generation) loading.value = false;
}
}
async function loadMore(): Promise<void> {
if (!nextCursor.value || loading.value || loadingMore.value) return;
const token = generation;
loadingMore.value = true;
moreError.value = "";
try {
const response = await api.audit<AuditResponse>({
...params,
cursor: nextCursor.value,
limit: PAGE_SIZE,
});
if (token !== generation) return;
records.value = dedupeRecords([...records.value, ...(response.records ?? [])]);
nextCursor.value = response.next_cursor || null;
hasMore.value = !!response.has_more;
pages += 1;
} catch (err) {
if (token === generation) moreError.value = failure(err);
} finally {
if (token === generation) loadingMore.value = false;
}
}
/** Re-reads page one after a live head. Returns the records this page did
* not already hold; the page decides whether to prepend or hold them. */
async function refresh(): Promise<AuditRecord[]> {
if (loading.value || error.value) return [];
const token = generation;
const response = await api.audit<AuditResponse>({ ...params, limit: PAGE_SIZE });
if (token !== generation) return [];
facets.value = facetsFrom(response.facets, facets.value);
// Only a single-page feed can take the new page-one cursor: a loaded older
// page is keyed to the cursor the operator is paging from.
if (pages === 1) {
nextCursor.value = response.next_cursor || null;
hasMore.value = !!response.has_more;
}
const known = new Set(records.value.map(recordKey));
return dedupeRecords(response.records ?? []).filter((record) => !known.has(recordKey(record)));
}
function prepend(incoming: AuditRecord[]): void {
if (!incoming.length) return;
records.value = dedupeRecords([...incoming, ...records.value]);
}
return {
records,
facets,
loading,
loadingMore,
error,
moreError,
nextCursor,
hasMore,
load,
loadMore,
refresh,
prepend,
};
});
+7 -3
View File
@@ -5,8 +5,12 @@ import { Button } from "@/components/ui/button";
import { formatValue, type Change } from "@/lib/changes";
/** One row per changed leaf, each revertable on its own, so a reviewer keeps
* the changes they want and drops the rest before saving. */
defineProps<{ changes: Change[]; label?: (path: string) => string }>();
* the changes they want and drops the rest before saving. A read-only diff
* passes `revertable: false`. */
withDefaults(
defineProps<{ changes: Change[]; label?: (path: string) => string; revertable?: boolean }>(),
{ revertable: true },
);
defineEmits<{ revert: [change: Change] }>();
</script>
@@ -18,7 +22,7 @@ defineEmits<{ revert: [change: Change] }>();
<p class="whitespace-pre-wrap break-words text-danger"><span class="font-sans">Before: </span>{{ formatValue(change.before) }}</p>
<p class="whitespace-pre-wrap break-words text-ok"><span class="font-sans">After: </span>{{ formatValue(change.after) }}</p>
</div>
<Button variant="ghost" size="icon-sm" :aria-label="`Revert ${label ? label(change.path) : change.path}`" title="Revert" @click="$emit('revert', change)">
<Button v-if="revertable" variant="ghost" size="icon-sm" :aria-label="`Revert ${label ? label(change.path) : change.path}`" title="Revert" @click="$emit('revert', change)">
<Undo2 />
</Button>
</li>
+23 -3
View File
@@ -11,8 +11,16 @@ import { randomUUID } from "./uuid.ts";
// The retry affordances rely on fetch settling, so bound it.
const DEFAULT_TIMEOUT_MS = 15000;
/** Query values are omitted when empty, so the server sees an absent filter. */
export type QueryParams = Record<string, string | number | null | undefined>;
/** Query values are omitted when empty, so the server sees an absent filter.
* An array becomes a repeated parameter, as filters like `categories` expect. */
export type QueryValue =
| string
| number
| boolean
| readonly (string | number)[]
| null
| undefined;
export type QueryParams = Record<string, QueryValue>;
/** Opaque payloads are passed through unchanged; the server owns their shape. */
export type Payload = Record<string, unknown>;
@@ -22,7 +30,14 @@ export type Payload = Record<string, unknown>;
function qs(params?: QueryParams): string {
const q = new URLSearchParams();
for (const [k, v] of Object.entries(params || {})) {
if (v !== "" && v != null) q.set(k, String(v));
if (v === "" || v == null) continue;
if (Array.isArray(v)) {
for (const item of v) {
if (item !== "" && item != null) q.append(k, String(item));
}
} else {
q.set(k, String(v));
}
}
const s = q.toString();
return s ? `?${s}` : "";
@@ -287,6 +302,11 @@ export const api = {
body: {},
}),
config: <T = unknown>() => request<T>("/api/config"),
// The audit feed is filtered and paginated on the server; export is a
// browser navigation, so its URL is built here beside the request.
audit: <T = unknown>(params: QueryParams = {}) => request<T>("/api/audit" + qs(params)),
auditExportURL: (format: "csv" | "json", params: QueryParams = {}) =>
"/api/audit/export" + qs({ ...params, format }),
logs: <T = unknown>(params?: QueryParams) =>
request<T>("/api/logs" + qs(params)),
taskLogs: <T = unknown>(id: string, params?: QueryParams) =>
+1 -1
View File
@@ -82,7 +82,7 @@ const settings: NavSpec = {
"/settings/status",
],
},
{ paths: ["/settings/authentication", "/settings/appearance", "/settings/history"] },
{ paths: ["/settings/authentication", "/settings/appearance", "/settings/audit"] },
],
};
+8 -7
View File
@@ -1,10 +1,11 @@
import { createRouter, createWebHistory } from "vue-router";
import { createRouter, createWebHistory, type RouteLocationGeneric } from "vue-router";
import ChannelsPage from "@/channels/ChannelsPage.vue";
import CuratorsPage from "@/curators/CuratorsPage.vue";
import DashboardPage from "@/dashboard/DashboardPage.vue";
import EventsPage from "@/events/EventsPage.vue";
import LogsPage from "@/logs/LogsPage.vue";
import AuditPage from "@/audit/AuditPage.vue";
import OrgShell from "@/org/OrgShell.vue";
import OrgOverviewPage from "@/org/OrgOverviewPage.vue";
import OrgMembersPage from "@/org/OrgMembersPage.vue";
@@ -14,7 +15,6 @@ import OrgAccessPage from "@/org/OrgAccessPage.vue";
import OrgModelsPage from "@/org/OrgModelsPage.vue";
import SchedulingPolicyPage from "@/settings/SchedulingPolicyPage.vue";
import ToolsPage from "@/settings/ToolsPage.vue";
import HistoryPage from "@/settings/HistoryPage.vue";
import InstructionsPage from "@/settings/InstructionsPage.vue";
import SchedulesPage from "@/settings/SchedulesPage.vue";
import ExtensionsPage from "@/settings/ExtensionsPage.vue";
@@ -383,17 +383,18 @@ const routes = [
},
},
{
path: "/settings/history",
name: "settings-history",
component: HistoryPage,
path: "/settings/audit",
name: "audit",
component: AuditPage,
meta: {
navPath: "/settings",
settings: true,
label: "History",
description: "Settings changes: who, when, previous value.",
label: "Audit",
description: "Settings, access, identity and runtime events.",
section: "settings",
},
},
{ path: "/settings/history", redirect: (to: RouteLocationGeneric) => ({ path: "/settings/audit", query: to.query, hash: to.hash }), meta: { nav: false } },
{
path: "/settings",
redirect: "/settings/status",
+3 -3
View File
@@ -3,13 +3,13 @@ import { History } from "@lucide/vue";
import { Button } from "@/components/ui/button";
/** Opens Settings > History filtered to these resource kinds. */
/** Opens Settings > Audit filtered to these resource kinds. */
const props = defineProps<{ kinds: string[] }>();
</script>
<template>
<Button variant="ghost" size="sm" as-child>
<RouterLink :to="{ path: '/settings/history', query: { section: props.kinds.join(',') } }">
<History data-icon="inline-start" /> History</RouterLink>
<RouterLink :to="{ path: '/settings/audit', query: { section: props.kinds.join(',') } }">
<History data-icon="inline-start" /> Audit</RouterLink>
</Button>
</template>
-207
View File
@@ -1,207 +0,0 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import { Section } from "@/components/ui/section";
import { Timestamp } from "@/components/ui/timestamp";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useSettingsStore, type AuditEntry } from "@/stores/settings";
import { formatValue } from "@/lib/changes";
import { filterHistory, historyEmptyTitle } from "./history";
/**
* Every settings change, one row per changed field, newest first. Restore
* stages the version before a change as a draft; applying it from the save
* bar is an ordinary replace, so the restore is itself recorded here.
*/
const store = useSettingsStore();
const { catalog } = storeToRefs(store);
const route = useRoute();
const router = useRouter();
const entries = ref<AuditEntry[]>([]);
const error = ref("");
const restoreError = ref("");
const expanded = ref<number | null>(null);
const titles = computed(() => new Map(catalog.value.map((r) => [r.kind, r.title])));
const kinds = computed(() => catalog.value.map((r) => r.kind));
async function load(): Promise<void> {
if (!kinds.value.length) return;
try {
entries.value = await store.audit(kinds.value);
error.value = "";
} catch (err) {
error.value = String((err as Error).message || err);
}
}
onMounted(store.load);
// Any stored version moving means a save happened somewhere: re-read.
const versions = computed(() =>
kinds.value.map((kind) => store.stateFor(kind).resource?.version).join(","),
);
watch([kinds, versions], load, { immediate: true });
// Filters live in the query, so every History link elsewhere is a deep link.
const ALL = "all";
const section = computed({
get: () => (route.query.section as string) || ALL,
set: (value: string) => setQuery({ section: value === ALL ? undefined : value }),
});
const actor = computed({
get: () => (route.query.actor as string) || ALL,
set: (value: string) => setQuery({ actor: value === ALL ? undefined : value }),
});
const since = computed({
get: () => (route.query.since as string) || ALL,
set: (value: string) => setQuery({ since: value === ALL ? undefined : value }),
});
function setQuery(patch: Record<string, string | undefined>) {
void router.replace({ query: { ...route.query, ...patch } });
}
const windows: Record<string, number> = { "24h": 86_400_000, "7d": 604_800_000, "30d": 2_592_000_000 };
const actorName = (id: string) => entries.value.find((entry) => entry.actor === id)?.actor_name || id;
const actors = computed(() => [...new Set(entries.value.map((e) => e.actor))].sort());
const sectionOptions = computed(() => {
const options = catalog.value.map((r) => ({ value: r.kind, label: r.title }));
// A deep link may name several kinds (a page that shows more than one).
if (section.value !== ALL && !options.some((o) => o.value === section.value))
options.unshift({
value: section.value,
label: section.value.split(",").map((k) => titles.value.get(k) ?? k).join(" + "),
});
return options;
});
const rows = computed(() =>
filterHistory(
entries.value,
{
kinds: section.value === ALL ? [] : section.value.split(","),
actor: actor.value === ALL ? undefined : actor.value,
sinceMs: windows[since.value],
},
Date.now(),
),
);
async function restoreBefore(entry: AuditEntry): Promise<void> {
const previous = (await store.history(entry.record_key)).find(
(revision) => revision.version === entry.version - 1,
);
if (!previous) {
restoreError.value = "That earlier version is no longer available.";
return;
}
restoreError.value = "";
store.stageRestore(entry.record_key, previous.value);
}
const restorable = (entry: AuditEntry) =>
entry.version > 1 && store.genericResources.some((r) => r.kind === entry.record_key);
</script>
<template>
<div>
<PageHeader title="History" />
<div class="mb-4 flex flex-wrap gap-2">
<Select v-model="section">
<SelectTrigger class="w-60" aria-label="Section">
<SelectValue>{{ section === ALL ? "All sections" : sectionOptions.find((o) => o.value === section)?.label ?? section }}</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem :value="ALL">All sections</SelectItem>
<SelectItem v-for="o in sectionOptions" :key="o.value" :value="o.value">{{ o.label }}</SelectItem>
</SelectContent>
</Select>
<Select v-model="actor">
<SelectTrigger class="w-48" aria-label="Changed by"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem :value="ALL">Anyone</SelectItem>
<SelectItem v-for="a in actors" :key="a" :value="a">{{ actorName(a) }}</SelectItem>
</SelectContent>
</Select>
<Select v-model="since">
<SelectTrigger class="w-40" aria-label="When"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem :value="ALL">Any time</SelectItem>
<SelectItem value="24h">Last 24 hours</SelectItem>
<SelectItem value="7d">Last 7 days</SelectItem>
<SelectItem value="30d">Last 30 days</SelectItem>
</SelectContent>
</Select>
</div>
<p v-if="restoreError" class="mb-2 text-sm text-danger" role="alert">{{ restoreError }}</p>
<p v-if="error" class="text-sm text-danger" role="alert">{{ error }}</p>
<Section v-else>
<Table class="table-fixed">
<TableHeader>
<TableRow>
<TableHead class="w-20">When</TableHead>
<TableHead class="w-36">Section</TableHead>
<TableHead class="w-24">Field</TableHead>
<TableHead>Change</TableHead>
<TableHead class="w-14">Version</TableHead>
<TableHead class="w-32">Changed by</TableHead>
<TableHead class="w-20"><span class="sr-only">Actions</span></TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="entry in rows" :key="entry.id" class="align-top">
<TableCell class="text-fg-muted"><Timestamp :at="entry.at" /></TableCell>
<TableCell class="truncate">{{ titles.get(entry.record_key) ?? entry.record_key }}</TableCell>
<TableCell class="truncate font-mono text-xs" :title="entry.field">{{ entry.field || "whole value" }}</TableCell>
<TableCell class="font-mono text-xs whitespace-normal">
<button
type="button"
class="block w-full min-w-0 text-left"
:aria-expanded="expanded === entry.id"
@click="expanded = expanded === entry.id ? null : entry.id"
>
<span :class="expanded === entry.id ? 'break-all' : 'truncate'" class="block text-danger">− {{ formatValue(entry.old_value ?? undefined) }}</span>
<span :class="expanded === entry.id ? 'break-all' : 'truncate'" class="block text-ok">+ {{ formatValue(entry.new_value ?? undefined) }}</span>
</button>
</TableCell>
<TableCell class="font-mono text-xs">{{ entry.version }}</TableCell>
<TableCell class="truncate" :title="`${entry.actor} · ${entry.source}`">
{{ entry.actor_name || entry.actor }}<span class="text-fg-subtle"> · {{ entry.source }}</span>
</TableCell>
<TableCell class="py-1 text-right">
<Button
v-if="restorable(entry)"
variant="ghost"
size="sm"
:disabled="store.stateFor(entry.record_key).saving"
@click="restoreBefore(entry)"
>Restore</Button
>
</TableCell>
</TableRow>
<TableRow v-if="!rows.length">
<TableCell colspan="7">
<Empty>
<EmptyHeader>
<EmptyTitle>{{ historyEmptyTitle(entries.length > 0) }}</EmptyTitle>
</EmptyHeader>
</Empty>
</TableCell>
</TableRow>
</TableBody>
</Table>
</Section>
</div>
</template>
-39
View File
@@ -1,39 +0,0 @@
interface HistoryEntry {
record_key: string;
actor: string;
at?: string;
}
export interface HistoryFilter {
/** Resource kinds to keep; empty or absent keeps every kind. */
kinds?: string[];
actor?: string;
/** Keep entries newer than this many milliseconds before now. */
sinceMs?: number;
}
/**
* historyEmptyTitle is what the history table's nothing-to-show row says: a
* history with entries whose filters match nothing asks the reader to change
* the filters, while a history with nothing recorded at all says so.
*/
export function historyEmptyTitle(entriesRecorded: boolean): string {
return entriesRecorded ? "No matching changes." : "No changes recorded yet.";
}
/** filterHistory keeps the audit entries that match every filter set. */
export function filterHistory<T extends HistoryEntry>(
entries: T[],
filter: HistoryFilter,
now: number,
): T[] {
return entries.filter((entry) => {
if (filter.kinds?.length && !filter.kinds.includes(entry.record_key)) return false;
if (filter.actor && entry.actor !== filter.actor) return false;
if (filter.sinceMs !== undefined) {
if (!entry.at) return false;
if (now - Date.parse(entry.at) > filter.sinceMs) return false;
}
return true;
});
}
+1 -25
View File
@@ -120,21 +120,7 @@ export interface ResourceRevision {
at?: string;
}
/** One changed field of one record, as sys_audit holds it. */
export interface AuditEntry {
id: number;
table: string;
record_key: string;
field: string;
old_value: unknown;
new_value: unknown;
version: number;
actor: string;
actor_name?: string;
source: string;
at?: string;
}
/** The revisions the resource history endpoint returns. */
interface HistoryResponse {
revisions?: ResourceRevision[];
}
@@ -478,15 +464,6 @@ export const useSettingsStore = defineStore("settings", () => {
return response.revisions ?? [];
}
async function audit(kinds: string[]): Promise<AuditEntry[]> {
const query = new URLSearchParams();
for (const kind of kinds) query.append("kind", kind);
const response = await request<{ entries?: AuditEntry[] }>(
`/api/control-plane/audit?${query}`,
);
return response.entries ?? [];
}
/** Services the credential bindings define, which identity grants choose from. */
const credentialServices = computed(() => {
const bindings = (drafts["credential-bindings"]?.value ?? []) as { service: string }[];
@@ -512,7 +489,6 @@ export const useSettingsStore = defineStore("settings", () => {
catalog,
catalogError,
genericResources,
audit,
history,
load,
loadResource,