Cotton code
391 lines · 18.0 KB · SwiftRaw
// The ONE place in this app that asks the operating system for anything.//// Every permission API iOS has that Cotton touches is called from this file and// nowhere else, and `CapabilityGateSweepTests` is what says so out loud. The// reason is not tidiness: an ask scattered across five features is five// different orderings, five different mappings of "not granted", and five// chances to touch a platform object before the answer came back — which is// exactly how the microphone, the speech recogniser and the camera each took// the app down in turn.//// **The mappings are total switches.** Every OS status is named; a status this// file has not thought about cannot fall through to a default that quietly// reads as "fine". `@unknown default` is present only because these are// imported Objective-C enums, where Swift cannot make exhaustiveness a compile// error — it is the conservative answer (`denied`) with a comment, never a// silent pass.//// **This type is not main-actor isolated, and that is load-bearing.**// `SFSpeechRecognizer.requestAuthorization` and// `AVCaptureDevice.requestAccess` answer on an arbitrary queue; handing either// a main-actor closure compiles a main-queue assertion into the closure's entry// and the process takes SIGTRAP the first time Apple answers off the main// thread — an app that vanishes to the home screen with no error and no crash// report the person can see. A plain `struct` inherits no isolation, so there// is no assertion to fail. Guard: `SpeechPermissionIsolationTests`.import AVFoundationimport Foundationimport Networkimport Speechimport Synchronizationimport UserNotifications/// The real one.public struct SystemCapabilityAuthority: CapabilityAuthority {    public init() {}    // MARK: - What the OS currently thinks    public func status(_ capability: DeviceCapability) async -> CapabilityAccess {        switch capability {        case .microphone:            return Self.access(AVAudioApplication.shared.recordPermission)        case .speech:            return Self.access(SFSpeechRecognizer.authorizationStatus())        case .camera:            return await LiveStores.access(for: .camera)?.status() ?? .unavailable        case .contacts:            // Only an app that installed its book can read contacts at all (`LiveStores`, `COTTON_NO_CONTACTS`).            return LiveStores.addressBook?.access() ?? .unavailable        case .notifications:            // A process with no app bundle — a command-line tool, a test            // runner — has no notification centre: `current()` raises an            // Objective-C exception there that Swift cannot catch. Nothing can            // be scheduled from it, which is what `unavailable` says.            guard Bundle.main.bundleIdentifier != nil, Bundle.main.bundleURL.pathExtension == "app" else {                return .unavailable            }            let settings = await UNUserNotificationCenter.current().notificationSettings()            return Self.access(settings.authorizationStatus)        case .photoLibrary, .photoLibraryAdd:            return await LiveStores.access(for: capability)?.status() ?? .unavailable        case .localNetwork:            return LocalNetworkAnswer.standing()        case .appleHealth:            return await Self.appleHealth?.status() ?? .unavailable        }    }    // MARK: - Asking    /// **A decided capability is never re-prompted.** iOS grants one prompt per    /// install; a second `requestAccess` on a denied permission calls back    /// immediately with the same answer, and a caller that treated that as "the    /// person just refused again" would put a second dialog's worth of copy on    /// screen for a dialog nobody saw.    public func ask(_ capability: DeviceCapability) async -> CapabilityAccess {        // THE LOCAL NETWORK HAS NO STANDING ANSWER TO READ. iOS offers no        // status call for it, so the only way to know is to use it and see —        // which prompts exactly once per install and never again. So this one        // is asked every time: an answer the person changed in Settings is        // read as it stands now, and nothing is shown twice.        if capability == .localNetwork { return await LocalNetworkAnswer.shared.ask() }        let standing = await status(capability)        guard standing.canBeAsked else { return standing }        switch capability {        case .microphone:            let granted = await AVAudioApplication.requestRecordPermission()            return granted ? .authorized : .denied        case .speech:            return Self.access(await Self.askForSpeech())        case .camera:            // The app's own camera (`App/Cotton/Camera+AVFoundation.swift`); none in an app built without one.            return await LiveStores.access(for: .camera)?.ask() ?? .unavailable        case .contacts:            // A process the app did not install an address book into — a test            // runner on a Mac, signed in to the owner's iCloud — is never            // asked about the person's contacts (`LiveStores`).            guard let book = LiveStores.addressBook else { return .unavailable }            let granted = await book.askAccess()            // Re-READ rather than inferred: iOS 18 can answer `limited`, which            // is a yes with a smaller book, and the mapping for that lives in            // one place.            return granted ? await status(.contacts) : .denied        case .notifications:            let granted =                (try? await UNUserNotificationCenter.current()                    .requestAuthorization(options: [.alert, .sound, .badge])) ?? false            // The ANSWER is re-read rather than inferred from the flag: a            // "false" here is `denied` for good, and the mapping is one place.            return granted ? .authorized : await status(.notifications)        case .photoLibrary, .photoLibraryAdd:            // The app's own photo library (`App/Cotton/CameraRoll+Photos.swift`); none in an app built without one.            return await LiveStores.access(for: capability)?.ask() ?? .unavailable        case .localNetwork:            // Answered above, before the standing read.            return standing        case .appleHealth:            guard let health = Self.appleHealth else { return .unavailable }            return await health.ask()        }    }    // MARK: - Apple Health, attached by the one app that links HealthKit    /// Apple Health's asking, which HealthKit alone can do. Only Cotton    /// Health links HealthKit (`CottonHealthKit`): an app whose binary names    /// HealthKit is held by App Review to say why, so no other Cotton app    /// carries it. Cotton Health attaches its asking here at launch, with    /// the types its reader reads, and every ask still comes through this    /// authority's ``status(_:)`` and ``ask(_:)``.    public static var appleHealth: (any AppleHealthAsking)? {        attachedHealth.withLock { $0 }    }    /// Attach Apple Health's asking (Cotton Health, before its first read).    public static func attachAppleHealth(_ asking: any AppleHealthAsking) {        attachedHealth.withLock { $0 = asking }    }    private static let attachedHealth = Mutex<(any AppleHealthAsking)?>(nil)    /// **`nonisolated`, `static`, and the app crashed for want of it.**    ///    /// `SFSpeechRecognizer.requestAuthorization` answers on an arbitrary queue.    /// Asked from inside a `@MainActor` type with the continuation resumed    /// inline, Swift 6 compiles a main-queue assertion into the completion's    /// entry, libdispatch logs *"BUG IN CLIENT OF LIBDISPATCH: Assertion    /// failed: Block was expected to execute on queue [com.apple.main-thread]"*    /// and the process takes SIGTRAP — which is what a person who declined    /// dictation once saw every single time they touched the microphone    /// afterwards, because the already-decided answer comes back on that same    /// background queue.    ///    /// Being `static` means there is no `self` to inherit isolation from, and    /// `nonisolated` states it for the reader as well as the compiler. This    /// code moved here from `SystemSpeechRecogniser` with its reason attached;    /// `SpeechPermissionIsolationTests` sweeps for the shape rather than    /// trusting the comment.    private nonisolated static func askForSpeech() async -> SFSpeechRecognizerAuthorizationStatus {        await withCheckedContinuation { continuation in            SFSpeechRecognizer.requestAuthorization { continuation.resume(returning: $0) }        }    }    // MARK: - The mappings, one per OS enum    public static func access(_ status: AVAudioApplication.recordPermission) -> CapabilityAccess {        switch status {        case .granted: return .authorized        case .undetermined: return .notDetermined        case .denied: return .denied        // A state this file has not seen. `denied` is the conservative answer:        // it shows a sentence and a way to Settings rather than letting a        // feature build an audio engine on a maybe.        @unknown default: return .denied        }    }    public static func access(_ status: SFSpeechRecognizerAuthorizationStatus) -> CapabilityAccess {        switch status {        case .authorized: return .authorized        case .notDetermined: return .notDetermined        case .denied: return .denied        case .restricted: return .restricted        @unknown default: return .denied        }    }    /// `provisional` and `ephemeral` are yeses — something can be delivered.    public static func access(_ status: UNAuthorizationStatus) -> CapabilityAccess {        switch status {        case .authorized, .provisional, .ephemeral: return .authorized        case .notDetermined: return .notDetermined        case .denied: return .denied        @unknown default: return .denied        }    }}// MARK: - The local network/// Whether Cotton may reach the Mac on this network — asked, remembered, and/// asked by one caller at a time.////// **Why a Bonjour browse, when the phone finds its Mac by NAME.** The Mac's/// address on this network comes from the household's name, through the relay/// (`GET /v1/me/server`); nothing here discovers a Mac. But iOS raises the/// Local Network prompt only when the app first USES the local network, and/// the first use used to be the first copy's own dial — which the prompt/// fails, at once, before the person has read it. The copy then left through/// the relay and never came back. So the question is put on its own, at the/// Join step, by the one operation whose answer iOS reports: a listener/// advertises a service, a browser looks for it, and the browser either finds/// it (allowed), is refused by policy (declined), or waits (the prompt is/// up). The service type exists for this and nothing else.actor LocalNetworkAnswer {    static let shared = LocalNetworkAnswer()    /// The service the probe advertises and browses for. It must be listed in    /// the app's `NSBonjourServices`, or iOS refuses the browse outright and    /// never lists Cotton under Local Network.    static let serviceType = "_cotton-find._tcp"    /// Where the last answer is kept, so a screen can read it without asking.    static let remembered = "cotton.localNetwork.answer"    /// How long an unanswered probe is waited for. A person reads the prompt    /// and taps within this; past it the copy goes ahead through the relay    /// rather than waiting on a prompt nobody is looking at.    static let ceiling: TimeInterval = 60    private var asking: Task<CapabilityAccess, Never>?    /// The answer the last ask left, or `notDetermined`. **Never prompts.**    nonisolated static func standing() -> CapabilityAccess {        guard applies else { return .unavailable }        switch UserDefaults.standard.string(forKey: remembered) {        case "authorized": return .authorized        case "denied": return .denied        default: return .notDetermined        }    }    /// Ask, or join the ask already in flight — the Join step raises it and    /// the first copy waits on the same one.    func ask() async -> CapabilityAccess {        guard Self.applies else { return .unavailable }        if let asking { return await asking.value }        let task = Task { await Self.probe() }        asking = task        let answer = await task.value        asking = nil        switch answer {        case .authorized: UserDefaults.standard.set("authorized", forKey: Self.remembered)        case .denied: UserDefaults.standard.set("denied", forKey: Self.remembered)        case .notDetermined, .restricted, .unavailable: break        }        return answer    }    /// A phone, in the app itself, whose plist names the probe's service.    /// Everything else — a Mac, a test runner, an extension — has nothing to    /// ask and is `unavailable`.    private nonisolated static var applies: Bool {        #if os(iOS)            guard Bundle.main.bundleURL.pathExtension == "app" else { return false }            let declared = Bundle.main.object(forInfoDictionaryKey: "NSBonjourServices") as? [String]            return declared?.contains(serviceType) == true        #else            return false        #endif    }    private nonisolated static func probe() async -> CapabilityAccess {        // Off Wi-Fi there is no Mac across the room and nothing to find; the        // probe would wait out its ceiling for an answer that cannot come.        guard await onALocalNetwork() else { return .unavailable }        return await LocalNetworkProbe().run(type: serviceType, ceiling: ceiling)    }    private nonisolated static func onALocalNetwork() async -> Bool {        await withCheckedContinuation { continuation in            let monitor = NWPathMonitor()            let first = FirstAnswer()            monitor.pathUpdateHandler = { path in                guard first.take() else { return }                monitor.cancel()                continuation.resume(                    returning: path.usesInterfaceType(.wifi) || path.usesInterfaceType(.wiredEthernet)                )            }            monitor.start(queue: DispatchQueue(label: "cotton.local-network.path"))        }    }}/// True once, then false: a handler the system may call again answers once.private final class FirstAnswer: @unchecked Sendable {    private let lock = NSLock()    private var taken = false    func take() -> Bool {        lock.withLock {            if taken { return false }            taken = true            return true        }    }}/// One listener and one browser for the same service, until iOS says which/// way the person answered. Everything it holds is touched on its own queue.private final class LocalNetworkProbe: @unchecked Sendable {    private let queue = DispatchQueue(label: "cotton.local-network.probe")    private var listener: NWListener?    private var browser: NWBrowser?    private var waiting: CheckedContinuation<CapabilityAccess, Never>?    func run(type: String, ceiling: TimeInterval) async -> CapabilityAccess {        await withCheckedContinuation { continuation in            queue.async { self.start(type: type, ceiling: ceiling, continuation) }        }    }    private func start(        type: String, ceiling: TimeInterval, _ continuation: CheckedContinuation<CapabilityAccess, Never>    ) {        waiting = continuation        guard let listener = try? NWListener(using: .tcp) else { return finish(.unavailable) }        self.listener = listener        listener.service = NWListener.Service(name: UUID().uuidString, type: type)        // Nothing is served: the service exists to be found by this process.        listener.newConnectionHandler = { $0.cancel() }        listener.stateUpdateHandler = { [weak self] state in            switch state {            case .waiting(let error), .failed(let error):                if let answer = Self.answer(in: error) { self?.finish(answer) }            default: break            }        }        let browser = NWBrowser(for: .bonjour(type: type, domain: nil), using: .tcp)        self.browser = browser        browser.stateUpdateHandler = { [weak self] state in            switch state {            case .waiting(let error):                if let answer = Self.answer(in: error) { self?.finish(answer) }            case .failed(let error):                self?.finish(Self.answer(in: error) ?? .notDetermined)            default: break            }        }        // FOUND — its own listener, which only an allowed app can see.        browser.browseResultsChangedHandler = { [weak self] results, _ in            if !results.isEmpty { self?.finish(.authorized) }        }        listener.start(queue: queue)        browser.start(queue: queue)        queue.asyncAfter(deadline: .now() + ceiling) { [weak self] in self?.finish(.notDetermined) }    }    /// What a DNS-SD refusal says about the permission, or `nil` for an error    /// that is not about it.    private static func answer(in error: NWError) -> CapabilityAccess? {        guard case .dns(let code) = error else { return nil }        switch Int(code) {        // kDNSServiceErr_PolicyDenied: the person said no, now or in Settings.        case -65570: return .denied        // kDNSServiceErr_NoAuth: the plist does not name the service.        case -65555: return .unavailable        default: return nil        }    }    private func finish(_ answer: CapabilityAccess) {        guard let waiting else { return }        self.waiting = nil        listener?.cancel()        browser?.cancel()        listener = nil        browser = nil        waiting.resume(returning: answer)    }}/// Apple Health's standing answer and its one prompt, read-only: what/// HealthKit says of reading the types Cotton Health reads. **Never shares**:/// the prompt asks to read and to write nothing.public protocol AppleHealthAsking: Sendable {    /// Whether the person has been asked; never prompts.    func status() async -> CapabilityAccess    /// Ask to read, once; an already-asked answer comes straight back.    func ask() async -> CapabilityAccess}