Skip to content

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

Move browser extension login/unlock to background to continue when popup close (#2374)

Leendert de Borst648b56eb03ab
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index deaebb2b8..c562f0749 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -4,13 +4,14 @@
import '@/platform/ClientServices';
+import { broadcastVaultUnlocked, handleAwaitPendingAuth, 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 { setupContextMenus } from '@/entrypoints/background/ContextMenu';
import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, handlePasskeyPopupResponse, handleGetRequestData, handleGetMatchingPasskeys, handleWebAuthnGetAssertion } from '@/entrypoints/background/PasskeyHandler';
import { handleOpenPopup, handlePopupWithItem, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';
import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePromptState, handleStoreLastAutofilled, handleGetLastAutofilled, handleClearLastAutofilled } from '@/entrypoints/background/SavePromptStateHandler';
-import { handleStoreTwoFactorState, handleGetTwoFactorState, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
+import { handleGetTwoFactorState, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetEncryptionKey, handleGetUnlockKeyDerivationParams, handleGetPersistedFormValues, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreUnlockKey, handleStoreUnlockKeyDerivationParams, handleStoreEncryptedVaultChunk, handleGetSyncState, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupUpdateVault, handleGroupRevokeAccess, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';
import { logFailure } from '@/utils/Diagnostics';
@@ -135,28 +136,6 @@ function onExtensionPageMessage<TType extends keyof IExtensionMessageProtocol>(
});
}
-/**
- * Notify content scripts in all tabs that the vault was unlocked, so any conditional passkey
- * request parked while the vault was locked can re-query and surface its passkeys.
- */
-async function broadcastVaultUnlocked(): Promise<void> {
- try {
- const tabs = await browser.tabs.query({});
- await Promise.all(tabs.map(async (tab) => {
- if (tab.id === undefined) {
- return;
- }
- try {
- await sendMessage('VAULT_UNLOCKED', undefined, tab.id);
- } catch {
- // No receiving content script in this tab — ignore.
- }
- }));
- } catch {
- // tabs.query can fail in rare contexts — best-effort, ignore.
- }
-}
-
/**
* Validate a WebAuthn create request against the sender's trusted origin, then forward it to the
* passkey create flow. Falls back when the sender is untrusted or validation fails.
@@ -286,10 +265,21 @@ export default defineBackground({
});
onExtensionPageMessage('STORE_UNLOCK_KEY_DERIVATION_PARAMS', ({ data }) => handleStoreUnlockKeyDerivationParams(data));
+ // 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_UNLOCK_PASSWORD', ({ data }) => handleUnlockWithPassword(data));
+ onExtensionPageMessage('AUTH_UNLOCK_PIN', ({ data }) => handleUnlockWithPin(data));
+ onExtensionPageMessage('AUTH_AWAIT_PENDING', () => handleAwaitPendingAuth());
+
onExtensionPageMessage('STORE_ENCRYPTED_VAULT', ({ data }) => handleStoreEncryptedVaultChunk(data));
onExtensionPageMessage('GET_SYNC_STATE', () => handleGetSyncState());
onExtensionPageMessage('FULL_VAULT_SYNC', ({ data }) => handleFullVaultSync(data));
+ onExtensionPageMessage('START_VAULT_SYNC', () => {
+ void handleFullVaultSync().catch(error => logFailure('Background vault sync failed', error));
+ return { success: true };
+ });
onExtensionPageMessage('GET_VAULT_MIGRATION_STATUS', () => handleGetVaultMigrationStatus());
onExtensionPageMessage('MIGRATE_VAULT_MANIFEST', () => handleMigrateVaultManifest());
onExtensionPageMessage('GROUP_CREATE_VAULT', ({ data }) => handleGroupCreateVault(data));
@@ -339,7 +329,6 @@ export default defineBackground({
onMessage('CLEAR_LAST_AUTOFILLED', ({ sender }) => handleClearLastAutofilled({ tabId: sender.tab!.id! }));
// Two-factor authentication state persistence
- onExtensionPageMessage('STORE_TWO_FACTOR_STATE', ({ data }) => handleStoreTwoFactorState(data));
onExtensionPageMessage('GET_TWO_FACTOR_STATE', () => handleGetTwoFactorState());
onExtensionPageMessage('CLEAR_TWO_FACTOR_STATE', () => handleClearTwoFactorState());
diff --git a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts b/apps/browser-extension/src/entrypoints/background/AuthHandler.ts
new file mode 100644
index 000000000..5612925c1
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/background/AuthHandler.ts
@@ -0,0 +1,312 @@
+import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';
+import { ServerUpdateRequiredError } from '@aliasvault/client/api/errors/ServerUpdateRequiredError';
+import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
+import { WebApiService } from '@aliasvault/client/api/WebApiService';
+import { describeAuthError, type AuthErrorOptions } from '@aliasvault/client/auth/AuthErrorMessage';
+import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
+import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';
+import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';
+import { logoutReasonKey } from '@aliasvault/client/sync/VaultSync';
+
+import { handleClearTwoFactorState, handleGetTwoFactorState, handleStoreTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
+import { handleClearSession, handleFullVaultSync, handleGetUnlockKeyDerivationParams, handleStoreUnlockKey, handleStoreUnlockKeyDerivationParams } from '@/entrypoints/background/VaultMessageHandler';
+
+import { StorageKeys } from '@/utils/constants/storageKeys';
+import { logExpected, logFailure } from '@/utils/Diagnostics';
+import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
+import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
+import { IncorrectPinError, InvalidPinFormatError, PinLockedError, resetFailedAttempts, unlockWithPin } from '@/utils/PinUnlockService';
+import type { BackgroundAuthResult } from '@/utils/types/messaging/BackgroundAuthResult';
+
+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
+
+import { browser, storage } from '#imports';
+
+/*
+ * Login and unlock run start in the popup but are completed in the background so they still complete when the popup closes mid-flow.
+ */
+let pendingAuth: Promise<BackgroundAuthResult> | null = null;
+
+/**
+ * Run an auth flow unless one is already running, in which case its result is returned.
+ */
+function runExclusive(flow: () => Promise<BackgroundAuthResult>): Promise<BackgroundAuthResult> {
+ if (pendingAuth) {
+ return pendingAuth;
+ }
+
+ const run = flow().finally(() => {
+ if (pendingAuth === run) {
+ pendingAuth = null;
+ }
+ });
+ pendingAuth = run;
+ return run;
+}
+
+/**
+ * The result of the auth flow that is running, or null when none is.
+ */
+export function handleAwaitPendingAuth(): Promise<BackgroundAuthResult | null> {
+ return pendingAuth ?? Promise.resolve(null);
+}
+
+/**
+ * Notify content scripts in all tabs that the vault was unlocked, so any conditional passkey request parked while
+ * the vault was locked can re-query, and an autofill popup the user unlocked from can reopen.
+ */
+export async function broadcastVaultUnlocked(): Promise<void> {
+ try {
+ const tabs = await browser.tabs.query({});
+ await Promise.all(tabs.map(async (tab) => {
+ if (tab.id === undefined) {
+ return;
+ }
+ try {
+ await sendMessage('VAULT_UNLOCKED', undefined, tab.id);
+ } catch {
+ // No receiving content script in this tab, ignore.
+ }
+ }));
+ } catch {
+ // tabs.query can fail in rare contexts, best-effort, ignore.
+ }
+}
+
+/**
+ * Map a failed flow to its result.
+ */
+async function failureResult(context: string, err: unknown, options?: AuthErrorOptions): Promise<BackgroundAuthResult> {
+ if (err instanceof VaultVersionIncompatibleError) {
+ return { status: 'logout', message: err.message };
+ }
+ if (err instanceof ClientUpgradeRequiredError) {
+ return { status: 'logout', reasonKey: 'common.errors.clientNotSupported' };
+ }
+
+ logFailure(context, err);
+ return { status: 'error', error: await describeAuthError(err, options) };
+}
+
+/**
+ * Check the server status before an unlock. Returns whether the server is reachable, or the logout this client needs.
+ */
+async function checkServerStatus(webApi: WebApiService): Promise<{ online: boolean } | { logout: BackgroundAuthResult }> {
+ try {
+ const status = await webApi.getStatus();
+ if (status.serverVersion === '0.0.0') {
+ return { online: false };
+ }
+
+ const statusError = webApi.validateStatusResponse(status);
+ if (statusError !== null) {
+ return { logout: { status: 'logout', reasonKey: logoutReasonKey(statusError) } };
+ }
+ return { online: true };
+ } catch (err) {
+ if (err instanceof ClientUpgradeRequiredError) {
+ return { logout: { status: 'logout', reasonKey: 'common.errors.clientNotSupported' } };
+ }
+
+ // Any other error is an auth failure: the server is reachable but the session is gone.
+ logExpected('[Auth] Status check failed during unlock', err);
+ return { logout: { status: 'logout', reasonKey: 'common.errors.sessionExpired' } };
+ }
+}
+
+/**
+ * Store the checked unlock key, which unlocks the vault, and tell content scripts about it.
+ */
+async function storeUnlockKey(unlockKey: string, offline: boolean, broadcast: boolean): Promise<void> {
+ const stored = await handleStoreUnlockKey(unlockKey);
+ if (!stored.success) {
+ throw new Error(stored.error);
+ }
+
+ await storage.setItem(StorageKeys.IS_OFFLINE_MODE, offline);
+ await LocalPreferencesService.setVaultLockedDismissUntil(0);
+ if (broadcast) {
+ void broadcastVaultUnlocked();
+ }
+}
+
+/**
+ * Unlock the vault with the master password, online against the server's key chain or offline against the cached one.
+ */
+export function handleUnlockWithPassword(data: { password: string }): Promise<BackgroundAuthResult> {
+ return runExclusive(async () => {
+ const webApi = new WebApiService();
+ const status = await checkServerStatus(webApi);
+ if ('logout' in status) {
+ return status.logout;
+ }
+
+ try {
+ let unlockKey: string;
+ if (status.online) {
+ const username = await storage.getItem<string>(StorageKeys.USERNAME);
+ const loginResponse = await new SrpLoginService(webApi).initiateLogin(username!);
+ const credentials = await SrpAuthService.prepareCredentials(data.password, loginResponse.salt, loginResponse.encryptionSettings);
+ await handleStoreUnlockKeyDerivationParams({ salt: loginResponse.salt, encryptionType: loginResponse.encryptionType, encryptionSettings: loginResponse.encryptionSettings });
+
+ // Throws an unlock-key-rejected (E-206) error on a wrong password.
+ unlockKey = credentials.passwordHashBase64;
+ await VaultKeyService.refreshKeyChain(unlockKey, webApi);
+ } else {
+ const storedParams = await handleGetUnlockKeyDerivationParams();
+ if (!storedParams) {
+ // Offline unlock needs the derivation params of an earlier online login.
+ return { status: 'error', error: { key: 'common.errors.serverNotAvailable', wrongPassword: false } };
+ }
+
+ const credentials = await SrpAuthService.prepareCredentials(data.password, storedParams.salt, storedParams.encryptionSettings);
+ unlockKey = credentials.passwordHashBase64;
+ await VaultKeyService.verifyUnlockKey(unlockKey);
+ }
+
+ await storeUnlockKey(unlockKey, !status.online, true);
+ await resetFailedAttempts();
+ await LocalPreferencesService.resetPasswordUnlockFailedAttempts();
+ await LocalPreferencesService.setLastUsedUnlockMethod('password');
+ return { status: 'success', offline: !status.online };
+ } catch (err) {
+ const message = await describeAuthError(err, { uncodedIsWrongPassword: true });
+ if (message.wrongPassword) {
+ const failedAttempts = await LocalPreferencesService.getPasswordUnlockFailedAttempts() + 1;
+ await LocalPreferencesService.setPasswordUnlockFailedAttempts(failedAttempts);
+ return { status: 'wrongPassword', failedAttempts };
+ }
+ return failureResult('Unlock error', err, { uncodedIsWrongPassword: true });
+ }
+ });
+}
+
+/**
+ * Unlock the vault with the PIN, which decrypts the stored unlock key.
+ */
+export function handleUnlockWithPin(data: { pin: string }): Promise<BackgroundAuthResult> {
+ return runExclusive(async () => {
+ try {
+ const unlockKey = await unlockWithPin(data.pin);
+ await VaultKeyService.verifyUnlockKey(unlockKey);
+
+ const status = await checkServerStatus(new WebApiService());
+ if ('logout' in status) {
+ return status.logout;
+ }
+
+ await storeUnlockKey(unlockKey, !status.online, true);
+ await LocalPreferencesService.setLastUsedUnlockMethod('pin');
+ return { status: 'success', offline: !status.online };
+ } catch (err) {
+ if (err instanceof PinLockedError) {
+ return { status: 'pinFailed', reason: 'locked' };
+ }
+ if (err instanceof IncorrectPinError) {
+ return { status: 'pinFailed', reason: 'incorrect', attemptsRemaining: err.attemptsRemaining };
+ }
+ if (err instanceof InvalidPinFormatError) {
+ return { status: 'pinFailed', reason: 'invalidFormat' };
+ }
+
+ const message = await describeAuthError(err, { fallback: 'common.errors.unknownErrorTryAgain' });
+ if (message.wrongPassword) {
+ // The key the PIN restored does not open the key chain, treat as an incorrect PIN.
+ logExpected('[Unlock] The entered PIN did not decrypt the vault', err);
+ return { status: 'pinFailed', reason: 'incorrect', attemptsRemaining: 3 };
+ }
+ return failureResult('PIN unlock failed', err, { fallback: 'common.errors.unknownErrorTryAgain' });
+ }
+ });
+}
+
+/**
+ * Log in with username and master password. Returns `twoFactorRequired` when the account needs a 2FA code next.
+ */
+export function handleLoginWithPassword(data: { username: string; password: string; rememberMe: boolean }): Promise<BackgroundAuthResult> {
+ return runExclusive(async () => {
+ try {
+ const username = SrpAuthService.normalizeUsername(data.username);
+ const srp = new SrpLoginService(new WebApiService());
+ const loginResponse = await srp.initiateLogin(username);
+ const { passwordHashString, passwordHashBase64 } = await SrpAuthService.prepareCredentials(data.password, loginResponse.salt, loginResponse.encryptionSettings);
+ const validation = await srp.validateLogin(username, passwordHashString, data.rememberMe, loginResponse);
+
+ if (validation.requiresTwoFactor) {
+ // Kept in memory for the 2FA step, which may come from a reopened popup.
+ handleStoreTwoFactorState({ username, loginResponse, passwordHashString, passwordHashBase64, rememberMe: data.rememberMe });
+ return { status: 'twoFactorRequired', username, rememberMe: data.rememberMe };
+ }
+ if (!validation.token) {
+ return { status: 'error', error: { key: 'common.errors.unknownError', wrongPassword: false } };
+ }
+
+ return await completeLogin(username, validation.token.token, validation.token.refreshToken, passwordHashBase64, loginResponse);
+ } catch (err) {
+ return failureResult('Login error', err);
+ }
+ });
+}
+
+/**
+ * Finish a login that needs a 2FA code, using the state the password step left behind.
+ */
+export function handleLoginWithTwoFactor(data: { code: string }): Promise<BackgroundAuthResult> {
+ return runExclusive(async () => {
+ const state = handleGetTwoFactorState();
+ if (!state) {
+ return { status: 'error', error: { key: 'common.errors.unknownError', wrongPassword: false } };
+ }
+
+ try {
+ const srp = new SrpLoginService(new WebApiService());
+ const validation = await srp.validateLogin2Fa(state.username, state.passwordHashString, state.rememberMe, state.loginResponse, parseInt(data.code));
+ if (!validation.token) {
+ return { status: 'error', error: { key: 'common.errors.unknownError', wrongPassword: false } };
+ }
+
+ handleClearTwoFactorState();
+ return await completeLogin(state.username, validation.token.token, validation.token.refreshToken, state.passwordHashBase64, state.loginResponse);
+ } catch (err) {
+ return failureResult('2FA error', err);
+ }
+ });
+}
+
+/**
+ * Store the session of an accepted login and pull its vault.
+ */
+async function completeLogin(username: string, token: string, refreshToken: string, unlockKey: string, derivationParams: UnlockKeyDerivationParams): 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.
+ const webApi = new WebApiService();
+ try {
+ await VaultKeyService.refreshKeyChain(unlockKey, webApi);
+ } catch (err) {
+ await webApi.revokeTokens();
+ await handleClearSession();
+ throw err;
+ }
+
+ await handleStoreUnlockKeyDerivationParams({ salt: derivationParams.salt, encryptionType: derivationParams.encryptionType, encryptionSettings: derivationParams.encryptionSettings });
+
+ // Content scripts are told once the vault is pulled: before that there is nothing to autofill from.
+ await storeUnlockKey(unlockKey, false, false);
+
+ const sync = await handleFullVaultSync({ forcePull: true, reportErrorToPopup: false });
+ if (sync.logoutReason === 'clientVersionNotSupported') {
+ throw new ClientUpgradeRequiredError();
+ }
+ if (sync.logoutReason === 'serverVersionNotSupported') {
+ return { status: 'error', error: await describeAuthError(new ServerUpdateRequiredError()) };
+ }
+ if (!sync.success) {
+ return { status: 'vaultPullFailed', sync };
+ }
+
+ void broadcastVaultUnlocked();
+ return { status: 'success', offline: false };
+}
diff --git a/apps/browser-extension/src/entrypoints/background/TwoFactorStateHandler.ts b/apps/browser-extension/src/entrypoints/background/TwoFactorStateHandler.ts
index a87d6e0c7..0ee61f42a 100644
--- a/apps/browser-extension/src/entrypoints/background/TwoFactorStateHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/TwoFactorStateHandler.ts
@@ -4,9 +4,8 @@
* This handler stores 2FA login state ONLY in memory, and the state automatically
* expires after a short timeout.
*
- * This allows users to enter username/password and get to 2FA prompt, close popup
- * to switch to authenticator app, and reopen popup and continue from 2FA prompt
- * without re-entering credentials.
+ * The background login flow (AuthHandler) stores it after the password step and reads it back for the 2FA step,
+ * so users can close the popup to switch to their authenticator app and continue without re-entering credentials.
*/
import type { LoginResponse } from '@aliasvault/models/webapi';
@@ -24,9 +23,9 @@ export type TwoFactorState = {
};
/**
- * Timeout for automatic state expiration (60 seconds).
+ * Timeout for automatic state expiration.
*/
-const STATE_EXPIRY_MS = 60 * 1000;
+const STATE_EXPIRY_MS = 5 * 60 * 1000;
/**
* In-memory storage for 2FA state.
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useFinishBackgroundAuth.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useFinishBackgroundAuth.ts
new file mode 100644
index 000000000..27e46434e
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useFinishBackgroundAuth.ts
@@ -0,0 +1,44 @@
+import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
+import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+import { useApp } from '@/entrypoints/popup/context/AppContext';
+import { useDb } from '@/entrypoints/popup/context/DbContext';
+
+import { logFailure } from '@/utils/Diagnostics';
+
+/**
+ * Finish a login or unlock the background completed: load the vault it unlocked and continue.
+ */
+export function useFinishBackgroundAuth(): (offline: boolean) => Promise<string | null> {
+ const { t } = useTranslation();
+ const app = useApp();
+ const dbContext = useDb();
+ const navigate = useNavigate();
+
+ return useCallback(async (offline: boolean): Promise<string | null> => {
+ try {
+ await app.initializeAuth();
+ await dbContext.setIsOffline(offline);
+
+ const sqliteClient = await dbContext.loadStoredDatabase();
+ if (sqliteClient && await sqliteClient.requiresLegacySqliteBlobMigration()) {
+ navigate('/upgrade', { replace: true });
+ return null;
+ }
+
+ // Reinitialize syncs with the server and routes to the page to show.
+ navigate('/reinitialize', { replace: true });
+ return null;
+ } catch (err) {
+ if (err instanceof VaultVersionIncompatibleError) {
+ await app.logout(err.message);
+ return null;
+ }
+ logFailure('Loading the unlocked vault failed', err);
+ return formatErrorMessage(await describeAuthError(err, { fallback: 'common.errors.unknownErrorTryAgain' }), t);
+ }
+ }, [app, dbContext, navigate, t]);
+}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx b/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx
index fc753e053..228cabe76 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx
@@ -199,17 +199,23 @@ const Reinitialize: React.FC = () => {
* This ensures the UI is responsive even if server is slow to respond.
* All branches below are idempotent so this can safely run more than once (see the `location.key` note above).
*/
- setIsInitialLoading(false);
if (inlineUnlock) {
- navigate('/unlock-success', { replace: true });
- } else {
- // Check for pending redirect URL in storage (set by useVaultLockRedirect hook)
- const pendingRedirectUrl = await consumePendingRedirectUrl();
- if (pendingRedirectUrl) {
- navigate(pendingRedirectUrl, { replace: true });
- } else {
- await restoreLastPage();
+ if (!hasInitialized.current) {
+ hasInitialized.current = true;
+ await sendMessage('START_VAULT_SYNC');
}
+ window.close();
+ return;
+ }
+
+ setIsInitialLoading(false);
+
+ // Check for pending redirect URL in storage (set by useVaultLockRedirect hook)
+ const pendingRedirectUrl = await consumePendingRedirectUrl();
+ if (pendingRedirectUrl) {
+ navigate(pendingRedirectUrl, { replace: true });
+ } else {
+ await restoreLastPage();
}
// Run the background sync once.
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
index 961ff2b96..52407c821 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
@@ -2,12 +2,10 @@ import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/Client
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 { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
-import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';
import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import { syncErrorMessage } from '@aliasvault/client/sync/SyncErrorMessage';
-import React, { useEffect, useState } from 'react';
+import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -22,17 +20,18 @@ 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';
+import { useFinishBackgroundAuth } from '@/entrypoints/popup/hooks/useFinishBackgroundAuth';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
import { StorageKeys } from '@/utils/constants/storageKeys';
import { logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
+import type { BackgroundAuthResult } from '@/utils/types/messaging/BackgroundAuthResult';
import { vaultStateEvents } from '@/events/VaultStateEvents';
import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';
import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
-import type { LoginResponse } from '@aliasvault/models/webapi';
import { storage } from '#imports';
@@ -58,9 +57,6 @@ const Login: React.FC = () => {
const { showLoading, hideLoading, setIsInitialLoading } = useLoading();
const [rememberMe, setRememberMe] = useState(true);
const [showPassword, setShowPassword] = useState(false);
- const [loginResponse, setLoginResponse] = useState<LoginResponse | null>(null);
- const [passwordHashString, setPasswordHashString] = useState<string | null>(null);
- const [passwordHashBase64, setPasswordHashBase64] = useState<string | null>(null);
const [twoFactorRequired, setTwoFactorRequired] = useState(false);
const [twoFactorCode, setTwoFactorCode] = useState('');
const [clientUrl, setClientUrl] = useState<string | null>(null);
@@ -68,7 +64,12 @@ const Login: React.FC = () => {
const [vaultError, setVaultError] = useState<VaultProcessingError | null>(null);
const [showMobileLoginModal, setShowMobileLoginModal] = useState(false);
const webApi = useWebApi();
- const srpUtil = new SrpLoginService(webApi);
+ const finishBackgroundAuth = useFinishBackgroundAuth();
+
+ /**
+ * True while this page waits for a background login, so its own login does not trigger the cross-window reload.
+ */
+ const authInFlightRef = useRef(false);
/**
* Pull the vault from the server.
@@ -104,7 +105,64 @@ const Login: React.FC = () => {
};
/**
- * Finish a password or mobile login: store the tokens and unlock key, then pull and load the vault.
+ * Run a login flow in the background and show its outcome. Resolves to the outcome, or null when none ran.
+ */
+ const runBackgroundAuth = async (start: () => Promise<BackgroundAuthResult | null>): Promise<BackgroundAuthResult | null> => {
+ authInFlightRef.current = true;
+ let result: BackgroundAuthResult | null = null;
+ try {
+ result = await start();
+ if (result) {
+ await handleAuthResult(result);
+ }
+ } catch (err) {
+ await showLoginError('Login error', err);
+ } finally {
+ // After a success the page navigates away, keep ignoring the unlock event until then.
+ authInFlightRef.current = result?.status === 'success';
+ }
+ return result;
+ };
+
+ /**
+ * Show the outcome of a background login flow.
+ */
+ const handleAuthResult = async (result: BackgroundAuthResult): Promise<void> => {
+ switch (result.status) {
+ case 'success': {
+ // Reset prefill flag so next logout will prefill again
+ usernamePrefillAttempted = false;
+ setTwoFactorRequired(false);
+ setTwoFactorCode('');
+ const finishError = await finishBackgroundAuth(result.offline);
+ if (finishError) {
+ setError(finishError);
+ }
+ return;
+ }
+ case 'twoFactorRequired':
+ setCredentials({ username: result.username, password: '' });
+ setRememberMe(result.rememberMe);
+ setTwoFactorRequired(true);
+ return;
+ case 'vaultPullFailed':
+ // The vault was fetched but couldn't be decrypted/materialized, surface the real error (copyable) for support.
+ setVaultError(new VaultProcessingError('vault-pull', new Error(syncErrorMessage(result.sync, t) ?? t('common.errors.unknownError'))));
+ return;
+ case 'logout':
+ setError(result.message ?? t(result.reasonKey ?? 'common.errors.unknownError'));
+ return;
+ case 'error':
+ setError(formatErrorMessage(result.error, t));
+ return;
+ default:
+ // An unlock flow finished while this page was open, reinitialize routes to where it left the popup.
+ navigate('/reinitialize', { replace: true });
+ }
+ };
+
+ /**
+ * Finish a mobile login: store the tokens and unlock key, then pull and load the vault.
* @param username - the normalized username
* @param token - the access token
* @param refreshToken - the refresh token
@@ -174,6 +232,14 @@ const Login: React.FC = () => {
}
setClientUrl(clientUrl);
+ // Pick up a login the background is still running because the popup was closed mid-login.
+ const pending = await runBackgroundAuth(() => sendMessage('AUTH_AWAIT_PENDING'));
+ if (pending) {
+ twoFactorStateRestoreAttempted = true;
+ setIsInitialLoading(false);
+ return;
+ }
+
/*
* Check for persisted 2FA state (from popup close during 2FA entry).
* This allows users to close the popup to switch to their authenticator app
@@ -183,11 +249,8 @@ const Login: React.FC = () => {
twoFactorStateRestoreAttempted = true;
const savedState = await sendMessage('GET_TWO_FACTOR_STATE');
if (savedState) {
- // Restore the 2FA state
+ // Restore the 2FA step, the background keeps what it needs to finish the login.
setCredentials({ username: savedState.username, password: '' });
- setLoginResponse(savedState.loginResponse);
- setPasswordHashString(savedState.passwordHashString);
- setPasswordHashBase64(savedState.passwordHashBase64);
setRememberMe(savedState.rememberMe);
setTwoFactorRequired(true);
setIsInitialLoading(false);
@@ -210,6 +273,7 @@ const Login: React.FC = () => {
setIsInitialLoading(false);
};
loadInitialData();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [setIsInitialLoading]);
// Set header buttons on mount and clear on unmount
@@ -236,7 +300,9 @@ const Login: React.FC = () => {
*/
useEffect(() => {
return vaultStateEvents.onVaultUnlocked(() => {
- window.location.reload();
+ if (!authInFlightRef.current) {
+ window.location.reload();
+ }
});
}, []);
@@ -247,72 +313,13 @@ const Login: React.FC = () => {
e.preventDefault();
setError(null);
setVaultError(null);
+ showLoading();
- try {
- showLoading();
-
- // Clear global message if set with every login attempt.
- app.clearGlobalMessage();
-
- // Initiate login with server
- const normalizedUsername = SrpAuthService.normalizeUsername(credentials.username);
- const loginResponse = await srpUtil.initiateLogin(normalizedUsername);
-
- // Derive key from password using Argon2id and prepare credentials
- const { passwordHashString, passwordHashBase64 } = await SrpAuthService.prepareCredentials(credentials.password, loginResponse.salt, loginResponse.encryptionSettings);
-
- // Validate login with SRP protocol
- const validationResponse = await srpUtil.validateLogin(
- normalizedUsername,
- passwordHashString,
- rememberMe,
- loginResponse
- );
-
- // Handle 2FA if required
- if (validationResponse.requiresTwoFactor) {
- // Store login response as we need it for 2FA validation
- setLoginResponse(loginResponse);
- // Store password hash string as we need it for 2FA validation
- setPasswordHashString(passwordHashString);
- // Store password hash base64 as we need it for decryption
- setPasswordHashBase64(passwordHashBase64);
- setTwoFactorRequired(true);
-
- /*
- * Persist 2FA state to background script so user can
- * close popup to switch to authenticator app and continue when reopening
- */
- await sendMessage('STORE_TWO_FACTOR_STATE', {
- username: normalizedUsername,
- loginResponse,
- passwordHashString,
- passwordHashBase64,
- rememberMe,
- });
-
- // Show app.
- hideLoading();
- return;
- }
-
- // Check if token was returned.
- if (!validationResponse.token) {
- throw new Error(t('common.errors.unknownError'));
- }
+ // Clear global message if set with every login attempt.
+ app.clearGlobalMessage();
- // Handle successful authentication
- await handleSuccessfulAuth(
- normalizedUsername,
- validationResponse.token.token,
- validationResponse.token.refreshToken,
- passwordHashBase64,
- loginResponse
- );
- } catch (err) {
- await showLoginError('Login error', err);
- hideLoading();
- }
+ await runBackgroundAuth(() => sendMessage('AUTH_LOGIN', { username: credentials.username, password: credentials.password, rememberMe }));
+ hideLoading();
};
/**
@@ -323,55 +330,16 @@ const Login: React.FC = () => {
setError(null);
setVaultError(null);
- try {
- showLoading();
-
- if (!passwordHashString || !passwordHashBase64 || !loginResponse) {
- throw new Error(t('common.errors.unknownError'));
- }
-
- // Validate that 2FA code is a 6-digit number
- const code = twoFactorCode.trim();
- if (!/^\d{6}$/.test(code)) {
- throw new Error(t('common.errors.invalidCode'));
- }
-
- const twoFaUsername = SrpAuthService.normalizeUsername(credentials.username);
- const validationResponse = await srpUtil.validateLogin2Fa(
- twoFaUsername,
- passwordHashString,
- rememberMe,
- loginResponse,
- parseInt(twoFactorCode)
- );
-
- // Check if token was returned.
- if (!validationResponse.token) {
- throw new Error(t('common.errors.unknownError'));
- }
-
- // Clear any persisted 2FA state since login is successful
- await sendMessage('CLEAR_TWO_FACTOR_STATE');
-
- // Handle successful authentication
- await handleSuccessfulAuth(
- twoFaUsername,
- validationResponse.token.token,
- validationResponse.token.refreshToken,
- passwordHashBase64,
- loginResponse
- );
-
- // Reset 2FA state and login response as it's no longer needed
- setTwoFactorRequired(false);
- setTwoFactorCode('');
- setPasswordHashString(null);
- setPasswordHashBase64(null);
- setLoginResponse(null);
- } catch (err) {
- await showLoginError('2FA error', err);
- hideLoading();
+ // Validate that 2FA code is a 6-digit number
+ const code = twoFactorCode.trim();
+ if (!/^\d{6}$/.test(code)) {
+ setError(t('common.errors.invalidCode'));
+ return;
}
+
+ showLoading();
+ await runBackgroundAuth(() => sendMessage('AUTH_LOGIN_TWO_FACTOR', { code }));
+ hideLoading();
};
/**
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
index 770e6f1fa..bbafbb7ef 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
@@ -1,8 +1,6 @@
import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';
import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';
-import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
-import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';
import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';
import { logoutReasonKey } from '@aliasvault/client/sync/VaultSync';
import React, { useEffect, useState, useCallback, useRef } from 'react';
@@ -23,20 +21,14 @@ 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';
+import { useFinishBackgroundAuth } from '@/entrypoints/popup/hooks/useFinishBackgroundAuth';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
-import { logExpected, logFailure } from '@/utils/Diagnostics';
+import { logFailure } from '@/utils/Diagnostics';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
-import {
- getPinLength,
- isPinEnabled,
- PinLockedError,
- IncorrectPinError,
- InvalidPinFormatError,
- resetFailedAttempts,
- unlockWithPin
-} from '@/utils/PinUnlockService';
+import { getPinLength, isPinEnabled, resetFailedAttempts } from '@/utils/PinUnlockService';
+import type { BackgroundAuthResult } from '@/utils/types/messaging/BackgroundAuthResult';
import { vaultStateEvents } from '@/events/VaultStateEvents';
@@ -60,7 +52,12 @@ const Unlock: React.FC = () => {
const { setHeaderButtons } = useHeaderButtons();
const webApi = useWebApi();
- const srpUtil = new SrpLoginService(webApi);
+ const finishBackgroundAuth = useFinishBackgroundAuth();
+
+ /**
+ * True while this page waits for a background unlock, so its own unlock does not trigger the cross-window reload.
+ */
+ const authInFlightRef = useRef(false);
// Unlock mode state
const [unlockMode, setUnlockMode] = useState<UnlockMode>('password');
@@ -70,7 +67,6 @@ const Unlock: React.FC = () => {
// Password unlock state
const [password, setPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
- const [passwordFailedAttempts, setPasswordFailedAttempts] = useState(0);
// Brute force protection constants
const MAX_PASSWORD_ATTEMPTS = 10;
@@ -143,16 +139,20 @@ const Unlock: React.FC = () => {
* Initialize unlock page - check status and PIN availability
*/
const initialize = async (): Promise<void> => {
- const [pinEnabled, pinLength, lastUsed, storedAttempts] = await Promise.all([
+ // Pick up an unlock the background is still running because the popup was closed mid-unlock.
+ const pending = await runBackgroundAuth(() => sendMessage('AUTH_AWAIT_PENDING'));
+ if (pending?.status === 'success') {
+ return;
+ }
+
+ const [pinEnabled, pinLength, lastUsed] = await Promise.all([
isPinEnabled(),
getPinLength(),
LocalPreferencesService.getLastUsedUnlockMethod(),
- LocalPreferencesService.getPasswordUnlockFailedAttempts(),
]);
setPinAvailable(pinEnabled);
setPinLength(pinLength || 6);
- setPasswordFailedAttempts(storedAttempts);
/*
* Pick the initial screen from the last-used method, falling back to
@@ -207,7 +207,9 @@ const Unlock: React.FC = () => {
*/
useEffect(() => {
return vaultStateEvents.onVaultUnlocked(() => {
- window.location.reload();
+ if (!authInFlightRef.current) {
+ window.location.reload();
+ }
});
}, []);
@@ -259,123 +261,68 @@ const Unlock: React.FC = () => {
}, [unlockMode]);
/**
- * Handle password unlock (supports both online and offline mode)
+ * Run a login or unlock flow in the background and show its outcome. Resolves to the outcome, or null when none ran.
*/
- const handlePasswordSubmit = async (e: React.FormEvent) : Promise<void> => {
- e.preventDefault();
- setError(null);
- showLoading();
-
- const statusResult = await checkStatus();
- if (statusResult.error) {
- // Fatal error (e.g., version mismatch), already handled by checkStatus
- hideLoading();
- return;
- }
-
+ const runBackgroundAuth = async (start: () => Promise<BackgroundAuthResult | null>): Promise<BackgroundAuthResult | null> => {
+ authInFlightRef.current = true;
+ let result: BackgroundAuthResult | null = null;
try {
- let unlockKey: string;
-
- if (statusResult.online) {
- // Online mode: get encryption params from server for key derivation
- const loginResponse = await srpUtil.initiateLogin(authContext.username!);
-
- // Derive key from password using user's encryption settings
- const credentials = await SrpAuthService.prepareCredentials(password, loginResponse.salt, loginResponse.encryptionSettings);
- // Store encryption params for future offline unlock
- await dbContext.storeUnlockKeyDerivationParams({
- salt: loginResponse.salt,
- encryptionType: loginResponse.encryptionType,
- encryptionSettings: loginResponse.encryptionSettings,
- });
-
- /*
- * Fetch the account key chain, check the unlock key opens it and cache it as-is. Throws an unlock-key-rejected
- * (E-206) error on a wrong password.
- */
- unlockKey = credentials.passwordHashBase64;
- await VaultKeyService.refreshKeyChain(unlockKey, webApi);
- } else {
- // Offline mode: use stored encryption params to derive key
- const storedParams = await sendMessage('GET_UNLOCK_KEY_DERIVATION_PARAMS');
-
- if (!storedParams) {
- // No stored params - can't unlock offline without having logged in before
- setError(t('common.errors.serverNotAvailable'));
- hideLoading();
- return;
- }
-
- // Derive key from password using stored encryption settings
- const credentials = await SrpAuthService.prepareCredentials(password, storedParams.salt, storedParams.encryptionSettings);
-
- /*
- * Offline: check the unlock key opens the locally cached account key chain. Throws an unlock-key-rejected
- * (E-206) error on a wrong password.
- */
- unlockKey = credentials.passwordHashBase64;
- await VaultKeyService.verifyUnlockKey(unlockKey);
-
- // Set offline mode
- await dbContext.setIsOffline(true);
+ result = await start();
+ if (result) {
+ await handleAuthResult(result);
}
-
- // Store the unlock key in session storage.
- await dbContext.storeUnlockKey(unlockKey);
-
- /*
- * Load the stored vault from background (decrypts using stored encryption key).
- * Throws an error with E-XXX code if decryption fails.
- */
- const sqliteClient = await dbContext.loadStoredDatabase();
- if (!sqliteClient) {
- // Edge case: no vault loaded but no error thrown (shouldn't happen)
- throw new Error(t('common.errors.wrongPassword'));
- }
-
- // Check if there are pending migrations
- if (await sqliteClient.requiresLegacySqliteBlobMigration()) {
- navigate('/upgrade', { replace: true });
- hideLoading();
- return;
- }
-
- // Clear dismiss until
- await LocalPreferencesService.setVaultLockedDismissUntil(0);
-
- // Reset PIN and password failed attempts on successful unlock
- await resetFailedAttempts();
- await LocalPreferencesService.resetPasswordUnlockFailedAttempts();
- await LocalPreferencesService.setLastUsedUnlockMethod('password');
- setPasswordFailedAttempts(0);
-
- /*
- * Navigate to reinitialize which will call syncVault to sync with server.
- * Other windows will pick up the encryption-key storage event via
- * vaultStateEvents.onVaultUnlocked and reload themselves.
- */
- navigate('/reinitialize', { replace: true });
} catch (err) {
- // Server refused this client version.
- if (err instanceof ClientUpgradeRequiredError) {
- await app.logout(t('common.errors.clientNotSupported'));
- } else if (err instanceof VaultVersionIncompatibleError) {
- // Check if it's a version incompatibility error
- await app.logout(err.message);
- } else {
- const message = await describeAuthError(err, { uncodedIsWrongPassword: true });
- if (message.wrongPassword) {
- await handlePasswordFailedAttempt();
- } else {
- setError(formatErrorMessage(message, t));
- }
- }
logFailure('Unlock error', err);
+ setError(t('common.errors.unknownErrorTryAgain'));
} finally {
- hideLoading();
+ // After a success the page navigates away, keep ignoring the unlock event until then.
+ authInFlightRef.current = result?.status === 'success';
+ }
+ return result;
+ };
+
+ /**
+ * Show the outcome of a background login or unlock flow.
+ */
+ const handleAuthResult = async (result: BackgroundAuthResult): Promise<void> => {
+ switch (result.status) {
+ case 'success': {
+ const finishError = await finishBackgroundAuth(result.offline);
+ if (finishError) {
+ setError(finishError);
+ }
+ return;
+ }
+ case 'wrongPassword':
+ handlePasswordFailedAttempt(result.failedAttempts);
+ return;
+ case 'pinFailed':
+ handlePinFailure(result.reason, result.attemptsRemaining);
+ return;
+ case 'logout':
+ await app.logout(result.message ?? t(result.reasonKey ?? 'common.errors.unknownError'));
+ return;
+ case 'error':
+ setError(formatErrorMessage(result.error, t));
+ setPin('');
+ return;
+ default:
+ // A login flow finished while this page was open, reinitialize routes to where it left the popup.
+ navigate('/reinitialize', { replace: true });
}
};
+ /**
+ * Handle password unlock (supports both online and offline mode)
+ */
+ const handlePasswordSubmit = async (e: React.FormEvent) : Promise<void> => {
+ e.preventDefault();
+ setError(null);
+ showLoading();
+ await runBackgroundAuth(() => sendMessage('AUTH_UNLOCK_PASSWORD', { password }));
+ hideLoading();
+ };
+
/**
* Handle PIN input change
*/
@@ -419,94 +366,35 @@ const Unlock: React.FC = () => {
setError(null);
showLoading();
+ await runBackgroundAuth(() => sendMessage('AUTH_UNLOCK_PIN', { pin: pinToUse }));
+ hideLoading();
+ };
- try {
- const unlockKey = await unlockWithPin(pinToUse);
- await VaultKeyService.verifyUnlockKey(unlockKey);
-
- // Check if we're online or offline (for offline mode flag)
- const statusResult = await checkStatus();
- if (!statusResult.online) {
- await dbContext.setIsOffline(true);
- }
-
- // Store the unlock key in session storage
- await dbContext.storeUnlockKey(unlockKey);
-
- /*
- * Always unlock from local vault first.
- * The /reinitialize page will call syncVault which handles:
- * - Checking if server has newer version
- * - Merging local changes with server if isDirty is true
- * - Overwriting local with server if no local changes
- *
- * Throws an error with E-XXX code if decryption fails.
- */
- const sqliteClient = await dbContext.loadStoredDatabase();
- if (!sqliteClient) {
- // Edge case: no vault loaded but no error thrown (shouldn't happen)
- throw new IncorrectPinError(3);
- }
-
- // Check if there are pending migrations
- if (await sqliteClient.requiresLegacySqliteBlobMigration()) {
- navigate('/upgrade', { replace: true });
- hideLoading();
- return;
- }
-
- // Clear dismiss until
- await LocalPreferencesService.setVaultLockedDismissUntil(0);
- await LocalPreferencesService.setLastUsedUnlockMethod('pin');
+ /**
+ * Show a rejected PIN.
+ */
+ const handlePinFailure = (reason: 'locked' | 'invalidFormat' | 'incorrect', attemptsRemaining?: number): void => {
+ if (reason === 'locked') {
+ setPinAvailable(false);
+ setUnlockMode('password');
+ setError(t('settings.unlockMethod.pinLocked'));
+ return;
+ }
- /*
- * Navigate to reinitialize which will call syncVault to sync with server.
- * Other windows will pick up the encryption-key storage event via
- * vaultStateEvents.onVaultUnlocked and reload themselves.
- */
- navigate('/reinitialize', { replace: true });
- hideLoading();
- } catch (err: unknown) {
- if (err instanceof PinLockedError) {
- setPinAvailable(false);
- setUnlockMode('password');
- setError(t('settings.unlockMethod.pinLocked'));
- } else if (err instanceof IncorrectPinError) {
- /* Show translatable error with attempts remaining */
- const attemptsRemaining = err.attemptsRemaining;
- if (attemptsRemaining === 1) {
- setError(t('settings.unlockMethod.incorrectPinSingular'));
- } else {
- setError(t('settings.unlockMethod.incorrectPin', { attemptsRemaining }));
- }
- setPin('');
- } else if (err instanceof InvalidPinFormatError) {
- setError(t('settings.unlockMethod.invalidPinFormat'));
- setPin('');
- } else {
- const message = await describeAuthError(err, { fallback: 'common.errors.unknownErrorTryAgain' });
- if (message.wrongPassword) {
- // The key the PIN restored does not unlock the vault, treat as incorrect PIN
- logExpected('[Unlock] The entered PIN did not decrypt the vault', err);
- setError(t('settings.unlockMethod.incorrectPin', { attemptsRemaining: 3 }));
- } else {
- logFailure('PIN unlock failed', err);
- setError(formatErrorMessage(message, t));
- }
- setPin('');
- }
- hideLoading();
+ if (reason === 'invalidFormat') {
+ setError(t('settings.unlockMethod.invalidPinFormat'));
+ } else if (attemptsRemaining === 1) {
+ setError(t('settings.unlockMethod.incorrectPinSingular'));
+ } else {
+ setError(t('settings.unlockMethod.incorrectPin', { attemptsRemaining }));
}
+ setPin('');
};
/**
* Handle failed password attempt with brute force protection
*/
- const handlePasswordFailedAttempt = async (): Promise<void> => {
- const newAttempts = passwordFailedAttempts + 1;
- setPasswordFailedAttempts(newAttempts);
- await LocalPreferencesService.setPasswordUnlockFailedAttempts(newAttempts);
-
+ const handlePasswordFailedAttempt = (newAttempts: number): void => {
const remainingAttempts = MAX_PASSWORD_ATTEMPTS - newAttempts;
// Clear password field
@@ -612,7 +500,6 @@ const Unlock: React.FC = () => {
await resetFailedAttempts();
await LocalPreferencesService.resetPasswordUnlockFailedAttempts();
await LocalPreferencesService.setLastUsedUnlockMethod('mobile');
- setPasswordFailedAttempts(0);
/*
* Navigate to reinitialize which will call syncVault to sync with server.
diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
index 5d46abf81..aab7c986b 100644
--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
@@ -21,6 +21,7 @@ import type { TwoFactorState } from '@/entrypoints/background/TwoFactorStateHand
import type { SavePromptPersistedState, LastAutofilledCredential } from '@/utils/loginDetector';
import type { PendingPasskeyRequest, WebAuthnSettingsResponse, WebAuthnPublicKeyGetPayload, MatchingPasskeysResponse, WebAuthnAssertionResponse } from '@/utils/passkey/types';
+import type { BackgroundAuthResult } from '@/utils/types/messaging/BackgroundAuthResult';
import type { BoolResponse } from '@/utils/types/messaging/BoolResponse';
import type { DuplicateCheckResponse } from '@/utils/types/messaging/DuplicateCheckResponse';
import type { FullVaultSyncRequest } from '@/utils/types/messaging/FullVaultSyncRequest';
@@ -35,7 +36,6 @@ import type { VaultMigrationKind } from '@aliasvault/client/sync/VaultManifestMi
import type { VaultMutationScope } from '@aliasvault/client/sync/VaultMutationScope';
import type { FullVaultSyncResult, SharedManifestDetails, VaultManifestMigrationResult } from '@aliasvault/client/sync/VaultSync';
import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
-import type { LoginResponse } from '@aliasvault/models/webapi';
/**
* How the background stores an encrypted vault blob, sent along with its last chunk (see VaultBlobTransfer).
@@ -54,6 +54,11 @@ export type VaultBlobStoreOptions = {
* the response shape (promises are unwrapped automatically by the library).
*/
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_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 };
AUTOFILL_CREATED_ITEM(data: { item: any; elementIdentifier?: string }): BoolResponse;
CHECK_AUTH_STATUS(): { isLoggedIn: boolean; isVaultLocked: boolean; requiresLegacySqliteBlobMigration: boolean; requiresManifestMigration: boolean; error?: string };
@@ -107,12 +112,12 @@ export interface IExtensionMessageProtocol {
SET_AUTO_LOCK_TIMEOUT(data: number): boolean;
SET_CLIPBOARD_CLEAR_TIMEOUT(data: number): boolean;
SET_RECENTLY_SELECTED(data: { itemId: string; manifestId: string; domain: string }): { success: boolean };
+ START_VAULT_SYNC(): BoolResponse;
STORE_ENCRYPTED_VAULT(data: { transferId: string; index: number; chunk: string; commit?: VaultBlobStoreOptions }): { success: boolean; mutationSequence: number } | null;
STORE_UNLOCK_KEY(data: string): BoolResponse;
STORE_UNLOCK_KEY_DERIVATION_PARAMS(data: UnlockKeyDerivationParams): BoolResponse;
STORE_LAST_AUTOFILLED(data: LastAutofilledCredential): { success: boolean };
STORE_SAVE_PROMPT_STATE(data: SavePromptPersistedState): { success: boolean };
- STORE_TWO_FACTOR_STATE(data: { username: string; loginResponse: LoginResponse; passwordHashString: string; passwordHashBase64: string; rememberMe: boolean }): void;
TOGGLE_CONTEXT_MENU(data: any): BoolResponse;
VAULT_SYNC_PHASE(data: { phase: VaultSyncPhase }): void;
VAULT_UNLOCKED(): void;
diff --git a/apps/browser-extension/src/utils/types/messaging/BackgroundAuthResult.ts b/apps/browser-extension/src/utils/types/messaging/BackgroundAuthResult.ts
new file mode 100644
index 000000000..e72bea9f9
--- /dev/null
+++ b/apps/browser-extension/src/utils/types/messaging/BackgroundAuthResult.ts
@@ -0,0 +1,15 @@
+import type { AuthErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';
+import type { FullVaultSyncResult } from '@aliasvault/client/sync/VaultSync';
+import type { TranslationKey } from '@aliasvault/i18n';
+
+/**
+ * Outcome of a login or unlock flow the background ran for the popup.
+ */
+export type BackgroundAuthResult =
+ | { status: 'success'; offline: boolean }
+ | { status: 'twoFactorRequired'; username: string; rememberMe: boolean }
+ | { status: 'wrongPassword'; failedAttempts: number }
+ | { status: 'pinFailed'; reason: 'locked' | 'invalidFormat' | 'incorrect'; attemptsRemaining?: number }
+ | { status: 'logout'; reasonKey?: TranslationKey; message?: string }
+ | { status: 'vaultPullFailed'; sync: FullVaultSyncResult }
+ | { status: 'error'; error: AuthErrorMessage };