diff --git a/src/components/layout/MainContent.tsx b/src/components/layout/MainContent.tsx index 396e1e5..e4d2d04 100644 --- a/src/components/layout/MainContent.tsx +++ b/src/components/layout/MainContent.tsx @@ -183,6 +183,11 @@ const CUSTOM_PAGES: Record = { () => import('@/features/storeTools/BlobStoreChangesPage'), (m) => m.BlobStoreChangesPage, ), + // Where inbuxa Admin and the webmail are served (inbuxa:FrontEnds, C-4) + FrontEnds: onDemand( + () => import('@/features/frontEnds/FrontEndsPage'), + (m) => m.FrontEndsPage, + ), }; /** Guided jobs, by the name after `Wizard/`; always reached by choosing "Guide me", never by default. */ diff --git a/src/features/frontEnds/FrontEndsPage.tsx b/src/features/frontEnds/FrontEndsPage.tsx new file mode 100644 index 0000000..8877ba3 --- /dev/null +++ b/src/features/frontEnds/FrontEndsPage.tsx @@ -0,0 +1,480 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +/** + * INBUXA: Settings › Network › Web › Front ends. Where inbuxa Admin and the + * webmail are served (`inbuxa:FrontEnds`, contract C-4), the same thing + * `inbuxa join` sets from the installer. Saving registers their sign-in and + * rebuilds the cross-origin allowlist on every node. + */ + +import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'; +import { useTranslation } from 'react-i18next'; +import { useBlocker } from 'react-router-dom'; +import { Check, Copy, KeyRound, Plus, X } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Badge } from '@/components/ui/badge'; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog'; +import { PageHeader } from '@/components/common/PageHeader'; +import { LoadingFallback } from '@/components/common/LoadingFallback'; +import { toast } from '@/hooks/use-toast'; +import { getApiBaseUrl } from '@/services/api'; +import { useAccountStore } from '@/stores/accountStore'; +import { fetchFrontEnds, FrontEndsUnavailable, saveFrontEnds } from './api'; +import { + cutsOffThisConsole, + draftOf, + draftProblem, + MIN_SECRET_LENGTH, + newSecret, + originProblem, + patchOf, + urlProblem, + type Draft, + type FrontEnds, +} from './model'; + +type Load = { kind: 'loading' } | { kind: 'ready'; current: FrontEnds } | { kind: 'error'; message: string }; + +const message = (e: unknown) => (e instanceof Error ? e.message : String(e)); + +function Section({ title, hint, children }: { title: string; hint: ReactNode; children: ReactNode }) { + return ( +
+
+

{title}

+

{hint}

