| 1 | import AppKit |
| 2 | import ApplicationServices |
| 3 | |
| 4 | /// Approves every system permission, keychain, and administrator prompt in the unattended guest. |
| 5 | /// Holds `password` (the login password) and `keychains/NAME` for other keychains. |
| 6 | let secrets = URL(fileURLWithPath: CommandLine.arguments[1]) |
| 7 | let approve = ["Always Allow", "Allow", "Allow Access", "OK", "Modify Settings", "Open System Settings", "Allow While Using App", "Continue"] |
| 8 | let giveUp = ["Cancel", "Deny", "Don’t Allow"] |
| 9 | var attempts: [String: (count: Int, last: Date)] = [:] |
| 10 | /// The Accessibility prompt only links to System Settings, where the named app's switch must be turned on. |
| 11 | var settingsTarget: (app: String, until: Date)? |
| 12 | |
| 13 | func log(_ message: String) { |
| 14 | FileHandle.standardError.write(Data("\(ISO8601DateFormatter().string(from: Date())) \(message)\n".utf8)) |
| 15 | } |
| 16 | |
| 17 | func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? { |
| 18 | var value: CFTypeRef? |
| 19 | return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil |
| 20 | } |
| 21 | |
| 22 | func role(_ element: AXUIElement) -> String? { attribute(element, "AXRole") as? String } |
| 23 | |
| 24 | /// SwiftUI buttons carry their label in AXDescription. |
| 25 | func name(_ element: AXUIElement) -> String? { |
| 26 | (attribute(element, "AXTitle") as? String).flatMap { $0.isEmpty ? nil : $0 } ?? attribute(element, "AXDescription") as? String |
| 27 | } |
| 28 | |
| 29 | func descendants(_ element: AXUIElement, depth: Int = 0) -> [AXUIElement] { |
| 30 | guard depth < 14, let children = attribute(element, "AXChildren") as? [AXUIElement] else { return [] } |
| 31 | return children + children.flatMap { descendants($0, depth: depth + 1) } |
| 32 | } |
| 33 | |
| 34 | /// SecurityAgent can report no AXWindows while its focused window is a live prompt. |
| 35 | func windows(_ app: AXUIElement) -> [AXUIElement] { |
| 36 | var result = attribute(app, "AXWindows") as? [AXUIElement] ?? [] |
| 37 | if let focused = attribute(app, "AXFocusedWindow"), !result.contains(where: { CFEqual($0, focused) }) { |
| 38 | result.append(focused as! AXUIElement) |
| 39 | } |
| 40 | return result |
| 41 | } |
| 42 | |
| 43 | func password(for text: String) -> String? { |
| 44 | let keychain = text.range(of: "” keychain").flatMap { text[..<$0.lowerBound].split(separator: "“").last }.map(String.init) |
| 45 | let file = keychain.flatMap { $0 == "login" ? nil : secrets.appending(components: "keychains", $0) } ?? secrets.appending(component: "password") |
| 46 | return (try? String(contentsOf: file, encoding: .utf8))?.trimmingCharacters(in: .newlines) |
| 47 | } |
| 48 | |
| 49 | func press(_ buttons: [AXUIElement], _ titles: [String]) -> String? { |
| 50 | for title in titles { |
| 51 | if let button = buttons.first(where: { name($0) == title }), |
| 52 | AXUIElementPerformAction(button, kAXPressAction as CFString) == .success { |
| 53 | return title |
| 54 | } |
| 55 | } |
| 56 | return nil |
| 57 | } |
| 58 | |
| 59 | func handle(_ prompt: AXUIElement, pid: pid_t) { |
| 60 | let elements = descendants(prompt) |
| 61 | let text = elements.filter { role($0) == "AXStaticText" }.compactMap { attribute($0, "AXValue") as? String } |
| 62 | .filter { !$0.isEmpty }.joined(separator: " ") |
| 63 | let buttons = elements.filter { role($0) == "AXButton" } |
| 64 | let secure = elements.filter { attribute($0, "AXSubrole") as? String == "AXSecureTextField" } |
| 65 | let key = "\(pid) \(text)" |
| 66 | let now = Date() |
| 67 | var attempt = attempts[key].flatMap { now.timeIntervalSince($0.last) < 60 ? $0 : nil } ?? (0, .distantPast) |
| 68 | // Give a pressed prompt time to close before treating it as rejected. |
| 69 | guard now.timeIntervalSince(attempt.last) > 3 else { return } |
| 70 | attempt = (attempt.count + 1, now) |
| 71 | attempts[key] = attempt |
| 72 | if attempt.count > 2 { |
| 73 | log("gave up (\(press(buttons, giveUp) ?? "no cancel button")): \(text)") |
| 74 | return |
| 75 | } |
| 76 | if !secure.isEmpty { |
| 77 | guard let password = password(for: text) else { return log("no password for: \(text)") } |
| 78 | for field in secure { AXUIElementSetAttributeValue(field, kAXValueAttribute as CFString, password as CFString) } |
| 79 | } |
| 80 | guard let pressed = press(buttons, approve) else { return log("no approve button: \(text)") } |
| 81 | if pressed == "Open System Settings", let app = text.split(separator: "”").first?.split(separator: "“").last { |
| 82 | settingsTarget = (String(app), now.addingTimeInterval(60)) |
| 83 | } |
| 84 | log("\(pressed): \(text)") |
| 85 | } |
| 86 | |
| 87 | /// The list only exposes rows scrolled into view, so this sweeps it with real scroll events until the app's switch is on. |
| 88 | func handleSettings(_ app: AXUIElement, pid: pid_t, target: String) { |
| 89 | for window in windows(app) { |
| 90 | let elements = descendants(window) |
| 91 | for sheet in elements where role(sheet) == "AXSheet" { handle(sheet, pid: pid) } |
| 92 | var list: AXUIElement? |
| 93 | for row in elements where attribute(row, "AXSubrole") as? String == "AXOutlineRow" { |
| 94 | let cells = descendants(row) |
| 95 | guard cells.contains(where: { attribute($0, "AXSubrole") as? String == "AXSwitch" }) else { continue } |
| 96 | list = list ?? row |
| 97 | guard cells.contains(where: { attribute($0, "AXValue") as? String == target }) else { continue } |
| 98 | for toggle in cells where attribute(toggle, "AXSubrole") as? String == "AXSwitch" |
| 99 | && (attribute(toggle, "AXValue") as? NSNumber)?.intValue == 0 { |
| 100 | if AXUIElementPerformAction(toggle, kAXPressAction as CFString) == .success { log("switched on: \(target)") } |
| 101 | } |
| 102 | } |
| 103 | guard var area = list else { continue } |
| 104 | var current = area |
| 105 | while let parent = attribute(current, "AXParent"), role(parent as! AXUIElement) != "AXWindow" { |
| 106 | current = parent as! AXUIElement |
| 107 | if role(current) == "AXScrollArea" { area = current } |
| 108 | } |
| 109 | var origin = CGPoint.zero, size = CGSize.zero |
| 110 | guard let position = attribute(area, "AXPosition"), let extent = attribute(area, "AXSize") else { continue } |
| 111 | AXValueGetValue(position as! AXValue, .cgPoint, &origin) |
| 112 | AXValueGetValue(extent as! AXValue, .cgSize, &size) |
| 113 | let center = CGPoint(x: origin.x + size.width / 2, y: origin.y + size.height / 2) |
| 114 | CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: center, mouseButton: .left)?.post(tap: .cghidEventTap) |
| 115 | let lines: Int32 = Int(Date().timeIntervalSince1970) % 12 == 0 ? 5000 : -40 |
| 116 | CGEvent(scrollWheelEvent2Source: nil, units: .line, wheelCount: 1, wheel1: lines, wheel2: 0, wheel3: 0)?.post(tap: .cghidEventTap) |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | _ = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary) |
| 121 | var trusted = false |
| 122 | Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in |
| 123 | guard AXIsProcessTrusted() else { return } |
| 124 | if !trusted { trusted = true; log("Accessibility approved; watching prompts") } |
| 125 | // NSWorkspace.runningApplications never refreshes without an NSApplication; this lookup is live. |
| 126 | for bundle in ["com.apple.UserNotificationCenter", "com.apple.SecurityAgent", "com.apple.accessibility.universalAccessAuthWarn", "com.apple.systempreferences"] { |
| 127 | for app in NSRunningApplication.runningApplications(withBundleIdentifier: bundle) { |
| 128 | let element = AXUIElementCreateApplication(app.processIdentifier) |
| 129 | AXUIElementSetMessagingTimeout(element, 2) |
| 130 | if bundle != "com.apple.systempreferences" { |
| 131 | for window in windows(element) { handle(window, pid: app.processIdentifier) } |
| 132 | } else if let target = settingsTarget, Date() < target.until { |
| 133 | handleSettings(element, pid: app.processIdentifier, target: target.app) |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | RunLoop.main.run() |