Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor iOS module dependency order (#1340)
Leendert de Borst74fd6c16569b
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swiftindex 3dde91eca..63e046637 100644--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift@@ -791,14 +791,20 @@ public class VaultManager: NSObject {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)+ } catch let error as PinUnlockError {+ // Handle PinUnlockError with proper error codes and localized messages+ switch error {+ case .notConfigured:+ reject("PIN_NOT_CONFIGURED", "PIN unlock is not configured", nil)+ case .locked:+ reject("PIN_LOCKED", "PIN locked after too many failed attempts", nil)+ case .incorrectPin(let attemptsRemaining):+ let message = "Incorrect PIN. \(attemptsRemaining) attempts remaining"+ reject("INCORRECT_PIN", message, nil)}+ } catch {+ // Fallback for any other errors+ reject("PIN_UNLOCK_ERROR", error.localizedDescription, error)}}diff --git a/apps/mobile-app/ios/VaultModels/PinUnlockError.swift b/apps/mobile-app/ios/VaultModels/PinUnlockError.swiftnew file mode 100644index 000000000..2d35038c7--- /dev/null+++ b/apps/mobile-app/ios/VaultModels/PinUnlockError.swift@@ -0,0 +1,31 @@+import Foundation++/// Error types for PIN unlock operations+/// This is in VaultModels so both VaultStoreKit and VaultUI can access it without circular dependencies+public enum PinUnlockError: Error {+ /// PIN is not configured+ case notConfigured++ /// PIN is locked after too many failed attempts+ case locked++ /// Incorrect PIN with remaining attempts+ case incorrectPin(attemptsRemaining: Int)++ /// Get error code for React Native bridge compatibility+ public var code: String {+ switch self {+ case .notConfigured: return "PIN_NOT_CONFIGURED"+ case .locked: return "PIN_LOCKED"+ case .incorrectPin: return "INCORRECT_PIN"+ }+ }++ /// Get attempts remaining (if applicable)+ public var attemptsRemaining: Int? {+ switch self {+ case .incorrectPin(let remaining): return remaining+ default: return nil+ }+ }+}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swiftindex 80ad58ea4..714695588 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift@@ -2,7 +2,7 @@ import Foundationimport CryptoKitimport Securityimport SignalArgon2-import VaultUI+import VaultModels/// Extension for the VaultStore class to handle PIN unlock functionalityextension VaultStore {@@ -10,6 +10,7 @@ extension VaultStore {private static let pinEncryptedKeyKey = "pinEncryptedKey"private static let pinSaltKey = "pinSalt"+ private static let pinPepperKey = "pinPepper" // Device-bound secretprivate static let pinLengthKey = "pinLength"private static let pinFailedAttemptsKey = "pinFailedAttempts"private static let maxPinAttempts = 4@@ -28,9 +29,9 @@ extension VaultStore {return length > 0 ? length : nil}- /// Get failed attempts count+ /// Get failed attempts count from secure storagepublic func getPinFailedAttempts() -> Int {- return userDefaults.integer(forKey: Self.pinFailedAttemptsKey)+ return (try? retrievePinFailedAttemptsFromKeychain()) ?? 0}// MARK: - PIN Setup Methods@@ -40,7 +41,7 @@ extension VaultStore {/// The encryption key is retrieved internally and never exposed to React Native layer////// - Parameters:- /// - pin: The PIN to set (4-8 digits)+ /// - pin: The PIN to set (4+ digits)/// - Throws: Error if PIN is invalid, vault not unlocked, or encryption failspublic func setupPin(_ pin: String) throws {// Get vault encryption key from memory (vault must be unlocked)@@ -55,8 +56,11 @@ extension VaultStore {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)+ // Generate or retrieve device pepper (device-bound secret)+ let pepper = try getOrCreateDevicePepper()++ // Derive key from PIN + pepper using Argon2id+ let pinKey = try derivePinKey(pin: pin, salt: salt, pepper: pepper)// Encrypt the vault encryption key using AES-GCMlet symmetricKey = SymmetricKey(data: pinKey)@@ -68,13 +72,15 @@ extension VaultStore {// Store encrypted key and salt in keychain (without biometric protection)try storePinDataInKeychain(encryptedKey: encryptedData, salt: salt)- // Store PIN metadata in UserDefaults+ // Initialize failed attempts counter in Keychain+ try storePinFailedAttemptsInKeychain(0)++ // Store PIN metadata in UserDefaults (non-sensitive data only)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")+ print("PIN unlock enabled successfully with device pepper")}// MARK: - PIN Unlock Methods@@ -84,23 +90,20 @@ extension VaultStore {////// - 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+ /// - Throws: PinUnlockError with specific error type and metadatapublic 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 clearedguard isPinEnabled() else {- throw NSError(domain: "VaultStore", code: 25, userInfo: [- NSLocalizedDescriptionKey: NSLocalizedString("pin_not_configured", bundle: Bundle.vaultUI, comment: "PIN not configured error")- ])+ throw PinUnlockError.notConfigured}do {- // Retrieve encrypted key and salt from keychain+ // Retrieve encrypted key, salt, and pepper from keychainlet (encryptedKey, salt) = try retrievePinDataFromKeychain()+ let pepper = try retrieveDevicePepper()- // Derive key from PIN- let pinKey = try derivePinKey(pin: pin, salt: salt)+ // Derive key from PIN + pepper+ let pinKey = try derivePinKey(pin: pin, salt: salt, pepper: pepper)// Decrypt the vault encryption keylet symmetricKey = SymmetricKey(data: pinKey)@@ -108,8 +111,7 @@ extension VaultStore {let decryptedKey = try AES.GCM.open(sealedBox, using: symmetricKey)// Reset failed attempts on success- userDefaults.set(0, forKey: Self.pinFailedAttemptsKey)- userDefaults.synchronize()+ try storePinFailedAttemptsInKeychain(0)// Return the decrypted vault encryption key as base64return decryptedKey.base64EncodedString()@@ -117,35 +119,23 @@ extension VaultStore {// Increment failed attemptslet currentAttempts = getPinFailedAttempts()let newAttempts = currentAttempts + 1- userDefaults.set(newAttempts, forKey: Self.pinFailedAttemptsKey)- userDefaults.synchronize()+ try? storePinFailedAttemptsInKeychain(newAttempts)// If max attempts reached, disable PIN and clear all stored dataif newAttempts >= Self.maxPinAttempts {try? removeAndDisablePin()- throw NSError(domain: "VaultStore", code: 26, userInfo: [- NSLocalizedDescriptionKey: NSLocalizedString("pin_locked_max_attempts", bundle: Bundle.vaultUI, comment: "PIN locked error")- ])+ throw PinUnlockError.locked}// Return incorrect PIN error with attempts remaininglet attemptsRemaining = Self.maxPinAttempts - newAttempts- let localizedMessage = String(- format: NSLocalizedString("pin_incorrect_attempts_remaining", bundle: Bundle.vaultUI, comment: "Incorrect PIN with attempts remaining"),- attemptsRemaining- )- throw NSError(domain: "VaultStore", code: 27, userInfo: [- NSLocalizedDescriptionKey: localizedMessage,- "attemptsRemaining": attemptsRemaining- ])+ throw PinUnlockError.incorrectPin(attemptsRemaining: attemptsRemaining)}}- /// Reset failed attempts counter- /// Called after successful password unlock+ /// Reset failed attempts counter (called after successful password unlock)public func resetPinFailedAttempts() {- userDefaults.set(0, forKey: Self.pinFailedAttemptsKey)- userDefaults.synchronize()+ try? storePinFailedAttemptsInKeychain(0)}/// Disable PIN unlock and remove all stored data@@ -153,39 +143,52 @@ extension VaultStore {// Remove PIN data from keychaintry removePinDataFromKeychain()+ // Remove failed attempts counter from keychain+ try removePinFailedAttemptsFromKeychain()++ // Note: We DO NOT remove the device pepper - it's reused if PIN is re-enabled+ // This maintains consistency and doesn't degrade security+// Clear PIN metadata from UserDefaultsuserDefaults.removeObject(forKey: VaultConstants.pinEnabledKey)userDefaults.removeObject(forKey: Self.pinLengthKey)- userDefaults.removeObject(forKey: Self.pinFailedAttemptsKey)userDefaults.synchronize()- print("PIN unlock disabled and all data removed")+ print("PIN unlock disabled and all data removed (pepper retained)")}// MARK: - Private PIN Methods- /// Derive encryption key from PIN using Argon2id+ /// Derive encryption key from PIN + pepper using Argon2id+ ///+ /// Uses Argon2id with high memory cost (64 MB) and a device-bound pepper+ /// to make offline brute-force attacks infeasible even if the encrypted blob is exfiltrated.///- /// 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.+ /// The pepper is a 32-byte random value stored in the Secure Enclave-protected Keychain,+ /// which means an attacker who steals the encrypted blob cannot brute-force offline+ /// because they don't have the pepper.///- /// 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 {+ /// Parameters:+ /// - pin: User's PIN (low entropy)+ /// - salt: Random salt (stored with encrypted data)+ /// - pepper: Device-bound secret+ private func derivePinKey(pin: String, salt: Data, pepper: 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+ // Concatenate PIN + pepper before hashing+ // This ensures offline brute-force is impossible without the pepper+ var combinedInput = Data()+ combinedInput.append(pinData)+ combinedInput.append(pepper)++ // Use SignalArgon2 to hash (PIN + pepper) via Argon2idguard let derivedKeyTuple = try? Argon2.hash(iterations: 3,memoryInKiB: 65536, // 64 MBthreads: 1,- password: pinData,+ password: combinedInput,salt: salt,desiredLength: 32,variant: .id,@@ -197,9 +200,74 @@ extension VaultStore {return derivedKeyTuple.raw}+ /// Get or create device pepper (device-bound secret)+ ///+ /// The pepper is a 32-byte random value stored in Keychain with Secure Enclave protection.+ /// It's only readable when the device is unlocked (passcode entered), but can be cached in memory.+ /// This prevents offline brute-force when only the encrypted blob would be captured.+ private func getOrCreateDevicePepper() throws -> Data {+ // Try to retrieve existing pepper+ if let pepper = try? retrieveDevicePepper() {+ return pepper+ }++ // Generate new 32-byte pepper+ var pepper = Data(count: 32)+ let result = pepper.withUnsafeMutableBytes {+ SecRandomCopyBytes(kSecRandomDefault, 32, $0.baseAddress!)+ }+ guard result == errSecSuccess else {+ throw NSError(domain: "VaultStore", code: 36, userInfo: [NSLocalizedDescriptionKey: "Failed to generate device pepper"])+ }++ // Store pepper in Keychain with device passcode protection+ // This uses kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly which provides:+ // 1. Device-bound (cannot be moved to another device)+ // 2. Requires passcode to be set+ // 3. Available when device is unlocked+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: VaultConstants.keychainService,+ kSecAttrAccount as String: Self.pinPepperKey,+ kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup,+ kSecValueData as String: pepper,+ kSecAttrAccessible as String: kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly+ ]++ let status = SecItemAdd(query as CFDictionary, nil)+ guard status == errSecSuccess else {+ throw NSError(domain: "VaultStore", code: 37, userInfo: [NSLocalizedDescriptionKey: "Failed to store device pepper: \(status)"])+ }++ print("Device pepper created and stored securely")+ return pepper+ }++ /// Retrieve device pepper from Keychain+ private func retrieveDevicePepper() throws -> Data {+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: VaultConstants.keychainService,+ kSecAttrAccount as String: Self.pinPepperKey,+ 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 pepper = result as? Data else {+ throw NSError(domain: "VaultStore", code: 38, userInfo: [NSLocalizedDescriptionKey: "Device pepper not found"])+ }++ return pepper+ }+/// 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+ // Note: We DO NOT store the pepper here - it's separate for securitylet pinData: [String: Data] = ["encryptedKey": encryptedKey,"salt": salt@@ -270,4 +338,66 @@ extension VaultStore {throw NSError(domain: "VaultStore", code: 34, userInfo: [NSLocalizedDescriptionKey: "Failed to remove PIN data from keychain: \(status)"])}}++ // MARK: - Failed Attempts Counter (Keychain Storage)++ /// Store failed attempts counter in Keychain (not UserDefaults)+ private func storePinFailedAttemptsInKeychain(_ attempts: Int) throws {+ let attemptsData = withUnsafeBytes(of: attempts) { Data($0) }++ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: VaultConstants.keychainService,+ kSecAttrAccount as String: Self.pinFailedAttemptsKey,+ kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup,+ kSecValueData as String: attemptsData,+ 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: 39, userInfo: [NSLocalizedDescriptionKey: "Failed to store attempts counter: \(status)"])+ }+ }++ /// Retrieve failed attempts counter from Keychain+ private func retrievePinFailedAttemptsFromKeychain() throws -> Int {+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: VaultConstants.keychainService,+ kSecAttrAccount as String: Self.pinFailedAttemptsKey,+ 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 {+ // Return 0 if not found+ return 0+ }++ return data.withUnsafeBytes { $0.load(as: Int.self) }+ }++ /// Remove failed attempts counter from Keychain+ private func removePinFailedAttemptsFromKeychain() throws {+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: VaultConstants.keychainService,+ kSecAttrAccount as String: Self.pinFailedAttemptsKey,+ kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup+ ]++ let status = SecItemDelete(query as CFDictionary)+ guard status == errSecSuccess || status == errSecItemNotFound else {+ throw NSError(domain: "VaultStore", code: 40, userInfo: [NSLocalizedDescriptionKey: "Failed to remove attempts counter: \(status)"])+ }+ }}diff --git a/apps/mobile-app/ios/VaultUI/Auth/PinUnlockView.swift b/apps/mobile-app/ios/VaultUI/Auth/PinUnlockView.swiftindex 22869b6cf..3a497c992 100644--- a/apps/mobile-app/ios/VaultUI/Auth/PinUnlockView.swift+++ b/apps/mobile-app/ios/VaultUI/Auth/PinUnlockView.swift@@ -1,4 +1,5 @@import SwiftUI+import VaultModelsimport UIKitprivate let locBundle = Bundle.vaultUI@@ -341,13 +342,13 @@ public class PinUnlockViewModel: ObservableObject {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 {- // Check for PIN disabled/locked errors (error codes 25 or 26)- // These occur when PIN was disabled due to max attempts or configuration issue- if nsError.code == 25 || nsError.code == 26 {- // Show the error message briefly before auto-dismissing+ } catch let pinError as PinUnlockError {+ // Handle PinUnlockError with localized messages+ switch pinError {+ case .notConfigured:+ // PIN was disabled/not configuredisUnlocking = false- self.error = nsError.localizedDescription+ self.error = String(localized: "pin_not_configured", bundle: locBundle)triggerErrorFeedback()// Wait to let user see the error message@@ -357,15 +358,31 @@ public class PinUnlockViewModel: ObservableObject {self.error = nilcancelHandler()return- }- // Handle other unlock errors (incorrect PIN, etc.)- isUnlocking = false- self.error = nsError.localizedDescription- triggerErrorFeedback()- shakeAndClear()- } catch let genericError {- // Generic error+ case .locked:+ // PIN locked after too many attempts+ isUnlocking = false+ self.error = String(localized: "pin_locked_max_attempts", bundle: locBundle)+ triggerErrorFeedback()++ // Wait to let user see the error message+ try? await Task.sleep(nanoseconds: 1_000_000_000) // 1 second++ // Clear the error and dismiss+ self.error = nil+ cancelHandler()+ return++ case .incorrectPin(let attemptsRemaining):+ // Incorrect PIN - show attempts remaining+ isUnlocking = false+ self.error = String(localized: "pin_incorrect_attempts_remaining", bundle: locBundle)+ .replacingOccurrences(of: "%d", with: "\(attemptsRemaining)")+ triggerErrorFeedback()+ shakeAndClear()+ }+ } catch {+ // Generic error fallbackisUnlocking = falseself.error = String(localized: "unlock_failed", bundle: locBundle)triggerErrorFeedback()