跳到主要内容

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

浏览文件

claude-window-macos.swift

140 行 · 6.6 KB历史下载
1// Capture one visible Claude Desktop window to stdout inside a Cage macOS VM.
2// Build with swiftc -parse-as-library -target arm64-apple-macos14.0.
3import AppKit
4import ImageIO
5import ScreenCaptureKit
6import Security
7import UniformTypeIdentifiers
8
9private let bundleID = "com.anthropic.claudefordesktop"
10
11struct Failure: Error {
12 let code: Int32
13 let message: String
14 init(_ code: Int32, _ message: String) {
15 self.code = code
16 self.message = message
17 }
18}
19
20func requireGuest() throws {
21 var model = [CChar](repeating: 0, count: 256)
22 var count = model.count
23 guard sysctlbyname("hw.model", &model, &count, nil, 0) == 0,
24 String(cString: model).range(of: #"^VirtualMac[0-9]+,[0-9]+$"#, options: .regularExpression) != nil else {
25 throw Failure(2, "not_cage_guest: Run inside a Cage virtual Mac.")
26 }
27 let fd = open("/var/db/cage-guest-os", O_RDONLY | O_NOFOLLOW | O_NONBLOCK)
28 guard fd >= 0 else { throw Failure(2, "not_cage_guest: Missing guest marker.") }
29 let marker = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
30 var metadata = stat()
31 guard fstat(fd, &metadata) == 0, metadata.st_mode & S_IFMT == S_IFREG,
32 metadata.st_uid == 0, metadata.st_mode & 0o022 == 0,
33 (5...6).contains(metadata.st_size),
34 let bytes = try marker.read(upToCount: 6), [Data("macos".utf8), Data("macos\n".utf8)].contains(bytes) else {
35 throw Failure(2, "not_cage_guest: Invalid guest marker.")
36 }
37}
38
39func claudeSigningRequirement() throws -> SecRequirement {
40 let expression = #"anchor apple generic and identifier "com.anthropic.claudefordesktop" and certificate leaf[subject.OU] = "Q6L2SF6YDW" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists"#
41 var requirement: SecRequirement?
42 guard SecRequirementCreateWithString(expression as CFString, [], &requirement) == errSecSuccess, let requirement else {
43 throw Failure(5, "identity_error: Could not construct the Claude signing requirement.")
44 }
45 return requirement
46}
47
48func claudePIDs() throws -> Set<pid_t> {
49 var console = stat()
50 var attributes: SessionAttributeBits = []
51 guard lstat("/dev/console", &console) == 0, console.st_uid >= 500, console.st_uid == geteuid(),
52 SessionGetInfo(callerSecuritySession, nil, &attributes) == errSecSuccess,
53 attributes.contains(.sessionHasGraphicAccess) else {
54 throw Failure(4, "requires_gui_login: Run as the logged-in guest desktop user in their GUI session.")
55 }
56 let path = URL(fileURLWithPath: "/Applications/Claude.app").resolvingSymlinksInPath()
57 let apps = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID).filter {
58 $0.bundleURL?.resolvingSymlinksInPath() == path && !$0.isTerminated
59 }
60 guard !apps.isEmpty else { throw Failure(3, "not_running: Launch /Applications/Claude.app in the guest.") }
61 let requirement = try claudeSigningRequirement()
62 let validPIDs = apps.compactMap { app -> pid_t? in
63 let attributes = [kSecGuestAttributePid: app.processIdentifier] as CFDictionary
64 var code: SecCode?
65 guard SecCodeCopyGuestWithAttributes(nil, attributes, [], &code) == errSecSuccess, let code,
66 SecCodeCheckValidity(code, [], requirement) == errSecSuccess else { return nil }
67 return app.processIdentifier
68 }
69 guard !validPIDs.isEmpty else { throw Failure(5, "identity_error: The running app failed Anthropic signature verification.") }
70 return Set(validPIDs)
71}
72
73func claudeWindow() async throws -> SCWindow {
74 try requireGuest()
75 let pids = try claudePIDs()
76 guard CGPreflightScreenCaptureAccess() else {
77 throw Failure(6, "screen_recording_permission: Authorize this capture tool in the guest's Privacy & Security settings.")
78 }
79 let content = try await SCShareableContent.excludingDesktopWindows(true, onScreenWindowsOnly: true)
80 let windows = content.windows.filter { window in
81 guard window.isOnScreen, window.windowLayer == 0, !window.frame.isEmpty,
82 let owner = window.owningApplication else { return false }
83 return owner.bundleIdentifier == bundleID && pids.contains(owner.processID)
84 }
85 guard let window = windows.max(by: { $0.frame.width * $0.frame.height < $1.frame.width * $1.frame.height }) else {
86 throw Failure(7, "no_visible_window: Open a Claude window on the guest desktop.")
87 }
88 return window
89}
90
91func screenshot(_ window: SCWindow, filter selected: SCContentFilter? = nil) async throws -> Data {
92 let filter = selected ?? SCContentFilter(desktopIndependentWindow: window)
93 let config = SCStreamConfiguration()
94 config.width = max(1, Int((filter.contentRect.width * CGFloat(filter.pointPixelScale)).rounded()))
95 config.height = max(1, Int((filter.contentRect.height * CGFloat(filter.pointPixelScale)).rounded()))
96 config.ignoreShadowsSingleWindow = true
97 config.showsCursor = false
98 if #available(macOS 14.2, *) { config.includeChildWindows = false }
99 let image = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: config)
100 return try pngData(image)
101}
102
103func pngData(_ image: CGImage) throws -> Data {
104 try encodedImage(image, type: .png)
105}
106
107func encodedImage(_ image: CGImage, type: UTType, properties: CFDictionary? = nil) throws -> Data {
108 let data = NSMutableData()
109 guard let encoder = CGImageDestinationCreateWithData(data, type.identifier as CFString, 1, nil) else {
110 throw Failure(8, "capture_failed: Could not create an image encoder.")
111 }
112 CGImageDestinationAddImage(encoder, image, properties)
113 guard CGImageDestinationFinalize(encoder) else { throw Failure(8, "capture_failed: Could not encode the window.") }
114 return data as Data
115}
116
117#if !GUEST_WINDOW_APP
118@main
119struct ClaudeWindow {
120 static func main() async {
121 do {
122 let png = try await screenshot(claudeWindow())
123 try FileHandle.standardOutput.write(contentsOf: png)
124 } catch {
125 let failure: Failure
126 if let known = error as? Failure {
127 failure = known
128 } else if (error as NSError).domain == SCStreamErrorDomain &&
129 (error as NSError).code == SCStreamError.userDeclined.rawValue {
130 failure = Failure(6, "screen_recording_permission: The guest user declined screen capture.")
131 } else {
132 failure = Failure(8, "capture_failed: \(error.localizedDescription)")
133 }
134 FileHandle.standardError.write(Data("\(failure.message)\n".utf8))
135 exit(failure.code)
136 }
137 }
138}
139
140#endif