Skip to content

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

Simplify react native pin unlock components (#1340)

Leendert de Borst66115496fbc7
diff --git a/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx b/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx
index e9ba82883..54983f8d1 100644
--- a/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx
@@ -4,8 +4,6 @@ import { useTranslation } from 'react-i18next';
import { StyleSheet, View, Alert, Platform, Linking, Switch, TouchableOpacity } from 'react-native';
import Toast from 'react-native-toast-message';
-import { isPinEnabled, removeAndDisablePin } from '@/utils/PinUnlockService';
-
import { useColors } from '@/hooks/useColorScheme';
import { ThemedContainer } from '@/components/themed/ThemedContainer';
@@ -60,7 +58,7 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
}
// Load PIN settings (locked state removed - automatically handled by native code)
- const enabled = await isPinEnabled();
+ const enabled = await NativeVaultManager.isPinEnabled();
setPinEnabled(enabled);
setInitialized(true);
@@ -137,7 +135,7 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
// If enabling biometrics and PIN is enabled, disable PIN first
if (value && pinEnabled) {
try {
- await removeAndDisablePin();
+ await NativeVaultManager.removeAndDisablePin();
setPinEnabled(false);
} catch (error) {
console.error('Failed to disable PIN:', error);
@@ -200,7 +198,7 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
*/
const handleDisablePin = useCallback(async () : Promise<void> => {
try {
- await removeAndDisablePin();
+ await NativeVaultManager.removeAndDisablePin();
setPinEnabled(false);
Toast.show({
type: 'success',
diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsx
index a6ae7d50c..1c5ad3e05 100644
--- a/apps/mobile-app/app/unlock.tsx
+++ b/apps/mobile-app/app/unlock.tsx
@@ -7,7 +7,6 @@ import { useState, useEffect, useCallback } from 'react';
import { StyleSheet, View, TextInput, Alert, KeyboardAvoidingView, Platform, ScrollView, Dimensions, TouchableWithoutFeedback, Keyboard, Text, Pressable } from 'react-native';
import EncryptionUtility from '@/utils/EncryptionUtility';
-import { isPinEnabled } from '@/utils/PinUnlockService';
import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
import { useColors } from '@/hooks/useColorScheme';
@@ -102,7 +101,7 @@ export default function UnlockScreen() : React.ReactNode {
console.error('PIN unlock failed:', err);
// Check if PIN is still enabled and update state accordingly
- const pinStillEnabled = await isPinEnabled();
+ const pinStillEnabled = await NativeVaultManager.isPinEnabled();
setPinAvailable(pinStillEnabled);
return;
}
@@ -123,7 +122,7 @@ export default function UnlockScreen() : React.ReactNode {
setBiometricDisplayName(t(displayNameKey));
// Check PIN availability
- const pinEnabled = await isPinEnabled();
+ const pinEnabled = await NativeVaultManager.isPinEnabled();
setPinAvailable(pinEnabled);
/*
diff --git a/apps/mobile-app/components/pin/PinNumpad.tsx b/apps/mobile-app/components/pin/PinNumpad.tsx
deleted file mode 100644
index e451dcc00..000000000
--- a/apps/mobile-app/components/pin/PinNumpad.tsx
+++ /dev/null
@@ -1,358 +0,0 @@
-import { MaterialIcons } from '@expo/vector-icons';
-import React from 'react';
-import { StyleSheet, View, Text, Pressable, Animated, TouchableOpacity } from 'react-native';
-
-import { useColors } from '@/hooks/useColorScheme';
-import { ThemedText } from '@/components/themed/ThemedText';
-
-/**
- * Animated button for numpad
- */
-const AnimatedNumpadButton: React.FC<{
- value: string;
- onPress: () => void;
- colors: ReturnType<typeof useColors>;
- style?: object;
-}> = ({ value, onPress, colors, style }) => {
- const scaleAnim = React.useRef(new Animated.Value(1)).current;
- const opacityAnim = React.useRef(new Animated.Value(0)).current;
-
- const handlePressIn = () => {
- Animated.parallel([
- Animated.spring(scaleAnim, {
- toValue: 0.9,
- useNativeDriver: true,
- speed: 50,
- bounciness: 0,
- }),
- Animated.timing(opacityAnim, {
- toValue: 1,
- duration: 100,
- useNativeDriver: true,
- }),
- ]).start();
- };
-
- const handlePressOut = () => {
- Animated.parallel([
- Animated.spring(scaleAnim, {
- toValue: 1,
- useNativeDriver: true,
- speed: 50,
- bounciness: 10,
- }),
- Animated.timing(opacityAnim, {
- toValue: 0,
- duration: 150,
- useNativeDriver: true,
- }),
- ]).start();
- };
-
- const buttonStyles = StyleSheet.create({
- button: {
- alignItems: 'center',
- backgroundColor: colors.accentBackground,
- borderRadius: 12,
- height: 60,
- justifyContent: 'center',
- overflow: 'hidden',
- },
- overlay: {
- ...StyleSheet.absoluteFillObject,
- backgroundColor: colors.primary,
- borderRadius: 12,
- },
- text: {
- color: colors.text,
- fontSize: 24,
- fontWeight: '600',
- },
- });
-
- return (
- <Pressable
- onPress={onPress}
- onPressIn={handlePressIn}
- onPressOut={handlePressOut}
- style={style}
- >
- <Animated.View
- style={[
- buttonStyles.button,
- {
- transform: [{ scale: scaleAnim }],
- },
- ]}
- >
- {/* Highlight overlay */}
- <Animated.View
- style={[
- buttonStyles.overlay,
- {
- opacity: opacityAnim.interpolate({
- inputRange: [0, 1],
- outputRange: [0, 0.2],
- }),
- },
- ]}
- />
-
- {/* Button content */}
- {typeof value === 'string' && value.length === 1 ? (
- <Text style={buttonStyles.text}>{value}</Text>
- ) : (
- <MaterialIcons name="backspace" size={24} color={colors.text} />
- )}
- </Animated.View>
- </Pressable>
- );
-};
-
-interface PinNumpadProps {
- pin: string;
- pinLength?: number; // Optional: if provided, shows dots; if not, shows digits
- onPinChange: (pin: string) => void;
- onSubmit?: () => void; // Optional: if provided, shows confirm button
- error?: string | null;
- title?: string;
- subtitle?: string;
- submitButtonText?: string;
- minLength?: number; // Minimum PIN length (default: 4)
- maxLength?: number; // Maximum PIN length (default: unlimited)
-}
-
-/**
- * Reusable PIN numpad component with dots or digit display
- */
-export const PinNumpad: React.FC<PinNumpadProps> = ({
- pin,
- pinLength,
- onPinChange,
- onSubmit,
- error,
- title,
- subtitle,
- submitButtonText = 'Confirm',
- minLength = 4,
- maxLength,
-}) => {
- const colors = useColors();
- const showDots = pinLength !== undefined;
- const showSubmitButton = onSubmit !== undefined;
-
- const handleNumpadClick = (digit: string) => {
- if (maxLength === undefined || pin.length < maxLength) {
- onPinChange(pin + digit);
- }
- };
-
- const handleBackspace = () => {
- onPinChange(pin.slice(0, -1));
- };
-
- const canSubmit = pin.length >= minLength;
-
- // Debug: Log when canSubmit changes
- React.useEffect(() => {
- console.debug('[PinNumpad] canSubmit:', canSubmit, 'pin.length:', pin.length, 'minLength:', minLength);
- }, [canSubmit, pin.length, minLength]);
-
- const styles = StyleSheet.create({
- confirmButton: {
- alignItems: 'center',
- backgroundColor: canSubmit ? colors.primary : colors.accentBorder,
- borderRadius: 8,
- height: 50,
- justifyContent: 'center',
- marginTop: 16,
- opacity: canSubmit ? 1 : 0.5,
- },
- confirmButtonText: {
- color: colors.primarySurfaceText,
- fontSize: 16,
- fontWeight: '600',
- },
- container: {
- width: '100%',
- },
- digitDisplay: {
- color: colors.text,
- fontSize: 42,
- fontWeight: '600',
- letterSpacing: 8,
- marginBottom: 24,
- minHeight: 48,
- textAlign: 'center',
- },
- errorText: {
- color: colors.errorText,
- fontSize: 14,
- marginBottom: 12,
- textAlign: 'center',
- },
- numpadButton: {
- alignItems: 'center',
- backgroundColor: colors.accentBackground,
- borderRadius: 12,
- height: 60,
- justifyContent: 'center',
- },
- numpadButtonText: {
- color: colors.text,
- fontSize: 24,
- fontWeight: '600',
- },
- numpadContainer: {
- marginTop: 16,
- },
- numpadRow: {
- flexDirection: 'row',
- gap: 12,
- marginBottom: 12,
- },
- pinDot: {
- borderColor: colors.accentBorder,
- borderRadius: 12,
- borderWidth: 2,
- height: 16,
- width: 16,
- },
- pinDotFilled: {
- backgroundColor: colors.primary,
- borderColor: colors.primary,
- },
- pinDotsContainer: {
- flexDirection: 'row',
- gap: 12,
- justifyContent: 'center',
- marginBottom: 24,
- },
- subtitle: {
- color: colors.text,
- fontSize: 16,
- marginBottom: 24,
- opacity: 0.7,
- textAlign: 'center',
- },
- title: {
- color: colors.text,
- fontSize: 20,
- fontWeight: '600',
- marginBottom: 8,
- textAlign: 'center',
- },
- });
-
- return (
- <View style={styles.container}>
- {/* Title */}
- {title && <ThemedText style={styles.title}>{title}</ThemedText>}
-
- {/* Subtitle */}
- {subtitle && <ThemedText style={styles.subtitle}>{subtitle}</ThemedText>}
-
- {/* PIN Display */}
- {showDots ? (
- // Show dots for fixed length
- <View style={styles.pinDotsContainer}>
- {Array.from({ length: pinLength }).map((_, i) => (
- <View
- key={i}
- style={[
- styles.pinDot,
- i < pin.length && styles.pinDotFilled
- ]}
- />
- ))}
- </View>
- ) : (
- // Show asterisks for variable length
- <Text style={styles.digitDisplay}>
- {pin ? '•'.repeat(pin.length) : '----'}
- </Text>
- )}
-
- {/* Error Message */}
- {error && <ThemedText style={styles.errorText}>{error}</ThemedText>}
-
- {/* On-Screen Numpad */}
- <View style={styles.numpadContainer}>
- {/* Row 1: 1-3 */}
- <View style={styles.numpadRow}>
- {[1, 2, 3].map((num) => (
- <AnimatedNumpadButton
- key={num}
- value={num.toString()}
- onPress={() => handleNumpadClick(num.toString())}
- colors={colors}
- style={{ flex: 1 }}
- />
- ))}
- </View>
-
- {/* Row 2: 4-6 */}
- <View style={styles.numpadRow}>
- {[4, 5, 6].map((num) => (
- <AnimatedNumpadButton
- key={num}
- value={num.toString()}
- onPress={() => handleNumpadClick(num.toString())}
- colors={colors}
- style={{ flex: 1 }}
- />
- ))}
- </View>
-
- {/* Row 3: 7-9 */}
- <View style={styles.numpadRow}>
- {[7, 8, 9].map((num) => (
- <AnimatedNumpadButton
- key={num}
- value={num.toString()}
- onPress={() => handleNumpadClick(num.toString())}
- colors={colors}
- style={{ flex: 1 }}
- />
- ))}
- </View>
-
- {/* Row 4: Empty, 0, Backspace */}
- <View style={styles.numpadRow}>
- <View style={{ flex: 1 }} />
- <AnimatedNumpadButton
- value="0"
- onPress={() => handleNumpadClick('0')}
- colors={colors}
- style={{ flex: 1 }}
- />
- <AnimatedNumpadButton
- value="backspace"
- onPress={handleBackspace}
- colors={colors}
- style={{ flex: 1 }}
- />
- </View>
- </View>
-
- {/* Confirm Button - only show if onSubmit is provided */}
- {showSubmitButton && (
- <TouchableOpacity
- style={styles.confirmButton}
- onPress={() => {
- console.debug('[PinNumpad] Submit button pressed, canSubmit:', canSubmit);
- if (onSubmit) {
- onSubmit();
- }
- }}
- disabled={!canSubmit}
- activeOpacity={0.7}
- >
- <ThemedText style={styles.confirmButtonText}>
- {submitButtonText}
- </ThemedText>
- </TouchableOpacity>
- )}
- </View>
- );
-};
diff --git a/apps/mobile-app/utils/PinUnlockService.ts b/apps/mobile-app/utils/PinUnlockService.ts
deleted file mode 100644
index cb0d2e5c8..000000000
--- a/apps/mobile-app/utils/PinUnlockService.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import NativeVaultManager from '@/specs/NativeVaultManager';
-
-/**
- * Mobile app PIN unlock service
- * Provides a TypeScript interface for native PIN unlock functionality
- */
-
-/**
- * Error thrown when PIN is locked after too many failed attempts.
- */
-export class PinLockedError extends Error {
- /**
- * Creates a new instance of PinLockedError.
- */
- public constructor() {
- super('PIN is locked due to too many failed attempts');
- this.name = 'PinLockedError';
- }
-}
-
-/**
- * Error thrown when an incorrect PIN is provided.
- */
-export class IncorrectPinError extends Error {
- public readonly attemptsRemaining: number;
-
- /**
- * Creates a new instance of IncorrectPinError.
- * @param attemptsRemaining - Number of attempts remaining
- */
- public constructor(attemptsRemaining: number) {
- super(`Incorrect PIN. ${attemptsRemaining} attempts remaining.`);
- this.name = 'IncorrectPinError';
- this.attemptsRemaining = attemptsRemaining;
- }
-}
-
-/**
- * Check if PIN unlock is enabled
- */
-export async function isPinEnabled(): Promise<boolean> {
- try {
- return await NativeVaultManager.isPinEnabled();
- } catch {
- return false;
- }
-}
-
-/**
- * Get the length of the configured PIN
- */
-export async function getPinLength(): Promise<number | null> {
- try {
- return await NativeVaultManager.getPinLength();
- } catch {
- return null;
- }
-}
-
-/**
- * Setup PIN unlock
- * The vault must be unlocked - encryption key is retrieved internally by native code
- * and never exposed to the React Native layer
- *
- * @param pin - The PIN to set (4-8 digits)
- */
-export async function setupPin(pin: string): Promise<void> {
- try {
- await NativeVaultManager.setupPin(pin);
- } catch (error: unknown) {
- console.error('[PinUnlockService] Failed to setup PIN:', error);
- throw error;
- }
-}
-
-/**
- * Unlock with PIN
- * Returns the decrypted vault encryption key
- * On success, failed attempts are automatically reset by native code
- * On max failures, PIN is automatically disabled by native code
- *
- * @param pin - The PIN to use for unlocking
- * @returns The decrypted vault encryption key (base64)
- */
-export async function unlockWithPin(pin: string): Promise<string> {
- try {
- const vaultEncryptionKey = await NativeVaultManager.unlockWithPin(pin);
- return vaultEncryptionKey;
- } catch (error: unknown) {
- // Handle specific error types
- if (error instanceof Error) {
- if (error.message.includes('locked after too many failed attempts')) {
- throw new PinLockedError();
- }
-
- // Extract attempts remaining from error message
- const attemptsMatch = error.message.match(/(\d+) attempts remaining/);
- if (attemptsMatch) {
- const attemptsRemaining = parseInt(attemptsMatch[1], 10);
- throw new IncorrectPinError(attemptsRemaining);
- }
- }
-
- console.error('[PinUnlockService] Failed to unlock with PIN:', error);
- throw error;
- }
-}
-
-/**
- * Disable PIN unlock and remove all stored (encrypted) data
- */
-export async function removeAndDisablePin(): Promise<void> {
- try {
- await NativeVaultManager.removeAndDisablePin();
- } catch (error) {
- console.error('[PinUnlockService] Failed to disable PIN:', error);
- throw error;
- }
-}