commit 5288fc27724989aeea82555e6d61cdfd61482b91
parent 87225e59c48ca643f0dca4ab58fca62c4834ef18
Author: finwo <finwo@pm.me>
Date: Sat, 7 Nov 2026 22:21:23 +0100
Implemented realm email domain management
Diffstat:
14 files changed, 1543 insertions(+), 8 deletions(-)
diff --git a/app/admin/src/assets/admin.css b/app/admin/src/assets/admin.css
@@ -107,6 +107,78 @@
padding-bottom: 0.75rem;
}
+.domain-name {
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ font-size: 0.8125rem;
+ overflow-wrap: anywhere;
+}
+
+.domain-status {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ color: var(--muted);
+ font-size: 0.8125rem;
+}
+
+.domain-status-dot {
+ width: 0.4375rem;
+ height: 0.4375rem;
+ flex: none;
+ border-radius: 50%;
+ background: var(--muted);
+}
+
+.domain-status.is-pending {
+ color: var(--warn);
+}
+
+.domain-status.is-pending .domain-status-dot {
+ background: var(--warn);
+}
+
+.domain-row-action {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 0.125rem;
+}
+
+.verify-record-name,
+.verify-record-value {
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ font-size: 0.8125rem;
+}
+
+.verify-copy-row {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 0.5rem;
+}
+
+@media (min-width: 40em) {
+ .domain-table {
+ table-layout: fixed;
+ }
+
+ .domain-table .domain-status-column {
+ width: 12rem;
+ }
+
+ .domain-table .domain-action-column {
+ width: 14rem;
+ }
+
+ .domain-table td.domain-action-column:not(:empty) {
+ padding-bottom: 0.75rem;
+ }
+
+ .domain-row-action {
+ flex-wrap: nowrap;
+ justify-content: flex-start;
+ }
+}
+
.realm-display {
color: inherit;
text-decoration: none;
diff --git a/app/admin/src/main.ts b/app/admin/src/main.ts
@@ -55,6 +55,12 @@ const routes: m.RouteDefs = {
'/hosts/:realm': {
render: () => m(Admin, {}),
},
+ '/email-domains': {
+ render: () => m(Admin, {}),
+ },
+ '/email-domains/: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
@@ -26,6 +26,7 @@ import { ClientEditPage } from './client-edit';
import { ClientsPage } from './clients';
import { GlobalUserPage } from './global-user';
import { HostsPage } from './hosts';
+import { EmailDomainsPage } from './email-domains';
import { UserPage } from './user';
import { UsersPage } from './users';
import { SettingsPage } from './settings';
@@ -137,6 +138,19 @@ function hostsRealm() {
}
}
+function emailDomainsRealm() {
+ const path = currentPath();
+ if (path !== '/email-domains' && !path.startsWith('/email-domains/')) return null;
+ const suffix = path.slice('/email-domains/'.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,
@@ -333,6 +347,7 @@ export const Admin: m.Component = {
const systemSettings = path === '/system-settings';
const realmSettings = path === '/settings' || path.startsWith('/settings/');
const hosts = path === '/hosts' || path.startsWith('/hosts/');
+ const emailDomains = path === '/email-domains' || path.startsWith('/email-domains/');
const title = realmsPath
? 'Realms | Administration'
: clients
@@ -349,9 +364,11 @@ export const Admin: m.Component = {
? 'System settings | Administration'
: hosts
? 'Hosts | Administration'
- : realmSettings
- ? 'Realm settings | Administration'
- : 'Administration';
+ : emailDomains
+ ? 'Email domains | Administration'
+ : realmSettings
+ ? 'Realm settings | Administration'
+ : 'Administration';
document.title = title;
},
@@ -378,11 +395,13 @@ export const Admin: m.Component = {
const systemSettings = path === '/system-settings';
const realmSettings = path === '/settings' || path.startsWith('/settings/');
const hosts = path === '/hosts' || path.startsWith('/hosts/');
+ const emailDomains = path === '/email-domains' || path.startsWith('/email-domains/');
const realmSlug = sessionsRealm();
const clientRealmSlug = clientsRealm();
const userRealmSlug = usersRealm();
const settingsRealmSlug = settingsRealm();
const hostsRealmSlug = hostsRealm();
+ const emailDomainsRealmSlug = emailDomainsRealm();
const clientEdit = clientEditPath();
const userDetail = userDetailPath();
const globalUser = globalUserDetailPath();
@@ -415,7 +434,7 @@ export const Admin: m.Component = {
href: appUrl(realmNav.href),
label: realmNav.label,
icon: LibraryBig,
- active: realmsPath || realmSettings || hosts,
+ active: realmsPath || realmSettings || hosts || emailDomains,
onclick: (event: Event) => {
event.preventDefault();
m.route.set(realmNav.href);
@@ -590,6 +609,14 @@ export const Admin: m.Component = {
canCreateRealm={Boolean(this.canCreateRealm)}
onAuthExpired={() => this.authExpired()}
/>
+ ) : emailDomains ? (
+ <EmailDomainsPage
+ realmSlug={emailDomainsRealmSlug}
+ realms={this.realms}
+ realmsError={this.realmsError}
+ canCreateRealm={Boolean(this.canCreateRealm)}
+ onAuthExpired={() => this.authExpired()}
+ />
) : realmSettings ? (
<SettingsPage
realmSlug={settingsRealmSlug}
diff --git a/app/admin/src/screen/email-domains.tsx b/app/admin/src/screen/email-domains.tsx
@@ -0,0 +1,698 @@
+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 {
+ createAdminRealmEmailDomain,
+ deleteAdminRealmEmailDomain,
+ loadAdminRealmEmailDomains,
+ verifyAdminRealmEmailDomain,
+} from '../util/auth';
+import { type AdminRealm, type AdminRealmEmailDomain } from '../util/api';
+
+interface EmailDomainsAttrs {
+ realmSlug: string | null;
+ realms: AdminRealm[] | null;
+ realmsError: Error | null;
+ canCreateRealm: boolean;
+ onAuthExpired: () => void;
+}
+
+function normalizeDomainValue(raw: string) {
+ return raw.trim().toLowerCase().replace(/\.$/, '');
+}
+
+function domainFormatError(raw: string): string | null {
+ const value = raw.trim();
+ const domain = normalizeDomainValue(value);
+
+ if (!domain) return 'Email domain is required.';
+ if (/\s/.test(value)) return 'Email domain must not contain spaces.';
+ if (domain.includes('@')) return 'Enter the domain without the @ symbol.';
+ if (domain.includes('://') || /^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
+ return 'Email domain must not include a scheme such as https://.';
+ }
+ if (domain.includes('/')) return 'Email domain must not include a path.';
+ if (domain.includes('*')) return 'Wildcard domains are not supported.';
+ if (domain.includes(':')) return 'Email domain must not include a port.';
+ if (value.endsWith('.')) return 'Email domain must not end with a dot.';
+ if (domain.startsWith('.')) return 'Email domain must not start with a dot.';
+ if (domain.length > 253) return 'Email domain must be 253 characters or fewer.';
+
+ const labels = domain.split('.');
+ if (labels.length < 2) return 'Enter a complete domain such as acme.test.';
+ for (const label of labels) {
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(label)) {
+ return 'Domain labels may use lowercase letters, numbers and hyphens.';
+ }
+ if (label.length > 63) return 'Each domain label must be 63 characters or fewer.';
+ }
+
+ return null;
+}
+
+function domainRequestError(e: any): boolean {
+ return e?.status === 401 || (e?.status === 400 && e?.code !== 'invalid_request');
+}
+
+function statusLabel(status: string) {
+ return status === 'verified' ? 'Verified' : 'Pending verification';
+}
+
+export const EmailDomainsPage: m.Component<EmailDomainsAttrs> = {
+ attrs: null as EmailDomainsAttrs | null,
+ loadedRealm: null as string | null,
+ loading: false,
+ redirecting: false,
+ domains: null as AdminRealmEmailDomain[] | 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,
+
+ verifyTarget: null as { domain: string; token: string } | null,
+ verifyError: null as Error | null,
+ verifying: false,
+ copied: false,
+ copyTimer: 0 as number | ReturnType<typeof setTimeout>,
+
+ removeTarget: null as string | null,
+ removeConfirm: '',
+ removeError: null as Error | null,
+ removing: false,
+
+ oninit(this: any, vnode: m.Vnode<EmailDomainsAttrs>) {
+ this.attrs = vnode.attrs;
+ this.ensure();
+ },
+
+ onupdate(this: any, vnode: m.Vnode<EmailDomainsAttrs>) {
+ 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.domains = 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(`/email-domains/${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.domains = null;
+ this.search = '';
+ m.redraw();
+
+ try {
+ const domains = await loadAdminRealmEmailDomains(realmSlug);
+ if (this.loadedRealm !== realmSlug) return;
+ this.domains = domains;
+ } 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 = domainFormatError(this.addValue);
+ if (formatError) {
+ this.addError = formatError;
+ this.addInvalid = true;
+ m.redraw();
+ return;
+ }
+
+ const domain = normalizeDomainValue(this.addValue);
+ this.creating = true;
+ this.addError = null;
+ this.addInvalid = false;
+ m.redraw();
+
+ try {
+ const response = await createAdminRealmEmailDomain(realmSlug, domain);
+ if (this.loadedRealm !== realmSlug) {
+ this.resetAdd();
+ return;
+ }
+ this.domains = [response.email_domain, ...(this.domains || [])];
+ this.notice = `Email domain ${response.email_domain.domain} added. Add the TXT record to verify this domain.`;
+ this.resetAdd();
+ } catch (e: any) {
+ if (domainRequestError(e)) {
+ this.attrs.onAuthExpired();
+ return;
+ }
+ this.addError = (e as Error).message || 'Unable to add email domain.';
+ this.addInvalid = true;
+ } finally {
+ this.creating = false;
+ m.redraw();
+ }
+ },
+
+ resetVerify(this: any) {
+ this.verifyTarget = null;
+ this.verifyError = null;
+ this.verifying = false;
+ this.copied = false;
+ if (this.copyTimer) {
+ clearTimeout(this.copyTimer as ReturnType<typeof setTimeout>);
+ this.copyTimer = 0;
+ }
+ },
+
+ openVerify(this: any, entry: AdminRealmEmailDomain) {
+ this.resetVerify();
+ this.verifyTarget = { domain: entry.domain, token: entry.verification_token || '' };
+ m.redraw();
+ },
+
+ flashCopied(this: any) {
+ this.copied = true;
+ if (this.copyTimer) clearTimeout(this.copyTimer as ReturnType<typeof setTimeout>);
+ this.copyTimer = setTimeout(() => {
+ this.copied = false;
+ m.redraw();
+ }, 2000);
+ m.redraw();
+ },
+
+ copyToken(this: any) {
+ const text = this.verifyTarget ? this.verifyTarget.token : '';
+ if (!text) return;
+ const clipboard =
+ typeof navigator !== 'undefined' && navigator.clipboard
+ ? navigator.clipboard
+ : null;
+ if (clipboard && clipboard.writeText) {
+ clipboard
+ .writeText(text)
+ .then(() => this.flashCopied())
+ .catch(() => this.fallbackCopy(text));
+ return;
+ }
+ this.fallbackCopy(text);
+ },
+
+ fallbackCopy(this: any, text: string) {
+ try {
+ const scratch = document.createElement('textarea');
+ scratch.value = text;
+ scratch.setAttribute('readonly', '');
+ scratch.style.position = 'absolute';
+ scratch.style.left = '-9999rem';
+ document.body.appendChild(scratch);
+ scratch.select();
+ document.execCommand('copy');
+ document.body.removeChild(scratch);
+ this.flashCopied();
+ } catch {
+ /* clipboard unavailable */
+ }
+ },
+
+ async submitVerify(this: any) {
+ const { realmSlug } = this.attrs;
+ const target = this.verifyTarget;
+ if (!realmSlug || !target || this.verifying) return;
+
+ this.verifying = true;
+ this.verifyError = null;
+ m.redraw();
+
+ try {
+ const response = await verifyAdminRealmEmailDomain(realmSlug, target.domain);
+ if (this.loadedRealm === realmSlug) {
+ this.domains = (this.domains || []).map((entry) =>
+ entry.domain === response.email_domain.domain ? response.email_domain : entry
+ );
+ this.notice = `Email domain ${response.email_domain.domain} verified.`;
+ }
+ this.resetVerify();
+ } catch (e: any) {
+ if (domainRequestError(e)) {
+ this.attrs.onAuthExpired();
+ return;
+ }
+ this.verifyError = e as Error;
+ } finally {
+ this.verifying = false;
+ m.redraw();
+ }
+ },
+
+ resetRemove(this: any) {
+ this.removeTarget = null;
+ this.removeConfirm = '';
+ this.removeError = null;
+ this.removing = false;
+ },
+
+ openRemove(this: any, domain: string) {
+ this.resetRemove();
+ this.removeTarget = domain;
+ m.redraw();
+ },
+
+ async submitRemove(this: any) {
+ const { realmSlug } = this.attrs;
+ const target = this.removeTarget;
+ if (!realmSlug || !target || this.removing) return;
+ if (normalizeDomainValue(this.removeConfirm) !== target) return;
+
+ this.removing = true;
+ this.removeError = null;
+ m.redraw();
+
+ try {
+ const result = await deleteAdminRealmEmailDomain(realmSlug, target);
+ if (this.loadedRealm === realmSlug) {
+ this.domains = (this.domains || []).filter((entry) => entry.domain !== result.domain);
+ this.notice = `Email domain ${result.domain} removed.`;
+ }
+ this.resetRemove();
+ } catch (e: any) {
+ if (domainRequestError(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: 'Email domains' },
+ ];
+
+ const domains = this.domains as AdminRealmEmailDomain[] | null;
+ const term = this.search.trim().toLowerCase();
+ const visible = domains ? domains.filter((entry) => !term || entry.domain.includes(term)) : [];
+
+ return (
+ <div>
+ <Breadcrumb items={breadcrumbItems} />
+ <PageHeader
+ row
+ title="Email domains"
+ subtitle="Domains used to assign new accounts to this realm."
+ >
+ <RealmSelector
+ realms={realms}
+ selected={selected}
+ onchange={(slug: string) => {
+ m.route.set(`/email-domains/${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 || !domains ? (
+ <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 domain-table-panel" aria-label="Realm email domains">
+ <div class="table-toolbar">
+ <div class="table-search">
+ <input
+ type="search"
+ value={this.search}
+ aria-label="Search email domains"
+ placeholder="Search email domains"
+ 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 email domain
+ </button>
+ </div>
+ ) : null}
+ </div>
+
+ <div class="data-table-wrap">
+ <table class="data-table data-table-static domain-table">
+ <thead>
+ <tr>
+ <th class="data-table-primary domain-name-column" scope="col">Domain</th>
+ <th class="domain-status-column" scope="col">Status</th>
+ {canManage ? <th class="domain-action-column" scope="col">Actions</th> : null}
+ </tr>
+ </thead>
+ <tbody>
+ {visible.map((entry: AdminRealmEmailDomain) => (
+ <tr>
+ <td class="data-table-primary domain-name-column" data-label="Domain">
+ <span class="domain-name">{entry.domain}</span>
+ </td>
+ <td class="domain-status-column" data-label="Status">
+ <span
+ class={
+ entry.status === 'pending'
+ ? 'domain-status is-pending'
+ : 'domain-status'
+ }
+ >
+ <span class="domain-status-dot" aria-hidden="true"></span>
+ {statusLabel(entry.status)}
+ </span>
+ </td>
+ {canManage ? (
+ <td class="domain-action-column" data-label="Actions">
+ <div class="domain-row-action">
+ {entry.status === 'pending' ? (
+ <button
+ class="action-button is-primary"
+ type="button"
+ onclick={() => this.openVerify(entry)}
+ >
+ Verify
+ </button>
+ ) : null}
+ <button
+ class="action-button is-danger"
+ type="button"
+ onclick={() => this.openRemove(entry.domain)}
+ >
+ Remove
+ </button>
+ </div>
+ </td>
+ ) : null}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {domains.length > 0 && visible.length === 0 ? (
+ <div class="empty">
+ <p>No email domains match this search.</p>
+ </div>
+ ) : domains.length === 0 ? (
+ <div class="empty">
+ <p>No email domains are assigned to this realm.</p>
+ </div>
+ ) : null}
+ </div>
+ </section>
+ )}
+
+ {this.addOpen ? (
+ <Modal title="Add email domain" 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">Email domain</span>
+ <input
+ class="field-control"
+ type="text"
+ value={this.addValue}
+ maxlength="253"
+ placeholder="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">
+ Enter the domain without @ or a protocol. New accounts matching this domain are
+ assigned to the realm once the domain is verified.
+ </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 domain'}
+ </button>
+ </div>
+ </form>
+ </Modal>
+ ) : null}
+
+ {this.verifyTarget ? (
+ <Modal title="Verify email domain" onClose={() => this.resetVerify()}>
+ <p class="modal-note">
+ Add the TXT record below to prove control of {this.verifyTarget.domain}. Accounts
+ using this domain are assigned to the realm automatically once verified.
+ </p>
+ {this.verifyError ? (
+ <div class="alert" role="alert">
+ {this.verifyError.message}
+ </div>
+ ) : null}
+
+ <div class="form-field">
+ <span class="field-label">TXT record name</span>
+ <input
+ class="field-control verify-record-name"
+ type="text"
+ value={`_auth-domain-challenge.${this.verifyTarget.domain}`}
+ readonly
+ />
+ </div>
+
+ <div class="form-field">
+ <span class="field-label">TXT record value</span>
+ <input
+ class="field-control verify-record-value"
+ type="text"
+ value={this.verifyTarget.token}
+ readonly
+ />
+ <div class="verify-copy-row">
+ <button
+ class="button-secondary"
+ type="button"
+ onclick={() => this.copyToken()}
+ >
+ {this.copied ? 'Copied' : 'Copy value'}
+ </button>
+ </div>
+ </div>
+
+ <p class="modal-note">
+ Automated DNS checking arrives in a later slice; mark the domain verified once the
+ record is in place.
+ </p>
+
+ <div class="modal-actions">
+ <button
+ class="button-secondary"
+ type="button"
+ disabled={this.verifying}
+ onclick={() => this.resetVerify()}
+ >
+ Close
+ </button>
+ <button
+ class="button"
+ type="button"
+ disabled={this.verifying}
+ onclick={() => this.submitVerify()}
+ >
+ {this.verifying ? 'Verifying' : 'Mark as verified'}
+ </button>
+ </div>
+ </Modal>
+ ) : null}
+
+ {this.removeTarget ? (
+ <Modal title="Remove email domain" onClose={() => this.resetRemove()}>
+ <p class="modal-note">
+ Remove {this.removeTarget}? This domain will stop assigning new accounts to{' '}
+ {breadcrumbRealm}. Existing accounts keep their current home realm, and realm
+ memberships are unaffected.
+ </p>
+ {this.removeError ? (
+ <div class="alert" role="alert">
+ {this.removeError.message}
+ </div>
+ ) : null}
+
+ <div class="form-field">
+ <span class="field-label">Confirm domain</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 domain 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 ||
+ normalizeDomainValue(this.removeConfirm) !== this.removeTarget
+ }
+ onclick={() => this.submitRemove()}
+ >
+ {this.removing ? 'Removing' : 'Remove domain'}
+ </button>
+ </div>
+ </Modal>
+ ) : null}
+ </div>
+ );
+ },
+};
diff --git a/app/admin/src/screen/realms.tsx b/app/admin/src/screen/realms.tsx
@@ -269,6 +269,8 @@ export const RealmsPage: m.Component<RealmsAttrs> = {
const settingsPath = (realm: AdminRealm) =>
`/settings/${encodeURIComponent(realm.slug)}`;
const hostsPath = (realm: AdminRealm) => `/hosts/${encodeURIComponent(realm.slug)}`;
+ const domainsPath = (realm: AdminRealm) =>
+ `/email-domains/${encodeURIComponent(realm.slug)}`;
const previewLogo = logoUrlError(this.createValue.logo_url)
? ''
: this.createValue.logo_url.trim();
@@ -394,9 +396,23 @@ export const RealmsPage: m.Component<RealmsAttrs> = {
) : (
<span class="realm-count">{pluralCount(realm.host_count, 'host')}</span>
)}
- <span class="realm-count">
- {pluralCount(realm.email_domain_count, 'domain')}
- </span>
+ {realm.can_edit ? (
+ <a
+ class="realm-count realm-count-link"
+ href={appUrl(domainsPath(realm))}
+ onclick={(event: MouseEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ m.route.set(domainsPath(realm));
+ }}
+ >
+ {pluralCount(realm.email_domain_count, 'domain')}
+ </a>
+ ) : (
+ <span class="realm-count">
+ {pluralCount(realm.email_domain_count, 'domain')}
+ </span>
+ )}
<span class="realm-count">{pluralCount(realm.client_count, 'client')}</span>
</span>
</td>
diff --git a/app/admin/src/screen/settings.tsx b/app/admin/src/screen/settings.tsx
@@ -407,7 +407,7 @@ export const SettingsPage: m.Component<SettingsAttrs> = {
<section class="panel">
<h2>Realm access</h2>
- <p class="note">Manage hostnames that resolve to this realm.</p>
+ <p class="note">Manage hostnames and email domains for this realm.</p>
<div class="settings-actions">
<a
class="button-secondary"
@@ -419,6 +419,16 @@ export const SettingsPage: m.Component<SettingsAttrs> = {
>
Hosts
</a>
+ <a
+ class="button-secondary"
+ href={appUrl(`/email-domains/${encodeURIComponent(realmSlug || '')}`)}
+ onclick={(event: MouseEvent) => {
+ event.preventDefault();
+ m.route.set(`/email-domains/${encodeURIComponent(realmSlug || '')}`);
+ }}
+ >
+ Email domains
+ </a>
</div>
</section>
</div>
diff --git a/app/admin/src/util/api.ts b/app/admin/src/util/api.ts
@@ -63,6 +63,36 @@ export interface AdminRealmHostDeleteResponse {
host: string;
}
+export type AdminRealmEmailDomainStatus = 'pending' | 'verified';
+
+export interface AdminRealmEmailDomain {
+ domain: string;
+ status: AdminRealmEmailDomainStatus;
+ verification_token: string | null;
+ verified_at: number | null;
+ created_at: number;
+}
+
+export interface AdminRealmEmailDomainListResponse {
+ email_domains: AdminRealmEmailDomain[];
+}
+
+export interface AdminRealmEmailDomainCreateResponse {
+ ok: boolean;
+ email_domain: AdminRealmEmailDomain;
+}
+
+export interface AdminRealmEmailDomainVerifyResponse {
+ ok: boolean;
+ email_domain: AdminRealmEmailDomain;
+}
+
+export interface AdminRealmEmailDomainDeleteResponse {
+ ok: boolean;
+ removed: boolean;
+ domain: 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,11 @@ import {
type AdminRealmCreateInput,
type AdminRealmCreateResponse,
type AdminRealmDeleteResponse,
+ type AdminRealmEmailDomain,
+ type AdminRealmEmailDomainCreateResponse,
+ type AdminRealmEmailDomainDeleteResponse,
+ type AdminRealmEmailDomainListResponse,
+ type AdminRealmEmailDomainVerifyResponse,
type AdminRealmHost,
type AdminRealmHostCreateResponse,
type AdminRealmHostDeleteResponse,
@@ -123,6 +128,51 @@ export async function deleteAdminRealmHost(
);
}
+export async function loadAdminRealmEmailDomains(
+ realmSlug: string
+): Promise<AdminRealmEmailDomain[]> {
+ const realm = encodeURIComponent(realmSlug);
+ const response = await adminJson<AdminRealmEmailDomainListResponse>(
+ `/api/v1/admin/realms/${realm}/email-domains`
+ );
+ return response.email_domains;
+}
+
+export async function createAdminRealmEmailDomain(
+ realmSlug: string,
+ domain: string
+): Promise<AdminRealmEmailDomainCreateResponse> {
+ const realm = encodeURIComponent(realmSlug);
+ return adminJson<AdminRealmEmailDomainCreateResponse>(
+ `/api/v1/admin/realms/${realm}/email-domains`,
+ { method: 'POST', body: JSON.stringify({ domain }) }
+ );
+}
+
+export async function verifyAdminRealmEmailDomain(
+ realmSlug: string,
+ domain: string
+): Promise<AdminRealmEmailDomainVerifyResponse> {
+ const realm = encodeURIComponent(realmSlug);
+ const encoded = encodeURIComponent(domain);
+ return adminJson<AdminRealmEmailDomainVerifyResponse>(
+ `/api/v1/admin/realms/${realm}/email-domains/${encoded}`,
+ { method: 'PATCH', body: JSON.stringify({ verified: true }) }
+ );
+}
+
+export async function deleteAdminRealmEmailDomain(
+ realmSlug: string,
+ domain: string
+): Promise<AdminRealmEmailDomainDeleteResponse> {
+ const realm = encodeURIComponent(realmSlug);
+ const encoded = encodeURIComponent(domain);
+ return adminJson<AdminRealmEmailDomainDeleteResponse>(
+ `/api/v1/admin/realms/${realm}/email-domains/${encoded}`,
+ { method: 'DELETE' }
+ );
+}
+
export async function loadAdminSessions(realmSlug: string): Promise<AdminSession[]> {
const realm = encodeURIComponent(realmSlug);
const response = await adminJson<{ sessions: AdminSession[] }>(
diff --git a/app/shared/style/global.css b/app/shared/style/global.css
@@ -21,6 +21,7 @@
--skeleton: #00000012;
--danger: #c9190b;
--danger-text: #c9190b;
+ --warn: #9a6700;
--field-line: rgba(0, 0, 0, 0.42);
--shadow: 0 0.125em 0.25em #0008;
--hex: url('./assets/hex-grid-light.svg');
@@ -1346,6 +1347,7 @@ select:focus-visible {
--row-hover: #ffffff14;
--skeleton: #ffffff14;
--danger-text: #f28b82;
+ --warn: #e3b341;
--field-line: rgba(255, 255, 255, 0.42);
--hex: url('./assets/hex-grid-dark.svg');
color-scheme: dark;
@@ -1372,6 +1374,7 @@ select:focus-visible {
--row-hover: #ffffff14;
--skeleton: #ffffff14;
--danger-text: #f28b82;
+ --warn: #e3b341;
--field-line: rgba(255, 255, 255, 0.42);
--hex: url('./assets/hex-grid-dark.svg');
color-scheme: dark;
diff --git a/server/src/controller/admin/realm-email-domains.js b/server/src/controller/admin/realm-email-domains.js
@@ -0,0 +1,110 @@
+import { app } from '../../app.js';
+import { authenticateAdminRequest } from '../../lib/admin-auth.js';
+import {
+ addAdminRealmEmailDomain,
+ deleteAdminRealmEmailDomain,
+ listAdminRealmEmailDomains,
+ verifyAdminRealmEmailDomain,
+} from '../../lib/admin-realm-email-domains.js';
+import { HttpError } from '../../lib/http/http-error.js';
+import { isSystemAdmin } from '../../lib/policy.js';
+
+function assertCreateBody(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 !== 'domain') {
+ throw new HttpError(400, 'invalid_request', `Unknown field: ${field}`);
+ }
+ }
+}
+
+function assertVerifyBody(body) {
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
+ throw new HttpError(400, 'invalid_request', 'Request body must be a JSON object');
+ }
+ const keys = Object.keys(body);
+ for (const field of keys) {
+ if (field !== 'verified') {
+ throw new HttpError(400, 'invalid_request', `Unknown field: ${field}`);
+ }
+ }
+ if (keys.length !== 1 || body.verified !== true) {
+ throw new HttpError(400, 'invalid_request', 'verified must be true');
+ }
+}
+
+export default [
+ {
+ method: 'get',
+ path: '/api/v1/admin/realms/:realm/email-domains',
+ name: 'admin.realm-email-domains.list',
+ async handler(req) {
+ const auth = await authenticateAdminRequest(req, {
+ realmSlug: req.params.realm,
+ });
+ const email_domains = await listAdminRealmEmailDomains({
+ systemDb: auth.systemDb,
+ realm: auth.realm,
+ });
+
+ return new app.HttpOk({ email_domains }, { 'cache-control': 'no-store' });
+ },
+ },
+ {
+ method: 'post',
+ path: '/api/v1/admin/realms/:realm/email-domains',
+ name: 'admin.realm-email-domains.create',
+ async handler(req) {
+ const auth = await authenticateAdminRequest(req, {
+ realmSlug: req.params.realm,
+ });
+ const body = req.body || {};
+ assertCreateBody(body);
+ const email_domain = await addAdminRealmEmailDomain({
+ systemDb: auth.systemDb,
+ realm: auth.realm,
+ domain: body.domain,
+ isSystemAdmin: isSystemAdmin(auth.user),
+ });
+
+ return new app.HttpOk({ ok: true, email_domain }, { 'cache-control': 'no-store' });
+ },
+ },
+ {
+ method: 'patch',
+ path: '/api/v1/admin/realms/:realm/email-domains/:domain',
+ name: 'admin.realm-email-domains.verify',
+ async handler(req) {
+ const auth = await authenticateAdminRequest(req, {
+ realmSlug: req.params.realm,
+ });
+ assertVerifyBody(req.body || {});
+ const email_domain = await verifyAdminRealmEmailDomain({
+ systemDb: auth.systemDb,
+ realm: auth.realm,
+ domain: req.params.domain,
+ });
+
+ return new app.HttpOk({ ok: true, email_domain }, { 'cache-control': 'no-store' });
+ },
+ },
+ {
+ method: 'delete',
+ path: '/api/v1/admin/realms/:realm/email-domains/:domain',
+ name: 'admin.realm-email-domains.delete',
+ async handler(req) {
+ const auth = await authenticateAdminRequest(req, {
+ realmSlug: req.params.realm,
+ });
+ const result = await deleteAdminRealmEmailDomain({
+ systemDb: auth.systemDb,
+ realm: auth.realm,
+ domain: req.params.domain,
+ });
+
+ return new app.HttpOk({ ok: true, ...result }, { 'cache-control': 'no-store' });
+ },
+ },
+];
diff --git a/server/src/lib/admin-realm-email-domains.js b/server/src/lib/admin-realm-email-domains.js
@@ -0,0 +1,112 @@
+import { HttpError } from './http/http-error.js';
+import {
+ addRealmEmailDomain,
+ findRealmEmailDomainOwner,
+ getRealmEmailDomain,
+ listRealmEmailDomains,
+ markRealmEmailDomainVerified,
+ normalizeEmailDomain,
+ removeRealmEmailDomain,
+ validateRealmEmailDomain,
+} from './realm.js';
+
+function invalidRequest(message) {
+ return new HttpError(400, 'invalid_request', message);
+}
+
+function serialize(row) {
+ const verified = Boolean(row.verified);
+ return {
+ domain: row.domain,
+ status: verified ? 'verified' : 'pending',
+ verification_token: verified ? null : row.verification_token ?? null,
+ verified_at: row.verified_at ?? null,
+ created_at: row.created_at,
+ };
+}
+
+function lookupDomain(domain) {
+ try {
+ const normalized = normalizeEmailDomain(domain);
+ if (!normalized) throw new Error('empty');
+ return normalized;
+ } catch {
+ throw invalidRequest('email domain is required');
+ }
+}
+
+export async function listAdminRealmEmailDomains({ systemDb, realm }) {
+ const rows = await listRealmEmailDomains(systemDb, realm.id);
+ return rows.map(serialize);
+}
+
+export async function addAdminRealmEmailDomain({
+ systemDb,
+ realm,
+ domain,
+ isSystemAdmin = false,
+}) {
+ const normalized = validateRealmEmailDomain(domain);
+
+ const existing = await findRealmEmailDomainOwner(systemDb, normalized);
+ if (existing) {
+ if (existing.realm_id === realm.id) {
+ throw new HttpError(
+ 409,
+ 'domain_in_use',
+ 'This email domain is already assigned to this realm.'
+ );
+ }
+ throw new HttpError(
+ 409,
+ 'domain_in_use',
+ isSystemAdmin
+ ? `This email domain is already assigned to ${existing.slug}.`
+ : 'This email domain is already assigned to another realm.'
+ );
+ }
+
+ try {
+ await addRealmEmailDomain(realm.id, normalized, { verified: false });
+ } catch {
+ throw new HttpError(409, 'domain_in_use', 'This email domain is already assigned.');
+ }
+
+ const row = await getRealmEmailDomain(systemDb, realm.id, normalized);
+ if (row) return serialize(row);
+
+ return {
+ domain: normalized,
+ status: 'pending',
+ verification_token: null,
+ verified_at: null,
+ created_at: Date.now(),
+ };
+}
+
+export async function verifyAdminRealmEmailDomain({ systemDb, realm, domain }) {
+ const normalized = lookupDomain(domain);
+
+ const row = await getRealmEmailDomain(systemDb, realm.id, normalized);
+ if (!row) {
+ throw new HttpError(404, 'domain_not_found', 'Email domain is not assigned to this realm.');
+ }
+ if (row.verified) return serialize(row);
+
+ await markRealmEmailDomainVerified(systemDb, realm.id, normalized);
+ const updated = await getRealmEmailDomain(systemDb, realm.id, normalized);
+ if (updated) return serialize(updated);
+
+ return serialize({ ...row, verified: 1, verification_token: null, verified_at: Date.now() });
+}
+
+export async function deleteAdminRealmEmailDomain({ systemDb, realm, domain }) {
+ const normalized = lookupDomain(domain);
+
+ const removed = await removeRealmEmailDomain(systemDb, realm.id, normalized);
+ if (!removed) {
+ throw new HttpError(404, 'domain_not_found', 'Email domain is not assigned to this realm.');
+ }
+
+ return { removed: true, domain: normalized };
+}
diff --git a/server/src/lib/realm.js b/server/src/lib/realm.js
@@ -512,3 +512,106 @@ export async function findRealmById(id) {
{ id }
);
}
+
+export function validateRealmEmailDomain(raw) {
+ const invalid = (message) => new HttpError(400, 'invalid_request', message);
+
+ if (typeof raw !== 'string') throw invalid('domain must be a string');
+ const value = raw.trim();
+ if (!value) throw invalid('email domain is required');
+ if (/\s/.test(value)) throw invalid('email domain must not contain spaces');
+
+ const lower = value.toLowerCase();
+ const domain = lower.replace(/\.$/, '');
+ if (!domain) throw invalid('email domain is required');
+ if (domain.includes('@')) throw invalid('enter the domain without the @ symbol');
+ if (domain.includes('://') || /^[a-z][a-z0-9+.-]*:\/\//i.test(lower)) {
+ throw invalid('email domain must not include a scheme such as https://');
+ }
+ if (domain.includes('/')) throw invalid('email domain must not include a path');
+ if (domain.includes('*')) throw invalid('wildcard domains are not supported');
+ if (domain.includes(':')) throw invalid('email domain must not include a port');
+ if (lower.endsWith('.')) throw invalid('email domain must not end with a dot');
+ if (domain.startsWith('.')) throw invalid('email domain must not start with a dot');
+ if (domain.length > 253) throw invalid('email domain must be 253 characters or fewer');
+
+ const labels = domain.split('.');
+ if (labels.length < 2) throw invalid('enter a complete domain such as acme.test');
+ for (const label of labels) {
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(label)) {
+ throw invalid('domain labels may use lowercase letters, numbers and hyphens');
+ }
+ if (label.length > 63) throw invalid('each domain label must be 63 characters or fewer');
+ }
+
+ return domain;
+}
+
+function lookupDomain(domain) {
+ return String(domain || '').trim().toLowerCase().replace(/\.$/, '');
+}
+
+export async function listRealmEmailDomains(targetDb, realmId) {
+ const db = targetDb || systemDb;
+ if (!db) throw new Error('realm registry is not initialized');
+ return db.all(
+ `SELECT domain, verified, verification_token, verified_at, created_at
+ FROM realm_email_domains
+ WHERE realm_id = {realmId}
+ ORDER BY created_at DESC, domain ASC`,
+ { realmId }
+ );
+}
+
+export async function findRealmEmailDomainOwner(targetDb, domain) {
+ const db = targetDb || systemDb;
+ if (!db) throw new Error('realm registry is not initialized');
+ const value = lookupDomain(domain);
+ if (!value) return null;
+ return db.get(
+ `SELECT d.domain, d.verified, d.realm_id, r.slug
+ FROM realm_email_domains d
+ JOIN realms r ON r.id = d.realm_id
+ WHERE d.domain = {domain}`,
+ { domain: value }
+ );
+}
+
+export async function getRealmEmailDomain(targetDb, realmId, domain) {
+ const db = targetDb || systemDb;
+ if (!db) throw new Error('realm registry is not initialized');
+ const value = lookupDomain(domain);
+ if (!value) return null;
+ return db.get(
+ `SELECT domain, realm_id, verified, verification_token, verified_at, created_at
+ FROM realm_email_domains
+ WHERE domain = {domain} AND realm_id = {realmId}`,
+ { domain: value, realmId }
+ );
+}
+
+export async function removeRealmEmailDomain(targetDb, realmId, domain) {
+ const db = targetDb || systemDb;
+ if (!db) throw new Error('realm registry is not initialized');
+ const value = lookupDomain(domain);
+ if (!value) return false;
+ const result = await db.run(
+ 'DELETE FROM realm_email_domains WHERE domain = {domain} AND realm_id = {realmId}',
+ { domain: value, realmId }
+ );
+ return result.changes > 0;
+}
+
+export async function markRealmEmailDomainVerified(targetDb, realmId, domain) {
+ const db = targetDb || systemDb;
+ if (!db) throw new Error('realm registry is not initialized');
+ const value = lookupDomain(domain);
+ if (!value) return false;
+ const result = await db.run(
+ `UPDATE realm_email_domains
+ SET verified = 1, verified_at = {now}, verification_token = NULL
+ WHERE domain = {domain} AND realm_id = {realmId} AND verified = 0`,
+ { domain: value, realmId, now: Date.now() }
+ );
+ return result.changes > 0;
+}
diff --git a/server/test/http.test.js b/server/test/http.test.js
@@ -4830,6 +4830,265 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
}
});
+ await t.test('admin realm email domain management', async () => {
+ const systemAdmin = await adminToken();
+ const acmeAdmin = await adminToken('it@acme.test');
+ const globexAdmin = await adminToken('contractor@personal.test');
+ const added = [];
+
+ const cleanupDomain = async (realm, domain) => {
+ await adminRequest(systemAdmin, {
+ method: 'DELETE',
+ path: `/api/v1/admin/realms/${realm}/email-domains/${encodeURIComponent(domain)}`,
+ });
+ };
+
+ try {
+ const list = await adminRequest(systemAdmin, {
+ path: '/api/v1/admin/realms/acme/email-domains',
+ });
+ assert.equal(list.status, 200);
+ assert.ok(Array.isArray(list.json.email_domains));
+ const seeded = list.json.email_domains.find((entry) => entry.domain === 'acme.test');
+ assert.ok(seeded, 'seeded acme.test present');
+ assert.equal(seeded.status, 'verified');
+ assert.equal(seeded.verification_token, null);
+ assert.equal(typeof seeded.verified_at, 'number');
+ assert.equal(typeof seeded.created_at, 'number');
+
+ const crossRealmList = await adminRequest(acmeAdmin, {
+ path: '/api/v1/admin/realms/globex/email-domains',
+ });
+ assert.equal(crossRealmList.status, 403);
+ assert.equal(crossRealmList.json.error.code, 'forbidden');
+
+ const foreignList = await adminRequest(globexAdmin, {
+ path: '/api/v1/admin/realms/acme/email-domains',
+ });
+ assert.equal(foreignList.status, 403);
+
+ const unknownRealm = await adminRequest(systemAdmin, {
+ path: '/api/v1/admin/realms/does-not-exist/email-domains',
+ });
+ assert.equal(unknownRealm.status, 404);
+
+ const created = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/email-domains',
+ body: { domain: ' Staff.Acme.test ' },
+ });
+ assert.equal(created.status, 200);
+ assert.equal(created.json.ok, true);
+ assert.equal(created.json.email_domain.domain, 'staff.acme.test');
+ assert.equal(created.json.email_domain.status, 'pending');
+ assert.equal(typeof created.json.email_domain.verification_token, 'string');
+ assert.ok(created.json.email_domain.verification_token.length > 0);
+ assert.equal(created.json.email_domain.verified_at, null);
+ added.push({ realm: 'acme', domain: 'staff.acme.test' });
+
+ for (const domain of [
+ 'https://x.test',
+ 'x.test:443',
+ 'x.test/path',
+ '*.acme.test',
+ 'user@acme.test',
+ 'two words.test',
+ 'nodot',
+ 'trailing.test.',
+ '@acme.test',
+ 'bad_underscore.test',
+ ]) {
+ const invalid = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/email-domains',
+ body: { domain },
+ });
+ assert.equal(invalid.status, 400, `expected 400 for ${domain}`);
+ assert.equal(invalid.json.error.code, 'invalid_request');
+ }
+
+ const emptyBody = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/email-domains',
+ 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/email-domains',
+ body: { hostname: 'ok.test' },
+ });
+ assert.equal(unknownField.status, 400);
+ assert.equal(unknownField.json.error.code, 'invalid_request');
+
+ const ownRealm = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/email-domains',
+ body: { domain: 'acme.test' },
+ });
+ assert.equal(ownRealm.status, 409);
+ assert.equal(ownRealm.json.error.code, 'domain_in_use');
+ assert.match(ownRealm.json.error.message, /this realm/i);
+
+ const otherSystem = await adminRequest(systemAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/email-domains',
+ body: { domain: 'globex.test' },
+ });
+ assert.equal(otherSystem.status, 409);
+ assert.equal(otherSystem.json.error.code, 'domain_in_use');
+ assert.match(otherSystem.json.error.message, /globex/);
+
+ const otherAcme = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/email-domains',
+ body: { domain: 'globex.test' },
+ });
+ assert.equal(otherAcme.status, 409);
+ assert.equal(otherAcme.json.error.code, 'domain_in_use');
+ assert.ok(!otherAcme.json.error.message.includes('globex'));
+
+ const shared = await adminRequest(acmeAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/email-domains',
+ body: { domain: 'shared.test' },
+ });
+ assert.equal(shared.status, 200);
+ added.push({ realm: 'acme', domain: 'shared.test' });
+
+ const sharedDup = await adminRequest(globexAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/globex/email-domains',
+ body: { domain: 'shared.test' },
+ });
+ assert.equal(sharedDup.status, 409);
+ assert.equal(sharedDup.json.error.code, 'domain_in_use');
+
+ const serviceDomain = await adminRequest(systemAdmin, {
+ method: 'POST',
+ path: '/api/v1/admin/realms/acme/email-domains',
+ body: { domain: 'identity.test' },
+ });
+ assert.equal(serviceDomain.status, 200);
+ assert.equal(serviceDomain.json.email_domain.status, 'pending');
+ added.push({ realm: 'acme', domain: 'identity.test' });
+
+ const falseVerify = await adminRequest(acmeAdmin, {
+ method: 'PATCH',
+ path: '/api/v1/admin/realms/acme/email-domains/staff.acme.test',
+ body: { verified: false },
+ });
+ assert.equal(falseVerify.status, 400);
+ assert.equal(falseVerify.json.error.code, 'invalid_request');
+
+ const verifyUnknownField = await adminRequest(acmeAdmin, {
+ method: 'PATCH',
+ path: '/api/v1/admin/realms/acme/email-domains/staff.acme.test',
+ body: { verified: true, extra: 1 },
+ });
+ assert.equal(verifyUnknownField.status, 400);
+ assert.equal(verifyUnknownField.json.error.code, 'invalid_request');
+
+ const missingVerify = await adminRequest(acmeAdmin, {
+ method: 'PATCH',
+ path: '/api/v1/admin/realms/acme/email-domains/nope.test',
+ body: { verified: true },
+ });
+ assert.equal(missingVerify.status, 404);
+ assert.equal(missingVerify.json.error.code, 'domain_not_found');
+
+ const crossVerify = await adminRequest(systemAdmin, {
+ method: 'PATCH',
+ path: '/api/v1/admin/realms/acme/email-domains/globex.test',
+ body: { verified: true },
+ });
+ assert.equal(crossVerify.status, 404);
+ assert.equal(crossVerify.json.error.code, 'domain_not_found');
+
+ const forbiddenVerify = await adminRequest(acmeAdmin, {
+ method: 'PATCH',
+ path: '/api/v1/admin/realms/globex/email-domains/globex.test',
+ body: { verified: true },
+ });
+ assert.equal(forbiddenVerify.status, 403);
+
+ const verified = await adminRequest(acmeAdmin, {
+ method: 'PATCH',
+ path: '/api/v1/admin/realms/acme/email-domains/staff.acme.test',
+ body: { verified: true },
+ });
+ assert.equal(verified.status, 200);
+ assert.equal(verified.json.ok, true);
+ assert.equal(verified.json.email_domain.domain, 'staff.acme.test');
+ assert.equal(verified.json.email_domain.status, 'verified');
+ assert.equal(verified.json.email_domain.verification_token, null);
+ assert.equal(typeof verified.json.email_domain.verified_at, 'number');
+
+ const dbRow = withSystemDatabase(env, (database) =>
+ database
+ .prepare(
+ 'SELECT verified, verification_token, verified_at FROM realm_email_domains WHERE domain = ?'
+ )
+ .get('staff.acme.test')
+ );
+ assert.equal(dbRow.verified, 1);
+ assert.equal(dbRow.verification_token, null);
+ assert.ok(dbRow.verified_at);
+
+ const reVerify = await adminRequest(acmeAdmin, {
+ method: 'PATCH',
+ path: '/api/v1/admin/realms/acme/email-domains/staff.acme.test',
+ body: { verified: true },
+ });
+ assert.equal(reVerify.status, 200);
+ assert.equal(reVerify.json.email_domain.status, 'verified');
+
+ const afterList = await adminRequest(acmeAdmin, {
+ path: '/api/v1/admin/realms/acme/email-domains',
+ });
+ const pendingRow = afterList.json.email_domains.find((e) => e.domain === 'shared.test');
+ assert.equal(pendingRow.status, 'pending');
+ assert.ok(pendingRow.verification_token);
+ const verifiedRow = afterList.json.email_domains.find((e) => e.domain === 'staff.acme.test');
+ assert.equal(verifiedRow.status, 'verified');
+
+ const crossRemove = await adminRequest(systemAdmin, {
+ method: 'DELETE',
+ path: '/api/v1/admin/realms/acme/email-domains/globex.test',
+ });
+ assert.equal(crossRemove.status, 404);
+ assert.equal(crossRemove.json.error.code, 'domain_not_found');
+
+ const forbiddenRemove = await adminRequest(acmeAdmin, {
+ method: 'DELETE',
+ path: '/api/v1/admin/realms/globex/email-domains/globex.test',
+ });
+ assert.equal(forbiddenRemove.status, 403);
+
+ const removed = await adminRequest(acmeAdmin, {
+ method: 'DELETE',
+ path: '/api/v1/admin/realms/acme/email-domains/staff.acme.test',
+ });
+ assert.equal(removed.status, 200);
+ assert.equal(removed.json.ok, true);
+ assert.equal(removed.json.removed, true);
+ assert.equal(removed.json.domain, 'staff.acme.test');
+
+ const again = await adminRequest(acmeAdmin, {
+ method: 'DELETE',
+ path: '/api/v1/admin/realms/acme/email-domains/staff.acme.test',
+ });
+ assert.equal(again.status, 404);
+ assert.equal(again.json.error.code, 'domain_not_found');
+ } finally {
+ for (const entry of added) {
+ await cleanupDomain(entry.realm, entry.domain);
+ }
+ }
+ });
+
await t.test('system branding updates Admin settings and discovery precedence', async () => {
const systemAdmin = await adminToken();
const acmeAdmin = await adminToken('it@acme.test');
diff --git a/server/test/realm.test.js b/server/test/realm.test.js
@@ -14,8 +14,11 @@ import {
findClientRealm,
findOidcClientHost,
findRealmByEmailDomain,
+ findRealmEmailDomainOwner,
+ getRealmEmailDomain,
getSystemDatabase,
initRealms,
+ markRealmEmailDomainVerified,
openRealmDatabase,
realmMetadata,
resolveRealm,
@@ -176,3 +179,39 @@ test('a realm can disable the long-session choice', async () => {
await fs.rm(dir, { recursive: true, force: true });
}
});
+
+test('unverified email domains assign a home realm only once verified', async () => {
+ const { dir, cfg } = await tempConfig();
+ try {
+ await initRealms(cfg);
+ const realm = await createRealm({ slug: 'acme', displayName: 'Acme' });
+ const systemDb = getSystemDatabase();
+
+ await addRealmEmailDomain(realm.id, 'Pending.Test', { verified: false });
+
+ assert.equal(await findRealmByEmailDomain('pending.test'), undefined);
+
+ const owner = await findRealmEmailDomainOwner(systemDb, 'pending.test');
+ assert.equal(owner.realm_id, realm.id);
+ assert.equal(owner.verified, 0);
+
+ const row = await getRealmEmailDomain(systemDb, realm.id, 'pending.test');
+ assert.equal(row.domain, 'pending.test');
+ assert.ok(row.verification_token);
+ assert.equal(row.verified_at, null);
+
+ assert.equal(await markRealmEmailDomainVerified(systemDb, realm.id, 'pending.test'), true);
+ assert.equal(await markRealmEmailDomainVerified(systemDb, realm.id, 'pending.test'), false);
+
+ const verified = await getRealmEmailDomain(systemDb, realm.id, 'pending.test');
+ assert.equal(verified.verified, 1);
+ assert.equal(verified.verification_token, null);
+ assert.ok(verified.verified_at);
+
+ const assigned = await findRealmByEmailDomain('pending.test');
+ assert.equal(assigned.id, realm.id);
+ } finally {
+ await closeRealms();
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+});