commit 684a6c8a5df7937237b26d491be187a0c0726c97
parent 16de87d127a37fe3d0d62756686b2ecc4df61ebf
Author: finwo <finwo@pm.me>
Date: Sat, 7 Nov 2026 19:27:17 +0100
Implemented realm host management
Diffstat:
12 files changed, 1166 insertions(+), 35 deletions(-)
diff --git a/app/admin/src/assets/admin.css b/app/admin/src/assets/admin.css
@@ -24,15 +24,89 @@
line-height: 1.4;
}
-.realm-meta > span {
+.realm-meta > * {
display: inline;
margin-right: 0.75rem;
}
-.realm-meta > span:last-child {
+.realm-meta > *:last-child {
margin-right: 0;
}
+.realm-count-link {
+ color: var(--accent-text);
+ cursor: pointer;
+ text-decoration: none;
+}
+
+.realm-count-link:hover {
+ color: var(--accent-text-hover);
+}
+
+.action-button {
+ display: inline-flex;
+ align-items: center;
+ min-height: 2rem;
+ padding: 0.25rem 0.625rem;
+ border: 0;
+ border-radius: 0.25rem;
+ background: transparent;
+ color: var(--muted);
+ font: inherit;
+ font-size: 0.8125rem;
+ font-weight: 500;
+ line-height: 1.4;
+ white-space: nowrap;
+ cursor: pointer;
+}
+
+.action-button:hover {
+ background: var(--row-hover);
+ color: var(--text);
+}
+
+.action-button:first-child {
+ margin-left: -0.625rem;
+}
+
+.action-button.is-primary {
+ color: var(--accent-text);
+}
+
+.action-button.is-primary:hover {
+ background: color-mix(in srgb, var(--accent) 12%, transparent);
+ color: var(--accent-text-hover);
+}
+
+.action-button.is-danger {
+ color: var(--danger-text);
+}
+
+.action-button.is-danger:hover {
+ background: color-mix(in srgb, var(--danger) 12%, transparent);
+ color: var(--danger-text);
+}
+
+.host-name {
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ font-size: 0.8125rem;
+ overflow-wrap: anywhere;
+}
+
+.host-added {
+ color: var(--muted);
+ font-size: 0.8125rem;
+}
+
+.host-row-action {
+ display: flex;
+ align-items: center;
+}
+
+.host-table td.host-action-column:not(:empty) {
+ padding-bottom: 0.75rem;
+}
+
.realm-display {
color: inherit;
text-decoration: none;
@@ -71,11 +145,6 @@
align-items: center;
}
-.realm-row-action .button-danger {
- width: 100%;
- white-space: nowrap;
-}
-
.realm-table-panel .table-actions {
width: 100%;
flex-direction: column;
@@ -494,10 +563,6 @@
justify-content: flex-start;
}
- .realm-row-action .button-danger {
- width: auto;
- }
-
.realm-table-panel .table-actions {
width: auto;
flex-direction: row;
diff --git a/app/admin/src/main.ts b/app/admin/src/main.ts
@@ -49,6 +49,12 @@ const routes: m.RouteDefs = {
'/settings/:realm': {
render: () => m(Admin, {}),
},
+ '/hosts': {
+ render: () => m(Admin, {}),
+ },
+ '/hosts/:realm': {
+ render: () => m(Admin, {}),
+ },
'/system-settings': {
render: () => m(Admin, {}),
},
diff --git a/app/admin/src/screen/admin.tsx b/app/admin/src/screen/admin.tsx
@@ -25,6 +25,7 @@ import { SessionsPage } from './sessions';
import { ClientEditPage } from './client-edit';
import { ClientsPage } from './clients';
import { GlobalUserPage } from './global-user';
+import { HostsPage } from './hosts';
import { UserPage } from './user';
import { UsersPage } from './users';
import { SettingsPage } from './settings';
@@ -123,6 +124,19 @@ function settingsRealm() {
}
}
+function hostsRealm() {
+ const path = currentPath();
+ if (path !== '/hosts' && !path.startsWith('/hosts/')) return null;
+ const suffix = path.slice('/hosts/'.length);
+ if (!suffix) return null;
+ const slug = suffix.split('/')[0];
+ try {
+ return decodeURIComponent(slug);
+ } catch {
+ return null;
+ }
+}
+
export const Admin: m.Component = {
user: null as UserInfo | null,
systemAdmin: false,
@@ -318,6 +332,7 @@ export const Admin: m.Component = {
const users = path === '/users' || path.startsWith('/users/');
const systemSettings = path === '/system-settings';
const realmSettings = path === '/settings' || path.startsWith('/settings/');
+ const hosts = path === '/hosts' || path.startsWith('/hosts/');
const title = realmsPath
? 'Realms | Administration'
: clients
@@ -332,9 +347,11 @@ export const Admin: m.Component = {
: 'Users | Administration'
: systemSettings
? 'System settings | Administration'
- : realmSettings
- ? 'Realm settings | Administration'
- : 'Administration';
+ : hosts
+ ? 'Hosts | Administration'
+ : realmSettings
+ ? 'Realm settings | Administration'
+ : 'Administration';
document.title = title;
},
@@ -360,10 +377,12 @@ export const Admin: m.Component = {
const users = path === '/users' || path.startsWith('/users/');
const systemSettings = path === '/system-settings';
const realmSettings = path === '/settings' || path.startsWith('/settings/');
+ const hosts = path === '/hosts' || path.startsWith('/hosts/');
const realmSlug = sessionsRealm();
const clientRealmSlug = clientsRealm();
const userRealmSlug = usersRealm();
const settingsRealmSlug = settingsRealm();
+ const hostsRealmSlug = hostsRealm();
const clientEdit = clientEditPath();
const userDetail = userDetailPath();
const globalUser = globalUserDetailPath();
@@ -396,7 +415,7 @@ export const Admin: m.Component = {
href: appUrl(realmNav.href),
label: realmNav.label,
icon: LibraryBig,
- active: realmsPath || realmSettings,
+ active: realmsPath || realmSettings || hosts,
onclick: (event: Event) => {
event.preventDefault();
m.route.set(realmNav.href);
@@ -563,6 +582,14 @@ export const Admin: m.Component = {
/>
) : systemSettings ? (
<SystemSettingsPage onAuthExpired={() => this.authExpired()} />
+ ) : hosts ? (
+ <HostsPage
+ realmSlug={hostsRealmSlug}
+ realms={this.realms}
+ realmsError={this.realmsError}
+ canCreateRealm={Boolean(this.canCreateRealm)}
+ onAuthExpired={() => this.authExpired()}
+ />
) : realmSettings ? (
<SettingsPage
realmSlug={settingsRealmSlug}
diff --git a/app/admin/src/screen/hosts.tsx b/app/admin/src/screen/hosts.tsx
@@ -0,0 +1,516 @@
+import m from 'mithril';
+import { Modal } from '@component/modal';
+import { PageHeader } from '@component/page-header';
+import { Breadcrumb } from '../component/breadcrumb';
+import { RealmSelector } from '../component/realm-selector';
+import { realmNavigation } from '../util/navigation';
+import {
+ createAdminRealmHost,
+ deleteAdminRealmHost,
+ loadAdminRealmHosts,
+} from '../util/auth';
+import { type AdminRealm, type AdminRealmHost } from '../util/api';
+
+interface HostsAttrs {
+ realmSlug: string | null;
+ realms: AdminRealm[] | null;
+ realmsError: Error | null;
+ canCreateRealm: boolean;
+ onAuthExpired: () => void;
+}
+
+function formatDate(value: number | null | undefined) {
+ if (!value) return 'Unknown';
+ return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium' }).format(new Date(value));
+}
+
+function normalizeHostValue(raw: string) {
+ return raw.trim().toLowerCase();
+}
+
+function hostFormatError(raw: string): string | null {
+ const value = raw.trim();
+ const host = normalizeHostValue(value);
+
+ if (!host) return 'Hostname is required.';
+ if (/\s/.test(value)) return 'Hostname must not contain spaces.';
+ if (host.includes('://') || /^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
+ return 'Hostname must not include a scheme such as https://.';
+ }
+ if (host.includes('@')) return 'Hostname must not include @.';
+ if (host.includes('/')) return 'Hostname must not include a path.';
+ if (host.includes('*')) return 'Wildcard hostnames are not supported.';
+ if (host.startsWith('[')) {
+ if (!host.endsWith(']')) return 'Enter a valid IPv6 hostname.';
+ } else if (host.includes(':')) {
+ return 'Hostname must not include a port.';
+ }
+ if (host.length > 253) return 'Hostname must be 253 characters or fewer.';
+ if (host.startsWith('.') || host.endsWith('.')) {
+ return 'Hostname must not start or end with a dot.';
+ }
+
+ if (!host.startsWith('[')) {
+ const labels = host.split('.');
+ if (labels.length < 2) return 'Enter a complete hostname such as login.acme.test.';
+ for (const label of labels) {
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(label)) {
+ return 'Hostname labels must use lowercase letters, numbers and hyphens.';
+ }
+ if (label.length > 63) return 'Each hostname label must be 63 characters or fewer.';
+ }
+ }
+
+ return null;
+}
+
+function hostRequestError(e: any): boolean {
+ return e?.status === 401 || (e?.status === 400 && e?.code !== 'invalid_request');
+}
+
+export const HostsPage: m.Component<HostsAttrs> = {
+ attrs: null as HostsAttrs | null,
+ loadedRealm: null as string | null,
+ loading: false,
+ redirecting: false,
+ hosts: null as AdminRealmHost[] | null,
+ error: null as Error | null,
+ notice: null as string | null,
+ search: '',
+
+ addOpen: false,
+ addValue: '',
+ addError: null as Error | string | null,
+ addInvalid: false,
+ creating: false,
+
+ removeTarget: null as string | null,
+ removeConfirm: '',
+ removeError: null as Error | null,
+ removing: false,
+
+ oninit(this: any, vnode: m.Vnode<HostsAttrs>) {
+ this.attrs = vnode.attrs;
+ this.ensure();
+ },
+
+ onupdate(this: any, vnode: m.Vnode<HostsAttrs>) {
+ this.attrs = vnode.attrs;
+ this.ensure();
+ },
+
+ ensure(this: any) {
+ const { realms, realmSlug } = this.attrs;
+ if (!realms) return;
+
+ if (realms.length === 0) {
+ this.loadedRealm = null;
+ this.hosts = null;
+ this.loading = false;
+ this.error = null;
+ if (!this.redirecting) {
+ this.redirecting = true;
+ m.route.set('/realms', null, { replace: true });
+ }
+ return;
+ }
+
+ const selected = realmSlug && realms.some((realm) => realm.slug === realmSlug);
+ if (!selected) {
+ if (!this.redirecting) {
+ this.redirecting = true;
+ m.route.set(`/hosts/${encodeURIComponent(realms[0].slug)}`, null, { replace: true });
+ }
+ return;
+ }
+
+ this.redirecting = false;
+ if (this.loadedRealm !== realmSlug) {
+ this.load(realmSlug!);
+ }
+ },
+
+ async load(this: any, realmSlug: string) {
+ this.loadedRealm = realmSlug;
+ this.loading = true;
+ this.error = null;
+ this.notice = null;
+ this.hosts = null;
+ this.search = '';
+ m.redraw();
+
+ try {
+ const hosts = await loadAdminRealmHosts(realmSlug);
+ if (this.loadedRealm !== realmSlug) return;
+ this.hosts = hosts;
+ } 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();
+ }
+ },
+
+ resetAdd(this: any) {
+ this.addOpen = false;
+ this.addValue = '';
+ this.addError = null;
+ this.addInvalid = false;
+ this.creating = false;
+ },
+
+ openAdd(this: any) {
+ this.resetAdd();
+ this.addOpen = true;
+ m.redraw();
+ },
+
+ async submitAdd(this: any) {
+ const { realmSlug } = this.attrs;
+ if (!realmSlug) return;
+
+ const formatError = hostFormatError(this.addValue);
+ if (formatError) {
+ this.addError = formatError;
+ this.addInvalid = true;
+ m.redraw();
+ return;
+ }
+
+ const host = normalizeHostValue(this.addValue);
+ this.creating = true;
+ this.addError = null;
+ this.addInvalid = false;
+ m.redraw();
+
+ try {
+ const response = await createAdminRealmHost(realmSlug, host);
+ if (this.loadedRealm !== realmSlug) {
+ this.resetAdd();
+ return;
+ }
+ this.hosts = [response.host, ...(this.hosts || [])];
+ this.notice = `Host ${response.host.host} added.`;
+ this.resetAdd();
+ } catch (e: any) {
+ if (hostRequestError(e)) {
+ this.attrs.onAuthExpired();
+ return;
+ }
+ this.addError = (e as Error).message || 'Unable to add host.';
+ this.addInvalid = true;
+ } finally {
+ this.creating = false;
+ m.redraw();
+ }
+ },
+
+ resetRemove(this: any) {
+ this.removeTarget = null;
+ this.removeConfirm = '';
+ this.removeError = null;
+ this.removing = false;
+ },
+
+ openRemove(this: any, host: string) {
+ this.resetRemove();
+ this.removeTarget = host;
+ m.redraw();
+ },
+
+ async submitRemove(this: any) {
+ const { realmSlug } = this.attrs;
+ const target = this.removeTarget;
+ if (!realmSlug || !target || this.removing) return;
+ if (normalizeHostValue(this.removeConfirm) !== target) return;
+
+ this.removing = true;
+ this.removeError = null;
+ m.redraw();
+
+ try {
+ const result = await deleteAdminRealmHost(realmSlug, target);
+ if (this.loadedRealm === realmSlug) {
+ this.hosts = (this.hosts || []).filter((entry) => entry.host !== result.host);
+ this.notice = `Host ${result.host} removed.`;
+ }
+ this.resetRemove();
+ } catch (e: any) {
+ if (hostRequestError(e)) {
+ this.attrs.onAuthExpired();
+ return;
+ }
+ this.removeError = e as Error;
+ } finally {
+ this.removing = false;
+ m.redraw();
+ }
+ },
+
+ view(this: any) {
+ const { realms, realmsError, realmSlug, canCreateRealm } = this.attrs;
+ const selected =
+ realms?.find((realm) => realm.slug === realmSlug) || realms?.[0] || null;
+ const canManage = Boolean(selected?.can_edit);
+ const nav = realmNavigation(realms, Boolean(canCreateRealm));
+ const breadcrumbRealm = selected?.display_name || selected?.slug || realmSlug || '';
+ const settingsHref = `/settings/${encodeURIComponent(selected?.slug || realmSlug || '')}`;
+
+ const breadcrumbItems = [
+ {
+ label: nav.label,
+ ...(nav.isPlural ? { path: '/realms' } : {}),
+ },
+ { label: breadcrumbRealm, path: settingsHref },
+ { label: 'Hosts' },
+ ];
+
+ const hosts = this.hosts as AdminRealmHost[] | null;
+ const term = this.search.trim().toLowerCase();
+ const visible = hosts ? hosts.filter((entry) => !term || entry.host.includes(term)) : [];
+
+ return (
+ <div>
+ <Breadcrumb items={breadcrumbItems} />
+ <PageHeader row title="Hosts" subtitle="Hostnames that resolve to this realm.">
+ <RealmSelector
+ realms={realms}
+ selected={selected}
+ onchange={(slug: string) => {
+ m.route.set(`/hosts/${encodeURIComponent(slug)}`);
+ }}
+ />
+ </PageHeader>
+
+ {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 (realmSlug) {
+ this.load(realmSlug);
+ }
+ }}
+ >
+ Try again
+ </button>
+ </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>
+ ) : this.loading || this.redirecting || !hosts ? (
+ <div class="panel" aria-busy="true">
+ <div class="skeleton skeleton-title"></div>
+ <div class="skeleton"></div>
+ <div class="skeleton skeleton-short"></div>
+ </div>
+ ) : (
+ <section class="table-panel host-table-panel" aria-label="Realm hosts">
+ <div class="table-toolbar">
+ <div class="table-search">
+ <input
+ type="search"
+ value={this.search}
+ aria-label="Search hosts"
+ placeholder="Search hosts"
+ oninput={(event: Event) => {
+ this.search = (event.target as HTMLInputElement).value;
+ }}
+ />
+ </div>
+ {canManage ? (
+ <div class="table-actions">
+ <button class="button" type="button" onclick={() => this.openAdd()}>
+ Add host
+ </button>
+ </div>
+ ) : null}
+ </div>
+
+ <div class="data-table-wrap">
+ <table class="data-table data-table-static host-table">
+ <thead>
+ <tr>
+ <th class="data-table-primary host-name-column" scope="col">Hostname</th>
+ <th class="host-added-column" scope="col">Added</th>
+ {canManage ? <th class="host-action-column" scope="col">Actions</th> : null}
+ </tr>
+ </thead>
+ <tbody>
+ {visible.map((entry: AdminRealmHost) => (
+ <tr>
+ <td class="data-table-primary host-name-column" data-label="Hostname">
+ <span class="host-name">{entry.host}</span>
+ </td>
+ <td class="host-added-column" data-label="Added">
+ <span class="host-added">{formatDate(entry.created_at)}</span>
+ </td>
+ {canManage ? (
+ <td class="host-action-column" data-label="Actions">
+ <div class="host-row-action">
+ <button
+ class="action-button is-danger"
+ type="button"
+ onclick={() => this.openRemove(entry.host)}
+ >
+ Remove
+ </button>
+ </div>
+ </td>
+ ) : null}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {hosts.length > 0 && visible.length === 0 ? (
+ <div class="empty">
+ <p>No hosts match this search.</p>
+ </div>
+ ) : hosts.length === 0 ? (
+ <div class="empty">
+ <p>No hosts are assigned to this realm.</p>
+ </div>
+ ) : null}
+ </div>
+ </section>
+ )}
+
+ {this.addOpen ? (
+ <Modal title="Add host" onClose={() => this.resetAdd()}>
+ <form
+ onsubmit={(event: Event) => {
+ event.preventDefault();
+ this.submitAdd();
+ }}
+ >
+ {this.addError ? (
+ <div class="alert" role="alert">
+ {typeof this.addError === 'string' ? this.addError : this.addError.message}
+ </div>
+ ) : null}
+
+ <div class="form-field">
+ <span class="field-label">Hostname</span>
+ <input
+ class="field-control"
+ type="text"
+ value={this.addValue}
+ maxlength="253"
+ placeholder="login.acme.test"
+ autocomplete="off"
+ spellcheck="false"
+ data-modal-autofocus
+ disabled={this.creating}
+ aria-invalid={this.addInvalid ? 'true' : null}
+ oninput={(event: Event) => {
+ this.addValue = (event.target as HTMLInputElement).value;
+ this.addError = null;
+ this.addInvalid = false;
+ }}
+ />
+ </div>
+ <p class="modal-note">
+ Lowercase hostname. Do not include a scheme, port, path or wildcard.
+ </p>
+
+ <div class="modal-actions">
+ <button
+ class="button-secondary"
+ type="button"
+ disabled={this.creating}
+ onclick={() => this.resetAdd()}
+ >
+ Cancel
+ </button>
+ <button class="button" type="submit" disabled={this.creating}>
+ {this.creating ? 'Adding' : 'Add host'}
+ </button>
+ </div>
+ </form>
+ </Modal>
+ ) : null}
+
+ {this.removeTarget ? (
+ <Modal title="Remove host" onClose={() => this.resetRemove()}>
+ <p class="modal-note">
+ Remove {this.removeTarget}? This hostname will stop resolving to{' '}
+ {breadcrumbRealm}. Sessions for this realm on that host will end. Realm settings,
+ clients and users are unaffected.
+ </p>
+ {this.removeError ? (
+ <div class="alert" role="alert">
+ {this.removeError.message}
+ </div>
+ ) : null}
+
+ <div class="form-field">
+ <span class="field-label">Confirm hostname</span>
+ <input
+ class="field-control"
+ type="text"
+ value={this.removeConfirm}
+ maxlength="253"
+ placeholder={this.removeTarget}
+ autocomplete="off"
+ spellcheck="false"
+ data-modal-autofocus
+ disabled={this.removing}
+ oninput={(event: Event) => {
+ this.removeConfirm = (event.target as HTMLInputElement).value;
+ this.removeError = null;
+ }}
+ />
+ </div>
+ <p class="modal-note">Type the hostname exactly to confirm.</p>
+
+ <div class="modal-actions">
+ <button
+ class="button-secondary"
+ type="button"
+ disabled={this.removing}
+ onclick={() => this.resetRemove()}
+ >
+ Cancel
+ </button>
+ <button
+ class="button-danger"
+ type="button"
+ disabled={
+ this.removing ||
+ normalizeHostValue(this.removeConfirm) !== this.removeTarget
+ }
+ onclick={() => this.submitRemove()}
+ >
+ {this.removing ? 'Removing' : 'Remove host'}
+ </button>
+ </div>
+ </Modal>
+ ) : null}
+ </div>
+ );
+ },
+};
diff --git a/app/admin/src/screen/realms.tsx b/app/admin/src/screen/realms.tsx
@@ -268,6 +268,7 @@ export const RealmsPage: m.Component<RealmsAttrs> = {
);
const settingsPath = (realm: AdminRealm) =>
`/settings/${encodeURIComponent(realm.slug)}`;
+ const hostsPath = (realm: AdminRealm) => `/hosts/${encodeURIComponent(realm.slug)}`;
const previewLogo = logoUrlError(this.createValue.logo_url)
? ''
: this.createValue.logo_url.trim();
@@ -377,31 +378,48 @@ export const RealmsPage: m.Component<RealmsAttrs> = {
</a>
<span class="realm-meta">
<span class="realm-slug">{realm.slug}</span>
- {realmCounts(realm).map((count) => (
- <span class="realm-count">{count}</span>
- ))}
+ <span class="realm-count">{pluralCount(realm.member_count, 'member')}</span>
+ {realm.can_edit ? (
+ <a
+ class="realm-count realm-count-link"
+ href={appUrl(hostsPath(realm))}
+ onclick={(event: MouseEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ m.route.set(hostsPath(realm));
+ }}
+ >
+ {pluralCount(realm.host_count, 'host')}
+ </a>
+ ) : (
+ <span class="realm-count">{pluralCount(realm.host_count, 'host')}</span>
+ )}
+ <span class="realm-count">
+ {pluralCount(realm.email_domain_count, 'domain')}
+ </span>
+ <span class="realm-count">{pluralCount(realm.client_count, 'client')}</span>
</span>
</td>
<td class="realm-owner-column" data-label="Owner">
<span class="realm-owner-name">{ownerName(realm)}</span>
<span class="realm-owner-meta">{ownerMeta(realm)}</span>
</td>
- <td class="realm-action-column">
- {realm.can_delete ? (
- <div class="realm-row-action">
- <button
- class="button-danger"
- type="button"
- onclick={(event: MouseEvent) => {
- event.stopPropagation();
- this.openDelete(realm);
- }}
- >
- Delete realm
- </button>
- </div>
- ) : null}
- </td>
+ <td class="realm-action-column">
+ {realm.can_delete ? (
+ <div class="realm-row-action">
+ <button
+ class="action-button is-danger"
+ type="button"
+ onclick={(event: MouseEvent) => {
+ event.stopPropagation();
+ this.openDelete(realm);
+ }}
+ >
+ Delete realm
+ </button>
+ </div>
+ ) : null}
+ </td>
</tr>
);
})}
diff --git a/app/admin/src/screen/settings.tsx b/app/admin/src/screen/settings.tsx
@@ -11,7 +11,7 @@ import { Breadcrumb } from '../component/breadcrumb';
import { RealmSelector } from '../component/realm-selector';
import { realmBreadcrumbItems } from '../util/navigation';
import { loadAdminRealmSettings, updateAdminRealmSettings } from '../util/auth';
-import type { AdminRealm, AdminRealmSettings } from '../util/api';
+import { appUrl, type AdminRealm, type AdminRealmSettings } from '../util/api';
interface SettingsAttrs {
realmSlug: string | null;
@@ -404,6 +404,23 @@ export const SettingsPage: m.Component<SettingsAttrs> = {
</div>
</div>
</section>
+
+ <section class="panel">
+ <h2>Realm access</h2>
+ <p class="note">Manage hostnames that resolve to this realm.</p>
+ <div class="settings-actions">
+ <a
+ class="button-secondary"
+ href={appUrl(`/hosts/${encodeURIComponent(realmSlug || '')}`)}
+ onclick={(event: MouseEvent) => {
+ event.preventDefault();
+ m.route.set(`/hosts/${encodeURIComponent(realmSlug || '')}`);
+ }}
+ >
+ Hosts
+ </a>
+ </div>
+ </section>
</div>
) : null}
</div>
diff --git a/app/admin/src/util/api.ts b/app/admin/src/util/api.ts
@@ -43,6 +43,26 @@ export interface AdminRealmDeleteResponse {
removed: boolean;
}
+export interface AdminRealmHost {
+ host: string;
+ created_at: number;
+}
+
+export interface AdminRealmHostListResponse {
+ hosts: AdminRealmHost[];
+}
+
+export interface AdminRealmHostCreateResponse {
+ ok: boolean;
+ host: AdminRealmHost;
+}
+
+export interface AdminRealmHostDeleteResponse {
+ ok: boolean;
+ removed: boolean;
+ host: string;
+}
+
export interface AdminRealmSettings {
slug: string;
display_name: string;
diff --git a/app/admin/src/util/auth.ts b/app/admin/src/util/auth.ts
@@ -16,6 +16,10 @@ import {
type AdminRealmCreateInput,
type AdminRealmCreateResponse,
type AdminRealmDeleteResponse,
+ type AdminRealmHost,
+ type AdminRealmHostCreateResponse,
+ type AdminRealmHostDeleteResponse,
+ type AdminRealmHostListResponse,
type AdminRealmSettings,
type AdminRealmSettingsInput,
type AdminRealmUser,
@@ -88,6 +92,37 @@ export async function deleteAdminRealm(realmSlug: string): Promise<AdminRealmDel
});
}
+export async function loadAdminRealmHosts(realmSlug: string): Promise<AdminRealmHost[]> {
+ const realm = encodeURIComponent(realmSlug);
+ const response = await adminJson<AdminRealmHostListResponse>(
+ `/api/v1/admin/realms/${realm}/hosts`
+ );
+ return response.hosts;
+}
+
+export async function createAdminRealmHost(
+ realmSlug: string,
+ host: string
+): Promise<AdminRealmHostCreateResponse> {
+ const realm = encodeURIComponent(realmSlug);
+ return adminJson<AdminRealmHostCreateResponse>(`/api/v1/admin/realms/${realm}/hosts`, {
+ method: 'POST',
+ body: JSON.stringify({ host }),
+ });
+}
+
+export async function deleteAdminRealmHost(
+ realmSlug: string,
+ host: string
+): Promise<AdminRealmHostDeleteResponse> {
+ const realm = encodeURIComponent(realmSlug);
+ const encoded = encodeURIComponent(host);
+ return adminJson<AdminRealmHostDeleteResponse>(
+ `/api/v1/admin/realms/${realm}/hosts/${encoded}`,
+ { method: 'DELETE' }
+ );
+}
+
export async function loadAdminSessions(realmSlug: string): Promise<AdminSession[]> {
const realm = encodeURIComponent(realmSlug);
const response = await adminJson<{ sessions: AdminSession[] }>(
diff --git a/server/src/controller/admin/realm-hosts.js b/server/src/controller/admin/realm-hosts.js
@@ -0,0 +1,80 @@
+import { app } from '../../app.js';
+import { authenticateAdminRequest } from '../../lib/admin-auth.js';
+import {
+ addAdminRealmHost,
+ deleteAdminRealmHost,
+ listAdminRealmHosts,
+ normalizeReservedHosts,
+} from '../../lib/admin-realm-hosts.js';
+import { HttpError } from '../../lib/http/http-error.js';
+import { isSystemAdmin } from '../../lib/policy.js';
+
+const reservedHosts = normalizeReservedHosts(app.config);
+
+function assertBody(body) {
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
+ throw new HttpError(400, 'invalid_request', 'Request body must be a JSON object');
+ }
+ for (const field of Object.keys(body)) {
+ if (field !== 'host') {
+ throw new HttpError(400, 'invalid_request', `Unknown field: ${field}`);
+ }
+ }
+}
+
+export default [
+ {
+ method: 'get',
+ path: '/api/v1/admin/realms/:realm/hosts',
+ name: 'admin.realm-hosts.list',
+ async handler(req) {
+ const auth = await authenticateAdminRequest(req, {
+ realmSlug: req.params.realm,
+ });
+ const hosts = await listAdminRealmHosts({
+ systemDb: auth.systemDb,
+ realm: auth.realm,
+ });
+
+ return new app.HttpOk({ hosts }, { 'cache-control': 'no-store' });
+ },
+ },
+ {
+ method: 'post',
+ path: '/api/v1/admin/realms/:realm/hosts',
+ name: 'admin.realm-hosts.create',
+ async handler(req) {
+ const auth = await authenticateAdminRequest(req, {
+ realmSlug: req.params.realm,
+ });
+ const body = req.body || {};
+ assertBody(body);
+ const host = await addAdminRealmHost({
+ systemDb: auth.systemDb,
+ realm: auth.realm,
+ host: body.host,
+ isSystemAdmin: isSystemAdmin(auth.user),
+ reservedHosts,
+ });
+
+ return new app.HttpOk({ ok: true, host }, { 'cache-control': 'no-store' });
+ },
+ },
+ {
+ method: 'delete',
+ path: '/api/v1/admin/realms/:realm/hosts/:host',
+ name: 'admin.realm-hosts.delete',
+ async handler(req) {
+ const auth = await authenticateAdminRequest(req, {
+ realmSlug: req.params.realm,
+ });
+ const result = await deleteAdminRealmHost({
+ systemDb: auth.systemDb,
+ realm: auth.realm,
+ host: req.params.host,
+ });
+
+ return new app.HttpOk({ ok: true, ...result }, { 'cache-control': 'no-store' });
+ },
+ },
+];
diff --git a/server/src/lib/admin-realm-hosts.js b/server/src/lib/admin-realm-hosts.js
@@ -0,0 +1,100 @@
+import { HttpError } from './http/http-error.js';
+import {
+ addRealmHost,
+ findOidcClientHost,
+ findRealmHost,
+ listRealmHosts,
+ normalizeHost,
+ removeRealmHost,
+ validateRealmHostname,
+} from './realm.js';
+
+function invalidRequest(message) {
+ return new HttpError(400, 'invalid_request', message);
+}
+
+export function normalizeReservedHosts(cfg) {
+ const sources = [cfg?.server?.public_url, cfg?.apps?.admin, cfg?.apps?.account];
+ const reserved = new Set();
+ for (const value of sources) {
+ if (!value) continue;
+ let hostname;
+ try {
+ hostname = new URL(value).hostname;
+ } catch {
+ continue;
+ }
+ const normalized = normalizeHost(hostname);
+ if (normalized) reserved.add(normalized);
+ }
+ return reserved;
+}
+
+export async function listAdminRealmHosts({ systemDb, realm }) {
+ const rows = await listRealmHosts(systemDb, realm.id);
+ return rows.map((row) => ({ host: row.host, created_at: row.created_at }));
+}
+
+export async function addAdminRealmHost({
+ systemDb,
+ realm,
+ host,
+ isSystemAdmin = false,
+ reservedHosts,
+}) {
+ const normalized = validateRealmHostname(host);
+
+ if (reservedHosts && reservedHosts.has(normalized)) {
+ throw new HttpError(
+ 409,
+ 'host_reserved',
+ 'This hostname is reserved for the authentication service.'
+ );
+ }
+
+ const clientHost = await findOidcClientHost(normalized);
+ if (clientHost) {
+ throw new HttpError(
+ 409,
+ 'host_in_use',
+ isSystemAdmin
+ ? 'This hostname is already assigned to a client application.'
+ : 'This hostname is already assigned.'
+ );
+ }
+
+ const existing = await findRealmHost(normalized);
+ if (existing) {
+ if (existing.id === realm.id) {
+ throw new HttpError(409, 'host_in_use', 'This hostname is already assigned to this realm.');
+ }
+ throw new HttpError(
+ 409,
+ 'host_in_use',
+ isSystemAdmin
+ ? `This hostname is already assigned to ${existing.slug}.`
+ : 'This hostname is already assigned to another realm.'
+ );
+ }
+
+ const createdAt = Date.now();
+ try {
+ await addRealmHost(realm.id, normalized);
+ } catch {
+ throw new HttpError(409, 'host_in_use', 'This hostname is already assigned.');
+ }
+
+ return { host: normalized, created_at: createdAt };
+}
+
+export async function deleteAdminRealmHost({ systemDb, realm, host }) {
+ const normalized = normalizeHost(host);
+ if (!normalized) throw invalidRequest('host is required');
+
+ const removed = await removeRealmHost(systemDb, realm.id, normalized);
+ if (!removed) {
+ throw new HttpError(404, 'host_not_found', 'Host is not assigned to this realm.');
+ }
+
+ return { removed: true, host: normalized };
+}
diff --git a/server/src/lib/realm.js b/server/src/lib/realm.js
@@ -105,6 +105,53 @@ export function normalizeHost(host) {
return value.replace(/\.$/, '');
}
+export function validateRealmHostname(raw) {
+ const invalid = (message) => new HttpError(400, 'invalid_request', message);
+
+ if (typeof raw !== 'string') throw invalid('host must be a string');
+ const value = raw.trim();
+ if (!value) throw invalid('host is required');
+ if (/\s/.test(value)) throw invalid('host must not contain spaces');
+ if (value.includes('://') || /^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
+ throw invalid('host must not include a scheme such as https://');
+ }
+ if (value.includes('@')) throw invalid('host must not include @');
+ if (value.includes('/')) throw invalid('host must not include a path');
+ if (value.includes('*')) throw invalid('wildcard hostnames are not supported');
+
+ const lower = value.toLowerCase();
+ if (lower.startsWith('[')) {
+ const bracketEnd = lower.indexOf(']');
+ if (bracketEnd === -1 || bracketEnd !== lower.length - 1) {
+ throw invalid('enter a valid IPv6 host without a port');
+ }
+ } else if (lower.includes(':')) {
+ throw invalid('host must not include a port');
+ }
+
+ if (lower.length > 253) throw invalid('host must be 253 characters or fewer');
+ if (lower.startsWith('.') || lower.endsWith('.')) {
+ throw invalid('host must not start or end with a dot');
+ }
+
+ const normalized = normalizeHost(value);
+ if (!normalized) throw invalid('host is required');
+ if (normalized !== lower) throw invalid('host must not include a port or trailing dot');
+
+ if (!normalized.startsWith('[')) {
+ const labels = normalized.split('.');
+ if (labels.length < 2) throw invalid('enter a complete hostname such as login.acme.test');
+ for (const label of labels) {
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(label)) {
+ throw invalid('host labels must use lowercase letters, numbers and hyphens');
+ }
+ if (label.length > 63) throw invalid('each host label must be 63 characters or fewer');
+ }
+ }
+
+ return normalized;
+}
+
export function normalizeEmailDomain(domain) {
const value = String(domain || '').trim().toLowerCase().replace(/\.$/, '');
if (!value || value.includes('@')) {
@@ -316,6 +363,27 @@ export async function addRealmHost(realmId, host) {
);
}
+export async function listRealmHosts(systemDb, realmId) {
+ if (!systemDb) throw new Error('realm registry is not initialized');
+ return systemDb.all(
+ `SELECT host, created_at FROM realm_hosts
+ WHERE realm_id = {realmId}
+ ORDER BY created_at DESC, host ASC`,
+ { realmId }
+ );
+}
+
+export async function removeRealmHost(systemDb, realmId, host) {
+ if (!systemDb) throw new Error('realm registry is not initialized');
+ const normalized = normalizeHost(host);
+ if (!normalized) return false;
+ const result = await systemDb.run(
+ 'DELETE FROM realm_hosts WHERE host = {host} AND realm_id = {realmId}',
+ { host: normalized, realmId }
+ );
+ return result.changes > 0;
+}
+
export async function addClientRealm(clientId, realmId) {
if (!systemDb) throw new Error('realm registry is not initialized');
const value = String(clientId || '').trim();
diff --git a/server/test/http.test.js b/server/test/http.test.js
@@ -4651,6 +4651,185 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
}
});
+ await t.test('admin realm host management', async () => {
+ const systemAdmin = await adminToken();
+ const acmeAdmin = await adminToken('it@acme.test');
+ const globexAdmin = await adminToken('contractor@personal.test');
+ const added = [];
+
+ const cleanupHost = async (realm, host) => {
+ await adminRequest(systemAdmin, {
+ method: 'DELETE',
+ path: `/api/v1/admin/realms/${realm}/hosts/${encodeURIComponent(host)}`,
+ });
+ };
+
+ try {
+ const list = await adminRequest(systemAdmin, {
+ path: '/api/v1/admin/realms/acme/hosts',
+ });
+ assert.equal(list.status, 200);
+ assert.ok(Array.isArray(list.json.hosts));
+ const seeded = list.json.hosts.find((entry) => entry.host === 'acme.localhost');
+ assert.ok(seeded, 'seeded acme.localhost present');
+ assert.equal(typeof seeded.created_at, 'number');
+
+ const crossRealmList = await adminRequest(acmeAdmin, {
+ path: '/api/v1/admin/realms/globex/hosts',
+ });
+ assert.equal(crossRealmList.status, 403);
+ assert.equal(crossRealmList.json.error.code, 'forbidden');
+
+ const foreignList = await adminRequest(globexAdmin, {
+ path: '/api/v1/admin/realms/acme/hosts',
+ });
+ assert.equal(foreignList.status, 403);
+
+ const unknownRealm = await adminRequest(systemAdmin, {
+ path: '/api/v1/admin/realms/does-not-exist/hosts',
+ });
+ assert.equal(unknownRealm.status, 404);
+
+ const created = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/hosts',
+ body: { host: ' Login.Acme.test ' },
+ });
+ assert.equal(created.status, 200);
+ assert.equal(created.json.ok, true);
+ assert.equal(created.json.host.host, 'login.acme.test');
+ assert.equal(typeof created.json.host.created_at, 'number');
+ added.push('login.acme.test');
+
+ const listed = await adminRequest(acmeAdmin, {
+ path: '/api/v1/admin/realms/acme/hosts',
+ });
+ assert.ok(listed.json.hosts.some((entry) => entry.host === 'login.acme.test'));
+
+ for (const host of [
+ 'HTTPS://login.acme.test',
+ 'login.acme.test:8443',
+ 'login.acme.test/path',
+ '*.acme.test',
+ 'user@login.acme.test',
+ 'two words.test',
+ 'nodot',
+ 'trailing.dot.test.',
+ 'UPPER.acme.test!',
+ ]) {
+ const invalid = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/hosts',
+ body: { host },
+ });
+ assert.equal(invalid.status, 400, `expected 400 for ${host}`);
+ assert.equal(invalid.json.error.code, 'invalid_request');
+ }
+
+ const emptyBody = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/hosts',
+ body: {},
+ });
+ assert.equal(emptyBody.status, 400);
+ assert.equal(emptyBody.json.error.code, 'invalid_request');
+
+ const unknownField = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/hosts',
+ body: { hostname: 'ok.acme.test' },
+ });
+ assert.equal(unknownField.status, 400);
+ assert.equal(unknownField.json.error.code, 'invalid_request');
+
+ const sameRealm = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/hosts',
+ body: { host: 'acme.localhost' },
+ });
+ assert.equal(sameRealm.status, 409);
+ assert.equal(sameRealm.json.error.code, 'host_in_use');
+ assert.match(sameRealm.json.error.message, /this realm/i);
+
+ const otherSystem = await adminRequest(systemAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/hosts',
+ body: { host: 'globex.localhost' },
+ });
+ assert.equal(otherSystem.status, 409);
+ assert.equal(otherSystem.json.error.code, 'host_in_use');
+ assert.match(otherSystem.json.error.message, /globex/);
+
+ const otherAcme = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/hosts',
+ body: { host: 'globex.localhost' },
+ });
+ assert.equal(otherAcme.status, 409);
+ assert.equal(otherAcme.json.error.code, 'host_in_use');
+ assert.ok(!otherAcme.json.error.message.includes('globex'));
+
+ const reserved = await adminRequest(systemAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/hosts',
+ body: { host: 'identity.test' },
+ });
+ assert.equal(reserved.status, 409);
+ assert.equal(reserved.json.error.code, 'host_reserved');
+
+ withSystemDatabase(env, (database) => {
+ database
+ .prepare('INSERT INTO oidc_client_hosts (host, client_id, created_at) VALUES (?, ?, ?)')
+ .run('app.acme.test', 'internal-app', Date.now());
+ });
+ const clientCollision = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/hosts',
+ body: { host: 'app.acme.test' },
+ });
+ assert.equal(clientCollision.status, 409);
+ assert.equal(clientCollision.json.error.code, 'host_in_use');
+ withSystemDatabase(env, (database) => {
+ database.prepare('DELETE FROM oidc_client_hosts WHERE host = ?').run('app.acme.test');
+ });
+
+ const removeWrongRealm = await adminRequest(systemAdmin, {
+ method: 'DELETE',
+ path: '/api/v1/admin/realms/acme/hosts/globex.localhost',
+ });
+ assert.equal(removeWrongRealm.status, 404);
+ assert.equal(removeWrongRealm.json.error.code, 'host_not_found');
+
+ const forbiddenRemove = await adminRequest(acmeAdmin, {
+ method: 'DELETE',
+ path: '/api/v1/admin/realms/globex/hosts/globex.localhost',
+ });
+ assert.equal(forbiddenRemove.status, 403);
+
+ const removed = await adminRequest(acmeAdmin, {
+ method: 'DELETE',
+ path: '/api/v1/admin/realms/acme/hosts/login.acme.test',
+ });
+ assert.equal(removed.status, 200);
+ assert.equal(removed.json.ok, true);
+ assert.equal(removed.json.removed, true);
+ assert.equal(removed.json.host, 'login.acme.test');
+ const index = added.indexOf('login.acme.test');
+ if (index >= 0) added.splice(index, 1);
+
+ const again = await adminRequest(acmeAdmin, {
+ method: 'DELETE',
+ path: '/api/v1/admin/realms/acme/hosts/login.acme.test',
+ });
+ assert.equal(again.status, 404);
+ assert.equal(again.json.error.code, 'host_not_found');
+ } finally {
+ for (const host of added) {
+ await cleanupHost('acme', host);
+ }
+ }
+ });
+
await t.test('system branding updates Admin settings and discovery precedence', async () => {
const systemAdmin = await adminToken();
const acmeAdmin = await adminToken('it@acme.test');