auth

Main authentication module for my projects
git clone git://git.finwo.net/app/auth
Log | Files | Refs

commit a5b3bde50d2fcbce9cf3fed4214f44d2bd5fba22
parent 19fa74927f3df0c78a64274cfb2332f00e76922d
Author: finwo <finwo@pm.me>
Date:   Thu,  5 Nov 2026 23:02:28 +0100

Implemented admin realm management

Diffstat:
Mapp/admin/src/assets/admin.css | 127++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Aapp/admin/src/component/breadcrumb.tsx | 41+++++++++++++++++++++++++++++++++++++++++
Dapp/admin/src/component/settings-target-selector.tsx | 44--------------------------------------------
Mapp/admin/src/main.ts | 3+++
Mapp/admin/src/screen/admin.tsx | 180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Mapp/admin/src/screen/client-edit.tsx | 21+++++++--------------
Mapp/admin/src/screen/clients.tsx | 6++++++
Mapp/admin/src/screen/global-user.tsx | 16++--------------
Mapp/admin/src/screen/overview.tsx | 43+++++--------------------------------------
Aapp/admin/src/screen/realms.tsx | 613+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/screen/sessions.tsx | 6++++++
Mapp/admin/src/screen/settings.tsx | 48+++++++++++++++++++++++-------------------------
Mapp/admin/src/screen/system-settings.tsx | 24++++++------------------
Mapp/admin/src/screen/user.tsx | 16++--------------
Mapp/admin/src/screen/users.tsx | 6++++++
Mapp/admin/src/util/api.ts | 35+++++++++++++++++++++++++++++++++++
Mapp/admin/src/util/auth.ts | 19+++++++++++++++++++
Aapp/admin/src/util/navigation.ts | 41+++++++++++++++++++++++++++++++++++++++++
Mserver/src/lib/admin-realms.js | 8+++++---
Mserver/test/admin-realms.test.js | 12+++++++++++-
Mserver/test/http.test.js | 2++
21 files changed, 1074 insertions(+), 237 deletions(-)

