Skip to content

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

Add mobile unlock screens to web app (#2413)

Leendert de Borst511a23ad90f2
diff --git a/apps/web/src/components/auth/MobileUnlockModal.tsx b/apps/web/src/components/auth/MobileUnlockModal.tsx
new file mode 100644
index 000000000..dad630200
--- /dev/null
+++ b/apps/web/src/components/auth/MobileUnlockModal.tsx
@@ -0,0 +1,171 @@
+import { isMobileLoginErrorCode, MOBILE_LOGIN_REQUEST_LIFETIME_SECONDS, MobileLoginErrorCode, MobileLoginService } from '@aliasvault/client/auth/MobileLoginService';
+import QRCode from 'qrcode';
+import React, { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AlertMessageError from '@/components/alerts/AlertMessageError';
+import FormModal from '@/components/shared/FormModal';
+import { useWebApi } from '@/context/WebApiContext';
+
+import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';
+
+type MobileUnlockModalProps = {
+ isOpen: boolean;
+ mode: 'login' | 'unlock';
+ onClose: () => void;
+ onSuccess: (result: MobileLoginResult) => Promise<void>;
+};
+
+/**
+ * Log in or unlock by scanning a QR code with the mobile app.
+ */
+const MobileUnlockModal: React.FC<MobileUnlockModalProps> = ({ isOpen, mode, onClose, onSuccess }) => {
+ const { t } = useTranslation();
+ const webApi = useWebApi();
+ const tk = 'pages.auth.mobileUnlockModal';
+ const [qrCodeUrl, setQrCodeUrl] = useState<string | null>(null);
+ const [verificationCode, setVerificationCode] = useState<string | null>(null);
+ const [error, setError] = useState<MobileLoginErrorCode | null>(null);
+ const [timeRemaining, setTimeRemaining] = useState(MOBILE_LOGIN_REQUEST_LIFETIME_SECONDS);
+ const onSuccessRef = useRef(onSuccess);
+ const onCloseRef = useRef(onClose);
+ onSuccessRef.current = onSuccess;
+ onCloseRef.current = onClose;
+
+ // Create a request each time the modal opens, and drop it when the modal closes.
+ useEffect(() => {
+ if (!isOpen) {
+ return;
+ }
+
+ const service = new MobileLoginService(webApi);
+ let cancelled = false;
+ setError(null);
+ setQrCodeUrl(null);
+ setVerificationCode(null);
+ setTimeRemaining(MOBILE_LOGIN_REQUEST_LIFETIME_SECONDS);
+
+ /**
+ * Show the QR code and wait for the mobile app to answer.
+ */
+ const start = async (): Promise<void> => {
+ try {
+ const { qrPayload, verificationCode: code } = await service.initiate();
+ const dataUrl = await QRCode.toDataURL(qrPayload, { width: 300, margin: 2 });
+ if (cancelled) {
+ service.cleanup();
+ return;
+ }
+ setQrCodeUrl(dataUrl);
+ setVerificationCode(code);
+
+ service.startPolling(
+ async (result) => {
+ if (cancelled) {
+ return;
+ }
+ try {
+ await onSuccessRef.current(result);
+ onCloseRef.current();
+ } catch {
+ setQrCodeUrl(null);
+ setError(MobileLoginErrorCode.GENERIC);
+ }
+ },
+ (errorCode) => {
+ if (cancelled) {
+ return;
+ }
+ setQrCodeUrl(null);
+ setError(errorCode);
+ }
+ );
+ } catch (err) {
+ if (!cancelled) {
+ setError(isMobileLoginErrorCode(err) ? err : MobileLoginErrorCode.GENERIC);
+ }
+ }
+ };
+ void start();
+
+ return (): void => {
+ cancelled = true;
+ service.cleanup();
+ };
+ }, [isOpen, webApi]);
+
+ // Count down while the QR code is shown.
+ useEffect(() => {
+ if (!qrCodeUrl) {
+ return;
+ }
+ const interval = setInterval(() => setTimeRemaining(prev => Math.max(prev - 1, 0)), 1000);
+ return (): void => clearInterval(interval);
+ }, [qrCodeUrl]);
+
+ /**
+ * Translated message for an error code.
+ */
+ const getErrorMessage = (errorCode: MobileLoginErrorCode): string => {
+ switch (errorCode) {
+ case MobileLoginErrorCode.TIMEOUT:
+ return t('mobileLogin.ErrorTimeout');
+ case MobileLoginErrorCode.DECLINED:
+ return t('mobileLogin.ErrorDeclined');
+ default:
+ return t('sharedResources.ErrorUnknown');
+ }
+ };
+
+ /**
+ * Format seconds as M:SS.
+ */
+ const formatTime = (seconds: number): string => `${Math.floor(seconds / 60)}:${(seconds % 60).toString().padStart(2, '0')}`;
+
+ return (
+ <FormModal
+ isOpen={isOpen}
+ title={mode === 'unlock' ? t(`${tk}.UnlockTitle`) : t(`${tk}.PageTitle`)}
+ maxWidth="md"
+ submitOnEnter={false}
+ onClose={onClose}
+ footerContent={(
+ <button type="button" onClick={onClose} className="inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 dark:bg-gray-700 dark:text-white dark:ring-gray-600 dark:hover:bg-gray-600">
+ {t('sharedResources.Cancel')}
+ </button>
+ )}>
+ <div className="flex items-start justify-between gap-3 mb-4">
+ <p className="text-sm text-gray-600 dark:text-gray-400">{t(`${tk}.ScanQrCodeDescription`)}</p>
+ {qrCodeUrl && (
+ <span className="flex-shrink-0 px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 text-xs font-medium tabular-nums text-gray-600 dark:text-gray-300">
+ {formatTime(timeRemaining)}
+ </span>
+ )}
+ </div>
+
+ {error && <AlertMessageError message={getErrorMessage(error)} hasTopMargin={false} />}
+
+ {qrCodeUrl && (
+ <div className="flex flex-col items-center w-full max-w-[300px] mx-auto">
+ <img src={qrCodeUrl} alt="QR Code" className="w-full bg-white rounded-lg border-4 border-gray-200 dark:border-gray-600 mb-3" />
+ {verificationCode && (
+ <div className="w-full flex items-center gap-3 p-3 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700/50">
+ <div className="flex-shrink-0 flex items-center justify-center w-14 h-14 rounded-full border-2 border-primary-500 bg-white dark:bg-gray-800 text-2xl font-bold text-gray-900 dark:text-white">
+ {verificationCode}
+ </div>
+ <p className="text-sm font-medium text-gray-700 dark:text-gray-300">{t(`${tk}.VerificationCodeDescription`)}</p>
+ </div>
+ )}
+ </div>
+ )}
+
+ {!qrCodeUrl && !error && (
+ <div className="flex justify-center py-8">
+ <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
+ </div>
+ )}
+ </FormModal>
+ );
+};
+
+export default MobileUnlockModal;
diff --git a/apps/web/src/i18n/locales/en.json b/apps/web/src/i18n/locales/en.json
index 25cf445cb..1621606b5 100644
--- a/apps/web/src/i18n/locales/en.json
+++ b/apps/web/src/i18n/locales/en.json
@@ -43,7 +43,6 @@
"serverError": "Could not reach AliasVault server. Please try again later or contact support if the problem persists.",
"serverNotAvailable": "The AliasVault server is not available. Please try again later or contact support if the problem persists.",
"serverVersionNotSupported": "The AliasVault server needs to be updated to a newer version in order to use this browser extension. Please contact support if you need help.",
- "serverVersionTooOld": "The AliasVault server needs to be updated to a newer version in order to use this feature. Please contact the server admin if you need help.",
"sessionExpired": "Your session has expired. Please log in again.",
"syncConflictMaxRetries": "Could not sync vault after multiple attempts. Please try again later.",
"unexpectedErrorContactSupport": "An unexpected error occurred. Please try again, and contact support if the problem persists.",
@@ -755,6 +754,7 @@
}
},
"mobileLogin": {
+ "ErrorDeclined": "The login request was declined on your mobile device.",
"ErrorTimeout": "Mobile login request timed out. Please reload the page and try again."
},
"pages": {
@@ -780,7 +780,8 @@
"mobileUnlockModal": {
"PageTitle": "Log in using Mobile App",
"ScanQrCodeDescription": "Scan this QR code with your AliasVault mobile app to login and unlock your vault.",
- "UnlockTitle": "Unlock using Mobile App"
+ "UnlockTitle": "Unlock using Mobile App",
+ "VerificationCodeDescription": "When the app asks for it, input this number."
},
"setup": {
"setup": {
diff --git a/apps/web/src/pages/auth/Login.tsx b/apps/web/src/pages/auth/Login.tsx
index fb2f938d6..01f7a61cd 100644
--- a/apps/web/src/pages/auth/Login.tsx
+++ b/apps/web/src/pages/auth/Login.tsx
@@ -12,6 +12,7 @@ import { Link, useNavigate } from 'react-router-dom';
import CriticalErrorPanel from '@/components/alerts/CriticalErrorPanel';
import ServerValidationErrors from '@/components/alerts/ServerValidationErrors';
+import MobileUnlockModal from '@/components/auth/MobileUnlockModal';
import PasswordInputField from '@/components/auth/PasswordInputField';
import FooterLogin from '@/components/layout/FooterLogin';
import FormLabel from '@/components/shared/FormLabel';
@@ -27,6 +28,8 @@ import { focusWhenVisible } from '@/utils/FocusWhenVisible';
import { StorageKeys } from '@/utils/StorageKeys';
import { vaultStore } from '@/vault/VaultStore';
+import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';
+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
import type { LoginResponse, ValidateLoginResponse } from '@aliasvault/models/webapi';
/** Which step of the login the page shows. */
@@ -56,12 +59,14 @@ const Login: React.FC = () => {
const [loginResponse, setLoginResponse] = useState<LoginResponse | null>(null);
const [passwordHashString, setPasswordHashString] = useState<string | null>(null);
const [passwordHashBase64, setPasswordHashBase64] = useState<string | null>(null);
+ const [showMobileLoginModal, setShowMobileLoginModal] = useState(false);
const usernameRef = useRef<HTMLInputElement>(null);
const twoFactorRef = useRef<HTMLInputElement>(null);
+ const isCompletingLogin = useRef(false);
// Already authenticated: go home.
useEffect(() => {
- if (auth.isInitialized && auth.isLoggedIn) {
+ if (auth.isInitialized && auth.isLoggedIn && !isCompletingLogin.current) {
navigate('/', { replace: true });
}
}, [auth.isInitialized, auth.isLoggedIn, navigate]);
@@ -120,21 +125,56 @@ const Login: React.FC = () => {
/**
* Store the tokens and the unlock key, then continue to the sync page which loads the vault.
*/
+ const completeLogin = async (loginUsername: string, accessToken: string, refreshToken: string, unlockKey: string, params: UnlockKeyDerivationParams): Promise<void> => {
+ isCompletingLogin.current = true;
+ try {
+ await auth.setAuthTokens(SrpAuthService.normalizeUsername(loginUsername), accessToken, refreshToken);
+
+ // Fetch the key chain, check the unlock key opens it and cache it; the vault key is derived from the two on demand.
+ try {
+ await VaultKeyService.refreshKeyChain(unlockKey, webApi);
+ } catch (err) {
+ // Without a usable key chain the session is useless; end it so the error shows on this form.
+ await auth.logout();
+ throw err;
+ }
+ await vaultStore.storeUnlockKeyDerivationParams(params);
+ await vaultStore.storeUnlockKey(unlockKey);
+
+ notifications.clearMessages();
+ navigate('/sync', { replace: true });
+ } finally {
+ isCompletingLogin.current = false;
+ }
+ };
+
+ /**
+ * Finish a password login once the server accepted it.
+ */
const processLoginVerify = async (validateLoginResponse: ValidateLoginResponse, hashBase64: string, response: LoginResponse): Promise<void> => {
if (!validateLoginResponse.token) {
throw new Error(t('components.auth.login.LoginRequestErrorMessage'));
}
+ const params = { salt: response.salt, encryptionType: response.encryptionType, encryptionSettings: response.encryptionSettings };
+ await completeLogin(username, validateLoginResponse.token.token, validateLoginResponse.token.refreshToken, hashBase64, params);
+ };
- 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);
+ /**
+ * Finish a login the mobile app approved: the mobile app sends the unlock key.
+ */
+ const handleMobileLoginSuccess = async (result: MobileLoginResult): Promise<void> => {
+ showLoading(t('components.auth.login.LoggingInMessage'));
+ setErrors([]);
+ setShowMobileLoginModal(false);
- notifications.clearMessages();
- navigate('/sync', { replace: true });
+ try {
+ const params = { salt: result.salt, encryptionType: result.encryptionType, encryptionSettings: result.encryptionSettings };
+ await completeLogin(result.username, result.token, result.refreshToken, result.unlockKey, params);
+ } catch (err) {
+ setErrors(toErrorMessages(err));
+ } finally {
+ hideLoading();
+ }
};
/**
@@ -337,7 +377,12 @@ const Login: React.FC = () => {
<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. */}
+ <button type="button" id="mobile-login-button" onClick={() => setShowMobileLoginModal(true)} className="hidden md:flex w-full px-5 py-2 text-base font-medium text-center text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 focus:ring-4 focus:ring-gray-200 dark:bg-gray-700 dark:text-white dark:border-gray-600 dark:hover:bg-gray-600 dark:focus:ring-gray-700 items-center justify-center gap-2">
+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
+ </svg>
+ {t('components.auth.login.MobileDeviceLink')}
+ </button>
</div>
{getAppConfig().publicRegistrationEnabled && (
@@ -348,6 +393,8 @@ const Login: React.FC = () => {
</form>
<FooterLogin />
+
+ <MobileUnlockModal isOpen={showMobileLoginModal} mode="login" onClose={() => setShowMobileLoginModal(false)} onSuccess={handleMobileLoginSuccess} />
</>
);
};
diff --git a/apps/web/src/pages/auth/Unlock.tsx b/apps/web/src/pages/auth/Unlock.tsx
index cb2c2a004..859e8659d 100644
--- a/apps/web/src/pages/auth/Unlock.tsx
+++ b/apps/web/src/pages/auth/Unlock.tsx
@@ -10,6 +10,7 @@ import { Link, useNavigate, useParams } from 'react-router-dom';
import CriticalErrorPanel from '@/components/alerts/CriticalErrorPanel';
import ServerValidationErrors from '@/components/alerts/ServerValidationErrors';
+import MobileUnlockModal from '@/components/auth/MobileUnlockModal';
import PasswordInputField from '@/components/auth/PasswordInputField';
import FooterLogin from '@/components/layout/FooterLogin';
import BoldLoadingIndicator from '@/components/loading/BoldLoadingIndicator';
@@ -24,6 +25,8 @@ import { focusWhenVisible } from '@/utils/FocusWhenVisible';
import { WebAuthnNotSupportedError, WebAuthnService } from '@/utils/WebAuthnService';
import { vaultStore } from '@/vault/VaultStore';
+import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';
+
/**
* Unlock page: derive the vault key from the master password again after a lock or page reload.
*/
@@ -44,6 +47,7 @@ const Unlock: React.FC = () => {
const [showWebAuthnButton, setShowWebAuthnButton] = useState(false);
const [password, setPassword] = useState('');
const [errors, setErrors] = useState<string[]>([]);
+ const [showMobileUnlockModal, setShowMobileUnlockModal] = useState(false);
const passwordRef = useRef<HTMLInputElement>(null);
const hasInitialized = useRef(false);
@@ -63,10 +67,9 @@ const Unlock: React.FC = () => {
} catch (err) {
if (err instanceof WebAuthnNotSupportedError) {
notifications.addErrorMessage(t('pages.auth.unlock.WebAuthnNotSupportedError'), true);
- } else {
+ } else if (!(err instanceof DOMException && err.name === 'NotAllowedError')) {
console.error('An error occurred while trying to unlock the vault with WebAuthn.', err);
}
- } finally {
setIsWebAuthnLoading(false);
}
}, [navigate, notifications, t]);
@@ -123,17 +126,16 @@ const Unlock: React.FC = () => {
}, [auth, dbContext, webApi, notifications, navigate, t, skipWebAuthn, unlockWithWebAuthn]);
useEffect(() => {
- if (!isLoading && !isWebAuthnLoading) {
+ if (!isLoading && !isWebAuthnLoading && !showWebAuthnButton) {
return focusWhenVisible(() => passwordRef.current);
}
- }, [isLoading, isWebAuthnLoading]);
+ }, [isLoading, isWebAuthnLoading, showWebAuthnButton]);
/**
- * Hide the passkey option and move focus to the password field.
+ * Switch from the passkey option to the password form.
*/
const showPasswordUnlock = (): void => {
setShowWebAuthnButton(false);
- passwordRef.current?.focus();
};
/**
@@ -187,6 +189,38 @@ const Unlock: React.FC = () => {
}
};
+ /**
+ * Replace the session with the one the mobile app approved and open the vault with the unlock key it sent.
+ */
+ const handleMobileUnlockSuccess = async (result: MobileLoginResult): Promise<void> => {
+ showLoading(t('pages.auth.unlock.UnlockingVaultMessage'));
+ setErrors([]);
+ setShowMobileUnlockModal(false);
+
+ try {
+ // The approval must belong to the account of the current session.
+ if (username && result.username.toLowerCase() !== username.toLowerCase()) {
+ setErrors([t('apiErrors.USERNAME_MISMATCH')]);
+ return;
+ }
+
+ // Revoke the tokens of the current session before storing the new ones.
+ await webApi.revokeCurrentTokens();
+ await auth.setAuthTokens(result.username, result.token, result.refreshToken);
+
+ // Throws an unlock-key-rejected (E-206) error if the key does not open the key chain.
+ await VaultKeyService.refreshKeyChain(result.unlockKey, webApi);
+ await vaultStore.storeUnlockKeyDerivationParams({ salt: result.salt, encryptionType: result.encryptionType, encryptionSettings: result.encryptionSettings });
+ await vaultStore.storeUnlockKey(result.unlockKey);
+ navigate('/sync', { replace: true });
+ } catch (err) {
+ console.error('Mobile unlock error:', err);
+ const codedError = translateCodedError(err, t);
+ if (err instanceof ClientUpgradeRequiredError) {
+ await auth.logout({ errorMessage: t('common.errors.clientVersionNotSupported') });
+ } else if (codedError) {
+ // A coded failure keeps its code, so the user can report it.
+ setErrors([codedError]);
} else if (import.meta.env.DEV && err instanceof Error) {
setErrors([err.message]);
} else {
@@ -257,25 +291,36 @@ const Unlock: React.FC = () => {
</p>
<ServerValidationErrors errors={errors} />
+
+ <form onSubmit={unlockSubmit} className="mt-4 space-y-6" av-enable="true" av-suppress-save="true">
+ <div>
+ <FormLabel htmlFor="password">{t('pages.auth.unlock.YourPasswordLabel')}</FormLabel>
+ <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>
</>
)}
- <form onSubmit={unlockSubmit} className="mt-4 space-y-6" av-enable="true" av-suppress-save="true">
- <div>
- <FormLabel htmlFor="password">{t('pages.auth.unlock.YourPasswordLabel')}</FormLabel>
- <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')}
+ {!dbContext.isOffline && (
+ <button type="button" id="mobile-unlock-button" onClick={() => setShowMobileUnlockModal(true)} className="hidden md:flex w-full px-5 py-2 text-base font-medium text-center text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 focus:ring-4 focus:ring-gray-200 dark:bg-gray-700 dark:text-white dark:border-gray-600 dark:hover:bg-gray-600 dark:focus:ring-gray-700 items-center justify-center gap-2 mt-4">
+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
+ </svg>
+ {t('pages.auth.unlock.UnlockWithMobileButton')}
</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 />
+
+ <MobileUnlockModal isOpen={showMobileUnlockModal} mode="unlock" onClose={() => setShowMobileUnlockModal(false)} onSuccess={handleMobileUnlockSuccess} />
</>
);
};