// The one wrapper around the `CGPreflight*EventAccess` / `CGRequest*EventAccess` // C API (CLAUDE.md, Swift standards: C APIs are wrapped once), plus the health // check that notices a grant being taken away while we run (contracts C2). // // Windows has no equivalent: a low-level hook needs no permission there. On // macOS the tap simply stops existing, so the app has to watch for it. // // CLAUDE.md, Workflow: an agent never grants, requests or scripts these // permissions. `request()` exists for a button the *user* clicks, and nothing in // this repository may call it on its own initiative. import CoreGraphics import Foundation import os /// Which macOS TCC permissions the current process holds. /// /// `listen` is Input Monitoring (needed to observe key events), `post` is /// Accessibility (needed to inject events and to run a swallowing tap). public struct PermissionState: Equatable, Sendable { /// Input Monitoring granted. public let listen: Bool /// Accessibility granted. public let post: Bool /// A state with both grants named explicitly. /// /// Public so another target can build one without asking TCC: a menu bar or /// a snapshot needs a "nothing granted yet" value before `preflight()` has /// ever run, and `preflight()` is a system query, not a constructor /// (app-engine request 1, authorised by the lead). public init(listen: Bool, post: Bool) { self.listen = listen self.post = post } /// True when both permissions are granted. public var isComplete: Bool { listen && post } } /// Preflight, request and watch the two grants the app needs. public enum Permissions { /// How often the health check re-reads the grants (contracts C2). public static let healthCheckInterval: TimeInterval = 5 /// Reads the current grants without prompting the user. public static func preflight() -> PermissionState { PermissionState( listen: CGPreflightListenEventAccess(), post: CGPreflightPostEventAccess()) } /// Asks macOS to show the system prompts for whichever grant is missing. /// /// **Only ever call this from a control the user clicked.** It shows modal /// system UI, and macOS shows each prompt once per code signature — spending /// it unasked leaves the user with a Settings pane and no explanation. /// Returns the state as macOS reports it immediately afterwards, which is /// normally still incomplete: the grant lands when the user flips the switch /// in System Settings, and the health check is what notices. @discardableResult public static func request() -> PermissionState { let state = preflight() if !state.listen { _ = CGRequestListenEventAccess() } if !state.post { _ = CGRequestPostEventAccess() } return preflight() } /// Starts re-reading the grants every `interval` seconds and calls `onChange` /// whenever they differ from the last reading. /// /// contracts C2: a revoked grant means the tap is dead, so the caller routes /// control local and shows the state in the menu bar. Keep the returned /// object alive; dropping it stops the check. public static func startHealthCheck( interval: TimeInterval = healthCheckInterval, onChange: @escaping @Sendable (PermissionState) -> Void ) -> PermissionHealthCheck { PermissionHealthCheck(interval: interval, onChange: onChange) } } /// A repeating permission check. Cancels itself when released. /// /// `@unchecked Sendable`: its only stored property is a `DispatchSourceTimer`, /// which is safe to use from any thread by its own contract. public final class PermissionHealthCheck: @unchecked Sendable { private let timer: any DispatchSourceTimer fileprivate init(interval: TimeInterval, onChange: @escaping @Sendable (PermissionState) -> Void) { let queue = DispatchQueue(label: "com.mwb-mac.permission-health", qos: .utility) let timer = DispatchSource.makeTimerSource(queue: queue) let last = OSAllocatedUnfairLock(initialState: Permissions.preflight()) timer.schedule(deadline: .now() + interval, repeating: interval, leeway: .seconds(1)) timer.setEventHandler { let current = Permissions.preflight() let changed = last.withLock { previous -> Bool in guard previous != current else { return false } previous = current return true } if changed { onChange(current) } } self.timer = timer timer.resume() } /// Stops the check. Idempotent. public func cancel() { timer.cancel() } deinit { timer.cancel() } }