+
+ {children} +
+ ); +} + +/** What this node's environment says beside the stored value; both are used. */ +function FromEnvironment({ name, value }: { name: string; value: string }) { + const { t } = useTranslation(); + return ( +

+ {t('frontEnds.fromEnvironment', 'Also {{value}}, from {{name}} on the node that answered. Both are used.', { + value, + name, + })} +

+ ); +} + +function CopyButton({ text }: { text: string }) { + const { t } = useTranslation(); + const [done, setDone] = useState(false); + return ( + + ); +} + +export function FrontEndsPage() { + const { t } = useTranslation(); + // Reading takes the HTTP settings' permission; changing it registers OAuth clients too. + const canSave = useAccountStore((s) => s.hasPermission('sysHttpUpdate') && s.hasPermission('sysOAuthClientUpdate')); + const [load, setLoad] = useState({ kind: 'loading' }); + const [fetches, setFetches] = useState(0); + const [draft, setDraft] = useState(null); + const [newOrigin, setNewOrigin] = useState(''); + const [originError, setOriginError] = useState(null); + const [cutOffOk, setCutOffOk] = useState(false); + const [saving, setSaving] = useState(false); + + useEffect(() => { + const controller = new AbortController(); + fetchFrontEnds(controller.signal) + .then((current) => { + if (controller.signal.aborted) return; + setLoad({ kind: 'ready', current }); + setDraft(draftOf(current)); + setNewOrigin(''); + setOriginError(null); + setCutOffOk(false); + }) + .catch((e: unknown) => { + if (controller.signal.aborted) return; + setLoad({ + kind: 'error', + message: + e instanceof FrontEndsUnavailable + ? t('frontEnds.unavailable', 'This server doesn’t keep its front ends’ addresses. Use its environment.') + : message(e), + }); + }); + return () => controller.abort(); + }, [fetches, t]); + + const current = load.kind === 'ready' ? load.current : null; + // An origin typed but not yet added counts: it's saved with the rest. + const effective = useMemo(() => { + if (!draft) return null; + const typed = newOrigin.trim(); + return typed && !originProblem(typed, draft.extraOrigins) + ? { ...draft, extraOrigins: [...draft.extraOrigins, typed] } + : draft; + }, [draft, newOrigin]); + const patch = useMemo(() => (effective && current ? patchOf(effective, current) : {}), [effective, current]); + const dirty = Object.keys(patch).length > 0; + const problem = effective && current ? draftProblem(effective, current) : null; + const cutOff = + effective && current ? cutsOffThisConsole(effective, current, window.location.origin, getApiBaseUrl()) : false; + + useEffect(() => { + if (!dirty) return; + const handler = (e: BeforeUnloadEvent) => e.preventDefault(); + window.addEventListener('beforeunload', handler); + return () => window.removeEventListener('beforeunload', handler); + }, [dirty]); + const blocker = useBlocker(dirty && !saving); + + const update = useCallback((change: Partial) => setDraft((d) => (d ? { ...d, ...change } : d)), []); + + const addOrigin = () => { + if (!draft) return; + const why = originProblem(newOrigin, draft.extraOrigins); + if (why) { + setOriginError(why); + return; + } + update({ extraOrigins: [...draft.extraOrigins, newOrigin.trim()] }); + setNewOrigin(''); + setOriginError(null); + }; + + const save = async () => { + if (!dirty || problem || (cutOff && !cutOffOk)) return; + setSaving(true); + try { + await saveFrontEnds(patch); + toast({ + title: t('frontEnds.saved', 'Front ends saved'), + description: t( + 'frontEnds.savedDetail', + 'Their sign-in is registered and every node now accepts requests from these addresses.', + ), + }); + setFetches((n) => n + 1); + } catch (e) { + toast({ variant: 'destructive', title: t('frontEnds.notSaved', 'Not saved'), description: message(e) }); + } finally { + setSaving(false); + } + }; + + const readOnly = !canSave; + + return ( +
+ + + {load.kind === 'loading' && } + {load.kind === 'error' && ( +
{load.message}
+ )} + + {current && draft && ( + <> + {readOnly && ( +

+ {t( + 'frontEnds.readOnly', + 'You can see these but not change them: that takes permission to update the HTTP settings and OAuth clients.', + )} +

+ )} + +
+
+ + update({ adminUrl: e.target.value })} + /> + {urlProblem(draft.adminUrl) &&

{urlProblem(draft.adminUrl)}

} +
+ {current.environmentAdminUrl && ( + + )} +
+ +
+
+ + update({ webmailUrl: e.target.value })} + /> + {urlProblem(draft.webmailUrl) && ( +

{urlProblem(draft.webmailUrl)}

+ )} +
+ {current.environmentWebmailUrl && ( + + )} + +
+
+ {t('frontEnds.secret', 'Client secret')} + {current.environmentWebmailClientSecret ? ( + {t('frontEnds.secretFromEnv', 'from INBUXA_WEBMAIL_CLIENT_SECRET')} + ) : current.webmailClientSecretSet && !draft.forgetSecret ? ( + {t('frontEnds.secretStored', 'stored')} + ) : ( + {t('frontEnds.secretNone', 'none')} + )} +
+ {current.environmentWebmailClientSecret ? ( +

+ {t( + 'frontEnds.secretEnvHint', + 'This node takes the secret from its environment, which wins at every start. To set it here, remove INBUXA_WEBMAIL_CLIENT_SECRET from every node first.', + )} +

+ ) : draft.webmailClientSecret ? ( +
+

+ {t( + 'frontEnds.secretNewHint', + 'Put this in the webmail’s OAUTH_CLIENT_SECRET now: the server keeps only a hash, so it can’t be shown again after you save.', + )} +

+
+ {draft.webmailClientSecret} + + +
+
+ ) : ( + !readOnly && ( +
+ + {current.webmailClientSecretSet && !draft.webmailUrl.trim() && ( + + )} +
+ ) + )} + {!current.environmentWebmailClientSecret && ( +

+ {t( + 'frontEnds.secretRules', + 'Made here, at least {{min}} characters, never shown again once saved. A new one stops the webmail signing in until it has the new one too.', + { min: MIN_SECRET_LENGTH }, + )} +

+ )} +
+
+ +
+ {draft.extraOrigins.length === 0 ? ( +

{t('frontEnds.originsNone', 'None.')}

+ ) : ( +
    + {draft.extraOrigins.map((o) => ( +
  • + {o} + {!readOnly && ( + + )} +
  • + ))} +
+ )} + {!readOnly && ( +
+
+ { + setNewOrigin(e.target.value); + setOriginError(null); + }} + onKeyDown={(e) => { + if (e.key === 'Enter') { + e.preventDefault(); + addOrigin(); + } + }} + /> + +
+ {originError &&

{originError}

} +
+ )} +
+ + {cutOff && ( +
+

+ {t( + 'frontEnds.cutOff', + 'You’re using the console at {{origin}}. After this change the server stops accepting requests from it, unless INBUXA_CORS_EXTRA_ORIGINS on every node names it, so this console would stop working. Change it from a console at the new address, or keep this one in Other origins.', + { origin: window.location.origin }, + )} +

+ +
+ )} + + {!readOnly && ( +
+ {problem && dirty && {problem}} + {dirty && !problem && ( + {t('frontEnds.unsaved', 'Unsaved changes')} + )} + + +
+ )} + + {current.changedAt && ( +

+ {t('frontEnds.changed', 'Last changed {{when}} by account {{who}}.', { + when: new Date(current.changedAt * 1000).toLocaleString(), + who: current.changedBy ?? '?', + })} +

+ )} + + )} + + { + if (!open && blocker.state === 'blocked') blocker.reset?.(); + }} + > + + + {t('form.unsavedChangesTitle', 'Unsaved changes')} + + {t('form.unsavedChanges', 'You have unsaved changes. Are you sure you want to leave?')} + + + + blocker.reset?.()}>{t('form.stay', 'Stay')} + blocker.proceed?.()}>{t('form.leave', 'Leave')} + + + +
+ ); +} diff --git a/src/features/frontEnds/api.ts b/src/features/frontEnds/api.ts new file mode 100644 index 0000000..aa9471e --- /dev/null +++ b/src/features/frontEnds/api.ts @@ -0,0 +1,47 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +/** INBUXA: `inbuxa:FrontEnds/get` and `/set` (contract C-4). */ + +import { getAccountId, jmapRequest } from '@/services/jmap/client'; +import { fromServer, type FrontEnds } from './model'; + +const CAPABILITY = 'urn:inbuxa:jmap'; + +/** The server has no `inbuxa:FrontEnds` (an older server, or inside a tenant). */ +export class FrontEndsUnavailable extends Error {} + +async function call(method: string, args: Record, signal?: AbortSignal) { + const responses = await jmapRequest([[method, { accountId: getAccountId('x:Account'), ...args }, '0']], signal, [ + CAPABILITY, + ]); + const [name, result] = responses[0] ?? []; + const r = result as Record & { type?: string; description?: string }; + if (name !== method) { + if (r?.type === 'unknownMethod' || r?.type === 'unknownCapability') throw new FrontEndsUnavailable(r.type); + throw new Error(r?.description ?? r?.type ?? `${method} failed`); + } + return r; +} + +export async function fetchFrontEnds(signal?: AbortSignal): Promise { + const result = await call('inbuxa:FrontEnds/get', { ids: null }, signal); + const item = (result.list as Record[] | undefined)?.[0]; + if (!item) throw new FrontEndsUnavailable('not found'); + return fromServer(item); +} + +/** Saves `patch`; throws with the server's reason if it refused. */ +export async function saveFrontEnds(patch: Record): Promise { + const result = await call('inbuxa:FrontEnds/set', { update: { singleton: patch } }); + const failed = ( + result.notUpdated as Record | undefined + )?.singleton; + if (failed) { + const where = failed.properties?.length ? ` (${failed.properties.join(', ')})` : ''; + throw new Error(`${failed.description ?? failed.type ?? 'Not saved'}${where}`); + } +} diff --git a/src/features/frontEnds/model.test.ts b/src/features/frontEnds/model.test.ts new file mode 100644 index 0000000..28310a3 --- /dev/null +++ b/src/features/frontEnds/model.test.ts @@ -0,0 +1,170 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { describe, expect, it } from 'vitest'; +import { + cutsOffThisConsole, + draftOf, + draftProblem, + fromServer, + newSecret, + originOf, + originProblem, + patchOf, + urlProblem, + type FrontEnds, +} from './model'; + +const base: FrontEnds = { + adminUrl: 'https://admin.example.com', + webmailUrl: null, + webmailClientSecretSet: false, + extraOrigins: [], + environmentAdminUrl: null, + environmentWebmailUrl: null, + environmentWebmailClientSecret: false, + changedAt: null, + changedBy: null, +}; +const SECRET = 'x'.repeat(32); + +describe('reading the singleton', () => { + it('takes what the server sends and treats empty strings as unset', () => { + const f = fromServer({ + id: 'singleton', + adminUrl: '', + webmailUrl: 'https://mail.example.com', + webmailClientSecret: null, + webmailClientSecretSet: true, + extraOrigins: ['https://a.example', 7], + environmentAdminUrl: 'https://env.example', + environmentWebmailUrl: null, + environmentWebmailClientSecret: false, + changedAt: 1_700_000_000, + changedBy: 'b', + }); + expect(f.adminUrl).toBeNull(); + expect(f.webmailUrl).toBe('https://mail.example.com'); + expect(f.webmailClientSecretSet).toBe(true); + expect(f.extraOrigins).toEqual(['https://a.example']); + expect(f.environmentAdminUrl).toBe('https://env.example'); + expect(f.changedAt).toBe(1_700_000_000); + }); +}); + +describe('origins', () => { + it('match the server: lowercased, default port dropped, path ignored', () => { + expect(originOf('HTTPS://Admin.Example.com:443/console/')).toBe('https://admin.example.com'); + expect(originOf('http://h:8080/x')).toBe('http://h:8080'); + expect(originOf('ftp://h')).toBeNull(); + expect(originOf('nonsense')).toBeNull(); + }); + + it('extra origins are origins only, once each', () => { + expect(originProblem('https://a.example', [])).toBeNull(); + expect(originProblem('https://a.example/path', [])).toMatch(/no path/); + expect(originProblem('a.example', [])).toMatch(/http or https/); + expect(originProblem('https://A.example:443', ['https://a.example'])).toMatch(/Already/); + expect(originProblem(' ', [])).toMatch(/Type/); + }); + + it('addresses may have a path but no credentials, query or fragment', () => { + expect(urlProblem('')).toBeNull(); + expect(urlProblem('https://mail.example.com/webmail')).toBeNull(); + expect(urlProblem('mail.example.com')).toMatch(/https:\/\//); + expect(urlProblem('https://u:p@mail.example.com')).toMatch(/user name/); + expect(urlProblem('https://mail.example.com/?a=1')).toMatch(/query/); + }); +}); + +describe('what gets saved', () => { + it('nothing when nothing changed, a trailing slash included', () => { + expect(patchOf({ ...draftOf(base), adminUrl: 'https://admin.example.com/' }, base)).toEqual({}); + }); + + it('only the properties that changed, with empty as null', () => { + const d = { ...draftOf(base), adminUrl: '', extraOrigins: ['https://B.example:443'] }; + expect(patchOf(d, base)).toEqual({ adminUrl: null, extraOrigins: ['https://b.example'] }); + }); + + it('a new secret is sent; forgetting one sends null', () => { + const stored = { ...base, webmailClientSecretSet: true }; + expect(patchOf({ ...draftOf(stored), webmailClientSecret: SECRET }, stored)).toEqual({ + webmailClientSecret: SECRET, + }); + expect(patchOf({ ...draftOf(stored), forgetSecret: true }, stored)).toEqual({ webmailClientSecret: null }); + expect(patchOf({ ...draftOf(base), forgetSecret: true }, base)).toEqual({}); + }); +}); + +describe('what the server would refuse', () => { + it('a webmail address needs a secret from somewhere', () => { + const d = { ...draftOf(base), webmailUrl: 'https://mail.example.com' }; + expect(draftProblem(d, base)).toMatch(/client secret/); + expect(draftProblem({ ...d, webmailClientSecret: SECRET }, base)).toBeNull(); + expect(draftProblem(d, { ...base, webmailClientSecretSet: true })).toBeNull(); + expect(draftProblem(d, { ...base, environmentWebmailClientSecret: true })).toBeNull(); + expect(draftProblem({ ...d, forgetSecret: true }, { ...base, webmailClientSecretSet: true })).toMatch( + /client secret/, + ); + }); + + it('a short secret, or one the environment would replace', () => { + expect(draftProblem({ ...draftOf(base), webmailClientSecret: 'short' }, base)).toMatch(/32/); + expect( + draftProblem( + { ...draftOf(base), webmailClientSecret: SECRET }, + { ...base, environmentWebmailClientSecret: true }, + ), + ).toMatch(/INBUXA_WEBMAIL_CLIENT_SECRET/); + }); + + it('a bad address', () => { + expect(draftProblem({ ...draftOf(base), adminUrl: 'admin.example.com' }, base)).toMatch(/Console address/); + }); +}); + +describe('cutting off the console in use', () => { + const here = 'https://admin.example.com'; + const api = 'https://mail.example.com'; + + it('warns when the address it is used from is taken out', () => { + const d = { ...draftOf(base), adminUrl: 'https://console.example.com' }; + expect(cutsOffThisConsole(d, base, here, api)).toBe(true); + }); + + it('not when it stays allowed another way', () => { + const moved = { ...draftOf(base), adminUrl: 'https://console.example.com' }; + expect(cutsOffThisConsole({ ...moved, extraOrigins: [here] }, base, here, api)).toBe(false); + expect(cutsOffThisConsole(moved, { ...base, environmentAdminUrl: `${here}/` }, here, api)).toBe(false); + expect(cutsOffThisConsole({ ...draftOf(base), adminUrl: `${here}/new-path` }, base, here, api)).toBe(false); + }); + + it('not for a console the server serves itself, or one never on the list', () => { + const cleared = { ...draftOf(base), adminUrl: '' }; + expect(cutsOffThisConsole(cleared, base, api, api)).toBe(false); + expect(cutsOffThisConsole(cleared, base, 'http://localhost:5174', api)).toBe(false); + }); + + it('also when it was only an extra origin', () => { + const f = { ...base, adminUrl: null, extraOrigins: [here] }; + expect(cutsOffThisConsole({ ...draftOf(f), extraOrigins: [] }, f, here, api)).toBe(true); + }); +}); + +describe('a new secret', () => { + it('is 48 URL-safe characters, long enough for the server', () => { + const s = newSecret(); + expect(s).toMatch(/^[A-Za-z0-9_-]{48}$/); + expect(s.length).toBeGreaterThanOrEqual(32); + expect(newSecret()).not.toBe(s); + }); + + it('uses every byte without bias', () => { + const s = newSecret((b) => b.map((_, i) => i * 4 + 3)); + expect(s.slice(0, 4)).toBe('DHLP'); + }); +}); diff --git a/src/features/frontEnds/model.ts b/src/features/frontEnds/model.ts new file mode 100644 index 0000000..d17b046 --- /dev/null +++ b/src/features/frontEnds/model.ts @@ -0,0 +1,180 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +/** + * INBUXA: `inbuxa:FrontEnds`, where the server's front ends are (contract + * C-4): the console's and the webmail's addresses, the webmail's client + * secret, and further origins allowed to call the server from a browser. + * + * The server registers each address as an OAuth client's redirect URI and + * builds its cross-origin allowlist from them, together with what its + * environment says (`INBUXA_ADMIN_URL`, `INBUXA_WEBMAIL_URL`, + * `INBUXA_CORS_EXTRA_ORIGINS`). Redirect URIs are only ever added; the + * allowlist is rebuilt on every save, so an origin taken out stops working. + */ + +/** The singleton as `inbuxa:FrontEnds/get` returns it. */ +export interface FrontEnds { + adminUrl: string | null; + webmailUrl: string | null; + webmailClientSecretSet: boolean; + extraOrigins: string[]; + /** What this node's environment says: the node that answered. */ + environmentAdminUrl: string | null; + environmentWebmailUrl: string | null; + environmentWebmailClientSecret: boolean; + /** Milliseconds since the epoch, or null if never set. */ + changedAt: number | null; + /** The account id of whoever set it last. */ + changedBy: string | null; +} + +/** What the page edits. A secret typed here is sent once and never read back. */ +export interface Draft { + adminUrl: string; + webmailUrl: string; + /** A new secret to send; empty means keep what's stored. */ + webmailClientSecret: string; + /** Forget the stored secret (only when no webmail address is left). */ + forgetSecret: boolean; + extraOrigins: string[]; +} + +/** The fewest characters the server takes for the webmail's secret. */ +export const MIN_SECRET_LENGTH = 32; + +export function draftOf(f: FrontEnds): Draft { + return { + adminUrl: f.adminUrl ?? '', + webmailUrl: f.webmailUrl ?? '', + webmailClientSecret: '', + forgetSecret: false, + extraOrigins: [...f.extraOrigins], + }; +} + +export function fromServer(v: Record): FrontEnds { + const str = (x: unknown) => (typeof x === 'string' && x.trim() !== '' ? x : null); + const list = Array.isArray(v.extraOrigins) ? v.extraOrigins.filter((o): o is string => typeof o === 'string') : []; + return { + adminUrl: str(v.adminUrl), + webmailUrl: str(v.webmailUrl), + webmailClientSecretSet: v.webmailClientSecretSet === true, + extraOrigins: list, + environmentAdminUrl: str(v.environmentAdminUrl), + environmentWebmailUrl: str(v.environmentWebmailUrl), + environmentWebmailClientSecret: v.environmentWebmailClientSecret === true, + changedAt: typeof v.changedAt === 'number' ? v.changedAt : null, + changedBy: str(v.changedBy), + }; +} + +/** + * The origin (`scheme://host[:port]`) of an http or https address, lowercased + * and without a default port, as the server works it out; null otherwise. + */ +export function originOf(url: string): string | null { + let u: URL; + try { + u = new URL(url.trim()); + } catch { + return null; + } + if (u.protocol !== 'http:' && u.protocol !== 'https:') return null; + if (!u.hostname) return null; + // URL already drops a default port and lowercases the scheme and host. + return `${u.protocol}//${u.host}`.toLowerCase(); +} + +/** Why an address can't be a front end's, or null if it can. Empty is fine: it clears it. */ +export function urlProblem(url: string): string | null { + const t = url.trim(); + if (t === '') return null; + let u: URL; + try { + u = new URL(t); + } catch { + return 'Not a web address. Start it with https://'; + } + if (u.protocol !== 'http:' && u.protocol !== 'https:') return 'Must start with https:// or http://'; + if (!u.hostname) return 'Has no host name'; + if (u.username || u.password) return 'Must not carry a user name or password'; + if (u.search || u.hash) return 'Must not have a query or a #fragment'; + return null; +} + +/** Why an extra origin can't be added, or null. */ +export function originProblem(origin: string, already: string[]): string | null { + const t = origin.trim(); + if (t === '') return 'Type an origin first'; + const o = originOf(t); + if (!o) return 'Not an http or https origin, such as https://mail.example.com'; + const u = new URL(t); + if ((u.pathname && u.pathname !== '/') || u.search || u.hash) return 'Just the origin: no path after the host'; + if (already.some((a) => originOf(a) === o)) return 'Already in the list'; + return null; +} + +/** Why the draft can't be saved, or null. */ +export function draftProblem(d: Draft, f: FrontEnds): string | null { + const admin = urlProblem(d.adminUrl); + if (admin) return `Console address: ${admin}`; + const webmail = urlProblem(d.webmailUrl); + if (webmail) return `Webmail address: ${webmail}`; + const secret = d.webmailClientSecret; + if (secret && f.environmentWebmailClientSecret) + return 'This node takes the webmail’s secret from INBUXA_WEBMAIL_CLIENT_SECRET, so one can’t be set here.'; + if (secret && secret.length < MIN_SECRET_LENGTH) + return `The webmail’s secret needs at least ${MIN_SECRET_LENGTH} characters.`; + const hasSecret = f.environmentWebmailClientSecret || secret !== '' || (f.webmailClientSecretSet && !d.forgetSecret); + if (d.webmailUrl.trim() && !hasSecret) return 'The webmail needs a client secret to be registered.'; + return null; +} + +const normUrl = (s: string) => { + const t = s.trim().replace(/\/+$/, ''); + return t === '' ? null : t; +}; + +/** Just what changed, as an `inbuxa:FrontEnds/set` update; empty if nothing did. */ +export function patchOf(d: Draft, f: FrontEnds): Record { + const patch: Record = {}; + const admin = normUrl(d.adminUrl); + if (admin !== (f.adminUrl ? normUrl(f.adminUrl) : null)) patch.adminUrl = admin; + const webmail = normUrl(d.webmailUrl); + if (webmail !== (f.webmailUrl ? normUrl(f.webmailUrl) : null)) patch.webmailUrl = webmail; + if (d.webmailClientSecret) patch.webmailClientSecret = d.webmailClientSecret; + else if (d.forgetSecret && f.webmailClientSecretSet) patch.webmailClientSecret = null; + const next = d.extraOrigins.map((o) => originOf(o) ?? o.trim()); + const same = next.length === f.extraOrigins.length && next.every((o, i) => o === f.extraOrigins[i]); + if (!same) patch.extraOrigins = next; + return patch; +} + +/** + * Whether saving would take the console's own origin off the server's + * allowlist, so this page (and the rest of the console) stops working once + * saved. Only for a console on another origin than the server's: one the + * server serves itself needs no allowlist. The environment's + * `INBUXA_CORS_EXTRA_ORIGINS` isn't shown over JMAP, so an origin only it + * names is still reported; the warning says so. + */ +export function cutsOffThisConsole(d: Draft, f: FrontEnds, consoleOrigin: string, apiOrigin: string): boolean { + const here = originOf(consoleOrigin); + if (!here || here === originOf(apiOrigin)) return false; + const allowed = (adminUrl: string | null, extra: string[]) => + [adminUrl, f.environmentAdminUrl, ...extra].some((u) => u !== null && originOf(u) === here); + return allowed(f.adminUrl, f.extraOrigins) && !allowed(normUrl(d.adminUrl), d.extraOrigins); +} + +type Fill = (bytes: Uint8Array) => Uint8Array; + +/** A new secret for the webmail: 48 characters from a URL-safe alphabet. */ +export function newSecret(random: Fill = (b) => crypto.getRandomValues(b)): string { + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; + // 64 symbols: each byte's low six bits pick one without bias. + return Array.from(random(new Uint8Array(48)), (b) => alphabet[b & 63]).join(''); +} diff --git a/src/i18n/en.json b/src/i18n/en.json index f097bd5..4705c6f 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -3150,5 +3150,47 @@ "addHint": "Opens the server’s registration page in a new window, where you confirm with your password and then your passkey.", "blocked": "The browser blocked the new window. Open the registration page here; the link works for 10 minutes and only once:", "openRegistration": "Open the registration page" + }, + "frontEnds": { + "fromEnvironment": "Also {{value}}, from {{name}} on the node that answered. Both are used.", + "copied": "Copied", + "copy": "Copy", + "unavailable": "This server doesn’t keep its front ends’ addresses. Use its environment.", + "saved": "Front ends saved", + "savedDetail": "Their sign-in is registered and every node now accepts requests from these addresses.", + "notSaved": "Not saved", + "title": "Front ends", + "subtitle": "Where inbuxa Admin and the webmail are served from. Saving registers their sign-in and lets browsers on these addresses call the server, on every node.", + "readOnly": "You can see these but not change them: that takes permission to update the HTTP settings and OAuth clients.", + "adminTitle": "inbuxa Admin", + "adminHint": "The console’s address when it isn’t served by the server itself, such as https://admin.example.com.", + "address": "Address", + "webmailTitle": "Webmail", + "webmailHint": "The webmail’s address, the same as its PUBLIC_URL plus BASE_PATH. It signs in through the server with a client secret that both sides know.", + "secret": "Client secret", + "secretFromEnv": "from INBUXA_WEBMAIL_CLIENT_SECRET", + "secretStored": "stored", + "secretNone": "none", + "secretEnvHint": "This node takes the secret from its environment, which wins at every start. To set it here, remove INBUXA_WEBMAIL_CLIENT_SECRET from every node first.", + "secretNewHint": "Put this in the webmail’s OAUTH_CLIENT_SECRET now: the server keeps only a hash, so it can’t be shown again after you save.", + "secretDiscard": "Don’t change it", + "secretReplace": "Make a new secret", + "secretMake": "Make a secret", + "secretKeep": "Keep the stored secret", + "secretForget": "Forget the stored secret", + "secretRules": "Made here, at least {{min}} characters, never shown again once saved. A new one stops the webmail signing in until it has the new one too.", + "originsTitle": "Other origins", + "originsHint": "Further sites allowed to call the server from a browser, such as a second webmail. Just the origin: https://host or https://host:port.", + "originsNone": "None.", + "originRemove": "Remove {{origin}}", + "originAdd": "Add an origin", + "add": "Add", + "cutOff": "You’re using the console at {{origin}}. After this change the server stops accepting requests from it, unless INBUXA_CORS_EXTRA_ORIGINS on every node names it, so this console would stop working. Change it from a console at the new address, or keep this one in Other origins.", + "cutOffOk": "I understand; save anyway", + "unsaved": "Unsaved changes", + "undo": "Undo changes", + "saving": "Saving…", + "save": "Save", + "changed": "Last changed {{when}} by account {{who}}." } } diff --git a/src/lib/layout.ts b/src/lib/layout.ts index e4cba50..4d2f455 100644 --- a/src/lib/layout.ts +++ b/src/lib/layout.ts @@ -74,6 +74,8 @@ const PAGES: Record = { 'CustomComponent/StoreCheck': { enterprise: false, visible: (c) => holds('sysStoreCheck', c) }, 'CustomComponent/StoreSnapshots': { enterprise: false, visible: (c) => holds('sysStoreSnapshot', c) }, 'CustomComponent/BlobStoreChanges': { enterprise: false, visible: (c) => holds('sysBlobStoreChange', c) }, + // inbuxa:FrontEnds is read with the HTTP settings' permission; server administrators only. + 'CustomComponent/FrontEnds': readOnly('sysHttp'), // Guided jobs are for whoever may read everything they change. 'Wizard/certificates': readOnly('sysDomain', 'sysAcmeProvider', 'sysCertificate'), 'Wizard/certificate-order': readOnly('sysDomain', 'sysAcmeProvider', 'sysCertificate'), diff --git a/src/lib/settingsLayout.ts b/src/lib/settingsLayout.ts index 9d63771..7028c13 100644 --- a/src/lib/settingsLayout.ts +++ b/src/lib/settingsLayout.ts @@ -189,7 +189,12 @@ export const SETTINGS_CATEGORIES: SettingsCategory[] = [ }, { name: 'Web', - pages: [p('x:Http', 'HTTP'), p('x:Http/HttpSecurity', 'HTTP security'), p('x:HttpForm', 'Contact form')], + pages: [ + p('x:Http', 'HTTP'), + p('CustomComponent/FrontEnds', 'Front ends'), + p('x:Http/HttpSecurity', 'HTTP security'), + p('x:HttpForm', 'Contact form'), + ], }, { name: 'DNS',