SPB Git

Repository Public

AppLock.swift 4.2 KB 115 lines swift

1import Foundation2import LocalAuthentication3import Observation45/// Optional local lock (Face ID / Touch ID / device passcode) at launch and after the app went to the background.6/// A convenience for a device left unattended: it never replaces server authentication, and step-up always is a7/// passkey ceremony verified by the server.8@MainActor9@Observable10final class AppLock {11    typealias Evaluator = @Sendable (_ reason: String) async -> Result<Void, LockError>1213    enum LockError: Error, Sendable, Equatable {14        case cancelled15        case unavailable(String)16        case failed(String)17    }1819    static let enabledKey = "mcc.lock.enabled"20    static let graceKey = "mcc.lock.grace"2122    private(set) var isLocked = false23    private(set) var isEvaluating = false24    private(set) var lastError: LockError?25    var isEnabled: Bool {26        didSet { defaults.set(isEnabled, forKey: Self.enabledKey); if !isEnabled { isLocked = false } }27    }28    /// Seconds in the background tolerated before locking again.29    var gracePeriod: TimeInterval {30        didSet { defaults.set(gracePeriod, forKey: Self.graceKey) }31    }3233    @ObservationIgnored private let defaults: UserDefaults34    @ObservationIgnored private let evaluator: Evaluator35    @ObservationIgnored private let now: @Sendable () -> Date36    @ObservationIgnored private var backgroundedAt: Date?3738    init(defaults: UserDefaults = .standard, now: @escaping @Sendable () -> Date = { Date() }, evaluator: @escaping Evaluator = AppLock.systemEvaluator) {39        self.defaults = defaults40        self.evaluator = evaluator41        self.now = now42        isEnabled = defaults.bool(forKey: Self.enabledKey)43        gracePeriod = defaults.object(forKey: Self.graceKey) as? TimeInterval ?? 044    }4546    func lockAtLaunchIfEnabled() { if isEnabled { isLocked = true } }4748    func appDidEnterBackground() {49        guard isEnabled else { return }50        backgroundedAt = now()51        // Lock right away when there is no grace period, so that the app switcher snapshot shows the lock screen.52        if gracePeriod <= 0 { isLocked = true }53    }5455    func appDidBecomeActive() {56        guard isEnabled, let since = backgroundedAt else { return }57        backgroundedAt = nil58        if now().timeIntervalSince(since) >= gracePeriod { isLocked = true }59    }6061    /// Asks the system to verify the device owner. Returns true when unlocked.62    @discardableResult63    func unlock(reason: String) async -> Bool {64        guard isLocked, !isEvaluating else { return !isLocked }65        isEvaluating = true66        defer { isEvaluating = false }67        switch await evaluator(reason) {68        case .success:69            isLocked = false70            lastError = nil71            return true72        case .failure(let e):73            lastError = e == .cancelled ? nil : e74            return false75        }76    }7778    /// Turning the lock on requires passing it once, so that nobody enables a lock the device cannot open.79    func enable(reason: String) async -> Bool {80        switch await evaluator(reason) {81        case .success:82            lastError = nil83            isEnabled = true84            return true85        case .failure(let e):86            lastError = e == .cancelled ? nil : e87            return false88        }89    }9091    /// What the device offers, for the label of the setting.92    static var biometryType: LABiometryType {93        let ctx = LAContext()94        _ = ctx.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil)95        return ctx.biometryType96    }9798    static let systemEvaluator: Evaluator = { reason in99        let ctx = LAContext()100        var err: NSError?101        // Biometrics with the device passcode as fallback.102        guard ctx.canEvaluatePolicy(.deviceOwnerAuthentication, error: &err) else {103            return .failure(.unavailable(err?.localizedDescription ?? ""))104        }105        do {106            try await ctx.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)107            return .success(())108        } catch let e as LAError where e.code == .userCancel || e.code == .appCancel || e.code == .systemCancel {109            return .failure(.cancelled)110        } catch {111            return .failure(.failed(error.localizedDescription))112        }113    }114}115
Files main
Menu

Theme