| 1 | |
| 2 | |
| 3 | import AppKit |
| 4 | import ScreenCaptureKit |
| 5 | import Security |
| 6 | |
| 7 | struct ProjectPanel: Decodable, Equatable { |
| 8 | let path, nonce: String |
| 9 | let pid: pid_t |
| 10 | let windowNumber: CGWindowID |
| 11 | } |
| 12 | |
| 13 | private func matchesInstalledProjectApp(pid: pid_t) -> Bool { |
| 14 | let path = "/Applications/CageProjectAccess.app" |
| 15 | guard NSRunningApplication(processIdentifier: pid)?.bundleURL?.path == path else { return false } |
| 16 | let url = URL(fileURLWithPath: path) |
| 17 | var dynamic: SecCode?, installed: SecStaticCode?, running: SecStaticCode?, requirement: SecRequirement? |
| 18 | let attributes = [kSecGuestAttributePid: pid] as CFDictionary |
| 19 | var st = stat() |
| 20 | guard lstat(path, &st) == 0, st.st_uid == 0, st.st_mode & 0o022 == 0, |
| 21 | SecRequirementCreateWithString(#"identifier "dev.cage.guest.project-access""# as CFString, [], &requirement) == errSecSuccess, |
| 22 | let requirement, |
| 23 | SecCodeCopyGuestWithAttributes(nil, attributes, [], &dynamic) == errSecSuccess, let dynamic, |
| 24 | SecCodeCheckValidity(dynamic, [], requirement) == errSecSuccess, |
| 25 | SecCodeCopyStaticCode(dynamic, [], &running) == errSecSuccess, let running, |
| 26 | SecStaticCodeCreateWithPath(url as CFURL, [], &installed) == errSecSuccess, let installed, |
| 27 | SecStaticCodeCheckValidity(installed, [], requirement) == errSecSuccess else { return false } |
| 28 | func hash(_ code: SecStaticCode) -> Data? { |
| 29 | var info: CFDictionary? |
| 30 | guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess else { return nil } |
| 31 | return (info as? [String: Any])?[kSecCodeInfoUnique as String] as? Data |
| 32 | } |
| 33 | guard let digest = hash(installed) else { return false } |
| 34 | return digest == hash(running) |
| 35 | } |
| 36 | |
| 37 | func pendingProjectPanel(_ path: String) throws -> ProjectPanel { |
| 38 | let missing = Failure(7, "no_project_panel") |
| 39 | let directory = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Cage/Projects", isDirectory: true) |
| 40 | let leaf = (path as NSString).lastPathComponent |
| 41 | guard leaf.range(of: "^[a-f0-9]{24}$", options: .regularExpression) != nil, |
| 42 | path == directory.appendingPathComponent(leaf).path else { throw missing } |
| 43 | var addr = sockaddr_un() |
| 44 | addr.sun_family = sa_family_t(AF_UNIX) |
| 45 | let socketPath = NSHomeDirectory() + "/Library/Application Support/Cage/project-terminal.sock" |
| 46 | let maxPath = MemoryLayout.size(ofValue: addr.sun_path) |
| 47 | guard socketPath.utf8.count < maxPath else { throw missing } |
| 48 | withUnsafeMutableBytes(of: &addr.sun_path) { dst in socketPath.utf8CString.withUnsafeBytes { dst.copyBytes(from: $0) } } |
| 49 | let fd = socket(AF_UNIX, SOCK_STREAM, 0) |
| 50 | guard fd >= 0 else { throw missing } |
| 51 | let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true) |
| 52 | let connected = withUnsafePointer(to: &addr) { ptr in |
| 53 | ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) } |
| 54 | } |
| 55 | var user = uid_t(), group = gid_t(), peer = pid_t(), len = socklen_t(MemoryLayout<pid_t>.size) |
| 56 | guard connected == 0, getpeereid(fd, &user, &group) == 0, user == geteuid(), |
| 57 | getsockopt(fd, SOL_LOCAL, LOCAL_PEERPID, &peer, &len) == 0, matchesInstalledProjectApp(pid: peer) else { throw missing } |
| 58 | var timeout = timeval(tv_sec: 2, tv_usec: 0) |
| 59 | setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) |
| 60 | var request = try JSONSerialization.data(withJSONObject: ["action":"panel", "path":path]) |
| 61 | request.append(10) |
| 62 | try file.write(contentsOf: request) |
| 63 | var body = Data() |
| 64 | while !body.contains(10), body.count < 4096, let chunk = try file.read(upToCount: 4096 - body.count), !chunk.isEmpty { body.append(chunk) } |
| 65 | guard let result = try? JSONDecoder().decode(ProjectPanel.self, from: body), result.path == path, result.pid == peer, |
| 66 | result.windowNumber > 0, UUID(uuidString: result.nonce) != nil else { throw missing } |
| 67 | return result |
| 68 | } |
| 69 | |
| 70 | @MainActor |
| 71 | func visibleProjectPanel(_ panel: ProjectPanel) async throws -> SCWindow { |
| 72 | guard CGPreflightScreenCaptureAccess() else { throw Failure(6, "project_screen_permission") } |
| 73 | let candidates = try await SCShareableContent.excludingDesktopWindows(true, onScreenWindowsOnly: true) |
| 74 | guard let window = candidates.windows.first(where: { $0.windowID == panel.windowNumber && $0.isOnScreen }), |
| 75 | let owner = window.owningApplication, NSWorkspace.shared.frontmostApplication?.processIdentifier == panel.pid, |
| 76 | owner.processID == panel.pid, owner.bundleIdentifier == "dev.cage.guest.project-access" else { |
| 77 | throw Failure(7, "no_project_panel") |
| 78 | } |
| 79 | return window |
| 80 | } |