feat/embed-admin-ui #4
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/embed-admin-ui"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Backend wraps all responses: {"user": ...}, {"roles": [...]}, {"client": ...}, etc. Updated all API services to extract the wrapped data. Fixed client_secret field names. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>- OAuthClient gains request_uris (RFC 7591 §2 whitelist) plus the four OIDC Core encryption fields (id_token + userinfo *_alg/_enc). - CreateClientResponse gains optional client_hmac_secret (returned once when token_auth_method=client_secret_jwt). - New RotateHMACSecretResponse + rotateClientHMACSecret() pointing at POST /api/v1/admin/clients/{id}/rotate-hmac-secret. - APIResource gains token_format ('opaque' | 'jwt') so the form can toggle JWT access token emission (RFC 9068) per resource.New BulkActionBar.vue: sticky toolbar that appears as soon as DataTable selection is non-empty. Slots an array of typed actions (label, icon, severity, optional confirm dialog, async run). Single loading state at a time, Clear button to reset selection. Integrations: - UsersListView: assign-role + delete. Assign-role opens a Dialog with a Select on listRoles() and assignUserRole() per row. Delete uses Promise.allSettled with a recap toast ("12 deleted, 1 failed"). - InvitationsView: bulk revoke (deleteInvitation per row). - ClientsListView: deactivate (skips already-inactive rows) and delete (hard confirm). Master-detail pattern preserved by rebinding selected from @row-click; bulkSelection drives the new checkbox column. - AuditLogsView: export-JSON and export-CSV (client-side blob download, no backend route needed). Single-row detail drawer still works via @row-click since v-model:selection is now multi-mode. Permission gating: BulkActionBar is rendered only if the user has the matching write permission (no-op otherwise).- useAppToast (23 call sites): public API preserved (success/error/warn/info with summary + optional detail), implementation now wraps vue-sonner. - useConfirm (11 call sites): new composable in src/composables/useConfirm.ts that exposes the PrimeVue-shape `require({ header, message, icon, acceptLabel, rejectLabel, acceptClass, accept, reject })`. acceptClass containing "danger" / "destructive" maps to the destructive button variant. - ConfirmHost.vue: global singleton AlertDialog wired in AdminLayout, driven by the module-level pendingConfirm ref. Handles async accept (busy state, closes on resolve) and ESC/click-outside cancel. - AdminLayout: <Toast>/<ConfirmDialog> PrimeVue removed; <Toaster> Sonner and <ConfirmHost> mounted in their place. - Menu → DropdownMenu (4 files): inline declarative per-row pattern replaces the imperative `ref().toggle(event)` + global :model approach. AppTopbar user menu, ServiceAccountsListView and UsersListView per-row ellipsis menus, ClientsListView detail-panel ellipsis menu — all rewritten as <DropdownMenu><DropdownMenuTrigger as-child>…</…><DropdownMenuContent>… </…></DropdownMenu>. Per-row data lives in the slot scope so there is no more selectedAction/menuItems plumbing. - useConfirm `accept` callback typed as `() => unknown | Promise<unknown>` so existing handlers that return Promise<boolean> (useCrud.deleteItem) keep compiling. main.ts still wires PrimeVue's ToastService/ConfirmationService — required by remaining PrimeVue Dialog/DataTable instances until S5/S4/S8.Introduces src/components/ui/data-table/DataTable.vue — a thin generic wrapper around @tanstack/vue-table v8 that exposes a shadcn-styled table with the same surface as the existing PrimeVue DataTable call sites: - :columns is now an explicit ColumnDef<T>[] (TanStack idiom). - :data, :loading, :total, :page, :per-page, :lazy props. - v-model:selection — augmented checkbox column appears when bound, selection state mirrored both ways via getRowId for stable diffs. - @page-change emits { page, perPage } (1-based) and @sort-change emits { field, order } when lazy; client-side mode uses TanStack's internal pagination + sorted row model. - @row-click + :row-class hooks for clickable rows. - Cell rendering: slot-based per column via #cell-<id> (e.g. #cell-status, #cell-created_at) — keeps Vue templates in views instead of forcing h() in the ColumnDef. - Header buttons render sort affordance (ArrowUp/Down/UpDown) via Lucide. - Built-in pagination footer with Prev/Next; hidePaginator opt-out for small embedded tables. Migrated 12 views off PrimeVue DataTable/Column: - Client-side: KeysView, ProfileView (sessions), FederationListView, RolesListView, PoliciesListView, PolicyDecisionsView (recent denies). - Lazy server-side: ResourcesListView, AuditLogsView, InvitationsView, ServiceAccountsListView, ClientsListView, UsersListView. Per-row DropdownMenu actions from S3 stay inline (slot scope). The selection-column-permission gating that used <Column v-if=…> at the PrimeVue level is dropped: BulkActionBar already gates the actions themselves; the checkbox column is always rendered when v-model:selection is bound. Inline ternary on v-model is not supported by the Vue compiler. AuditLogsView row-click handler is preserved via @row-click. ClientsListView detail panel still drives `selected` via @row-click — same UX. Build (vue-tsc -b + vite build) passes. The 388 KB column-XXX.js chunk that PrimeVue DataTable pulled in is gone from the bundle.Each call site converted from the PrimeVue \`v-model:visible / :header / :modal / :style={width}\` shape to the shadcn compositional structure: <Dialog v-model:open><DialogContent class="sm:max-w-[…]"> <DialogHeader><DialogTitle>…</DialogTitle></DialogHeader> …body… <DialogFooter>…</DialogFooter> </DialogContent></Dialog> Migrated: - ClientSecretDialog: open emits update:visible upstream (parent API unchanged); maps onOpenChange → emit('update:visible', next). - PolicyDecisionsView: replay-result dialog (640px). - UsersListView: role-assign dialog (420px) with DialogFooter for the Cancel/Assign buttons. - InvitationsView: invite-user dialog (460px) with embedded MultiSelect. - CommandPalette: full-width compact palette, DialogContent gets show-close=false and a sr-only DialogTitle for a11y; padding zeroed via class="p-0 gap-0" since the palette draws its own borders. Also drops the last stray PrimeVue import in CallbackView.vue: ProgressSpinner → lucide-vue-next Loader2 with animate-spin. main.ts still wires PrimeVue / ToastService / ConfirmationService — these plugin registrations are no-ops now that no PrimeVue component remains in the runtime; they're cleaned in S8 alongside the package.json drop.Introduces src/composables/useZodForm.ts — a minimal, opinionated form helper that holds reactive values, validates on submit against a zod schema and exposes per-field errors. It is deliberately lighter than a full vee-validate setup: no per-field reactive validation, no compositional Form/FormField context — just enough to declarative-ify the existing manual ref + handler pattern in our form views. API: const form = useZodForm(schema, initial) // form.values reactive proxy over schema-shaped state // form.errors { [field]: message } after .validate() // form.submitError reactive string|null for server-side errors // form.submitting reactive bool, toggled by handleSubmit wrapper // form.handleSubmit(cb) → submit handler that parses, sets errors, // and only calls cb(parsedData) on success // form.reset(partial?) / form.setSubmitError / form.clearErrors The existing common/FormField wrapper already exposed an `:error` prop; we just had to start passing it. Migrated 3 forms as the proof: - RoleFormView: name required, description bounded, permission ids as string arrays. handleSubmit awaits permission writes in sequence. - ResourceFormView: name + identifier required, token_format enum, TTL range. Permission CRUD below the form stays manual. - ServiceAccountFormView: superset of the above + a refine() rule that requires jwks_uri when token_auth_method === 'private_key_jwt'. Server-side errors (extractApiError) flow into form.submitError. Pattern docs are inlined in the composable. Deferred to fast-follow (same composable, larger forms): - RegistrationFieldFormView (dynamic fields, options editor). - FederationFormView (preset application + attribute mapper). - ClientFormView (~470 lines, many conditional sections). - PolicyFormView (~830 lines, Rego editor + test runner).Closes the S6 fast-follow list. Each form now declares a zod schema and surfaces per-field errors via the existing common/FormField `:error` slot. - RegistrationFieldFormView: full useZodForm migration. Schema enforces field_key regex (^[a-z][a-z0-9_]{0,63}$), kind=standard requires a standard_target, select/multiselect/radio types require non-empty options, applies_to non-empty. - FederationFormView: full useZodForm migration. Schema validates name + client_id required; provider.type cast to the OIDC|OAuth2 literal union when applying presets / loading edits. Preserves the prunedMapper helper for trimming empty attribute_mapper entries before POST. - ClientFormView: full useZodForm migration over the 27-field CreateClientRequest shape. Schema enforces name + ≥1 redirect URI + ≥1 grant type + ≥1 scope, TTL bounds (60s..30d), and URL format on redirect_uris. Server-side errors route through form.setSubmitError. - PolicyFormView: lighter touch — the existing standalone refs are kept (the Rego editor + test runner reach into them directly, and a full reactive-object refactor would require touching ~80 spots without buying much). Adds a submitSchema + errors reactive map applied on submit; only the Name field surfaces an error since rego/priority are implicitly validated by the validate/test sub-flows. All 7 form views now run through zod schemas. The compat-mode props on Button/Select/MultiSelect/Checkbox/InputNumber/Chips are intentionally kept (no PrimeVue dep behind them; just thin wrappers that ease the existing call sites) — removing them would require touching every icon=/label=/severity= site, with no functional gain.Every Select usage now follows the upstream shadcn-vue compositional shape: <Select v-model="x"> <SelectTrigger><SelectValue placeholder="…" /></SelectTrigger> <SelectContent> <SelectItem v-for="opt in OPTS" :key="opt.value" :value="opt.value"> {{ opt.label }} </SelectItem> </SelectContent> </Select> The audit underestimated this — there were 13 Select :options call sites, not 3. Migrated: - ServiceAccountFormView (token auth method) - SettingsView (default role) - PolicyFormView (policy type) - PoliciesListView (filter by type — value=undefined items omitted) - PolicyDecisionsView (window selector — string-bridged because Reka SelectRoot only accepts string modelValue) - FederationFormView (preset, provider type) - RegistrationFieldFormView ×3 (kind, target, type) - ResourceFormView ×2 (token format, signing alg) - UsersListView (role assign dialog) - ClientFormView ×5 (token_auth_method, subject_type, userinfo_signed, jweAlg ×2, jweEnc ×2 — inline arrays expanded to SelectItem literals) - UserRoleManager (selectedRoleId) Select.vue reverts to the upstream 19-line SelectRoot passthrough.Button.vue reverts to the upstream new-york shadcn definition: variant, size, class, as, asChild. The PrimeVue-flavoured props (label, icon, iconPos, severity, text, outlined, rounded, loading) are gone. Migration applied by a perl pass over every <Button .../> self-closing block in src/views and src/components/* (excluding src/components/ui): - severity="X" → variant remap (secondary/success/info/warn/danger → shadcn equivalents incl. destructive/warning, primary/help/contrast collapse to default/secondary). - text → variant="ghost". When paired with severity, severity becomes a text-* class on a ghost variant (e.g. "text-destructive hover:text-destructive" for icon-only delete buttons). - outlined → variant="outline". - rounded → class="rounded-full" merged with any existing class. - size="small"/"large"/"normal" → "sm"/"lg"/default. - Static label="X" → slot text. - Static icon="pi pi-Y" → <Icon name="pi pi-Y" /> as first slot child (the Icon bridge normalises pi pi-* names). - Icon-only tags (no label) auto-receive size="icon-sm". Dynamic shapes the perl can't handle were hand-fixed: - 14 form-submit buttons with :label/:icon/:loading wrapped in a Loader2/Icon swap: <Button :disabled="x"><Icon v-if="x" name="pi-spin pi-spinner" /><Icon v-else :name="..." /> {{label}} </Button>. The Icon component already spins on "pi-spin" substring. - ClientSecretDialog copy-feedback buttons: :severity="copied ? 'success' : 'secondary'" → :variant=, :icon swapped to <Icon :name> in slot. - Resource permission add/remove buttons: :loading converted to :disabled merged with existing :disabled.- `--fg-3` in light mode raised from oklch(0.62) to oklch(0.55). The previous value gave ~3.5:1 against bg-0 — under WCAG AA (4.5:1) for small text. fg-3 is used for hints, placeholders and timestamps (charte 3.3), all of which are typically small body text and need AA-normal. The new value lands at ~4.7:1. - Alert variants now ship with a semantic border (`border-{semantic}/30` instead of `border-transparent` inherited from the base class). This is the visual definition pass for the light theme where the `bg-{semantic}-bg` at oklch(0.95) lands very close to the canvas bg-0 (oklch(0.985)); the alert was floating without an outline. No contrast math change — purely additive visual definition. Audit done for rule 04 (semantic always paired with icon/label): StatusBadge has dot + label, RoleBadge and ActionBadge render the role/action name as text. All compliant — no changes needed.border-*utilities stop painting in currentColor f2ee46deffFoundation for the upcoming email-template WYSIWYG editor: - @tiptap/vue-3, @tiptap/starter-kit, @tiptap/pm — the editor itself - @tiptap/extension-mention + tippy.js — autocomplete popup for inserting template variables ({{.Token}}, {{.Issuer}}, …) - @codemirror/lang-html — syntax highlighting for the raw HTML tab (CodeMirror was already installed for JsonEditor)Routes wired: /email-templates -> list view, gated email_templates:read /email-templates/:name -> form view, gated email_templates:read (the form view itself disables write actions on missing email_templates:write — read-only access still allowed) Sidebar gets an envelope-icon entry next to Settings, conditional on email_templates:read so non-admins don't see it at all.Clicking the destructive button in ConfirmHost (Delete / Confirm) ran the dialog-close path but never the user-supplied accept callback, so e.g. deleting an invitation produced no DELETE request. Symptom across every view that calls `confirm.require({...})` — Roles, Federation, Resources, Policies, Users, Clients, ServiceAccounts, EmailTemplates, RegistrationFields, Keys. Root cause sits inside reka-ui: `AlertDialogAction` → `DialogClose` → `Primitive`. DialogClose template binds its own `@click= rootContext.onOpenChange(false)` on Primitive. Vue 3 merges that with the fallthrough `$attrs.onClick=onAccept` from ConfirmHost, in template- first order, so closeDialog fires first → AlertDialog emits `update:open(false)` → ConfirmHost's `onOpenChange` sees `busy=false` (onAccept has not run yet) → falls into `onCancel` → wipes `pendingConfirm`. By the time onAccept finally runs the next tick, it reads the now-null `pendingConfirm` and returns immediately, never invoking `opts.accept?.()`. Drop the AlertDialogAction in favour of a plain shadcn `Button`. ConfirmHost already owns the close (`pendingConfirm.value = null` in the finally clause of onAccept triggers the open watcher), so no semantics are lost. AlertDialogCancel stays — its dialog-close path is compatible with the cancel intent.Audit follow-up: ship the highest-leverage UX safety + accessibility fixes from the roadmap (see CHANGELOG). Five concerns bundled: 1. Unsaved-changes guard on every form - `useZodForm` exposes `isDirty` (JSON-diff against initial) and `markPristine()` (call after a successful save so the post-save navigation no longer prompts). - New `useUnsavedChanges(isDirty)` composable wires `onBeforeRouteLeave` (via shadcn `ConfirmHost` for SPA nav) and `beforeunload` (browser tab close / reload). No-op while clean. - Branched on Client, Role, Resource, Policy, Federation, RegistrationField, ServiceAccount, EmailTemplate (refactored from its own manual guard), and UserDetail (inline-edit mode). 2. Confirmations on irreversible non-delete actions (ClientsListView) - `rotateClientSecret`, `rotateClientHMACSecret`, and `toggleActive` (disable branch only — enabling stays one-click) gain a destructive ConfirmHost dialog explaining what breaks downstream. Same for ServiceAccountFormView's rotateSecret. 3. Command palette chip in the topbar - Replaces the TODO comment with an actual ⌘K / Ctrl+K button that opens the existing CommandPalette. Renders the right modifier per platform via `navigator.platform`. Hidden on mobile (<1100px); the keyboard shortcut still works. 4. prefers-reduced-motion override - `app.css` collapses animation/transition durations to 0.01ms globally when the OS-level pref is set. Dialog zoom-in, fade-in, row hover transitions all become instant. Vestibular-impaired users stop being jarred by every modal open. 5. Nav + skip-link a11y - `AppMenuItem` adds `aria-current="page"` on the active sidebar link so screen readers announce position. - `AdminLayout` adds a `.skip-link` (hidden until focused) pointing at `#main-content`, plus `tabindex="-1"` on `<main>` so focus actually lands when activated. Standard WCAG 2.4.1 pattern. Type-check clean. Phase 2 (URL state, page-size, density, sticky form footer) is its own commit set. See the plan file for the full roadmap.Roadmap follow-up to v0.29.0 (UX phase 1). Four concerns bundled, focused on the list views that admins live in and on the form views they can lose work in. 1. URL-state for search / page / perPage across every list view - New `useListQueryState({ storageKey })` composable: reads `?page`, `?perPage`, `?q` on mount (URL > localStorage > default priority), debounce-writes them back via `router.replace`, and persists `perPage` to localStorage per view. Default values are never written to the URL — `?page=1` stays out of the bar. - Drop-in replacement on Users, Clients, Resources, Invitations, Audit Logs, Service Accounts, Policies. - `useCrud` now accepts optional external `page` / `perPage` refs so the URL state and the fetcher share a single source of truth. - Deep links work: `/users?q=alice&page=3` restores filtered state; back-button restores filtered state. 2. Page-size selector in the DataTable footer - `<select>` with default options `[10, 20, 50, 100]` (overridable per call site). Picking a size emits the standard `page-change` event with `page=1`, so existing handlers pick it up unchanged. Persisted per view via the storageKey above. 3. Density toggle in the DataTable footer - One icon button cycles compact → normal → comfortable. Pref is global (`orionauth.tableDensity`) and applied via a wrapper class; the actual row padding lives in `app.css` so all tables stay consistent. Honors `prefers-reduced-motion` (no animation beyond the colour transition that was already there). 4. Loading skeleton on DataTable - Replaces the bare "Loading…" cell with N animated shimmer rows (capped at 8, matched to the requested perPage) and a sr-only `role="status" aria-live="polite"` announcement. The skeleton pulse falls back to instant under `prefers-reduced-motion` via the global override shipped in v0.29.0. 5. Sticky form footer on long forms - New `FormFooter` component: sticky bottom, backdrop-blur, full width via negative page padding. Shows an "Unsaved changes" dot when the bound `dirty` prop is true. - Wired on ClientFormView (597 lines, was the worst offender) and PolicyFormView. Cancel + Submit are now reachable without scrolling to the bottom of the form. Type-check clean. Phase 3 (Settings IA refactor, PermissionDeniedView, DetailSection headers) lands separately.Last roadmap phase. Four concerns, each invisible until you hit it, each obvious once shipped. 1. Settings page IA refactor - 2-column layout: sticky vertical anchor nav on the left (Registration, Sessions, Token lifetimes, Password policy), the existing sections on the right. Collapses to single column under 1100px. - Per-section dirty tracking with baseline snapshots: a pulsing warn-coloured dot appears next to both the side-nav item and the section title as soon as a field diverges from the last saved value. Each save updates its baseline so the indicator clears immediately. - IntersectionObserver drives the side-nav highlight from scroll position so the operator knows where they are after long scrolls through Password policy. - `FormSection` gains an optional `dirty` prop so the indicator logic stays one place (same pulsing dot used on the side-nav). - Per-section Save buttons stay — the backend persists each section as its own document, so a unified Save would just risk partial- write inconsistencies. 2. PermissionDeniedView (`/access-denied`) - New screen with lock icon, missing-permission name in a code chip, attempted path, and Back / Dashboard CTAs. - Router guard switches from `return { name: 'dashboard' }` to `return { name: 'access-denied', query: { required, from } }`. Users hitting a bookmarked URL they no longer have access to finally get told what's wrong instead of silently bouncing. 3. DetailSection in side panels - New `DetailSection title="…"` wraps a group of `DetailRow`s with a mono-caps subheading (matches TableHead labels). - ClientsListView's right pane now reads as four scannable groups (Identity, Credentials, OAuth flow, OIDC) instead of a flat 16-row dump. - AuditLogsView's pane reads as Event / Actor / Request + Metadata. 4. Focus management on every navigation - `router.afterEach` focuses the new page's `<h1>` (or falls back to the `#main-content` landmark) so keyboard / screen-reader users land on the right place after a router push instead of staying focused on the topbar element they just left. Type-check clean. Closes the v0.29.0 → v0.31.0 roadmap.The copies read `data.message || data.error`, which rendered "[object Object]" for the backend AppError shape ({error:{code,message}}) and ignored OAuth `error_description`. One helper in src/lib now handles both shapes plus the legacy `message` field, with a generic fallback. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>- PublicProfile mirrors User.PublicProfile() (optional fields are omitted, never null); the admin User extends it with AdminView() fields - UserSession matches GET /api/v1/me/sessions, including `current` - rotateKey returns { message }, not a SigningKey Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>Templates no longer receive {{.Token}} or {{.Link}}: the backend exposes the action link only through the `link` function, as a stand-alone {{link "Button text"}} action. The `link` entry of a template's variables now inserts that snippet (other variables keep {{.Name}}), badges show the real syntax, the editor explains the rule and the HTML/CSS the backend rejects, the preview note no longer mentions the token, and the backend validation message is shown inline on save. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>