auth

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

commit cca943d35f2e9d5066abb29679a5254365bd12e7
parent 75d38b8e1b292c5d1324cb0beeee7cad4bf90944
Author: finwo <finwo@pm.me>
Date:   Sun,  1 Nov 2026 23:20:59 +0100

Added realm branding management

Diffstat:
Mapp/admin/src/assets/admin.css | 49++++++++++++++++++++++++++++++++++++++++++++++++-
Mapp/admin/src/screen/settings.tsx | 284+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mapp/admin/src/util/api.ts | 4++++
Mapp/login/src/screen/login.tsx | 16++++++++++++++--
Mapp/shared/style/global.css | 6++++--
Mmockup/plain/admin-settings.html | 284++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mmockup/plain/global.css | 6++++--
Aserver/src/lib/admin-branding.js | 183+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/src/lib/admin-settings.js | 24++++++++++++++++++++++--
Mserver/src/lib/realm.js | 12++----------
Aserver/test/admin-branding.test.js | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/test/http.test.js | 120++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
12 files changed, 952 insertions(+), 135 deletions(-)

diff --git a/app/admin/src/assets/admin.css b/app/admin/src/assets/admin.css @@ -223,10 +223,18 @@ margin-top: 0; } +.settings-stack { + min-width: 0; + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 1rem; +} + .settings-form { + min-width: 0; display: grid; + grid-template-columns: minmax(0, 1fr); width: 100%; - min-width: 0; max-width: 100%; gap: 1rem; margin-top: 1rem; @@ -248,6 +256,45 @@ max-width: 100%; } +.branding-preview { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.75rem; + margin-top: 0.25rem; +} + +.branding-logo-preview, +.branding-color-preview { + width: 2rem; + height: 2rem; + overflow: hidden; + background: var(--row); +} + +.branding-logo-preview { + display: inline-flex; + align-items: center; + justify-content: center; + color: var(--muted); +} + +.branding-logo-preview img { + width: 100%; + height: 100%; + object-fit: contain; +} + +.branding-color-preview { + border-radius: 0.25rem; + background: var(--field-line); +} + +.branding-logo-preview.is-empty, +.branding-color-preview.is-empty { + border-bottom: 1pt solid var(--field-line); +} + .field-grid { display: grid; grid-template-columns: minmax(0, 1fr); diff --git a/app/admin/src/screen/settings.tsx b/app/admin/src/screen/settings.tsx @@ -15,40 +15,128 @@ interface SettingsAttrs { interface SettingsFormValue { display_name: string; allow_session_duration_choice: boolean; + logo_url: string; + primary_color: string; } +interface SettingsValidation { + message: string; + field: 'display_name' | 'logo_url' | 'primary_color'; +} + +const LOGO_MAX_LENGTH = 2048; +const PRIMARY_COLOR_PATTERN = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i; + function formFromSettings(settings: AdminRealmSettings): SettingsFormValue { return { display_name: settings.display_name, allow_session_duration_choice: settings.allow_session_duration_choice, + logo_url: settings.logo_url || '', + primary_color: settings.primary_color || '', }; } -function validateForm(value: SettingsFormValue): string | null { +function normalizePreviewColor(value: string): string | null { + const color = value.trim().toLowerCase(); + if (!PRIMARY_COLOR_PATTERN.test(color)) return null; + if (color.length === 4) { + return `#${color[1]}${color[1]}${color[2]}${color[2]}${color[3]}${color[3]}`; + } + return color; +} + +function isLoopbackHostname(hostname: string): boolean { + const host = hostname.startsWith('[') && hostname.endsWith(']') + ? hostname.slice(1, -1) + : hostname; + return ( + host === 'localhost' || + host.endsWith('.localhost') || + host === '127.0.0.1' || + host === '::1' + ); +} + +function logoUrlError(value: string): string | null { + const url = value.trim(); + if (!url) return null; + if (url.length > LOGO_MAX_LENGTH) { + return `Logo URL must be ${LOGO_MAX_LENGTH} characters or fewer.`; + } + if (url.includes('*')) return 'Logo URL cannot contain wildcards.'; + + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return 'Logo URL must be absolute.'; + } + + const allowedProtocol = + parsed.protocol === 'https:' || + (parsed.protocol === 'http:' && isLoopbackHostname(parsed.hostname)); + if (!allowedProtocol) { + return 'Logo URL must use https, or http for a loopback host.'; + } + if (parsed.username || parsed.password) return 'Logo URL cannot contain credentials.'; + if (parsed.hash) return 'Logo URL cannot contain a fragment.'; + + return null; +} + +function validateForm(value: SettingsFormValue): SettingsValidation | null { const displayName = value.display_name.trim(); if (!displayName) { - return 'Display name is required.'; + return { message: 'Display name is required.', field: 'display_name' }; } if (/[\r\n]/.test(value.display_name)) { - return 'Display name must be a single line.'; + return { message: 'Display name must be a single line.', field: 'display_name' }; } if (displayName.length > 100) { - return 'Display name must be 100 characters or fewer.'; + return { + message: 'Display name must be 100 characters or fewer.', + field: 'display_name', + }; + } + + const logoError = logoUrlError(value.logo_url); + if (logoError) { + return { message: logoError, field: 'logo_url' }; + } + if (value.primary_color.trim() && !normalizePreviewColor(value.primary_color)) { + return { + message: 'Primary color must be a #rgb or #rrggbb hex color.', + field: 'primary_color', + }; } return null; } +function fieldFromError(message: string | null | undefined): SettingsValidation['field'] | null { + if (!message) return null; + if (message.includes('logo_url')) return 'logo_url'; + if (message.includes('primary_color')) return 'primary_color'; + if (message.includes('display_name')) return 'display_name'; + return null; +} + export const SettingsPage: m.Component<SettingsAttrs> = { attrs: null as SettingsAttrs | null, loadedRealm: null as string | null, loading: false, redirecting: false, settings: null as AdminRealmSettings | null, - form: { display_name: '', allow_session_duration_choice: true } as SettingsFormValue, + form: { + display_name: '', + allow_session_duration_choice: true, + logo_url: '', + primary_color: '', + } as SettingsFormValue, error: null as Error | null, formError: null as Error | string | null, + invalidField: null as SettingsValidation['field'] | null, notice: null as string | null, pending: false, @@ -98,7 +186,13 @@ export const SettingsPage: m.Component<SettingsAttrs> = { this.formError = null; this.notice = null; this.settings = null; - this.form = { display_name: '', allow_session_duration_choice: true }; + this.invalidField = null; + this.form = { + display_name: '', + allow_session_duration_choice: true, + logo_url: '', + primary_color: '', + }; m.redraw(); try { @@ -126,7 +220,8 @@ export const SettingsPage: m.Component<SettingsAttrs> = { const validationError = validateForm(this.form); if (validationError) { - this.formError = validationError; + this.formError = validationError.message; + this.invalidField = validationError.field; this.notice = null; m.redraw(); return; @@ -134,6 +229,7 @@ export const SettingsPage: m.Component<SettingsAttrs> = { this.pending = true; this.formError = null; + this.invalidField = null; this.notice = null; m.redraw(); @@ -141,6 +237,8 @@ export const SettingsPage: m.Component<SettingsAttrs> = { const settings = await updateAdminRealmSettings(realmSlug, { display_name: this.form.display_name.trim(), allow_session_duration_choice: this.form.allow_session_duration_choice, + logo_url: this.form.logo_url.trim() || null, + primary_color: this.form.primary_color.trim() || null, }); if (this.loadedRealm !== realmSlug) return; @@ -150,11 +248,15 @@ export const SettingsPage: m.Component<SettingsAttrs> = { this.notice = 'Realm settings saved.'; await this.attrs.onRealmsChanged(); } catch (e: any) { - if (e?.status === 401 || e?.status === 400) { + if ( + e?.status === 401 || + (e?.status === 400 && e?.code !== 'invalid_request') + ) { this.attrs.onAuthExpired(); return; } this.formError = e as Error; + this.invalidField = fieldFromError(e?.message); } finally { this.pending = false; m.redraw(); @@ -165,10 +267,12 @@ export const SettingsPage: m.Component<SettingsAttrs> = { const { realms, realmsError, realmSlug } = this.attrs; const selected = realms?.find((realm) => realm.slug === realmSlug) || realms?.[0] || null; + const previewLogo = logoUrlError(this.form.logo_url) ? '' : this.form.logo_url.trim(); + const previewColor = normalizePreviewColor(this.form.primary_color); return ( <div> - <PageHeader row title="Realm settings" subtitle="Realm name and login behavior."> + <PageHeader row title="Realm settings" subtitle="Realm name, branding, and login behavior."> <RealmSelector realms={realms} selected={selected} @@ -220,58 +324,126 @@ export const SettingsPage: m.Component<SettingsAttrs> = { <div class="skeleton skeleton-short"></div> </div> ) : this.settings ? ( - <section class="panel"> - <h2>Realm details</h2> - <form class="settings-form" onsubmit={(event: Event) => { - event.preventDefault(); - this.submit(); - }}> - {this.formError ? ( - <div class="alert" role="alert"> - {typeof this.formError === 'string' ? this.formError : this.formError.message} + <div class="settings-stack"> + <section class="panel"> + <h2>Realm details</h2> + <form class="settings-form" onsubmit={(event: Event) => { + event.preventDefault(); + this.submit(); + }}> + {this.formError ? ( + <div class="alert" role="alert"> + {typeof this.formError === 'string' ? this.formError : this.formError.message} + </div> + ) : null} + + <div class="form-field"> + <span class="field-label">Realm ID</span> + <input class="field-control" value={this.settings.slug} disabled /> </div> - ) : null} - <div class="form-field"> - <span class="field-label">Realm ID</span> - <input class="field-control" value={this.settings.slug} disabled /> - </div> + <div class="form-field"> + <span class="field-label">Display name</span> + <input + class="field-control" + value={this.form.display_name} + maxlength="100" + disabled={this.pending} + aria-invalid={this.invalidField === 'display_name' ? 'true' : null} + oninput={(event: Event) => { + this.form.display_name = (event.target as HTMLInputElement).value; + this.invalidField = null; + }} + /> + </div> - <div class="form-field"> - <span class="field-label">Display name</span> - <input - class="field-control" - value={this.form.display_name} - maxlength="100" - disabled={this.pending} - aria-invalid={Boolean(this.formError)} - oninput={(event: Event) => { - this.form.display_name = (event.target as HTMLInputElement).value; - }} - /> - </div> + <label class="checkbox-row"> + <input + type="checkbox" + checked={this.form.allow_session_duration_choice} + disabled={this.pending} + onchange={(event: Event) => { + this.form.allow_session_duration_choice = ( + event.target as HTMLInputElement + ).checked; + }} + /> + <span>Show "Keep me signed in" on login</span> + </label> + </form> + </section> + + <section class="panel"> + <h2>Realm branding</h2> + <p class="note">Shown on login and consent for clients in this realm.</p> + <div class="settings-form"> + <div class="field-grid"> + <div class="form-field"> + <span class="field-label">Logo URL</span> + <input + class="field-control" + type="url" + value={this.form.logo_url} + placeholder="https://app.example.test/logo.svg" + maxlength="2048" + disabled={this.pending} + aria-invalid={this.invalidField === 'logo_url' ? 'true' : null} + oninput={(event: Event) => { + this.form.logo_url = (event.target as HTMLInputElement).value; + this.invalidField = null; + }} + /> + </div> + + <div class="form-field"> + <span class="field-label">Primary color</span> + <input + class="field-control" + value={this.form.primary_color} + placeholder="#25a" + maxlength="7" + spellcheck="false" + disabled={this.pending} + aria-invalid={this.invalidField === 'primary_color' ? 'true' : null} + oninput={(event: Event) => { + this.form.primary_color = (event.target as HTMLInputElement).value; + this.invalidField = null; + }} + /> + </div> + </div> - <label class="checkbox-row"> - <input - type="checkbox" - checked={this.form.allow_session_duration_choice} - disabled={this.pending} - onchange={(event: Event) => { - this.form.allow_session_duration_choice = ( - event.target as HTMLInputElement - ).checked; - }} - /> - <span>Show "Keep me signed in" on login</span> - </label> - - <div class="settings-actions"> - <button class="button" type="submit" disabled={this.pending}> - {this.pending ? 'Saving' : 'Save changes'} - </button> + <div class="branding-preview" aria-hidden="true"> + <span class={`branding-logo-preview${previewLogo ? '' : ' is-empty'}`}> + {previewLogo ? ( + <img + src={previewLogo} + alt="" + onerror={(event: Event) => { + (event.target as HTMLImageElement).style.visibility = 'hidden'; + }} + /> + ) : null} + </span> + <span + class={`branding-color-preview${previewColor ? '' : ' is-empty'}`} + style={previewColor ? { background: previewColor } : {}} + ></span> + </div> + + <div class="settings-actions"> + <button + class="button" + type="button" + disabled={this.pending} + onclick={() => this.submit()} + > + {this.pending ? 'Saving' : 'Save changes'} + </button> + </div> </div> - </form> - </section> + </section> + </div> ) : null} </div> ); diff --git a/app/admin/src/util/api.ts b/app/admin/src/util/api.ts @@ -14,6 +14,8 @@ export interface AdminRealmSettings { slug: string; display_name: string; allow_session_duration_choice: boolean; + logo_url: string | null; + primary_color: string | null; created_at: number; updated_at: number; } @@ -21,6 +23,8 @@ export interface AdminRealmSettings { export interface AdminRealmSettingsInput { display_name: string; allow_session_duration_choice: boolean; + logo_url?: string | null; + primary_color?: string | null; } export interface AdminRole { diff --git a/app/login/src/screen/login.tsx b/app/login/src/screen/login.tsx @@ -58,6 +58,11 @@ function scopeDescription(scope: string, realmName: string) { return `Use the ${scope} permission.`; } +function primaryColor(value: unknown) { + if (typeof value !== 'string') return '#25A'; + return /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(value) ? value : '#25A'; +} + const TextField: m.Component<TextFieldAttrs> = { view({ attrs }) { return ( @@ -260,7 +265,7 @@ export const Login: m.Component<{ clientId?: string }> = { view(this: any) { const branding = this.discovery?.branding || {}; - const primary = typeof branding.primary_color === 'string' ? branding.primary_color : '#25A'; + const primary = primaryColor(branding.primary_color); const style = { '--realm-primary': primary } as any; if (!this.discovery && this.error) { @@ -285,7 +290,14 @@ export const Login: m.Component<{ clientId?: string }> = { <div class="auth-page" style={style}> <div class={`auth-card${this.step === 'consent' ? ' auth-card-consent' : ''}`}> {typeof branding.logo_url === 'string' && branding.logo_url ? ( - <img class="auth-logo" src={branding.logo_url} alt={title} /> + <img + class="auth-logo" + src={branding.logo_url} + alt={title} + onerror={(event: Event) => { + (event.target as HTMLImageElement).style.display = 'none'; + }} + /> ) : null} <h1>{title}</h1> diff --git a/app/shared/style/global.css b/app/shared/style/global.css @@ -110,6 +110,7 @@ textarea { } .sidebar { + min-width: 0; display: flex; flex-direction: column; min-height: auto; @@ -118,6 +119,7 @@ textarea { } .nav { + min-width: 0; display: flex; flex-direction: row; flex-wrap: nowrap; @@ -142,12 +144,12 @@ textarea { } .nav-item { + min-width: 0; display: flex; align-items: center; justify-content: center; gap: 0.75rem; - min-width: 4rem; - flex: 1 0 auto; + flex: 1 1 0; padding: 0.6875rem 0.5rem; color: rgba(255, 255, 255, 0.82); font-size: 0.875rem; diff --git a/mockup/plain/admin-settings.html b/mockup/plain/admin-settings.html @@ -7,9 +7,10 @@ <link rel="stylesheet" href="./global.css" /> <style> .settings-form { + min-width: 0; display: grid; + grid-template-columns: minmax(0, 1fr); width: 100%; - min-width: 0; max-width: 100%; gap: 1rem; margin-top: 1rem; @@ -35,6 +36,63 @@ max-width: 100%; } + .settings-stack { + min-width: 0; + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 1rem; + } + + .field-grid { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 1rem; + } + + .branding-preview { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.75rem; + margin-top: 0.25rem; + } + + .branding-logo-preview, + .branding-color-preview { + width: 2rem; + height: 2rem; + overflow: hidden; + background: var(--row); + } + + .branding-logo-preview { + display: inline-flex; + align-items: center; + justify-content: center; + color: var(--muted); + } + + .branding-logo-preview svg { + width: 1.25rem; + height: 1.25rem; + } + + .branding-logo-preview img { + width: 100%; + height: 100%; + object-fit: contain; + } + + .branding-color-preview { + border-radius: 0.25rem; + background: var(--field-line); + } + + .branding-logo-preview.is-empty, + .branding-color-preview.is-empty { + border-bottom: 1pt solid var(--field-line); + } + .state-preview { margin-top: 2rem; } @@ -42,6 +100,12 @@ .state-preview > h2 { margin-bottom: 0.75rem; } + + @media (min-width: 40em) { + .field-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + } </style> </head> <body> @@ -151,7 +215,7 @@ <div class="page-header page-header-row"> <div> <h1>Realm settings</h1> - <p>Realm name and login behavior.</p> + <p>Realm name, branding, and login behavior.</p> </div> <label class="realm-select"> <span>Realm</span> @@ -162,29 +226,64 @@ </label> </div> - <section class="panel"> - <h2>Realm details</h2> - <form class="settings-form"> - <div class="form-field"> - <span class="field-label">Realm ID</span> - <input class="field-control" value="acme" disabled /> - </div> + <div class="settings-stack"> + <section class="panel"> + <h2>Realm details</h2> + <form class="settings-form"> + <div class="form-field"> + <span class="field-label">Realm ID</span> + <input class="field-control" value="acme" disabled /> + </div> - <div class="form-field"> - <span class="field-label">Display name</span> - <input class="field-control" value="Acme" maxlength="100" /> - </div> + <div class="form-field"> + <span class="field-label">Display name</span> + <input class="field-control" value="Acme" maxlength="100" /> + </div> + + <label class="checkbox-row"> + <input type="checkbox" checked /> + <span>Show "Keep me signed in" on login</span> + </label> + </form> + </section> + + <section class="panel"> + <h2>Realm branding</h2> + <p class="note">Shown on login and consent for clients in this realm.</p> + <div class="settings-form"> + <div class="field-grid"> + <div class="form-field"> + <span class="field-label">Logo URL</span> + <input + class="field-control" + type="url" + value="https://acme.example.test/logo.svg" + placeholder="https://app.example.test/logo.svg" + maxlength="2048" + /> + </div> - <label class="checkbox-row"> - <input type="checkbox" checked /> - <span>Show "Keep me signed in" on login</span> - </label> + <div class="form-field"> + <span class="field-label">Primary color</span> + <input class="field-control" value="#2255aa" placeholder="#25a" maxlength="7" spellcheck="false" /> + </div> + </div> + + <div class="branding-preview" aria-hidden="true"> + <span class="branding-logo-preview"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> + <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> + <span class="branding-color-preview" style="background: #2255aa"></span> + </div> - <div class="settings-actions"> - <button class="button" type="submit">Save changes</button> + <div class="settings-actions"> + <button class="button" type="submit">Save changes</button> + </div> </div> - </form> - </section> + </section> + </div> <section class="state-preview"> <h2>Loading state</h2> @@ -198,57 +297,124 @@ <section class="state-preview"> <h2>Saved state</h2> <div class="notice" role="status">Realm settings saved.</div> - <section class="panel"> - <h2>Realm details</h2> - <form class="settings-form"> - <div class="form-field"> - <span class="field-label">Realm ID</span> - <input class="field-control" value="acme" disabled /> - </div> + <div class="settings-stack"> + <section class="panel"> + <h2>Realm details</h2> + <form class="settings-form"> + <div class="form-field"> + <span class="field-label">Realm ID</span> + <input class="field-control" value="acme" disabled /> + </div> - <div class="form-field"> - <span class="field-label">Display name</span> - <input class="field-control" value="Acme Inc" maxlength="100" /> - </div> + <div class="form-field"> + <span class="field-label">Display name</span> + <input class="field-control" value="Acme Inc" maxlength="100" /> + </div> - <label class="checkbox-row"> - <input type="checkbox" /> - <span>Show "Keep me signed in" on login</span> - </label> + <label class="checkbox-row"> + <input type="checkbox" /> + <span>Show "Keep me signed in" on login</span> + </label> + </form> + </section> - <div class="settings-actions"> - <button class="button" type="submit">Save changes</button> + <section class="panel"> + <h2>Realm branding</h2> + <p class="note">Shown on login and consent for clients in this realm.</p> + <div class="settings-form"> + <div class="field-grid"> + <div class="form-field"> + <span class="field-label">Logo URL</span> + <input + class="field-control" + type="url" + value="https://acme.example.test/logo.svg" + placeholder="https://app.example.test/logo.svg" + maxlength="2048" + /> + </div> + + <div class="form-field"> + <span class="field-label">Primary color</span> + <input class="field-control" value="#2255aa" placeholder="#25a" maxlength="7" spellcheck="false" /> + </div> + </div> + + <div class="branding-preview" aria-hidden="true"> + <span class="branding-logo-preview"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> + <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> + <span class="branding-color-preview" style="background: #2255aa"></span> + </div> + + <div class="settings-actions"> + <button class="button" type="submit">Save changes</button> + </div> </div> - </form> - </section> + </section> + </div> </section> <section class="state-preview"> <h2>Validation error</h2> <div class="alert" role="alert">Display name is required.</div> - <section class="panel"> - <h2>Realm details</h2> - <form class="settings-form"> - <div class="form-field"> - <span class="field-label">Realm ID</span> - <input class="field-control" value="acme" disabled /> - </div> + <div class="settings-stack"> + <section class="panel"> + <h2>Realm details</h2> + <form class="settings-form"> + <div class="form-field"> + <span class="field-label">Realm ID</span> + <input class="field-control" value="acme" disabled /> + </div> - <div class="form-field"> - <span class="field-label">Display name</span> - <input class="field-control" value="" aria-invalid="true" maxlength="100" /> - </div> + <div class="form-field"> + <span class="field-label">Display name</span> + <input class="field-control" value="" aria-invalid="true" maxlength="100" /> + </div> - <label class="checkbox-row"> - <input type="checkbox" checked /> - <span>Show "Keep me signed in" on login</span> - </label> + <label class="checkbox-row"> + <input type="checkbox" checked /> + <span>Show "Keep me signed in" on login</span> + </label> + </form> + </section> - <div class="settings-actions"> - <button class="button" type="submit">Save changes</button> + <section class="panel"> + <h2>Realm branding</h2> + <p class="note">Shown on login and consent for clients in this realm.</p> + <div class="settings-form"> + <div class="field-grid"> + <div class="form-field"> + <span class="field-label">Logo URL</span> + <input + class="field-control" + type="url" + value="http://acme.example.test/logo.svg" + placeholder="https://app.example.test/logo.svg" + aria-invalid="true" + maxlength="2048" + /> + </div> + + <div class="form-field"> + <span class="field-label">Primary color</span> + <input class="field-control" value="#25a" placeholder="#25a" maxlength="7" spellcheck="false" /> + </div> + </div> + + <div class="branding-preview" aria-hidden="true"> + <span class="branding-logo-preview is-empty"></span> + <span class="branding-color-preview" style="background: #2255aa"></span> + </div> + + <div class="settings-actions"> + <button class="button" type="submit">Save changes</button> + </div> </div> - </form> - </section> + </section> + </div> </section> </main> </div> diff --git a/mockup/plain/global.css b/mockup/plain/global.css @@ -98,6 +98,7 @@ body { } .sidebar { + min-width: 0; display: flex; flex-direction: column; min-height: auto; @@ -106,6 +107,7 @@ body { } .nav { + min-width: 0; display: flex; flex-direction: row; flex-wrap: nowrap; @@ -130,12 +132,12 @@ body { } .nav-item { + min-width: 0; display: flex; align-items: center; justify-content: center; gap: 0.75rem; - min-width: 4rem; - flex: 1 0 auto; + flex: 1 1 0; padding: 0.6875rem 0.5rem; color: rgba(255, 255, 255, 0.82); font-size: 0.875rem; diff --git a/server/src/lib/admin-branding.js b/server/src/lib/admin-branding.js @@ -0,0 +1,183 @@ +import { HttpError } from './http/http-error.js'; + +const LOGO_MAX_LENGTH = 2048; +const PRIMARY_COLOR_PATTERN = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i; + +function invalidRequest(message) { + return new HttpError(400, 'invalid_request', message); +} + +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function parseBranding(rawBranding) { + try { + const parsed = JSON.parse(rawBranding || '{}'); + return isPlainObject(parsed) ? parsed : {}; + } catch { + return {}; + } +} + +function isLoopbackHostname(hostname) { + const host = hostname.startsWith('[') && hostname.endsWith(']') + ? hostname.slice(1, -1) + : hostname; + return ( + host === 'localhost' || + host.endsWith('.localhost') || + host === '127.0.0.1' || + host === '::1' + ); +} + +function normalizeStoredPrimaryColor(value) { + if (typeof value !== 'string') return null; + + const color = value.trim().toLowerCase(); + if (!PRIMARY_COLOR_PATTERN.test(color)) return null; + if (color.length === 4) { + return `#${color[1]}${color[1]}${color[2]}${color[2]}${color[3]}${color[3]}`; + } + return color; +} + +function normalizePrimaryColor(value) { + if (value === null || (typeof value === 'string' && !value.trim())) return null; + if (typeof value !== 'string') { + throw invalidRequest('primary_color must be a string or null'); + } + + const color = normalizeStoredPrimaryColor(value); + if (!color) { + throw invalidRequest('primary_color must be a #rgb or #rrggbb hex color'); + } + return color; +} + +function normalizeLogoUrl(value) { + if (value === null || (typeof value === 'string' && !value.trim())) return null; + if (typeof value !== 'string') { + throw invalidRequest('logo_url must be a string or null'); + } + + const url = value.trim(); + if (!url) return null; + if (url.length > LOGO_MAX_LENGTH) { + throw invalidRequest(`logo_url must be at most ${LOGO_MAX_LENGTH} characters`); + } + if (url.includes('*')) { + throw invalidRequest('logo_url cannot contain wildcards'); + } + + let parsed; + try { + parsed = new URL(url); + } catch { + throw invalidRequest('logo_url must be an absolute URL'); + } + + const allowedProtocol = + parsed.protocol === 'https:' || + (parsed.protocol === 'http:' && isLoopbackHostname(parsed.hostname)); + if (!allowedProtocol) { + throw invalidRequest('logo_url must use https, or http for a loopback host'); + } + if (parsed.username || parsed.password) { + throw invalidRequest('logo_url cannot contain credentials'); + } + if (parsed.hash) { + throw invalidRequest('logo_url cannot contain a fragment'); + } + + return url; +} + +export function hasBrandingPatch(body) { + return ( + isPlainObject(body) && + (Object.hasOwn(body, 'logo_url') || Object.hasOwn(body, 'primary_color')) + ); +} + +export function normalizeBrandingPatch(body) { + const input = {}; + if (Object.hasOwn(body, 'logo_url')) { + input.logo_url = normalizeLogoUrl(body.logo_url); + } + if (Object.hasOwn(body, 'primary_color')) { + input.primary_color = normalizePrimaryColor(body.primary_color); + } + return input; +} + +export function applyBrandingPatch(rawBranding, patch) { + if (!hasBrandingPatch(patch)) { + return typeof rawBranding === 'string' ? rawBranding : JSON.stringify(parseBranding(rawBranding)); + } + + const current = parseBranding(rawBranding); + const next = { ...current }; + + if (Object.hasOwn(patch, 'logo_url')) { + if (patch.logo_url === null) { + delete next.logo_url; + } else { + next.logo_url = patch.logo_url; + } + } + + if (Object.hasOwn(patch, 'primary_color')) { + if (patch.primary_color === null) { + delete next.primary_color; + } else { + next.primary_color = patch.primary_color; + } + } + + return JSON.stringify(next); +} + +export function serializeBranding(rawBranding) { + const branding = parseBranding(rawBranding); + const logoUrl = + typeof branding.logo_url === 'string' && branding.logo_url.trim() + ? branding.logo_url.trim() + : null; + + return { + logo_url: logoUrl, + primary_color: normalizeStoredPrimaryColor(branding.primary_color), + }; +} + +export function normalizeBrandingObject(rawBranding) { + const branding = parseBranding(rawBranding); + const normalized = { ...branding }; + + if (Object.hasOwn(normalized, 'logo_url')) { + const logoUrl = + typeof normalized.logo_url === 'string' ? normalized.logo_url.trim() : ''; + if (logoUrl) { + normalized.logo_url = logoUrl; + } else { + delete normalized.logo_url; + } + } + + if (Object.hasOwn(normalized, 'primary_color')) { + const color = normalizeStoredPrimaryColor(normalized.primary_color); + if (color) { + normalized.primary_color = color; + } else { + delete normalized.primary_color; + } + } + + return normalized; +} + +export function parseBrandingValue(rawBranding) { + return parseBranding(rawBranding); +} diff --git a/server/src/lib/admin-settings.js b/server/src/lib/admin-settings.js @@ -1,7 +1,18 @@ +import { + applyBrandingPatch, + hasBrandingPatch, + normalizeBrandingPatch, + serializeBranding, +} from './admin-branding.js'; import { HttpError } from './http/http-error.js'; const DISPLAY_NAME_MAX_LENGTH = 100; -const ALLOWED_FIELDS = new Set(['display_name', 'allow_session_duration_choice']); +const ALLOWED_FIELDS = new Set([ + 'display_name', + 'allow_session_duration_choice', + 'logo_url', + 'primary_color', +]); function invalidRequest(message) { return new HttpError(400, 'invalid_request', message); @@ -44,6 +55,7 @@ function serializeSettings(row, realmSlug) { slug: realmSlug, display_name: row.display_name, allow_session_duration_choice: Boolean(row.allow_session_duration_choice), + ...serializeBranding(row.branding), created_at: row.created_at, updated_at: row.updated_at, }; @@ -51,7 +63,8 @@ function serializeSettings(row, realmSlug) { async function loadSettingsRow(realmDb, realmSlug) { const row = await realmDb.get( - `SELECT slug, display_name, allow_session_duration_choice, created_at, updated_at + `SELECT slug, display_name, branding, allow_session_duration_choice, + created_at, updated_at FROM realm_settings WHERE id = 1` ); @@ -89,6 +102,8 @@ export function normalizeAdminRealmSettingsPatch(body) { ); } + Object.assign(input, normalizeBrandingPatch(body)); + return input; } @@ -112,15 +127,20 @@ export async function updateAdminRealmSettings({ const allowSessionDurationChoice = Object.hasOwn(input, 'allow_session_duration_choice') ? input.allow_session_duration_choice : Boolean(current.allow_session_duration_choice); + const branding = hasBrandingPatch(input) + ? applyBrandingPatch(current.branding, input) + : current.branding; await realmDb.run( `UPDATE realm_settings SET display_name = {displayName}, + branding = {branding}, allow_session_duration_choice = {allowSessionDurationChoice}, updated_at = {now} WHERE id = 1`, { displayName, + branding, allowSessionDurationChoice: allowSessionDurationChoice ? 1 : 0, now, } diff --git a/server/src/lib/realm.js b/server/src/lib/realm.js @@ -1,6 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; import crypto from 'node:crypto'; +import { normalizeBrandingObject } from './admin-branding.js'; import { openDatabase, runMigrations } from './db/index.js'; import { MIGRATIONS_ROOT } from './db/migrate.js'; import { HttpError } from './http/http-error.js'; @@ -31,15 +32,6 @@ async function migrateSystem(db) { }); } -function parseBranding(raw) { - try { - const parsed = JSON.parse(raw || '{}'); - return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}; - } catch { - return {}; - } -} - async function ensureRole(db, slug, name, now) { const existing = await db.get('SELECT id FROM roles WHERE slug = {slug}', { slug }); if (existing) return existing.id; @@ -161,7 +153,7 @@ export async function realmMetadata(realm) { return { slug: settings.slug, display_name: settings.display_name, - branding: parseBranding(settings.branding), + branding: normalizeBrandingObject(settings.branding), allow_session_duration_choice: Boolean(settings.allow_session_duration_choice), }; } diff --git a/server/test/admin-branding.test.js b/server/test/admin-branding.test.js @@ -0,0 +1,99 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + applyBrandingPatch, + hasBrandingPatch, + normalizeBrandingPatch, + serializeBranding, +} from '../src/lib/admin-branding.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 branding normalizes primary colors and clears empty values', () => { + assert.deepEqual(normalizeBrandingPatch({ primary_color: '#25A' }), { + primary_color: '#2255aa', + }); + assert.deepEqual(normalizeBrandingPatch({ primary_color: '#abc' }), { + primary_color: '#aabbcc', + }); + assert.deepEqual(normalizeBrandingPatch({ primary_color: '' }), { + primary_color: null, + }); + assert.deepEqual(normalizeBrandingPatch({ primary_color: null }), { + primary_color: null, + }); + + expectHttpError( + () => normalizeBrandingPatch({ primary_color: 'red' }), + 400, + 'invalid_request' + ); +}); + +test('admin branding validates logo URLs for https and loopback use', () => { + assert.deepEqual( + normalizeBrandingPatch({ logo_url: ' https://acme.test/logo.svg?size=large ' }), + { logo_url: 'https://acme.test/logo.svg?size=large' } + ); + assert.deepEqual(normalizeBrandingPatch({ logo_url: 'http://localhost/logo.svg' }), { + logo_url: 'http://localhost/logo.svg', + }); + assert.deepEqual( + normalizeBrandingPatch({ logo_url: 'http://acme.localhost/logo.svg' }), + { logo_url: 'http://acme.localhost/logo.svg' } + ); + + for (const logoUrl of [ + 'http://acme.test/logo.svg', + 'data:image/svg+xml,%3Csvg/%3E', + 'javascript:alert(1)', + '/logo.svg', + 'https://user:password@acme.test/logo.svg', + 'https://acme.test/logo.svg#fragment', + 'https://*.acme.test/logo.svg', + `https://acme.test/${'a'.repeat(2048)}.svg`, + ]) { + expectHttpError( + () => normalizeBrandingPatch({ logo_url: logoUrl }), + 400, + 'invalid_request' + ); + } +}); + +test('admin branding patches preserve unknown keys and clear individual fields', () => { + const current = JSON.stringify({ + primary_color: '#2255aa', + custom_asset: 'https://acme.test/custom.png', + }); + + const updated = applyBrandingPatch(current, { + logo_url: 'https://acme.test/logo.svg', + }); + assert.deepEqual(JSON.parse(updated), { + primary_color: '#2255aa', + custom_asset: 'https://acme.test/custom.png', + logo_url: 'https://acme.test/logo.svg', + }); + + const cleared = applyBrandingPatch(updated, { logo_url: null }); + assert.deepEqual(JSON.parse(cleared), { + primary_color: '#2255aa', + custom_asset: 'https://acme.test/custom.png', + }); + assert.equal(hasBrandingPatch({ logo_url: null }), true); + assert.equal(hasBrandingPatch({ display_name: 'Acme' }), false); + assert.deepEqual(serializeBranding(cleared), { + logo_url: null, + primary_color: '#2255aa', + }); +}); diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -3929,18 +3929,34 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { } }); - await t.test('admin realm settings update name and login behavior', async () => { + await t.test('admin realm settings update name, branding, and login behavior', async () => { const acmeAdmin = await adminToken('it@acme.test'); const systemAdmin = await adminToken(); let original = null; + let originalBranding = null; + + const readBranding = () => + withRealmDatabase(env, 'acme', (database) => + database.prepare('SELECT branding FROM realm_settings WHERE id = 1').get().branding + ); + const writeBranding = (value) => + withRealmDatabase(env, 'acme', (database) => { + database + .prepare('UPDATE realm_settings SET branding = ? WHERE id = 1') + .run(value); + }); try { + originalBranding = readBranding(); + const initial = await adminRequest(acmeAdmin, { path: '/api/v1/admin/realms/acme/settings', }); assert.equal(initial.status, 200); assert.equal(initial.json.settings.slug, 'acme'); assert.equal(typeof initial.json.settings.created_at, 'number'); + assert.equal(initial.json.settings.logo_url, null); + assert.equal(initial.json.settings.primary_color, '#2255aa'); original = initial.json.settings; const crossRealm = await adminRequest(acmeAdmin, { @@ -3957,6 +3973,8 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.equal(renamed.json.ok, true); assert.equal(renamed.json.settings.display_name, 'Acme Inc'); assert.equal(renamed.json.settings.allow_session_duration_choice, true); + assert.equal(renamed.json.settings.logo_url, null); + assert.equal(renamed.json.settings.primary_color, '#2255aa'); const realms = await adminRequest(systemAdmin, { path: '/api/v1/admin/realms', @@ -3970,6 +3988,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { const publicRenamed = await acme({ path: '/api/v1/realm' }); assert.equal(publicRenamed.json.display_name, 'Acme Inc'); assert.equal(publicRenamed.json.allow_session_duration_choice, true); + assert.equal(publicRenamed.json.branding.primary_color, '#2255aa'); const disabledChoice = await adminRequest(systemAdmin, { method: 'PATCH', @@ -3979,11 +3998,57 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.equal(disabledChoice.status, 200); assert.equal(disabledChoice.json.settings.display_name, 'Acme Inc'); assert.equal(disabledChoice.json.settings.allow_session_duration_choice, false); + assert.equal(disabledChoice.json.settings.logo_url, null); + assert.equal(disabledChoice.json.settings.primary_color, '#2255aa'); const publicDisabledChoice = await acme({ path: '/api/v1/realm' }); assert.equal(publicDisabledChoice.json.display_name, 'Acme Inc'); assert.equal(publicDisabledChoice.json.allow_session_duration_choice, false); + const logoUpdated = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: '/api/v1/admin/realms/acme/settings', + body: { logo_url: ' https://acme.test/logo.svg?size=large ' }, + }); + assert.equal(logoUpdated.status, 200); + assert.equal(logoUpdated.json.settings.display_name, 'Acme Inc'); + assert.equal(logoUpdated.json.settings.allow_session_duration_choice, false); + assert.equal( + logoUpdated.json.settings.logo_url, + 'https://acme.test/logo.svg?size=large' + ); + assert.equal(logoUpdated.json.settings.primary_color, '#2255aa'); + + const publicLogo = await acme({ path: '/api/v1/realm' }); + assert.equal(publicLogo.json.branding.logo_url, 'https://acme.test/logo.svg?size=large'); + assert.equal(publicLogo.json.branding.primary_color, '#2255aa'); + + const discovery = await acme({ + path: '/oidc/internal-app/openid-configuration', + }); + assert.equal(discovery.status, 200); + assert.equal(discovery.json.branding.logo_url, 'https://acme.test/logo.svg?size=large'); + assert.equal(discovery.json.branding.primary_color, '#2255aa'); + + const colorUpdated = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: '/api/v1/admin/realms/acme/settings', + body: { primary_color: '#abc' }, + }); + assert.equal(colorUpdated.status, 200); + assert.equal(colorUpdated.json.settings.display_name, 'Acme Inc'); + assert.equal(colorUpdated.json.settings.allow_session_duration_choice, false); + assert.equal( + colorUpdated.json.settings.logo_url, + 'https://acme.test/logo.svg?size=large' + ); + assert.equal(colorUpdated.json.settings.primary_color, '#aabbcc'); + + const updatedDiscovery = await acme({ + path: '/oidc/internal-app/openid-configuration', + }); + assert.equal(updatedDiscovery.json.branding.primary_color, '#aabbcc'); + const emptyPatch = await adminRequest(acmeAdmin, { method: 'PATCH', path: '/api/v1/admin/realms/acme/settings', @@ -3999,6 +4064,11 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { { display_name: 'A'.repeat(101) }, { display_name: 'Acme\nInc' }, { allow_session_duration_choice: 'false' }, + { logo_url: 'http://acme.test/logo.svg' }, + { logo_url: 'data:image/svg+xml,%3Csvg/%3E' }, + { logo_url: 'https://acme.test/logo.svg#fragment' }, + { primary_color: 'red' }, + { primary_color: '#25aa' }, ]) { const invalid = await adminRequest(acmeAdmin, { method: 'PATCH', @@ -4009,6 +4079,51 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.equal(invalid.json.error.code, 'invalid_request'); } + writeBranding( + JSON.stringify({ + custom_asset: 'https://acme.test/custom.png', + primary_color: '#123456', + }) + ); + + const preservedName = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: '/api/v1/admin/realms/acme/settings', + body: { display_name: 'Custom Acme' }, + }); + assert.equal(preservedName.status, 200); + assert.equal(preservedName.json.settings.logo_url, null); + assert.equal(preservedName.json.settings.primary_color, '#123456'); + assert.deepEqual(JSON.parse(readBranding()), { + custom_asset: 'https://acme.test/custom.png', + primary_color: '#123456', + }); + + const preservedLogo = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: '/api/v1/admin/realms/acme/settings', + body: { logo_url: 'https://acme.test/custom-logo.svg' }, + }); + assert.equal(preservedLogo.status, 200); + assert.deepEqual(JSON.parse(readBranding()), { + custom_asset: 'https://acme.test/custom.png', + primary_color: '#123456', + logo_url: 'https://acme.test/custom-logo.svg', + }); + + const clearedLogo = await adminRequest(acmeAdmin, { + method: 'PATCH', + path: '/api/v1/admin/realms/acme/settings', + body: { logo_url: '' }, + }); + assert.equal(clearedLogo.status, 200); + assert.equal(clearedLogo.json.settings.logo_url, null); + assert.equal(clearedLogo.json.settings.primary_color, '#123456'); + assert.deepEqual(JSON.parse(readBranding()), { + custom_asset: 'https://acme.test/custom.png', + primary_color: '#123456', + }); + const stored = withRealmDatabase(env, 'acme', (database) => database .prepare('SELECT slug, status FROM realm_settings WHERE id = 1') @@ -4027,6 +4142,9 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }, }); } + if (originalBranding !== null) { + writeBranding(originalBranding); + } } }); } finally {