Repository Public
1//2// VQuant iOS3// File: VQuant/Auth/AppLock.swift4// Description: Biometric lock of the app (Face ID / Touch ID, device passcode as fallback) with LocalAuthentication.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation11import LocalAuthentication12import Observation1314/// Local lock of the app's windows. It protects what is already on the device from someone holding the unlocked15/// phone. It is not server authentication: the server trusts the device session, which only a passkey can open, and16/// asks for a passkey again before sensitive operations. Nothing biometric leaves the device — LocalAuthentication17/// answers yes or no.18@MainActor19@Observable20final class AppLock {21 enum Grace: Int, CaseIterable, Identifiable, Sendable {22 case immediately = 0, oneMinute = 60, fiveMinutes = 300, fifteenMinutes = 90023 var id: Int { rawValue }24 var label: String {25 switch self { case .immediately: "Immédiatement"; case .oneMinute: "Après 1 minute"; case .fiveMinutes: "Après 5 minutes"; case .fifteenMinutes: "Après 15 minutes" }26 }27 }28 private(set) var isLocked = false29 private(set) var isAuthenticating = false30 private(set) var lastError: String?31 /// True while the app is not active: the content is covered in the app switcher.32 var isObscured = false3334 private(set) var isEnabled: Bool35 var grace: Grace { didSet { defaults.set(grace.rawValue, forKey: Keys.grace) } }3637 private let defaults: UserDefaults38 private let evaluator: @Sendable (String) async -> Result<Bool, LockFailure>39 private var backgroundedAt: Date?40 private enum Keys { static let enabled = "applock.enabled"; static let grace = "applock.grace" }41 enum LockFailure: Error, Sendable { case unavailable, cancelled, refused }4243 init(defaults: UserDefaults = .standard, evaluator: (@Sendable (String) async -> Result<Bool, LockFailure>)? = nil) {44 self.defaults = defaults45 self.evaluator = evaluator ?? AppLock.systemEvaluator46 isEnabled = defaults.bool(forKey: Keys.enabled)47 grace = Grace(rawValue: defaults.integer(forKey: Keys.grace)) ?? .immediately48 isLocked = isEnabled49 }5051 static var biometryName: String {52 let ctx = LAContext(); _ = ctx.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)53 switch ctx.biometryType {54 case .faceID: return "Face ID"55 case .touchID: return "Touch ID"56 case .opticID: return "Optic ID"57 default: return "le code de l’appareil"58 }59 }60 static var biometrySymbol: String {61 let ctx = LAContext(); _ = ctx.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)62 switch ctx.biometryType { case .faceID: return "faceid"; case .touchID: return "touchid"; case .opticID: return "opticid"; default: return "lock" }63 }64 /// Biometrics, or at least a device passcode.65 static var canAuthenticate: Bool { LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) }6667 func didEnterBackground(now: Date = Date()) { backgroundedAt = now }6869 func willEnterForeground(now: Date = Date()) {70 guard isEnabled, let t = backgroundedAt else { return }71 if now.timeIntervalSince(t) >= Double(grace.rawValue) { isLocked = true }72 backgroundedAt = nil73 }7475 /// Turning the lock on or off requires passing it (the app must not lock its owner out, nor be unlocked by a passer-by).76 @discardableResult77 func setEnabled(_ on: Bool) async -> Bool {78 guard await evaluate(reason: on ? "Activer le verrouillage de VQuant" : "Désactiver le verrouillage de VQuant") else { return false }79 isEnabled = on; isLocked = false80 defaults.set(on, forKey: Keys.enabled)81 return true82 }8384 func unlock() async {85 guard isLocked, !isAuthenticating else { return }86 if await evaluate(reason: "Déverrouiller VQuant") { isLocked = false; lastError = nil }87 }8889 /// Local confirmation before an action that changes account data from this device.90 func confirm(_ reason: String) async -> Bool {91 guard Self.canAuthenticate else { return true } // no passcode on the device: the system offers nothing to ask92 return await evaluate(reason: reason)93 }9495 /// Right after a passkey sign-in the lock is switched on by default (the owner has just proved presence). It96 /// remains a choice: turned off in Settings, it stays off.97 func enableByDefaultAfterSignIn() {98 guard defaults.object(forKey: Keys.enabled) == nil, Self.canAuthenticate else { return }99 isEnabled = true; isLocked = false100 defaults.set(true, forKey: Keys.enabled)101 }102103 func reset() {104 isEnabled = false; isLocked = false; backgroundedAt = nil105 defaults.removeObject(forKey: Keys.enabled)106 }107108 private func evaluate(reason: String) async -> Bool {109 isAuthenticating = true; defer { isAuthenticating = false }110 switch await evaluator(reason) {111 case .success(let ok): return ok112 case .failure(.unavailable): lastError = "Aucun code ni biométrie n’est configuré sur cet appareil."; return false113 case .failure(.refused): lastError = "Vérification refusée."; return false114 case .failure(.cancelled): return false115 }116 }117118 private static let systemEvaluator: @Sendable (String) async -> Result<Bool, LockFailure> = { reason in119 let ctx = LAContext()120 ctx.localizedCancelTitle = "Annuler"121 // deviceOwnerAuthentication: biometrics first, the device passcode as the system fallback122 guard ctx.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) else { return .failure(.unavailable) }123 do { return .success(try await ctx.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) }124 catch let e as LAError { return .failure([.userCancel, .appCancel, .systemCancel].contains(e.code) ? .cancelled : .refused) }125 catch { return .failure(.refused) }126 }127}128