Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update browser extension login flow to reuse core/client logic
Leendert de Borstb94269454e4e
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.tsindex 0e62ba956..6813c780d 100644--- a/apps/browser-extension/src/entrypoints/background.ts+++ b/apps/browser-extension/src/entrypoints/background.ts@@ -4,7 +4,7 @@import '@/platform/ClientServices';-import { broadcastVaultUnlocked, handleAwaitPendingAuth, handleLoginWithPassword, handleLoginWithTwoFactor, handleUnlockWithPassword, handleUnlockWithPin } from '@/entrypoints/background/AuthHandler';+import { broadcastVaultUnlocked, handleAwaitPendingAuth, handleLoginWithMobile, handleLoginWithPassword, handleLoginWithTwoFactor, handleUnlockWithPassword, handleUnlockWithPin } from '@/entrypoints/background/AuthHandler';import { handleResetAutoLockTimer, handlePopupHeartbeat, handleSetAutoLockTimeout, initializeAutoLockAlarm, handleAutoLockAlarm } from '@/entrypoints/background/AutolockTimeoutHandler';import { handleClipboardCopied, handleSetClipboardClearTimeout, handleGetClipboardCountdownState } from '@/entrypoints/background/ClipboardClearHandler';import { handleBlockLoginSaveForDomain, handleDisableAutofillForSite, handleDismissVaultLockedPopup, handleGetContentSettings, handleGetLanguage, handleIsLoginSaveBlocked, restrictContentScriptStorage } from '@/entrypoints/background/ContentSettingsHandler';@@ -299,6 +299,7 @@ export default defineBackground({// Login and unlock run in the background so they complete when the popup closes mid-flow.onExtensionPageMessage('AUTH_LOGIN', ({ data }) => handleLoginWithPassword(data));onExtensionPageMessage('AUTH_LOGIN_TWO_FACTOR', ({ data }) => handleLoginWithTwoFactor(data));+ onExtensionPageMessage('AUTH_LOGIN_MOBILE', ({ data }) => handleLoginWithMobile(data));onExtensionPageMessage('AUTH_UNLOCK_PASSWORD', ({ data }) => handleUnlockWithPassword(data));onExtensionPageMessage('AUTH_UNLOCK_PIN', ({ data }) => handleUnlockWithPin(data));onExtensionPageMessage('AUTH_AWAIT_PENDING', () => handleAwaitPendingAuth());diff --git a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts b/apps/browser-extension/src/entrypoints/background/AuthHandler.tsindex 71d442017..0f23e5377 100644--- a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/AuthHandler.ts@@ -20,6 +20,8 @@ import { sendMessage } from '@/utils/messaging/ExtensionMessaging';import { IncorrectPinError, InvalidPinFormatError, PinLockedError, removeAndDisablePin, resetFailedAttempts, unlockWithPin } from '@/utils/PinUnlockService';import type { BackgroundAuthResult } from '@/utils/types/messaging/BackgroundAuthResult';+import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';+import type { KeyChainKey } from '@aliasvault/client/auth/VaultKeyService';import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';import { browser, storage } from '#imports';@@ -249,7 +251,7 @@ export function handleLoginWithPassword(data: { username: string; password: strireturn { status: 'error', error: { key: 'common.errors.unknownError', wrongPassword: false } };}- return await completeLogin(username, validation.token.token, validation.token.refreshToken, credentials.unlockKeyBase64, loginResponse, data.password);+ return await completeLogin(username, validation.token.token, validation.token.refreshToken, { unlockKey: credentials.unlockKeyBase64 }, loginResponse, data.password);} catch (err) {return failureResult('Login error', err);}@@ -274,30 +276,44 @@ export function handleLoginWithTwoFactor(data: { code: string }): Promise<Backgr}handleClearTwoFactorState();- return await completeLogin(state.username, validation.token.token, validation.token.refreshToken, state.unlockKeyBase64, state.derivationParams);+ return await completeLogin(state.username, validation.token.token, validation.token.refreshToken, { unlockKey: state.unlockKeyBase64 }, state.derivationParams);} catch (err) {return failureResult('2FA error', err);}});}+/**+ * Finish a login a mobile app approved, with the Account Key it sent.+ */+export function handleLoginWithMobile(data: MobileLoginResult): Promise<BackgroundAuthResult> {+ return runExclusive(async () => {+ try {+ const { salt, encryptionType, encryptionSettings } = data;+ return await completeLogin(SrpAuthService.normalizeUsername(data.username), data.token, data.refreshToken, { accountKey: data.accountKey }, { salt, encryptionType, encryptionSettings });+ } catch (err) {+ return failureResult('Mobile login error', err);+ }+ });+}+/*** Store the session of an accepted login and pull its vault. A password login also raises older key derivation* settings to the current defaults.*/-async function completeLogin(username: string, token: string, refreshToken: string, unlockKey: string, derivationParams: UnlockKeyDerivationParams, password?: string): Promise<BackgroundAuthResult> {+async function completeLogin(username: string, token: string, refreshToken: string, key: KeyChainKey, derivationParams: UnlockKeyDerivationParams, password?: string): Promise<BackgroundAuthResult> {await storage.setItem(StorageKeys.USERNAME, username);await storage.setItem(StorageKeys.ACCESS_TOKEN, token);await storage.setItem(StorageKeys.REFRESH_TOKEN, refreshToken);- // Fetch the key chain and check the unlock key opens it. Not recoverable when it fails, so log out again.+ // Fetch the key chain and check the key opens it. Not recoverable when it fails, so log out again.const webApi = new WebApiService();- await UnlockService.completeKeyChainLogin({ unlockKey }, derivationParams, webApi, async () => {+ await UnlockService.completeKeyChainLogin(key, derivationParams, webApi, async () => {await webApi.revokeTokens();await handleClearSession();});- if (password) {- await UnlockService.upgradeKeyDerivation(password, derivationParams, unlockKey, webApi, username);+ if (password && 'unlockKey' in key) {+ await UnlockService.upgradeKeyDerivation(password, derivationParams, key.unlockKey, webApi, username);}// Content scripts are told once the vault is pulled: before that there is nothing to autofill from.diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsxindex 5a21b6954..3a5c79d76 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx@@ -1,8 +1,5 @@-import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';-import { ServerUpdateRequiredError } from '@aliasvault/client/api/errors/ServerUpdateRequiredError';import { VaultProcessingError } from '@aliasvault/client/api/errors/VaultProcessingError';import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';-import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';import { AppInfo } from '@aliasvault/client/platform/AppInfo';import { syncErrorMessage, syncErrorReportDetail } from '@aliasvault/client/sync/SyncErrorMessage';import React, { useEffect, useRef, useState } from 'react';@@ -17,7 +14,6 @@ import Icon from '@/entrypoints/popup/components/Icons/Icon';import LoginServerInfo from '@/entrypoints/popup/components/LoginServerInfo';import VaultErrorReport from '@/entrypoints/popup/components/VaultErrorReport';import { useApp } from '@/entrypoints/popup/context/AppContext';-import { useDb } from '@/entrypoints/popup/context/DbContext';import { useHeaderButtons } from '@/entrypoints/popup/context/HeaderButtonsContext';import { useLoading } from '@/entrypoints/popup/context/LoadingContext';import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';@@ -32,7 +28,6 @@ import type { BackgroundAuthResult } from '@/utils/types/messaging/BackgroundAutimport { vaultStateEvents } from '@/events/VaultStateEvents';import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';-import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';import { storage } from '#imports';@@ -49,7 +44,6 @@ const Login: React.FC = () => {const { t } = useTranslation();const navigate = useNavigate();const app = useApp();- const dbContext = useDb();const { setHeaderButtons } = useHeaderButtons();const [credentials, setCredentials] = useState({username: '',@@ -72,24 +66,6 @@ const Login: React.FC = () => {*/const authInFlightRef = useRef(false);- /**- * Pull the vault from the server.- */- const pullAndLoadVault = async (): Promise<void> => {- const result = await sendMessage('FULL_VAULT_SYNC', { forcePull: true, reportErrorToPopup: false });- if (result.logoutReason === 'clientVersionNotSupported') {- throw new ClientUpgradeRequiredError();- }- if (result.logoutReason === 'serverVersionNotSupported') {- throw new ServerUpdateRequiredError();- }- if (!result.success) {- throw new VaultProcessingError('vault-pull', new Error(syncErrorMessage(result, t) ?? t('common.errors.unknownError')), syncErrorReportDetail(result));- }-- await dbContext.loadStoredDatabase();- };-/*** Show login attempt failure.* @param context - what failed, for the console@@ -162,65 +138,6 @@ const Login: React.FC = () => {}};- /**- * Finish a mobile login: store the tokens and the Account Key, then pull and load the vault.- * @param username - the normalized username- * @param token - the access token- * @param refreshToken - the refresh token- * @param accountKeyFromMobile - the Account Key the phone sent, base64- * @param derivationParams - how the unlock key is derived from the password- */- const handleSuccessfulAuth = async (- username: string,- token: string,- refreshToken: string,- accountKeyFromMobile: string,- derivationParams: UnlockKeyDerivationParams- ) : Promise<void> => {- // Store auth info first; the vault fetch below makes an authenticated request via the stored access token.- await app.setAuthTokens(username, token, refreshToken);-- /*- * Fetch the account's key chain, check the unlock key opens it and cache it as-is; the vault encryption key is- * derived from the two on demand. Legacy accounts have no chain.- */- let accountKey: string;- try {- accountKey = await VaultKeyService.refreshKeyChain({ accountKey: accountKeyFromMobile }, webApi);- } catch (err) {- // If key chain can't be fetched, logout user and show error as this is not a recoverable error.- await app.logout();- throw err;- }-- await dbContext.storeUnlockKeyDerivationParams({- salt: derivationParams.salt,- encryptionType: derivationParams.encryptionType,- encryptionSettings: derivationParams.encryptionSettings- });-- // Store the Account Key, then pull and load the vault.- await dbContext.storeAccountKey(accountKey);- await pullAndLoadVault();-- // Reset prefill flag so next logout will prefill again- usernamePrefillAttempted = false;-- /*- * Navigate to reinitialize page which will:- * 1. Call syncVault() to check version compatibility- * 2. Send the vault through /upgrade when either the legacy sqlite-blob chain or the manifest migration applies- * 3. Navigate to appropriate page- *- * Other windows on /login or /unlock pick up the encryption-key storage- * event via vaultStateEvents.onVaultUnlocked and reload themselves.- */- navigate('/reinitialize', { replace: true });-- // Show app.- hideLoading();- };-useEffect(() => {/*** Load the client URL, check for saved username, and restore 2FA state if available.@@ -354,12 +271,14 @@ const Login: React.FC = () => {app.clearGlobalMessage();setIsInitialLoading(false);- // The mobile device sends its Account Key.- await handleSuccessfulAuth(result.username, result.token, result.refreshToken, result.accountKey, result);- } catch (err) {- await showLoginError('Mobile login error', err);+ // The background stores the session with the Account Key the mobile device sent and pulls the vault.+ const outcome = await runBackgroundAuth(() => sendMessage('AUTH_LOGIN_MOBILE', result));+ if (outcome?.status !== 'success') {+ // Let the modal show an error too; runBackgroundAuth already shows the reason on this page.+ throw new Error('Mobile login failed');+ }+ } finally {hideLoading();- throw err; // Re-throw to let modal show error}};diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.tsindex 3ced24fd5..caa937c47 100644--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts@@ -29,6 +29,7 @@ import type { SaveLoginResponse } from '@/utils/types/messaging/SaveLoginResponsimport type { VaultSyncPhase } from '@/utils/types/messaging/VaultSyncPhase';import type { VaultSyncState } from '@/utils/types/messaging/VaultSyncState';+import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';import type { ItemUsageAction } from '@aliasvault/client/database';import type { ItemRef } from '@aliasvault/client/database/ItemRef';import type { VaultMigrationKind } from '@aliasvault/client/sync/VaultManifestMigration';@@ -59,6 +60,7 @@ export interface IExtensionMessageProtocol {AUTH_AWAIT_PENDING(): BackgroundAuthResult | null;AUTH_LOGIN(data: { username: string; password: string; rememberMe: boolean }): BackgroundAuthResult;AUTH_LOGIN_TWO_FACTOR(data: { code: string }): BackgroundAuthResult;+ AUTH_LOGIN_MOBILE(data: MobileLoginResult): BackgroundAuthResult;AUTH_UNLOCK_PASSWORD(data: { password: string }): BackgroundAuthResult;AUTH_UNLOCK_PIN(data: { pin: string }): BackgroundAuthResult;ADD_URL_TO_CREDENTIAL(data: { itemId: string; manifestId: string; url: string }): { success: boolean; error?: string };diff --git a/apps/web/src/pages/auth/Unlock.tsx b/apps/web/src/pages/auth/Unlock.tsxindex f1e704429..beb9794d1 100644--- a/apps/web/src/pages/auth/Unlock.tsx+++ b/apps/web/src/pages/auth/Unlock.tsx@@ -199,7 +199,7 @@ const Unlock: React.FC = () => {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.+ // Throws a key-out-of-sync (E-208) error if the key does not open the key chain.await UnlockService.completeKeyChainLogin({ accountKey: result.accountKey }, result, webApi);navigate('/sync', { replace: true });} catch (err) {diff --git a/core/client/src/auth/VaultKeyService.ts b/core/client/src/auth/VaultKeyService.tsindex 6d0d41cce..b081d76b1 100644--- a/core/client/src/auth/VaultKeyService.ts+++ b/core/client/src/auth/VaultKeyService.ts@@ -71,7 +71,8 @@ export class VaultKeyService {* @param key - the unlock key of the password login, or the Account Key a mobile app sent* @param webApi - the API client to use* @returns The Account Key to store for this session.- * @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain (wrong password).+ * @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the unlock key does not open the chain (wrong password),+ * or {@link AppErrorCode.KEY_OUT_OF_SYNC} when the Account Key does not (a stale key).*/public static async refreshKeyChain(key: KeyChainKey, webApi?: WebApiService): Promise<string> {const result = await VaultKeyService.fetchVaultKey(webApi);@@ -94,7 +95,16 @@ export class VaultKeyService {throw new Error(formatErrorWithCode(`Unsupported Account Key algorithm '${result.vaultKey.algorithm}'`, AppErrorCode.VAULT_VERSION_INCOMPATIBLE));}- const keys = await VaultKeyService.openChain(key, result.vaultKey.encryptedAccountKey, result.vaultKey.encryptedVek ?? null, null);+ let keys: SessionKeys;+ try {+ keys = await VaultKeyService.openChain(key, result.vaultKey.encryptedAccountKey, result.vaultKey.encryptedVek ?? null, null);+ } catch (error) {+ // An Account Key the server's chain rejects is stale (the keys changed since it was stored), never a wrong password.+ if ('accountKey' in key && error instanceof Error && extractErrorCode(error.message) === AppErrorCode.UNLOCK_KEY_REJECTED) {+ throw new Error(formatErrorWithCode('The Account Key does not open the key chain the server holds', AppErrorCode.KEY_OUT_OF_SYNC));+ }+ throw error;+ }/** A device holding a vault under its unlock key but no chain yet (the account was upgraded on another device) stays