Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add auth flow pages (#2413)
Leendert de Borst7dd95972a21e
diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsxindex 0e7beef2f..e84ac4781 100644--- a/apps/web/src/App.tsx+++ b/apps/web/src/App.tsx@@ -6,7 +6,6 @@ import MainLayout from '@/layouts/MainLayout';import ForgotPassword from '@/pages/auth/ForgotPassword';import Login from '@/pages/auth/Login';import Logout from '@/pages/auth/Logout';-import Register from '@/pages/auth/Register';import Setup from '@/pages/auth/Setup';import Start from '@/pages/auth/Start';import Unlock from '@/pages/auth/Unlock';@@ -15,7 +14,7 @@ import Home from '@/pages/Home';import Sync from '@/pages/sync/Sync';/**- * The route table. Paths are the Blazor client's, so existing links and bookmarks keep working.+ * The route table.*/const App: React.FC = () => (<BrowserRouter>@@ -27,7 +26,6 @@ const App: React.FC = () => (<Route path="/user/login" element={<Login />} /><Route path="/unlock" element={<Unlock />} /><Route path="/unlock/:skipWebAuthn" element={<Unlock />} />- <Route path="/user/register" element={<Register />} /><Route path="/user/forgot-password" element={<ForgotPassword />} /></Route><Route path="/user/setup" element={<Setup />} />diff --git a/apps/web/src/context/ConfirmModalContext.tsx b/apps/web/src/context/ConfirmModalContext.tsxnew file mode 100644index 000000000..034f2246f--- /dev/null+++ b/apps/web/src/context/ConfirmModalContext.tsx@@ -0,0 +1,68 @@+import React, { createContext, useCallback, useContext, useMemo, useRef, useState } from 'react';++import ConfirmModal from '@/components/shared/ConfirmModal';++/**+ * What a confirmation asks.+ */+type ConfirmRequest = {+ title: string;+ message: string;+ confirmText: string;+ cancelText: string;+};++type ConfirmModalContextType = {+ showConfirmation: (title: string, message: string, confirmText: string, cancelText: string) => Promise<boolean>;+}++const ConfirmModalContext = createContext<ConfirmModalContextType | undefined>(undefined);++/**+ * Global confirm dialog.+ */+export const ConfirmModalProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ const [request, setRequest] = useState<ConfirmRequest | null>(null);+ const resolver = useRef<((confirmed: boolean) => void) | null>(null);++ /**+ * Show the confirm dialog and resolve with the user's answer.+ */+ const showConfirmation = useCallback((title: string, message: string, confirmText: string, cancelText: string): Promise<boolean> => {+ return new Promise<boolean>((resolve) => {+ resolver.current = resolve;+ setRequest({ title, message, confirmText, cancelText });+ });+ }, []);++ /**+ * Close the dialog with the user's answer.+ */+ const close = useCallback((confirmed: boolean): void => {+ setRequest(null);+ resolver.current?.(confirmed);+ resolver.current = null;+ }, []);++ const value = useMemo(() => ({ showConfirmation }), [showConfirmation]);++ return (+ <ConfirmModalContext.Provider value={value}>+ {children}+ {request && (+ <ConfirmModal title={request.title} message={request.message} confirmText={request.confirmText} cancelText={request.cancelText} onClose={close} />+ )}+ </ConfirmModalContext.Provider>+ );+};++/**+ * Hook to use the confirm dialog.+ */+export const useConfirmModal = (): ConfirmModalContextType => {+ const context = useContext(ConfirmModalContext);+ if (context === undefined) {+ throw new Error('useConfirmModal must be used within a ConfirmModalProvider');+ }+ return context;+};diff --git a/apps/web/src/layouts/AuthLayout.tsx b/apps/web/src/layouts/AuthLayout.tsxindex 44e68e45d..90e56c61c 100644--- a/apps/web/src/layouts/AuthLayout.tsx+++ b/apps/web/src/layouts/AuthLayout.tsx@@ -13,7 +13,7 @@ const AuthLayout: React.FC = () => {const path = location.pathname.toLowerCase();// Show on login, forgot password and register, not during setup or unlock.- const showLanguageSwitcher = path.includes('/user/login') || path.includes('/user/forgot-password') || path.includes('/user/register') || path.endsWith('/');+ const showLanguageSwitcher = path.includes('/user/login') || path.includes('/user/forgot-password') || path.endsWith('/');return (<div className="flex flex-col items-center justify-center px-6 pt-8 pb-8 mx-auto md:h-screen pt:mt-0 relative">@@ -24,7 +24,7 @@ const AuthLayout: React.FC = () => {)}<Logo /><div className="w-full max-w-xl p-6 sm:p-8 bg-white rounded-lg shadow dark:bg-gray-800">- <GlobalNotificationDisplay marginTop={false} marginBottom={true} />+ <GlobalNotificationDisplay marginTop={false} marginBottom={true} paddingX={false} /><Outlet /></div></div>diff --git a/apps/web/src/pages/auth/ForgotPassword.tsx b/apps/web/src/pages/auth/ForgotPassword.tsxnew file mode 100644index 000000000..281707861--- /dev/null+++ b/apps/web/src/pages/auth/ForgotPassword.tsx@@ -0,0 +1,37 @@+import React from 'react';+import { useTranslation } from 'react-i18next';++import { getAppConfig } from '@/config/AppConfig';+import { usePageTitle } from '@/hooks/usePageTitle';++/** Marker put in the support string's placeholder so the mail link can be replaced. */+const EMAIL_MARKER = '%%EMAIL%%';++/**+ * The lost password page: there is no recovery, only advice.+ */+const ForgotPassword: React.FC = () => {+ const { t } = useTranslation();+ const tk = 'pages.auth.forgotPassword';+ usePageTitle(t(`${tk}.LostPasswordTitle`));+ const supportEmail = getAppConfig().supportEmail;+ const [before, after] = t(`${tk}.ContactSupportWithEmail`, { 0: EMAIL_MARKER }).split(EMAIL_MARKER);++ return (+ <>+ <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">{t(`${tk}.LostPasswordTitle`)}</h2>+ <div className="text-sm space-y-4 text-gray-500 dark:text-gray-400">+ <p>{t(`${tk}.NoRecoveryExplanation`)}</p>+ <p>{t(`${tk}.NewAccountRequired`)}</p>+ <div>+ <h3 className="font-medium mb-2 text-gray-900 dark:text-white">{t(`${tk}.RecentlyChangedPasswordTitle`)}</h3>+ {supportEmail.length > 0+ ? <p>{before}<a href={`mailto:${supportEmail}`} className="text-primary-600 hover:underline dark:text-primary-400">{supportEmail}</a>{after ?? ''}</p>+ : <p>{t(`${tk}.ContactAdministrator`)}</p>}+ </div>+ </div>+ </>+ );+};++export default ForgotPassword;diff --git a/apps/web/src/pages/auth/Login.tsx b/apps/web/src/pages/auth/Login.tsxnew file mode 100644index 000000000..55bfaa130--- /dev/null+++ b/apps/web/src/pages/auth/Login.tsx@@ -0,0 +1,334 @@+import { ApiAuthError } from '@aliasvault/client/api/errors/ApiAuthError';+import { getErrorMessage, hasErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';+import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';+import { ServerUpdateRequiredError } from '@aliasvault/client/api/errors/ServerUpdateRequiredError';+import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';+import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';+import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';+import { getPlatform } from '@aliasvault/client/platform';+import React, { useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Link, useNavigate } from 'react-router-dom';++import ServerValidationErrors from '@/components/alerts/ServerValidationErrors';+import InputTextField from '@/components/auth/InputTextField';+import PasswordInputField from '@/components/auth/PasswordInputField';+import FooterLogin from '@/components/layout/FooterLogin';+import { getAppConfig } from '@/config/AppConfig';+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 { StorageKeys } from '@/utils/StorageKeys';+import { vaultStore } from '@/vault/VaultStore';++import type { LoginResponse, ValidateLoginResponse } from '@aliasvault/models/webapi';++/** Which step of the login the page shows. */+type LoginStep = 'credentials' | 'two-factor' | 'recovery-code';++/**+ * Login page: SRP login with the master password, with 2FA and recovery code steps.+ */+const Login: React.FC = () => {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const auth = useAuth();+ const webApi = useWebApi();+ const notifications = useNotifications();+ const { showLoading, hideLoading } = useLoading();+ const srpUtil = useMemo(() => new SrpLoginService(webApi), [webApi]);+ usePageTitle(t('components.auth.login.PageTitle'));++ const [step, setStep] = useState<LoginStep>('credentials');+ const [username, setUsername] = useState('');+ const [password, setPassword] = useState('');+ const [rememberMe, setRememberMe] = useState(false);+ const [twoFactorCode, setTwoFactorCode] = useState('');+ const [rememberMachine, setRememberMachine] = useState(false);+ const [recoveryCode, setRecoveryCode] = useState('');+ const [errors, setErrors] = useState<string[]>([]);+ const [loginResponse, setLoginResponse] = useState<LoginResponse | null>(null);+ const [passwordHashString, setPasswordHashString] = useState<string | null>(null);+ const [passwordHashBase64, setPasswordHashBase64] = useState<string | null>(null);+ const usernameRef = useRef<HTMLInputElement>(null);+ const twoFactorRef = useRef<HTMLInputElement>(null);++ // Already authenticated: go home.+ useEffect(() => {+ if (auth.isInitialized && auth.isLoggedIn) {+ navigate('/', { replace: true });+ }+ }, [auth.isInitialized, auth.isLoggedIn, navigate]);++ // Show the message a forced logout left behind, and prefill the username it kept.+ useEffect(() => {+ if (auth.globalMessage) {+ notifications.addErrorMessage(auth.globalMessage, true);+ auth.clearGlobalMessage();+ }+ getPlatform().storage.get<string>(StorageKeys.USERNAME).then((saved) => {+ if (saved) {+ setUsername(current => current || saved);+ }+ });+ const timer = setTimeout(() => usernameRef.current?.focus(), 300);+ return (): void => clearTimeout(timer);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ useEffect(() => {+ if (step === 'two-factor') {+ const timer = setTimeout(() => twoFactorRef.current?.focus(), 100);+ return (): void => clearTimeout(timer);+ }+ }, [step]);++ /**+ * Turn a failure into the message(s) the form shows.+ */+ const toErrorMessages = (err: unknown): string[] => {+ console.error('Login error:', err);+ if (err instanceof ClientUpgradeRequiredError) {+ return [t('common.errors.clientVersionNotSupported')];+ }+ if (err instanceof ServerUpdateRequiredError) {+ return [t('common.errors.serverVersionNotSupported')];+ }+ if (err instanceof ApiAuthError) {+ const key = `apiErrors.${err.message}`;+ return [t(key) === key ? err.message : t(key)];+ }+ if (hasErrorCode(err)) {+ return [getErrorMessage(err, t('components.auth.login.LoginErrorMessage'))];+ }+ if (import.meta.env.DEV && err instanceof Error) {+ return [err.message];+ }+ return [t('components.auth.login.LoginErrorMessage')];+ };++ /**+ * Store the tokens and the unlock key, then continue to the sync page which loads the vault.+ */+ const processLoginVerify = async (validateLoginResponse: ValidateLoginResponse, hashBase64: string, response: LoginResponse): Promise<void> => {+ if (!validateLoginResponse.token) {+ throw new Error(t('components.auth.login.LoginRequestErrorMessage'));+ }++ const normalizedUsername = SrpAuthService.normalizeUsername(username);+ await auth.setAuthTokens(normalizedUsername, validateLoginResponse.token.token, validateLoginResponse.token.refreshToken);++ // Fetch the key chain, check the unlock key opens it and cache it; the vault key is derived from the two on demand.+ await VaultKeyService.refreshKeyChain(hashBase64, webApi);+ await vaultStore.storeUnlockKeyDerivationParams({ salt: response.salt, encryptionType: response.encryptionType, encryptionSettings: response.encryptionSettings });+ await vaultStore.storeUnlockKey(hashBase64);++ notifications.clearMessages();+ navigate('/sync', { replace: true });+ };++ /**+ * Username and password step.+ */+ const handleLogin = async (e: React.FormEvent): Promise<void> => {+ e.preventDefault();+ showLoading(t('components.auth.login.LoggingInMessage'));+ setErrors([]);++ try {+ notifications.clearMessages();+ const normalizedUsername = SrpAuthService.normalizeUsername(username);+ const response = await srpUtil.initiateLogin(normalizedUsername);++ // Derive the KEK from the password.+ const prepared = await SrpAuthService.prepareCredentials(password, response.salt, response.encryptionSettings);+ const validateLoginResponse = await srpUtil.validateLogin(normalizedUsername, prepared.passwordHashString, rememberMe, response);++ if (validateLoginResponse.requiresTwoFactor) {+ setLoginResponse(response);+ setPasswordHashString(prepared.passwordHashString);+ setPasswordHashBase64(prepared.passwordHashBase64);+ setStep('two-factor');+ return;+ }++ await processLoginVerify(validateLoginResponse, prepared.passwordHashBase64, response);+ } catch (err) {+ setErrors(toErrorMessages(err));+ } finally {+ hideLoading();+ }+ };++ /**+ * Authenticator code step.+ */+ const handle2Fa = async (e: React.FormEvent): Promise<void> => {+ e.preventDefault();+ showLoading(t('components.auth.login.VerifyingTwoFactorCodeMessage'));+ setErrors([]);++ try {+ if (!loginResponse || !passwordHashString || !passwordHashBase64) {+ throw new Error(t('components.auth.login.LoginRequestErrorMessage'));+ }+ const code = twoFactorCode.trim();+ if (!/^\d{6}$/.test(code)) {+ throw new Error(t('common.errors.invalidCode'));+ }+ const validateLoginResponse = await srpUtil.validateLogin2Fa(username, passwordHashString, rememberMe || rememberMachine, loginResponse, parseInt(code, 10));+ await processLoginVerify(validateLoginResponse, passwordHashBase64, loginResponse);+ } catch (err) {+ setErrors(toErrorMessages(err));+ } finally {+ hideLoading();+ }+ };++ /**+ * Recovery code step.+ */+ const handleRecoveryCode = async (e: React.FormEvent): Promise<void> => {+ e.preventDefault();+ showLoading(t('components.auth.login.VerifyingRecoveryCodeMessage'));+ setErrors([]);++ try {+ if (!loginResponse || !passwordHashString || !passwordHashBase64) {+ throw new Error(t('components.auth.login.LoginRequestErrorMessage'));+ }+ const validateLoginResponse = await srpUtil.validateLoginRecoveryCode(username, passwordHashString, rememberMe, loginResponse, recoveryCode.trim());+ await processLoginVerify(validateLoginResponse, passwordHashBase64, loginResponse);+ } catch (err) {+ setErrors(toErrorMessages(err));+ } finally {+ hideLoading();+ }+ };++ const inputClass = 'bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500';+ const submitClass = 'w-full text-white bg-primary-600 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800';++ if (step === 'two-factor') {+ return (+ <>+ <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">+ {t('components.auth.login.TwoFactorAuthenticationTitle')}+ </h2>++ <ServerValidationErrors errors={errors} />++ <p className="text-gray-700 dark:text-gray-300 mb-6">{t('components.auth.login.TwoFactorAuthenticationDescription')}</p>+ <div className="w-full">+ <form onSubmit={handle2Fa} className="space-y-6" av-enable="true" av-suppress-save="true">+ <div>+ <label htmlFor="two-factor-code" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">{t('components.auth.login.AuthenticatorCodeLabel')}</label>+ <input ref={twoFactorRef} id="two-factor-code" type="number" value={twoFactorCode} onChange={(e) => setTwoFactorCode(e.target.value)} className={inputClass} autoComplete="one-time-code" />+ </div>+ <div className="flex items-start">+ <div className="flex items-center h-5">+ <input id="remember-machine" type="checkbox" checked={rememberMachine} onChange={(e) => setRememberMachine(e.target.checked)} className="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-primary-600 dark:ring-offset-gray-800" />+ </div>+ <div className="ml-3 text-sm">+ <label htmlFor="remember-machine" className="font-medium text-gray-900 dark:text-white">{t('components.auth.login.RememberMachineLabel')}</label>+ </div>+ </div>+ <button type="submit" className={submitClass}>{t('components.auth.login.LoginButton')}</button>+ </form>+ </div>+ <p className="mt-6 text-sm text-gray-700 dark:text-gray-300">+ {t('components.auth.login.DontHaveAuthenticatorText')}+ </p>+ <p className="text-sm text-gray-700 dark:text-gray-300">+ <button onClick={() => {+ setErrors([]); setStep('recovery-code');+ }} className="text-primary-600 hover:underline dark:text-primary-500">{t('components.auth.login.LoginWithRecoveryCodeLink')}</button>+ </p>+ <FooterLogin />+ </>+ );+ }++ if (step === 'recovery-code') {+ return (+ <>+ <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">+ {t('components.auth.login.RecoveryCodeVerificationTitle')}+ </h2>++ <ServerValidationErrors errors={errors} />++ <p className="text-gray-700 dark:text-gray-300 mb-6">+ {t('components.auth.login.RecoveryCodeDescription')}+ </p>+ <div className="w-full">+ <form onSubmit={handleRecoveryCode} className="space-y-6">+ <div>+ <label htmlFor="recovery-code" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">{t('components.auth.login.RecoveryCodeLabel')}</label>+ <input id="recovery-code" type="text" value={recoveryCode} onChange={(e) => setRecoveryCode(e.target.value)} className={inputClass} autoComplete="off" />+ </div>+ <button type="submit" className={submitClass}>{t('components.auth.login.LoginButton')}</button>+ </form>+ </div>+ <p className="mt-6 text-sm text-gray-700 dark:text-gray-300">+ {t('components.auth.login.RegainedAccessText')}+ </p>+ <p className="text-sm text-gray-700 dark:text-gray-300">+ <button onClick={() => {+ setErrors([]); setStep('two-factor');+ }} className="text-primary-600 hover:underline dark:text-primary-500">{t('components.auth.login.LoginWithAuthenticatorLink')}</button>+ </p>+ <FooterLogin />+ </>+ );+ }++ return (+ <>+ <h2 className="text-2xl font-bold text-gray-900 dark:text-white">+ {t('components.auth.login.PageTitle')}+ </h2>++ <form onSubmit={handleLogin} className="mt-4 space-y-6" av-enable="true" av-suppress-save="true">+ <ServerValidationErrors errors={errors} />+ <div>+ <label htmlFor="email" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">{t('components.auth.login.UsernameOrEmailLabel')}</label>+ <InputTextField ref={usernameRef} id="email" value={username} onValueChange={setUsername} type="text" placeholder={t('components.auth.login.UsernamePlaceholder')} autoCapitalize="off" autoCorrect="off" required />+ </div>+ <div>+ <label htmlFor="password" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">{t('components.auth.login.PasswordLabel')}</label>+ <PasswordInputField id="password" value={password} onValueChange={setPassword} placeholder={t('components.auth.login.PasswordPlaceholder')} />+ </div>++ <div className="flex items-start">+ <div className="flex items-center h-5">+ <input id="remember" type="checkbox" checked={rememberMe} onChange={(e) => setRememberMe(e.target.checked)} className="w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600" />+ </div>+ <div className="ml-3 text-sm">+ <label htmlFor="remember" className="font-medium text-gray-900 dark:text-white">{t('components.auth.login.RememberMeLabel')}</label>+ </div>+ <Link to="/user/forgot-password" className="ml-auto text-sm text-primary-700 hover:underline dark:text-primary-500">{t('components.auth.login.LostPasswordLink')}</Link>+ </div>++ <div className="flex flex-col gap-4">+ <button type="submit" id="login-button" className="w-full px-5 py-2 text-base font-medium text-center text-white bg-primary-700 rounded-lg hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800 flex items-center justify-center gap-2">+ {t('components.auth.login.LoginButton')}+ </button>+ {/* TODO: mobile app login (QR code) is not implemented yet. */}+ </div>++ {getAppConfig().publicRegistrationEnabled && (+ <div className="text-sm font-medium text-gray-500 dark:text-gray-400 text-center">+ {t('components.auth.login.NoAccountYetText')} <Link to="/user/setup" className="text-primary-700 hover:underline dark:text-primary-500">{t('components.auth.login.CreateNewVaultLink')}</Link>+ </div>+ )}+ </form>++ <FooterLogin />+ </>+ );+};++export default Login;diff --git a/apps/web/src/pages/auth/Logout.tsx b/apps/web/src/pages/auth/Logout.tsxnew file mode 100644index 000000000..bda165a3a--- /dev/null+++ b/apps/web/src/pages/auth/Logout.tsx@@ -0,0 +1,58 @@+import React, { useEffect, useRef } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';++import BoldLoadingIndicator from '@/components/loading/BoldLoadingIndicator';+import { useAuth } from '@/context/AuthContext';+import { useNotifications } from '@/context/NotificationContext';+import { usePageTitle } from '@/hooks/usePageTitle';+import { WebAuthnService } from '@/utils/WebAuthnService';++/**+ * Logs the user out and returns to the start page.+ */+const Logout: React.FC = () => {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const auth = useAuth();+ const notifications = useNotifications();+ const hasStarted = useRef(false);+ usePageTitle(t('pages.auth.logout.LoggingOutTitle'));++ useEffect(() => {+ if (hasStarted.current) {+ return;+ }+ hasStarted.current = true;++ /**+ * Revoke the tokens and redirect to the start page.+ */+ const run = async (): Promise<void> => {+ WebAuthnService.disable();+ await auth.logout({ userInitiated: true });+ notifications.clearMessages();+ await new Promise(resolve => setTimeout(resolve, 500));+ navigate('/', { replace: true });+ };+ void run();+ }, [auth, notifications, navigate]);++ return (+ <div className="fixed inset-0 flex flex-col items-center justify-center px-6 pt-8 pb-8 h-full w-full">+ <div className="relative p-6 sm:p-8 bg-white dark:bg-gray-700 rounded-lg sm:shadow-xl max-w-md w-full mx-auto">+ <div className="text-center">+ <div className="space-y-4">+ <BoldLoadingIndicator />+ <h2 className="text-xl font-semibold text-gray-900 dark:text-white">{t('pages.auth.logout.LoggingOutTitle')}</h2>+ <p className="text-sm text-gray-500 dark:text-gray-400">+ {t('pages.auth.logout.LoggingOutDescription')}+ </p>+ </div>+ </div>+ </div>+ </div>+ );+};++export default Logout;diff --git a/apps/web/src/pages/auth/Setup.tsx b/apps/web/src/pages/auth/Setup.tsxnew file mode 100644index 000000000..818481bc1--- /dev/null+++ b/apps/web/src/pages/auth/Setup.tsx@@ -0,0 +1,131 @@+import React, { useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';++import LanguageSwitcher from '@/components/auth/LanguageSwitcher';+import { CreatingStep, PasswordStep, TermsAndConditionsStep, UsernameStep } from '@/components/auth/setup/SetupSteps';+import { getAppConfig } from '@/config/AppConfig';+import { usePageTitle } from '@/hooks/usePageTitle';++/** The wizard steps, in order. */+const STEPS = ['terms', 'username', 'password', 'creating'] as const;+type SetupStep = typeof STEPS[number];++/**+ * The create vault wizard: terms, username, password, then registration.+ */+const Setup: React.FC = () => {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const tk = 'pages.auth.setup.setup';+ usePageTitle(t(`${tk}.SetupStepTitle`));++ const [step, setStep] = useState<SetupStep>('terms');+ const [agreedToTerms, setAgreedToTerms] = useState(false);+ const [username, setUsername] = useState('');+ const [password, setPassword] = useState('');++ useEffect(() => {+ if (!getAppConfig().publicRegistrationEnabled) {+ navigate('/user/login', { replace: true });+ }+ }, [navigate]);++ const isNextEnabled = step === 'terms' ? agreedToTerms : step === 'username' ? username.trim().length > 0 : step === 'password' ? password.trim().length > 0 : false;+ const stepIndex = STEPS.indexOf(step);+ const progressPercentage = Math.floor(stepIndex * 100 / (STEPS.length - 1));++ /**+ * The title of a step.+ */+ const stepTitle = (): string => {+ switch (step) {+ case 'terms': return t(`${tk}.TermsAndConditionsStepTitle`);+ case 'username': return t(`${tk}.UsernameStepTitle`);+ case 'password': return t(`${tk}.PasswordStepTitle`);+ default: return t(`${tk}.CreatingStepTitle`);+ }+ };++ /**+ * One step forward.+ */+ const goNext = (): void => {+ if (!isNextEnabled) {+ return;+ }+ setStep(STEPS[Math.min(stepIndex + 1, STEPS.length - 1)]);+ window.scrollTo({ top: 0 });+ };++ /**+ * One step back.+ */+ const goBack = (): void => {+ setStep(STEPS[Math.max(stepIndex - 1, 0)]);+ };++ const onRegistered = useCallback((): void => {+ navigate('/', { replace: true });+ }, [navigate]);++ return (+ <div className="min-h-screen bg-gray-100 dark:bg-gray-900 flex flex-col lg:items-center lg:justify-center">+ <div className="absolute top-4 right-4 z-10 mt-16 lg:mt-0 hidden lg:block">+ <LanguageSwitcher />+ </div>+ <div className="w-full mx-auto lg:max-w-xl lg:bg-white lg:dark:bg-gray-800 lg:shadow-xl lg:rounded-lg lg:overflow-hidden flex flex-col">+ <div className="flex flex-col flex-grow">+ <div className="flex-grow p-6 pt-4 lg:pt-6 pb-28 lg:pb-4">+ <div className="flex justify-between items-center mb-4">+ <div>+ <button type="button" onClick={goBack} className={`text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200 ${step === 'terms' ? 'invisible' : ''}`}>+ <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>+ </svg>+ </button>+ </div>+ <div className="flex-grow text-center">+ <h2 className="text-xl font-semibold text-gray-900 dark:text-white">{stepTitle()}</h2>+ </div>+ <button type="button" onClick={() => navigate('/')} className="text-gray-500 -mt-1 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200">+ <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path>+ </svg>+ </button>+ </div>+ {progressPercentage > 0 && (+ <div className="w-full bg-gray-200 rounded-full h-2.5 mb-4 dark:bg-gray-700 mt-4">+ <div className="bg-primary-600 h-2.5 rounded-full" style={{ width: `${progressPercentage}%` }}></div>+ </div>+ )}++ <form onSubmit={(e) => {+ e.preventDefault();+ goNext();+ }}>+ {step === 'terms' && <TermsAndConditionsStep agreedToTerms={agreedToTerms} onAgreedToTermsChange={setAgreedToTerms} />}+ {step === 'username' && <UsernameStep defaultUsername={username} onUsernameChange={setUsername} />}+ {step === 'password' && <PasswordStep onPasswordChange={setPassword} />}+ {step === 'creating' && <CreatingStep username={username} password={password} onDone={onRegistered} />}+ <button type="submit" className="hidden" />+ </form>+ </div>+ <div className="fixed lg:relative bottom-0 left-0 right-0 p-4 bg-gray-100 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700 lg:bg-transparent lg:dark:bg-transparent lg:border-0">+ {step === 'password' && password.trim().length > 0 ? (+ <button type="button" onClick={goNext} className="w-full py-3 px-4 bg-green-600 hover:bg-green-700 text-white font-semibold rounded-lg transition duration-300 ease-in-out">+ {t(`${tk}.CreateAccountButton`)}+ </button>+ ) : step !== 'creating' && (+ <button type="button" onClick={goNext} disabled={!isNextEnabled} className={`w-full py-3 px-4 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition duration-300 ease-in-out ${isNextEnabled ? '' : 'opacity-50 cursor-not-allowed'}`}>+ {t(`${tk}.ContinueButton`)}+ </button>+ )}+ </div>+ </div>+ </div>+ </div>+ );+};++export default Setup;diff --git a/apps/web/src/pages/auth/Start.tsx b/apps/web/src/pages/auth/Start.tsxnew file mode 100644index 000000000..fcaa4a123--- /dev/null+++ b/apps/web/src/pages/auth/Start.tsx@@ -0,0 +1,88 @@+import React, { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Link, useNavigate } from 'react-router-dom';++import MessageInfo from '@/components/alerts/MessageInfo';+import LanguageSwitcher from '@/components/auth/LanguageSwitcher';+import Logo from '@/components/auth/Logo';+import FooterLogin from '@/components/layout/FooterLogin';+import { getAppConfig } from '@/config/AppConfig';+import { useAuth } from '@/context/AuthContext';+import { usePageTitle } from '@/hooks/usePageTitle';++/**+ * Landing page for visitors who are not logged in.+ */+const Start: React.FC = () => {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const { isInitialized, isLoggedIn } = useAuth();+ const [isHttpWarning, setIsHttpWarning] = useState(false);+ usePageTitle('AliasVault');++ useEffect(() => {+ if (isInitialized && isLoggedIn) {+ navigate('/', { replace: true });+ }+ }, [isInitialized, isLoggedIn, navigate]);++ /**+ * Browsers only allow the crypto APIs over HTTPS, except on localhost.+ */+ useEffect(() => {+ const host = window.location.hostname.toLowerCase();+ const isLocalhost = host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]';+ setIsHttpWarning(window.location.protocol === 'http:' && !isLocalhost);+ }, []);++ return (+ <>+ <div className="relative">+ <div className="absolute top-4 right-4 z-10">+ <LanguageSwitcher />+ </div>+ </div>++ <div className="flex flex-col items-center justify-center px-6 pt-8 pb-8 mx-auto md:h-screen pt:mt-0 relative">+ <div className="w-full max-w-7xl mx-auto flex flex-col lg:flex-row bg-gray-100 dark:bg-gray-900">+ <div className="hidden lg:flex lg:w-1/2 items-center justify-center p-8">+ <div className="text-white text-4xl font-bold">+ <img src="/img/logo.svg" alt="AliasVault" className="w-64 h-64" />+ </div>+ </div>++ <div className="w-full lg:w-1/2 flex items-center justify-center bg-gray-100 dark:bg-gray-900">+ <div className="w-full max-w-xl space-y-4">+ <Logo />+ <h2 className="text-3xl font-semibold text-gray-800 dark:text-gray-200 mb-6">+ {t('pages.auth.start.MainTitle')}+ </h2>+ <p className="text-lg text-gray-600 dark:text-gray-300 mb-8">+ {t('pages.auth.start.TaglineText')}+ </p>+ {isHttpWarning && (+ <MessageInfo title={t('pages.auth.start.HttpsWarningTitle')}>+ {t('pages.auth.start.HttpsWarningMessage')}+ </MessageInfo>+ )}+ <div className="space-y-4">+ {getAppConfig().publicRegistrationEnabled && (+ <Link to="/user/setup" className="block w-full py-3 px-4 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition duration-300 ease-in-out text-center">+ {t('pages.auth.start.CreateNewVaultButton')}+ </Link>+ )}+ <Link to="/user/login" className="block w-full py-3 px-4 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-800 text-gray-800 dark:text-white font-semibold rounded-lg transition duration-300 ease-in-out text-center">+ {t('pages.auth.start.LoginExistingAccountButton')}+ </Link>+ </div>+ </div>+ </div>++ <FooterLogin />+ </div>+ </div>+ </>+ );+};++export default Start;diff --git a/apps/web/src/pages/auth/Unlock.tsx b/apps/web/src/pages/auth/Unlock.tsxnew file mode 100644index 000000000..189aa44e1--- /dev/null+++ b/apps/web/src/pages/auth/Unlock.tsx@@ -0,0 +1,254 @@+import { extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';+import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';+import { MasterPasswordService } from '@aliasvault/client/auth/MasterPasswordService';+import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';+import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';+import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Link, useNavigate, useParams } from 'react-router-dom';++import ServerValidationErrors from '@/components/alerts/ServerValidationErrors';+import PasswordInputField from '@/components/auth/PasswordInputField';+import FooterLogin from '@/components/layout/FooterLogin';+import BoldLoadingIndicator from '@/components/loading/BoldLoadingIndicator';+import { useAuth } from '@/context/AuthContext';+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 { WebAuthnNotSupportedError, WebAuthnService } from '@/utils/WebAuthnService';+import { vaultStore } from '@/vault/VaultStore';++/**+ * Unlock page: derive the vault key from the master password again after a lock or page reload.+ */+const Unlock: React.FC = () => {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const auth = useAuth();+ const dbContext = useDb();+ const webApi = useWebApi();+ const notifications = useNotifications();+ const { showLoading, hideLoading } = useLoading();+ const srpUtil = useMemo(() => new SrpLoginService(webApi), [webApi]);+ usePageTitle(t('pages.auth.unlock.UnlockButton'));++ const { skipWebAuthn } = useParams<{ skipWebAuthn?: string }>();+ const [isLoading, setIsLoading] = useState(true);+ const [isWebAuthnLoading, setIsWebAuthnLoading] = useState(false);+ const [showWebAuthnButton, setShowWebAuthnButton] = useState(false);+ const [password, setPassword] = useState('');+ const [errors, setErrors] = useState<string[]>([]);+ const passwordRef = useRef<HTMLInputElement>(null);+ const hasInitialized = useRef(false);++ const username = auth.username;++ /**+ * Decrypt the unlock key with the passkey and open the vault.+ */+ const unlockWithWebAuthn = useCallback(async (): Promise<void> => {+ if (!WebAuthnService.isEnabled()) {+ return;+ }+ setIsWebAuthnLoading(true);+ try {+ await WebAuthnService.unlock();+ navigate('/sync', { replace: true });+ } catch (err) {+ if (err instanceof WebAuthnNotSupportedError) {+ notifications.addErrorMessage(t('pages.auth.unlock.WebAuthnNotSupportedError'), true);+ } else {+ console.error('An error occurred while trying to unlock the vault with WebAuthn.', err);+ }+ } finally {+ setIsWebAuthnLoading(false);+ }+ }, [navigate, notifications, t]);++ /**+ * Check the session with the server; a rejected token logs the user out through the API service.+ */+ useEffect(() => {+ if (!auth.isInitialized || hasInitialized.current) {+ return;+ }+ hasInitialized.current = true;++ /**+ * Status check on page load.+ */+ const statusCheck = async (): Promise<void> => {+ if (!auth.isLoggedIn) {+ notifications.addErrorMessage(t('pages.auth.unlock.SessionTimedOutError'));+ navigate('/user/login', { replace: true });+ return;+ }++ try {+ const status = await webApi.getStatus();+ if (status.serverVersion === '0.0.0') {+ await dbContext.setIsOffline(true);+ } else {+ const statusError = webApi.validateStatusResponse(status);+ if (statusError !== null) {+ await auth.logout({ errorMessage: t('common.errors.' + statusError) });+ return;+ }+ await dbContext.setIsOffline(false);+ }+ } catch (err) {+ if (err instanceof ClientUpgradeRequiredError) {+ await auth.logout({ errorMessage: t('common.errors.clientVersionNotSupported') });+ return;+ }+ setErrors([t('pages.auth.unlock.ConnectionFailedError')]);+ }++ setIsLoading(false);++ // A passkey unlocks right away unless the user came here to type the password instead.+ const passkeyEnabled = WebAuthnService.isEnabled();+ setShowWebAuthnButton(passkeyEnabled);+ if (passkeyEnabled && skipWebAuthn !== 'true') {+ await unlockWithWebAuthn();+ }+ };+ void statusCheck();+ }, [auth, dbContext, webApi, notifications, navigate, t, skipWebAuthn, unlockWithWebAuthn]);++ useEffect(() => {+ if (!isLoading && !isWebAuthnLoading && !showWebAuthnButton) {+ const timer = setTimeout(() => passwordRef.current?.focus(), 100);+ return (): void => clearTimeout(timer);+ }+ }, [isLoading, isWebAuthnLoading, showWebAuthnButton]);++ /**+ * Derive the KEK from the password and open the vault key chain: online through the server, offline through the+ * cached key material.+ */+ const unlockSubmit = async (e: React.FormEvent): Promise<void> => {+ e.preventDefault();+ if (!username) {+ return;+ }+ showLoading(t('pages.auth.unlock.UnlockingVaultMessage'));+ setErrors([]);++ try {+ let unlockKey: string;+ if (dbContext.getIsOffline()) {+ const params = await MasterPasswordService.getStoredDerivationParams();+ if (!params) {+ throw new Error(t('pages.auth.unlock.ConnectionFailedError'));+ }+ const prepared = await SrpAuthService.prepareCredentials(password, params.salt, params.encryptionSettings);+ unlockKey = prepared.passwordHashBase64;+ // Throws an unlock-key-rejected (E-206) error on a wrong password.+ await VaultKeyService.verifyUnlockKey(unlockKey);+ } else {+ const loginResponse = await srpUtil.initiateLogin(username);+ const prepared = await SrpAuthService.prepareCredentials(password, loginResponse.salt, loginResponse.encryptionSettings);+ await vaultStore.storeUnlockKeyDerivationParams({ salt: loginResponse.salt, encryptionType: loginResponse.encryptionType, encryptionSettings: loginResponse.encryptionSettings });+ unlockKey = prepared.passwordHashBase64;+ // Throws an unlock-key-rejected (E-206) error on a wrong password.+ await VaultKeyService.refreshKeyChain(unlockKey, webApi);+ }++ await vaultStore.storeUnlockKey(unlockKey);+ navigate('/sync', { replace: true });+ } catch (err) {+ console.error('Unlock error:', err);+ const code = err instanceof Error ? extractErrorCode(err.message) : null;+ if (await VaultKeyService.isWrongUnlockKey(code)) {+ setErrors([t('pages.auth.unlock.IncorrectPasswordError')]);+ } else if (import.meta.env.DEV && err instanceof Error) {+ setErrors([err.message]);+ } else {+ setErrors([t('pages.auth.unlock.GenericUnlockError')]);+ }+ } finally {+ hideLoading();+ }+ };++ if (isLoading) {+ return (+ <>+ <ServerValidationErrors errors={errors} />+ <BoldLoadingIndicator />+ </>+ );+ }++ if (isWebAuthnLoading) {+ return (+ <>+ <ServerValidationErrors errors={errors} />+ <BoldLoadingIndicator />+ <p className="mt-6 text-center font-normal text-gray-500 dark:text-gray-400">{t('pages.auth.unlock.LoggingInWithWebAuthn')}</p>+ </>+ );+ }++ return (+ <>+ <div className="flex space-x-4">+ <div className="w-8 h-8 rounded-full bg-primary-100 dark:bg-primary-900 flex items-center justify-center">+ <span className="text-primary-600 dark:text-primary-400 text-base font-medium">+ {username?.charAt(0).toUpperCase() ?? '?'}+ </span>+ </div>+ <h2 className="mb-3 text-2xl font-bold text-gray-900 dark:text-white">{username}</h2>+ </div>++ {showWebAuthnButton ? (+ <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} />++ <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">+ <svg className="w-5 h-5 mr-2 -ml-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M17.414 2.586a2 2 0 00-2.828 0L7 10.172V13h2.828l7.586-7.586a2 2 0 000-2.828z"></path><path fillRule="evenodd" d="M2 6a2 2 0 012-2h4a1 1 0 010 2H4v10h10v-4a1 1 0 112 0v4a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" clipRule="evenodd"></path></svg>+ {t('pages.auth.unlock.UnlockWithWebAuthn')}+ </button>+ <button type="button" onClick={() => setShowWebAuthnButton(false)} className="inline-flex items-center justify-center px-5 py-2 text-base font-medium text-center text-gray-900 rounded-lg border border-gray-300 hover:bg-gray-100 focus:ring-4 focus:ring-gray-100 dark:text-white dark:border-gray-700 dark:hover:bg-gray-700 dark:focus:ring-gray-800">+ {t('pages.auth.unlock.UnlockWithPassword')}+ </button>+ </div>+ </div>+ ) : (+ <>+ <p className="text-base font-normal text-gray-500 dark:text-gray-400 mb-4">+ {t('pages.auth.unlock.EnterMasterPasswordDescription')}+ </p>++ <ServerValidationErrors errors={errors} />+ </>+ )}++ <form onSubmit={unlockSubmit} className="mt-4 space-y-6" av-enable="true" av-suppress-save="true">+ <div>+ <label htmlFor="password" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">{t('pages.auth.unlock.YourPasswordLabel')}</label>+ <PasswordInputField ref={passwordRef} id="password" value={password} onValueChange={setPassword} placeholder="••••••••" />+ </div>++ <button type="submit" id="unlock-button" className="w-full px-5 py-2 text-base font-medium text-center text-white bg-primary-700 rounded-lg hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800 flex items-center justify-center gap-2">+ {t('pages.auth.unlock.UnlockButton')}+ </button>+ </form>++ <div className="text-sm text-center font-medium text-gray-500 dark:text-gray-400 mt-6">+ {t('pages.auth.unlock.SwitchAccountsText')} <Link to="/user/logout" className="text-primary-700 hover:underline dark:text-primary-500">{t('pages.auth.unlock.LogOutLink')}</Link>+ </div>++ <FooterLogin />+ </>+ );+};++export default Unlock;