Repository Public
1// SP Notes iOS2// File: Core/AppLock.swift3// Description: Optional biometric lock of the app on this device (Face ID / Touch ID, device passcode as the system fallback).4// Purely local: nothing biometric ever leaves the device, and the server session is not involved. The "enabled"5// flag is mirrored into the App Group defaults (`WidgetLock`) at launch and at every change, so the widgets show6// a redacted state while the lock is on (2.0; the 1.0 key in the standard defaults stays the source of truth).7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import LocalAuthentication11import Observation12import SwiftUI1314@MainActor15@Observable16final class AppLock {17 enum Biometry { case faceID, touchID, opticID, none }1819 /// The user's choice; stored in the app's defaults (not synced).20 var isEnabled: Bool {21 didSet {22 defaults.set(isEnabled, forKey: Keys.enabled)23 mirror.set(isEnabled)24 if !isEnabled { isLocked = false }25 if oldValue != isEnabled { onEnabledChange?(isEnabled) }26 }27 }28 /// Called when the setting changes (the application model reloads the widget timelines).29 @ObservationIgnored var onEnabledChange: (@MainActor (Bool) -> Void)?30 /// True when this launch changed the mirror read by the widgets (first launch after the 1.0 → 2.0 update with the lock on,31 /// or a mirror that went out of step): the widgets are reloaded once.32 @ObservationIgnored private(set) var mirrorChangedAtLaunch = false33 @ObservationIgnored private let mirror: WidgetLock34 /// Seconds in the background after which the app locks again (0 = immediately).35 var gracePeriod: TimeInterval { didSet { defaults.set(gracePeriod, forKey: Keys.grace) } }36 private(set) var isLocked: Bool37 private(set) var lastError: String?38 private var backgroundedAt: Date?39 private var isAuthenticating = false40 private let defaults: UserDefaults4142 private enum Keys { static let enabled = WidgetLock.enabledKey; static let grace = "lock.grace" }4344 init(defaults: UserDefaults = .standard, mirror: WidgetLock = .shared) {45 self.defaults = defaults46 self.mirror = mirror47 isEnabled = defaults.bool(forKey: Keys.enabled)48 mirrorChangedAtLaunch = mirror.set(defaults.bool(forKey: Keys.enabled))49 gracePeriod = defaults.object(forKey: Keys.grace) as? TimeInterval ?? 6050 isLocked = defaults.bool(forKey: Keys.enabled)51 }5253 /// What the device offers right now. `.none` when no biometry is enrolled: the lock then uses the device passcode alone.54 var biometry: Biometry {55 let context = LAContext()56 var error: NSError?57 guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else { return .none }58 switch context.biometryType {59 case .faceID: return .faceID60 case .touchID: return .touchID61 case .opticID: return .opticID62 default: return .none63 }64 }6566 /// False when the device has neither biometry nor a passcode: the lock cannot be offered at all.67 var canProtect: Bool { LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) }6869 var biometryName: String {70 switch biometry {71 case .faceID: return "Face ID"72 case .touchID: return "Touch ID"73 case .opticID: return "Optic ID"74 case .none: return String(localized: "le code de l’appareil")75 }76 }77 var biometrySymbol: String {78 switch biometry { case .faceID: return "faceid"; case .touchID: return "touchid"; case .opticID: return "opticid"; case .none: return "lock.fill" }79 }8081 func sceneDidEnterBackground() { if isEnabled { backgroundedAt = Date() } }8283 func sceneWillEnterForeground() {84 guard isEnabled, !isLocked else { return }85 if let since = backgroundedAt, Date().timeIntervalSince(since) >= gracePeriod { isLocked = true }86 backgroundedAt = nil87 }8889 /// Asks the system to authenticate the owner of the device. Returns true when unlocked.90 @discardableResult91 func unlock() async -> Bool {92 guard isLocked else { return true }93 guard !isAuthenticating else { return false }94 isAuthenticating = true95 defer { isAuthenticating = false }96 let context = LAContext()97 context.localizedCancelTitle = String(localized: "Annuler")98 var error: NSError?99 guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else {100 // No passcode on the device any more: a lock that cannot be opened would only lose access, so it is lifted.101 isLocked = false102 lastError = nil103 return true104 }105 do {106 let ok = try await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: String(localized: "Déverrouiller tes notes"))107 if ok { isLocked = false; lastError = nil }108 return ok109 } catch let failure as LAError where failure.code == .userCancel || failure.code == .appCancel || failure.code == .systemCancel {110 return false111 } catch {112 lastError = error.localizedDescription113 return false114 }115 }116117 /// Turning the lock off requires the same proof as opening it (someone holding the unlocked phone cannot simply remove it).118 func disable() async -> Bool {119 let context = LAContext()120 if context.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) {121 guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: String(localized: "Désactiver le verrouillage de SP Notes"))) == true else { return false }122 }123 isEnabled = false124 return true125 }126127 /// Turning the lock on requires proving it can be opened.128 func enable() async -> Bool {129 let context = LAContext()130 guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) else { return false }131 guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: String(localized: "Activer le verrouillage de SP Notes"))) == true else { return false }132 isEnabled = true133 isLocked = false134 return true135 }136}137