| 1 | import Cocoa |
| 2 | import Darwin |
| 3 | |
| 4 | @main |
| 5 | final class CageUpdateInstaller: NSObject, NSApplicationDelegate { |
| 6 | private var plan: CageUpdatePlan! |
| 7 | private var parent: NSRunningApplication! |
| 8 | private var manager = FileManager.default |
| 9 | private var didReplace = false |
| 10 | private var originalVersion = "" |
| 11 | |
| 12 | static func main() { |
| 13 | CageProfile.pinEnvironment() |
| 14 | let app = NSApplication.shared |
| 15 | let delegate = CageUpdateInstaller(); app.delegate = delegate |
| 16 | app.setActivationPolicy(.accessory) |
| 17 | withExtendedLifetime(delegate) { app.run() } |
| 18 | } |
| 19 | func applicationDidFinishLaunching(_ notification: Notification) { |
| 20 | DispatchQueue.global(qos: .userInitiated).async { |
| 21 | do { |
| 22 | try self.readPlan() |
| 23 | let directory = URL(fileURLWithPath: self.plan.target).deletingLastPathComponent() |
| 24 | DispatchQueue.main.async { |
| 25 | if FileManager.default.isWritableFile(atPath: directory.path) { self.prepare() } |
| 26 | else { |
| 27 | NSWorkspace.shared.requestAuthorization(to: .replaceFile) { authorization, _ in |
| 28 | DispatchQueue.main.async { |
| 29 | guard let authorization else { self.finishBeforeCommit("未获得安装权限,原应用已保留"); return } |
| 30 | self.manager = FileManager(authorization: authorization) |
| 31 | self.prepare() |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | } catch { self.finishBeforeCommit(error.localizedDescription) } |
| 37 | } |
| 38 | } |
| 39 | private func readPlan() throws { |
| 40 | guard CommandLine.arguments.count == 2 else { throw CageUpdateError("安装任务无效") } |
| 41 | let location = URL(fileURLWithPath: CommandLine.arguments[1]).resolvingSymlinksInPath() |
| 42 | let directory = location.deletingLastPathComponent() |
| 43 | let attributes = try FileManager.default.attributesOfItem(atPath: directory.path) |
| 44 | guard (attributes[.ownerAccountID] as? NSNumber)?.uint32Value == getuid(), |
| 45 | ((attributes[.posixPermissions] as? NSNumber)?.intValue ?? 0) & 0o077 == 0 else { throw CageUpdateError("安装任务目录权限无效") } |
| 46 | let data = try Data(contentsOf: location) |
| 47 | guard data.count <= 16384 else { throw CageUpdateError("安装任务过大") } |
| 48 | plan = try JSONDecoder().decode(CageUpdatePlan.self, from: data) |
| 49 | guard plan.parentPID == getppid(), let running = NSRunningApplication(processIdentifier: plan.parentPID), |
| 50 | running.bundleURL?.resolvingSymlinksInPath().path == plan.target else { throw CageUpdateError("安装任务不属于当前 Cage 应用") } |
| 51 | parent = running |
| 52 | let selfURL = URL(fileURLWithPath: CommandLine.arguments[0]).resolvingSymlinksInPath() |
| 53 | let ownTeam = try CageUpdateFiles.signingInfo(selfURL, bundle: false) |
| 54 | guard ownTeam == plan.team, |
| 55 | URL(fileURLWithPath: plan.candidate).resolvingSymlinksInPath().path == directory.appendingPathComponent("Cage.app").path, |
| 56 | plan.backup == directory.appendingPathComponent("previous.app").path, |
| 57 | plan.resultPath == directory.deletingLastPathComponent().appendingPathComponent("last-result.json").path, |
| 58 | selfURL.deletingLastPathComponent() == directory else { throw CageUpdateError("安装任务路径或签名不匹配") } |
| 59 | let target = URL(fileURLWithPath: plan.target) |
| 60 | guard target == target.resolvingSymlinksInPath(), target.pathExtension == "app", !target.path.hasPrefix("/Volumes/") else { throw CageUpdateError("安装位置不支持自动更新") } |
| 61 | _ = try CageUpdateFiles.signingInfo(target, bundle: true, expectedTeam: ownTeam) |
| 62 | try CageUpdateFiles.verifyApp(URL(fileURLWithPath: plan.candidate), version: plan.version, team: ownTeam) |
| 63 | let info = try PropertyListSerialization.propertyList(from: Data(contentsOf: target.appendingPathComponent("Contents/Info.plist")), format: nil) as? [String: Any] |
| 64 | guard let current = info?["CageVersion"] as? String, CageUpdateVersion.isNewer(plan.version, than: current) else { throw CageUpdateError("更新版本必须高于当前安装版本") } |
| 65 | originalVersion = current |
| 66 | } |
| 67 | private func prepare() { |
| 68 | DispatchQueue.global(qos: .userInitiated).async { |
| 69 | do { |
| 70 | let backup = URL(fileURLWithPath: self.plan.backup) |
| 71 | if FileManager.default.fileExists(atPath: backup.path) { try FileManager.default.removeItem(at: backup) } |
| 72 | try FileManager.default.copyItem(at: URL(fileURLWithPath: self.plan.target), to: backup) |
| 73 | _ = try CageUpdateFiles.signingInfo(backup, bundle: true, expectedTeam: self.plan.team) |
| 74 | self.send(["status": "ready"]) |
| 75 | let command = FileHandle.standardInput.readDataToEndOfFile() |
| 76 | guard command == Data("COMMIT\n".utf8) else { self.exitHelper(); return } |
| 77 | let deadline = Date().addingTimeInterval(90) |
| 78 | while !self.parent.isTerminated && Date() < deadline { Thread.sleep(forTimeInterval: 0.1) } |
| 79 | guard self.parent.isTerminated else { throw CageUpdateError("Cage 尚未退出,更新未安装") } |
| 80 | try self.replace() |
| 81 | DispatchQueue.main.async { self.openInstalled() } |
| 82 | } catch { |
| 83 | if self.parent?.isTerminated == true { self.recover(error.localizedDescription) } |
| 84 | else { self.finishBeforeCommit(error.localizedDescription) } |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | private func replace() throws { |
| 89 | let target = URL(fileURLWithPath: plan.target) |
| 90 | let candidate = URL(fileURLWithPath: plan.candidate) |
| 91 | _ = try CageUpdateFiles.signingInfo(target, bundle: true, expectedTeam: plan.team) |
| 92 | try CageUpdateFiles.verifyApp(candidate, version: plan.version, team: plan.team) |
| 93 | try CageUpdateFiles.replaceAndVerify(target: target, candidate: candidate, backup: URL(fileURLWithPath: plan.backup), manager: manager, onReplace: { self.didReplace = true }) { |
| 94 | try CageUpdateFiles.verifyApp($0, version: plan.version, team: plan.team) |
| 95 | } |
| 96 | } |
| 97 | private func openInstalled() { |
| 98 | let configuration = NSWorkspace.OpenConfiguration() |
| 99 | configuration.activates = true |
| 100 | configuration.createsNewApplicationInstance = true |
| 101 | let token = UUID().uuidString |
| 102 | var environment = inheritedProfile(); environment["CAGE_UPDATE_CONFIRMATION"] = token |
| 103 | configuration.environment = environment |
| 104 | NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: plan.target), configuration: configuration) { app, error in |
| 105 | guard error == nil, let app else { self.recover("新版本未能启动,正在恢复原应用"); return } |
| 106 | let acknowledgement = URL(fileURLWithPath: self.plan.resultPath).deletingLastPathComponent().appendingPathComponent("launch-\(token).json") |
| 107 | DispatchQueue.global(qos: .utility).async { |
| 108 | let deadline = Date().addingTimeInterval(45) |
| 109 | while !app.isTerminated && Date() < deadline { |
| 110 | if let data = try? Data(contentsOf: acknowledgement), data.count < 1024, |
| 111 | let value = try? JSONSerialization.jsonObject(with: data) as? [String: String], value["version"] == self.plan.version { |
| 112 | try? FileManager.default.removeItem(at: acknowledgement) |
| 113 | self.record(success: true, message: "Cage 已更新至 \(self.plan.version)") |
| 114 | self.cleanSuccessfulTask(); self.exitHelper(); return |
| 115 | } |
| 116 | Thread.sleep(forTimeInterval: 0.2) |
| 117 | } |
| 118 | DispatchQueue.main.async { _ = app.terminate() } |
| 119 | let terminationDeadline = Date().addingTimeInterval(10) |
| 120 | while !app.isTerminated && Date() < terminationDeadline { Thread.sleep(forTimeInterval: 0.1) } |
| 121 | if app.isTerminated { self.recover("新版本工作台未能就绪,正在恢复原应用") } |
| 122 | else { |
| 123 | self.record(success: false, message: "新版本未确认就绪,请退出 Cage 后重试;原应用备份已保留") |
| 124 | self.exitHelper() |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | private func inheritedProfile() -> [String: String] { |
| 130 | if let path = ProcessInfo.processInfo.environment["CLAUDE_CAGE_CONFIG"] { return ["CLAUDE_CAGE_CONFIG": path] } |
| 131 | return [:] |
| 132 | } |
| 133 | private func recover(_ reason: String) { |
| 134 | DispatchQueue.global(qos: .userInitiated).async { |
| 135 | var message = reason |
| 136 | var canOpen = false |
| 137 | let target = URL(fileURLWithPath: self.plan.target), backup = URL(fileURLWithPath: self.plan.backup) |
| 138 | do { |
| 139 | let originalIntact = (try? CageUpdateFiles.verifyApp(target, version: self.originalVersion, team: self.plan.team, gatekeeper: false)) != nil |
| 140 | if self.didReplace || !originalIntact { |
| 141 | try CageUpdateFiles.verifyApp(backup, version: self.originalVersion, team: self.plan.team, gatekeeper: false) |
| 142 | |
| 143 | |
| 144 | let control = backup.appendingPathComponent("Contents/Resources/cage") |
| 145 | let handoffData = try CageUpdateFiles.run(control.path, ["prepare-update", "--json"], timeout: 90) |
| 146 | guard let handoff = try JSONSerialization.jsonObject(with: handoffData) as? [String: Any], handoff["status"] as? String == "prepared" else { |
| 147 | throw CageUpdateError("新版本后台尚未安全退出,原应用备份已保留") |
| 148 | } |
| 149 | if !originalIntact { try CageUpdateFiles.restore(backup: backup, target: target, manager: self.manager) } |
| 150 | try CageUpdateFiles.verifyApp(target, version: self.originalVersion, team: self.plan.team, gatekeeper: false) |
| 151 | message += "。已恢复原应用,可稍后重试" |
| 152 | } else { message += "。原应用已保留" } |
| 153 | canOpen = true |
| 154 | } catch { message += "。自动恢复未完成,未启动未经验证的应用。备份位置:\(backup.path)" } |
| 155 | self.record(success: false, message: message) |
| 156 | DispatchQueue.main.async { |
| 157 | guard canOpen else { |
| 158 | let alert = NSAlert(); alert.messageText = "Cage 更新与自动恢复未完成"; alert.informativeText = message; alert.runModal() |
| 159 | self.exitHelper(); return |
| 160 | } |
| 161 | let configuration = NSWorkspace.OpenConfiguration(); configuration.activates = true; configuration.createsNewApplicationInstance = true; configuration.environment = self.inheritedProfile() |
| 162 | NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: self.plan.target), configuration: configuration) { app, _ in |
| 163 | if app == nil { |
| 164 | let alert = NSAlert(); alert.messageText = "Cage 更新未完成"; alert.informativeText = message; alert.runModal() |
| 165 | } |
| 166 | self.exitHelper() |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | private func record(success: Bool, message: String) { |
| 172 | guard let data = try? JSONSerialization.data(withJSONObject: ["success": success, "message": message, "version": plan.version]) else { return } |
| 173 | try? CageUpdateFiles.write(data, to: URL(fileURLWithPath: plan.resultPath)) |
| 174 | } |
| 175 | private func cleanSuccessfulTask() { |
| 176 | let directory = URL(fileURLWithPath: plan.backup).deletingLastPathComponent() |
| 177 | try? FileManager.default.removeItem(at: directory) |
| 178 | } |
| 179 | private func finishBeforeCommit(_ message: String) { send(["status": "error", "message": message]); exitHelper() } |
| 180 | private func send(_ value: [String: Any]) { |
| 181 | if var data = try? JSONSerialization.data(withJSONObject: value) { data.append(10); try? FileHandle.standardOutput.write(contentsOf: data) } |
| 182 | } |
| 183 | private func exitHelper() { DispatchQueue.main.async { NSApp.terminate(nil) } } |
| 184 | } |