auth

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

commit 541335a99d5d5064d6e4fad2387dcc1979235cef
parent d3dc4dced3d5343d6c48482aa51da79c295a286e
Author: finwo <finwo@pm.me>
Date:   Tue,  3 Nov 2026 21:47:51 +0100

Added client branding management

Diffstat:
Mapp/admin/src/assets/admin.css | 14++++++++++++++
Mapp/admin/src/component/client-form.tsx | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/screen/client-edit.tsx | 26+++++++++++++++++++++++++-
Mapp/admin/src/screen/clients.tsx | 28+++++++++++++++++++++++++++-
Mapp/admin/src/screen/settings.tsx | 80+++++++++++++------------------------------------------------------------------
Mapp/admin/src/util/api.ts | 3+++
Aapp/shared/util/branding.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/src/controller/oidc.js | 9+++++----
Mserver/src/lib/admin-branding.js | 2++
Mserver/src/lib/admin-clients.js | 37++++++++++++++++++++++++-------------
Mserver/src/lib/oidc/clients.js | 3++-
Mserver/test/admin-branding.test.js | 27+++++++++++++++++++++++++++
Mserver/test/http.test.js | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13 files changed, 454 insertions(+), 87 deletions(-)

diff --git a/app/admin/src/assets/admin.css b/app/admin/src/assets/admin.css @@ -352,6 +352,20 @@ line-height: 1.4; } +.branding-field { + margin: 0; + padding: 0; + border: 0; +} + +.branding-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; diff --git a/app/admin/src/component/client-form.tsx b/app/admin/src/component/client-form.tsx @@ -1,5 +1,13 @@ import m from 'mithril'; import { SelectMenu } from '@component/select-menu'; +import { + brandingFromInput, + logoUrlError, + normalizePreviewColor, + validateBrandingFields, + type BrandingField, + type BrandingValidationError, +} from '@util/branding'; import type { AdminClient, AdminClientInput, AdminRole } from '../util/api'; export interface ClientFormValue { @@ -14,6 +22,8 @@ export interface ClientFormValue { token_endpoint_auth_method: AdminClient['token_endpoint_auth_method']; require_pkce: boolean; consent_mode: AdminClient['consent_mode']; + logo_url: string; + primary_color: string; } export function defaultClientForm(): ClientFormValue { @@ -29,6 +39,8 @@ export function defaultClientForm(): ClientFormValue { token_endpoint_auth_method: 'none', require_pkce: true, consent_mode: 'remembered', + logo_url: '', + primary_color: '', }; } @@ -49,6 +61,8 @@ export function clientFormValue(client: AdminClient): ClientFormValue { token_endpoint_auth_method: client.token_endpoint_auth_method, require_pkce: client.require_pkce, consent_mode: client.consent_mode, + logo_url: client.logo_url || '', + primary_color: client.primary_color || '', }; } @@ -65,9 +79,14 @@ export function toClientInput(value: ClientFormValue): AdminClientInput { token_endpoint_auth_method: tokenEndpointAuthMethod, require_pkce: tokenEndpointAuthMethod === 'none' ? true : value.require_pkce, consent_mode: value.consent_mode, + ...brandingFromInput(value), }; } +export function validateClientBranding(value: ClientFormValue): BrandingValidationError | null { + return validateBrandingFields(value); +} + interface ClientFormAttrs { value: ClientFormValue; roles: AdminRole[]; @@ -75,6 +94,8 @@ interface ClientFormAttrs { submitLabel: string; pending: boolean; error: Error | string | null; + invalidField?: BrandingField | null; + onclearerror?: () => void; onsubmit: () => void; oncancel?: () => void; } @@ -83,6 +104,9 @@ export const ClientForm: m.Component<ClientFormAttrs> = { view({ attrs }) { const value = attrs.value; const requirePkce = value.token_endpoint_auth_method === 'none' || value.require_pkce; + const previewLogo = logoUrlError(value.logo_url) ? '' : value.logo_url.trim(); + const previewColor = normalizePreviewColor(value.primary_color); + const clearError = () => attrs.onclearerror?.(); return ( <form @@ -233,6 +257,64 @@ export const ClientForm: m.Component<ClientFormAttrs> = { /> </div> + <fieldset class="branding-field"> + <legend>Branding</legend> + <p class="note">Optional client overrides. Empty values use this realm's branding.</p> + <div class="field-grid"> + <div class="form-field"> + <span class="field-label">Logo URL</span> + <input + class="field-control" + type="url" + value={value.logo_url} + placeholder="https://app.example.test/logo.svg" + maxlength="2048" + disabled={attrs.pending} + aria-invalid={attrs.invalidField === 'logo_url' ? 'true' : null} + oninput={(event: Event) => { + value.logo_url = (event.target as HTMLInputElement).value; + clearError(); + }} + /> + </div> + + <div class="form-field"> + <span class="field-label">Primary color</span> + <input + class="field-control" + value={value.primary_color} + placeholder="#25a" + maxlength="7" + spellcheck="false" + disabled={attrs.pending} + aria-invalid={attrs.invalidField === 'primary_color' ? 'true' : null} + oninput={(event: Event) => { + value.primary_color = (event.target as HTMLInputElement).value; + clearError(); + }} + /> + </div> + </div> + + <div class="branding-preview" aria-hidden="true"> + <span class={`branding-logo-preview${previewLogo ? '' : ' is-empty'}`}> + {previewLogo ? ( + <img + src={previewLogo} + alt="" + onerror={(event: Event) => { + (event.target as HTMLImageElement).style.visibility = 'hidden'; + }} + /> + ) : null} + </span> + <span + class={`branding-color-preview${previewColor ? '' : ' is-empty'}`} + style={previewColor ? { background: previewColor } : {}} + ></span> + </div> + </fieldset> + <fieldset class="role-field"> <legend>Required roles</legend> {attrs.roles.length === 0 ? ( diff --git a/app/admin/src/screen/client-edit.tsx b/app/admin/src/screen/client-edit.tsx @@ -1,12 +1,17 @@ import m from 'mithril'; import { Modal } from '@component/modal'; import { PageHeader } from '@component/page-header'; +import { + brandingValidationErrorField, + type BrandingField, +} from '@util/branding'; import { RealmSelector } from '../component/realm-selector'; import { ClientForm, clientFormValue, defaultClientForm, toClientInput, + validateClientBranding, } from '../component/client-form'; import { deleteAdminClient, @@ -39,6 +44,7 @@ export const ClientEditPage: m.Component<ClientEditAttrs> = { form: defaultClientForm(), error: null as Error | null, formError: null as Error | string | null, + invalidField: null as BrandingField | null, notice: null as string | null, secret: null as { clientId: string; secret: string } | null, pending: false, @@ -84,6 +90,7 @@ export const ClientEditPage: m.Component<ClientEditAttrs> = { this.loadedKey = key; this.form = defaultClientForm(); this.formError = null; + this.invalidField = null; this.notice = null; this.secret = null; this.pending = false; @@ -98,6 +105,7 @@ export const ClientEditPage: m.Component<ClientEditAttrs> = { this.loading = true; this.error = null; this.formError = null; + this.invalidField = null; this.notice = null; this.secret = null; m.redraw(); @@ -130,8 +138,18 @@ export const ClientEditPage: m.Component<ClientEditAttrs> = { const { realmSlug, clientId } = this.attrs; if (!realmSlug || !clientId) return; + const brandingError = validateClientBranding(this.form); + if (brandingError) { + this.formError = brandingError.message; + this.invalidField = brandingError.field; + this.notice = null; + m.redraw(); + return; + } + this.pending = true; this.formError = null; + this.invalidField = null; this.notice = null; try { @@ -140,11 +158,12 @@ export const ClientEditPage: m.Component<ClientEditAttrs> = { this.notice = 'Client settings saved.'; await this.load(realmSlug, clientId); } 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 = brandingValidationErrorField(e?.message); } finally { this.pending = false; m.redraw(); @@ -312,6 +331,11 @@ export const ClientEditPage: m.Component<ClientEditAttrs> = { submitLabel="Save changes" pending={this.pending} error={this.formError} + invalidField={this.invalidField} + onclearerror={() => { + this.formError = null; + this.invalidField = null; + }} onsubmit={() => this.submit()} oncancel={() => m.route.set(`/clients/${encodeURIComponent(this.attrs.realmSlug || '')}`)} /> diff --git a/app/admin/src/screen/clients.tsx b/app/admin/src/screen/clients.tsx @@ -3,12 +3,17 @@ import m from 'mithril'; import { Icon } from '@component/icon'; import { Modal } from '@component/modal'; import { PageHeader } from '@component/page-header'; +import { + brandingValidationErrorField, + type BrandingField, +} from '@util/branding'; import { RealmSelector } from '../component/realm-selector'; import { ClientForm, defaultClientForm, parseUriLines, toClientInput, + validateClientBranding, type ClientFormValue, } from '../component/client-form'; import { @@ -66,6 +71,7 @@ export const ClientsPage: m.Component<ClientsAttrs> = { createOpen: false, createValue: defaultClientForm(), createError: null as Error | string | null, + createInvalidField: null as BrandingField | null, oninit(this: any, vnode: m.Vnode<ClientsAttrs>) { this.attrs = vnode.attrs; @@ -107,6 +113,7 @@ export const ClientsPage: m.Component<ClientsAttrs> = { this.createOpen = false; this.createValue = defaultClientForm(); this.createError = null; + this.createInvalidField = null; this.load(realmSlug); } }, @@ -144,6 +151,7 @@ export const ClientsPage: m.Component<ClientsAttrs> = { this.createOpen = true; this.createValue = defaultClientForm(); this.createError = null; + this.createInvalidField = null; m.redraw(); }, @@ -151,6 +159,7 @@ export const ClientsPage: m.Component<ClientsAttrs> = { this.createOpen = false; this.createValue = defaultClientForm(); this.createError = null; + this.createInvalidField = null; m.redraw(); }, @@ -162,12 +171,22 @@ export const ClientsPage: m.Component<ClientsAttrs> = { 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.'; + this.createInvalidField = null; + m.redraw(); + return; + } + + const brandingError = validateClientBranding(value); + if (brandingError) { + this.createError = brandingError.message; + this.createInvalidField = brandingError.field; m.redraw(); return; } this.creating = true; this.createError = null; + this.createInvalidField = null; this.secret = null; try { @@ -181,13 +200,15 @@ export const ClientsPage: m.Component<ClientsAttrs> = { } this.createOpen = false; this.createValue = defaultClientForm(); + this.createInvalidField = null; await this.load(realmSlug); } 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.createError = e as Error; + this.createInvalidField = brandingValidationErrorField(e?.message); } finally { this.creating = false; m.redraw(); @@ -373,6 +394,11 @@ export const ClientsPage: m.Component<ClientsAttrs> = { submitLabel="Create client" pending={this.creating} error={this.createError} + invalidField={this.createInvalidField} + onclearerror={() => { + this.createError = null; + this.createInvalidField = null; + }} onsubmit={() => this.submitCreate()} oncancel={() => this.cancelCreate()} /> diff --git a/app/admin/src/screen/settings.tsx b/app/admin/src/screen/settings.tsx @@ -1,5 +1,12 @@ import m from 'mithril'; import { PageHeader } from '@component/page-header'; +import { + brandingFromInput, + brandingValidationErrorField, + logoUrlError, + normalizePreviewColor, + validateBrandingFields, +} from '@util/branding'; import { RealmSelector } from '../component/realm-selector'; import { loadAdminRealmSettings, updateAdminRealmSettings } from '../util/auth'; import type { AdminRealm, AdminRealmSettings } from '../util/api'; @@ -24,9 +31,6 @@ interface SettingsValidation { 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, @@ -36,54 +40,6 @@ function formFromSettings(settings: AdminRealmSettings): SettingsFormValue { }; } -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(); @@ -100,25 +56,16 @@ function validateForm(value: SettingsFormValue): SettingsValidation | null { }; } - 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', - }; - } + const brandingError = validateBrandingFields(value); + if (brandingError) return brandingError; 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'; + const brandingField = brandingValidationErrorField(message); + if (brandingField) return brandingField; + if (message?.includes('display_name')) return 'display_name'; return null; } @@ -237,8 +184,7 @@ 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, + ...brandingFromInput(this.form), }); if (this.loadedRealm !== realmSlug) return; diff --git a/app/admin/src/util/api.ts b/app/admin/src/util/api.ts @@ -36,6 +36,7 @@ export interface AdminClient { client_id: string; name: string; logo_url: string | null; + primary_color: string | null; access_mode: 'internal' | 'members' | 'public'; enabled: boolean; scopes: string; @@ -61,6 +62,8 @@ export interface AdminClientInput { token_endpoint_auth_method: AdminClient['token_endpoint_auth_method']; require_pkce: boolean; consent_mode: AdminClient['consent_mode']; + logo_url?: string | null; + primary_color?: string | null; } export interface AdminClientCreateInput extends AdminClientInput { diff --git a/app/shared/util/branding.ts b/app/shared/util/branding.ts @@ -0,0 +1,91 @@ +export const LOGO_MAX_LENGTH = 2048; + +export type BrandingField = 'logo_url' | 'primary_color'; + +export interface BrandingFormValue { + logo_url: string; + primary_color: string; +} + +export interface BrandingValidationError { + message: string; + field: BrandingField; +} + +const PRIMARY_COLOR_PATTERN = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i; + +export 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; +} + +export 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' + ); +} + +export 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; +} + +export function validateBrandingFields(value: BrandingFormValue): BrandingValidationError | null { + 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; +} + +export function brandingFromInput(value: BrandingFormValue) { + return { + logo_url: value.logo_url.trim() || null, + primary_color: value.primary_color.trim() || null, + }; +} + +export function brandingValidationErrorField(message: string | null | undefined): BrandingField | null { + if (!message) return null; + if (message.includes('logo_url')) return 'logo_url'; + if (message.includes('primary_color')) return 'primary_color'; + return null; +} diff --git a/server/src/controller/oidc.js b/server/src/controller/oidc.js @@ -1,5 +1,6 @@ import crypto from 'node:crypto'; import { app } from '../app.js'; +import { normalizeBrandingObject } from '../lib/admin-branding.js'; import { serveAppDocument, systemClientPostLogoutUris, @@ -118,10 +119,10 @@ function systemCallbacks(context, client) { async function discovery(context, client) { const realm = context.realm ? await realmMetadata(context.realm) : null; const urls = endpointUrls(context); - const branding = - Object.keys(client.branding || {}).length > 0 - ? client.branding - : realm?.branding || {}; + const branding = { + ...(realm?.branding || {}), + ...normalizeBrandingObject(client.branding), + }; const scopes = String(client.scopes || 'openid profile email') .split(/\s+/) .filter(Boolean); diff --git a/server/src/lib/admin-branding.js b/server/src/lib/admin-branding.js @@ -12,6 +12,8 @@ function isPlainObject(value) { } function parseBranding(rawBranding) { + if (isPlainObject(rawBranding)) return rawBranding; + try { const parsed = JSON.parse(rawBranding || '{}'); return isPlainObject(parsed) ? parsed : {}; diff --git a/server/src/lib/admin-clients.js b/server/src/lib/admin-clients.js @@ -1,4 +1,10 @@ import crypto from 'node:crypto'; +import { + applyBrandingPatch, + hasBrandingPatch, + normalizeBrandingPatch, + serializeBranding, +} from './admin-branding.js'; import { addClientRealm, findClientRealm } from './realm.js'; import { hashClientSecret } from './oidc/clients.js'; import { HttpError } from './http/http-error.js'; @@ -244,19 +250,12 @@ async function loadRoles(db, 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), + ...serializeBranding(row.branding), enabled: Boolean(row.enabled), scopes: row.scopes || DEFAULT_SCOPES, required_roles: requiredRoles, @@ -359,6 +358,8 @@ export function normalizeCreateInput(body) { 'token_endpoint_auth_method', 'require_pkce', 'consent_mode', + 'logo_url', + 'primary_color', ]) ); @@ -401,6 +402,7 @@ export function normalizeCreateInput(body) { tokenEndpointAuthMethod: method, requirePkce, consentMode, + branding: normalizeBrandingPatch(body), }; } @@ -422,6 +424,8 @@ export async function normalizeUpdateInput(body, db) { 'token_endpoint_auth_method', 'require_pkce', 'consent_mode', + 'logo_url', + 'primary_color', ]) ); @@ -458,6 +462,7 @@ export async function normalizeUpdateInput(body, db) { if (Object.hasOwn(body, 'require_pkce')) { result.requirePkce = validateBoolean(body.require_pkce, 'require_pkce'); } + Object.assign(result, normalizeBrandingPatch(body)); if (Object.keys(result).length === 0) { throw invalidRequest('At least one field must be provided'); } @@ -495,6 +500,7 @@ export async function createAdminRealmClient({ systemDb, realmDb, realmId, input const requiredRoles = validateRoles(input.requiredRoles, knownRoles); const clientId = crypto.randomUUID(); const now = Date.now(); + const branding = applyBrandingPatch('{}', input.branding); const clientSecret = input.tokenEndpointAuthMethod === 'client_secret_basic' ? generateClientSecret() : null; @@ -505,10 +511,10 @@ export async function createAdminRealmClient({ systemDb, realmDb, realmId, input (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})`, + VALUES + ({id}, {clientId}, {name}, {redirectUris}, {scopes}, {accessMode}, {enabled}, {branding}, + {clientSecretHash}, {tokenEndpointAuthMethod}, {requirePkce}, + {postLogoutRedirectUris}, {consentMode}, {createdAt}, {updatedAt})`, { id: clientId, clientId: input.clientId, @@ -517,6 +523,7 @@ export async function createAdminRealmClient({ systemDb, realmDb, realmId, input scopes: input.scopes, accessMode: input.accessMode, enabled: input.enabled ? 1 : 0, + branding, clientSecretHash: clientSecret ? hashClientSecret(clientSecret) : null, tokenEndpointAuthMethod: input.tokenEndpointAuthMethod, requirePkce: input.requirePkce ? 1 : 0, @@ -588,6 +595,9 @@ export async function updateAdminRealmClient({ requirePkce, consentMode: input.consentMode ?? current.consent_mode, }; + const branding = hasBrandingPatch(input) + ? applyBrandingPatch(row.branding, input) + : row.branding; const clientSecretHash = tokenEndpointAuthMethod === 'client_secret_basic' ? row.client_secret_hash : null; const now = Date.now(); @@ -597,7 +607,7 @@ export async function updateAdminRealmClient({ await tx.run( `UPDATE oidc_clients SET name = {name}, redirect_uris = {redirectUris}, scopes = {scopes}, - access_mode = {accessMode}, enabled = {enabled}, + access_mode = {accessMode}, enabled = {enabled}, branding = {branding}, client_secret_hash = {clientSecretHash}, token_endpoint_auth_method = {tokenEndpointAuthMethod}, require_pkce = {requirePkce}, @@ -610,6 +620,7 @@ export async function updateAdminRealmClient({ scopes: next.scopes, accessMode: next.accessMode, enabled: next.enabled ? 1 : 0, + branding, clientSecretHash, tokenEndpointAuthMethod: next.tokenEndpointAuthMethod, requirePkce: next.requirePkce ? 1 : 0, diff --git a/server/src/lib/oidc/clients.js b/server/src/lib/oidc/clients.js @@ -1,4 +1,5 @@ import crypto from 'node:crypto'; +import { normalizeBrandingObject } from '../admin-branding.js'; const SYSTEM_CLIENTS = { admin: { @@ -80,7 +81,7 @@ export async function getClient(db, clientId) { require_pkce: Boolean(row.require_pkce), redirect_uris: parseJson(row.redirect_uris, []), post_logout_redirect_uris: parseJson(row.post_logout_redirect_uris, []), - branding: parseJson(row.branding, {}), + branding: normalizeBrandingObject(row.branding), required_roles: roles.map((role) => role.slug), system_client: false, }; diff --git a/server/test/admin-branding.test.js b/server/test/admin-branding.test.js @@ -3,6 +3,7 @@ import assert from 'node:assert/strict'; import { applyBrandingPatch, hasBrandingPatch, + normalizeBrandingObject, normalizeBrandingPatch, serializeBranding, } from '../src/lib/admin-branding.js'; @@ -97,3 +98,29 @@ test('admin branding patches preserve unknown keys and clear individual fields', primary_color: '#2255aa', }); }); + +test('admin branding normalization accepts raw JSON and parsed objects', () => { + assert.deepEqual( + normalizeBrandingObject( + JSON.stringify({ + logo_url: ' https://acme.test/logo.svg ', + primary_color: '#25A', + }) + ), + { + logo_url: 'https://acme.test/logo.svg', + primary_color: '#2255aa', + } + ); + + assert.deepEqual( + normalizeBrandingObject({ + logo_url: '', + primary_color: 'red', + custom_asset: 'https://acme.test/custom.png', + }), + { + custom_asset: 'https://acme.test/custom.png', + } + ); +}); diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -2975,6 +2975,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { 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); + assert.equal(listed.get('confidential-app').primary_color, null); const clientId = 'admin-created-public'; const oldUri = `${origin('created.localhost')}/callback`; @@ -2993,6 +2994,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { 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.primary_color, null); assert.equal(created.json.client_secret, undefined); const duplicate = await createAdminClient(admin, 'acme', { @@ -3036,6 +3038,143 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { } }); + await t.test('admin clients manage branding with realm fallback', async () => { + const admin = await adminToken('it@acme.test'); + const clientId = 'admin-branding-client'; + const redirectUri = `${origin('branding-client.localhost')}/callback`; + const clientLogo = 'https://client.example.test/client-logo.svg'; + const updatedClientColor = '#2255aa'; + const realmLogo = 'https://realm.example.test/realm-logo.svg'; + const realmColor = '#123456'; + const realmAsset = 'https://realm.example.test/realm.css'; + const clientAsset = 'https://client.example.test/client.css'; + let originalRealmBranding = null; + + const readRealmBranding = () => + withRealmDatabase(env, 'acme', (database) => + database.prepare('SELECT branding FROM realm_settings WHERE id = 1').get().branding + ); + const writeRealmBranding = (value) => + withRealmDatabase(env, 'acme', (database) => { + database.prepare('UPDATE realm_settings SET branding = ? WHERE id = 1').run(value); + }); + const readClientBranding = () => + withRealmDatabase(env, 'acme', (database) => + database + .prepare('SELECT branding FROM oidc_clients WHERE client_id = ?') + .get(clientId).branding + ); + const writeClientBranding = (value) => + withRealmDatabase(env, 'acme', (database) => { + database + .prepare('UPDATE oidc_clients SET branding = ? WHERE client_id = ?') + .run(value, clientId); + }); + + try { + originalRealmBranding = readRealmBranding(); + writeRealmBranding( + JSON.stringify({ + logo_url: realmLogo, + primary_color: realmColor, + custom_realm_asset: realmAsset, + }) + ); + + const created = await createAdminClient(admin, 'acme', { + client_id: clientId, + name: 'Branding Client', + access_mode: 'public', + redirect_uris: [redirectUri], + logo_url: clientLogo, + primary_color: '#abc', + }); + assert.equal(created.status, 200); + assert.equal(created.json.client.logo_url, clientLogo); + assert.equal(created.json.client.primary_color, '#aabbcc'); + + let discovery = await acme({ path: `/oidc/${clientId}/openid-configuration` }); + assert.equal(discovery.status, 200); + assert.deepEqual(discovery.json.branding, { + logo_url: clientLogo, + primary_color: '#aabbcc', + custom_realm_asset: realmAsset, + }); + + const colorUpdated = await updateAdminClient(admin, 'acme', clientId, { + primary_color: '#25a', + }); + assert.equal(colorUpdated.status, 200); + assert.equal(colorUpdated.json.client.logo_url, clientLogo); + assert.equal(colorUpdated.json.client.primary_color, updatedClientColor); + + writeClientBranding( + JSON.stringify({ + logo_url: 'https://old-client.example.test/logo.svg', + custom_asset: clientAsset, + primary_color: '#ff0000', + }) + ); + + const logoCleared = await updateAdminClient(admin, 'acme', clientId, { + logo_url: '', + }); + assert.equal(logoCleared.status, 200); + assert.equal(logoCleared.json.client.logo_url, null); + assert.equal(logoCleared.json.client.primary_color, '#ff0000'); + assert.deepEqual(JSON.parse(readClientBranding()), { + custom_asset: clientAsset, + primary_color: '#ff0000', + }); + + discovery = await acme({ path: `/oidc/${clientId}/openid-configuration` }); + assert.deepEqual(discovery.json.branding, { + logo_url: realmLogo, + primary_color: '#ff0000', + custom_realm_asset: realmAsset, + custom_asset: clientAsset, + }); + + const colorCleared = await updateAdminClient(admin, 'acme', clientId, { + primary_color: null, + }); + assert.equal(colorCleared.status, 200); + assert.equal(colorCleared.json.client.primary_color, null); + assert.deepEqual(JSON.parse(readClientBranding()), { + custom_asset: clientAsset, + }); + + discovery = await acme({ path: `/oidc/${clientId}/openid-configuration` }); + assert.deepEqual(discovery.json.branding, { + logo_url: realmLogo, + primary_color: realmColor, + custom_realm_asset: realmAsset, + custom_asset: clientAsset, + }); + + for (const body of [ + { logo_url: 'http://client.example.test/logo.svg' }, + { logo_url: 'data:image/svg+xml,%3Csvg/%3E' }, + { logo_url: 'https://client.example.test/logo.svg#fragment' }, + { primary_color: 'red' }, + ]) { + const invalid = await updateAdminClient(admin, 'acme', clientId, body); + assert.equal(invalid.status, 400); + assert.equal(invalid.json.error.code, 'invalid_request'); + } + + assert.deepEqual(JSON.parse(readClientBranding()), { + custom_asset: clientAsset, + }); + } finally { + const cleanup = await deleteAdminClient(admin, 'acme', clientId); + assert.ok(cleanup.status === 200 || cleanup.status === 404); + if (originalRealmBranding !== null) { + writeRealmBranding(originalRealmBranding); + } + } + }); + await t.test('admin clients rotate confidential client secrets', async () => { const admin = await adminToken('it@acme.test'); const clientId = 'admin-created-confidential';