跳到主要内容

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

浏览文件

Updates.swift

510 行 · 31.5 KB历史下载
1import Cocoa
2import CryptoKit
3import Security
4import Darwin
5
6let cageUpdateBundleID = "io.github.lee-xeo.claude-cage"
7
8enum CageProfile {
9 static var clientOnly: Bool { Bundle.main.object(forInfoDictionaryKey: "CageClientOnly") as? Bool == true }
10 static var macGuestTrial: Bool { Bundle.main.bundleIdentifier == cageUpdateBundleID + ".macos-trial" }
11 static func configURL() -> URL {
12 if macGuestTrial {
13 return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude-cage/macos-trial/config.json")
14 }
15 if let path = ProcessInfo.processInfo.environment["CLAUDE_CAGE_CONFIG"], !path.isEmpty {
16 return URL(fileURLWithPath: path).standardizedFileURL
17 }
18 return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(clientOnly ? ".claude-cage/client/config.json" : ".claude-cage/config.json")
19 }
20
21 // Every helper and relaunched app inherits the same absolute profile, even
22 // when its working directory differs from the original launch directory.
23 static func pinEnvironment() { setenv("CLAUDE_CAGE_CONFIG", configURL().path, 1) }
24}
25
26final class CageUpdateValidation {
27 private let lock = NSLock()
28 private let completion = DispatchGroup()
29 private var cancelled = false
30 private var process: Process?
31
32 init() { completion.enter() }
33 func checkCancellation() throws {
34 lock.lock(); defer { lock.unlock() }
35 if cancelled { throw CageUpdateError("更新验证已取消") }
36 }
37 func start(_ value: Process) throws {
38 lock.lock(); defer { lock.unlock() }
39 if cancelled { throw CageUpdateError("更新验证已取消") }
40 try value.run()
41 process = value
42 }
43 func released(_ value: Process) {
44 lock.lock(); defer { lock.unlock() }
45 if process === value { process = nil }
46 }
47 func cancel() {
48 lock.lock(); cancelled = true; let active = process; lock.unlock()
49 if let active { CageUpdateFiles.stop(active) }
50 }
51 func finish() { completion.leave() }
52 func wait() { completion.wait() }
53}
54
55struct CageUpdateError: LocalizedError {
56 let message: String
57 var errorDescription: String? { message }
58 init(_ message: String) { self.message = message }
59}
60
61struct CageUpdatePlan: Codable {
62 let version: String
63 let team: String
64 let target: String
65 let candidate: String
66 let backup: String
67 let parentPID: Int32
68 let resultPath: String
69}
70
71enum CageUpdateVersion {
72 static func isNewer(_ candidate: String, than current: String) -> Bool {
73 func parts(_ text: String) -> ([Int], [String])? {
74 guard text.range(of: "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$", options: .regularExpression) != nil else { return nil }
75 let sections = text.split(separator: "-", maxSplits: 1).map(String.init)
76 let numbers = sections[0].split(separator: ".").compactMap { Int($0) }
77 guard numbers.count == 3 else { return nil }
78 let pre = sections.count == 2 ? sections[1].split(separator: ".").map(String.init) : []
79 if pre.contains(where: { $0.count > 1 && $0.first == "0" && $0.allSatisfy(\.isNumber) }) { return nil }
80 return (numbers, pre)
81 }
82 guard let (a, ap) = parts(candidate), let (b, bp) = parts(current) else { return false }
83 for i in 0..<3 where a[i] != b[i] { return a[i] > b[i] }
84 if ap.isEmpty || bp.isEmpty { return ap.isEmpty && !bp.isEmpty }
85 for i in 0..<min(ap.count, bp.count) where ap[i] != bp[i] {
86 let x = ap[i], y = bp[i], xn = x.allSatisfy(\.isNumber), yn = y.allSatisfy(\.isNumber)
87 if xn && yn { return x.count == y.count ? x > y : x.count > y.count }
88 if xn != yn { return !xn }
89 return x > y
90 }
91 return ap.count > bp.count
92 }
93}
94
95enum CageUpdateFiles {
96 static func restore(backup: URL, target: URL, manager: FileManager) throws {
97 let copy = backup.deletingLastPathComponent().appendingPathComponent("restore-" + UUID().uuidString + ".app")
98 try FileManager.default.copyItem(at: backup, to: copy)
99 defer { try? FileManager.default.removeItem(at: copy) }
100 if FileManager.default.fileExists(atPath: target.path) {
101 _ = try manager.replaceItemAt(target, withItemAt: copy, backupItemName: nil, options: [.usingNewMetadataOnly])
102 } else {
103 try manager.moveItem(at: copy, to: target)
104 }
105 }
106 static func replaceAndVerify(target: URL, candidate: URL, backup: URL, manager: FileManager, onReplace: () -> Void = {}, restoreOriginal: (() throws -> Void)? = nil, verify: (URL) throws -> Void) throws {
107 do {
108 _ = try manager.replaceItemAt(target, withItemAt: candidate, backupItemName: nil, options: [.usingNewMetadataOnly])
109 onReplace()
110 try verify(target)
111 } catch {
112 do {
113 if let restoreOriginal { try restoreOriginal() }
114 else { try restore(backup: backup, target: target, manager: manager) }
115 }
116 catch { throw CageUpdateError("安装与自动恢复均未完成,原应用备份已保留") }
117 throw CageUpdateError("安装验证失败,已恢复原应用")
118 }
119 }
120 static func privateDirectory(_ url: URL) throws {
121 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
122 let values = try url.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey])
123 guard values.isDirectory == true, values.isSymbolicLink != true else { throw CageUpdateError("更新目录无效") }
124 try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: url.path)
125 }
126 static func write(_ data: Data, to url: URL) throws {
127 try data.write(to: url, options: .atomic)
128 try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)
129 }
130 static func digest(_ url: URL, validation: CageUpdateValidation? = nil) throws -> String {
131 let file = try FileHandle(forReadingFrom: url)
132 defer { try? file.close() }
133 var hash = SHA256()
134 while let data = try file.read(upToCount: 1024 * 1024), !data.isEmpty { try validation?.checkCancellation(); hash.update(data: data) }
135 return hash.finalize().map { String(format: "%02x", $0) }.joined()
136 }
137 static func stop(_ process: Process) {
138 guard process.isRunning else { return }
139 process.terminate()
140 DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) {
141 if process.isRunning { Darwin.kill(process.processIdentifier, SIGKILL) }
142 }
143 }
144 static func run(_ executable: String, _ arguments: [String], timeout: TimeInterval = 90, validation: CageUpdateValidation? = nil) throws -> Data {
145 let process = Process()
146 process.executableURL = URL(fileURLWithPath: executable)
147 process.arguments = arguments
148 let pipe = Pipe(); process.standardOutput = pipe; process.standardError = pipe
149 let expiration = DispatchWorkItem { stop(process) }
150 if let validation { try validation.start(process) } else { try process.run() }
151 defer { validation?.released(process) }
152 DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + timeout, execute: expiration)
153 let data = pipe.fileHandleForReading.readDataToEndOfFile()
154 process.waitUntilExit(); expiration.cancel()
155 try validation?.checkCancellation()
156 guard process.terminationStatus == 0, data.count <= 1024 * 1024 else { throw CageUpdateError("本机更新验证未完成,请重试") }
157 return data
158 }
159 static func signingInfo(_ url: URL, bundle: Bool, expectedTeam: String? = nil) throws -> String {
160 var code: SecStaticCode?
161 guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess, let code else { throw CageUpdateError("无法读取应用签名") }
162 var requirement: SecRequirement?
163 let identity = bundle ? " and identifier \"\(cageUpdateBundleID)\"" : ""
164 let team = expectedTeam.map { " and certificate leaf[subject.OU] = \"\($0)\"" } ?? ""
165 let expression = "anchor apple generic 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\(identity)\(team)"
166 guard SecRequirementCreateWithString(expression as CFString, [], &requirement) == errSecSuccess else { throw CageUpdateError("无法建立发布者签名要求") }
167 let flags = SecCSFlags(rawValue: kSecCSStrictValidate | kSecCSCheckAllArchitectures | kSecCSCheckNestedCode)
168 guard SecStaticCodeCheckValidity(code, flags, requirement) == errSecSuccess else { throw CageUpdateError("更新应用的 Apple 签名无效或发布者不匹配") }
169 var information: CFDictionary?
170 guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &information) == errSecSuccess,
171 let info = information as? [String: Any], let actual = info[kSecCodeInfoTeamIdentifier as String] as? String,
172 actual.range(of: "^[A-Z0-9]{10}$", options: .regularExpression) != nil else { throw CageUpdateError("当前开发构建没有可验证的发布者,无法自动安装更新") }
173 if let expectedTeam, actual != expectedTeam { throw CageUpdateError("更新应用的发布者不匹配") }
174 return actual
175 }
176 static func verifyArchitecture(_ executable: URL, validation: CageUpdateValidation? = nil) throws {
177 _ = try run("/usr/bin/lipo", [executable.path, "-verify_arch", "arm64"], validation: validation)
178 }
179 static func verifyApp(_ url: URL, version: String, team: String, gatekeeper: Bool = true, validation: CageUpdateValidation? = nil) throws {
180 try validation?.checkCancellation()
181 let values = try url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
182 guard values.isDirectory == true, values.isSymbolicLink != true, url.pathExtension == "app" else { throw CageUpdateError("更新包中缺少有效的 Cage.app") }
183 let plist = url.appendingPathComponent("Contents/Info.plist")
184 guard let info = try PropertyListSerialization.propertyList(from: Data(contentsOf: plist), format: nil) as? [String: Any],
185 info["CFBundleIdentifier"] as? String == cageUpdateBundleID,
186 info["CageVersion"] as? String == version,
187 info["CFBundleExecutable"] as? String == "Cage" else { throw CageUpdateError("更新包的应用身份或版本不匹配") }
188 if let minimum = info["LSMinimumSystemVersion"] as? String {
189 let parts = minimum.split(separator: ".").compactMap { Int($0) }
190 guard minimum.range(of: "^[0-9]+(\\.[0-9]+){0,2}$", options: .regularExpression) != nil,
191 (1...3).contains(parts.count), ProcessInfo.processInfo.isOperatingSystemAtLeast(OperatingSystemVersion(majorVersion: parts[0], minorVersion: parts.count > 1 ? parts[1] : 0, patchVersion: parts.count > 2 ? parts[2] : 0)) else { throw CageUpdateError("此更新需要更高版本的 macOS") }
192 }
193 _ = try signingInfo(url, bundle: true, expectedTeam: team)
194 try verifyArchitecture(url.appendingPathComponent("Contents/MacOS/Cage"), validation: validation)
195 for name in ["cage", "mihomo", "CageUpdateInstaller"] {
196 let nested = url.appendingPathComponent("Contents/Resources/\(name)")
197 guard FileManager.default.fileExists(atPath: nested.path) else { throw CageUpdateError("更新包缺少必要的应用组件") }
198 _ = try signingInfo(nested, bundle: false, expectedTeam: team)
199 }
200 if gatekeeper { _ = try run("/usr/sbin/spctl", ["--assess", "--type", "execute", "--verbose=2", url.path], validation: validation) }
201 try validation?.checkCancellation()
202 }
203 static func validateTree(_ app: URL, validation: CageUpdateValidation? = nil) throws {
204 let base = app.resolvingSymlinksInPath().path + "/"
205 guard let items = FileManager.default.enumerator(at: app, includingPropertiesForKeys: [.isRegularFileKey, .fileSizeKey, .isSymbolicLinkKey], options: []) else { throw CageUpdateError("无法检查更新包内容") }
206 var total: Int64 = 0
207 var count = 0
208 for case let entry as URL in items {
209 try validation?.checkCancellation()
210 count += 1
211 guard count <= 50000, entry.resolvingSymlinksInPath().path.hasPrefix(base) else { throw CageUpdateError("更新包包含越界文件或过多文件") }
212 let values = try entry.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
213 if values.isRegularFile == true { total += Int64(values.fileSize ?? 0) }
214 guard total <= 1024 * 1024 * 1024 else { throw CageUpdateError("解包后的应用超过 1 GiB") }
215 }
216 }
217 static func withMountedImage<T>(archive: URL, directory: URL, validation: CageUpdateValidation? = nil, body: (URL) throws -> T) throws -> T {
218 let mount = directory.appendingPathComponent("mount", isDirectory: true)
219 try privateDirectory(mount)
220 defer {
221 if (try? run("/usr/bin/hdiutil", ["detach", mount.path], timeout: 30)) == nil {
222 _ = try? run("/usr/bin/hdiutil", ["detach", "-force", mount.path], timeout: 30)
223 }
224 }
225 _ = try run("/usr/bin/hdiutil", ["attach", "-readonly", "-nobrowse", "-noautoopen", "-mountpoint", mount.path, archive.path], validation: validation)
226 try validation?.checkCancellation()
227 return try body(mount)
228 }
229 static func extract(archive: URL, hash: String, version: String, team: String, directory: URL, validation: CageUpdateValidation? = nil) throws -> URL {
230 guard try digest(archive, validation: validation) == hash else { throw CageUpdateError("安装包下载后发生变化,请重新下载") }
231 return try withMountedImage(archive: archive, directory: directory, validation: validation) { mount in
232 let source = mount.appendingPathComponent("Cage.app", isDirectory: true)
233 try validateTree(source, validation: validation)
234 try verifyApp(source, version: version, team: team, validation: validation)
235 let target = directory.appendingPathComponent("Cage.app", isDirectory: true)
236 _ = try run("/usr/bin/ditto", [source.path, target.path], validation: validation)
237 try validateTree(target, validation: validation)
238 try verifyApp(target, version: version, team: team, validation: validation)
239 return target
240 }
241 }
242}
243
244/// Owns update state for one native window. All state transitions run on main.
245final class CageAppUpdater {
246 private let bundleURL: URL
247 private let root: URL
248 private let onChange: ([String: Any]) -> Void
249 private let quit: () -> Void
250 private let reconnect: () -> Void
251 private var state: [String: Any]
252 private var worker: Process?
253 private var validationTask: CageUpdateValidation?
254 private var installer: Process?
255 private var installerInput: Pipe?
256 private var prepared: (directory: URL, app: URL, version: String, team: String)?
257 private var generation = 0
258 private var launchAcknowledged = false
259 private var workbenchInitialized = false
260 private var waitingForTermination = false
261 private var installationCommitted = false
262
263 init(bundleURL: URL, onChange: @escaping ([String: Any]) -> Void, quit: @escaping () -> Void, reconnect: @escaping () -> Void) {
264 self.bundleURL = bundleURL.resolvingSymlinksInPath()
265 self.onChange = onChange; self.quit = quit; self.reconnect = reconnect
266 root = CageProfile.configURL().deletingLastPathComponent().appendingPathComponent("updates", isDirectory: true)
267 let version = Bundle(url: bundleURL)?.object(forInfoDictionaryKey: "CageVersion") as? String ?? "开发版本"
268 state = ["phase": "idle", "currentVersion": version, "message": ""]
269 if let data = try? Data(contentsOf: root.appendingPathComponent("last-result.json")), data.count < 16384,
270 let result = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
271 state["message"] = result["message"] as? String ?? ""
272 if result["success"] as? Bool == false { state["phase"] = "failed"; state["retryable"] = true }
273 }
274 }
275 func handle(_ operation: String) -> [String: Any] {
276 if Bundle(url: bundleURL)?.bundleIdentifier == cageUpdateBundleID + ".macos-trial" {
277 if state["phase"] as? String != "manual" {
278 change(["phase": "manual", "message": "macOS 客机试用版通过本机安装更新。"])
279 }
280 return state
281 }
282 if Bundle(url: bundleURL)?.object(forInfoDictionaryKey: "CageClientOnly") as? Bool == true {
283 if state["phase"] as? String != "manual" || operation != "status" {
284 change(["phase": "manual", "message": "轻量客户端使用独立安装包更新;连接配置会保留,云端任务不受影响。"])
285 }
286 return state
287 }
288 let busy = ["checking", "downloading", "downloaded", "verifying", "installing"].contains(state["phase"] as? String ?? "")
289 if ["check", "install"].contains(operation), let value = state["retryAt"] as? String,
290 let date = ISO8601DateFormatter().date(from: value), date > Date() { return state }
291 switch operation {
292 case "status": break
293 case "check": if !busy && worker == nil && validationTask == nil && installer == nil && prepared == nil { startDownload(checkOnly: true) }
294 case "install":
295 if !busy && worker == nil && validationTask == nil && installer == nil { if prepared != nil { beginInstallation() } else { startDownload(checkOnly: false) } }
296 case "cancel":
297 if installer == nil && state["phase"] as? String != "installing" { generation += 1; if let worker { CageUpdateFiles.stop(worker) }; validationTask?.cancel(); change(["phase": prepared == nil ? "available" : "ready", "message": "更新已暂停,可稍后继续", "retryable": true]) }
298 default: break
299 }
300 return state
301 }
302 func cancelForTermination() {
303 generation += 1
304 if let worker { CageUpdateFiles.stop(worker) }
305 validationTask?.cancel()
306 try? installerInput?.fileHandleForWriting.close()
307 if !installationCommitted, let installer { CageUpdateFiles.stop(installer) }
308 }
309 func prepareForTermination(_ completion: @escaping () -> Void) -> Bool {
310 if installationCommitted { return false }
311 if waitingForTermination { return true }
312 let download = worker, validation = validationTask, helper = installer
313 let directory = prepared?.directory
314 cancelForTermination()
315 guard download != nil || validation != nil || helper != nil || directory != nil else { return false }
316 waitingForTermination = true
317 change(["message": "正在取消更新并清理临时文件…"])
318 DispatchQueue.global(qos: .utility).async {
319 download?.waitUntilExit()
320 validation?.wait()
321 helper?.waitUntilExit()
322 if let directory { try? FileManager.default.removeItem(at: directory) }
323 DispatchQueue.main.async { self.waitingForTermination = false; completion() }
324 }
325 return true
326 }
327 var awaitingInitialWorkbench: Bool {
328 guard let token = ProcessInfo.processInfo.environment["CAGE_UPDATE_CONFIRMATION"], UUID(uuidString: token) != nil else { return false }
329 return !workbenchInitialized
330 }
331 func markLaunchReady() {
332 workbenchInitialized = true
333 guard !launchAcknowledged, let token = ProcessInfo.processInfo.environment["CAGE_UPDATE_CONFIRMATION"], UUID(uuidString: token) != nil,
334 let data = try? JSONSerialization.data(withJSONObject: ["version": state["currentVersion"] as? String ?? ""]) else { return }
335 do {
336 try CageUpdateFiles.privateDirectory(root)
337 try CageUpdateFiles.write(data, to: root.appendingPathComponent("launch-\(token).json"))
338 launchAcknowledged = true
339 change(["phase": "current", "message": "Cage 已更新至 \(state["currentVersion"] as? String ?? "")"])
340 } catch { failure("更新已安装,但启动确认未能保存") }
341 }
342 private func change(_ values: [String: Any]) {
343 if values["phase"] as? String == "current" { state.removeValue(forKey: "latestVersion") }
344 for (key, value) in values { state[key] = value }
345 onChange(state)
346 }
347 private func failure(_ message: String, retryAt: String = "") { change(["phase": "failed", "message": message, "retryable": true, "retryAt": retryAt]) }
348 private var cage: URL { bundleURL.appendingPathComponent("Contents/Resources/cage") }
349 private func startDownload(checkOnly: Bool) {
350 generation += 1; let operation = generation
351 change(["phase": "checking", "message": "正在通过所选代理检查更新", "receivedBytes": 0, "totalBytes": 0, "retryable": false, "retryAt": ""])
352 let process = Process(); process.executableURL = cage; process.arguments = ["app-update", checkOnly ? "check" : "download"]
353 let pipe = Pipe(); process.standardOutput = pipe; process.standardError = FileHandle.nullDevice
354 worker = process
355 do { try process.run() } catch { worker = nil; failure("无法启动更新检查,请确认应用组件完整"); return }
356 DispatchQueue.global(qos: .utility).async {
357 var pending = Data(); var last: [String: Any]?
358 while true {
359 let chunk = pipe.fileHandleForReading.availableData
360 if chunk.isEmpty { break }
361 pending.append(chunk)
362 if pending.count > 65536 { process.terminate(); break }
363 while let end = pending.firstIndex(of: 10) {
364 let line = pending.prefix(upTo: end); pending.removeSubrange(...end)
365 guard let value = try? JSONSerialization.jsonObject(with: line) as? [String: Any] else { continue }
366 last = value
367 var visible = value; visible.removeValue(forKey: "archivePath"); visible.removeValue(forKey: "sha256")
368 DispatchQueue.main.async { if self.generation == operation { self.change(visible) } }
369 }
370 }
371 process.waitUntilExit()
372 let result = last
373 DispatchQueue.main.async {
374 if self.worker === process { self.worker = nil }
375 guard self.generation == operation else { return }
376 if process.terminationStatus != 0 {
377 self.failure(result?["message"] as? String ?? "更新请求未完成,请重试", retryAt: result?["retryAt"] as? String ?? "")
378 } else if !checkOnly, let result, result["phase"] as? String == "downloaded" {
379 self.verifyDownload(result, operation: operation)
380 }
381 }
382 }
383 }
384 private func verifyDownload(_ result: [String: Any], operation: Int) {
385 guard let path = result["archivePath"] as? String, let hash = result["sha256"] as? String,
386 let version = result["latestVersion"] as? String, hash.range(of: "^[0-9a-f]{64}$", options: .regularExpression) != nil else { failure("下载进程返回了无效安装包"); return }
387 let archive = URL(fileURLWithPath: path).resolvingSymlinksInPath()
388 guard archive.path.hasPrefix(root.resolvingSymlinksInPath().path + "/download-"), archive.lastPathComponent == "Cage.dmg" else { failure("安装包路径不属于本次私有下载"); return }
389 change(["phase": "verifying", "message": "正在验证 Apple 签名和应用内容", "retryable": false])
390 let task = CageUpdateValidation()
391 validationTask = task
392 DispatchQueue.global(qos: .userInitiated).async {
393 defer {
394 task.finish()
395 DispatchQueue.main.async { if self.validationTask === task { self.validationTask = nil } }
396 }
397 let directory = self.root.appendingPathComponent("verified-" + UUID().uuidString, isDirectory: true)
398 do {
399 try task.checkCancellation()
400 let team = try CageUpdateFiles.signingInfo(self.bundleURL, bundle: true)
401 try CageUpdateFiles.privateDirectory(directory)
402 let app = try CageUpdateFiles.extract(archive: archive, hash: hash, version: version, team: team, directory: directory, validation: task)
403 try task.checkCancellation()
404 try? FileManager.default.removeItem(at: archive.deletingLastPathComponent())
405 DispatchQueue.main.async {
406 if self.generation != operation { try? FileManager.default.removeItem(at: directory); return }
407 self.prepared = (directory, app, version, team)
408 self.change(["phase": "ready", "message": "更新已下载并验证", "retryable": true])
409 self.beginInstallation()
410 }
411 } catch {
412 try? FileManager.default.removeItem(at: directory)
413 try? FileManager.default.removeItem(at: archive.deletingLastPathComponent())
414 DispatchQueue.main.async { if self.generation == operation { self.failure(error.localizedDescription) } }
415 }
416 }
417 }
418 private func beginInstallation() {
419 guard let prepared, installer == nil else { return }
420 change(["phase": "installing", "message": "正在准备安装更新", "retryable": false])
421 let operation = generation
422 let task = CageUpdateValidation()
423 validationTask = task
424 DispatchQueue.global(qos: .userInitiated).async {
425 defer {
426 task.finish()
427 DispatchQueue.main.async { if self.validationTask === task { self.validationTask = nil } }
428 }
429 do {
430 guard !self.bundleURL.path.hasPrefix("/Volumes/"), self.bundleURL.pathExtension == "app" else { throw CageUpdateError("请先将 Cage 安装到应用程序目录,再自动更新") }
431 try CageUpdateFiles.verifyApp(prepared.app, version: prepared.version, team: prepared.team, validation: task)
432 let helper = prepared.directory.appendingPathComponent("CageUpdateInstaller")
433 let originalHelper = self.bundleURL.appendingPathComponent("Contents/Resources/CageUpdateInstaller")
434 try? FileManager.default.removeItem(at: helper)
435 try FileManager.default.copyItem(at: originalHelper, to: helper)
436 _ = try CageUpdateFiles.signingInfo(helper, bundle: false, expectedTeam: prepared.team)
437 let plan = CageUpdatePlan(version: prepared.version, team: prepared.team, target: self.bundleURL.path, candidate: prepared.app.path,
438 backup: prepared.directory.appendingPathComponent("previous.app").path, parentPID: ProcessInfo.processInfo.processIdentifier, resultPath: self.root.appendingPathComponent("last-result.json").path)
439 let planURL = prepared.directory.appendingPathComponent("install.json")
440 try CageUpdateFiles.write(JSONEncoder().encode(plan), to: planURL)
441 try task.checkCancellation()
442 DispatchQueue.main.async { if self.generation == operation { self.launchInstaller(helper: helper, plan: planURL) } }
443 } catch { DispatchQueue.main.async { if self.generation == operation { self.failure(error.localizedDescription) } } }
444 }
445 }
446 private func launchInstaller(helper: URL, plan: URL) {
447 let process = Process(); process.executableURL = helper; process.arguments = [plan.path]
448 let input = Pipe(), output = Pipe(); process.standardInput = input; process.standardOutput = output; process.standardError = FileHandle.nullDevice
449 installer = process; installerInput = input
450 do { try process.run() } catch { installer = nil; installerInput = nil; failure("无法启动安全安装程序"); return }
451 DispatchQueue.global(qos: .userInitiated).async {
452 var data = Data()
453 while data.count < 16384 {
454 let byte = output.fileHandleForReading.readData(ofLength: 1)
455 if byte.isEmpty || byte == Data([10]) { break }
456 data.append(byte)
457 }
458 let response = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
459 DispatchQueue.main.async {
460 guard self.installer === process, !self.waitingForTermination else { return }
461 if response?["status"] as? String == "ready" { self.prepareEnvironment(stop: false) }
462 else { self.abortInstaller(); self.failure(response?["message"] as? String ?? "安全安装准备失败,原应用已保留") }
463 }
464 }
465 }
466 private func abortInstaller() {
467 try? installerInput?.fileHandleForWriting.close()
468 installerInput = nil
469 if let helper = installer {
470 CageUpdateFiles.stop(helper)
471 DispatchQueue.global(qos: .utility).async {
472 helper.waitUntilExit()
473 DispatchQueue.main.async { if self.installer === helper { self.installer = nil } }
474 }
475 }
476 }
477 private func prepareEnvironment(stop: Bool) {
478 change(["phase": "installing", "message": stop ? "正在停止环境,准备安装" : "正在检查环境是否可安全更新"])
479 DispatchQueue.global(qos: .userInitiated).async {
480 do {
481 let arguments = ["prepare-update"] + (stop ? ["--stop"] : []) + ["--json"]
482 let process = Process(); process.executableURL = self.cage; process.arguments = arguments
483 let output = Pipe(); process.standardOutput = output; process.standardError = FileHandle.nullDevice
484 try process.run()
485 let expiration = DispatchWorkItem { if process.isRunning { process.terminate() } }
486 DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 180, execute: expiration)
487 let data = output.fileHandleForReading.readDataToEndOfFile(); process.waitUntilExit(); expiration.cancel()
488 guard data.count <= 16384, let result = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw CageUpdateError("无法确认环境已停止") }
489 DispatchQueue.main.async {
490 guard !self.waitingForTermination else { return }
491 switch result["status"] as? String {
492 case "prepared" where process.terminationStatus == 0:
493 guard self.installer?.isRunning == true else { self.failure("安装程序已退出,原应用已保留"); self.reconnect(); return }
494 do {
495 try self.installerInput?.fileHandleForWriting.write(contentsOf: Data("COMMIT\n".utf8))
496 try self.installerInput?.fileHandleForWriting.close()
497 self.installationCommitted = true
498 self.change(["phase": "installing", "message": "正在安装并重启 Cage"])
499 self.quit()
500 } catch { self.abortInstaller(); self.failure("无法开始安装,原应用已保留"); self.reconnect() }
501 case "stop_required" where !stop:
502 self.prepareEnvironment(stop: true)
503 default:
504 self.abortInstaller(); self.failure(result["message"] as? String ?? "环境未能安全停止,更新未安装")
505 }
506 }
507 } catch { DispatchQueue.main.async { self.abortInstaller(); self.failure(error.localizedDescription) } }
508 }
509 }
510}