auth

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

commit d5d1100cbe90815e959863a8f256ec3886f67707
parent c9c6c0046b2189a47e350083a74d775def84f2a8
Author: finwo <finwo@pm.me>
Date:   Sat, 24 Oct 2026 20:08:36 +0200

Added OIDC client management

Diffstat:
Mapp/admin/src/assets/admin.css | 211+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/src/component/client-form.tsx | 282+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/src/component/realm-selector.tsx | 38++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/main.ts | 9+++++++++
Mapp/admin/src/screen/admin.tsx | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Aapp/admin/src/screen/client-edit.tsx | 417+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/src/screen/clients.tsx | 411+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/screen/sessions.tsx | 31++++++++++++-------------------
Mapp/admin/src/util/api.ts | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/util/auth.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mapp/login/src/assets/login.css | 11+++++------
Aapp/shared/component/modal.tsx | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mapp/shared/style/global.css | 224+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Amockup/plain/admin-client-detail.html | 280+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Amockup/plain/admin-clients.html | 365+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmockup/plain/admin-dashboard.html | 17+++++++++--------
Mmockup/plain/global.css | 391+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/src/controller/admin/clients.js | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/src/controller/admin/roles/list.js | 17+++++++++++++++++
Mserver/src/index.js | 2+-
Aserver/src/lib/admin-clients.js | 714+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/src/lib/apps.js | 22++++++++++++++--------
Aserver/test/admin-clients.test.js | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/test/http.test.js | 550+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
24 files changed, 4366 insertions(+), 53 deletions(-)

