Front ends: a page for where inbuxa Admin and the webmail are served #259

Merged
jcoffey-dev merged 1 commits from feat/front-ends-page into main 2026-11-21 07:23:21 +00:00
8 changed files with 932 additions and 1 deletions

No files matched your search

+5
View File
@@ -183,6 +183,11 @@ const CUSTOM_PAGES: Record<string, ComponentType> = {
() => 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. */
+480
View File
@@ -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 (
<section className="space-y-3 rounded-xl border bg-card p-4">
<div>
<h2 className="font-medium">{title}</h2>
<p className="text-sm text-muted-foreground">{hint}</p>
</div>
{children}
</section>
);
}
/** 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 (
<p className="text-sm text-muted-foreground">
{t('frontEnds.fromEnvironment', 'Also {{value}}, from {{name}} on the node that answered. Both are used.', {
value,
name,
})}
</p>
);
}
function CopyButton({ text }: { text: string }) {
const { t } = useTranslation();
const [done, setDone] = useState(false);
return (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => {
void navigator.clipboard.writeText(text).then(() => {
setDone(true);
setTimeout(() => setDone(false), 1500);
});
}}
>
{done ? <Check className="mr-2 h-4 w-4" /> : <Copy className="mr-2 h-4 w-4" />}
{done ? t('frontEnds.copied', 'Copied') : t('frontEnds.copy', 'Copy')}
</Button>
);
}
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<Load>({ kind: 'loading' });
const [fetches, setFetches] = useState(0);
const [draft, setDraft] = useState<Draft | null>(null);
const [newOrigin, setNewOrigin] = useState('');
const [originError, setOriginError] = useState<string | null>(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<Draft>) => 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 (
<div className="mx-auto max-w-3xl space-y-5">
<PageHeader
icon="globe"
title={t('frontEnds.title', 'Front ends')}
subtitle={t(
'frontEnds.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.',
)}
/>
{load.kind === 'loading' && <LoadingFallback />}
{load.kind === 'error' && (
<div className="rounded-lg border border-dashed p-12 text-center text-muted-foreground">{load.message}</div>
)}
{current && draft && (
<>
{readOnly && (
<p className="rounded-lg border border-dashed p-3 text-sm text-muted-foreground">
{t(
'frontEnds.readOnly',
'You can see these but not change them: that takes permission to update the HTTP settings and OAuth clients.',
)}
</p>
)}
<Section
title={t('frontEnds.adminTitle', 'inbuxa Admin')}
hint={t(
'frontEnds.adminHint',
'The console’s address when it isn’t served by the server itself, such as https://admin.example.com.',
)}
>
<div className="space-y-1">
<Label htmlFor="fe-admin">{t('frontEnds.address', 'Address')}</Label>
<Input
id="fe-admin"
type="url"
autoComplete="off"
placeholder="https://admin.example.com"
value={draft.adminUrl}
disabled={readOnly}
onChange={(e) => update({ adminUrl: e.target.value })}
/>
{urlProblem(draft.adminUrl) && <p className="text-sm text-destructive">{urlProblem(draft.adminUrl)}</p>}
</div>
{current.environmentAdminUrl && (
<FromEnvironment name="INBUXA_ADMIN_URL" value={current.environmentAdminUrl} />
)}
</Section>
<Section
title={t('frontEnds.webmailTitle', 'Webmail')}
hint={t(
'frontEnds.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.',
)}
>
<div className="space-y-1">
<Label htmlFor="fe-webmail">{t('frontEnds.address', 'Address')}</Label>
<Input
id="fe-webmail"
type="url"
autoComplete="off"
placeholder="https://mail.example.com"
value={draft.webmailUrl}
disabled={readOnly}
onChange={(e) => update({ webmailUrl: e.target.value })}
/>
{urlProblem(draft.webmailUrl) && (
<p className="text-sm text-destructive">{urlProblem(draft.webmailUrl)}</p>
)}
</div>
{current.environmentWebmailUrl && (
<FromEnvironment name="INBUXA_WEBMAIL_URL" value={current.environmentWebmailUrl} />
)}
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm font-medium">{t('frontEnds.secret', 'Client secret')}</span>
{current.environmentWebmailClientSecret ? (
<Badge variant="secondary">{t('frontEnds.secretFromEnv', 'from INBUXA_WEBMAIL_CLIENT_SECRET')}</Badge>
) : current.webmailClientSecretSet && !draft.forgetSecret ? (
<Badge variant="secondary">{t('frontEnds.secretStored', 'stored')}</Badge>
) : (
<Badge variant="outline">{t('frontEnds.secretNone', 'none')}</Badge>
)}
</div>
{current.environmentWebmailClientSecret ? (
<p className="text-sm text-muted-foreground">
{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.',
)}
</p>
) : draft.webmailClientSecret ? (
<div className="space-y-2 rounded-lg border border-amber-500/40 bg-amber-500/5 p-3">
<p className="text-sm">
{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.',
)}
</p>
<div className="flex flex-wrap items-center gap-2">
<code className="break-all rounded bg-muted px-2 py-1 text-xs">{draft.webmailClientSecret}</code>
<CopyButton text={draft.webmailClientSecret} />
<Button type="button" variant="ghost" size="sm" onClick={() => update({ webmailClientSecret: '' })}>
{t('frontEnds.secretDiscard', 'Don’t change it')}
</Button>
</div>
</div>
) : (
!readOnly && (
<div className="flex flex-wrap gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => update({ webmailClientSecret: newSecret(), forgetSecret: false })}
>
<KeyRound className="mr-2 h-4 w-4" />
{current.webmailClientSecretSet
? t('frontEnds.secretReplace', 'Make a new secret')
: t('frontEnds.secretMake', 'Make a secret')}
</Button>
{current.webmailClientSecretSet && !draft.webmailUrl.trim() && (
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => update({ forgetSecret: !draft.forgetSecret })}
>
{draft.forgetSecret
? t('frontEnds.secretKeep', 'Keep the stored secret')
: t('frontEnds.secretForget', 'Forget the stored secret')}
</Button>
)}
</div>
)
)}
{!current.environmentWebmailClientSecret && (
<p className="text-xs text-muted-foreground">
{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 },
)}
</p>
)}
</div>
</Section>
<Section
title={t('frontEnds.originsTitle', 'Other origins')}
hint={t(
'frontEnds.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.',
)}
>
{draft.extraOrigins.length === 0 ? (
<p className="text-sm text-muted-foreground">{t('frontEnds.originsNone', 'None.')}</p>
) : (
<ul className="space-y-1">
{draft.extraOrigins.map((o) => (
<li key={o} className="flex items-center justify-between gap-2 rounded-md border px-3 py-1.5 text-sm">
<span className="break-all">{o}</span>
{!readOnly && (
<Button
type="button"
variant="ghost"
size="sm"
aria-label={t('frontEnds.originRemove', 'Remove {{origin}}', { origin: o })}
onClick={() => update({ extraOrigins: draft.extraOrigins.filter((x) => x !== o) })}
>
<X className="h-4 w-4" />
</Button>
)}
</li>
))}
</ul>
)}
{!readOnly && (
<div className="space-y-1">
<div className="flex gap-2">
<Input
aria-label={t('frontEnds.originAdd', 'Add an origin')}
type="url"
autoComplete="off"
placeholder="https://other.example.com"
value={newOrigin}
onChange={(e) => {
setNewOrigin(e.target.value);
setOriginError(null);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
addOrigin();
}
}}
/>
<Button type="button" variant="outline" onClick={addOrigin}>
<Plus className="mr-2 h-4 w-4" />
{t('frontEnds.add', 'Add')}
</Button>
</div>
{originError && <p className="text-sm text-destructive">{originError}</p>}
</div>
)}
</Section>
{cutOff && (
<div className="space-y-2 rounded-lg border border-destructive/50 bg-destructive/5 p-3 text-sm">
<p>
{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 },
)}
</p>
<label className="flex items-center gap-2">
<input type="checkbox" checked={cutOffOk} onChange={(e) => setCutOffOk(e.target.checked)} />
{t('frontEnds.cutOffOk', 'I understand; save anyway')}
</label>
</div>
)}
{!readOnly && (
<div className="flex flex-wrap items-center justify-end gap-3">
{problem && dirty && <span className="text-sm text-destructive">{problem}</span>}
{dirty && !problem && (
<span className="text-xs text-muted-foreground">{t('frontEnds.unsaved', 'Unsaved changes')}</span>
)}
<Button
variant="outline"
disabled={!dirty || saving}
onClick={() => {
setDraft(draftOf(current));
setNewOrigin('');
setOriginError(null);
setCutOffOk(false);
}}
>
{t('frontEnds.undo', 'Undo changes')}
</Button>
<Button disabled={!dirty || !!problem || saving || (cutOff && !cutOffOk)} onClick={() => void save()}>
{saving ? t('frontEnds.saving', 'Saving…') : t('frontEnds.save', 'Save')}
</Button>
</div>
)}
{current.changedAt && (
<p className="text-xs text-muted-foreground">
{t('frontEnds.changed', 'Last changed {{when}} by account {{who}}.', {
when: new Date(current.changedAt * 1000).toLocaleString(),
who: current.changedBy ?? '?',
})}
</p>
)}
</>
)}
<AlertDialog
open={blocker.state === 'blocked'}
onOpenChange={(open) => {
if (!open && blocker.state === 'blocked') blocker.reset?.();
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('form.unsavedChangesTitle', 'Unsaved changes')}</AlertDialogTitle>
<AlertDialogDescription>
{t('form.unsavedChanges', 'You have unsaved changes. Are you sure you want to leave?')}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => blocker.reset?.()}>{t('form.stay', 'Stay')}</AlertDialogCancel>
<AlertDialogAction onClick={() => blocker.proceed?.()}>{t('form.leave', 'Leave')}</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
+47
View File
@@ -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<string, unknown>, 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<string, unknown> & { 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<FrontEnds> {
const result = await call('inbuxa:FrontEnds/get', { ids: null }, signal);
const item = (result.list as Record<string, unknown>[] | 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<string, unknown>): Promise<void> {
const result = await call('inbuxa:FrontEnds/set', { update: { singleton: patch } });
const failed = (
result.notUpdated as Record<string, { type?: string; description?: string; properties?: string[] }> | undefined
)?.singleton;
if (failed) {
const where = failed.properties?.length ? ` (${failed.properties.join(', ')})` : '';
throw new Error(`${failed.description ?? failed.type ?? 'Not saved'}${where}`);
}
}
+170
View File
@@ -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:[email protected]')).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');
});
});
+180
View File
@@ -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<string, unknown>): 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<string, unknown> {
const patch: Record<string, unknown> = {};
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<ArrayBuffer>) => Uint8Array<ArrayBuffer>;
/** 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('');
}
+42
View File
@@ -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}}."
}
}
+2
View File
@@ -74,6 +74,8 @@ const PAGES: Record<string, PageRule> = {
'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'),
+6 -1
View File
@@ -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',