Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add delete account implementation (#771)
Leendert de Borstafa9ad8b2f5a
diff --git a/apps/mobile-app/app/(tabs)/settings/index.tsx b/apps/mobile-app/app/(tabs)/settings/index.tsxindex 977495464..88b9915f4 100644--- a/apps/mobile-app/app/(tabs)/settings/index.tsx+++ b/apps/mobile-app/app/(tabs)/settings/index.tsx@@ -1,4 +1,4 @@-import { StyleSheet, View, ScrollView, TouchableOpacity, Image, Animated, Platform } from 'react-native';+import { StyleSheet, View, ScrollView, TouchableOpacity, Animated, Platform } from 'react-native';import { router, useFocusEffect } from 'expo-router';import { Ionicons } from '@expo/vector-icons';import { useRef, useState, useCallback } from 'react';@@ -14,7 +14,7 @@ import { useAuth } from '@/context/AuthContext';import { CollapsibleHeader } from '@/components/ui/CollapsibleHeader';import { InlineSkeletonLoader } from '@/components/ui/InlineSkeletonLoader';import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';-import avatarImage from '@/assets/images/avatar.webp';+import { UsernameDisplay } from '@/components/ui/UsernameDisplay';/*** Settings screen.@@ -22,7 +22,7 @@ import avatarImage from '@/assets/images/avatar.webp';export default function SettingsScreen() : React.ReactNode {const webApi = useWebApi();const colors = useColors();- const { username, getAuthMethodDisplay, shouldShowIosAutofillReminder } = useAuth();+ const { getAuthMethodDisplay, shouldShowIosAutofillReminder } = useAuth();const { getAutoLockTimeout } = useAuth();const scrollY = useRef(new Animated.Value(0)).current;const scrollViewRef = useRef<ScrollView>(null);@@ -111,12 +111,6 @@ export default function SettingsScreen() : React.ReactNode {};const styles = StyleSheet.create({- avatar: {- borderRadius: 20,- height: 40,- marginRight: 12,- width: 40,- },container: {flex: 1,paddingBottom: insets.bottom,@@ -190,18 +184,6 @@ export default function SettingsScreen() : React.ReactNode {skeletonLoader: {marginRight: 8,},- userInfoContainer: {- alignItems: 'center',- backgroundColor: colors.background,- borderRadius: 10,- flexDirection: 'row',- marginBottom: 20,- },- usernameText: {- color: colors.text,- fontSize: 16,- fontWeight: '600',- },versionContainer: {alignItems: 'center',marginTop: 20,@@ -233,14 +215,7 @@ export default function SettingsScreen() : React.ReactNode {style={styles.scrollView}><TitleContainer title="Settings" />- <View style={styles.userInfoContainer}>- <Image- source={avatarImage}- style={styles.avatar}- />- <ThemedText style={styles.usernameText}>Logged in as: {username}</ThemedText>- </View>-+ <UsernameDisplay /><View style={styles.section}>{Platform.OS === 'ios' && (<>diff --git a/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx b/apps/mobile-app/app/(tabs)/settings/security/change-password.tsxindex 45bc40ce8..cfa16634d 100644--- a/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx+++ b/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx@@ -1,5 +1,3 @@-import { Buffer } from 'buffer';-import { StyleSheet, View, Alert, ScrollView } from 'react-native';import { useState } from 'react';import { useSafeAreaInsets } from 'react-native-safe-area-context';@@ -11,11 +9,9 @@ import { useColors } from '@/hooks/useColorScheme';import { ThemedTextInput } from '@/components/themed/ThemedTextInput';import { ThemedButton } from '@/components/themed/ThemedButton';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';+import { UsernameDisplay } from '@/components/ui/UsernameDisplay';/*** Change password screen.@@ -25,7 +21,6 @@ export default function ChangePasswordScreen(): React.ReactNode {const colors = useColors();const insets = useSafeAreaInsets();const authContext = useAuth();- const dbContext = useDb();const { executeVaultPasswordChange, syncStatus } = useVaultMutate();const [currentPassword, setCurrentPassword] = useState('');@@ -96,34 +91,12 @@ export default function ChangePasswordScreen(): React.ReactNode {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');+ const currentPasswordHashBase64 = await authContext.verifyPassword(currentPassword);+ if (!currentPasswordHashBase64) {Alert.alert('Error', 'Current password is not correct');return;}- // 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@@ -162,6 +135,7 @@ export default function ChangePasswordScreen(): React.ReactNode {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>+ <UsernameDisplay /><View style={styles.form}><View style={styles.inputContainer}><ThemedText style={styles.label}>Current Password</ThemedText>diff --git a/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx b/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsxindex c4bcb962d..0eb72a737 100644--- a/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx+++ b/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx@@ -1,80 +1,113 @@-import { StyleSheet, View, TouchableOpacity, Animated, Alert } from 'react-native';+import { StyleSheet, View, Alert, ScrollView } from 'react-native';import { router } from 'expo-router';-import { Ionicons } from '@expo/vector-icons';-import { useRef, useState } from 'react';+import { useState } from 'react';import { useSafeAreaInsets } from 'react-native-safe-area-context';+import srp from 'secure-remote-password/client';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 { DeleteAccountInitiateRequest, DeleteAccountInitiateResponse } from '@/utils/types/webapi/DeleteAccountInitiate';+import { DeleteAccountRequest } from '@/utils/types/webapi/DeleteAccountRequest';+import { UsernameDisplay } from '@/components/ui/UsernameDisplay';+import LoadingOverlay from '@/components/LoadingOverlay';/*** Delete account screen.*/-export default function DeleteAccountScreen() : React.ReactNode {+export default function DeleteAccountScreen(): React.ReactNode {const colors = useColors();const insets = useSafeAreaInsets();- const scrollY = useRef(new Animated.Value(0)).current;const webApi = useWebApi();- const { username } = useAuth();+ const { username, verifyPassword, logout } = useAuth();const [confirmUsername, setConfirmUsername] = useState('');const [password, setPassword] = useState('');const [isLoading, setIsLoading] = useState(false);+ const [loadingStatus, setLoadingStatus] = useState<string | null>(null);const [step, setStep] = useState<'username' | 'password'>('username');const styles = StyleSheet.create({button: {- marginTop: 8,+ marginTop: 16,},buttonDanger: {- backgroundColor: colors.error,+ backgroundColor: colors.errorBackground,},container: {flex: 1,+ marginTop: 42,paddingBottom: insets.bottom,- paddingHorizontal: 14,+ paddingHorizontal: 16,paddingTop: insets.top,},+ contentContainer: {+ paddingBottom: 40,+ },form: {backgroundColor: colors.accentBackground,- borderRadius: 10,+ borderColor: colors.accentBorder,+ borderRadius: 12,+ borderWidth: 1,marginTop: 20,+ padding: 20,+ },+ header: {padding: 16,+ paddingBottom: 0,+ },+ headerText: {+ color: colors.textMuted,+ fontSize: 13,},inputContainer: {- marginBottom: 16,+ marginBottom: 20,+ marginTop: 20,},label: {color: colors.text,fontSize: 16,+ fontWeight: '500',marginBottom: 8,},- scrollContent: {- paddingBottom: 40,- paddingTop: 42,+ warningIcon: {+ alignSelf:'flex-start',+ color: colors.errorText,+ fontSize: 16,},- scrollView: {+ warningItem: {+ alignItems: 'center',+ flexDirection: 'row',+ marginBottom: 10,+ paddingLeft: 8,+ },+ warningItemText: {+ color: colors.text,flex: 1,+ fontSize: 14,+ marginLeft: 8,},warningText: {- color: colors.error,+ backgroundColor: colors.errorBackground,+ borderColor: colors.errorBorder,+ borderRadius: 12,+ borderWidth: 1,+ color: colors.errorText,fontSize: 14,- marginBottom: 16,+ marginBottom: 20,+ padding: 16,textAlign: 'center',},});/**- *+ * Handles the username confirmation step*/- const handleUsernameSubmit = () => {+ const handleUsernameSubmit = (): void => {if (confirmUsername !== username) {Alert.alert('Error', 'Username does not match');return;@@ -83,9 +116,9 @@ export default function DeleteAccountScreen() : React.ReactNode {};/**- *+ * Handles the account deletion process*/- const handleDeleteAccount = async () => {+ const handleDeleteAccount = async (): Promise<void> => {if (!password) {Alert.alert('Error', 'Please enter your password');return;@@ -100,86 +133,167 @@ export default function DeleteAccountScreen() : React.ReactNode {text: 'Delete Account',style: 'destructive',/**- *+ * Handles the delete account press.*/- onPress: async () => {- try {- setIsLoading(true);-- // Verify password- /*- * const isValid = await vault.verifyPassword(password);- *if (!isValid) {- *Alert.alert('Error', 'Password is incorrect');- *return;- *}- *- * // Delete account- *await webApi.deleteAccount();- */-- // Log out and return to login- await webApi.logout();- router.replace('/login');- } catch (error) {- Alert.alert('Error', 'Failed to delete account. Please try again.');- } finally {- setIsLoading(false);- }- },+ onPress: async (): Promise<void> => handleDeleteAccountPress(),},]);};+ /**+ * Handles the account deletion process+ */+ const handleDeleteAccountPress = async (): Promise<void> => {+ try {+ setIsLoading(true);+ setLoadingStatus('Verifying password...');+ const currentPasswordHashBase64 = await verifyPassword(password);+ if (!currentPasswordHashBase64) {+ Alert.alert('Error', 'Current password is not correct');+ return;+ }++ setLoadingStatus('Initiating account deletion');++ await new Promise((resolve) => setTimeout(resolve, 500));++ if (!username) {+ throw new Error('Username not found. Please login again.');+ }++ const deleteAccountInitiateRequest: DeleteAccountInitiateRequest = {+ username: username,+ };++ // Get the current salt and server ephemeral+ const data = await webApi.post<DeleteAccountInitiateRequest, DeleteAccountInitiateResponse>('Auth/delete-account/initiate', deleteAccountInitiateRequest);+ const currentSalt = data.salt;+ const currentServerEphemeral = data.serverEphemeral;++ setLoadingStatus('Verifying with server');+ // 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 sanitizedUsername = username?.toLowerCase().trim();+ if (!sanitizedUsername) {+ throw new Error('Username not found. Please login again.');+ }++ const privateKey = srp.derivePrivateKey(currentSalt, sanitizedUsername, currentPasswordHashString);+ const newClientSession = srp.deriveSession(+ newClientEphemeral.secret,+ currentServerEphemeral,+ currentSalt,+ sanitizedUsername,+ privateKey+ );++ const deleteAccountRequest: DeleteAccountRequest = {+ username: sanitizedUsername,+ clientPublicEphemeral: newClientEphemeral.public,+ clientSessionProof: newClientSession.proof,+ };++ setLoadingStatus('Deleting account');+ await new Promise((resolve) => setTimeout(resolve, 1500));++ // Send final delete request with SRP proof.+ await webApi.post('Auth/delete-account/confirm', deleteAccountRequest);++ // Logout silently and navigate to login screen.+ await logout('Account deleted successfully');+ router.replace('/login');+ } catch (error) {+ console.error('Error deleting account:', error);+ Alert.alert('Error', 'Failed to delete account. Please try again.');+ } finally {+ setIsLoading(false);+ setLoadingStatus(null);+ }+ };++ /**+ * Renders a warning item with a bullet point+ * @param text - The warning text to display+ * @returns A React component+ */+ const WarningItem = ({ text }: { text: string }): React.ReactNode => (+ <View style={styles.warningItem}>+ <ThemedText style={styles.warningIcon}>•</ThemedText>+ <ThemedText style={styles.warningItemText}>{text}</ThemedText>+ </View>+ );++ /**+ * Renders the delete account screen+ * @returns A React component+ */return (- <ThemedView style={styles.container}>- <View style={styles.scrollContent}>- <View style={styles.form}>- {step === 'username' ? (- <>- <ThemedText style={styles.warningText}>- Warning: This action cannot be undone. All your data will be permanently deleted.- </ThemedText>- <View style={styles.inputContainer}>- <ThemedText style={styles.label}>Enter your username to confirm</ThemedText>- <ThemedTextInput- value={confirmUsername}- onChangeText={setConfirmUsername}- placeholder="Enter username"- autoCapitalize="none"+ <>+ {isLoading && <LoadingOverlay status={loadingStatus ?? ''} />}+ <ThemedView style={styles.container}>+ <ScrollView contentContainerStyle={styles.contentContainer}>+ <View style={styles.header}>+ <ThemedText style={styles.headerText}>+ Deleting your account will immediately and permanently delete all of your data.+ </ThemedText>+ </View>+ <UsernameDisplay />+ <View style={styles.form}>+ {step === 'username' ? (+ <>+ <ThemedText style={styles.warningText}>+ Warning: This action cannot be undone. All your data will be permanently deleted.+ </ThemedText>+ <WarningItem text="All encrypted vaults which includes all of your credentials will be permanently deleted" />+ <WarningItem text="Your email aliases will be orphaned and cannot be claimed by other users" />+ <WarningItem text="Your account cannot be recovered after deletion" />+ <View style={styles.inputContainer}>+ <ThemedText style={styles.label}>Enter your username to continue</ThemedText>+ <ThemedTextInput+ value={confirmUsername}+ onChangeText={setConfirmUsername}+ placeholder="Enter username"+ autoCapitalize="none"+ />+ </View>+ <ThemedButton+ title="Continue"+ onPress={handleUsernameSubmit}+ style={styles.button}/>- </View>- <ThemedButton- title="Continue"- onPress={handleUsernameSubmit}- style={styles.button}- />- </>- ) : (- <>- <ThemedText style={styles.warningText}>- Please enter your password to confirm account deletion- </ThemedText>- <View style={styles.inputContainer}>- <ThemedText style={styles.label}>Password</ThemedText>- <ThemedTextInput- secureTextEntry- value={password}- onChangeText={setPassword}- placeholder="Enter password"+ </>+ ) : (+ <>+ <ThemedText style={styles.warningText}>+ Final warning: Enter your password to permanently delete your account.+ </ThemedText>+ <WarningItem text="Account deletion is irreversible and cannot be undone. Pressing the button below will delete your account immmediately and permanently." />+ <View style={styles.inputContainer}>+ <ThemedText style={styles.label}>Password</ThemedText>+ <ThemedTextInput+ secureTextEntry+ value={password}+ onChangeText={setPassword}+ placeholder="Enter password"+ />+ </View>+ <ThemedButton+ title="Delete Account"+ onPress={handleDeleteAccount}+ loading={isLoading}+ style={[styles.button, styles.buttonDanger]}/>- </View>- <ThemedButton- title="Delete Account"- onPress={handleDeleteAccount}- loading={isLoading}- style={[styles.button, styles.buttonDanger]}- />- </>- )}- </View>- </View>- </ThemedView>+ </>+ )}+ </View>+ </ScrollView>+ </ThemedView>+ </>);}\ No newline at end of filediff --git a/apps/mobile-app/components/themed/ThemedButton.tsx b/apps/mobile-app/components/themed/ThemedButton.tsxindex f69ee6bac..dd6eb6178 100644--- a/apps/mobile-app/components/themed/ThemedButton.tsx+++ b/apps/mobile-app/components/themed/ThemedButton.tsx@@ -39,7 +39,7 @@ export const ThemedButton: React.FC<ThemedButtonProps> = ({opacity: 0.7,},buttonText: {- color: colors.background,+ color: colors.primarySurfaceText,fontSize: 16,fontWeight: '600',},diff --git a/apps/mobile-app/components/ui/UsernameDisplay.tsx b/apps/mobile-app/components/ui/UsernameDisplay.tsxnew file mode 100644index 000000000..284a0a6f6--- /dev/null+++ b/apps/mobile-app/components/ui/UsernameDisplay.tsx@@ -0,0 +1,52 @@+import { StyleSheet, View, Image } from 'react-native';++import { ThemedText } from '@/components/themed/ThemedText';+import { useColors } from '@/hooks/useColorScheme';+import { useAuth } from '@/context/AuthContext';+import avatarImage from '@/assets/images/avatar.webp';++/**+ * Username display component.+ */+export function UsernameDisplay(): React.ReactNode {+ const colors = useColors();+ const { username } = useAuth();++ const styles = StyleSheet.create({+ avatar: {+ borderRadius: 20,+ height: 40,+ marginRight: 12,+ width: 40,+ },+ avatar: {+ borderRadius: 20,+ height: 40,+ marginRight: 12,+ width: 40,+ },+ userInfoContainer: {+ alignItems: 'center',+ backgroundColor: colors.background,+ borderRadius: 10,+ flexDirection: 'row',+ marginTop: 10,+ },+ usernameText: {+ color: colors.text,+ fontSize: 16,+ fontWeight: '600',+ },++ });++ return (+ <View style={styles.userInfoContainer}>+ <Image+ source={avatarImage}+ style={styles.avatar}+ />+ <ThemedText style={styles.usernameText}>Logged in as: {username}</ThemedText>+ </View>+ );+}diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsxindex fc26f3c8e..b09862a1b 100644--- a/apps/mobile-app/context/AuthContext.tsx+++ b/apps/mobile-app/context/AuthContext.tsx@@ -7,6 +7,7 @@ import * as LocalAuthentication from 'expo-local-authentication';import { useDb } from '@/context/DbContext';import NativeVaultManager from '@/specs/NativeVaultManager';+import EncryptionUtility from '@/utils/EncryptionUtility';// Create a navigation referenceexport const navigationRef = React.createRef<NavigationContainerRef<ParamListBase>>();@@ -32,6 +33,7 @@ type AuthContextType = {setAutoLockTimeout: (timeout: number) => Promise<void>;getBiometricDisplayName: () => Promise<string>;setOfflineMode: (isOffline: boolean) => void;+ verifyPassword: (password: string) => Promise<string | null>;// iOS Autofill methodsshouldShowIosAutofillReminder: boolean;markIosAutofillConfigured: () => Promise<void>;@@ -260,6 +262,38 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children}}, []);+ /**+ * 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) {+ 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,+ 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) {+ return null;+ }++ return currentPasswordHashBase64;+ }, [dbContext]);+// Handle app state changesuseEffect(() => {const subscription = AppState.addEventListener('change', async (nextAppState) => {@@ -344,6 +378,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ childrengetBiometricDisplayName,markIosAutofillConfigured,setReturnUrl,+ verifyPassword,setOfflineMode: setIsOffline,}), [isLoggedIn,@@ -367,6 +402,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ childrengetBiometricDisplayName,markIosAutofillConfigured,setReturnUrl,+ verifyPassword,]);return (diff --git a/apps/mobile-app/utils/types/webapi/DeleteAccountInitiate.ts b/apps/mobile-app/utils/types/webapi/DeleteAccountInitiate.tsnew file mode 100644index 000000000..703d3fbbe--- /dev/null+++ b/apps/mobile-app/utils/types/webapi/DeleteAccountInitiate.ts@@ -0,0 +1,16 @@+/**+ * Represents a delete account initiate response.+ */+export type DeleteAccountInitiateRequest = {+ username: string;+};++/**+ * Represents a delete account initiate response.+ */+export type DeleteAccountInitiateResponse = {+ salt: string;+ serverEphemeral: string;+ encryptionType: string;+ encryptionSettings: string;+};diff --git a/apps/mobile-app/utils/types/webapi/DeleteAccountRequest.ts b/apps/mobile-app/utils/types/webapi/DeleteAccountRequest.tsnew file mode 100644index 000000000..23cb3f26a--- /dev/null+++ b/apps/mobile-app/utils/types/webapi/DeleteAccountRequest.ts@@ -0,0 +1,8 @@+/**+ * Represents a delete account request.+ */+export type DeleteAccountRequest = {+ username: string;+ clientPublicEphemeral: string;+ clientSessionProof: string;+};