Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatSecurity/Sources/AppLock.swift3// Description: Optional Face ID / Touch ID application lock (passcode fallback) with a background grace period.4import Foundation5import LocalAuthentication6import Observation78/// What AppLock needs from LocalAuthentication; injectable for tests.9public protocol LockAuthenticating: Sendable {10 func canAuthenticate() -> (available: Bool, biometry: AppLock.Biometry, reason: String?)11 func authenticate(reason: String) async throws -> Bool12}1314public struct SystemLockAuthenticator: LockAuthenticating {15 public init() {}16 public func canAuthenticate() -> (available: Bool, biometry: AppLock.Biometry, reason: String?) {17 let context = LAContext(); var error: NSError?18 let ok = context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error)19 let biometry: AppLock.Biometry = switch context.biometryType {20 case .faceID: .faceID21 case .touchID: .touchID22 case .opticID: .opticID23 default: .none24 }25 return (ok, biometry, error?.localizedDescription)26 }27 public func authenticate(reason: String) async throws -> Bool {28 // deviceOwnerAuthentication = biometrics first, then the device passcode / password29 try await LAContext().evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)30 }31}3233@MainActor @Observable34public final class AppLock {35 public enum State: Sendable, Equatable { case unlocked, locked, unlocking }36 public enum Biometry: String, Sendable { case none, touchID, faceID, opticID37 public var label: String { switch self { case .none: "Passcode"; case .touchID: "Touch ID"; case .faceID: "Face ID"; case .opticID: "Optic ID" } }38 public var symbol: String { switch self { case .none: "lock"; case .touchID: "touchid"; case .faceID: "faceid"; case .opticID: "opticid" } }39 }4041 public private(set) var state: State = .unlocked42 public private(set) var lastError: String?43 public var isEnabled: Bool { didSet { if !isEnabled { state = .unlocked } } }44 public var gracePeriod: TimeInterval4546 private let authenticator: any LockAuthenticating47 private let now: @Sendable () -> Date48 private var backgroundedAt: Date?4950 public init(isEnabled: Bool = false, gracePeriod: TimeInterval = 60, lockAtLaunch: Bool = true,51 authenticator: any LockAuthenticating = SystemLockAuthenticator(), now: @escaping @Sendable () -> Date = { Date() }) {52 self.isEnabled = isEnabled; self.gracePeriod = gracePeriod; self.authenticator = authenticator; self.now = now53 if isEnabled && lockAtLaunch { state = .locked }54 }5556 public var isLocked: Bool { state != .unlocked }57 public var availability: (available: Bool, biometry: Biometry, reason: String?) { authenticator.canAuthenticate() }5859 public func lock() { if isEnabled { state = .locked } }6061 public func didEnterBackground() { if isEnabled, state == .unlocked { backgroundedAt = now() } }6263 public func willEnterForeground() {64 guard isEnabled, let since = backgroundedAt else { return }65 backgroundedAt = nil66 if now().timeIntervalSince(since) >= gracePeriod { state = .locked }67 }6869 /// Returns true when the app is unlocked afterwards.70 @discardableResult71 public func unlock(reason: String = "Unlock Local Chat") async -> Bool {72 guard isEnabled, state == .locked else { return state == .unlocked }73 state = .unlocking; lastError = nil74 do {75 let ok = try await authenticator.authenticate(reason: reason)76 state = ok ? .unlocked : .locked77 } catch {78 lastError = (error as? LAError)?.code == .userCancel ? nil : error.localizedDescription79 state = .locked80 }81 return state == .unlocked82 }8384 /// Turning the lock on requires a successful authentication first, so the user cannot lock themselves out.85 public func enable() async -> Bool {86 guard availability.available else { lastError = availability.reason ?? "No passcode or biometrics are set up on this device."; return false }87 do {88 guard try await authenticator.authenticate(reason: "Turn on the Local Chat lock") else { return false }89 isEnabled = true; state = .unlocked; return true90 } catch { lastError = error.localizedDescription; return false }91 }92}93