@mano8/astro-auth-m8 2.0.0 → 2.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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,41 @@ This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
  The major version tracks the supported `fa-auth-m8` **API contract**, not just
7
7
  this package's own surface: a backend contract repoint is always a major.
8
8
 
9
+ ## 2.1.0
10
+
11
+ Additive only; the supported backend contract stays `fa-auth-m8@2.0`, range
12
+ `>=2.0.0 <3.0.0`.
13
+
14
+ ### Added
15
+
16
+ - **`RequireRole minimumRole`**, an explicit minimum-role mode:
17
+ `minimumRole="admin"` renders when the signed-in role meets or exceeds
18
+ `admin` on the ordered hierarchy. It decides identically to
19
+ `roles={["admin"]}` — each array entry has been a floor since 2.0.0 — but
20
+ says what the backend dependency says instead of reading as exact membership,
21
+ so a consumer expressing a single floor no longer hand-enumerates a role
22
+ array. `roles` is unchanged and stays for guards that accept several
23
+ unrelated tiers; `superuser` remains the separate dual-evidence gate. A guard
24
+ may carry more than one mode and grants on the first that holds; one carrying
25
+ no mode grants nothing, as before.
26
+ - **`hasMinimumRole`, `hasSuperuserPrivileges`, `privilegeClaimsAreConsistent`
27
+ and `ORDERED_ROLES` re-exported from `./react`**, as the same bindings the
28
+ `./authorization` subpath exports — not a second implementation. Gating
29
+ something that is not a subtree (a menu entry, a row action, a `disabled`
30
+ attribute) now reaches the comparison from the subpath the guard already
31
+ comes from.
32
+
33
+ ### Changed
34
+
35
+ - `security-panel` gates its audit-log read with `minimumRole="admin"` rather
36
+ than `roles={["admin"]}`. Behaviour is identical; the copied file and the
37
+ `registry/r` output both change, so a consumer re-adding the block picks up
38
+ the new spelling.
39
+ - `compatibility.test.ts` now pins the published `faAuthM8` package-metadata
40
+ block against the `compatibility.ts` constants, so the machine-readable half
41
+ of the contract claim cannot drift from the half the browser preflight
42
+ enforces.
43
+
9
44
  ## 2.0.0
10
45
 
