Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add security settings pages (#2413)

Leendert de Borstb18cc116ac41
diff --git a/apps/web/src/components/alerts/MessageWarning.tsx b/apps/web/src/components/alerts/MessageWarning.tsx
index eff48961d..458b4516d 100644
--- a/apps/web/src/components/alerts/MessageWarning.tsx
+++ b/apps/web/src/components/alerts/MessageWarning.tsx
@@ -7,7 +7,7 @@ const MessageWarning: React.FC<{ message: string }> = ({ message }) => {
if (!message) {
return null;
}
- return <div className="p-4 mb-4 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200 rounded-lg">{message}</div>;
+ return <div className="p-4 mb-4 text-sm bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200 rounded-lg">{message}</div>;
};
export default MessageWarning;
diff --git a/apps/web/src/components/alerts/ServerValidationErrors.tsx b/apps/web/src/components/alerts/ServerValidationErrors.tsx
index 94ab0e2d2..e06ec5373 100644
--- a/apps/web/src/components/alerts/ServerValidationErrors.tsx
+++ b/apps/web/src/components/alerts/ServerValidationErrors.tsx
@@ -5,12 +5,12 @@ import AlertMessageError from '@/components/alerts/AlertMessageError';
/**
* List of form-level errors.
*/
-const ServerValidationErrors: React.FC<{ errors: string[] }> = ({ errors }) => {
+const ServerValidationErrors: React.FC<{ errors: string[]; className?: string }> = ({ errors, className = '' }) => {
if (errors.length === 0) {
return null;
}
return (
- <div className="messages-container">
+ <div className={`messages-container ${className}`.trim()}>
{errors.map((error, index) => (
<AlertMessageError key={index} message={error} />
))}
diff --git a/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx b/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx
index ea940b4b3..3f41671f6 100644
--- a/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx
+++ b/apps/web/src/components/settings/security/QuickVaultUnlockSection.tsx
@@ -1,7 +1,6 @@
-import React, { useCallback, useEffect, useImperativeHandle, useState, forwardRef } from 'react';
+import React, { useCallback, useImperativeHandle, useState, forwardRef } from 'react';
import { useTranslation } from 'react-i18next';
-import LoadingIndicator from '@/components/loading/LoadingIndicator';
import SecuritySection, { type SectionHandle } from '@/components/settings/security/SecuritySection';
import Button from '@/components/shared/Button';
import { useAuth } from '@/context/AuthContext';
@@ -16,17 +15,13 @@ const QuickVaultUnlockSection = forwardRef<SectionHandle>((_, ref) => {
const { t } = useTranslation();
const auth = useAuth();
const notifications = useNotifications();
- const [isLoading, setIsLoading] = useState(true);
- const [enabled, setEnabled] = useState(false);
+ const [enabled, setEnabled] = useState(() => WebAuthnService.isEnabled());
const tk = 'components.main.settings.security.quickVaultUnlockSection';
const loadData = useCallback(async (): Promise<void> => {
- setIsLoading(true);
setEnabled(WebAuthnService.isEnabled());
- setIsLoading(false);
}, []);
useImperativeHandle(ref, () => ({ loadData }), [loadData]);
- useEffect(() => void loadData(), [loadData]);
/**
* Create a passkey and encrypt the session keys with it.
@@ -58,7 +53,7 @@ const QuickVaultUnlockSection = forwardRef<SectionHandle>((_, ref) => {
return (
<SecuritySection title={t(`${tk}.Title`)}>
- {isLoading ? <LoadingIndicator /> : enabled ? (
+ {enabled ? (
<>
<div className="mb-3 text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.EnabledDescription`)}</div>
<Button color="danger" onClick={() => void disable()}>{t(`${tk}.DisableButton`)}</Button>
diff --git a/apps/web/src/pages/auth/Login.tsx b/apps/web/src/pages/auth/Login.tsx
index 7c08822fa..565f35300 100644
--- a/apps/web/src/pages/auth/Login.tsx
+++ b/apps/web/src/pages/auth/Login.tsx
@@ -219,7 +219,7 @@ const Login: React.FC = () => {
{t('components.auth.login.TwoFactorAuthenticationTitle')}
</h2>
- <ServerValidationErrors errors={errors} />
+ <ServerValidationErrors errors={errors} className="mb-4" />
<p className="text-gray-700 dark:text-gray-300 mb-6">{t('components.auth.login.TwoFactorAuthenticationDescription')}</p>
<div className="w-full">
@@ -259,7 +259,7 @@ const Login: React.FC = () => {
{t('components.auth.login.RecoveryCodeVerificationTitle')}
</h2>
- <ServerValidationErrors errors={errors} />
+ <ServerValidationErrors errors={errors} className="mb-4" />
<p className="text-gray-700 dark:text-gray-300 mb-6">
{t('components.auth.login.RecoveryCodeDescription')}
diff --git a/apps/web/src/pages/auth/Unlock.tsx b/apps/web/src/pages/auth/Unlock.tsx
index 5bfaec148..41099f893 100644
--- a/apps/web/src/pages/auth/Unlock.tsx
+++ b/apps/web/src/pages/auth/Unlock.tsx
@@ -209,7 +209,7 @@ const Unlock: React.FC = () => {
<div className="mb-6">
<p className="text-base font-normal text-gray-500 dark:text-gray-400 mb-4">{t('pages.auth.unlock.QuickUnlockDescription')}</p>
- <ServerValidationErrors errors={errors} />
+ <ServerValidationErrors errors={errors} className="mb-4" />
<div className="flex space-x-4">
<button type="button" onClick={() => void unlockWithWebAuthn()} className="flex-grow inline-flex items-center justify-center px-5 py-2 text-base font-medium text-center text-white rounded-lg bg-primary-700 hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 sm:w-auto dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">
diff --git a/apps/web/src/pages/settings/security/ChangePassword.tsx b/apps/web/src/pages/settings/security/ChangePassword.tsx
new file mode 100644
index 000000000..5cb163f47
--- /dev/null
+++ b/apps/web/src/pages/settings/security/ChangePassword.tsx
@@ -0,0 +1,151 @@
+import { IncorrectPasswordError, MasterPasswordService, PasswordChangedElsewhereError } from '@aliasvault/client/auth/MasterPasswordService';
+import { MIN_ACCEPTED_PASSWORD_LENGTH } from '@aliasvault/client/utilities/PasswordStrength';
+import React, { useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import PasswordInputField from '@/components/auth/PasswordInputField';
+import Breadcrumb from '@/components/shared/Breadcrumb';
+import Card from '@/components/shared/Card';
+import FormLabel from '@/components/shared/FormLabel';
+import H1 from '@/components/shared/H1';
+import PasswordStrengthIndicator from '@/components/shared/PasswordStrengthIndicator';
+import { useDb } from '@/context/DbContext';
+import { useLoading } from '@/context/LoadingContext';
+import { useNotifications } from '@/context/NotificationContext';
+import { useWebApi } from '@/context/WebApiContext';
+import { usePageTitle } from '@/hooks/usePageTitle';
+import { useVaultSync } from '@/hooks/useVaultSync';
+import { apiErrorMessage } from '@/utils/ApiErrors';
+
+const VALIDATION_DEBOUNCE_MS = 800;
+
+/**
+ * The change master password page.
+ */
+const ChangePassword: React.FC = () => {
+ const { t } = useTranslation();
+ const dbContext = useDb();
+ const webApi = useWebApi();
+ const notifications = useNotifications();
+ const { showLoading, hideLoading } = useLoading();
+ const { syncVault } = useVaultSync();
+ const tk = 'components.main.pages.settings.security.changePassword';
+ usePageTitle(t(`${tk}.PageTitle`));
+
+ const [currentPassword, setCurrentPassword] = useState('');
+ const [newPassword, setNewPassword] = useState('');
+ const [newPasswordConfirm, setNewPasswordConfirm] = useState('');
+ const [validationError, setValidationError] = useState('');
+ const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ /**
+ * Check length and match of the new password.
+ */
+ const validate = (password: string, confirm: string): void => {
+ if (password.trim().length > 0 && password.length < MIN_ACCEPTED_PASSWORD_LENGTH) {
+ setValidationError(t('validationMessages.PasswordMinLengthGeneric', { 0: MIN_ACCEPTED_PASSWORD_LENGTH }));
+ return;
+ }
+ if (confirm.trim().length > 0 && password !== confirm) {
+ setValidationError(t('validationMessages.PasswordsDoNotMatchGeneric'));
+ return;
+ }
+ setValidationError('');
+ };
+
+ /**
+ * Validate after a typing pause.
+ */
+ const onNewPasswordChange = (value: string): void => {
+ setNewPassword(value);
+ setValidationError('');
+ if (debounceTimer.current) {
+ clearTimeout(debounceTimer.current);
+ }
+ debounceTimer.current = setTimeout(() => validate(value, newPasswordConfirm), VALIDATION_DEBOUNCE_MS);
+ };
+
+ /**
+ * Validate right away.
+ */
+ const onConfirmChange = (value: string): void => {
+ setNewPasswordConfirm(value);
+ validate(newPassword, value);
+ };
+
+ const isSubmitEnabled = currentPassword.trim().length > 0 && newPassword.trim().length > 0 && newPasswordConfirm.trim().length > 0 && newPassword === newPasswordConfirm && validationError.length === 0 && newPassword.length >= MIN_ACCEPTED_PASSWORD_LENGTH;
+
+ /**
+ * Submit password change.
+ */
+ const changePassword = async (e: React.FormEvent): Promise<void> => {
+ e.preventDefault();
+ setValidationError('');
+ if (newPassword.length < MIN_ACCEPTED_PASSWORD_LENGTH) {
+ setValidationError(t('validationMessages.PasswordMinLengthGeneric', { 0: MIN_ACCEPTED_PASSWORD_LENGTH }));
+ return;
+ }
+
+ showLoading(t(`${tk}.ChangingPasswordMessage`));
+ notifications.clearMessages();
+ try {
+ await MasterPasswordService.changePassword(webApi, currentPassword, newPassword);
+ setCurrentPassword('');
+ setNewPassword('');
+ setNewPasswordConfirm('');
+ notifications.addSuccessMessage(t(`${tk}.PasswordChangedSuccessfully`), true);
+ } catch (error) {
+ console.error('Password change failed:', error);
+ if (error instanceof IncorrectPasswordError) {
+ notifications.addErrorMessage(t('apiErrors.PASSWORD_MISMATCH'), true);
+ } else if (error instanceof PasswordChangedElsewhereError) {
+ notifications.addErrorMessage(t('common.errors.passwordChanged'), true);
+ } else {
+ notifications.addErrorMessage(apiErrorMessage(error, t, t(`${tk}.FailedToChangePassword`)), true);
+ }
+ return;
+ } finally {
+ hideLoading();
+ }
+
+ // Sync afterwards to ensure the local state and the server match.
+ await syncVault();
+ };
+
+ return (
+ <>
+ <div className="grid grid-cols-1 px-4 pt-6 xl:grid-cols-3 xl:gap-4 dark:bg-gray-900">
+ <div className="mb-4 col-span-full xl:mb-2">
+ <Breadcrumb items={[{ displayName: t('sharedResources.Home'), url: '/', showHomeIcon: true }, { displayName: t(`${tk}.BreadcrumbSecuritySettings`), url: '/settings/security' }, { displayName: t(`${tk}.BreadcrumbChangePassword`) }]} />
+ <H1>{t(`${tk}.PageTitle`)}</H1>
+ <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.PageDescription`)}</p>
+ </div>
+ </div>
+
+ <Card>
+ <form onSubmit={changePassword} className="space-y-4">
+ <div>
+ <FormLabel htmlFor="currentPassword">{t(`${tk}.CurrentPasswordLabel`)}</FormLabel>
+ <PasswordInputField id="currentPassword" value={currentPassword} onValueChange={setCurrentPassword} placeholder={t(`${tk}.CurrentPasswordLabel`)} />
+ </div>
+ <div>
+ <FormLabel htmlFor="newPassword">{t(`${tk}.NewPasswordLabel`)}</FormLabel>
+ <PasswordInputField id="newPassword" value={newPassword} onValueChange={onNewPasswordChange} placeholder={t(`${tk}.NewPasswordLabel`)} />
+ <PasswordStrengthIndicator password={newPassword} />
+ </div>
+ <div>
+ <FormLabel htmlFor="newPasswordConfirm">{t(`${tk}.ConfirmNewPasswordLabel`)}</FormLabel>
+ <PasswordInputField id="newPasswordConfirm" value={newPasswordConfirm} onValueChange={onConfirmChange} placeholder={t(`${tk}.ConfirmNewPasswordLabel`)} />
+ </div>
+ {validationError.length > 0 && <div className="mt-2 text-sm text-red-600 dark:text-red-400">{validationError}</div>}
+ <button type="submit" disabled={!isSubmitEnabled} className={`w-full bg-primary-500 text-white py-2 px-4 rounded-md hover:bg-primary-600 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 transition duration-150 ease-in-out ${isSubmitEnabled ? '' : 'opacity-50 cursor-not-allowed'}`}>
+ {t(`${tk}.ChangePasswordButton`)}
+ </button>
+ </form>
+ </Card>
+ {dbContext.isOffline && <div className="mx-4 text-sm text-red-600 dark:text-red-400">{t('common.errors.serverNotAvailable')}</div>}
+ </>
+ );
+};
+
+export default ChangePassword;
diff --git a/apps/web/src/pages/settings/security/DeleteAccount.tsx b/apps/web/src/pages/settings/security/DeleteAccount.tsx
new file mode 100644
index 000000000..4caf90466
--- /dev/null
+++ b/apps/web/src/pages/settings/security/DeleteAccount.tsx
@@ -0,0 +1,141 @@
+import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
+import React, { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+import MessageWarning from '@/components/alerts/MessageWarning';
+import Breadcrumb from '@/components/shared/Breadcrumb';
+import Button from '@/components/shared/Button';
+import Card from '@/components/shared/Card';
+import FormLabel from '@/components/shared/FormLabel';
+import H1 from '@/components/shared/H1';
+import InputTextField from '@/components/shared/InputTextField';
+import { useAuth } from '@/context/AuthContext';
+import { useLoading } from '@/context/LoadingContext';
+import { useNotifications } from '@/context/NotificationContext';
+import { useWebApi } from '@/context/WebApiContext';
+import { usePageTitle } from '@/hooks/usePageTitle';
+import { apiErrorMessage } from '@/utils/ApiErrors';
+
+import type { DeleteAccountInitiateRequest, DeleteAccountInitiateResponse, DeleteAccountRequest } from '@aliasvault/models/webapi';
+
+/**
+ * The delete account page: confirm the username, then prove the
+ * password over SRP and delete.
+ */
+const DeleteAccount: React.FC = () => {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const auth = useAuth();
+ const webApi = useWebApi();
+ const notifications = useNotifications();
+ const { showLoading, hideLoading } = useLoading();
+ const tk = 'components.main.pages.settings.security.deleteAccount';
+ usePageTitle(t(`${tk}.PageTitle`));
+
+ const [showPasswordConfirm, setShowPasswordConfirm] = useState(false);
+ const [username, setUsername] = useState('');
+ const [password, setPassword] = useState('');
+ const currentUsername = auth.username ?? '';
+
+ /**
+ * First step: the typed username must match the account.
+ */
+ const confirmUsername = (e: React.FormEvent): void => {
+ e.preventDefault();
+ notifications.clearMessages();
+ if (username.length === 0) {
+ notifications.addErrorMessage(t(`${tk}.UsernameRequired`), true);
+ return;
+ }
+ if (username.trim().toLowerCase() !== currentUsername.trim().toLowerCase()) {
+ notifications.addErrorMessage(t(`${tk}.UsernameDoesNotMatch`), true);
+ return;
+ }
+ setShowPasswordConfirm(true);
+ };
+
+ /**
+ * Second step: prove the password and delete the account.
+ */
+ const deleteAccountConfirmed = async (e: React.FormEvent): Promise<void> => {
+ e.preventDefault();
+ if (password.length === 0) {
+ notifications.addErrorMessage(t('validationMessages.PasswordRequired'), true);
+ return;
+ }
+ showLoading(t(`${tk}.DeletingAccountMessage`));
+ notifications.clearMessages();
+ try {
+ const initiate = await webApi.post<DeleteAccountInitiateRequest, DeleteAccountInitiateResponse>('Auth/delete-account/initiate', { username: currentUsername });
+ const prepared = await SrpAuthService.prepareCredentials(password, initiate.salt, initiate.encryptionSettings);
+ const proof = await SrpAuthService.deriveClientProof(initiate.salt, initiate.srpIdentity, prepared.passwordHashString, initiate.serverEphemeral);
+ await webApi.post<DeleteAccountRequest, unknown>('Auth/delete-account/confirm', { username: currentUsername, clientPublicEphemeral: proof.clientPublicEphemeral, clientSessionProof: proof.clientSessionProof }, false);
+ navigate('/user/logout');
+ } catch (error) {
+ console.error('Account deletion failed:', error);
+ notifications.addErrorMessage(apiErrorMessage(error, t, t(`${tk}.ErrorProcessingRequest`)), true);
+ } finally {
+ hideLoading();
+ }
+ };
+
+ return (
+ <>
+ <div className="grid grid-cols-1 px-4 pt-6 xl:grid-cols-3 xl:gap-4 dark:bg-gray-900">
+ <div className="mb-4 col-span-full xl:mb-2">
+ <Breadcrumb items={[{ displayName: t('sharedResources.Home'), url: '/', showHomeIcon: true }, { displayName: t(`${tk}.BreadcrumbSecuritySettings`), url: '/settings/security' }, { displayName: t(`${tk}.BreadcrumbDeleteAccount`) }]} />
+ <H1>{t(`${tk}.PageTitle`)}</H1>
+ </div>
+ </div>
+
+ <Card>
+ {!showPasswordConfirm ? (
+ <>
+ <MessageWarning message={t(`${tk}.PermanentActionWarning`)} />
+ <div className="mt-4 mb-6 text-sm text-gray-600 dark:text-gray-400">
+ <p className="mb-2">{t(`${tk}.PleaseNote`)}</p>
+ <ul className="list-disc list-inside space-y-2">
+ <li>{t(`${tk}.VaultsDeletedNote`)}</li>
+ <li>{t(`${tk}.EmailAliasesOrphanedNote`)}</li>
+ <li>{t(`${tk}.AccountCannotBeRecoveredNote`)}</li>
+ </ul>
+ </div>
+ <form onSubmit={confirmUsername}>
+ <div className="mb-4">
+ <FormLabel htmlFor="username">{t(`${tk}.ConfirmUsernameLabel`)}</FormLabel>
+ <InputTextField id="username" type="text" value={username} onValueChange={setUsername} />
+ </div>
+ <div className="flex space-x-3">
+ <Button type="submit" color="danger">{t(`${tk}.ContinueWithAccountDeletion`)}</Button>
+ <Button type="button" color="secondary" onClick={() => navigate('/settings/security')}>{t('sharedResources.Cancel')}</Button>
+ </div>
+ </form>
+ </>
+ ) : (
+ <>
+ <MessageWarning message={t(`${tk}.FinalWarning`)} />
+ <div className="mt-4 mb-6 text-sm text-gray-600 dark:text-gray-400">
+ <p className="mb-2">{t(`${tk}.PleaseNote`)}</p>
+ <ul className="list-disc list-inside space-y-2">
+ <li>{t(`${tk}.DeletionIrreversibleNote`)}</li>
+ </ul>
+ </div>
+ <form onSubmit={deleteAccountConfirmed}>
+ <div className="mb-4">
+ <FormLabel htmlFor="password">{t(`${tk}.EnterPasswordLabel`)}</FormLabel>
+ <InputTextField id="password" type="password" value={password} onValueChange={setPassword} />
+ </div>
+ <div className="flex space-x-3">
+ <Button type="submit" color="danger">{t(`${tk}.DeleteMyAccount`)}</Button>
+ <Button type="button" color="secondary" onClick={() => navigate('/settings/security')}>{t('sharedResources.Cancel')}</Button>
+ </div>
+ </form>
+ </>
+ )}
+ </Card>
+ </>
+ );
+};
+
+export default DeleteAccount;
diff --git a/apps/web/src/pages/settings/security/Disable2Fa.tsx b/apps/web/src/pages/settings/security/Disable2Fa.tsx
new file mode 100644
index 000000000..aad29f513
--- /dev/null
+++ b/apps/web/src/pages/settings/security/Disable2Fa.tsx
@@ -0,0 +1,91 @@
+import React, { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+import AlertMessageError from '@/components/alerts/AlertMessageError';
+import LoadingIndicator from '@/components/loading/LoadingIndicator';
+import Breadcrumb from '@/components/shared/Breadcrumb';
+import Card from '@/components/shared/Card';
+import H1 from '@/components/shared/H1';
+import { useNotifications } from '@/context/NotificationContext';
+import { useWebApi } from '@/context/WebApiContext';
+import { usePageTitle } from '@/hooks/usePageTitle';
+
+/**
+ * The disable two-factor authentication page.
+ */
+const Disable2Fa: React.FC = () => {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const webApi = useWebApi();
+ const notifications = useNotifications();
+ const tk = 'components.main.pages.settings.security.disable2Fa';
+ usePageTitle(t(`${tk}.PageTitle`));
+ const [isLoading, setIsLoading] = useState(true);
+ const hasStarted = useRef(false);
+
+ useEffect(() => {
+ if (hasStarted.current) {
+ return;
+ }
+ hasStarted.current = true;
+
+ /**
+ * Only show the page when two-factor is actually on.
+ */
+ const check = async (): Promise<void> => {
+ try {
+ const status = await webApi.get<{ twoFactorEnabled: boolean }>('TwoFactorAuth/status');
+ if (!status.twoFactorEnabled) {
+ notifications.addErrorMessage(t(`${tk}.TwoFactorNotEnabled`));
+ navigate('/settings/security');
+ return;
+ }
+ } catch (error) {
+ console.error('Failed to read 2FA status:', error);
+ }
+ setIsLoading(false);
+ };
+ void check();
+ }, [navigate, notifications, t, webApi]);
+
+ /**
+ * Switch two-factor off.
+ */
+ const disableTwoFactor = async (): Promise<void> => {
+ try {
+ await webApi.post<null, unknown>('TwoFactorAuth/disable', null, false);
+ notifications.addSuccessMessage(t(`${tk}.TwoFactorDisabledSuccess`));
+ navigate('/settings/security');
+ } catch (error) {
+ console.error('Failed to disable 2FA:', error);
+ notifications.addErrorMessage(t(`${tk}.FailedToDisable2Fa`), true);
+ }
+ };
+
+ if (isLoading) {
+ return <LoadingIndicator />;
+ }
+
+ return (
+ <>
+ <div className="grid grid-cols-1 px-4 pt-6 xl:grid-cols-3 xl:gap-4 dark:bg-gray-900">
+ <div className="mb-4 col-span-full xl:mb-2">
+ <Breadcrumb items={[{ displayName: t('sharedResources.Home'), url: '/', showHomeIcon: true }, { displayName: t(`${tk}.BreadcrumbSecuritySettings`), url: '/settings/security' }, { displayName: t(`${tk}.BreadcrumbDisable2Fa`) }]} />
+ <H1>{t(`${tk}.PageTitle`)}</H1>
+ <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.PageDescription`)}</p>
+ </div>
+ </div>
+
+ <Card>
+ <AlertMessageError hasTopMargin={false} message={t(`${tk}.WarningMessage`)} />
+ <div className="mb-3 mt-4 text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.StatusMessage`)}</div>
+ <button type="button" onClick={() => void disableTwoFactor()} className="bg-red-500 text-white py-2 px-4 rounded-md hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 transition duration-150 ease-in-out">
+ {t(`${tk}.ConfirmDisableButton`)}
+ </button>
+ </Card>
+ </>
+ );
+};
+
+export default Disable2Fa;
diff --git a/apps/web/src/pages/settings/security/Enable2Fa.tsx b/apps/web/src/pages/settings/security/Enable2Fa.tsx
new file mode 100644
index 000000000..f17cebb78
--- /dev/null
+++ b/apps/web/src/pages/settings/security/Enable2Fa.tsx
@@ -0,0 +1,133 @@
+import QRCode from 'qrcode';
+import React, { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import LoadingIndicator from '@/components/loading/LoadingIndicator';
+import Breadcrumb from '@/components/shared/Breadcrumb';
+import Card from '@/components/shared/Card';
+import H1 from '@/components/shared/H1';
+import { useNotifications } from '@/context/NotificationContext';
+import { useWebApi } from '@/context/WebApiContext';
+import { usePageTitle } from '@/hooks/usePageTitle';
+
+/**
+ * The recovery codes shown once after enabling two-factor authentication.
+ */
+const ShowRecoveryCodes: React.FC<{ recoveryCodes: string[] }> = ({ recoveryCodes }) => {
+ const { t } = useTranslation();
+ const tk = 'components.main.settings.security.showRecoveryCodes';
+ return (
+ <div className="max-w-2xl mx-auto px-4 lg:mt-8">
+ <Card variant="plain">
+ <h3 className="mb-4 text-lg font-medium text-gray-900 dark:text-white">{t(`${tk}.Title`)}</h3>
+ <div className="text-sm text-gray-600 dark:text-gray-400 mb-4">{t(`${tk}.Description`)}</div>
+ <div className="bg-primary-100 border-l-4 border-primary-500 text-primary-700 p-4 mb-4 dark:bg-gray-700 dark:border-primary-500 dark:text-gray-200">
+ <p className="font-semibold">{t(`${tk}.WarningTitle`)}</p>
+ <p>{t(`${tk}.WarningDescription`)}</p>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2" id="recovery-codes">
+ {recoveryCodes.map(code => (
+ <div key={code}>
+ <code className="block p-3 bg-gray-100 dark:bg-gray-700 dark:text-gray-200 rounded border font-mono text-center">{code}</code>
+ </div>
+ ))}
+ </div>
+ </Card>
+ </div>
+ );
+};
+
+/**
+ * The enable two-factor authentication page.
+ */
+const Enable2Fa: React.FC = () => {
+ const { t } = useTranslation();
+ const webApi = useWebApi();
+ const notifications = useNotifications();
+ const tk = 'components.main.pages.settings.security.enable2Fa';
+ usePageTitle(t(`${tk}.PageTitle`));
+
+ const [isLoading, setIsLoading] = useState(true);
+ const [qrCodeDataUrl, setQrCodeDataUrl] = useState('');
+ const [secret, setSecret] = useState('');
+ const [code, setCode] = useState('');
+ const [recoveryCodes, setRecoveryCodes] = useState<string[] | null>(null);
+ const hasStarted = useRef(false);
+
+ useEffect(() => {
+ if (hasStarted.current) {
+ return;
+ }
+ hasStarted.current = true;
+
+ /**
+ * Ask the server for a new authenticator secret and render it as a QR code.
+ */
+ const setup = async (): Promise<void> => {
+ try {
+ const result = await webApi.post<null, { secret: string; qrCodeUrl: string }>('TwoFactorAuth/enable', null);
+ // Spaces every four characters make the secret easier to type over.
+ setSecret((result.secret.match(/.{1,4}/g) ?? []).join(' ').toLowerCase());
+ setQrCodeDataUrl(await QRCode.toDataURL(result.qrCodeUrl, { width: 256, margin: 2 }));
+ } catch (error) {
+ console.error('Failed to start 2FA setup:', error);
+ notifications.addErrorMessage(t(`${tk}.FailedToEnable2Fa`), true);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ void setup();
+ }, [notifications, t, webApi]);
+
+ /**
+ * Verify the first code and switch two-factor on.
+ */
+ const verifySetup = async (e: React.FormEvent): Promise<void> => {
+ e.preventDefault();
+ try {
+ const result = await webApi.post<string, { recoveryCodes: string[] }>('TwoFactorAuth/verify', code);
+ notifications.addSuccessMessage(t(`${tk}.TwoFactorEnabledSuccess`), true);
+ setRecoveryCodes(result.recoveryCodes);
+ } catch (error) {
+ console.error('Failed to verify 2FA code:', error);
+ notifications.addErrorMessage(t(`${tk}.FailedToEnable2Fa`), true);
+ }
+ };
+
+ return (
+ <>
+ <div className="grid grid-cols-1 px-4 pt-6 xl:grid-cols-3 xl:gap-4 dark:bg-gray-900">
+ <div className="mb-4 col-span-full xl:mb-2">
+ <Breadcrumb items={[{ displayName: t('sharedResources.Home'), url: '/', showHomeIcon: true }, { displayName: t(`${tk}.BreadcrumbSecuritySettings`), url: '/settings/security' }, { displayName: t(`${tk}.BreadcrumbEnable2Fa`) }]} />
+ <H1>{t(`${tk}.PageTitle`)}</H1>
+ <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.PageDescription`)}</p>
+ </div>
+ </div>
+
+ {isLoading ? <LoadingIndicator /> : recoveryCodes !== null ? <ShowRecoveryCodes recoveryCodes={recoveryCodes} /> : (
+ <div className="max-w-2xl mx-auto px-4 lg:mt-8">
+ <Card variant="plain">
+ <div className="space-y-6">
+ <div id="authenticator-uri" className="flex justify-center">
+ {qrCodeDataUrl.length > 0 && <img src={qrCodeDataUrl} alt="QR code" className="w-64 h-64" />}
+ </div>
+ <p className="text-sm text-gray-600 dark:text-gray-400 text-center">{t(`${tk}.QrCodeInstructions`)}</p>
+ <div className="text-lg font-mono text-center bg-gray-100 dark:bg-gray-700 p-3 rounded border dark:text-gray-200" id="authenticator-secret">{secret}</div>
+
+ <form onSubmit={verifySetup} className="space-y-4" av-enable="true" av-suppress-save="true">
+ <div>
+ <input id="verificationCode" type="text" value={code} onChange={e => setCode(e.target.value)} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400" placeholder={t(`${tk}.VerificationCodePlaceholder`)} autoComplete="one-time-code" />
+ </div>
+ <button type="submit" className="w-full bg-primary-500 text-white py-2 px-4 rounded-md hover:bg-primary-600 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 transition duration-150 ease-in-out">
+ {t(`${tk}.VerifyAndEnableButton`)}
+ </button>
+ </form>
+ </div>
+ </Card>
+ </div>
+ )}
+ </>
+ );
+};
+
+export default Enable2Fa;