diff --git a/app/admin/src/assets/admin.css b/app/admin/src/assets/admin.css @@ -17,40 +17,81 @@ line-height: 1.5; } -.realm-list { - display: grid; - gap: 0.25rem; - margin: 0; - padding: 0; - list-style: none; +.realm-meta { + display: block; + color: var(--muted); + font-size: 0.8125rem; + line-height: 1.4; } -.realm-link { - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: space-between; - gap: 0.5rem 1rem; - padding: 0.875rem 0.75rem; - background: var(--row); +.realm-meta > span { + display: inline; + margin-right: 0.75rem; +} + +.realm-meta > span:last-child { + margin-right: 0; +} + +.realm-display { color: inherit; text-decoration: none; } -.realm-link:hover { - background: var(--row-hover); +.realm-display:hover { + color: var(--accent-text-hover); +} + +.realm-slug, +.realm-owner-meta { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; } -.realm-name { - font-size: 0.9375rem; +.realm-owner-name { + display: block; font-weight: 500; line-height: 1.4; } -.realm-slug { +.realm-owner-meta { + display: block; + margin-top: 0.125rem; color: var(--muted); font-size: 0.8125rem; line-height: 1.4; + overflow-wrap: anywhere; +} + +.realm-table td.realm-action-column:not(:empty) { + padding-bottom: 0.75rem; +} + +.realm-row-action { + display: flex; + align-items: center; +} + +.realm-row-action .button-danger { + width: 100%; + white-space: nowrap; +} + +.realm-table-panel .table-actions { + width: 100%; + flex-direction: column; + align-items: stretch; +} + +.realm-table-panel .table-actions .button { + width: 100%; +} + +.realm-create-form .field-grid { + margin-top: 1rem; +} + +.realm-create-form .branding-preview { + margin-bottom: 1rem; } .session-stack { @@ -131,7 +172,7 @@ gap: 1rem; } -.client-breadcrumb { +.breadcrumb { display: flex; flex-wrap: wrap; align-items: center; @@ -142,7 +183,7 @@ line-height: 1.4; } -.client-breadcrumb a { +.breadcrumb a { color: var(--accent-text); text-decoration: none; } @@ -422,4 +463,48 @@ .field-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } + + .realm-meta { + display: flex; + flex-wrap: wrap; + gap: 0.25rem 0.75rem; + } + + .realm-meta > span { + margin-right: 0; + } + + .realm-table { + table-layout: fixed; + } + + .realm-table .table-icon-column { + width: 4rem; + } + + .realm-table .realm-owner-column { + width: 13rem; + } + + .realm-table .realm-action-column { + width: 12rem; + } + + .realm-row-action { + justify-content: flex-start; + } + + .realm-row-action .button-danger { + width: auto; + } + + .realm-table-panel .table-actions { + width: auto; + flex-direction: row; + align-items: center; + } + + .realm-table-panel .table-actions .button { + width: auto; + } } diff --git a/app/admin/src/component/breadcrumb.tsx b/app/admin/src/component/breadcrumb.tsx @@ -0,0 +1,41 @@ +import m from 'mithril'; +import { appUrl } from '../util/api'; + +export interface BreadcrumbItem { + label: string; + path?: string; +} + +interface BreadcrumbAttrs { + items: BreadcrumbItem[]; +} + +export const Breadcrumb: m.Component<BreadcrumbAttrs> = { + view({ attrs }) { + return ( + <div class="breadcrumb"> + {attrs.items.map((item, index) => { + const isCurrent = index === attrs.items.length - 1 || !item.path; + return [ + index > 0 ? <span aria-hidden="true">/</span> : null, + isCurrent ? ( + <span aria-current={index === attrs.items.length - 1 ? 'page' : undefined}> + {item.label} + </span> + ) : ( + <a + href={appUrl(item.path!)} + onclick={(event: Event) => { + event.preventDefault(); + m.route.set(item.path!); + }} + > + {item.label} + </a> + ), + ]; + })} + </div> + ); + }, +}; diff --git a/app/admin/src/component/settings-target-selector.tsx b/app/admin/src/component/settings-target-selector.tsx @@ -1,44 +0,0 @@ -import m from 'mithril'; -import { SelectMenu, type SelectMenuOption } from '@component/select-menu'; -import type { AdminRealm } from '../util/api'; - -interface SettingsTargetSelectorAttrs { - realms: AdminRealm[] | null; - selectedSystem: boolean; - selectedRealm: AdminRealm | null; - onchange: (target: string) => void; -} - -export const SettingsTargetSelector: m.Component<SettingsTargetSelectorAttrs> = { - view({ attrs }) { - const { realms, selectedSystem, selectedRealm } = attrs; - - if (!realms || realms.length === 0) { - if (selectedSystem) { - return <span class="realm-current">System branding</span>; - } - if (selectedRealm) { - return <span class="realm-current">{selectedRealm.display_name}</span>; - } - return null; - } - - const options: SelectMenuOption[] = [ - { value: 'system', label: 'System branding' }, - ...realms.map((realm) => ({ value: realm.slug, label: realm.display_name })), - ]; - - return ( - <div class="realm-select"> - <span>Settings</span> - <SelectMenu - autoWidth - ariaLabel="Settings" - value={selectedSystem ? 'system' : selectedRealm?.slug || ''} - options={options} - onchange={attrs.onchange} - /> - </div> - ); - }, -}; diff --git a/app/admin/src/main.ts b/app/admin/src/main.ts @@ -10,6 +10,9 @@ const routes: m.RouteDefs = { '/': { render: () => m(Admin, {}), }, + '/realms': { + render: () => m(Admin, {}), + }, '/sessions': { render: () => m(Admin, {}), }, diff --git a/app/admin/src/screen/admin.tsx b/app/admin/src/screen/admin.tsx @@ -1,4 +1,4 @@ -import { Activity, AppWindow, LayoutGrid, Settings, Users } from 'lucide'; +import { Activity, AppWindow, LayoutGrid, LibraryBig, Settings, Users } from 'lucide'; import m from 'mithril'; import { AppShell } from '@component/app-shell'; import { type NavItem } from '@component/nav'; @@ -18,7 +18,9 @@ import { startAdminLogin, } from '../util/auth'; import { appUrl, getAuthUrl, type AdminRealm, type UserInfo } from '../util/api'; +import { realmNavigation } from '../util/navigation'; import { OverviewPage } from './overview'; +import { RealmsPage } from './realms'; import { SessionsPage } from './sessions'; import { ClientEditPage } from './client-edit'; import { ClientsPage } from './clients'; @@ -124,6 +126,10 @@ function settingsRealm() { export const Admin: m.Component = { user: null as UserInfo | null, systemAdmin: false, + canCreateRealm: false, + adminAccessLoaded: false, + accountRedirecting: false, + routeGuardActive: false, realms: null as AdminRealm[] | null, realmsError: null as Error | null, error: null as Error | null, @@ -160,6 +166,7 @@ export const Admin: m.Component = { this.lastPath = path; this.mobileNavOpen = false; } + this.ensureRouteAccess(); this.updateTitle(); }, @@ -203,13 +210,18 @@ export const Admin: m.Component = { try { const me = await loadAdminMe(); this.systemAdmin = me.is_system_admin; + this.canCreateRealm = me.can_create_realm; + this.adminAccessLoaded = true; } catch (e: any) { if (e?.status === 401 || e?.status === 400) { await this.login(); return; } this.systemAdmin = false; + this.canCreateRealm = false; } + + this.ensureRouteAccess(); m.redraw(); }, @@ -228,28 +240,87 @@ export const Admin: m.Component = { }, async reloadRealms(this: any) { + let reloadFailed = false; + try { this.realms = await loadAdminRealms(); this.realmsError = null; } catch (e: any) { + reloadFailed = true; if (e?.status === 401 || e?.status === 400) { await this.login(); return; } this.realmsError = e as Error; } + + try { + const me = await loadAdminMe(); + this.systemAdmin = me.is_system_admin; + this.canCreateRealm = me.can_create_realm; + this.adminAccessLoaded = true; + } catch (e: any) { + reloadFailed = true; + if (e?.status === 401 || e?.status === 400) { + await this.login(); + return; + } + this.canCreateRealm = false; + this.adminAccessLoaded = false; + } + + if (!reloadFailed) { + this.ensureRouteAccess(); + } m.redraw(); }, + ensureRouteAccess(this: any) { + if (!this.realms || !this.adminAccessLoaded || this.accountRedirecting) return false; + + const path = currentPath(); + + if (this.realms.length === 0 && !this.canCreateRealm) { + this.accountRedirecting = true; + this.routeGuardActive = true; + clearAdminTokens(); + window.location.assign(`${this.authUrl}/app/account`); + return true; + } + + if ( + path === '/realms' && + this.realms.length === 1 && + !this.canCreateRealm + ) { + this.routeGuardActive = true; + m.route.set(`/settings/${encodeURIComponent(this.realms[0].slug)}`, null, { + replace: true, + }); + return true; + } + + if (path === '/system-settings' && !this.systemAdmin) { + this.routeGuardActive = true; + m.route.set('/', null, { replace: true }); + return true; + } + + this.routeGuardActive = false; + return false; + }, + updateTitle(this: any) { const path = currentPath(); + const realmsPath = path === '/realms'; const clients = path === '/clients' || path.startsWith('/clients/'); const sessions = path === '/sessions' || path.startsWith('/sessions/'); const users = path === '/users' || path.startsWith('/users/'); const systemSettings = path === '/system-settings'; const realmSettings = path === '/settings' || path.startsWith('/settings/'); - const settings = systemSettings || realmSettings; - const title = clients + const title = realmsPath + ? 'Realms | Administration' + : clients ? path.includes('/edit/') ? 'Edit client | Administration' : 'Clients | Administration' @@ -261,7 +332,7 @@ export const Admin: m.Component = { : 'Users | Administration' : systemSettings ? 'System settings | Administration' - : settings + : realmSettings ? 'Realm settings | Administration' : 'Administration'; document.title = title; @@ -282,12 +353,13 @@ export const Admin: m.Component = { view(this: any) { const user = this.user; const path = currentPath(); + const routeGuardActive = Boolean(this.routeGuardActive || this.accountRedirecting); + const realmsPath = path === '/realms'; const sessions = path === '/sessions' || path.startsWith('/sessions/'); const clients = path === '/clients' || path.startsWith('/clients/'); const users = path === '/users' || path.startsWith('/users/'); const systemSettings = path === '/system-settings'; const realmSettings = path === '/settings' || path.startsWith('/settings/'); - const settings = systemSettings || realmSettings; const realmSlug = sessionsRealm(); const clientRealmSlug = clientsRealm(); const userRealmSlug = usersRealm(); @@ -304,38 +376,51 @@ export const Admin: m.Component = { ? `/clients/${encodeURIComponent(firstRealm)}` : '/clients'; const usersHref = firstRealm ? `/users/${encodeURIComponent(firstRealm)}` : '/users'; - const settingsHref = this.systemAdmin - ? '/system-settings' - : firstRealm - ? `/settings/${encodeURIComponent(firstRealm)}` - : '/settings'; + const realmNav = realmNavigation(this.realms, Boolean(this.canCreateRealm)); const navItems: NavItem[] = [ { href: appUrl('/'), label: 'Overview', icon: LayoutGrid, - active: !sessions && !clients && !users && !settings, + active: path === '/', onclick: (event: Event) => { event.preventDefault(); m.route.set('/'); }, }, - { - href: appUrl(clientsHref), - label: 'Clients', - icon: AppWindow, - active: clients, + ]; + + if (realmNav.visible) { + navItems.push({ + href: appUrl(realmNav.href), + label: realmNav.label, + icon: LibraryBig, + active: realmsPath || realmSettings, onclick: (event: Event) => { event.preventDefault(); - m.route.set(clientsHref); + m.route.set(realmNav.href); }, - }, - { - href: appUrl(sessionsHref), - label: 'Sessions', - icon: Activity, - active: sessions, + }); + } + + if (firstRealm) { + navItems.push( + { + href: appUrl(clientsHref), + label: 'Clients', + icon: AppWindow, + active: clients, + onclick: (event: Event) => { + event.preventDefault(); + m.route.set(clientsHref); + }, + }, + { + href: appUrl(sessionsHref), + label: 'Sessions', + icon: Activity, + active: sessions, onclick: (event: Event) => { event.preventDefault(); m.route.set(sessionsHref); @@ -350,18 +435,22 @@ export const Admin: m.Component = { event.preventDefault(); m.route.set(usersHref); }, + } + ); + } + + if (this.systemAdmin) { + navItems.push({ + href: appUrl('/system-settings'), + label: 'Settings', + icon: Settings, + active: systemSettings, + onclick: (event: Event) => { + event.preventDefault(); + m.route.set('/system-settings'); }, - { - href: appUrl(settingsHref), - label: 'Settings', - icon: Settings, - active: settings, - onclick: (event: Event) => { - event.preventDefault(); - m.route.set(settingsHref); - }, - }, - ]; + }); + } return ( <AppShell @@ -424,8 +513,16 @@ export const Admin: m.Component = { </div> ) : null} - {!user ? ( + {!user || routeGuardActive || this.accountRedirecting ? ( <div class="loading">Loading session</div> + ) : realmsPath ? ( + <RealmsPage + realms={this.realms} + realmsError={this.realmsError} + canCreateRealm={Boolean(this.canCreateRealm)} + onAuthExpired={() => this.authExpired()} + onRealmsChanged={() => this.reloadRealms()} + /> ) : clients && clientEdit ? ( <ClientEditPage realmSlug={clientEdit.realmSlug} @@ -465,16 +562,13 @@ export const Admin: m.Component = { isGlobal={isGlobalUsers} /> ) : systemSettings ? ( - <SystemSettingsPage - realms={this.realms} - onAuthExpired={() => this.authExpired()} - /> + <SystemSettingsPage onAuthExpired={() => this.authExpired()} /> ) : realmSettings ? ( <SettingsPage realmSlug={settingsRealmSlug} realms={this.realms} realmsError={this.realmsError} - isSystemAdmin={Boolean(this.systemAdmin)} + canCreateRealm={Boolean(this.canCreateRealm)} onAuthExpired={() => this.authExpired()} onRealmsChanged={() => this.reloadRealms()} /> @@ -486,11 +580,7 @@ export const Admin: m.Component = { onAuthExpired={() => this.authExpired()} /> ) : ( - <OverviewPage - user={user} - realms={this.realms} - realmsError={this.realmsError} - /> + <OverviewPage user={user} /> )} </AppShell> ); diff --git a/app/admin/src/screen/client-edit.tsx b/app/admin/src/screen/client-edit.tsx @@ -5,6 +5,7 @@ import { brandingValidationErrorField, type BrandingField, } from '@util/branding'; +import { Breadcrumb } from '../component/breadcrumb'; import { RealmSelector } from '../component/realm-selector'; import { ClientForm, @@ -237,6 +238,12 @@ export const ClientEditPage: m.Component<ClientEditAttrs> = { return ( <div> + <Breadcrumb + items={[ + { label: 'Clients', path: `/clients/${encodeURIComponent(this.attrs.realmSlug || '')}` }, + { label: clientId || 'Unknown' }, + ]} + /> <PageHeader row title="Edit client" subtitle="OIDC client registration."> <RealmSelector realms={realms} @@ -247,20 +254,6 @@ export const ClientEditPage: m.Component<ClientEditAttrs> = { /> </PageHeader> - <div class="client-breadcrumb"> - <a - href={appUrl(`/clients/${encodeURIComponent(this.attrs.realmSlug || '')}`)} - onclick={(event: Event) => { - event.preventDefault(); - m.route.set(`/clients/${encodeURIComponent(this.attrs.realmSlug || '')}`); - }} - > - Clients - </a> - <span aria-hidden="true">/</span> - <span>{clientId || 'Unknown'}</span> - </div> - {realmsError ? ( <div class="alert" role="alert"> {realmsError.message} diff --git a/app/admin/src/screen/clients.tsx b/app/admin/src/screen/clients.tsx @@ -7,6 +7,7 @@ import { brandingValidationErrorField, type BrandingField, } from '@util/branding'; +import { Breadcrumb } from '../component/breadcrumb'; import { RealmSelector } from '../component/realm-selector'; import { ClientForm, @@ -91,6 +92,10 @@ export const ClientsPage: m.Component<ClientsAttrs> = { this.clients = []; this.loading = false; this.error = null; + if (!this.redirecting) { + this.redirecting = true; + m.route.set('/realms', null, { replace: true }); + } return; } @@ -226,6 +231,7 @@ export const ClientsPage: m.Component<ClientsAttrs> = { return ( <div> + <Breadcrumb items={[{ label: 'Clients' }]} /> <PageHeader row title="Clients" diff --git a/app/admin/src/screen/global-user.tsx b/app/admin/src/screen/global-user.tsx @@ -1,5 +1,6 @@ import m from 'mithril'; import { PageHeader } from '@component/page-header'; +import { Breadcrumb } from '../component/breadcrumb'; import { loadAdminGlobalUser } from '../util/auth'; import { appUrl, type AdminGlobalUserMembership, type AdminGlobalUserDetail } from '../util/api'; import { formatTime } from '@util/format'; @@ -69,6 +70,7 @@ export const GlobalUserPage: m.Component<GlobalUserAttrs> = { return ( <div> + <Breadcrumb items={[{ label: 'Users', path: '/users/global' }, { label: displayName }]} /> <PageHeader row title="User" subtitle="Global identity and realm memberships."> <a class="button-secondary" href={appUrl('/users/global')} onclick={(event: Event) => { event.preventDefault(); @@ -78,20 +80,6 @@ export const GlobalUserPage: m.Component<GlobalUserAttrs> = { </a> </PageHeader> - <div class="client-breadcrumb"> - <a - href={appUrl('/users/global')} - onclick={(event: Event) => { - event.preventDefault(); - m.route.set('/users/global'); - }} - > - Users - </a> - <span aria-hidden="true">/</span> - <span>{displayName}</span> - </div> - {realmsError ? ( <div class="alert" role="alert"> {realmsError.message} diff --git a/app/admin/src/screen/overview.tsx b/app/admin/src/screen/overview.tsx @@ -1,12 +1,11 @@ import m from 'mithril'; import { PageHeader } from '@component/page-header'; -import { appUrl, type AdminRealm, type UserInfo } from '../util/api'; +import { Breadcrumb } from '../component/breadcrumb'; +import { type UserInfo } from '../util/api'; import { getAdminTokens } from '../util/auth'; interface OverviewAttrs { user: UserInfo; - realms: AdminRealm[] | null; - realmsError: Error | null; } function roleLabel(user: UserInfo) { @@ -15,15 +14,13 @@ function roleLabel(user: UserInfo) { export const OverviewPage: m.Component<OverviewAttrs> = { view({ attrs }) { - const { user, realms, realmsError } = attrs; + const { user } = attrs; const tokens = getAdminTokens(); return ( <div> - <PageHeader - title="Overview" - subtitle="Provider summary and administration." - /> + <Breadcrumb items={[{ label: 'Overview' }]} /> + <PageHeader title="Overview" subtitle="Provider summary and administration." /> <div class="grid"> <section class="panel"> @@ -70,36 +67,6 @@ export const OverviewPage: m.Component<OverviewAttrs> = { </dl> </section> - <section class="panel panel-wide"> - <h2>Administration</h2> - {realmsError ? ( - <p class="note" role="alert"> - {realmsError.message} - </p> - ) : realms === null ? ( - <p class="note">Loading realms.</p> - ) : realms.length === 0 ? ( - <p class="note">No realms are available for this account.</p> - ) : ( - <ul class="realm-list"> - {realms.map((realm) => ( - <li> - <a - class="realm-link" - href={appUrl(`/sessions/${encodeURIComponent(realm.slug)}`)} - onclick={(event: Event) => { - event.preventDefault(); - m.route.set(`/sessions/${encodeURIComponent(realm.slug)}`); - }} - > - <span class="realm-name">{realm.display_name}</span> - <span class="realm-slug">{realm.slug}</span> - </a> - </li> - ))} - </ul> - )} - </section> </div> </div> ); diff --git a/app/admin/src/screen/realms.tsx b/app/admin/src/screen/realms.tsx @@ -0,0 +1,613 @@ +import { LibraryBig } from 'lucide'; +import m from 'mithril'; +import { Icon } from '@component/icon'; +import { Modal } from '@component/modal'; +import { PageHeader } from '@component/page-header'; +import { + brandingFromInput, + brandingValidationErrorField, + logoUrlError, + normalizePreviewColor, + validateBrandingFields, +} from '@util/branding'; +import { Breadcrumb } from '../component/breadcrumb'; +import { + createAdminRealm, + deleteAdminRealm, +} from '../util/auth'; +import { + appUrl, + type AdminRealm, +} from '../util/api'; + +interface RealmsAttrs { + realms: AdminRealm[] | null; + realmsError: Error | null; + canCreateRealm: boolean; + onAuthExpired: () => void; + onRealmsChanged: () => Promise<void>; +} + +interface RealmCreateValue { + display_name: string; + slug: string; + logo_url: string; + primary_color: string; +} + +type RealmCreateField = 'display_name' | 'slug' | 'logo_url' | 'primary_color'; + +interface RealmCreateValidation { + message: string; + field: RealmCreateField; +} + +const RESERVED_SLUGS = new Set(['admin', 'account', 'global']); +const SLUG_PATTERN = /^[a-z0-9][a-z0-9-]*$/; + +function defaultCreateValue(): RealmCreateValue { + return { + display_name: '', + slug: '', + logo_url: '', + primary_color: '', + }; +} + +function slugify(value: string) { + return value + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 63); +} + +function pluralCount(count: number, label: string) { + return `${count} ${label}${count === 1 ? '' : 's'}`; +} + +function realmCounts(realm: AdminRealm) { + return [ + pluralCount(realm.member_count, 'member'), + pluralCount(realm.host_count, 'host'), + pluralCount(realm.email_domain_count, 'domain'), + pluralCount(realm.client_count, 'client'), + ]; +} + +function ownerName(realm: AdminRealm) { + return realm.owner?.display_name || realm.owner?.username || 'Unassigned'; +} + +function ownerMeta(realm: AdminRealm) { + return realm.owner?.email || realm.owner?.username || 'No owner assigned'; +} + +function matchesSearch(realm: AdminRealm, term: string) { + if (!term) return true; + return [ + realm.display_name, + realm.slug, + ownerName(realm), + ownerMeta(realm), + ...realmCounts(realm), + ] + .join(' ') + .toLowerCase() + .includes(term); +} + +function validateCreate( + value: RealmCreateValue, + existingSlugs: Set<string> +): RealmCreateValidation | null { + const displayName = value.display_name.trim(); + const slug = value.slug.trim().toLowerCase(); + + if (!displayName) { + return { message: 'Display name is required.', field: 'display_name' }; + } + if (/[\r\n]/.test(value.display_name)) { + return { message: 'Display name must be a single line.', field: 'display_name' }; + } + if (displayName.length > 100) { + return { message: 'Display name must be 100 characters or fewer.', field: 'display_name' }; + } + if (!slug) { + return { message: 'Realm ID is required.', field: 'slug' }; + } + if (!SLUG_PATTERN.test(slug)) { + return { + message: 'Realm ID must use lowercase letters, numbers and hyphens.', + field: 'slug', + }; + } + if (slug.length > 63) { + return { message: 'Realm ID must be 63 characters or fewer.', field: 'slug' }; + } + if (RESERVED_SLUGS.has(slug)) { + return { message: `Realm ID ${slug} is reserved.`, field: 'slug' }; + } + if (existingSlugs.has(slug)) { + return { message: 'Realm ID already exists.', field: 'slug' }; + } + + return validateBrandingFields(value); +} + +function createFieldFromError(message: string | null | undefined): RealmCreateField | null { + if (!message) return null; + if (/realm slug|realm id/i.test(message)) return 'slug'; + if (/display_name|display name/i.test(message)) return 'display_name'; + return brandingValidationErrorField(message); +} + +export const RealmsPage: m.Component<RealmsAttrs> = { + attrs: null as RealmsAttrs | null, + search: '', + notice: null as string | null, + createOpen: false, + createValue: defaultCreateValue(), + createError: null as Error | string | null, + createInvalidField: null as RealmCreateField | null, + slugTouched: false, + creating: false, + deleteTarget: null as AdminRealm | null, + deleteConfirm: '', + deleteError: null as Error | null, + deleting: false, + + oninit(this: any, vnode: m.Vnode<RealmsAttrs>) { + this.attrs = vnode.attrs; + }, + + onupdate(this: any, vnode: m.Vnode<RealmsAttrs>) { + this.attrs = vnode.attrs; + }, + + resetCreate(this: any) { + this.createOpen = false; + this.createValue = defaultCreateValue(); + this.createError = null; + this.createInvalidField = null; + this.slugTouched = false; + this.creating = false; + }, + + resetDelete(this: any) { + this.deleteTarget = null; + this.deleteConfirm = ''; + this.deleteError = null; + this.deleting = false; + }, + + existingSlugs(this: any) { + return new Set((this.attrs?.realms || []).map((realm: AdminRealm) => realm.slug)); + }, + + openCreate(this: any) { + this.resetCreate(); + this.createOpen = true; + m.redraw(); + }, + + openDelete(this: any, realm: AdminRealm) { + this.resetDelete(); + this.deleteTarget = realm; + m.redraw(); + }, + + async submitCreate(this: any) { + const validationError = validateCreate(this.createValue, this.existingSlugs()); + if (validationError) { + this.createError = validationError.message; + this.createInvalidField = validationError.field; + m.redraw(); + return; + } + + this.creating = true; + this.createError = null; + this.createInvalidField = null; + m.redraw(); + + try { + const response = await createAdminRealm({ + slug: this.createValue.slug.trim().toLowerCase(), + display_name: this.createValue.display_name.trim(), + ...brandingFromInput(this.createValue), + }); + await this.attrs.onRealmsChanged(); + this.notice = `Realm ${response.realm.display_name} created.`; + this.resetCreate(); + } catch (e: any) { + if (e?.status === 401 || (e?.status === 400 && e?.code !== 'invalid_request')) { + this.attrs.onAuthExpired(); + return; + } + this.createError = e as Error; + this.createInvalidField = + e?.code === 'realm_slug_exists' ? 'slug' : createFieldFromError(e?.message); + } finally { + this.creating = false; + m.redraw(); + } + }, + + async submitDelete(this: any) { + const realm = this.deleteTarget; + if (!realm || this.deleteConfirm.trim() !== realm.slug || this.deleting) return; + + this.deleting = true; + this.deleteError = null; + m.redraw(); + + try { + await deleteAdminRealm(realm.slug); + await this.attrs.onRealmsChanged(); + this.notice = `Realm ${realm.display_name} deleted.`; + this.resetDelete(); + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.deleteError = e as Error; + } finally { + this.deleting = false; + m.redraw(); + } + }, + + view(this: any) { + const { realms, realmsError, canCreateRealm } = this.attrs; + const term = this.search.trim().toLowerCase(); + const visibleRealms = (realms || []).filter((realm: AdminRealm) => + matchesSearch(realm, term) + ); + const settingsPath = (realm: AdminRealm) => + `/settings/${encodeURIComponent(realm.slug)}`; + const previewLogo = logoUrlError(this.createValue.logo_url) + ? '' + : this.createValue.logo_url.trim(); + const previewColor = normalizePreviewColor(this.createValue.primary_color); + const deleteSlug = this.deleteTarget?.slug || ''; + const deleteConfirmationMatches = + Boolean(this.deleteTarget) && this.deleteConfirm.trim() === deleteSlug; + + return ( + <div> + <Breadcrumb items={[{ label: 'Realms' }]} /> + <PageHeader title="Realms" subtitle="Realm registry and administrative access." /> + + {realmsError ? ( + <div class="alert" role="alert"> + <p>{realmsError.message}</p> + <button + class="button-secondary" + type="button" + onclick={() => this.attrs.onRealmsChanged()} + > + Try again + </button> + </div> + ) : null} + + {this.notice ? ( + <div class="notice" role="status"> + {this.notice} + </div> + ) : null} + + {!realms ? ( + <div class="panel" aria-busy="true"> + <div class="skeleton skeleton-title"></div> + <div class="skeleton"></div> + <div class="skeleton skeleton-short"></div> + <div class="skeleton"></div> + <div class="skeleton skeleton-short"></div> + </div> + ) : ( + <section class="table-panel realm-table-panel"> + <h2 class="sr-only">Realm registry</h2> + <div class="table-toolbar"> + <div class="table-search"> + <input + type="search" + value={this.search} + aria-label="Search realms" + placeholder="Search realms" + oninput={(event: Event) => { + this.search = (event.target as HTMLInputElement).value; + }} + /> + </div> + <div class="table-actions"> + {canCreateRealm ? ( + <button class="button" type="button" onclick={() => this.openCreate()}> + Register realm + </button> + ) : null} + </div> + </div> + + <div class="data-table-wrap"> + <table class="data-table realm-table"> + <thead> + <tr> + <th class="table-icon-column" scope="col"> + <span class="sr-only">Realm</span> + </th> + <th class="data-table-primary realm-name-column" scope="col">Realm</th> + <th class="realm-owner-column" scope="col">Owner</th> + <th class="realm-action-column" scope="col">Actions</th> + </tr> + </thead> + <tbody> + {visibleRealms.map((realm: AdminRealm) => { + const href = settingsPath(realm); + return ( + <tr + tabindex="0" + onclick={() => m.route.set(href)} + onkeydown={(event: KeyboardEvent) => { + if (event.target !== event.currentTarget) return; + if (event.key !== 'Enter' && event.key !== ' ') return; + event.preventDefault(); + m.route.set(href); + }} + > + <td class="table-icon-column"> + <span class="table-icon" aria-hidden="true"> + {Icon(LibraryBig)} + </span> + </td> + <td class="data-table-primary realm-name-column"> + <a + class="realm-display" + href={appUrl(href)} + onclick={(event: MouseEvent) => { + event.preventDefault(); + event.stopPropagation(); + m.route.set(href); + }} + > + {realm.display_name} + </a> + <span class="realm-meta"> + <span class="realm-slug">{realm.slug}</span> + {realmCounts(realm).map((count) => ( + <span class="realm-count">{count}</span> + ))} + </span> + </td> + <td class="realm-owner-column" data-label="Owner"> + <span class="realm-owner-name">{ownerName(realm)}</span> + <span class="realm-owner-meta">{ownerMeta(realm)}</span> + </td> + <td class="realm-action-column"> + {realm.can_delete ? ( + <div class="realm-row-action"> + <button + class="button-danger" + type="button" + onclick={(event: MouseEvent) => { + event.stopPropagation(); + this.openDelete(realm); + }} + > + Delete realm + </button> + </div> + ) : null} + </td> + </tr> + ); + })} + </tbody> + </table> + {realms.length > 0 && visibleRealms.length === 0 ? ( + <div class="empty"> + <p>No realms match this search.</p> + </div> + ) : realms.length === 0 ? ( + <div class="empty"> + <p>No realms are available for this account.</p> + </div> + ) : null} + </div> + </section> + )} + + {this.createOpen ? ( + <Modal title="Register a realm" onClose={() => this.resetCreate()}> + <form + class="realm-create-form" + onsubmit={(event: Event) => { + event.preventDefault(); + this.submitCreate(); + }} + > + {this.createError ? ( + <div class="alert" role="alert"> + {typeof this.createError === 'string' + ? this.createError + : this.createError.message} + </div> + ) : null} + + <div class="form-field"> + <span class="field-label">Display name</span> + <input + class="field-control" + value={this.createValue.display_name} + maxlength="100" + placeholder="Acme Inc" + data-modal-autofocus + disabled={this.creating} + aria-invalid={this.createInvalidField === 'display_name' ? 'true' : null} + oninput={(event: Event) => { + const value = (event.target as HTMLInputElement).value; + this.createValue.display_name = value; + if (!this.slugTouched) { + this.createValue.slug = slugify(value); + } + this.createError = null; + this.createInvalidField = null; + }} + /> + </div> + + <div class="form-field"> + <span class="field-label">Realm ID</span> + <input + class="field-control" + value={this.createValue.slug} + maxlength="63" + placeholder="acme" + spellcheck="false" + disabled={this.creating} + aria-invalid={this.createInvalidField === 'slug' ? 'true' : null} + oninput={(event: Event) => { + this.createValue.slug = (event.target as HTMLInputElement).value; + this.slugTouched = true; + this.createError = null; + this.createInvalidField = null; + }} + /> + </div> + <p class="modal-note"> + Lowercase letters, numbers and hyphens. admin, account and global are reserved. + </p> + + <div class="field-grid"> + <div class="form-field"> + <span class="field-label">Logo URL</span> + <input + class="field-control" + type="url" + value={this.createValue.logo_url} + placeholder="https://app.example.test/logo.svg" + maxlength="2048" + disabled={this.creating} + aria-invalid={this.createInvalidField === 'logo_url' ? 'true' : null} + oninput={(event: Event) => { + this.createValue.logo_url = (event.target as HTMLInputElement).value; + this.createError = null; + this.createInvalidField = null; + }} + /> + </div> + + <div class="form-field"> + <span class="field-label">Primary color</span> + <input + class="field-control" + value={this.createValue.primary_color} + placeholder="#25a" + maxlength="7" + spellcheck="false" + disabled={this.creating} + aria-invalid={this.createInvalidField === 'primary_color' ? 'true' : null} + oninput={(event: Event) => { + this.createValue.primary_color = (event.target as HTMLInputElement).value; + this.createError = null; + this.createInvalidField = null; + }} + /> + </div> + </div> + + <div class="branding-preview" aria-hidden="true"> + <span class={`branding-logo-preview${previewLogo ? '' : ' is-empty'}`}> + {previewLogo ? ( + <img + src={previewLogo} + alt="" + onerror={(event: Event) => { + (event.target as HTMLImageElement).style.visibility = 'hidden'; + }} + /> + ) : null} + </span> + <span + class={`branding-color-preview${previewColor ? '' : ' is-empty'}`} + style={previewColor ? { background: previewColor } : {}} + ></span> + </div> + + <div class="modal-actions"> + <button + class="button-secondary" + type="button" + disabled={this.creating} + onclick={() => this.resetCreate()} + > + Cancel + </button> + <button class="button" type="submit" disabled={this.creating}> + {this.creating ? 'Creating' : 'Create realm'} + </button> + </div> + </form> + </Modal> + ) : null} + + {this.deleteTarget ? ( + <Modal title="Delete realm" onClose={() => this.resetDelete()}> + <p class="modal-note"> + Delete {this.deleteTarget.display_name} ({deleteSlug})? Realm settings, clients, + hosts, email domains, sessions, consents, refresh tokens and memberships will be + permanently removed. Users remain global accounts; home-realm users return to no + home realm. + </p> + {this.deleteError ? ( + <div class="alert" role="alert"> + {this.deleteError.message} + </div> + ) : null} + + <div class="form-field"> + <span class="field-label">Confirm realm ID</span> + <input + class="field-control" + value={this.deleteConfirm} + maxlength="63" + placeholder={deleteSlug} + autocomplete="off" + spellcheck="false" + data-modal-autofocus + disabled={this.deleting} + oninput={(event: Event) => { + this.deleteConfirm = (event.target as HTMLInputElement).value; + this.deleteError = null; + }} + /> + </div> + <p class="modal-note">Type the realm ID exactly to confirm.</p> + + <div class="modal-actions"> + <button + class="button-secondary" + type="button" + disabled={this.deleting} + onclick={() => this.resetDelete()} + > + Cancel + </button> + <button + class="button-danger" + type="button" + disabled={!deleteConfirmationMatches || this.deleting} + onclick={() => this.submitDelete()} + > + {this.deleting ? 'Deleting' : 'Delete realm'} + </button> + </div> + </Modal> + ) : null} + </div> + ); + }, +}; diff --git a/app/admin/src/screen/sessions.tsx b/app/admin/src/screen/sessions.tsx @@ -1,5 +1,6 @@ import m from 'mithril'; import { PageHeader } from '@component/page-header'; +import { Breadcrumb } from '../component/breadcrumb'; import { RealmSelector } from '../component/realm-selector'; import type { AdminRealm, AdminSession } from '../util/api'; import { @@ -51,6 +52,10 @@ export const SessionsPage: m.Component<SessionsAttrs> = { this.sessions = []; this.loading = false; this.error = null; + if (!this.redirecting) { + this.redirecting = true; + m.route.set('/realms', null, { replace: true }); + } return; } @@ -136,6 +141,7 @@ export const SessionsPage: m.Component<SessionsAttrs> = { return ( <div> + <Breadcrumb items={[{ label: 'Sessions' }]} /> <PageHeader row title="Sessions" diff --git a/app/admin/src/screen/settings.tsx b/app/admin/src/screen/settings.tsx @@ -7,8 +7,9 @@ import { normalizePreviewColor, validateBrandingFields, } from '@util/branding'; +import { Breadcrumb } from '../component/breadcrumb'; import { RealmSelector } from '../component/realm-selector'; -import { SettingsTargetSelector } from '../component/settings-target-selector'; +import { realmBreadcrumbItems } from '../util/navigation'; import { loadAdminRealmSettings, updateAdminRealmSettings } from '../util/auth'; import type { AdminRealm, AdminRealmSettings } from '../util/api'; @@ -16,7 +17,7 @@ interface SettingsAttrs { realmSlug: string | null; realms: AdminRealm[] | null; realmsError: Error | null; - isSystemAdmin: boolean; + canCreateRealm: boolean; onAuthExpired: () => void; onRealmsChanged: () => Promise<void>; } @@ -108,6 +109,10 @@ export const SettingsPage: m.Component<SettingsAttrs> = { this.settings = null; this.loading = false; this.error = null; + if (!this.redirecting) { + this.redirecting = true; + m.route.set('/realms', null, { replace: true }); + } return; } @@ -212,37 +217,30 @@ export const SettingsPage: m.Component<SettingsAttrs> = { }, view(this: any) { - const { realms, realmsError, realmSlug, isSystemAdmin } = this.attrs; + const { realms, realmsError, realmSlug } = this.attrs; const selected = realms?.find((realm) => realm.slug === realmSlug) || realms?.[0] || null; const previewLogo = logoUrlError(this.form.logo_url) ? '' : this.form.logo_url.trim(); const previewColor = normalizePreviewColor(this.form.primary_color); + const breadcrumbRealm = selected?.slug || realmSlug || ''; return ( <div> - <PageHeader row title="Realm settings" subtitle="Realm name, branding, and login behavior."> - {isSystemAdmin ? ( - <SettingsTargetSelector - realms={realms} - selectedSystem={false} - selectedRealm={selected} - onchange={(target: string) => { - if (target === 'system') { - m.route.set('/system-settings'); - return; - } - m.route.set(`/settings/${encodeURIComponent(target)}`); - }} - /> - ) : ( - <RealmSelector - realms={realms} - selected={selected} - onchange={(slug: string) => { - m.route.set(`/settings/${encodeURIComponent(slug)}`); - }} - /> + <Breadcrumb + items={realmBreadcrumbItems( + realms, + Boolean(this.attrs.canCreateRealm), + selected?.display_name || breadcrumbRealm )} + /> + <PageHeader row title="Realm settings" subtitle="Realm name, branding, and login behavior."> + <RealmSelector + realms={realms} + selected={selected} + onchange={(slug: string) => { + m.route.set(`/settings/${encodeURIComponent(slug)}`); + }} + /> </PageHeader> {realmsError ? ( diff --git a/app/admin/src/screen/system-settings.tsx b/app/admin/src/screen/system-settings.tsx @@ -1,6 +1,6 @@ import m from 'mithril'; import { PageHeader } from '@component/page-header'; -import { SettingsTargetSelector } from '../component/settings-target-selector'; +import { Breadcrumb } from '../component/breadcrumb'; import { brandingFromInput, brandingValidationErrorField, @@ -9,10 +9,9 @@ import { validateBrandingFields, } from '@util/branding'; import { loadAdminSystemSettings, updateAdminSystemSettings } from '../util/auth'; -import type { AdminRealm, AdminSystemSettings } from '../util/api'; +import type { AdminSystemSettings } from '../util/api'; interface SystemSettingsAttrs { - realms: AdminRealm[] | null; onAuthExpired: () => void; } @@ -123,27 +122,16 @@ export const SystemSettingsPage: m.Component<SystemSettingsAttrs> = { }, view(this: any) { - const realms = this.attrs?.realms || null; const previewLogo = logoUrlError(this.form.logo_url) ? '' : this.form.logo_url.trim(); const previewColor = normalizePreviewColor(this.form.primary_color); return ( <div> + <Breadcrumb items={[{ label: 'Settings' }]} /> <PageHeader - row - title="System branding" - subtitle="Global logo and primary color for the identity provider." - > - <SettingsTargetSelector - realms={realms} - selectedSystem - selectedRealm={null} - onchange={(target: string) => { - if (target === 'system') return; - m.route.set(`/settings/${encodeURIComponent(target)}`); - }} - /> - </PageHeader> + title="System settings" + subtitle="Provider branding for authentication surfaces." + /> {this.error ? ( <div class="alert" role="alert"> diff --git a/app/admin/src/screen/user.tsx b/app/admin/src/screen/user.tsx @@ -2,6 +2,7 @@ import m from 'mithril'; import { Modal } from '@component/modal'; import { PageHeader } from '@component/page-header'; import { SelectMenu } from '@component/select-menu'; +import { Breadcrumb } from '../component/breadcrumb'; import { RealmSelector } from '../component/realm-selector'; import { createAdminUserBan, @@ -341,6 +342,7 @@ export const UserPage: m.Component<UserAttrs> = { return ( <div> + <Breadcrumb items={[{ label: 'Users', path: usersHref }, { label: displayName }]} /> <PageHeader row title="User" subtitle="Account, consent and app restrictions."> <RealmSelector realms={realms} @@ -351,20 +353,6 @@ export const UserPage: m.Component<UserAttrs> = { /> </PageHeader> - <div class="client-breadcrumb"> - <a - href={appUrl(usersHref)} - onclick={(event: Event) => { - event.preventDefault(); - m.route.set(usersHref); - }} - > - Users - </a> - <span aria-hidden="true">/</span> - <span>{displayName}</span> - </div> - {realmsError ? ( <div class="alert" role="alert"> {realmsError.message} diff --git a/app/admin/src/screen/users.tsx b/app/admin/src/screen/users.tsx @@ -3,6 +3,7 @@ import m from 'mithril'; import { Icon } from '@component/icon'; import { Modal } from '@component/modal'; import { PageHeader } from '@component/page-header'; +import { Breadcrumb } from '../component/breadcrumb'; import { RealmSelector } from '../component/realm-selector'; import { addAdminRealmMember, @@ -102,6 +103,10 @@ export const UsersPage: m.Component<UsersAttrs> = { this.users = []; this.loading = false; this.error = null; + if (!this.redirecting) { + this.redirecting = true; + m.route.set('/realms', null, { replace: true }); + } return; } @@ -228,6 +233,7 @@ export const UsersPage: m.Component<UsersAttrs> = { return ( <div> + <Breadcrumb items={[{ label: 'Users' }]} /> <PageHeader row title="Users" diff --git a/app/admin/src/util/api.ts b/app/admin/src/util/api.ts @@ -5,9 +5,42 @@ import type { Discovery, TokenResponse, UserInfo } from '@api/oidc'; export type { ApiError, Discovery, TokenResponse, UserInfo }; +export interface AdminRealmOwner { + id: string; + username: string | null; + display_name: string | null; + email: string | null; +} + export interface AdminRealm { slug: string; display_name: string; + owner: AdminRealmOwner | null; + host_count: number; + email_domain_count: number; + client_count: number; + member_count: number; + created_at: number; + updated_at: number; + can_edit: boolean; + can_delete: boolean; +} + +export interface AdminRealmCreateInput { + slug: string; + display_name: string; + logo_url?: string | null; + primary_color?: string | null; +} + +export interface AdminRealmCreateResponse { + ok: boolean; + realm: AdminRealm; +} + +export interface AdminRealmDeleteResponse { + ok: boolean; + removed: boolean; } export interface AdminRealmSettings { @@ -199,6 +232,8 @@ export interface AdminMeUser { display_name: string; email: string | null; is_system_admin: boolean; + home_realm_slug: string | null; + can_create_realm: boolean; } export interface AdminGlobalUser { diff --git a/app/admin/src/util/auth.ts b/app/admin/src/util/auth.ts @@ -13,6 +13,9 @@ import { type AdminGlobalUserDetail, type AdminMeUser, type AdminRealm, + type AdminRealmCreateInput, + type AdminRealmCreateResponse, + type AdminRealmDeleteResponse, type AdminRealmSettings, type AdminRealmSettingsInput, type AdminRealmUser, @@ -69,6 +72,22 @@ export async function loadAdminRealms(): Promise<AdminRealm[]> { return response.realms; } +export async function createAdminRealm( + input: AdminRealmCreateInput +): Promise<AdminRealmCreateResponse> { + return adminJson<AdminRealmCreateResponse>('/api/v1/admin/realms', { + method: 'POST', + body: JSON.stringify(input), + }); +} + +export async function deleteAdminRealm(realmSlug: string): Promise<AdminRealmDeleteResponse> { + const realm = encodeURIComponent(realmSlug); + return adminJson<AdminRealmDeleteResponse>(`/api/v1/admin/realms/${realm}`, { + method: 'DELETE', + }); +} + export async function loadAdminSessions(realmSlug: string): Promise<AdminSession[]> { const realm = encodeURIComponent(realmSlug); const response = await adminJson<{ sessions: AdminSession[] }>( diff --git a/app/admin/src/util/navigation.ts b/app/admin/src/util/navigation.ts @@ -0,0 +1,41 @@ +import type { AdminRealm } from './api'; + +export interface RealmNavigation { + visible: boolean; + label: string; + href: string; + isPlural: boolean; +} + +export function realmNavigation( + realms: AdminRealm[] | null, + canCreateRealm: boolean +): RealmNavigation { + const realmCount = realms?.length || 0; + const singleRealmOnly = realmCount === 1 && !canCreateRealm; + const firstSlug = realms?.[0]?.slug || ''; + + return { + visible: realmCount > 0 || canCreateRealm, + label: singleRealmOnly ? 'Realm' : 'Realms', + href: singleRealmOnly + ? `/settings/${encodeURIComponent(firstSlug)}` + : '/realms', + isPlural: !singleRealmOnly, + }; +} + +export function realmBreadcrumbItems( + realms: AdminRealm[] | null, + canCreateRealm: boolean, + realmSlug: string +) { + const navigation = realmNavigation(realms, canCreateRealm); + return [ + { + label: navigation.label, + ...(navigation.isPlural ? { path: '/realms' } : {}), + }, + { label: realmSlug }, + ]; +} diff --git a/server/src/lib/admin-realms.js b/server/src/lib/admin-realms.js @@ -11,7 +11,7 @@ import { } from './realm.js'; import { destroySessionById } from './session.js'; import { listAdminRealms } from './system-clients.js'; -import { assignRole, ensureMembership } from './users.js'; +import { assignRole, ensureMembership, getPrimaryEmail } from './users.js'; const CREATE_ALLOWED_FIELDS = new Set(['slug', 'display_name', 'logo_url', 'primary_color']); @@ -73,12 +73,14 @@ export function normalizeCreateRealmInput(body) { return { slug, displayName, branding }; } -function serializeOwner(ownerUserId, owner) { +async function serializeOwner(systemDb, ownerUserId, owner) { if (!ownerUserId) return null; + const email = await getPrimaryEmail(systemDb, ownerUserId); return { id: ownerUserId, username: owner?.username || null, display_name: owner?.display_name || null, + email: email?.email || null, }; } @@ -116,7 +118,7 @@ export async function loadAdminRealmDetail(systemDb, realm, actor) { return { slug: realm.slug, display_name: settings.display_name, - owner: serializeOwner(realm.owner_user_id, owner), + owner: await serializeOwner(systemDb, realm.owner_user_id, owner), host_count: await countRealmRows(systemDb, 'realm_hosts', realm.id), email_domain_count: await countRealmRows(systemDb, 'realm_email_domains', realm.id), client_count: await countRealmRows(systemDb, 'client_realms', realm.id), diff --git a/server/test/admin-realms.test.js b/server/test/admin-realms.test.js @@ -16,7 +16,7 @@ import { listAdminRealmsDetail, normalizeCreateRealmInput, } from '../src/lib/admin-realms.js'; -import { createUser, getUserRoles } from '../src/lib/users.js'; +import { addUserEmail, createUser, getUserRoles } from '../src/lib/users.js'; async function withRealmRegistry(fn) { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'auth-admin-realms-')); @@ -86,6 +86,10 @@ test('createAdminRealm assigns creator ownership, membership and realm-admin rol displayName: 'Creator', isSystemAdmin: true, }); + await addUserEmail(systemDb, actorId, 'creator@example.test', { + verified: true, + primary: true, + }); const actor = { id: actorId, status: 'active', is_system_admin: 1 }; const realm = await createAdminRealm({ @@ -108,6 +112,7 @@ test('createAdminRealm assigns creator ownership, membership and realm-admin rol id: actorId, username: 'creator', display_name: 'Creator', + email: 'creator@example.test', }); const row = await findRealmBySlug('acme'); @@ -156,6 +161,10 @@ test('listAdminRealmsDetail includes owned realms and owner deletion permission' isSystemAdmin: true, }); const ownerId = await createUser(systemDb, { username: 'owner' }); + await addUserEmail(systemDb, ownerId, 'owner@example.test', { + verified: true, + primary: true, + }); await createAdminRealm({ systemDb, actor: { id: adminId, status: 'active', is_system_admin: 1 }, @@ -176,6 +185,7 @@ test('listAdminRealmsDetail includes owned realms and owner deletion permission' id: ownerId, username: 'owner', display_name: 'owner', + email: 'owner@example.test', }); assert.equal(listed[0].member_count, 2); }); diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -2720,6 +2720,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { id: userId(env, 'admin'), username: 'admin', display_name: 'System Admin', + email: 'admin@system.test', }); const realmRow = withSystemDatabase(env, (database) => @@ -2773,6 +2774,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { id: ownerId, username: 'contractor', display_name: 'Contractor', + email: 'contractor@personal.test', }); const ownerSettings = await adminRequest(ownerAdmin, {