// 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 AVFoundationimportFoundationimportNetworkimportSpeechimportSynchronizationimportUserNotifications/// The real one.publicstructSystemCapabilityAuthority: CapabilityAuthority {publicinit() {}// MARK: - What the OS currently thinkspublicfunc status(_ capability: DeviceCapability) async -> CapabilityAccess {switch capability {case .microphone:returnSelf.access(AVAudioApplication.shared.recordPermission)case .speech:returnSelf.access(SFSpeechRecognizer.authorizationStatus())case .camera:returnawaitLiveStores.access(for: .camera)?.status() ?? .unavailablecase .contacts:// Only an app that installed its book can read contacts at all (`LiveStores`, `COTTON_NO_CONTACTS`).returnLiveStores.addressBook?.access() ?? .unavailablecase .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.guardBundle.main.bundleIdentifier != nil, Bundle.main.bundleURL.pathExtension == "app"else {return .unavailable }let settings = await UNUserNotificationCenter.current().notificationSettings()returnSelf.access(settings.authorizationStatus)case .photoLibrary, .photoLibraryAdd:returnawaitLiveStores.access(for: capability)?.status() ?? .unavailablecase .localNetwork:returnLocalNetworkAnswer.standing()case .appleHealth:returnawaitSelf.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.publicfunc 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 { returnawaitLocalNetworkAnswer.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 : .deniedcase .speech:returnSelf.access(awaitSelf.askForSpeech())case .camera:// The app's own camera (`App/Cotton/Camera+AVFoundation.swift`); none in an app built without one.returnawaitLiveStores.access(for: .camera)?.ask() ?? .unavailablecase .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`).guardlet 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) : .deniedcase .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.returnawaitLiveStores.access(for: capability)?.ask() ?? .unavailablecase .localNetwork:// Answered above, before the standing read.return standingcase .appleHealth:guardlet health = Self.appleHealth else { return .unavailable }returnawait 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(_:)``.publicstaticvar appleHealth: (any AppleHealthAsking)? { attachedHealth.withLock { $0 } }/// Attach Apple Health's asking (Cotton Health, before its first read).publicstaticfunc attachAppleHealth(_ asking: any AppleHealthAsking) { attachedHealth.withLock { $0 = asking } }privatestaticlet 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 staticfunc askForSpeech() async -> SFSpeechRecognizerAuthorizationStatus {await withCheckedContinuation { continuation in SFSpeechRecognizer.requestAuthorization { continuation.resume(returning: $0) } } }// MARK: - The mappings, one per OS enumpublicstaticfunc access(_ status: AVAudioApplication.recordPermission) -> CapabilityAccess {switch status {case .granted: return .authorizedcase .undetermined: return .notDeterminedcase .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 } }publicstaticfunc access(_ status: SFSpeechRecognizerAuthorizationStatus) -> CapabilityAccess {switch status {case .authorized: return .authorizedcase .notDetermined: return .notDeterminedcase .denied: return .deniedcase .restricted: return .restricted @unknown default: return .denied } }/// `provisional` and `ephemeral` are yeses — something can be delivered.publicstaticfunc access(_ status: UNAuthorizationStatus) -> CapabilityAccess {switch status {case .authorized, .provisional, .ephemeral: return .authorizedcase .notDetermined: return .notDeterminedcase .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 {staticlet 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.staticlet serviceType = "_cotton-find._tcp"/// Where the last answer is kept, so a screen can read it without asking.staticlet 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.staticlet ceiling: TimeInterval = 60privatevar asking: Task<CapabilityAccess, Never>?/// The answer the last ask left, or `notDetermined`. **Never prompts.** nonisolated staticfunc standing() -> CapabilityAccess {guard applies else { return .unavailable }switchUserDefaults.standard.string(forKey: remembered) {case"authorized": return .authorizedcase"denied": return .denieddefault: 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 {guardSelf.applies else { return .unavailable }iflet asking { returnawait asking.value }let task = Task { awaitSelf.probe() } asking = tasklet answer = await task.value asking = nilswitch 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 staticvar applies: Bool { #if os(iOS)guardBundle.main.bundleURL.pathExtension == "app"else { returnfalse }let declared = Bundle.main.object(forInfoDictionaryKey: "NSBonjourServices") as? [String]return declared?.contains(serviceType) == true #elsereturnfalse #endif }private nonisolated staticfunc 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.guardawait onALocalNetwork() else { return .unavailable }returnawaitLocalNetworkProbe().run(type: serviceType, ceiling: ceiling) }private nonisolated staticfunc onALocalNetwork() async -> Bool {await withCheckedContinuation { continuation inlet monitor = NWPathMonitor()let first = FirstAnswer() monitor.pathUpdateHandler = { path inguard 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.privatefinalclassFirstAnswer: @unchecked Sendable {privatelet lock = NSLock()privatevar taken = falsefunc take() -> Bool { lock.withLock {if taken { returnfalse } taken = truereturntrue } }}/// 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.privatefinalclassLocalNetworkProbe: @unchecked Sendable {privatelet queue = DispatchQueue(label: "cotton.local-network.probe")privatevar listener: NWListener?privatevar browser: NWBrowser?privatevar 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) } } }privatefunc start( type: String, ceiling: TimeInterval, _ continuation: CheckedContinuation<CapabilityAccess, Never> ) { waiting = continuationguardlet 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 = { [weakself] state inswitch state {case .waiting(let error), .failed(let error):iflet 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 = { [weakself] state inswitch state {case .waiting(let error):iflet 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 = { [weakself] results, _ inif !results.isEmpty { self?.finish(.authorized) } } listener.start(queue: queue) browser.start(queue: queue) queue.asyncAfter(deadline: .now() + ceiling) { [weakself] inself?.finish(.notDetermined) } }/// What a DNS-SD refusal says about the permission, or `nil` for an error/// that is not about it.privatestaticfunc answer(in error: NWError) -> CapabilityAccess? {guardcase .dns(let code) = error else { returnnil }switchInt(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 .unavailabledefault: returnnil } }privatefunc finish(_ answer: CapabilityAccess) {guardlet 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.publicprotocolAppleHealthAsking: 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}