Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add server sanity checks to login flow (#771)
Leendert de Borst928860bd3846
diff --git a/apps/browser-extension/src/utils/WebApiService.ts b/apps/browser-extension/src/utils/WebApiService.tsindex 431b9fec7..b6dcec65c 100644--- a/apps/browser-extension/src/utils/WebApiService.ts+++ b/apps/browser-extension/src/utils/WebApiService.ts@@ -101,15 +101,15 @@ export class WebApiService {const baseUrl = await this.getBaseUrl();const url = baseUrl + endpoint;const headers = new Headers(options.headers ?? {});-+// Add client version headerheaders.set('X-AliasVault-Client', `${AppInfo.CLIENT_NAME}-${AppInfo.VERSION}`);-+const requestOptions: RequestInit = {...options,headers,};-+try {const response = await fetch(url, requestOptions);return response;@@ -270,7 +270,7 @@ export class WebApiService {}if (!statusResponse.clientVersionSupported) {- return 'This version of the AliasVault browser extension is outdated. Please update your browser extension to the latest version.';+ return 'This version of the AliasVault browser extension is not supported by the server anymore. Please update your browser extension to the latest version.';}if (!AppInfo.isServerVersionSupported(statusResponse.serverVersion)) {diff --git a/apps/mobile-app/app/(tabs)/credentials/index.tsx b/apps/mobile-app/app/(tabs)/credentials/index.tsxindex 78cefc817..1aa753dee 100644--- a/apps/mobile-app/app/(tabs)/credentials/index.tsx+++ b/apps/mobile-app/app/(tabs)/credentials/index.tsx@@ -1,4 +1,4 @@-import { StyleSheet, Text, FlatList, TouchableOpacity, TextInput, RefreshControl, Platform, Animated } from 'react-native';+import { StyleSheet, Text, FlatList, TouchableOpacity, TextInput, RefreshControl, Platform, Animated, Alert } from 'react-native';import { useState, useEffect, useCallback, useRef } from 'react';import { useNavigation } from '@react-navigation/native';import { useRouter } from 'expo-router';@@ -20,6 +20,7 @@ import { CollapsibleHeader } from '@/components/ui/CollapsibleHeader';import { SkeletonLoader } from '@/components/ui/SkeletonLoader';import emitter from '@/utils/EventEmitter';import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';+import { useWebApi } from '@/context/WebApiContext';/*** Credentials screen.@@ -27,6 +28,7 @@ import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';export default function CredentialsScreen() : React.ReactNode {const [searchQuery, setSearchQuery] = useState('');const { syncVault } = useVaultSync();+ const webApi = useWebApi();const colors = useColors();const flatListRef = useRef<FlatList>(null);const scrollY = useRef(new Animated.Value(0)).current;@@ -159,17 +161,16 @@ export default function CredentialsScreen() : React.ReactNode {/*** On error.*/- onError: (error) => {+ onError: async (error) => {console.error('Error syncing vault:', error);setRefreshing(false);setIsLoadingCredentials(false);- setTimeout(() => {- Toast.show({- type: 'error',- text1: 'Vault sync failed',- text2: error,- });- }, 200);++ // Show modal with error message+ Alert.alert('Error', error);++ // Logout user+ await webApi.logout(error);},});} catch (err) {@@ -182,7 +183,7 @@ export default function CredentialsScreen() : React.ReactNode {text2: err instanceof Error ? err.message : 'Unknown error',});}- }, [syncVault, loadCredentials, setIsLoadingCredentials, authContext.isOffline, setRefreshing]);+ }, [syncVault, loadCredentials, setIsLoadingCredentials, authContext.isOffline, setRefreshing, webApi]);useEffect(() => {if (!isAuthenticated || !isDatabaseAvailable) {diff --git a/apps/mobile-app/app/_layout.tsx b/apps/mobile-app/app/_layout.tsxindex 3d74250a2..0ff4f2d95 100644--- a/apps/mobile-app/app/_layout.tsx+++ b/apps/mobile-app/app/_layout.tsx@@ -12,7 +12,7 @@ import { install } from 'react-native-quick-crypto';import { useColors, useColorScheme } from '@/hooks/useColorScheme';import { DbProvider, useDb } from '@/context/DbContext';import { AuthProvider, useAuth } from '@/context/AuthContext';-import { WebApiProvider } from '@/context/WebApiContext';+import { useWebApi, WebApiProvider } from '@/context/WebApiContext';import { AliasVaultToast } from '@/components/Toast';import NativeVaultManager from '@/specs/NativeVaultManager';import { useVaultSync } from '@/hooks/useVaultSync';@@ -33,6 +33,7 @@ function RootLayoutNav() : React.ReactNode {const { initializeAuth } = useAuth();const { syncVault } = useVaultSync();const dbContext = useDb();+ const webApi = useWebApi();const [bootComplete, setBootComplete] = useState(false);const [redirectTarget, setRedirectTarget] = useState<string | null>(null);@@ -151,16 +152,20 @@ function RootLayoutNav() : React.ReactNode {/*** Handle error during vault sync.*/- onError: () => {- // Logout user and navigate to the login screen.- setRedirectTarget('/unlock');+ onError: async (error: string) => {+ // Show modal with error message+ Alert.alert('Error', error);++ // The logout user and navigate to the login screen.+ await webApi.logout(error);+ setRedirectTarget('/login');setBootComplete(true);}});};initialize();- }, [dbContext, syncVault, initializeAuth]);+ }, [dbContext, syncVault, initializeAuth, webApi]);useEffect(() => {/**diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsxindex f9e8d83b4..da52384ae 100644--- a/apps/mobile-app/app/login.tsx+++ b/apps/mobile-app/app/login.tsx@@ -14,7 +14,8 @@ import {ScrollView,KeyboardAvoidingView,Platform,- Dimensions+ Dimensions,+ Alert} from 'react-native';import { router } from 'expo-router';import AsyncStorage from '@react-native-async-storage/async-storage';@@ -36,6 +37,7 @@ import LoadingIndicator from '@/components/LoadingIndicator';import { LoginResponse } from '@/utils/types/webapi/Login';import { VaultResponse } from '@/utils/types/webapi/VaultResponse';import { EncryptionKeyDerivationParams } from '@/utils/types/messaging/EncryptionKeyDerivationParams';+import { useVaultSync } from '@/hooks/useVaultSync';/*** Login screen.@@ -96,6 +98,7 @@ export default function LoginScreen() : React.ReactNode {const authContext = useAuth();const dbContext = useDb();const webApi = useWebApi();+ const { syncVault } = useVaultSync();const srpUtil = new SrpUtility(webApi);@@ -113,8 +116,6 @@ export default function LoginScreen() : React.ReactNode {passwordHashBase64: string,initiateLoginResponse: LoginResponse) : Promise<void> => {-- // Create KeyDerivationParams from initiateLoginResponseconst encryptionKeyDerivationParams : EncryptionKeyDerivationParams = {encryptionType: initiateLoginResponse.encryptionType,encryptionSettings: initiateLoginResponse.encryptionSettings,@@ -125,11 +126,27 @@ export default function LoginScreen() : React.ReactNode {await dbContext.storeEncryptionKey(passwordHashBase64);await dbContext.storeEncryptionKeyDerivationParams(encryptionKeyDerivationParams);await dbContext.initializeDatabase(vaultResponseJson);++ /**+ * After setting auth tokens, execute a server status check immediately+ * which takes care of certain sanity checks such as ensuring client/server+ * compatibility.+ */+ await syncVault({+ initialSync: true,+ /**+ * Handle the status update.+ */+ onError: (message) => {+ // Show modal with error message+ Alert.alert('Error', message);+ webApi.logout(message);+ }+ });+await authContext.login();- // Update offline mode to false as we have successfully logged in.authContext.setOfflineMode(false);-setTwoFactorRequired(false);setTwoFactorCode('');setPasswordHashString(null);diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.tsindex 3f96dbca5..529349545 100644--- a/apps/mobile-app/hooks/useVaultSync.ts+++ b/apps/mobile-app/hooks/useVaultSync.ts@@ -5,6 +5,7 @@ import { useAuth } from '@/context/AuthContext';import { useDb } from '@/context/DbContext';import { useWebApi } from '@/context/WebApiContext';import { VaultResponse } from '@/utils/types/webapi/VaultResponse';+import { AppInfo } from '@/utils/AppInfo';/*** Utility function to ensure a minimum time has elapsed for an operation@@ -68,19 +69,23 @@ export const useVaultSync = () : {300,initialSync);- const statusError = webApi.validateStatusResponse(statusResponse);- if (statusError !== null) {- // Only logout if it's an authentication error, not a network error- if (statusError.includes('authentication') || statusError.includes('unauthorized')) {- await webApi.logout(statusError);- onError?.(statusError);- return false;- }- // For other errors, go into offline mode- authContext.setOfflineMode(true);+ if (statusResponse.serverVersion === '0.0.0') {+ // Server is not available, go into offline modeonOffline?.();- return true;+ return false;+ }++ if (!statusResponse.clientVersionSupported) {+ const statusError = 'This version of the AliasVault mobile app is not supported by the server anymore. Please update your app to the latest version.';+ onError?.(statusError);+ return false;+ }++ if (!AppInfo.isServerVersionSupported(statusResponse.serverVersion)) {+ const statusError = 'The AliasVault server needs to be updated to a newer version in order to use this mobile app. Please contact support if you need help.';+ onError?.(statusError);+ return false;}// If we get here, it means we have a valid connection to the server.diff --git a/apps/mobile-app/utils/WebApiService.ts b/apps/mobile-app/utils/WebApiService.tsindex b6694a4e4..aaffb33fe 100644--- a/apps/mobile-app/utils/WebApiService.ts+++ b/apps/mobile-app/utils/WebApiService.ts@@ -250,7 +250,7 @@ export class WebApiService {try {return await this.get<StatusResponse>('Auth/status');} catch (error) {- if (error instanceof Error && error.message.includes('Session expired')) {+ if (error instanceof Error && error.message.includes('expired')) {/*** If session expired, logout the user immediately as otherwise this would* trigger a server offline banner.@@ -271,25 +271,6 @@ export class WebApiService {}}- /**- * Validates the status response and returns an error message if validation fails.- */- public validateStatusResponse(statusResponse: StatusResponse): string | null {- if (statusResponse.serverVersion === '0.0.0') {- return 'The AliasVault server is not available. Please try again later or contact support if the problem persists.';- }-- if (!statusResponse.clientVersionSupported) {- return 'This version of the AliasVault browser extension is outdated. Please update your browser extension to the latest version.';- }-- if (!AppInfo.isServerVersionSupported(statusResponse.serverVersion)) {- return 'The AliasVault server needs to be updated to a newer version in order to use this browser extension. Please contact support if you need help.';- }-- return null;- }-/*** Validates the vault response and returns an error message if validation fails*/