Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Claude Remote / Codex Remote9// File : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteAuth/BiometricLock.swift10// Module : ClaudeRemoteAuth11// Repository : https://git.spboucher.ai/claude-remote-apple12// Project Website : https://claude.spboucher.ai13// Created : 2026-11-2914// Last Modified : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import LocalAuthentication90import Observation9192public enum BiometryKind: String, Sendable, Hashable {93 case none, touchID, faceID, opticID94 public var displayName: String {95 switch self {96 case .none: "Passcode"97 case .touchID: "Touch ID"98 case .faceID: "Face ID"99 case .opticID: "Optic ID"100 }101 }102 public var symbolName: String {103 switch self {104 case .none: "lock"105 case .touchID: "touchid"106 case .faceID: "faceid"107 case .opticID: "opticid"108 }109 }110}111112public enum LocalAuthError: Error, Hashable, Sendable {113 /// The user dismissed the prompt.114 case cancelled115 /// Neither biometrics nor a device passcode/password is set up.116 case unavailable117 case failed118}119120/// Device-owner verification (LocalAuthentication), abstracted for tests. This is LOCAL121/// protection of the app's UI; it is unrelated to the server session.122public protocol LocalAuthenticating: Sendable {123 /// Biometry offered by this device (`.none` = passcode / password only).124 func biometry() -> BiometryKind125 /// Whether the device owner can be verified at all (biometrics or passcode).126 func canAuthenticate() -> Bool127 /// Prompts for biometrics with passcode fallback. Throws `LocalAuthError`.128 func authenticate(reason: String) async throws129}130131public struct SystemLocalAuthenticator: LocalAuthenticating {132 public init() {}133134 public func biometry() -> BiometryKind {135 let context = LAContext()136 _ = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)137 switch context.biometryType {138 case .touchID: return .touchID139 case .faceID: return .faceID140 case .opticID: return .opticID141 default: return .none142 }143 }144145 public func canAuthenticate() -> Bool {146 LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil)147 }148149 public func authenticate(reason: String) async throws {150 let context = LAContext()151 var error: NSError?152 guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else { throw LocalAuthError.unavailable }153 do {154 guard try await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason) else { throw LocalAuthError.failed }155 } catch let e as LAError {156 switch e.code {157 case .userCancel, .appCancel, .systemCancel: throw LocalAuthError.cancelled158 case .passcodeNotSet, .biometryNotAvailable, .biometryNotEnrolled: throw LocalAuthError.unavailable159 default: throw LocalAuthError.failed160 }161 }162 }163}164165/// App lock: Face ID / Touch ID (passcode fallback) in front of the UI, with auto-lock after a166/// period of inactivity. Purely local — it neither replaces nor refreshes the server session.167///168/// lock.appDidEnterBackground() // scene phase .background169/// lock.appWillEnterForeground() // scene phase .active → locks if the timeout elapsed170/// if lock.isLocked { LockScreen { try await lock.unlock() } }171@MainActor172@Observable173public final class BiometricLock {174 public private(set) var isLocked: Bool175 /// User preference (stored in `UserDefaults`: it is not a secret).176 public var isEnabled: Bool {177 didSet {178 defaults.set(isEnabled, forKey: Keys.enabled)179 if !isEnabled { isLocked = false }180 }181 }182 /// Inactivity after which the app locks. 0 = lock every time the app leaves the foreground.183 public var timeout: TimeInterval {184 didSet { defaults.set(timeout, forKey: Keys.timeout) }185 }186 public private(set) var isAuthenticating = false187 public var biometry: BiometryKind { authenticator.biometry() }188 /// False when the device has neither biometrics nor a passcode: the lock cannot be enabled.189 public var isAvailable: Bool { authenticator.canAuthenticate() }190191 @ObservationIgnored private let authenticator: any LocalAuthenticating192 @ObservationIgnored private let defaults: UserDefaults193 @ObservationIgnored private let now: @Sendable () -> Date194 @ObservationIgnored private var lastActiveAt: Date195196 private enum Keys {197 static let enabled = "cr.lock.enabled"198 static let timeout = "cr.lock.timeout"199 }200201 public static let timeoutChoices: [TimeInterval] = [0, 60, 5 * 60, 15 * 60, 60 * 60]202203 public init(authenticator: any LocalAuthenticating = SystemLocalAuthenticator(), defaults: UserDefaults = .standard,204 now: @escaping @Sendable () -> Date = { Date() }) {205 self.authenticator = authenticator206 self.defaults = defaults207 self.now = now208 let enabled = defaults.bool(forKey: Keys.enabled)209 isEnabled = enabled210 timeout = defaults.object(forKey: Keys.timeout) as? TimeInterval ?? 5 * 60211 isLocked = enabled // a cold start always begins locked212 lastActiveAt = now()213 }214215 /// Call on user interaction to push the auto-lock deadline (foreground inactivity).216 public func noteActivity() {217 if !isLocked { lastActiveAt = now() }218 }219220 public func appDidEnterBackground() {221 lastActiveAt = now()222 if isEnabled, timeout <= 0 { isLocked = true }223 }224225 public func appWillEnterForeground() { lockIfExpired() }226227 /// Locks when enabled and the inactivity timeout elapsed. Also usable from a foreground timer.228 public func lockIfExpired() {229 guard isEnabled, !isLocked else { return }230 if now().timeIntervalSince(lastActiveAt) >= timeout { isLocked = true }231 }232233 public func lock() {234 if isEnabled { isLocked = true }235 }236237 /// Prompts for Face ID / Touch ID / passcode. Returns true when unlocked.238 @discardableResult239 public func unlock(reason: String = "Unlock the app") async -> Bool {240 guard isLocked else { return true }241 guard !isAuthenticating else { return false }242 isAuthenticating = true243 defer { isAuthenticating = false }244 do {245 try await authenticator.authenticate(reason: reason)246 isLocked = false247 lastActiveAt = now()248 return true249 } catch {250 return false251 }252 }253254 /// Turns the lock on after verifying the owner once (so nobody else can enable it).255 public func enable(reason: String = "Enable app lock") async throws {256 try await authenticator.authenticate(reason: reason)257 isEnabled = true258 isLocked = false259 lastActiveAt = now()260 }261262 /// Turns the lock off; requires a successful verification.263 public func disable(reason: String = "Disable app lock") async throws {264 try await authenticator.authenticate(reason: reason)265 isEnabled = false266 }267}268