| 1 | import AppKit |
| 2 | import IOKit |
| 3 | import Security |
| 4 | |
| 5 | |
| 6 | |
| 7 | @MainActor |
| 8 | enum MacMaintenance { |
| 9 | private static let applications: Set<String> = ["com.apple.systempreferences", "com.apple.authorizationhost"] |
| 10 | private static let panes = [ |
| 11 | "projects": "x-apple.systempreferences:com.apple.ExtensionsPreferences?extensionPointIdentifier=com.apple.fskit.fsmodule", |
| 12 | "screen": "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture", |
| 13 | "input": "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility", |
| 14 | ] |
| 15 | |
| 16 | static func settingsURL(for purpose: String) -> URL? { |
| 17 | panes[purpose].flatMap { URL(string: $0) } |
| 18 | } |
| 19 | |
| 20 | static func runPasswordProbe(purpose: String) -> Never { |
| 21 | guard panes[purpose] != nil else { exit(2) } |
| 22 | MacSetupPassword.runStream() |
| 23 | } |
| 24 | |
| 25 | private static func consoleSession() throws -> String { |
| 26 | try consoleUser() |
| 27 | let entry = IORegistryGetRootEntry(kIOMainPortDefault) |
| 28 | guard entry != 0 else { throw Failure(4, "requires_gui_login") } |
| 29 | defer { IOObjectRelease(entry) } |
| 30 | guard let property = IORegistryEntryCreateCFProperty(entry, "IOConsoleUsers" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue(), |
| 31 | let sessions = property as? [[String: Any]] else { throw Failure(4, "requires_gui_login") } |
| 32 | let active = sessions.filter { $0["kCGSSessionOnConsoleKey"] as? Bool == true } |
| 33 | guard active.count == 1, let current = active.first, |
| 34 | current["kCGSessionLoginDoneKey"] as? Bool == true, |
| 35 | current["CGSSessionScreenIsLocked"] as? Bool != true, |
| 36 | current["kCGSSessionUserIDKey"] as? UInt32 == getuid(), |
| 37 | current["kCGSSessionUserNameKey"] as? String == NSUserName(), |
| 38 | let session = current["CGSSessionUniqueSessionUUID"] as? String, |
| 39 | UUID(uuidString: session) != nil else { throw Failure(4, "requires_gui_login") } |
| 40 | return session |
| 41 | } |
| 42 | |
| 43 | private static func verified(_ app: NSRunningApplication) -> Bool { |
| 44 | guard let bundle = app.bundleIdentifier, applications.contains(bundle) else { return false } |
| 45 | var code: SecCode?, requirement: SecRequirement? |
| 46 | return SecRequirementCreateWithString("anchor apple and identifier \"\(bundle)\"" as CFString, [], &requirement) == errSecSuccess && |
| 47 | SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributePid as String: app.processIdentifier] as CFDictionary, [], &code) == errSecSuccess && |
| 48 | code != nil && requirement != nil && SecCodeCheckValidity(code!, [], requirement!) == errSecSuccess |
| 49 | } |
| 50 | |
| 51 | static func run(_ operation: String, purpose: String) throws -> [String: Any] { |
| 52 | try requireGuest() |
| 53 | let session = try consoleSession() |
| 54 | guard let url = settingsURL(for: purpose) else { throw Failure(8, "maintenance_purpose_invalid") } |
| 55 | if operation == "open" { |
| 56 | if purpose == "projects" { |
| 57 | let configuration = NSWorkspace.OpenConfiguration() |
| 58 | configuration.activates = false |
| 59 | NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: "/Applications/macFUSE.app"), configuration: configuration) |
| 60 | } |
| 61 | guard NSWorkspace.shared.open(url) else { throw Failure(8, "maintenance_open_failed") } |
| 62 | return ["opened": true] |
| 63 | } |
| 64 | guard operation == "probe", let front = NSWorkspace.shared.frontmostApplication else { |
| 65 | throw Failure(7, "maintenance_foreground_changed") |
| 66 | } |
| 67 | if !verified(front) { |
| 68 | return ["error": "maintenance_foreground_changed", "blocking_pid": front.processIdentifier, |
| 69 | "blocking_bundle": front.bundleIdentifier ?? ""] |
| 70 | } |
| 71 | guard let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else { |
| 72 | throw Failure(7, "maintenance_window_unavailable") |
| 73 | } |
| 74 | let display = CGDisplayBounds(CGMainDisplayID()) |
| 75 | var covering: [(bounds: CGRect, pid: Int32?, window: UInt32?)] = [] |
| 76 | for window in windows { |
| 77 | guard let raw = window[kCGWindowBounds as String] as? [String: Any], |
| 78 | let bounds = CGRect(dictionaryRepresentation: raw as CFDictionary), bounds.width > 0, bounds.height > 0, |
| 79 | (window[kCGWindowAlpha as String] as? Double ?? 1) > 0 else { continue } |
| 80 | let owner = window[kCGWindowOwnerPID as String] as? Int32 |
| 81 | if owner == front.processIdentifier && bounds.width >= 100 && bounds.height >= 60 { |
| 82 | let region = bounds.intersection(display) |
| 83 | guard !region.isNull, region.width >= 80, region.height >= 40, |
| 84 | let id = window[kCGWindowNumber as String] as? UInt32 else { |
| 85 | throw Failure(7, "maintenance_window_unavailable") |
| 86 | } |
| 87 | guard try consoleSession() == session else { throw Failure(4, "requires_gui_login") } |
| 88 | guard NSWorkspace.shared.frontmostApplication?.processIdentifier == front.processIdentifier else { |
| 89 | throw Failure(7, "maintenance_foreground_changed") |
| 90 | } |
| 91 | if let blocker = covering.first(where: { $0.bounds.intersects(region) }) { |
| 92 | let bundle = blocker.pid.flatMap { NSRunningApplication(processIdentifier: $0)?.bundleIdentifier } |
| 93 | return ["error": "maintenance_window_obscured", "blocking_pid": blocker.pid ?? 0, |
| 94 | "blocking_window": blocker.window ?? 0, "blocking_bundle": bundle ?? ""] |
| 95 | } |
| 96 | return ["version": 1, "session": session, "user": NSUserName(), "pid": front.processIdentifier, |
| 97 | "window": id, "bundle": front.bundleIdentifier!, |
| 98 | "password_focused": MacSetupPassword.passwordFocused(front, window: bounds), |
| 99 | "rect": [region.minX, region.minY, region.width, region.height], |
| 100 | "display": [display.minX, display.minY, display.width, display.height]] |
| 101 | } |
| 102 | if owner != front.processIdentifier { |
| 103 | covering.append((bounds, owner, window[kCGWindowNumber as String] as? UInt32)) |
| 104 | } |
| 105 | } |
| 106 | throw Failure(7, "maintenance_window_unavailable") |
| 107 | } |
| 108 | } |