Skip to content

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

8.0 KB
Raw Blame
import Foundation
import RustCoreFramework
import UIKit
import LocalAuthentication
import CryptoKit
import Security
import VaultModels
import VaultUtils

/// This class is used to store and retrieve the encrypted AliasVault database and encryption key.
/// It also handles executing queries against the SQLite database and biometric authentication.
///
/// This class is used by both the iOS Autofill extension and the React Native app and is the lowest
/// level where all important data is stored and retrieved from.
public class VaultStore {
    /// A shared instance of the VaultStore class that can be used to access the vault which does
    /// require re-authentication every time the vault is accessed.
    public static let shared = VaultStore()

    /// The user defaults using the shared container which is accessible by both the React Native
    /// app and the iOS Autofill extension.
    internal let userDefaults = UserDefaults(suiteName: VaultConstants.userDefaultsSuite)!

    /// The enabled authentication methods for the vault.
    internal var enabledAuthMethods: AuthMethods = []

    /// The auto-lock timeout for the vault.
    internal var autoLockTimeout: Int = VaultConstants.defaultAutoLockTimeout

    /// The database connection for the decrypted in-memory vault.
    /// The live vault, held in the Rust core's memory. Nil while vault is locked.
    internal var dbConnection: SqliteMemoryDatabase?

    /// The modification date of the stored vault file the live database was loaded from or last written to.
    internal var loadedVaultStamp: Date?

    /// The Account Key the unlocked session holds and the keychain and PIN protect (see `VaultStore+LegacyKeyConversion`).
    internal var accountKey: Data?

    /// The encryption key for the vault, derived from the Account Key. Nil while the vault is locked.
    internal var encryptionKey: Data? {
        return sessionKeys?.vaultEncryptionKey
    }

    /// The account private key (JWK) of the unlocked session, derived from the Account Key.
    internal var accountPrivateKey: String? {
        return sessionKeys?.accountPrivateKey
    }

    /// The Account Key of the unlocked session (base64), which the sync engine opens the signing key with.
    internal var accountKeyBase64: String? {
        return sessionKeys?.accountKey.base64EncodedString()
    }

    /// What the session key opens in the cached account key chain. A session opened before the device had a chain holds the
    /// unlock key, which still opens it as such once a sync caches the chain (see `VaultStore+LegacyKeyConversion`).
    private var sessionKeys: SessionKeys? {
        guard let accountKey = accountKey else {
            return nil
        }
        // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.
        return try? openStoredKey(accountKey)
    }

    /// Last successful biometric/PIN auth operation.
    private var lastSuccessfulAuthAt: TimeInterval?

    /// Lock for accessing the last successful auth operation.
    private let authRecencyLock = NSLock()

    /// Maximum window of time for which a recent-auth grace can be honored, regardless of caller input.
    private static let maxAuthRecencyWindowSeconds: Double = 15.0

    /// The key derivation parameters used to derive the encryption key from the password.
    internal var keyDerivationParams: String?

    /// The sync operations on this store (the wrapper around the Rust sync engine).
    internal lazy var sync = VaultSync(vaultStore: self)

    /// The timer for the auto-lock timeout.
    private var clearCacheTimer: Timer?

    /// Initialize the VaultStore
    public init() {
        excludeSharedContainerFromBackup()
        loadSavedSettings()
        setupNotificationObservers()
    }

    /// Deinitialize the VaultStore
    deinit {
        NotificationCenter.default.removeObserver(self)
        self.clearCacheTimer?.invalidate()
    }

    /// Whether the vault is currently unlocked
    public var isVaultUnlocked: Bool {
        return accountKey != nil
    }

    // MARK: - Authentication Recency

    /// Mark successful authorization call to be used for future recency checks.
    internal func markSuccessfulAuth() {
        authRecencyLock.lock()
        lastSuccessfulAuthAt = ProcessInfo.processInfo.systemUptime
        authRecencyLock.unlock()
    }

    /// Invalidate the recency timestamp. Must be called whenever the encryption key is cleared
    /// (lock, sign-out, auto-lock) so the grace window cannot outlive the unlocked state.
    internal func clearLastSuccessfulAuth() {
        authRecencyLock.lock()
        lastSuccessfulAuthAt = nil
        authRecencyLock.unlock()
    }

    /// Check if we're within the recency window for last successful auth attempt.
    public func wasRecentlyAuthenticated(_ maxRecencySeconds: Double) -> Bool {
        guard maxRecencySeconds > 0 else { return false }
        let effectiveWindow = min(maxRecencySeconds, Self.maxAuthRecencyWindowSeconds)
        authRecencyLock.lock()
        let last = lastSuccessfulAuthAt
        authRecencyLock.unlock()
        guard let last = last else { return false }
        return ProcessInfo.processInfo.systemUptime - last < effectiveWindow
    }

    /// Exclude the entire shared app group container from iCloud and iTunes backups.
    /// All app data (encrypted vault database, UserDefaults plist with auth tokens and key
    /// derivation parameters) is security-sensitive and device-bound. Note: actual encryption keys
    /// are stored separately in the Keychain with ThisDeviceOnly accessibility.
    private func excludeSharedContainerFromBackup() {
        guard var containerURL = FileManager.default.containerURL(
            forSecurityApplicationGroupIdentifier: VaultConstants.userDefaultsSuite
        ) else {
            return
        }

        var resourceValues = URLResourceValues()
        resourceValues.isExcludedFromBackup = true
        try? containerURL.setResourceValues(resourceValues)
    }

    private func loadSavedSettings() {
        if userDefaults.object(forKey: VaultConstants.authMethodsKey) != nil {
            let savedRawValue = userDefaults.integer(forKey: VaultConstants.authMethodsKey)
            self.enabledAuthMethods = AuthMethods(rawValue: savedRawValue)
        }

        if userDefaults.object(forKey: VaultConstants.autoLockTimeoutKey) != nil {
            self.autoLockTimeout = userDefaults.integer(forKey: VaultConstants.autoLockTimeoutKey)
        }

        if let savedParams = userDefaults.string(forKey: VaultConstants.unlockKeyDerivationParamsKey) {
            self.keyDerivationParams = savedParams
        }
    }

    private func setupNotificationObservers() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(appDidEnterBackground),
            name: UIApplication.didEnterBackgroundNotification,
            object: nil
        )

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(appWillEnterForeground),
            name: UIApplication.willEnterForegroundNotification,
            object: nil
        )
    }

    // MARK: - Background/Foreground Handling
    @objc private func appDidEnterBackground() {
        print("App entered background, starting auto-lock timer with \(autoLockTimeout) seconds")
        clearLastSuccessfulAuth()
        if self.autoLockTimeout > 0 {
            self.clearCacheTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(self.autoLockTimeout), repeats: false) { [weak self] _ in
                print("Auto-lock timer fired, clearing cache")
                self?.clearCache()
            }
        }
    }

    @objc private func appWillEnterForeground() {
        print("App will enter foreground, canceling clear cache timer")

        if let timer = self.clearCacheTimer, timer.fireDate < Date() {
            print("Timer has elapsed, cache should have been cleared already when app was in background, but clearing it again to be sure")
            clearCache()
        }

        self.clearCacheTimer?.invalidate()
        self.clearCacheTimer = nil
    }
}