11
46
  Aligns the plugin with the `fa-auth-m8@2.0` contract (service `2.0.0`,
package/README.md CHANGED
@@ -52,6 +52,19 @@ hasSuperuserPrivileges(user.role, user.is_superuser);
52
52
 
53
53
  The valid role/flag pairs are `superadmin` with `is_superuser: true`, and every other role with `is_superuser: false`. `privilegeClaimsAreConsistent` exposes that invariant on its own, and `ORDERED_ROLES` exposes the hierarchy, highest privilege first. Any other pair - including an unrecognised role - grants nothing. These are display predicates; the backend stays the authority.
54
54
 
55
+ All four are also re-exported from `@mano8/astro-auth-m8/react`, as the same bindings, so a consumer gating something that is not a subtree - a menu entry, a table row action, a `disabled` attribute - reaches the comparison from the subpath it already imports `RequireRole` from. Wherever a subtree *is* what you are gating, `RequireRole` is the shorter spelling:
56
+
57
+ ```tsx
58
+ import { RequireRole } from "@mano8/astro-auth-m8/react";
59
+
60
+ // Minimum-role mode: at least admin, so a superadmin is admitted too.
61
+ <RequireRole minimumRole="admin" fallback={<p>Admin access required.</p>}>
62
+ <AuditLog />
63
+ </RequireRole>
64
+ ```
65
+
66
+ `minimumRole` is the form to reach for: it says what the backend dependency says. `roles={[...]}` remains for a guard that genuinely accepts several unrelated tiers - each entry is a floor there too, so `roles={["admin"]}` and `minimumRole="admin"` decide identically, but the array reads as exact membership and invites hand-enumeration. `superuser` is the separate dual-evidence gate. A guard may carry more than one mode and grants on the first that holds; one carrying none grants nothing.
67
+
55
68
  ## Error presentation
56
69
 
57
70
  `@mano8/astro-auth-m8/errors` exports `ApiError` plus `describeApiError(error, fallback)`, which maps the `fa-auth-m8` 2.0.0 authorization/rate-limit/retention error contracts to an operator-readable `{ title, description? }` (used by the `errorMessage` helper in the account registry blocks):
@@ -152,7 +165,7 @@ Install `@mano8/astro-auth-m8` from npm first, then consume the registry as a **
152
165
 
153
166
  `dashboard-overview` is the landing view; `profile-panel`, `sessions-panel`, `api-keys-panel`, `admin-users-panel`, and `security-panel` are the secondary account tabs (drop them into `account-dashboard`'s `extraTabs`, or into your own shell). Each reads its headless logic straight from the package hooks - no local adapter layer - and takes its strings via `labels`. `api-keys-panel` and `admin-users-panel` use the canonical `astro-ui-m8` data-table with client-side search, sorting, pagination, column visibility, and row selection. Their shared `account-crud` dependency is installed automatically; it supplies the popup form, destructive-action confirmation, fixed row actions, and bottom-right toast host. `admin-users-panel` self-gates with `RequireRole superuser`.
154
167
 
155
- `security-panel` carries both 2.0.0 admin tiers in one tab and gates them differently, mirroring the service: the audit log is behind `RequireRole roles={["admin"]}` (role hierarchy alone, so an admin sees its own surface and a superadmin is admitted too) and the two retention purges are behind `RequireRole superuser` (dual evidence). Each purge picks its window from the closed `RetentionWindowSchema` enum and runs only through a confirmation that names what is deleted and that a window below the service's retention floor is refused - the floor is server-side configuration published by no endpoint, so the service's rejection is surfaced verbatim instead of pre-validated. A `503` locks the purge control and reports the outcome as *unknown* until the operator explicitly acknowledges having checked, so the next click can never be a blind retry. Drop it into `account-dashboard`'s `extraTabs` with `minRole: "admin"`.
168
+ `security-panel` carries both 2.0.0 admin tiers in one tab and gates them differently, mirroring the service: the audit log is behind `RequireRole minimumRole="admin"` (role hierarchy alone, so an admin sees its own surface and a superadmin is admitted too) and the two retention purges are behind `RequireRole superuser` (dual evidence). Each purge picks its window from the closed `RetentionWindowSchema` enum and runs only through a confirmation that names what is deleted and that a window below the service's retention floor is refused - the floor is server-side configuration published by no endpoint, so the service's rejection is surfaced verbatim instead of pre-validated. A `503` locks the purge control and reports the outcome as *unknown* until the operator explicitly acknowledges having checked, so the next click can never be a blind retry. Drop it into `account-dashboard`'s `extraTabs` with `minRole: "admin"`.
156
169
 
157
170
  Files land under `src/components/fa-auth/` (the items' `target`), import shadcn primitives via `@/components/ui/*`, and pull headless logic from the installed package. The plugin package is intentionally **not** listed in registry item `dependencies`; install the published `@mano8/astro-auth-m8` package from npm yourself so shadcn only copies the skin files.
158
171
 
@@ -1,9 +1,46 @@
1
1
  import type { ReactNode } from "react";
2
2
  import type { RoleType } from "../schemas.js";
3
- export declare function RequireRole({ children, roles, superuser, fallback }: {
3
+ export type RequireRoleProps = {
4
4
  children: ReactNode;
5
+ /**
6
+ * Minimum-role mode: render when the signed-in role meets or exceeds this
7
+ * one on the ordered hierarchy (`hasMinimumRole`).
8
+ *
9
+ * This is the form to reach for. `minimumRole="admin"` says what the backend
10
+ * dependency says - *at least* admin - where the equivalent `roles={["admin"]}`
11
+ * reads as exact membership and only behaves as a floor because this guard
12
+ * compares hierarchically. Consumers were hand-enumerating role arrays to
13
+ * express a floor; a single role is the honest spelling of it (`RBAC-06`).
14
+ */
15
+ minimumRole?: RoleType;
16
+ /**
17
+ * Any-of mode: render when the signed-in role meets or exceeds *any* listed
18
+ * role. Each entry is still a floor, not an exact match, so
19
+ * `roles={["admin"]}` admits a `superadmin`.
20
+ *
21
+ * Kept for guards that genuinely accept several unrelated tiers. For a single
22
+ * floor, prefer {@link minimumRole}.
23
+ */
5
24
  roles?: RoleType[];
25
+ /**
26
+ * Superuser mode: render only on dual evidence (`role === "superadmin"` and
27
+ * `is_superuser === true`), never on either claim alone.
28
+ */
6
29
  superuser?: boolean;
7
30
  fallback?: ReactNode;
8
- }): ReactNode;
31
+ };
32
+ /**
33
+ * Render `children` when the signed-in user satisfies any supplied mode.
34
+ *
35
+ * The modes are a union, evaluated independently, so a guard carrying more
36
+ * than one grants on the first that holds. With no mode supplied nothing is
37
+ * granted - an unqualified guard is a mistake, and failing closed makes it a
38
+ * visible one.
39
+ *
40
+ * Every comparison goes through `../authorization.js`, this package's single
41
+ * encoding of the hierarchy and of the `role`/`is_superuser` invariant. The
42
+ * backend remains the authority; this only keeps the UI from offering surfaces
43
+ * the service would refuse.
44
+ */
45
+ export declare function RequireRole({ children, minimumRole, roles, superuser, fallback }: RequireRoleProps): ReactNode;
9
46
  //# sourceMappingURL=RequireRole.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"RequireRole.d.ts","sourceRoot":"","sources":["../../../../src/runtime/react/RequireRole.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAEvC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAG9C,wBAAgB,WAAW,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,SAAiB,EAAE,QAAe,EAAE,EAAE;IAAE,QAAQ,EAAE,SAAS,CAAC;IAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC;IAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,SAAS,CAAA;CAAE,aAM1K"}
1
+ {"version":3,"file":"RequireRole.d.ts","sourceRoot":"","sources":["../../../../src/runtime/react/RequireRole.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAEvC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAG9C,MAAM,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,EAAE,SAAS,CAAC;IACpB;;;;;;;;;OASG;IACH,WAAW,CAAC,EAAE,QAAQ,CAAC;IACvB;;;;;;;OAOG;IACH,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC;IACnB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,QAAQ,CAAC,EAAE,SAAS,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAgB,WAAW,CAAC,EAAE,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE,SAAiB,EAAE,QAAe,EAAE,EAAE,gBAAgB,aAOjH"}
@@ -1,11 +1,26 @@
1
1
  import { useAuth } from "./AuthProvider.js";
2
2
  import { hasMinimumRole, hasSuperuserPrivileges } from "../authorization.js";
3
- export function RequireRole({ children, roles, superuser = false, fallback = null }) {
3
+ /**
4
+ * Render `children` when the signed-in user satisfies any supplied mode.
5
+ *
6
+ * The modes are a union, evaluated independently, so a guard carrying more
7
+ * than one grants on the first that holds. With no mode supplied nothing is
8
+ * granted - an unqualified guard is a mistake, and failing closed makes it a
9
+ * visible one.
10
+ *
11
+ * Every comparison goes through `../authorization.js`, this package's single
12
+ * encoding of the hierarchy and of the `role`/`is_superuser` invariant. The
13
+ * backend remains the authority; this only keeps the UI from offering surfaces
14
+ * the service would refuse.
15
+ */
16
+ export function RequireRole({ children, minimumRole, roles, superuser = false, fallback = null }) {
4
17
  const { user, loading } = useAuth();
5
18
  if (loading || !user)
6
19
  return fallback;
7
20
  if (superuser && hasSuperuserPrivileges(user.role, user.is_superuser))
8
21
  return children;
22
+ if (minimumRole && hasMinimumRole(user.role, minimumRole))
23
+ return children;
9
24
  if (roles?.some((requiredRole) => hasMinimumRole(user.role, requiredRole)))
10
25
  return children;
11
26
  return fallback;
@@ -1 +1 @@
1
- {"version":3,"file":"RequireRole.js","sourceRoot":"","sources":["../../../../src/runtime/react/RequireRole.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAE5C,OAAO,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAE7E,MAAM,UAAU,WAAW,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,SAAS,GAAG,KAAK,EAAE,QAAQ,GAAG,IAAI,EAA0F;IACzK,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;IACpC,IAAI,OAAO,IAAI,CAAC,IAAI;QAAE,OAAO,QAAQ,CAAC;IACtC,IAAI,SAAS,IAAI,sBAAsB,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,QAAQ,CAAC;IACvF,IAAI,KAAK,EAAE,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QAAE,OAAO,QAAQ,CAAC;IAC5F,OAAO,QAAQ,CAAC;AAClB,CAAC"}
1
+ {"version":3,"file":"RequireRole.js","sourceRoot":"","sources":["../../../../src/runtime/react/RequireRole.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAE5C,OAAO,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAgC7E;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,WAAW,CAAC,EAAE,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE,SAAS,GAAG,KAAK,EAAE,QAAQ,GAAG,IAAI,EAAoB;IAChH,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;IACpC,IAAI,OAAO,IAAI,CAAC,IAAI;QAAE,OAAO,QAAQ,CAAC;IACtC,IAAI,SAAS,IAAI,sBAAsB,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,QAAQ,CAAC;IACvF,IAAI,WAAW,IAAI,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC;QAAE,OAAO,QAAQ,CAAC;IAC3E,IAAI,KAAK,EAAE,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QAAE,OAAO,QAAQ,CAAC;IAC5F,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -3,4 +3,5 @@ export * from "./AuthQueryProvider.js";
3
3
  export * from "./AuthProvider.js";
4
4
  export * from "./RequireAuth.js";
5
5
  export * from "./RequireRole.js";
6
+ export { ORDERED_ROLES, hasMinimumRole, hasSuperuserPrivileges, privilegeClaimsAreConsistent } from "../authorization.js";
6
7
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/runtime/react/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,KAAK,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACxG,cAAc,wBAAwB,CAAC;AACvC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/runtime/react/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,KAAK,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACxG,cAAc,wBAAwB,CAAC;AACvC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,kBAAkB,CAAC;AAOjC,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,sBAAsB,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC"}
@@ -6,4 +6,11 @@ export * from "./AuthQueryProvider.js";
6
6
  export * from "./AuthProvider.js";
7
7
  export * from "./RequireAuth.js";
8
8
  export * from "./RequireRole.js";
9
+ // The hierarchy primitives, re-exported alongside `RequireRole` so a consumer
10
+ // gating something that is not a subtree - a menu entry, a table row action, a
11
+ // disabled attribute - reaches the same comparison from the same subpath it
12
+ // already imports the guard from, instead of hand-rolling a role-ordered list
13
+ // (`RBAC-06`). `./authorization` remains the framework-neutral home; these are
14
+ // the same bindings, not a second implementation.
15
+ export { ORDERED_ROLES, hasMinimumRole, hasSuperuserPrivileges, privilegeClaimsAreConsistent } from "../authorization.js";
9
16
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtime/react/index.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,gFAAgF;AAChF,uDAAuD;AACvD,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAA6B,MAAM,kBAAkB,CAAC;AACxG,cAAc,wBAAwB,CAAC;AACvC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtime/react/index.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,gFAAgF;AAChF,uDAAuD;AACvD,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAA6B,MAAM,kBAAkB,CAAC;AACxG,cAAc,wBAAwB,CAAC;AACvC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,kBAAkB,CAAC;AACjC,8EAA8E;AAC9E,+EAA+E;AAC/E,4EAA4E;AAC5E,8EAA8E;AAC9E,+EAA+E;AAC/E,kDAAkD;AAClD,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,sBAAsB,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mano8/astro-auth-m8",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Astro integration and headless client for fa-auth-m8.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -62,7 +62,7 @@
62
62
  "test:unit": "vitest run"
63
63
  },
64
64
  "dependencies": {
65
- "@mano8/astro-ui-m8": "^1.4.1"
65
+ "@mano8/astro-ui-m8": "^1.4.2"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "@astrojs/react": "^6.0.1",
@@ -19,7 +19,7 @@
19
19
  "files": [
20
20
  {
21
21
  "path": "registry/blocks/account/security-panel.tsx",
22
- "content": "\"use client\";\n\n// fa-auth security panel: the admin-tier privileged-action audit log plus the\n// two superadmin-only retention purges. Headless logic stays a live dependency\n// — `useAuditLog` / `useSecurityPurges` (@mano8/astro-auth-m8/hooks) own the\n// calls and the package Zod schemas own the closed retention-window enum. This\n// file is only the shadcn skin, copied into the consumer via the @fa-m8-auth\n// registry — edit (and translate via `labels`) freely per app.\n//\n// Two tiers, two deliberately different gates, mirroring fa-auth-m8 2.0.0:\n// * the audit-log READ is authorized by the role hierarchy alone\n// (`get_current_active_admin`), so it is gated with `RequireRole\n// roles={[\"admin\"]}` — gating it on superuser would hide an admin's own\n// surface from them;\n// * both PURGES are superuser actions (`get_current_active_superuser`), so\n// they are gated with `RequireRole superuser` (dual evidence).\n// Which rows the log returns — an admin's own, or every row for a superadmin —\n// is decided server-side from the authenticated principal. This panel renders\n// what it receives and never sends an actor id to widen or narrow that.\nimport * as React from \"react\";\nimport type { ColumnDef } from \"@tanstack/react-table\";\nimport { RotateCcw, Trash2 } from \"lucide-react\";\nimport { RequireRole } from \"@mano8/astro-auth-m8/react\";\nimport { useAuditLog, useSecurityPurges } from \"@mano8/astro-auth-m8/hooks\";\nimport { ApiError } from \"@mano8/astro-auth-m8/errors\";\nimport {\n RetentionWindowSchema,\n type PrivilegedActionAuditPublic,\n type PurgeResponse,\n type RetentionWindow,\n} from \"@mano8/astro-auth-m8/schemas\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\nimport { DataTable } from \"@/components/m8-ui/data-table\";\nimport { DataTableColumnHeader } from \"@/components/m8-ui/data-table-column-header\";\nimport {\n AccountToastHost,\n accountToast,\n ConfirmDeleteDialog,\n errorMessage,\n useClientTable,\n type UseClientTableOptions,\n} from \"./account-crud\";\n\nexport interface SecurityPanelLabels {\n auditTitle: string;\n auditDescription: string;\n auditScopeNotice: string;\n adminRequired: string;\n refresh: string;\n loading: string;\n empty: string;\n search: string;\n when: string;\n action: string;\n actor: string;\n actorRole: string;\n table: string;\n row: string;\n targetOwner: string;\n notAvailable: string;\n auditLoadFailed: string;\n purgeTitle: string;\n purgeDescription: string;\n retentionFloorNotice: string;\n window: string;\n windowLabels: Record<RetentionWindow, string>;\n purgeAuditTitle: string;\n purgeAuditDescription: string;\n purgeAuditConfirmTitle: string;\n purgeAuditConfirmBody: string;\n purgeKeysTitle: string;\n purgeKeysDescription: string;\n purgeKeysConfirmTitle: string;\n purgeKeysConfirmBody: string;\n purge: string;\n purging: string;\n cancel: string;\n purged: string;\n purgedRemoved: string;\n purgeFailed: string;\n unknownOutcomeTitle: string;\n unknownOutcomeBody: string;\n unknownOutcomeAcknowledge: string;\n}\n\nconst DEFAULT_LABELS: SecurityPanelLabels = {\n auditTitle: \"Privileged action audit log\",\n auditDescription:\n \"Every privileged write recorded by the auth service, newest first.\",\n auditScopeNotice:\n \"Scope is decided by the auth service from your own credentials: an admin sees the entries it authored, a superadmin sees every entry. This view never requests another user's entries.\",\n adminRequired: \"The audit log is available to admin accounts and above.\",\n refresh: \"Refresh\",\n loading: \"Loading audit entries...\",\n empty: \"No audit entries found.\",\n search: \"Search entries\",\n when: \"When\",\n action: \"Action\",\n actor: \"Actor\",\n actorRole: \"Actor role\",\n table: \"Table\",\n row: \"Row\",\n targetOwner: \"Target owner\",\n notAvailable: \"n/a\",\n auditLoadFailed: \"Failed to load the audit log.\",\n purgeTitle: \"Retention purges\",\n purgeDescription:\n \"Superuser-only maintenance: permanently delete records older than the selected retention window.\",\n retentionFloorNotice:\n \"The auth service enforces a minimum retention floor. It is server-side configuration and is not published by any endpoint, so a window shorter than the floor cannot be caught here - the service rejects it and its reason is shown verbatim.\",\n window: \"Retention window\",\n windowLabels: {\n \"1w\": \"Older than 1 week\",\n \"1m\": \"Older than 1 month\",\n \"3m\": \"Older than 3 months\",\n \"6m\": \"Older than 6 months\",\n \"1y\": \"Older than 1 year\",\n },\n purgeAuditTitle: \"Purge audit entries\",\n purgeAuditDescription:\n \"Deletes privileged-action audit entries older than the selected window.\",\n purgeAuditConfirmTitle: \"Purge audit entries?\",\n purgeAuditConfirmBody:\n \"This permanently deletes every audit entry older than the selected retention window. Audit history cannot be restored, and entries below the service's retention floor are refused.\",\n purgeKeysTitle: \"Purge revoked API keys\",\n purgeKeysDescription:\n \"Deletes revoked or expired API key records older than the selected window.\",\n purgeKeysConfirmTitle: \"Purge API key records?\",\n purgeKeysConfirmBody:\n \"This permanently deletes revoked and expired API key records older than the selected retention window. The records cannot be restored, and windows below the service's retention floor are refused.\",\n purge: \"Purge\",\n purging: \"Purging...\",\n cancel: \"Cancel\",\n purged: \"Purge complete.\",\n purgedRemoved: \"Records removed\",\n purgeFailed: \"Purge failed.\",\n unknownOutcomeTitle: \"Outcome unknown\",\n unknownOutcomeBody:\n \"The auth service could not confirm whether this purge ran. Check the current record counts before doing anything else - re-running it now could delete more than you intend, and the reported count would be wrong either way.\",\n unknownOutcomeAcknowledge: \"I have checked - re-enable\",\n};\n\nfunction formatDate(value: string | null | undefined, fallback: string): string {\n return value ? new Date(value).toLocaleString() : fallback;\n}\n\n// Raw identifiers are shown verbatim in a mono face: they are what an operator\n// correlates against the service's own logs, so they are never truncated.\nfunction monoCell(value: string | null | undefined, fallback: string) {\n return <span className=\"font-mono text-xs\">{value ?? fallback}</span>;\n}\n\n// Human-readable, sortable columns.\nfunction auditDetailColumns(\n t: SecurityPanelLabels,\n): ColumnDef<PrivilegedActionAuditPublic>[] {\n return [\n {\n accessorKey: \"created_at\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.when} />\n ),\n cell: ({ row }) => formatDate(row.original.created_at, t.notAvailable),\n },\n {\n accessorKey: \"action\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.action} />\n ),\n cell: ({ row }) => (\n <Badge variant=\"outline\" className=\"capitalize\">\n {row.original.action}\n </Badge>\n ),\n },\n {\n accessorKey: \"table_name\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.table} />\n ),\n },\n {\n accessorKey: \"actor_role\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.actorRole} />\n ),\n cell: ({ row }) => (\n <span className=\"capitalize\">{row.original.actor_role}</span>\n ),\n },\n ];\n}\n\n// The three id columns differ only by which field they read, so they share one\n// builder rather than repeating the same cell three times.\nfunction auditIdentifierColumns(\n t: SecurityPanelLabels,\n): ColumnDef<PrivilegedActionAuditPublic>[] {\n const identifier = (\n accessorKey: \"row_pk\" | \"actor_user_id\" | \"target_owner_id\",\n header: string,\n ): ColumnDef<PrivilegedActionAuditPublic> => ({\n accessorKey,\n header,\n enableSorting: false,\n cell: ({ row }) => monoCell(row.original[accessorKey], t.notAvailable),\n });\n\n return [\n identifier(\"row_pk\", t.row),\n identifier(\"actor_user_id\", t.actor),\n identifier(\"target_owner_id\", t.targetOwner),\n ];\n}\n\n// Client-side search/sort behaviour for the audit rows. Static, so it is built\n// once here rather than on every render of the section.\nconst AUDIT_TABLE_OPTIONS: UseClientTableOptions<PrivilegedActionAuditPublic> = {\n search: (entry) => `${entry.action} ${entry.table_name} ${entry.actor_user_id}`,\n sorters: {\n created_at: (entry) => entry.created_at,\n action: (entry) => entry.action,\n actor_role: (entry) => entry.actor_role,\n table_name: (entry) => entry.table_name,\n },\n initialSortBy: \"created_at\",\n initialSortDir: \"desc\",\n};\n\nfunction AuditRefreshButton({\n t,\n reload,\n}: {\n t: SecurityPanelLabels;\n reload: () => Promise<unknown>;\n}) {\n return (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n onClick={() => {\n reload().catch((error) => {\n accountToast.error(errorMessage(error, t.auditLoadFailed));\n });\n }}\n >\n <RotateCcw className=\"size-4\" />\n {t.refresh}\n </Button>\n );\n}\n\nfunction AuditLogSection({ t }: { t: SecurityPanelLabels }) {\n // No actor filter is sent: the service scopes the rows from the caller's own\n // credentials, and passing one here could only ever ask for someone else's.\n const { rows, count, loading, reload } = useAuditLog({}, false);\n\n React.useEffect(() => {\n reload().catch(() => {});\n }, [reload]);\n\n const controller = useClientTable(rows, AUDIT_TABLE_OPTIONS);\n const columns = React.useMemo(\n () => [...auditDetailColumns(t), ...auditIdentifierColumns(t)],\n [t],\n );\n\n return (\n <Card>\n <CardHeader>\n <CardTitle>{t.auditTitle}</CardTitle>\n <CardDescription>{t.auditDescription}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{t.auditScopeNotice}</p>\n <DataTable<PrivilegedActionAuditPublic, unknown>\n columns={columns}\n data={controller.data}\n rowCount={controller.rowCount}\n page={controller.page}\n pageSize={controller.pageSize}\n onPageChange={controller.onPageChange}\n onPageSizeChange={controller.onPageSizeChange}\n sortBy={controller.sortBy}\n sortDir={controller.sortDir}\n onSortChange={controller.onSortChange}\n q={controller.q}\n onSearchChange={controller.onSearchChange}\n loading={loading && count === 0}\n getRowId={(entry) => entry.id}\n labels={{\n loading: t.loading,\n empty: t.empty,\n toolbar: { search: t.search },\n }}\n addButton={<AuditRefreshButton t={t} reload={reload} />}\n />\n </CardContent>\n </Card>\n );\n}\n\nfunction PurgeCard({\n t,\n title,\n description,\n confirmTitle,\n confirmBody,\n action,\n testId,\n}: {\n t: SecurityPanelLabels;\n title: string;\n description: string;\n confirmTitle: string;\n confirmBody: string;\n action: (retention: RetentionWindow) => Promise<PurgeResponse>;\n testId: string;\n}) {\n const [retention, setRetention] = React.useState<RetentionWindow>(\"1y\");\n const [confirming, setConfirming] = React.useState(false);\n const [pending, setPending] = React.useState(false);\n // Set on a 503 only. The purge may or may not have run, so the control is\n // locked until the operator explicitly acknowledges having checked: a purge\n // is not idempotent in its reporting, and a blind re-run would both delete\n // more than intended and report a count the operator would misread.\n const [outcomeUnknown, setOutcomeUnknown] = React.useState(false);\n\n const confirm = async () => {\n setPending(true);\n try {\n const result = await action(retention);\n setConfirming(false);\n accountToast.success({\n title: t.purged,\n description: `${t.purgedRemoved}: ${result.removed}`,\n });\n } catch (error) {\n if (error instanceof ApiError && error.status === 503) {\n setOutcomeUnknown(true);\n setConfirming(false);\n }\n // 429 (rate limited, not attempted), 503 (unknown) and the free-text 400\n // retention-floor rejection are all mapped by the package's\n // describeApiError; nothing is retried automatically here.\n accountToast.error(errorMessage(error, t.purgeFailed));\n } finally {\n setPending(false);\n }\n };\n\n const selectId = `${testId}-window`;\n\n return (\n <Card className=\"h-full\" data-account-purge={testId}>\n <CardHeader>\n <CardTitle className=\"text-base\">{title}</CardTitle>\n <CardDescription>{description}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"space-y-1\">\n <Label htmlFor={selectId}>{t.window}</Label>\n {/* Closed enum, never free text or a date: the service accepts only\n these five windows, and the list is derived from the package\n schema so it cannot drift from the contract. */}\n <select\n id={selectId}\n aria-label={t.window}\n className=\"h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50\"\n value={retention}\n onChange={(event) =>\n setRetention(event.target.value as RetentionWindow)\n }\n >\n {RetentionWindowSchema.options.map((option) => (\n <option key={option} value={option}>\n {t.windowLabels[option]}\n </option>\n ))}\n </select>\n </div>\n\n {outcomeUnknown ? (\n <div\n role=\"alert\"\n className=\"space-y-2 rounded-md border border-destructive/50 p-3 text-sm\"\n >\n <p className=\"font-medium\">{t.unknownOutcomeTitle}</p>\n <p className=\"text-muted-foreground\">{t.unknownOutcomeBody}</p>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n onClick={() => setOutcomeUnknown(false)}\n data-account-action=\"acknowledge-unknown\"\n >\n {t.unknownOutcomeAcknowledge}\n </Button>\n </div>\n ) : null}\n\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n disabled={pending || outcomeUnknown}\n onClick={() => setConfirming(true)}\n data-account-action=\"purge\"\n >\n <Trash2 className=\"size-3.5\" />\n {pending ? t.purging : t.purge}\n </Button>\n </CardContent>\n\n {/* Purges are never a one-click action: each goes through its own\n confirmation naming what is deleted and that a window below the\n service's retention floor is refused. */}\n <ConfirmDeleteDialog\n open={confirming}\n onOpenChange={(open) => {\n if (!open) setConfirming(false);\n }}\n title={confirmTitle}\n description={`${confirmBody} ${t.retentionFloorNotice}`}\n confirmLabel={t.purge}\n cancelLabel={t.cancel}\n pending={pending}\n onConfirm={() => {\n void confirm();\n }}\n />\n </Card>\n );\n}\n\nfunction PurgeSection({ t }: { t: SecurityPanelLabels }) {\n const { purgeAudit, purgeKeys } = useSecurityPurges();\n\n return (\n <Card>\n <CardHeader>\n <CardTitle>{t.purgeTitle}</CardTitle>\n <CardDescription>{t.purgeDescription}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{t.retentionFloorNotice}</p>\n <div className=\"grid auto-rows-fr gap-4 lg:grid-cols-2\">\n <PurgeCard\n t={t}\n testId=\"audit-log\"\n title={t.purgeAuditTitle}\n description={t.purgeAuditDescription}\n confirmTitle={t.purgeAuditConfirmTitle}\n confirmBody={t.purgeAuditConfirmBody}\n action={purgeAudit}\n />\n <PurgeCard\n t={t}\n testId=\"api-keys\"\n title={t.purgeKeysTitle}\n description={t.purgeKeysDescription}\n confirmTitle={t.purgeKeysConfirmTitle}\n confirmBody={t.purgeKeysConfirmBody}\n action={purgeKeys}\n />\n </div>\n </CardContent>\n </Card>\n );\n}\n\nexport function SecurityPanel({\n labels,\n}: {\n labels?: Partial<SecurityPanelLabels>;\n}) {\n const t = {\n ...DEFAULT_LABELS,\n ...labels,\n windowLabels: { ...DEFAULT_LABELS.windowLabels, ...labels?.windowLabels },\n };\n\n return (\n <div className=\"not-content flex w-full flex-col gap-6\">\n <AccountToastHost />\n {/* Admin tier: role hierarchy only, so a superadmin is admitted too. */}\n <RequireRole\n roles={[\"admin\"]}\n fallback={\n <p className=\"text-sm text-muted-foreground\">{t.adminRequired}</p>\n }\n >\n <AuditLogSection t={t} />\n </RequireRole>\n {/* Superadmin tier: dual evidence. Rendering nothing (not a message) for\n everyone else keeps the maintenance surface out of an admin's view. */}\n <RequireRole superuser>\n <PurgeSection t={t} />\n </RequireRole>\n </div>\n );\n}\n",
22
+ "content": "\"use client\";\n\n// fa-auth security panel: the admin-tier privileged-action audit log plus the\n// two superadmin-only retention purges. Headless logic stays a live dependency\n// — `useAuditLog` / `useSecurityPurges` (@mano8/astro-auth-m8/hooks) own the\n// calls and the package Zod schemas own the closed retention-window enum. This\n// file is only the shadcn skin, copied into the consumer via the @fa-m8-auth\n// registry — edit (and translate via `labels`) freely per app.\n//\n// Two tiers, two deliberately different gates, mirroring fa-auth-m8 2.0.0:\n// * the audit-log READ is authorized by the role hierarchy alone\n// (`get_current_active_admin`), so it is gated with `RequireRole\n// minimumRole=\"admin\"` — gating it on superuser would hide an admin's own\n// surface from them;\n// * both PURGES are superuser actions (`get_current_active_superuser`), so\n// they are gated with `RequireRole superuser` (dual evidence).\n// Which rows the log returns — an admin's own, or every row for a superadmin —\n// is decided server-side from the authenticated principal. This panel renders\n// what it receives and never sends an actor id to widen or narrow that.\nimport * as React from \"react\";\nimport type { ColumnDef } from \"@tanstack/react-table\";\nimport { RotateCcw, Trash2 } from \"lucide-react\";\nimport { RequireRole } from \"@mano8/astro-auth-m8/react\";\nimport { useAuditLog, useSecurityPurges } from \"@mano8/astro-auth-m8/hooks\";\nimport { ApiError } from \"@mano8/astro-auth-m8/errors\";\nimport {\n RetentionWindowSchema,\n type PrivilegedActionAuditPublic,\n type PurgeResponse,\n type RetentionWindow,\n} from \"@mano8/astro-auth-m8/schemas\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\nimport { DataTable } from \"@/components/m8-ui/data-table\";\nimport { DataTableColumnHeader } from \"@/components/m8-ui/data-table-column-header\";\nimport {\n AccountToastHost,\n accountToast,\n ConfirmDeleteDialog,\n errorMessage,\n useClientTable,\n type UseClientTableOptions,\n} from \"./account-crud\";\n\nexport interface SecurityPanelLabels {\n auditTitle: string;\n auditDescription: string;\n auditScopeNotice: string;\n adminRequired: string;\n refresh: string;\n loading: string;\n empty: string;\n search: string;\n when: string;\n action: string;\n actor: string;\n actorRole: string;\n table: string;\n row: string;\n targetOwner: string;\n notAvailable: string;\n auditLoadFailed: string;\n purgeTitle: string;\n purgeDescription: string;\n retentionFloorNotice: string;\n window: string;\n windowLabels: Record<RetentionWindow, string>;\n purgeAuditTitle: string;\n purgeAuditDescription: string;\n purgeAuditConfirmTitle: string;\n purgeAuditConfirmBody: string;\n purgeKeysTitle: string;\n purgeKeysDescription: string;\n purgeKeysConfirmTitle: string;\n purgeKeysConfirmBody: string;\n purge: string;\n purging: string;\n cancel: string;\n purged: string;\n purgedRemoved: string;\n purgeFailed: string;\n unknownOutcomeTitle: string;\n unknownOutcomeBody: string;\n unknownOutcomeAcknowledge: string;\n}\n\nconst DEFAULT_LABELS: SecurityPanelLabels = {\n auditTitle: \"Privileged action audit log\",\n auditDescription:\n \"Every privileged write recorded by the auth service, newest first.\",\n auditScopeNotice:\n \"Scope is decided by the auth service from your own credentials: an admin sees the entries it authored, a superadmin sees every entry. This view never requests another user's entries.\",\n adminRequired: \"The audit log is available to admin accounts and above.\",\n refresh: \"Refresh\",\n loading: \"Loading audit entries...\",\n empty: \"No audit entries found.\",\n search: \"Search entries\",\n when: \"When\",\n action: \"Action\",\n actor: \"Actor\",\n actorRole: \"Actor role\",\n table: \"Table\",\n row: \"Row\",\n targetOwner: \"Target owner\",\n notAvailable: \"n/a\",\n auditLoadFailed: \"Failed to load the audit log.\",\n purgeTitle: \"Retention purges\",\n purgeDescription:\n \"Superuser-only maintenance: permanently delete records older than the selected retention window.\",\n retentionFloorNotice:\n \"The auth service enforces a minimum retention floor. It is server-side configuration and is not published by any endpoint, so a window shorter than the floor cannot be caught here - the service rejects it and its reason is shown verbatim.\",\n window: \"Retention window\",\n windowLabels: {\n \"1w\": \"Older than 1 week\",\n \"1m\": \"Older than 1 month\",\n \"3m\": \"Older than 3 months\",\n \"6m\": \"Older than 6 months\",\n \"1y\": \"Older than 1 year\",\n },\n purgeAuditTitle: \"Purge audit entries\",\n purgeAuditDescription:\n \"Deletes privileged-action audit entries older than the selected window.\",\n purgeAuditConfirmTitle: \"Purge audit entries?\",\n purgeAuditConfirmBody:\n \"This permanently deletes every audit entry older than the selected retention window. Audit history cannot be restored, and entries below the service's retention floor are refused.\",\n purgeKeysTitle: \"Purge revoked API keys\",\n purgeKeysDescription:\n \"Deletes revoked or expired API key records older than the selected window.\",\n purgeKeysConfirmTitle: \"Purge API key records?\",\n purgeKeysConfirmBody:\n \"This permanently deletes revoked and expired API key records older than the selected retention window. The records cannot be restored, and windows below the service's retention floor are refused.\",\n purge: \"Purge\",\n purging: \"Purging...\",\n cancel: \"Cancel\",\n purged: \"Purge complete.\",\n purgedRemoved: \"Records removed\",\n purgeFailed: \"Purge failed.\",\n unknownOutcomeTitle: \"Outcome unknown\",\n unknownOutcomeBody:\n \"The auth service could not confirm whether this purge ran. Check the current record counts before doing anything else - re-running it now could delete more than you intend, and the reported count would be wrong either way.\",\n unknownOutcomeAcknowledge: \"I have checked - re-enable\",\n};\n\nfunction formatDate(value: string | null | undefined, fallback: string): string {\n return value ? new Date(value).toLocaleString() : fallback;\n}\n\n// Raw identifiers are shown verbatim in a mono face: they are what an operator\n// correlates against the service's own logs, so they are never truncated.\nfunction monoCell(value: string | null | undefined, fallback: string) {\n return <span className=\"font-mono text-xs\">{value ?? fallback}</span>;\n}\n\n// Human-readable, sortable columns.\nfunction auditDetailColumns(\n t: SecurityPanelLabels,\n): ColumnDef<PrivilegedActionAuditPublic>[] {\n return [\n {\n accessorKey: \"created_at\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.when} />\n ),\n cell: ({ row }) => formatDate(row.original.created_at, t.notAvailable),\n },\n {\n accessorKey: \"action\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.action} />\n ),\n cell: ({ row }) => (\n <Badge variant=\"outline\" className=\"capitalize\">\n {row.original.action}\n </Badge>\n ),\n },\n {\n accessorKey: \"table_name\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.table} />\n ),\n },\n {\n accessorKey: \"actor_role\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.actorRole} />\n ),\n cell: ({ row }) => (\n <span className=\"capitalize\">{row.original.actor_role}</span>\n ),\n },\n ];\n}\n\n// The three id columns differ only by which field they read, so they share one\n// builder rather than repeating the same cell three times.\nfunction auditIdentifierColumns(\n t: SecurityPanelLabels,\n): ColumnDef<PrivilegedActionAuditPublic>[] {\n const identifier = (\n accessorKey: \"row_pk\" | \"actor_user_id\" | \"target_owner_id\",\n header: string,\n ): ColumnDef<PrivilegedActionAuditPublic> => ({\n accessorKey,\n header,\n enableSorting: false,\n cell: ({ row }) => monoCell(row.original[accessorKey], t.notAvailable),\n });\n\n return [\n identifier(\"row_pk\", t.row),\n identifier(\"actor_user_id\", t.actor),\n identifier(\"target_owner_id\", t.targetOwner),\n ];\n}\n\n// Client-side search/sort behaviour for the audit rows. Static, so it is built\n// once here rather than on every render of the section.\nconst AUDIT_TABLE_OPTIONS: UseClientTableOptions<PrivilegedActionAuditPublic> = {\n search: (entry) => `${entry.action} ${entry.table_name} ${entry.actor_user_id}`,\n sorters: {\n created_at: (entry) => entry.created_at,\n action: (entry) => entry.action,\n actor_role: (entry) => entry.actor_role,\n table_name: (entry) => entry.table_name,\n },\n initialSortBy: \"created_at\",\n initialSortDir: \"desc\",\n};\n\nfunction AuditRefreshButton({\n t,\n reload,\n}: {\n t: SecurityPanelLabels;\n reload: () => Promise<unknown>;\n}) {\n return (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n onClick={() => {\n reload().catch((error) => {\n accountToast.error(errorMessage(error, t.auditLoadFailed));\n });\n }}\n >\n <RotateCcw className=\"size-4\" />\n {t.refresh}\n </Button>\n );\n}\n\nfunction AuditLogSection({ t }: { t: SecurityPanelLabels }) {\n // No actor filter is sent: the service scopes the rows from the caller's own\n // credentials, and passing one here could only ever ask for someone else's.\n const { rows, count, loading, reload } = useAuditLog({}, false);\n\n React.useEffect(() => {\n reload().catch(() => {});\n }, [reload]);\n\n const controller = useClientTable(rows, AUDIT_TABLE_OPTIONS);\n const columns = React.useMemo(\n () => [...auditDetailColumns(t), ...auditIdentifierColumns(t)],\n [t],\n );\n\n return (\n <Card>\n <CardHeader>\n <CardTitle>{t.auditTitle}</CardTitle>\n <CardDescription>{t.auditDescription}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{t.auditScopeNotice}</p>\n <DataTable<PrivilegedActionAuditPublic, unknown>\n columns={columns}\n data={controller.data}\n rowCount={controller.rowCount}\n page={controller.page}\n pageSize={controller.pageSize}\n onPageChange={controller.onPageChange}\n onPageSizeChange={controller.onPageSizeChange}\n sortBy={controller.sortBy}\n sortDir={controller.sortDir}\n onSortChange={controller.onSortChange}\n q={controller.q}\n onSearchChange={controller.onSearchChange}\n loading={loading && count === 0}\n getRowId={(entry) => entry.id}\n labels={{\n loading: t.loading,\n empty: t.empty,\n toolbar: { search: t.search },\n }}\n addButton={<AuditRefreshButton t={t} reload={reload} />}\n />\n </CardContent>\n </Card>\n );\n}\n\nfunction PurgeCard({\n t,\n title,\n description,\n confirmTitle,\n confirmBody,\n action,\n testId,\n}: {\n t: SecurityPanelLabels;\n title: string;\n description: string;\n confirmTitle: string;\n confirmBody: string;\n action: (retention: RetentionWindow) => Promise<PurgeResponse>;\n testId: string;\n}) {\n const [retention, setRetention] = React.useState<RetentionWindow>(\"1y\");\n const [confirming, setConfirming] = React.useState(false);\n const [pending, setPending] = React.useState(false);\n // Set on a 503 only. The purge may or may not have run, so the control is\n // locked until the operator explicitly acknowledges having checked: a purge\n // is not idempotent in its reporting, and a blind re-run would both delete\n // more than intended and report a count the operator would misread.\n const [outcomeUnknown, setOutcomeUnknown] = React.useState(false);\n\n const confirm = async () => {\n setPending(true);\n try {\n const result = await action(retention);\n setConfirming(false);\n accountToast.success({\n title: t.purged,\n description: `${t.purgedRemoved}: ${result.removed}`,\n });\n } catch (error) {\n if (error instanceof ApiError && error.status === 503) {\n setOutcomeUnknown(true);\n setConfirming(false);\n }\n // 429 (rate limited, not attempted), 503 (unknown) and the free-text 400\n // retention-floor rejection are all mapped by the package's\n // describeApiError; nothing is retried automatically here.\n accountToast.error(errorMessage(error, t.purgeFailed));\n } finally {\n setPending(false);\n }\n };\n\n const selectId = `${testId}-window`;\n\n return (\n <Card className=\"h-full\" data-account-purge={testId}>\n <CardHeader>\n <CardTitle className=\"text-base\">{title}</CardTitle>\n <CardDescription>{description}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"space-y-1\">\n <Label htmlFor={selectId}>{t.window}</Label>\n {/* Closed enum, never free text or a date: the service accepts only\n these five windows, and the list is derived from the package\n schema so it cannot drift from the contract. */}\n <select\n id={selectId}\n aria-label={t.window}\n className=\"h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50\"\n value={retention}\n onChange={(event) =>\n setRetention(event.target.value as RetentionWindow)\n }\n >\n {RetentionWindowSchema.options.map((option) => (\n <option key={option} value={option}>\n {t.windowLabels[option]}\n </option>\n ))}\n </select>\n </div>\n\n {outcomeUnknown ? (\n <div\n role=\"alert\"\n className=\"space-y-2 rounded-md border border-destructive/50 p-3 text-sm\"\n >\n <p className=\"font-medium\">{t.unknownOutcomeTitle}</p>\n <p className=\"text-muted-foreground\">{t.unknownOutcomeBody}</p>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n onClick={() => setOutcomeUnknown(false)}\n data-account-action=\"acknowledge-unknown\"\n >\n {t.unknownOutcomeAcknowledge}\n </Button>\n </div>\n ) : null}\n\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n disabled={pending || outcomeUnknown}\n onClick={() => setConfirming(true)}\n data-account-action=\"purge\"\n >\n <Trash2 className=\"size-3.5\" />\n {pending ? t.purging : t.purge}\n </Button>\n </CardContent>\n\n {/* Purges are never a one-click action: each goes through its own\n confirmation naming what is deleted and that a window below the\n service's retention floor is refused. */}\n <ConfirmDeleteDialog\n open={confirming}\n onOpenChange={(open) => {\n if (!open) setConfirming(false);\n }}\n title={confirmTitle}\n description={`${confirmBody} ${t.retentionFloorNotice}`}\n confirmLabel={t.purge}\n cancelLabel={t.cancel}\n pending={pending}\n onConfirm={() => {\n void confirm();\n }}\n />\n </Card>\n );\n}\n\nfunction PurgeSection({ t }: { t: SecurityPanelLabels }) {\n const { purgeAudit, purgeKeys } = useSecurityPurges();\n\n return (\n <Card>\n <CardHeader>\n <CardTitle>{t.purgeTitle}</CardTitle>\n <CardDescription>{t.purgeDescription}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{t.retentionFloorNotice}</p>\n <div className=\"grid auto-rows-fr gap-4 lg:grid-cols-2\">\n <PurgeCard\n t={t}\n testId=\"audit-log\"\n title={t.purgeAuditTitle}\n description={t.purgeAuditDescription}\n confirmTitle={t.purgeAuditConfirmTitle}\n confirmBody={t.purgeAuditConfirmBody}\n action={purgeAudit}\n />\n <PurgeCard\n t={t}\n testId=\"api-keys\"\n title={t.purgeKeysTitle}\n description={t.purgeKeysDescription}\n confirmTitle={t.purgeKeysConfirmTitle}\n confirmBody={t.purgeKeysConfirmBody}\n action={purgeKeys}\n />\n </div>\n </CardContent>\n </Card>\n );\n}\n\nexport function SecurityPanel({\n labels,\n}: {\n labels?: Partial<SecurityPanelLabels>;\n}) {\n const t = {\n ...DEFAULT_LABELS,\n ...labels,\n windowLabels: { ...DEFAULT_LABELS.windowLabels, ...labels?.windowLabels },\n };\n\n return (\n <div className=\"not-content flex w-full flex-col gap-6\">\n <AccountToastHost />\n {/* Admin tier: role hierarchy only, so a superadmin is admitted too. */}\n <RequireRole\n minimumRole=\"admin\"\n fallback={\n <p className=\"text-sm text-muted-foreground\">{t.adminRequired}</p>\n }\n >\n <AuditLogSection t={t} />\n </RequireRole>\n {/* Superadmin tier: dual evidence. Rendering nothing (not a message) for\n everyone else keeps the maintenance surface out of an admin's view. */}\n <RequireRole superuser>\n <PurgeSection t={t} />\n </RequireRole>\n </div>\n );\n}\n",
23
23
  "type": "registry:component",
24
24
  "target": "components/fa-auth/security-panel.tsx"
25
25
  }