Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update 2FA persist handler to only store data we actually need (#2469)
Leendert de Borst6959cbc0db25
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.tsindex b1100d1e0..7fb25d788 100644--- a/apps/browser-extension/src/entrypoints/background.ts+++ b/apps/browser-extension/src/entrypoints/background.ts@@ -11,7 +11,7 @@ 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 { handleGetTwoFactorState, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';+import { handleGetTwoFactorPrompt, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetEncryptionKey, handleGetUnlockKeyDerivationParams, handleGetPersistedFormValues, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreAccountKey, 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';@@ -329,7 +329,7 @@ export default defineBackground({onMessage('CLEAR_LAST_AUTOFILLED', ({ sender }) => handleClearLastAutofilled({ tabId: sender.tab!.id! }));// Two-factor authentication state persistence- onExtensionPageMessage('GET_TWO_FACTOR_STATE', () => handleGetTwoFactorState());+ onExtensionPageMessage('GET_TWO_FACTOR_STATE', () => handleGetTwoFactorPrompt());onExtensionPageMessage('CLEAR_TWO_FACTOR_STATE', () => handleClearTwoFactorState());// Clipboard management messagesdiff --git a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts b/apps/browser-extension/src/entrypoints/background/AuthHandler.tsindex 6d7060797..ad174b43f 100644--- a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/AuthHandler.ts@@ -234,11 +234,13 @@ export function handleLoginWithPassword(data: { username: string; password: striconst srp = new SrpLoginService(new WebApiService());const loginResponse = await srp.initiateLogin(username);const credentials = await SrpAuthService.prepareLoginCredentials(data.password, loginResponse, username);- const validation = await srp.validateLogin(username, credentials, data.rememberMe, loginResponse);+ const proof = await srp.createLoginProof(username, credentials, loginResponse);+ const validation = await srp.validateLoginWithProof(username, proof, data.rememberMe, loginResponse.loginSessionId);if (validation.requiresTwoFactor) {- // Kept in memory for the 2FA step, which may come from a reopened popup.- handleStoreTwoFactorState({ username, loginResponse, credentials, rememberMe: data.rememberMe });+ // Kept in memory for the 2FA step, which may come from a reopened popup. The server accepts the same proof again.+ const { salt, encryptionType, encryptionSettings } = loginResponse;+ handleStoreTwoFactorState({ username, rememberMe: data.rememberMe, loginSessionId: loginResponse.loginSessionId, proof, unlockKeyBase64: credentials.unlockKeyBase64, derivationParams: { salt, encryptionType, encryptionSettings } });return { status: 'twoFactorRequired', username, rememberMe: data.rememberMe };}if (!validation.token) {@@ -264,13 +266,13 @@ export function handleLoginWithTwoFactor(data: { code: string }): Promise<Backgrtry {const srp = new SrpLoginService(new WebApiService());- const validation = await srp.validateLogin2Fa(state.username, state.credentials, state.rememberMe, state.loginResponse, parseInt(data.code));+ const validation = await srp.validateLogin2FaWithProof(state.username, state.proof, state.rememberMe, state.loginSessionId, 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.credentials.unlockKeyBase64, state.loginResponse);+ return await completeLogin(state.username, validation.token.token, validation.token.refreshToken, state.unlockKeyBase64, state.derivationParams);} catch (err) {return failureResult('2FA error', err);}diff --git a/apps/browser-extension/src/entrypoints/background/TwoFactorStateHandler.ts b/apps/browser-extension/src/entrypoints/background/TwoFactorStateHandler.tsindex 9eff8c70a..fe82f4ecc 100644--- a/apps/browser-extension/src/entrypoints/background/TwoFactorStateHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/TwoFactorStateHandler.ts@@ -1,29 +1,29 @@/*** In-memory 2FA state handler for persisting login state during popup close/reopen.- *- * This handler stores 2FA login state ONLY in memory, and the state automatically- * expires after a short timeout.- *- * 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 { PreparedCredentials } from '@aliasvault/client/auth/SrpAuthService';-import type { LoginResponse } from '@aliasvault/models/webapi';+import type { LoginProof } from '@aliasvault/client/auth/SrpLoginService';+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';/**- * The 2FA state that is persisted in memory.+ * The 2FA state that is kept in memory.*/export type TwoFactorState = {username: string;- loginResponse: LoginResponse;- credentials: PreparedCredentials;rememberMe: boolean;- timestamp: number;+ loginSessionId: string;+ proof: LoginProof;+ unlockKeyBase64: string;+ derivationParams: UnlockKeyDerivationParams;};/**- * Timeout for automatic state expiration.+ * What the popup gets to restore the 2FA step: no key material.+ */+export type TwoFactorPrompt = Pick<TwoFactorState, 'username' | 'rememberMe'>;++/**+ * Timeout after which the state is cleared.*/const STATE_EXPIRY_MS = 5 * 60 * 1000;@@ -32,38 +32,38 @@ const STATE_EXPIRY_MS = 5 * 60 * 1000;* Intentionally NOT persisted to any storage - lives only in service worker memory.*/let twoFactorState: TwoFactorState | null = null;+let expiryTimer: ReturnType<typeof setTimeout> | null = null;/**- * Store 2FA state in memory with current timestamp.+ * Store 2FA state in memory until the 2FA step completes, it is cleared, or the timeout passes.*/-export function handleStoreTwoFactorState(state: Omit<TwoFactorState, 'timestamp'>): void {- twoFactorState = {- ...state,- timestamp: Date.now(),- };+export function handleStoreTwoFactorState(state: TwoFactorState): void {+ handleClearTwoFactorState();+ twoFactorState = state;+ expiryTimer = setTimeout(handleClearTwoFactorState, STATE_EXPIRY_MS);}/**- * Retrieve 2FA state from memory.- * Returns null if no state exists or if the state has expired.+ * Retrieve the 2FA state for the background login flow, or null when there is none.*/export function handleGetTwoFactorState(): TwoFactorState | null {- if (!twoFactorState) {- return null;- }-- // Check if state has expired- if (Date.now() - twoFactorState.timestamp > STATE_EXPIRY_MS) {- twoFactorState = null;- return null;- }-return twoFactorState;}+/**+ * Whether a 2FA step is pending and for whom, for the popup to restore it.+ */+export function handleGetTwoFactorPrompt(): TwoFactorPrompt | null {+ return twoFactorState ? { username: twoFactorState.username, rememberMe: twoFactorState.rememberMe } : null;+}+/*** Clear 2FA state from memory.*/export function handleClearTwoFactorState(): void {+ if (expiryTimer) {+ clearTimeout(expiryTimer);+ expiryTimer = null;+ }twoFactorState = null;}diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.tsindex 2ffb384f6..7cf7508bb 100644--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts@@ -17,7 +17,7 @@ export type TotpSecret = {Period: number;};-import type { TwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';+import type { TwoFactorPrompt } from '@/entrypoints/background/TwoFactorStateHandler';import type { SavePromptPersistedState, LastAutofilledCredential } from '@/utils/loginDetector';import type { PendingPasskeyRequest, WebAuthnSettingsResponse, WebAuthnPublicKeyGetPayload, MatchingPasskeysResponse, WebAuthnAssertionResponse } from '@/utils/passkey/types';@@ -88,7 +88,7 @@ export interface IExtensionMessageProtocol {GET_SEARCH_ITEMS(data: { searchTerm: string }): ItemsResponse;GET_SYNC_STATE(): VaultSyncState;GET_TOTP_SECRETS(data: { items: ItemRef[] }): { success: boolean; secrets?: Record<string, TotpSecret>; error?: string };- GET_TWO_FACTOR_STATE(): TwoFactorState | null;+ GET_TWO_FACTOR_STATE(): TwoFactorPrompt | null;GET_VAULT_MIGRATION_STATUS(): VaultMigrationKind;GET_WEBAUTHN_SETTINGS(data: any): WebAuthnSettingsResponse;GROUP_CREATE_VAULT(data: { groupId: string; name: string }): { success: boolean; error?: string; apiErrorCode?: string };diff --git a/core/client/src/auth/SrpLoginService.ts b/core/client/src/auth/SrpLoginService.tsindex 5310f751d..5e1470f45 100644--- a/core/client/src/auth/SrpLoginService.ts+++ b/core/client/src/auth/SrpLoginService.ts@@ -6,7 +6,7 @@ import { SrpAuthService, type LoginCredentials, type SrpClientSession } from './import type { WebApiService } from '../api/WebApiService';import type { AccountKeyHierarchy } from '../crypto/AccountKeys';import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';-import type { LoginResponse, TokenModel, ValidateLoginRequest, ValidateLoginRequest2Fa, ValidateLoginResponse } from '@aliasvault/models/webapi';+import type { LegacySrpVerifierUpgrade, LoginResponse, TokenModel, ValidateLoginRequest, ValidateLoginRequest2Fa, ValidateLoginResponse } from '@aliasvault/models/webapi';/*** The part of an API client the auth requests need.@@ -20,6 +20,14 @@ type ValidateLoginRequestRecoveryCode = ValidateLoginRequest & {recoveryCode: string;};+/**+ * A login proof derived once from the password, reusable for every validate request of the same login session.+ */+export type LoginProof = {+ session: SrpClientSession;+ legacyVerifierUpgrade?: LegacySrpVerifierUpgrade;+};+/*** A registered account: its session tokens plus the key material the caller keeps client-side.*/@@ -76,10 +84,7 @@ export class SrpLoginService {* @returns The validate response*/public async validateLogin(username: string, credentials: LoginCredentials, rememberMe: boolean, loginResponse: LoginResponse): Promise<ValidateLoginResponse> {- const normalizedUsername = SrpAuthService.normalizeUsername(username);- const session = await SrpAuthService.deriveLoginSession(loginResponse, normalizedUsername, credentials.passwordHashString);- const model: ValidateLoginRequest = this.validateModel(normalizedUsername, rememberMe, session, credentials, loginResponse);- return this.verifiedLoginResponse(session, await this.post('Auth/validate', model));+ return this.validateLoginWithProof(username, await this.createLoginProof(username, credentials, loginResponse), rememberMe, loginResponse.loginSessionId);}/**@@ -92,10 +97,46 @@ export class SrpLoginService {* @returns The validate response*/public async validateLogin2Fa(username: string, credentials: LoginCredentials, rememberMe: boolean, loginResponse: LoginResponse, code2Fa: number): Promise<ValidateLoginResponse> {- const normalizedUsername = SrpAuthService.normalizeUsername(username);- const session = await SrpAuthService.deriveLoginSession(loginResponse, normalizedUsername, credentials.passwordHashString);- const model: ValidateLoginRequest2Fa = { ...this.validateModel(normalizedUsername, rememberMe, session, credentials, loginResponse), code2Fa };- return this.verifiedLoginResponse(session, await this.post('Auth/validate-2fa', model));+ return this.validateLogin2FaWithProof(username, await this.createLoginProof(username, credentials, loginResponse), rememberMe, loginResponse.loginSessionId, code2Fa);+ }++ /**+ * Derive the proof of a login session from the password hash, so a caller can keep the proof instead of the hash.+ * @param username - The username+ * @param credentials - The SRP password hash and, for a legacy verifier, its upgrade+ * @param loginResponse - The initiate response+ * @returns The login proof+ */+ public async createLoginProof(username: string, credentials: LoginCredentials, loginResponse: LoginResponse): Promise<LoginProof> {+ const session = await SrpAuthService.deriveLoginSession(loginResponse, SrpAuthService.normalizeUsername(username), credentials.passwordHashString);+ return { session, legacyVerifierUpgrade: credentials.legacyVerifierUpgrade };+ }++ /**+ * Validate login with a 2FA authenticator code, using a proof from {@link createLoginProof}.+ * @param username - The username+ * @param proof - The login proof+ * @param rememberMe - Whether to request an extended token lifetime+ * @param loginSessionId - The login session id from the initiate response+ * @param code2Fa - The authenticator code+ * @returns The validate response+ */+ public async validateLogin2FaWithProof(username: string, proof: LoginProof, rememberMe: boolean, loginSessionId: string, code2Fa: number): Promise<ValidateLoginResponse> {+ const model: ValidateLoginRequest2Fa = { ...this.proofModel(SrpAuthService.normalizeUsername(username), rememberMe, proof, loginSessionId), code2Fa };+ return this.verifiedLoginResponse(proof.session, await this.post('Auth/validate-2fa', model));+ }++ /**+ * Validate login with the server using a proof from {@link createLoginProof}.+ * @param username - The username+ * @param proof - The login proof+ * @param rememberMe - Whether to request an extended token lifetime+ * @param loginSessionId - The login session id from the initiate response+ * @returns The validate response+ */+ public async validateLoginWithProof(username: string, proof: LoginProof, rememberMe: boolean, loginSessionId: string): Promise<ValidateLoginResponse> {+ const model: ValidateLoginRequest = this.proofModel(SrpAuthService.normalizeUsername(username), rememberMe, proof, loginSessionId);+ return this.verifiedLoginResponse(proof.session, await this.post('Auth/validate', model));}/**@@ -108,23 +149,21 @@ export class SrpLoginService {* @returns The validate response*/public async validateLoginRecoveryCode(username: string, credentials: LoginCredentials, rememberMe: boolean, loginResponse: LoginResponse, recoveryCode: string): Promise<ValidateLoginResponse> {- const normalizedUsername = SrpAuthService.normalizeUsername(username);- const session = await SrpAuthService.deriveLoginSession(loginResponse, normalizedUsername, credentials.passwordHashString);- const model: ValidateLoginRequestRecoveryCode = { ...this.validateModel(normalizedUsername, rememberMe, session, credentials, loginResponse), recoveryCode };- return this.verifiedLoginResponse(session, await this.post('Auth/validate-recovery-code', model));+ const proof = await this.createLoginProof(username, credentials, loginResponse);+ const model: ValidateLoginRequestRecoveryCode = { ...this.proofModel(SrpAuthService.normalizeUsername(username), rememberMe, proof, loginResponse.loginSessionId), recoveryCode };+ return this.verifiedLoginResponse(proof.session, await this.post('Auth/validate-recovery-code', model));}/*** Build the fields every validate request carries.* @param username - The normalized username* @param rememberMe - Whether to request an extended token lifetime- * @param session - The client session- * @param credentials - The SRP password hash and, for a legacy verifier, its upgrade- * @param loginResponse - The initiate response+ * @param proof - The login proof+ * @param loginSessionId - The login session id from the initiate response* @returns The validate request*/- private validateModel(username: string, rememberMe: boolean, session: SrpClientSession, credentials: LoginCredentials, loginResponse: LoginResponse): ValidateLoginRequest {- return { username, rememberMe, ...session.proof, loginSessionId: loginResponse.loginSessionId, legacyVerifierUpgrade: credentials.legacyVerifierUpgrade };+ private proofModel(username: string, rememberMe: boolean, proof: LoginProof, loginSessionId: string): ValidateLoginRequest {+ return { username, rememberMe, ...proof.session.proof, loginSessionId, legacyVerifierUpgrade: proof.legacyVerifierUpgrade };}/**