diff --git a/app/admin/src/assets/admin.css b/app/admin/src/assets/admin.css @@ -124,8 +124,219 @@ line-height: 1.5; } +.section-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 1rem; + margin-bottom: 1.25rem; +} + +.section-header h2 { + margin: 0; +} + +.client-stack { + display: grid; + gap: 1rem; +} + +.client-breadcrumb { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + margin-bottom: 1rem; + color: var(--muted); + font-size: 0.8125rem; + line-height: 1.4; +} + +.client-breadcrumb a { + color: var(--accent-text); + text-decoration: none; +} + +.client-header { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; +} + +.client-header h2 { + margin: 0; +} + +.client-title { + color: inherit; + text-decoration: none; +} + +.client-title:hover { + color: var(--accent-text-hover); +} + +.client-id { + margin: 0.25rem 0 0; + color: var(--muted); + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 0.8125rem; + line-height: 1.4; + overflow-wrap: anywhere; +} + +.client-badge { + color: var(--muted); + font-size: 0.75rem; + line-height: 1.4; + text-transform: uppercase; +} + +.client-details { + margin-top: 1.25rem; +} + +.client-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + margin-top: 1.25rem; +} + +.client-form { + display: grid; + gap: 1rem; + margin-top: 1rem; +} + +.modal-body .client-form { + margin-top: 0; +} + +.field-grid { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 1rem; +} + +.form-field { + min-width: 0; + display: grid; + gap: 0.25rem; +} + +.field-label { + color: var(--muted); + font-size: 0.75rem; + line-height: 1.4; +} + +.field-control, +.field-textarea { + width: 100%; + padding: 0.5rem 0.75rem; + border: 0; + border-bottom: 1pt solid var(--field-line); + border-radius: 0; + background: var(--surface); + color: inherit; + font: inherit; + font-size: 0.875rem; + line-height: 1.5; +} + +.field-textarea { + min-height: 6rem; + resize: vertical; +} + +.field-control:focus, +.field-textarea:focus { + outline: 2pt solid var(--accent); + outline-offset: 2pt; +} + +.field-control:disabled { + color: var(--muted); + opacity: 1; +} + +.role-field { + margin: 0; + padding: 0; + border: 0; +} + +.role-field legend { + margin-bottom: 0.5rem; + padding: 0; + color: var(--muted); + font-size: 0.75rem; + line-height: 1.4; +} + +.checkbox-list { + display: grid; + gap: 0.5rem; +} + +.checkbox-row { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.875rem; + line-height: 1.5; +} + +.checkbox-row input { + width: 1rem; + height: 1rem; +} + +.secret-panel { + display: grid; + gap: 0.75rem; +} + +.secret-header { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; +} + +.secret-header h2 { + margin: 0; +} + +.danger-zone h2 { + color: var(--danger); +} + +.secret-value { + display: block; + margin-top: 1rem; + padding: 0.75rem; + background: var(--row); + color: inherit; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 0.8125rem; + line-height: 1.5; + overflow-wrap: anywhere; + white-space: pre-wrap; +} + @media (min-width: 40em) { .realm-select select { width: auto; } + + .field-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } } diff --git a/app/admin/src/component/client-form.tsx b/app/admin/src/component/client-form.tsx @@ -0,0 +1,282 @@ +import m from 'mithril'; +import type { AdminClient, AdminClientInput, AdminRole } from '../util/api'; + +export interface ClientFormValue { + client_id: string; + name: string; + access_mode: AdminClient['access_mode']; + enabled: boolean; + scopes: string; + required_roles: string[]; + redirect_uris: string; + post_logout_redirect_uris: string; + token_endpoint_auth_method: AdminClient['token_endpoint_auth_method']; + require_pkce: boolean; + consent_mode: AdminClient['consent_mode']; +} + +export function defaultClientForm(): ClientFormValue { + return { + client_id: '', + name: '', + access_mode: 'members', + enabled: true, + scopes: 'openid profile email', + required_roles: [], + redirect_uris: '', + post_logout_redirect_uris: '', + token_endpoint_auth_method: 'none', + require_pkce: true, + consent_mode: 'remembered', + }; +} + +export function parseUriLines(value: string): string[] { + return [...new Set(value.split('\n').map((item) => item.trim()).filter(Boolean))]; +} + +export function clientFormValue(client: AdminClient): ClientFormValue { + return { + client_id: client.client_id, + name: client.name, + access_mode: client.access_mode, + enabled: client.enabled, + scopes: client.scopes, + required_roles: [...client.required_roles], + redirect_uris: client.redirect_uris.join('\n'), + post_logout_redirect_uris: client.post_logout_redirect_uris.join('\n'), + token_endpoint_auth_method: client.token_endpoint_auth_method, + require_pkce: client.require_pkce, + consent_mode: client.consent_mode, + }; +} + +export function toClientInput(value: ClientFormValue): AdminClientInput { + const tokenEndpointAuthMethod = value.token_endpoint_auth_method; + return { + name: value.name.trim(), + access_mode: value.access_mode, + enabled: value.enabled, + scopes: value.scopes.trim(), + required_roles: [...value.required_roles], + redirect_uris: parseUriLines(value.redirect_uris), + post_logout_redirect_uris: parseUriLines(value.post_logout_redirect_uris), + token_endpoint_auth_method: tokenEndpointAuthMethod, + require_pkce: tokenEndpointAuthMethod === 'none' ? true : value.require_pkce, + consent_mode: value.consent_mode, + }; +} + +interface ClientFormAttrs { + value: ClientFormValue; + roles: AdminRole[]; + editing: boolean; + submitLabel: string; + pending: boolean; + error: Error | string | null; + onsubmit: () => void; + oncancel?: () => void; +} + +export const ClientForm: m.Component<ClientFormAttrs> = { + view({ attrs }) { + const value = attrs.value; + const requirePkce = value.token_endpoint_auth_method === 'none' || value.require_pkce; + + return ( + <form + class="client-form" + onsubmit={(event: Event) => { + event.preventDefault(); + attrs.onsubmit(); + }} + > + {attrs.error ? ( + <div class="alert" role="alert"> + {typeof attrs.error === 'string' ? attrs.error : attrs.error.message} + </div> + ) : null} + + <div class="field-grid"> + <div class="form-field"> + <span class="field-label">Client ID</span> + <input + class="field-control" + value={value.client_id} + disabled={attrs.editing} + placeholder="my-app" + oninput={(event: Event) => { + value.client_id = (event.target as HTMLInputElement).value; + }} + /> + </div> + + <div class="form-field"> + <span class="field-label">Name</span> + <input + class="field-control" + value={value.name} + oninput={(event: Event) => { + value.name = (event.target as HTMLInputElement).value; + }} + /> + </div> + + <div class="form-field"> + <span class="field-label">Access mode</span> + <select + class="field-control" + value={value.access_mode} + onchange={(event: Event) => { + value.access_mode = (event.target as HTMLSelectElement) + .value as ClientFormValue['access_mode']; + }} + > + <option value="internal">Internal: home-realm members</option> + <option value="members">Members: active realm members</option> + <option value="public">Public: any authenticated user</option> + </select> + </div> + + <div class="form-field"> + <span class="field-label">Consent</span> + <select + class="field-control" + value={value.consent_mode} + onchange={(event: Event) => { + value.consent_mode = (event.target as HTMLSelectElement) + .value as ClientFormValue['consent_mode']; + }} + > + <option value="remembered">Remembered: prompt once</option> + <option value="trusted">Trusted: skip for home realm</option> + </select> + </div> + + <div class="form-field"> + <span class="field-label">Token authentication</span> + <select + class="field-control" + value={value.token_endpoint_auth_method} + onchange={(event: Event) => { + const method = (event.target as HTMLSelectElement) + .value as ClientFormValue['token_endpoint_auth_method']; + value.token_endpoint_auth_method = method; + if (method === 'none') value.require_pkce = true; + }} + > + <option value="none">Public client: PKCE</option> + <option value="client_secret_basic">Confidential: client secret</option> + </select> + </div> + + <label class="checkbox-row"> + <input + type="checkbox" + checked={value.enabled} + onchange={(event: Event) => { + value.enabled = (event.target as HTMLInputElement).checked; + }} + /> + <span>Enabled</span> + </label> + + <label class="checkbox-row"> + <input + type="checkbox" + checked={requirePkce} + disabled={value.token_endpoint_auth_method === 'none'} + onchange={(event: Event) => { + value.require_pkce = (event.target as HTMLInputElement).checked; + }} + /> + <span>Require PKCE</span> + </label> + </div> + + <div class="form-field"> + <span class="field-label">Scopes</span> + <input + class="field-control" + value={value.scopes} + oninput={(event: Event) => { + value.scopes = (event.target as HTMLInputElement).value; + }} + /> + </div> + + <div class="form-field"> + <span class="field-label">Redirect URIs</span> + <textarea + class="field-control field-textarea" + value={value.redirect_uris} + placeholder="https://app.example.test/callback" + oninput={(event: Event) => { + value.redirect_uris = (event.target as HTMLTextAreaElement).value; + }} + /> + </div> + + <div class="form-field"> + <span class="field-label">Post-logout redirect URIs</span> + <textarea + class="field-control field-textarea" + value={value.post_logout_redirect_uris} + placeholder="https://app.example.test/" + oninput={(event: Event) => { + value.post_logout_redirect_uris = (event.target as HTMLTextAreaElement).value; + }} + /> + </div> + + <fieldset class="role-field"> + <legend>Required roles</legend> + {attrs.roles.length === 0 ? ( + <p class="note">No realm roles are available.</p> + ) : ( + <div class="checkbox-list"> + {attrs.roles.map((role) => { + const checked = value.required_roles.includes(role.slug); + return ( + <label class="checkbox-row"> + <input + type="checkbox" + checked={checked} + onchange={(event: Event) => { + const index = value.required_roles.indexOf(role.slug); + const selected = (event.target as HTMLInputElement).checked; + if (selected && index === -1) { + value.required_roles.push(role.slug); + } + if (!selected && index !== -1) { + value.required_roles.splice(index, 1); + } + }} + /> + <span>{role.name}</span> + </label> + ); + })} + </div> + )} + </fieldset> + + <div class="client-actions"> + <button class="button" type="submit" disabled={attrs.pending}> + {attrs.pending ? 'Saving' : attrs.submitLabel} + </button> + {attrs.oncancel ? ( + <button + class="button-secondary" + type="button" + disabled={attrs.pending} + onclick={attrs.oncancel} + > + Cancel + </button> + ) : null} + </div> + </form> + ); + }, +}; diff --git a/app/admin/src/component/realm-selector.tsx b/app/admin/src/component/realm-selector.tsx @@ -0,0 +1,38 @@ +import m from 'mithril'; +import type { AdminRealm } from '../util/api'; + +interface RealmSelectorAttrs { + realms: AdminRealm[] | null; + selected: AdminRealm | null; + onchange: (slug: string) => void; +} + +export const RealmSelector: m.Component<RealmSelectorAttrs> = { + view({ attrs }) { + const { realms, selected } = attrs; + + if (realms && realms.length > 1) { + return ( + <label class="realm-select"> + <span>Realm</span> + <select + value={selected?.slug || ''} + onchange={(event: Event) => { + attrs.onchange((event.target as HTMLSelectElement).value); + }} + > + {realms.map((realm) => ( + <option value={realm.slug}>{realm.display_name}</option> + ))} + </select> + </label> + ); + } + + if (selected) { + return <span class="realm-current">{selected.display_name}</span>; + } + + return null; + }, +}; diff --git a/app/admin/src/main.ts b/app/admin/src/main.ts @@ -16,6 +16,15 @@ const routes: m.RouteDefs = { '/sessions/:realm': { render: () => m(Admin, {}), }, + '/clients': { + render: () => m(Admin, {}), + }, + '/clients/:realm': { + render: () => m(Admin, {}), + }, + '/clients/:realm/edit/:client': { + render: () => m(Admin, {}), + }, '/callback': { render: () => m(AdminCallback, {}), }, diff --git a/app/admin/src/screen/admin.tsx b/app/admin/src/screen/admin.tsx @@ -1,4 +1,4 @@ -import { Activity, LayoutGrid } from 'lucide'; +import { Activity, AppWindow, LayoutGrid } from 'lucide'; import m from 'mithril'; import { AppShell } from '@component/app-shell'; import { Nav, type NavItem } from '@component/nav'; @@ -18,6 +18,8 @@ import { import { appUrl, getAuthUrl, type AdminRealm, type UserInfo } from '../util/api'; import { OverviewPage } from './overview'; import { SessionsPage } from './sessions'; +import { ClientEditPage } from './client-edit'; +import { ClientsPage } from './clients'; function currentPath() { return (m.route.get() || '/').split('?')[0]; @@ -33,6 +35,33 @@ function sessionsRealm() { } } +function clientsRealm() { + const path = currentPath(); + if (path !== '/clients' && !path.startsWith('/clients/')) return null; + const suffix = path.slice('/clients/'.length); + if (!suffix) return null; + const slug = suffix.split('/')[0]; + try { + return decodeURIComponent(slug); + } catch { + return null; + } +} + +function clientEditPath() { + const path = currentPath(); + const match = /^\/clients\/([^/]+)\/edit\/(.+)$/.exec(path); + if (!match) return null; + try { + return { + realmSlug: decodeURIComponent(match[1]), + clientId: decodeURIComponent(match[2]), + }; + } catch { + return null; + } +} + export const Admin: m.Component = { user: null as UserInfo | null, realms: null as AdminRealm[] | null, @@ -104,10 +133,17 @@ export const Admin: m.Component = { }, updateTitle(this: any) { - document.title = - currentPath() === '/sessions' || currentPath().startsWith('/sessions/') - ? 'Sessions ยท Administration' + const path = currentPath(); + const clients = path === '/clients' || path.startsWith('/clients/'); + const sessions = path === '/sessions' || path.startsWith('/sessions/'); + const title = clients + ? path.includes('/edit/') + ? 'Edit client | Administration' + : 'Clients | Administration' + : sessions + ? 'Sessions | Administration' : 'Administration'; + document.title = title; }, cycleTheme(this: any) { @@ -116,25 +152,42 @@ export const Admin: m.Component = { view(this: any) { const user = this.user; - const sessions = currentPath() === '/sessions' || currentPath().startsWith('/sessions/'); + const path = currentPath(); + const sessions = path === '/sessions' || path.startsWith('/sessions/'); + const clients = path === '/clients' || path.startsWith('/clients/'); const realmSlug = sessionsRealm(); - const sessionsHref = - this.realms && this.realms.length > 0 - ? `/sessions/${encodeURIComponent(this.realms[0].slug)}` - : '/sessions'; + const clientRealmSlug = clientsRealm(); + const clientEdit = clientEditPath(); + const firstRealm = this.realms && this.realms.length > 0 ? this.realms[0].slug : null; + const sessionsHref = firstRealm + ? `/sessions/${encodeURIComponent(firstRealm)}` + : '/sessions'; + const clientsHref = firstRealm + ? `/clients/${encodeURIComponent(firstRealm)}` + : '/clients'; const navItems: NavItem[] = [ { href: appUrl('/'), label: 'Overview', icon: LayoutGrid, - active: !sessions, + active: !sessions && !clients, onclick: (event: Event) => { event.preventDefault(); m.route.set('/'); }, }, { + 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, @@ -181,9 +234,23 @@ export const Admin: m.Component = { {!user ? ( <div class="loading">Loading session</div> + ) : clients && clientEdit ? ( + <ClientEditPage + realmSlug={clientEdit.realmSlug} + clientId={clientEdit.clientId} + realms={this.realms} + realmsError={this.realmsError} + onAuthExpired={() => this.authExpired()} + /> + ) : clients ? ( + <ClientsPage + realmSlug={clientRealmSlug} + realms={this.realms} + realmsError={this.realmsError} + onAuthExpired={() => this.authExpired()} + /> ) : sessions ? ( <SessionsPage - key={realmSlug || 'select'} realmSlug={realmSlug} realms={this.realms} realmsError={this.realmsError} diff --git a/app/admin/src/screen/client-edit.tsx b/app/admin/src/screen/client-edit.tsx @@ -0,0 +1,417 @@ +import m from 'mithril'; +import { Modal } from '@component/modal'; +import { PageHeader } from '@component/page-header'; +import { RealmSelector } from '../component/realm-selector'; +import { + ClientForm, + clientFormValue, + defaultClientForm, + toClientInput, +} from '../component/client-form'; +import { + deleteAdminClient, + loadAdminClients, + loadAdminRoles, + rotateAdminClientSecret, + updateAdminClient, +} from '../util/auth'; +import { appUrl, type AdminClient, type AdminRealm, type AdminRole } from '../util/api'; + +interface ClientEditAttrs { + realmSlug: string | null; + clientId: string | null; + realms: AdminRealm[] | null; + realmsError: Error | null; + onAuthExpired: () => void; +} + +function clientKey(realmSlug: string | null, clientId: string | null) { + return `${realmSlug || ''}:${clientId || ''}`; +} + +export const ClientEditPage: m.Component<ClientEditAttrs> = { + attrs: null as ClientEditAttrs | null, + loadedKey: null as string | null, + loading: false, + redirecting: false, + clients: null as AdminClient[] | null, + roles: [] as AdminRole[], + form: defaultClientForm(), + error: null as Error | null, + formError: null as Error | string | null, + notice: null as string | null, + secret: null as { clientId: string; secret: string } | null, + pending: false, + rotateConfirm: false, + rotating: false, + deleteOpen: false, + deleting: false, + + oninit(this: any, vnode: m.Vnode<ClientEditAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + onupdate(this: any, vnode: m.Vnode<ClientEditAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + ensure(this: any) { + const { realms, realmSlug, clientId } = this.attrs; + if (!realms) return; + + if (realms.length === 0) { + this.clients = []; + 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(`/clients/${encodeURIComponent(realms[0].slug)}`, null, { replace: true }); + } + return; + } + + this.redirecting = false; + const key = clientKey(realmSlug, clientId); + if (key === this.loadedKey) return; + + this.loadedKey = key; + this.form = defaultClientForm(); + this.formError = null; + this.notice = null; + this.secret = null; + this.pending = false; + this.rotateConfirm = false; + this.rotating = false; + this.deleteOpen = false; + this.deleting = false; + if (realmSlug && clientId) this.load(realmSlug, clientId); + }, + + async load(this: any, realmSlug: string, clientId: string) { + this.loading = true; + this.error = null; + this.formError = null; + this.notice = null; + this.secret = null; + m.redraw(); + + try { + const [clients, roles] = await Promise.all([ + loadAdminClients(realmSlug), + loadAdminRoles(realmSlug), + ]); + if (this.loadedKey !== clientKey(realmSlug, clientId)) return; + + this.clients = clients; + this.roles = roles; + const client = clients.find((item) => item.client_id === clientId); + if (client) this.form = clientFormValue(client); + } catch (e: any) { + if (this.loadedKey !== clientKey(realmSlug, clientId)) return; + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + if (this.loadedKey === clientKey(realmSlug, clientId)) this.loading = false; + m.redraw(); + } + }, + + async submit(this: any) { + const { realmSlug, clientId } = this.attrs; + if (!realmSlug || !clientId) return; + + this.pending = true; + this.formError = null; + this.notice = null; + + try { + const response = await updateAdminClient(realmSlug, clientId, toClientInput(this.form)); + this.form = clientFormValue(response.client); + this.notice = 'Client settings saved.'; + await this.load(realmSlug, clientId); + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.formError = e as Error; + } finally { + this.pending = false; + m.redraw(); + } + }, + + async rotate(this: any) { + const { realmSlug, clientId } = this.attrs; + if (!realmSlug || !clientId) return; + + this.rotating = true; + this.error = null; + this.notice = null; + this.secret = null; + + try { + const response = await rotateAdminClientSecret(realmSlug, clientId); + this.secret = { clientId, secret: response.client_secret }; + this.rotateConfirm = false; + await this.load(realmSlug, clientId); + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + this.rotating = false; + m.redraw(); + } + }, + + openDelete(this: any) { + this.deleteOpen = true; + this.error = null; + m.redraw(); + }, + + cancelDelete(this: any) { + this.deleteOpen = false; + m.redraw(); + }, + + async deleteClient(this: any) { + const { realmSlug, clientId } = this.attrs; + if (!realmSlug || !clientId) return; + + this.deleting = true; + this.error = null; + + try { + await deleteAdminClient(realmSlug, clientId); + m.route.set(`/clients/${encodeURIComponent(realmSlug)}`); + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + this.deleting = false; + m.redraw(); + } + }, + + view(this: any) { + const { realms, realmsError, clientId } = this.attrs; + const selected = + realms?.find((realm) => realm.slug === this.attrs.realmSlug) || realms?.[0] || null; + const client = this.clients?.find((item) => item.client_id === clientId) || null; + + return ( + <div> + <PageHeader row title="Edit client" subtitle="OIDC client registration."> + <RealmSelector + realms={realms} + selected={selected} + onchange={(slug: string) => { + m.route.set(`/clients/${encodeURIComponent(slug)}`); + }} + /> + </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} + </div> + ) : null} + + {this.error ? ( + <div class="alert" role="alert"> + <p>{this.error.message}</p> + <button + class="button-secondary" + type="button" + onclick={() => { + if (this.attrs.realmSlug && clientId) { + this.load(this.attrs.realmSlug, clientId); + } + }} + > + Try again + </button> + </div> + ) : null} + + {this.notice ? ( + <div class="notice" role="status"> + {this.notice} + </div> + ) : null} + + {this.secret ? ( + <div class="panel secret-panel"> + <div class="secret-header"> + <div> + <h2>Client secret</h2> + <p class="note">{this.secret.clientId}</p> + </div> + <button + class="button-secondary" + type="button" + onclick={() => { + this.secret = null; + }} + > + Done + </button> + </div> + <p class="note">Copy this secret now. The previous secret no longer works.</p> + <code class="secret-value">{this.secret.secret}</code> + </div> + ) : null} + + {!realms ? ( + <div class="loading">Loading realms</div> + ) : this.loading || this.redirecting ? ( + <div class="panel" aria-busy="true"> + <div class="skeleton skeleton-title"></div> + <div class="skeleton"></div> + <div class="skeleton skeleton-short"></div> + </div> + ) : client ? ( + <div class="client-stack"> + <section class="panel"> + <h2>Settings</h2> + <ClientForm + value={this.form} + roles={this.roles} + editing={true} + submitLabel="Save changes" + pending={this.pending} + error={this.formError} + onsubmit={() => this.submit()} + oncancel={() => m.route.set(`/clients/${encodeURIComponent(this.attrs.realmSlug || '')}`)} + /> + </section> + + <section class="panel"> + <h2>Secret</h2> + <p class="note"> + {client.has_secret + ? 'A client secret is configured. Rotating invalidates the previous value.' + : 'No client secret is configured. Creating one switches this client to confidential authentication.'} + </p> + {this.rotateConfirm ? ( + <div class="client-actions"> + <button + class="button-danger" + type="button" + disabled={this.rotating} + onclick={() => this.rotate()} + > + {this.rotating ? 'Rotating' : 'Confirm'} + </button> + <button + class="button-secondary" + type="button" + disabled={this.rotating} + onclick={() => { + this.rotateConfirm = false; + m.redraw(); + }} + > + Cancel + </button> + </div> + ) : ( + <div class="client-actions"> + <button + class="button" + type="button" + disabled={this.rotating} + onclick={() => { + this.rotateConfirm = true; + m.redraw(); + }} + > + {client.has_secret ? 'Rotate secret' : 'Create secret'} + </button> + </div> + )} + </section> + + <section class="panel danger-zone"> + <h2>Danger zone</h2> + <p class="note"> + Deleting removes the client registration and related authorization state. + </p> + <div class="client-actions"> + <button + class="button-danger" + type="button" + onclick={() => this.openDelete()} + > + Delete client + </button> + </div> + </section> + </div> + ) : ( + <div class="empty"> + <p>This client was not found in the selected realm.</p> + </div> + )} + + {this.deleteOpen && client ? ( + <Modal title="Delete client" onClose={() => this.cancelDelete()}> + <p class="modal-note"> + Delete {client.name} ({client.client_id}) from {this.attrs.realmSlug}? + This cannot be undone. + </p> + <div class="modal-actions"> + <button + class="button-secondary" + type="button" + disabled={this.deleting} + onclick={() => this.cancelDelete()} + > + Cancel + </button> + <button + class="button-danger" + type="button" + disabled={this.deleting} + onclick={() => this.deleteClient()} + > + {this.deleting ? 'Deleting' : 'Delete client'} + </button> + </div> + </Modal> + ) : null} + </div> + ); + }, +}; diff --git a/app/admin/src/screen/clients.tsx b/app/admin/src/screen/clients.tsx @@ -0,0 +1,411 @@ +import { AppWindow } from 'lucide'; +import m from 'mithril'; +import { Icon } from '@component/icon'; +import { Modal } from '@component/modal'; +import { PageHeader } from '@component/page-header'; +import { RealmSelector } from '../component/realm-selector'; +import { + ClientForm, + defaultClientForm, + parseUriLines, + toClientInput, + type ClientFormValue, +} from '../component/client-form'; +import { + createAdminClient, + loadAdminClients, + loadAdminRoles, +} from '../util/auth'; +import { + appUrl, + type AdminClient, + type AdminClientResponse, + type AdminRealm, + type AdminRole, +} from '../util/api'; + +interface ClientsAttrs { + realmSlug: string | null; + realms: AdminRealm[] | null; + realmsError: Error | null; + onAuthExpired: () => void; +} + +const ACCESS_MODE_LABELS: Record<AdminClient['access_mode'], string> = { + internal: 'Internal', + members: 'Members', + public: 'Public', +}; + +function matchesSearch(client: AdminClient, term: string) { + if (!term) return true; + const haystack = [ + client.name, + client.client_id, + ACCESS_MODE_LABELS[client.access_mode], + ].join(' ').toLowerCase(); + return haystack.includes(term); +} + +function clientPath(realmSlug: string, clientId: string) { + return `/clients/${encodeURIComponent(realmSlug)}/edit/${encodeURIComponent(clientId)}`; +} + +export const ClientsPage: m.Component<ClientsAttrs> = { + attrs: null as ClientsAttrs | null, + loadedRealm: null as string | null, + loading: false, + redirecting: false, + clients: null as AdminClient[] | null, + roles: [] as AdminRole[], + search: '', + error: null as Error | null, + notice: null as string | null, + secret: null as { clientId: string; secret: string } | null, + creating: false, + createOpen: false, + createValue: defaultClientForm(), + createError: null as Error | string | null, + + oninit(this: any, vnode: m.Vnode<ClientsAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + onupdate(this: any, vnode: m.Vnode<ClientsAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + ensure(this: any) { + const { realms, realmSlug } = this.attrs; + if (!realms) return; + + if (realms.length === 0) { + this.clients = []; + 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(`/clients/${encodeURIComponent(realms[0].slug)}`, null, { + replace: true, + }); + } + return; + } + + this.redirecting = false; + if (this.loadedRealm !== realmSlug) { + this.search = ''; + this.notice = null; + this.secret = null; + this.createOpen = false; + this.createValue = defaultClientForm(); + this.createError = null; + this.load(realmSlug); + } + }, + + async load(this: any, realmSlug: string) { + this.loadedRealm = realmSlug; + this.loading = true; + this.error = null; + this.clients = null; + m.redraw(); + + try { + const [clients, roles] = await Promise.all([ + loadAdminClients(realmSlug), + loadAdminRoles(realmSlug), + ]); + if (this.loadedRealm === realmSlug) { + this.clients = clients; + this.roles = roles; + } + } 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(); + } + }, + + openCreate(this: any) { + this.createOpen = true; + this.createValue = defaultClientForm(); + this.createError = null; + m.redraw(); + }, + + cancelCreate(this: any) { + this.createOpen = false; + this.createValue = defaultClientForm(); + this.createError = null; + m.redraw(); + }, + + async submitCreate(this: any) { + const { realmSlug } = this.attrs; + if (!realmSlug) return; + + const value: ClientFormValue = this.createValue; + const clientId = value.client_id.trim(); + if (!clientId || !value.name.trim() || parseUriLines(value.redirect_uris).length === 0) { + this.createError = 'Client ID, name, and at least one redirect URI are required.'; + m.redraw(); + return; + } + + this.creating = true; + this.createError = null; + this.secret = null; + + try { + const response: AdminClientResponse = await createAdminClient(realmSlug, { + client_id: clientId, + ...toClientInput(value), + }); + this.notice = `Client ${response.client.name} created.`; + if (response.client_secret) { + this.secret = { clientId: response.client.client_id, secret: response.client_secret }; + } + this.createOpen = false; + this.createValue = defaultClientForm(); + await this.load(realmSlug); + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.createError = e as Error; + } finally { + this.creating = false; + m.redraw(); + } + }, + + view(this: any) { + const { realms, realmsError } = this.attrs; + const selected = + realms?.find((realm) => realm.slug === this.attrs.realmSlug) || realms?.[0] || null; + const term = this.search.trim().toLowerCase(); + const visibleClients = (this.clients || []).filter((client: AdminClient) => + matchesSearch(client, term) + ); + + return ( + <div> + <PageHeader + row + title="Clients" + subtitle="OIDC clients registered in this realm." + > + <RealmSelector + realms={realms} + selected={selected} + onchange={(slug: string) => { + this.search = ''; + this.notice = null; + this.secret = null; + m.route.set(`/clients/${encodeURIComponent(slug)}`); + }} + /> + </PageHeader> + + {this.error ? ( + <div class="alert" role="alert"> + <p>{this.error.message}</p> + {this.attrs.realmSlug ? ( + <button + class="button-secondary" + type="button" + onclick={() => this.load(this.attrs.realmSlug)} + > + Try again + </button> + ) : null} + </div> + ) : null} + + {this.notice ? ( + <div class="notice" role="status"> + {this.notice} + </div> + ) : null} + + + + {!realms ? ( + <div class="loading">Loading realms</div> + ) : realms.length === 0 ? ( + <div class="empty"> + <p>No realms are available for this account.</p> + </div> + ) : ( + <div class="table-panel"> + <div class="table-toolbar"> + <div class="table-search"> + <input + type="search" + value={this.search} + aria-label="Search clients" + placeholder="Search clients" + oninput={(event: Event) => { + this.search = (event.target as HTMLInputElement).value; + }} + /> + </div> + <div class="table-actions"> + <button + class="button" + type="button" + disabled={!this.attrs.realmSlug} + onclick={() => this.openCreate()} + > + New client + </button> + </div> + </div> + + {this.loading || this.redirecting || !this.clients ? ( + <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> + ) : this.clients.length === 0 ? ( + <div class="empty"> + <p>No OIDC clients are registered in this realm.</p> + </div> + ) : ( + <div class="data-table-wrap"> + <table class="data-table"> + <thead> + <tr> + <th class="table-icon-column" scope="col"> + <span class="sr-only">Icon</span> + </th> + <th class="data-table-primary" scope="col">Application</th> + <th scope="col">Access</th> + </tr> + </thead> + <tbody> + {visibleClients.map((client: AdminClient) => { + const href = clientPath(this.attrs.realmSlug || '', client.client_id); + return ( + <tr + tabindex="0" + onclick={() => { + if (this.attrs.realmSlug) m.route.set(href); + }} + onkeydown={(event: KeyboardEvent) => { + if ( + event.target !== event.currentTarget || + !this.attrs.realmSlug + ) { + return; + } + if (event.key !== 'Enter' && event.key !== ' ') return; + event.preventDefault(); + m.route.set(href); + }} + > + <td> + <span class="table-icon" aria-hidden="true"> + {client.logo_url ? ( + <img src={client.logo_url} alt="" /> + ) : ( + Icon(AppWindow) + )} + </span> + </td> + <td class="data-table-primary"> + <a + class="client-title" + href={appUrl(href)} + onclick={(event: MouseEvent) => { + event.preventDefault(); + event.stopPropagation(); + if (this.attrs.realmSlug) m.route.set(href); + }} + > + <strong>{client.name}</strong> + </a> + <span class="data-table-sub">{client.client_id}</span> + {client.enabled ? null : ( + <span class="data-table-status">Disabled</span> + )} + </td> + <td>{ACCESS_MODE_LABELS[client.access_mode]}</td> + </tr> + ); + })} + </tbody> + </table> + {visibleClients.length === 0 ? ( + <div class="empty"> + <p>No clients match this search.</p> + </div> + ) : null} + </div> + )} + </div> + )} + + {this.createOpen ? ( + <Modal title="Register a client" onClose={() => this.cancelCreate()}> + <ClientForm + value={this.createValue} + roles={this.roles} + editing={false} + submitLabel="Create client" + pending={this.creating} + error={this.createError} + onsubmit={() => this.submitCreate()} + oncancel={() => this.cancelCreate()} + /> + </Modal> + ) : null} + + {this.secret ? ( + <Modal + title="Client secret created" + onClose={() => { + this.secret = null; + m.redraw(); + }} + > + <p class="modal-note"> + Copy the secret for {this.secret.clientId} now. It will not be shown again. + </p> + <code class="secret-value">{this.secret.secret}</code> + <div class="modal-actions"> + <button + class="button" + type="button" + onclick={() => { + this.secret = null; + m.redraw(); + }} + > + Done + </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 { RealmSelector } from '../component/realm-selector'; import type { AdminRealm, AdminSession } from '../util/api'; import { loadAdminSessions, @@ -66,6 +67,9 @@ export const SessionsPage: m.Component<SessionsAttrs> = { this.redirecting = false; if (this.loadedRealm !== realmSlug) { + this.notice = null; + this.confirmKey = null; + this.pendingKey = null; this.load(realmSlug); } }, @@ -137,25 +141,14 @@ export const SessionsPage: m.Component<SessionsAttrs> = { title="Sessions" subtitle="Active sessions with access to this realm." > - {realms && realms.length > 1 ? ( - <label class="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="realm-current">{selected.display_name}</span> - ) : null} + <RealmSelector + realms={realms} + selected={selected} + onchange={(slug: string) => { + this.notice = null; + m.route.set(`/sessions/${encodeURIComponent(slug)}`); + }} + /> </PageHeader> {realmsError ? ( diff --git a/app/admin/src/util/api.ts b/app/admin/src/util/api.ts @@ -10,6 +10,59 @@ export interface AdminRealm { display_name: string; } +export interface AdminRole { + slug: string; + name: string; +} + +export interface AdminClient { + client_id: string; + name: string; + logo_url: string | null; + access_mode: 'internal' | 'members' | 'public'; + enabled: boolean; + scopes: string; + required_roles: string[]; + redirect_uris: string[]; + post_logout_redirect_uris: string[]; + token_endpoint_auth_method: 'none' | 'client_secret_basic'; + require_pkce: boolean; + consent_mode: 'remembered' | 'trusted'; + has_secret: boolean; + created_at: number; + updated_at: number; +} + +export interface AdminClientInput { + name: string; + access_mode: AdminClient['access_mode']; + enabled: boolean; + scopes: string; + required_roles: string[]; + redirect_uris: string[]; + post_logout_redirect_uris: string[]; + token_endpoint_auth_method: AdminClient['token_endpoint_auth_method']; + require_pkce: boolean; + consent_mode: AdminClient['consent_mode']; +} + +export interface AdminClientCreateInput extends AdminClientInput { + client_id: string; +} + +export interface AdminClientResponse { + ok: boolean; + client: AdminClient; + client_secret?: string; +} + +export interface AdminClientSecretResponse { + ok: boolean; + client_id: string; + client: AdminClient; + client_secret: string; +} + export interface AdminSession { public_id: string; user: { @@ -64,6 +117,7 @@ export async function adminApi(path: string, accessToken: string, init: RequestI const authUrl = await getAuthUrl(); const headers = new Headers(init.headers); headers.set('authorization', `Bearer ${accessToken}`); + if (init.body !== undefined) headers.set('content-type', 'application/json'); return fetch(`${authUrl}${path}`, { ...init, credentials: 'omit', diff --git a/app/admin/src/util/auth.ts b/app/admin/src/util/auth.ts @@ -4,7 +4,13 @@ import { adminApi, appUrl, getDiscovery, + type AdminClient, + type AdminClientCreateInput, + type AdminClientInput, + type AdminClientResponse, + type AdminClientSecretResponse, type AdminRealm, + type AdminRole, type AdminSession, } from './api'; @@ -68,3 +74,69 @@ export async function terminateAdminSession(realmSlug: string, publicId: string) method: 'DELETE', }); } + +export async function loadAdminRoles(realmSlug: string): Promise<AdminRole[]> { + const realm = encodeURIComponent(realmSlug); + const response = await adminJson<{ roles: AdminRole[] }>( + `/api/v1/admin/realms/${realm}/roles` + ); + return response.roles; +} + +export async function loadAdminClients(realmSlug: string): Promise<AdminClient[]> { + const realm = encodeURIComponent(realmSlug); + const response = await adminJson<{ clients: AdminClient[] }>( + `/api/v1/admin/realms/${realm}/clients` + ); + return response.clients; +} + +export async function createAdminClient( + realmSlug: string, + input: AdminClientCreateInput +): Promise<AdminClientResponse> { + const realm = encodeURIComponent(realmSlug); + return adminJson<AdminClientResponse>(`/api/v1/admin/realms/${realm}/clients`, { + method: 'POST', + body: JSON.stringify(input), + }); +} + +export async function updateAdminClient( + realmSlug: string, + clientId: string, + input: AdminClientInput +): Promise<AdminClientResponse> { + const realm = encodeURIComponent(realmSlug); + const client = encodeURIComponent(clientId); + return adminJson<AdminClientResponse>( + `/api/v1/admin/realms/${realm}/clients/${client}`, + { + method: 'PATCH', + body: JSON.stringify(input), + } + ); +} + +export async function deleteAdminClient(realmSlug: string, clientId: string) { + const realm = encodeURIComponent(realmSlug); + const client = encodeURIComponent(clientId); + return adminJson(`/api/v1/admin/realms/${realm}/clients/${client}`, { + method: 'DELETE', + }); +} + +export async function rotateAdminClientSecret( + realmSlug: string, + clientId: string +): Promise<AdminClientSecretResponse> { + const realm = encodeURIComponent(realmSlug); + const client = encodeURIComponent(clientId); + return adminJson<AdminClientSecretResponse>( + `/api/v1/admin/realms/${realm}/clients/${client}/secret`, + { + method: 'POST', + body: JSON.stringify({}), + } + ); +} diff --git a/app/login/src/assets/login.css b/app/login/src/assets/login.css @@ -18,15 +18,14 @@ body { .auth-page { min-height: 100vh; - display: flex; - justify-content: center; - align-items: flex-start; - padding: 12vh 1.5rem 3rem; + display: grid; + place-items: center; + padding: 0; background: var(--auth-surface); } .auth-card { - width: min(24rem, 100%); + width: min(calc(100% - 2rem), 24rem); padding: 2rem; background: var(--auth-surface); border-radius: 0; @@ -212,7 +211,7 @@ body { } .auth-card-consent { - width: min(28rem, 100%); + width: min(calc(100% - 2rem), 28rem); } .auth-consent-account { diff --git a/app/shared/component/modal.tsx b/app/shared/component/modal.tsx @@ -0,0 +1,58 @@ +import { X } from 'lucide'; +import m from 'mithril'; +import { Icon } from './icon'; + +export interface ModalAttrs { + title: string; + onClose: () => void; +} + +export const Modal: m.Component<ModalAttrs> = { + oncreate(this: any, vnode: m.Vnode<ModalAttrs>) { + this.focusBefore = document.activeElement; + this.onKeydown = (event: KeyboardEvent) => { + if (event.key === 'Escape') vnode.attrs.onClose(); + }; + window.addEventListener('keydown', this.onKeydown); + const target = vnode.dom?.querySelector('[data-modal-autofocus]') as HTMLElement | null; + target?.focus(); + }, + + onremove(this: any) { + window.removeEventListener('keydown', this.onKeydown); + (this.focusBefore as HTMLElement | null)?.focus?.(); + }, + + view({ attrs, children }) { + return ( + <div + class="modal-overlay" + onmousedown={(event: MouseEvent) => { + if (event.target === event.currentTarget) attrs.onClose(); + }} + > + <div + class="modal" + role="dialog" + aria-modal="true" + aria-label={attrs.title} + tabindex="-1" + > + <div class="modal-header"> + <h2 id={`modal-${attrs.title}`}>{attrs.title}</h2> + <button + class="modal-close" + type="button" + aria-label="Close dialog" + data-modal-autofocus + onclick={() => attrs.onClose()} + > + {Icon(X)} + </button> + </div> + <div class="modal-body">{children}</div> + </div> + </div> + ); + }, +}; diff --git a/app/shared/style/global.css b/app/shared/style/global.css @@ -545,6 +545,225 @@ textarea { margin-top: 1.5rem; } +.sr-only { + position: absolute; + width: 1pt; + height: 1pt; + padding: 0; + margin: -1pt; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +.table-panel { + background: var(--surface); + color: var(--text); + box-shadow: var(--shadow); +} + +.table-toolbar { + display: flex; + flex-direction: column; + gap: 1rem; + padding: 1rem 1.5rem; + border-bottom: 1pt solid var(--row); +} + +.table-search { + flex: 1; + min-width: 0; +} + +.table-search input { + width: 100%; + padding: 0.5rem 0; + border: 0; + border-bottom: 1pt solid var(--field-line); + border-radius: 0; + background: transparent; + color: inherit; + font: inherit; + font-size: 1rem; + line-height: 1.5; + outline: none; +} + +.table-search input:focus { + border-bottom-color: var(--accent); +} + +.table-actions { + display: flex; + justify-content: flex-end; + flex-wrap: wrap; + gap: 1rem; +} + +.data-table-wrap { + overflow-x: auto; +} + +.data-table { + width: 100%; + border-collapse: collapse; + font-size: 0.875rem; +} + +.data-table th, +.data-table td { + padding: 0.75rem 1.5rem; + border-bottom: 1pt solid var(--row); + text-align: left; + vertical-align: middle; +} + +.data-table th { + color: var(--muted); + font-size: 0.75rem; + font-weight: 500; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.data-table tbody tr { + cursor: pointer; +} + +.data-table tbody tr:hover { + background: var(--row-hover); +} + +.data-table tbody tr:focus-visible { + outline: 2pt solid var(--accent); + outline-offset: -2pt; +} + +.data-table tbody tr:last-child td { + border-bottom: 0; +} + +.table-icon-column { + width: 1%; +} + +.data-table-primary { + min-width: 16rem; +} + +.data-table-sub { + display: block; + margin-top: 0.125rem; + color: var(--muted); + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: 0.8125rem; + overflow-wrap: anywhere; +} + +.data-table-status { + display: block; + margin-top: 0.125rem; + color: var(--muted); + font-size: 0.8125rem; +} + +.table-icon { + display: grid; + place-items: center; + width: 2rem; + height: 2rem; + flex: none; + overflow: hidden; + background: var(--row); + color: var(--muted); +} + +.table-icon img { + width: 100%; + height: 100%; + object-fit: contain; +} + +.table-icon svg { + width: 1.125rem; + height: 1.125rem; +} + +.modal-overlay { + position: fixed; + inset: 0; + z-index: 100; + display: grid; + place-items: center; + padding: 1rem; + background: rgba(0, 0, 0, 0.58); +} + +.modal { + width: min(100%, 32rem); + max-height: calc(100vh - 2rem); + overflow: auto; + background: var(--surface); + color: var(--text); + box-shadow: var(--shadow); +} + +.modal-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + padding: 1.5rem 1.5rem 0; +} + +.modal-header h2 { + margin: 0; + font-size: 1.25rem; + font-weight: 400; + line-height: 1.3; +} + +.modal-close { + display: grid; + place-items: center; + width: 2rem; + height: 2rem; + padding: 0; + border: 0; + border-radius: 0; + background: transparent; + color: var(--muted); + cursor: pointer; +} + +.modal-close:hover { + color: var(--text); +} + +.modal-close svg { + width: 1.25rem; + height: 1.25rem; +} + +.modal-body { + padding: 1.5rem; +} + +.modal-note { + margin: 0; + color: var(--muted); + font-size: 0.875rem; + line-height: 1.6; +} + +.modal-actions { + display: flex; + justify-content: flex-end; + gap: 1rem; + margin-top: 1.5rem; +} + a:focus-visible, button:focus-visible, summary:focus-visible, @@ -568,6 +787,11 @@ select:focus-visible { } @media (min-width: 40em) { + .table-toolbar { + flex-direction: row; + align-items: center; + } + .nav-item span { display: inline; } diff --git a/mockup/plain/admin-client-detail.html b/mockup/plain/admin-client-detail.html @@ -0,0 +1,280 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>Admin client detail mockup</title> + <link rel="stylesheet" href="./global.css" /> + </head> + <body> + <header class="topbar"> + <a class="brand" href="./admin-dashboard.html"> + <svg class="brand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /> + </svg> + <span class="brand-name">Auth</span> + </a> + <details class="user-menu"> + <summary aria-label="Account menu"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="10" /> + <circle cx="12" cy="10" r="3" /> + <path d="M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662" /> + </svg> + </summary> + <div class="user-panel"> + <div class="user-summary"> + <span class="user-name">System Admin</span> + <span class="user-meta">admin@system.test</span> + </div> + <div class="user-menu-list"> + <a class="user-menu-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" /> + <circle cx="12" cy="12" r="3" /> + </svg> + <span>Account settings</span> + </a> + <button class="user-menu-item" type="button" data-user-theme> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="4" /> + <path d="M12 2v2" /> + <path d="M12 20v2" /> + <path d="m4.93 4.93 1.41 1.41" /> + <path d="m17.66 17.66 1.41 1.41" /> + <path d="M2 12h2" /> + <path d="M20 12h2" /> + <path d="m6.34 17.66-1.41 1.41" /> + <path d="m19.07 4.93-1.41 1.41" /> + </svg> + <span>Theme</span> + <span class="user-menu-value" data-user-theme-value>Auto</span> + </button> + <a class="user-menu-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" /> + <path d="m16 17 5-5-5-5" /> + <path d="M21 12H9" /> + </svg> + <span>Sign out</span> + </a> + </div> + </div> + </details> + </header> + + <div class="app"> + <aside class="sidebar"> + <nav class="nav" aria-label="Administration"> + <p class="nav-label">Administration</p> + <a class="nav-item" href="./admin-dashboard.html"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <rect x="3" y="3" width="7" height="7" /> + <rect x="14" y="3" width="7" height="7" /> + <rect x="3" y="14" width="7" height="7" /> + <rect x="14" y="14" width="7" height="7" /> + </svg> + <span>Overview</span> + </a> + <a class="nav-item is-active" href="./admin-clients.html" aria-current="page"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <rect x="2" y="4" width="20" height="16" rx="2" /> + <path d="M10 4v4" /> + <path d="M2 8h20" /> + <path d="M6 4v4" /> + </svg> + <span>Clients</span> + </a> + <a class="nav-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M22 12h-4l-3 8-6-16-3 8H2" /> + </svg> + <span>Sessions</span> + </a> + <a class="nav-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="9" /> + <path d="M3 12h18" /> + <path d="M12 3a15 15 0 0 1 0 18a15 15 0 0 1 0-18" /> + </svg> + <span>Realms</span> + </a> + <a class="nav-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> + <circle cx="12" cy="7" r="4" /> + </svg> + <span>Users</span> + </a> + </nav> + </aside> + + <div class="main"> + <main class="content"> + <div class="page-header page-header-row"> + <div> + <div class="client-breadcrumb"> + <a href="./admin-clients.html">Clients</a> + <span aria-hidden="true">/</span> + <span>Internal App</span> + </div> + <h1>Internal App</h1> + <p>internal-app</p> + </div> + <button class="button" type="button">Save changes</button> + </div> + + <div class="client-stack"> + <section class="panel"> + <h2>Settings</h2> + <dl class="details"> + <div> + <dt>Access mode</dt> + <dd>Internal</dd> + </div> + <div> + <dt>Consent</dt> + <dd>Remembered</dd> + </div> + <div> + <dt>Token authentication</dt> + <dd>Public client: PKCE</dd> + </div> + <div> + <dt>Scopes</dt> + <dd>openid profile email</dd> + </div> + <div> + <dt>Redirect URIs</dt> + <dd>https://app.acme.localhost/callback</dd> + </div> + <div> + <dt>Required roles</dt> + <dd>None</dd> + </div> + </dl> + </section> + + <section class="panel"> + <h2>Secret</h2> + <p class="note">No client secret is configured. Creating one switches this client to confidential authentication.</p> + <div class="client-actions"> + <button class="button" type="button">Create secret</button> + </div> + </section> + + <section class="panel danger-zone"> + <h2>Danger zone</h2> + <p class="note">Deleting removes the client registration and related authorization state.</p> + <div class="client-actions"> + <button class="button-danger" type="button" data-dialog-open="client-delete-dialog">Delete client</button> + </div> + </section> + </div> + </main> + </div> + </div> + + <div id="client-delete-dialog" class="modal-overlay" hidden> + <div class="modal" role="dialog" aria-modal="true" aria-labelledby="client-delete-title"> + <div class="modal-header"> + <h2 id="client-delete-title">Delete client</h2> + <button class="modal-close" type="button" aria-label="Close dialog" data-dialog-close> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M18 6 6 18" /> + <path d="m6 6 12 12" /> + </svg> + </button> + </div> + <div class="modal-body"> + <p class="modal-note"> + Delete Internal App (internal-app) from acme? This cannot be undone. + </p> + <div class="modal-actions"> + <button class="button-secondary" type="button" data-dialog-close>Cancel</button> + <button class="button-danger" type="button" data-dialog-close>Delete client</button> + </div> + </div> + </div> + </div> + + <div class="mockup-controls" aria-label="Mockup theme"> + <span class="mockup-label">Mockup</span> + <button class="mockup-button is-active" type="button" data-theme-target="auto">Auto</button> + <button class="mockup-button" type="button" data-theme-target="light">Light</button> + <button class="mockup-button" type="button" data-theme-target="dark">Dark</button> + </div> + + <script> + const root = document.documentElement; + const themeButtons = document.querySelectorAll('[data-theme-target]'); + const userThemeButton = document.querySelector('[data-user-theme]'); + const userThemeValue = document.querySelector('[data-user-theme-value]'); + let currentTheme = 'auto'; + + function setTheme(value) { + currentTheme = value; + if (value === 'auto') { + root.removeAttribute('data-theme'); + } else { + root.setAttribute('data-theme', value); + } + themeButtons.forEach((button) => { + button.classList.toggle('is-active', button.dataset.themeTarget === value); + }); + if (userThemeValue) { + userThemeValue.textContent = value.charAt(0).toUpperCase() + value.slice(1); + } + } + + themeButtons.forEach((button) => { + button.addEventListener('click', () => setTheme(button.dataset.themeTarget)); + }); + + userThemeButton?.addEventListener('click', () => { + const themes = ['auto', 'light', 'dark']; + setTheme(themes[(themes.indexOf(currentTheme) + 1) % themes.length]); + }); + + const userMenu = document.querySelector('.user-menu'); + document.addEventListener('click', (event) => { + if (userMenu && userMenu.open && !userMenu.contains(event.target)) { + userMenu.open = false; + } + }); + + function visibleDialogs() { + return [...document.querySelectorAll('.modal-overlay:not([hidden])')]; + } + + document.querySelectorAll('[data-dialog-open]').forEach((button) => { + button.addEventListener('click', () => { + const dialog = document.getElementById(button.dataset.dialogOpen); + if (!dialog) return; + dialog.hidden = false; + dialog.querySelector('.modal-close')?.focus(); + }); + }); + + document.querySelectorAll('[data-dialog-close]').forEach((button) => { + button.addEventListener('click', () => { + button.closest('.modal-overlay').hidden = true; + }); + }); + + document.querySelectorAll('.modal-overlay').forEach((overlay) => { + overlay.addEventListener('mousedown', (event) => { + if (event.target === overlay) overlay.hidden = true; + }); + }); + + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape') { + visibleDialogs().forEach((dialog) => { + dialog.hidden = true; + }); + } + }); + </script> + </body> +</html> diff --git a/mockup/plain/admin-clients.html b/mockup/plain/admin-clients.html @@ -0,0 +1,365 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>Admin clients mockup</title> + <link rel="stylesheet" href="./global.css" /> + </head> + <body> + <header class="topbar"> + <a class="brand" href="./admin-dashboard.html"> + <svg class="brand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /> + </svg> + <span class="brand-name">Auth</span> + </a> + <details class="user-menu"> + <summary aria-label="Account menu"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="10" /> + <circle cx="12" cy="10" r="3" /> + <path d="M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662" /> + </svg> + </summary> + <div class="user-panel"> + <div class="user-summary"> + <span class="user-name">System Admin</span> + <span class="user-meta">admin@system.test</span> + </div> + <div class="user-menu-list"> + <a class="user-menu-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" /> + <circle cx="12" cy="12" r="3" /> + </svg> + <span>Account settings</span> + </a> + <button class="user-menu-item" type="button" data-user-theme> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="4" /> + <path d="M12 2v2" /> + <path d="M12 20v2" /> + <path d="m4.93 4.93 1.41 1.41" /> + <path d="m17.66 17.66 1.41 1.41" /> + <path d="M2 12h2" /> + <path d="M20 12h2" /> + <path d="m6.34 17.66-1.41 1.41" /> + <path d="m19.07 4.93-1.41 1.41" /> + </svg> + <span>Theme</span> + <span class="user-menu-value" data-user-theme-value>Auto</span> + </button> + <a class="user-menu-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" /> + <path d="m16 17 5-5-5-5" /> + <path d="M21 12H9" /> + </svg> + <span>Sign out</span> + </a> + </div> + </div> + </details> + </header> + + <div class="app"> + <aside class="sidebar"> + <nav class="nav" aria-label="Administration"> + <p class="nav-label">Administration</p> + <a class="nav-item" href="./admin-dashboard.html"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <rect x="3" y="3" width="7" height="7" /> + <rect x="14" y="3" width="7" height="7" /> + <rect x="3" y="14" width="7" height="7" /> + <rect x="14" y="14" width="7" height="7" /> + </svg> + <span>Overview</span> + </a> + <a class="nav-item is-active" href="./admin-clients.html" aria-current="page"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <rect x="2" y="4" width="20" height="16" rx="2" /> + <path d="M10 4v4" /> + <path d="M2 8h20" /> + <path d="M6 4v4" /> + </svg> + <span>Clients</span> + </a> + <a class="nav-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M22 12h-4l-3 8-6-16-3 8H2" /> + </svg> + <span>Sessions</span> + </a> + <a class="nav-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="9" /> + <path d="M3 12h18" /> + <path d="M12 3a15 15 0 0 1 0 18a15 15 0 0 1 0-18" /> + </svg> + <span>Realms</span> + </a> + <a class="nav-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> + <circle cx="12" cy="7" r="4" /> + </svg> + <span>Users</span> + </a> + </nav> + </aside> + + <div class="main"> + <main class="content"> + <div class="page-header page-header-row"> + <div> + <h1>Clients</h1> + <p>OIDC clients registered in this realm.</p> + </div> + <label class="realm-select"> + <span>Realm</span> + <select> + <option selected>Acme</option> + <option>Globex</option> + </select> + </label> + </div> + + <section class="table-panel" aria-labelledby="client-table-title"> + <h2 id="client-table-title" class="sr-only">Registered clients</h2> + <div class="table-toolbar"> + <div class="table-search"> + <input id="client-search" type="search" aria-label="Search clients" placeholder="Search clients" /> + </div> + <div class="table-actions"> + <button class="button" type="button" data-dialog-open="client-create-dialog">New client</button> + </div> + </div> + + <div class="data-table-wrap"> + <table class="data-table"> + <thead> + <tr> + <th class="table-icon-column" scope="col"><span class="sr-only">Icon</span></th> + <th class="data-table-primary" scope="col">Application</th> + <th scope="col">Access</th> + </tr> + </thead> + <tbody id="client-rows"> + <tr data-row-href="./admin-client-detail.html" data-search="internal app internal-app internal"> + <td> + <span class="table-icon" aria-hidden="true"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> + <rect x="2" y="4" width="20" height="16" rx="2" /> + <path d="M10 4v4" /> + <path d="M2 8h20" /> + <path d="M6 4v4" /> + </svg> + </span> + </td> + <td class="data-table-primary"> + <a href="./admin-client-detail.html">Internal App</a> + <span class="data-table-sub">internal-app</span> + </td> + <td>Internal</td> + </tr> + <tr data-row-href="./admin-client-detail.html" data-search="members portal members-app members"> + <td> + <span class="table-icon" aria-hidden="true"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> + <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" /> + <circle cx="9" cy="7" r="4" /> + <path d="M22 21v-2a4 4 0 0 0-3-3.87" /> + <path d="M16 3.13a4 4 0 0 1 0 7.75" /> + </svg> + </span> + </td> + <td class="data-table-primary"> + <a href="./admin-client-detail.html">Members Portal</a> + <span class="data-table-sub">members-app</span> + </td> + <td>Members</td> + </tr> + <tr data-row-href="./admin-client-detail.html" data-search="public site public-app public"> + <td> + <span class="table-icon" aria-hidden="true"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> + <circle cx="12" cy="12" r="10" /> + <path d="M12 2a15.3 15.3 0 0 1 0 20" /> + <path d="M12 2a15.3 15.3 0 0 0 0 20" /> + <path d="M2 12h20" /> + </svg> + </span> + </td> + <td class="data-table-primary"> + <a href="./admin-client-detail.html">Public Site</a> + <span class="data-table-sub">public-app</span> + </td> + <td>Public</td> + </tr> + <tr data-row-href="./admin-client-detail.html" data-search="secure service secure-app members disabled confidential"> + <td> + <span class="table-icon" aria-hidden="true"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> + <rect x="3" y="11" width="18" height="11" rx="2" /> + <path d="M7 11V7a5 5 0 0 1 10 0v4" /> + </svg> + </span> + </td> + <td class="data-table-primary"> + <a href="./admin-client-detail.html">Secure Service</a> + <span class="data-table-sub">secure-app</span> + <span class="data-table-status">Disabled</span> + </td> + <td>Members</td> + </tr> + </tbody> + </table> + <div id="client-search-empty" class="empty" hidden> + <p>No clients match this search.</p> + </div> + </div> + </section> + </main> + </div> + </div> + + <div id="client-create-dialog" class="modal-overlay" hidden> + <div class="modal" role="dialog" aria-modal="true" aria-labelledby="client-create-title"> + <div class="modal-header"> + <h2 id="client-create-title">Register a client</h2> + <button class="modal-close" type="button" aria-label="Close dialog" data-dialog-close> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M18 6 6 18" /> + <path d="m6 6 12 12" /> + </svg> + </button> + </div> + <div class="modal-body"> + <label class="form-field"> + <span class="field-label">Client ID</span> + <input class="field-control" type="text" placeholder="my-app" /> + </label> + <label class="form-field"> + <span class="field-label">Name</span> + <input class="field-control" type="text" placeholder="My App" /> + </label> + <label class="form-field"> + <span class="field-label">Access mode</span> + <select class="field-control"> + <option>Internal: home-realm members</option> + <option selected>Members: active realm members</option> + <option>Public: any authenticated user</option> + </select> + </label> + <label class="form-field"> + <span class="field-label">Redirect URIs</span> + <textarea class="field-control" rows="3" placeholder="https://app.example.test/callback"></textarea> + </label> + <div class="modal-actions"> + <button class="button-secondary" type="button" data-dialog-close>Cancel</button> + <button class="button" type="button" data-dialog-close>Create client</button> + </div> + </div> + </div> + </div> + + <div class="mockup-controls" aria-label="Mockup theme"> + <span class="mockup-label">Mockup</span> + <button class="mockup-button is-active" type="button" data-theme-target="auto">Auto</button> + <button class="mockup-button" type="button" data-theme-target="light">Light</button> + <button class="mockup-button" type="button" data-theme-target="dark">Dark</button> + </div> + + <script> + const root = document.documentElement; + const themeButtons = document.querySelectorAll('[data-theme-target]'); + const userThemeButton = document.querySelector('[data-user-theme]'); + const userThemeValue = document.querySelector('[data-user-theme-value]'); + let currentTheme = 'auto'; + + function setTheme(value) { + currentTheme = value; + if (value === 'auto') { + root.removeAttribute('data-theme'); + } else { + root.setAttribute('data-theme', value); + } + themeButtons.forEach((button) => { + button.classList.toggle('is-active', button.dataset.themeTarget === value); + }); + if (userThemeValue) { + userThemeValue.textContent = value.charAt(0).toUpperCase() + value.slice(1); + } + } + + themeButtons.forEach((button) => { + button.addEventListener('click', () => setTheme(button.dataset.themeTarget)); + }); + + userThemeButton?.addEventListener('click', () => { + const themes = ['auto', 'light', 'dark']; + setTheme(themes[(themes.indexOf(currentTheme) + 1) % themes.length]); + }); + + const userMenu = document.querySelector('.user-menu'); + document.addEventListener('click', (event) => { + if (userMenu && userMenu.open && !userMenu.contains(event.target)) { + userMenu.open = false; + } + }); + + function visibleDialogs() { + return [...document.querySelectorAll('.modal-overlay:not([hidden])')]; + } + + document.querySelectorAll('[data-dialog-open]').forEach((button) => { + button.addEventListener('click', () => { + const dialog = document.getElementById(button.dataset.dialogOpen); + if (!dialog) return; + dialog.hidden = false; + dialog.querySelector('.modal-close')?.focus(); + }); + }); + + document.querySelectorAll('[data-dialog-close]').forEach((button) => { + button.addEventListener('click', () => { + button.closest('.modal-overlay').hidden = true; + }); + }); + + document.querySelectorAll('.modal-overlay').forEach((overlay) => { + overlay.addEventListener('mousedown', (event) => { + if (event.target === overlay) overlay.hidden = true; + }); + }); + + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape') { + visibleDialogs().forEach((dialog) => { + dialog.hidden = true; + }); + } + }); + + const search = document.getElementById('client-search'); + const empty = document.getElementById('client-search-empty'); + search?.addEventListener('input', () => { + const term = search.value.trim().toLowerCase(); + let visible = 0; + document.querySelectorAll('#client-rows tr').forEach((row) => { + const match = !term || row.dataset.search.includes(term); + row.hidden = !match; + if (match) visible += 1; + }); + if (empty) empty.hidden = visible > 0; + }); + + document.querySelectorAll('#client-rows tr[data-row-href]').forEach((row) => { + row.addEventListener('click', () => { + window.location.href = row.dataset.rowHref; + }); + }); + </script> + </body> +</html> diff --git a/mockup/plain/admin-dashboard.html b/mockup/plain/admin-dashboard.html @@ -111,6 +111,15 @@ </svg> <span>Overview</span> </a> + <a class="nav-item" href="./admin-clients.html"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <rect x="2" y="4" width="20" height="16" rx="2" /> + <path d="M10 4v4" /> + <path d="M2 8h20" /> + <path d="M6 4v4" /> + </svg> + <span>Clients</span> + </a> <a class="nav-item" href="#"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M22 12h-4l-3 8-6-16-3 8H2" /> @@ -132,14 +141,6 @@ </svg> <span>Users</span> </a> - <a class="nav-item" href="#"> - <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> - <circle cx="8" cy="15" r="4" /> - <path d="m11 12 9-9" /> - <path d="m17 6 3 3" /> - </svg> - <span>Clients</span> - </a> </nav> </aside> diff --git a/mockup/plain/global.css b/mockup/plain/global.css @@ -182,6 +182,26 @@ body { line-height: 1.5; } +.page-header-row { + display: grid; + gap: 1rem; + margin-bottom: 1.5rem; +} + +.page-header-row h1 { + margin: 0; + font-size: 1.5rem; + font-weight: 400; + line-height: 1.3; +} + +.page-header-row p { + margin: 0.25rem 0 0; + color: var(--muted); + font-size: 0.875rem; + line-height: 1.5; +} + .grid { display: grid; grid-template-columns: minmax(0, 1fr); @@ -419,6 +439,363 @@ body { background: rgba(255, 255, 255, 0.18); } +.button-secondary { + display: inline-block; + padding: 0.625rem 1.25rem; + border: 1pt solid var(--accent); + border-radius: 0; + background: transparent; + color: var(--accent-text); + font: inherit; + font-size: 0.8125rem; + font-weight: 500; + letter-spacing: 0.05em; + line-height: 1.4; + text-decoration: none; + text-transform: uppercase; + cursor: pointer; +} + +.button-secondary:hover { + background: var(--row-hover); + color: var(--accent-text-hover); +} + +.button-danger { + display: inline-block; + padding: 0.625rem 1.25rem; + border: 0; + border-radius: 0; + background: var(--danger); + color: #fff; + font: inherit; + font-size: 0.8125rem; + font-weight: 500; + letter-spacing: 0.05em; + line-height: 1.4; + text-decoration: none; + text-transform: uppercase; + cursor: pointer; +} + +.realm-select { + display: grid; + gap: 0.25rem; +} + +.realm-select > span { + color: var(--muted); + font-size: 0.75rem; + line-height: 1.4; +} + +.realm-select select { + width: 100%; + padding: 0.5rem 0.75rem; + border: 0; + border-bottom: 1pt solid var(--field-line); + border-radius: 0; + background: var(--surface); + color: inherit; + font: inherit; + font-size: 0.875rem; + line-height: 1.5; +} + +.sr-only { + position: absolute; + width: 1pt; + height: 1pt; + padding: 0; + margin: -1pt; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +.table-panel { + background: var(--surface); + color: var(--text); + box-shadow: var(--shadow); +} + +.table-toolbar { + display: flex; + flex-direction: column; + gap: 1rem; + padding: 1rem 1.5rem; + border-bottom: 1pt solid var(--row); +} + +.table-search { + flex: 1; + min-width: 0; +} + +.table-search input { + width: 100%; + padding: 0.5rem 0; + border: 0; + border-bottom: 1pt solid var(--field-line); + border-radius: 0; + background: transparent; + color: inherit; + font: inherit; + font-size: 1rem; + line-height: 1.5; + outline: none; +} + +.table-search input:focus { + border-bottom-color: var(--accent); +} + +.table-actions { + display: flex; + justify-content: flex-end; + flex-wrap: wrap; + gap: 1rem; +} + +.data-table-wrap { + overflow-x: auto; +} + +.data-table { + width: 100%; + border-collapse: collapse; + font-size: 0.875rem; +} + +.data-table th, +.data-table td { + padding: 0.75rem 1.5rem; + border-bottom: 1pt solid var(--row); + text-align: left; + vertical-align: middle; +} + +.data-table th { + color: var(--muted); + font-size: 0.75rem; + font-weight: 500; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.data-table tbody tr { + cursor: pointer; +} + +.data-table tbody tr:hover { + background: var(--row-hover); +} + +.data-table tbody tr:last-child td { + border-bottom: 0; +} + +.table-icon-column { + width: 1%; +} + +.data-table-primary { + min-width: 16rem; +} + +.data-table-primary a { + color: inherit; + font-weight: 500; + text-decoration: none; +} + +.data-table-primary a:hover { + color: var(--accent-text-hover); +} + +.data-table-sub { + display: block; + margin-top: 0.125rem; + color: var(--muted); + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: 0.8125rem; + overflow-wrap: anywhere; +} + +.data-table-status { + display: block; + margin-top: 0.125rem; + color: var(--muted); + font-size: 0.8125rem; +} + +.table-icon { + display: grid; + place-items: center; + width: 2rem; + height: 2rem; + flex: none; + overflow: hidden; + background: var(--row); + color: var(--muted); +} + +.table-icon img { + width: 100%; + height: 100%; + object-fit: contain; +} + +.table-icon svg { + width: 1.125rem; + height: 1.125rem; +} + +.client-breadcrumb { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + margin-bottom: 1rem; + color: var(--muted); + font-size: 0.8125rem; + line-height: 1.4; +} + +.client-breadcrumb a { + color: var(--accent-text); + text-decoration: none; +} + +.client-stack { + display: grid; + gap: 1rem; +} + +.client-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + margin-top: 1.25rem; +} + +.danger-zone h2 { + color: var(--danger); +} + +.secret-value { + display: block; + margin-top: 1rem; + padding: 0.75rem; + background: var(--row); + color: inherit; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 0.8125rem; + line-height: 1.5; + overflow-wrap: anywhere; + white-space: pre-wrap; +} + +.modal-overlay { + position: fixed; + inset: 0; + z-index: 100; + display: grid; + place-items: center; + padding: 1rem; + background: rgba(0, 0, 0, 0.58); +} + +.modal { + width: min(100%, 32rem); + max-height: calc(100vh - 2rem); + overflow: auto; + background: var(--surface); + color: var(--text); + box-shadow: var(--shadow); +} + +.modal-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + padding: 1.5rem 1.5rem 0; +} + +.modal-header h2 { + margin: 0; + font-size: 1.25rem; + font-weight: 400; + line-height: 1.3; +} + +.modal-close { + display: grid; + place-items: center; + width: 2rem; + height: 2rem; + padding: 0; + border: 0; + background: transparent; + color: var(--muted); + cursor: pointer; +} + +.modal-close:hover { + color: var(--text); +} + +.modal-close svg { + width: 1.25rem; + height: 1.25rem; +} + +.modal-body { + padding: 1.5rem; +} + +.modal-note { + margin: 0; + color: var(--muted); + font-size: 0.875rem; + line-height: 1.6; +} + +.modal-actions { + display: flex; + justify-content: flex-end; + gap: 1rem; + margin-top: 1.5rem; +} + +.form-field { + display: grid; + gap: 0.25rem; + margin-bottom: 1rem; +} + +.field-label { + color: var(--muted); + font-size: 0.75rem; + line-height: 1.4; +} + +.field-control { + width: 100%; + padding: 0.5rem 0.75rem; + border: 0; + border-bottom: 1pt solid var(--field-line); + border-radius: 0; + background: var(--surface); + color: inherit; + font: inherit; + font-size: 0.875rem; + line-height: 1.5; +} + a:focus-visible, button:focus-visible, summary:focus-visible { @@ -427,6 +804,20 @@ summary:focus-visible { } @media (min-width: 40em) { + .page-header-row { + grid-template-columns: minmax(0, 1fr) auto; + align-items: end; + } + + .table-toolbar { + flex-direction: row; + align-items: center; + } + + .realm-select select { + width: auto; + } + .nav-item span { display: inline; } diff --git a/server/src/controller/admin/clients.js b/server/src/controller/admin/clients.js @@ -0,0 +1,104 @@ +import { app } from '../../app.js'; +import { authenticateAdminRequest } from '../../lib/admin-auth.js'; +import { + createAdminRealmClient, + deleteAdminRealmClient, + listAdminRealmClients, + normalizeCreateInput, + rotateAdminClientSecret, + updateAdminRealmClient, +} from '../../lib/admin-clients.js'; + +export default [ + { + method: 'get', + path: '/api/v1/admin/realms/:realm/clients', + name: 'admin.clients.list', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const clients = await listAdminRealmClients(auth.systemDb, auth.realmDb, auth.realm.id); + + return new app.HttpOk({ clients }, { 'cache-control': 'no-store' }); + }, + }, + { + method: 'post', + path: '/api/v1/admin/realms/:realm/clients', + name: 'admin.clients.create', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const input = normalizeCreateInput(req.body || {}); + const { client, client_secret: clientSecret } = await createAdminRealmClient({ + systemDb: auth.systemDb, + realmDb: auth.realmDb, + realmId: auth.realm.id, + input, + }); + + const response = { ok: true, client }; + if (clientSecret) response.client_secret = clientSecret; + return new app.HttpOk(response, { 'cache-control': 'no-store' }); + }, + }, + { + method: 'patch', + path: '/api/v1/admin/realms/:realm/clients/:clientId', + name: 'admin.clients.update', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const client = await updateAdminRealmClient({ + realmDb: auth.realmDb, + clientId: req.params.clientId, + body: req.body || {}, + }); + + return new app.HttpOk({ ok: true, client }, { 'cache-control': 'no-store' }); + }, + }, + { + method: 'delete', + path: '/api/v1/admin/realms/:realm/clients/:clientId', + name: 'admin.clients.delete', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const result = await deleteAdminRealmClient({ + systemDb: auth.systemDb, + realmDb: auth.realmDb, + realmId: auth.realm.id, + clientId: req.params.clientId, + }); + + return new app.HttpOk( + { ok: true, removed: result.removed, client_id: req.params.clientId }, + { 'cache-control': 'no-store' } + ); + }, + }, + { + method: 'post', + path: '/api/v1/admin/realms/:realm/clients/:clientId/secret', + name: 'admin.clients.rotate_secret', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const { client, client_secret: clientSecret } = await rotateAdminClientSecret({ + realmDb: auth.realmDb, + clientId: req.params.clientId, + }); + + return new app.HttpOk( + { ok: true, client_id: client.client_id, client: client, client_secret: clientSecret }, + { 'cache-control': 'no-store' } + ); + }, + }, +]; diff --git a/server/src/controller/admin/roles/list.js b/server/src/controller/admin/roles/list.js @@ -0,0 +1,17 @@ +import { app } from '../../../app.js'; +import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { listAdminRealmRoles } from '../../../lib/admin-clients.js'; + +export default { + method: 'get', + path: '/api/v1/admin/realms/:realm/roles', + name: 'admin.roles.list', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const roles = await listAdminRealmRoles(auth.realmDb); + + return new app.HttpOk({ roles }, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/index.js b/server/src/index.js @@ -44,7 +44,7 @@ app.use( }, }) ); -app.use(bodyParser.json({ limit: '16kb' })); +app.use(bodyParser.json({ limit: '64kb' })); app.use(bodyParser.urlencoded({ extended: false, limit: '16kb' })); const routes = []; diff --git a/server/src/lib/admin-clients.js b/server/src/lib/admin-clients.js @@ -0,0 +1,714 @@ +import crypto from 'node:crypto'; +import { addClientRealm, findClientRealm } from './realm.js'; +import { hashClientSecret } from './oidc/clients.js'; +import { HttpError } from './http/http-error.js'; +import { destroySessionById } from './session.js'; + +const DEFAULT_SCOPES = 'openid profile email'; +const CLIENT_ID_MAX_LENGTH = 64; +const NAME_MAX_LENGTH = 100; +const URI_MAX_LENGTH = 2048; +const MAX_URI_COUNT = 10; +const MAX_SCOPE_COUNT = 50; +const MAX_ROLE_COUNT = 20; +const RESERVED_CLIENT_IDS = new Set(['admin', 'account']); +const CLIENT_ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/; +const ACCESS_MODES = new Set(['internal', 'members', 'public']); +const CONSENT_MODES = new Set(['remembered', 'trusted']); +const TOKEN_AUTH_METHODS = new Set(['none', 'client_secret_basic']); + +function invalidRequest(message, code = 'invalid_request') { + return new HttpError(400, code, message); +} + +function notFound(message, code = 'client_not_found') { + return new HttpError(404, code, message); +} + +function conflict(message, code = 'client_id_exists') { + return new HttpError(409, code, message); +} + +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function parseJson(raw, fallback) { + try { + return JSON.parse(raw || 'null') ?? fallback; + } catch { + return fallback; + } +} + +function assertBody(body) { + if (!isPlainObject(body)) { + throw invalidRequest('Request body must be a JSON object'); + } +} + +function assertKnownFields(body, allowed) { + for (const field of Object.keys(body)) { + if (!allowed.has(field)) { + throw invalidRequest(`Unknown field: ${field}`); + } + } +} + +function validateEnum(value, values, field) { + if (!values.has(value)) { + throw invalidRequest(`${field} must be one of ${[...values].join(', ')}`); + } + return value; +} + +function validateBoolean(value, field) { + if (typeof value !== 'boolean') { + throw invalidRequest(`${field} must be a boolean`); + } + return value; +} + +function validateClientId(value) { + if (typeof value !== 'string') { + throw invalidRequest('client_id must be a string', 'invalid_client_id'); + } + const clientId = value.trim(); + if (!CLIENT_ID_PATTERN.test(clientId) || clientId.length > CLIENT_ID_MAX_LENGTH) { + throw invalidRequest( + 'client_id must contain only lowercase letters, digits, and hyphens, and must start with a letter or digit', + 'invalid_client_id' + ); + } + if (RESERVED_CLIENT_IDS.has(clientId)) { + throw invalidRequest('This client_id is reserved', 'reserved_client_id'); + } + return clientId; +} + +function validateName(value) { + if (typeof value !== 'string') { + throw invalidRequest('name must be a string'); + } + const name = value.trim(); + if (!name || name.length > NAME_MAX_LENGTH) { + throw invalidRequest(`name must be between 1 and ${NAME_MAX_LENGTH} characters`); + } + return name; +} + +export function normalizeScopes(value) { + let raw = value; + if (raw === undefined || raw === null) raw = DEFAULT_SCOPES; + if (Array.isArray(raw)) raw = raw.join(' '); + if (typeof raw !== 'string') { + throw invalidRequest('scopes must be a string or an array of strings'); + } + + const scopes = [...new Set(raw.trim().split(/\s+/).filter(Boolean))]; + if (!scopes.includes('openid')) { + throw invalidRequest('scopes must include openid'); + } + if (scopes.length > MAX_SCOPE_COUNT) { + throw invalidRequest(`scopes may contain at most ${MAX_SCOPE_COUNT} entries`); + } + for (const scope of scopes) { + if (!/^[\x21-\x7e]+$/.test(scope)) { + throw invalidRequest('scopes must contain only printable non-whitespace characters'); + } + } + return scopes.join(' '); +} + +export function normalizeUriList(value, field, { required = false } = {}) { + if (value === undefined || value === null || (Array.isArray(value) && value.length === 0)) { + if (required) { + throw invalidRequest(`${field} must contain at least one URL`); + } + return []; + } + + let values; + if (Array.isArray(value)) { + values = value; + } else if (typeof value === 'string') { + values = value.trim().split(/\s+/); + } else { + throw invalidRequest(`${field} must be an array of URLs`); + } + + if (values.length > MAX_URI_COUNT) { + throw invalidRequest(`${field} may contain at most ${MAX_URI_COUNT} URLs`); + } + + const result = new Set(); + for (const item of values) { + if (typeof item !== 'string') { + throw invalidRequest(`${field} must contain only strings`); + } + const uri = item.trim(); + if (!uri || uri.length > URI_MAX_LENGTH) { + throw invalidRequest( + `${field} URLs must be between 1 and ${URI_MAX_LENGTH} characters` + ); + } + if (uri.includes('*')) { + throw invalidRequest(`${field} URLs cannot contain wildcards`); + } + + let parsed; + try { + parsed = new URL(uri); + } catch { + throw invalidRequest(`${field} URLs must be absolute`); + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + throw invalidRequest(`${field} URLs must use http or https`); + } + if (parsed.username || parsed.password) { + throw invalidRequest(`${field} URLs cannot contain credentials`); + } + if (parsed.hash) { + throw invalidRequest(`${field} URLs cannot contain fragments`); + } + result.add(uri); + } + + if (required && result.size === 0) { + throw invalidRequest(`${field} must contain at least one URL`); + } + return [...result]; +} + +function mapMappingError(error) { + const message = String(error?.message || ''); + if (/reserved/.test(message)) { + return invalidRequest('This client_id is reserved', 'reserved_client_id'); + } + if (/invalid client id/.test(message)) { + return invalidRequest('client_id is invalid', 'invalid_client_id'); + } + if (/already assigned/.test(message)) { + return conflict(); + } + return error; +} + +function mapDatabaseError(error) { + if (/UNIQUE constraint failed: oidc_clients\.client_id/.test(String(error?.message || ''))) { + return conflict(); + } + return error; +} + +async function getKnownRoleSet(db) { + const roles = await db.all('SELECT slug FROM roles'); + return new Set(roles.map((role) => role.slug)); +} + +function validateRoles(value, knownRoles) { + if (value === undefined || value === null) return []; + if (!Array.isArray(value)) { + throw invalidRequest('required_roles must be an array'); + } + if (value.length > MAX_ROLE_COUNT) { + throw invalidRequest(`required_roles may contain at most ${MAX_ROLE_COUNT} entries`); + } + + const result = new Set(); + for (const item of value) { + if (typeof item !== 'string') { + throw invalidRequest('required_roles must contain only strings'); + } + const slug = item.trim(); + if (!slug) { + throw invalidRequest('required_roles cannot contain empty values'); + } + if (!knownRoles.has(slug)) { + throw invalidRequest(`Unknown role: ${slug}`, 'unknown_role'); + } + result.add(slug); + } + return [...result]; +} + +async function loadRoles(db, id) { + const rows = await db.all( + `SELECT r.slug + FROM oidc_client_roles cr + JOIN roles r ON r.id = cr.role_id + WHERE cr.client_id = {id} + ORDER BY r.slug ASC`, + { id } + ); + return rows.map((row) => row.slug); +} + +function brandingLogoUrl(rawBranding) { + const branding = parseJson(rawBranding, {}); + return typeof branding?.logo_url === 'string' && branding.logo_url.trim() + ? branding.logo_url.trim() + : null; +} + +function serializeClient(row, requiredRoles) { + return { + client_id: row.client_id, + name: row.name, + access_mode: row.access_mode, + logo_url: brandingLogoUrl(row.branding), + enabled: Boolean(row.enabled), + scopes: row.scopes || DEFAULT_SCOPES, + required_roles: requiredRoles, + redirect_uris: parseJson(row.redirect_uris, []), + post_logout_redirect_uris: parseJson(row.post_logout_redirect_uris, []), + token_endpoint_auth_method: row.token_endpoint_auth_method || 'none', + require_pkce: Boolean(row.require_pkce), + consent_mode: row.consent_mode || 'remembered', + has_secret: Boolean(row.client_secret_hash), + created_at: row.created_at, + updated_at: row.updated_at, + }; +} + +export async function getAdminClientRow(db, clientId) { + return db.get( + `SELECT id, client_id, name, redirect_uris, scopes, access_mode, enabled, + branding, client_secret_hash, token_endpoint_auth_method, require_pkce, + post_logout_redirect_uris, consent_mode, created_at, updated_at + FROM oidc_clients + WHERE client_id = {clientId}`, + { clientId } + ); +} + +export async function loadAdminClient(db, clientId) { + const row = await getAdminClientRow(db, clientId); + if (!row) return null; + return serializeClient(row, await loadRoles(db, row.id)); +} + +export async function listAdminRealmClients(systemDb, realmDb, realmId) { + const mappedRows = await systemDb.all( + 'SELECT client_id FROM client_realms WHERE realm_id = {realmId} ORDER BY client_id ASC', + { realmId } + ); + const mapped = new Set(mappedRows.map((row) => row.client_id)); + if (mapped.size === 0) return []; + + const rows = await realmDb.all( + `SELECT id, client_id, name, redirect_uris, scopes, access_mode, enabled, + branding, client_secret_hash, token_endpoint_auth_method, require_pkce, + post_logout_redirect_uris, consent_mode, created_at, updated_at + FROM oidc_clients + ORDER BY name COLLATE NOCASE ASC, client_id ASC` + ); + const roleRows = await realmDb.all( + `SELECT c.client_id, r.slug + FROM oidc_client_roles cr + JOIN roles r ON r.id = cr.role_id + JOIN oidc_clients c ON c.id = cr.client_id + ORDER BY r.slug ASC` + ); + + const rolesByClient = new Map(); + for (const role of roleRows) { + const current = rolesByClient.get(role.client_id) || []; + current.push(role.slug); + rolesByClient.set(role.client_id, current); + } + + return rows + .filter((row) => mapped.has(row.client_id)) + .map((row) => serializeClient(row, rolesByClient.get(row.client_id) || [])); +} + +export async function listAdminRealmRoles(realmDb) { + return realmDb.all( + 'SELECT slug, name FROM roles ORDER BY name COLLATE NOCASE ASC, slug ASC' + ); +} + +function currentClientState(row) { + return { + name: row.name, + access_mode: row.access_mode, + enabled: Boolean(row.enabled), + scopes: row.scopes || DEFAULT_SCOPES, + redirect_uris: parseJson(row.redirect_uris, []), + post_logout_redirect_uris: parseJson(row.post_logout_redirect_uris, []), + token_endpoint_auth_method: row.token_endpoint_auth_method || 'none', + require_pkce: Boolean(row.require_pkce), + consent_mode: row.consent_mode || 'remembered', + }; +} + +export function normalizeCreateInput(body) { + assertBody(body); + assertKnownFields( + body, + new Set([ + 'client_id', + 'name', + 'access_mode', + 'enabled', + 'scopes', + 'required_roles', + 'redirect_uris', + 'post_logout_redirect_uris', + 'token_endpoint_auth_method', + 'require_pkce', + 'consent_mode', + ]) + ); + + const clientId = validateClientId(body.client_id); + const name = validateName(body.name); + const accessMode = validateEnum( + body.access_mode === undefined ? 'members' : body.access_mode, + ACCESS_MODES, + 'access_mode' + ); + const consentMode = validateEnum( + body.consent_mode === undefined ? 'remembered' : body.consent_mode, + CONSENT_MODES, + 'consent_mode' + ); + const enabled = validateBoolean(body.enabled === undefined ? true : body.enabled, 'enabled'); + const method = validateEnum( + body.token_endpoint_auth_method === undefined ? 'none' : body.token_endpoint_auth_method, + TOKEN_AUTH_METHODS, + 'token_endpoint_auth_method' + ); + let requirePkce = validateBoolean( + body.require_pkce === undefined ? true : body.require_pkce, + 'require_pkce' + ); + if (method === 'none') requirePkce = true; + + return { + clientId, + name, + accessMode, + enabled, + scopes: normalizeScopes(body.scopes), + requiredRoles: body.required_roles ?? [], + redirectUris: normalizeUriList(body.redirect_uris, 'redirect_uris', { required: true }), + postLogoutRedirectUris: normalizeUriList( + body.post_logout_redirect_uris, + 'post_logout_redirect_uris' + ), + tokenEndpointAuthMethod: method, + requirePkce, + consentMode, + }; +} + +export async function normalizeUpdateInput(body, db) { + assertBody(body); + if (Object.hasOwn(body, 'client_id')) { + throw invalidRequest('client_id cannot be updated'); + } + assertKnownFields( + body, + new Set([ + 'name', + 'access_mode', + 'enabled', + 'scopes', + 'required_roles', + 'redirect_uris', + 'post_logout_redirect_uris', + 'token_endpoint_auth_method', + 'require_pkce', + 'consent_mode', + ]) + ); + + const knownRoles = await getKnownRoleSet(db); + const result = {}; + if (Object.hasOwn(body, 'name')) result.name = validateName(body.name); + if (Object.hasOwn(body, 'access_mode')) { + result.accessMode = validateEnum(body.access_mode, ACCESS_MODES, 'access_mode'); + } + if (Object.hasOwn(body, 'enabled')) result.enabled = validateBoolean(body.enabled, 'enabled'); + if (Object.hasOwn(body, 'consent_mode')) { + result.consentMode = validateEnum(body.consent_mode, CONSENT_MODES, 'consent_mode'); + } + if (Object.hasOwn(body, 'scopes')) result.scopes = normalizeScopes(body.scopes); + if (Object.hasOwn(body, 'required_roles')) { + result.requiredRoles = validateRoles(body.required_roles, knownRoles); + } + if (Object.hasOwn(body, 'redirect_uris')) { + result.redirectUris = normalizeUriList(body.redirect_uris, 'redirect_uris', { required: true }); + } + if (Object.hasOwn(body, 'post_logout_redirect_uris')) { + result.postLogoutRedirectUris = normalizeUriList( + body.post_logout_redirect_uris, + 'post_logout_redirect_uris' + ); + } + if (Object.hasOwn(body, 'token_endpoint_auth_method')) { + result.tokenEndpointAuthMethod = validateEnum( + body.token_endpoint_auth_method, + TOKEN_AUTH_METHODS, + 'token_endpoint_auth_method' + ); + } + if (Object.hasOwn(body, 'require_pkce')) { + result.requirePkce = validateBoolean(body.require_pkce, 'require_pkce'); + } + if (Object.keys(result).length === 0) { + throw invalidRequest('At least one field must be provided'); + } + return result; +} + +async function insertClientRoles(tx, clientId, roles) { + for (const slug of roles) { + const role = await tx.get('SELECT id FROM roles WHERE slug = {slug}', { slug }); + if (!role) { + throw invalidRequest(`Unknown role: ${slug}`, 'unknown_role'); + } + await tx.run( + 'INSERT INTO oidc_client_roles (client_id, role_id) VALUES ({clientId}, {roleId})', + { clientId, roleId: role.id } + ); + } +} + +export function generateClientSecret() { + return crypto.randomBytes(32).toString('base64url'); +} + +export async function createAdminRealmClient({ systemDb, realmDb, realmId, input }) { + const mapping = await findClientRealm(input.clientId); + if (mapping) { + throw conflict(); + } + const existing = await getAdminClientRow(realmDb, input.clientId); + if (existing) { + throw conflict(); + } + + const knownRoles = await getKnownRoleSet(realmDb); + const requiredRoles = validateRoles(input.requiredRoles, knownRoles); + const clientId = crypto.randomUUID(); + const now = Date.now(); + const clientSecret = + input.tokenEndpointAuthMethod === 'client_secret_basic' ? generateClientSecret() : null; + + try { + await realmDb.transaction(async (tx) => { + await tx.run( + `INSERT INTO oidc_clients + (id, client_id, name, redirect_uris, scopes, access_mode, enabled, branding, + client_secret_hash, token_endpoint_auth_method, require_pkce, + post_logout_redirect_uris, consent_mode, created_at, updated_at) + VALUES + ({id}, {clientId}, {name}, {redirectUris}, {scopes}, {accessMode}, {enabled}, '{}', + {clientSecretHash}, {tokenEndpointAuthMethod}, {requirePkce}, + {postLogoutRedirectUris}, {consentMode}, {createdAt}, {updatedAt})`, + { + id: clientId, + clientId: input.clientId, + name: input.name, + redirectUris: JSON.stringify(input.redirectUris), + scopes: input.scopes, + accessMode: input.accessMode, + enabled: input.enabled ? 1 : 0, + clientSecretHash: clientSecret ? hashClientSecret(clientSecret) : null, + tokenEndpointAuthMethod: input.tokenEndpointAuthMethod, + requirePkce: input.requirePkce ? 1 : 0, + postLogoutRedirectUris: JSON.stringify(input.postLogoutRedirectUris), + consentMode: input.consentMode, + createdAt: now, + updatedAt: now, + } + ); + await insertClientRoles(tx, clientId, requiredRoles); + }); + } catch (error) { + throw mapDatabaseError(error); + } + + try { + await addClientRealm(input.clientId, realmId); + } catch (error) { + await realmDb.run('DELETE FROM oidc_client_roles WHERE client_id = {id}', { id: clientId }); + await realmDb.run('DELETE FROM oidc_clients WHERE id = {id}', { id: clientId }); + throw mapMappingError(error); + } + + const client = await loadAdminClient(realmDb, input.clientId); + if (!client) { + throw new HttpError(500, 'internal_error', 'Client was not created'); + } + return { client, client_secret: clientSecret }; +} + +export async function updateAdminRealmClient({ + realmDb, + clientId, + body, +}) { + const row = await getAdminClientRow(realmDb, clientId); + if (!row) { + throw notFound(); + } + + const current = currentClientState(row); + const input = await normalizeUpdateInput(body, realmDb); + const tokenEndpointAuthMethod = + input.tokenEndpointAuthMethod ?? current.token_endpoint_auth_method; + let requirePkce = input.requirePkce ?? current.require_pkce; + if (tokenEndpointAuthMethod === 'none') { + requirePkce = true; + } + if (tokenEndpointAuthMethod === 'none' && input.requirePkce === false) { + throw invalidRequest('Public clients must require PKCE'); + } + if (tokenEndpointAuthMethod === 'client_secret_basic' && !row.client_secret_hash) { + throw new HttpError( + 409, + 'client_secret_required', + 'A client secret is required for client_secret_basic' + ); + } + + const next = { + name: input.name ?? current.name, + accessMode: input.accessMode ?? current.access_mode, + enabled: input.enabled ?? current.enabled, + scopes: input.scopes ?? current.scopes, + redirectUris: input.redirectUris ?? current.redirect_uris, + postLogoutRedirectUris: + input.postLogoutRedirectUris ?? current.post_logout_redirect_uris, + tokenEndpointAuthMethod, + requirePkce, + consentMode: input.consentMode ?? current.consent_mode, + }; + const clientSecretHash = + tokenEndpointAuthMethod === 'client_secret_basic' ? row.client_secret_hash : null; + const now = Date.now(); + + try { + await realmDb.transaction(async (tx) => { + await tx.run( + `UPDATE oidc_clients + SET name = {name}, redirect_uris = {redirectUris}, scopes = {scopes}, + access_mode = {accessMode}, enabled = {enabled}, + client_secret_hash = {clientSecretHash}, + token_endpoint_auth_method = {tokenEndpointAuthMethod}, + require_pkce = {requirePkce}, + post_logout_redirect_uris = {postLogoutRedirectUris}, + consent_mode = {consentMode}, updated_at = {updatedAt} + WHERE id = {id}`, + { + name: next.name, + redirectUris: JSON.stringify(next.redirectUris), + scopes: next.scopes, + accessMode: next.accessMode, + enabled: next.enabled ? 1 : 0, + clientSecretHash, + tokenEndpointAuthMethod: next.tokenEndpointAuthMethod, + requirePkce: next.requirePkce ? 1 : 0, + postLogoutRedirectUris: JSON.stringify(next.postLogoutRedirectUris), + consentMode: next.consentMode, + updatedAt: now, + id: row.id, + } + ); + + if (Object.hasOwn(input, 'requiredRoles')) { + await tx.run('DELETE FROM oidc_client_roles WHERE client_id = {id}', { id: row.id }); + await insertClientRoles(tx, row.id, input.requiredRoles); + } + }); + } catch (error) { + throw mapDatabaseError(error); + } + + const client = await loadAdminClient(realmDb, clientId); + if (!client) { + throw new HttpError(500, 'internal_error', 'Client was not updated'); + } + return client; +} + +export async function rotateAdminClientSecret({ realmDb, clientId }) { + const row = await getAdminClientRow(realmDb, clientId); + if (!row) { + throw notFound(); + } + + const clientSecret = generateClientSecret(); + await realmDb.run( + `UPDATE oidc_clients + SET client_secret_hash = {hash}, token_endpoint_auth_method = 'client_secret_basic', + updated_at = {updatedAt} + WHERE id = {id}`, + { + hash: hashClientSecret(clientSecret), + updatedAt: Date.now(), + id: row.id, + } + ); + + const client = await loadAdminClient(realmDb, clientId); + if (!client) { + throw new HttpError(500, 'internal_error', 'Client secret was not updated'); + } + return { client, client_secret: clientSecret }; +} + +async function deleteRealmClientState(realmDb, clientId, rowId) { + await realmDb.transaction(async (tx) => { + await tx.run('DELETE FROM oidc_client_roles WHERE client_id = {id}', { id: rowId }); + await tx.run('DELETE FROM auth_requests WHERE client_id = {clientId}', { clientId }); + await tx.run('DELETE FROM authorization_codes WHERE client_id = {clientId}', { clientId }); + await tx.run('DELETE FROM app_bans WHERE client_id = {clientId}', { clientId }); + await tx.run('DELETE FROM oidc_clients WHERE id = {id}', { id: rowId }); + }); +} + +export async function deleteAdminRealmClient({ systemDb, realmDb, realmId, clientId }) { + const mapping = await findClientRealm(clientId); + if (mapping && mapping.realm_id !== realmId) { + throw notFound(); + } + + const row = await getAdminClientRow(realmDb, clientId); + if (!row && !mapping) { + throw notFound(); + } + + if (row) { + await deleteRealmClientState(realmDb, clientId, row.id); + } + + const now = Date.now(); + await systemDb.transaction(async (tx) => { + const sessions = await tx.all( + 'SELECT id FROM sessions WHERE realm_id = {realmId} AND client_id = {clientId}', + { realmId, clientId } + ); + for (const session of sessions) { + await destroySessionById(tx, session.id, now); + } + + await tx.run( + 'DELETE FROM refresh_tokens WHERE realm_id = {realmId} AND client_id = {clientId}', + { realmId, clientId } + ); + await tx.run( + 'DELETE FROM client_consents WHERE realm_id = {realmId} AND client_id = {clientId}', + { realmId, clientId } + ); + if (mapping) { + await tx.run('DELETE FROM client_realms WHERE client_id = {clientId}', { clientId }); + } + }); + + return { removed: true }; +} diff --git a/server/src/lib/apps.js b/server/src/lib/apps.js @@ -15,15 +15,21 @@ function appDist(name) { } export function appIndex(name) { - if (!cache.has(name)) { - const file = path.join(appDist(name), 'index.html'); - try { - cache.set(name, fs.readFileSync(file)); - } catch { - cache.set(name, null); - } + const file = path.join(appDist(name), 'index.html'); + let modified; + try { + modified = fs.statSync(file).mtimeMs; + } catch { + cache.set(name, null); + return null; } - return cache.get(name); + + const cached = cache.get(name); + if (cached && cached.modified === modified) return cached.content; + + const content = fs.readFileSync(file); + cache.set(name, { modified, content }); + return content; } export function serveAppDocument(res, name) { diff --git a/server/test/admin-clients.test.js b/server/test/admin-clients.test.js @@ -0,0 +1,50 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + generateClientSecret, + normalizeScopes, + normalizeUriList, +} from '../src/lib/admin-clients.js'; + +function expectHttpError(fn, status, code) { + try { + fn(); + } catch (error) { + assert.equal(error.status, status); + assert.equal(error.code, code); + return; + } + assert.fail('Expected an HTTP error'); +} + +test('admin client scopes are normalized and must include openid', () => { + assert.equal(normalizeScopes('openid email'), 'openid email'); + assert.equal(normalizeScopes(['email', 'openid', 'email']), 'email openid'); + expectHttpError(() => normalizeScopes('email profile'), 400, 'invalid_request'); +}); + +test('admin client redirect URIs are absolute and exact', () => { + assert.deepEqual( + normalizeUriList( + ['http://localhost:3000/callback', 'https://app.example.test/callback'], + 'redirect_uris', + { required: true } + ), + ['http://localhost:3000/callback', 'https://app.example.test/callback'] + ); + expectHttpError( + () => normalizeUriList(['/callback'], 'redirect_uris', { required: true }), + 400, + 'invalid_request' + ); + expectHttpError( + () => normalizeUriList(['https://app.test/callback#token'], 'redirect_uris'), + 400, + 'invalid_request' + ); +}); + +test('admin client secrets are URL-safe random values', () => { + assert.match(generateClientSecret(), /^[A-Za-z0-9_-]{43}$/); + assert.notEqual(generateClientSecret(), generateClientSecret()); +}); diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -410,6 +410,60 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }); } + const adminRequest = (admin, options) => + identity({ bearer: admin.access_token, ...options }); + + async function createAdminClient(admin, realm, body) { + return adminRequest(admin, { + method: 'POST', + path: `/api/v1/admin/realms/${realm}/clients`, + body, + }); + } + + async function updateAdminClient(admin, realm, clientId, body) { + return adminRequest(admin, { + method: 'PATCH', + path: `/api/v1/admin/realms/${realm}/clients/${encodeURIComponent(clientId)}`, + body, + }); + } + + async function deleteAdminClient(admin, realm, clientId) { + return adminRequest(admin, { + method: 'DELETE', + path: `/api/v1/admin/realms/${realm}/clients/${encodeURIComponent(clientId)}`, + }); + } + + async function authorizeCodeForClient( + requester, + { clientId, identifier, redirectUri, scope = 'openid profile', state } + ) { + const { verifier, challenge } = pkce(); + const authorizePath = + `/oidc/${clientId}/authorize?response_type=code&client_id=${clientId}` + + `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(scope)}` + + `&state=${state}&code_challenge=${challenge}&code_challenge_method=S256`; + const first = await requester({ path: authorizePath }); + let jar = mergeCookies('', first); + const login = await requester({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: clientId, identifier, password: 'demo' }, + cookie: jar, + }); + jar = mergeCookies(jar, login); + const completed = await completeAuthorization(requester, { + path: authorizePath.split('?')[0], + cookie: jar, + clientId, + }); + const code = locationQuery(completed.response).searchParams.get('code'); + assert.ok(code); + return { verifier, code }; + } + await t.test('realm metadata is served for a realm hostname', async () => { const response = await acme({ path: '/api/v1/realm' }); assert.equal(response.status, 200); @@ -2607,6 +2661,502 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { } }); + await t.test('admin clients list roles and create realm clients', async () => { + const admin = await adminToken('it@acme.test'); + const roles = await adminRequest(admin, { + path: '/api/v1/admin/realms/acme/roles', + }); + assert.equal(roles.status, 200); + assert.ok(roles.json.roles.some((role) => role.slug === 'realm-admin')); + + const list = await adminRequest(admin, { + path: '/api/v1/admin/realms/acme/clients', + }); + assert.equal(list.status, 200); + const listed = new Map(list.json.clients.map((client) => [client.client_id, client])); + assert.ok(listed.has('internal-app')); + assert.equal(listed.has('admin'), false); + assert.equal(listed.get('acme-public-app').has_secret, false); + assert.equal(listed.get('confidential-app').has_secret, true); + assert.equal(listed.get('confidential-app').logo_url, null); + + const clientId = 'admin-created-public'; + const oldUri = `${origin('created.localhost')}/callback`; + const newUri = `${origin('created2.localhost')}/callback`; + try { + const created = await createAdminClient(admin, 'acme', { + client_id: clientId, + name: 'Admin Created Public', + access_mode: 'members', + redirect_uris: [oldUri], + required_roles: ['realm-admin'], + }); + assert.equal(created.status, 200); + assert.equal(created.json.ok, true); + assert.equal(created.json.client.client_id, clientId); + assert.equal(created.json.client.required_roles.length, 1); + assert.equal(created.json.client.require_pkce, true); + assert.equal(created.json.client.logo_url, null); + assert.equal(created.json.client_secret, undefined); + + const duplicate = await createAdminClient(admin, 'acme', { + client_id: clientId, + name: 'Duplicate', + redirect_uris: [newUri], + }); + assert.equal(duplicate.status, 409); + assert.equal(duplicate.json.error.code, 'client_id_exists'); + + const updated = await updateAdminClient(admin, 'acme', clientId, { + name: 'Renamed Public', + access_mode: 'public', + redirect_uris: [newUri], + required_roles: [], + }); + assert.equal(updated.status, 200); + assert.equal(updated.json.client.name, 'Renamed Public'); + assert.equal(updated.json.client.access_mode, 'public'); + assert.deepEqual(updated.json.client.required_roles, []); + + const { challenge } = pkce(); + const denied = await acme({ + path: + `/oidc/${clientId}/authorize?response_type=code&client_id=${clientId}` + + `&redirect_uri=${encodeURIComponent(oldUri)}&scope=openid&state=old-uri` + + `&code_challenge=${challenge}&code_challenge_method=S256`, + }); + assert.equal(denied.status, 400); + assert.equal(denied.json.error, 'invalid_request'); + + const token = await accessToken(acme, { + clientId, + identifier: 'alice@acme.test', + redirectUri: newUri, + }); + assert.ok(token.access_token); + } finally { + const cleanup = await deleteAdminClient(admin, 'acme', clientId); + assert.ok(cleanup.status === 200 || cleanup.status === 404); + } + }); + + await t.test('admin clients rotate confidential client secrets', async () => { + const admin = await adminToken('it@acme.test'); + const clientId = 'admin-created-confidential'; + const redirectUri = `${origin('created-conf.localhost')}/callback`; + try { + const created = await createAdminClient(admin, 'acme', { + client_id: clientId, + name: 'Admin Created Confidential', + access_mode: 'members', + token_endpoint_auth_method: 'client_secret_basic', + redirect_uris: [redirectUri], + }); + assert.equal(created.status, 200); + assert.match(created.json.client_secret, /^[A-Za-z0-9_-]{43}$/); + assert.equal(created.json.client.has_secret, true); + + const initial = await authorizeCodeForClient(acme, { + clientId, + identifier: 'alice@acme.test', + redirectUri, + state: 'conf-initial', + }); + const initialToken = await acme({ + method: 'POST', + path: `/oidc/${clientId}/token`, + form: { + grant_type: 'authorization_code', + code: initial.code, + redirect_uri: redirectUri, + code_verifier: initial.verifier, + }, + headers: { + authorization: `Basic ${Buffer.from(`${clientId}:${created.json.client_secret}`).toString('base64')}`, + }, + }); + assert.equal(initialToken.status, 200); + + const rotated = await adminRequest(admin, { + method: 'POST', + path: `/api/v1/admin/realms/acme/clients/${clientId}/secret`, + }); + assert.equal(rotated.status, 200); + assert.match(rotated.json.client_secret, /^[A-Za-z0-9_-]{43}$/); + assert.notEqual(rotated.json.client_secret, created.json.client_secret); + assert.equal(rotated.json.client.token_endpoint_auth_method, 'client_secret_basic'); + + const second = await authorizeCodeForClient(acme, { + clientId, + identifier: 'alice@acme.test', + redirectUri, + state: 'conf-old-secret', + }); + const oldDenied = await acme({ + method: 'POST', + path: `/oidc/${clientId}/token`, + form: { + grant_type: 'authorization_code', + code: second.code, + redirect_uri: redirectUri, + code_verifier: second.verifier, + }, + headers: { + authorization: `Basic ${Buffer.from(`${clientId}:${created.json.client_secret}`).toString('base64')}`, + }, + }); + assert.equal(oldDenied.status, 401); + assert.equal(oldDenied.json.error, 'invalid_client'); + + const newAllowed = await acme({ + method: 'POST', + path: `/oidc/${clientId}/token`, + form: { + grant_type: 'authorization_code', + code: second.code, + redirect_uri: redirectUri, + code_verifier: second.verifier, + }, + headers: { + authorization: `Basic ${Buffer.from(`${clientId}:${rotated.json.client_secret}`).toString('base64')}`, + }, + }); + assert.equal(newAllowed.status, 200); + + const cleared = await updateAdminClient(admin, 'acme', clientId, { + token_endpoint_auth_method: 'none', + }); + assert.equal(cleared.status, 200); + assert.equal(cleared.json.client.has_secret, false); + assert.equal(cleared.json.client.require_pkce, true); + + const discovery = await acme({ path: `/oidc/${clientId}/openid-configuration` }); + assert.deepEqual(discovery.json.token_endpoint_auth_methods_supported, ['none']); + + const publicAccess = await authorizeCodeForClient(acme, { + clientId, + identifier: 'alice@acme.test', + redirectUri, + state: 'conf-to-public', + }); + const publicToken = await acme({ + method: 'POST', + path: `/oidc/${clientId}/token`, + form: { + grant_type: 'authorization_code', + code: publicAccess.code, + redirect_uri: redirectUri, + client_id: clientId, + code_verifier: publicAccess.verifier, + }, + }); + assert.equal(publicToken.status, 200); + } finally { + const cleanup = await deleteAdminClient(admin, 'acme', clientId); + assert.ok(cleanup.status === 200 || cleanup.status === 404); + } + }); + + await t.test('admin client APIs enforce validation and target scope', async () => { + const acmeAdmin = await adminToken('it@acme.test'); + const systemAdmin = await adminToken(); + const redirectUri = `${origin('created-scope.localhost')}/callback`; + + const crossRealm = await adminRequest(acmeAdmin, { + path: '/api/v1/admin/realms/globex/clients', + }); + assert.equal(crossRealm.status, 403); + + const reserved = await createAdminClient(acmeAdmin, 'acme', { + client_id: 'admin', + name: 'Reserved', + redirect_uris: [redirectUri], + }); + assert.equal(reserved.status, 400); + assert.equal(reserved.json.error.code, 'reserved_client_id'); + + const invalidId = await createAdminClient(acmeAdmin, 'acme', { + client_id: 'Bad App', + name: 'Invalid', + redirect_uris: [redirectUri], + }); + assert.equal(invalidId.status, 400); + assert.equal(invalidId.json.error.code, 'invalid_client_id'); + + const invalidRedirect = await createAdminClient(acmeAdmin, 'acme', { + client_id: 'admin-invalid-redirect', + name: 'Invalid Redirect', + redirect_uris: ['/relative'], + }); + assert.equal(invalidRedirect.status, 400); + assert.equal(invalidRedirect.json.error.code, 'invalid_request'); + + const missingOpenid = await createAdminClient(acmeAdmin, 'acme', { + client_id: 'admin-invalid-scope', + name: 'Invalid Scope', + scopes: 'email profile', + redirect_uris: [redirectUri], + }); + assert.equal(missingOpenid.status, 400); + assert.equal(missingOpenid.json.error.code, 'invalid_request'); + + const unknownRole = await createAdminClient(acmeAdmin, 'acme', { + client_id: 'admin-unknown-role', + name: 'Unknown Role', + required_roles: ['missing-role'], + redirect_uris: [redirectUri], + }); + assert.equal(unknownRole.status, 400); + assert.equal(unknownRole.json.error.code, 'unknown_role'); + + const globalClient = 'admin-global-unique'; + try { + const created = await createAdminClient(acmeAdmin, 'acme', { + client_id: globalClient, + name: 'Global Unique', + redirect_uris: [redirectUri], + }); + assert.equal(created.status, 200); + + const duplicate = await createAdminClient(systemAdmin, 'globex', { + client_id: globalClient, + name: 'Duplicate Realm', + redirect_uris: [redirectUri], + }); + assert.equal(duplicate.status, 409); + assert.equal(duplicate.json.error.code, 'client_id_exists'); + + const systemUpdate = await updateAdminClient(systemAdmin, 'acme', 'admin', { + name: 'Cannot Update', + }); + assert.equal(systemUpdate.status, 404); + + const missingUpdate = await updateAdminClient(acmeAdmin, 'acme', 'missing-client', { + name: 'Missing', + }); + assert.equal(missingUpdate.status, 404); + + const publicClient = 'admin-secret-patch'; + try { + const publicCreated = await createAdminClient(acmeAdmin, 'acme', { + client_id: publicClient, + name: 'Public Patch', + redirect_uris: [redirectUri], + }); + assert.equal(publicCreated.status, 200); + + const secretRequired = await updateAdminClient(acmeAdmin, 'acme', publicClient, { + token_endpoint_auth_method: 'client_secret_basic', + }); + assert.equal(secretRequired.status, 409); + assert.equal(secretRequired.json.error.code, 'client_secret_required'); + + const pkceDenied = await updateAdminClient(acmeAdmin, 'acme', publicClient, { + require_pkce: false, + }); + assert.equal(pkceDenied.status, 400); + assert.equal(pkceDenied.json.error.code, 'invalid_request'); + } finally { + const cleanup = await deleteAdminClient(acmeAdmin, 'acme', publicClient); + assert.ok(cleanup.status === 200 || cleanup.status === 404); + } + } finally { + const cleanup = await deleteAdminClient(acmeAdmin, 'acme', globalClient); + assert.ok(cleanup.status === 200 || cleanup.status === 404); + } + }); + + await t.test('admin client deletion cleans related client state', async () => { + const admin = await adminToken('it@acme.test'); + const clientId = 'admin-delete-flow'; + const host = 'delete-flow.localhost'; + const redirectUri = `${origin(host)}/callback`; + const deleteRequest = (options = {}) => + request(port, { host: `${host}:${port}`, ...options }); + clearBans(env, { username: 'alice', realm: 'acme' }); + + try { + const created = await createAdminClient(admin, 'acme', { + client_id: clientId, + name: 'Delete Flow', + access_mode: 'members', + redirect_uris: [redirectUri], + }); + assert.equal(created.status, 200); + + withSystemDatabase(env, (database) => { + database + .prepare( + 'INSERT INTO oidc_client_hosts (host, client_id, created_at) VALUES (?, ?, ?)' + ) + .run(host, clientId, Date.now()); + }); + + const login = await deleteRequest({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: clientId, identifier: 'alice@acme.test', password: 'demo' }, + }); + assert.equal(login.status, 200); + const cookie = mergeCookies('', login); + const beforeSession = await deleteRequest({ path: '/api/v1/session', cookie }); + assert.equal(beforeSession.status, 200); + assert.equal(beforeSession.json.scope.client_id, clientId); + + const { verifier, challenge } = pkce(); + const authorizePath = + `/oidc/authorize?response_type=code&client_id=${clientId}` + + `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20profile` + + `&state=delete-flow&code_challenge=${challenge}&code_challenge_method=S256`; + const approved = await completeAuthorization(deleteRequest, { + path: authorizePath, + cookie, + clientId, + }); + const code = locationQuery(approved.response).searchParams.get('code'); + assert.ok(code); + const token = await deleteRequest({ + method: 'POST', + path: '/oidc/token', + form: { + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + client_id: clientId, + code_verifier: verifier, + }, + }); + assert.equal(token.status, 200); + + const aliceId = userId(env, 'alice'); + const acmeId = realmId(env, 'acme'); + const sessionId = activeSessionId(env, cookie); + insertRefreshToken(env, { + sessionId, + userId: aliceId, + realmId: acmeId, + clientId, + }); + + withRealmDatabase(env, 'acme', (database) => { + const now = Date.now(); + database + .prepare( + `INSERT INTO app_bans (user_id, client_id, created_by, created_at) + VALUES (?, ?, ?, ?)` + ) + .run(aliceId, clientId, userId(env, 'acme-it'), now); + database + .prepare( + `INSERT OR REPLACE INTO app_bans (user_id, client_id, created_by, created_at) + VALUES (?, '*', ?, ?)` + ) + .run(aliceId, userId(env, 'acme-it'), now); + database + .prepare( + `INSERT INTO auth_requests + (id, client_id, redirect_uri, scope, state, nonce, code_challenge, + code_challenge_method, session_id, user_id, auth_time, created_at, + expires_at, completed_at) + VALUES (?, ?, ?, ?, ?, ?, NULL, NULL, NULL, ?, NULL, ?, ?, NULL)` + ) + .run('delete-flow-auth', clientId, redirectUri, 'openid', 'state', 'nonce', aliceId, now, now + 60_000); + database + .prepare( + `INSERT INTO authorization_codes + (id, auth_request_id, client_id, user_id, redirect_uri, scope, nonce, + code_challenge, code_challenge_method, session_id, auth_time, created_at, + expires_at, consumed_at) + VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, 1, ?, ?, NULL)` + ) + .run( + 'delete-flow-code', + 'delete-flow-code-request', + clientId, + aliceId, + redirectUri, + 'openid', + 'nonce', + now, + now + 60_000 + ); + }); + + const deleted = await deleteAdminClient(admin, 'acme', clientId); + assert.equal(deleted.status, 200); + assert.equal(deleted.json.removed, true); + assert.equal(deleted.json.client_id, clientId); + + assert.equal( + withSystemDatabase(env, (database) => + database.prepare('SELECT COUNT(*) AS count FROM sessions WHERE id = ?').get(sessionId).count + ), + 0 + ); + assert.equal( + withSystemDatabase(env, (database) => + database.prepare('SELECT COUNT(*) AS count FROM client_realms WHERE client_id = ?').get(clientId).count + ), + 0 + ); + assert.equal( + withSystemDatabase(env, (database) => + database.prepare('SELECT COUNT(*) AS count FROM oidc_client_hosts WHERE client_id = ?').get(clientId).count + ), + 0 + ); + assert.equal( + withSystemDatabase(env, (database) => + database.prepare('SELECT COUNT(*) AS count FROM client_consents WHERE client_id = ?').get(clientId).count + ), + 0 + ); + assert.equal( + withSystemDatabase(env, (database) => + database.prepare('SELECT COUNT(*) AS count FROM refresh_tokens WHERE client_id = ?').get(clientId).count + ), + 0 + ); + assert.equal( + withRealmDatabase(env, 'acme', (database) => + database.prepare('SELECT COUNT(*) AS count FROM oidc_clients WHERE client_id = ?').get(clientId).count + ), + 0 + ); + assert.equal( + withRealmDatabase(env, 'acme', (database) => + database.prepare('SELECT COUNT(*) AS count FROM auth_requests WHERE client_id = ?').get(clientId).count + ), + 0 + ); + assert.equal( + withRealmDatabase(env, 'acme', (database) => + database.prepare('SELECT COUNT(*) AS count FROM authorization_codes WHERE client_id = ?').get(clientId).count + ), + 0 + ); + assert.equal( + withRealmDatabase(env, 'acme', (database) => + database.prepare('SELECT COUNT(*) AS count FROM app_bans WHERE client_id = ?').get(clientId).count + ), + 0 + ); + assert.equal( + withRealmDatabase(env, 'acme', (database) => + database.prepare(`SELECT COUNT(*) AS count FROM app_bans WHERE client_id = '*' AND user_id = ?`).get(aliceId).count + ), + 1 + ); + + const afterDelete = await acme({ path: `/oidc/${clientId}/openid-configuration` }); + assert.equal(afterDelete.status, 404); + } finally { + const cleanup = await deleteAdminClient(admin, 'acme', clientId); + assert.ok(cleanup.status === 200 || cleanup.status === 404); + clearBans(env, { username: 'alice', realm: 'acme' }); + } + }); + await t.test('confidential clients authenticate with client_secret_basic', async () => { const { verifier, challenge } = pkce(); const redirectUri = `${origin('confidential.localhost')}/callback`;