Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update browser extension mobile login screens (#2159)
Leendert de Borst619c8264a32e
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/MobileUnlockModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/MobileUnlockModal.tsxindex 2687e477e..5f5c42527 100644--- a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/MobileUnlockModal.tsx+++ b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/MobileUnlockModal.tsx@@ -30,6 +30,7 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({}) => {const { t } = useTranslation();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<number>(120); // 2 minutes in secondsconst mobileLoginRef = useRef<MobileLoginUtility | null>(null);@@ -42,6 +43,8 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({switch (errorCode) {case MobileLoginErrorCode.TIMEOUT:return t('common.errors.mobileLoginRequestExpired');+ case MobileLoginErrorCode.DECLINED:+ return t('common.errors.mobileLoginRequestDeclined');case MobileLoginErrorCode.SERVER_OUTDATED:return t('common.errors.serverVersionNotSupported');case MobileLoginErrorCode.GENERIC:@@ -86,6 +89,7 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({try {setError(null);setQrCodeUrl(null);+ setVerificationCode(null);setTimeRemaining(120);// Initialize mobile login utility@@ -93,20 +97,15 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({mobileLoginRef.current = new MobileLoginUtility(webApi);}- // Initiate mobile login and get QR code data- const { requestId, publicKeyHash } = await mobileLoginRef.current.initiate();-- /*- * Generate QR code with AliasVault prefix for mobile login.- * Include public key hash as query parameter for security verification.- */- const qrData = `aliasvault://open/mobile-unlock/${requestId}?pk=${publicKeyHash}`;- const qrDataUrl = await QRCode.toDataURL(qrData, {- width: 256,+ // Initiate mobile login and get the QR code text plus the number the user taps in the mobile app+ const { qrPayload, verificationCode: code } = await mobileLoginRef.current.initiate();+ const qrDataUrl = await QRCode.toDataURL(qrPayload, {+ width: 300,margin: 2,});setQrCodeUrl(qrDataUrl);+ setVerificationCode(code);// Start polling for responseawait mobileLoginRef.current.startPolling(@@ -188,9 +187,16 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({showHeaderBorder={false}bodyClassName="px-6 pb-6">- <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">- {description}- </p>+ <div className="flex items-start justify-between gap-3 mb-4">+ <p className="text-sm text-gray-600 dark:text-gray-400">+ {description}+ </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 && (<div className="mb-4 p-3 bg-red-100 dark:bg-red-900/30 border border-red-400 dark:border-red-700 rounded text-red-700 dark:text-red-400 text-sm">@@ -199,11 +205,18 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({)}{qrCodeUrl && (- <div className="flex flex-col items-center mb-4">- <img src={qrCodeUrl} alt="QR Code" className="border-4 border-gray-200 dark:border-gray-600 rounded mb-3" />- <div className="text-gray-700 dark:text-gray-300 text-sm font-medium">- {formatTime(timeRemaining)}- </div>+ <div className="flex flex-col items-center w-full max-w-[300px] mx-auto">+ <img src={qrCodeUrl} alt="QR Code" className="w-full border-4 border-gray-200 dark:border-gray-600 rounded 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('auth.mobileUnlockVerificationCode')}+ </p>+ </div>+ )}</div>)}@@ -212,14 +225,6 @@ const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div></div>)}-- <button- type="button"- onClick={handleClose}- className="mt-4 w-full inline-flex justify-center rounded-md bg-white dark:bg-gray-700 px-3 py-2 text-sm font-semibold text-gray-900 dark:text-gray-200 shadow-sm ring-1 ring-inset ring-gray-300 dark:ring-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-primary-500"- >- {t('common.cancel')}- </button></ModalWrapper>);};diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsxindex c186ac62d..8d1b2efdc 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx@@ -387,10 +387,10 @@ const Login: React.FC = () => {await app.setAuthTokens(result.username, result.token, result.refreshToken);// The mobile device sends the unlock key: fetch the account's key chain, check the key opens it and cache it.- await VaultKeyService.refreshKeyChain(result.decryptionKey, webApi);+ await VaultKeyService.refreshKeyChain(result.unlockKey, webApi);// Store the unlock key and derivation params.- await dbContext.storeUnlockKey(result.decryptionKey);+ await dbContext.storeUnlockKey(result.unlockKey);await dbContext.storeUnlockKeyDerivationParams({salt: result.salt,encryptionType: result.encryptionType,diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsxindex 1867cd9e9..ec8eb0e10 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx@@ -562,6 +562,12 @@ const Unlock: React.FC = () => {const handleMobileUnlockSuccess = async (result: MobileLoginResult): Promise<void> => {showLoading();try {+ // Check if the approval belongs to the same account as the current session.+ if (authContext.username && result.username.toLowerCase() !== authContext.username.toLowerCase()) {+ setError(t('common.apiErrors.USERNAME_MISMATCH'));+ return;+ }+/** Revoke the old refresh token (from existing logged in session) before setting new ones* that we get from the mobile login request.@@ -574,10 +580,10 @@ const Unlock: React.FC = () => {/** The mobile device sends the password-derived key (the KEK).*/- await VaultKeyService.refreshKeyChain(result.decryptionKey, webApi);+ await VaultKeyService.refreshKeyChain(result.unlockKey, webApi);// Store the unlock key and derivation params- await dbContext.storeUnlockKey(result.decryptionKey);+ await dbContext.storeUnlockKey(result.unlockKey);await dbContext.storeUnlockKeyDerivationParams({salt: result.salt,encryptionType: result.encryptionType,diff --git a/apps/browser-extension/src/entrypoints/popup/types/MobileLoginErrorCode.ts b/apps/browser-extension/src/entrypoints/popup/types/MobileLoginErrorCode.tsindex 07d836c8b..66eca90b9 100644--- a/apps/browser-extension/src/entrypoints/popup/types/MobileLoginErrorCode.ts+++ b/apps/browser-extension/src/entrypoints/popup/types/MobileLoginErrorCode.ts@@ -13,6 +13,11 @@ export enum MobileLoginErrorCode {*/SERVER_OUTDATED = 'SERVER_OUTDATED',+ /**+ * The request was declined on the mobile device.+ */+ DECLINED = 'DECLINED',+/*** A generic error occurred during mobile login.*/diff --git a/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts b/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.tsindex 64ae440bc..93ba43d51 100644--- a/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts+++ b/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts@@ -1,5 +1,6 @@import { Buffer } from 'buffer';+import { MobileLoginProtocol } from '@aliasvault/client/auth/MobileLoginProtocol';import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';import { serverPredatesV2Api } from '@aliasvault/client/sync/LegacyStorageModelMigration';@@ -8,7 +9,7 @@ import { MobileLoginErrorCode } from '@/entrypoints/popup/types/MobileLoginErrorimport type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';import type { WebApiService } from '@aliasvault/client/api/WebApiService';-import type { LoginResponse, MobileLoginInitiateResponse, MobileLoginPollResponse } from '@aliasvault/models/webapi';+import type { MobileLoginInitiateResponse, MobileLoginPayload, MobileLoginPollResponse } from '@aliasvault/models/webapi';/*** Utility class for mobile login operations@@ -16,9 +17,11 @@ import type { LoginResponse, MobileLoginInitiateResponse, MobileLoginPollResponsexport class MobileLoginUtility {private webApi: WebApiService;private pollingInterval: NodeJS.Timeout | null = null;+ private pollingTimeout: NodeJS.Timeout | null = null;+ private isPollInFlight = false;private requestId: string | null = null;+ private pollSecret: string | null = null;private privateKey: CryptoKey | null = null;- private publicKeyHash: string | null = null;/*** Constructor for the MobileLoginUtility class.@@ -30,31 +33,15 @@ export class MobileLoginUtility {}/**- * Computes a SHA-256 hash of the public key and returns the first 16 characters.- */- private async computePublicKeyHash(publicKey: string): Promise<string> {- const encoder = new TextEncoder();- const data = encoder.encode(publicKey);- const hashBuffer = await crypto.subtle.digest('SHA-256', data);- const hashArray = Array.from(new Uint8Array(hashBuffer));- const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');- // Return first 16 characters for a compact but secure fingerprint- return hashHex.substring(0, 16);- }-- /**- * Initiates a mobile login request and returns the QR code data- * @returns Object containing requestId and publicKeyHash for QR code generation+ * Initiates a mobile login request.+ * @returns The text for the QR code and the verification code the user has to type into the mobile app* @throws {MobileLoginErrorCode} If initiation fails*/- public async initiate(): Promise<{ requestId: string; publicKeyHash: string }> {+ public async initiate(): Promise<{ qrPayload: string; verificationCode: string }> {try {const { publicKeyJwk, privateKey } = await EncryptionUtility.generateRsaKeyPairNonExtractable();this.privateKey = privateKey;- // Compute hash of public key for QR code binding- this.publicKeyHash = await this.computePublicKeyHash(publicKeyJwk);-// Send public key to server (no auth required)const response = await this.webApi.rawFetch('auth/mobile-login/initiate', {method: 'POST',@@ -79,12 +66,17 @@ export class MobileLoginUtility {}const data = await response.json() as MobileLoginInitiateResponse;+ if (!data.requestId || !data.pollSecret) {+ // A server without the poll secret still runs the old handshake, which this client no longer takes part in.+ throw MobileLoginErrorCode.SERVER_OUTDATED;+ }this.requestId = data.requestId;+ this.pollSecret = data.pollSecret;- // Return QR code data (request ID and public key hash)+ // The QR code binds the request to this key pair, the verification code is derived from the same key.return {- requestId: this.requestId,- publicKeyHash: this.publicKeyHash,+ qrPayload: MobileLoginProtocol.buildQrPayload(data.requestId, await MobileLoginProtocol.computePublicKeyHash(publicKeyJwk)),+ verificationCode: await MobileLoginProtocol.computeVerificationCode(publicKeyJwk),};} catch (error) {if (typeof error === 'string' && Object.values(MobileLoginErrorCode).includes(error as MobileLoginErrorCode)) {@@ -101,7 +93,7 @@ export class MobileLoginUtility {onSuccess: (result: MobileLoginResult) => void,onError: (errorCode: MobileLoginErrorCode) => void): Promise<void> {- if (!this.requestId || !this.privateKey) {+ if (!this.requestId || !this.pollSecret || !this.privateKey) {throw new Error('Must call initiate() before starting polling');}@@ -109,24 +101,33 @@ export class MobileLoginUtility {* Polls the server for mobile login response*/const pollFn = async (): Promise<void> => {+ // An approved request can be collected once, so a slow poll must never overlap with the next one.+ if (this.isPollInFlight) {+ return;+ }+ this.isPollInFlight = true;+try {if (!this.requestId) {this.stopPolling();return;}- const response = await this.webApi.rawFetch(- `auth/mobile-login/poll/${this.requestId}`,- {- method: 'GET',- }- );+ const response = await this.webApi.rawFetch('auth/mobile-login/poll', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ requestId: this.requestId,+ pollSecret: this.pollSecret,+ }),+ });if (!response.ok) {if (response.status === 404) {// Request expired or not found- this.stopPolling();- this.requestId = null;+ this.cleanup();onError(MobileLoginErrorCode.TIMEOUT);return;}@@ -135,62 +136,41 @@ export class MobileLoginUtility {const data = await response.json() as MobileLoginPollResponse;- if (data.fulfilled && data.encryptedSymmetricKey) {- // Capture key locally; stopPolling() nulls the field.+ if (data.status === 'Declined') {+ this.cleanup();+ onError(MobileLoginErrorCode.DECLINED);+ return;+ }++ if (data.status === 'Approved' && data.encryptedSymmetricKey && data.encryptedPayload && data.encryptedUnlockKey) {+ // Capture key locally; cleanup() nulls the field.const privateKey = this.privateKey!;- this.stopPolling();+ this.cleanup();- // Decrypt the encrypted decryption key with RSA private key- const decryptionKeyBytes = await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedDecryptionKey!, privateKey);- const decryptionKey = Buffer.from(decryptionKeyBytes).toString('base64');+ // The mobile app encrypted the unlock key with our public key+ const unlockKeyBytes = await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedUnlockKey, privateKey);+ const unlockKey = Buffer.from(unlockKeyBytes).toString('base64');- // Decrypt the other encrypted fields with the symmetric key+ // The server encrypted the session payload with a symmetric key, which is encrypted with our public keyconst symmetricKeyBytes = await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedSymmetricKey, privateKey);const symmetricKey = Buffer.from(symmetricKeyBytes).toString('base64');-- const token = await EncryptionUtility.symmetricDecrypt(data.encryptedToken!, symmetricKey);- const refreshToken = await EncryptionUtility.symmetricDecrypt(data.encryptedRefreshToken!, symmetricKey);- const username = await EncryptionUtility.symmetricDecrypt(data.encryptedUsername!, symmetricKey);-- this.requestId = null;-- // Call /login endpoint with username to get salt and encryption settings- const loginResponse = await this.webApi.rawFetch('auth/login', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify({- username,- }),+ const payload = JSON.parse(await EncryptionUtility.symmetricDecrypt(data.encryptedPayload, symmetricKey)) as MobileLoginPayload;++ onSuccess({+ username: payload.username,+ token: payload.token,+ refreshToken: payload.refreshToken,+ unlockKey: unlockKey,+ salt: payload.salt,+ encryptionType: payload.encryptionType,+ encryptionSettings: payload.encryptionSettings,});-- if (!loginResponse.ok) {- onError(MobileLoginErrorCode.GENERIC);- return;- }-- const loginData = await loginResponse.json() as LoginResponse;-- // Create result object using the MobileLoginResult type- const result: MobileLoginResult = {- username: username,- token: token,- refreshToken: refreshToken,- decryptionKey: decryptionKey,- salt: loginData.salt,- encryptionType: loginData.encryptionType,- encryptionSettings: loginData.encryptionSettings,- };-- // Call success callback with result object- onSuccess(result);-}} catch {- this.stopPolling();- this.requestId = null;+ this.cleanup();onError(MobileLoginErrorCode.GENERIC);+ } finally {+ this.isPollInFlight = false;}};@@ -198,10 +178,9 @@ export class MobileLoginUtility {this.pollingInterval = setInterval(pollFn, 3000);// Stop polling after 3.5 minutes (adds 1.5 minute buffer to default 2 minute timer for edge cases)- setTimeout(() => {+ this.pollingTimeout = setTimeout(() => {if (this.pollingInterval) {- this.stopPolling();- this.requestId = null;+ this.cleanup();onError(MobileLoginErrorCode.TIMEOUT);}}, 210000);@@ -215,6 +194,10 @@ export class MobileLoginUtility {clearInterval(this.pollingInterval);this.pollingInterval = null;}+ if (this.pollingTimeout) {+ clearTimeout(this.pollingTimeout);+ this.pollingTimeout = null;+ }this.privateKey = null;}@@ -224,6 +207,6 @@ export class MobileLoginUtility {public cleanup(): void {this.stopPolling();this.requestId = null;- this.publicKeyHash = null;+ this.pollSecret = null;}}diff --git a/apps/browser-extension/src/i18n/locales/en.json b/apps/browser-extension/src/i18n/locales/en.jsonindex 219744ed7..b9ae2e5e1 100644--- a/apps/browser-extension/src/i18n/locales/en.json+++ b/apps/browser-extension/src/i18n/locales/en.json@@ -30,6 +30,7 @@"loginWithMobile": "Log in using Mobile App","unlockWithMobile": "Unlock using Mobile App","scanQrCode": "Scan this QR code with your AliasVault mobile app to log in and unlock your vault.",+ "mobileUnlockVerificationCode": "When the app asks for it, input this number.","passwordAttemptsWarning": "Incorrect password. You will be logged out if you enter the wrong password {{remainingAttempts}} more times.","maxAttemptsReached": "Too many failed unlock attempts. You have been logged out for security reasons."},@@ -128,7 +129,8 @@"vaultLoadError": "Something went wrong while loading your vault. Please copy the error details below and contact support for help.","wrongPassword": "Incorrect password. Please try again.","sessionExpired": "Your session has expired. Please log in again.",- "mobileLoginRequestExpired": "Mobile login request timed out. Please reload the page and try again."+ "mobileLoginRequestExpired": "Mobile login request timed out. Please reload the page and try again.",+ "mobileLoginRequestDeclined": "The login request was declined on your mobile device."},"apiErrors": {"UNKNOWN_ERROR": "An unknown error occurred. Please try again.",diff --git a/apps/browser-extension/src/utils/types/messaging/MobileLoginResult.ts b/apps/browser-extension/src/utils/types/messaging/MobileLoginResult.tsindex 92a00118f..07ff53ff5 100644--- a/apps/browser-extension/src/utils/types/messaging/MobileLoginResult.ts+++ b/apps/browser-extension/src/utils/types/messaging/MobileLoginResult.ts@@ -18,9 +18,9 @@ export type MobileLoginResult = {refreshToken: string;/**- * The unlock key the mobile app sent.+ * The account unlock key the mobile app sent.*/- decryptionKey: string;+ unlockKey: string;/*** The user's salt for key derivation.