Skip to content

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

23.6 KB
Raw Blame
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import { sharingText } from '@aliasvault/client/sharing/SharingView';
import { CapabilityKeys } from '@aliasvault/models/webapi';
import { Ionicons } from '@expo/vector-icons';
import { router, useFocusEffect, useNavigation } from 'expo-router';
import { useEffect, useRef, useState, useCallback } from 'react';
import { StyleSheet, View, ScrollView, TouchableOpacity, Animated, Platform, Linking } from 'react-native';

import { useApiUrl } from '@/utils/ApiUrlUtility';
import { AppUnlockUtility } from '@/utils/AppUnlockUtility';

import { useColors } from '@/hooks/useColorScheme';
import { useDeveloperToolsUnlock } from '@/hooks/useDeveloperToolsUnlock';
import { useLogout } from '@/hooks/useLogout';
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
import { useNavigationDebounce } from '@/hooks/useNavigationDebounce';
import { useTranslation } from '@/hooks/useTranslation';

import { AccountFingerprint } from '@/components/sharing/AccountFingerprint';
import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedText } from '@/components/themed/ThemedText';
import { AndroidHeader } from '@/components/ui/AndroidHeader';
import { CollapsibleHeader } from '@/components/ui/CollapsibleHeader';
import { InlineSkeletonLoader } from '@/components/ui/InlineSkeletonLoader';
import { TitleContainer } from '@/components/ui/TitleContainer';
import { UsernameDisplay } from '@/components/ui/UsernameDisplay';
import { useApp } from '@/context/AppContext';
import { useCapabilities } from '@/context/CapabilityContext';
import { useDialog } from '@/context/DialogContext';
import { LocalPreferencesService } from '@/services/LocalPreferencesService';
import NativeVaultManager from '@/specs/NativeVaultManager';

/**
 * Settings screen.
 */
