Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add vault password change logic to react native (#771)
Leendert de Borst822815080c5b
diff --git a/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx b/apps/mobile-app/app/(tabs)/settings/security/change-password.tsxindex 5666b88d6..45bc40ce8 100644--- a/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx+++ b/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx@@ -1,31 +1,38 @@-import { StyleSheet, View, TouchableOpacity, Animated, Alert } from 'react-native';-import { router } from 'expo-router';-import { Ionicons } from '@expo/vector-icons';-import { useRef, useState } from 'react';+import { Buffer } from 'buffer';++import { StyleSheet, View, Alert, ScrollView } from 'react-native';+import { useState } from 'react';import { useSafeAreaInsets } from 'react-native-safe-area-context';+import { router } from 'expo-router';import { ThemedText } from '@/components/themed/ThemedText';import { ThemedView } from '@/components/themed/ThemedView';import { useColors } from '@/hooks/useColorScheme';-import { TitleContainer } from '@/components/ui/TitleContainer';-import { CollapsibleHeader } from '@/components/ui/CollapsibleHeader';import { ThemedTextInput } from '@/components/themed/ThemedTextInput';import { ThemedButton } from '@/components/themed/ThemedButton';-import { useWebApi } from '@/context/WebApiContext';+import { useAuth } from '@/context/AuthContext';+import { useDb } from '@/context/DbContext';+import EncryptionUtility from '@/utils/EncryptionUtility';+import NativeVaultManager from '@/specs/NativeVaultManager';+import { useVaultMutate } from '@/hooks/useVaultMutate';+import LoadingOverlay from '@/components/LoadingOverlay';/*** Change password screen.+ * @returns {React.ReactNode} The rendered component*/-export default function ChangePasswordScreen() : React.ReactNode {+export default function ChangePasswordScreen(): React.ReactNode {const colors = useColors();const insets = useSafeAreaInsets();- const scrollY = useRef(new Animated.Value(0)).current;- const webApi = useWebApi();+ const authContext = useAuth();+ const dbContext = useDb();+ const { executeVaultPasswordChange, syncStatus } = useVaultMutate();const [currentPassword, setCurrentPassword] = useState('');const [newPassword, setNewPassword] = useState('');const [confirmPassword, setConfirmPassword] = useState('');const [isLoading, setIsLoading] = useState(false);+ const [loadingStatus, setLoadingStatus] = useState<string | null>(null);const styles = StyleSheet.create({button: {@@ -33,16 +40,28 @@ export default function ChangePasswordScreen() : React.ReactNode {},container: {flex: 1,+ marginTop: 42,paddingBottom: insets.bottom,paddingHorizontal: 14,paddingTop: insets.top,},+ contentContainer: {+ paddingBottom: 40,+ },form: {backgroundColor: colors.accentBackground,borderRadius: 10,marginTop: 20,padding: 16,},+ header: {+ padding: 16,+ paddingBottom: 0,+ },+ headerText: {+ color: colors.textMuted,+ fontSize: 13,+ },inputContainer: {marginBottom: 16,},@@ -51,19 +70,13 @@ export default function ChangePasswordScreen() : React.ReactNode {fontSize: 16,marginBottom: 8,},- scrollContent: {- paddingBottom: 40,- paddingTop: 42,- },- scrollView: {- flex: 1,- },});/**- *+ * Handle the submit button press.+ * @returns {Promise<void>} A promise that resolves when the operation is complete*/- const handleSubmit = async () => {+ const handleSubmit = async (): Promise<void> => {if (!currentPassword || !newPassword || !confirmPassword) {Alert.alert('Error', 'Please fill in all fields');return;@@ -74,76 +87,121 @@ export default function ChangePasswordScreen() : React.ReactNode {return;}+ if (!authContext.username) {+ Alert.alert('Error', 'User not authenticated');+ return;+ }+try {setIsLoading(true);+ setLoadingStatus('Initiating password change...');++ // Check locally if the current password is correct by attempting to decrypt the vault+ const encryptionKeyDerivationParams = await NativeVaultManager.getEncryptionKeyDerivationParams();+ if (!encryptionKeyDerivationParams) {+ 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(+ currentPassword,+ params.salt,+ params.encryptionType,+ params.encryptionSettings+ );++ const currentPasswordHashBase64 = Buffer.from(passwordHash).toString('base64');++ // Check if the current password is correct by attempting to decrypt the vault+ const dbAvailable = await dbContext.testDatabaseConnection(currentPasswordHashBase64);+ if (!dbAvailable) {+ console.error('Current password is not correct');+ Alert.alert('Error', 'Current password is not correct');+ return;+ }- // Verify current password- /*- * const isValid = await verifyPassword(currentPassword);- *if (!isValid) {- *Alert.alert('Error', 'Current password is incorrect');- *return;- *}- *- * // Create new vault version with new password- *await createNewVersion(newPassword);- *- * // Submit to server- *await webApi.submitVaultVersion(vault.getCurrentVersion());- *- *Alert.alert('Success', 'Password changed successfully', [- *{ text: 'OK', onPress: () => router.back() }- *]);- */+ // 2nd. if it is, we pass the new plain text password to the vault password change sync hook and that takes care of all the rest?+ await executeVaultPasswordChange(currentPasswordHashBase64, newPassword);++ // Show confirm dialog and go back to the settings screen+ Alert.alert('Success', 'Password changed successfully', [+ { text: 'OK',+ /**+ * Reset the password change state and go back to the settings screen+ */+ onPress: () : void => {+ setCurrentPassword('');+ setNewPassword('');+ setConfirmPassword('');+ router.back();+ } }+ ]);} catch (error) {+ console.error('Password change error:', error);Alert.alert('Error', 'Failed to change password. Please try again.');} finally {setIsLoading(false);+ setLoadingStatus(null);}};return (- <ThemedView style={styles.container}>- <View style={styles.scrollContent}>- <View style={styles.form}>- <View style={styles.inputContainer}>- <ThemedText style={styles.label}>Current Password</ThemedText>- <ThemedTextInput- secureTextEntry- value={currentPassword}- onChangeText={setCurrentPassword}- placeholder="Enter current password"- />+ <>+ {(isLoading) && (+ <LoadingOverlay status={syncStatus.length > 0 ? syncStatus : loadingStatus ?? ''} />+ )}+ <ThemedView style={styles.container}>+ <ScrollView+ contentContainerStyle={styles.contentContainer}+ >+ <View style={styles.header}>+ <ThemedText style={styles.headerText}>+ Changing your master password also changes the vault encryption keys. It is advised to periodically change your master password to keep your vaults secure.+ </ThemedText></View>+ <View style={styles.form}>+ <View style={styles.inputContainer}>+ <ThemedText style={styles.label}>Current Password</ThemedText>+ <ThemedTextInput+ secureTextEntry+ value={currentPassword}+ onChangeText={setCurrentPassword}+ placeholder="Enter current password"+ />+ </View>- <View style={styles.inputContainer}>- <ThemedText style={styles.label}>New Password</ThemedText>- <ThemedTextInput- secureTextEntry- value={newPassword}- onChangeText={setNewPassword}- placeholder="Enter new password"- />- </View>+ <View style={styles.inputContainer}>+ <ThemedText style={styles.label}>New Password</ThemedText>+ <ThemedTextInput+ secureTextEntry+ value={newPassword}+ onChangeText={setNewPassword}+ placeholder="Enter new password"+ />+ </View>++ <View style={styles.inputContainer}>+ <ThemedText style={styles.label}>Confirm New Password</ThemedText>+ <ThemedTextInput+ secureTextEntry+ value={confirmPassword}+ onChangeText={setConfirmPassword}+ placeholder="Confirm new password"+ />+ </View>- <View style={styles.inputContainer}>- <ThemedText style={styles.label}>Confirm New Password</ThemedText>- <ThemedTextInput- secureTextEntry- value={confirmPassword}- onChangeText={setConfirmPassword}- placeholder="Confirm new password"+ <ThemedButton+ title="Change Password"+ onPress={handleSubmit}+ loading={isLoading}+ style={styles.button}/></View>-- <ThemedButton- title="Change Password"- onPress={handleSubmit}- loading={isLoading}- style={styles.button}- />- </View>- </View>- </ThemedView>+ </ScrollView>+ </ThemedView>+ </>);}\ No newline at end of filediff --git a/apps/mobile-app/context/DbContext.tsx b/apps/mobile-app/context/DbContext.tsxindex a34f34cb9..b3839e507 100644--- a/apps/mobile-app/context/DbContext.tsx+++ b/apps/mobile-app/context/DbContext.tsx@@ -159,11 +159,13 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }await sqliteClient.storeEncryptionKey(derivedKey);// Initialize the database- await unlockVault();+ const unlocked = await unlockVault();+ if (!unlocked) {+ return false;+ }// Try to get the database version as a simple test queryconst version = await sqliteClient.getDatabaseVersion();-if (version && version.length > 0) {return true;}diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.tsindex 8a28cb967..f67bae042 100644--- a/apps/mobile-app/hooks/useVaultMutate.ts+++ b/apps/mobile-app/hooks/useVaultMutate.ts@@ -1,11 +1,17 @@import { useCallback, useState } from 'react';import Toast from 'react-native-toast-message';+import srp from 'secure-remote-password/client';import { useVaultSync } from '@/hooks/useVaultSync';import { useAuth } from '@/context/AuthContext';import { useDb } from '@/context/DbContext';import { useWebApi } from '@/context/WebApiContext';import NativeVaultManager from '@/specs/NativeVaultManager';+import { Vault } from '@/utils/types/webapi/Vault';+import EncryptionUtility from '@/utils/EncryptionUtility';+import { PasswordChangeInitiateResponse } from '@/utils/types/webapi/PasswordChangeInitiateResponse';+import { VaultPasswordChangeRequest } from '@/utils/types/webapi/VaultPasswordChangeRequest';+import { EncryptionKeyDerivationParams } from '@/utils/types/messaging/EncryptionKeyDerivationParams';type VaultPostResponse = {status: number;@@ -22,6 +28,7 @@ type VaultMutationOptions = {*/export function useVaultMutate() : {executeVaultMutation: (operation: () => Promise<void>, options?: VaultMutationOptions) => Promise<void>;+ executeVaultPasswordChange: (currentPasswordHashBase64: string, newPasswordPlainText: string, options?: VaultMutationOptions) => Promise<void>;isLoading: boolean;syncStatus: string;} {@@ -33,17 +40,9 @@ export function useVaultMutate() : {const { syncVault } = useVaultSync();/**- * Execute the provided operation (e.g. create/update/delete credential)+ * Prepare the vault for upload, returns the new vault object with the updated revision number and encrypted database.*/- const executeOperation = useCallback(async (- operation: () => Promise<void>,- options: VaultMutationOptions- ) : Promise<void> => {- setSyncStatus('Saving changes to vault');-- // Execute the provided operation (e.g. create/update/delete credential)- await operation();-+ const prepareVault = useCallback(async () : Promise<Vault> => {// Get the current vault revision numberconst currentRevision = await NativeVaultManager.getCurrentVaultRevisionNumber();@@ -74,7 +73,7 @@ export function useVaultMutate() : {}// Create vault object for upload- const newVault = {+ return {blob: encryptedDb,createdAt: new Date().toISOString(),credentialsCount: credentials.length,@@ -88,6 +87,22 @@ export function useVaultMutate() : {username: username,version: await dbContext.sqliteClient!.getDatabaseVersion() ?? '0.0.0'};+ }, [dbContext, authContext]);++ /**+ * Execute the provided operation (e.g. create/update/delete credential)+ */+ const executeMutateOperation = useCallback(async (+ operation: () => Promise<void>,+ options: VaultMutationOptions+ ) : Promise<void> => {+ setSyncStatus('Saving changes to vault');++ // Execute the provided operation (e.g. create/update/delete credential)+ await operation();++ setSyncStatus('Uploading vault to server');+ const newVault = await prepareVault();try {// Upload to server@@ -114,8 +129,110 @@ export function useVaultMutate() : {}throw error;}- }, [dbContext, authContext, webApi]);+ }, [authContext, webApi, prepareVault]);++ /**+ * Execute the provided operation (e.g. create/update/delete credential)+ */+ const executePasswordChangeOperation = useCallback(async (+ currentPasswordHashBase64: string,+ newPasswordPlainText: string,+ options: VaultMutationOptions+ ) : Promise<void> => {+ setSyncStatus('Saving changes to vault');++ const data = await webApi.authFetch<PasswordChangeInitiateResponse>('Auth/change-password/initiate');+ const currentSalt = data.salt;+ const currentServerEphemeral = data.serverEphemeral;++ // Convert base64 string to hex string+ const currentPasswordHashString = Buffer.from(currentPasswordHashBase64, 'base64').toString('hex').toUpperCase();++ // Generate client ephemeral and session+ const newClientEphemeral = srp.generateEphemeral();+ // Get username from the auth context, always lowercase and trimmed which is required for the argon2id key derivation+ const username = authContext.username?.toLowerCase().trim();+ if (!username) {+ throw new Error('Username not found. Please login again.');+ }+ const privateKey = srp.derivePrivateKey(currentSalt, username, currentPasswordHashString);+ const newClientSession = srp.deriveSession(+ newClientEphemeral.secret,+ currentServerEphemeral,+ currentSalt,+ username,+ privateKey+ );++ // Generate salt and verifier for new password+ const newSalt = srp.generateSalt();+ const newPasswordHash = await EncryptionUtility.deriveKeyFromPassword(newPasswordPlainText, newSalt, data.encryptionType, data.encryptionSettings);+ const newPasswordHashString = Buffer.from(newPasswordHash).toString('hex').toUpperCase();++ // Set new password hash locally+ try {++ // Store the new encryption key and derivation parameters locally+ const newEncryptionKeyDerivationParams : EncryptionKeyDerivationParams = {+ encryptionType: data.encryptionType,+ encryptionSettings: data.encryptionSettings,+ salt: newSalt,+ };++ await dbContext.storeEncryptionKey(Buffer.from(newPasswordHash).toString('base64'));+ await dbContext.storeEncryptionKeyDerivationParams(newEncryptionKeyDerivationParams);++ /**+ * Persist the new encrypted database with the new encryption key by starting and committing a transaction.+ * which simulates a vault mutation operation. As part of this operation, a new encrypted database is created+ * locally which can then be uploaded to the server.+ */+ await NativeVaultManager.beginTransaction();+ await NativeVaultManager.commitTransaction();++ // Unlock the newly persisted database to ensure it works and the new encryption key will be persisted in the keychain.+ await NativeVaultManager.unlockVault();+ } catch {+ // If any part of this fails, we need logout the user as the local vault and stored encryption key are now potentially corrupt.+ authContext.logout('Error during password change operation. Please log in again to retrieve your latest vault.');+ }++ // Generate SRP password change data+ const newPrivateKey = srp.derivePrivateKey(newSalt, username, newPasswordHashString);+ const newVerifier = srp.deriveVerifier(newPrivateKey);++ // Get the current vault revision number+ const vault = await prepareVault();+ setSyncStatus('Uploading vault to server');++ // Convert default vault object to password change vault object+ const passwordChangeVault : VaultPasswordChangeRequest = {+ ...vault,+ currentClientPublicEphemeral: newClientEphemeral.public,+ currentClientSessionProof: newClientSession.proof,+ newPasswordSalt: newSalt,+ newPasswordVerifier: newVerifier+ };++ try {+ // Upload to server+ await webApi.post<typeof passwordChangeVault, VaultPostResponse>('Vault/change-password', passwordChangeVault);++ // If we get here, it means we have a valid connection to the server.+ authContext.setOfflineMode(false);++ await NativeVaultManager.setCurrentVaultRevisionNumber(passwordChangeVault.currentRevisionNumber + 1);+ options.onSuccess?.();+ } catch (error) {+ console.error('Error during password change operation:', error);+ throw error;+ }+ }, [dbContext, authContext, webApi, prepareVault]);++ /**+ * Hook to execute a vault mutation which uploads a new encrypted vault to the server+ */const executeVaultMutation = useCallback(async (operation: () => Promise<void>,options: VaultMutationOptions = {}@@ -138,14 +255,95 @@ export function useVaultMutate() : {if (hasNewVault) {// Vault was changed, but has now been reloaded so we can continue with the operation.}- await executeOperation(operation, options);+ await executeMutateOperation(operation, options);+ },+ /**+ * Handle offline state and prompt user for action.+ */+ onError: () => {+ // Still offline, proceed with local operation+ executeMutateOperation(operation, options);+ }+ });+ } else {+ await syncVault({+ /**+ * Handle the status update.+ */+ onStatus: (message) => setSyncStatus(message),+ /**+ * Handle successful vault sync and continue with vault mutation.+ */+ onSuccess: async (hasNewVault) => {+ if (hasNewVault) {+ // Vault was changed, but has now been reloaded so we can continue with the operation.+ }+ await executeMutateOperation(operation, options);+ },+ /**+ * Handle error during vault sync.+ */+ onError: (error) => {+ Toast.show({+ type: 'error',+ text1: 'Failed to sync vault',+ text2: error,+ position: 'bottom'+ });+ options.onError?.(new Error(error));+ }+ });+ }+ } catch (error) {+ console.error('Error during vault mutation:', error);+ Toast.show({+ type: 'error',+ text1: 'Operation failed',+ text2: error instanceof Error ? error.message : 'Unknown error',+ position: 'bottom'+ });+ options.onError?.(error instanceof Error ? error : new Error('Unknown error'));+ } finally {+ setIsLoading(false);+ setSyncStatus('');+ }+ }, [syncVault, executeMutateOperation, authContext.isOffline]);++ /**+ * Hook to execute a password change which uploads a new encrypted vault to the server+ * with updated SRP verifier and salt. It shares common logic with the regular vault mutation upload.+ */+ const executeVaultPasswordChange = useCallback(async (+ currentPasswordHashBase64: string,+ newPasswordPlainText: string,+ options: VaultMutationOptions = {}+ ) => {+ try {+ setIsLoading(true);+ setSyncStatus('Checking for vault updates');++ // If we're in offline mode, try to sync once to see if we can get back online+ if (authContext.isOffline) {+ await syncVault({+ /**+ * Handle the status update.+ */+ onStatus: (message) => setSyncStatus(message),+ /**+ * Handle successful vault sync and continue with vault mutation.+ */+ onSuccess: async (hasNewVault) => {+ if (hasNewVault) {+ // Vault was changed, but has now been reloaded so we can continue with the operation.+ }+ await executePasswordChangeOperation(currentPasswordHashBase64, newPasswordPlainText, options);},/*** Handle offline state and prompt user for action.*/onError: () => {// Still offline, proceed with local operation- executeOperation(operation, options);+ executePasswordChangeOperation(currentPasswordHashBase64, newPasswordPlainText, options);}});} else {@@ -161,7 +359,7 @@ export function useVaultMutate() : {if (hasNewVault) {// Vault was changed, but has now been reloaded so we can continue with the operation.}- await executeOperation(operation, options);+ await executePasswordChangeOperation(currentPasswordHashBase64, newPasswordPlainText, options);},/*** Handle error during vault sync.@@ -190,10 +388,11 @@ export function useVaultMutate() : {setIsLoading(false);setSyncStatus('');}- }, [syncVault, executeOperation, authContext.isOffline]);+ }, [syncVault, executePasswordChangeOperation, authContext.isOffline]);return {executeVaultMutation,+ executeVaultPasswordChange,isLoading,syncStatus};diff --git a/apps/mobile-app/utils/types/webapi/PasswordChangeInitiateResponse.ts b/apps/mobile-app/utils/types/webapi/PasswordChangeInitiateResponse.tsnew file mode 100644index 000000000..a217476d0--- /dev/null+++ b/apps/mobile-app/utils/types/webapi/PasswordChangeInitiateResponse.ts@@ -0,0 +1,9 @@+/**+ * Represents a password change initiate response.+ */+export type PasswordChangeInitiateResponse = {+ salt: string;+ serverEphemeral: string;+ encryptionType: string;+ encryptionSettings: string;+};diff --git a/apps/mobile-app/utils/types/webapi/VaultPasswordChangeRequest.ts b/apps/mobile-app/utils/types/webapi/VaultPasswordChangeRequest.tsnew file mode 100644index 000000000..5651576cf--- /dev/null+++ b/apps/mobile-app/utils/types/webapi/VaultPasswordChangeRequest.ts@@ -0,0 +1,11 @@+import { Vault } from "./Vault";++/**+ * Represents a request to change the users password including a new vault that is encrypted with the new password.+ */+export type VaultPasswordChangeRequest = Vault & {+ currentClientPublicEphemeral: string;+ currentClientSessionProof: string;+ newPasswordSalt: string;+ newPasswordVerifier: string;+}