Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add password confirm to vault export in mobile app (#1687)
Leendert de Borst50bac180b60a
diff --git a/apps/mobile-app/app/(tabs)/settings/_layout.tsx b/apps/mobile-app/app/(tabs)/settings/_layout.tsxindex 83c31f4fd..410881f63 100644--- a/apps/mobile-app/app/(tabs)/settings/_layout.tsx+++ b/apps/mobile-app/app/(tabs)/settings/_layout.tsx@@ -156,6 +156,14 @@ export default function SettingsLayout(): React.ReactNode {...defaultHeaderOptions,}}/>+ <Stack.Screen+ name="password-confirm"+ options={{+ title: t('settings.passwordConfirm.title'),+ headerBackTitle: t('settings.importExport'),+ ...defaultHeaderOptions,+ }}+ /></Stack>);}\ No newline at end of filediff --git a/apps/mobile-app/app/(tabs)/settings/import-export.tsx b/apps/mobile-app/app/(tabs)/settings/import-export.tsxindex e05ca82a6..4c820b1b8 100644--- a/apps/mobile-app/app/(tabs)/settings/import-export.tsx+++ b/apps/mobile-app/app/(tabs)/settings/import-export.tsx@@ -5,11 +5,13 @@ import { useState } from 'react';import { StyleSheet, View, TouchableOpacity } from 'react-native';import type { Item } from '@/utils/dist/core/models/vault';-import { FieldKey, getFieldValue, itemToCredential } from '@/utils/dist/core/models/vault';+import { getFieldValue, itemToCredential } from '@/utils/dist/core/models/vault';import { useColors } from '@/hooks/useColorScheme';+import { usePasswordConfirm } from '@/hooks/usePasswordConfirm';import { useTranslation } from '@/hooks/useTranslation';+import LoadingOverlay from '@/components/LoadingOverlay';import { ThemedContainer } from '@/components/themed/ThemedContainer';import { ThemedScrollView } from '@/components/themed/ThemedScrollView';import { ThemedText } from '@/components/themed/ThemedText';@@ -46,6 +48,7 @@ export default function ImportExportScreen(): React.ReactNode {const { t } = useTranslation();const dbContext = useDb();const { showAlert, showConfirm } = useDialog();+ const { requestPasswordConfirm } = usePasswordConfirm();const [isExporting, setIsExporting] = useState(false);/**@@ -97,8 +100,11 @@ export default function ImportExportScreen(): React.ReactNode {// Convert item to credential format for backward compatibility with CSV exportconst credential = itemToCredential(item);- // Get nickname from item fields (not in Credential type but needed for CSV)- const nickName = getFieldValue(item, FieldKey.AliasNickname) ?? '';+ /*+ * Get nickname from item fields (not in Credential type but needed for CSV)+ * Note: AliasNickname is not a standard FieldKey, use string literal+ */+ const nickName = getFieldValue(item, 'alias.nickname') ?? '';const record: ICredentialCsvRecord = {Version: '1.5.0',@@ -182,15 +188,26 @@ export default function ImportExportScreen(): React.ReactNode {};/**- * Show export confirmation dialog.+ * Show export confirmation dialog, then password verification.*/const showExportConfirmation = (): void => {showConfirm(t('settings.exportConfirmTitle'),t('settings.exportWarning'),t('common.confirm'),- () => {- handleExport();+ async () => {+ // Request password confirmation via modal page+ const passwordHash = await requestPasswordConfirm({+ description: t('settings.passwordConfirm.exportDescription'),+ });++ if (!passwordHash) {+ // User cancelled+ return;+ }++ // Password verified, proceed with export+ await handleExport();},{ confirmStyle: 'destructive' });@@ -259,33 +276,15 @@ export default function ImportExportScreen(): React.ReactNode {};const styles = StyleSheet.create({- section: {- backgroundColor: colors.accentBackground,- borderRadius: 10,- marginTop: 16,- padding: 16,- },- sectionTitle: {- fontSize: 18,- fontWeight: '600',- marginBottom: 8,- color: colors.text,- },- sectionDescription: {- fontSize: 14,- color: colors.textMuted,- marginBottom: 16,- lineHeight: 20,- },button: {+ alignItems: 'center',backgroundColor: colors.primary,borderRadius: 8,- paddingVertical: 12,- paddingHorizontal: 16,- marginVertical: 8,flexDirection: 'row',- alignItems: 'center',justifyContent: 'center',+ marginVertical: 8,+ paddingHorizontal: 16,+ paddingVertical: 12,},buttonDisabled: {opacity: 0.5,@@ -299,58 +298,81 @@ export default function ImportExportScreen(): React.ReactNode {importNote: {backgroundColor: colors.tertiary + '20', // Use tertiary color with opacityborderRadius: 8,- padding: 12,marginTop: 8,+ padding: 12,},importNoteText: {- fontSize: 14,color: colors.text,+ fontSize: 14,+ lineHeight: 20,+ },+ section: {+ backgroundColor: colors.accentBackground,+ borderRadius: 10,+ marginTop: 16,+ padding: 16,+ },+ sectionDescription: {+ color: colors.textMuted,+ fontSize: 14,lineHeight: 20,+ marginBottom: 16,+ },+ sectionTitle: {+ color: colors.text,+ fontSize: 18,+ fontWeight: '600',+ marginBottom: 8,},});return (- <ThemedContainer>- <ThemedScrollView>- {/* Import Section */}- <View style={styles.section}>- <ThemedText style={styles.sectionTitle}>- {t('settings.importSectionTitle')}- </ThemedText>- <ThemedText style={styles.sectionDescription}>- {t('settings.importSectionDescription')}- </ThemedText>- <View style={styles.importNote}>- <ThemedText style={styles.importNoteText}>- {t('settings.importWebNote')}+ <>+ {isExporting && (+ <LoadingOverlay status={t('settings.exporting')} />+ )}+ <ThemedContainer>+ <ThemedScrollView>+ {/* Import Section */}+ <View style={styles.section}>+ <ThemedText style={styles.sectionTitle}>+ {t('settings.importSectionTitle')}+ </ThemedText>+ <ThemedText style={styles.sectionDescription}>+ {t('settings.importSectionDescription')}</ThemedText>+ <View style={styles.importNote}>+ <ThemedText style={styles.importNoteText}>+ {t('settings.importWebNote')}+ </ThemedText>+ </View></View>- </View>-- {/* Export Section */}- <View style={styles.section}>- <ThemedText style={styles.sectionTitle}>- {t('settings.exportSectionTitle')}- </ThemedText>- <ThemedText style={styles.sectionDescription}>- {t('settings.exportSectionDescription')}- </ThemedText>-- <TouchableOpacity- style={[styles.button, isExporting && styles.buttonDisabled]}- onPress={() => showExportConfirmation()}- disabled={isExporting}- >- <Ionicons name="document-text" size={20} color={colors.primarySurfaceText} />- <ThemedText style={styles.buttonText}>- {isExporting- ? (t('settings.exporting'))- : (t('settings.exportCsvButton'))- }++ {/* Export Section */}+ <View style={styles.section}>+ <ThemedText style={styles.sectionTitle}>+ {t('settings.exportSectionTitle')}+ </ThemedText>+ <ThemedText style={styles.sectionDescription}>+ {t('settings.exportSectionDescription')}</ThemedText>- </TouchableOpacity>- </View>- </ThemedScrollView>- </ThemedContainer>++ <TouchableOpacity+ style={[styles.button, isExporting && styles.buttonDisabled]}+ onPress={() => showExportConfirmation()}+ disabled={isExporting}+ >+ <Ionicons name="document-text" size={20} color={colors.primarySurfaceText} />+ <ThemedText style={styles.buttonText}>+ {isExporting+ ? (t('settings.exporting'))+ : (t('settings.exportCsvButton'))+ }+ </ThemedText>+ </TouchableOpacity>+ </View>+ </ThemedScrollView>+ </ThemedContainer>+ </>);-}\ No newline at end of file+}diff --git a/apps/mobile-app/app/(tabs)/settings/password-confirm.tsx b/apps/mobile-app/app/(tabs)/settings/password-confirm.tsxnew file mode 100644index 000000000..300629657--- /dev/null+++ b/apps/mobile-app/app/(tabs)/settings/password-confirm.tsx@@ -0,0 +1,166 @@+import { router, useLocalSearchParams } from 'expo-router';+import { useState, useEffect, useRef } from 'react';+import { StyleSheet, View, KeyboardAvoidingView, Platform } from 'react-native';++import { useColors } from '@/hooks/useColorScheme';+import { useTranslation } from '@/hooks/useTranslation';++import LoadingOverlay from '@/components/LoadingOverlay';+import { ThemedButton } from '@/components/themed/ThemedButton';+import { ThemedContainer } from '@/components/themed/ThemedContainer';+import { ThemedScrollView } from '@/components/themed/ThemedScrollView';+import { ThemedText } from '@/components/themed/ThemedText';+import { ThemedTextInput } from '@/components/themed/ThemedTextInput';+import { useAuth } from '@/context/AuthContext';+import { passwordConfirmEmitter } from '@/events/PasswordConfirmEmitter';++/**+ * Password confirmation screen.+ * This screen can be used to confirm the user's password before performing+ * sensitive operations like exporting vault data.+ *+ * Usage:+ * 1. Navigate to this screen with optional description param+ * 2. Listen to passwordConfirmEmitter for 'confirmed' or 'cancelled' events+ * 3. On 'confirmed', the password hash is passed as the event payload+ * 4. Back navigation (swipe/button) automatically emits 'cancelled'+ */+export default function PasswordConfirmScreen(): React.ReactNode {+ const colors = useColors();+ const { t } = useTranslation();+ const authContext = useAuth();+ const params = useLocalSearchParams<{+ description?: string;+ }>();++ const [password, setPassword] = useState('');+ const [error, setError] = useState('');+ const [isVerifying, setIsVerifying] = useState(false);++ // Track if we've already emitted a result (confirmed or cancelled)+ const hasEmittedResult = useRef(false);++ const description = params.description ?? t('settings.passwordConfirm.defaultDescription');++ // Emit 'cancelled' when component unmounts (back navigation) if no result was emitted+ useEffect(() => {+ return (): void => {+ if (!hasEmittedResult.current) {+ passwordConfirmEmitter.emit('cancelled');+ }+ };+ }, []);++ /**+ * Handle password verification.+ */+ const handleVerify = async (): Promise<void> => {+ if (!password) {+ setError(t('validation.required'));+ return;+ }++ setError('');+ setIsVerifying(true);++ try {+ const passwordHashBase64 = await authContext.verifyPassword(password);+ if (!passwordHashBase64) {+ setError(t('auth.errors.incorrectPassword'));+ return;+ }++ // Password verified - emit success and go back+ hasEmittedResult.current = true;+ passwordConfirmEmitter.emit('confirmed', passwordHashBase64);+ router.back();+ } catch (err) {+ console.error('Password verification error:', err);+ setError(t('common.errors.unknownError'));+ } finally {+ setIsVerifying(false);+ }+ };++ const styles = StyleSheet.create({+ button: {+ marginTop: 8,+ },+ errorText: {+ color: colors.red,+ fontSize: 13,+ marginTop: 8,+ },+ form: {+ backgroundColor: colors.accentBackground,+ borderRadius: 10,+ marginTop: 20,+ padding: 16,+ },+ headerText: {+ color: colors.textMuted,+ fontSize: 13,+ lineHeight: 20,+ },+ inputContainer: {+ marginBottom: 16,+ },+ keyboardAvoidingView: {+ flex: 1,+ },+ label: {+ color: colors.text,+ fontSize: 16,+ marginBottom: 8,+ },+ });++ return (+ <>+ {isVerifying && (+ <LoadingOverlay status={t('settings.securitySettings.deleteAccount.verifyingPassword')} />+ )}+ <KeyboardAvoidingView+ behavior={Platform.OS === 'ios' ? 'padding' : 'height'}+ style={styles.keyboardAvoidingView}+ >+ <ThemedContainer testID="password-confirm-screen">+ <ThemedScrollView>+ <ThemedText style={styles.headerText}>+ {description}+ </ThemedText>++ <View style={styles.form}>+ <View style={styles.inputContainer}>+ <ThemedText style={styles.label}>+ {t('auth.password')}+ </ThemedText>+ <ThemedTextInput+ testID="password-confirm-input"+ secureTextEntry+ value={password}+ onChangeText={setPassword}+ placeholder={t('auth.enterPasswordPlaceholder')}+ editable={!isVerifying}+ autoFocus+ />+ {error ? (+ <ThemedText style={styles.errorText}>{error}</ThemedText>+ ) : null}+ </View>++ <ThemedButton+ testID="password-confirm-button"+ title={t('common.confirm')}+ onPress={handleVerify}+ loading={isVerifying}+ disabled={!password || isVerifying}+ style={styles.button}+ />+ </View>+ </ThemedScrollView>+ </ThemedContainer>+ </KeyboardAvoidingView>+ </>+ );+}diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsxindex 37789e0c6..1496b1853 100644--- a/apps/mobile-app/context/AuthContext.tsx+++ b/apps/mobile-app/context/AuthContext.tsx@@ -389,9 +389,9 @@ export const AuthProvider: React.FC<{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) {+ // Check if the current password is correct+ const isValid = await dbContext.verifyEncryptionKey(currentPasswordHashBase64);+ if (!isValid) {return null;}diff --git a/apps/mobile-app/context/DbContext.tsx b/apps/mobile-app/context/DbContext.tsxindex fc0adcdbf..96b967ba5 100644--- a/apps/mobile-app/context/DbContext.tsx+++ b/apps/mobile-app/context/DbContext.tsx@@ -28,6 +28,7 @@ type DbContextType = {clearDatabase: () => void;getVaultMetadata: () => Promise<VaultMetadata | null>;testDatabaseConnection: (derivedKey: string) => Promise<boolean>;+ verifyEncryptionKey: (derivedKey: string) => Promise<boolean>;unlockVault: () => Promise<boolean>;checkStoredVault: () => Promise<void>;setDatabaseAvailable: () => void;@@ -244,6 +245,25 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }return false;}, [sqliteClient, unlockVault]);+ /**+ * Verify if the provided encryption key is valid.+ * @param derivedKey The encryption key to verify+ * @returns true if the key is valid, false if invalid (wrong password)+ */+ const verifyEncryptionKey = useCallback(async (derivedKey: string): Promise<boolean> => {+ try {+ await sqliteClient.storeEncryptionKeyInMemory(derivedKey);+ await unlockVault();++ const version = await sqliteClient.getDatabaseVersion();+ return !!(version && version.version && version.version.length > 0);+ } catch (error) {+ // Unlock failed - likely wrong password/key+ console.error('verifyEncryptionKey failed:', error);+ return false;+ }+ }, [sqliteClient, unlockVault]);+const contextValue = useMemo(() => ({sqliteClient,dbInitialized,@@ -260,12 +280,13 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }clearDatabase,getVaultMetadata,testDatabaseConnection,+ verifyEncryptionKey,unlockVault,storeEncryptionKey,storeEncryptionKeyDerivationParams,checkStoredVault,setDatabaseAvailable,- }), [sqliteClient, dbInitialized, dbAvailable, isDirty, isSyncing, isOffline, setIsSyncing, setIsOffline, shouldSuppressEmailErrors, refreshSyncState, hasPendingMigrations, clearDatabase, getVaultMetadata, testDatabaseConnection, unlockVault, storeEncryptionKey, storeEncryptionKeyDerivationParams, checkStoredVault, setDatabaseAvailable]);+ }), [sqliteClient, dbInitialized, dbAvailable, isDirty, isSyncing, isOffline, setIsSyncing, setIsOffline, shouldSuppressEmailErrors, refreshSyncState, hasPendingMigrations, clearDatabase, getVaultMetadata, testDatabaseConnection, verifyEncryptionKey, unlockVault, storeEncryptionKey, storeEncryptionKeyDerivationParams, checkStoredVault, setDatabaseAvailable]);return (<DbContext.Provider value={contextValue}>diff --git a/apps/mobile-app/context/DialogContext.tsx b/apps/mobile-app/context/DialogContext.tsxindex ac2f72e2d..d60568272 100644--- a/apps/mobile-app/context/DialogContext.tsx+++ b/apps/mobile-app/context/DialogContext.tsx@@ -204,9 +204,9 @@ export function DialogProvider({ children }: DialogProviderProps): React.ReactNo{text: confirmText,style: options?.confirmStyle ?? 'default',- onPress: async (): Promise<void> => {- await onConfirm();+ onPress: (): void => {setDialogConfig(null);+ onConfirm();},},],diff --git a/apps/mobile-app/events/PasswordConfirmEmitter.ts b/apps/mobile-app/events/PasswordConfirmEmitter.tsnew file mode 100644index 000000000..69673cfff--- /dev/null+++ b/apps/mobile-app/events/PasswordConfirmEmitter.ts@@ -0,0 +1,60 @@+/**+ * Event emitter for password confirmation results.+ */++type PasswordConfirmEvent = 'confirmed' | 'cancelled';+type ConfirmedListener = (passwordHash: string) => void;+type CancelledListener = () => void;++class PasswordConfirmEmitter {+ private confirmedListeners: ConfirmedListener[] = [];+ private cancelledListeners: CancelledListener[] = [];++ /**+ * Subscribe to the 'confirmed' event.+ * Called when password is successfully verified.+ * @param listener - Receives the password hash (base64)+ * @returns Unsubscribe function+ */+ onConfirmed(listener: ConfirmedListener): () => void {+ this.confirmedListeners.push(listener);+ return () => {+ this.confirmedListeners = this.confirmedListeners.filter(l => l !== listener);+ };+ }++ /**+ * Subscribe to the 'cancelled' event.+ * Called when user cancels password confirmation.+ * @returns Unsubscribe function+ */+ onCancelled(listener: CancelledListener): () => void {+ this.cancelledListeners.push(listener);+ return () => {+ this.cancelledListeners = this.cancelledListeners.filter(l => l !== listener);+ };+ }++ /**+ * Emit an event.+ * @param event - The event type+ * @param payload - Optional payload (password hash for 'confirmed')+ */+ emit(event: PasswordConfirmEvent, payload?: string): void {+ if (event === 'confirmed' && payload) {+ this.confirmedListeners.forEach(listener => listener(payload));+ } else if (event === 'cancelled') {+ this.cancelledListeners.forEach(listener => listener());+ }+ }++ /**+ * Remove all listeners. Useful for cleanup.+ */+ removeAllListeners(): void {+ this.confirmedListeners = [];+ this.cancelledListeners = [];+ }+}++export const passwordConfirmEmitter = new PasswordConfirmEmitter();diff --git a/apps/mobile-app/hooks/usePasswordConfirm.ts b/apps/mobile-app/hooks/usePasswordConfirm.tsnew file mode 100644index 000000000..cda571d8d--- /dev/null+++ b/apps/mobile-app/hooks/usePasswordConfirm.ts@@ -0,0 +1,108 @@+import { useCallback, useEffect, useRef } from 'react';+import { Platform } from 'react-native';+import { router } from 'expo-router';++import { passwordConfirmEmitter } from '@/events/PasswordConfirmEmitter';++/**+ * Delay in ms before navigating to password confirm screen.+ * This allows the previous dialog/alert to dismiss before the modal appears.+ * iOS needs a longer delay because the native Alert has a dismiss animation.+ */+const NAVIGATION_DELAY_MS = Platform.OS === 'ios' ? 350 : 100;++type PasswordConfirmOptions = {+ /**+ * Custom description for the password confirm screen.+ * If not provided, uses default translation.+ */+ description?: string;+};++type UsePasswordConfirmReturn = {+ /**+ * Request password confirmation from the user.+ * Opens the password-confirm modal and returns a promise that resolves+ * with the password hash if confirmed, or null if cancelled.+ *+ * @param options - Optional title and description for the modal+ * @returns Promise<string | null> - Password hash (base64) or null if cancelled+ */+ requestPasswordConfirm: (options?: PasswordConfirmOptions) => Promise<string | null>;+};++/**+ * Hook for requesting password confirmation from the user.+ * Opens a modal screen where the user enters their password, which is then+ * verified before returning the password hash.+ *+ * This is useful for sensitive operations like:+ * - Exporting vault data+ * - Vault reset operations+ * - Other security-sensitive actions+ *+ * Usage:+ * ```ts+ * const { requestPasswordConfirm } = usePasswordConfirm();+ *+ * const handleSensitiveAction = async () => {+ * const passwordHash = await requestPasswordConfirm({+ * description: 'Enter your password to continue.',+ * });+ *+ * if (!passwordHash) {+ * // User cancelled+ * return;+ * }+ *+ * // Proceed with sensitive action using passwordHash+ * };+ * ```+ */+export function usePasswordConfirm(): UsePasswordConfirmReturn {+ // Store resolve function to call when we receive emitter events+ const resolveRef = useRef<((value: string | null) => void) | null>(null);++ // Subscribe to emitter events on mount+ useEffect(() => {+ const unsubscribeConfirmed = passwordConfirmEmitter.onConfirmed((passwordHash) => {+ if (resolveRef.current) {+ resolveRef.current(passwordHash);+ resolveRef.current = null;+ }+ });++ const unsubscribeCancelled = passwordConfirmEmitter.onCancelled(() => {+ if (resolveRef.current) {+ resolveRef.current(null);+ resolveRef.current = null;+ }+ });++ return () => {+ unsubscribeConfirmed();+ unsubscribeCancelled();+ };+ }, []);++ const requestPasswordConfirm = useCallback((options?: PasswordConfirmOptions): Promise<string | null> => {+ return new Promise((resolve) => {+ resolveRef.current = resolve;++ // Add a small delay to allow the previous dialog to dismiss before navigating+ setTimeout(() => {+ // Navigate to password-confirm screen with optional params+ router.push({+ pathname: '/(tabs)/settings/password-confirm',+ params: {+ ...(options?.description && { description: options.description }),+ },+ });+ }, NAVIGATION_DELAY_MS);+ });+ }, []);++ return {+ requestPasswordConfirm,+ };+}diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.jsonindex 56654d471..b5358e927 100644--- a/apps/mobile-app/i18n/locales/en.json+++ b/apps/mobile-app/i18n/locales/en.json@@ -179,6 +179,11 @@"exporting": "Exporting...","exportConfirmTitle": "Export Vault","exportWarning": "Warning: Exporting your vault to an unencrypted file will expose all of your passwords and sensitive information in plain text. Only do this on trusted devices and ensure you:\n\n• Store the exported file in a secure location\n• Delete the file when you no longer need it\n• Never share the exported file with others\n\nAre you sure you want to continue with the export?",+ "passwordConfirm": {+ "title": "Confirm Password",+ "defaultDescription": "Please enter your master password to continue.",+ "exportDescription": "For security reasons, please enter your master password to confirm this export."+ },"security": "Security","appVersion": "App version {{version}} ({{url}})","autoLockOptions": {