@frigear-nu/audit-log 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +28 -2
  2. package/dist/module.d.mts +122 -0
  3. package/dist/module.json +9 -0
  4. package/dist/module.mjs +96 -0
  5. package/dist/runtime/access.d.ts +1 -0
  6. package/dist/runtime/access.js +17 -0
  7. package/dist/runtime/app/pages/admin.d.vue.ts +3 -0
  8. package/dist/runtime/app/pages/admin.vue +285 -0
  9. package/dist/runtime/app/pages/admin.vue.d.ts +3 -0
  10. package/dist/runtime/app/widgets/RecentActivity.d.vue.ts +6 -0
  11. package/dist/runtime/app/widgets/RecentActivity.vue +73 -0
  12. package/dist/runtime/app/widgets/RecentActivity.vue.d.ts +6 -0
  13. package/dist/runtime/i18n/lang/da.json +80 -0
  14. package/dist/runtime/i18n/lang/en.json +80 -0
  15. package/dist/runtime/menus/admin.d.ts +2 -0
  16. package/dist/runtime/menus/admin.js +18 -0
  17. package/dist/runtime/server/db/schema.postgresql.d.ts +179 -0
  18. package/dist/runtime/server/db/schema.postgresql.js +26 -0
  19. package/dist/runtime/server/db/schema.sqlite.d.ts +195 -0
  20. package/dist/runtime/server/db/schema.sqlite.js +26 -0
  21. package/dist/runtime/server/routes/admin/audit.get.d.ts +2 -0
  22. package/dist/runtime/server/routes/admin/audit.get.js +21 -0
  23. package/dist/runtime/server/routes/admin/export.get.d.ts +2 -0
  24. package/dist/runtime/server/routes/admin/export.get.js +48 -0
  25. package/dist/runtime/server/routes/admin/modules.get.d.ts +2 -0
  26. package/dist/runtime/server/routes/admin/modules.get.js +8 -0
  27. package/dist/runtime/server/tasks/prune.d.ts +2 -0
  28. package/dist/runtime/server/tasks/prune.js +10 -0
  29. package/dist/runtime/server/utils/audit-schemas.d.ts +68 -0
  30. package/dist/runtime/server/utils/audit-schemas.js +30 -0
  31. package/dist/runtime/server/utils/audit.d.ts +48 -0
  32. package/dist/runtime/server/utils/audit.js +110 -0
  33. package/dist/runtime/utils/api.d.ts +13 -0
  34. package/dist/runtime/utils/api.js +14 -0
  35. package/dist/runtime/utils/index.d.ts +1 -0
  36. package/dist/runtime/utils/index.js +1 -0
  37. package/dist/runtime/utils/kinds.d.ts +21 -0
  38. package/dist/runtime/utils/kinds.js +16 -0
  39. package/dist/types.d.mts +3 -0
  40. package/package.json +97 -3
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # @frigear-nu/audit-log
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An append-only audit log. Modules record who downloaded, changed or reached what with one server call, and staff
4
+ review the log at `/admin/audit-log` and download it as CSV.
5
+
6
+ - **Recording** (server, auto-imported): `recordAudit(event, { action, kind, module, target?, data? })` reads the actor
7
+ and how they called (session, API token, OAuth) from the request; `recordSystemAudit({...})` is for tasks and
8
+ webhooks; `recordDownload(event, { action, module, format, rowCount, filters })` is what every download calls. A
9
+ failed write is logged and never fails the request. Each entry fires the `audit:recorded` Nitro hook.
10
+ - **Viewer** (`/admin/audit-log`, with `@frigear-nu/admin`, in the Settings group): filter by kind (Downloads first),
11
+ module, period and search, open an entry in a slideover. `audit:pii`, granted to `admin`.
12
+ - **Export**: the entries the filters match as CSV (formula-safe cells), itself recorded as `audit.exported`.
13
+ `audit-export:pii`, granted to `admin`.
14
+ - **Retention**: unset keeps every entry; `retentionDays` adds the nightly `audit:prune` task.
15
+
16
+ Both permissions are sensitive: `*` never covers them, so a host that gives its admins `*` grants them by name.
17
+
18
+ ## Quick Setup
19
+
20
+ ```ts
21
+ export default defineNuxtConfig({
22
+ modules: ['@nuxthub/core', '@frigear-nu/admin', '@frigear-nu/audit-log'],
23
+ auditLog: { retentionDays: 730 },
24
+ })
25
+ ```
26
+
27
+ Generate and commit a migration for the `audit_log` table in your app (see the repository `AGENTS.md`).
28
+
29
+ Docs: [docs.frigear.dev/modules/platform/audit-log](https://docs.frigear.dev/modules/platform/audit-log).
@@ -0,0 +1,122 @@
1
+ import * as _nuxt_schema from '@nuxt/schema';
2
+
3
+ /** What kind of action an entry records; `download` is what the viewer's "Downloads" filter shows. */
4
+ type AuditKind = 'download' | 'change' | 'access' | 'security' | 'other';
5
+ /**
6
+ * How the actor called: a cookie session, an API token, an OAuth access token, the system (a task or a webhook, through
7
+ * `recordSystemAudit`), or a request nobody signed in to.
8
+ */
9
+ type AuditCredential = 'session' | 'token' | 'oauth' | 'system' | 'anonymous';
10
+ /** A JSON value of an entry's `data`. */
11
+ type AuditData = Record<string, unknown>;
12
+ /** The record an action was done to. */
13
+ interface AuditTarget {
14
+ /** The kind of record, such as `subscription-plan` or `document`. */
15
+ type: string;
16
+ /** Its id, as text. */
17
+ id: string | number;
18
+ }
19
+ /** What `recordAudit` and `recordSystemAudit` take. */
20
+ interface AuditEntryInput {
21
+ /** What happened, as `<module>.<thing>.<verb>`: `subscriptions.members.exported`. Its label is `audit.actions.<action>`. */
22
+ action: string;
23
+ kind: AuditKind;
24
+ /** The module that records it: `subscriptions`. */
25
+ module: string;
26
+ target?: AuditTarget | null;
27
+ /** Filters, a row count, a format. Never free-text search terms or personal data: the log keeps it for good. */
28
+ data?: AuditData | null;
29
+ /**
30
+ * The actor, when the request's own caller is not it (a sign-in, before the session exists). Left out, it is the
31
+ * caller of the request.
32
+ */
33
+ actorId?: string | number | null;
34
+ }
35
+ /** What `recordDownload` takes: the same for every download, so the log reads them alike. */
36
+ interface AuditDownloadInput {
37
+ /** `subscriptions.members.exported`. */
38
+ action: string;
39
+ module: string;
40
+ /** `csv`, `xlsx`, `pdf`, `json`, ... */
41
+ format: string;
42
+ /** How many rows (or files) went out. */
43
+ rowCount: number;
44
+ /** The filters the export applied, by key. Leave free-text search out: `searched: true` says one was used. */
45
+ filters?: Record<string, unknown>;
46
+ target?: AuditTarget | null;
47
+ /** Anything else worth keeping, under the same rule as `data`. */
48
+ data?: AuditData | null;
49
+ }
50
+ /** The `audit:recorded` Nitro hook's context: the entry as stored. */
51
+ interface AuditRecordedContext {
52
+ entry: AuditEntryDto;
53
+ }
54
+ /** The actor of an entry, as the log shows them. */
55
+ interface AuditActorDto {
56
+ id: number;
57
+ name: string | null;
58
+ }
59
+ /** One entry of the log, as `audit:pii` holders get it. */
60
+ interface AuditEntryDto {
61
+ id: string;
62
+ action: string;
63
+ kind: AuditKind;
64
+ module: string;
65
+ actorId: string | null;
66
+ /** The actor's name, when they are a user that still exists. */
67
+ actor: AuditActorDto | null;
68
+ credential: AuditCredential;
69
+ targetType: string | null;
70
+ targetId: string | null;
71
+ data: AuditData | null;
72
+ createdAt: string;
73
+ }
74
+ interface ModuleOptions {
75
+ /**
76
+ * Days an entry is kept. Unset (the default) keeps every entry for good. Set, the `audit:prune` task deletes older
77
+ * entries on `retentionCron`, and records each prune in the log (`audit.pruned`).
78
+ */
79
+ retentionDays?: number;
80
+ /** When the prune runs, as a cron expression (nightly by default). `false` registers the task without a schedule. */
81
+ retentionCron?: string | false;
82
+ settings?: {
83
+ pages?: {
84
+ /** The staff page. `true` (the default, with `@frigear-nu/admin`) is `/admin/audit-log`; `false` turns it off. */
85
+ admin?: boolean | string;
86
+ };
87
+ };
88
+ }
89
+ interface AuditRuntimeConfig {
90
+ /** `0` keeps every entry. */
91
+ retentionDays: number;
92
+ }
93
+ interface PublicModuleOptions {
94
+ pages: {
95
+ admin?: string;
96
+ };
97
+ }
98
+
99
+ declare module '@nuxt/schema' {
100
+ interface NuxtConfig {
101
+ auditLog?: ModuleOptions;
102
+ }
103
+ interface RuntimeConfig {
104
+ auditLog: AuditRuntimeConfig;
105
+ }
106
+ interface PublicRuntimeConfig {
107
+ auditLog: PublicModuleOptions;
108
+ }
109
+ }
110
+ declare module 'nitropack' {
111
+ interface NitroRuntimeHooks {
112
+ /**
113
+ * An entry was written (`recordAudit`, `recordSystemAudit`, `recordDownload`): forward it to a log drain or a SIEM.
114
+ * A listener that throws is logged; the request goes on.
115
+ */
116
+ 'audit:recorded': (ctx: AuditRecordedContext) => void | Promise<void>;
117
+ }
118
+ }
119
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
120
+
121
+ export { _default as default };
122
+ export type { AuditActorDto, AuditCredential, AuditData, AuditDownloadInput, AuditEntryDto, AuditEntryInput, AuditKind, AuditRecordedContext, AuditRuntimeConfig, AuditTarget, ModuleOptions, PublicModuleOptions };
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "@frigear-nu/audit-log",
3
+ "configKey": "auditLog",
4
+ "version": "0.1.0",
5
+ "builder": {
6
+ "@nuxt/module-builder": "1.0.4",
7
+ "unbuild": "unknown"
8
+ }
9
+ }
@@ -0,0 +1,96 @@
1
+ import { defineNuxtModule, createResolver, hasNuxtModule, addServerImportsDir } from '@nuxt/kit';
2
+ import { registerModule, registerTailwindSource, registerLocales, resolvePagePath, registerDatabaseTable, addModuleRoutes, isClientOnlyApp, inlineModuleRuntime, addModulePages, addOptionalMenuSource, serverModuleDependencies } from '@frigear-nu/module-kit/utils';
3
+ import { registerAccess } from '@frigear-nu/auth/utils';
4
+ import { auditAccess } from '../dist/runtime/access.js';
5
+
6
+ const MODULE_NAME = "@frigear-nu/audit-log";
7
+ const DEFAULT_PRUNE_CRON = "45 3 * * *";
8
+ const module$1 = defineNuxtModule({
9
+ meta: { name: MODULE_NAME, configKey: "auditLog" },
10
+ defaults: {
11
+ settings: { pages: {} }
12
+ },
13
+ moduleDependencies: (nuxt) => ({
14
+ ...serverModuleDependencies(nuxt, { "@nuxthub/core": { version: ">=0.10" } }),
15
+ "@frigear-nu/module-kit": { version: ">=0.0.1" },
16
+ "@frigear-nu/auth": { version: ">=0.0.1" },
17
+ // Actors are users: their names come from the `users` table (`loadUserRefs`).
18
+ "@frigear-nu/users": { version: ">=0.0.1" },
19
+ "@frigear-nu/ui": { version: ">=0.0.1" },
20
+ "@frigear-nu/menu": { version: ">=0.0.1", optional: true },
21
+ // Provides the admin route and shell the staff page lives in.
22
+ "@frigear-nu/admin": { version: ">=0.0.0", optional: true }
23
+ }),
24
+ async setup(options, nuxt) {
25
+ registerModule(MODULE_NAME, nuxt);
26
+ const resolver = createResolver(import.meta.url);
27
+ registerAccess(nuxt, auditAccess, { from: MODULE_NAME });
28
+ registerTailwindSource(nuxt, resolver.resolve("./runtime/app"));
29
+ registerLocales(nuxt, resolver.resolve("./runtime/i18n/lang"));
30
+ const settings = options.settings ?? {};
31
+ let adminPath;
32
+ if (hasNuxtModule("@frigear-nu/admin")) {
33
+ const { adminRoute } = await import('@frigear-nu/admin/utils');
34
+ adminPath = resolvePagePath(settings.pages?.admin ?? true, adminRoute(nuxt, "audit-log"));
35
+ }
36
+ const retentionDays = Math.max(0, Math.floor(options.retentionDays ?? 0));
37
+ const existing = nuxt.options.runtimeConfig.auditLog;
38
+ nuxt.options.runtimeConfig.auditLog = { retentionDays: retentionDays || existing?.retentionDays || 0 };
39
+ const publicConfig = { pages: { admin: adminPath } };
40
+ nuxt.options.runtimeConfig.public.auditLog = publicConfig;
41
+ registerDatabaseTable(nuxt, {
42
+ resolver,
43
+ schema: (dialect) => `./runtime/server/db/schema.${dialect}`
44
+ });
45
+ addModuleRoutes(resolver, [
46
+ { method: "get", path: "", file: "admin/audit.get" },
47
+ { method: "get", path: "modules", file: "admin/modules.get" },
48
+ { method: "get", path: "export", file: "admin/export.get" }
49
+ ], { base: "/api/admin/audit" });
50
+ if (!isClientOnlyApp(nuxt)) addServerImportsDir(resolver.resolve("./runtime/server/utils"));
51
+ inlineModuleRuntime(nuxt, resolver);
52
+ const cron = retentionDays ? options.retentionCron === void 0 ? DEFAULT_PRUNE_CRON : options.retentionCron : false;
53
+ if (retentionDays && !isClientOnlyApp(nuxt)) {
54
+ nuxt.hook("nitro:config", (nitroConfig) => {
55
+ nitroConfig.experimental ||= {};
56
+ nitroConfig.experimental.tasks = true;
57
+ nitroConfig.tasks ||= {};
58
+ nitroConfig.tasks["audit:prune"] = {
59
+ handler: resolver.resolve("./runtime/server/tasks/prune"),
60
+ description: "Delete audit log entries older than the retention period."
61
+ };
62
+ if (cron) {
63
+ nitroConfig.scheduledTasks ||= {};
64
+ const scheduled = nitroConfig.scheduledTasks[cron];
65
+ nitroConfig.scheduledTasks[cron] = [...Array.isArray(scheduled) ? scheduled : scheduled ? [scheduled] : [], "audit:prune"];
66
+ }
67
+ });
68
+ if (cron) {
69
+ nuxt.hook("nitro:init", (nitro) => {
70
+ if (!nitro.options.preset.startsWith("cloudflare")) return;
71
+ const wrangler = (nitro.options.cloudflare ||= {}).wrangler ||= {};
72
+ wrangler.triggers = { ...wrangler.triggers, crons: [.../* @__PURE__ */ new Set([...wrangler.triggers?.crons ?? [], cron])] };
73
+ });
74
+ }
75
+ }
76
+ addModulePages(MODULE_NAME, resolver, [
77
+ { name: "audit-log-admin", path: adminPath, file: "./runtime/app/pages/admin.vue" }
78
+ ]);
79
+ if (adminPath) addOptionalMenuSource(nuxt, { file: resolver.resolve("./runtime/menus/admin"), menu: "admin.nav.settings" });
80
+ if (adminPath && hasNuxtModule("@frigear-nu/widget")) {
81
+ const { extendAdminDashboard } = await import('@frigear-nu/admin/utils');
82
+ extendAdminDashboard(nuxt, {
83
+ id: "audit-log-recent",
84
+ component: resolver.resolve("./runtime/app/widgets/RecentActivity.vue"),
85
+ title: "Recent activity",
86
+ icon: "i-lucide-history",
87
+ titleKey: "audit.admin.recent.title",
88
+ order: 25,
89
+ size: { cols: 2, minCols: 1, maxCols: 4, rows: 2 },
90
+ permission: auditAccess.permissions.pii
91
+ });
92
+ }
93
+ }
94
+ });
95
+
96
+ export { module$1 as default };
@@ -0,0 +1 @@
1
+ export declare const auditAccess: import("@frigear-nu/auth/access").Access<"audit", "pii" | "audit-export:pii", never, never>;
@@ -0,0 +1,17 @@
1
+ import { defineAccess } from "@frigear-nu/auth/access";
2
+ export const auditAccess = defineAccess("audit", {
3
+ permissions: {
4
+ "pii": {
5
+ label: "Read the audit log",
6
+ description: "See who downloaded, changed and reached what, and when.",
7
+ sensitive: true,
8
+ grantTo: ["admin"]
9
+ },
10
+ "audit-export:pii": {
11
+ label: "Export the audit log",
12
+ description: "Download the audit log as a CSV file.",
13
+ sensitive: true,
14
+ grantTo: ["admin"]
15
+ }
16
+ }
17
+ });
@@ -0,0 +1,3 @@
1
+ declare const __VLS_export: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
2
+ declare const _default: typeof __VLS_export;
3
+ export default _default;
@@ -0,0 +1,285 @@
1
+ <script setup>
2
+ import { authApi } from "@frigear-nu/auth/api";
3
+ import { auditApi } from "../../utils/api";
4
+ import { AUDIT_KIND_COLORS, AUDIT_KINDS } from "../../utils/kinds";
5
+ import { auditAccess } from "../../access";
6
+ import { computed, emptyCell, errorMessage, h, resolveComponent, tableUi, useFetch, useFormat, useLazyFetch, useModuleT, useRoute, useRouter, useTableQuery } from "#imports";
7
+ defineOptions({ name: "AuditLogAdminPage" });
8
+ const t = useModuleT("audit");
9
+ const format = useFormat();
10
+ const route = useRoute();
11
+ const router = useRouter();
12
+ const DAY_MS = 24 * 60 * 60 * 1e3;
13
+ const RANGES = { day: 1, week: 7, month: 30, year: 365 };
14
+ const { page, pageSize, search, query, filters, filtered, reset } = useTableQuery({
15
+ pageSize: 50,
16
+ sort: { id: "createdAt", desc: true },
17
+ filters: { kind: "all", module: "all", range: "all" }
18
+ });
19
+ const from = computed(() => {
20
+ const days = RANGES[filters.range];
21
+ return days ? new Date(Date.now() - days * DAY_MS).toISOString().slice(0, 10) : void 0;
22
+ });
23
+ const apiQuery = computed(() => ({ ...query.value, range: void 0, from: from.value }));
24
+ const { data, status, error, refresh } = await useFetch(auditApi.admin.list, { query: apiQuery });
25
+ const { data: access } = await useFetch(authApi.me.access, { key: "audit-log:access", default: () => ({ permissions: [] }), onResponseError: () => {
26
+ } });
27
+ const canExport = computed(() => !!access.value?.permissions?.includes(auditAccess.permissions["audit-export:pii"]));
28
+ const { data: modules } = useLazyFetch(auditApi.admin.modules, { key: "audit-log:modules", default: () => [] });
29
+ const rows = computed(() => data.value?.items ?? []);
30
+ const pending = computed(() => status.value === "pending");
31
+ const loading = computed(() => pending.value && !data.value);
32
+ const refreshing = computed(() => pending.value && !!data.value);
33
+ const forbidden = computed(() => error.value?.statusCode === 401 || error.value?.statusCode === 403);
34
+ const showToolbar = computed(() => filtered.value || (data.value?.total ?? 0) > 8);
35
+ const exportHref = computed(() => {
36
+ const params = new URLSearchParams();
37
+ const active = { q: query.value.q, kind: filters.kind, module: filters.module, from: from.value };
38
+ for (const [key, value] of Object.entries(active)) {
39
+ if (value && value !== "all") params.set(key, value);
40
+ }
41
+ const search2 = params.toString();
42
+ return search2 ? `${auditApi.admin.export}?${search2}` : auditApi.admin.export;
43
+ });
44
+ const kindLabel = (kind) => t(`kinds.${kind}`, { download: "Downloads", change: "Change", access: "Access", security: "Security", other: "Other" }[kind] ?? kind);
45
+ const credentialLabel = (credential) => t(`credentials.${credential}`, { session: "Session", token: "API token", oauth: "OAuth app", system: "System", anonymous: "Not signed in" }[credential] ?? credential);
46
+ const actionLabel = (action) => t(`actions.${action}`, action);
47
+ const actorName = (entry) => entry.actor?.name ?? (entry.actorId ? t("admin.unknownUser", "Deleted user {id}", { id: entry.actorId }) : t("system", "System"));
48
+ const targetOf = (entry) => [entry.targetType, entry.targetId].filter(Boolean).join(" ");
49
+ const kindOptions = computed(() => [
50
+ { value: "all", label: t("admin.allKinds", "All kinds") },
51
+ ...AUDIT_KINDS.map((kind) => ({ value: kind, label: kindLabel(kind) }))
52
+ ]);
53
+ const moduleOptions = computed(() => [
54
+ { value: "all", label: t("admin.allModules", "All modules") },
55
+ ...[.../* @__PURE__ */ new Set([...modules.value ?? [], ...filters.module !== "all" ? [filters.module] : []])].map((name) => ({ value: name, label: name }))
56
+ ]);
57
+ const rangeOptions = computed(() => [
58
+ { value: "all", label: t("admin.anyTime", "Any time") },
59
+ { value: "day", label: t("ranges.day", "Last 24 hours") },
60
+ { value: "week", label: t("ranges.week", "Last 7 days") },
61
+ { value: "month", label: t("ranges.month", "Last 30 days") },
62
+ { value: "year", label: t("ranges.year", "Last year") }
63
+ ]);
64
+ const TableIdentity = resolveComponent("TableIdentity");
65
+ const StatusBadge = resolveComponent("StatusBadge");
66
+ const columns = computed(() => [
67
+ {
68
+ id: "time",
69
+ header: t("admin.time", "Time"),
70
+ cell: ({ row }) => h("span", { class: "tabular-nums whitespace-nowrap" }, format.dateTime(row.original.createdAt))
71
+ },
72
+ {
73
+ id: "actor",
74
+ header: t("admin.actor", "Who"),
75
+ cell: ({ row }) => h(TableIdentity, { title: actorName(row.original), description: credentialLabel(row.original.credential) })
76
+ },
77
+ {
78
+ id: "action",
79
+ header: t("admin.action", "Action"),
80
+ cell: ({ row }) => h("div", { class: "flex flex-col" }, [
81
+ h("span", { class: "text-highlighted" }, actionLabel(row.original.action)),
82
+ h("span", { class: "text-xs text-muted" }, row.original.module)
83
+ ])
84
+ },
85
+ {
86
+ id: "kind",
87
+ header: t("admin.kind", "Kind"),
88
+ cell: ({ row }) => h(StatusBadge, { status: row.original.kind, label: kindLabel(row.original.kind), colors: AUDIT_KIND_COLORS })
89
+ },
90
+ {
91
+ id: "target",
92
+ header: t("admin.target", "Target"),
93
+ cell: ({ row }) => {
94
+ const target = targetOf(row.original);
95
+ return target ? h("span", { class: "font-mono text-xs break-all" }, target) : emptyCell();
96
+ }
97
+ }
98
+ ]);
99
+ const selectedId = computed(() => typeof route.query.entry === "string" ? route.query.entry : null);
100
+ const selected = computed(() => selectedId.value ? rows.value.find((entry) => entry.id === selectedId.value) ?? null : null);
101
+ function open(entry) {
102
+ void router.replace({ query: { ...route.query, entry: entry.id } });
103
+ }
104
+ function close() {
105
+ const { entry: _entry, ...rest } = route.query;
106
+ void router.replace({ query: rest });
107
+ }
108
+ const details = computed(() => {
109
+ const entry = selected.value;
110
+ if (!entry) return [];
111
+ return [
112
+ { key: "time", label: t("admin.time", "Time"), value: format.dateTime(entry.createdAt) },
113
+ { key: "action", label: t("admin.action", "Action"), value: actionLabel(entry.action) },
114
+ { key: "kind", label: t("admin.kind", "Kind"), value: kindLabel(entry.kind) },
115
+ { key: "module", label: t("admin.module", "Module"), value: entry.module },
116
+ { key: "actor", label: t("admin.actor", "Who"), value: actorName(entry) },
117
+ { key: "credential", label: t("admin.credential", "Signed in with"), value: credentialLabel(entry.credential) },
118
+ { key: "target", label: t("admin.target", "Target"), value: targetOf(entry) || null }
119
+ ];
120
+ });
121
+ </script>
122
+
123
+ <template>
124
+ <div class="flex flex-col gap-4">
125
+ <PageHeading
126
+ :title="t('admin.title', 'Audit log')"
127
+ :description="t('admin.description', 'Who downloaded, changed and reached what, and when. Entries are never edited.')"
128
+ >
129
+ <template
130
+ v-if="canExport && !forbidden"
131
+ #actions
132
+ >
133
+ <TooltipButton
134
+ color="neutral"
135
+ variant="outline"
136
+ icon="i-lucide-download"
137
+ :label="t('admin.export', 'Export audit log')"
138
+ :tooltip="t('admin.exportHint', 'Download every entry the filters match as a CSV file; the download is recorded too')"
139
+ :to="exportHref"
140
+ external
141
+ download
142
+ data-audit-export
143
+ />
144
+ </template>
145
+ </PageHeading>
146
+
147
+ <UEmpty
148
+ v-if="error && !data"
149
+ :icon="forbidden ? 'i-lucide-lock' : 'i-lucide-circle-alert'"
150
+ :title="forbidden ? t('admin.forbidden', 'You are not allowed to see the audit log') : t('admin.loadFailed', 'The audit log could not be loaded')"
151
+ :description="forbidden ? void 0 : errorMessage(error, '')"
152
+ :actions="forbidden ? [] : [{ label: t('admin.tryAgain', 'Try again'), icon: 'i-lucide-rotate-ccw', color: 'neutral', variant: 'outline', onClick: () => refresh() }]"
153
+ />
154
+
155
+ <template v-else>
156
+ <PageToolbar v-if="showToolbar">
157
+ <UInput
158
+ v-model="search"
159
+ icon="i-lucide-search"
160
+ :loading="pending"
161
+ :placeholder="t('admin.search', 'Search actions and ids')"
162
+ :aria-label="t('admin.search', 'Search actions and ids')"
163
+ class="w-full sm:max-w-xs"
164
+ />
165
+ <USelect
166
+ v-model="filters.kind"
167
+ :items="kindOptions"
168
+ :aria-label="t('admin.kind', 'Kind')"
169
+ class="w-40"
170
+ />
171
+ <USelect
172
+ v-model="filters.module"
173
+ :items="moduleOptions"
174
+ :aria-label="t('admin.module', 'Module')"
175
+ class="w-44"
176
+ />
177
+ <USelect
178
+ v-model="filters.range"
179
+ :items="rangeOptions"
180
+ :aria-label="t('admin.range', 'When')"
181
+ class="w-40"
182
+ />
183
+ <UButton
184
+ v-if="filtered"
185
+ variant="ghost"
186
+ color="neutral"
187
+ icon="i-lucide-x"
188
+ :label="t('admin.clearFilters', 'Clear filters')"
189
+ @click="reset"
190
+ />
191
+ </PageToolbar>
192
+
193
+ <TableCard
194
+ :loading="loading"
195
+ :refreshing="refreshing"
196
+ >
197
+ <UTable
198
+ :data="rows"
199
+ :columns="columns"
200
+ :ui="tableUi()"
201
+ data-audit-table
202
+ @select="(_, row) => open(row.original)"
203
+ >
204
+ <template #empty>
205
+ <UEmpty
206
+ v-if="filtered"
207
+ variant="naked"
208
+ icon="i-lucide-search"
209
+ :title="t('admin.noMatches', 'No entries match')"
210
+ :actions="[{ label: t('admin.clearFilters', 'Clear filters'), color: 'neutral', variant: 'outline', onClick: reset }]"
211
+ />
212
+ <UEmpty
213
+ v-else
214
+ variant="naked"
215
+ icon="i-lucide-scroll-text"
216
+ :title="t('admin.empty', 'Nothing recorded yet')"
217
+ :description="t('admin.emptyDescription', 'Downloads and other actions the modules record show up here.')"
218
+ />
219
+ </template>
220
+ </UTable>
221
+ <template #footer>
222
+ <TablePagination
223
+ v-model:page="page"
224
+ v-model:page-size="pageSize"
225
+ :total="data?.total ?? 0"
226
+ />
227
+ </template>
228
+ </TableCard>
229
+ </template>
230
+
231
+ <USlideover
232
+ :open="!!selected"
233
+ :title="selected ? actionLabel(selected.action) : t('admin.entry', 'Audit entry')"
234
+ :description="selected?.id"
235
+ :ui="{ footer: 'justify-end gap-2' }"
236
+ @update:open="(value) => {
237
+ if (!value) close();
238
+ }"
239
+ >
240
+ <template #body>
241
+ <div
242
+ v-if="selected"
243
+ class="flex flex-col gap-4"
244
+ data-audit-entry
245
+ >
246
+ <DescriptionList
247
+ :items="details"
248
+ :empty="t('admin.noTarget', 'None')"
249
+ >
250
+ <template #kind>
251
+ <StatusBadge
252
+ :status="selected.kind"
253
+ :label="kindLabel(selected.kind)"
254
+ :colors="AUDIT_KIND_COLORS"
255
+ />
256
+ </template>
257
+ <template
258
+ v-if="targetOf(selected)"
259
+ #target
260
+ >
261
+ <span class="font-mono text-xs break-all">{{ targetOf(selected) }}</span>
262
+ </template>
263
+ </DescriptionList>
264
+ <div
265
+ v-if="selected.data"
266
+ class="flex flex-col gap-2"
267
+ >
268
+ <p class="text-sm font-medium text-highlighted">
269
+ {{ t("admin.data", "Details") }}
270
+ </p>
271
+ <pre class="text-xs font-mono whitespace-pre-wrap break-all rounded-md bg-elevated p-3">{{ JSON.stringify(selected.data, null, 2) }}</pre>
272
+ </div>
273
+ </div>
274
+ </template>
275
+ <template #footer>
276
+ <UButton
277
+ color="neutral"
278
+ variant="outline"
279
+ :label="t('admin.close', 'Close')"
280
+ @click="close"
281
+ />
282
+ </template>
283
+ </USlideover>
284
+ </div>
285
+ </template>
@@ -0,0 +1,3 @@
1
+ declare const __VLS_export: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
2
+ declare const _default: typeof __VLS_export;
3
+ export default _default;
@@ -0,0 +1,6 @@
1
+ type __VLS_Props = {
2
+ framed?: boolean;
3
+ };
4
+ declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
5
+ declare const _default: typeof __VLS_export;
6
+ export default _default;
@@ -0,0 +1,73 @@
1
+ <script setup>
2
+ import { auditApi } from "../../utils/api";
3
+ import { auditActionWords } from "../../utils/kinds";
4
+ import { useFormat, useLazyFetch, useLocaleLink, useModuleT, useRuntimeConfig } from "#imports";
5
+ defineOptions({ name: "AuditLogRecentActivity" });
6
+ defineProps({
7
+ framed: { type: Boolean, required: false }
8
+ });
9
+ const RECENT = 11;
10
+ const t = useModuleT("audit");
11
+ const format = useFormat();
12
+ const { localize } = useLocaleLink();
13
+ const adminPage = useRuntimeConfig().public.auditLog?.pages?.admin;
14
+ const viewer = adminPage ? localize(adminPage) : void 0;
15
+ const { data, status } = useLazyFetch(auditApi.admin.list, {
16
+ key: "admin-audit-recent",
17
+ query: { pageSize: RECENT }
18
+ });
19
+ const kindIcons = {
20
+ download: "i-lucide-download",
21
+ change: "i-lucide-pencil",
22
+ access: "i-lucide-eye",
23
+ security: "i-lucide-shield-alert",
24
+ other: "i-lucide-activity"
25
+ };
26
+ const actionLabel = (action) => t(`actions.${action}`, auditActionWords(action));
27
+ const actorName = (entry) => entry.actor?.name ?? (entry.actorId ? t("admin.unknownUser", "Deleted user {id}", { id: entry.actorId }) : t("system", "System"));
28
+ const entryLink = (entry) => viewer ? `${viewer}?entry=${encodeURIComponent(entry.id)}` : void 0;
29
+ const kindTones = { download: "text-info", security: "text-warning" };
30
+ const iconColor = (kind) => kindTones[kind] ?? "text-muted";
31
+ </script>
32
+
33
+ <template>
34
+ <ListCard
35
+ :title="framed ? void 0 : t('admin.recent.title', 'Recent activity')"
36
+ :description="t('admin.recent.description', 'The latest entries of the audit log.')"
37
+ :loading="(status === 'pending' || status === 'idle') && !data?.items.length"
38
+ :is-empty="(status === 'success' || status === 'error') && !data?.items.length"
39
+ :empty="status === 'error' ? t('admin.recent.error', 'Could not load the audit log.') : t('admin.recent.empty', 'Nothing recorded yet.')"
40
+ :to="viewer"
41
+ :to-label="t('admin.recent.viewAll', 'Open the audit log')"
42
+ >
43
+ <li
44
+ v-for="entry in data?.items"
45
+ :key="entry.id"
46
+ class="flex items-center gap-3"
47
+ data-audit-recent
48
+ >
49
+ <UIcon
50
+ :name="kindIcons[entry.kind] ?? kindIcons.other"
51
+ :class="['size-4 shrink-0', iconColor(entry.kind)]"
52
+ />
53
+ <div class="min-w-0 flex-1">
54
+ <NuxtLink
55
+ v-if="entryLink(entry)"
56
+ :to="entryLink(entry)"
57
+ class="text-highlighted block truncate font-medium hover:underline"
58
+ >{{ actionLabel(entry.action) }}</NuxtLink>
59
+ <span
60
+ v-else
61
+ class="text-highlighted block truncate font-medium"
62
+ >{{ actionLabel(entry.action) }}</span>
63
+ <p class="text-muted truncate text-xs">
64
+ {{ actorName(entry) }} · {{ entry.module }}
65
+ </p>
66
+ </div>
67
+ <time
68
+ class="text-muted shrink-0 text-xs tabular-nums"
69
+ :datetime="entry.createdAt"
70
+ >{{ format.shortDateTime(entry.createdAt) }}</time>
71
+ </li>
72
+ </ListCard>
73
+ </template>
@@ -0,0 +1,6 @@
1
+ type __VLS_Props = {
2
+ framed?: boolean;
3
+ };
4
+ declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
5
+ declare const _default: typeof __VLS_export;
6
+ export default _default;