import AppKit import Darwin import Foundation @MainActor final class RealityApplicationChild { private struct RegistrationObservation: Codable, Sendable { let observedAt: Date let pid: Int32 let found: Bool let bundleID: String? let bundleURL: URL? let launchDate: Date? let activationPolicy: Int? let isTerminated: Bool? let isFinishedLaunching: Bool? @MainActor init(pid: Int32, application: NSRunningApplication?) { observedAt = Date() self.pid = pid found = application != nil bundleID = application?.bundleIdentifier bundleURL = application?.bundleURL launchDate = application?.launchDate activationPolicy = application?.activationPolicy.rawValue isTerminated = application?.isTerminated isFinishedLaunching = application?.isFinishedLaunching } } private struct RegistrationReceipt: Codable, Sendable { let pid: Int32 let parentPID: Int32 let expectedBundleID: String let expectedBundleURL: URL let executable: URL? let observations: [RegistrationObservation] } let process = Process() private let applicationURL: URL private let bundleID: String private let output: FileHandle private let errors: FileHandle private let receiptURL: URL init(applicationURL: URL, bundleID: String, arguments: [String], directory: URL) throws { let applicationURL = applicationURL.resolvingSymlinksInPath().standardizedFileURL guard let bundle = Bundle(url: applicationURL), bundle.bundleIdentifier == bundleID, let executable = bundle.executableURL?.resolvingSymlinksInPath(), executable.deletingLastPathComponent().path == applicationURL.appendingPathComponent("Contents/MacOS", isDirectory: true).path else { throw RealityError("Direct app launch requires its matching bundle executable") } self.applicationURL = applicationURL self.bundleID = bundleID let stem = directory.appendingPathComponent("application-child-\(UUID())") receiptURL = stem.appendingPathExtension("json") let outputURL = stem.appendingPathExtension("stdout") let errorsURL = stem.appendingPathExtension("stderr") guard FileManager.default.createFile(atPath: outputURL.path, contents: nil), FileManager.default.createFile(atPath: errorsURL.path, contents: nil) else { throw RealityError("Cannot create owned application launch logs") } output = try FileHandle(forWritingTo: outputURL) errors = try FileHandle(forWritingTo: errorsURL) process.executableURL = executable process.arguments = arguments process.currentDirectoryURL = directory process.environment = Self.guiEnvironment(ProcessInfo.processInfo.environment) process.standardOutput = output process.standardError = errors } static func guiEnvironment(_ inherited: [String: String]) -> [String: String] { var environment = inherited environment.removeValue(forKey: "ELECTRON_RUN_AS_NODE") environment.removeValue(forKey: "__CFBundleIdentifier") return environment } func launch() async throws -> NSRunningApplication { try process.run() try requireKernelIdentity() var observations: [RegistrationObservation] = [] @MainActor func recordRegistration() throws { try encodeJSON( RegistrationReceipt( pid: process.processIdentifier, parentPID: getpid(), expectedBundleID: bundleID, expectedBundleURL: applicationURL, executable: process.executableURL, observations: observations), to: receiptURL) } try recordRegistration() let deadline = ContinuousClock.now.advanced(by: .seconds(10)) do { repeat { try Task.checkCancellation() let application = NSRunningApplication(processIdentifier: process.processIdentifier) observations.append(RegistrationObservation(pid: process.processIdentifier, application: application)) guard process.isRunning else { throw RealityError("Owned application exited before GUI registration; see \(receiptURL.path)") } if let application, !application.isTerminated, application.bundleIdentifier == bundleID, application.bundleURL?.resolvingSymlinksInPath().standardizedFileURL.path == applicationURL.path, application.launchDate != nil { try requireKernelIdentity() try recordRegistration() return application } try await Task.sleep(for: .milliseconds(25)) } while ContinuousClock.now < deadline throw RealityError( "Owned application did not provide complete exact-child launch identity; see \(receiptURL.path)") } catch { do { try recordRegistration() } catch let recording { throw RealityError("\(error); registration evidence could not be saved: \(recording)") } throw error } } func discardOwnedChild() async throws { if process.isRunning { try requireKernelIdentity() guard kill(process.processIdentifier, SIGKILL) == 0 else { throw RealityError("Cannot discard owned application child: errno \(errno)") } let deadline = ContinuousClock.now.advanced(by: .seconds(5)) while process.isRunning, ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) } } guard !process.isRunning else { throw RealityError("Owned application child survived discard") } try output.close() try errors.close() } private func requireKernelIdentity() throws { guard process.isRunning, let executable = process.executableURL else { throw RealityError("Safety stop: owned application child is no longer live") } let pid = process.processIdentifier var info = proc_bsdinfo() let size = Int32(MemoryLayout.size) var path = [UInt8](repeating: 0, count: 4 * Int(MAXPATHLEN)) guard proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, size) == size, proc_pidpath(pid, &path, UInt32(path.count)) > 0, info.pbi_pid == UInt32(pid), info.pbi_ppid == UInt32(getpid()) else { throw RealityError("Safety stop: application kernel child identity could not be verified") } let actual = String(decoding: path.prefix(while: { $0 != 0 }), as: UTF8.self) guard actual == executable.path else { throw RealityError("Safety stop: application kernel executable differs from its retained launch") } } }