export default function SettingsScreen() : React.ReactNode {
  const colors = useColors();
  const { t } = useTranslation();
  const { showAlert, showConfirm } = useDialog();
  const { shouldShowAutofillReminder } = useApp();
  const { getAutoLockTimeout } = useApp();
  const hasCapability = useCapabilities();
  const { logoutUserInitiated } = useLogout();
  const { loadApiUrl, getDisplayUrl } = useApiUrl();
  const navigate = useNavigationDebounce();
  const navigation = useNavigation();
  const [scrollY] = useState(() => new Animated.Value(0));
  const scrollViewRef = useRef<ScrollView>(null);
  const [autoLockDisplay, setAutoLockDisplay] = useState<string>('');
  const [clipboardClearDisplay, setClipboardClearDisplay] = useState<string>('');
  const [authMethodDisplay, setAuthMethodDisplay] = useState<string>('');
  const [serverVersion, setServerVersion] = useState<string | null>(null);
  const [ownFingerprint, setOwnFingerprint] = useState<string | null>(null);
  const isSharingEnabled = hasCapability(CapabilityKeys.VaultSharing);

  // The own fingerprint is derived natively from the signing private key, which only the native layer can open.
  useFocusEffect(useCallback(() => {
    if (!isSharingEnabled) {
      return;
    }
    NativeVaultManager.getSigningKeyFingerprint().then(setOwnFingerprint).catch(() => setOwnFingerprint(null));
  }, [isSharingEnabled]));
  const [isFirstLoad, setIsFirstLoad] = useMinDurationLoading(true, 100);
  const { isEnabled: isDeveloperToolsEnabled, registerTap, refresh: refreshDeveloperTools } = useDeveloperToolsUnlock();

  useFocusEffect(
    useCallback(() => {
      /**
       * Load the auto-lock display.
       */
      const loadAutoLockDisplay = async () : Promise<void> => {
        const autoLockTimeout = await getAutoLockTimeout();
        let display = t('common.never');

        if (autoLockTimeout === 5) {
          display = t('common.duration.5seconds');
        } else if (autoLockTimeout === 15) {
          display = t('common.duration.15seconds');
        } else if (autoLockTimeout === 30) {
          display = t('common.duration.30seconds');
        } else if (autoLockTimeout === 60) {
          display = t('settings.autoLockOptions.1minute');
        } else if (autoLockTimeout === 300) {
          display = t('settings.autoLockOptions.5minutes');
        } else if (autoLockTimeout === 900) {
          display = t('settings.autoLockOptions.15minutes');
        } else if (autoLockTimeout === 1800) {
          display = t('settings.autoLockOptions.30minutes');
        } else if (autoLockTimeout === 3600) {
          display = t('settings.autoLockOptions.1hour');
        } else if (autoLockTimeout === 14400) {
          display = t('settings.autoLockOptions.4hours');
        } else if (autoLockTimeout === 28800) {
          display = t('settings.autoLockOptions.8hours');
        } else if (autoLockTimeout === 86400) {
          display = t('settings.autoLockOptions.24hours');
        }

        setAutoLockDisplay(display);
      };

      /**
       * Load the clipboard clear display.
       */
      const loadClipboardClearDisplay = async () : Promise<void> => {
        const clipboardTimeout = await LocalPreferencesService.getClipboardClearTimeout();
        let display = t('common.never');

        if (clipboardTimeout === 5) {
          display = t('common.duration.5seconds');
        } else if (clipboardTimeout === 10) {
          display = t('settings.clipboardClearOptions.10seconds');
        } else if (clipboardTimeout === 15) {
          display = t('common.duration.15seconds');
        } else if (clipboardTimeout === 30) {
          display = t('common.duration.30seconds');
        }

        setClipboardClearDisplay(display);
      };

      /**
       * Load the auth method display.
       */
      const loadAuthMethodDisplay = async () : Promise<void> => {
        const authMethodKey = await AppUnlockUtility.getAuthMethodDisplayKey();
        setAuthMethodDisplay(t(authMethodKey));
      };

      /**
       * Load the server version stored on the last sync so it can be shown next to the app version.
       */
      const loadServerVersion = async () : Promise<void> => {
        const version = await NativeVaultManager.getServerVersion();
        setServerVersion(version ?? null);
      };

      /**
       * Load all settings data.
       */
      const loadData = async () : Promise<void> => {
        await Promise.all([loadAutoLockDisplay(), loadClipboardClearDisplay(), loadAuthMethodDisplay(), loadApiUrl(), loadServerVersion()]);
        setIsFirstLoad(false);
      };

      loadData();
      refreshDeveloperTools();
    }, [getAutoLockTimeout, setIsFirstLoad, loadApiUrl, refreshDeveloperTools, t])
  );

  /*
   * Replace the header declared in the settings layout, so the logo can carry the hidden
   * developer tools unlock gesture. Android only, on iOS the TitleContainer logo carries it.
   */
  useEffect(() => {
    if (Platform.OS !== 'android') {
      return;
    }

    navigation.setOptions({
      /**
       * Define the custom Android header, matching the one in the settings layout.
       * @returns {React.ReactNode} The header component
       */
      headerTitle: (): React.ReactNode => (
        <AndroidHeader title={t('common.settings')} onLogoPress={registerTap} />
      ),
    });
  }, [navigation, registerTap, t]);

  /**
   * Handle the vault unlock press.
   */
  const handleVaultUnlockPress = () : void => {
    navigate(() => router.push('/(tabs)/settings/vault-unlock'));
  };

  /**
   * Handle the auto-lock press.
   */
  const handleAutoLockPress = () : void => {
    navigate(() => router.push('/(tabs)/settings/auto-lock'));
  };

  /**
   * Handle the iOS autofill press.
   */
  const handleIosAutofillPress = () : void => {
    navigate(() => router.push('/(tabs)/settings/ios-autofill'));
  };

  /**
   * Handle the Android autofill press.
   */
  const handleAndroidAutofillPress = () : void => {
    navigate(() => router.push('/(tabs)/settings/android-autofill'));
  };

  /**
   * Handle the identity generator settings press.
   */
  const handleIdentityGeneratorPress = () : void => {
    navigate(() => router.push('/(tabs)/settings/identity-generator'));
  };

  /**
   * Handle the password generator settings press.
   */
  const handlePasswordGeneratorPress = () : void => {
    navigate(() => router.push('/(tabs)/settings/password-generator'));
  };

  /**
   * Handle the clipboard clear settings press.
   */
  const handleClipboardClearPress = () : void => {
    navigate(() => router.push('/(tabs)/settings/clipboard-clear'));
  };

  /**
   * Handle the language settings press.
   */
  const handleLanguagePress = (): void => {
    const isIOS = Platform.OS === 'ios';

    showConfirm(
      t('settings.language'),
      t('settings.languageSystemMessage'),
      t('settings.openSettings'),
      async (): Promise<void> => {
        if (isIOS) {
          // Open iOS Settings app
          await Linking.openURL('app-settings:');
        } else {
          // Fallback to general locale settings
          try {
            await Linking.openSettings();
            return;
          } catch (error) {
            console.warn('Failed to open general locale settings:', error);
          }

          // Fallback to general settings
          try {
            await Linking.openSettings();
            return;
          } catch (error) {
            console.warn('Failed to open general settings:', error);
          }

          // Final fallback - show manual instructions
          showAlert(
            t('common.error') ?? 'Error',
            'Unable to open device settings. Please manually navigate to the app settings and change the language.'
          );
        }
      },
      { cancelText: t('common.cancel') }
    );
  };

  const styles = StyleSheet.create({
    accountSection: {
      backgroundColor: colors.accentBackground,
      borderRadius: 10,
      overflow: 'hidden',
    },
    groupSection: {
      backgroundColor: colors.accentBackground,
      borderRadius: 10,
      marginTop: 8,
      overflow: 'hidden',
    },
    ownCodeHint: {
      color: colors.textMuted,
      fontSize: 13,
      marginTop: 8,
    },
    ownCodeSection: {
      padding: 16,
    },
    groupTitle: {
      color: colors.textMuted,
      fontSize: 13,
      fontWeight: '600',
      marginLeft: 16,
      marginTop: 24,
      textTransform: 'uppercase',
    },
    scrollContent: {
      paddingBottom: 80,
      paddingTop: Platform.OS === 'ios' ? 42 : 16,
    },
    scrollView: {
      flex: 1,
    },
    section: {
      backgroundColor: colors.accentBackground,
      borderRadius: 10,
      marginTop: 20,
      overflow: 'hidden',
    },
    separator: {
      backgroundColor: colors.accentBorder,
      height: StyleSheet.hairlineWidth,
      marginLeft: 52,
    },
    settingItem: {
      alignItems: 'center',
      backgroundColor: colors.accentBackground,
      flexDirection: 'row',
      paddingHorizontal: 16,
      paddingVertical: 6,
    },
    settingItemBadge: {
      alignItems: 'center',
      backgroundColor: colors.primary,
      borderRadius: 8,
      height: 16,
      justifyContent: 'center',
      marginRight: 8,
      width: 16,
    },
    settingItemBadgeText: {
      color: colors.primarySurfaceText,
      fontSize: 10,
      fontWeight: '600',
      lineHeight: 16,
      textAlign: 'center',
    },
    settingItemContent: {
      alignItems: 'center',
      flex: 1,
      flexDirection: 'row',
      paddingVertical: 10,
    },
    settingItemIcon: {
      alignItems: 'center',
      height: 24,
      justifyContent: 'center',
      marginRight: 12,
      width: 24,
    },
    settingItemText: {
      color: colors.text,
      flex: 1,
      fontSize: 16,
    },
    settingItemTextDeveloper: {
      color: colors.red,
      flex: 1,
      fontSize: 16,
    },
    settingItemValue: {
      color: colors.textMuted,
      flexShrink: 1,
      fontSize: 16,
      marginRight: 8,
      maxWidth: '50%',
      textAlign: 'right',
    },
    skeletonLoader: {
      marginRight: 8,
    },
    versionContainer: {
      alignItems: 'center',
      marginTop: 20,
      opacity: 0.6,
      paddingBottom: 16,
    },
    versionText: {
      color: colors.textMuted,
      fontSize: 12,
      lineHeight: 20,
      textAlign: 'center',
    },
    versionLabel: {
      color: colors.textMuted,
      fontSize: 12,
      lineHeight: 20,
      fontWeight: 'bold',
    },
  });

  return (
    <ThemedContainer testID="settings-screen">
      <CollapsibleHeader
        title={t('common.settings')}
        scrollY={scrollY}
        showNavigationHeader={false}
      />
      <Animated.ScrollView
        ref={scrollViewRef}
        onScroll={Animated.event(
          [{ nativeEvent: { contentOffset: { y: scrollY } } }],
          { useNativeDriver: true }
        )}
        scrollEventThrottle={16}
        contentContainerStyle={styles.scrollContent}
        scrollIndicatorInsets={{ bottom: 40 }}
        style={styles.scrollView}
      >
        <TitleContainer title={t('common.settings')} onLogoPress={registerTap} />
        <View style={styles.accountSection}>
          <UsernameDisplay />
          <View style={styles.separator} />
          <TouchableOpacity
            testID="qr-scanner-link"
            style={styles.settingItem}
            onPress={() => navigate(() => router.push('/(tabs)/settings/qr-scanner'))}
          >
            <View style={styles.settingItemIcon}>
              <Ionicons name="qr-code-outline" size={20} color={colors.text} />
            </View>
            <View style={styles.settingItemContent}>
              <ThemedText style={styles.settingItemText}>{t('settings.qrScanner.scanningMessage')}</ThemedText>
              <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
            </View>
          </TouchableOpacity>
        </View>

        {/* The account fingerprint people need to invite this account to a shared folder. */}
        {isSharingEnabled && ownFingerprint && (
          <View style={[styles.groupSection, styles.ownCodeSection]}>
            <AccountFingerprint code={ownFingerprint} />
            <ThemedText style={styles.ownCodeHint}>{sharingText.yourFingerprintSettingsHint}</ThemedText>
          </View>
        )}

        <ThemedText style={styles.groupTitle}>{t('settings.groups.autofill')}</ThemedText>
        <View style={styles.groupSection}>
          {Platform.OS === 'ios' && (
            <TouchableOpacity
              style={styles.settingItem}
              onPress={handleIosAutofillPress}
            >
              <View style={styles.settingItemIcon}>
                <Ionicons name="key-outline" size={20} color={colors.text} />
              </View>
              <View style={styles.settingItemContent}>
                <ThemedText style={styles.settingItemText}>{t('settings.autofill')}</ThemedText>
                {shouldShowAutofillReminder && (
                  <View style={styles.settingItemBadge}>
                    <ThemedText style={styles.settingItemBadgeText}>1</ThemedText>
                  </View>
                )}
                <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
              </View>
            </TouchableOpacity>
          )}
          {Platform.OS === 'android' && (
            <TouchableOpacity
              style={styles.settingItem}
              onPress={handleAndroidAutofillPress}
            >
              <View style={styles.settingItemIcon}>
                <Ionicons name="key-outline" size={20} color={colors.text} />
              </View>
              <View style={styles.settingItemContent}>
                <ThemedText style={styles.settingItemText}>{t('settings.autofill')}</ThemedText>
                {shouldShowAutofillReminder && (
                  <View style={styles.settingItemBadge}>
                    <ThemedText style={styles.settingItemBadgeText}>1</ThemedText>
                  </View>
                )}
                <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
              </View>
            </TouchableOpacity>
          )}
        </View>

        <ThemedText style={styles.groupTitle}>{t('settings.security')}</ThemedText>
        <View style={styles.groupSection}>
          <TouchableOpacity
            style={styles.settingItem}
            onPress={handleVaultUnlockPress}
          >
            <View style={styles.settingItemIcon}>
              <Ionicons name="lock-closed" size={20} color={colors.text} />
            </View>
            <View style={styles.settingItemContent}>
              <ThemedText style={styles.settingItemText}>{t('settings.vaultUnlock')}</ThemedText>
              {isFirstLoad ? (
                <InlineSkeletonLoader width={100} style={styles.skeletonLoader} />
              ) : (
                <ThemedText style={styles.settingItemValue}>{authMethodDisplay}</ThemedText>
              )}
              <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          <TouchableOpacity
            style={styles.settingItem}
            onPress={handleAutoLockPress}
          >
            <View style={styles.settingItemIcon}>
              <Ionicons name="timer-outline" size={20} color={colors.text} />
            </View>
            <View style={styles.settingItemContent}>
              <ThemedText style={styles.settingItemText}>{t('settings.autoLock')}</ThemedText>
              {isFirstLoad ? (
                <InlineSkeletonLoader width={80} style={styles.skeletonLoader} />
              ) : (
                <ThemedText style={styles.settingItemValue}>{autoLockDisplay}</ThemedText>
              )}
              <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          <TouchableOpacity
            style={styles.settingItem}
            onPress={handleClipboardClearPress}
          >
            <View style={styles.settingItemIcon}>
              <Ionicons name="clipboard-outline" size={20} color={colors.text} />
            </View>
            <View style={styles.settingItemContent}>
              <ThemedText style={styles.settingItemText}>{t('settings.clipboardClear')}</ThemedText>
              {isFirstLoad ? (
                <InlineSkeletonLoader width={80} style={styles.skeletonLoader} />
              ) : (
                <ThemedText style={styles.settingItemValue}>{clipboardClearDisplay}</ThemedText>
              )}
              <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          <TouchableOpacity
            testID="security-settings-link"
            style={styles.settingItem}
            onPress={() => router.push('/(tabs)/settings/security')}
          >
            <View style={styles.settingItemIcon}>
              <Ionicons name="shield-checkmark" size={20} color={colors.text} />
            </View>
            <View style={styles.settingItemContent}>
              <ThemedText style={styles.settingItemText}>{t('settings.accountSecurity')}</ThemedText>
              <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
            </View>
          </TouchableOpacity>
        </View>

        <ThemedText style={styles.groupTitle}>{t('settings.groups.generators')}</ThemedText>
        <View style={styles.groupSection}>
          <TouchableOpacity
            style={styles.settingItem}
            onPress={handlePasswordGeneratorPress}
          >
            <View style={styles.settingItemIcon}>
              <Ionicons name="key-sharp" size={20} color={colors.text} />
            </View>
            <View style={styles.settingItemContent}>
              <ThemedText style={styles.settingItemText}>{t('settings.passwordGenerator')}</ThemedText>
              <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          <TouchableOpacity
            style={styles.settingItem}
            onPress={handleIdentityGeneratorPress}
          >
            <View style={styles.settingItemIcon}>
              <Ionicons name="person-outline" size={20} color={colors.text} />
            </View>
            <View style={styles.settingItemContent}>
              <ThemedText style={styles.settingItemText}>{t('settings.identityGenerator')}</ThemedText>
              <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
            </View>
          </TouchableOpacity>
        </View>

        <ThemedText style={styles.groupTitle}>{t('navigation.vault')}</ThemedText>
        <View style={styles.groupSection}>
          <TouchableOpacity
            style={styles.settingItem}
            onPress={() => router.push('/(tabs)/settings/import-export')}
          >
            <View style={styles.settingItemIcon}>
              <Ionicons name="swap-horizontal" size={20} color={colors.text} />
            </View>
            <View style={styles.settingItemContent}>
              <ThemedText style={styles.settingItemText}>{t('settings.importExport')}</ThemedText>
              <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
            </View>
          </TouchableOpacity>
        </View>

        <ThemedText style={styles.groupTitle}>{t('settings.groups.general')}</ThemedText>
        <View style={styles.groupSection}>
          <TouchableOpacity
            style={styles.settingItem}
            onPress={handleLanguagePress}
          >
            <View style={styles.settingItemIcon}>
              <Ionicons name="language" size={20} color={colors.text} />
            </View>
            <View style={styles.settingItemContent}>
              <ThemedText style={styles.settingItemText}>{t('settings.language')}</ThemedText>
              <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
            </View>
          </TouchableOpacity>
          <View style={styles.separator} />
          <TouchableOpacity
            style={styles.settingItem}
            onPress={logoutUserInitiated}
          >
            <View style={styles.settingItemIcon}>
              <Ionicons name="log-out" size={20} color={colors.primary} />
            </View>
            <View style={styles.settingItemContent}>
              <ThemedText style={[styles.settingItemText, { color: colors.primary }]}>{t('common.logout')}</ThemedText>
            </View>
          </TouchableOpacity>
        </View>

        {isDeveloperToolsEnabled && (
          <View style={styles.section}>
            {/* Note: developer only screen, not required to be translated */}
            <TouchableOpacity
              style={styles.settingItem}
              onPress={() => navigate(() => router.push('/(tabs)/settings/developer-tools'))}
            >
              <View style={styles.settingItemIcon}>
                <Ionicons name="code-slash" size={20} color={colors.red} />
              </View>
              <View style={styles.settingItemContent}>
                <ThemedText style={styles.settingItemTextDeveloper}>Developer tools</ThemedText>
                <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
              </View>
            </TouchableOpacity>
          </View>
        )}

        <TouchableOpacity style={styles.versionContainer} onPress={registerTap} activeOpacity={1}>
          <ThemedText style={styles.versionText}>
            <ThemedText style={styles.versionLabel}>{t('settings.appVersion')}:</ThemedText> {AppInfo.VERSION}
          </ThemedText>
          {serverVersion && (
            <ThemedText style={styles.versionText}>
              <ThemedText style={styles.versionLabel}>{t('settings.serverVersion')}:</ThemedText> {serverVersion} ({getDisplayUrl()})
            </ThemedText>
          )}
        </TouchableOpacity>
      </Animated.ScrollView>

    </ThemedContainer>
  );
}