auth

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

commit 16a41ca021698287a0b47daceac0c9b52123f14e
parent 842219fb65369264729f18da74e42a456e9e773a
Author: finwo <finwo@pm.me>
Date:   Thu, 22 Oct 2026 20:04:14 +0200

Added admin session UI and mobile-first layout

Diffstat:
Mapp/admin/src/assets/admin.css | 510++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mapp/admin/src/main.ts | 8++++++++
Mapp/admin/src/screen/admin.tsx | 215+++++++++++++++++++++++++++++++++++++++++++++++++------------------------------
Aapp/admin/src/screen/overview.tsx | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/src/screen/sessions.tsx | 354+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/util/api.ts | 29+++++++++++++++++++++++++++++
Mapp/admin/src/util/auth.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/src/util/format.ts | 14++++++++++++++
Aapp/admin/src/util/theme.ts | 39+++++++++++++++++++++++++++++++++++++++
Aserver/src/controller/admin/realms/list.js | 15+++++++++++++++
Mserver/src/lib/admin-auth.js | 9++++++++-
Mserver/src/lib/system-clients.js | 19++++++++++++++++++-
Mserver/test/http.test.js | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13 files changed, 1268 insertions(+), 174 deletions(-)

diff --git a/app/admin/src/assets/admin.css b/app/admin/src/assets/admin.css @@ -1,6 +1,7 @@ :root { font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; --admin-canvas: #f3f3f3; + --admin-page: #fff; --admin-surface: #fff; --admin-sidebar: #000; --admin-sidebar-active: #333; @@ -10,9 +11,18 @@ --admin-accent: #25a; --admin-accent-hover: #2a66cc; --admin-accent-active: #1b468c; + --admin-accent-text: #25a; + --admin-accent-text-hover: #2a66cc; + --admin-accent-text-active: #1b468c; + --admin-on-accent: #fff; --admin-menu-hover: #8884; + --admin-row: #00000008; + --admin-row-hover: #0000000d; + --admin-skeleton: #00000012; --admin-danger: #c9190b; + --admin-field-line: rgba(0, 0, 0, 0.42); --admin-shadow: 0 0.125em 0.25em #0008; + --admin-hex: url('./hex-grid-light.svg'); } *, @@ -33,6 +43,13 @@ body { -webkit-font-smoothing: antialiased; } +button, +input, +select, +textarea { + font: inherit; +} + .admin-app { min-height: 100vh; background: var(--admin-canvas); @@ -68,6 +85,7 @@ body { } .admin-brand-name { + color: #fff; font-size: 1.125rem; font-weight: 500; line-height: 1.3; @@ -75,26 +93,28 @@ body { .admin-body { display: grid; - grid-template-columns: 15rem minmax(0, 1fr); + grid-template-columns: minmax(0, 1fr); + grid-template-rows: auto minmax(0, 1fr); min-height: calc(100vh - 3.5rem); } .admin-sidebar { display: flex; flex-direction: column; - min-height: calc(100vh - 3.5rem); + min-height: auto; background: var(--admin-sidebar); color: #fff; } .admin-nav { display: flex; - flex: 1; - flex-direction: column; + flex-direction: row; + flex-wrap: wrap; padding: 0.75rem 0; } .admin-nav-label { + display: none; margin: 0; padding: 0.5rem 1.5rem; color: rgba(255, 255, 255, 0.46); @@ -106,9 +126,11 @@ body { .admin-nav-item { display: flex; + flex: none; align-items: center; + justify-content: center; gap: 0.75rem; - width: 100%; + width: auto; padding: 0.6875rem 1.5rem; color: rgba(255, 255, 255, 0.82); font-size: 0.875rem; @@ -118,6 +140,10 @@ body { user-select: none; } +.admin-nav-item span { + display: none; +} + .admin-nav-item svg { flex: none; width: 1.125rem; @@ -144,16 +170,74 @@ body { width: 100%; max-width: 72rem; margin: 0 auto; - padding: 1.75rem 2rem 3rem; + padding: 1.75rem clamp(1rem, 4vw, 2rem) 3rem; +} + +.admin-page-header { + margin-bottom: 1.5rem; +} + +.admin-page-header h1 { + margin: 0; + font-size: 1.5rem; + font-weight: 400; + line-height: 1.3; +} + +.admin-page-header p { + margin: 0.25rem 0 0; + color: var(--admin-muted); + font-size: 0.875rem; + line-height: 1.5; +} + +.admin-page-header-row { + display: grid; + grid-template-columns: minmax(0, 1fr); + align-items: start; + gap: 1rem; +} + +.admin-realm-select { + display: grid; + gap: 0.25rem; +} + +.admin-realm-select > span { + color: var(--admin-muted); + font-size: 0.75rem; + line-height: 1.4; +} + +.admin-realm-select select { + width: 100%; + padding: 0.5rem 0.75rem; + border: 0; + border-bottom: 1pt solid var(--admin-field-line); + border-radius: 0; + background: var(--admin-surface); + color: inherit; + font: inherit; + font-size: 0.875rem; + line-height: 1.5; +} + +.admin-realm-current { + color: var(--admin-muted); + font-size: 0.875rem; + line-height: 1.5; } .admin-grid { display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-template-columns: minmax(0, 1fr); gap: 1rem; } -.admin-panel { +.admin-panel, +.admin-session, +.admin-session-skeleton { + min-width: 0; padding: 1.5rem; background: var(--admin-surface); box-shadow: var(--admin-shadow); @@ -164,7 +248,8 @@ body { margin-top: 1rem; } -.admin-panel h2 { +.admin-panel h2, +.admin-session h2 { margin: 0 0 1.25rem; font-size: 1.0625rem; font-weight: 500; @@ -179,7 +264,7 @@ body { .admin-definition > div { display: grid; - grid-template-columns: 8.5rem minmax(0, 1fr); + grid-template-columns: minmax(0, 1fr); gap: 1rem; } @@ -210,11 +295,211 @@ body { line-height: 1.5; } +.admin-alert p { + margin: 0 0 0.5rem; +} + +.admin-notice { + margin: 0 0 1rem; + padding: 0.75rem 1rem; + background: var(--admin-row); + color: var(--admin-text); + font-size: 0.875rem; + line-height: 1.5; +} + .admin-loading { color: var(--admin-muted); font-size: 0.875rem; } +.admin-empty { + padding: 1.5rem; + background: var(--admin-surface); + box-shadow: var(--admin-shadow); +} + +.admin-empty p { + margin: 0; + color: var(--admin-muted); + font-size: 0.875rem; + line-height: 1.6; +} + +.admin-realm-list { + display: grid; + gap: 0.25rem; + margin: 0; + padding: 0; + list-style: none; +} + +.admin-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(--admin-row); + color: inherit; + text-decoration: none; +} + +.admin-realm-link:hover { + background: var(--admin-row-hover); +} + +.admin-realm-name { + font-size: 0.9375rem; + font-weight: 500; + line-height: 1.4; +} + +.admin-realm-slug { + color: var(--admin-muted); + font-size: 0.8125rem; + line-height: 1.4; +} + +.admin-session-stack { + display: grid; + gap: 1rem; +} + +.admin-session-header { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; +} + +.admin-session-header h2 { + margin: 0; +} + +.admin-session-user { + margin: 0.25rem 0 0; + color: var(--admin-muted); + font-size: 0.8125rem; + line-height: 1.4; +} + +.admin-session-badge { + color: var(--admin-danger); + font-size: 0.75rem; + line-height: 1.4; +} + +.admin-session-details { + margin-top: 1.25rem; +} + +.admin-session-agent { + margin: 0.75rem 0 0; + color: var(--admin-muted); + font-size: 0.75rem; + line-height: 1.5; + overflow-wrap: anywhere; +} + +.admin-session-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + margin-top: 1.25rem; +} + +.admin-confirm { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + color: var(--admin-muted); + font-size: 0.875rem; + line-height: 1.5; +} + +.admin-button, +.admin-button-secondary, +.admin-button-danger { + display: inline-block; + padding: 0.625rem 1.25rem; + border: 0; + border-radius: 0; + background: var(--admin-accent); + color: var(--admin-on-accent); + font: inherit; + font-size: 0.8125rem; + font-weight: 500; + letter-spacing: 0.05em; + line-height: 1.4; + text-align: center; + text-decoration: none; + text-transform: uppercase; + cursor: pointer; +} + +.admin-button:hover { + background: var(--admin-accent-hover); +} + +.admin-button:active { + background: var(--admin-accent-active); +} + +.admin-button-secondary { + background: transparent; + color: var(--admin-accent-text); +} + +.admin-button-secondary:hover { + background: var(--admin-row-hover); + color: var(--admin-accent-text-hover); +} + +.admin-button-secondary:active { + background: var(--admin-row); + color: var(--admin-accent-text-active); +} + +.admin-button-danger { + background: var(--admin-danger); + color: #fff; +} + +.admin-button-danger:hover { + background: var(--admin-danger); + filter: brightness(1.08); +} + +.admin-button:disabled, +.admin-button-secondary:disabled, +.admin-button-danger:disabled { + cursor: default; + opacity: 0.55; +} + +.admin-skeleton { + height: 0.75rem; + background: var(--admin-skeleton); +} + +.admin-skeleton + .admin-skeleton { + margin-top: 0.75rem; +} + +.admin-skeleton-title { + width: 8rem; + height: 1rem; +} + +.admin-skeleton-short { + width: 35%; +} + .admin-user-menu { position: relative; } @@ -289,9 +574,13 @@ body { gap: 0.75rem; width: 100%; padding: 0.625rem 1rem; + border: 0; + background: transparent; color: rgba(255, 255, 255, 0.82); + font: inherit; font-size: 0.875rem; line-height: 1.4; + text-align: left; text-decoration: none; cursor: pointer; user-select: none; @@ -308,61 +597,89 @@ body { color: #fff; } +.admin-user-menu-value { + margin-left: auto; + color: rgba(255, 255, 255, 0.56); + font-size: 0.75rem; +} + .admin-status-page { + display: grid; + place-items: center; min-height: 100vh; - display: flex; - justify-content: center; - align-items: flex-start; - padding: 12vh 1.5rem 3rem; - background: #fff; - color: #1b1b1b; + padding: 0; + background: var(--admin-surface); + color: var(--admin-text); } .admin-status-panel { - width: min(24rem, 100%); + position: relative; + width: min(calc(100% - 2rem), 28rem); padding: 2rem; - background: #fff; + background: var(--admin-surface); } .admin-status-panel h1 { - margin: 0 0 1.5rem; + margin: 0 0 1rem; + padding-right: 3rem; font-size: 1.5rem; font-weight: 400; line-height: 1.3; } +.admin-status-icon { + position: absolute; + top: 2rem; + right: 2rem; + width: 2rem; + height: 2rem; + color: currentColor; +} + +.admin-spinner { + position: absolute; + top: 2rem; + right: 2rem; + width: 2rem; + height: 2rem; + border: 0.1875rem solid var(--admin-skeleton); + border-top-color: var(--admin-text); + border-radius: 50%; + animation: admin-spin 1s linear infinite; +} + +@keyframes admin-spin { + to { + transform: rotate(360deg); + } +} + .admin-status-note { margin: 0; - color: rgba(0, 0, 0, 0.6); + color: var(--admin-muted); font-size: 0.875rem; - line-height: 1.5; + line-height: 1.6; } .admin-status-error { margin: 0; color: var(--admin-danger); font-size: 0.875rem; - line-height: 1.5; -} - -.admin-status-link { - display: inline-block; - margin-top: 1rem; - color: var(--admin-accent); - font-size: 0.875rem; -} - -.admin-status-link:hover { - color: var(--admin-accent-hover); - text-decoration: none; + line-height: 1.6; } -.admin-status-link:active { - color: var(--admin-accent-active); +.admin-status-actions { + display: flex; + justify-content: flex-end; + align-items: center; + gap: 1rem; + margin-top: 1.5rem; } .admin-app a:focus-visible, +.admin-app button:focus-visible, .admin-app summary:focus-visible, +.admin-app select:focus-visible, .admin-status-page a:focus-visible { outline: 2pt solid var(--admin-accent); outline-offset: 2pt; @@ -370,8 +687,8 @@ body { @media (min-width: 35em) { .admin-status-page { - background-color: #fff; - background-image: url('./hex-grid-light.svg'); + background-color: var(--admin-page); + background-image: var(--admin-hex); background-position: center; background-repeat: no-repeat; background-size: cover; @@ -382,95 +699,104 @@ body { } } -@media (max-width: 60em) { - .admin-body { - grid-template-columns: minmax(0, 1fr); +@media (min-width: 40em) { + .admin-nav-item span { + display: inline; } - .admin-sidebar { - min-height: auto; + .admin-definition > div { + grid-template-columns: 8.5rem minmax(0, 1fr); } - .admin-nav { - flex-direction: row; - flex-wrap: wrap; - padding: 0; + .admin-page-header-row { + grid-template-columns: minmax(0, 1fr) auto; } - .admin-nav-label { - display: none; + .admin-realm-select select { + width: auto; } +} - .admin-nav-item { - width: auto; - flex: 1; - justify-content: center; +@media (min-width: 60em) { + .admin-body { + grid-template-columns: 15rem minmax(0, 1fr); + grid-template-rows: minmax(0, 1fr); } - .admin-grid { - grid-template-columns: minmax(0, 1fr); + .admin-sidebar { + min-height: calc(100vh - 3.5rem); } - .admin-panel-wide { - margin-top: 0; + .admin-nav { + flex: 1; + flex-direction: column; + flex-wrap: nowrap; } -} -@media (max-width: 37.5em) { - .admin-topbar { - padding: 0 1rem; + .admin-nav-label { + display: block; } - .admin-content { - padding: 1.25rem 1rem 2rem; + .admin-nav-item { + width: 100%; + justify-content: flex-start; } - .admin-nav-item span { - display: none; + .admin-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); } +} - .admin-definition > div { - grid-template-columns: minmax(0, 1fr); - gap: 0.125rem; +@media (prefers-reduced-motion: reduce) { + .admin-spinner { + animation: none; } } @media (prefers-color-scheme: dark) { - :root { + :root:not([data-theme]) { --admin-canvas: #181818; + --admin-page: #000; --admin-surface: #282828; --admin-sidebar: #000; --admin-sidebar-active: #333; --admin-topbar: #000; --admin-text: #e7e7e7; --admin-muted: #a0a4a8; + --admin-accent-text: #4d8dff; + --admin-accent-text-hover: #6ea8ff; + --admin-accent-text-active: #3b7cff; + --admin-row: #ffffff0d; + --admin-row-hover: #ffffff14; + --admin-skeleton: #ffffff14; --admin-danger: #f28b82; - } - - body { + --admin-field-line: rgba(255, 255, 255, 0.42); + --admin-hex: url('./hex-grid-dark.svg'); color-scheme: dark; } +} - .admin-status-page { - background-color: #222; - color: #fff; - } - - .admin-status-panel { - background-color: #222; - } - - .admin-status-note { - color: rgba(255, 255, 255, 0.6); - } +:root[data-theme="light"] { + color-scheme: light; } -@media (min-width: 35em) and (prefers-color-scheme: dark) { - .admin-status-page { - background-color: #222; - background-image: url('./hex-grid-dark.svg'); - background-position: center; - background-repeat: no-repeat; - background-size: cover; - } +:root[data-theme="dark"] { + --admin-canvas: #181818; + --admin-page: #000; + --admin-surface: #282828; + --admin-sidebar: #000; + --admin-sidebar-active: #333; + --admin-topbar: #000; + --admin-text: #e7e7e7; + --admin-muted: #a0a4a8; + --admin-accent-text: #4d8dff; + --admin-accent-text-hover: #6ea8ff; + --admin-accent-text-active: #3b7cff; + --admin-row: #ffffff0d; + --admin-row-hover: #ffffff14; + --admin-skeleton: #ffffff14; + --admin-danger: #f28b82; + --admin-field-line: rgba(255, 255, 255, 0.42); + --admin-hex: url('./hex-grid-dark.svg'); + color-scheme: dark; } diff --git a/app/admin/src/main.ts b/app/admin/src/main.ts @@ -1,6 +1,7 @@ import m from 'mithril'; import { Admin, AdminCallback } from './screen/admin'; import { getBasePath } from './util/api'; +import { applyTheme, getTheme } from './util/theme'; import './assets/admin.css'; @@ -8,10 +9,17 @@ const routes: m.RouteDefs = { '/': { render: () => m(Admin, {}), }, + '/sessions': { + render: () => m(Admin, {}), + }, + '/sessions/:realm': { + render: () => m(Admin, {}), + }, '/callback': { render: () => m(AdminCallback, {}), }, }; +applyTheme(getTheme()); m.route.prefix = getBasePath(); m.route(document.body, '/', routes); diff --git a/app/admin/src/screen/admin.tsx b/app/admin/src/screen/admin.tsx @@ -1,28 +1,60 @@ import m from 'mithril'; -import { CircleUserRound, Hexagon, LayoutGrid, LogOut, Settings } from 'lucide'; +import { + Activity, + CircleAlert, + CircleUserRound, + Hexagon, + LayoutGrid, + LogOut, + Settings, + Sun, +} from 'lucide'; import { adminSignOut, + clearAdminTokens, completeAdminLogin, getAdminTokens, + loadAdminRealms, loadAdminUser, startAdminLogin, } from '../util/auth'; -import { appUrl, getAuthUrl, type UserInfo } from '../util/api'; +import { appUrl, getAuthUrl, type AdminRealm, type UserInfo } from '../util/api'; import { icon } from '../util/icon'; +import { applyTheme, cycleTheme, getTheme, themeLabel, type Theme } from '../util/theme'; +import { OverviewPage } from './overview'; +import { SessionsPage } from './sessions'; + +function currentPath() { + return (m.route.get() || '/').split('?')[0]; +} -function roleLabel(user: UserInfo) { - return user.is_system_admin ? 'System administrator' : 'Realm administrator'; +function sessionsRealm() { + const path = currentPath(); + if (!path.startsWith('/sessions/')) return null; + try { + return decodeURIComponent(path.slice('/sessions/'.length)); + } catch { + return null; + } } export const Admin: m.Component = { user: null as UserInfo | null, + realms: null as AdminRealm[] | null, + realmsError: null as Error | null, error: null as Error | null, authUrl: window.location.origin, + theme: getTheme() as Theme, oninit(this: any) { + applyTheme(this.theme); this.load(); }, + onupdate(this: any) { + this.updateTitle(); + }, + async load(this: any) { try { this.authUrl = await getAuthUrl(); @@ -31,37 +63,70 @@ export const Admin: m.Component = { } if (!getAdminTokens()) { - try { - await startAdminLogin(); - } catch (e) { - this.error = e as Error; - m.redraw(); - } + await this.login(); return; } try { this.user = await loadAdminUser(); - document.title = 'Administration'; - } catch (e) { - const error = e as any; - if (error?.status === 401 || error?.status === 400 || !getAdminTokens()) { - try { - await startAdminLogin(); - return; - } catch (loginError) { - this.error = loginError as Error; - } - } else { - this.error = error as Error; + this.updateTitle(); + } catch (e: any) { + if (e?.status === 401 || e?.status === 400 || !getAdminTokens()) { + await this.login(); + return; + } + this.error = e as Error; + m.redraw(); + return; + } + + try { + this.realms = await loadAdminRealms(); + this.realmsError = null; + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + await this.login(); + return; } + this.realms = []; + this.realmsError = e as Error; } m.redraw(); }, + async login(this: any) { + try { + await startAdminLogin(); + } catch (e) { + this.error = e as Error; + m.redraw(); + } + }, + + async authExpired(this: any) { + clearAdminTokens(); + await this.login(); + }, + + updateTitle(this: any) { + document.title = + currentPath() === '/sessions' || currentPath().startsWith('/sessions/') + ? 'Sessions · Administration' + : 'Administration'; + }, + + cycleTheme(this: any) { + this.theme = cycleTheme(); + }, + view(this: any) { - const tokens = getAdminTokens(); const user = this.user; + const sessions = currentPath() === '/sessions' || currentPath().startsWith('/sessions/'); + const realmSlug = sessionsRealm(); + const sessionsHref = + this.realms && this.realms.length > 0 + ? `/sessions/${encodeURIComponent(this.realms[0].slug)}` + : '/sessions'; return ( <div class="admin-app"> @@ -106,6 +171,16 @@ export const Admin: m.Component = { {icon(Settings)} <span>Account settings</span> </a> + <button + class="admin-user-menu-item" + type="button" + aria-label={`Theme: ${themeLabel(this.theme)}`} + onclick={() => this.cycleTheme()} + > + {icon(Sun)} + <span>Theme</span> + <span class="admin-user-menu-value">{themeLabel(this.theme)}</span> + </button> <a class="admin-user-menu-item" href="#" @@ -130,9 +205,9 @@ export const Admin: m.Component = { <nav class="admin-nav" aria-label="Administration"> <p class="admin-nav-label">Administration</p> <a - class="admin-nav-item is-active" + class={`admin-nav-item${sessions ? '' : ' is-active'}`} href={appUrl('/')} - aria-current="page" + aria-current={sessions ? undefined : 'page'} onclick={(event: Event) => { event.preventDefault(); m.route.set('/'); @@ -141,6 +216,18 @@ export const Admin: m.Component = { {icon(LayoutGrid)} <span>Overview</span> </a> + <a + class={`admin-nav-item${sessions ? ' is-active' : ''}`} + href={appUrl(sessionsHref)} + aria-current={sessions ? 'page' : undefined} + onclick={(event: Event) => { + event.preventDefault(); + m.route.set(sessionsHref); + }} + > + {icon(Activity)} + <span>Sessions</span> + </a> </nav> </aside> @@ -154,59 +241,20 @@ export const Admin: m.Component = { {!user ? ( <div class="admin-loading">Loading session</div> + ) : sessions ? ( + <SessionsPage + key={realmSlug || 'select'} + realmSlug={realmSlug} + realms={this.realms} + realmsError={this.realmsError} + onAuthExpired={() => this.authExpired()} + /> ) : ( - <div class="admin-grid"> - <section class="admin-panel"> - <h2>Account</h2> - <dl class="admin-definition"> - <div> - <dt>User</dt> - <dd>{user.name}</dd> - </div> - <div> - <dt>Email</dt> - <dd>{user.email || 'Not set'}</dd> - </div> - <div> - <dt>Username</dt> - <dd>{user.preferred_username}</dd> - </div> - <div> - <dt>Role</dt> - <dd>{roleLabel(user)}</dd> - </div> - </dl> - </section> - - <section class="admin-panel"> - <h2>Access</h2> - <dl class="admin-definition"> - <div> - <dt>Client</dt> - <dd>admin</dd> - </div> - <div> - <dt>Refresh</dt> - <dd>Automatic</dd> - </div> - <div> - <dt>Scope</dt> - <dd>{tokens?.scope || 'openid'}</dd> - </div> - <div> - <dt>Session</dt> - <dd>Active</dd> - </div> - </dl> - </section> - - <section class="admin-panel admin-panel-wide"> - <h2>Administration</h2> - <p class="admin-note"> - Realm and session management arrive in the next admin slice. - </p> - </section> - </div> + <OverviewPage + user={user} + realms={this.realms} + realmsError={this.realmsError} + /> )} </div> </main> @@ -238,6 +286,11 @@ export const AdminCallback: m.Component = { return ( <div class="admin-status-page"> <div class="admin-status-panel"> + {this.error ? ( + icon(CircleAlert, { class: 'admin-status-icon' }) + ) : ( + <div class="admin-spinner" aria-hidden="true"></div> + )} <h1>{this.error ? 'Sign-in failed' : 'Completing sign-in'}</h1> {this.error ? ( <p class="admin-status-error" role="alert"> @@ -247,9 +300,11 @@ export const AdminCallback: m.Component = { <p class="admin-status-note">Establishing the administrative session.</p> )} {this.error ? ( - <a class="admin-status-link" href={appUrl('/')}> - Return to administration - </a> + <div class="admin-status-actions"> + <a class="admin-button" href={appUrl('/')}> + Return to administration + </a> + </div> ) : null} </div> </div> diff --git a/app/admin/src/screen/overview.tsx b/app/admin/src/screen/overview.tsx @@ -0,0 +1,106 @@ +import m from 'mithril'; +import { appUrl, type AdminRealm, type UserInfo } from '../util/api'; +import { getAdminTokens } from '../util/auth'; + +interface OverviewAttrs { + user: UserInfo; + realms: AdminRealm[] | null; + realmsError: Error | null; +} + +function roleLabel(user: UserInfo) { + return user.is_system_admin ? 'System administrator' : 'Realm administrator'; +} + +export const OverviewPage: m.Component<OverviewAttrs> = { + view({ attrs }) { + const { user, realms, realmsError } = attrs; + const tokens = getAdminTokens(); + + return ( + <div class="admin-overview"> + <div class="admin-page-header"> + <h1>Overview</h1> + <p>Provider summary and administration.</p> + </div> + + <div class="admin-grid"> + <section class="admin-panel"> + <h2>Account</h2> + <dl class="admin-definition"> + <div> + <dt>User</dt> + <dd>{user.name}</dd> + </div> + <div> + <dt>Email</dt> + <dd>{user.email || 'Not set'}</dd> + </div> + <div> + <dt>Username</dt> + <dd>{user.preferred_username}</dd> + </div> + <div> + <dt>Role</dt> + <dd>{roleLabel(user)}</dd> + </div> + </dl> + </section> + + <section class="admin-panel"> + <h2>Access</h2> + <dl class="admin-definition"> + <div> + <dt>Client</dt> + <dd>admin</dd> + </div> + <div> + <dt>Refresh</dt> + <dd>Automatic</dd> + </div> + <div> + <dt>Scope</dt> + <dd>{tokens?.scope || 'openid'}</dd> + </div> + <div> + <dt>Session</dt> + <dd>Active</dd> + </div> + </dl> + </section> + + <section class="admin-panel admin-panel-wide"> + <h2>Administration</h2> + {realmsError ? ( + <p class="admin-note" role="alert"> + {realmsError.message} + </p> + ) : realms === null ? ( + <p class="admin-note">Loading realms.</p> + ) : realms.length === 0 ? ( + <p class="admin-note">No realms are available for this account.</p> + ) : ( + <ul class="admin-realm-list"> + {realms.map((realm) => ( + <li> + <a + class="admin-realm-link" + href={appUrl(`/sessions/${encodeURIComponent(realm.slug)}`)} + onclick={(event: Event) => { + event.preventDefault(); + m.route.set(`/sessions/${encodeURIComponent(realm.slug)}`); + }} + > + <span class="admin-realm-name">{realm.display_name}</span> + <span class="admin-realm-slug">{realm.slug}</span> + </a> + </li> + ))} + </ul> + )} + </section> + </div> + </div> + ); + }, +}; diff --git a/app/admin/src/screen/sessions.tsx b/app/admin/src/screen/sessions.tsx @@ -0,0 +1,354 @@ +import m from 'mithril'; +import type { AdminRealm, AdminSession } from '../util/api'; +import { + loadAdminSessions, + revokeAdminSessionRealm, + terminateAdminSession, +} from '../util/auth'; +import { formatTime, scopeLabel } from '../util/format'; + +interface SessionsAttrs { + realmSlug: string | null; + realms: AdminRealm[] | null; + realmsError: Error | null; + onAuthExpired: () => void; +} + +type SessionAction = 'realm' | 'terminate'; + +function actionKey(action: SessionAction, session: AdminSession) { + return `${action}:${session.public_id}`; +} + +export const SessionsPage: m.Component<SessionsAttrs> = { + attrs: null as SessionsAttrs | null, + loadedRealm: null as string | null, + loading: false, + redirecting: false, + sessions: null as AdminSession[] | null, + error: null as Error | null, + notice: null as string | null, + confirmKey: null as string | null, + pendingKey: null as string | null, + + oninit(this: any, vnode: m.Vnode<SessionsAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + onupdate(this: any, vnode: m.Vnode<SessionsAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + ensure(this: any) { + const { realms, realmSlug } = this.attrs; + if (!realms) return; + + if (realms.length === 0) { + this.sessions = []; + this.loading = false; + this.error = null; + return; + } + + const selected = realmSlug && realms.some((realm) => realm.slug === realmSlug); + if (!selected) { + if (!this.redirecting) { + this.redirecting = true; + m.route.set(`/sessions/${encodeURIComponent(realms[0].slug)}`, null, { + replace: true, + }); + } + return; + } + + this.redirecting = false; + if (this.loadedRealm !== realmSlug) { + this.load(realmSlug); + } + }, + + async load(this: any, realmSlug: string) { + this.loadedRealm = realmSlug; + this.loading = true; + this.error = null; + this.sessions = null; + m.redraw(); + + try { + const sessions = await loadAdminSessions(realmSlug); + if (this.loadedRealm === realmSlug) this.sessions = sessions; + } catch (e: any) { + if (this.loadedRealm !== realmSlug) return; + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + if (this.loadedRealm === realmSlug) this.loading = false; + m.redraw(); + } + }, + + async act(this: any, session: AdminSession, action: SessionAction) { + const { realmSlug } = this.attrs; + if (!realmSlug) return; + + const key = actionKey(action, session); + this.pendingKey = key; + this.error = null; + this.notice = null; + + try { + if (action === 'realm') { + await revokeAdminSessionRealm(realmSlug, session.public_id); + this.notice = + 'Realm access revoked. The next authorization for this realm requires re-verification.'; + } else { + await terminateAdminSession(realmSlug, session.public_id); + this.notice = 'Session terminated.'; + } + this.confirmKey = null; + await this.load(realmSlug); + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + this.pendingKey = null; + m.redraw(); + } + }, + + view(this: any) { + const { realms, realmsError } = this.attrs; + const selected = + realms?.find((realm) => realm.slug === this.attrs.realmSlug) || realms?.[0] || null; + + return ( + <div class="admin-sessions"> + <div class="admin-page-header admin-page-header-row"> + <div> + <h1>Sessions</h1> + <p>Active sessions with access to this realm.</p> + </div> + {realms && realms.length > 1 ? ( + <label class="admin-realm-select"> + <span>Realm</span> + <select + value={selected?.slug || ''} + onchange={(event: Event) => { + const value = (event.target as HTMLSelectElement).value; + this.notice = null; + m.route.set(`/sessions/${encodeURIComponent(value)}`); + }} + > + {realms.map((realm) => ( + <option value={realm.slug}>{realm.display_name}</option> + ))} + </select> + </label> + ) : selected ? ( + <span class="admin-realm-current">{selected.display_name}</span> + ) : null} + </div> + + {realmsError ? ( + <div class="admin-alert" role="alert"> + {realmsError.message} + </div> + ) : null} + + {this.error ? ( + <div class="admin-alert" role="alert"> + <p>{this.error.message}</p> + {this.attrs.realmSlug ? ( + <button + class="admin-button-secondary" + type="button" + onclick={() => this.load(this.attrs.realmSlug)} + > + Try again + </button> + ) : null} + </div> + ) : null} + + {this.notice ? ( + <div class="admin-notice" role="status"> + {this.notice} + </div> + ) : null} + + {!realms ? ( + <div class="admin-loading">Loading realms</div> + ) : realms.length === 0 ? ( + <div class="admin-empty"> + <p>No realms are available for this account.</p> + </div> + ) : this.loading || this.redirecting ? ( + <div class="admin-session-stack" aria-busy="true"> + <div class="admin-session-skeleton"> + <div class="admin-skeleton admin-skeleton-title"></div> + <div class="admin-skeleton"></div> + <div class="admin-skeleton admin-skeleton-short"></div> + </div> + <div class="admin-session-skeleton"> + <div class="admin-skeleton admin-skeleton-title"></div> + <div class="admin-skeleton"></div> + <div class="admin-skeleton admin-skeleton-short"></div> + </div> + </div> + ) : this.sessions && this.sessions.length > 0 ? ( + <div class="admin-session-stack"> + {this.sessions.map((session: AdminSession) => { + const realmKey = actionKey('realm', session); + const terminateKey = actionKey('terminate', session); + const pending = this.pendingKey; + const revokePending = pending === realmKey; + const terminatePending = pending === terminateKey; + + return ( + <article class="admin-session"> + <div class="admin-session-header"> + <div> + <h2>{session.user.display_name || session.user.username}</h2> + <p class="admin-session-user"> + {session.user.username} + {session.user.status !== 'active' + ? ` · ${session.user.status}` + : ''} + </p> + </div> + {session.revoked_at ? ( + <span class="admin-session-badge"> + Realm access revoked {formatTime(session.revoked_at)} + </span> + ) : null} + </div> + + <dl class="admin-definition admin-session-details"> + <div> + <dt>Scope</dt> + <dd>{scopeLabel(session.scope.type)}</dd> + </div> + <div> + <dt>Host</dt> + <dd>{session.scope.host || 'Canonical'}</dd> + </div> + <div> + <dt>Client</dt> + <dd>{session.scope.client_id || 'None'}</dd> + </div> + <div> + <dt>Last seen</dt> + <dd>{formatTime(session.last_seen_at)}</dd> + </div> + <div> + <dt>Expires</dt> + <dd>{formatTime(session.expires_at)}</dd> + </div> + <div> + <dt>Address</dt> + <dd>{session.ip || 'Unknown'}</dd> + </div> + </dl> + + {session.user_agent ? ( + <p class="admin-session-agent">{session.user_agent}</p> + ) : null} + + <div class="admin-session-actions"> + {session.revoked_at ? null : this.confirmKey === realmKey ? ( + <div class="admin-confirm"> + <span>Revoke this realm’s access?</span> + <button + class="admin-button" + type="button" + disabled={Boolean(pending)} + onclick={() => this.act(session, 'realm')} + > + {revokePending ? 'Revoking' : 'Confirm'} + </button> + <button + class="admin-button-secondary" + type="button" + disabled={Boolean(pending)} + onclick={() => { + this.confirmKey = null; + m.redraw(); + }} + > + Cancel + </button> + </div> + ) : ( + <button + class="admin-button-secondary" + type="button" + disabled={Boolean(pending)} + onclick={() => { + this.confirmKey = realmKey; + m.redraw(); + }} + > + Revoke realm access + </button> + )} + + {session.can_terminate ? ( + this.confirmKey === terminateKey ? ( + <div class="admin-confirm"> + <span>Terminate this session?</span> + <button + class="admin-button admin-button-danger" + type="button" + disabled={Boolean(pending)} + onclick={() => this.act(session, 'terminate')} + > + {terminatePending ? 'Terminating' : 'Confirm'} + </button> + <button + class="admin-button-secondary" + type="button" + disabled={Boolean(pending)} + onclick={() => { + this.confirmKey = null; + m.redraw(); + }} + > + Cancel + </button> + </div> + ) : ( + <button + class="admin-button-danger" + type="button" + disabled={Boolean(pending)} + onclick={() => { + this.confirmKey = terminateKey; + m.redraw(); + }} + > + Terminate session + </button> + ) + ) : null} + </div> + </article> + ); + })} + </div> + ) : ( + <div class="admin-empty"> + <p>No active sessions with access to this realm.</p> + </div> + )} + </div> + ); + }, +}; diff --git a/app/admin/src/util/api.ts b/app/admin/src/util/api.ts @@ -34,6 +34,35 @@ export interface UserInfo { is_system_admin: boolean; } +export interface AdminRealm { + slug: string; + display_name: string; +} + +export interface AdminSession { + public_id: string; + user: { + id: string; + username: string; + display_name: string; + home_realm_id: string | null; + status: string; + }; + scope: { + type: string; + host: string | null; + client_id: string | null; + }; + created_at: number; + last_seen_at: number; + expires_at: number; + user_agent: string; + ip: string; + revoked_at: number | null; + revoked_by: string | null; + can_terminate: boolean; +} + export interface ApiError extends Error { code?: string; status?: number; diff --git a/app/admin/src/util/auth.ts b/app/admin/src/util/auth.ts @@ -1,9 +1,13 @@ import { + adminApi, appUrl, exchangeCode, getDiscovery, getUserInfo, refreshAccessToken, + type AdminRealm, + type AdminSession, + type ApiError, type TokenResponse, type UserInfo, } from './api'; @@ -148,6 +152,60 @@ export async function ensureAdminAccessToken() { return (await refreshAdminTokens()).access_token; } +async function adminJson<T>(path: string, init: RequestInit = {}): Promise<T> { + let accessToken = await ensureAdminAccessToken(); + let response = await adminApi(path, accessToken, init); + if (response.status === 401) { + accessToken = (await refreshAdminTokens()).access_token; + response = await adminApi(path, accessToken, init); + } + + let payload: any = null; + try { + payload = await response.json(); + } catch { + payload = null; + } + if (!response.ok) { + const error = new Error( + payload?.error_description || payload?.error?.message || response.statusText + ) as ApiError; + error.code = payload?.error?.code || payload?.error; + error.status = response.status; + throw error; + } + return payload as T; +} + +export async function loadAdminRealms(): Promise<AdminRealm[]> { + const response = await adminJson<{ realms: AdminRealm[] }>('/api/v1/admin/realms'); + return response.realms; +} + +export async function loadAdminSessions(realmSlug: string): Promise<AdminSession[]> { + const realm = encodeURIComponent(realmSlug); + const response = await adminJson<{ sessions: AdminSession[] }>( + `/api/v1/admin/realms/${realm}/sessions` + ); + return response.sessions; +} + +export async function revokeAdminSessionRealm(realmSlug: string, publicId: string) { + const realm = encodeURIComponent(realmSlug); + const session = encodeURIComponent(publicId); + await adminJson(`/api/v1/admin/realms/${realm}/sessions/${session}/realm`, { + method: 'DELETE', + }); +} + +export async function terminateAdminSession(realmSlug: string, publicId: string) { + const realm = encodeURIComponent(realmSlug); + const session = encodeURIComponent(publicId); + await adminJson(`/api/v1/admin/realms/${realm}/sessions/${session}`, { + method: 'DELETE', + }); +} + export async function loadAdminUser(): Promise<UserInfo> { let accessToken = await ensureAdminAccessToken(); try { diff --git a/app/admin/src/util/format.ts b/app/admin/src/util/format.ts @@ -0,0 +1,14 @@ +export function formatTime(value: number | null | undefined) { + if (!value) return 'Unknown'; + return new Intl.DateTimeFormat(undefined, { + dateStyle: 'medium', + timeStyle: 'short', + }).format(new Date(value)); +} + +export function scopeLabel(type: string) { + if (type === 'global') return 'Canonical session'; + if (type === 'realm') return 'Realm session'; + if (type === 'client') return 'Client session'; + return type; +} diff --git a/app/admin/src/util/theme.ts b/app/admin/src/util/theme.ts @@ -0,0 +1,39 @@ +export type Theme = 'auto' | 'light' | 'dark'; + +const THEME_KEY = 'auth_theme'; +const THEMES: Theme[] = ['auto', 'light', 'dark']; + +export function getTheme(): Theme { + try { + const value = localStorage.getItem(THEME_KEY); + if (value === 'light' || value === 'dark') return value; + } catch { + return 'auto'; + } + return 'auto'; +} + +export function applyTheme(theme: Theme) { + if (theme === 'auto') { + document.documentElement.removeAttribute('data-theme'); + } else { + document.documentElement.setAttribute('data-theme', theme); + } +} + +export function setTheme(theme: Theme) { + try { + localStorage.setItem(THEME_KEY, theme); + } catch {} + applyTheme(theme); +} + +export function cycleTheme(): Theme { + const next = THEMES[(THEMES.indexOf(getTheme()) + 1) % THEMES.length]; + setTheme(next); + return next; +} + +export function themeLabel(theme: Theme) { + return theme.charAt(0).toUpperCase() + theme.slice(1); +} diff --git a/server/src/controller/admin/realms/list.js b/server/src/controller/admin/realms/list.js @@ -0,0 +1,15 @@ +import { app } from '../../../app.js'; +import { authenticateAdminSession } from '../../../lib/admin-auth.js'; +import { listAdminRealmOptions } from '../../../lib/system-clients.js'; + +export default { + method: 'get', + path: '/api/v1/admin/realms', + name: 'admin.realms.list', + async handler(req) { + const auth = await authenticateAdminSession(req); + const realms = await listAdminRealmOptions(auth.systemDb, auth.user); + + return new app.HttpOk({ realms }, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/lib/admin-auth.js b/server/src/lib/admin-auth.js @@ -12,7 +12,7 @@ function bearerToken(req) { return header.startsWith('Bearer ') ? header.slice(7) : null; } -export async function authenticateAdminRequest(req, { realmSlug }) { +export async function authenticateAdminSession(req) { const hostContext = await resolveHostContext(req, { publicUrl: app.config.server.public_url, }); @@ -56,6 +56,13 @@ export async function authenticateAdminRequest(req, { realmSlug }) { throw new HttpError(401, 'invalid_token', 'The admin session is not active'); } + return { systemDb, user, session }; +} + +export async function authenticateAdminRequest(req, { realmSlug }) { + const auth = await authenticateAdminSession(req); + const { systemDb, user, session } = auth; + const realm = await resolveRealm({ slug: realmSlug }); const realmDb = await openRealmDatabase(realm); const membership = await getMembership(realmDb, user.id); diff --git a/server/src/lib/system-clients.js b/server/src/lib/system-clients.js @@ -1,5 +1,5 @@ import { isSystemAdmin } from './policy.js'; -import { openRealmDatabase } from './realm.js'; +import { openRealmDatabase, realmMetadata } from './realm.js'; import { getMembership, getUserRoles } from './users.js'; export async function listAdminRealms(systemDb, user) { @@ -23,6 +23,23 @@ export async function listAdminRealms(systemDb, user) { return accessible; } +export async function listAdminRealmOptions(systemDb, user) { + const realms = await listAdminRealms(systemDb, user); + const options = []; + for (const realm of realms) { + try { + const metadata = await realmMetadata(realm); + options.push({ + slug: realm.slug, + display_name: metadata.display_name, + }); + } catch { + continue; + } + } + return options; +} + export async function canUseSystemClient(systemDb, { user, client }) { if (!user || user.status !== 'active' || !client?.enabled) return false; if (client.client_id === 'account') return true; diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -2197,6 +2197,65 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.ok(refreshed.json.refresh_token); }); + await t.test('admin realm APIs list only accessible realms', async () => { + const missing = await identity({ path: '/api/v1/admin/realms' }); + assert.equal(missing.status, 401); + assert.equal(missing.json.error.code, 'invalid_token'); + + const alice = await accessToken(acme, { + clientId: 'internal-app', + identifier: 'alice@acme.test', + redirectUri: `${origin('app.acme.localhost')}/callback`, + }); + const wrongAudience = await identity({ + path: '/api/v1/admin/realms', + bearer: alice.access_token, + }); + assert.equal(wrongAudience.status, 401); + assert.equal(wrongAudience.json.error.code, 'invalid_token'); + + const realmHost = await acme({ path: '/api/v1/admin/realms' }); + assert.equal(realmHost.status, 404); + + const clientHost = await app({ path: '/api/v1/admin/realms' }); + assert.equal(clientHost.status, 404); + + const system = await identity({ + path: '/api/v1/admin/realms', + bearer: (await adminToken()).access_token, + }); + assert.equal(system.status, 200); + assert.equal(system.headers['cache-control'], 'no-store'); + assert.deepEqual( + system.json.realms.map((realm) => realm.slug), + ['acme', 'globex'] + ); + assert.deepEqual( + system.json.realms.map((realm) => realm.display_name), + ['Acme', 'Globex'] + ); + + const acmeAdmin = await identity({ + path: '/api/v1/admin/realms', + bearer: (await adminToken('it@acme.test')).access_token, + }); + assert.equal(acmeAdmin.status, 200); + assert.deepEqual( + acmeAdmin.json.realms.map((realm) => realm.slug), + ['acme'] + ); + + const globexAdmin = await identity({ + path: '/api/v1/admin/realms', + bearer: (await adminToken('contractor@personal.test')).access_token, + }); + assert.equal(globexAdmin.status, 200); + assert.deepEqual( + globexAdmin.json.realms.map((realm) => realm.slug), + ['globex'] + ); + }); + await t.test('admin session APIs require an active admin token', async () => { const missing = await identity({ path: '/api/v1/admin/realms/acme/sessions' }); assert.equal(missing.status, 401); @@ -2523,6 +2582,13 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }); try { + const realms = await identity({ + path: '/api/v1/admin/realms', + bearer: admin.access_token, + }); + assert.equal(realms.status, 200); + assert.deepEqual(realms.json.realms, []); + const response = await identity({ path: '/api/v1/admin/realms/acme/sessions', bearer: admin.access_token,