| 1 | import AppKit |
| 2 | import ApplicationServices |
| 3 | import Carbon |
| 4 | import Security |
| 5 | import UniformTypeIdentifiers |
| 6 | |
| 7 | |
| 8 | struct MacOpenSender { |
| 9 | let audit: Data |
| 10 | let pid: pid_t |
| 11 | |
| 12 | init?(_ event: NSAppleEventDescriptor) { |
| 13 | guard let data = event.attributeDescriptor(forKeyword: AEKeyword(keySenderAuditTokenAttr))?.data, |
| 14 | data.count == MemoryLayout<audit_token_t>.size else { return nil } |
| 15 | var token = audit_token_t() |
| 16 | _ = withUnsafeMutableBytes(of: &token) { data.copyBytes(to: $0) } |
| 17 | let process = audit_token_to_pid(token) |
| 18 | guard process > 0, audit_token_to_euid(token) == geteuid(), |
| 19 | event.attributeDescriptor(forKeyword: AEKeyword(keySenderPIDAttr))?.int32Value == process else { return nil } |
| 20 | audit = data |
| 21 | pid = process |
| 22 | } |
| 23 | |
| 24 | func isOfficialClaude() -> Bool { |
| 25 | guard let application = NSRunningApplication(processIdentifier: pid), !application.isTerminated, |
| 26 | application.bundleIdentifier == "com.anthropic.claudefordesktop", |
| 27 | application.bundleURL?.resolvingSymlinksInPath() == URL(fileURLWithPath: "/Applications/Claude.app").resolvingSymlinksInPath(), |
| 28 | let requirement = try? claudeSigningRequirement() else { return false } |
| 29 | var code: SecCode? |
| 30 | guard SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributeAudit as String: audit] as CFDictionary, [], &code) == errSecSuccess, |
| 31 | let code else { return false } |
| 32 | return SecCodeCheckValidity(code, [], requirement) == errSecSuccess |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | @MainActor |
| 37 | final class MacNativeOpen: NSObject { |
| 38 | static let shared = MacNativeOpen() |
| 39 | private(set) var openWithMetadata: Data? |
| 40 | |
| 41 | func install() { |
| 42 | NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(openDocuments(_:reply:)), |
| 43 | forEventClass: AEEventClass(kCoreEventClass), andEventID: AEEventID(kAEOpenDocuments)) |
| 44 | } |
| 45 | |
| 46 | static func fileURLs(_ event: NSAppleEventDescriptor) throws -> [URL] { |
| 47 | guard let direct = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)), |
| 48 | (1...32).contains(direct.numberOfItems) else { throw Failure(8, "file_open_request_invalid") } |
| 49 | return try (1...direct.numberOfItems).map { index in |
| 50 | guard let descriptor = direct.atIndex(index)?.coerce(toDescriptorType: DescType(typeFileURL)), |
| 51 | descriptor.data.count <= 98304, |
| 52 | let url = URL(dataRepresentation: descriptor.data, relativeTo: nil), url.isFileURL, |
| 53 | url.host == nil || url.host == "" || url.host == "localhost", |
| 54 | url.user == nil, url.password == nil, url.query == nil, url.fragment == nil, |
| 55 | let encodedPath = URLComponents(url: url, resolvingAgainstBaseURL: false)?.percentEncodedPath, |
| 56 | let decodedPath = encodedPath.removingPercentEncoding, !decodedPath.contains("\0"), |
| 57 | url.path.hasPrefix("/"), url.path.utf8.count <= 32768 else { |
| 58 | throw Failure(8, "file_open_request_invalid") |
| 59 | } |
| 60 | return url.standardizedFileURL |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | static func selfTest() throws { |
| 65 | func event(_ values: [String]) -> NSAppleEventDescriptor { |
| 66 | let request = NSAppleEventDescriptor.appleEvent(withEventClass: AEEventClass(kCoreEventClass), |
| 67 | eventID: AEEventID(kAEOpenDocuments), targetDescriptor: nil, |
| 68 | returnID: AEReturnID(kAutoGenerateReturnID), transactionID: AETransactionID(kAnyTransactionID)) |
| 69 | let list = NSAppleEventDescriptor.list() |
| 70 | for (index, value) in values.enumerated() { |
| 71 | list.insert(NSAppleEventDescriptor(descriptorType: DescType(typeFileURL), data: Data(value.utf8))!, at: index + 1) |
| 72 | } |
| 73 | request.setParam(list, forKeyword: AEKeyword(keyDirectObject)) |
| 74 | return request |
| 75 | } |
| 76 | let valid = event(["file:///tmp/cage-open-self-test/a%20b.txt", "file://localhost/tmp/cage-open-self-test/c.txt"]) |
| 77 | guard try fileURLs(valid).map(\.path) == ["/tmp/cage-open-self-test/a b.txt", "/tmp/cage-open-self-test/c.txt"], |
| 78 | MacOpenSender(valid) == nil else { throw Failure(8, "file_open_self_test_valid_paths") } |
| 79 | let invalid = [[], ["https://example.invalid/file"], ["file://example.invalid/tmp/a"], |
| 80 | ["file:///tmp/a?query=1"], ["file:///tmp/a#fragment"], ["file:///tmp/a%00b"], |
| 81 | Array(repeating: "file:///tmp/cage-open-self-test/a", count: 33)] |
| 82 | for (index, values) in invalid.enumerated() { |
| 83 | if (try? fileURLs(event(values))) != nil { throw Failure(8, "file_open_self_test_invalid_\(index)") } |
| 84 | } |
| 85 | guard try fileURLs(event(Array(repeating: "file:///tmp/cage-open-self-test/a", count: 32))).count == 32 else { |
| 86 | throw Failure(8, "file_open_self_test_failed") |
| 87 | } |
| 88 | valid.setAttribute(NSAppleEventDescriptor(int32: getpid()), forKeyword: AEKeyword(keySenderPIDAttr)) |
| 89 | valid.setAttribute(NSAppleEventDescriptor(descriptorType: DescType(typeAuditToken), data: Data(repeating: 0, count: 32))!, |
| 90 | forKeyword: AEKeyword(keySenderAuditTokenAttr)) |
| 91 | guard MacOpenSender(valid) == nil else { throw Failure(8, "file_open_self_test_failed") } |
| 92 | print("macOS native open parser and untrusted-event checks passed") |
| 93 | } |
| 94 | |
| 95 | private static func focusedWindow(_ pid: pid_t) -> AXUIElement? { |
| 96 | var value: CFTypeRef? |
| 97 | guard AXUIElementCopyAttributeValue(AXUIElementCreateApplication(pid), kAXFocusedWindowAttribute as CFString, &value) == .success, |
| 98 | let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil } |
| 99 | return (value as! AXUIElement) |
| 100 | } |
| 101 | |
| 102 | @objc private func openDocuments(_ event: NSAppleEventDescriptor, reply: NSAppleEventDescriptor) { |
| 103 | do { |
| 104 | let urls = try Self.fileURLs(event) |
| 105 | guard let sender = MacOpenSender(event), sender.isOfficialClaude() else { |
| 106 | for url in urls { try forwardToGuestApplication(url) } |
| 107 | return |
| 108 | } |
| 109 | let epoch = try MacGUISession.shared.validate() |
| 110 | guard AXIsProcessTrusted(), let window = Self.focusedWindow(sender.pid) else { throw Failure(7, "file_open_target_changed") } |
| 111 | let validate = { |
| 112 | try MacGUISession.shared.validate(epoch) |
| 113 | guard sender.isOfficialClaude(), let current = Self.focusedWindow(sender.pid), CFEqual(current, window) else { |
| 114 | throw Failure(7, "file_open_target_changed") |
| 115 | } |
| 116 | } |
| 117 | try MacDesktopFiles.shared.queueOpen(paths: urls.map(\.path), action: "open", validate: validate) |
| 118 | let restoreFocus = { |
| 119 | guard (try? validate()) != nil, |
| 120 | NSWorkspace.shared.frontmostApplication?.processIdentifier == getpid() else { return } |
| 121 | if NSRunningApplication(processIdentifier: sender.pid)?.activate(options: []) != true { |
| 122 | GuestDiagnostic.record("files", "file_open_focus_restore_failed") |
| 123 | } |
| 124 | } |
| 125 | restoreFocus() |
| 126 | DispatchQueue.main.async { restoreFocus() } |
| 127 | } catch { |
| 128 | let reason = (error as? Failure)?.message ?? "file_open_failed" |
| 129 | GuestDiagnostic.record("files", reason) |
| 130 | reply.setParam(NSAppleEventDescriptor(int32: Int32(errAEEventFailed)), forKeyword: AEKeyword(keyErrorNumber)) |
| 131 | reply.setParam(NSAppleEventDescriptor(string: reason), forKeyword: AEKeyword(keyErrorString)) |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | private func forwardToGuestApplication(_ url: URL) throws { |
| 136 | let values = try url.resourceValues(forKeys: [.contentTypeKey, .isDirectoryKey]) |
| 137 | let type = values.isDirectory == true ? UTType.folder : values.contentType ?? UTType.data |
| 138 | let current = Bundle.main.bundleURL.resolvingSymlinksInPath() |
| 139 | let preferred = NSWorkspace.shared.urlForApplication(toOpen: type) |
| 140 | let candidates = [preferred].compactMap { $0 } + NSWorkspace.shared.urlsForApplications(toOpen: type) |
| 141 | guard let target = candidates.first(where: { |
| 142 | $0.resolvingSymlinksInPath() != current && Bundle(url: $0)?.bundleIdentifier != Bundle.main.bundleIdentifier |
| 143 | }) else { throw Failure(8, "file_open_application_unavailable") } |
| 144 | |
| 145 | let configuration = NSWorkspace.OpenConfiguration() |
| 146 | configuration.addsToRecentItems = false |
| 147 | NSWorkspace.shared.open([url], withApplicationAt: target, configuration: configuration) { _, error in |
| 148 | if error != nil { GuestDiagnostic.record("files", "file_open_application_failed") } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | func prepareMetadata() async throws { |
| 153 | let bundle = Bundle.main.bundleURL.resolvingSymlinksInPath() |
| 154 | guard bundle.path == "/Applications/Cage Guest Window.app", Bundle.main.bundleIdentifier == "dev.cage.GuestClaudeWindow", |
| 155 | LSRegisterURL(bundle as CFURL, true) == noErr else { throw Failure(8, "file_open_registration_failed") } |
| 156 | let cache = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library/Caches/dev.cage.GuestClaudeWindow", isDirectory: true) |
| 157 | var attributes = stat() |
| 158 | guard lstat(cache.path, &attributes) == 0, attributes.st_mode & S_IFMT == S_IFDIR, |
| 159 | attributes.st_uid == geteuid(), attributes.st_mode & 0o077 == 0 else { throw Failure(8, "file_open_cache_invalid") } |
| 160 | let fixture = cache.appendingPathComponent("openwith-\(UUID().uuidString.lowercased()).txt") |
| 161 | let fd = open(fixture.path, O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW, 0o600) |
| 162 | guard fd >= 0 else { throw Failure(8, "file_open_metadata_failed") } |
| 163 | close(fd) |
| 164 | defer { try? FileManager.default.removeItem(at: fixture) } |
| 165 | try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in |
| 166 | NSWorkspace.shared.setDefaultApplication(at: bundle, toOpenFileAt: fixture) { error in |
| 167 | if let error { continuation.resume(throwing: error) } |
| 168 | else { continuation.resume() } |
| 169 | } |
| 170 | } |
| 171 | guard NSWorkspace.shared.urlForApplication(toOpen: fixture)?.resolvingSymlinksInPath() == bundle else { |
| 172 | throw Failure(8, "file_open_registration_failed") |
| 173 | } |
| 174 | let name = "com.apple.LaunchServices.OpenWith" |
| 175 | let length = getxattr(fixture.path, name, nil, 0, 0, XATTR_NOFOLLOW) |
| 176 | guard (1...8192).contains(length) else { throw Failure(8, "file_open_metadata_failed") } |
| 177 | var bytes = [UInt8](repeating: 0, count: length) |
| 178 | guard getxattr(fixture.path, name, &bytes, bytes.count, 0, XATTR_NOFOLLOW) == length else { |
| 179 | throw Failure(8, "file_open_metadata_failed") |
| 180 | } |
| 181 | let temporary = cache.appendingPathComponent("openwith-\(UUID().uuidString.lowercased()).data") |
| 182 | let output = open(temporary.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600) |
| 183 | guard output >= 0 else { throw Failure(8, "file_open_metadata_failed") } |
| 184 | let file = FileHandle(fileDescriptor: output, closeOnDealloc: true) |
| 185 | defer { try? FileManager.default.removeItem(at: temporary) } |
| 186 | try file.write(contentsOf: Data(bytes)) |
| 187 | try file.synchronize() |
| 188 | try file.close() |
| 189 | guard rename(temporary.path, cache.appendingPathComponent("openwith.data").path) == 0 else { |
| 190 | throw Failure(8, "file_open_metadata_failed") |
| 191 | } |
| 192 | openWithMetadata = Data(bytes) |
| 193 | } |
| 194 | } |