| author | |
| committer | |
| log | 2f957cc719b6462fdeae120ffc10bbba049b8e91 |
| tree | 240c7397a466c9dfe584c44f0ecaac686d230bf6 |
| parent | 4ae0f11857a0e606a692e8b3c90bd65ce8c05bc7 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
A prompt-approver LaunchAgent answers TCC, Accessibility, keychain, and
authorization prompts in the Mac agent VM. Guest computer tools run on the
Command Line Tools Python so recovery works without the selected Xcode.
Assisted-by: claude-opus-5.55 files changed, 218 insertions(+), 3 deletions(-)
tools/install-mac-computer.py+2-2| ... | @@ -11,7 +11,7 @@ root = Path(__file__).resolve().parent | ... | @@ -11,7 +11,7 @@ root = Path(__file__).resolve().parent |
| 11 | identity = vm.tart("exec", vm.NAME, "/bin/hostname", capture_output=True, text=True, timeout=10).stdout.strip() | 11 | identity = vm.tart("exec", vm.NAME, "/bin/hostname", capture_output=True, text=True, timeout=10).stdout.strip() |
| 12 | print("Installing guest tools in " + identity, flush=True) | 12 | print("Installing guest tools in " + identity, flush=True) |
| 13 | source = {name: (root / name).read_text() for name in ["mac-computer.py", "mac-agent-gui.swift"]} | 13 | source = {name: (root / name).read_text() for name in ["mac-computer.py", "mac-agent-gui.swift"]} |
| 14 | vm.tart("exec", "-i", vm.NAME, "/usr/bin/python3", "-c", ''' | 14 | vm.tart("exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", "-c", ''' |
| 15 | import json, pathlib, subprocess, sys, tempfile | 15 | import json, pathlib, subprocess, sys, tempfile |
| 16 | files = json.load(sys.stdin) | 16 | files = json.load(sys.stdin) |
| 17 | with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as temporary: | 17 | with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as temporary: |
| ... | @@ -33,7 +33,7 @@ for name in ["mac-agent-vm.py", "mac-vm-bridge.py"]: | ... | @@ -33,7 +33,7 @@ for name in ["mac-agent-vm.py", "mac-vm-bridge.py"]: |
| 33 | os.replace(pending, target) | 33 | os.replace(pending, target) |
| 34 | finally: | 34 | finally: |
| 35 | pending.unlink(missing_ok=True) | 35 | pending.unlink(missing_ok=True) |
| 36 | result = vm.tart("exec", "-i", vm.NAME, "/usr/bin/python3", "/usr/local/libexec/snowglobe-computer.py", | 36 | result = vm.tart("exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", "/usr/local/libexec/snowglobe-computer.py", |
| 37 | input=b'{"action":"status"}', capture_output=True, timeout=15) | 37 | input=b'{"action":"status"}', capture_output=True, timeout=15) |
| 38 | value = json.loads(result.stdout) | 38 | value = json.loads(result.stdout) |
| 39 | if not all(value.get("permissions", {}).get(name) for name in ["accessibility", "screenCapture", "postEvent"]): | 39 | if not all(value.get("permissions", {}).get(name) for name in ["accessibility", "screenCapture", "postEvent"]): |
tools/install-mac-prompt-approver.py created+60| ... | @@ -0,0 +1,60 @@ | ||
| 1 | #!/usr/bin/env python3 | ||
| 2 | """Install the guest LaunchAgent that approves system permission and password prompts.""" | ||
| 3 | from importlib import import_module | ||
| 4 | import json | ||
| 5 | from pathlib import Path | ||
| 6 | |||
| 7 | vm = import_module("mac-agent-vm") | ||
| 8 | request = { | ||
| 9 | "source": (Path(__file__).resolve().parent / "mac-prompt-approver.swift").read_text(), | ||
| 10 | "password": (vm.ROOT / "private/password").read_text().strip(), | ||
| 11 | } | ||
| 12 | vm.tart("exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", "-c", ''' | ||
| 13 | import hashlib, json, os, pathlib, plistlib, subprocess, sys, tempfile, time | ||
| 14 | request = json.load(sys.stdin) | ||
| 15 | label = "net.paperclover.prompt-approver" | ||
| 16 | support = pathlib.Path.home() / "Library/Application Support" / label | ||
| 17 | support.mkdir(mode=0o700, parents=True, exist_ok=True) | ||
| 18 | password = support / "password" | ||
| 19 | password.touch(mode=0o600) | ||
| 20 | password.write_text(request["password"]) | ||
| 21 | with tempfile.TemporaryDirectory(prefix="prompt-approver-install-") as temporary: | ||
| 22 | root = pathlib.Path(temporary) | ||
| 23 | (root / "main.swift").write_text(request["source"]) | ||
| 24 | subprocess.run(["/usr/bin/swiftc", "-O", str(root / "main.swift"), "-o", str(root / "prompt-approver")], check=True) | ||
| 25 | # TCC keeps an ad-hoc binary's first cdhash for its path, so each build needs its own path. | ||
| 26 | built = (root / "prompt-approver").read_bytes() | ||
| 27 | binary = pathlib.Path(f"/usr/local/libexec/prompt-approver-{hashlib.sha256(built).hexdigest()[:12]}/prompt-approver") | ||
| 28 | if not binary.exists(): | ||
| 29 | subprocess.run(["sudo", "-n", "install", "-d", str(binary.parent)], check=True) | ||
| 30 | subprocess.run(["sudo", "-n", "install", "-m", "755", str(root / "prompt-approver"), str(binary)], check=True) | ||
| 31 | for old in pathlib.Path("/usr/local/libexec").glob("prompt-approver-*"): | ||
| 32 | if old != binary.parent: | ||
| 33 | subprocess.run(["sudo", "-n", "rm", "-rf", str(old)], check=True) | ||
| 34 | agent = pathlib.Path.home() / f"Library/LaunchAgents/{label}.plist" | ||
| 35 | agent.write_bytes(plistlib.dumps({ | ||
| 36 | "Label": label, | ||
| 37 | "ProgramArguments": [str(binary), str(support)], | ||
| 38 | "RunAtLoad": True, | ||
| 39 | "KeepAlive": True, | ||
| 40 | "StandardErrorPath": str(pathlib.Path.home() / "Library/Logs/prompt-approver.log"), | ||
| 41 | })) | ||
| 42 | domain = f"gui/{os.getuid()}" | ||
| 43 | subprocess.run(["launchctl", "bootout", f"{domain}/{label}"], stderr=subprocess.DEVNULL) | ||
| 44 | subprocess.run(["launchctl", "bootstrap", domain, str(agent)], check=True) | ||
| 45 | # A copy run under this already-approved guest agent approves the LaunchAgent's own Accessibility request. | ||
| 46 | log = pathlib.Path.home() / "Library/Logs/prompt-approver.log" | ||
| 47 | start = log.stat().st_size if log.exists() else 0 | ||
| 48 | helper = subprocess.Popen([str(binary), str(support)]) | ||
| 49 | try: | ||
| 50 | for _ in range(120): | ||
| 51 | with log.open() as stream: | ||
| 52 | stream.seek(start) | ||
| 53 | if "Accessibility approved" in stream.read(): | ||
| 54 | break | ||
| 55 | time.sleep(1) | ||
| 56 | else: | ||
| 57 | sys.exit("prompt-approver was not approved for Accessibility; approve it in System Settings.") | ||
| 58 | finally: | ||
| 59 | helper.terminate() | ||
| 60 | ''', input=json.dumps(request).encode(), timeout=180) | ||
tools/mac-agent-vm.md+16| ... | @@ -14,6 +14,10 @@ despite permissive POSIX modes. The signed Tart app is protected by its | ... | @@ -14,6 +14,10 @@ despite permissive POSIX modes. The signed Tart app is protected by its |
| 14 | ancestor directory ACL because macOS App Management rejects modifying the | 14 | ancestor directory ACL because macOS App Management rejects modifying the |
| 15 | bundle's own ACL. Volume ownership and host security settings are unchanged. | 15 | bundle's own ACL. Volume ownership and host security settings are unchanged. |
| 16 | 16 | ||
| 17 | Documents is APFS-encrypted (Project, in the same container, is not). Its | ||
| 18 | passphrase is in the host login keychain under the volume UUID, and the | ||
| 19 | `net.paperclover.documents-unlock` LaunchAgent unlocks the volume at login. | ||
| 20 | |||
| 17 | ```sh | 21 | ```sh |
| 18 | python3 tools/mac-agent-vm.py start | 22 | python3 tools/mac-agent-vm.py start |
| 19 | python3 tools/mac-agent-vm.py status | 23 | python3 tools/mac-agent-vm.py status |
| ... | @@ -244,6 +248,18 @@ future apps and request-only categories can still prompt. SIP remains enabled. | ... | @@ -244,6 +248,18 @@ future apps and request-only categories can still prompt. SIP remains enabled. |
| 244 | FSEvents and durable disk synchronization remain enabled. Apply OS updates | 248 | FSEvents and durable disk synchronization remain enabled. Apply OS updates |
| 245 | deliberately between test runs, then recheck GUI permissions and boot. | 249 | deliberately between test runs, then recheck GUI permissions and boot. |
| 246 | 250 | ||
| 251 | Future prompts are approved unattended by the `net.paperclover.prompt-approver` | ||
| 252 | LaunchAgent: TCC alerts, Accessibility requests (via System Settings), | ||
| 253 | keychain access, and administrator authorization. Password fields get the | ||
| 254 | guest login password from `password` in its Application Support directory, or | ||
| 255 | `keychains/NAME` for a prompt naming another keychain; `knife-signing` links to | ||
| 256 | `~/.config/knife-signing.keychain-db.password`. A prompt still open after two | ||
| 257 | attempts is cancelled. Every action is logged to | ||
| 258 | `~/Library/Logs/prompt-approver.log`. Install or update it with | ||
| 259 | `python3 tools/install-mac-prompt-approver.py`; a changed build gets a new path | ||
| 260 | because TCC pins an ad-hoc binary's first code hash to its path, and the | ||
| 261 | installer approves it by running a copy under the already-approved guest agent. | ||
| 262 | |||
| 247 | Shared `jj`, `pnpm`, and workspace command routing is maintained in | 263 | Shared `jj`, `pnpm`, and workspace command routing is maintained in |
| 248 | [project tools](project-store.md). | 264 | [project tools](project-store.md). |
| 249 | 265 |
tools/mac-prompt-approver.swift created+138| ... | @@ -0,0 +1,138 @@ | ||
| 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() | ||
tools/mac-vm-bridge.py+2-1| ... | @@ -48,7 +48,8 @@ def computer(request): | ... | @@ -48,7 +48,8 @@ def computer(request): |
| 48 | with tempfile.TemporaryFile() as source, selectors.DefaultSelector() as selector: | 48 | with tempfile.TemporaryFile() as source, selectors.DefaultSelector() as selector: |
| 49 | source.write(json.dumps(request).encode()) | 49 | source.write(json.dumps(request).encode()) |
| 50 | source.seek(0) | 50 | source.seek(0) |
| 51 | process = subprocess.Popen([str(vm.TART), "exec", "-i", vm.NAME, "/usr/bin/python3", | 51 | # Recovery must work when the selected Xcode is unavailable. |
| 52 | process = subprocess.Popen([str(vm.TART), "exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", | ||
| 52 | "/usr/local/libexec/snowglobe-computer.py"], stdin=source, stdout=subprocess.PIPE, | 53 | "/usr/local/libexec/snowglobe-computer.py"], stdin=source, stdout=subprocess.PIPE, |
| 53 | stderr=subprocess.PIPE, start_new_session=True, env={**os.environ, "TART_HOME": str(vm.ROOT / "state")}) | 54 | stderr=subprocess.PIPE, start_new_session=True, env={**os.environ, "TART_HOME": str(vm.ROOT / "state")}) |
| 54 | output = bytearray() | 55 | output = bytearray() |