5 Commits
12 changed files with 362 additions and 32 deletions

No files matched your search

+17
View File
@@ -2,6 +2,23 @@
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
## [2.0.6] - 2026-11-13
### Fixed
- OIDC sign-in keeps a query already present in the provider's `authorization_endpoint` (for example Casdoor's `?organization=`) and appends its own parameters with `&`.
- Clicking or hovering a list row in Safari now targets that row instead of the last row of the table.
## [2.0.5] - 2026-11-05
### Added
- Passkey registration under Account > Credentials.
### Changed
### Fixed
- Dates and numbers are formatted with the account locale, or the browser's preferred language when the account uses the default, instead of always en-US.
- The last setup screen no longer tells users to sign in with credentials that were never created when an external directory is used.
## [2.0.4] - 2026-11-02
### Added
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "stalwart-webui",
"private": true,
"version": "2.0.4",
"version": "2.0.6",
"stalwart": {
"minServerVersion": "1.0.0"
},
@@ -78,4 +78,4 @@
"typescript-eslint": "^8.71.2",
"vite": "^8.3.4"
}
}
}
@@ -104,10 +104,15 @@ export function SuccessScreen({
<div className="rounded-xl bg-info-soft p-4 text-info">
<p className="text-sm">
<span className="font-medium">{t('bootstrap.nextStepLabel', 'Next step:')}</span>{' '}
{t(
'bootstrap.nextStepBody',
'restart Stalwart for the new configuration to take effect. Once restarted, sign in with the credentials above to continue administering your server.',
)}
{hasCredentials
? t(
'bootstrap.nextStepBody',
'restart Stalwart for the new configuration to take effect. Once restarted, sign in with the credentials above to continue administering your server.',
)
: t(
'bootstrap.nextStepBodyNoCredentials',
'restart Stalwart for the new configuration to take effect. No administrator account was created because accounts come from the external directory. Once restarted, sign in with the recovery administrator set in STALWART_RECOVERY_ADMIN and assign an administrator role to a directory account.',
)}
</p>
</div>
</div>
+3 -1
View File
@@ -9,6 +9,7 @@ import { deepMerge, resolveForm, resolveObject, type ResolvedView } from '@/lib/
import { SECRET_MASK } from '@/lib/jmapUtils';
import { embeddedEntries, isRecord, resolveEmbedded } from '@/lib/embeddedSchema';
import { isMissingValue, isRequiredField, isUnchangedSecret } from '@/lib/fieldRules';
import { widgetTraits } from '@/components/forms/widgets/registry';
import type { BlobUpload } from '@/services/jmap/client';
import type { JmapSetError, ValidationError } from '@/types/jmap';
import type { Field, FieldType, Fields, Form, FormField, Schema } from '@/types/schema';
@@ -297,7 +298,8 @@ export interface RenderableSection {
}
export function buildSections(form: Form | null, fields: Fields | null, mode: FormMode): RenderableSection[] {
const visible = (field: Field) => !(mode === 'create' && field.update === 'serverSet');
const visible = (field: Field) =>
mode === 'create' ? field.update !== 'serverSet' : !widgetTraits(field.type).createOnly;
if (!form) {
if (!fields) return [];
const all = Object.entries(fields.properties)
@@ -40,6 +40,12 @@ const OtpAuthField = lazy(() =>
import('@/components/forms/widgets/OtpAuthField').then((m) => ({ default: m.OtpAuthField })),
);
const PasskeyRegistrationField = lazy(() =>
import('@/components/forms/widgets/PasskeyRegistrationField').then((m) => ({
default: m.PasskeyRegistrationField,
})),
);
function narrow<T extends FieldType>(props: WidgetProps): WidgetProps<T> {
return props as WidgetProps<T>;
}
@@ -82,6 +88,12 @@ export function FieldControl(props: WidgetProps) {
<OtpAuthField {...narrow<FieldTypeObject>(props)} />
</Suspense>
);
case 'object:x:PasskeyRegistration':
return (
<Suspense fallback={null}>
<PasskeyRegistrationField {...narrow<FieldTypeObject>(props)} />
</Suspense>
);
case 'objectList':
return <ObjectListWidget {...narrow<FieldTypeObjectList>(props)} />;
case 'set':
@@ -0,0 +1,251 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useEffect, useId, useState, type KeyboardEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { FingerprintPattern, Loader2, ShieldCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useFormContext } from '@/components/forms/formContext';
import { getAccountId, jmapCall, jmapGetOne } from '@/services/jmap/client';
import { JmapMethodError } from '@/services/errors';
import type { WidgetProps } from '@/components/forms/widgets/types';
import type { FieldTypeObject } from '@/types/schema';
interface PasskeyRegistrationValue {
clientDataJson?: string;
attestationObject?: string;
}
interface CredentialDescriptorJson {
type: 'public-key';
id: string;
}
interface CreationOptionsJson {
rp: { id: string; name: string };
user: { id: string; name: string; displayName: string };
challenge: string;
pubKeyCredParams: { type: 'public-key'; alg: number }[];
timeout: number;
excludeCredentials: CredentialDescriptorJson[];
authenticatorSelection: AuthenticatorSelectionCriteria;
attestation: AttestationConveyancePreference;
}
interface RegistrationOptionsResponse {
accountId: string;
publicKey: CreationOptionsJson;
}
type PublicKeyCredentialStatic = {
parseCreationOptionsFromJSON?: (options: CreationOptionsJson) => PublicKeyCredentialCreationOptions;
};
function toBase64Url(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function fromBase64Url(value: string): Uint8Array<ArrayBuffer> {
let base64 = value.replace(/-/g, '+').replace(/_/g, '/');
while (base64.length % 4) base64 += '=';
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
function parseCreationOptions(options: CreationOptionsJson): PublicKeyCredentialCreationOptions {
const parse = (window.PublicKeyCredential as unknown as PublicKeyCredentialStatic).parseCreationOptionsFromJSON;
if (typeof parse === 'function') return parse(options);
return {
rp: options.rp,
user: { ...options.user, id: fromBase64Url(options.user.id) },
challenge: fromBase64Url(options.challenge),
pubKeyCredParams: options.pubKeyCredParams,
timeout: options.timeout,
excludeCredentials: options.excludeCredentials.map((credential) => ({
type: credential.type,
id: fromBase64Url(credential.id),
})),
authenticatorSelection: options.authenticatorSelection,
attestation: options.attestation,
};
}
function isPasskeySupported(): boolean {
return typeof window !== 'undefined' && !!window.PublicKeyCredential && !!navigator.credentials?.create;
}
function isRegistered(value: unknown): boolean {
const registration = value as PasskeyRegistrationValue | null | undefined;
return !!registration?.clientDataJson && !!registration.attestationObject;
}
export function PasskeyRegistrationField({ value, onChange, readOnly }: WidgetProps<FieldTypeObject>) {
const { t } = useTranslation();
const { mode } = useFormContext();
const secretId = useId();
const otpId = useId();
const [currentSecret, setCurrentSecret] = useState('');
const [otpCode, setOtpCode] = useState('');
const [otpRequired, setOtpRequired] = useState(false);
const [waiting, setWaiting] = useState(false);
const [error, setError] = useState<string | null>(null);
const isActive = mode === 'create' && !readOnly;
useEffect(() => {
if (!isActive) return;
const controller = new AbortController();
jmapGetOne('x:AccountPassword', 'singleton', undefined, { signal: controller.signal })
.then((password) => {
const otpAuth = password?.otpAuth as { otpUrl?: string | null } | undefined;
setOtpRequired(!!otpAuth?.otpUrl);
})
.catch(() => {
if (!controller.signal.aborted) setOtpRequired(true);
});
return () => controller.abort();
}, [isActive]);
if (!isActive) return null;
if (!isPasskeySupported()) {
return (
<p className="text-sm text-muted-foreground">
{t('passkey.unsupported', 'This browser does not support passkeys.')}
</p>
);
}
if (isRegistered(value)) {
return (
<div className="flex items-center gap-2 rounded-xl bg-muted p-4 text-sm">
<ShieldCheck className="h-4 w-4 shrink-0" aria-hidden="true" />
<span className="flex-1">{t('passkey.ready', 'Passkey created. Save to add it to your account.')}</span>
<Button type="button" variant="ghost" size="sm" onClick={() => onChange(null)}>
{t('passkey.createAgain', 'Create again')}
</Button>
</div>
);
}
const createPasskey = async () => {
setError(null);
if (!currentSecret) {
setError(t('passkey.secretRequired', 'Enter your current password to create a passkey.'));
return;
}
const code = otpCode.trim();
if (otpRequired && !code) {
setError(t('passkey.otpRequired', 'Enter your current authenticator code to create a passkey.'));
return;
}
setWaiting(true);
try {
const options = await jmapCall<RegistrationOptionsResponse>('x:Passkey/registrationOptions', {
accountId: getAccountId('x:Passkey'),
currentSecret,
...(code ? { otpCode: code } : {}),
});
const credential = await navigator.credentials.create({ publicKey: parseCreationOptions(options.publicKey) });
if (!(credential instanceof PublicKeyCredential)) throw new Error('No passkey was returned');
const response = credential.response as AuthenticatorAttestationResponse;
setCurrentSecret('');
setOtpCode('');
onChange({
clientDataJson: toBase64Url(response.clientDataJSON),
attestationObject: toBase64Url(response.attestationObject),
});
} catch (err) {
if (err instanceof DOMException && (err.name === 'NotAllowedError' || err.name === 'AbortError')) return;
if (err instanceof DOMException && err.name === 'InvalidStateError') {
setError(t('passkey.alreadyRegistered', 'This device already holds a passkey for your account.'));
} else if (err instanceof JmapMethodError && err.description) {
setError(err.description);
} else {
console.error('Passkey registration failed', err);
setError(t('passkey.createFailed', 'The passkey could not be created. Please try again.'));
}
} finally {
setWaiting(false);
}
};
const submitOnEnter = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
e.preventDefault();
if (!waiting) void createPasskey();
}
};
return (
<div className="space-y-4 rounded-xl bg-muted p-4">
<p className="text-xs text-muted-foreground">
{t(
'passkey.createPrompt',
'Confirm your password, then follow the prompt from your browser to create a passkey on this device or a security key.',
)}
</p>
<div className="space-y-1.5">
<Label htmlFor={secretId} className="text-sm font-medium">
{t('passkey.currentSecretLabel', 'Current password')}
</Label>
<Input
id={secretId}
type="password"
autoComplete="current-password"
value={currentSecret}
onChange={(e) => setCurrentSecret(e.target.value)}
onKeyDown={submitOnEnter}
disabled={waiting}
className="max-w-sm"
/>
</div>
{otpRequired && (
<div className="space-y-1.5">
<Label htmlFor={otpId} className="text-sm font-medium">
{t('otp.currentCodeLabel', 'Current code')}
</Label>
<Input
id={otpId}
type="text"
inputMode="numeric"
autoComplete="one-time-code"
placeholder="123456"
value={otpCode}
onChange={(e) => setOtpCode(e.target.value.replace(/\s+/g, ''))}
onKeyDown={submitOnEnter}
disabled={waiting}
maxLength={10}
className="font-mono tracking-widest text-center max-w-[12rem]"
/>
</div>
)}
{error && (
<p className="text-sm text-destructive" role="alert">
{error}
</p>
)}
<div className="flex items-center justify-end">
<Button type="button" size="sm" onClick={() => void createPasskey()} disabled={waiting}>
{waiting ? (
<Loader2 className="animate-spin" aria-hidden="true" />
) : (
<FingerprintPattern aria-hidden="true" />
)}
{waiting ? t('passkey.waiting', 'Waiting for your passkey') : t('passkey.create', 'Create passkey')}
</Button>
</div>
</div>
);
}
+5
View File
@@ -14,6 +14,7 @@ export interface WidgetTraits {
labelMode: LabelMode;
readOnlyAsValue: boolean;
layout: RowLayout;
createOnly?: true;
}
export type WidgetKey =
@@ -33,6 +34,7 @@ export type WidgetKey =
| 'object:x:Expression'
| 'object:x:Rate'
| 'object:x:OtpAuth'
| 'object:x:PasskeyRegistration'
| 'objectList'
| 'set'
| 'set:enum'
@@ -65,6 +67,8 @@ export function widgetKey(type: FieldType): WidgetKey {
return 'object:x:Rate';
case 'x:OtpAuth':
return 'object:x:OtpAuth';
case 'x:PasskeyRegistration':
return 'object:x:PasskeyRegistration';
default:
return 'object';
}
@@ -100,6 +104,7 @@ const TRAITS: Record<WidgetKey, WidgetTraits> = {
'object:x:Expression': { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
'object:x:Rate': { labelMode: 'control', readOnlyAsValue: false, layout: 'side' },
'object:x:OtpAuth': { labelMode: 'none', readOnlyAsValue: false, layout: 'block' },
'object:x:PasskeyRegistration': { labelMode: 'none', readOnlyAsValue: false, layout: 'block', createOnly: true },
objectList: { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
set: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
'set:enum': { labelMode: 'group', readOnlyAsValue: true, layout: 'side' },
+35 -12
View File
@@ -4,8 +4,8 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import type { ReactNode } from 'react';
import { Link } from 'react-router-dom';
import type { MouseEvent, ReactNode } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Checkbox } from '@/components/ui/checkbox';
@@ -39,8 +39,26 @@ interface ListTableProps {
const BODY_CELL = 'px-3.5 py-2.5 first:pl-5 last:pr-5 align-middle';
const STRETCHED_LINK =
"font-semibold text-foreground hover:underline focus-visible:outline-none after:absolute after:inset-0 after:content-[''] focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-ring";
const ROW_LINK =
'rounded-sm font-semibold text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
const INTERACTIVE = 'a, button, input, label, select, textarea, [role="checkbox"], [data-row-controls]';
function isRowClick(event: MouseEvent<HTMLTableRowElement>): boolean {
const target = event.target;
return (
event.button === 0 &&
!event.defaultPrevented &&
!event.metaKey &&
!event.ctrlKey &&
!event.shiftKey &&
!event.altKey &&
target instanceof Element &&
event.currentTarget.contains(target) &&
target.closest(INTERACTIVE) === null &&
window.getSelection()?.isCollapsed !== false
);
}
export function ListTable({
caption,
@@ -60,6 +78,7 @@ export function ListTable({
busy,
}: ListTableProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const colSpan = columns.length + (selection ? 1 : 0) + (renderRowActions ? 1 : 0);
const rows = items.flatMap((item) => {
const id = itemId(item);
@@ -111,12 +130,20 @@ export function ListTable({
<tr
key={id}
className={cn(
'relative border-t border-border transition-colors duration-150',
'border-t border-border transition-colors duration-150',
href && 'cursor-pointer',
selection?.isSelected(id) ? 'bg-highlight/70' : 'hover:bg-muted/55',
)}
onClick={
href
? (event) => {
if (isRowClick(event)) void navigate(href);
}
: undefined
}
>
{selection && (
<td className="relative z-10 w-10 py-2.5 pl-5 pr-2 align-middle">
<td data-row-controls className="w-10 py-2.5 pl-5 pr-2 align-middle">
<Checkbox
checked={selection.isSelected(id)}
onCheckedChange={() => selection.toggle(id)}
@@ -139,11 +166,7 @@ export function ListTable({
return (
<th key={col.name} scope="row" className={cn(BODY_CELL, 'text-left font-normal')}>
{href ? (
<Link
to={href}
className={STRETCHED_LINK}
aria-label={isEmptyValue(value) ? label : undefined}
>
<Link to={href} className={ROW_LINK} aria-label={isEmptyValue(value) ? label : undefined}>
{content}
</Link>
) : (
@@ -159,7 +182,7 @@ export function ListTable({
);
})}
{renderRowActions && (
<td className="relative z-10 py-1.5 pl-2 pr-3 text-right align-middle">
<td data-row-controls className="py-1.5 pl-2 pr-3 text-right align-middle">
{renderRowActions(item, id, label)}
</td>
)}
+14
View File
@@ -23,6 +23,7 @@
"finishSetup": "Finish setup",
"loadingSetup": "Loading setup...",
"nextStepBody": "restart Stalwart for the new configuration to take effect. Once restarted, sign in with the credentials above to continue administering your server.",
"nextStepBodyNoCredentials": "restart Stalwart for the new configuration to take effect. No administrator account was created because accounts come from the external directory. Once restarted, sign in with the recovery administrator set in STALWART_RECOVERY_ADMIN and assign an administrator role to a directory account.",
"nextStepLabel": "Next step:",
"noConfirm": "The server did not confirm the update.",
"stepOf": "Step {{current}} of {{total}}",
@@ -408,6 +409,19 @@
"statusDisabled": "Two-factor authentication is not enabled.",
"statusEnabled": "Two-factor authentication is enabled."
},
"passkey": {
"alreadyRegistered": "This device already holds a passkey for your account.",
"create": "Create passkey",
"createAgain": "Create again",
"createFailed": "The passkey could not be created. Please try again.",
"createPrompt": "Confirm your password, then follow the prompt from your browser to create a passkey on this device or a security key.",
"currentSecretLabel": "Current password",
"otpRequired": "Enter your current authenticator code to create a passkey.",
"ready": "Passkey created. Save to add it to your account.",
"secretRequired": "Enter your current password to create a passkey.",
"unsupported": "This browser does not support passkeys.",
"waiting": "Waiting for your passkey"
},
"rate": {
"count": "Count",
"per": "per",
+4 -9
View File
@@ -4,21 +4,16 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import i18next from 'i18next';
import { SIZE_UNITS } from '@/lib/durationFormat';
import { DEFAULT_LOCALE, useAccountStore } from '@/stores/accountStore';
export type DateInput = string | number | Date;
function baseLanguage(tag: string): string {
return tag.toLowerCase().split(/[-_]/)[0];
}
export function getFormatLocale(): string {
const { locale } = useAccountStore.getState();
if (locale && locale !== DEFAULT_LOCALE) return locale;
const nav = typeof navigator !== 'undefined' ? (navigator.languages ?? [navigator.language]) : [];
const lang = i18next.resolvedLanguage || i18next.language;
if (!lang || lang === 'cimode') return nav[0] || 'en';
const wanted = baseLanguage(lang);
return nav.find((tag) => tag && baseLanguage(tag) === wanted) ?? lang;
return nav[0] || DEFAULT_LOCALE;
}
const numberFormats = new Map<string, Intl.NumberFormat>();
+7 -3
View File
@@ -235,7 +235,7 @@ export async function startAuthFlow(username: string, returnUrl?: string | null)
params.set('resource', resource);
}
window.location.href = `${authorization_endpoint}?${params.toString()}`;
window.location.href = appendQuery(authorization_endpoint, params);
}
export function getStoredOAuthData() {
@@ -276,6 +276,10 @@ export function buildEndSessionUrl(endSessionEndpoint: string, postLogoutRedirec
client_id: clientId,
post_logout_redirect_uri: postLogoutRedirectUri,
});
const sep = endSessionEndpoint.includes('?') ? '&' : '?';
return `${endSessionEndpoint}${sep}${params.toString()}`;
return appendQuery(endSessionEndpoint, params);
}
function appendQuery(endpoint: string, params: URLSearchParams): string {
const sep = endpoint.includes('?') ? '&' : '?';
return `${endpoint}${sep}${params.toString()}`;
}
+3 -1
View File
@@ -7,6 +7,8 @@
import { create } from 'zustand';
import { isCommunityEdition } from '@/lib/permissions';
export const DEFAULT_LOCALE = 'en-US';
export type Edition = 'enterprise' | 'community' | (string & {});
export interface AccountState {
@@ -22,7 +24,7 @@ export interface AccountState {
export const useAccountStore = create<AccountState>()((set, get) => ({
permissions: [],
edition: 'community',
locale: 'en',
locale: DEFAULT_LOCALE,
setAccountInfo: (permissions, edition, locale) => {
set({ permissions, edition, locale });