Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/AppSupport.swift3// Description: App configuration (server, DEBUG-only launch arguments), Keychain selection, persisted settings, passkeys (AuthenticationServices), app lock, notifications and badge.4import AuthenticationServices5import LocalAuthentication6import SPMailCore7import SwiftUI8import UserNotifications9#if os(macOS)10import AppKit11#else12import UIKit13#endif1415enum AppConfig {16 static let productionURL = URL(string: "https://mail.spboucher.ai")!17 /// Administration (addresses, API keys, approvals, webhooks, explorer) stays in the webmail: the apps only link to it.18 static let adminURL = URL(string: "https://mail.spboucher.ai/admin")!19 static let relyingParty = "mail.spboucher.ai"20 static let refreshTaskId = "ai.spboucher.spmail.refresh"21 static let bundleId = Bundle.main.bundleIdentifier ?? "ai.spboucher.spmail"2223 #if DEBUG24 // Development switches, compiled out of Release: `-spmBaseURL http://localhost:8761 -spmDevToken <token> [-spmSelfTest YES]`.25 static var baseURL: URL { UserDefaults.standard.string(forKey: "spmBaseURL").flatMap(URL.init(string:)) ?? productionURL }26 static var devToken: String? { UserDefaults.standard.string(forKey: "spmDevToken").flatMap { $0.isEmpty ? nil : $0 } }27 static var selfTest: Bool { UserDefaults.standard.bool(forKey: "spmSelfTest") }28 static var screenshotScene: String? { UserDefaults.standard.string(forKey: "spmScene") }29 #else30 static var baseURL: URL { productionURL }31 #endif3233 static var cacheDirectory: URL {34 let base = (try? FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)) ?? FileManager.default.temporaryDirectory35 return base.appendingPathComponent("SPMail", isDirectory: true)36 }3738 @MainActor static var clientInfo: ClientInfo {39 #if os(macOS)40 let v = ProcessInfo.processInfo.operatingSystemVersion41 return ClientInfo(deviceName: Host.current().localizedName ?? "Mac", platform: "macOS \(v.majorVersion).\(v.minorVersion)")42 #else43 return ClientInfo(deviceName: UIDevice.current.name, platform: "\(UIDevice.current.systemName) \(UIDevice.current.systemVersion)")44 #endif45 }46 static var userAgent: String {47 let v = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0"48 #if os(macOS)49 return "SPMail-macOS/\(v)"50 #else51 return "SPMail-iOS/\(v)"52 #endif53 }5455 /// The Keychain used for the bearer token and the cache key. The data-protection keychain needs an application identifier56 /// (signed with a provisioning profile); the profile-less development variant on macOS falls back to the login keychain.57 static func secrets() -> SecretStore {58 let modern = KeychainStore(service: bundleId, dataProtection: true)59 #if os(macOS)60 // reading an absent item succeeds even without the entitlement; only a write tells the truth61 do { try modern.write("probe", Data([1])); try modern.delete("probe") } catch { return KeychainStore(service: bundleId, dataProtection: false) }62 #endif63 return modern64 }65}6667/// What one swipe slot of a message row does (iOS / iPadOS; configurable in Settings › Apparence).68enum SwipeAction: String, CaseIterable, Identifiable, Sendable {69 case none, readUnread, flag, pin, archive, snooze, delete, more70 var id: String { rawValue }71 var title: String {72 switch self {73 case .none: L("Aucune"); case .readUnread: L("Lu / non lu"); case .flag: L("Drapeau"); case .pin: L("Épingler"); case .archive: L("Archiver")74 case .snooze: L("Mettre en veille"); case .delete: L("Supprimer"); case .more: L("Plus")75 }76 }77 var icon: String {78 switch self {79 case .none: "minus"; case .readUnread: "envelope.badge"; case .flag: "flag"; case .pin: "pin"; case .archive: "archivebox"; case .snooze: "clock"; case .delete: "trash"; case .more: "ellipsis.circle"80 }81 }82}8384@MainActor @Observable85final class AppSettings {86 private let d = UserDefaults.standard8788 /// system | light | dark | midnight — per device.89 var theme: SPTheme { didSet { d.set(theme.rawValue, forKey: "theme") } }90 var density: Density { didSet { d.set(density.rawValue, forKey: "density") } }91 var threaded: Bool { didSet { d.set(threaded, forKey: "threaded") } }92 /// 0, 1 or 2 preview lines under the subject.93 var previewLines: Int { didSet { d.set(previewLines, forKey: "previewLines") } }94 var showAvatars: Bool { didSet { d.set(showAvatars, forKey: "showAvatars") } }95 var readingFont: ReadingFont { didSet { d.set(readingFont.rawValue, forKey: "readingFont") } }96 /// « Dark reading »: message bodies follow the dark themes instead of staying on a white sheet. Off by default.97 var darkReading: Bool { didSet { d.set(darkReading, forKey: "darkReading") } }98 /// Opaque chrome in the app, in addition to the system « Reduce transparency » setting.99 var reduceTransparency: Bool { didSet { d.set(reduceTransparency, forKey: "reduceTransparency") } }100 var markReadOnOpen: Bool { didSet { d.set(markReadOnOpen, forKey: "markReadOnOpen") } }101 /// Base size of message text; on iOS it scales with Dynamic Type.102 var bodyFontSize: Int { didSet { d.set(bodyFontSize, forKey: "bodyFontSize") } }103 var lockEnabled: Bool { didSet { d.set(lockEnabled, forKey: "lockEnabled") } }104 /// Minutes of inactivity before the app locks itself (0 = as soon as the app is left).105 var lockAfterMinutes: Int { didSet { d.set(lockAfterMinutes, forKey: "lockAfterMinutes") } }106 /// The app's content is covered in the app switcher (independent from the lock).107 var hideInAppSwitcher: Bool { didSet { d.set(hideInAppSwitcher, forKey: "hideInAppSwitcher") } }108 var notificationsEnabled: Bool { didSet { d.set(notificationsEnabled, forKey: "notificationsEnabled") } }109 /// Notifications are held back until the person resumes them (menu bar extra, Settings).110 var notificationsPaused: Bool { didSet { d.set(notificationsPaused, forKey: "notificationsPaused") } }111 /// Notifications say « Nouveau message » without sender or subject.112 var hideNotificationContent: Bool { didSet { d.set(hideNotificationContent, forKey: "hideNotificationContent") } }113 /// Subjects and senders in Spotlight. Off unless the person turns it on.114 var spotlightEnabled: Bool { didSet { d.set(spotlightEnabled, forKey: "spotlightEnabled") } }115 /// macOS: unread counts and recent messages in the menu bar.116 var showMenuBarExtra: Bool { didSet { d.set(showMenuBarExtra, forKey: "showMenuBarExtra") } }117 var swipeLeading: [SwipeAction] { didSet { d.set(swipeLeading.map(\.rawValue), forKey: "swipeLeading") } }118 var swipeTrailing: [SwipeAction] { didSet { d.set(swipeTrailing.map(\.rawValue), forKey: "swipeTrailing") } }119120 static let defaultSwipeLeading: [SwipeAction] = [.readUnread, .flag]121 static let defaultSwipeTrailing: [SwipeAction] = [.archive, .snooze, .more]122123 init() {124 d.register(defaults: ["threaded": true, "previewLines": 2, "markReadOnOpen": true, "bodyFontSize": 15, "lockEnabled": false, "lockAfterMinutes": 5,125 "notificationsEnabled": true, "hideNotificationContent": false, "spotlightEnabled": false, "showAvatars": true, "showMenuBarExtra": true])126 // 1.1 stored « appearance » (system / light / dark): the same raw values, so the choice carries over127 theme = SPTheme(rawValue: d.string(forKey: "theme") ?? d.string(forKey: "appearance") ?? "") ?? .system128 density = Density(rawValue: d.string(forKey: "density") ?? "") ?? .comfortable129 threaded = d.bool(forKey: "threaded")130 previewLines = min(2, max(0, d.integer(forKey: "previewLines")))131 showAvatars = d.bool(forKey: "showAvatars")132 readingFont = ReadingFont(rawValue: d.string(forKey: "readingFont") ?? "") ?? .system133 darkReading = d.bool(forKey: "darkReading")134 reduceTransparency = d.bool(forKey: "reduceTransparency")135 markReadOnOpen = d.bool(forKey: "markReadOnOpen")136 bodyFontSize = d.integer(forKey: "bodyFontSize")137 lockEnabled = d.bool(forKey: "lockEnabled")138 lockAfterMinutes = d.integer(forKey: "lockAfterMinutes")139 hideInAppSwitcher = d.bool(forKey: "hideInAppSwitcher")140 notificationsEnabled = d.bool(forKey: "notificationsEnabled")141 notificationsPaused = d.bool(forKey: "notificationsPaused")142 hideNotificationContent = d.bool(forKey: "hideNotificationContent")143 spotlightEnabled = d.bool(forKey: "spotlightEnabled")144 showMenuBarExtra = d.bool(forKey: "showMenuBarExtra")145 swipeLeading = (d.stringArray(forKey: "swipeLeading")?.compactMap(SwipeAction.init(rawValue:))).flatMap { $0.isEmpty ? nil : $0 } ?? Self.defaultSwipeLeading146 swipeTrailing = (d.stringArray(forKey: "swipeTrailing")?.compactMap(SwipeAction.init(rawValue:))).flatMap { $0.isEmpty ? nil : $0 } ?? Self.defaultSwipeTrailing147 }148149 var colorScheme: ColorScheme? { theme.colorScheme }150}151152// MARK: - passkeys153154/// Passkeys through the system (iCloud Keychain, Touch ID / Face ID). Relying party = the web app's domain, so one passkey signs in everywhere.155/// The JSON shapes are exactly SimpleWebAuthn's AuthenticationResponseJSON / RegistrationResponseJSON (base64url fields).156@MainActor157final class PasskeyCoordinator: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {158 private var continuation: CheckedContinuation<ASAuthorization, Error>?159 private let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: AppConfig.relyingParty)160161 private func perform(_ request: ASAuthorizationRequest) async throws -> ASAuthorization {162 try await withCheckedThrowingContinuation { c in163 continuation = c164 let controller = ASAuthorizationController(authorizationRequests: [request])165 controller.delegate = self166 controller.presentationContextProvider = self167 controller.performRequests()168 }169 }170 func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {171 continuation?.resume(returning: authorization); continuation = nil172 }173 func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {174 continuation?.resume(throwing: error); continuation = nil175 }176 func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {177 #if os(macOS)178 return NSApp.keyWindow ?? NSApp.windows.first ?? ASPresentationAnchor()179 #else180 let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first181 return scene?.keyWindow ?? ASPresentationAnchor()182 #endif183 }184185 /// Sign-in with a discoverable credential → AuthenticationResponseJSON.186 func assertion(options: JSONValue) async throws -> JSONValue {187 guard let challenge = options["challenge"].stringValue.flatMap(Data.init(base64URL:)) else { throw APIError(status: 0, code: "bad_options", message: "Invalid sign-in options") }188 let request = provider.createCredentialAssertionRequest(challenge: challenge)189 request.userVerificationPreference = .required190 guard let a = try await perform(request).credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { throw APIError(status: 0, code: "no_credential", message: "No passkey was returned") }191 let id = a.credentialID.base64URL192 return ["id": .string(id), "rawId": .string(id), "type": "public-key", "authenticatorAttachment": "platform", "clientExtensionResults": [:],193 "response": ["clientDataJSON": .string(a.rawClientDataJSON.base64URL), "authenticatorData": .string(a.rawAuthenticatorData.base64URL),194 "signature": .string(a.signature.base64URL), "userHandle": .string(a.userID.base64URL)]]195 }196197 /// New passkey (enrollment link, or an extra key for a signed-in account) → RegistrationResponseJSON.198 func registration(options: JSONValue) async throws -> JSONValue {199 guard let challenge = options["challenge"].stringValue.flatMap(Data.init(base64URL:)), let userId = options["user"]["id"].stringValue.flatMap(Data.init(base64URL:)),200 let name = options["user"]["name"].stringValue else { throw APIError(status: 0, code: "bad_options", message: "Invalid registration options") }201 let request = provider.createCredentialRegistrationRequest(challenge: challenge, name: name, userID: userId)202 request.userVerificationPreference = .required203 if let display = options["user"]["displayName"].stringValue { request.displayName = display }204 guard let r = try await perform(request).credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration, let attestation = r.rawAttestationObject else {205 throw APIError(status: 0, code: "no_credential", message: "No passkey was created")206 }207 let id = r.credentialID.base64URL208 return ["id": .string(id), "rawId": .string(id), "type": "public-key", "authenticatorAttachment": "platform", "clientExtensionResults": [:],209 "response": ["clientDataJSON": .string(r.rawClientDataJSON.base64URL), "attestationObject": .string(attestation.base64URL), "transports": ["internal", "hybrid"]]]210 }211212 /// Extracts the one-time token from a pasted `https://mail.spboucher.ai/enroll#<token>` link (or a bare token).213 static func enrollmentToken(from input: String) -> String? {214 let s = input.trimmingCharacters(in: .whitespacesAndNewlines)215 let candidate: String216 if let hash = s.lastIndex(of: "#") {217 guard let url = URL(string: String(s[..<hash])), url.host?.lowercased() == AppConfig.relyingParty || url.host == AppConfig.baseURL.host, url.path.hasPrefix("/enroll") else { return nil }218 candidate = String(s[s.index(after: hash)...])219 } else { candidate = s }220 return candidate.range(of: "^[A-Za-z0-9_-]{20,120}$", options: .regularExpression) != nil ? candidate : nil221 }222}223224// MARK: - app lock225226enum AppLock {227 /// Touch ID / Face ID with the device passcode (or account password) as fallback.228 static func unlock(reason: String) async -> Bool {229 let context = LAContext()230 var error: NSError?231 guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else { return false }232 return (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) ?? false233 }234 static var isAvailable: Bool { LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) }235 static var biometryName: String {236 let c = LAContext()237 _ = c.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)238 switch c.biometryType {239 case .faceID: return "Face ID"240 case .touchID: return "Touch ID"241 case .opticID: return "Optic ID"242 default: return String(localized: "le code de l’appareil")243 }244 }245}246247// MARK: - notifications and badge248249@MainActor250enum Notifier {251 static func requestAuthorization() async -> Bool {252 (try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound])) ?? false253 }254255 /// Local notification for mail detected while running or during a background refresh. Built on the device from the synced headers.256 static func notify(_ mails: [EmailSummary], account: String, hideContent: Bool) async {257 guard !mails.isEmpty else { return }258 let center = UNUserNotificationCenter.current()259 guard await center.notificationSettings().authorizationStatus == .authorized else { return }260 for m in mails.prefix(5) {261 let content = UNMutableNotificationContent()262 if hideContent {263 content.title = String(localized: "Nouveau message")264 } else {265 content.title = m.sender?.displayName ?? String(localized: "Nouveau message")266 content.body = m.subject.isEmpty ? String(localized: "(sans objet)") : m.subject267 }268 content.sound = .default269 content.threadIdentifier = account270 content.userInfo = ["account": account, "email": m.id]271 try? await center.add(UNNotificationRequest(identifier: "\(account)/\(m.id)", content: content, trigger: nil))272 }273 if mails.count > 5 {274 let content = UNMutableNotificationContent()275 content.title = String(localized: "\(mails.count - 5) autres nouveaux messages")276 try? await center.add(UNNotificationRequest(identifier: "\(account)/more", content: content, trigger: nil))277 }278 }279280 static func setBadge(_ count: Int) {281 Task { try? await UNUserNotificationCenter.current().setBadgeCount(max(0, count)) }282 #if os(macOS)283 NSApp?.dockTile.badgeLabel = count > 0 ? String(count) : nil284 #endif285 }286287 static func registerForPush() {288 #if os(macOS)289 NSApp?.registerForRemoteNotifications()290 #else291 UIApplication.shared.registerForRemoteNotifications()292 #endif293 }294}295296func L(_ key: String.LocalizationValue) -> String { String(localized: key) }297298extension Date {299 /// Compact date for list rows: time today, weekday this week, date otherwise.300 var listLabel: String {301 let cal = Calendar.current302 if cal.isDateInToday(self) { return formatted(date: .omitted, time: .shortened) }303 if cal.isDateInYesterday(self) { return String(localized: "Hier") }304 if let days = cal.dateComponents([.day], from: self, to: Date()).day, days < 6 { return formatted(.dateTime.weekday(.wide)) }305 return formatted(date: .numeric, time: .omitted)306 }307}308309extension Int {310 var byteLabel: String { ByteCountFormatter.string(fromByteCount: Int64(self), countStyle: .file) }311}312