Skip to content

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

Mobile app pin unlock scaffolding (#1340)

Leendert de Borst0ddd24c40e01
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
index 0e947404b..334becf52 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
@@ -1242,4 +1242,144 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
}
}
+
+ // MARK: - PIN Unlock Methods
+
+ /**
+ * Check if PIN unlock is enabled.
+ * @param promise The promise to resolve.
+ */
+ @ReactMethod
+ override fun isPinEnabled(promise: Promise) {
+ try {
+ val enabled = vaultStore.isPinEnabled()
+ promise.resolve(enabled)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error checking if PIN is enabled", e)
+ promise.reject("ERR_IS_PIN_ENABLED", "Failed to check if PIN is enabled: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Get the configured PIN length.
+ * @param promise The promise to resolve.
+ */
+ @ReactMethod
+ override fun getPinLength(promise: Promise) {
+ try {
+ val length = vaultStore.getPinLength()
+ promise.resolve(length)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error getting PIN length", e)
+ promise.reject("ERR_GET_PIN_LENGTH", "Failed to get PIN length: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Get failed PIN attempts count.
+ * @param promise The promise to resolve.
+ */
+ @ReactMethod
+ override fun getPinFailedAttempts(promise: Promise) {
+ try {
+ val attempts = vaultStore.getPinFailedAttempts()
+ promise.resolve(attempts)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error getting PIN failed attempts", e)
+ promise.reject("ERR_GET_PIN_FAILED_ATTEMPTS", "Failed to get PIN failed attempts: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Setup PIN unlock.
+ * @param pin The PIN to set.
+ * @param vaultEncryptionKeyBase64 The vault encryption key.
+ * @param promise The promise to resolve.
+ */
+ @ReactMethod
+ override fun setupPin(pin: String, vaultEncryptionKeyBase64: String, promise: Promise) {
+ try {
+ vaultStore.setupPin(pin, vaultEncryptionKeyBase64)
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error setting up PIN", e)
+ promise.reject("ERR_SETUP_PIN", "Failed to setup PIN: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Unlock with PIN.
+ * @param pin The PIN to unlock with.
+ * @param promise The promise to resolve.
+ */
+ @ReactMethod
+ override fun unlockWithPin(pin: String, promise: Promise) {
+ try {
+ val vaultEncryptionKey = vaultStore.unlockWithPin(pin)
+ promise.resolve(vaultEncryptionKey)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error unlocking with PIN", e)
+ // Extract attempts remaining from exception message if available
+ val message = e.message ?: "Unknown error"
+ val attemptsPattern = """(\d+) attempts remaining""".toRegex()
+ val matchResult = attemptsPattern.find(message)
+ if (matchResult != null) {
+ val attemptsRemaining = matchResult.groupValues[1].toInt()
+ val errorData = Arguments.createMap()
+ errorData.putInt("attemptsRemaining", attemptsRemaining)
+ promise.reject("INCORRECT_PIN", message, e)
+ } else {
+ promise.reject("ERR_UNLOCK_WITH_PIN", "Failed to unlock with PIN: ${e.message}", e)
+ }
+ }
+ }
+
+ /**
+ * Reset failed PIN attempts counter.
+ * @param promise The promise to resolve.
+ */
+ @ReactMethod
+ override fun resetPinFailedAttempts(promise: Promise) {
+ try {
+ vaultStore.resetPinFailedAttempts()
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error resetting PIN failed attempts", e)
+ promise.reject("ERR_RESET_PIN_FAILED_ATTEMPTS", "Failed to reset PIN failed attempts: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Disable PIN unlock and remove all stored data.
+ * @param promise The promise to resolve.
+ */
+ @ReactMethod
+ override fun removeAndDisablePin(promise: Promise) {
+ try {
+ vaultStore.removeAndDisablePin()
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error removing and disabling PIN", e)
+ promise.reject("ERR_REMOVE_AND_DISABLE_PIN", "Failed to remove and disable PIN: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Show native PIN unlock UI.
+ * This presents a native PIN unlock screen modally and handles the unlock flow.
+ * On success, the vault is unlocked and the encryption key is stored in memory.
+ * On cancel or error, the promise is rejected.
+ *
+ * @param promise The promise to resolve on success or reject on error/cancel.
+ */
+ @ReactMethod
+ override fun showPinUnlockUI(promise: Promise) {
+ // TODO: Implement native Android PIN unlock UI
+ // For now, reject with NOT_IMPLEMENTED to allow React Native to fall back
+ promise.reject(
+ "NOT_IMPLEMENTED",
+ "Native PIN unlock UI not yet implemented on Android. Please use the React Native PIN UI.",
+ null
+ )
+ }
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt
new file mode 100644
index 000000000..b0732bbf9
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt
@@ -0,0 +1,276 @@
+package net.aliasvault.app.vaultstore
+
+import android.util.Base64
+import android.util.Log
+import net.aliasvault.app.vaultstore.storageprovider.StorageProvider
+import org.signal.argon2.Argon2
+import org.signal.argon2.MemoryCost
+import org.signal.argon2.Type
+import org.signal.argon2.Version
+import java.security.SecureRandom
+import javax.crypto.Cipher
+import javax.crypto.spec.GCMParameterSpec
+import javax.crypto.spec.SecretKeySpec
+
+/**
+ * Handles PIN unlock functionality for the vault store.
+ * This component manages PIN-based unlocking by encrypting the vault encryption key
+ * with a key derived from the user's PIN using Argon2id.
+ *
+ * Security features:
+ * - 4 failed attempts maximum before requiring full password
+ * - PIN must be 4-8 digits
+ * - Encryption key derived using Argon2id (memory-hard, GPU-resistant)
+ * - Failed attempts counter stored separately
+ * - Encrypted data automatically deleted after max failed attempts
+ *
+ * @param storageProvider The storage provider for persisting PIN data
+ */
+class VaultPin(
+ private val storageProvider: StorageProvider,
+) {
+ companion object {
+ /**
+ * The tag for logging.
+ */
+ private const val TAG = "VaultPin"
+
+ /**
+ * The maximum number of failed PIN attempts before locking.
+ */
+ private const val MAX_PIN_ATTEMPTS = 4
+
+ /**
+ * Shared preferences keys for PIN data.
+ */
+ private const val PIN_ENABLED_KEY = "aliasvault_pin_enabled"
+ private const val PIN_ENCRYPTED_KEY_KEY = "aliasvault_pin_encrypted_key"
+ private const val PIN_SALT_KEY = "aliasvault_pin_salt"
+ private const val PIN_LENGTH_KEY = "aliasvault_pin_length"
+ private const val PIN_FAILED_ATTEMPTS_KEY = "aliasvault_pin_failed_attempts"
+
+ /**
+ * Argon2id parameters for PIN key derivation.
+ * These parameters are chosen for security against brute-force attacks:
+ * - Memory: 65536 KB (64 MB) - makes GPU attacks much harder
+ * - Iterations: 3 - standard for Argon2id
+ * - Parallelism: 1 - suitable for mobile environment
+ * - Output: 32 bytes for AES-256-GCM
+ */
+ private const val ARGON2_ITERATIONS = 3
+ private const val ARGON2_MEMORY_KB = 65536 // 64 MB
+ private const val ARGON2_PARALLELISM = 1
+ private const val ARGON2_OUTPUT_LENGTH = 32
+
+ /**
+ * Keystore alias for PIN encryption.
+ */
+ private const val KEYSTORE_ALIAS = "alias_vault_pin_key"
+
+ /**
+ * AES-GCM parameters.
+ */
+ private const val GCM_IV_LENGTH = 12
+ private const val GCM_TAG_LENGTH = 128
+ }
+
+ // MARK: - PIN Status Methods
+
+ /**
+ * Check if PIN unlock is enabled.
+ * @return True if PIN unlock is enabled, false otherwise
+ */
+ fun isPinEnabled(): Boolean {
+ return storageProvider.getBoolean(PIN_ENABLED_KEY, false)
+ }
+
+ /**
+ * Get the configured PIN length.
+ * @return The PIN length, or null if PIN is not enabled
+ */
+ fun getPinLength(): Int? {
+ if (!isPinEnabled()) return null
+ val length = storageProvider.getInt(PIN_LENGTH_KEY, 0)
+ return if (length > 0) length else null
+ }
+
+ /**
+ * Get failed attempts count.
+ * @return The number of failed PIN attempts
+ */
+ fun getPinFailedAttempts(): Int {
+ return storageProvider.getInt(PIN_FAILED_ATTEMPTS_KEY, 0)
+ }
+
+ // MARK: - PIN Setup Methods
+
+ /**
+ * Setup PIN unlock.
+ * Encrypts the vault encryption key with the PIN and stores it securely.
+ *
+ * @param pin The PIN to set (4-8 digits)
+ * @param vaultEncryptionKeyBase64 The base64-encoded vault encryption key to protect
+ * @throws IllegalArgumentException if PIN format is invalid
+ * @throws Exception if encryption or storage fails
+ */
+ @Throws(Exception::class)
+ fun setupPin(pin: String, vaultEncryptionKeyBase64: String) {
+ // Decode the vault encryption key
+ val vaultEncryptionKey = Base64.decode(vaultEncryptionKeyBase64, Base64.NO_WRAP)
+
+ // Generate random salt
+ val salt = ByteArray(16)
+ SecureRandom().nextBytes(salt)
+ val saltBase64 = Base64.encodeToString(salt, Base64.NO_WRAP)
+
+ // Derive key from PIN using Argon2id
+ val pinKey = derivePinKey(pin, salt)
+
+ // Encrypt the vault encryption key using AES-GCM
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ val secretKey = SecretKeySpec(pinKey, "AES")
+
+ // Generate random IV for AES-GCM
+ val iv = ByteArray(GCM_IV_LENGTH)
+ SecureRandom().nextBytes(iv)
+
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))
+ val encryptedKey = cipher.doFinal(vaultEncryptionKey)
+
+ // Combine IV + encrypted data
+ val combined = ByteArray(iv.size + encryptedKey.size)
+ System.arraycopy(iv, 0, combined, 0, iv.size)
+ System.arraycopy(encryptedKey, 0, combined, iv.size, encryptedKey.size)
+ val combinedBase64 = Base64.encodeToString(combined, Base64.NO_WRAP)
+
+ // Store encrypted key, salt, and metadata in SharedPreferences
+ storageProvider.putBoolean(PIN_ENABLED_KEY, true)
+ storageProvider.putString(PIN_ENCRYPTED_KEY_KEY, combinedBase64)
+ storageProvider.putString(PIN_SALT_KEY, saltBase64)
+ storageProvider.putInt(PIN_LENGTH_KEY, pin.length)
+ storageProvider.putInt(PIN_FAILED_ATTEMPTS_KEY, 0)
+
+ Log.d(TAG, "PIN unlock enabled successfully")
+ }
+
+ // MARK: - PIN Unlock Methods
+
+ /**
+ * Unlock with PIN.
+ * Returns the decrypted vault encryption key.
+ *
+ * @param pin The PIN to use for unlocking
+ * @return The decrypted vault encryption key (base64)
+ * @throws IllegalArgumentException if PIN format is invalid
+ * @throws IllegalStateException if PIN is not configured or is locked
+ * @throws Exception if decryption fails or PIN is incorrect
+ */
+ @Throws(Exception::class)
+ fun unlockWithPin(pin: String): String {
+ // Check if PIN is enabled
+ // Note: If PIN was previously locked (max attempts), it's automatically disabled and cleared,
+ // so isPinEnabled() returning false means either PIN was never set up or it was locked and cleared
+ if (!isPinEnabled()) {
+ throw IllegalStateException("PIN unlock is not configured")
+ }
+
+ try {
+ // Retrieve encrypted key and salt
+ val encryptedKeyBase64 = storageProvider.getString(PIN_ENCRYPTED_KEY_KEY, null)
+ ?: throw IllegalStateException("No encrypted key found")
+ val saltBase64 = storageProvider.getString(PIN_SALT_KEY, null)
+ ?: throw IllegalStateException("No salt found")
+
+ // Decode encrypted package
+ val combined = Base64.decode(encryptedKeyBase64, Base64.NO_WRAP)
+ val iv = combined.copyOfRange(0, GCM_IV_LENGTH)
+ val encryptedData = combined.copyOfRange(GCM_IV_LENGTH, combined.size)
+
+ // Derive key from PIN
+ val salt = Base64.decode(saltBase64, Base64.NO_WRAP)
+ val pinKey = derivePinKey(pin, salt)
+
+ // Decrypt the vault encryption key
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ val secretKey = SecretKeySpec(pinKey, "AES")
+ cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))
+ val decryptedKey = cipher.doFinal(encryptedData)
+
+ // Reset failed attempts on success
+ storageProvider.putInt(PIN_FAILED_ATTEMPTS_KEY, 0)
+
+ // Return the decrypted vault encryption key as base64
+ return Base64.encodeToString(decryptedKey, Base64.NO_WRAP)
+ } catch (e: Exception) {
+ // Increment failed attempts
+ val currentAttempts = getPinFailedAttempts()
+ val newAttempts = currentAttempts + 1
+ storageProvider.putInt(PIN_FAILED_ATTEMPTS_KEY, newAttempts)
+
+ // If max attempts reached, disable PIN and clear all stored data
+ if (newAttempts >= MAX_PIN_ATTEMPTS) {
+ removeAndDisablePin()
+ throw IllegalStateException("PIN locked after too many failed attempts")
+ }
+
+ // Return incorrect PIN error with attempts remaining
+ val attemptsRemaining = MAX_PIN_ATTEMPTS - newAttempts
+ throw Exception("Incorrect PIN. $attemptsRemaining attempts remaining", e)
+ }
+ }
+
+ /**
+ * Reset failed attempts counter.
+ * Called after successful password unlock.
+ */
+ fun resetPinFailedAttempts() {
+ storageProvider.putInt(PIN_FAILED_ATTEMPTS_KEY, 0)
+ }
+
+ /**
+ * Disable PIN unlock and remove all stored data.
+ */
+ fun removeAndDisablePin() {
+ // Clear all PIN data from SharedPreferences
+ storageProvider.remove(PIN_ENABLED_KEY)
+ storageProvider.remove(PIN_ENCRYPTED_KEY_KEY)
+ storageProvider.remove(PIN_SALT_KEY)
+ storageProvider.remove(PIN_LENGTH_KEY)
+ storageProvider.remove(PIN_FAILED_ATTEMPTS_KEY)
+
+ Log.d(TAG, "PIN unlock disabled and all data removed")
+ }
+
+ // MARK: - Private PIN Methods
+
+ /**
+ * Derive encryption key from PIN using Argon2id.
+ *
+ * Uses Argon2id with high memory cost (64 MB) to make brute-force attacks
+ * significantly more expensive. This is especially important for PINs which
+ * have lower entropy than passwords.
+ *
+ * @param pin The PIN string
+ * @param salt The salt bytes
+ * @return The derived key bytes (32 bytes)
+ * @throws Exception if key derivation fails
+ */
+ @Throws(Exception::class)
+ private fun derivePinKey(pin: String, salt: ByteArray): ByteArray {
+ try {
+ val argon2 = Argon2.Builder(Version.V13)
+ .type(Type.Argon2id)
+ .memoryCost(MemoryCost.KiB(ARGON2_MEMORY_KB))
+ .parallelism(ARGON2_PARALLELISM)
+ .iterations(ARGON2_ITERATIONS)
+ .hashLength(ARGON2_OUTPUT_LENGTH)
+ .build()
+
+ val result = argon2.hash(pin.toByteArray(), salt)
+ return result.hash
+ } catch (e: Exception) {
+ Log.e(TAG, "Argon2 PIN hashing failed", e)
+ throw Exception("Argon2 PIN hashing failed", e)
+ }
+ }
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
index 8a6e19f1b..6c51cb820 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
@@ -71,6 +71,7 @@ class VaultStore(
private val mutate = VaultMutate(databaseComponent, query, metadata)
private val cache = VaultCache(crypto, databaseComponent, keystoreProvider, storageProvider)
private val passkey = VaultPasskey(databaseComponent)
+ private val pin = VaultPin(storageProvider)
// endregion
@@ -556,4 +557,62 @@ class VaultStore(
}
// endregion
+
+ // region PIN Methods
+
+ /**
+ * Check if PIN unlock is enabled.
+ */
+ fun isPinEnabled(): Boolean {
+ return pin.isPinEnabled()
+ }
+
+ /**
+ * Get the configured PIN length.
+ */
+ fun getPinLength(): Int? {
+ return pin.getPinLength()
+ }
+
+ /**
+ * Get failed PIN attempts count.
+ */
+ fun getPinFailedAttempts(): Int {
+ return pin.getPinFailedAttempts()
+ }
+
+ // Note: isPinLocked() removed - PIN is automatically disabled after max attempts
+ // Use isPinEnabled() instead - it returns false when PIN is not set up OR was locked and cleared
+
+ /**
+ * Setup PIN unlock.
+ */
+ @Throws(Exception::class)
+ fun setupPin(pinValue: String, vaultEncryptionKeyBase64: String) {
+ pin.setupPin(pinValue, vaultEncryptionKeyBase64)
+ }
+
+ /**
+ * Unlock with PIN.
+ */
+ @Throws(Exception::class)
+ fun unlockWithPin(pinValue: String): String {
+ return pin.unlockWithPin(pinValue)
+ }
+
+ /**
+ * Reset failed PIN attempts counter.
+ */
+ fun resetPinFailedAttempts() {
+ pin.resetPinFailedAttempts()
+ }
+
+ /**
+ * Disable PIN unlock and remove all stored data.
+ */
+ fun removeAndDisablePin() {
+ pin.removeAndDisablePin()
+ }
+
+ // endregion
}
diff --git a/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx b/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx
index 3bc37bdce..a7c5f6d43 100644
--- a/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx
@@ -1,15 +1,22 @@
+import { MaterialIcons } from '@expo/vector-icons';
import * as LocalAuthentication from 'expo-local-authentication';
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { StyleSheet, View, Alert, Platform, Linking, Switch, TouchableOpacity } from 'react-native';
+import { StyleSheet, View, Alert, Platform, Linking, Switch, TouchableOpacity, Modal } from 'react-native';
import Toast from 'react-native-toast-message';
+import { isPinEnabled, setupPin, removeAndDisablePin } from '@/utils/PinUnlockService';
+
import { useColors } from '@/hooks/useColorScheme';
+import { PinNumpad } from '@/components/pin/PinNumpad';
import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedScrollView } from '@/components/themed/ThemedScrollView';
import { ThemedText } from '@/components/themed/ThemedText';
+import { ThemedView } from '@/components/themed/ThemedView';
+import { RobustPressable } from '@/components/ui/RobustPressable';
import { AuthMethod, useAuth } from '@/context/AuthContext';
+import { useDb } from '@/context/DbContext';
/**
* Vault unlock settings screen.
@@ -17,6 +24,7 @@ import { AuthMethod, useAuth } from '@/context/AuthContext';
export default function VaultUnlockSettingsScreen() : React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
+ const dbContext = useDb();
const [initialized, setInitialized] = useState(false);
const { setAuthMethods, getEnabledAuthMethods, getBiometricDisplayNameKey } = useAuth();
const [hasBiometrics, setHasBiometrics] = useState(false);
@@ -24,6 +32,15 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
const [biometricDisplayName, setBiometricDisplayName] = useState('');
const [_, setEnabledAuthMethods] = useState<AuthMethod[]>([]);
+ // PIN state
+ const [pinEnabled, setPinEnabled] = useState(false);
+ const [pinLocked, setPinLocked] = useState(false);
+ const [showPinSetup, setShowPinSetup] = useState(false);
+ const [pinSetupStep, setPinSetupStep] = useState(1);
+ const [newPin, setNewPin] = useState('');
+ const [confirmPin, setConfirmPin] = useState('');
+ const [pinError, setPinError] = useState<string | null>(null);
+
useEffect(() => {
/**
* Initialize the auth methods.
@@ -53,6 +70,11 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
setIsBiometricsEnabled(true);
}
+ // Load PIN settings (locked state removed - automatically handled by native code)
+ const enabled = await isPinEnabled();
+ setPinEnabled(enabled);
+ setPinLocked(false); // No longer tracking locked state
+
setInitialized(true);
} catch (error) {
console.error('Failed to initialize auth:', error);
@@ -124,6 +146,16 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
return;
}
+ // If enabling biometrics and PIN is enabled, disable PIN first
+ if (value && pinEnabled) {
+ try {
+ await removeAndDisablePin();
+ setPinEnabled(false);
+ } catch (error) {
+ console.error('Failed to disable PIN:', error);
+ }
+ }
+
setIsBiometricsEnabled(value);
setAuthMethods(value ? ['faceid', 'password'] : ['password']);
@@ -136,9 +168,136 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
visibilityTime: 1200,
});
}
- }, [hasBiometrics, setAuthMethods, biometricDisplayName, t]);
+ }, [hasBiometrics, pinEnabled, setAuthMethods, biometricDisplayName, t]);
+
+ /**
+ * Handle enable PIN.
+ */
+ const handleEnablePin = useCallback(() : void => {
+ // Don't disable biometrics yet - only after successful PIN setup
+ setPinSetupStep(1);
+ setNewPin('');
+ setConfirmPin('');
+ setShowPinSetup(true);
+ }, []);
+
+ /**
+ * Handle disable PIN.
+ */
+ const handleDisablePin = useCallback(async () : Promise<void> => {
+ try {
+ await removeAndDisablePin();
+ setPinEnabled(false);
+ setPinLocked(false);
+ Toast.show({
+ type: 'success',
+ text1: t('settings.vaultUnlockSettings.pinDisabled'),
+ position: 'bottom',
+ visibilityTime: 1200,
+ });
+ } catch (error) {
+ console.error('Failed to disable PIN:', error);
+ Alert.alert(
+ t('common.error'),
+ t('common.errors.unknownErrorTryAgain'),
+ [{ text: t('common.ok'), style: 'default' }]
+ );
+ }
+ }, [t]);
+
+ /**
+ * Handle PIN change for step 1 (enter new PIN).
+ */
+ const handleNewPinChange = useCallback((pin: string) : void => {
+ setNewPin(pin);
+ setPinError(null);
+ }, []);
+
+ /**
+ * Handle step 1 submit (advance to confirmation).
+ */
+ const handleNewPinSubmit = useCallback(() : void => {
+ setPinSetupStep(2);
+ }, []);
+
+ /**
+ * Handle PIN change for step 2 (confirm PIN).
+ */
+ const handleConfirmPinChange = useCallback((pin: string) : void => {
+ setConfirmPin(pin);
+ setPinError(null);
+ }, []);
+
+ /**
+ * Handle step 2 submit (confirm and save PIN).
+ */
+ const handleConfirmPinSubmit = useCallback(() : void => {
+ if (confirmPin !== newPin) {
+ setPinError(t('settings.vaultUnlockSettings.pinMismatch'));
+ // Restart from step 1 on mismatch
+ setTimeout(() => {
+ setPinSetupStep(1);
+ setNewPin('');
+ setConfirmPin('');
+ setPinError(null);
+ }, 1000); // Show error for 1s before restarting
+ return;
+ }
+
+ // PINs match, submit
+ handlePinSetupSubmit(confirmPin);
+ }, [confirmPin, newPin, t]);
+
+ /**
+ * Handle PIN setup submit.
+ */
+ const handlePinSetupSubmit = useCallback(async (pin: string) : Promise<void> => {
+ try {
+ // Setup PIN - encryption key is retrieved internally by native code
+ await setupPin(pin);
+
+ // PIN setup successful - now disable biometrics if it was enabled
+ if (isBiometricsEnabled) {
+ setIsBiometricsEnabled(false);
+ await setAuthMethods(['password']);
+ }
+
+ setPinEnabled(true);
+ setShowPinSetup(false);
+ setPinSetupStep(1);
+ setNewPin('');
+ setConfirmPin('');
+ setPinError(null);
+ Toast.show({
+ type: 'success',
+ text1: t('settings.vaultUnlockSettings.pinEnabled'),
+ position: 'bottom',
+ visibilityTime: 1200,
+ });
+ } catch (error) {
+ console.error('Failed to enable PIN:', error);
+ let errorMessage = t('common.errors.unknownErrorTryAgain');
+
+ setPinError(errorMessage);
+ setConfirmPin('');
+ }
+ }, [isBiometricsEnabled, setAuthMethods, t]);
const styles = StyleSheet.create({
+ button: {
+ alignItems: 'center',
+ backgroundColor: colors.primary,
+ borderRadius: 8,
+ height: 50,
+ justifyContent: 'center',
+ marginTop: 16,
+ width: '100%',
+ },
+ buttonText: {
+ color: colors.primarySurfaceText,
+ fontSize: 16,
+ fontWeight: '600',
+ },
disabledText: {
color: colors.textMuted,
opacity: 0.5,
@@ -147,11 +306,69 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
color: colors.textMuted,
fontSize: 13,
},
+ helpIcon: {
+ marginLeft: 8,
+ },
helpText: {
color: colors.textMuted,
fontSize: 13,
marginTop: 4,
},
+ input: {
+ backgroundColor: colors.background,
+ borderColor: colors.accentBorder,
+ borderRadius: 8,
+ borderWidth: 1,
+ color: colors.text,
+ fontSize: 24,
+ height: 60,
+ letterSpacing: 8,
+ paddingHorizontal: 16,
+ textAlign: 'center',
+ },
+ modalButton: {
+ alignItems: 'center',
+ backgroundColor: colors.primary,
+ borderRadius: 8,
+ height: 50,
+ justifyContent: 'center',
+ marginTop: 16,
+ width: '100%',
+ },
+ modalButtonText: {
+ color: colors.primarySurfaceText,
+ fontSize: 16,
+ fontWeight: '600',
+ },
+ modalCloseButton: {
+ padding: 8,
+ position: 'absolute',
+ right: 8,
+ top: 8,
+ },
+ modalContainer: {
+ backgroundColor: 'rgba(0, 0, 0, 0.5)',
+ flex: 1,
+ justifyContent: 'center',
+ padding: 20,
+ },
+ modalContent: {
+ backgroundColor: colors.accentBackground,
+ borderRadius: 16,
+ padding: 24,
+ },
+ modalText: {
+ color: colors.textMuted,
+ fontSize: 14,
+ marginBottom: 16,
+ },
+ modalTitle: {
+ color: colors.text,
+ fontSize: 18,
+ fontWeight: '600',
+ marginBottom: 16,
+ paddingRight: 32,
+ },
option: {
borderBottomColor: colors.accentBorder,
borderBottomWidth: StyleSheet.hairlineWidth,
@@ -169,6 +386,11 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
justifyContent: 'space-between',
marginBottom: 4,
},
+ optionHeaderLeft: {
+ alignItems: 'center',
+ flex: 1,
+ flexDirection: 'row',
+ },
optionLast: {
borderBottomWidth: 0,
},
@@ -176,6 +398,11 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
color: colors.text,
fontSize: 16,
},
+ warningText: {
+ color: colors.errorBorder,
+ fontSize: 13,
+ marginTop: 4,
+ },
});
return (
@@ -214,6 +441,34 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
)}
</TouchableOpacity>
+ {/* PIN option */}
+ <TouchableOpacity
+ style={styles.option}
+ onPress={pinEnabled && !pinLocked ? handleDisablePin : handleEnablePin}
+ >
+ <View style={styles.optionHeader}>
+ <View style={styles.optionHeaderLeft}>
+ <ThemedText style={[styles.optionText, pinLocked && styles.disabledText]}>
+ {t('settings.vaultUnlockSettings.pin')}
+ </ThemedText>
+ </View>
+ <View pointerEvents="none">
+ <Switch
+ value={pinEnabled && !pinLocked}
+ disabled={pinLocked}
+ />
+ </View>
+ </View>
+ <ThemedText style={styles.helpText}>
+ {t('settings.vaultUnlockSettings.pinDescription')}
+ </ThemedText>
+ {pinLocked && (
+ <ThemedText style={styles.warningText}>
+ {t('settings.vaultUnlockSettings.pinLocked')}
+ </ThemedText>
+ )}
+ </TouchableOpacity>
+
<View style={[styles.option, styles.optionLast]}>
<View style={styles.optionHeader}>
<ThemedText style={styles.optionText}>{t('credentials.password')}</ThemedText>
@@ -227,6 +482,61 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
</ThemedText>
</View>
</View>
+
+ {/* PIN Setup Modal */}
+ <Modal
+ visible={showPinSetup}
+ transparent={true}
+ animationType="fade"
+ onRequestClose={() => {
+ setShowPinSetup(false);
+ setPinSetupStep(1);
+ setNewPin('');
+ setConfirmPin('');
+ }}
+ >
+ <View style={styles.modalContainer}>
+ <ThemedView style={styles.modalContent}>
+ <TouchableOpacity
+ style={styles.modalCloseButton}
+ onPress={() => {
+ setShowPinSetup(false);
+ setPinSetupStep(1);
+ setNewPin('');
+ setConfirmPin('');
+ }}
+ >
+ <MaterialIcons name="close" size={24} color={colors.textMuted} />
+ </TouchableOpacity>
+
+ {pinSetupStep === 1 ? (
+ <PinNumpad
+ pin={newPin}
+ onPinChange={handleNewPinChange}
+ onSubmit={handleNewPinSubmit}
+ error={pinError}
+ title={t('settings.vaultUnlockSettings.setupPin')}
+ subtitle={t('settings.vaultUnlockSettings.enterNewPinDescription')}
+ submitButtonText={t('common.next')}
+ minLength={4}
+ maxLength={8}
+ />
+ ) : (
+ <PinNumpad
+ pin={confirmPin}
+ onPinChange={handleConfirmPinChange}
+ onSubmit={handleConfirmPinSubmit}
+ error={pinError}
+ title={t('settings.vaultUnlockSettings.confirmPin')}
+ subtitle={t('settings.vaultUnlockSettings.confirmPinDescription')}
+ submitButtonText={t('common.confirm')}
+ minLength={4}
+ maxLength={8}
+ />
+ )}
+ </ThemedView>
+ </View>
+ </Modal>
</ThemedScrollView>
</ThemedContainer>
);
diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsx
index 47a06092a..c12954f78 100644
--- a/apps/mobile-app/app/unlock.tsx
+++ b/apps/mobile-app/app/unlock.tsx
@@ -7,6 +7,9 @@ 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';
@@ -20,6 +23,7 @@ import { Avatar } from '@/components/ui/Avatar';
import { RobustPressable } from '@/components/ui/RobustPressable';
import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
+import NativeVaultManager from '@/specs/NativeVaultManager';
/**
* Unlock screen.
@@ -35,6 +39,12 @@ export default function UnlockScreen() : React.ReactNode {
const [biometricDisplayName, setBiometricDisplayName] = useState('');
const [showPassword, setShowPassword] = useState(false);
+ // PIN unlock state
+ const [pinAvailable, setPinAvailable] = useState(false);
+
+ // Error state for password unlock
+ const [error, setError] = useState<string | null>(null);
+
/**
* Check if the key derivation parameters are stored in native storage.
* If not, we can't unlock the vault so logout instead to redirect user to login screen.
@@ -53,16 +63,20 @@ export default function UnlockScreen() : React.ReactNode {
getKeyDerivationParams();
/**
- * Fetch the biometric config.
+ * Fetch the biometric config and PIN availability.
*/
- const fetchBiometricConfig = async () : Promise<void> => {
+ const fetchConfig = async () : Promise<void> => {
const enabled = await isBiometricsEnabled();
setIsBiometricsAvailable(enabled);
const displayNameKey = await getBiometricDisplayNameKey();
setBiometricDisplayName(t(displayNameKey));
+
+ // Check PIN availability
+ const pinEnabled = await isPinEnabled();
+ setPinAvailable(pinEnabled);
};
- fetchBiometricConfig();
+ fetchConfig();
}, [isBiometricsEnabled, getKeyDerivationParams, getBiometricDisplayNameKey, t]);
@@ -79,6 +93,7 @@ export default function UnlockScreen() : React.ReactNode {
return;
}
+ setError(null);
setIsLoading(true);
try {
if (!isLoggedIn || !username) {
@@ -140,6 +155,79 @@ export default function UnlockScreen() : React.ReactNode {
}
};
+ /**
+ * Handle PIN unlock using native UI.
+ * Falls back to showing an alert on Android where native UI is not yet implemented.
+ */
+ const handlePinUnlock = useCallback(async () : Promise<void> => {
+ try {
+ /*
+ * Show native PIN unlock UI
+ * This will handle the unlock internally and store the encryption key
+ */
+ await NativeVaultManager.showPinUnlockUI();
+
+ // Vault is now unlocked in native memory, test the connection
+ const isUnlocked = await dbContext.testDatabaseConnection();
+
+ if (isUnlocked) {
+ // Check if the vault is up to date, if not, redirect to the upgrade page.
+ if (await dbContext.hasPendingMigrations()) {
+ router.replace('/upgrade');
+ return;
+ }
+
+ /*
+ * Navigate to initialize page which will handle vault sync and then navigate to credentials
+ * This ensures we always check for vault updates even after local unlock
+ */
+ router.replace('/initialize');
+ } else {
+ // This shouldn't happen if unlock succeeded, but handle it
+ Alert.alert(
+ t('common.error'),
+ t('auth.errors.incorrectPassword'),
+ [{ text: t('common.ok'), style: 'default' }]
+ );
+ }
+ } catch (err: unknown) {
+ // User cancelled or error occurred
+ if (err && typeof err === 'object' && 'code' in err) {
+ const error = err as { code?: string; message?: string };
+ if (error.code === 'USER_CANCELLED') {
+ // User cancelled PIN entry - just return, don't show error
+ return;
+ } else if (error.code === 'NOT_IMPLEMENTED') {
+ /*
+ * Native PIN UI not implemented on this platform (Android)
+ * Show informative message
+ */
+ Alert.alert(
+ t('common.info'),
+ 'Native PIN unlock is currently only available on iOS. Android support coming soon.',
+ [{ text: t('common.ok'), style: 'default' }]
+ );
+ return;
+ } else if (error.code === 'PIN_DISABLED') {
+ // PIN was disabled due to too many attempts
+ setPinAvailable(false);
+ Alert.alert(
+ t('common.error'),
+ t('settings.vaultUnlockSettings.pinLocked'),
+ [{ text: t('common.ok'), style: 'default' }]
+ );
+ } else {
+ console.error('PIN unlock failed:', err);
+ Alert.alert(
+ t('common.error'),
+ error.message || t('common.errors.unknownErrorTryAgain'),
+ [{ text: t('common.ok'), style: 'default' }]
+ );
+ }
+ }
+ }
+ }, [dbContext, t, setPinAvailable]);
+
/**
* Handle the logout.
*/
@@ -195,6 +283,12 @@ export default function UnlockScreen() : React.ReactNode {
padding: 20,
width: '100%',
},
+ errorText: {
+ color: colors.errorBorder,
+ fontSize: 14,
+ marginBottom: 12,
+ textAlign: 'center',
+ },
faceIdButton: {
alignItems: 'center',
height: 50,
@@ -242,6 +336,14 @@ export default function UnlockScreen() : React.ReactNode {
keyboardAvoidingView: {
flex: 1,
},
+ linkButton: {
+ marginTop: 16,
+ },
+ linkButtonText: {
+ color: colors.primary,
+ fontSize: 16,
+ textAlign: 'center',
+ },
loadingContainer: {
alignItems: 'center',
flex: 1,
@@ -286,6 +388,7 @@ export default function UnlockScreen() : React.ReactNode {
},
});
+ // Render password mode or loading
return (
<ThemedView style={styles.container}>
{isLoading ? (
@@ -320,6 +423,9 @@ export default function UnlockScreen() : React.ReactNode {
</View>
<ThemedText style={styles.subtitle}>{t('auth.enterPassword')}</ThemedText>
+ {/* Error Message */}
+ {error && <ThemedText style={styles.errorText}>{error}</ThemedText>}
+
<View style={styles.inputContainer}>
<MaterialIcons
name="lock"
@@ -369,6 +475,16 @@ export default function UnlockScreen() : React.ReactNode {
<ThemedText style={styles.faceIdButtonText}>{t('auth.tryBiometricAgain', { biometric: biometricDisplayName })}</ThemedText>
</RobustPressable>
)}
+
+ {/* Use PIN Button */}
+ {pinAvailable && (
+ <Pressable
+ style={styles.linkButton}
+ onPress={handlePinUnlock}
+ >
+ <ThemedText style={styles.linkButtonText}>{t('auth.unlockWithPin')}</ThemedText>
+ </Pressable>
+ )}
</View>
<RobustPressable
diff --git a/apps/mobile-app/components/pin/PinNumpad.tsx b/apps/mobile-app/components/pin/PinNumpad.tsx
new file mode 100644
index 000000000..704b52135
--- /dev/null
+++ b/apps/mobile-app/components/pin/PinNumpad.tsx
@@ -0,0 +1,348 @@
+import { MaterialIcons } from '@expo/vector-icons';
+import React from 'react';
+import { StyleSheet, View, Text, Pressable, Animated } from 'react-native';
+
+import { useColors } from '@/hooks/useColorScheme';
+import { ThemedText } from '@/components/themed/ThemedText';
+import { RobustPressable } from '@/components/ui/RobustPressable';
+
+/**
+ * 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;
+
+ 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 && (
+ <RobustPressable
+ style={styles.confirmButton}
+ onPress={onSubmit}
+ disabled={!canSubmit}
+ >
+ <ThemedText style={styles.confirmButtonText}>
+ {submitButtonText}
+ </ThemedText>
+ </RobustPressable>
+ )}
+ </View>
+ );
+};
diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsx
index f22e90944..59fb24e6e 100644
--- a/apps/mobile-app/context/AuthContext.tsx
+++ b/apps/mobile-app/context/AuthContext.tsx
@@ -283,20 +283,30 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
/**
* Get the display label translation key for the current auth method
- * Prefers Face ID if enabled, otherwise falls back to Password
+ * Priority: Biometrics > PIN > Password
*/
const getAuthMethodDisplayKey = useCallback(async (): Promise<string> => {
- const methods = await getEnabledAuthMethods();
- if (methods.includes('faceid')) {
- try {
+ try {
+ // Check for biometrics first (highest priority)
+ const methods = await getEnabledAuthMethods();
+ if (methods.includes('faceid')) {
if (await isBiometricsEnabledOnDevice()) {
return await getBiometricDisplayNameKey();
}
- } catch (error) {
- console.error('Failed to check Face ID enrollment:', error);
}
+
+ // Check for PIN (second priority)
+ const pinEnabled = await NativeVaultManager.isPinEnabled();
+ if (pinEnabled) {
+ return 'settings.vaultUnlockSettings.pin';
+ }
+
+ // Fallback to password
+ return 'credentials.password';
+ } catch (error) {
+ console.error('Failed to get auth method display key:', error);
+ return 'credentials.password';
}
- return 'credentials.password';
}, [getEnabledAuthMethods, getBiometricDisplayNameKey, isBiometricsEnabledOnDevice]);
/**
diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.json
index 1a93169a0..186abfda3 100644
--- a/apps/mobile-app/i18n/locales/en.json
+++ b/apps/mobile-app/i18n/locales/en.json
@@ -16,8 +16,13 @@
"loadMore": "Load more",
"use": "Use",
"confirm": "Confirm",
+ "next": "Next",
+ "notice": "Notice",
+ "enabled": "Enabled",
+ "disabled": "Disabled",
"errors": {
- "unknownError": "An unknown error occurred. Please try again."
+ "unknownError": "An unknown error occurred. Please try again.",
+ "unknownErrorTryAgain": "An unknown error occurred. Please try again."
}
},
"auth": {
@@ -34,6 +39,10 @@
"verifyingAuthCode": "Verifying authentication code",
"verify": "Verify",
"unlockVault": "Unlock Vault",
+ "unlockWithPin": "Unlock with PIN",
+ "useMasterPassword": "Use Master Password",
+ "enterPin": "Enter PIN",
+ "enterPinToUnlock": "Enter your PIN to unlock your vault",
"enterPassword": "Enter your password to unlock your vault",
"enterPasswordPlaceholder": "Password",
"enterAuthCode": "Enter 6-digit code",
@@ -285,6 +294,20 @@
"biometricDisabledMessage": "{{biometric}} is disabled for AliasVault. In order to use it, please enable it in your device settings first.",
"biometricHelp": "Your vault decryption key will be securely stored on your local device in the {{keystore}} and can be accessed securely with {{biometric}}.",
"biometricUnavailableHelp": "{{biometric}} is not available. Tap to open settings and/or go to your device settings to enable and configure it.",
+ "pin": "PIN Code",
+ "pinDescription": "Use a custom PIN code to unlock your vault quickly",
+ "pinHelp": "Your vault decryption key will be encrypted with your PIN and stored securely on your device.",
+ "pinEnabled": "PIN unlock enabled successfully",
+ "pinDisabled": "PIN unlock has been disabled",
+ "setupPin": "Setup PIN",
+ "enterNewPin": "Enter New PIN",
+ "enterNewPinDescription": "Choose a PIN to unlock your vault",
+ "confirmPin": "Confirm PIN",
+ "confirmPinDescription": "Re-enter your PIN to confirm",
+ "pinMismatch": "PINs do not match. Please try again.",
+ "pinLocked": "PIN locked after too many failed attempts. Please use your master password.",
+ "incorrectPin": "Incorrect PIN. {{attemptsRemaining}} attempts remaining.",
+ "incorrectPinSingular": "Incorrect PIN. 1 attempt remaining.",
"passwordHelp": "Re-enter your full master password to unlock your vault. This is always enabled as fallback option.",
"keystoreIOS": "iOS Keychain",
"keystoreAndroid": "Android Keystore"
diff --git a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
index 870cf1989..320cebd7a 100644
--- a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
+++ b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
@@ -1226,7 +1226,7 @@
CODE_SIGN_ENTITLEMENTS = AliasVault/AliasVault.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEVELOPMENT_TEAM = 8PHW4HN3F7;
ENABLE_BITCODE = NO;
GCC_PREPROCESSOR_DEFINITIONS = (
@@ -1241,7 +1241,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
- MARKETING_VERSION = 0.25.0;
+ MARKETING_VERSION = 0.24.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
@@ -1267,7 +1267,7 @@
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = AliasVault/AliasVault.entitlements;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEVELOPMENT_TEAM = 8PHW4HN3F7;
INFOPLIST_FILE = AliasVault/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = AliasVault;
@@ -1277,7 +1277,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
- MARKETING_VERSION = 0.25.0;
+ MARKETING_VERSION = 0.24.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
@@ -1422,7 +1422,7 @@
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = 8PHW4HN3F7;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -1458,7 +1458,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = 8PHW4HN3F7;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -1492,7 +1492,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = 8PHW4HN3F7;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -1549,7 +1549,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = 8PHW4HN3F7;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -1602,7 +1602,7 @@
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = 8PHW4HN3F7;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -1655,7 +1655,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = 8PHW4HN3F7;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -1704,7 +1704,7 @@
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = 8PHW4HN3F7;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -1739,7 +1739,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = 8PHW4HN3F7;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -1772,7 +1772,7 @@
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = 8PHW4HN3F7;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -1825,7 +1825,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = 8PHW4HN3F7;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -1874,7 +1874,7 @@
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = 8PHW4HN3F7;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -1926,7 +1926,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = 8PHW4HN3F7;
DYLIB_COMPATIBILITY_VERSION = 1;
@@ -1977,7 +1977,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_ENTITLEMENTS = autofill/autofill.entitlements;
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = 8PHW4HN3F7;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -1993,7 +1993,7 @@
"@executable_path/../../Frameworks",
);
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
- MARKETING_VERSION = 0.25.0;
+ MARKETING_VERSION = 0.24.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_DEBUG";
@@ -2022,7 +2022,7 @@
CODE_SIGN_ENTITLEMENTS = autofill/autofill.entitlements;
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
- CURRENT_PROJECT_VERSION = 2500100;
+ CURRENT_PROJECT_VERSION = 2400902;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = 8PHW4HN3F7;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -2038,7 +2038,7 @@
"@executable_path/../../Frameworks",
);
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
- MARKETING_VERSION = 0.25.0;
+ MARKETING_VERSION = 0.24.0;
MTL_FAST_MATH = YES;
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_RELEASE";
PRODUCT_BUNDLE_IDENTIFIER = net.aliasvault.app.autofill;
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
index 8405563b5..cb72af014 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
@@ -103,123 +103,30 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
return
}
- // Check if biometric authentication is available before attempting unlock
- if !vaultStore.isBiometricAuthEnabled() {
- // Biometric auth is not enabled or not available - show error
- let alert = UIAlertController(
- title: NSLocalizedString("biometric_auth_required", comment: "Biometric Authentication Required"),
- message: NSLocalizedString("biometric_auth_required_message", comment: "Please enable Face ID in the main AliasVault app to use autofill."),
- preferredStyle: .alert
- )
- alert.addAction(UIAlertAction(title: NSLocalizedString("ok", comment: "OK"), style: .default) { [weak self] _ in
- self?.extensionContext.cancelRequest(withError: NSError(
- domain: ASExtensionErrorDomain,
- code: ASExtensionError.userCanceled.rawValue
- ))
- })
- present(alert, animated: true)
- return
- }
-
- // Try to unlock the vault. If it fails, show proper error message.
- do {
- try vaultStore.unlockVault()
- } catch let error as NSError {
- print("Failed to unlock vault: \(error)")
-
- // Check for specific error codes to provide better user feedback
- var errorTitle = NSLocalizedString("unlock_failed", comment: "Unlock Failed")
- var errorMessage = error.localizedDescription
-
- if error.domain == "VaultStore" {
- switch error.code {
- case 3:
- // No encryption key found in memory
- errorTitle = NSLocalizedString("no_encryption_key", comment: "No Encryption Key")
- errorMessage = NSLocalizedString("no_encryption_key_message", comment: "No encryption key found. Please unlock the vault in the main AliasVault app first.")
- case 2:
- // Biometric auth not available
- errorTitle = NSLocalizedString("biometric_unavailable", comment: "Biometric Unavailable")
- errorMessage = NSLocalizedString("biometric_unavailable_message", comment: "Face ID is not available on this device.")
- case 9:
- // Failed to retrieve key from keychain
- errorTitle = NSLocalizedString("keychain_error", comment: "Keychain Error")
- errorMessage = NSLocalizedString("keychain_error_message", comment: "Failed to retrieve encryption key. This may be due to cancelled biometric authentication.")
- default:
- break
- }
- }
+ // Check if any authentication method is enabled (PIN or biometric)
+ let pinEnabled = vaultStore.isPinEnabled()
+ let biometricEnabled = vaultStore.isBiometricAuthEnabled()
+ if !pinEnabled && !biometricEnabled {
+ // No authentication method is enabled - show error
let alert = UIAlertController(
- title: errorTitle,
- message: errorMessage,
+ title: NSLocalizedString("auth_required", comment: "Authentication Required"),
+ message: NSLocalizedString("auth_required_message", comment: "Please enable Face ID or PIN unlock in the main AliasVault app to use autofill."),
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: NSLocalizedString("ok", comment: "OK"), style: .default) { [weak self] _ in
self?.extensionContext.cancelRequest(withError: NSError(
domain: ASExtensionErrorDomain,
- code: ASExtensionError.failed.rawValue,
- userInfo: [NSLocalizedDescriptionKey: errorMessage]
+ code: ASExtensionError.userCanceled.rawValue
))
})
present(alert, animated: true)
return
}
- // Handle passkey registration mode after vault is unlocked
- if isPasskeyRegistrationMode {
- guard let params = passkeyRegistrationParams else {
- extensionContext.cancelRequest(withError: NSError(
- domain: ASExtensionErrorDomain,
- code: ASExtensionError.failed.rawValue,
- userInfo: [NSLocalizedDescriptionKey: "Missing passkey registration parameters"]
- ))
- return
- }
-
- // Show passkey registration UI
- showPasskeyRegistrationView(
- rpId: params.rpId,
- userName: params.userName,
- userDisplayName: params.userDisplayName,
- userId: params.userId,
- clientDataHash: params.clientDataHash,
- vaultStore: vaultStore,
- enablePrf: params.enablePrf,
- prfInputs: params.prfInputs
- )
- return
- }
-
- // Only set up the view if we haven't already
- if currentHostingController == nil {
- do {
- try setupView(vaultStore: vaultStore)
-
- // Perform initial credential sync if the credential identity store is empty
- // This is an OOBE (Out Of Box Experience) step to populate the store on first use
- // Note: Regular syncs happen in the main app, this is just a fallback
- Task {
- await performInitialSyncIfNeeded(vaultStore: vaultStore)
- }
- } catch {
- print("Failed to setup view: \(error)")
- let alert = UIAlertController(
- title: NSLocalizedString("loading_error", comment: ""),
- message: NSLocalizedString("loading_error_message", comment: ""),
- preferredStyle: .alert
- )
- alert.addAction(UIAlertAction(title: NSLocalizedString("ok", comment: ""), style: .default) { [weak self] _ in
- self?.extensionContext.cancelRequest(withError: NSError(
- domain: ASExtensionErrorDomain,
- code: ASExtensionError.failed.rawValue,
- userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("failed_to_load_credentials", comment: "")]
- ))
- })
- present(alert, animated: true)
- return
- }
- }
+ // Show unlock coordinator which will handle PIN/biometric unlock
+ // and then show the actual view after successful unlock
+ showUnlockCoordinator(vaultStore: vaultStore)
}
override public func viewDidAppear(_ animated: Bool) {
@@ -228,8 +135,8 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
// If we're in quick return mode, now trigger the unlock and complete the request
// The loading view is already visible from viewWillAppear
if isQuickReturnMode {
- // Dispatch async to ensure the view is fully rendered before showing biometric prompt
- // This prevents a race condition where the first tap doesn't trigger the biometric UI
+ // Dispatch async to ensure the view is fully rendered before showing auth prompt
+ // This prevents a race condition where the first tap doesn't trigger the auth UI
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
@@ -239,20 +146,32 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
return
}
- // Check if biometric authentication is available
- if !vaultStore.isBiometricAuthEnabled() {
- print("Quick return failed: Biometric auth not enabled")
+ // Check if any authentication method is enabled
+ let pinEnabled = vaultStore.isPinEnabled()
+ let biometricEnabled = vaultStore.isBiometricAuthEnabled()
+
+ if !pinEnabled && !biometricEnabled {
+ print("Quick return failed: No auth method enabled")
self.extensionContext.cancelRequest(withError: NSError(
domain: ASExtensionErrorDomain,
code: ASExtensionError.failed.rawValue,
- userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("biometric_auth_required_message", comment: "Please enable Face ID in the main AliasVault app to use autofill.")]
+ userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("auth_required_message", comment: "Please enable Face ID or PIN unlock in the main AliasVault app to use autofill.")]
))
return
}
+ // If PIN is enabled, show PIN unlock immediately (PIN takes priority)
+ if pinEnabled {
+ self.showQuickReturnPinUnlock(vaultStore: vaultStore)
+ return
+ }
+
+ // Only biometric is enabled - try to unlock with biometric
do {
+ // Try to unlock the vault with biometric
try vaultStore.unlockVault()
+ // Unlock succeeded - process the credential request
if let passkeyRequest = self.quickReturnPasskeyRequest {
self.handleQuickReturnPasskeyCredential(vaultStore: vaultStore, request: passkeyRequest)
} else if let passwordRequest = self.quickReturnPasswordRequest {
@@ -267,7 +186,7 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
switch error.code {
case 3:
errorMessage = NSLocalizedString("no_encryption_key_message", comment: "No encryption key found. Please unlock the vault in the main AliasVault app first.")
- case 9:
+ case 8, 9:
errorMessage = NSLocalizedString("keychain_error_message", comment: "Failed to retrieve encryption key. This may be due to cancelled biometric authentication.")
default:
break
@@ -284,6 +203,61 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
}
}
+ /// Show PIN unlock for quick return mode when biometric fails
+ private func showQuickReturnPinUnlock(vaultStore: VaultStore) {
+ // Remove the loading view
+ if let loadingController = currentHostingController {
+ loadingController.willMove(toParent: nil)
+ loadingController.view.removeFromSuperview()
+ loadingController.removeFromParent()
+ currentHostingController = nil
+ }
+
+ // Create PIN unlock view model with injected dependencies
+ let viewModel = PinUnlockViewModel(
+ pinLength: vaultStore.getPinLength(),
+ unlockHandler: { [weak self] pin in
+ guard let self = self else { return }
+
+ // Attempt to unlock with PIN
+ let encryptionKeyBase64 = try vaultStore.unlockWithPin(pin)
+
+ // Store the encryption key and unlock
+ try vaultStore.storeEncryptionKey(base64Key: encryptionKeyBase64)
+ try vaultStore.unlockVault()
+
+ // Process the credential request
+ await MainActor.run {
+ if let passkeyRequest = self.quickReturnPasskeyRequest {
+ self.handleQuickReturnPasskeyCredential(vaultStore: vaultStore, request: passkeyRequest)
+ } else if let passwordRequest = self.quickReturnPasswordRequest {
+ self.handleQuickReturnPasswordCredential(vaultStore: vaultStore, request: passwordRequest)
+ }
+ }
+ },
+ cancelHandler: { [weak self] in
+ self?.handleCancel()
+ }
+ )
+
+ // Show PIN unlock view
+ let pinUnlockView = PinUnlockView(viewModel: viewModel)
+ let hostingController = UIHostingController(rootView: pinUnlockView)
+ addChild(hostingController)
+ view.addSubview(hostingController.view)
+
+ hostingController.view.translatesAutoresizingMaskIntoConstraints = false
+ NSLayoutConstraint.activate([
+ hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
+ hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
+ hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
+ hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
+ ])
+
+ hostingController.didMove(toParent: self)
+ currentHostingController = hostingController
+ }
+
private func setupView(vaultStore: VaultStore) throws {
let hostingController: UIViewController
@@ -342,6 +316,99 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
))
}
+ // MARK: - Unlock Flow
+
+ /// Show the unlock coordinator which handles PIN/biometric unlock
+ private func showUnlockCoordinator(vaultStore: VaultStore) {
+ let unlockController = UnlockCoordinatorViewController(
+ vaultStore: vaultStore,
+ onUnlocked: { [weak self] in
+ self?.onUnlockSuccess(vaultStore: vaultStore)
+ },
+ onCancel: { [weak self] in
+ self?.handleCancel()
+ }
+ )
+
+ // Add as child view controller
+ addChild(unlockController)
+ view.addSubview(unlockController.view)
+
+ unlockController.view.translatesAutoresizingMaskIntoConstraints = false
+ NSLayoutConstraint.activate([
+ unlockController.view.topAnchor.constraint(equalTo: view.topAnchor),
+ unlockController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
+ unlockController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
+ unlockController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
+ ])
+
+ unlockController.didMove(toParent: self)
+ self.currentHostingController = unlockController
+ }
+
+ /// Called after successful unlock - show the actual credential/passkey view
+ private func onUnlockSuccess(vaultStore: VaultStore) {
+ // Remove the unlock coordinator view
+ if let unlockController = currentHostingController {
+ unlockController.willMove(toParent: nil)
+ unlockController.view.removeFromSuperview()
+ unlockController.removeFromParent()
+ currentHostingController = nil
+ }
+
+ // Handle passkey registration mode after vault is unlocked
+ if isPasskeyRegistrationMode {
+ guard let params = passkeyRegistrationParams else {
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.failed.rawValue,
+ userInfo: [NSLocalizedDescriptionKey: "Missing passkey registration parameters"]
+ ))
+ return
+ }
+
+ // Show passkey registration UI
+ showPasskeyRegistrationView(
+ rpId: params.rpId,
+ userName: params.userName,
+ userDisplayName: params.userDisplayName,
+ userId: params.userId,
+ clientDataHash: params.clientDataHash,
+ vaultStore: vaultStore,
+ enablePrf: params.enablePrf,
+ prfInputs: params.prfInputs
+ )
+ return
+ }
+
+ // Set up the credential/passkey selection view
+ do {
+ try setupView(vaultStore: vaultStore)
+
+ // Perform initial credential sync if the credential identity store is empty
+ // This is an OOBE (Out Of Box Experience) step to populate the store on first use
+ // Note: Regular syncs happen in the main app, this is just a fallback
+ Task {
+ await performInitialSyncIfNeeded(vaultStore: vaultStore)
+ }
+ } catch {
+ print("Failed to setup view: \(error)")
+ let alert = UIAlertController(
+ title: NSLocalizedString("loading_error", comment: ""),
+ message: NSLocalizedString("loading_error_message", comment: ""),
+ preferredStyle: .alert
+ )
+ alert.addAction(UIAlertAction(title: NSLocalizedString("ok", comment: ""), style: .default) { [weak self] _ in
+ self?.extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.failed.rawValue,
+ userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("failed_to_load_credentials", comment: "")]
+ ))
+ })
+ present(alert, animated: true)
+ }
+ }
+
// MARK: - Passkey Support
override public func provideCredentialWithoutUserInteraction(for credentialRequest: ASCredentialRequest) {
@@ -416,30 +483,15 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
return false
}
- // Check if Face ID/Touch ID is enabled
- let context = LAContext()
- var authMethod = NSLocalizedString("face_id_touch_id", comment: "")
- var biometricsAvailable = false
- var biometricsError: NSError?
-
- // Check if device supports biometrics
- if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &biometricsError) {
- biometricsAvailable = true
- switch context.biometryType {
- case .faceID:
- authMethod = NSLocalizedString("face_id", comment: "")
- case .touchID:
- authMethod = NSLocalizedString("touch_id", comment: "")
- default:
- break
- }
- }
+ // Check if any authentication method (PIN or biometric) is enabled
+ let pinEnabled = vaultStore.isPinEnabled()
+ let biometricEnabled = vaultStore.getAuthMethods().contains(.faceID)
- // First check if biometrics are available on the device
- if !biometricsAvailable {
+ // If neither PIN nor biometric is enabled, show error
+ if !pinEnabled && !biometricEnabled {
let alert = UIAlertController(
- title: String(format: NSLocalizedString("biometric_required", comment: ""), authMethod),
- message: String(format: NSLocalizedString("biometric_required_message", comment: ""), authMethod),
+ title: NSLocalizedString("auth_required", comment: ""),
+ message: NSLocalizedString("auth_required_message", comment: ""),
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: NSLocalizedString("ok", comment: ""), style: .default) { [weak self] _ in
@@ -452,21 +504,41 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
return false
}
- // Then check if Face ID/Touch ID is enabled in the app settings
- if !vaultStore.getAuthMethods().contains(.faceID) {
- let alert = UIAlertController(
- title: String(format: NSLocalizedString("biometric_required", comment: ""), authMethod),
- message: String(format: NSLocalizedString("biometric_app_required_message", comment: ""), authMethod),
- preferredStyle: .alert
- )
- alert.addAction(UIAlertAction(title: NSLocalizedString("ok", comment: ""), style: .default) { [weak self] _ in
- self?.extensionContext.cancelRequest(withError: NSError(
- domain: ASExtensionErrorDomain,
- code: ASExtensionError.userCanceled.rawValue
- ))
- })
- present(alert, animated: true)
- return false
+ // If biometric is enabled, check if device supports it
+ if biometricEnabled {
+ let context = LAContext()
+ var authMethod = NSLocalizedString("face_id_touch_id", comment: "")
+ var biometricsError: NSError?
+
+ // Check if device supports biometrics
+ if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &biometricsError) {
+ switch context.biometryType {
+ case .faceID:
+ authMethod = NSLocalizedString("face_id", comment: "")
+ case .touchID:
+ authMethod = NSLocalizedString("touch_id", comment: "")
+ default:
+ break
+ }
+ } else {
+ // Device doesn't support biometrics but biometric is enabled
+ // Check if PIN is available as fallback
+ if !pinEnabled {
+ let alert = UIAlertController(
+ title: String(format: NSLocalizedString("biometric_required", comment: ""), authMethod),
+ message: String(format: NSLocalizedString("biometric_required_message", comment: ""), authMethod),
+ preferredStyle: .alert
+ )
+ alert.addAction(UIAlertAction(title: NSLocalizedString("ok", comment: ""), style: .default) { [weak self] _ in
+ self?.extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.userCanceled.rawValue
+ ))
+ })
+ present(alert, animated: true)
+ return false
+ }
+ }
}
return true
diff --git a/apps/mobile-app/ios/Autofill/UnlockCoordinator.swift b/apps/mobile-app/ios/Autofill/UnlockCoordinator.swift
new file mode 100644
index 000000000..6cf1f7e59
--- /dev/null
+++ b/apps/mobile-app/ios/Autofill/UnlockCoordinator.swift
@@ -0,0 +1,151 @@
+import SwiftUI
+import UIKit
+import VaultStoreKit
+import VaultUI
+
+/// Coordinator view that handles the unlock flow before showing the actual autofill/passkey content
+/// This view decides whether to show PIN unlock, biometric unlock, or directly show the content
+struct UnlockCoordinatorView: View {
+ @StateObject private var coordinator: UnlockCoordinator
+
+ init(
+ vaultStore: VaultStore,
+ onUnlocked: @escaping () -> Void,
+ onCancel: @escaping () -> Void
+ ) {
+ _coordinator = StateObject(wrappedValue: UnlockCoordinator(
+ vaultStore: vaultStore,
+ onUnlocked: onUnlocked,
+ onCancel: onCancel
+ ))
+ }
+
+ var body: some View {
+ Group {
+ if let pinViewModel = coordinator.pinViewModel {
+ // Show PIN unlock view
+ PinUnlockView(viewModel: pinViewModel)
+ } else {
+ // Show loading while attempting biometric unlock
+ VStack {
+ ProgressView()
+ .progressViewStyle(CircularProgressViewStyle())
+ .scaleEffect(1.5)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(Color(UIColor.systemBackground))
+ }
+ }
+ .onAppear {
+ coordinator.startUnlockFlow()
+ }
+ }
+}
+
+/// Coordinator that manages the unlock flow logic
+@MainActor
+class UnlockCoordinator: ObservableObject {
+ @Published var pinViewModel: PinUnlockViewModel?
+
+ let vaultStore: VaultStore
+ private let onUnlocked: () -> Void
+ private let onCancel: () -> Void
+
+ init(
+ vaultStore: VaultStore,
+ onUnlocked: @escaping () -> Void,
+ onCancel: @escaping () -> Void
+ ) {
+ self.vaultStore = vaultStore
+ self.onUnlocked = onUnlocked
+ self.onCancel = onCancel
+ }
+
+ func startUnlockFlow() {
+ // Check if PIN is enabled
+ let pinEnabled = vaultStore.isPinEnabled()
+ let biometricEnabled = vaultStore.isBiometricAuthEnabled()
+
+ if pinEnabled {
+ // PIN is enabled - show PIN unlock view
+ createPinViewModel()
+ } else if biometricEnabled {
+ // Only biometric is enabled - attempt biometric unlock
+ Task {
+ await attemptBiometricUnlock()
+ }
+ } else {
+ // No auth method enabled - this shouldn't happen, but cancel the request
+ cancel()
+ }
+ }
+
+ private func createPinViewModel() {
+ pinViewModel = PinUnlockViewModel(
+ pinLength: vaultStore.getPinLength(),
+ unlockHandler: { [weak self] pin in
+ guard let self = self else { return }
+
+ // Attempt to unlock with PIN
+ let encryptionKeyBase64 = try self.vaultStore.unlockWithPin(pin)
+
+ // Store the encryption key in memory
+ try self.vaultStore.storeEncryptionKey(base64Key: encryptionKeyBase64)
+
+ // Now unlock the vault with the key in memory
+ try self.vaultStore.unlockVault()
+
+ // Success - proceed to the actual autofill/passkey view
+ await MainActor.run {
+ self.onUnlocked()
+ }
+ },
+ cancelHandler: { [weak self] in
+ self?.cancel()
+ }
+ )
+ }
+
+ func cancel() {
+ onCancel()
+ }
+
+ private func attemptBiometricUnlock() async {
+ do {
+ // Attempt to unlock with biometric
+ try vaultStore.unlockVault()
+
+ // Success - proceed to the actual autofill/passkey view
+ onUnlocked()
+ } catch {
+ print("Biometric unlock failed: \(error)")
+ // If biometric fails, check if PIN is available as fallback
+ if vaultStore.isPinEnabled() {
+ createPinViewModel()
+ } else {
+ // No fallback available - cancel
+ cancel()
+ }
+ }
+ }
+}
+
+/// UIHostingController wrapper for the UnlockCoordinatorView
+class UnlockCoordinatorViewController: UIHostingController<UnlockCoordinatorView> {
+ init(
+ vaultStore: VaultStore,
+ onUnlocked: @escaping () -> Void,
+ onCancel: @escaping () -> Void
+ ) {
+ let coordinatorView = UnlockCoordinatorView(
+ vaultStore: vaultStore,
+ onUnlocked: onUnlocked,
+ onCancel: onCancel
+ )
+ super.init(rootView: coordinatorView)
+ }
+
+ @MainActor required dynamic init?(coder aDecoder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
+}
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index eb10887ce..e2a35da23 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -247,4 +247,30 @@
[vaultManager mutateVault:resolve rejecter:reject];
}
+// MARK: - PIN Unlock
+
+- (void)isPinEnabled:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager isPinEnabled:resolve rejecter:reject];
+}
+
+- (void)getPinLength:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager getPinLength:resolve rejecter:reject];
+}
+
+- (void)setupPin:(NSString *)pin resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager setupPin:pin resolver:resolve rejecter:reject];
+}
+
+- (void)unlockWithPin:(NSString *)pin resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager unlockWithPin:pin resolver:resolve rejecter:reject];
+}
+
+- (void)removeAndDisablePin:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager removeAndDisablePin:resolve rejecter:reject];
+}
+
+- (void)showPinUnlockUI:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager showPinUnlockUI:resolve rejecter:reject];
+}
+
@end
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 758635656..2e4fe811a 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -3,6 +3,8 @@ import SQLite
import LocalAuthentication
import VaultStoreKit
import VaultModels
+import SwiftUI
+import VaultUI
/**
* This class is used as a bridge to allow React Native to interact with the VaultStoreKit class.
@@ -746,6 +748,134 @@ public class VaultManager: NSObject {
}
}
+ // MARK: - PIN Unlock Methods
+
+ @objc
+ func isPinEnabled(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ resolve(vaultStore.isPinEnabled())
+ }
+
+ @objc
+ func getPinLength(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ if let length = vaultStore.getPinLength() {
+ resolve(length)
+ } else {
+ resolve(nil)
+ }
+ }
+
+ @objc
+ func getPinFailedAttempts(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ resolve(vaultStore.getPinFailedAttempts())
+ }
+
+ @objc
+ func setupPin(_ pin: String,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ do {
+ try vaultStore.setupPin(pin)
+ resolve(nil)
+ } catch {
+ reject("SETUP_PIN_ERROR", "Failed to setup PIN: \(error.localizedDescription)", error)
+ }
+ }
+
+ @objc
+ func unlockWithPin(_ pin: String,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ do {
+ let vaultEncryptionKey = try vaultStore.unlockWithPin(pin)
+ resolve(vaultEncryptionKey)
+ } catch let error as NSError {
+ // Extract attempts remaining from error if available and include in message
+ if let attemptsRemaining = error.userInfo["attemptsRemaining"] as? Int {
+ let message = "\(error.localizedDescription) - \(attemptsRemaining) attempts remaining"
+ reject("INCORRECT_PIN", message, error)
+ } else {
+ reject("PIN_UNLOCK_ERROR", error.localizedDescription, error)
+ }
+ }
+ }
+
+ @objc
+ func resetPinFailedAttempts(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ vaultStore.resetPinFailedAttempts()
+ resolve(nil)
+ }
+
+ @objc
+ func removeAndDisablePin(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ do {
+ try vaultStore.removeAndDisablePin()
+ resolve(nil)
+ } catch {
+ reject("REMOVE_PIN_ERROR", "Failed to remove PIN: \(error.localizedDescription)", error)
+ }
+ }
+
+ @objc
+ func showPinUnlockUI(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ DispatchQueue.main.async { [weak self] in
+ guard let self = self else {
+ reject("INTERNAL_ERROR", "VaultManager instance deallocated", nil)
+ return
+ }
+
+ // Get the root view controller from React Native
+ guard let rootVC = RCTPresentedViewController() else {
+ reject("NO_VIEW_CONTROLLER", "No view controller available", nil)
+ return
+ }
+
+ // Create PIN unlock view with ViewModel
+ let viewModel = PinUnlockViewModel(
+ pinLength: self.vaultStore.getPinLength(),
+ unlockHandler: { [weak self] pin in
+ guard let self = self else {
+ throw NSError(domain: "VaultManager", code: -1, userInfo: [NSLocalizedDescriptionKey: "VaultManager instance deallocated"])
+ }
+
+ // Unlock vault with PIN
+ let encryptionKeyBase64 = try self.vaultStore.unlockWithPin(pin)
+
+ // Store the encryption key in memory
+ try self.vaultStore.storeEncryptionKey(base64Key: encryptionKeyBase64)
+
+ // Now unlock the vault with the key in memory
+ try self.vaultStore.unlockVault()
+
+ // Success - dismiss and resolve
+ await MainActor.run {
+ rootVC.dismiss(animated: true) {
+ resolve(nil)
+ }
+ }
+ },
+ cancelHandler: {
+ // User cancelled
+ rootVC.dismiss(animated: true) {
+ reject("USER_CANCELLED", "User cancelled PIN unlock", nil)
+ }
+ }
+ )
+
+ let pinView = PinUnlockView(viewModel: viewModel)
+ let hostingController = UIHostingController(rootView: pinView)
+
+ // Present modally as full screen
+ hostingController.modalPresentationStyle = .fullScreen
+ rootVC.present(hostingController, animated: true)
+ }
+ }
+
@objc
func requiresMainQueueSetup() -> Bool {
return false
diff --git a/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift b/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift
index 2474900da..1f8f1ff9f 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Constants/VaultConstants.swift
@@ -15,6 +15,7 @@ public struct VaultConstants {
static let encryptionKeyDerivationParamsKey = "aliasvault_encryption_key_derivation_params"
static let usernameKey = "aliasvault_username"
static let offlineModeKey = "aliasvault_offline_mode"
+ static let pinEnabledKey = "aliasvault_pin_enabled"
static let defaultAutoLockTimeout: Int = 3600 // 1 hour in seconds
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
new file mode 100644
index 000000000..a84c46d27
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
@@ -0,0 +1,264 @@
+import Foundation
+import CryptoKit
+import Security
+import SignalArgon2
+
+/// Extension for the VaultStore class to handle PIN unlock functionality
+extension VaultStore {
+ // MARK: - PIN Constants
+
+ private static let pinEncryptedKeyKey = "pinEncryptedKey"
+ private static let pinSaltKey = "pinSalt"
+ private static let pinLengthKey = "pinLength"
+ private static let pinFailedAttemptsKey = "pinFailedAttempts"
+ private static let maxPinAttempts = 4
+
+ // MARK: - PIN Status Methods
+
+ /// Check if PIN unlock is enabled
+ public func isPinEnabled() -> Bool {
+ return userDefaults.bool(forKey: VaultConstants.pinEnabledKey)
+ }
+
+ /// Get the configured PIN length
+ public func getPinLength() -> Int? {
+ guard isPinEnabled() else { return nil }
+ let length = userDefaults.integer(forKey: Self.pinLengthKey)
+ return length > 0 ? length : nil
+ }
+
+ /// Get failed attempts count
+ public func getPinFailedAttempts() -> Int {
+ return userDefaults.integer(forKey: Self.pinFailedAttemptsKey)
+ }
+
+ // MARK: - PIN Setup Methods
+
+ /// Setup PIN unlock
+ /// Encrypts the vault encryption key (from memory) with the PIN and stores it securely
+ /// The encryption key is retrieved internally and never exposed to React Native layer
+ ///
+ /// - Parameters:
+ /// - pin: The PIN to set (4-8 digits)
+ /// - Throws: Error if PIN is invalid, vault not unlocked, or encryption fails
+ public func setupPin(_ pin: String) throws {
+ // Get vault encryption key from memory (vault must be unlocked)
+ let vaultEncryptionKey = try getEncryptionKey()
+
+ // Generate random salt
+ var salt = Data(count: 16)
+ let result = salt.withUnsafeMutableBytes {
+ SecRandomCopyBytes(kSecRandomDefault, 16, $0.baseAddress!)
+ }
+ guard result == errSecSuccess else {
+ throw NSError(domain: "VaultStore", code: 22, userInfo: [NSLocalizedDescriptionKey: "Failed to generate random salt"])
+ }
+
+ // Derive key from PIN using Argon2id
+ let pinKey = try derivePinKey(pin: pin, salt: salt)
+
+ // Encrypt the vault encryption key using AES-GCM
+ let symmetricKey = SymmetricKey(data: pinKey)
+ let sealedBox = try AES.GCM.seal(vaultEncryptionKey, using: symmetricKey)
+ guard let encryptedData = sealedBox.combined else {
+ throw NSError(domain: "VaultStore", code: 23, userInfo: [NSLocalizedDescriptionKey: "Failed to encrypt vault key"])
+ }
+
+ // Store encrypted key and salt in keychain (without biometric protection)
+ try storePinDataInKeychain(encryptedKey: encryptedData, salt: salt)
+
+ // Store PIN metadata in UserDefaults
+ userDefaults.set(true, forKey: VaultConstants.pinEnabledKey)
+ userDefaults.set(pin.count, forKey: Self.pinLengthKey)
+ userDefaults.set(0, forKey: Self.pinFailedAttemptsKey)
+ userDefaults.synchronize()
+
+ print("PIN unlock enabled successfully")
+ }
+
+ // MARK: - PIN Unlock Methods
+
+ /// Unlock with PIN
+ /// Returns the decrypted vault encryption key
+ ///
+ /// - Parameter pin: The PIN to use for unlocking
+ /// - Returns: The decrypted vault encryption key (base64)
+ /// - Throws: Error if PIN is incorrect, locked, or not configured
+ public func unlockWithPin(_ pin: String) throws -> String {
+ // Check if PIN is enabled
+ // Note: If PIN was previously locked (max attempts), it's automatically disabled and cleared,
+ // so isPinEnabled() returning false means either PIN was never set up or it was locked and cleared
+ guard isPinEnabled() else {
+ throw NSError(domain: "VaultStore", code: 25, userInfo: [NSLocalizedDescriptionKey: "PIN unlock is not configured"])
+ }
+
+ do {
+ // Retrieve encrypted key and salt from keychain
+ let (encryptedKey, salt) = try retrievePinDataFromKeychain()
+
+ // Derive key from PIN
+ let pinKey = try derivePinKey(pin: pin, salt: salt)
+
+ // Decrypt the vault encryption key
+ let symmetricKey = SymmetricKey(data: pinKey)
+ let sealedBox = try AES.GCM.SealedBox(combined: encryptedKey)
+ let decryptedKey = try AES.GCM.open(sealedBox, using: symmetricKey)
+
+ // Reset failed attempts on success
+ userDefaults.set(0, forKey: Self.pinFailedAttemptsKey)
+ userDefaults.synchronize()
+
+ // Return the decrypted vault encryption key as base64
+ return decryptedKey.base64EncodedString()
+ } catch {
+ // Increment failed attempts
+ let currentAttempts = getPinFailedAttempts()
+ let newAttempts = currentAttempts + 1
+ userDefaults.set(newAttempts, forKey: Self.pinFailedAttemptsKey)
+ userDefaults.synchronize()
+
+ // If max attempts reached, disable PIN and clear all stored data
+ if newAttempts >= Self.maxPinAttempts {
+ try? removeAndDisablePin()
+ throw NSError(domain: "VaultStore", code: 26, userInfo: [NSLocalizedDescriptionKey: "PIN locked after too many failed attempts"])
+ }
+
+ // Return incorrect PIN error with attempts remaining
+ let attemptsRemaining = Self.maxPinAttempts - newAttempts
+ throw NSError(domain: "VaultStore", code: 27, userInfo: [
+ NSLocalizedDescriptionKey: "Incorrect PIN. \(attemptsRemaining) attempts remaining",
+ "attemptsRemaining": attemptsRemaining
+ ])
+ }
+ }
+
+ /// Reset failed attempts counter
+ /// Called after successful password unlock
+ public func resetPinFailedAttempts() {
+ userDefaults.set(0, forKey: Self.pinFailedAttemptsKey)
+ userDefaults.synchronize()
+ }
+
+ /// Disable PIN unlock and remove all stored data
+ public func removeAndDisablePin() throws {
+ // Remove PIN data from keychain
+ try removePinDataFromKeychain()
+
+ // Clear PIN metadata from UserDefaults
+ userDefaults.removeObject(forKey: VaultConstants.pinEnabledKey)
+ userDefaults.removeObject(forKey: Self.pinLengthKey)
+ userDefaults.removeObject(forKey: Self.pinFailedAttemptsKey)
+ userDefaults.synchronize()
+
+ print("PIN unlock disabled and all data removed")
+ }
+
+ // MARK: - Private PIN Methods
+
+ /// Derive encryption key from PIN using Argon2id
+ ///
+ /// Uses Argon2id with high memory cost (64 MB) to make brute-force attacks
+ /// significantly more expensive. This is especially important for PINs which
+ /// have lower entropy than passwords.
+ ///
+ /// Parameters chosen for security:
+ /// - Memory: 65536 KiB (64 MB) - makes GPU attacks much harder
+ /// - Iterations: 3 - standard for Argon2id
+ /// - Parallelism: 1 - suitable for mobile environment
+ /// - Output: 32 bytes for AES-256-GCM
+ private func derivePinKey(pin: String, salt: Data) throws -> Data {
+ guard let pinData = pin.data(using: .utf8) else {
+ throw NSError(domain: "VaultStore", code: 28, userInfo: [NSLocalizedDescriptionKey: "Failed to convert PIN to data"])
+ }
+
+ // Use SignalArgon2 to hash the PIN via Argon2id
+ guard let derivedKeyTuple = try? Argon2.hash(
+ iterations: 3,
+ memoryInKiB: 65536, // 64 MB
+ threads: 1,
+ password: pinData,
+ salt: salt,
+ desiredLength: 32,
+ variant: .id,
+ version: .v13
+ ) else {
+ throw NSError(domain: "VaultStore", code: 29, userInfo: [NSLocalizedDescriptionKey: "Argon2 PIN hashing failed"])
+ }
+
+ return derivedKeyTuple.raw
+ }
+
+ /// Store PIN encrypted data in keychain (without biometric protection)
+ private func storePinDataInKeychain(encryptedKey: Data, salt: Data) throws {
+ // Create a dictionary to store both encrypted key and salt
+ let pinData: [String: Data] = [
+ "encryptedKey": encryptedKey,
+ "salt": salt
+ ]
+
+ guard let dataToStore = try? JSONEncoder().encode(pinData) else {
+ throw NSError(domain: "VaultStore", code: 30, userInfo: [NSLocalizedDescriptionKey: "Failed to encode PIN data"])
+ }
+
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: VaultConstants.keychainService,
+ kSecAttrAccount as String: Self.pinEncryptedKeyKey,
+ kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup,
+ kSecValueData as String: dataToStore,
+ // Use device passcode protection but not biometric protection
+ kSecAttrAccessible as String: kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
+ ]
+
+ // Delete existing item if present
+ SecItemDelete(query as CFDictionary)
+
+ // Add new item
+ let status = SecItemAdd(query as CFDictionary, nil)
+ guard status == errSecSuccess else {
+ throw NSError(domain: "VaultStore", code: 31, userInfo: [NSLocalizedDescriptionKey: "Failed to store PIN data in keychain: \(status)"])
+ }
+ }
+
+ /// Retrieve PIN encrypted data from keychain
+ private func retrievePinDataFromKeychain() throws -> (encryptedKey: Data, salt: Data) {
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: VaultConstants.keychainService,
+ kSecAttrAccount as String: Self.pinEncryptedKeyKey,
+ kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup,
+ kSecReturnData as String: true,
+ kSecMatchLimit as String: kSecMatchLimitOne
+ ]
+
+ var result: AnyObject?
+ let status = SecItemCopyMatching(query as CFDictionary, &result)
+
+ guard status == errSecSuccess, let data = result as? Data else {
+ throw NSError(domain: "VaultStore", code: 32, userInfo: [NSLocalizedDescriptionKey: "No PIN data found in keychain"])
+ }
+
+ guard let pinData = try? JSONDecoder().decode([String: Data].self, from: data),
+ let encryptedKey = pinData["encryptedKey"],
+ let salt = pinData["salt"] else {
+ throw NSError(domain: "VaultStore", code: 33, userInfo: [NSLocalizedDescriptionKey: "Failed to decode PIN data"])
+ }
+
+ return (encryptedKey, salt)
+ }
+
+ /// Remove PIN data from keychain
+ private func removePinDataFromKeychain() throws {
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: VaultConstants.keychainService,
+ kSecAttrAccount as String: Self.pinEncryptedKeyKey,
+ kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup
+ ]
+
+ let status = SecItemDelete(query as CFDictionary)
+ guard status == errSecSuccess || status == errSecItemNotFound else {
+ throw NSError(domain: "VaultStore", code: 34, userInfo: [NSLocalizedDescriptionKey: "Failed to remove PIN data from keychain: \(status)"])
+ }
+ }
+}
diff --git a/apps/mobile-app/ios/VaultUI/Auth/PinUnlockView.swift b/apps/mobile-app/ios/VaultUI/Auth/PinUnlockView.swift
new file mode 100644
index 000000000..74382fd52
--- /dev/null
+++ b/apps/mobile-app/ios/VaultUI/Auth/PinUnlockView.swift
@@ -0,0 +1,372 @@
+import SwiftUI
+
+private let locBundle = Bundle.vaultUI
+
+/// SwiftUI view for PIN unlock in native autofill/passkey flows
+/// Similar to the React Native PinNumpad component
+public struct PinUnlockView: View {
+ @ObservedObject public var viewModel: PinUnlockViewModel
+ @Environment(\.colorScheme) var colorScheme
+
+ public init(viewModel: PinUnlockViewModel) {
+ self._viewModel = ObservedObject(wrappedValue: viewModel)
+ }
+
+ public var body: some View {
+ GeometryReader { geometry in
+ ZStack {
+ VStack(spacing: 0) {
+ // Header with cancel button
+ HStack {
+ Spacer()
+ Button(action: {
+ viewModel.cancel()
+ }) {
+ Text(String(localized: "cancel", bundle: locBundle))
+ .foregroundColor(theme.primary)
+ }
+ .padding(.trailing, 20)
+ }
+ .padding(.top, 20)
+ .frame(height: 50)
+
+ Spacer()
+
+ // AliasVault Logo
+ Image("Logo", bundle: .vaultUI)
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .frame(width: 80, height: 80)
+ .padding(.bottom, 20)
+
+ // Title
+ Text(String(localized: "unlock_vault", bundle: locBundle))
+ .font(.system(size: 24, weight: .semibold))
+ .foregroundColor(theme.text)
+ .padding(.bottom, 8)
+
+ // Subtitle
+ if let pinLength = viewModel.pinLength {
+ Text(String(format: String(localized: "enter_pin_to_unlock", bundle: locBundle), pinLength))
+ .font(.system(size: 16))
+ .foregroundColor(theme.text.opacity(0.7))
+ .multilineTextAlignment(.center)
+ .padding(.horizontal, 40)
+ .padding(.bottom, 32)
+ } else {
+ Text(String(localized: "enter_pin_to_unlock_vault", bundle: locBundle))
+ .font(.system(size: 16))
+ .foregroundColor(theme.text.opacity(0.7))
+ .multilineTextAlignment(.center)
+ .padding(.horizontal, 40)
+ .padding(.bottom, 32)
+ }
+
+ // PIN dots display
+ if let pinLength = viewModel.pinLength {
+ HStack(spacing: 12) {
+ ForEach(0..<pinLength, id: \.self) { index in
+ Circle()
+ .strokeBorder(
+ index < viewModel.pin.count ? theme.primary : theme.accentBorder,
+ lineWidth: 2
+ )
+ .background(
+ Circle()
+ .fill(index < viewModel.pin.count ? theme.primary : Color.clear)
+ )
+ .frame(width: 16, height: 16)
+ }
+ }
+ .padding(.bottom, 24)
+ } else {
+ // For variable length, show bullet points
+ Text(viewModel.pin.isEmpty ? "----" : String(repeating: "•", count: viewModel.pin.count))
+ .font(.system(size: 42, weight: .semibold))
+ .foregroundColor(theme.text)
+ .kerning(8)
+ .frame(minHeight: 48)
+ .padding(.bottom, 24)
+ }
+
+ // Error message
+ if let error = viewModel.error {
+ Text(error)
+ .font(.system(size: 14))
+ .foregroundColor(theme.errorBorder)
+ .multilineTextAlignment(.center)
+ .padding(.horizontal, 40)
+ .padding(.bottom, 12)
+ .transition(.opacity)
+ }
+
+ Spacer()
+
+ // Numpad
+ VStack(spacing: 12) {
+ // Row 1: 1-3
+ HStack(spacing: 12) {
+ ForEach(1...3, id: \.self) { num in
+ NumpadButton(value: "\(num)", theme: theme) {
+ viewModel.addDigit("\(num)")
+ }
+ }
+ }
+
+ // Row 2: 4-6
+ HStack(spacing: 12) {
+ ForEach(4...6, id: \.self) { num in
+ NumpadButton(value: "\(num)", theme: theme) {
+ viewModel.addDigit("\(num)")
+ }
+ }
+ }
+
+ // Row 3: 7-9
+ HStack(spacing: 12) {
+ ForEach(7...9, id: \.self) { num in
+ NumpadButton(value: "\(num)", theme: theme) {
+ viewModel.addDigit("\(num)")
+ }
+ }
+ }
+
+ // Row 4: Empty, 0, Backspace
+ HStack(spacing: 12) {
+ // Empty space
+ Color.clear
+ .frame(height: 60)
+
+ // 0 button
+ NumpadButton(value: "0", theme: theme) {
+ viewModel.addDigit("0")
+ }
+
+ // Backspace button
+ NumpadButton(icon: "delete.left", theme: theme) {
+ viewModel.removeDigit()
+ }
+ }
+ }
+ .padding(.horizontal, 40)
+ .padding(.bottom, 40)
+ }
+ .frame(width: geometry.size.width, height: geometry.size.height)
+ .background(theme.background)
+ .blur(radius: viewModel.isUnlocking ? 2 : 0)
+ .disabled(viewModel.isUnlocking)
+
+ // Loading overlay
+ if viewModel.isUnlocking {
+ ZStack {
+ Color.black.opacity(0.3)
+ .ignoresSafeArea()
+
+ VStack(spacing: 16) {
+ ProgressView()
+ .progressViewStyle(CircularProgressViewStyle(tint: theme.primary))
+ .scaleEffect(1.5)
+
+ Text(String(localized: "unlocking", bundle: locBundle))
+ .font(.system(size: 16, weight: .medium))
+ .foregroundColor(theme.text)
+ }
+ .padding(24)
+ .background(
+ RoundedRectangle(cornerRadius: 16)
+ .fill(theme.accentBackground)
+ )
+ .shadow(color: Color.black.opacity(0.2), radius: 10, x: 0, y: 4)
+ }
+ .transition(.opacity)
+ }
+ }
+ }
+ }
+
+ private var theme: Theme {
+ colorScheme == .dark ? Theme.dark : Theme.light
+ }
+}
+
+/// Numpad button component
+struct NumpadButton: View {
+ let value: String?
+ let icon: String?
+ let theme: Theme
+ let action: () -> Void
+
+ @State private var isPressed = false
+
+ init(value: String, theme: Theme, action: @escaping () -> Void) {
+ self.value = value
+ self.icon = nil
+ self.theme = theme
+ self.action = action
+ }
+
+ init(icon: String, theme: Theme, action: @escaping () -> Void) {
+ self.value = nil
+ self.icon = icon
+ self.theme = theme
+ self.action = action
+ }
+
+ var body: some View {
+ Button(action: {
+ action()
+ }) {
+ ZStack {
+ RoundedRectangle(cornerRadius: 12)
+ .fill(theme.accentBackground)
+
+ // Highlight overlay when pressed
+ if isPressed {
+ RoundedRectangle(cornerRadius: 12)
+ .fill(theme.primary.opacity(0.2))
+ }
+
+ if let value = value {
+ Text(value)
+ .font(.system(size: 24, weight: .semibold))
+ .foregroundColor(theme.text)
+ } else if let icon = icon {
+ Image(systemName: icon)
+ .font(.system(size: 24))
+ .foregroundColor(theme.text)
+ }
+ }
+ .frame(height: 60)
+ }
+ .buttonStyle(NumpadButtonStyle(isPressed: $isPressed))
+ }
+}
+
+/// Custom button style for numpad buttons with press animation
+struct NumpadButtonStyle: ButtonStyle {
+ @Binding var isPressed: Bool
+
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .scaleEffect(configuration.isPressed ? 0.9 : 1.0)
+ .animation(.spring(response: 0.3, dampingFraction: 0.6), value: configuration.isPressed)
+ .onChange(of: configuration.isPressed) { newValue in
+ isPressed = newValue
+ }
+ }
+}
+
+// MARK: - Theme
+
+/// Theme colors matching the React Native app
+struct Theme {
+ let background: Color
+ let text: Color
+ let primary: Color
+ let accentBackground: Color
+ let accentBorder: Color
+ let errorBorder: Color
+
+ static let light = Theme(
+ background: Color(UIColor.systemBackground),
+ text: Color(UIColor.label),
+ primary: ColorConstants.Light.primary,
+ accentBackground: Color(UIColor.secondarySystemBackground),
+ accentBorder: Color(UIColor.separator),
+ errorBorder: Color.red
+ )
+
+ static let dark = Theme(
+ background: Color(UIColor.systemBackground),
+ text: Color(UIColor.label),
+ primary: ColorConstants.Dark.primary,
+ accentBackground: Color(UIColor.secondarySystemBackground),
+ accentBorder: Color(UIColor.separator),
+ errorBorder: Color.red
+ )
+}
+
+// MARK: - ViewModel
+
+/// ViewModel for PIN unlock
+@MainActor
+public class PinUnlockViewModel: ObservableObject {
+ @Published public var pin: String = ""
+ @Published public var error: String?
+ @Published public var isUnlocking: Bool = false
+
+ public let pinLength: Int?
+ private let unlockHandler: (String) async throws -> Void
+ private let cancelHandler: () -> Void
+
+ public init(
+ pinLength: Int?,
+ unlockHandler: @escaping (String) async throws -> Void,
+ cancelHandler: @escaping () -> Void
+ ) {
+ self.pinLength = pinLength
+ self.unlockHandler = unlockHandler
+ self.cancelHandler = cancelHandler
+ }
+
+ public func addDigit(_ digit: String) {
+ // Clear error when user starts typing again
+ error = nil
+
+ // Add digit to PIN
+ if let maxLength = pinLength, pin.count >= maxLength {
+ // Don't add more digits if we've reached max length
+ return
+ }
+
+ pin += digit
+
+ // Auto-submit when PIN reaches expected length
+ if let expectedLength = pinLength, pin.count == expectedLength {
+ // Small delay to show the last dot filled before attempting unlock
+ Task {
+ await attemptUnlock()
+ }
+ }
+ }
+
+ public func removeDigit() {
+ guard !pin.isEmpty else { return }
+ pin.removeLast()
+ error = nil
+ }
+
+ public func cancel() {
+ cancelHandler()
+ }
+
+ private func attemptUnlock() async {
+ // Show loading state
+ isUnlocking = true
+
+ do {
+ // Call the injected unlock handler with the PIN
+ try await unlockHandler(pin)
+ // Success - the handler will navigate away or complete the flow
+ // Keep loading state active since we're navigating
+ } catch let nsError as NSError {
+ // Handle unlock errors
+ isUnlocking = false
+ self.error = nsError.localizedDescription
+ shakeAndClear()
+ } catch let genericError {
+ // Generic error
+ isUnlocking = false
+ self.error = String(localized: "unlock_failed", bundle: locBundle)
+ shakeAndClear()
+ }
+ }
+
+ private func shakeAndClear() {
+ // Clear the PIN after a short delay to show error
+ Task {
+ try? await Task.sleep(nanoseconds: 500_000_000) // 500ms
+ pin = ""
+ }
+ }
+}
diff --git a/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings b/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings
index c309e8f57..5a0d6c72d 100644
Binary files a/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings and b/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings differ
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index d6f1139ed..11e9b4fee 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -89,6 +89,14 @@ export interface Spec extends TurboModule {
isNewVaultVersionAvailable(): Promise<{ isNewVersionAvailable: boolean; newRevision: number | null }>;
downloadVault(newRevision: number): Promise<boolean>;
mutateVault(): Promise<boolean>;
+
+ // PIN unlock methods
+ isPinEnabled(): Promise<boolean>;
+ getPinLength(): Promise<number | null>;
+ unlockWithPin(pin: string): Promise<string>;
+ setupPin(pin: string): Promise<void>;
+ removeAndDisablePin(): Promise<void>;
+ showPinUnlockUI(): Promise<void>;
}
export default TurboModuleRegistry.getEnforcing<Spec>('NativeVaultManager');
diff --git a/apps/mobile-app/utils/PinUnlockService.ts b/apps/mobile-app/utils/PinUnlockService.ts
new file mode 100644
index 000000000..cb0d2e5c8
--- /dev/null
+++ b/apps/mobile-app/utils/PinUnlockService.ts
@@ -0,0 +1,119 @@
+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;
+ }
+}