Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add sanity check to logout user if local vault decryption fails, e.g. after key migration (#2507)
Leendert de Borst2f7892282769
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex 5a40bf90c..9620635e4 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -650,8 +650,13 @@ export async function createVaultSqliteClient() : Promise<SqliteClient> {return cachedSqliteClient;}- // Decrypt the vault- const decryptedVault = await decryptVaultBlob(encryptedVault, encryptionKey);+ let decryptedVault: Uint8Array;+ try {+ decryptedVault = await decryptVaultBlob(encryptedVault, encryptionKey);+ } catch {+ // E-203: the stored vault does not decrypt with the session key+ throw new Error(formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.VAULT_DECRYPT_FAILED));+ }// Initialize the SQLite client with the decrypted vaultconst sqliteClient = new SqliteClient();diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useFinishBackgroundAuth.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useFinishBackgroundAuth.tsindex 27e46434e..8cd1dff73 100644--- a/apps/browser-extension/src/entrypoints/popup/hooks/useFinishBackgroundAuth.ts+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useFinishBackgroundAuth.ts@@ -1,5 +1,7 @@+import { AppErrorCode, getAppErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';+import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';@@ -37,6 +39,11 @@ export function useFinishBackgroundAuth(): (offline: boolean) => Promise<stringawait app.logout(err.message);return null;}+ if (getAppErrorCode(err) === AppErrorCode.VAULT_DECRYPT_FAILED && await VaultKeyService.hasLocalVaultKey()) {+ // The key chain opened but the stored vault does not decrypt; the next login pulls the vault again.+ await app.logout(t('common.errors.sessionExpired'));+ return null;+ }logFailure('Loading the unlocked vault failed', err);return formatErrorMessage(await describeAuthError(err, { fallback: 'common.errors.unknownErrorTryAgain' }), t);}diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsxindex 45617695c..4aa8d7ae2 100644--- a/apps/mobile-app/app/unlock.tsx+++ b/apps/mobile-app/app/unlock.tsx@@ -1,5 +1,6 @@import { AppErrorCode, formatErrorWithCode, getAppErrorCode, getErrorTranslationKey } from '@aliasvault/client/api/errors/AppErrorCodes';import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';+import { logoutEventEmitter } from '@aliasvault/client/api/LogoutEventEmitter';import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';import * as Haptics from 'expo-haptics';import { LinearGradient } from 'expo-linear-gradient';@@ -33,6 +34,19 @@ async function unlockErrorMessage(err: unknown, t: (key: string) => string): Proreturn formatErrorMessage(await describeAuthError(err, { uncodedIsWrongPassword: true }), t);}+/**+ * Log out when the key chain opened but the stored vault did not decrypt; the next login pulls the vault again.+ * @param err - the thrown error+ * @returns Whether a logout was started.+ */+async function logoutOnUnreadableVault(err: unknown): Promise<boolean> {+ if (getAppErrorCode(err) !== AppErrorCode.VAULT_DECRYPT_FAILED || await NativeVaultManager.getAccountKeyChain() === null) {+ return false;+ }+ logoutEventEmitter.emit('common.errors.sessionExpired');+ return true;+}+/*** Unlock screen.*/@@ -145,6 +159,10 @@ export default function UnlockScreen() : React.ReactNode {return;}+ if (await logoutOnUnreadableVault(err)) {+ return;+ }+// Check if max attempts reachedif (err && typeof err === 'object' && 'code' in err && err.code === 'MAX_ATTEMPTS_REACHED') {// Max attempts reached - vault has been cleared, force logout@@ -226,6 +244,10 @@ export default function UnlockScreen() : React.ReactNode {return;}+ if (await logoutOnUnreadableVault(err)) {+ return;+ }+// Check if max attempts reachedif (err && typeof err === 'object' && 'code' in err && err.code === 'MAX_ATTEMPTS_REACHED') {// Max attempts reached - vault has been cleared, force logout@@ -266,8 +288,8 @@ export default function UnlockScreen() : React.ReactNode {}// Not unlocked means user cancelled - return false but don't show errorreturn false;- } catch {- return false;+ } catch (err) {+ return logoutOnUnreadableVault(err);}}, [dbContext]);@@ -301,6 +323,10 @@ export default function UnlockScreen() : React.ReactNode {} catch (err) {console.error('Biometric retry error:', err);+ if (await logoutOnUnreadableVault(err)) {+ return;+ }+// Check if this is a cancellation - don't show error, just allow retryconst errorCode = getAppErrorCode(err);if (errorCode === AppErrorCode.BIOMETRIC_CANCELLED) {diff --git a/apps/web/src/pages/sync/Sync.tsx b/apps/web/src/pages/sync/Sync.tsxindex 312056914..570b7e31f 100644--- a/apps/web/src/pages/sync/Sync.tsx+++ b/apps/web/src/pages/sync/Sync.tsx@@ -1,4 +1,6 @@+import { AppErrorCode, getAppErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';+import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';import { AppInfo } from '@aliasvault/client/platform/AppInfo';import { syncErrorMessage, syncErrorReport } from '@aliasvault/client/sync/SyncErrorMessage';import { VaultMigrationKind } from '@aliasvault/client/sync/VaultManifestMigration';@@ -112,6 +114,12 @@ const Sync: React.FC = () => {setStatus('version-unrecognized');return;}+ if (getAppErrorCode(error) === AppErrorCode.VAULT_DECRYPT_FAILED && await VaultKeyService.hasLocalVaultKey()) {+ // The key chain opened but the stored vault does not decrypt; the next login pulls the vault again.+ await auth.logout({ errorMessage: t('common.errors.sessionExpired') });+ navigate('/user/login', { replace: true });+ return;+ }setErrorDetails(error instanceof Error ? error.message : String(error));setStatus('decryption-failed');return;@@ -123,7 +131,7 @@ const Sync: React.FC = () => {}await navigateToHome();- }, [dbContext, navigateToHome, t]);+ }, [auth, dbContext, navigate, navigateToHome, t]);/*** Pull the vault when none is stored yet (right after login), then open it.diff --git a/core/client/src/auth/VaultKeyService.ts b/core/client/src/auth/VaultKeyService.tsindex 42e264c6a..ce36fac45 100644--- a/core/client/src/auth/VaultKeyService.ts+++ b/core/client/src/auth/VaultKeyService.ts@@ -88,6 +88,15 @@ export class VaultKeyService {}const keys = await VaultKeyService.openChain(unlockKeyBase64, result.vaultKey.encryptedAccountKey, result.vaultKey.encryptedVek ?? null, null);++ /*+ * A device holding a vault under its unlock key but no chain yet (the account was upgraded on another device) stays+ * a legacy session: its first sync caches the chain and re-encrypts the stored vault under the VEK in one step.+ */+ if (keys.accountKey !== unlockKeyBase64 && !await VaultKeyService.hasLocalVaultKey() && await getPlatform().storage.get(StorageKeys.ENCRYPTED_VAULT) !== null) {+ return unlockKeyBase64;+ }+await VaultKeyService.cacheVaultKeyBlobs(result.vaultKey);return keys.accountKey;}diff --git a/core/rust/src/vault_sync/engine.rs b/core/rust/src/vault_sync/engine.rsindex 264ec8eb4..4caa6df79 100644--- a/core/rust/src/vault_sync/engine.rs+++ b/core/rust/src/vault_sync/engine.rs@@ -94,8 +94,27 @@ async fn full_sync_operation(ctx: &mut Ctx) -> FullSyncResult {/// Full vault sync, re-running itself when a mutation raced a store or the server refused a push as outdated.pub(crate) async fn full_sync(ctx: &mut Ctx) -> SyncResult<FullSyncResult> {let mut outdated_resyncs = 0u32;+ let mut dropped_local_vault = false;loop {- match full_sync_once(ctx).await? {+ let flow = match full_sync_once(ctx).await {+ Ok(flow) => flow,+ Err(error) => {+ let error = ctx.diagnose_local_vault_failure(error).await;+ if dropped_local_vault || !matches!(error, SyncError::VaultDecryptFailed(_)) {+ return Err(error);+ }+ // A stored vault that does not decrypt is useless to every reader, so it is dropped and the server's vault pulled over it, once.+ ctx.warn(format!("[Sync] The stored vault does not decrypt with the session key; dropping it and pulling the server's vault. {}", error)).await;+ dropped_local_vault = true;+ ctx.discard_local_vault();+ if ctx.is_dirty && state::mark_clean(&ctx.host, ctx.mutation_sequence).await? {+ ctx.is_dirty = false;+ }+ ctx.request.force_pull = true;+ continue;+ }+ };+ match flow {Flow::Done(result) => return Ok(result),Flow::Resync { outdated } => {if outdated {diff --git a/core/rust/src/vault_sync/state.rs b/core/rust/src/vault_sync/state.rsindex 9bed0910d..67ca37d7b 100644--- a/core/rust/src/vault_sync/state.rs+++ b/core/rust/src/vault_sync/state.rs@@ -31,6 +31,8 @@ pub(crate) struct Ctx {pub vault_key_probed: bool,pub served_manifest_names: HashMap<String, String>,has_local_vault: bool,+ /// The stored vault did not decrypt with the session key, so this run treats it as absent until a store replaces it.+ local_vault_discarded: bool,/// The VEK of every shared manifest this account holds a grant on, unwrapped once per run.shared_veks: Mutex<Option<HashMap<String, String>>>,}@@ -58,20 +60,30 @@ impl Ctx {vault_key_probed: false,served_manifest_names: HashMap::new(),has_local_vault: false,+ local_vault_discarded: false,shared_veks: Mutex::new(None),host,request,}}- /// Whether the host holds an at-rest vault.+ /// Whether the host holds an at-rest vault this run has not discarded.pub async fn has_local_vault(&mut self) -> SyncResult<bool> {+ if self.local_vault_discarded {+ return Ok(false);+ }if !self.has_local_vault {self.has_local_vault = load_vault(&self.host).await?.is_some();}Ok(self.has_local_vault)}+ /// Treat the stored vault as absent for the rest of this run; the next successful store replaces it.+ pub fn discard_local_vault(&mut self) {+ self.local_vault_discarded = true;+ self.has_local_vault = false;+ }+/// The session's vault encryption key, or the locked-vault error.pub fn encryption_key(&self) -> SyncResult<String> {self.encryption_key.clone().ok_or(SyncError::VaultLocked)@@ -83,9 +95,26 @@ impl Ctx {self.encryption_key = Some(key);}- /// Persist the at-rest vault blob.- pub async fn store_vault(&self, encrypted_blob: &str, mark_dirty: bool, expected_mutation_seq: Option<u64>, revision: Option<i64>) -> SyncResult<StoreOutcome> {- store_vault_with_key(&self.host, encrypted_blob, mark_dirty, expected_mutation_seq, revision, self.new_encryption_key.clone()).await+ /// Persist the at-rest vault blob; a successful store replaces a discarded one.+ pub async fn store_vault(&mut self, encrypted_blob: &str, mark_dirty: bool, expected_mutation_seq: Option<u64>, revision: Option<i64>) -> SyncResult<StoreOutcome> {+ let stored = store_vault_with_key(&self.host, encrypted_blob, mark_dirty, expected_mutation_seq, revision, self.new_encryption_key.clone()).await?;+ if stored.success {+ self.local_vault_discarded = false;+ }+ Ok(stored)+ }++ /// Re-read a failed local database command as `VaultDecryptFailed` when the stored vault does not decrypt with the session key.+ pub async fn diagnose_local_vault_failure(&self, error: SyncError) -> SyncError {+ if !matches!(error, SyncError::Host { command: "dbQuery" | "dbExec" | "dbExport", .. }) {+ return error;+ }+ let (Some(key), Ok(Some(blob))) = (self.encryption_key.as_deref(), load_vault(&self.host).await) else { return error };+ match decrypt_vault_blob(&blob, key) {+ Ok(_) => error,+ Err(decrypt @ SyncError::VaultDecryptFailed(_)) => decrypt,+ Err(other) => SyncError::VaultDecryptFailed(other.to_string()),+ }}/// Write the local database as the at-rest vault under the session key. `dirty` records it as a pending change