跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

macos-setup-password.swift

241 行 · 15.7 KB历史下载
1import AppKit
2import IOKit
3import Security
4
5@MainActor
6enum MacSetupPassword {
7 private static func validateRequest(_ data: Data) throws {
8 guard data.count <= 4096, let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
9 value.isEmpty || (value.count == 1 && value["action"] as? String == "probe") else {
10 throw Failure(8, "setup_password_probe_request_invalid")
11 }
12 }
13
14 nonisolated private static func nextLine() -> Data? {
15 var data = Data()
16 var oversized = false
17 while true {
18 let byte = fgetc(stdin)
19 if byte == EOF { return data.isEmpty && !oversized ? nil : (oversized ? Data() : data) }
20 if byte == 10 { return oversized ? Data() : data }
21 if data.count < 4096 { data.append(UInt8(byte)) }
22 else { oversized = true }
23 }
24 }
25
26 static func runStream() -> Never {
27 _ = signal(SIGPIPE, SIG_IGN)
28 NSApplication.shared.setActivationPolicy(.prohibited)
29 DispatchQueue.global(qos: .userInitiated).async {
30 while let data = nextLine() {
31 let finished = DispatchSemaphore(value: 0)
32 DispatchQueue.main.async {
33 let response: [String: Any]
34 do {
35 try validateRequest(data)
36 response = try probe()
37 } catch { response = ["error": (error as? Failure)?.message ?? "setup_password_probe_failed"] }
38 do {
39 var encoded = try JSONSerialization.data(withJSONObject: response)
40 encoded.append(10)
41 try FileHandle.standardOutput.write(contentsOf: encoded)
42 } catch { exit(0) }
43 finished.signal()
44 }
45 finished.wait()
46 }
47 DispatchQueue.main.async { exit(0) }
48 }
49 NSApplication.shared.run()
50 exit(0)
51 }
52
53 struct Window {
54 let id: UInt32
55 let pid: pid_t
56 let bounds: CGRect
57 let layer: Int
58 var systemSurface = false
59 }
60
61 private static func signed(_ app: NSRunningApplication, bundle: String) -> Bool {
62 guard app.bundleIdentifier == bundle else { return false }
63 var code: SecCode?, requirement: SecRequirement?
64 return SecRequirementCreateWithString("anchor apple and identifier \"\(bundle)\"" as CFString, [], &requirement) == errSecSuccess &&
65 SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributePid as String: app.processIdentifier] as CFDictionary, [], &code) == errSecSuccess &&
66 code != nil && requirement != nil && SecCodeCheckValidity(code!, [], requirement!) == errSecSuccess
67 }
68
69 private static func consoleSession() throws -> String {
70 try consoleUser()
71 let entry = IORegistryGetRootEntry(kIOMainPortDefault)
72 guard entry != 0 else { throw Failure(4, "requires_gui_login") }
73 defer { IOObjectRelease(entry) }
74 guard let property = IORegistryEntryCreateCFProperty(entry, "IOConsoleUsers" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue(),
75 let sessions = property as? [[String: Any]] else { throw Failure(4, "requires_gui_login") }
76 let active = sessions.filter { $0["kCGSSessionOnConsoleKey"] as? Bool == true }
77 guard active.count == 1, let current = active.first,
78 current["kCGSessionLoginDoneKey"] as? Bool == true,
79 current["CGSSessionScreenIsLocked"] as? Bool != true,
80 current["kCGSSessionUserIDKey"] as? UInt32 == getuid(),
81 current["kCGSSessionUserNameKey"] as? String == NSUserName(),
82 let session = current["CGSSessionUniqueSessionUUID"] as? String,
83 UUID(uuidString: session) != nil else { throw Failure(4, "requires_gui_login") }
84 return session
85 }
86
87 static func select(windows: [Window], pid: pid_t, bundle: String, display: CGRect, accessibility: Bool) throws -> Window {
88 guard ["com.apple.systempreferences", "com.apple.authorizationhost"].contains(bundle),
89 let index = windows.firstIndex(where: { $0.pid == pid && $0.layer == 0 && $0.bounds.width >= 80 && $0.bounds.height >= 40 }) else {
90 throw Failure(7, "setup_password_window_unavailable")
91 }
92 let target = windows[index]
93 guard display.contains(target.bounds), target.id != 0 else { throw Failure(7, "setup_password_window_unavailable") }
94 if !accessibility && bundle == "com.apple.systempreferences" {
95 let parent = windows.dropFirst(index + 1).contains { window in
96 window.pid == pid && window.layer == 0 && window.bounds.contains(target.bounds) &&
97 window.bounds.width > target.bounds.width && window.bounds.height > target.bounds.height &&
98 target.bounds.width * target.bounds.height < window.bounds.width * window.bounds.height * 0.75
99 }
100 guard parent else { throw Failure(7, "setup_password_window_unavailable") }
101 }
102 for window in windows.prefix(index) where !window.systemSurface && window.bounds.intersects(target.bounds) {
103 throw Failure(7, "setup_password_window_obscured")
104 }
105 return target
106 }
107
108 static func allowsPasswordProcess(hostBundle: String, hostPID: pid_t, fieldPID: pid_t,
109 fieldBundle: String, appleSigned: Bool) -> Bool {
110 guard hostPID > 0, fieldPID > 0,
111 ["com.apple.systempreferences", "com.apple.authorizationhost"].contains(hostBundle) else { return false }
112 if fieldPID == hostPID { return true }
113 return hostBundle == "com.apple.systempreferences" && appleSigned &&
114 ["com.apple.settings.PrivacySecurity.extension", "com.apple.extensionkit.AppExtensionManagement"].contains(fieldBundle)
115 }
116
117 static func passwordFocused(_ app: NSRunningApplication, window: CGRect) -> Bool {
118 guard let bundle = app.bundleIdentifier, AXIsProcessTrusted(),
119 ["com.apple.systempreferences", "com.apple.authorizationhost"].contains(bundle), signed(app, bundle: bundle) else { return false }
120 let application = AXUIElementCreateApplication(app.processIdentifier)
121 AXUIElementSetMessagingTimeout(application, 0.25)
122 func attribute(_ element: AXUIElement, _ key: String) -> CFTypeRef? {
123 var value: CFTypeRef?
124 return AXUIElementCopyAttributeValue(element, key as CFString, &value) == .success ? value : nil
125 }
126 func bounds(_ element: AXUIElement) -> CGRect? {
127 var origin = CGPoint.zero, size = CGSize.zero
128 guard let position = attribute(element, kAXPositionAttribute), let extent = attribute(element, kAXSizeAttribute),
129 CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(extent) == AXValueGetTypeID(),
130 AXValueGetValue(position as! AXValue, .cgPoint, &origin), AXValueGetValue(extent as! AXValue, .cgSize, &size),
131 [origin.x, origin.y, size.width, size.height].allSatisfy({ $0.isFinite }), size.width > 0, size.height > 0 else { return nil }
132 return CGRect(origin: origin, size: size)
133 }
134 func ownsTarget(_ element: AXUIElement) -> Bool {
135 var pid: pid_t = 0
136 guard AXUIElementGetPid(element, &pid) == .success, pid == app.processIdentifier,
137 let role = attribute(element, kAXRoleAttribute) as? String, [kAXSheetRole, kAXWindowRole].contains(role),
138 let rect = bounds(element) else { return false }
139 return abs(rect.minX - window.minX) < 1 && abs(rect.minY - window.minY) < 1 &&
140 abs(rect.width - window.width) < 1 && abs(rect.height - window.height) < 1
141 }
142 guard let value = attribute(application, kAXFocusedUIElementAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() else { return false }
143 let field = value as! AXUIElement
144 AXUIElementSetMessagingTimeout(field, 0.25)
145 var pid: pid_t = 0
146 guard AXUIElementGetPid(field, &pid) == .success,
147 attribute(field, kAXSubroleAttribute) as? String == kAXSecureTextFieldSubrole,
148 attribute(field, kAXEnabledAttribute) as? Bool == true,
149 let fieldBounds = bounds(field), window.contains(fieldBounds) else { return false }
150 let owner = pid == app.processIdentifier ? app : NSRunningApplication(processIdentifier: pid)
151 let ownerBundle = owner?.bundleIdentifier ?? ""
152 guard allowsPasswordProcess(hostBundle: bundle, hostPID: app.processIdentifier, fieldPID: pid,
153 fieldBundle: ownerBundle, appleSigned: owner.map { signed($0, bundle: ownerBundle) } ?? false) else { return false }
154 // System Settings embeds Apple settings extensions. Their secure field
155 // can omit AXWindow; AXParent links it to the host's authorization sheet.
156 if let raw = attribute(field, kAXWindowAttribute), CFGetTypeID(raw) == AXUIElementGetTypeID(), ownsTarget(raw as! AXUIElement) { return true }
157 var ancestor = field
158 for _ in 0..<12 {
159 guard let raw = attribute(ancestor, kAXParentAttribute), CFGetTypeID(raw) == AXUIElementGetTypeID() else { return false }
160 ancestor = raw as! AXUIElement
161 AXUIElementSetMessagingTimeout(ancestor, 0.25)
162 if ownsTarget(ancestor) { return true }
163 }
164 return false
165 }
166
167 static func probe() throws -> [String: Any] {
168 try requireGuest()
169 let session = try consoleSession()
170 guard let front = NSWorkspace.shared.frontmostApplication, let bundle = front.bundleIdentifier,
171 ["com.apple.systempreferences", "com.apple.authorizationhost"].contains(bundle), signed(front, bundle: bundle) else {
172 throw Failure(7, "setup_password_foreground_changed")
173 }
174 guard let raw = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else {
175 throw Failure(7, "setup_password_window_unavailable")
176 }
177 let display = CGDisplayBounds(CGMainDisplayID())
178 var trustedSurfaces: [pid_t: Bool] = [:]
179 let windows = raw.compactMap { item -> Window? in
180 guard let id = item[kCGWindowNumber as String] as? UInt32, let pid = item[kCGWindowOwnerPID as String] as? Int32,
181 let rectangle = item[kCGWindowBounds as String] as? [String: Any], let bounds = CGRect(dictionaryRepresentation: rectangle as CFDictionary),
182 bounds.width > 0, bounds.height > 0, (item[kCGWindowAlpha as String] as? Double ?? 1) > 0,
183 let layer = item[kCGWindowLayer as String] as? Int else { return nil }
184 var surface = false
185 if layer > 0, abs(bounds.minX - display.minX) < 1, abs(bounds.minY - display.minY) < 1,
186 abs(bounds.width - display.width) < 1, abs(bounds.height - display.height) < 1 {
187 if let cached = trustedSurfaces[pid] { surface = cached }
188 else {
189 if let app = NSRunningApplication(processIdentifier: pid), let owner = app.bundleIdentifier,
190 ["com.apple.dock", "com.apple.notificationcenterui"].contains(owner) { surface = signed(app, bundle: owner) }
191 trustedSurfaces[pid] = surface
192 }
193 }
194 return Window(id: id, pid: pid, bounds: bounds, layer: layer, systemSurface: surface)
195 }
196 let accessibility = AXIsProcessTrusted()
197 let target = try select(windows: windows, pid: front.processIdentifier, bundle: bundle, display: display, accessibility: accessibility)
198 let focused = accessibility && passwordFocused(front, window: target.bounds)
199 guard NSWorkspace.shared.frontmostApplication?.processIdentifier == front.processIdentifier,
200 try consoleSession() == session else { throw Failure(7, "setup_password_foreground_changed") }
201 return ["version": 1, "session": session, "user": NSUserName(), "pid": front.processIdentifier,
202 "window": target.id, "bundle": bundle, "rect": [target.bounds.minX, target.bounds.minY, target.bounds.width, target.bounds.height],
203 "display": [display.minX, display.minY, display.width, display.height], "accessibility": accessibility,
204 "password_focused": focused, "selection_required": !accessibility]
205 }
206
207 static func selfTest() throws {
208 try validateRequest(Data("{}".utf8))
209 try validateRequest(Data("{\"action\":\"probe\"}".utf8))
210 for request in ["", "[]", "{\"action\":\"other\"}", "{\"action\":\"probe\",\"text\":\"test-secret\"}"] {
211 do { try validateRequest(Data(request.utf8)); throw Failure(1, "setup_password_test_request") }
212 catch let error as Failure where error.message == "setup_password_probe_request_invalid" { }
213 }
214 // System Settings may host a secure field in its signed Apple extension.
215 for extensionBundle in ["com.apple.settings.PrivacySecurity.extension", "com.apple.extensionkit.AppExtensionManagement"] {
216 guard allowsPasswordProcess(hostBundle: "com.apple.systempreferences", hostPID: 613, fieldPID: 731,
217 fieldBundle: extensionBundle, appleSigned: true),
218 !allowsPasswordProcess(hostBundle: "com.apple.systempreferences", hostPID: 613, fieldPID: 731,
219 fieldBundle: extensionBundle, appleSigned: false) else { throw Failure(1, "setup_password_test_extension_signature") }
220 }
221 guard allowsPasswordProcess(hostBundle: "com.apple.authorizationhost", hostPID: 613, fieldPID: 613,
222 fieldBundle: "com.apple.authorizationhost", appleSigned: true),
223 !allowsPasswordProcess(hostBundle: "com.apple.systempreferences", hostPID: 613, fieldPID: 731,
224 fieldBundle: "com.apple.finder", appleSigned: true),
225 !allowsPasswordProcess(hostBundle: "com.apple.authorizationhost", hostPID: 613, fieldPID: 731,
226 fieldBundle: "com.apple.settings.PrivacySecurity.extension", appleSigned: true) else { throw Failure(1, "setup_password_test_process_binding") }
227 let display = CGRect(x: 0, y: 0, width: 1920, height: 1200)
228 let parent = Window(id: 38, pid: 2338, bounds: CGRect(x: 598, y: 258, width: 723, height: 625), layer: 0)
229 let panel = Window(id: 49, pid: 2338, bounds: CGRect(x: 830, y: 376, width: 260, height: 389), layer: 0)
230 let overlay = Window(id: 8, pid: 613, bounds: display, layer: 20, systemSurface: true)
231 guard try select(windows: [overlay, panel, parent], pid: panel.pid, bundle: "com.apple.systempreferences", display: display, accessibility: false).id == panel.id else { throw Failure(1, "setup_password_test_selection") }
232 let ordinary = Window(id: 9, pid: 999, bounds: panel.bounds, layer: 0)
233 for windows in [[parent], [ordinary, panel, parent], [Window(id: 9, pid: 999, bounds: display, layer: 20), panel, parent], [panel]] {
234 do { _ = try select(windows: windows, pid: panel.pid, bundle: "com.apple.systempreferences", display: display, accessibility: false); throw Failure(1, "setup_password_test_accepted_invalid") }
235 catch let error as Failure where error.code == 7 { }
236 }
237 guard try select(windows: [panel], pid: panel.pid, bundle: "com.apple.authorizationhost", display: display, accessibility: false).id == panel.id,
238 try select(windows: [parent], pid: panel.pid, bundle: "com.apple.systempreferences", display: display, accessibility: true).id == parent.id else { throw Failure(1, "setup_password_test_accessibility") }
239 print("macOS setup password window selection, system surfaces, obscuration and first-permission cases passed")
240 }
241}