Skip to content

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

Add SrpSalt check to the useVaultSync hook (#1118)

Leendert de Borst4da1333aa55d
diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsx
index 6a1e411e4..0ae3f4652 100644
--- a/apps/mobile-app/app/login.tsx
+++ b/apps/mobile-app/app/login.tsx
@@ -244,8 +244,6 @@ export default function LoginScreen() : React.ReactNode {
await new Promise(resolve => requestAnimationFrame(resolve));
try {
- authContext.clearGlobalMessage();
-
const initiateLoginResponse = await srpUtil.initiateLogin(ConversionUtility.normalizeUsername(credentials.username));
const passwordHash = await EncryptionUtility.deriveKeyFromPassword(
diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsx
index 734304d1b..44449d330 100644
--- a/apps/mobile-app/app/unlock.tsx
+++ b/apps/mobile-app/app/unlock.tsx
@@ -17,13 +17,12 @@ import { Avatar } from '@/components/ui/Avatar';
import { useAuth } from '@/context/AuthContext';
import { useDb } from '@/context/DbContext';
import { useWebApi } from '@/context/WebApiContext';
-import NativeVaultManager from '@/specs/NativeVaultManager';
/**
* Unlock screen.
*/
export default function UnlockScreen() : React.ReactNode {
- const { isLoggedIn, username, isBiometricsEnabled } = useAuth();
+ const { isLoggedIn, username, isBiometricsEnabled, getBiometricDisplayNameKey, getEncryptionKeyDerivationParams } = useAuth();
const dbContext = useDb();
const [password, setPassword] = useState('');
const [isLoading, setIsLoading] = useState(false);
@@ -31,22 +30,21 @@ export default function UnlockScreen() : React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
const webApi = useWebApi();
- const { getBiometricDisplayNameKey } = useAuth();
const [biometricDisplayName, setBiometricDisplayName] = useState('');
/**
* Check if the key derivation parameters are stored in native storage.
* If not, we can't unlock the vault so logout instead to redirect user to login screen.
*/
- const getKeyDerivationParams = useCallback(async () : Promise<string | null> => {
- const encryptionKeyDerivationParams = await NativeVaultManager.getEncryptionKeyDerivationParams();
- if (!encryptionKeyDerivationParams) {
+ const getKeyDerivationParams = useCallback(async () : Promise<{ salt: string; encryptionType: string; encryptionSettings: string } | null> => {
+ const params = await getEncryptionKeyDerivationParams();
+ if (!params) {
await webApi.logout();
router.replace('/login');
return null;
}
- return encryptionKeyDerivationParams;
- }, [webApi]);
+ return params;
+ }, [webApi, getEncryptionKeyDerivationParams]);
useEffect(() => {
getKeyDerivationParams();
@@ -83,14 +81,11 @@ export default function UnlockScreen() : React.ReactNode {
}
// Get the key derivation parameters from native storage
- const encryptionKeyDerivationParams = await getKeyDerivationParams();
- if (!encryptionKeyDerivationParams) {
+ const params = await getKeyDerivationParams();
+ if (!params) {
return;
}
- // Parse the key derivation parameters
- const params = JSON.parse(encryptionKeyDerivationParams);
-
// Derive the encryption key from the password using the stored parameters
const passwordHash = await EncryptionUtility.deriveKeyFromPassword(
password,
diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsx
index 211f5aa18..6ae639242 100644
--- a/apps/mobile-app/context/AuthContext.tsx
+++ b/apps/mobile-app/context/AuthContext.tsx
@@ -3,7 +3,7 @@ import { NavigationContainerRef, ParamListBase } from '@react-navigation/native'
import * as LocalAuthentication from 'expo-local-authentication';
import { router, useGlobalSearchParams, usePathname } from 'expo-router';
import React, { createContext, useContext, useState, useEffect, useMemo, useCallback, useRef } from 'react';
-import { AppState, Platform } from 'react-native';
+import { Alert, AppState, Platform } from 'react-native';
import EncryptionUtility from '@/utils/EncryptionUtility';
@@ -26,8 +26,6 @@ type AuthContextType = {
initializeAuth: () => Promise<{ isLoggedIn: boolean; enabledAuthMethods: AuthMethod[] }>;
login: () => Promise<void>;
logout: (errorMessage?: string) => Promise<void>;
- globalMessage: string | null;
- clearGlobalMessage: () => void;
setAuthMethods: (methods: AuthMethod[]) => Promise<void>;
getAuthMethodDisplayKey: () => Promise<string>;
getAutoLockTimeout: () => Promise<number>;
@@ -36,6 +34,7 @@ type AuthContextType = {
isBiometricsEnabledOnDevice: () => Promise<boolean>;
setOfflineMode: (isOffline: boolean) => void;
verifyPassword: (password: string) => Promise<string | null>;
+ getEncryptionKeyDerivationParams: () => Promise<{ salt: string; encryptionType: string; encryptionSettings: string } | null>;
// Autofill methods
shouldShowAutofillReminder: boolean;
markAutofillConfigured: () => Promise<void>;
@@ -58,7 +57,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [isInitialized, setIsInitialized] = useState(false);
const [username, setUsername] = useState<string | null>(null);
- const [globalMessage, setGlobalMessage] = useState<string | null>(null);
const [shouldShowAutofillReminder, setShouldShowAutofillReminder] = useState(false);
const [returnUrl, setReturnUrl] = useState<{ path: string; params?: object } | null>(null);
const [isOffline, setIsOffline] = useState(false);
@@ -167,22 +165,15 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
await AsyncStorage.removeItem('authMethods');
dbContext?.clearDatabase();
- // Set local storage global message that will be shown on the login page.
if (errorMessage) {
- setGlobalMessage(errorMessage);
+ // Show alert
+ Alert.alert(errorMessage);
}
setUsername(null);
setIsLoggedIn(false);
}, [dbContext]);
- /**
- * Clear global message (called after displaying the message).
- */
- const clearGlobalMessage = useCallback((): void => {
- setGlobalMessage(null);
- }, []);
-
/**
* Set the authentication methods and save them to storage
*/
@@ -286,19 +277,37 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
}
}, []);
+ /**
+ * Get the encryption key derivation parameters from native storage.
+ * Returns parsed parameters or null if not available.
+ */
+ const getEncryptionKeyDerivationParams = useCallback(async (): Promise<{
+ salt: string;
+ encryptionType: string;
+ encryptionSettings: string;
+ } | null> => {
+ try {
+ const encryptionKeyDerivationParams = await NativeVaultManager.getEncryptionKeyDerivationParams();
+ if (!encryptionKeyDerivationParams) {
+ return null;
+ }
+ return JSON.parse(encryptionKeyDerivationParams);
+ } catch (error) {
+ console.error('Failed to get encryption key derivation params:', error);
+ return null;
+ }
+ }, []);
+
/**
* Verify the password. Returns the current password hash if the password is correct, otherwise returns null.
*/
const verifyPassword = useCallback(async (password: string): Promise<string | null> => {
- // Check locally if the current password is correct by attempting to decrypt the vault
- const encryptionKeyDerivationParams = await NativeVaultManager.getEncryptionKeyDerivationParams();
- if (!encryptionKeyDerivationParams) {
+ // Get the key derivation parameters
+ const params = await getEncryptionKeyDerivationParams();
+ if (!params) {
throw new Error('Failed to verify current password. Please try again.');
}
- // Parse the key derivation parameters
- const params = JSON.parse(encryptionKeyDerivationParams);
-
// Derive the encryption key from the password using the stored parameters
const passwordHash = await EncryptionUtility.deriveKeyFromPassword(
password,
@@ -316,7 +325,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
}
return currentPasswordHashBase64;
- }, [dbContext]);
+ }, [dbContext, getEncryptionKeyDerivationParams]);
// Handle app state changes
useEffect(() => {
@@ -383,7 +392,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
isLoggedIn,
isInitialized,
username,
- globalMessage,
shouldShowAutofillReminder,
returnUrl,
isOffline,
@@ -393,7 +401,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
initializeAuth,
login,
logout,
- clearGlobalMessage,
setAuthMethods,
getAuthMethodDisplayKey,
isBiometricsEnabledOnDevice,
@@ -403,12 +410,12 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
markAutofillConfigured,
setReturnUrl,
verifyPassword,
+ getEncryptionKeyDerivationParams,
setOfflineMode: setIsOffline,
}), [
isLoggedIn,
isInitialized,
username,
- globalMessage,
shouldShowAutofillReminder,
returnUrl,
isOffline,
@@ -418,7 +425,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
initializeAuth,
login,
logout,
- clearGlobalMessage,
setAuthMethods,
getAuthMethodDisplayKey,
isBiometricsEnabledOnDevice,
@@ -428,6 +434,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
markAutofillConfigured,
setReturnUrl,
verifyPassword,
+ getEncryptionKeyDerivationParams,
]);
return (
diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.ts
index 8dbb77465..a94975e87 100644
--- a/apps/mobile-app/hooks/useVaultSync.ts
+++ b/apps/mobile-app/hooks/useVaultSync.ts
@@ -90,6 +90,19 @@ export const useVaultSync = () : {
return false;
}
+ // Check if the SRP salt has changed compared to locally stored encryption key derivation params
+ const keyDerivationParams = await authContext.getEncryptionKeyDerivationParams();
+ if (keyDerivationParams && statusResponse.srpSalt !== '' && statusResponse.srpSalt !== keyDerivationParams.salt) {
+ /**
+ * Server SRP salt has changed compared to locally stored value, which means the user has changed
+ * their password since the last time they logged in. This means that the local encryption key is no
+ * longer valid and the user needs to re-authenticate. We trigger a logout but do not revoke tokens
+ * as these were already revoked by the server upon password change.
+ */
+ await webApi.logout(t('vault.errors.passwordChanged'), false);
+ return false;
+ }
+
// If we get here, it means we have a valid connection to the server.
authContext.setOfflineMode(false);
diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.json
index 21c1dddf2..436f26f3e 100644
--- a/apps/mobile-app/i18n/locales/en.json
+++ b/apps/mobile-app/i18n/locales/en.json
@@ -80,7 +80,8 @@
"versionNotSupported": "This version of the AliasVault mobile app is not supported by the server anymore. Please update your app to the latest version.",
"serverNeedsUpdate": "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.",
"vaultDecryptFailed": "Vault could not be decrypted, if the problem persists please logout and login again.",
- "unknownErrorDuringSync": "Unknown error during vault sync"
+ "unknownErrorDuringSync": "Unknown error during vault sync",
+ "passwordChanged": "Your password has changed since the last time you logged in. Please login again for security reasons."
}
},
"credentials": {
diff --git a/apps/mobile-app/utils/WebApiService.ts b/apps/mobile-app/utils/WebApiService.ts
index ef3191081..6111b3550 100644
--- a/apps/mobile-app/utils/WebApiService.ts
+++ b/apps/mobile-app/utils/WebApiService.ts
@@ -261,19 +261,21 @@ export class WebApiService {
/**
* Logout and revoke tokens via WebApi and remove local storage tokens via AuthContext.
*/
- public async logout(statusError: string | null = null): Promise<void> {
+ public async logout(statusError: string | null = null, revokeTokens: boolean = true): Promise<void> {
// Logout and revoke tokens via WebApi.
try {
- const refreshToken = await this.getRefreshToken();
- if (!refreshToken) {
- return;
- }
+ if (revokeTokens) {
+ const refreshToken = await this.getRefreshToken();
+ if (!refreshToken) {
+ return;
+ }
- // We do not await this as we want to continue with the logout even if the revoke fails or takes a long time.
- this.post('Auth/revoke', {
- token: await this.getAccessToken(),
- refreshToken: refreshToken,
- }, false);
+ // We do not await this as we want to continue with the logout even if the revoke fails or takes a long time.
+ this.post('Auth/revoke', {
+ token: await this.getAccessToken(),
+ refreshToken: refreshToken,
+ }, false);
+ }
} catch (err) {
console.error('WebApi logout error:', err);
}
diff --git a/apps/mobile-app/utils/dist/shared/models/webapi/index.d.ts b/apps/mobile-app/utils/dist/shared/models/webapi/index.d.ts
index 4e5f860e2..37b362306 100644
--- a/apps/mobile-app/utils/dist/shared/models/webapi/index.d.ts
+++ b/apps/mobile-app/utils/dist/shared/models/webapi/index.d.ts
@@ -65,6 +65,7 @@ type StatusResponse = {
clientVersionSupported: boolean;
serverVersion: string;
vaultRevision: number;
+ srpSalt: string;
};
/**
diff --git a/shared/models/src/webapi/StatusResponse.ts b/shared/models/src/webapi/StatusResponse.ts
index 53d4181f0..2942ee945 100644
--- a/shared/models/src/webapi/StatusResponse.ts
+++ b/shared/models/src/webapi/StatusResponse.ts
@@ -5,4 +5,5 @@ export type StatusResponse = {
clientVersionSupported: boolean;
serverVersion: string;
vaultRevision: number;
+ srpSalt: string;
}