From 2f957cc719b6462fdeae120ffc10bbba049b8e91 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Fri, 23 Oct 2026 18:18:08 -0700 Subject: [PATCH] Approve Mac VM prompts unattended and run guest tools on CLT Python 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.5 --- tools/install-mac-computer.py | 4 +- tools/install-mac-prompt-approver.py | 60 ++++++++++++ tools/mac-agent-vm.md | 16 ++++ tools/mac-prompt-approver.swift | 138 +++++++++++++++++++++++++++ tools/mac-vm-bridge.py | 3 +- 5 files changed, 218 insertions(+), 3 deletions(-) create mode 100644 tools/install-mac-prompt-approver.py create mode 100644 tools/mac-prompt-approver.swift diff --git a/tools/install-mac-computer.py b/tools/install-mac-computer.py index b8a5f72cbe31336950f7275914fe4f257d1aac8b..5c5db8f751e270c863924b75738eec395d094cfa 100644 --- a/tools/install-mac-computer.py +++ b/tools/install-mac-computer.py @@ -11,7 +11,7 @@ root = Path(__file__).resolve().parent identity = vm.tart("exec", vm.NAME, "/bin/hostname", capture_output=True, text=True, timeout=10).stdout.strip() print("Installing guest tools in " + identity, flush=True) source = {name: (root / name).read_text() for name in ["mac-computer.py", "mac-agent-gui.swift"]} -vm.tart("exec", "-i", vm.NAME, "/usr/bin/python3", "-c", ''' +vm.tart("exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", "-c", ''' import json, pathlib, subprocess, sys, tempfile files = json.load(sys.stdin) with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as temporary: @@ -33,7 +33,7 @@ for name in ["mac-agent-vm.py", "mac-vm-bridge.py"]: os.replace(pending, target) finally: pending.unlink(missing_ok=True) -result = vm.tart("exec", "-i", vm.NAME, "/usr/bin/python3", "/usr/local/libexec/snowglobe-computer.py", +result = vm.tart("exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", "/usr/local/libexec/snowglobe-computer.py", input=b'{"action":"status"}', capture_output=True, timeout=15) value = json.loads(result.stdout) if not all(value.get("permissions", {}).get(name) for name in ["accessibility", "screenCapture", "postEvent"]): diff --git a/tools/install-mac-prompt-approver.py b/tools/install-mac-prompt-approver.py new file mode 100644 index 0000000000000000000000000000000000000000..0c633cb259220013772640bfa77a8729087f276e --- /dev/null +++ b/tools/install-mac-prompt-approver.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Install the guest LaunchAgent that approves system permission and password prompts.""" +from importlib import import_module +import json +from pathlib import Path + +vm = import_module("mac-agent-vm") +request = { + "source": (Path(__file__).resolve().parent / "mac-prompt-approver.swift").read_text(), + "password": (vm.ROOT / "private/password").read_text().strip(), +} +vm.tart("exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", "-c", ''' +import hashlib, json, os, pathlib, plistlib, subprocess, sys, tempfile, time +request = json.load(sys.stdin) +label = "net.paperclover.prompt-approver" +support = pathlib.Path.home() / "Library/Application Support" / label +support.mkdir(mode=0o700, parents=True, exist_ok=True) +password = support / "password" +password.touch(mode=0o600) +password.write_text(request["password"]) +with tempfile.TemporaryDirectory(prefix="prompt-approver-install-") as temporary: + root = pathlib.Path(temporary) + (root / "main.swift").write_text(request["source"]) + subprocess.run(["/usr/bin/swiftc", "-O", str(root / "main.swift"), "-o", str(root / "prompt-approver")], check=True) + # TCC keeps an ad-hoc binary's first cdhash for its path, so each build needs its own path. + built = (root / "prompt-approver").read_bytes() + binary = pathlib.Path(f"/usr/local/libexec/prompt-approver-{hashlib.sha256(built).hexdigest()[:12]}/prompt-approver") + if not binary.exists(): + subprocess.run(["sudo", "-n", "install", "-d", str(binary.parent)], check=True) + subprocess.run(["sudo", "-n", "install", "-m", "755", str(root / "prompt-approver"), str(binary)], check=True) + for old in pathlib.Path("/usr/local/libexec").glob("prompt-approver-*"): + if old != binary.parent: + subprocess.run(["sudo", "-n", "rm", "-rf", str(old)], check=True) +agent = pathlib.Path.home() / f"Library/LaunchAgents/{label}.plist" +agent.write_bytes(plistlib.dumps({ + "Label": label, + "ProgramArguments": [str(binary), str(support)], + "RunAtLoad": True, + "KeepAlive": True, + "StandardErrorPath": str(pathlib.Path.home() / "Library/Logs/prompt-approver.log"), +})) +domain = f"gui/{os.getuid()}" +subprocess.run(["launchctl", "bootout", f"{domain}/{label}"], stderr=subprocess.DEVNULL) +subprocess.run(["launchctl", "bootstrap", domain, str(agent)], check=True) +# A copy run under this already-approved guest agent approves the LaunchAgent's own Accessibility request. +log = pathlib.Path.home() / "Library/Logs/prompt-approver.log" +start = log.stat().st_size if log.exists() else 0 +helper = subprocess.Popen([str(binary), str(support)]) +try: + for _ in range(120): + with log.open() as stream: + stream.seek(start) + if "Accessibility approved" in stream.read(): + break + time.sleep(1) + else: + sys.exit("prompt-approver was not approved for Accessibility; approve it in System Settings.") +finally: + helper.terminate() +''', input=json.dumps(request).encode(), timeout=180) diff --git a/tools/mac-agent-vm.md b/tools/mac-agent-vm.md index 3f7e032e77c9a067b19846045657e7f9f8ac8fd6..1cfaf85411c27fb068694321f0de0dd08d733e5a 100644 --- a/tools/mac-agent-vm.md +++ b/tools/mac-agent-vm.md @@ -14,6 +14,10 @@ despite permissive POSIX modes. The signed Tart app is protected by its ancestor directory ACL because macOS App Management rejects modifying the bundle's own ACL. Volume ownership and host security settings are unchanged. +Documents is APFS-encrypted (Project, in the same container, is not). Its +passphrase is in the host login keychain under the volume UUID, and the +`net.paperclover.documents-unlock` LaunchAgent unlocks the volume at login. + ```sh python3 tools/mac-agent-vm.py start python3 tools/mac-agent-vm.py status @@ -244,6 +248,18 @@ future apps and request-only categories can still prompt. SIP remains enabled. FSEvents and durable disk synchronization remain enabled. Apply OS updates deliberately between test runs, then recheck GUI permissions and boot. +Future prompts are approved unattended by the `net.paperclover.prompt-approver` +LaunchAgent: TCC alerts, Accessibility requests (via System Settings), +keychain access, and administrator authorization. Password fields get the +guest login password from `password` in its Application Support directory, or +`keychains/NAME` for a prompt naming another keychain; `knife-signing` links to +`~/.config/knife-signing.keychain-db.password`. A prompt still open after two +attempts is cancelled. Every action is logged to +`~/Library/Logs/prompt-approver.log`. Install or update it with +`python3 tools/install-mac-prompt-approver.py`; a changed build gets a new path +because TCC pins an ad-hoc binary's first code hash to its path, and the +installer approves it by running a copy under the already-approved guest agent. + Shared `jj`, `pnpm`, and workspace command routing is maintained in [project tools](project-store.md). diff --git a/tools/mac-prompt-approver.swift b/tools/mac-prompt-approver.swift new file mode 100644 index 0000000000000000000000000000000000000000..514cbbdf38e16f063013392ebaf45ee762bb32bf --- /dev/null +++ b/tools/mac-prompt-approver.swift @@ -0,0 +1,138 @@ +import AppKit +import ApplicationServices + +/// Approves every system permission, keychain, and administrator prompt in the unattended guest. +/// Holds `password` (the login password) and `keychains/NAME` for other keychains. +let secrets = URL(fileURLWithPath: CommandLine.arguments[1]) +let approve = ["Always Allow", "Allow", "Allow Access", "OK", "Modify Settings", "Open System Settings", "Allow While Using App", "Continue"] +let giveUp = ["Cancel", "Deny", "Don’t Allow"] +var attempts: [String: (count: Int, last: Date)] = [:] +/// The Accessibility prompt only links to System Settings, where the named app's switch must be turned on. +var settingsTarget: (app: String, until: Date)? + +func log(_ message: String) { + FileHandle.standardError.write(Data("\(ISO8601DateFormatter().string(from: Date())) \(message)\n".utf8)) +} + +func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? { + var value: CFTypeRef? + return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil +} + +func role(_ element: AXUIElement) -> String? { attribute(element, "AXRole") as? String } + +/// SwiftUI buttons carry their label in AXDescription. +func name(_ element: AXUIElement) -> String? { + (attribute(element, "AXTitle") as? String).flatMap { $0.isEmpty ? nil : $0 } ?? attribute(element, "AXDescription") as? String +} + +func descendants(_ element: AXUIElement, depth: Int = 0) -> [AXUIElement] { + guard depth < 14, let children = attribute(element, "AXChildren") as? [AXUIElement] else { return [] } + return children + children.flatMap { descendants($0, depth: depth + 1) } +} + +/// SecurityAgent can report no AXWindows while its focused window is a live prompt. +func windows(_ app: AXUIElement) -> [AXUIElement] { + var result = attribute(app, "AXWindows") as? [AXUIElement] ?? [] + if let focused = attribute(app, "AXFocusedWindow"), !result.contains(where: { CFEqual($0, focused) }) { + result.append(focused as! AXUIElement) + } + return result +} + +func password(for text: String) -> String? { + let keychain = text.range(of: "” keychain").flatMap { text[..<$0.lowerBound].split(separator: "“").last }.map(String.init) + let file = keychain.flatMap { $0 == "login" ? nil : secrets.appending(components: "keychains", $0) } ?? secrets.appending(component: "password") + return (try? String(contentsOf: file, encoding: .utf8))?.trimmingCharacters(in: .newlines) +} + +func press(_ buttons: [AXUIElement], _ titles: [String]) -> String? { + for title in titles { + if let button = buttons.first(where: { name($0) == title }), + AXUIElementPerformAction(button, kAXPressAction as CFString) == .success { + return title + } + } + return nil +} + +func handle(_ prompt: AXUIElement, pid: pid_t) { + let elements = descendants(prompt) + let text = elements.filter { role($0) == "AXStaticText" }.compactMap { attribute($0, "AXValue") as? String } + .filter { !$0.isEmpty }.joined(separator: " ") + let buttons = elements.filter { role($0) == "AXButton" } + let secure = elements.filter { attribute($0, "AXSubrole") as? String == "AXSecureTextField" } + let key = "\(pid) \(text)" + let now = Date() + var attempt = attempts[key].flatMap { now.timeIntervalSince($0.last) < 60 ? $0 : nil } ?? (0, .distantPast) + // Give a pressed prompt time to close before treating it as rejected. + guard now.timeIntervalSince(attempt.last) > 3 else { return } + attempt = (attempt.count + 1, now) + attempts[key] = attempt + if attempt.count > 2 { + log("gave up (\(press(buttons, giveUp) ?? "no cancel button")): \(text)") + return + } + if !secure.isEmpty { + guard let password = password(for: text) else { return log("no password for: \(text)") } + for field in secure { AXUIElementSetAttributeValue(field, kAXValueAttribute as CFString, password as CFString) } + } + guard let pressed = press(buttons, approve) else { return log("no approve button: \(text)") } + if pressed == "Open System Settings", let app = text.split(separator: "”").first?.split(separator: "“").last { + settingsTarget = (String(app), now.addingTimeInterval(60)) + } + log("\(pressed): \(text)") +} + +/// The list only exposes rows scrolled into view, so this sweeps it with real scroll events until the app's switch is on. +func handleSettings(_ app: AXUIElement, pid: pid_t, target: String) { + for window in windows(app) { + let elements = descendants(window) + for sheet in elements where role(sheet) == "AXSheet" { handle(sheet, pid: pid) } + var list: AXUIElement? + for row in elements where attribute(row, "AXSubrole") as? String == "AXOutlineRow" { + let cells = descendants(row) + guard cells.contains(where: { attribute($0, "AXSubrole") as? String == "AXSwitch" }) else { continue } + list = list ?? row + guard cells.contains(where: { attribute($0, "AXValue") as? String == target }) else { continue } + for toggle in cells where attribute(toggle, "AXSubrole") as? String == "AXSwitch" + && (attribute(toggle, "AXValue") as? NSNumber)?.intValue == 0 { + if AXUIElementPerformAction(toggle, kAXPressAction as CFString) == .success { log("switched on: \(target)") } + } + } + guard var area = list else { continue } + var current = area + while let parent = attribute(current, "AXParent"), role(parent as! AXUIElement) != "AXWindow" { + current = parent as! AXUIElement + if role(current) == "AXScrollArea" { area = current } + } + var origin = CGPoint.zero, size = CGSize.zero + guard let position = attribute(area, "AXPosition"), let extent = attribute(area, "AXSize") else { continue } + AXValueGetValue(position as! AXValue, .cgPoint, &origin) + AXValueGetValue(extent as! AXValue, .cgSize, &size) + let center = CGPoint(x: origin.x + size.width / 2, y: origin.y + size.height / 2) + CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: center, mouseButton: .left)?.post(tap: .cghidEventTap) + let lines: Int32 = Int(Date().timeIntervalSince1970) % 12 == 0 ? 5000 : -40 + CGEvent(scrollWheelEvent2Source: nil, units: .line, wheelCount: 1, wheel1: lines, wheel2: 0, wheel3: 0)?.post(tap: .cghidEventTap) + } +} + +_ = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary) +var trusted = false +Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in + guard AXIsProcessTrusted() else { return } + if !trusted { trusted = true; log("Accessibility approved; watching prompts") } + // NSWorkspace.runningApplications never refreshes without an NSApplication; this lookup is live. + for bundle in ["com.apple.UserNotificationCenter", "com.apple.SecurityAgent", "com.apple.accessibility.universalAccessAuthWarn", "com.apple.systempreferences"] { + for app in NSRunningApplication.runningApplications(withBundleIdentifier: bundle) { + let element = AXUIElementCreateApplication(app.processIdentifier) + AXUIElementSetMessagingTimeout(element, 2) + if bundle != "com.apple.systempreferences" { + for window in windows(element) { handle(window, pid: app.processIdentifier) } + } else if let target = settingsTarget, Date() < target.until { + handleSettings(element, pid: app.processIdentifier, target: target.app) + } + } + } +} +RunLoop.main.run() diff --git a/tools/mac-vm-bridge.py b/tools/mac-vm-bridge.py index e2b5b76ad29fcfe654db075d35faf65b5a3e5c55..c9dcfdeb0a6399fc565dde6508a9b085b161036b 100644 --- a/tools/mac-vm-bridge.py +++ b/tools/mac-vm-bridge.py @@ -48,7 +48,8 @@ def computer(request): with tempfile.TemporaryFile() as source, selectors.DefaultSelector() as selector: source.write(json.dumps(request).encode()) source.seek(0) - process = subprocess.Popen([str(vm.TART), "exec", "-i", vm.NAME, "/usr/bin/python3", + # Recovery must work when the selected Xcode is unavailable. + process = subprocess.Popen([str(vm.TART), "exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", "/usr/local/libexec/snowglobe-computer.py"], stdin=source, stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True, env={**os.environ, "TART_HOME": str(vm.ROOT / "state")}) output = bytearray() -- 2.54.1