authoravatarclover caruso<git@paperclover.net>2026-10-23 18:18:08-07:00
committeravatarclover caruso<git@paperclover.net>2026-10-24 19:01:23-07:00
log2f957cc719b6462fdeae120ffc10bbba049b8e91
tree240c7397a466c9dfe584c44f0ecaac686d230bf6
parent4ae0f11857a0e606a692e8b3c90bd65ce8c05bc7
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

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

5 files changed, 218 insertions(+), 3 deletions(-)

tools/install-mac-computer.py+2-2
......@@ -11,7 +11,7 @@ root = Path(__file__).resolve().parent
1111identity = vm.tart("exec", vm.NAME, "/bin/hostname", capture_output=True, text=True, timeout=10).stdout.strip()
1212print("Installing guest tools in " + identity, flush=True)
1313source = {name: (root / name).read_text() for name in ["mac-computer.py", "mac-agent-gui.swift"]}
14vm.tart("exec", "-i", vm.NAME, "/usr/bin/python3", "-c", '''
14vm.tart("exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", "-c", '''
1515import json, pathlib, subprocess, sys, tempfile
1616files = json.load(sys.stdin)
1717with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as temporary:
......@@ -33,7 +33,7 @@ for name in ["mac-agent-vm.py", "mac-vm-bridge.py"]:
3333 os.replace(pending, target)
3434 finally:
3535 pending.unlink(missing_ok=True)
36result = vm.tart("exec", "-i", vm.NAME, "/usr/bin/python3", "/usr/local/libexec/snowglobe-computer.py",
36result = vm.tart("exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", "/usr/local/libexec/snowglobe-computer.py",
3737 input=b'{"action":"status"}', capture_output=True, timeout=15)
3838value = json.loads(result.stdout)
3939if 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."""
3from importlib import import_module
4import json
5from pathlib import Path
6
7vm = import_module("mac-agent-vm")
8request = {
9 "source": (Path(__file__).resolve().parent / "mac-prompt-approver.swift").read_text(),
10 "password": (vm.ROOT / "private/password").read_text().strip(),
11}
12vm.tart("exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", "-c", '''
13import hashlib, json, os, pathlib, plistlib, subprocess, sys, tempfile, time
14request = json.load(sys.stdin)
15label = "net.paperclover.prompt-approver"
16support = pathlib.Path.home() / "Library/Application Support" / label
17support.mkdir(mode=0o700, parents=True, exist_ok=True)
18password = support / "password"
19password.touch(mode=0o600)
20password.write_text(request["password"])
21with 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)
34agent = pathlib.Path.home() / f"Library/LaunchAgents/{label}.plist"
35agent.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}))
42domain = f"gui/{os.getuid()}"
43subprocess.run(["launchctl", "bootout", f"{domain}/{label}"], stderr=subprocess.DEVNULL)
44subprocess.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.
46log = pathlib.Path.home() / "Library/Logs/prompt-approver.log"
47start = log.stat().st_size if log.exists() else 0
48helper = subprocess.Popen([str(binary), str(support)])
49try:
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.")
58finally:
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
1414ancestor directory ACL because macOS App Management rejects modifying the
1515bundle's own ACL. Volume ownership and host security settings are unchanged.
1616
17Documents is APFS-encrypted (Project, in the same container, is not). Its
18passphrase is in the host login keychain under the volume UUID, and the
19`net.paperclover.documents-unlock` LaunchAgent unlocks the volume at login.
20
1721```sh
1822python3 tools/mac-agent-vm.py start
1923python3 tools/mac-agent-vm.py status
......@@ -244,6 +248,18 @@ future apps and request-only categories can still prompt. SIP remains enabled.
244248FSEvents and durable disk synchronization remain enabled. Apply OS updates
245249deliberately between test runs, then recheck GUI permissions and boot.
246250
251Future prompts are approved unattended by the `net.paperclover.prompt-approver`
252LaunchAgent: TCC alerts, Accessibility requests (via System Settings),
253keychain access, and administrator authorization. Password fields get the
254guest 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
257attempts 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
260because TCC pins an ad-hoc binary's first code hash to its path, and the
261installer approves it by running a copy under the already-approved guest agent.
262
247263Shared `jj`, `pnpm`, and workspace command routing is maintained in
248264[project tools](project-store.md).
249265
tools/mac-prompt-approver.swift created+138
......@@ -0,0 +1,138 @@
1import AppKit
2import 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.
6let secrets = URL(fileURLWithPath: CommandLine.arguments[1])
7let approve = ["Always Allow", "Allow", "Allow Access", "OK", "Modify Settings", "Open System Settings", "Allow While Using App", "Continue"]
8let giveUp = ["Cancel", "Deny", "Don’t Allow"]
9var 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.
11var settingsTarget: (app: String, until: Date)?
12
13func log(_ message: String) {
14 FileHandle.standardError.write(Data("\(ISO8601DateFormatter().string(from: Date())) \(message)\n".utf8))
15}
16
17func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? {
18 var value: CFTypeRef?
19 return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil
20}
21
22func role(_ element: AXUIElement) -> String? { attribute(element, "AXRole") as? String }
23
24/// SwiftUI buttons carry their label in AXDescription.
25func name(_ element: AXUIElement) -> String? {
26 (attribute(element, "AXTitle") as? String).flatMap { $0.isEmpty ? nil : $0 } ?? attribute(element, "AXDescription") as? String
27}
28
29func 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.
35func 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
43func 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
49func 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
59func 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.
88func 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)
121var trusted = false
122Timer.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}
138RunLoop.main.run()
tools/mac-vm-bridge.py+2-1
......@@ -48,7 +48,8 @@ def computer(request):
4848 with tempfile.TemporaryFile() as source, selectors.DefaultSelector() as selector:
4949 source.write(json.dumps(request).encode())
5050 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",
5253 "/usr/local/libexec/snowglobe-computer.py"], stdin=source, stdout=subprocess.PIPE,
5354 stderr=subprocess.PIPE, start_new_session=True, env={**os.environ, "TART_HOME": str(vm.ROOT / "state")})
5455 output = bytearray()