SPB Git

Repository Public

AppLock.swift 2.4 KB 65 lines swift

1import Foundation2import LocalAuthentication3import Observation45/// Optional local lock (Touch ID / the Mac's password) at launch and after inactivity.6///7/// A convenience for a Mac left unattended, nothing more: it never replaces the server's authentication, and a8/// sensitive operation still requires the passkey step-up that the server verifies. Unlocking here grants nothing9/// on the server.10@MainActor11@Observable12final class AppLock {13    static let enabledKey = "mcc.lock.enabled"14    static let idleKey = "mcc.lock.idleMinutes"1516    private(set) var isLocked = false17    private(set) var lastError: String?18    var isEnabled: Bool {19        didSet { UserDefaults.standard.set(isEnabled, forKey: Self.enabledKey); if !isEnabled { isLocked = false } }20    }21    var idleMinutes: Int {22        didSet { UserDefaults.standard.set(idleMinutes, forKey: Self.idleKey) }23    }24    @ObservationIgnored private var lastActivity = Date()25    @ObservationIgnored private let disabled: Bool2627    init(disabled: Bool = false) {28        self.disabled = disabled29        isEnabled = !disabled && UserDefaults.standard.bool(forKey: Self.enabledKey)30        let m = UserDefaults.standard.integer(forKey: Self.idleKey)31        idleMinutes = m > 0 ? m : 1032        isLocked = isEnabled33    }3435    var isAvailable: Bool {36        var error: NSError?37        return LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: &error)38    }3940    func noteActivity(now: Date = Date()) { lastActivity = now }4142    /// Called when the app becomes active again: locks if it stayed idle longer than the chosen delay.43    func evaluateIdle(now: Date = Date()) {44        guard isEnabled, !isLocked else { return }45        if now.timeIntervalSince(lastActivity) >= Double(idleMinutes) * 60 { isLocked = true }46    }4748    func lockNow() { if isEnabled { isLocked = true } }4950    func unlock(reason: String) async {51        guard isLocked else { return }52        let context = LAContext()53        do {54            if try await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason) {55                isLocked = false56                lastError = nil57                lastActivity = Date()58            }59        } catch {60            let code = (error as? LAError)?.code61            lastError = (code == .userCancel || code == .appCancel || code == .systemCancel) ? nil : error.localizedDescription62        }63    }64}65
Files main
Menu

Theme