@capgo/capacitor-updater 9.0.0 → 9.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CapgoCapacitorUpdater.podspec +3 -6
  2. package/Package.swift +30 -0
  3. package/README.md +2382 -292
  4. package/android/build.gradle +37 -15
  5. package/android/consumer-rules.pro +48 -0
  6. package/android/proguard-rules.pro +23 -0
  7. package/android/src/main/AndroidManifest.xml +0 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +92 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +115 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +227 -195
  11. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +24 -23
  12. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +7435 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5144 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +564 -121
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +43 -49
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +4 -4
  19. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
  20. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +230 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +1969 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +278 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +385 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -0
  26. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +79 -0
  27. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +419 -0
  28. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  29. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
  30. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +959 -0
  31. package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
  32. package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +323 -0
  33. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  34. package/dist/docs.json +4431 -840
  35. package/dist/esm/definitions.d.ts +2607 -225
  36. package/dist/esm/definitions.js +103 -1
  37. package/dist/esm/definitions.js.map +1 -1
  38. package/dist/esm/history.d.ts +1 -0
  39. package/dist/esm/history.js +283 -0
  40. package/dist/esm/history.js.map +1 -0
  41. package/dist/esm/index.d.ts +3 -2
  42. package/dist/esm/index.js +5 -4
  43. package/dist/esm/index.js.map +1 -1
  44. package/dist/esm/web.d.ts +53 -42
  45. package/dist/esm/web.js +180 -37
  46. package/dist/esm/web.js.map +1 -1
  47. package/dist/plugin.cjs.js +570 -37
  48. package/dist/plugin.cjs.js.map +1 -1
  49. package/dist/plugin.js +570 -37
  50. package/dist/plugin.js.map +1 -1
  51. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
  52. package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
  53. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
  54. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
  55. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +5642 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +4572 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +380 -0
  60. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
  61. package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
  62. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +452 -0
  63. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +380 -0
  64. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  65. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
  66. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +97 -0
  67. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +871 -0
  68. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
  69. package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
  70. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +304 -0
  71. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  72. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  73. package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
  74. package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
  75. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +3905 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -0
  80. package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
  81. package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
  82. package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
  83. package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
  84. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1095 -0
  85. package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
  86. package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
  87. package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
  88. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +192 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -0
  91. package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
  92. package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
  93. package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
  94. package/package.json +80 -43
  95. package/scripts/builtin-hashes-lib.mjs +148 -0
  96. package/scripts/capacitor-builtin-hashes-hook.mjs +65 -0
  97. package/scripts/resolve-real-path.mjs +25 -0
  98. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +0 -1130
  99. package/ios/Plugin/BundleInfo.swift +0 -113
  100. package/ios/Plugin/BundleStatus.swift +0 -48
  101. package/ios/Plugin/CapacitorUpdater.swift +0 -858
  102. package/ios/Plugin/CapacitorUpdaterPlugin.h +0 -10
  103. package/ios/Plugin/CapacitorUpdaterPlugin.m +0 -27
  104. package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -677
  105. package/ios/Plugin/CryptoCipher.swift +0 -240
  106. /package/{LICENCE → LICENSE} +0 -0
  107. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
  108. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
  109. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
@@ -0,0 +1,4572 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+
7
+ import Foundation
8
+ import Compression
9
+ import UIKit
10
+
11
+ @objc public class CapgoUpdater: NSObject {
12
+ private var logger: Logger!
13
+
14
+ private let versionCode: String = Bundle.main.versionCode ?? ""
15
+ private let versionOs = UIDevice.current.systemVersion
16
+ private let libraryDir: URL = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first!
17
+ private let DEFAULT_FOLDER: String = ""
18
+ private let bundleDirectory: String = "NoCloud/ionic_built_snapshots"
19
+ private let INFO_SUFFIX: String = "_info"
20
+ private let FALLBACK_VERSION: String = "pastVersion"
21
+ private let NEXT_VERSION: String = "nextVersion"
22
+ private let PREVIEW_FALLBACK_VERSION: String = "previewFallbackVersion"
23
+ private let PENDING_DELETE_IDS: String = "pendingDeleteIds"
24
+ private var unzipPercent = 0
25
+ private let TEMP_UNZIP_PREFIX: String = "capgo_unzip_"
26
+ /// 32 files in flight on every device. Fewer leaves 2-core phones waiting on per-request latency;
27
+ /// capping by CPU count (8 on 4 cores) was 2-4x slower on emulators limited to 2, 4 and 8 cores.
28
+ static let manifestMaxConcurrentFiles = 32
29
+ private static let emptySha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
30
+ private let deletePaceSeconds: TimeInterval = 0.075
31
+ private let deleteLock = NSLock()
32
+
33
+ // Add this line to declare cacheFolder
34
+ private let cacheFolder: URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("capgo_downloads")
35
+
36
+ public let CAP_SERVER_PATH: String = "serverBasePath"
37
+ public var versionBuild: String = ""
38
+ public var customId: String = ""
39
+ public var pluginVersion: String = ""
40
+ public var timeout: Double = 20
41
+ public var statsUrl: String = ""
42
+ /// Optional gate run before any download touches disk (e.g. wait for launch cleanup).
43
+ public var beforeDownload: (() throws -> Void)?
44
+ public var channelUrl: String = ""
45
+ public var defaultChannel: String = ""
46
+ public var appId: String = ""
47
+ public var deviceID = ""
48
+ public var previewSession = false
49
+ public var publicKey: String = ""
50
+ /// When true (default) every URL the updater talks to must be https, including redirect hops. Config `httpsOnly`.
51
+ /// Config `http3` (default true): bundle and manifest downloads may use HTTP/3 (see `preferHTTP3`).
52
+ public var http3Enabled: Bool = true
53
+
54
+ public var httpsOnly: Bool = true {
55
+ didSet { redirectPolicy.httpsOnly = httpsOnly }
56
+ }
57
+ /// When true (default) a bundle whose version is lower than the native app version is refused. Config `builtinMinimum`.
58
+ public var builtinMinimum: Bool = true
59
+ private let versionFloorRejectionLock = NSLock()
60
+ private var lastVersionFloorRejection: String?
61
+ /// Error raised when `httpsOnly` is set and a URL is not https.
62
+ public static func httpsOnlyError(_ url: URL) -> NSError {
63
+ return NSError(
64
+ domain: "CapgoUpdater",
65
+ code: 7,
66
+ userInfo: [NSLocalizedDescriptionKey: "httpsOnly is enabled and \(url.absoluteString) is not https"]
67
+ )
68
+ }
69
+
70
+ /// Returns nil when the URL may be requested, or the `httpsOnly` error to fail with.
71
+ func checkAllowedScheme(_ url: URL?) -> Error? {
72
+ guard self.httpsOnly, let url else {
73
+ return nil
74
+ }
75
+ if url.scheme?.lowercased() == "https" {
76
+ return nil
77
+ }
78
+ logger.error("httpsOnly is enabled and \(url.absoluteString) is not https")
79
+ return Self.httpsOnlyError(url)
80
+ }
81
+
82
+ func assertAllowedScheme(_ url: URL) throws {
83
+ if let error = checkAllowedScheme(url) {
84
+ throw error
85
+ }
86
+ }
87
+
88
+ // Cached key ID calculated once from publicKey
89
+ private var cachedKeyId: String?
90
+
91
+ // Temporary 429 block until this epoch ms (Retry-After / rateLimitResetAt). No sticky latch.
92
+ // Guarded by rateLimitStateLock so concurrent 429s cannot shorten the window or mix metadata.
93
+ private static let rateLimitStateLock = NSLock()
94
+ private static var rateLimitBlockedUntilMs: Double = 0
95
+ private static var rateLimitBlockedError: String = "too_many_requests"
96
+ private static var rateLimitBlockedMessage: String = "Too many requests"
97
+
98
+ // Flag to track if we've already sent the rate limit statistic - prevents infinite loop.
99
+ // Released again when the send fails, so a later 429 can retry it.
100
+ private static var rateLimitStatisticSent = false
101
+
102
+ // Upper bound for a client-side 429 block, so a bogus Retry-After cannot block the app for days.
103
+ private static let maxRateLimitWindowMs: Double = 24 * 60 * 60 * 1000
104
+
105
+ // Stats batching - queue events and send max once per second
106
+ private var statsQueue: [QueuedStatsEvent] = []
107
+ private var statsInFlight: [QueuedStatsEvent] = []
108
+ private let statsQueueLock = NSLock()
109
+ private let statsPersistLock = NSLock()
110
+ private var statsFlushTimer: Timer?
111
+ private var statsStopped = false
112
+ private static let statsFlushInterval: TimeInterval = 1.0
113
+ private static let maxPendingStats = 200
114
+ private let pendingStatsFileName = "capgo_pending_stats.json"
115
+ /// When set, pending stats persist under this directory instead of `libraryDir` (unit tests only).
116
+ internal var pendingStatsDirectoryOverride: URL?
117
+
118
+ private struct QueuedStatsEvent {
119
+ let event: StatsEvent
120
+ let onSent: (() -> Void)?
121
+ }
122
+
123
+ private static func sanitizeHeaderValue(_ value: String) -> String {
124
+ if value.isEmpty {
125
+ return "unknown"
126
+ }
127
+
128
+ let filteredScalars = value.unicodeScalars.filter { scalar in
129
+ let cp = scalar.value
130
+ let isVisibleAscii = (0x20...0x7E).contains(cp)
131
+ let isIso88591 = (0xA0...0xFF).contains(cp)
132
+ return isVisibleAscii || isIso88591
133
+ }
134
+
135
+ let sanitized = String(String.UnicodeScalarView(filteredScalars)).trimmingCharacters(in: .whitespacesAndNewlines)
136
+ return sanitized.isEmpty ? "unknown" : sanitized
137
+ }
138
+
139
+ static func buildUserAgent(appId: String, pluginVersion: String, versionOs: String) -> String {
140
+ let safePluginVersion = sanitizeHeaderValue(pluginVersion)
141
+ let safeAppId = sanitizeHeaderValue(appId)
142
+ let safeVersionOs = sanitizeHeaderValue(versionOs)
143
+ return "CapacitorUpdater/\(safePluginVersion) (\(safeAppId)) ios/\(safeVersionOs)"
144
+ }
145
+
146
+ private var userAgent: String {
147
+ CapgoUpdater.buildUserAgent(appId: appId, pluginVersion: pluginVersion, versionOs: versionOs)
148
+ }
149
+
150
+ struct RequestResult {
151
+ let data: Data?
152
+ let response: HTTPURLResponse?
153
+ let error: Error?
154
+ let timedOut: Bool
155
+ }
156
+
157
+ struct DownloadRequestResult {
158
+ let fileURL: URL?
159
+ let response: HTTPURLResponse?
160
+ let error: Error?
161
+ let timedOut: Bool
162
+ /// Bytes URLSession kept from an interrupted transfer, usable with downloadTask(withResumeData:).
163
+ var resumeData: Data?
164
+ }
165
+
166
+ /// Resume data carried between the retry attempts of one manifest file.
167
+ final class ManifestResumeState {
168
+ var data: Data?
169
+ }
170
+
171
+ enum SecurePathError: Error {
172
+ case emptyPath
173
+ case windowsPath
174
+ case absolutePath
175
+ case pathTraversal
176
+ }
177
+
178
+ static func containsPathTraversalSegment(_ relativePath: String) -> Bool {
179
+ return relativePath.split(separator: "/").contains(where: { $0 == ".." })
180
+ }
181
+
182
+ static func resolvePathInsideDirectory(baseDirectory: URL, relativePath: String) throws -> URL {
183
+ if relativePath.isEmpty {
184
+ throw SecurePathError.emptyPath
185
+ }
186
+ if relativePath.contains("\\") || relativePath.contains("\0") {
187
+ throw SecurePathError.windowsPath
188
+ }
189
+ if containsPathTraversalSegment(relativePath) {
190
+ throw SecurePathError.pathTraversal
191
+ }
192
+ if (relativePath as NSString).isAbsolutePath {
193
+ throw SecurePathError.absolutePath
194
+ }
195
+
196
+ let canonicalBase = baseDirectory.standardizedFileURL
197
+ let canonicalBasePath = canonicalBase.path
198
+ let normalizedBasePath = canonicalBasePath.hasSuffix("/") ? canonicalBasePath : "\(canonicalBasePath)/"
199
+ let canonicalTarget = canonicalBase.appendingPathComponent(relativePath).standardizedFileURL
200
+ let canonicalTargetPath = canonicalTarget.path
201
+
202
+ // Require a strict child of the base. Equality would accept "." and wipe/write the root.
203
+ if !canonicalTargetPath.hasPrefix(normalizedBasePath) {
204
+ throw SecurePathError.pathTraversal
205
+ }
206
+
207
+ return canonicalTarget
208
+ }
209
+
210
+ static func resolveBundleDirectory(libraryDir: URL, bundleId: String) throws -> URL {
211
+ let bundleRoot = libraryDir.appendingPathComponent("NoCloud/ionic_built_snapshots")
212
+ return try resolvePathInsideDirectory(baseDirectory: bundleRoot, relativePath: bundleId)
213
+ }
214
+
215
+ static func resolveManifestTargetPath(baseDirectory: URL, fileName: String) throws -> URL {
216
+ let isBrotli = fileName.hasSuffix(".br")
217
+ let targetFileName = isBrotli ? String(fileName.dropLast(3)) : fileName
218
+ return try resolvePathInsideDirectory(baseDirectory: baseDirectory, relativePath: targetFileName)
219
+ }
220
+
221
+ static func rememberManifestTarget(_ seenTargets: inout Set<String>, targetFile: URL) -> Bool {
222
+ return seenTargets.insert(targetFile.standardizedFileURL.path).inserted
223
+ }
224
+
225
+ private struct ManifestDownloadTask {
226
+ let fileName: String
227
+ let downloadUrl: String
228
+ let finalFileHash: String
229
+ /// SHA-256 of the encrypted bytes from the signed file_hash; `nil` for unencrypted manifests.
230
+ let ciphertextHash: String?
231
+ let isBrotli: Bool
232
+ let destFileName: String
233
+ let destFilePath: URL
234
+ let builtinFilePath: URL
235
+ let cacheFilePath: URL?
236
+ let legacyCacheFilePath: URL?
237
+ }
238
+
239
+ private func isTimedOutError(_ error: Error?) -> Bool {
240
+ if case let .sessionTaskFailed(underlying)? = error as? NetworkError {
241
+ return isTimedOutError(underlying)
242
+ }
243
+ guard let nsError = error as NSError? else {
244
+ return false
245
+ }
246
+
247
+ return nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorTimedOut
248
+ }
249
+
250
+ /// Errors produced by the URLSession transport. Descriptions intentionally match the messages the
251
+ /// previous Alamofire transport surfaced so logs and JS-facing error strings stay the same.
252
+ enum NetworkError: LocalizedError {
253
+ case sessionTaskFailed(Error)
254
+ case emptyResponse
255
+ case invalidURL(String)
256
+ case bodyEncodingFailed(Error?)
257
+ case downloadedFileMoveFailed(Error, source: URL, destination: URL)
258
+
259
+ var errorDescription: String? {
260
+ switch self {
261
+ case let .sessionTaskFailed(error):
262
+ return "URLSessionTask failed with error: \(error.localizedDescription)"
263
+ case .emptyResponse:
264
+ return "Response could not be serialized, input data was nil or zero length."
265
+ case let .invalidURL(url):
266
+ return "URL is not valid: \(url)"
267
+ case let .bodyEncodingFailed(error):
268
+ return "JSON could not be encoded because of error:\n\(error?.localizedDescription ?? "Invalid JSON object provided for parameter or object encoding.")"
269
+ case let .downloadedFileMoveFailed(error, source, destination):
270
+ return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)"
271
+ }
272
+ }
273
+ }
274
+
275
+ /// Mirrors Alamofire's `responseData` serializer: an empty body is an error unless the status allows it.
276
+ static func emptyResponseError(data: Data?, response: HTTPURLResponse?, method: String?) -> Error? {
277
+ if let data, !data.isEmpty {
278
+ return nil
279
+ }
280
+ if method?.uppercased() == "HEAD" || [204, 205].contains(response?.statusCode ?? 0) {
281
+ return nil
282
+ }
283
+ return NetworkError.emptyResponse
284
+ }
285
+
286
+ // lazy var is not thread-safe; concurrent manifest downloads can race first access when statsUrl is empty.
287
+ private var cachedUrlSession: URLSession?
288
+ private let urlSessionLock = NSLock()
289
+ private var urlSession: URLSession {
290
+ urlSessionLock.lock()
291
+ defer { urlSessionLock.unlock() }
292
+ if let session = cachedUrlSession {
293
+ return session
294
+ }
295
+ let configuration = URLSessionConfiguration.ephemeral
296
+ configuration.httpAdditionalHeaders = ["User-Agent": self.userAgent]
297
+ configuration.httpCookieStorage = nil
298
+ configuration.httpShouldSetCookies = false
299
+ configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
300
+ configuration.urlCache = nil
301
+ configuration.httpMaximumConnectionsPerHost = Self.manifestMaxConcurrentFiles
302
+ redirectPolicy.onBlockedRedirect = { [weak self] source, target in
303
+ self?.logger?.error("Blocked redirect to a non-https URL (httpsOnly, or allowHttpsToHttpRedirect is false)")
304
+ self?.logger?.debug("Redirect from \(source?.absoluteString ?? "") to \(target?.absoluteString ?? "")")
305
+ }
306
+ downloadMetricsDelegate.onMetrics = { [weak self] task, metrics in
307
+ guard let url = task.originalRequest?.url else {
308
+ return
309
+ }
310
+ let status = (task.response as? HTTPURLResponse)?.statusCode ?? 0
311
+ self?.logger?.debug(
312
+ "Download protocol \(Self.networkProtocol(of: metrics) ?? "unknown") (HTTP \(status)) \(url.host ?? "")\(url.path)"
313
+ )
314
+ }
315
+ let session = URLSession(configuration: configuration, delegate: redirectPolicy, delegateQueue: nil)
316
+ cachedUrlSession = session
317
+ return session
318
+ }
319
+
320
+ /// Owned separately from `CapgoUpdater` because URLSession retains its delegate strongly.
321
+ private let redirectPolicy = RedirectPolicyDelegate()
322
+ /// Task delegate set only on https download tasks, to log the negotiated protocol (see `DownloadMetricsDelegate`).
323
+ private let downloadMetricsDelegate = DownloadMetricsDelegate()
324
+
325
+ /// Follow redirects from HTTPS to plain HTTP. Off by default so a redirect can never downgrade updater traffic.
326
+ public var allowHttpsToHttpRedirect: Bool {
327
+ get { redirectPolicy.allowHttpsToHttpRedirect }
328
+ set { redirectPolicy.allowHttpsToHttpRedirect = newValue }
329
+ }
330
+
331
+ /// Runs a raw data task on the updater session (no cookies, no cache, redirect policy applied).
332
+ @discardableResult
333
+ func startRawDataTask(_ request: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
334
+ if let schemeError = checkAllowedScheme(request.url) {
335
+ // Never resumed: the session will not call back, so the completion runs exactly once.
336
+ let idle = self.urlSession.dataTask(with: request) { _, _, _ in }
337
+ completion(nil, nil, schemeError)
338
+ return idle
339
+ }
340
+ let task = self.urlSession.dataTask(with: request, completionHandler: completion)
341
+ task.resume()
342
+ return task
343
+ }
344
+
345
+ /// Runs a data task and reports `(data, response, error)` like Alamofire's `responseData` did:
346
+ /// `data` is nil when no bytes were received, transport errors are wrapped, and an empty body is an error
347
+ /// unless the status code is 204/205 (or the request is HEAD).
348
+ @discardableResult
349
+ private func startDataTask(
350
+ _ request: URLRequest,
351
+ completionQueue: DispatchQueue,
352
+ completion: @escaping (Data?, HTTPURLResponse?, Error?) -> Void
353
+ ) -> URLSessionDataTask {
354
+ if let schemeError = checkAllowedScheme(request.url) {
355
+ // Never resumed: the session will not call back, so the completion runs exactly once.
356
+ let idle = self.urlSession.dataTask(with: request) { _, _, _ in }
357
+ completionQueue.async {
358
+ completion(nil, nil, schemeError)
359
+ }
360
+ return idle
361
+ }
362
+ let task = self.urlSession.dataTask(with: request) { data, response, error in
363
+ let httpResponse = response as? HTTPURLResponse
364
+ // URLSession may give nil `data` for 204 No Content and still deliver the HTTPURLResponse.
365
+ let body: Data?
366
+ if let data {
367
+ body = data.isEmpty ? nil : data
368
+ } else {
369
+ body = nil
370
+ }
371
+ let resultError: Error?
372
+ if let error {
373
+ resultError = NetworkError.sessionTaskFailed(error)
374
+ } else {
375
+ resultError = Self.emptyResponseError(data: body, response: httpResponse, method: request.httpMethod)
376
+ }
377
+ completionQueue.async {
378
+ completion(body, httpResponse, resultError)
379
+ }
380
+ }
381
+ task.resume()
382
+ return task
383
+ }
384
+
385
+ /// Builds a POST request with a JSON body (same headers as Alamofire's JSON encoders).
386
+ func makeJSONPostRequest(urlString: String, body: () throws -> Data) -> Result<URLRequest, Error> {
387
+ guard let url = URL(string: urlString) else {
388
+ return .failure(NetworkError.invalidURL(urlString))
389
+ }
390
+ var request = URLRequest(url: url)
391
+ request.httpMethod = "POST"
392
+ request.timeoutInterval = self.timeout
393
+ do {
394
+ request.httpBody = try body()
395
+ } catch let error as NetworkError {
396
+ return .failure(error)
397
+ } catch {
398
+ return .failure(NetworkError.bodyEncodingFailed(error))
399
+ }
400
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
401
+ return .success(request)
402
+ }
403
+
404
+ /// Fire-and-forget JSON POST whose completion runs on the main queue, like Alamofire's default `responseData`.
405
+ private func sendJSONPost(
406
+ urlString: String,
407
+ body: () throws -> Data,
408
+ completion: @escaping (Data?, HTTPURLResponse?, Error?) -> Void
409
+ ) {
410
+ switch makeJSONPostRequest(urlString: urlString, body: body) {
411
+ case let .success(request):
412
+ self.startDataTask(request, completionQueue: .main, completion: completion)
413
+ case let .failure(error):
414
+ DispatchQueue.main.async {
415
+ completion(nil, nil, error)
416
+ }
417
+ }
418
+ }
419
+ private let networkResponseQueue = DispatchQueue(label: "ee.forgr.capacitor-updater.network-response", qos: .utility)
420
+
421
+ public var notifyDownloadRaw: (String, Int, Bool, BundleInfo?) -> Void = { _, _, _, _ in }
422
+ public func notifyDownload(id: String, percent: Int, ignoreMultipleOfTen: Bool = false, bundle: BundleInfo? = nil) {
423
+ let emit = {
424
+ self.notifyDownloadRaw(id, percent, ignoreMultipleOfTen, bundle)
425
+ }
426
+ if Thread.isMainThread {
427
+ emit()
428
+ } else {
429
+ DispatchQueue.main.async {
430
+ emit()
431
+ }
432
+ }
433
+ }
434
+ public var notifyDownload: (String, Int) -> Void = { _, _ in }
435
+ public var notifyListeners: (String, [String: Any]) -> Void = { _, _ in }
436
+
437
+ public func setLogger(_ logger: Logger) {
438
+ self.logger = logger
439
+ }
440
+
441
+ private func createRequest(url: URL, method: String, parameters: [String: Any]? = nil, expectsJSONResponse: Bool = false) -> URLRequest? {
442
+ var request = URLRequest(url: url)
443
+ request.httpMethod = method
444
+ request.timeoutInterval = self.timeout
445
+ request.setValue(self.userAgent, forHTTPHeaderField: "User-Agent")
446
+ if expectsJSONResponse || parameters != nil {
447
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
448
+ }
449
+
450
+ guard let parameters else {
451
+ return request
452
+ }
453
+
454
+ guard JSONSerialization.isValidJSONObject(parameters) else {
455
+ logger.error("Invalid JSON body for \(method) \(url.absoluteString)")
456
+ return nil
457
+ }
458
+
459
+ do {
460
+ request.httpBody = try JSONSerialization.data(withJSONObject: parameters)
461
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
462
+ return request
463
+ } catch {
464
+ logger.error("Error encoding request body for \(method) \(url.absoluteString)")
465
+ logger.debug("Error: \(error.localizedDescription)")
466
+ return nil
467
+ }
468
+ }
469
+
470
+ func performRequest(_ request: URLRequest, label: String) -> RequestResult {
471
+ let waitTimeout = max(self.timeout + 5, 10)
472
+ let semaphore = DispatchSemaphore(value: 0)
473
+ var responseData: Data?
474
+ var httpResponse: HTTPURLResponse?
475
+ var requestError: Error?
476
+ let dataTask = self.startDataTask(request, completionQueue: self.networkResponseQueue) { data, response, error in
477
+ responseData = data
478
+ httpResponse = response
479
+ requestError = error
480
+ semaphore.signal()
481
+ }
482
+
483
+ if semaphore.wait(timeout: .now() + waitTimeout) == .timedOut {
484
+ dataTask.cancel()
485
+ logger.error("\(label) timed out after \(Int(waitTimeout))s")
486
+ return RequestResult(data: responseData, response: httpResponse, error: requestError, timedOut: true)
487
+ }
488
+
489
+ // URLSession can report its own timeout (NSURLErrorTimedOut) before the semaphore deadline.
490
+ let timedOut = isTimedOutError(requestError)
491
+ if timedOut {
492
+ logger.error("\(label) timed out after \(Int(request.timeoutInterval))s")
493
+ }
494
+ return RequestResult(data: responseData, response: httpResponse, error: requestError, timedOut: timedOut)
495
+ }
496
+
497
+ static func isHTTPS(_ url: URL?) -> Bool {
498
+ return url?.scheme?.lowercased() == "https"
499
+ }
500
+
501
+ /// Bundle and manifest downloads only: try HTTP/3 on the first request instead of waiting for Alt-Svc.
502
+ /// The updater session is ephemeral, so it forgets Alt-Svc every launch, and the bundle zip is usually the
503
+ /// first request to the CDN host in a process: without this flag it would always go over HTTP/2.
504
+ /// URLSession races QUIC and falls back to HTTP/2 or HTTP/1.1 on its own when the server or network
505
+ /// does not do HTTP/3 (finding from https://github.com/Cap-go/capacitor-updater/issues/1027, credit autopylotben).
506
+ /// API calls keep the default negotiation. Plain http is left alone: HTTP/3 needs TLS.
507
+ static func preferHTTP3(_ request: URLRequest, enabled: Bool) -> URLRequest {
508
+ guard enabled, isHTTPS(request.url) else {
509
+ return request
510
+ }
511
+ var request = request
512
+ request.assumesHTTP3Capable = true
513
+ return request
514
+ }
515
+
516
+ /// Downloads a URL to a temporary file, reporting cumulative `(received, expected)` bytes for `2xx` responses.
517
+ func performDownloadRequest(
518
+ _ request: URLRequest,
519
+ label: String,
520
+ resumeData: Data? = nil,
521
+ onProgress: ((Int64, Int64) -> Void)? = nil
522
+ ) -> DownloadRequestResult {
523
+ if let schemeError = checkAllowedScheme(request.url) {
524
+ return DownloadRequestResult(fileURL: nil, response: nil, error: schemeError, timedOut: false)
525
+ }
526
+ let waitTimeout = max(self.timeout + 5, 10)
527
+ let semaphore = DispatchSemaphore(value: 0)
528
+ var tempFileURL: URL?
529
+ var httpResponse: HTTPURLResponse?
530
+ var requestError: Error?
531
+ var interruptedResumeData: Data?
532
+ let temporaryDownloadURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
533
+ let completion: (URL?, URLResponse?, Error?) -> Void = { location, response, error in
534
+ // URLSession deletes `location` once this handler returns, so move it synchronously here.
535
+ var movedFileURL: URL?
536
+ var resultError: Error?
537
+ var resultResumeData: Data?
538
+ if let error {
539
+ resultError = NetworkError.sessionTaskFailed(error)
540
+ resultResumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data
541
+ } else if let location {
542
+ do {
543
+ let fileManager = FileManager.default
544
+ try fileManager.createDirectory(
545
+ at: temporaryDownloadURL.deletingLastPathComponent(),
546
+ withIntermediateDirectories: true,
547
+ attributes: nil
548
+ )
549
+ self.removeFileIfPresent(at: temporaryDownloadURL)
550
+ try fileManager.moveItem(at: location, to: temporaryDownloadURL)
551
+ movedFileURL = temporaryDownloadURL
552
+ } catch {
553
+ resultError = NetworkError.downloadedFileMoveFailed(error, source: location, destination: temporaryDownloadURL)
554
+ }
555
+ }
556
+ let taskResponse = response as? HTTPURLResponse
557
+ self.networkResponseQueue.async {
558
+ tempFileURL = movedFileURL
559
+ httpResponse = taskResponse
560
+ requestError = resultError
561
+ interruptedResumeData = resultResumeData
562
+ semaphore.signal()
563
+ }
564
+ }
565
+ // Plain http keeps exactly the previous path: no HTTP/3 hint and no metrics delegate.
566
+ let secureDownload = Self.isHTTPS(request.url)
567
+ let request = secureDownload ? Self.preferHTTP3(request, enabled: self.http3Enabled) : request
568
+ let downloadTask = resumeData.map { self.urlSession.downloadTask(withResumeData: $0, completionHandler: completion) }
569
+ ?? self.urlSession.downloadTask(with: request, completionHandler: completion)
570
+ if secureDownload {
571
+ downloadTask.delegate = self.downloadMetricsDelegate
572
+ }
573
+ let resumedBytes: Int64 = {
574
+ guard let range = request.value(forHTTPHeaderField: "Range"),
575
+ range.hasPrefix("bytes="),
576
+ let start = range.dropFirst("bytes=".count).split(separator: "-").first else {
577
+ return 0
578
+ }
579
+ return Int64(start) ?? 0
580
+ }()
581
+ let progressObservation: NSKeyValueObservation? = onProgress.map { progressHandler in
582
+ downloadTask.progress.observe(\.fractionCompleted, options: [.new]) { progress, _ in
583
+ guard let httpResponse = downloadTask.response as? HTTPURLResponse,
584
+ (200..<300).contains(httpResponse.statusCode) else {
585
+ return
586
+ }
587
+ let responseExpected = httpResponse.expectedContentLength
588
+ let taskExpected = downloadTask.countOfBytesExpectedToReceive
589
+ let expected = responseExpected > 0
590
+ ? responseExpected
591
+ : (taskExpected > 0 ? taskExpected : progress.totalUnitCount)
592
+ let taskReceived = downloadTask.countOfBytesReceived
593
+ let received: Int64
594
+ if progress.fractionCompleted >= 1.0 && expected > 0 {
595
+ received = expected
596
+ } else if progress.totalUnitCount == expected && progress.completedUnitCount > taskReceived {
597
+ received = min(expected, progress.completedUnitCount)
598
+ } else if taskReceived > 0 {
599
+ received = expected > 0 ? min(expected, taskReceived) : taskReceived
600
+ } else if expected > 0 && progress.fractionCompleted > 0 {
601
+ received = min(expected, Int64((progress.fractionCompleted * Double(expected)).rounded()))
602
+ } else {
603
+ received = progress.completedUnitCount
604
+ }
605
+ if expected > 0 && received >= 0 {
606
+ let baseline = Self.shouldAppendHttpBody(statusCode: httpResponse.statusCode, existingBytes: resumedBytes)
607
+ ? resumedBytes
608
+ : 0
609
+ progressHandler(baseline + received, baseline + expected)
610
+ }
611
+ }
612
+ }
613
+ defer {
614
+ progressObservation?.invalidate()
615
+ }
616
+ downloadTask.resume()
617
+
618
+ if semaphore.wait(timeout: .now() + waitTimeout) == .timedOut {
619
+ downloadTask.cancel()
620
+ logger.error("\(label) timed out after \(Int(waitTimeout))s")
621
+ return DownloadRequestResult(
622
+ fileURL: existingDownloadFileURL(tempFileURL, fallback: temporaryDownloadURL),
623
+ response: httpResponse,
624
+ error: requestError,
625
+ timedOut: true
626
+ )
627
+ }
628
+
629
+ if isTimedOutError(requestError) {
630
+ logger.error("\(label) timed out after \(Int(waitTimeout))s")
631
+ }
632
+
633
+ return DownloadRequestResult(
634
+ fileURL: existingDownloadFileURL(tempFileURL, fallback: temporaryDownloadURL),
635
+ response: httpResponse,
636
+ error: requestError,
637
+ timedOut: isTimedOutError(requestError),
638
+ resumeData: interruptedResumeData
639
+ )
640
+ }
641
+
642
+ private func existingDownloadFileURL(_ fileURL: URL?, fallback: URL) -> URL? {
643
+ let fileManager = FileManager.default
644
+ if let fileURL, fileManager.fileExists(atPath: fileURL.path) {
645
+ return fileURL
646
+ }
647
+ return fileManager.fileExists(atPath: fallback.path) ? fallback : nil
648
+ }
649
+
650
+ static func shouldAppendHttpBody(statusCode: Int, existingBytes: Int64) -> Bool {
651
+ existingBytes > 0 && statusCode == 206
652
+ }
653
+
654
+ static func safePartialToken(_ fileName: String) -> String {
655
+ CryptoCipher.shortPathKey(fileName)
656
+ }
657
+
658
+ /// Scoped to one download so concurrent downloads of the same file never write one partial.
659
+ static func manifestPartialURL(cacheFolder: URL, downloadId: String, hash: String, fileName: String) -> URL {
660
+ let owner = CryptoCipher.shortPathKey(downloadId)
661
+ let token = safePartialToken(fileName)
662
+ if isSafeCacheHash(hash) && hash.count == 64 {
663
+ return cacheFolder.appendingPathComponent("partial_\(owner)_\(hash)_\(token).tmp")
664
+ }
665
+ let digest = CryptoCipher.shortPathKey("\(hash)|\(fileName)")
666
+ return cacheFolder.appendingPathComponent("partial_\(owner)_\(digest)_\(token).tmp")
667
+ }
668
+
669
+ private func removePartialManifestBundleDirectory(_ destFolder: URL) {
670
+ guard FileManager.default.fileExists(atPath: destFolder.path) else {
671
+ return
672
+ }
673
+ do {
674
+ try FileManager.default.removeItem(at: destFolder)
675
+ } catch {
676
+ logger.error("Failed to remove partial manifest bundle directory")
677
+ logger.debug("Path: \(destFolder.path), Error: \(error.localizedDescription)")
678
+ }
679
+ }
680
+
681
+ private func cleanupOldManifestPartials() {
682
+ let cutoff = Date().addingTimeInterval(-3600)
683
+ guard let files = try? FileManager.default.contentsOfDirectory(
684
+ at: cacheFolder,
685
+ includingPropertiesForKeys: [.contentModificationDateKey],
686
+ options: [.skipsHiddenFiles]
687
+ ) else {
688
+ return
689
+ }
690
+ for url in files {
691
+ let name = url.lastPathComponent
692
+ guard name.hasPrefix("partial_") && name.hasSuffix(".tmp") else {
693
+ continue
694
+ }
695
+ let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast
696
+ if modified < cutoff {
697
+ try? FileManager.default.removeItem(at: url)
698
+ }
699
+ }
700
+ }
701
+
702
+ func storeDownloadedFile(_ downloadedFileURL: URL, at tempPath: URL, existingBytes: Int64, response: HTTPURLResponse?) throws {
703
+ let fileManager = FileManager.default
704
+ if Self.shouldAppendHttpBody(statusCode: response?.statusCode ?? 0, existingBytes: existingBytes) ||
705
+ (existingBytes > 0 && response == nil) {
706
+ let fileHandle = try FileHandle(forWritingTo: tempPath)
707
+ defer {
708
+ try? fileHandle.close()
709
+ }
710
+ fileHandle.seek(toFileOffset: UInt64(existingBytes))
711
+ let input = try FileHandle(forReadingFrom: downloadedFileURL)
712
+ defer {
713
+ try? input.close()
714
+ }
715
+ let chunkSize = CryptoCipher.copyBufferBytes()
716
+ while true {
717
+ let done: Bool = try autoreleasepool {
718
+ let chunk = try input.read(upToCount: chunkSize) ?? Data()
719
+ if chunk.isEmpty {
720
+ return true
721
+ }
722
+ fileHandle.write(chunk)
723
+ return false
724
+ }
725
+ if done {
726
+ break
727
+ }
728
+ }
729
+ try? fileManager.removeItem(at: downloadedFileURL)
730
+ return
731
+ }
732
+
733
+ removeFileIfPresent(at: tempPath)
734
+ try fileManager.moveItem(at: downloadedFileURL, to: tempPath)
735
+ }
736
+
737
+ private func persistPartialDownload(_ downloadResult: DownloadRequestResult, id: String, tempPath: URL, existingBytes: Int64) {
738
+ guard let downloadedFileURL = downloadResult.fileURL else {
739
+ return
740
+ }
741
+ guard FileManager.default.fileExists(atPath: downloadedFileURL.path) else {
742
+ return
743
+ }
744
+ if let statusCode = downloadResult.response?.statusCode, statusCode < 200 || statusCode >= 300 {
745
+ return
746
+ }
747
+
748
+ do {
749
+ try storeDownloadedFile(downloadedFileURL, at: tempPath, existingBytes: existingBytes, response: downloadResult.response)
750
+ logger.info("Stored partial download for retry")
751
+ } catch {
752
+ logger.error("Failed to store partial download")
753
+ logger.debug("Path: \(downloadedFileURL.path), Error: \(error)")
754
+ }
755
+ }
756
+
757
+ deinit {
758
+ shutdown()
759
+ // Alamofire's Session invalidated its URLSession on deinit; keep releasing the session the same way.
760
+ cachedUrlSession?.invalidateAndCancel()
761
+ }
762
+
763
+ public func shutdown() {
764
+ statsPersistLock.lock()
765
+ defer { statsPersistLock.unlock() }
766
+ guard !statsStopped else { return }
767
+ statsStopped = true
768
+ statsFlushTimer?.invalidate()
769
+ statsFlushTimer = nil
770
+ persistStatsQueueLocked()
771
+ }
772
+
773
+ private func calcTotalPercent(percent: Int, min: Int, max: Int) -> Int {
774
+ return (percent * (max - min)) / 100 + min
775
+ }
776
+
777
+ private func randomString(length: Int) -> String {
778
+ let letters: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
779
+ return String((0..<length).map { _ in letters.randomElement()! })
780
+ }
781
+
782
+ private func requireSessionKeyForEncryptedUpdate(sessionKey: String, versionName: String? = nil) throws {
783
+ if !self.publicKey.isEmpty && !CryptoCipher.isValidSessionKey(sessionKey) {
784
+ logger.error("Public key present but no valid session key provided")
785
+ self.sendStats(action: "session_key_required", versionName: versionName)
786
+ throw NSError(
787
+ domain: "CapgoUpdater",
788
+ code: 1,
789
+ userInfo: [NSLocalizedDescriptionKey: "Session key required when public key is present"]
790
+ )
791
+ }
792
+ }
793
+
794
+ /// `builtinMinimum`: refuse any bundle version lower than the native app version (`versionBuild`).
795
+ /// Versions that do not parse as semver skip the check so odd native version strings never block updates.
796
+ /// Consecutive identical rejections report one stat per updater instance; every attempt still validates and throws.
797
+ func requireVersionNotBelowBuiltin(_ version: String) throws {
798
+ guard self.builtinMinimum else {
799
+ _ = self.recordVersionFloorRejection(nil)
800
+ return
801
+ }
802
+ // Build metadata (+...) never takes part in ordering, and may contain dots the parser rejects.
803
+ let bundleCore = String(version.split(separator: "+", maxSplits: 1).first ?? "")
804
+ let nativeCore = String(self.versionBuild.split(separator: "+", maxSplits: 1).first ?? "")
805
+ guard let parsedBundle = try? CapgoSemanticVersion(bundleCore),
806
+ let parsedNative = try? CapgoSemanticVersion(nativeCore) else {
807
+ _ = self.recordVersionFloorRejection(nil)
808
+ logger?.debug("builtinMinimum skipped: cannot parse bundle version \(version) or native version \(self.versionBuild)")
809
+ return
810
+ }
811
+ // Only major.minor.patch matter: a prerelease bundle at the native version is not a rollback.
812
+ let bundleVersion = CapgoSemanticVersion(major: parsedBundle.major, minor: parsedBundle.minor, patch: parsedBundle.patch)
813
+ let nativeVersion = CapgoSemanticVersion(major: parsedNative.major, minor: parsedNative.minor, patch: parsedNative.patch)
814
+ if bundleVersion < nativeVersion {
815
+ let message = "Bundle version \(version) is below native version \(self.versionBuild) (builtinMinimum)"
816
+ logger?.error(message)
817
+ if self.recordVersionFloorRejection(message) {
818
+ self.sendStats(action: "version_below_native", versionName: version)
819
+ }
820
+ throw NSError(
821
+ domain: "CapgoUpdater",
822
+ code: 8,
823
+ userInfo: [NSLocalizedDescriptionKey: message]
824
+ )
825
+ }
826
+ _ = self.recordVersionFloorRejection(nil)
827
+ }
828
+
829
+ /// Records the latest rejection atomically and returns whether it needs a stat. Nil clears the last rejection.
830
+ private func recordVersionFloorRejection(_ message: String?) -> Bool {
831
+ versionFloorRejectionLock.lock()
832
+ defer { versionFloorRejectionLock.unlock() }
833
+ let shouldReport = message != nil && lastVersionFloorRejection != message
834
+ lastVersionFloorRejection = message
835
+ return shouldReport
836
+ }
837
+
838
+ public func setPublicKey(_ publicKey: String) {
839
+ // Empty string means no encryption - proceed normally
840
+ if publicKey.isEmpty {
841
+ self.publicKey = ""
842
+ self.cachedKeyId = nil
843
+ return
844
+ }
845
+
846
+ // Non-empty: must be a valid RSA key or crash
847
+ guard RSAPublicKey.load(rsaPublicKey: publicKey) != nil else {
848
+ fatalError("Invalid public key in capacitor.config.json: failed to parse RSA key. Remove the key or provide a valid PEM-formatted RSA public key.")
849
+ }
850
+
851
+ self.publicKey = publicKey
852
+ self.cachedKeyId = CryptoCipher.calcKeyId(publicKey: publicKey)
853
+ }
854
+
855
+ public func getKeyId() -> String? {
856
+ return self.cachedKeyId
857
+ }
858
+
859
+ private var isDevEnvironment: Bool {
860
+ #if DEBUG
861
+ return true
862
+ #else
863
+ return false
864
+ #endif
865
+ }
866
+
867
+ private func isProd() -> Bool {
868
+ return !self.isDevEnvironment && !self.isAppStoreReceiptSandbox() && !self.hasEmbeddedMobileProvision()
869
+ }
870
+
871
+ private func installSource() -> String? {
872
+ if isEmulator() || self.isDevEnvironment || self.hasEmbeddedMobileProvision() {
873
+ return nil
874
+ }
875
+ guard let receiptURL = Bundle.main.appStoreReceiptURL else {
876
+ return nil
877
+ }
878
+ if receiptURL.lastPathComponent == "sandboxReceipt" {
879
+ return "testflight"
880
+ }
881
+ guard FileManager.default.fileExists(atPath: receiptURL.path) else {
882
+ return nil
883
+ }
884
+ return "app_store"
885
+ }
886
+
887
+ /**
888
+ * Checks if there is sufficient disk space for a download.
889
+ * Matches Android behavior: 2x safety margin, throws "insufficient_disk_space"
890
+ * - Parameter estimatedSize: The estimated size of the download in bytes. Defaults to 50MB.
891
+ */
892
+ private func checkDiskSpace(estimatedSize: Int64 = 50 * 1024 * 1024) throws {
893
+ let fileManager = FileManager.default
894
+ guard let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
895
+ return
896
+ }
897
+
898
+ do {
899
+ let attributes = try fileManager.attributesOfFileSystem(forPath: documentDirectory.path)
900
+ guard let freeSpace = attributes[.systemFreeSize] as? Int64 else {
901
+ logger.warn("Could not determine free disk space, proceeding with download")
902
+ return
903
+ }
904
+
905
+ let requiredSpace = estimatedSize * 2 // 2x safety margin like Android
906
+
907
+ if freeSpace < requiredSpace {
908
+ logger.error("Insufficient disk space. Available: \(freeSpace), Required: \(requiredSpace)")
909
+ self.sendStats(action: "insufficient_disk_space")
910
+ throw CustomError.insufficientDiskSpace
911
+ }
912
+ } catch let error as CustomError {
913
+ throw error
914
+ } catch {
915
+ logger.warn("Error checking disk space: \(error.localizedDescription)")
916
+ }
917
+ }
918
+
919
+ private struct RemoteBlockResult {
920
+ let blocked: Bool
921
+ let error: String
922
+ let message: String
923
+ }
924
+
925
+ /**
926
+ * Handle HTTP 429 responses by honouring Retry-After / rateLimitResetAt.
927
+ * All 429s use the same temporary client block — no sticky latch until restart.
928
+ */
929
+ private func checkAndHandleRateLimitResponse(
930
+ statusCode: Int?,
931
+ data: Data? = nil,
932
+ response: HTTPURLResponse? = nil
933
+ ) -> RemoteBlockResult {
934
+ guard statusCode == 429 else {
935
+ return RemoteBlockResult(blocked: false, error: "", message: "")
936
+ }
937
+
938
+ let parsed = parseRemoteError(from: data)
939
+ let errorCode = parsed.error.isEmpty ? "too_many_requests" : parsed.error
940
+ let message = parsed.message.isEmpty ? "Too many requests" : parsed.message
941
+
942
+ let retryUntilMs = resolveRateLimitBlockedUntilMs(data: data, response: response)
943
+ CapgoUpdater.recordRateLimitBlock(untilMs: retryUntilMs, error: errorCode, message: message)
944
+
945
+ // Claim last, and only when there is somewhere to send it, so a 429 burst with no
946
+ // stats URL does not claim and release the latch once per response.
947
+ if errorCode == "too_many_requests" && !previewSession && !statsUrl.isEmpty && CapgoUpdater.claimRateLimitStatistic() {
948
+ DispatchQueue.global(qos: .utility).async {
949
+ self.sendRateLimitStatistic()
950
+ }
951
+ }
952
+
953
+ let nowMs = Date().timeIntervalSince1970 * 1000
954
+ let retryAfter = CapgoUpdater.retryAfterSecondsForLog(untilMs: retryUntilMs, nowMs: nowMs)
955
+ logger.warn("Received 429 (\(errorCode)). Honouring Retry-After: \(retryAfter)s.")
956
+ return RemoteBlockResult(blocked: true, error: errorCode, message: message)
957
+ }
958
+
959
+ /// Stores the block deadline and its metadata together, keeping the longest deadline
960
+ /// so a concurrent 429 with a shorter window cannot cut the block short.
961
+ private static func recordRateLimitBlock(untilMs: Double, error: String, message: String) {
962
+ rateLimitStateLock.lock()
963
+ defer { rateLimitStateLock.unlock() }
964
+ if untilMs > rateLimitBlockedUntilMs {
965
+ rateLimitBlockedUntilMs = untilMs
966
+ rateLimitBlockedError = error
967
+ rateLimitBlockedMessage = message
968
+ } else if rateLimitBlockedUntilMs <= 0 {
969
+ rateLimitBlockedError = error
970
+ rateLimitBlockedMessage = message
971
+ }
972
+ }
973
+
974
+ /// Seconds left in the block, clamped and finite so the Int conversion can never trap.
975
+ private static func retryAfterSecondsForLog(untilMs: Double, nowMs: Double) -> Int {
976
+ let seconds = ((untilMs - nowMs) / 1000).rounded(.up)
977
+ guard seconds.isFinite, seconds > 0 else {
978
+ return 0
979
+ }
980
+ return Int(min(seconds, maxRateLimitWindowMs / 1000))
981
+ }
982
+
983
+ /// Returns true for the first 429 only, so the rate-limit statistic is sent once.
984
+ private static func claimRateLimitStatistic() -> Bool {
985
+ rateLimitStateLock.lock()
986
+ defer { rateLimitStateLock.unlock() }
987
+ if rateLimitStatisticSent {
988
+ return false
989
+ }
990
+ rateLimitStatisticSent = true
991
+ return true
992
+ }
993
+
994
+ /// Gives the claim back when the statistic never made it out, so a later 429 can retry it.
995
+ private static func releaseRateLimitStatisticClaim() {
996
+ rateLimitStateLock.lock()
997
+ defer { rateLimitStateLock.unlock() }
998
+ rateLimitStatisticSent = false
999
+ }
1000
+
1001
+ private func parseRemoteError(from data: Data?) -> (error: String, message: String) {
1002
+ guard let data = data,
1003
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
1004
+ return ("", "")
1005
+ }
1006
+ let error = json["error"] as? String ?? ""
1007
+ let message = json["message"] as? String ?? ""
1008
+ return (error, message)
1009
+ }
1010
+
1011
+ private func resolveRateLimitBlockedUntilMs(data: Data?, response: HTTPURLResponse?) -> Double {
1012
+ let nowMs = Date().timeIntervalSince1970 * 1000
1013
+ let candidate = rawRateLimitDeadlineMs(data: data, response: response, nowMs: nowMs)
1014
+ // NaN and past deadlines mean "no client-side block"; anything further out is capped.
1015
+ guard candidate > nowMs else {
1016
+ return 0
1017
+ }
1018
+ return min(candidate, nowMs + CapgoUpdater.maxRateLimitWindowMs)
1019
+ }
1020
+
1021
+ private func rawRateLimitDeadlineMs(data: Data?, response: HTTPURLResponse?, nowMs: Double) -> Double {
1022
+ if let header = response?.value(forHTTPHeaderField: "Retry-After")?.trimmingCharacters(in: .whitespacesAndNewlines),
1023
+ let seconds = Double(header), seconds >= 0 {
1024
+ return nowMs + seconds * 1000
1025
+ }
1026
+
1027
+ if let data = data,
1028
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
1029
+ let moreInfo = json["moreInfo"] as? [String: Any]
1030
+ if let retryAfter = (moreInfo?["retryAfterSeconds"] as? NSNumber)?.doubleValue
1031
+ ?? (json["retryAfterSeconds"] as? NSNumber)?.doubleValue,
1032
+ retryAfter >= 0 {
1033
+ return nowMs + retryAfter * 1000
1034
+ }
1035
+ if let resetAt = (moreInfo?["rateLimitResetAt"] as? NSNumber)?.doubleValue
1036
+ ?? (json["rateLimitResetAt"] as? NSNumber)?.doubleValue {
1037
+ return resetAt
1038
+ }
1039
+ }
1040
+
1041
+ // No retry hint — do not hold a client-side block; allow immediate retry to the worker
1042
+ return 0
1043
+ }
1044
+
1045
+ private func isRemoteBlocked() -> Bool {
1046
+ CapgoUpdater.rateLimitStateLock.lock()
1047
+ defer { CapgoUpdater.rateLimitStateLock.unlock() }
1048
+ if CapgoUpdater.rateLimitBlockedUntilMs <= 0 {
1049
+ return false
1050
+ }
1051
+ if Date().timeIntervalSince1970 * 1000 >= CapgoUpdater.rateLimitBlockedUntilMs {
1052
+ CapgoUpdater.rateLimitBlockedUntilMs = 0
1053
+ return false
1054
+ }
1055
+ return true
1056
+ }
1057
+
1058
+ private func remoteBlockedClientError() -> (error: String, message: String) {
1059
+ CapgoUpdater.rateLimitStateLock.lock()
1060
+ defer { CapgoUpdater.rateLimitStateLock.unlock() }
1061
+ return (CapgoUpdater.rateLimitBlockedError, CapgoUpdater.rateLimitBlockedMessage)
1062
+ }
1063
+
1064
+ /**
1065
+ * Send a synchronous statistic about rate limiting
1066
+ * Note: This method uses a semaphore to block until the request completes.
1067
+ * It MUST be called from a background queue to avoid blocking the main thread.
1068
+ */
1069
+ private func sendRateLimitStatistic() {
1070
+ guard !statsUrl.isEmpty else {
1071
+ // The URL was cleared after the claim was taken; nothing went out, so hand it back.
1072
+ CapgoUpdater.releaseRateLimitStatisticClaim()
1073
+ return
1074
+ }
1075
+
1076
+ let current = getCurrentBundle()
1077
+ var parameters = createInfoObject()
1078
+ parameters.action = "rate_limit_reached"
1079
+ parameters.version_name = current.getVersionName()
1080
+ parameters.old_version_name = ""
1081
+
1082
+ // Send synchronously using semaphore (safe because we're on a background queue)
1083
+ let semaphore = DispatchSemaphore(value: 0)
1084
+ let parameterValues = parameters.toParameters()
1085
+ self.sendJSONPost(urlString: self.statsUrl, body: {
1086
+ guard JSONSerialization.isValidJSONObject(parameterValues) else {
1087
+ throw NetworkError.bodyEncodingFailed(nil)
1088
+ }
1089
+ return try JSONSerialization.data(withJSONObject: parameterValues)
1090
+ }, completion: { _, response, error in
1091
+ let statusCode = response?.statusCode
1092
+ if let error {
1093
+ CapgoUpdater.releaseRateLimitStatisticClaim()
1094
+ self.logger.error("Error sending rate limit statistic")
1095
+ self.logger.debug("Error: \(error.localizedDescription)")
1096
+ } else if (200...299).contains(statusCode ?? 0) {
1097
+ self.logger.info("Rate limit statistic sent")
1098
+ } else {
1099
+ CapgoUpdater.releaseRateLimitStatisticClaim()
1100
+ self.logger.error("Error sending rate limit statistic")
1101
+ self.logger.debug("Response code: \(statusCode.map(String.init) ?? "nil")")
1102
+ }
1103
+ semaphore.signal()
1104
+ })
1105
+ semaphore.wait()
1106
+ }
1107
+
1108
+ // MARK: Private
1109
+ private func hasEmbeddedMobileProvision() -> Bool {
1110
+ guard Bundle.main.path(forResource: "embedded", ofType: "mobileprovision") == nil else {
1111
+ return true
1112
+ }
1113
+ return false
1114
+ }
1115
+
1116
+ private func isAppStoreReceiptSandbox() -> Bool {
1117
+
1118
+ if isEmulator() {
1119
+ return false
1120
+ } else {
1121
+ guard let url: URL = Bundle.main.appStoreReceiptURL else {
1122
+ return false
1123
+ }
1124
+ guard url.lastPathComponent == "sandboxReceipt" else {
1125
+ return false
1126
+ }
1127
+ return true
1128
+ }
1129
+ }
1130
+
1131
+ private func isEmulator() -> Bool {
1132
+ #if targetEnvironment(simulator)
1133
+ return true
1134
+ #else
1135
+ return false
1136
+ #endif
1137
+ }
1138
+ // Persistent path /var/mobile/Containers/Data/Application/8C0C07BE-0FD3-4FD4-B7DF-90A88E12B8C3/Library/NoCloud/ionic_built_snapshots/FOLDER
1139
+ // Hot Reload path /var/mobile/Containers/Data/Application/8C0C07BE-0FD3-4FD4-B7DF-90A88E12B8C3/Documents/FOLDER
1140
+ // Normal /private/var/containers/Bundle/Application/8C0C07BE-0FD3-4FD4-B7DF-90A88E12B8C3/App.app/public
1141
+
1142
+ private func prepareFolder(source: URL) throws {
1143
+ if !FileManager.default.fileExists(atPath: source.path) {
1144
+ do {
1145
+ try FileManager.default.createDirectory(atPath: source.path, withIntermediateDirectories: true, attributes: nil)
1146
+ } catch {
1147
+ logger.error("Cannot create directory")
1148
+ logger.debug("Directory path: \(source.path)")
1149
+ throw CustomError.cannotCreateDirectory
1150
+ }
1151
+ }
1152
+ }
1153
+
1154
+ private func deleteFolder(source: URL) throws {
1155
+ do {
1156
+ try FileManager.default.removeItem(atPath: source.path)
1157
+ } catch {
1158
+ logger.error("File not removed")
1159
+ logger.debug("Path: \(source.path)")
1160
+ throw CustomError.cannotDeleteDirectory
1161
+ }
1162
+ }
1163
+
1164
+ private func unflatFolder(source: URL, dest: URL) throws -> Bool {
1165
+ let index: URL = source.appendingPathComponent("index.html")
1166
+ do {
1167
+ let files: [String] = try FileManager.default.contentsOfDirectory(atPath: source.path)
1168
+ if files.count == 1 && source.appendingPathComponent(files[0]).isDirectory && !FileManager.default.fileExists(atPath: index.path) {
1169
+ try FileManager.default.moveItem(at: source.appendingPathComponent(files[0]), to: dest)
1170
+ return true
1171
+ } else {
1172
+ try FileManager.default.moveItem(at: source, to: dest)
1173
+ return false
1174
+ }
1175
+ } catch {
1176
+ logger.error("File not moved")
1177
+ logger.debug("Source: \(source.path), Dest: \(dest.path)")
1178
+ throw CustomError.cannotUnflat
1179
+ }
1180
+ }
1181
+
1182
+ private func resolveZipEntry(path: String, destUnZip: URL) throws -> URL {
1183
+ do {
1184
+ return try Self.resolvePathInsideDirectory(baseDirectory: destUnZip, relativePath: path)
1185
+ } catch SecurePathError.windowsPath {
1186
+ logger.error("Unzip failed: Windows path not supported")
1187
+ logger.debug("Invalid path: \(path)")
1188
+ self.sendStats(action: "windows_path_fail")
1189
+ throw CustomError.cannotUnzip
1190
+ } catch {
1191
+ self.sendStats(action: "canonical_path_fail")
1192
+ throw CustomError.cannotUnzip
1193
+ }
1194
+ }
1195
+
1196
+ // Symlink targets are paths; anything bigger than this is not a legitimate link.
1197
+ private static let maxZipSymlinkTargetBytes = 64 * 1024
1198
+
1199
+ /// A zip symlink target must be a relative path without `..`, so a link can only point further down.
1200
+ /// A lexical check alone is not enough: with `m -> .`, the target `m/..` normalizes to the link folder but
1201
+ /// physically resolves to its parent.
1202
+ static func isSafeZipSymlinkTarget(_ target: String) -> Bool {
1203
+ if target.isEmpty || target.contains("\0") || target.contains("\\") {
1204
+ return false
1205
+ }
1206
+ if (target as NSString).isAbsolutePath {
1207
+ return false
1208
+ }
1209
+ return !containsPathTraversalSegment(target)
1210
+ }
1211
+
1212
+ private static func realPath(_ path: String) -> String? {
1213
+ guard let resolved = Darwin.realpath(path, nil) else {
1214
+ return nil
1215
+ }
1216
+ defer { free(resolved) }
1217
+ return String(cString: resolved)
1218
+ }
1219
+
1220
+ /// Resolves symlinks on the deepest existing ancestor of `url` and throws when it is outside `root`.
1221
+ /// Run before creating anything, so a symlinked folder can never redirect a write out of the bundle.
1222
+ static func assertPhysicallyInsideDirectory(_ url: URL, root: URL) throws {
1223
+ guard let rootPath = realPath(root.path) else {
1224
+ throw SecurePathError.pathTraversal
1225
+ }
1226
+ let normalizedRoot = rootPath.hasSuffix("/") ? rootPath : "\(rootPath)/"
1227
+ var candidate = url.standardizedFileURL.path
1228
+ while true {
1229
+ if let resolved = realPath(candidate) {
1230
+ if resolved != rootPath && !resolved.hasPrefix(normalizedRoot) {
1231
+ throw SecurePathError.pathTraversal
1232
+ }
1233
+ return
1234
+ }
1235
+ let parent = (candidate as NSString).deletingLastPathComponent
1236
+ if parent == candidate || parent.isEmpty {
1237
+ throw SecurePathError.pathTraversal
1238
+ }
1239
+ candidate = parent
1240
+ }
1241
+ }
1242
+
1243
+ /// `fileExists` follows symlinks, so a dangling link would be missed; this does not follow the last component.
1244
+ private static func itemExistsWithoutFollowingLink(at url: URL) -> Bool {
1245
+ return (try? FileManager.default.attributesOfItem(atPath: url.path)) != nil
1246
+ }
1247
+
1248
+ private func extractZipEntry(_ archive: ZipArchiveReader, entry: ZipEntry, to destPath: URL, bufferSize: Int = CryptoCipher.ioBufferBytes()) throws {
1249
+ let fileManager = FileManager.default
1250
+
1251
+ switch entry.type {
1252
+ case .directory:
1253
+ try fileManager.createDirectory(at: destPath, withIntermediateDirectories: true, attributes: nil)
1254
+ case .file:
1255
+ let parentDir = destPath.deletingLastPathComponent()
1256
+ try fileManager.createDirectory(at: parentDir, withIntermediateDirectories: true, attributes: nil)
1257
+
1258
+ if Self.itemExistsWithoutFollowingLink(at: destPath) {
1259
+ try fileManager.removeItem(at: destPath)
1260
+ }
1261
+
1262
+ guard fileManager.createFile(atPath: destPath.path, contents: nil) else {
1263
+ throw CustomError.cannotUnzip
1264
+ }
1265
+
1266
+ let fileHandle = try FileHandle(forWritingTo: destPath)
1267
+ defer {
1268
+ fileHandle.closeFile()
1269
+ }
1270
+
1271
+ try archive.extract(entry, bufferSize: bufferSize) { data in
1272
+ if !data.isEmpty {
1273
+ fileHandle.write(data)
1274
+ }
1275
+ }
1276
+ case .symlink:
1277
+ let linkData = try archive.readSmallEntry(entry, maxBytes: Self.maxZipSymlinkTargetBytes, bufferSize: bufferSize)
1278
+
1279
+ guard let linkPath = String(data: linkData, encoding: .utf8), Self.isSafeZipSymlinkTarget(linkPath) else {
1280
+ logger.error("Unzip failed: unsafe symlink target")
1281
+ logger.debug("Entry: \(entry.path)")
1282
+ self.sendStats(action: "canonical_path_fail")
1283
+ throw CustomError.cannotUnzip
1284
+ }
1285
+
1286
+ let parentDir = destPath.deletingLastPathComponent()
1287
+ try fileManager.createDirectory(at: parentDir, withIntermediateDirectories: true, attributes: nil)
1288
+
1289
+ let isAbsolutePath = (linkPath as NSString).isAbsolutePath
1290
+ let linkURL = URL(fileURLWithPath: linkPath, relativeTo: isAbsolutePath ? nil : parentDir)
1291
+ let canonicalPath = linkURL.standardizedFileURL.path
1292
+ let canonicalDir = parentDir.standardizedFileURL.path
1293
+ let normalizedDir = canonicalDir.hasSuffix("/") ? canonicalDir : "\(canonicalDir)/"
1294
+
1295
+ if canonicalPath != canonicalDir && !canonicalPath.hasPrefix(normalizedDir) {
1296
+ throw CustomError.cannotUnzip
1297
+ }
1298
+
1299
+ if Self.itemExistsWithoutFollowingLink(at: destPath) {
1300
+ try fileManager.removeItem(at: destPath)
1301
+ }
1302
+
1303
+ try fileManager.createSymbolicLink(atPath: destPath.path, withDestinationPath: linkPath)
1304
+ }
1305
+ }
1306
+
1307
+ func saveDownloaded(sourceZip: URL, id: String, base: URL, notify: Bool, bufferSize: Int = CryptoCipher.ioBufferBytes()) throws {
1308
+ try prepareFolder(source: base)
1309
+ let destPersist: URL = base.appendingPathComponent(id)
1310
+ let destUnZip: URL = libraryDir.appendingPathComponent(TEMP_UNZIP_PREFIX + randomString(length: 10))
1311
+
1312
+ self.unzipPercent = 0
1313
+ self.notifyDownload(id: id, percent: 75)
1314
+
1315
+ // Open the archive
1316
+ let archive: ZipArchiveReader
1317
+ do {
1318
+ archive = try ZipArchiveReader(url: sourceZip)
1319
+ } catch {
1320
+ self.sendStats(action: "unzip_fail")
1321
+ throw CustomError.cannotUnzip
1322
+ }
1323
+
1324
+ // Create destination directory
1325
+ try FileManager.default.createDirectory(at: destUnZip, withIntermediateDirectories: true, attributes: nil)
1326
+
1327
+ // Count total entries for progress
1328
+ let totalEntries = archive.entries.count
1329
+ var processedEntries = 0
1330
+
1331
+ do {
1332
+ for entry in archive.entries {
1333
+ let destPath = try resolveZipEntry(path: entry.path, destUnZip: destUnZip)
1334
+ do {
1335
+ // Symlinks extracted earlier must not move this entry out of the bundle folder.
1336
+ try Self.assertPhysicallyInsideDirectory(destPath.deletingLastPathComponent(), root: destUnZip)
1337
+ } catch {
1338
+ logger.error("Unzip failed: entry resolves outside the bundle folder")
1339
+ logger.debug("Entry: \(entry.path)")
1340
+ self.sendStats(action: "canonical_path_fail")
1341
+ throw CustomError.cannotUnzip
1342
+ }
1343
+
1344
+ if entry.type == .directory {
1345
+ try FileManager.default.createDirectory(at: destPath, withIntermediateDirectories: true, attributes: nil)
1346
+ processedEntries += 1
1347
+ if notify && totalEntries > 0 {
1348
+ let newPercent = self.calcTotalPercent(percent: Int(Double(processedEntries) / Double(totalEntries) * 100), min: 75, max: 81)
1349
+ if newPercent != self.unzipPercent {
1350
+ self.unzipPercent = newPercent
1351
+ self.notifyDownload(id: id, percent: newPercent)
1352
+ }
1353
+ }
1354
+ continue
1355
+ }
1356
+
1357
+ // Create parent directories if needed
1358
+ let parentDir = destPath.deletingLastPathComponent()
1359
+ if !FileManager.default.fileExists(atPath: parentDir.path) {
1360
+ try FileManager.default.createDirectory(at: parentDir, withIntermediateDirectories: true, attributes: nil)
1361
+ }
1362
+
1363
+ try self.extractZipEntry(archive, entry: entry, to: destPath, bufferSize: bufferSize)
1364
+
1365
+ // Update progress
1366
+ processedEntries += 1
1367
+ if notify && totalEntries > 0 {
1368
+ let newPercent = self.calcTotalPercent(percent: Int(Double(processedEntries) / Double(totalEntries) * 100), min: 75, max: 81)
1369
+ if newPercent != self.unzipPercent {
1370
+ self.unzipPercent = newPercent
1371
+ self.notifyDownload(id: id, percent: newPercent)
1372
+ }
1373
+ }
1374
+ }
1375
+ } catch {
1376
+ self.sendStats(action: "unzip_fail")
1377
+ try? FileManager.default.removeItem(at: destUnZip)
1378
+ throw error
1379
+ }
1380
+
1381
+ if try unflatFolder(source: destUnZip, dest: destPersist) {
1382
+ try deleteFolder(source: destUnZip)
1383
+ }
1384
+
1385
+ // Cleanup: remove the downloaded/decrypted zip after successful extraction
1386
+ do {
1387
+ if FileManager.default.fileExists(atPath: sourceZip.path) {
1388
+ try FileManager.default.removeItem(at: sourceZip)
1389
+ }
1390
+ } catch {
1391
+ logger.error("Could not delete source zip")
1392
+ logger.debug("Path: \(sourceZip.path), Error: \(error)")
1393
+ }
1394
+ }
1395
+
1396
+ private func populateDeltaCacheAsync(for id: String, manifest: [ManifestEntry]? = nil, sessionKey: String = "") {
1397
+ DispatchQueue.global(qos: .utility).async { [weak self] in
1398
+ self?.populateDeltaCache(for: id, manifest: manifest, sessionKey: sessionKey)
1399
+ }
1400
+ }
1401
+
1402
+ struct ManifestLookupEntry {
1403
+ let hash: String
1404
+ /// The manifest's own file name, `.br` suffix included when present.
1405
+ let originalFileName: String
1406
+ }
1407
+
1408
+ /// Keys are stripped of the `.br` suffix so they match the extracted file names on
1409
+ /// disk, not the manifest's (possibly brotli-compressed) original file names.
1410
+ func manifestHashLookup(manifest: [ManifestEntry]?, sessionKey: String) -> [String: ManifestLookupEntry] {
1411
+ guard let manifest else {
1412
+ return [:]
1413
+ }
1414
+ var lookup: [String: ManifestLookupEntry] = [:]
1415
+ for entry in manifest {
1416
+ guard let fileName = entry.file_name,
1417
+ let hash = resolveManifestFileHash(entry: entry, sessionKey: sessionKey) else {
1418
+ continue
1419
+ }
1420
+ let destFileName = fileName.hasSuffix(".br") ? String(fileName.dropLast(3)) : fileName
1421
+ lookup[destFileName] = ManifestLookupEntry(hash: hash, originalFileName: fileName)
1422
+ }
1423
+ return lookup
1424
+ }
1425
+
1426
+ /// `manifest` must only contain entries the caller already checksum-verified
1427
+ /// (as `downloadManifest` does) — the hashes are trusted as-is, not re-checked.
1428
+ func populateDeltaCache(for id: String, manifest: [ManifestEntry]? = nil, sessionKey: String = "") {
1429
+ let bundleDir: URL
1430
+ do {
1431
+ bundleDir = try self.getBundleDirectory(id: id)
1432
+ } catch {
1433
+ logger.debug("Skip delta cache population: invalid bundle id")
1434
+ return
1435
+ }
1436
+ let fileManager = FileManager.default
1437
+
1438
+ guard fileManager.fileExists(atPath: bundleDir.path) else {
1439
+ logger.debug("Skip delta cache population: bundle dir missing")
1440
+ return
1441
+ }
1442
+
1443
+ do {
1444
+ try fileManager.createDirectory(at: cacheFolder, withIntermediateDirectories: true, attributes: nil)
1445
+ } catch {
1446
+ logger.debug("Skip delta cache population: failed to create cache dir")
1447
+ return
1448
+ }
1449
+
1450
+ guard let enumerator = fileManager.enumerator(at: bundleDir, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles]) else {
1451
+ return
1452
+ }
1453
+
1454
+ let knownEntries = manifestHashLookup(manifest: manifest, sessionKey: sessionKey)
1455
+ let builtinFolder = self.builtinFolderURL()
1456
+
1457
+ for case let fileURL as URL in enumerator {
1458
+ let resourceValues = try? fileURL.resourceValues(forKeys: [.isDirectoryKey])
1459
+ if resourceValues?.isDirectory == true {
1460
+ continue
1461
+ }
1462
+
1463
+ let relativePath = String(fileURL.path.dropFirst(bundleDir.path.count + 1))
1464
+ let knownEntry = knownEntries[relativePath]
1465
+
1466
+ let checksum = knownEntry?.hash ?? CryptoCipher.calcChecksum(filePath: fileURL)
1467
+ if checksum.isEmpty {
1468
+ continue
1469
+ }
1470
+
1471
+ // Builtin is already a permanent reuse source (see isManifestEntryAvailableLocally),
1472
+ // so there's no need to also duplicate this file into the delta cache
1473
+ let builtinLookupName = knownEntry?.originalFileName ?? relativePath
1474
+ let isBuiltinOrigin: Bool
1475
+ if let builtinFilePath = try? Self.resolveManifestTargetPath(baseDirectory: builtinFolder, fileName: builtinLookupName) {
1476
+ isBuiltinOrigin = builtinFileMatches(builtinFilePath, expectedHash: checksum)
1477
+ } else {
1478
+ isBuiltinOrigin = false
1479
+ }
1480
+ if isBuiltinOrigin {
1481
+ continue
1482
+ }
1483
+
1484
+ let cacheFile = cacheFolder.appendingPathComponent("\(checksum)_\(fileURL.lastPathComponent)")
1485
+ if fileManager.fileExists(atPath: cacheFile.path) {
1486
+ continue
1487
+ }
1488
+
1489
+ do {
1490
+ try linkOrCopyImmutableFile(from: fileURL, to: cacheFile)
1491
+ } catch {
1492
+ logger.debug("Delta cache copy failed: \(fileURL.path)")
1493
+ }
1494
+ }
1495
+ }
1496
+
1497
+ private func createInfoObject(appIdOverride: String? = nil) -> InfoObject {
1498
+ return InfoObject(
1499
+ platform: "ios",
1500
+ device_id: self.deviceID,
1501
+ app_id: appIdOverride ?? self.appId,
1502
+ custom_id: self.customId,
1503
+ version_build: self.versionBuild,
1504
+ version_code: self.versionCode,
1505
+ version_os: self.versionOs,
1506
+ version_name: self.getCurrentBundle().getVersionName(),
1507
+ plugin_version: self.pluginVersion,
1508
+ is_emulator: self.isEmulator(),
1509
+ is_prod: self.isProd(),
1510
+ installSource: self.installSource(),
1511
+ action: nil,
1512
+ channel: nil,
1513
+ defaultChannel: self.defaultChannel,
1514
+ key_id: self.cachedKeyId
1515
+ )
1516
+ }
1517
+
1518
+ public func getLatest(url: URL, channel: String?, appIdOverride: String? = nil) -> AppVersion {
1519
+ let latest: AppVersion = AppVersion()
1520
+ if isRemoteBlocked() {
1521
+ let blocked = remoteBlockedClientError()
1522
+ logger.debug("Skipping getLatest due to remote block (\(blocked.error)).")
1523
+ latest.message = blocked.message
1524
+ latest.error = blocked.error
1525
+ latest.kind = "failed"
1526
+ return latest
1527
+ }
1528
+ func applyLatestResponse(_ value: AppVersionDec?) {
1529
+ if let url = value?.url {
1530
+ latest.url = url
1531
+ }
1532
+ if let checksum = value?.checksum {
1533
+ latest.checksum = checksum
1534
+ }
1535
+ if let version = value?.version {
1536
+ latest.version = version
1537
+ }
1538
+ if let major = value?.major {
1539
+ latest.major = major
1540
+ }
1541
+ if let breaking = value?.breaking {
1542
+ latest.breaking = breaking
1543
+ }
1544
+ if let error = value?.error {
1545
+ latest.error = error
1546
+ }
1547
+ if let kind = value?.kind {
1548
+ latest.kind = kind
1549
+ }
1550
+ if let message = value?.message {
1551
+ latest.message = message
1552
+ }
1553
+ if let sessionKey = value?.session_key {
1554
+ latest.sessionKey = sessionKey
1555
+ }
1556
+ if let data = value?.data {
1557
+ latest.data = data
1558
+ }
1559
+ if let manifest = value?.manifest {
1560
+ latest.manifest = manifest
1561
+ }
1562
+ if let link = value?.link {
1563
+ latest.link = link
1564
+ }
1565
+ if let comment = value?.comment {
1566
+ latest.comment = comment
1567
+ }
1568
+ }
1569
+
1570
+ var parameters: InfoObject = self.createInfoObject(appIdOverride: appIdOverride)
1571
+ if let channel = channel {
1572
+ parameters.defaultChannel = channel
1573
+ }
1574
+ guard let request = createRequest(url: url, method: "POST", parameters: parameters.toParameters()) else {
1575
+ latest.message = "Error getting Latest"
1576
+ latest.error = "request_error"
1577
+ latest.kind = "failed"
1578
+ return latest
1579
+ }
1580
+
1581
+ let result = performRequest(request, label: "getLatest")
1582
+ latest.statusCode = result.response?.statusCode ?? 0
1583
+
1584
+ if result.timedOut {
1585
+ latest.message = "Error getting Latest"
1586
+ latest.error = "timeout_error"
1587
+ latest.kind = "failed"
1588
+ return latest
1589
+ }
1590
+
1591
+ if let error = result.error {
1592
+ self.logger.error("Error getting latest version")
1593
+ self.logger.debug("Error: \(error.localizedDescription)")
1594
+ latest.message = "Error getting Latest"
1595
+ latest.error = "response_error"
1596
+ latest.kind = "failed"
1597
+ return latest
1598
+ }
1599
+
1600
+ guard let data = result.data else {
1601
+ self.logger.error("Missing latest version response data")
1602
+ latest.message = "Error getting Latest"
1603
+ latest.error = "response_error"
1604
+ latest.kind = "failed"
1605
+ return latest
1606
+ }
1607
+
1608
+ let rateLimit = self.checkAndHandleRateLimitResponse(
1609
+ statusCode: latest.statusCode,
1610
+ data: data,
1611
+ response: result.response
1612
+ )
1613
+ if rateLimit.blocked {
1614
+ latest.message = rateLimit.message
1615
+ latest.error = rateLimit.error
1616
+ latest.kind = "failed"
1617
+ return latest
1618
+ }
1619
+
1620
+ guard let responseValue = try? JSONDecoder().decode(AppVersionDec.self, from: data) else {
1621
+ self.logger.error("Error decoding latest version")
1622
+ latest.message = "Error getting Latest"
1623
+ latest.error = "decode_error"
1624
+ latest.kind = "failed"
1625
+ return latest
1626
+ }
1627
+
1628
+ applyLatestResponse(responseValue)
1629
+
1630
+ if latest.statusCode < 200 || latest.statusCode >= 300 {
1631
+ if latest.message == nil || latest.message?.isEmpty == true {
1632
+ latest.message = responseValue.message ?? "Server error: \(latest.statusCode)"
1633
+ }
1634
+ if latest.error == nil || latest.error?.isEmpty == true {
1635
+ latest.error = responseValue.error ?? "response_error"
1636
+ }
1637
+ if latest.kind == nil || latest.kind?.isEmpty == true {
1638
+ latest.kind = responseValue.kind ?? "failed"
1639
+ }
1640
+ return latest
1641
+ }
1642
+
1643
+ return latest
1644
+ }
1645
+
1646
+ private func setCurrentBundle(bundle: String) {
1647
+ UserDefaults.standard.set(bundle, forKey: self.CAP_SERVER_PATH)
1648
+ UserDefaults.standard.synchronize()
1649
+ logger.info("Current bundle set to: \((bundle ).isEmpty ? BundleInfo.ID_BUILTIN : bundle)")
1650
+ }
1651
+
1652
+ static func shouldResetForForeignBundle(bundlePath: String?, isBuiltin: Bool, hasStoredBundleInfo: Bool) -> Bool {
1653
+ guard let bundlePath, !bundlePath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
1654
+ return false
1655
+ }
1656
+ return !isBuiltin && !hasStoredBundleInfo
1657
+ }
1658
+
1659
+ private func hasStoredBundleInfo(id: String) -> Bool {
1660
+ guard !id.isEmpty,
1661
+ id != BundleInfo.ID_BUILTIN,
1662
+ id != BundleInfo.VERSION_UNKNOWN else {
1663
+ return false
1664
+ }
1665
+ return UserDefaults.standard.object(forKey: "\(id)\(self.INFO_SUFFIX)") != nil
1666
+ }
1667
+
1668
+ // Per-download temp file paths to prevent collisions when multiple downloads run concurrently
1669
+ private func tempDataPath(for id: String) -> URL {
1670
+ return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("package_\(id).tmp")
1671
+ }
1672
+
1673
+ private func updateInfoPath(for id: String) -> URL {
1674
+ return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("update_\(id).dat")
1675
+ }
1676
+
1677
+ private var tempData = Data()
1678
+
1679
+ private func verifyChecksum(file: URL, expectedHash: String) -> Bool {
1680
+ let actualHash = CryptoCipher.calcChecksum(filePath: file)
1681
+ return actualHash == expectedHash
1682
+ }
1683
+
1684
+ /// Overridable so tests can point it at a writable directory instead of the
1685
+ /// real (read-only) app bundle.
1686
+ func builtinFolderURL() -> URL {
1687
+ Bundle.main.bundleURL.appendingPathComponent("public")
1688
+ }
1689
+
1690
+ // Precomputed builtin hashes: `ota-builtin-hashes.json` in the web assets dir (Capacitor sync hook).
1691
+ // Loaded lazily once per process; missing or invalid JSON is cached as an empty map.
1692
+ static let builtinHashesFileName = "ota-builtin-hashes.json"
1693
+ private static func isSha256Hex(_ value: String) -> Bool {
1694
+ guard value.count == 64 else { return false }
1695
+ let hex = CharacterSet(charactersIn: "0123456789abcdefABCDEF")
1696
+ return value.unicodeScalars.allSatisfy { hex.contains($0) }
1697
+ }
1698
+
1699
+ private struct BuiltinHashEntry {
1700
+ let hash: String
1701
+ /// `nil` for legacy string-only manifest entries (no size gate).
1702
+ let size: Int64?
1703
+ }
1704
+
1705
+ private var cachedBuiltinHashes: [String: BuiltinHashEntry]?
1706
+ private let builtinHashesLock = NSLock()
1707
+ /// Disk reads of `ota-builtin-hashes.json` (lazy once per updater instance / process).
1708
+ private(set) var builtinHashesTableLoadCount = 0
1709
+
1710
+ private func builtinHashes() -> [String: BuiltinHashEntry] {
1711
+ builtinHashesLock.lock()
1712
+ defer { builtinHashesLock.unlock() }
1713
+ if let hashes = cachedBuiltinHashes {
1714
+ return hashes
1715
+ }
1716
+ var hashes: [String: BuiltinHashEntry] = [:]
1717
+ let tableURL = builtinFolderURL().appendingPathComponent(Self.builtinHashesFileName)
1718
+ builtinHashesTableLoadCount += 1
1719
+ if let data = try? Data(contentsOf: tableURL),
1720
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
1721
+ let files = json["files"] as? [String: Any] {
1722
+ for (key, value) in files {
1723
+ if let hash = value as? String, Self.isSha256Hex(hash) {
1724
+ hashes[key] = BuiltinHashEntry(hash: hash, size: nil)
1725
+ continue
1726
+ }
1727
+ guard let obj = value as? [String: Any],
1728
+ let hash = obj["sha256"] as? String,
1729
+ Self.isSha256Hex(hash) else { continue }
1730
+ let sizeValue: Int64?
1731
+ if obj["size"] == nil || obj["size"] is NSNull {
1732
+ sizeValue = nil
1733
+ } else if let size = obj["size"] as? NSNumber,
1734
+ CFGetTypeID(size) != CFBooleanGetTypeID(),
1735
+ let exact = Int64(exactly: size.doubleValue),
1736
+ exact >= 0 {
1737
+ sizeValue = exact
1738
+ } else {
1739
+ continue
1740
+ }
1741
+ hashes[key] = BuiltinHashEntry(hash: hash, size: sizeValue)
1742
+ }
1743
+ }
1744
+ cachedBuiltinHashes = hashes
1745
+ return hashes
1746
+ }
1747
+
1748
+ private func builtinTableVerdict(relativePath: String, fileURL: URL, expectedHash: String) -> Bool? {
1749
+ guard let entry = builtinHashes()[relativePath] else {
1750
+ return nil
1751
+ }
1752
+ guard FileManager.default.fileExists(atPath: fileURL.path) else {
1753
+ return false
1754
+ }
1755
+ if let expectedSize = entry.size {
1756
+ let actualSize = (try? fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize).map { Int64($0) }
1757
+ if actualSize != expectedSize {
1758
+ return nil
1759
+ }
1760
+ }
1761
+ return entry.hash.lowercased() == expectedHash.lowercased()
1762
+ }
1763
+
1764
+ private func builtinFileMatches(_ builtinFilePath: URL, expectedHash: String) -> Bool {
1765
+ let basePath = builtinFolderURL().standardizedFileURL.path
1766
+ let filePath = builtinFilePath.standardizedFileURL.path
1767
+ if filePath.hasPrefix(basePath + "/") {
1768
+ let relativePath = String(filePath.dropFirst(basePath.count + 1))
1769
+ if let verdict = builtinTableVerdict(relativePath: relativePath, fileURL: builtinFilePath, expectedHash: expectedHash) {
1770
+ return verdict
1771
+ }
1772
+ }
1773
+ return FileManager.default.fileExists(atPath: builtinFilePath.path) &&
1774
+ verifyChecksum(file: builtinFilePath, expectedHash: expectedHash)
1775
+ }
1776
+
1777
+ private func resolveManifestFileHash(entry: ManifestEntry, sessionKey: String) -> String? {
1778
+ guard var fileHash = entry.file_hash, !fileHash.isEmpty else {
1779
+ return nil
1780
+ }
1781
+ if !self.publicKey.isEmpty {
1782
+ if !CryptoCipher.isValidSessionKey(sessionKey) {
1783
+ return nil
1784
+ }
1785
+ do {
1786
+ fileHash = try CryptoCipher.decryptChecksum(checksum: fileHash, publicKey: self.publicKey)
1787
+ } catch {
1788
+ logger.error("Checksum decryption failed while checking missing manifest files")
1789
+ logger.debug("File: \(entry.file_name ?? "unknown"), Error: \(error.localizedDescription)")
1790
+ return nil
1791
+ }
1792
+ }
1793
+ return fileHash
1794
+ }
1795
+
1796
+ private func isManifestEntryAvailableLocally(entry: ManifestEntry, sessionKey: String) -> Bool {
1797
+ guard let fileName = entry.file_name,
1798
+ let fileHash = resolveManifestFileHash(entry: entry, sessionKey: sessionKey) else {
1799
+ return false
1800
+ }
1801
+
1802
+ let builtinFolder = self.builtinFolderURL()
1803
+ // The .br suffix describes transport; builtin assets are uncompressed.
1804
+ guard let builtinFilePath = try? Self.resolveManifestTargetPath(baseDirectory: builtinFolder, fileName: fileName) else {
1805
+ return false
1806
+ }
1807
+ if builtinFileMatches(builtinFilePath, expectedHash: fileHash) {
1808
+ return true
1809
+ }
1810
+
1811
+ let fileNameWithoutPath = (fileName as NSString).lastPathComponent
1812
+ let isBrotli = fileName.hasSuffix(".br")
1813
+ let cacheBaseName = isBrotli ? String(fileNameWithoutPath.dropLast(3)) : fileNameWithoutPath
1814
+ if Self.isSafeCacheHash(fileHash) {
1815
+ let cacheFilePath = cacheFolder.appendingPathComponent("\(fileHash)_\(cacheBaseName)")
1816
+ // Cache files are named `{hash}_{filename}` and were checksum-verified
1817
+ // when written. Re-hashing every hit re-reads the whole bundle and
1818
+ // OOMs/janks low-RAM devices during getMissing / delta apply.
1819
+ if isReusableCacheFile(cacheFilePath, expectedHash: fileHash) {
1820
+ return true
1821
+ }
1822
+
1823
+ if isBrotli {
1824
+ let legacyCacheFilePath = cacheFolder.appendingPathComponent("\(fileHash)_\(fileNameWithoutPath)")
1825
+ if isReusableCacheFile(legacyCacheFilePath, expectedHash: fileHash) {
1826
+ return true
1827
+ }
1828
+ }
1829
+ }
1830
+
1831
+ return false
1832
+ }
1833
+
1834
+ /// SHA-256 hash-named cache files were verified when written. Existence is
1835
+ /// enough for non-empty files; empty files are reused only for the empty SHA-256.
1836
+ /// CRC32 (8 hex) is too collision-prone to trust without a re-read.
1837
+ private func isReusableCacheFile(_ url: URL, expectedHash: String) -> Bool {
1838
+ guard Self.isSafeCacheHash(expectedHash), expectedHash.count == 64 else {
1839
+ return false
1840
+ }
1841
+ let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? -1
1842
+ if size > 0 {
1843
+ return true
1844
+ }
1845
+ return size == 0 && expectedHash.lowercased() == Self.emptySha256
1846
+ }
1847
+
1848
+ static func isSafeCacheHash(_ hash: String) -> Bool {
1849
+ let count = hash.count
1850
+ guard count == 64 || count == 8 else {
1851
+ return false
1852
+ }
1853
+ return hash.unicodeScalars.allSatisfy { scalar in
1854
+ (0x30...0x39).contains(scalar.value) ||
1855
+ (0x41...0x46).contains(scalar.value) ||
1856
+ (0x61...0x66).contains(scalar.value)
1857
+ }
1858
+ }
1859
+
1860
+ public func getMissingBundleFiles(manifest: [ManifestEntry], sessionKey: String) -> [ManifestEntry] {
1861
+ return manifest.filter { entry in
1862
+ !isManifestEntryAvailableLocally(entry: entry, sessionKey: sessionKey)
1863
+ }
1864
+ }
1865
+
1866
+ public func missingBundleFilesResult(manifest: [ManifestEntry], sessionKey: String) -> [String: Any] {
1867
+ let missing = getMissingBundleFiles(manifest: manifest, sessionKey: sessionKey)
1868
+ return [
1869
+ "missing": missing.map { $0.toDict() },
1870
+ "total": manifest.count,
1871
+ "missingCount": missing.count,
1872
+ "reusableCount": manifest.count - missing.count
1873
+ ]
1874
+ }
1875
+
1876
+ private func manifestSizeUrl(from updateUrl: URL) -> URL {
1877
+ var components = URLComponents(url: updateUrl, resolvingAgainstBaseURL: false)
1878
+ let path = components?.path ?? updateUrl.path
1879
+ let trimmedPath = path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
1880
+ components?.path = trimmedPath == ""
1881
+ ? "/manifest_size"
1882
+ : "/\(trimmedPath)/manifest_size"
1883
+ components?.query = nil
1884
+ return components?.url ?? updateUrl.appendingPathComponent("manifest_size")
1885
+ }
1886
+
1887
+ private func unavailableBundleSizeResult(manifest: [ManifestEntry], error: String) -> [String: Any] {
1888
+ return [
1889
+ "totalSize": 0,
1890
+ "knownFiles": 0,
1891
+ "unknownFiles": manifest.count,
1892
+ "files": manifest.map {
1893
+ var dict = $0.toDict()
1894
+ dict["error"] = error
1895
+ return dict
1896
+ }
1897
+ ]
1898
+ }
1899
+
1900
+ public func getBundleDownloadSize(updateUrl: URL, version: String?, manifest: [ManifestEntry]) -> [String: Any] {
1901
+ if manifest.isEmpty {
1902
+ return [
1903
+ "totalSize": 0,
1904
+ "knownFiles": 0,
1905
+ "unknownFiles": 0,
1906
+ "files": []
1907
+ ]
1908
+ }
1909
+
1910
+ var parameters = self.createInfoObject().toParameters()
1911
+ parameters["version"] = version ?? ""
1912
+ parameters["manifest"] = manifest.map { $0.toDict() }
1913
+
1914
+ guard let request = createRequest(url: manifestSizeUrl(from: updateUrl), method: "POST", parameters: parameters) else {
1915
+ return unavailableBundleSizeResult(manifest: manifest, error: "request_error")
1916
+ }
1917
+
1918
+ let result = performRequest(request, label: "getBundleDownloadSize")
1919
+ if result.timedOut {
1920
+ return unavailableBundleSizeResult(manifest: manifest, error: "timeout_error")
1921
+ }
1922
+ if let error = result.error {
1923
+ logger.error("Error getting bundle download size")
1924
+ logger.debug("Error: \(error.localizedDescription)")
1925
+ return unavailableBundleSizeResult(manifest: manifest, error: "response_error")
1926
+ }
1927
+ guard let data = result.data,
1928
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
1929
+ return unavailableBundleSizeResult(manifest: manifest, error: "parse_error")
1930
+ }
1931
+
1932
+ let statusCode = result.response?.statusCode ?? 0
1933
+ if statusCode < 200 || statusCode >= 300 {
1934
+ return unavailableBundleSizeResult(manifest: manifest, error: "response_error")
1935
+ }
1936
+
1937
+ return json
1938
+ }
1939
+
1940
+ private func runBeforeDownload() throws {
1941
+ try beforeDownload?()
1942
+ }
1943
+
1944
+ public func downloadManifest(manifest: [ManifestEntry], version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
1945
+ let id = self.randomString(length: 10)
1946
+ let totalFiles = manifest.count
1947
+
1948
+ // Thread-safe counters for concurrent operations
1949
+ let progressLock = NSLock()
1950
+ var completedFiles = 0
1951
+ var lastProgressPercent = -1
1952
+ let hasError = AtomicBool(initialValue: false)
1953
+ var downloadError: Error?
1954
+ var firstFile: String?
1955
+ var failedFiles = 0
1956
+ var failureStage = "prepare_or_schedule"
1957
+ let started = ProcessInfo.processInfo.systemUptime
1958
+ func reportFailure(_ error: Error) {
1959
+ let failure = Self.manifestFailureCause(error)
1960
+ var metadata = ["attempt_id": id, "files_completed": String(completedFiles), "files_total": String(totalFiles),
1961
+ "files_failed": String(failedFiles), "error_type": failure.domain, "error_code": String(failure.code),
1962
+ "elapsed_ms": String(Int((ProcessInfo.processInfo.systemUptime - started) * 1000))]
1963
+ metadata["failure_stage"] = failureStage
1964
+ metadata["last_percent"] = String(max(0, lastProgressPercent))
1965
+ metadata["first_file"] = firstFile
1966
+ if failure.domain == "StatusCodeError" { metadata["http_status"] = String(failure.code) }
1967
+ self.sendStats(
1968
+ action: "download_manifest_file_fail", versionName: version,
1969
+ oldVersionName: "", metadata: metadata
1970
+ )
1971
+ }
1972
+ let errorLock = NSLock()
1973
+
1974
+ func recordInvalidEntry(_ error: Error, _ fileName: String?) {
1975
+ failedFiles += 1
1976
+ if downloadError == nil {
1977
+ downloadError = error
1978
+ }
1979
+ if firstFile == nil, let fileName, !fileName.isEmpty {
1980
+ firstFile = fileName
1981
+ }
1982
+ hasError.value = true
1983
+ }
1984
+
1985
+ let decryptionSession = CryptoCipher.DecryptionSession(publicKey: self.publicKey, sessionKey: sessionKey)
1986
+ let builtinFolder = self.builtinFolderURL()
1987
+ let destFolder: URL
1988
+ do {
1989
+ try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
1990
+ try self.requireVersionNotBelowBuiltin(version)
1991
+ for entry in manifest {
1992
+ if let downloadUrl = entry.download_url, let url = URL(string: downloadUrl) {
1993
+ do {
1994
+ try self.assertAllowedScheme(url)
1995
+ } catch {
1996
+ recordInvalidEntry(error, entry.file_name)
1997
+ throw error
1998
+ }
1999
+ }
2000
+ }
2001
+ try self.runBeforeDownload()
2002
+ logger.info("downloadManifest start \(id)")
2003
+ destFolder = try self.getBundleDirectory(id: id)
2004
+
2005
+ // Check disk space before starting manifest download (estimate 100KB per file, minimum 50MB)
2006
+ let estimatedSize = Int64(max(manifest.count * 100 * 1024, 50 * 1024 * 1024))
2007
+ try checkDiskSpace(estimatedSize: estimatedSize)
2008
+
2009
+ try FileManager.default.createDirectory(at: cacheFolder, withIntermediateDirectories: true, attributes: nil)
2010
+ cleanupOldManifestPartials()
2011
+ try FileManager.default.createDirectory(at: destFolder, withIntermediateDirectories: true, attributes: nil)
2012
+ } catch {
2013
+ reportFailure(error)
2014
+ throw error
2015
+ }
2016
+
2017
+ // Create and save BundleInfo before starting the download process
2018
+ let bundleInfo = BundleInfo(id: id, version: version, status: BundleStatus.DOWNLOADING, downloaded: Date(), checksum: "", link: link, comment: comment)
2019
+ self.saveBundleInfo(id: id, bundle: bundleInfo)
2020
+
2021
+ // Send stats for manifest download start
2022
+ self.sendStats(
2023
+ action: "download_manifest_start", versionName: version,
2024
+ oldVersionName: "", metadata: ["attempt_id": id]
2025
+ )
2026
+
2027
+ // Notify the start of the download process
2028
+ self.notifyDownload(id: id, percent: 0, ignoreMultipleOfTen: true)
2029
+
2030
+ var tasks: [ManifestDownloadTask] = []
2031
+ var seenTargets = Set<String>()
2032
+
2033
+ for entry in manifest {
2034
+ guard let fileName = entry.file_name,
2035
+ let downloadUrl = entry.download_url else {
2036
+ let error = NSError(
2037
+ domain: "ManifestEntryError",
2038
+ code: 1,
2039
+ userInfo: [
2040
+ NSLocalizedDescriptionKey: "Manifest entry is missing file_name or download_url"
2041
+ ]
2042
+ )
2043
+ recordInvalidEntry(error, entry.file_name)
2044
+ logger.error("Manifest entry is missing file_name or download_url")
2045
+ continue
2046
+ }
2047
+ guard let entryFileHash = entry.file_hash, !entryFileHash.isEmpty else {
2048
+ logger.error("Missing file_hash for manifest entry: \(entry.file_name ?? "unknown")")
2049
+ let error = NSError(
2050
+ domain: "ManifestEntryError",
2051
+ code: 2,
2052
+ userInfo: [
2053
+ NSLocalizedDescriptionKey: "Manifest entry is missing file_hash for \(entry.file_name ?? "unknown")"
2054
+ ]
2055
+ )
2056
+ recordInvalidEntry(error, entry.file_name)
2057
+ continue
2058
+ }
2059
+ var fileHash = entryFileHash
2060
+ var ciphertextHash: String?
2061
+
2062
+ // Decrypt checksum if needed (done before creating operation)
2063
+ if !self.publicKey.isEmpty {
2064
+ if !CryptoCipher.isValidSessionKey(sessionKey) {
2065
+ let error = NSError(
2066
+ domain: "CapgoUpdater",
2067
+ code: 1,
2068
+ userInfo: [NSLocalizedDescriptionKey: "Session key required when public key is present"]
2069
+ )
2070
+ self.sendStats(action: "session_key_required", versionName: version)
2071
+ recordInvalidEntry(error, entry.file_name)
2072
+ logger.error("Public key present but no valid session key provided")
2073
+ continue
2074
+ }
2075
+ do {
2076
+ let signed = try CryptoCipher.decryptBundleChecksum(checksum: fileHash, publicKey: self.publicKey)
2077
+ fileHash = signed.plain
2078
+ ciphertextHash = signed.ciphertext
2079
+ } catch {
2080
+ recordInvalidEntry(error, entry.file_name)
2081
+ logger.error("Checksum decryption failed")
2082
+ logger.debug("Bundle: \(id), File: \(fileName), Error: \(error)")
2083
+ continue
2084
+ }
2085
+ }
2086
+
2087
+ let finalFileHash = fileHash
2088
+ let fileNameWithoutPath = (fileName as NSString).lastPathComponent
2089
+ let isBrotli = fileName.hasSuffix(".br")
2090
+ let cacheBaseName = isBrotli ? String(fileNameWithoutPath.dropLast(3)) : fileNameWithoutPath
2091
+ let cacheFilePath: URL? = Self.isSafeCacheHash(finalFileHash)
2092
+ ? cacheFolder.appendingPathComponent("\(finalFileHash)_\(cacheBaseName)")
2093
+ : nil
2094
+ let legacyCacheFilePath: URL? = isBrotli && cacheFilePath != nil
2095
+ ? cacheFolder.appendingPathComponent("\(finalFileHash)_\(fileNameWithoutPath)")
2096
+ : nil
2097
+
2098
+ let destFileName = isBrotli ? String(fileName.dropLast(3)) : fileName
2099
+ let destFilePath: URL
2100
+ let builtinFilePath: URL
2101
+ do {
2102
+ destFilePath = try Self.resolveManifestTargetPath(baseDirectory: destFolder, fileName: fileName)
2103
+ builtinFilePath = try Self.resolveManifestTargetPath(baseDirectory: builtinFolder, fileName: fileName)
2104
+ if !Self.rememberManifestTarget(&seenTargets, targetFile: destFilePath) {
2105
+ logger.error("Duplicate manifest target path: \(fileName)")
2106
+ self.sendStats(action: "manifest_path_fail", versionName: "\(version):\(fileName)")
2107
+ let error = NSError(
2108
+ domain: "ManifestEntryError",
2109
+ code: 3,
2110
+ userInfo: [
2111
+ NSLocalizedDescriptionKey: "Duplicate manifest target path for \(fileName)"
2112
+ ]
2113
+ )
2114
+ recordInvalidEntry(error, entry.file_name)
2115
+ continue
2116
+ }
2117
+ } catch {
2118
+ logger.error("Invalid manifest file path: \(fileName)")
2119
+ self.sendStats(action: "manifest_path_fail", versionName: "\(version):\(fileName)")
2120
+ recordInvalidEntry(error, entry.file_name)
2121
+ continue
2122
+ }
2123
+
2124
+ tasks.append(
2125
+ ManifestDownloadTask(
2126
+ fileName: fileName,
2127
+ downloadUrl: downloadUrl,
2128
+ finalFileHash: finalFileHash,
2129
+ ciphertextHash: ciphertextHash,
2130
+ isBrotli: isBrotli,
2131
+ destFileName: destFileName,
2132
+ destFilePath: destFilePath,
2133
+ builtinFilePath: builtinFilePath,
2134
+ cacheFilePath: cacheFilePath,
2135
+ legacyCacheFilePath: legacyCacheFilePath
2136
+ )
2137
+ )
2138
+ }
2139
+
2140
+ if hasError.value {
2141
+ let resolvedError = downloadError ?? NSError(
2142
+ domain: "ManifestDownloadError",
2143
+ code: 1,
2144
+ userInfo: [NSLocalizedDescriptionKey: "Manifest download failed due to invalid or missing entries"]
2145
+ )
2146
+ let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
2147
+ self.saveBundleInfo(id: id, bundle: errorBundle)
2148
+ removePartialManifestBundleDirectory(destFolder)
2149
+ reportFailure(resolvedError)
2150
+ throw resolvedError
2151
+ }
2152
+
2153
+ var operations: [Operation] = []
2154
+
2155
+ for task in tasks {
2156
+ do {
2157
+ try FileManager.default.createDirectory(
2158
+ at: task.destFilePath.deletingLastPathComponent(),
2159
+ withIntermediateDirectories: true,
2160
+ attributes: nil
2161
+ )
2162
+ } catch {
2163
+ let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
2164
+ self.saveBundleInfo(id: id, bundle: errorBundle)
2165
+ removePartialManifestBundleDirectory(destFolder)
2166
+ self.notifyDownload(id: id, percent: 0, bundle: errorBundle)
2167
+ recordInvalidEntry(error, task.fileName)
2168
+ reportFailure(error)
2169
+ throw error
2170
+ }
2171
+
2172
+ let operation = BlockOperation { [weak self] in
2173
+ guard let self = self else { return }
2174
+ guard !hasError.value else { return } // Skip if error already occurred
2175
+
2176
+ do {
2177
+ // Try builtin first
2178
+ if self.builtinFileMatches(task.builtinFilePath, expectedHash: task.finalFileHash) {
2179
+ try self.copyItemReplacing(from: task.builtinFilePath, to: task.destFilePath)
2180
+ self.logger.info("downloadManifest \(task.fileName) using builtin file \(id)")
2181
+ }
2182
+ // Try cache
2183
+ else if
2184
+ (task.cacheFilePath != nil &&
2185
+ self.tryCopyFromCache(from: task.cacheFilePath!, to: task.destFilePath, expectedHash: task.finalFileHash)) ||
2186
+ (task.legacyCacheFilePath != nil &&
2187
+ self.tryCopyFromCache(from: task.legacyCacheFilePath!, to: task.destFilePath, expectedHash: task.finalFileHash)) {
2188
+ self.logger.info("downloadManifest \(task.fileName) copy from cache \(id)")
2189
+ }
2190
+ // Download
2191
+ else {
2192
+ try self.downloadManifestFile(task, version: version, bundleId: id, decryptionSession: decryptionSession) {
2193
+ hasError.value
2194
+ }
2195
+ }
2196
+
2197
+ progressLock.lock()
2198
+ completedFiles += 1
2199
+ let percent = self.calcTotalPercent(percent: Int((Double(completedFiles) / Double(totalFiles)) * 100), min: 10, max: 70)
2200
+ if percent > lastProgressPercent {
2201
+ lastProgressPercent = percent
2202
+ self.notifyDownload(id: id, percent: percent, bundle: bundleInfo)
2203
+ }
2204
+ progressLock.unlock()
2205
+
2206
+ } catch {
2207
+ errorLock.lock()
2208
+ failureStage = "process_file"
2209
+ failedFiles += 1
2210
+ if downloadError == nil {
2211
+ downloadError = error
2212
+ firstFile = task.fileName
2213
+ }
2214
+ errorLock.unlock()
2215
+ hasError.value = true
2216
+ self.logger.error("Manifest file download failed: \(task.fileName)")
2217
+ self.logger.debug("Bundle: \(id), File: \(task.fileName), Error: \(error.localizedDescription)")
2218
+ }
2219
+ }
2220
+
2221
+ operations.append(operation)
2222
+ }
2223
+
2224
+ // Execute all operations concurrently and wait for completion
2225
+ manifestDownloadQueue.addOperations(operations, waitUntilFinished: true)
2226
+
2227
+ if hasError.value {
2228
+ let resolvedError = downloadError ?? NSError(
2229
+ domain: "ManifestDownloadError",
2230
+ code: 1,
2231
+ userInfo: [NSLocalizedDescriptionKey: "Manifest download failed due to invalid or missing entries"]
2232
+ )
2233
+ // Update bundle status to ERROR if download failed
2234
+ let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
2235
+ self.saveBundleInfo(id: id, bundle: errorBundle)
2236
+ removePartialManifestBundleDirectory(destFolder)
2237
+ reportFailure(resolvedError)
2238
+ throw resolvedError
2239
+ }
2240
+
2241
+ // Update bundle status to PENDING after successful download
2242
+ let updatedBundle = bundleInfo.setStatus(status: BundleStatus.PENDING.storedValue)
2243
+ self.saveBundleInfo(id: id, bundle: updatedBundle)
2244
+
2245
+ // Send stats for manifest download complete
2246
+ self.sendStats(
2247
+ action: "download_manifest_complete", versionName: version,
2248
+ oldVersionName: "", metadata: ["attempt_id": id]
2249
+ )
2250
+
2251
+ self.notifyDownload(id: id, percent: 100, bundle: updatedBundle)
2252
+ logger.info("downloadManifest done \(id)")
2253
+ return updatedBundle
2254
+ }
2255
+
2256
+ /// Downloads a single manifest file synchronously
2257
+ /// Used by downloadManifest for concurrent file downloads
2258
+ private func downloadManifestFile(
2259
+ _ task: ManifestDownloadTask, version: String, bundleId: String, decryptionSession: CryptoCipher.DecryptionSession,
2260
+ shouldStop: () -> Bool
2261
+ ) throws {
2262
+ let resume = ManifestResumeState()
2263
+ for attempt in 1...3 {
2264
+ do {
2265
+ try downloadManifestFileOnce(task, version: version, bundleId: bundleId, decryptionSession: decryptionSession, resume: resume)
2266
+ return
2267
+ } catch {
2268
+ guard attempt < 3 && Self.isRetryableManifestError(error) else {
2269
+ throw error
2270
+ }
2271
+ // Back off in short steps so a failed or cancelled manifest stops retrying promptly.
2272
+ for _ in 0..<(5 * attempt) {
2273
+ if shouldStop() { throw error }
2274
+ Thread.sleep(forTimeInterval: 0.05)
2275
+ }
2276
+ }
2277
+ }
2278
+ }
2279
+
2280
+ /// Transport errors arrive wrapped in NetworkError.sessionTaskFailed; classify the underlying error.
2281
+ static func manifestFailureCause(_ error: Error) -> NSError {
2282
+ if case let .sessionTaskFailed(underlying)? = error as? NetworkError {
2283
+ return manifestFailureCause(underlying)
2284
+ }
2285
+ return error as NSError
2286
+ }
2287
+
2288
+ static func isRetryableManifestError(_ error: Error) -> Bool {
2289
+ let failure = manifestFailureCause(error)
2290
+ if failure.domain == manifestResumeErrorDomain {
2291
+ return true
2292
+ }
2293
+ if failure.domain == "StatusCodeError" {
2294
+ return failure.code == 408 || (500...599).contains(failure.code)
2295
+ }
2296
+ return failure.domain == NSURLErrorDomain && [
2297
+ NSURLErrorTimedOut, NSURLErrorNetworkConnectionLost, NSURLErrorNotConnectedToInternet,
2298
+ NSURLErrorCannotConnectToHost, NSURLErrorCannotFindHost, NSURLErrorDNSLookupFailed
2299
+ ].contains(failure.code)
2300
+ }
2301
+
2302
+ /// A resumed transfer that cannot be trusted: drop the partial and fetch the whole file on the next attempt.
2303
+ static let manifestResumeErrorDomain = "ManifestResumeError"
2304
+
2305
+ private func downloadManifestFileOnce(
2306
+ _ task: ManifestDownloadTask, version: String, bundleId: String, decryptionSession: CryptoCipher.DecryptionSession,
2307
+ resume: ManifestResumeState
2308
+ ) throws {
2309
+ let downloadUrl = task.downloadUrl
2310
+ let destFilePath = task.destFilePath
2311
+ let cacheFilePath = task.cacheFilePath
2312
+ let fileHash = task.finalFileHash
2313
+ let fileName = task.fileName
2314
+ let destFileName = task.destFileName
2315
+ let isBrotli = task.isBrotli
2316
+ guard let url = URL(string: downloadUrl) else {
2317
+ throw NSError(
2318
+ domain: "ManifestDownloadError",
2319
+ code: 1,
2320
+ userInfo: [NSLocalizedDescriptionKey: "Invalid manifest download URL for file \(fileName): \(downloadUrl)"]
2321
+ )
2322
+ }
2323
+
2324
+ guard var request = createRequest(url: url, method: "GET") else {
2325
+ throw NSError(
2326
+ domain: "ManifestDownloadError",
2327
+ code: 2,
2328
+ userInfo: [NSLocalizedDescriptionKey: "Invalid manifest request for file \(fileName): \(downloadUrl)"]
2329
+ )
2330
+ }
2331
+
2332
+ try FileManager.default.createDirectory(at: cacheFolder, withIntermediateDirectories: true, attributes: nil)
2333
+ let partialURL = Self.manifestPartialURL(cacheFolder: cacheFolder, downloadId: bundleId, hash: fileHash, fileName: fileName)
2334
+ let resumeData = resume.data
2335
+ resume.data = nil
2336
+ if resumeData != nil {
2337
+ // URLSession resumes its own interrupted transfer and returns the whole file.
2338
+ try? FileManager.default.removeItem(at: partialURL)
2339
+ }
2340
+ let existingBytes: Int64
2341
+ if FileManager.default.fileExists(atPath: partialURL.path) {
2342
+ existingBytes = Int64((try FileManager.default.attributesOfItem(atPath: partialURL.path)[.size] as? NSNumber)?.int64Value ?? 0)
2343
+ } else {
2344
+ existingBytes = 0
2345
+ }
2346
+ if existingBytes > 0 {
2347
+ request.setValue("bytes=\(existingBytes)-", forHTTPHeaderField: "Range")
2348
+ }
2349
+ // True while the bytes on disk come from more than one response; a bad result then earns a clean GET.
2350
+ var resumed = resumeData != nil
2351
+
2352
+ let label = "downloadManifestFile \(fileName)"
2353
+ let result = resumeData.map { performDownloadRequest(request, label: label, resumeData: $0) }
2354
+ ?? performDownloadRequest(request, label: label)
2355
+ resume.data = result.resumeData
2356
+ defer {
2357
+ if let fileURL = result.fileURL {
2358
+ try? FileManager.default.removeItem(at: fileURL)
2359
+ }
2360
+ }
2361
+
2362
+ if result.timedOut {
2363
+ persistPartialDownload(result, id: bundleId, tempPath: partialURL, existingBytes: existingBytes)
2364
+ throw NSError(
2365
+ domain: NSURLErrorDomain,
2366
+ code: NSURLErrorTimedOut,
2367
+ userInfo: [NSLocalizedDescriptionKey: "Timed out downloading manifest file \(fileName) at url \(downloadUrl)"]
2368
+ )
2369
+ }
2370
+
2371
+ if let error = result.error {
2372
+ persistPartialDownload(result, id: bundleId, tempPath: partialURL, existingBytes: existingBytes)
2373
+ self.logger.error("Manifest file download network error")
2374
+ self.logger.debug("Bundle: \(bundleId), File: \(fileName), Error: \(error.localizedDescription)")
2375
+ throw error
2376
+ }
2377
+
2378
+ let statusCode = result.response?.statusCode ?? 200
2379
+ var storeOffset = existingBytes
2380
+ if statusCode == 206 && existingBytes > 0 {
2381
+ switch Self.contentRangeStart(result.response?.value(forHTTPHeaderField: "Content-Range")) {
2382
+ case .some(existingBytes):
2383
+ resumed = true
2384
+ case .some(0):
2385
+ storeOffset = 0
2386
+ default:
2387
+ try? FileManager.default.removeItem(at: partialURL)
2388
+ throw NSError(
2389
+ domain: Self.manifestResumeErrorDomain,
2390
+ code: 1,
2391
+ userInfo: [NSLocalizedDescriptionKey: "Content-Range does not continue the partial for \(fileName)"]
2392
+ )
2393
+ }
2394
+ }
2395
+ if statusCode == 416 && existingBytes > 0 {
2396
+ logger.debug("Range not satisfiable, using existing partial \(partialURL.lastPathComponent)")
2397
+ resumed = true
2398
+ } else if statusCode < 200 || statusCode >= 300 {
2399
+ throw NSError(domain: "StatusCodeError", code: statusCode, userInfo: [NSLocalizedDescriptionKey: "Failed to fetch. Status code (\(statusCode)) invalid for file \(fileName) at url \(downloadUrl)"])
2400
+ } else {
2401
+ guard let downloadedFileURL = result.fileURL, FileManager.default.fileExists(atPath: downloadedFileURL.path) else {
2402
+ throw NSError(
2403
+ domain: "ManifestDownloadError",
2404
+ code: 3,
2405
+ userInfo: [NSLocalizedDescriptionKey: "Manifest file response was empty for \(fileName) at url \(downloadUrl)"]
2406
+ )
2407
+ }
2408
+ try storeDownloadedFile(downloadedFileURL, at: partialURL, existingBytes: storeOffset, response: result.response)
2409
+ }
2410
+
2411
+ guard FileManager.default.fileExists(atPath: partialURL.path) else {
2412
+ throw NSError(
2413
+ domain: "ManifestDownloadError",
2414
+ code: 3,
2415
+ userInfo: [NSLocalizedDescriptionKey: "Manifest file response was empty for \(fileName) at url \(downloadUrl)"]
2416
+ )
2417
+ }
2418
+
2419
+ var workURL: URL?
2420
+ defer {
2421
+ if let workURL {
2422
+ try? FileManager.default.removeItem(at: workURL)
2423
+ }
2424
+ }
2425
+
2426
+ do {
2427
+ var source = partialURL
2428
+ if decryptionSession.isEncrypted {
2429
+ let work = cacheFolder.appendingPathComponent("work_\(UUID().uuidString)_\((fileName as NSString).lastPathComponent)")
2430
+ try FileManager.default.copyItem(at: partialURL, to: work)
2431
+ workURL = work
2432
+ do {
2433
+ try decryptionSession.decryptFile(filePath: work, expectedCiphertextSha256: task.ciphertextHash)
2434
+ } catch {
2435
+ try? FileManager.default.removeItem(at: partialURL)
2436
+ if resumed { throw Self.resumeVerificationError(error, fileName: fileName) }
2437
+ if case CryptoCipher.CiphertextChecksumError.mismatch = error {
2438
+ self.sendStats(action: "download_manifest_checksum_fail", versionName: "\(version):\(destFileName)")
2439
+ } else {
2440
+ self.sendStats(action: "decrypt_fail", versionName: version)
2441
+ }
2442
+ throw error
2443
+ }
2444
+ source = work
2445
+ }
2446
+
2447
+ let calculatedChecksum: String
2448
+ if isBrotli {
2449
+ do {
2450
+ calculatedChecksum = try decompressBrotli(from: source, to: destFilePath, fileName: fileName)
2451
+ } catch {
2452
+ try? FileManager.default.removeItem(at: partialURL)
2453
+ if resumed { throw Self.resumeVerificationError(error, fileName: fileName) }
2454
+ self.sendStats(action: "download_manifest_brotli_fail", versionName: "\(version):\(destFileName)")
2455
+ throw error
2456
+ }
2457
+ } else {
2458
+ let handle = try FileHandle(forReadingFrom: source)
2459
+ defer { try? handle.close() }
2460
+ let length = (try FileManager.default.attributesOfItem(atPath: source.path)[.size] as? NSNumber)?.uint64Value ?? 0
2461
+ calculatedChecksum = try streamCopy(from: handle, count: length, to: destFilePath)
2462
+ }
2463
+
2464
+ CryptoCipher.logChecksumInfo(label: "Calculated checksum", hexChecksum: calculatedChecksum)
2465
+ CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: fileHash)
2466
+ if calculatedChecksum != fileHash {
2467
+ try? FileManager.default.removeItem(at: destFilePath)
2468
+ try? FileManager.default.removeItem(at: partialURL)
2469
+ let mismatch = NSError(domain: "ChecksumError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Computed checksum is not equal to required checksum (\(calculatedChecksum) != \(fileHash)) for file \(fileName) at url \(downloadUrl)"])
2470
+ if resumed { throw Self.resumeVerificationError(mismatch, fileName: fileName) }
2471
+ self.sendStats(action: "download_manifest_checksum_fail", versionName: "\(version):\(destFileName)")
2472
+ throw mismatch
2473
+ }
2474
+
2475
+ if let cacheFilePath {
2476
+ do {
2477
+ try linkOrCopyImmutableFile(from: destFilePath, to: cacheFilePath)
2478
+ } catch {
2479
+ logger.debug("Delta cache write failed: \(error.localizedDescription)")
2480
+ }
2481
+ }
2482
+ try? FileManager.default.removeItem(at: partialURL)
2483
+
2484
+ self.logger.info("Manifest file downloaded and cached")
2485
+ self.logger.debug("Bundle: \(bundleId), File: \(fileName), Brotli: \(isBrotli), Encrypted: \(decryptionSession.isEncrypted)")
2486
+ } catch {
2487
+ self.logger.error("Manifest file download failed")
2488
+ self.logger.debug("Bundle: \(bundleId), File: \(fileName), Error: \(error.localizedDescription)")
2489
+ throw error
2490
+ }
2491
+ }
2492
+
2493
+ /// Bad bytes after a resume earn a clean GET; local storage errors are not wrapped and stay permanent.
2494
+ private static func resumeVerificationError(_ underlying: Error, fileName: String) -> NSError {
2495
+ NSError(
2496
+ domain: manifestResumeErrorDomain,
2497
+ code: 2,
2498
+ userInfo: [NSLocalizedDescriptionKey: "Resumed transfer failed verification for \(fileName)", NSUnderlyingErrorKey: underlying]
2499
+ )
2500
+ }
2501
+
2502
+ /// Start offset of a `bytes start-end/total` Content-Range header, or nil when absent or malformed.
2503
+ static func contentRangeStart(_ header: String?) -> Int64? {
2504
+ guard let header, header.hasPrefix("bytes ") else {
2505
+ return nil
2506
+ }
2507
+ let range = header.dropFirst("bytes ".count)
2508
+ guard let dash = range.firstIndex(of: "-") else {
2509
+ return nil
2510
+ }
2511
+ return Int64(range[range.startIndex..<dash].trimmingCharacters(in: .whitespaces))
2512
+ }
2513
+
2514
+ /// Copy a file to the destination, replacing any existing file.
2515
+ private func copyItemReplacing(from source: URL, to destination: URL) throws {
2516
+ let fileManager = FileManager.default
2517
+ try fileManager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)
2518
+ if fileManager.fileExists(atPath: destination.path) {
2519
+ try fileManager.removeItem(at: destination)
2520
+ }
2521
+ try fileManager.copyItem(at: source, to: destination)
2522
+ }
2523
+
2524
+ func copyMatchingBuiltinFilesForTests(files: [(source: URL, dest: URL, hash: String)]) throws {
2525
+ let queue = OperationQueue()
2526
+ queue.maxConcurrentOperationCount = CapgoUpdater.manifestMaxConcurrentFiles
2527
+ let lock = NSLock()
2528
+ var firstError: Error?
2529
+ for file in files {
2530
+ queue.addOperation { [weak self] in
2531
+ guard let self else { return }
2532
+ do {
2533
+ guard self.verifyChecksum(file: file.source, expectedHash: file.hash) else {
2534
+ throw NSError(
2535
+ domain: "CapgoInstallPerf",
2536
+ code: 1,
2537
+ userInfo: [NSLocalizedDescriptionKey: "builtin checksum mismatch"]
2538
+ )
2539
+ }
2540
+ try self.copyItemReplacing(from: file.source, to: file.dest)
2541
+ } catch {
2542
+ lock.lock()
2543
+ if firstError == nil {
2544
+ firstError = error
2545
+ }
2546
+ lock.unlock()
2547
+ }
2548
+ }
2549
+ }
2550
+ queue.waitUntilAllOperationsAreFinished()
2551
+ if let firstError {
2552
+ throw firstError
2553
+ }
2554
+ }
2555
+
2556
+ /// Copy via a unique temp name then rename, so a crash cannot leave a
2557
+ /// non-empty partial file that `isReusableCacheFile` would trust.
2558
+ private func copyItemAtomically(from source: URL, to destination: URL) throws {
2559
+ let fileManager = FileManager.default
2560
+ try fileManager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)
2561
+ let tempURL = destination.deletingLastPathComponent().appendingPathComponent("\(destination.lastPathComponent).\(UUID().uuidString).tmp")
2562
+ defer {
2563
+ try? fileManager.removeItem(at: tempURL)
2564
+ }
2565
+ try fileManager.copyItem(at: source, to: tempURL)
2566
+ try replaceItemAtomically(at: destination, withItemAt: tempURL)
2567
+ }
2568
+
2569
+ /// Only updater-owned verified bundle/cache files, which are never rewritten in place.
2570
+ func linkOrCopyImmutableFile(from source: URL, to destination: URL) throws {
2571
+ let manager = FileManager.default
2572
+ try manager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
2573
+ let temp = destination.deletingLastPathComponent().appendingPathComponent("capgo-link-\(UUID().uuidString).tmp")
2574
+ defer { try? manager.removeItem(at: temp) }
2575
+ do {
2576
+ try manager.linkItem(at: source.resolvingSymlinksInPath(), to: temp)
2577
+ } catch {
2578
+ try copyItemAtomically(from: source.resolvingSymlinksInPath(), to: destination)
2579
+ return
2580
+ }
2581
+ try replaceItemAtomically(at: destination, withItemAt: temp)
2582
+ }
2583
+
2584
+ /// One-step replace when dest exists, move when it does not. Avoids the
2585
+ /// fileExists/removeItem race that can fail a verified install.
2586
+ private func replaceItemAtomically(at destination: URL, withItemAt tempURL: URL) throws {
2587
+ let fileManager = FileManager.default
2588
+ do {
2589
+ _ = try fileManager.replaceItemAt(destination, withItemAt: tempURL)
2590
+ } catch {
2591
+ if fileManager.fileExists(atPath: destination.path) {
2592
+ throw error
2593
+ }
2594
+ try fileManager.moveItem(at: tempURL, to: destination)
2595
+ }
2596
+ }
2597
+
2598
+ private func removeFileIfPresent(at url: URL) {
2599
+ let fileManager = FileManager.default
2600
+ guard fileManager.fileExists(atPath: url.path) else {
2601
+ return
2602
+ }
2603
+ try? fileManager.removeItem(at: url)
2604
+ }
2605
+
2606
+ /// Atomically try to copy a file from cache - returns true if successful, false if file doesn't exist or copy failed
2607
+ /// This handles the race condition where OS can delete cache files between exists() check and copy
2608
+ private func tryCopyFromCache(from source: URL, to destination: URL, expectedHash: String) -> Bool {
2609
+ // First quick check - if file doesn't exist or was truncated, don't bother
2610
+ guard isReusableCacheFile(source, expectedHash: expectedHash) else {
2611
+ return false
2612
+ }
2613
+
2614
+ // Hash is in the cache file name and was verified when written.
2615
+ // Re-hashing here would re-read every reused file on low-RAM devices.
2616
+ do {
2617
+ try linkOrCopyImmutableFile(from: source, to: destination)
2618
+ return true
2619
+ } catch {
2620
+ // File was deleted between check and copy, or other IO error - caller should download instead
2621
+ logger.debug("Cache copy failed (likely OS eviction): \(error.localizedDescription)")
2622
+ return false
2623
+ }
2624
+ }
2625
+
2626
+ /// Stream Brotli from disk to disk. Peek only the 3-byte header and last byte
2627
+ /// for the empty/wrapper special cases; never load the whole file.
2628
+ func decompressBrotli(from source: URL, to dest: URL, fileName: String) throws -> String {
2629
+ let fileManager = FileManager.default
2630
+ try fileManager.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)
2631
+ let length = (try fileManager.attributesOfItem(atPath: source.path)[.size] as? NSNumber)?.uint64Value ?? 0
2632
+ if length == 0 {
2633
+ try Data().write(to: dest, options: .atomic)
2634
+ return CryptoCipher.RunningChecksum().hex()
2635
+ }
2636
+
2637
+ let handle = try FileHandle(forReadingFrom: source)
2638
+ defer {
2639
+ try? handle.close()
2640
+ }
2641
+
2642
+ let head = try handle.read(upToCount: 3) ?? Data()
2643
+ var last: UInt8 = 0
2644
+ if length >= 1 {
2645
+ try handle.seek(toOffset: length - 1)
2646
+ last = try handle.read(upToCount: 1)?.first ?? 0
2647
+ }
2648
+
2649
+ if length == 3 && head.count == 3 && head[0] == 0x1B && head[1] == 0x00 && head[2] == 0x06 {
2650
+ try Data().write(to: dest, options: .atomic)
2651
+ return CryptoCipher.RunningChecksum().hex()
2652
+ }
2653
+
2654
+ if length > 3 && head.count == 3 && last == 0x03 {
2655
+ let isEmptyWrapper = head[0] == 0x1B && head[1] == 0x00 && head[2] == 0x06
2656
+ let isQualityZeroWrapper = head[0] == 0x0b && head[1] == 0x02 && head[2] == 0x80
2657
+ if isEmptyWrapper || isQualityZeroWrapper {
2658
+ try handle.seek(toOffset: 3)
2659
+ return try streamCopy(from: handle, count: length - 4, to: dest)
2660
+ }
2661
+ }
2662
+
2663
+ try handle.seek(toOffset: 0)
2664
+ return try streamBrotliDecode(from: handle, to: dest, fileName: fileName)
2665
+ }
2666
+
2667
+ func streamCopy(from handle: FileHandle, count: UInt64, to dest: URL) throws -> String {
2668
+ let fileManager = FileManager.default
2669
+ let tempURL = dest.deletingLastPathComponent().appendingPathComponent("capgo-br-\(UUID().uuidString).tmp")
2670
+ fileManager.createFile(atPath: tempURL.path, contents: nil)
2671
+ let output = try FileHandle(forWritingTo: tempURL)
2672
+ defer {
2673
+ try? output.close()
2674
+ try? fileManager.removeItem(at: tempURL)
2675
+ }
2676
+
2677
+ let hasher = CryptoCipher.RunningChecksum()
2678
+ var remaining = count
2679
+ let chunkSize = CryptoCipher.ioBufferBytes()
2680
+ while remaining > 0 {
2681
+ let readCount: Int = try autoreleasepool {
2682
+ let toRead = Int(min(UInt64(chunkSize), remaining))
2683
+ let chunk = try handle.read(upToCount: toRead) ?? Data()
2684
+ if !chunk.isEmpty {
2685
+ hasher.update(chunk)
2686
+ try output.write(contentsOf: chunk)
2687
+ }
2688
+ return chunk.count
2689
+ }
2690
+ if readCount == 0 {
2691
+ break
2692
+ }
2693
+ remaining -= UInt64(readCount)
2694
+ }
2695
+ try output.close()
2696
+ try replaceItemAtomically(at: dest, withItemAt: tempURL)
2697
+ return hasher.hex()
2698
+ }
2699
+
2700
+ private func streamBrotliDecode(from handle: FileHandle, to dest: URL, fileName: String) throws -> String {
2701
+ let fileManager = FileManager.default
2702
+ let tempURL = dest.deletingLastPathComponent().appendingPathComponent("capgo-br-\(UUID().uuidString).tmp")
2703
+ fileManager.createFile(atPath: tempURL.path, contents: nil)
2704
+ let output = try FileHandle(forWritingTo: tempURL)
2705
+ defer {
2706
+ try? output.close()
2707
+ try? fileManager.removeItem(at: tempURL)
2708
+ }
2709
+ let hasher = CryptoCipher.RunningChecksum()
2710
+
2711
+ let chunkSize = max(CryptoCipher.ioBufferBytes(), 65536)
2712
+ var inputBuffer = [UInt8](repeating: 0, count: chunkSize)
2713
+ var outputBuffer = [UInt8](repeating: 0, count: chunkSize)
2714
+
2715
+ let streamPointer = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
2716
+ var status = compression_stream_init(streamPointer, COMPRESSION_STREAM_DECODE, COMPRESSION_BROTLI)
2717
+ guard status != COMPRESSION_STATUS_ERROR else {
2718
+ logger.error("Failed to initialize Brotli stream")
2719
+ logger.debug("File: \(fileName), Status: \(status)")
2720
+ throw NSError(domain: "BrotliDecompressionError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to initialize Brotli stream for \(fileName)"])
2721
+ }
2722
+ defer {
2723
+ compression_stream_destroy(streamPointer)
2724
+ streamPointer.deallocate()
2725
+ }
2726
+
2727
+ try inputBuffer.withUnsafeMutableBufferPointer { inBuf in
2728
+ try outputBuffer.withUnsafeMutableBufferPointer { outBuf in
2729
+ guard let inBase = inBuf.baseAddress, let outBase = outBuf.baseAddress else {
2730
+ throw NSError(domain: "BrotliDecompressionError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to get buffer address for \(fileName)"])
2731
+ }
2732
+ streamPointer.pointee.src_size = 0
2733
+ streamPointer.pointee.dst_ptr = outBase
2734
+ streamPointer.pointee.dst_size = chunkSize
2735
+
2736
+ var flags: Int32 = 0
2737
+ var inputExhausted = false
2738
+ while true {
2739
+ if streamPointer.pointee.src_size == 0 && !inputExhausted {
2740
+ let chunk = try handle.read(upToCount: chunkSize) ?? Data()
2741
+ if chunk.isEmpty {
2742
+ inputExhausted = true
2743
+ flags = Int32(bitPattern: COMPRESSION_STREAM_FINALIZE.rawValue)
2744
+ } else {
2745
+ chunk.copyBytes(to: inBase, count: chunk.count)
2746
+ streamPointer.pointee.src_ptr = UnsafePointer(inBase)
2747
+ streamPointer.pointee.src_size = chunk.count
2748
+ }
2749
+ }
2750
+
2751
+ status = compression_stream_process(streamPointer, flags)
2752
+ let have = chunkSize - streamPointer.pointee.dst_size
2753
+ if have > 0 {
2754
+ let decoded = Data(bytes: outBase, count: have)
2755
+ hasher.update(decoded)
2756
+ try output.write(contentsOf: decoded)
2757
+ }
2758
+ streamPointer.pointee.dst_ptr = outBase
2759
+ streamPointer.pointee.dst_size = chunkSize
2760
+
2761
+ if status == COMPRESSION_STATUS_END {
2762
+ break
2763
+ }
2764
+ if status == COMPRESSION_STATUS_ERROR {
2765
+ logger.error("Brotli process failed")
2766
+ logger.debug("File: \(fileName), Status: \(status)")
2767
+ throw NSError(domain: "BrotliDecompressionError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to decompress Brotli data for file \(fileName)"])
2768
+ }
2769
+ if inputExhausted && streamPointer.pointee.src_size == 0 && have == 0 {
2770
+ logger.error("Brotli decompression stalled")
2771
+ logger.debug("File: \(fileName)")
2772
+ throw NSError(domain: "BrotliDecompressionError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to decompress Brotli data for file \(fileName)"])
2773
+ }
2774
+ }
2775
+ }
2776
+ }
2777
+
2778
+ try output.close()
2779
+ try replaceItemAtomically(at: dest, withItemAt: tempURL)
2780
+ return hasher.hex()
2781
+ }
2782
+
2783
+ /// Resolves the checksums a zip bundle must match: required, and RSA-decrypted when a public key is set
2784
+ /// (`ciphertext` is then the signed SHA-256 of the encrypted zip, checked before decrypting).
2785
+ func resolveExpectedBundleChecksum(_ checksum: String, versionName: String) throws -> CryptoCipher.BundleChecksum {
2786
+ if checksum.isEmpty {
2787
+ logger.error("No checksum provided")
2788
+ self.sendStats(action: "checksum_required", versionName: versionName)
2789
+ throw NSError(domain: "ChecksumError", code: 2, userInfo: [NSLocalizedDescriptionKey: "Checksum required"])
2790
+ }
2791
+ return try CryptoCipher.decryptBundleChecksum(checksum: checksum, publicKey: self.publicKey)
2792
+ }
2793
+
2794
+ /// Downloads and extracts a zip bundle without checking its checksum; the caller must verify it.
2795
+ /// Encrypted bundles always fail here: decrypting needs the signed ciphertext checksum (`downloadVerified`).
2796
+ /// Prefer `downloadVerified`, which rejects a bad archive before extracting it.
2797
+ public func download(url: URL, version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
2798
+ return try self.downloadZip(url: url, version: version, sessionKey: sessionKey, link: link, comment: comment, expectedChecksum: nil)
2799
+ }
2800
+
2801
+ /// Downloads a zip bundle and extracts it only when it matches `expectedChecksum`, the checksum from the
2802
+ /// update response (required, RSA-decrypted when a public key is set). The SHA-256 of the downloaded and
2803
+ /// decrypted archive is compared before anything is extracted: a mismatch deletes the archive, reports
2804
+ /// `checksum_fail` and throws `ObjectSavableError.checksum`.
2805
+ public func downloadVerified(
2806
+ url: URL,
2807
+ version: String,
2808
+ sessionKey: String,
2809
+ expectedChecksum: String,
2810
+ link: String? = nil,
2811
+ comment: String? = nil
2812
+ ) throws -> BundleInfo {
2813
+ return try self.downloadZip(url: url, version: version, sessionKey: sessionKey, link: link, comment: comment, expectedChecksum: expectedChecksum)
2814
+ }
2815
+
2816
+ /// Downloads, verifies, and extracts a zip bundle while emitting progress from 0% to 100%.
2817
+ private func downloadZip(
2818
+ url: URL,
2819
+ version: String,
2820
+ sessionKey: String,
2821
+ link: String?,
2822
+ comment: String?,
2823
+ expectedChecksum: String?
2824
+ ) throws -> BundleInfo {
2825
+ try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
2826
+ try self.requireVersionNotBelowBuiltin(version)
2827
+ try self.assertAllowedScheme(url)
2828
+ let expectedChecksums = try expectedChecksum.map { try self.resolveExpectedBundleChecksum($0, versionName: version) }
2829
+ let expectedHash = expectedChecksums?.plain
2830
+ try self.runBeforeDownload()
2831
+ let id: String = self.randomString(length: 10)
2832
+ // Each download uses its own temp files keyed by bundle ID to prevent collisions
2833
+ if version != getLocalUpdateVersion(for: id) {
2834
+ cleanDownloadData(for: id)
2835
+ }
2836
+ ensureResumableFilesExist(for: id)
2837
+ saveDownloadInfo(version, for: id)
2838
+
2839
+ // Check disk space before starting download (matches Android behavior)
2840
+ try checkDiskSpace()
2841
+
2842
+ var checksum = ""
2843
+ var lastSentProgress = 0
2844
+ let totalReceivedBytes: Int64 = loadDownloadProgress(for: id) // Retrieving the amount of already downloaded data if exist, defined at 0 otherwise
2845
+ let tempPath = tempDataPath(for: id)
2846
+ let bundleInfo = BundleInfo(id: id, version: version, status: BundleStatus.DOWNLOADING, downloaded: Date(), checksum: checksum, link: link, comment: comment)
2847
+ self.saveBundleInfo(id: id, bundle: bundleInfo)
2848
+
2849
+ // Send stats for zip download start
2850
+ self.sendStats(
2851
+ action: "download_zip_start", versionName: version,
2852
+ oldVersionName: "", metadata: ["attempt_id": id]
2853
+ )
2854
+
2855
+ // Opening connection for streaming the bytes
2856
+ if totalReceivedBytes == 0 {
2857
+ self.notifyDownload(id: id, percent: 0, ignoreMultipleOfTen: true)
2858
+ }
2859
+ var mainError: NSError?
2860
+
2861
+ guard var request = createRequest(url: url, method: "GET") else {
2862
+ self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
2863
+ throw NSError(
2864
+ domain: "DownloadError",
2865
+ code: 2,
2866
+ userInfo: [NSLocalizedDescriptionKey: "Invalid download request for \(url.absoluteString)"]
2867
+ )
2868
+ }
2869
+
2870
+ if totalReceivedBytes > 0 {
2871
+ request.setValue("bytes=\(totalReceivedBytes)-", forHTTPHeaderField: "Range")
2872
+ }
2873
+
2874
+ let progressLock = NSLock()
2875
+ let downloadResult = performDownloadRequest(request, label: "download \(version)") { [weak self] totalReceived, totalExpected in
2876
+ guard let self, totalExpected > 0 else { return }
2877
+ let rawPercent = Int((Double(totalReceived) / Double(totalExpected)) * 100)
2878
+ let scaledPercent = self.calcTotalPercent(percent: min(100, max(0, rawPercent)), min: 10, max: 70)
2879
+ progressLock.lock()
2880
+ if scaledPercent > lastSentProgress && scaledPercent < 70 {
2881
+ lastSentProgress = scaledPercent
2882
+ self.notifyDownload(id: id, percent: scaledPercent, bundle: bundleInfo)
2883
+ }
2884
+ progressLock.unlock()
2885
+ }
2886
+ // Error responses (e.g. an HTTP 404 body) are also saved to a temp file; never leave them behind.
2887
+ defer {
2888
+ if let fileURL = downloadResult.fileURL {
2889
+ try? FileManager.default.removeItem(at: fileURL)
2890
+ }
2891
+ }
2892
+
2893
+ if downloadResult.timedOut {
2894
+ persistPartialDownload(downloadResult, id: id, tempPath: tempPath, existingBytes: totalReceivedBytes)
2895
+ mainError = NSError(
2896
+ domain: NSURLErrorDomain,
2897
+ code: NSURLErrorTimedOut,
2898
+ userInfo: [NSLocalizedDescriptionKey: "Timed out downloading bundle from \(url.absoluteString)"]
2899
+ )
2900
+ } else if let error = downloadResult.error {
2901
+ logger.error("Download failed")
2902
+ persistPartialDownload(downloadResult, id: id, tempPath: tempPath, existingBytes: totalReceivedBytes)
2903
+ mainError = error as NSError
2904
+ } else if let statusCode = downloadResult.response?.statusCode, statusCode < 200 || statusCode >= 300 {
2905
+ logger.error("Download failed")
2906
+ mainError = NSError(
2907
+ domain: "DownloadError",
2908
+ code: statusCode,
2909
+ userInfo: [NSLocalizedDescriptionKey: "Download request failed with status code \(statusCode)"]
2910
+ )
2911
+ } else if let downloadedFileURL = downloadResult.fileURL {
2912
+ do {
2913
+ try storeDownloadedFile(downloadedFileURL, at: tempPath, existingBytes: totalReceivedBytes, response: downloadResult.response)
2914
+
2915
+ progressLock.lock()
2916
+ if lastSentProgress < 70 {
2917
+ lastSentProgress = 70
2918
+ self.notifyDownload(id: id, percent: 70, ignoreMultipleOfTen: true)
2919
+ }
2920
+ progressLock.unlock()
2921
+ self.logger.info("Download complete")
2922
+ } catch let error as NSError {
2923
+ mainError = error
2924
+ } catch {
2925
+ mainError = error as NSError
2926
+ }
2927
+ } else {
2928
+ mainError = NSError(
2929
+ domain: "DownloadError",
2930
+ code: 1,
2931
+ userInfo: [NSLocalizedDescriptionKey: "Downloaded file is missing at \(tempPath.path)"]
2932
+ )
2933
+ }
2934
+
2935
+ if mainError != nil {
2936
+ logger.error("Failed to download bundle")
2937
+ logger.debug("Error: \(String(describing: mainError))")
2938
+ self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
2939
+ throw mainError!
2940
+ }
2941
+
2942
+ let finalPath = tempPath.deletingLastPathComponent().appendingPathComponent("\(id)")
2943
+ do {
2944
+ // The encrypted zip is hashed and checked against the signed digest before decrypting.
2945
+ try CryptoCipher.decryptFile(
2946
+ filePath: tempPath,
2947
+ publicKey: self.publicKey,
2948
+ sessionKey: sessionKey,
2949
+ version: version,
2950
+ expectedCiphertextSha256: expectedChecksums?.ciphertext
2951
+ )
2952
+ try FileManager.default.moveItem(at: tempPath, to: finalPath)
2953
+ } catch {
2954
+ if case CryptoCipher.CiphertextChecksumError.mismatch = error {
2955
+ self.sendStats(action: "checksum_fail", versionName: version)
2956
+ }
2957
+ logger.error("Failed to decrypt file")
2958
+ logger.debug("Error: \(error)")
2959
+ self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
2960
+ cleanDownloadData(for: id)
2961
+ throw error
2962
+ }
2963
+
2964
+ checksum = CryptoCipher.calcChecksum(filePath: finalPath)
2965
+ CryptoCipher.logChecksumInfo(label: "Calculated bundle checksum", hexChecksum: checksum)
2966
+ if let expectedHash, checksum.isEmpty || checksum != expectedHash {
2967
+ // Never extract an archive that failed verification.
2968
+ logger.error("Checksum mismatch, bundle rejected before extraction")
2969
+ CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: expectedHash)
2970
+ self.sendStats(action: "checksum_fail", versionName: version)
2971
+ try? FileManager.default.removeItem(at: finalPath)
2972
+ self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
2973
+ cleanDownloadData(for: id)
2974
+ // Drop it like the previous post-extraction check did, so the next update check downloads it again.
2975
+ _ = self.delete(id: id)
2976
+ throw ObjectSavableError.checksum
2977
+ }
2978
+
2979
+ do {
2980
+ logger.info("Downloading: 80% (unzipping)")
2981
+ try self.saveDownloaded(sourceZip: finalPath, id: id, base: self.libraryDir.appendingPathComponent(self.bundleDirectory), notify: true)
2982
+ self.populateDeltaCacheAsync(for: id)
2983
+
2984
+ } catch {
2985
+ logger.error("Failed to unzip file")
2986
+ logger.debug("Error: \(error)")
2987
+ self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
2988
+ // Best-effort cleanup of the decrypted zip file when unzip fails
2989
+ do {
2990
+ if FileManager.default.fileExists(atPath: finalPath.path) {
2991
+ try FileManager.default.removeItem(at: finalPath)
2992
+ }
2993
+ } catch {
2994
+ logger.error("Could not delete failed zip")
2995
+ logger.debug("Path: \(finalPath.path), Error: \(error)")
2996
+ }
2997
+ cleanDownloadData(for: id)
2998
+ throw error
2999
+ }
3000
+
3001
+ self.notifyDownload(id: id, percent: 90)
3002
+ logger.info("Downloading: 90% (wrapping up)")
3003
+ let info = BundleInfo(id: id, version: version, status: BundleStatus.PENDING, downloaded: Date(), checksum: checksum, link: link, comment: comment)
3004
+ self.saveBundleInfo(id: id, bundle: info)
3005
+ self.cleanDownloadData(for: id)
3006
+
3007
+ // Send stats for zip download complete
3008
+ self.sendStats(
3009
+ action: "download_zip_complete", versionName: version,
3010
+ oldVersionName: "", metadata: ["attempt_id": id]
3011
+ )
3012
+
3013
+ self.notifyDownload(id: id, percent: 100, bundle: info)
3014
+ logger.info("Downloading: 100% (complete)")
3015
+ return info
3016
+ }
3017
+ private func ensureResumableFilesExist(for id: String) {
3018
+ let fileManager = FileManager.default
3019
+ let tempPath = tempDataPath(for: id)
3020
+ let infoPath = updateInfoPath(for: id)
3021
+ if !fileManager.fileExists(atPath: tempPath.path) {
3022
+ if !fileManager.createFile(atPath: tempPath.path, contents: Data()) {
3023
+ logger.error("Cannot ensure temp data file exists")
3024
+ logger.debug("Path: \(tempPath.path)")
3025
+ }
3026
+ }
3027
+
3028
+ if !fileManager.fileExists(atPath: infoPath.path) {
3029
+ if !fileManager.createFile(atPath: infoPath.path, contents: Data()) {
3030
+ logger.error("Cannot ensure update info file exists")
3031
+ logger.debug("Path: \(infoPath.path)")
3032
+ }
3033
+ }
3034
+ }
3035
+
3036
+ private func cleanDownloadData(for id: String) {
3037
+ let fileManager = FileManager.default
3038
+ let tempPath = tempDataPath(for: id)
3039
+ let infoPath = updateInfoPath(for: id)
3040
+ // Deleting package_<id>.tmp
3041
+ if fileManager.fileExists(atPath: tempPath.path) {
3042
+ do {
3043
+ try fileManager.removeItem(at: tempPath)
3044
+ } catch {
3045
+ logger.error("Could not delete temp data file")
3046
+ logger.debug("Path: \(tempPath), Error: \(error)")
3047
+ }
3048
+ }
3049
+ // Deleting update_<id>.dat
3050
+ if fileManager.fileExists(atPath: infoPath.path) {
3051
+ do {
3052
+ try fileManager.removeItem(at: infoPath)
3053
+ } catch {
3054
+ logger.error("Could not delete update info file")
3055
+ logger.debug("Path: \(infoPath), Error: \(error)")
3056
+ }
3057
+ }
3058
+ }
3059
+
3060
+ private func savePartialData(startingAt byteOffset: UInt64, for id: String) {
3061
+ let fileManager = FileManager.default
3062
+ let tempPath = tempDataPath(for: id)
3063
+ do {
3064
+ // Check if package_<id>.tmp exist
3065
+ if !fileManager.fileExists(atPath: tempPath.path) {
3066
+ try self.tempData.write(to: tempPath, options: .atomicWrite)
3067
+ } else {
3068
+ // If yes, it start writing on it
3069
+ let fileHandle = try FileHandle(forWritingTo: tempPath)
3070
+ fileHandle.seek(toFileOffset: byteOffset) // Moving at the specified position to start writing
3071
+ fileHandle.write(self.tempData)
3072
+ fileHandle.closeFile()
3073
+ }
3074
+ } catch {
3075
+ logger.error("Failed to write partial data")
3076
+ logger.debug("Byte offset: \(byteOffset), Error: \(error)")
3077
+ }
3078
+ self.tempData.removeAll() // Clearing tempData to avoid writing the same data multiple times
3079
+ }
3080
+
3081
+ private func saveDownloadInfo(_ version: String, for id: String) {
3082
+ let infoPath = updateInfoPath(for: id)
3083
+ do {
3084
+ try "\(version)".write(to: infoPath, atomically: true, encoding: .utf8)
3085
+ } catch {
3086
+ logger.error("Failed to save download progress")
3087
+ logger.debug("Error: \(error)")
3088
+ }
3089
+ }
3090
+
3091
+ private func getLocalUpdateVersion(for id: String) -> String { // Return the version that was tried to be downloaded on last download attempt
3092
+ let infoPath = updateInfoPath(for: id)
3093
+ if !FileManager.default.fileExists(atPath: infoPath.path) {
3094
+ return "nil"
3095
+ }
3096
+ guard let versionString = try? String(contentsOf: infoPath),
3097
+ let version = Optional(versionString) else {
3098
+ return "nil"
3099
+ }
3100
+ return version
3101
+ }
3102
+
3103
+ private func loadDownloadProgress(for id: String) -> Int64 {
3104
+ let fileManager = FileManager.default
3105
+ let tempPath = tempDataPath(for: id)
3106
+ do {
3107
+ let attributes = try fileManager.attributesOfItem(atPath: tempPath.path)
3108
+ if let fileSize = attributes[.size] as? NSNumber {
3109
+ return fileSize.int64Value
3110
+ }
3111
+ } catch {
3112
+ logger.error("Could not retrieve download progress size")
3113
+ logger.debug("Error: \(error)")
3114
+ }
3115
+ return 0
3116
+ }
3117
+
3118
+ public func list(raw: Bool = false) -> [BundleInfo] {
3119
+ if !raw {
3120
+ // UserDefaults.standard.dictionaryRepresentation().values
3121
+ let dest: URL = libraryDir.appendingPathComponent(bundleDirectory)
3122
+ do {
3123
+ let files: [String] = try FileManager.default.contentsOfDirectory(atPath: dest.path)
3124
+ var res: [BundleInfo] = []
3125
+ logger.info("list File : \(dest.path)")
3126
+ if dest.exist {
3127
+ for id: String in files {
3128
+ res.append(self.getBundleInfo(id: id))
3129
+ }
3130
+ }
3131
+ return res
3132
+ } catch {
3133
+ logger.info("No version available \(dest.path)")
3134
+ return []
3135
+ }
3136
+ } else {
3137
+ guard let regex = try? NSRegularExpression(pattern: "^[0-9A-Za-z]{10}_info$") else {
3138
+ logger.error("Invalid regex ?????")
3139
+ return []
3140
+ }
3141
+ return UserDefaults.standard.dictionaryRepresentation().keys.filter {
3142
+ let range = NSRange($0.startIndex..., in: $0)
3143
+ let matches = regex.matches(in: $0, range: range)
3144
+ return !matches.isEmpty
3145
+ }.map {
3146
+ $0.components(separatedBy: "_")[0]
3147
+ }.map {
3148
+ self.getBundleInfo(id: $0)
3149
+ }
3150
+ }
3151
+
3152
+ }
3153
+
3154
+ public func delete(id: String, removeInfo: Bool) -> Bool {
3155
+ self.deleteLock.lock()
3156
+ defer { self.deleteLock.unlock() }
3157
+
3158
+ let destPersist: URL
3159
+ do {
3160
+ destPersist = try self.getBundleDirectory(id: id)
3161
+ } catch {
3162
+ logger.error("Cannot delete bundle with invalid id")
3163
+ logger.debug("Bundle ID: \(id), Error: \(error.localizedDescription)")
3164
+ return false
3165
+ }
3166
+
3167
+ let deleted: BundleInfo = self.getBundleInfo(id: id)
3168
+ if deleted.isBuiltin() || self.getCurrentBundleId() == id {
3169
+ logger.info("Cannot delete current or builtin bundle")
3170
+ logger.debug("Bundle ID: \(id)")
3171
+ return false
3172
+ }
3173
+
3174
+ if let previewFallback = self.getPreviewFallbackBundle(),
3175
+ !previewFallback.isDeleted(),
3176
+ !previewFallback.isErrorStatus(),
3177
+ !previewFallback.isDeleting(),
3178
+ previewFallback.getId() == id {
3179
+ logger.info("Cannot delete the preview fallback bundle")
3180
+ logger.debug("Bundle ID: \(id)")
3181
+ return false
3182
+ }
3183
+
3184
+ // Check if this is the next bundle and prevent deletion if it is
3185
+ if let next = self.getNextBundle(),
3186
+ !next.isDeleted() &&
3187
+ !next.isErrorStatus() &&
3188
+ !next.isDeleting() &&
3189
+ next.getId() == id {
3190
+ logger.info("Cannot delete the next bundle")
3191
+ logger.debug("Bundle ID: \(id)")
3192
+ return false
3193
+ }
3194
+
3195
+ let hadRegistry = self.hasStoredBundleInfo(id: id)
3196
+ let hadFolder = FileManager.default.fileExists(atPath: destPersist.path)
3197
+ if !hadRegistry && !hadFolder {
3198
+ logger.error("Cannot delete unknown bundle")
3199
+ logger.debug("Bundle ID: \(id)")
3200
+ self.dequeuePendingDelete(id: id)
3201
+ return false
3202
+ }
3203
+
3204
+ // Persist DELETING before touching disk so kill/OOM can resume on next launch.
3205
+ if !deleted.isDeleting() {
3206
+ if !self.saveBundleInfo(id: id, bundle: deleted.setStatus(status: BundleStatus.DELETING.storedValue)) {
3207
+ logger.error("Failed to persist DELETING marker, aborting disk delete")
3208
+ logger.debug("Bundle ID: \(id)")
3209
+ return false
3210
+ }
3211
+ UserDefaults.standard.synchronize()
3212
+ }
3213
+
3214
+ if FileManager.default.fileExists(atPath: destPersist.path) {
3215
+ do {
3216
+ try FileManager.default.removeItem(atPath: destPersist.path)
3217
+ } catch {
3218
+ logger.error("Bundle folder not removed, will retry later")
3219
+ logger.debug("Path: \(destPersist.path), Error: \(error.localizedDescription)")
3220
+ return false
3221
+ }
3222
+ }
3223
+
3224
+ // Only drop registry after the folder is confirmed gone.
3225
+ if FileManager.default.fileExists(atPath: destPersist.path) {
3226
+ logger.error("Bundle folder still present after delete, will retry later")
3227
+ logger.debug("Bundle ID: \(id)")
3228
+ return false
3229
+ }
3230
+
3231
+ let finalized: Bool
3232
+ if removeInfo {
3233
+ finalized = self.saveBundleInfo(id: id, bundle: nil)
3234
+ } else {
3235
+ finalized = self.saveBundleInfo(id: id, bundle: deleted.setStatus(status: BundleStatus.DELETED.storedValue))
3236
+ }
3237
+ guard finalized else {
3238
+ logger.error("Failed to finalize delete registry update, will retry later")
3239
+ logger.debug("Bundle ID: \(id)")
3240
+ return false
3241
+ }
3242
+ UserDefaults.standard.synchronize()
3243
+ self.dequeuePendingDelete(id: id)
3244
+ logger.info("Bundle deleted and confirmed gone")
3245
+ logger.debug("Version: \(deleted.getVersionName())")
3246
+ self.sendStats(action: "delete", versionName: deleted.getVersionName())
3247
+ return true
3248
+ }
3249
+
3250
+ public func delete(id: String) -> Bool {
3251
+ return self.delete(id: id, removeInfo: true)
3252
+ }
3253
+
3254
+ /// Resume incomplete deletes one-by-one. Safe across app kill / OOM because
3255
+ /// delete() marks DELETING before disk work and only clears registry after confirm.
3256
+ public func drainPendingDeletes() {
3257
+ var pendingIds = Set(self.list(raw: true).filter { $0.isDeleting() }.map { $0.getId() }.filter { !$0.isEmpty })
3258
+ pendingIds.formUnion(self.getPendingDeleteIds())
3259
+ for id in pendingIds {
3260
+ if Thread.current.isCancelled {
3261
+ logger.warn("drainPendingDeletes was cancelled")
3262
+ return
3263
+ }
3264
+ logger.info("Resuming pending delete for bundle: \(id)")
3265
+ if self.delete(id: id, removeInfo: true) {
3266
+ self.dequeuePendingDelete(id: id)
3267
+ }
3268
+ Thread.sleep(forTimeInterval: self.deletePaceSeconds)
3269
+ }
3270
+ }
3271
+
3272
+ private func getPendingDeleteIds() -> Set<String> {
3273
+ guard let raw = UserDefaults.standard.string(forKey: self.PENDING_DELETE_IDS), !raw.isEmpty else {
3274
+ return []
3275
+ }
3276
+ return Set(raw.split(separator: ",").map { String($0) }.filter { !$0.isEmpty })
3277
+ }
3278
+
3279
+ private func enqueuePendingDelete(id: String) {
3280
+ guard !id.isEmpty else { return }
3281
+ var ids = self.getPendingDeleteIds()
3282
+ guard ids.insert(id).inserted else { return }
3283
+ UserDefaults.standard.set(ids.sorted().joined(separator: ","), forKey: self.PENDING_DELETE_IDS)
3284
+ UserDefaults.standard.synchronize()
3285
+ }
3286
+
3287
+ private func dequeuePendingDelete(id: String) {
3288
+ guard !id.isEmpty else { return }
3289
+ var ids = self.getPendingDeleteIds()
3290
+ guard ids.remove(id) != nil else { return }
3291
+ if ids.isEmpty {
3292
+ UserDefaults.standard.removeObject(forKey: self.PENDING_DELETE_IDS)
3293
+ } else {
3294
+ UserDefaults.standard.set(ids.sorted().joined(separator: ","), forKey: self.PENDING_DELETE_IDS)
3295
+ }
3296
+ UserDefaults.standard.synchronize()
3297
+ }
3298
+
3299
+ public func cleanupDeltaCache() {
3300
+ cleanupDeltaCache(threadToCheck: nil)
3301
+ }
3302
+
3303
+ public func cleanupDeltaCache(threadToCheck: Thread?) {
3304
+ // Check if thread was cancelled
3305
+ if let thread = threadToCheck, thread.isCancelled {
3306
+ logger.warn("cleanupDeltaCache was cancelled before starting")
3307
+ return
3308
+ }
3309
+
3310
+ let fileManager = FileManager.default
3311
+ guard fileManager.fileExists(atPath: cacheFolder.path) else {
3312
+ return
3313
+ }
3314
+ do {
3315
+ try fileManager.removeItem(at: cacheFolder)
3316
+ logger.info("Cleaned up delta cache folder")
3317
+ } catch {
3318
+ logger.error("Failed to cleanup delta cache")
3319
+ logger.debug("Error: \(error.localizedDescription)")
3320
+ }
3321
+ }
3322
+
3323
+ public func cleanupDownloadDirectories(allowedIds: Set<String>) {
3324
+ cleanupDownloadDirectories(allowedIds: allowedIds, threadToCheck: nil)
3325
+ }
3326
+
3327
+ public func cleanupDownloadDirectories(allowedIds: Set<String>, threadToCheck: Thread?) {
3328
+ let bundleRoot = libraryDir.appendingPathComponent(bundleDirectory)
3329
+ let fileManager = FileManager.default
3330
+
3331
+ guard fileManager.fileExists(atPath: bundleRoot.path) else {
3332
+ return
3333
+ }
3334
+
3335
+ do {
3336
+ let contents = try fileManager.contentsOfDirectory(at: bundleRoot, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles])
3337
+
3338
+ for url in contents {
3339
+ // Check if thread was cancelled
3340
+ if let thread = threadToCheck, thread.isCancelled {
3341
+ logger.warn("cleanupDownloadDirectories was cancelled")
3342
+ return
3343
+ }
3344
+
3345
+ let resourceValues = try url.resourceValues(forKeys: [.isDirectoryKey])
3346
+ if resourceValues.isDirectory != true {
3347
+ continue
3348
+ }
3349
+
3350
+ let id = url.lastPathComponent
3351
+
3352
+ if allowedIds.contains(id) {
3353
+ continue
3354
+ }
3355
+
3356
+ do {
3357
+ try fileManager.removeItem(at: url)
3358
+ if fileManager.fileExists(atPath: url.path) {
3359
+ logger.error("Orphan bundle directory still present after delete")
3360
+ logger.debug("Bundle ID: \(id)")
3361
+ continue
3362
+ }
3363
+ self.removeBundleInfo(id: id)
3364
+ logger.info("Deleted orphan bundle directory")
3365
+ logger.debug("Bundle ID: \(id)")
3366
+ } catch {
3367
+ logger.error("Failed to delete orphan bundle directory")
3368
+ logger.debug("Bundle ID: \(id), Error: \(error.localizedDescription)")
3369
+ }
3370
+ }
3371
+ } catch {
3372
+ logger.error("Failed to enumerate bundle directory for cleanup")
3373
+ logger.debug("Error: \(error.localizedDescription)")
3374
+ }
3375
+ }
3376
+
3377
+ public func allowedBundleIdsForCleanup() -> Set<String> {
3378
+ var allowedIds = Set(self.list(raw: true).compactMap { info -> String? in
3379
+ let id = info.getId()
3380
+ // DELETED tombstones must not protect leftover folders.
3381
+ // DELETING stays protected so drainPendingDeletes owns the removal.
3382
+ if id.isEmpty || info.isDeleted() {
3383
+ return nil
3384
+ }
3385
+ return id
3386
+ })
3387
+ let currentId = self.getCurrentBundleId()
3388
+ if !currentId.isEmpty {
3389
+ allowedIds.insert(currentId)
3390
+ }
3391
+ let fallback = self.getFallbackBundle()
3392
+ let fallbackId = fallback.getId()
3393
+ if !fallbackId.isEmpty && !fallback.isDeleting() {
3394
+ allowedIds.insert(fallbackId)
3395
+ }
3396
+ if let next = self.getNextBundle() {
3397
+ let nextId = next.getId()
3398
+ if !nextId.isEmpty && !next.isDeleting() {
3399
+ allowedIds.insert(nextId)
3400
+ }
3401
+ }
3402
+ if let previewFallback = self.getPreviewFallbackBundle() {
3403
+ let previewId = previewFallback.getId()
3404
+ if !previewId.isEmpty && !previewFallback.isDeleting() {
3405
+ allowedIds.insert(previewId)
3406
+ }
3407
+ }
3408
+ return allowedIds
3409
+ }
3410
+
3411
+ public func cleanupOrphanedTempFolders(threadToCheck: Thread?) {
3412
+ let fileManager = FileManager.default
3413
+
3414
+ do {
3415
+ let contents = try fileManager.contentsOfDirectory(at: libraryDir, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles])
3416
+
3417
+ for url in contents {
3418
+ // Check if thread was cancelled
3419
+ if let thread = threadToCheck, thread.isCancelled {
3420
+ logger.warn("cleanupOrphanedTempFolders was cancelled")
3421
+ return
3422
+ }
3423
+
3424
+ let resourceValues = try url.resourceValues(forKeys: [.isDirectoryKey])
3425
+ if resourceValues.isDirectory != true {
3426
+ continue
3427
+ }
3428
+
3429
+ let folderName = url.lastPathComponent
3430
+
3431
+ // Only delete folders with the temp unzip prefix
3432
+ if !folderName.hasPrefix(TEMP_UNZIP_PREFIX) {
3433
+ continue
3434
+ }
3435
+
3436
+ do {
3437
+ try fileManager.removeItem(at: url)
3438
+ logger.info("Deleted orphaned temp unzip folder")
3439
+ logger.debug("Folder: \(folderName)")
3440
+ } catch {
3441
+ logger.error("Failed to delete orphaned temp folder")
3442
+ logger.debug("Folder: \(folderName), Error: \(error.localizedDescription)")
3443
+ }
3444
+ }
3445
+ } catch {
3446
+ logger.error("Failed to enumerate library directory for temp folder cleanup")
3447
+ logger.debug("Error: \(error.localizedDescription)")
3448
+ }
3449
+
3450
+ if let thread = threadToCheck, thread.isCancelled {
3451
+ logger.warn("cleanupOrphanedTempFolders was cancelled")
3452
+ return
3453
+ }
3454
+
3455
+ // Also cleanup old download temp files (package_*.tmp and update_*.dat)
3456
+ cleanupOldDownloadTempFiles(threadToCheck: threadToCheck)
3457
+ }
3458
+
3459
+ private func cleanupOldDownloadTempFiles(threadToCheck: Thread? = nil) {
3460
+ let fileManager = FileManager.default
3461
+ guard let documentsDir = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
3462
+ return
3463
+ }
3464
+
3465
+ do {
3466
+ let contents = try fileManager.contentsOfDirectory(at: documentsDir, includingPropertiesForKeys: [.contentModificationDateKey], options: [.skipsHiddenFiles])
3467
+ let oneHourAgo = Date().addingTimeInterval(-3600)
3468
+
3469
+ for url in contents {
3470
+ if let thread = threadToCheck, thread.isCancelled {
3471
+ logger.warn("cleanupOldDownloadTempFiles was cancelled")
3472
+ return
3473
+ }
3474
+ let fileName = url.lastPathComponent
3475
+ // Only cleanup package_*.tmp and update_*.dat files
3476
+ let isDownloadTemp = (fileName.hasPrefix("package_") && fileName.hasSuffix(".tmp")) ||
3477
+ (fileName.hasPrefix("update_") && fileName.hasSuffix(".dat"))
3478
+ if !isDownloadTemp {
3479
+ continue
3480
+ }
3481
+
3482
+ // Only delete files older than 1 hour
3483
+ if let modDate = try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate,
3484
+ modDate < oneHourAgo {
3485
+ do {
3486
+ try fileManager.removeItem(at: url)
3487
+ logger.debug("Deleted old download temp file: \(fileName)")
3488
+ } catch {
3489
+ logger.debug("Failed to delete old download temp file: \(fileName), Error: \(error.localizedDescription)")
3490
+ }
3491
+ }
3492
+ }
3493
+ } catch {
3494
+ logger.debug("Failed to enumerate documents directory for temp file cleanup: \(error.localizedDescription)")
3495
+ }
3496
+ }
3497
+
3498
+ public func getBundleDirectory(id: String) throws -> URL {
3499
+ return try Self.resolveBundleDirectory(libraryDir: libraryDir, bundleId: id)
3500
+ }
3501
+
3502
+ struct ResetState {
3503
+ let currentBundlePath: String
3504
+ let fallbackBundleId: String
3505
+ let nextBundleId: String?
3506
+ }
3507
+
3508
+ func captureResetState() -> ResetState {
3509
+ ResetState(
3510
+ currentBundlePath: UserDefaults.standard.string(forKey: self.CAP_SERVER_PATH) ?? self.DEFAULT_FOLDER,
3511
+ fallbackBundleId: UserDefaults.standard.string(forKey: self.FALLBACK_VERSION) ?? BundleInfo.ID_BUILTIN,
3512
+ nextBundleId: UserDefaults.standard.string(forKey: self.NEXT_VERSION)
3513
+ )
3514
+ }
3515
+
3516
+ func restoreResetState(_ state: ResetState) {
3517
+ let currentBundlePath = state.currentBundlePath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
3518
+ ? self.DEFAULT_FOLDER
3519
+ : state.currentBundlePath
3520
+ let fallbackBundleId = state.fallbackBundleId.isEmpty ? BundleInfo.ID_BUILTIN : state.fallbackBundleId
3521
+
3522
+ self.setCurrentBundle(bundle: currentBundlePath)
3523
+ UserDefaults.standard.set(fallbackBundleId, forKey: self.FALLBACK_VERSION)
3524
+ if let nextBundleId = state.nextBundleId, !nextBundleId.isEmpty {
3525
+ UserDefaults.standard.set(nextBundleId, forKey: self.NEXT_VERSION)
3526
+ } else {
3527
+ UserDefaults.standard.removeObject(forKey: self.NEXT_VERSION)
3528
+ }
3529
+ UserDefaults.standard.synchronize()
3530
+ }
3531
+
3532
+ func prepareResetStateForTransition() {
3533
+ self.setCurrentBundle(bundle: "")
3534
+ self.setFallbackBundle(fallback: Optional<BundleInfo>.none)
3535
+ _ = self.setNextBundle(next: Optional<String>.none)
3536
+ }
3537
+
3538
+ func finalizeResetTransition(previousBundleName: String, isInternal: Bool) {
3539
+ if !isInternal {
3540
+ self.sendStats(action: "reset", versionName: self.getCurrentBundle().getVersionName(), oldVersionName: previousBundleName)
3541
+ }
3542
+ }
3543
+
3544
+ func canSet(bundle: BundleInfo) -> Bool {
3545
+ bundle.isBuiltin() || self.bundleExists(id: bundle.getId())
3546
+ }
3547
+
3548
+ public func set(bundle: BundleInfo) -> Bool {
3549
+ return self.set(id: bundle.getId())
3550
+ }
3551
+
3552
+ func bundleExists(id: String) -> Bool {
3553
+ let destPersist: URL
3554
+ do {
3555
+ destPersist = try self.getBundleDirectory(id: id)
3556
+ } catch {
3557
+ return false
3558
+ }
3559
+ let indexPersist: URL = destPersist.appendingPathComponent("index.html")
3560
+ let bundleIndo: BundleInfo = self.getBundleInfo(id: id)
3561
+ if
3562
+ destPersist.exist &&
3563
+ destPersist.isDirectory &&
3564
+ !indexPersist.isDirectory &&
3565
+ indexPersist.exist &&
3566
+ !bundleIndo.isDeleted() &&
3567
+ !bundleIndo.isDeleting() {
3568
+ return true
3569
+ }
3570
+ return false
3571
+ }
3572
+
3573
+ /// Activates a stored bundle only if it meets the native version floor. Builtin reset is always allowed.
3574
+ public func set(id: String) -> Bool {
3575
+ let newBundle: BundleInfo = self.getBundleInfo(id: id)
3576
+ if newBundle.isBuiltin() {
3577
+ self.reset()
3578
+ return true
3579
+ }
3580
+ if bundleExists(id: id) {
3581
+ do {
3582
+ try self.requireVersionNotBelowBuiltin(newBundle.getVersionName())
3583
+ } catch {
3584
+ return false
3585
+ }
3586
+ let currentBundleName = self.getCurrentBundle().getVersionName()
3587
+ guard let bundleDir = try? self.getBundleDirectory(id: id) else {
3588
+ self.setBundleStatus(id: id, status: BundleStatus.ERROR)
3589
+ self.sendStats(action: "set_fail", versionName: newBundle.getVersionName())
3590
+ return false
3591
+ }
3592
+ self.setCurrentBundle(bundle: bundleDir.path)
3593
+ self.setBundleStatus(id: id, status: BundleStatus.PENDING)
3594
+ self.sendStats(action: "set", versionName: newBundle.getVersionName(), oldVersionName: currentBundleName)
3595
+ return true
3596
+ }
3597
+ self.setBundleStatus(id: id, status: BundleStatus.ERROR)
3598
+ self.sendStats(action: "set_fail", versionName: newBundle.getVersionName())
3599
+ return false
3600
+ }
3601
+
3602
+ /// Stages a pending bundle without finalizing it, checking the version floor before changing the active path.
3603
+ func stagePendingReload(bundle: BundleInfo) -> Bool {
3604
+ guard !bundle.isBuiltin(), bundleExists(id: bundle.getId()) else {
3605
+ return false
3606
+ }
3607
+ do {
3608
+ try self.requireVersionNotBelowBuiltin(bundle.getVersionName())
3609
+ let bundleDir = try self.getBundleDirectory(id: bundle.getId())
3610
+ self.setCurrentBundle(bundle: bundleDir.path)
3611
+ return true
3612
+ } catch {
3613
+ return false
3614
+ }
3615
+ }
3616
+
3617
+ /// Points the current bundle back at `bundle` without sending stats, after an
3618
+ /// install whose reload failed left the WebView on it.
3619
+ func restoreCurrentBundle(_ bundle: BundleInfo) {
3620
+ if bundle.isBuiltin() {
3621
+ self.setCurrentBundle(bundle: "")
3622
+ } else if bundleExists(id: bundle.getId()),
3623
+ let bundleDir = try? self.getBundleDirectory(id: bundle.getId()) {
3624
+ self.setCurrentBundle(bundle: bundleDir.path)
3625
+ }
3626
+ }
3627
+
3628
+ func stagePreviewFallbackReload(bundle: BundleInfo) -> Bool {
3629
+ guard !bundle.isErrorStatus() else {
3630
+ return false
3631
+ }
3632
+ if bundle.isBuiltin() {
3633
+ self.setCurrentBundle(bundle: self.DEFAULT_FOLDER)
3634
+ return true
3635
+ }
3636
+ guard bundleExists(id: bundle.getId()) else {
3637
+ return false
3638
+ }
3639
+ guard let bundleDir = try? self.getBundleDirectory(id: bundle.getId()) else {
3640
+ return false
3641
+ }
3642
+ self.setCurrentBundle(bundle: bundleDir.path)
3643
+ return true
3644
+ }
3645
+
3646
+ func finalizePendingReload(bundle: BundleInfo, previousBundleName: String) {
3647
+ guard !bundle.isBuiltin() else {
3648
+ return
3649
+ }
3650
+ self.sendStats(action: "set", versionName: bundle.getVersionName(), oldVersionName: previousBundleName)
3651
+ }
3652
+
3653
+ public func autoReset() {
3654
+ let currentBundle: BundleInfo = self.getCurrentBundle()
3655
+ if !currentBundle.isBuiltin() && !self.bundleExists(id: currentBundle.getId()) {
3656
+ logger.info("Folder at bundle path does not exist. Triggering reset.")
3657
+ self.reset()
3658
+ return
3659
+ }
3660
+ let bundlePath = UserDefaults.standard.string(forKey: self.CAP_SERVER_PATH)
3661
+ if Self.shouldResetForForeignBundle(
3662
+ bundlePath: bundlePath,
3663
+ isBuiltin: currentBundle.isBuiltin(),
3664
+ hasStoredBundleInfo: self.hasStoredBundleInfo(id: currentBundle.getId())
3665
+ ) {
3666
+ logger.info("Current bundle id is not one of the bundle ids stored by this plugin. Triggering reset.")
3667
+ self.reset()
3668
+ }
3669
+ }
3670
+
3671
+ public func reset() {
3672
+ self.reset(isInternal: false)
3673
+ }
3674
+
3675
+ public func reset(isInternal: Bool) {
3676
+ logger.info("reset: \(isInternal)")
3677
+ let currentBundleName = self.getCurrentBundle().getVersionName()
3678
+ self.prepareResetStateForTransition()
3679
+ self.finalizeResetTransition(previousBundleName: currentBundleName, isInternal: isInternal)
3680
+ }
3681
+
3682
+ public func setSuccess(bundle: BundleInfo, autoDeletePrevious: Bool) {
3683
+ self.setBundleStatus(id: bundle.getId(), status: BundleStatus.SUCCESS)
3684
+ let fallback: BundleInfo = self.getFallbackBundle()
3685
+ let previewFallback = self.getPreviewFallbackBundle()
3686
+ let fallbackIsPreviewFallback = previewFallback?.getId() == fallback.getId()
3687
+ logger.info("Fallback bundle is: \(fallback.toString())")
3688
+ logger.info("Version successfully loaded: \(bundle.toString())")
3689
+ let previousFallbackId = fallback.getId()
3690
+ let nextBundle = self.getNextBundle()
3691
+ let previousIsNext = nextBundle?.getId() == previousFallbackId &&
3692
+ !(nextBundle?.isDeleted() ?? true) &&
3693
+ !(nextBundle?.isErrorStatus() ?? true) &&
3694
+ !(nextBundle?.isDeleting() ?? true)
3695
+ let shouldDeletePrevious = autoDeletePrevious &&
3696
+ !fallback.isBuiltin() &&
3697
+ previousFallbackId != bundle.getId() &&
3698
+ !fallbackIsPreviewFallback &&
3699
+ !previousIsNext
3700
+ if shouldDeletePrevious {
3701
+ // Mark durable intent before fallback switch so a kill mid-flight still retries.
3702
+ if !self.saveBundleInfo(id: previousFallbackId, bundle: fallback.setStatus(status: BundleStatus.DELETING.storedValue)) {
3703
+ self.logger.error("Failed to persist DELETING for previous bundle; queueing durable retry")
3704
+ self.logger.debug("Bundle ID: \(previousFallbackId)")
3705
+ self.enqueuePendingDelete(id: previousFallbackId)
3706
+ }
3707
+ UserDefaults.standard.synchronize()
3708
+ }
3709
+ self.setFallbackBundle(fallback: bundle)
3710
+ if shouldDeletePrevious {
3711
+ DispatchQueue.global(qos: .utility).async {
3712
+ let res = self.delete(id: previousFallbackId)
3713
+ if res {
3714
+ self.logger.info("Deleted previous bundle")
3715
+ self.logger.debug("Bundle ID: \(previousFallbackId)")
3716
+ } else {
3717
+ self.logger.info("Previous bundle delete incomplete, will retry")
3718
+ self.logger.debug("Bundle ID: \(previousFallbackId)")
3719
+ }
3720
+ }
3721
+ }
3722
+ }
3723
+
3724
+ public func setError(bundle: BundleInfo) {
3725
+ self.setBundleStatus(id: bundle.getId(), status: BundleStatus.ERROR)
3726
+ }
3727
+
3728
+ func unsetChannel(
3729
+ defaultChannelKey: String,
3730
+ defaultChannelFromSetChannelKey: String,
3731
+ configDefaultChannel: String,
3732
+ allowSetDefaultChannel: Bool
3733
+ ) -> SetChannel {
3734
+ let setChannel: SetChannel = SetChannel()
3735
+
3736
+ if !allowSetDefaultChannel {
3737
+ logger.error("unsetChannel is disabled by allowSetDefaultChannel config")
3738
+ setChannel.message = "unsetChannel is disabled by configuration"
3739
+ setChannel.error = "disabled_by_config"
3740
+ return setChannel
3741
+ }
3742
+
3743
+ // Clear persisted defaultChannel and revert to config value
3744
+ UserDefaults.standard.removeObject(forKey: defaultChannelKey)
3745
+ UserDefaults.standard.removeObject(forKey: defaultChannelFromSetChannelKey)
3746
+ UserDefaults.standard.synchronize()
3747
+ self.defaultChannel = configDefaultChannel
3748
+ self.logger.info("Persisted defaultChannel cleared, reverted to config value: \(configDefaultChannel)")
3749
+
3750
+ setChannel.status = "ok"
3751
+ setChannel.message = "Channel override removed"
3752
+ return setChannel
3753
+ }
3754
+
3755
+ func setChannel(
3756
+ channel: String,
3757
+ defaultChannelKey: String,
3758
+ defaultChannelFromSetChannelKey: String,
3759
+ allowSetDefaultChannel: Bool,
3760
+ configDefaultChannel: String = ""
3761
+ ) -> SetChannel {
3762
+ let setChannel: SetChannel = SetChannel()
3763
+
3764
+ // Check if setting defaultChannel is allowed
3765
+ if !allowSetDefaultChannel {
3766
+ logger.error("setChannel is disabled by allowSetDefaultChannel config")
3767
+ setChannel.message = "setChannel is disabled by configuration"
3768
+ setChannel.error = "disabled_by_config"
3769
+ return setChannel
3770
+ }
3771
+
3772
+ if isRemoteBlocked() {
3773
+ let blocked = remoteBlockedClientError()
3774
+ logger.debug("Skipping setChannel due to remote block (\(blocked.error)).")
3775
+ setChannel.message = blocked.message
3776
+ setChannel.error = blocked.error
3777
+ return setChannel
3778
+ }
3779
+
3780
+ if (self.channelUrl ).isEmpty {
3781
+ logger.error("Channel URL is not set")
3782
+ setChannel.message = "Channel URL is not set"
3783
+ setChannel.error = "missing_config"
3784
+ return setChannel
3785
+ }
3786
+ guard let channelURL = URL(string: self.channelUrl) else {
3787
+ logger.error("Invalid channel URL")
3788
+ setChannel.message = "Channel URL is invalid"
3789
+ setChannel.error = "invalid_config"
3790
+ return setChannel
3791
+ }
3792
+ var parameters: InfoObject = self.createInfoObject()
3793
+ parameters.channel = channel
3794
+ guard let request = createRequest(url: channelURL, method: "POST", parameters: parameters.toParameters()) else {
3795
+ setChannel.error = "Request failed: invalid request"
3796
+ return setChannel
3797
+ }
3798
+
3799
+ let result = performRequest(request, label: "setChannel")
3800
+
3801
+ let rateLimit = self.checkAndHandleRateLimitResponse(
3802
+ statusCode: result.response?.statusCode,
3803
+ data: result.data,
3804
+ response: result.response
3805
+ )
3806
+ if rateLimit.blocked {
3807
+ setChannel.message = rateLimit.message
3808
+ setChannel.error = rateLimit.error
3809
+ return setChannel
3810
+ }
3811
+
3812
+ if result.timedOut {
3813
+ setChannel.error = "Request timed out"
3814
+ return setChannel
3815
+ }
3816
+
3817
+ if let error = result.error {
3818
+ self.logger.error("Error setting channel")
3819
+ self.logger.debug("Error: \(error.localizedDescription)")
3820
+ setChannel.error = "Request failed: \(error.localizedDescription)"
3821
+ return setChannel
3822
+ }
3823
+
3824
+ guard let data = result.data else {
3825
+ setChannel.error = "Request failed: empty response"
3826
+ return setChannel
3827
+ }
3828
+
3829
+ guard let responseValue = try? JSONDecoder().decode(SetChannelDec.self, from: data) else {
3830
+ setChannel.error = "decode_error"
3831
+ return setChannel
3832
+ }
3833
+
3834
+ let statusCode = result.response?.statusCode ?? 0
3835
+ if statusCode < 200 || statusCode >= 300 {
3836
+ setChannel.message = responseValue.message ?? "Server error: \(statusCode)"
3837
+ setChannel.error = responseValue.error ?? "response_error"
3838
+ return setChannel
3839
+ }
3840
+
3841
+ if let error = responseValue.error {
3842
+ setChannel.error = error
3843
+ } else if responseValue.unset == true {
3844
+ UserDefaults.standard.removeObject(forKey: defaultChannelKey)
3845
+ UserDefaults.standard.removeObject(forKey: defaultChannelFromSetChannelKey)
3846
+ UserDefaults.standard.synchronize()
3847
+ self.defaultChannel = configDefaultChannel
3848
+ self.logger.info("Public channel requested, channel override removed")
3849
+
3850
+ setChannel.status = responseValue.status ?? "ok"
3851
+ setChannel.message = responseValue.message
3852
+ ?? "Public channel requested, channel override removed. Device will use public channel automatically."
3853
+ } else {
3854
+ self.defaultChannel = channel
3855
+ UserDefaults.standard.set(channel, forKey: defaultChannelKey)
3856
+ UserDefaults.standard.set(true, forKey: defaultChannelFromSetChannelKey)
3857
+ UserDefaults.standard.synchronize()
3858
+ self.logger.info("defaultChannel persisted locally: \(channel)")
3859
+
3860
+ setChannel.status = responseValue.status ?? ""
3861
+ setChannel.message = responseValue.message ?? ""
3862
+ }
3863
+ return setChannel
3864
+ }
3865
+
3866
+ func getChannel(
3867
+ defaultChannelKey: String? = nil,
3868
+ defaultChannelFromSetChannelKey: String? = nil,
3869
+ configDefaultChannel: String = ""
3870
+ ) -> GetChannel {
3871
+ let getChannel: GetChannel = GetChannel()
3872
+ // Check if rate limit was exceeded
3873
+ if isRemoteBlocked() {
3874
+ let blocked = remoteBlockedClientError()
3875
+ logger.debug("Skipping getChannel due to remote block (\(blocked.error)).")
3876
+ getChannel.message = blocked.message
3877
+ getChannel.error = blocked.error
3878
+ return getChannel
3879
+ }
3880
+
3881
+ if (self.channelUrl ).isEmpty {
3882
+ logger.error("Channel URL is not set")
3883
+ getChannel.message = "Channel URL is not set"
3884
+ getChannel.error = "missing_config"
3885
+ return getChannel
3886
+ }
3887
+ guard let channelURL = URL(string: self.channelUrl) else {
3888
+ logger.error("Invalid channel URL")
3889
+ getChannel.message = "Channel URL is invalid"
3890
+ getChannel.error = "invalid_config"
3891
+ return getChannel
3892
+ }
3893
+ let parameters: InfoObject = self.createInfoObject()
3894
+ guard let request = createRequest(url: channelURL, method: "PUT", parameters: parameters.toParameters()) else {
3895
+ getChannel.error = "Request failed: invalid request"
3896
+ return getChannel
3897
+ }
3898
+
3899
+ let result = performRequest(request, label: "getChannel")
3900
+
3901
+ let rateLimit = self.checkAndHandleRateLimitResponse(
3902
+ statusCode: result.response?.statusCode,
3903
+ data: result.data,
3904
+ response: result.response
3905
+ )
3906
+ if rateLimit.blocked {
3907
+ getChannel.message = rateLimit.message
3908
+ getChannel.error = rateLimit.error
3909
+ return getChannel
3910
+ }
3911
+
3912
+ if result.timedOut {
3913
+ getChannel.error = "Request timed out"
3914
+ return getChannel
3915
+ }
3916
+
3917
+ if let error = result.error {
3918
+ if let data = result.data, let bodyString = String(data: data, encoding: .utf8) {
3919
+ if bodyString.contains("channel_not_found") && result.response?.statusCode == 400 && !self.defaultChannel.isEmpty {
3920
+ getChannel.channel = self.defaultChannel
3921
+ getChannel.status = "default"
3922
+ return getChannel
3923
+ }
3924
+ }
3925
+
3926
+ self.logger.error("Error getting channel")
3927
+ self.logger.debug("Error: \(error.localizedDescription)")
3928
+ getChannel.error = "Request failed: \(error.localizedDescription)"
3929
+ return getChannel
3930
+ }
3931
+
3932
+ guard let data = result.data else {
3933
+ getChannel.error = "Request failed: empty response"
3934
+ return getChannel
3935
+ }
3936
+
3937
+ guard let responseValue = try? JSONDecoder().decode(GetChannelDec.self, from: data) else {
3938
+ getChannel.error = "decode_error"
3939
+ return getChannel
3940
+ }
3941
+
3942
+ let statusCode = result.response?.statusCode ?? 0
3943
+ if let error = responseValue.error {
3944
+ if error == "channel_not_found", statusCode == 400, !self.defaultChannel.isEmpty {
3945
+ getChannel.channel = self.defaultChannel
3946
+ getChannel.status = "default"
3947
+ return getChannel
3948
+ }
3949
+ getChannel.error = error
3950
+ getChannel.message = responseValue.message ?? ""
3951
+ return getChannel
3952
+ }
3953
+
3954
+ if statusCode < 200 || statusCode >= 300 {
3955
+ getChannel.message = responseValue.message ?? "Server error: \(statusCode)"
3956
+ getChannel.error = "response_error"
3957
+ } else {
3958
+ getChannel.status = responseValue.status ?? ""
3959
+ getChannel.message = responseValue.message ?? ""
3960
+ getChannel.channel = responseValue.channel ?? ""
3961
+ getChannel.allowSet = responseValue.allowSet ?? true
3962
+ persistDefaultChannelFromResponse(
3963
+ channel: responseValue.channel,
3964
+ status: responseValue.status,
3965
+ defaultChannelKey: defaultChannelKey,
3966
+ defaultChannelFromSetChannelKey: defaultChannelFromSetChannelKey,
3967
+ configDefaultChannel: configDefaultChannel
3968
+ )
3969
+ }
3970
+ return getChannel
3971
+ }
3972
+
3973
+ func persistDefaultChannelFromResponse(
3974
+ channel: String?,
3975
+ status: String?,
3976
+ defaultChannelKey: String?,
3977
+ defaultChannelFromSetChannelKey: String? = nil,
3978
+ configDefaultChannel: String = ""
3979
+ ) {
3980
+ if status == "default" {
3981
+ guard let channelName = channel?.trimmingCharacters(in: .whitespacesAndNewlines),
3982
+ !channelName.isEmpty else {
3983
+ return
3984
+ }
3985
+ var persisted = defaultChannel.trimmingCharacters(in: .whitespacesAndNewlines)
3986
+ if let defaultChannelKey, !defaultChannelKey.isEmpty,
3987
+ let stored = UserDefaults.standard.string(forKey: defaultChannelKey) {
3988
+ let trimmedStored = stored.trimmingCharacters(in: .whitespacesAndNewlines)
3989
+ if !trimmedStored.isEmpty {
3990
+ persisted = trimmedStored
3991
+ }
3992
+ }
3993
+ let fromSetChannel: Bool
3994
+ if let defaultChannelFromSetChannelKey, !defaultChannelFromSetChannelKey.isEmpty {
3995
+ fromSetChannel = UserDefaults.standard.bool(forKey: defaultChannelFromSetChannelKey)
3996
+ } else {
3997
+ fromSetChannel = false
3998
+ }
3999
+ // Upgrades: values from setChannel() before this marker existed read as stale fallbacks and may clear here.
4000
+ if channelName == persisted, !fromSetChannel {
4001
+ self.defaultChannel = configDefaultChannel
4002
+ if let defaultChannelKey, !defaultChannelKey.isEmpty {
4003
+ UserDefaults.standard.removeObject(forKey: defaultChannelKey)
4004
+ if let defaultChannelFromSetChannelKey, !defaultChannelFromSetChannelKey.isEmpty {
4005
+ UserDefaults.standard.removeObject(forKey: defaultChannelFromSetChannelKey)
4006
+ }
4007
+ UserDefaults.standard.synchronize()
4008
+ }
4009
+ logger.info("defaultChannel cleared stale getChannel() fallback: \(channelName)")
4010
+ }
4011
+ return
4012
+ }
4013
+ guard let channelName = channel?.trimmingCharacters(in: .whitespacesAndNewlines),
4014
+ !channelName.isEmpty,
4015
+ channelName != BundleInfo.ID_BUILTIN else {
4016
+ return
4017
+ }
4018
+
4019
+ let preserveSetChannelMarker: Bool
4020
+ if let defaultChannelFromSetChannelKey, !defaultChannelFromSetChannelKey.isEmpty {
4021
+ preserveSetChannelMarker =
4022
+ UserDefaults.standard.bool(forKey: defaultChannelFromSetChannelKey) && channelName == defaultChannel
4023
+ } else {
4024
+ preserveSetChannelMarker = false
4025
+ }
4026
+
4027
+ self.defaultChannel = channelName
4028
+ if let defaultChannelKey, !defaultChannelKey.isEmpty {
4029
+ UserDefaults.standard.set(channelName, forKey: defaultChannelKey)
4030
+ if let defaultChannelFromSetChannelKey, !defaultChannelFromSetChannelKey.isEmpty, !preserveSetChannelMarker {
4031
+ UserDefaults.standard.set(false, forKey: defaultChannelFromSetChannelKey)
4032
+ }
4033
+ UserDefaults.standard.synchronize()
4034
+ }
4035
+ logger.info("defaultChannel synchronized from getChannel(): \(channelName)")
4036
+ }
4037
+
4038
+ func listChannels() -> ListChannels {
4039
+ let listChannels: ListChannels = ListChannels()
4040
+
4041
+ // Check if rate limit was exceeded
4042
+ if isRemoteBlocked() {
4043
+ let blocked = remoteBlockedClientError()
4044
+ logger.debug("Skipping listChannels due to remote block (\(blocked.error)).")
4045
+ listChannels.error = blocked.error
4046
+ return listChannels
4047
+ }
4048
+
4049
+ if (self.channelUrl).isEmpty {
4050
+ logger.error("Channel URL is not set")
4051
+ listChannels.error = "Channel URL is not set"
4052
+ return listChannels
4053
+ }
4054
+
4055
+ // Create info object and convert to query parameters
4056
+ let infoObject = self.createInfoObject()
4057
+ var urlComponents = URLComponents(string: self.channelUrl)
4058
+ var queryItems: [URLQueryItem] = urlComponents?.queryItems ?? []
4059
+
4060
+ for (key, value) in infoObject.toParameters() {
4061
+ queryItems.append(URLQueryItem(name: key, value: String(describing: value)))
4062
+ }
4063
+
4064
+ urlComponents?.queryItems = queryItems
4065
+
4066
+ guard let url = urlComponents?.url else {
4067
+ logger.error("Invalid channel URL")
4068
+ listChannels.error = "Invalid channel URL"
4069
+ return listChannels
4070
+ }
4071
+
4072
+ guard let request = createRequest(url: url, method: "GET", expectsJSONResponse: true) else {
4073
+ listChannels.error = "Invalid channel URL"
4074
+ return listChannels
4075
+ }
4076
+
4077
+ let result = performRequest(request, label: "listChannels")
4078
+
4079
+ let rateLimit = self.checkAndHandleRateLimitResponse(
4080
+ statusCode: result.response?.statusCode,
4081
+ data: result.data,
4082
+ response: result.response
4083
+ )
4084
+ if rateLimit.blocked {
4085
+ listChannels.error = rateLimit.error
4086
+ return listChannels
4087
+ }
4088
+
4089
+ if result.timedOut {
4090
+ listChannels.error = "Request timed out"
4091
+ return listChannels
4092
+ }
4093
+
4094
+ if let error = result.error {
4095
+ self.logger.error("Error listing channels")
4096
+ self.logger.debug("Error: \(error.localizedDescription)")
4097
+ listChannels.error = "Request failed: \(error.localizedDescription)"
4098
+ return listChannels
4099
+ }
4100
+
4101
+ guard let data = result.data else {
4102
+ listChannels.error = "Request failed: empty response"
4103
+ return listChannels
4104
+ }
4105
+
4106
+ guard let responseValue = try? JSONDecoder().decode(ListChannelsDec.self, from: data) else {
4107
+ listChannels.error = "decode_error"
4108
+ return listChannels
4109
+ }
4110
+
4111
+ let statusCode = result.response?.statusCode ?? 0
4112
+ if let error = responseValue.error {
4113
+ listChannels.error = error
4114
+ return listChannels
4115
+ }
4116
+
4117
+ if statusCode < 200 || statusCode >= 300 {
4118
+ listChannels.error = "response_error"
4119
+ return listChannels
4120
+ }
4121
+
4122
+ if let channels = responseValue.channels {
4123
+ listChannels.channels = channels.map { channel in
4124
+ var channelDict: [String: Any] = [:]
4125
+ channelDict["id"] = channel.id
4126
+ channelDict["name"] = channel.name ?? ""
4127
+ channelDict["public"] = channel.public ?? false
4128
+ channelDict["allow_self_set"] = channel.allow_self_set ?? false
4129
+ return channelDict
4130
+ }
4131
+ }
4132
+
4133
+ return listChannels
4134
+ }
4135
+
4136
+ private let operationQueue = OperationQueue()
4137
+
4138
+ private let manifestDownloadQueue: OperationQueue = {
4139
+ let queue = OperationQueue()
4140
+ queue.name = "com.capgo.manifestDownload"
4141
+ queue.qualityOfService = .userInitiated
4142
+ queue.maxConcurrentOperationCount = CapgoUpdater.manifestMaxConcurrentFiles
4143
+ return queue
4144
+ }()
4145
+
4146
+ func sendStats(action: String, versionName: String? = nil, oldVersionName: String? = "") {
4147
+ sendStatsWithMetadata(action: action, versionName: versionName, oldVersionName: oldVersionName, metadata: nil, onSent: nil)
4148
+ }
4149
+
4150
+ func sendStats(action: String, versionName: String?, oldVersionName: String?, metadata: [String: String]) {
4151
+ sendStatsWithMetadata(action: action, versionName: versionName, oldVersionName: oldVersionName, metadata: metadata, onSent: nil)
4152
+ }
4153
+
4154
+ func sendStats(action: String, versionName: String?, oldVersionName: String?, metadata: [String: String], onSent: @escaping () -> Void) {
4155
+ sendStatsWithMetadata(action: action, versionName: versionName, oldVersionName: oldVersionName, metadata: metadata, onSent: onSent)
4156
+ }
4157
+
4158
+ private func sendStatsWithMetadata(
4159
+ action: String,
4160
+ versionName: String?,
4161
+ oldVersionName: String?,
4162
+ metadata: [String: String]?,
4163
+ onSent: (() -> Void)?
4164
+ ) {
4165
+ if statsStopped {
4166
+ return
4167
+ }
4168
+
4169
+ if previewSession {
4170
+ logger.debug("Skipping sendStats during preview session.")
4171
+ return
4172
+ }
4173
+
4174
+ guard !statsUrl.isEmpty else {
4175
+ return
4176
+ }
4177
+
4178
+ let resolvedVersionName = versionName ?? getCurrentBundle().getVersionName()
4179
+ let info = createInfoObject()
4180
+
4181
+ let event = StatsEvent(
4182
+ platform: info.platform,
4183
+ device_id: info.device_id,
4184
+ app_id: info.app_id,
4185
+ custom_id: info.custom_id,
4186
+ version_build: info.version_build,
4187
+ version_code: info.version_code,
4188
+ version_os: info.version_os,
4189
+ version_name: resolvedVersionName,
4190
+ old_version_name: oldVersionName ?? "",
4191
+ plugin_version: info.plugin_version,
4192
+ is_emulator: info.is_emulator,
4193
+ is_prod: info.is_prod,
4194
+ installSource: info.installSource,
4195
+ action: action,
4196
+ channel: info.channel,
4197
+ defaultChannel: info.defaultChannel,
4198
+ key_id: info.key_id,
4199
+ metadata: metadata,
4200
+ timestamp: Int64(Date().timeIntervalSince1970 * 1000)
4201
+ )
4202
+
4203
+ statsQueueLock.lock()
4204
+ if statsStopped {
4205
+ statsQueueLock.unlock()
4206
+ return
4207
+ }
4208
+ if statsQueue.count >= CapgoUpdater.maxPendingStats {
4209
+ statsQueue.removeFirst(statsQueue.count - CapgoUpdater.maxPendingStats + 1)
4210
+ }
4211
+ statsQueue.append(QueuedStatsEvent(event: event, onSent: onSent))
4212
+ statsQueueLock.unlock()
4213
+
4214
+ ensureStatsTimerStarted()
4215
+ }
4216
+
4217
+ func restorePendingStats() {
4218
+ let fileURL = pendingStatsFileURL()
4219
+ guard FileManager.default.fileExists(atPath: fileURL.path),
4220
+ let data = try? Data(contentsOf: fileURL),
4221
+ let events = try? JSONDecoder().decode([StatsEvent].self, from: data) else {
4222
+ return
4223
+ }
4224
+
4225
+ statsQueueLock.lock()
4226
+ for event in events {
4227
+ if statsQueue.count >= CapgoUpdater.maxPendingStats {
4228
+ break
4229
+ }
4230
+ statsQueue.append(QueuedStatsEvent(event: event, onSent: nil))
4231
+ }
4232
+ let restoredCount = statsQueue.count
4233
+ statsQueueLock.unlock()
4234
+
4235
+ if restoredCount > 0 {
4236
+ logger.info("Restored \(restoredCount) pending stats events")
4237
+ ensureStatsTimerStarted()
4238
+ }
4239
+ }
4240
+
4241
+ func persistPendingStats() {
4242
+ persistStatsQueue()
4243
+ }
4244
+
4245
+ private func pendingStatsRootDirectory() -> URL {
4246
+ pendingStatsDirectoryOverride ?? libraryDir
4247
+ }
4248
+
4249
+ private func pendingStatsFileURL() -> URL {
4250
+ pendingStatsRootDirectory().appendingPathComponent(pendingStatsFileName)
4251
+ }
4252
+
4253
+ private func writePendingStatsFile(events: [StatsEvent]) {
4254
+ let fileURL = pendingStatsFileURL()
4255
+ let root = pendingStatsRootDirectory()
4256
+ do {
4257
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
4258
+ let data = try JSONEncoder().encode(events)
4259
+ let temp = root.appendingPathComponent("\(pendingStatsFileName).\(UUID().uuidString).tmp")
4260
+ defer { self.removeFileIfPresent(at: temp) }
4261
+ try data.write(to: temp)
4262
+ try replaceItemAtomically(at: fileURL, withItemAt: temp)
4263
+ var resourceURL = fileURL
4264
+ var values = URLResourceValues()
4265
+ values.isExcludedFromBackup = true
4266
+ try resourceURL.setResourceValues(values)
4267
+ } catch {
4268
+ logger.error("Failed to persist stats queue")
4269
+ logger.debug("Error: \(error.localizedDescription)")
4270
+ }
4271
+ }
4272
+
4273
+ private func persistStatsQueue() {
4274
+ statsPersistLock.lock()
4275
+ defer { statsPersistLock.unlock() }
4276
+ guard !statsStopped else { return }
4277
+ persistStatsQueueLocked()
4278
+ }
4279
+
4280
+ /// Caller must hold statsPersistLock, including for the final shutdown snapshot.
4281
+ private func persistStatsQueueLocked() {
4282
+ statsQueueLock.lock()
4283
+ var events = statsInFlight.map(\.event) + statsQueue.map(\.event)
4284
+ statsQueueLock.unlock()
4285
+ if events.count > CapgoUpdater.maxPendingStats {
4286
+ events = Array(events.suffix(CapgoUpdater.maxPendingStats))
4287
+ }
4288
+
4289
+ writePendingStatsFile(events: events)
4290
+ }
4291
+
4292
+ private func ensureStatsTimerStarted() {
4293
+ if statsStopped {
4294
+ return
4295
+ }
4296
+ DispatchQueue.main.async { [weak self] in
4297
+ guard let self = self, !self.statsStopped else { return }
4298
+ if self.statsFlushTimer == nil || !self.statsFlushTimer!.isValid {
4299
+ // Use closure-based timer to avoid strong reference cycle
4300
+ self.statsFlushTimer = Timer.scheduledTimer(
4301
+ withTimeInterval: CapgoUpdater.statsFlushInterval,
4302
+ repeats: true
4303
+ ) { [weak self] _ in
4304
+ self?.flushStatsQueue()
4305
+ }
4306
+ }
4307
+ }
4308
+ }
4309
+
4310
+ private func flushStatsQueue() {
4311
+ if statsStopped {
4312
+ return
4313
+ }
4314
+ // While Retry-After is active, keep stats queued and skip the network call.
4315
+ if isRemoteBlocked() {
4316
+ logger.debug("Deferring stats flush until Retry-After expires.")
4317
+ return
4318
+ }
4319
+
4320
+ statsQueueLock.lock()
4321
+ guard statsInFlight.isEmpty, !statsQueue.isEmpty else {
4322
+ statsQueueLock.unlock()
4323
+ return
4324
+ }
4325
+ let queuedEvents = statsQueue
4326
+ statsQueue.removeAll()
4327
+ statsInFlight = queuedEvents
4328
+ statsQueueLock.unlock()
4329
+ persistStatsQueue()
4330
+
4331
+ let eventsToSend = queuedEvents.map(\.event)
4332
+
4333
+ operationQueue.maxConcurrentOperationCount = 1
4334
+
4335
+ let operation = BlockOperation {
4336
+ let semaphore = DispatchSemaphore(value: 0)
4337
+ self.sendJSONPost(urlString: self.statsUrl, body: {
4338
+ try JSONEncoder().encode(eventsToSend)
4339
+ }, completion: { responseData, httpResponse, responseError in
4340
+ if self.abandonStoppedStatsFlush() {
4341
+ semaphore.signal()
4342
+ return
4343
+ }
4344
+ if self.checkAndHandleRateLimitResponse(statusCode: httpResponse?.statusCode, data: responseData, response: httpResponse).blocked {
4345
+ self.requeueStatsEvents(queuedEvents)
4346
+ semaphore.signal()
4347
+ return
4348
+ }
4349
+
4350
+ if let statusCode = httpResponse?.statusCode, !(200...299).contains(statusCode) {
4351
+ if CapgoUpdater.isTransientStatsFailure(statusCode) {
4352
+ self.requeueStatsEvents(queuedEvents)
4353
+ self.logger.error("Error sending stats batch")
4354
+ self.logger.debug("Retrying later, response code: \(statusCode)")
4355
+ } else {
4356
+ self.clearStatsInFlight()
4357
+ self.logger.error("Dropping stats batch after permanent error")
4358
+ self.logger.debug("Response code: \(statusCode)")
4359
+ }
4360
+ semaphore.signal()
4361
+ return
4362
+ }
4363
+
4364
+ if let error = responseError {
4365
+ self.requeueStatsEvents(queuedEvents)
4366
+ self.logger.error("Error sending stats batch")
4367
+ self.logger.debug("Response: nil, Error: \(error.localizedDescription)")
4368
+ } else {
4369
+ self.clearStatsInFlight()
4370
+ self.logger.info("Stats batch sent successfully")
4371
+ self.logger.debug("Sent \(eventsToSend.count) events")
4372
+ self.runStatsCallbacks(queuedEvents)
4373
+ }
4374
+ semaphore.signal()
4375
+ })
4376
+ semaphore.wait()
4377
+ if !self.statsStopped {
4378
+ self.persistStatsQueue()
4379
+ }
4380
+ }
4381
+ operationQueue.addOperation(operation)
4382
+ }
4383
+
4384
+ private func abandonStoppedStatsFlush() -> Bool {
4385
+ statsStopped
4386
+ }
4387
+
4388
+ /// Only 429, request timeout and 5xx are worth retrying; other 4xx are permanent rejections.
4389
+ private static func isTransientStatsFailure(_ statusCode: Int) -> Bool {
4390
+ return statusCode == 429 || statusCode == 408 || statusCode >= 500
4391
+ }
4392
+
4393
+ private func runStatsCallbacks(_ sentEvents: [QueuedStatsEvent]) {
4394
+ for sentEvent in sentEvents {
4395
+ sentEvent.onSent?()
4396
+ }
4397
+ }
4398
+
4399
+ private func requeueStatsEvents(_ events: [QueuedStatsEvent]) {
4400
+ guard !statsStopped, !events.isEmpty else { return }
4401
+ statsQueueLock.lock()
4402
+ statsInFlight.removeAll()
4403
+ statsQueue.insert(contentsOf: events, at: 0)
4404
+ if statsQueue.count > CapgoUpdater.maxPendingStats {
4405
+ statsQueue.removeFirst(statsQueue.count - CapgoUpdater.maxPendingStats)
4406
+ }
4407
+ statsQueueLock.unlock()
4408
+ persistStatsQueue()
4409
+ ensureStatsTimerStarted()
4410
+ }
4411
+
4412
+ private func clearStatsInFlight() {
4413
+ statsQueueLock.lock()
4414
+ statsInFlight.removeAll()
4415
+ statsQueueLock.unlock()
4416
+ }
4417
+
4418
+ public func getBundleInfo(id: String?) -> BundleInfo {
4419
+ var trueId = BundleInfo.VERSION_UNKNOWN
4420
+ if id != nil {
4421
+ trueId = id!
4422
+ }
4423
+ let result: BundleInfo
4424
+ if BundleInfo.ID_BUILTIN == trueId {
4425
+ result = BundleInfo(id: trueId, version: self.versionBuild, status: BundleStatus.SUCCESS, checksum: "")
4426
+ } else if BundleInfo.VERSION_UNKNOWN == trueId {
4427
+ result = BundleInfo(id: trueId, version: "", status: BundleStatus.ERROR, checksum: "")
4428
+ } else {
4429
+ do {
4430
+ result = try UserDefaults.standard.getObj(forKey: "\(trueId)\(self.INFO_SUFFIX)", castTo: BundleInfo.self)
4431
+ } catch {
4432
+ logger.error("Failed to parse bundle info")
4433
+ logger.debug("Bundle ID: \(trueId), Error: \(error.localizedDescription)")
4434
+ result = BundleInfo(id: trueId, version: "", status: BundleStatus.PENDING, checksum: "")
4435
+ }
4436
+ }
4437
+ return result
4438
+ }
4439
+
4440
+ public func getBundleInfoByVersionName(version: String) -> BundleInfo? {
4441
+ let installed: [BundleInfo] = self.list()
4442
+ for i in installed {
4443
+ if i.getVersionName() == version {
4444
+ return i
4445
+ }
4446
+ }
4447
+ return nil
4448
+ }
4449
+
4450
+ private func removeBundleInfo(id: String) {
4451
+ self.saveBundleInfo(id: id, bundle: nil)
4452
+ }
4453
+
4454
+ @discardableResult
4455
+ public func saveBundleInfo(id: String, bundle: BundleInfo?) -> Bool {
4456
+ if bundle != nil && (bundle!.isBuiltin() || bundle!.isUnknown()) {
4457
+ logger.info("Not saving info for bundle [\(id)] \(bundle?.toString() ?? "")")
4458
+ return false
4459
+ }
4460
+ if bundle == nil {
4461
+ logger.info("Removing info for bundle [\(id)]")
4462
+ UserDefaults.standard.removeObject(forKey: "\(id)\(self.INFO_SUFFIX)")
4463
+ return true
4464
+ }
4465
+ let update = bundle!.setId(id: id)
4466
+ logger.info("Storing info for bundle [\(id)] \(update.toString())")
4467
+ do {
4468
+ try UserDefaults.standard.setObj(update, forKey: "\(id)\(self.INFO_SUFFIX)")
4469
+ return true
4470
+ } catch {
4471
+ logger.error("Failed to save bundle info")
4472
+ logger.debug("Bundle ID: \(id), Error: \(error.localizedDescription)")
4473
+ return false
4474
+ }
4475
+ }
4476
+
4477
+ private func setBundleStatus(id: String, status: BundleStatus) {
4478
+ logger.info("Setting status for bundle [\(id)] to \(status)")
4479
+ let info = self.getBundleInfo(id: id)
4480
+ self.saveBundleInfo(id: id, bundle: info.setStatus(status: status.storedValue))
4481
+ }
4482
+
4483
+ public func getCurrentBundle() -> BundleInfo {
4484
+ return self.getBundleInfo(id: self.getCurrentBundleId())
4485
+ }
4486
+
4487
+ public func getCurrentBundleId() -> String {
4488
+ guard let bundlePath: String = UserDefaults.standard.string(forKey: self.CAP_SERVER_PATH) else {
4489
+ return BundleInfo.ID_BUILTIN
4490
+ }
4491
+ if (bundlePath).isEmpty {
4492
+ return BundleInfo.ID_BUILTIN
4493
+ }
4494
+ let bundleID: String = bundlePath.components(separatedBy: "/").last ?? bundlePath
4495
+ return bundleID
4496
+ }
4497
+
4498
+ public func isUsingBuiltin() -> Bool {
4499
+ return (UserDefaults.standard.string(forKey: self.CAP_SERVER_PATH) ?? "") == self.DEFAULT_FOLDER
4500
+ }
4501
+
4502
+ public func getFallbackBundle() -> BundleInfo {
4503
+ let id: String = UserDefaults.standard.string(forKey: self.FALLBACK_VERSION) ?? BundleInfo.ID_BUILTIN
4504
+ return self.getBundleInfo(id: id)
4505
+ }
4506
+
4507
+ private func setFallbackBundle(fallback: BundleInfo?) {
4508
+ UserDefaults.standard.set(fallback == nil ? BundleInfo.ID_BUILTIN : fallback!.getId(), forKey: self.FALLBACK_VERSION)
4509
+ UserDefaults.standard.synchronize()
4510
+ }
4511
+
4512
+ public func getNextBundle() -> BundleInfo? {
4513
+ let id: String? = UserDefaults.standard.string(forKey: self.NEXT_VERSION)
4514
+ return self.getBundleInfo(id: id)
4515
+ }
4516
+
4517
+ /// Clears the stored next bundle when it is already the running bundle, so nothing stays pending.
4518
+ @discardableResult
4519
+ public func clearNextBundleIfCurrent() -> Bool {
4520
+ guard let next = self.getNextBundle(), !next.isUnknown(), next.getId() == self.getCurrentBundle().getId() else {
4521
+ return false
4522
+ }
4523
+ logger?.info("Next bundle \(next.getId()) is already the current bundle. Clearing next.")
4524
+ _ = self.setNextBundle(next: Optional<String>.none)
4525
+ return true
4526
+ }
4527
+
4528
+ public func getPreviewFallbackBundle() -> BundleInfo? {
4529
+ guard let id = UserDefaults.standard.string(forKey: self.PREVIEW_FALLBACK_VERSION) else {
4530
+ return nil
4531
+ }
4532
+ let bundle = self.getBundleInfo(id: id)
4533
+ if !bundle.isBuiltin() && !self.bundleExists(id: id) {
4534
+ _ = self.setPreviewFallbackBundle(fallback: nil)
4535
+ return nil
4536
+ }
4537
+ return bundle
4538
+ }
4539
+
4540
+ public func setPreviewFallbackBundle(fallback: String?) -> Bool {
4541
+ guard let fallbackId = fallback else {
4542
+ UserDefaults.standard.removeObject(forKey: self.PREVIEW_FALLBACK_VERSION)
4543
+ UserDefaults.standard.synchronize()
4544
+ return true
4545
+ }
4546
+ let newBundle: BundleInfo = self.getBundleInfo(id: fallbackId)
4547
+ if !newBundle.isBuiltin() && !self.bundleExists(id: fallbackId) {
4548
+ return false
4549
+ }
4550
+ UserDefaults.standard.set(fallbackId, forKey: self.PREVIEW_FALLBACK_VERSION)
4551
+ UserDefaults.standard.synchronize()
4552
+ return true
4553
+ }
4554
+
4555
+ public func setNextBundle(next: String?) -> Bool {
4556
+ guard let nextId: String = next else {
4557
+ UserDefaults.standard.removeObject(forKey: self.NEXT_VERSION)
4558
+ UserDefaults.standard.synchronize()
4559
+ return false
4560
+ }
4561
+ let newBundle: BundleInfo = self.getBundleInfo(id: nextId)
4562
+ if !newBundle.isBuiltin() && !self.bundleExists(id: nextId) {
4563
+ return false
4564
+ }
4565
+ UserDefaults.standard.set(nextId, forKey: self.NEXT_VERSION)
4566
+ UserDefaults.standard.synchronize()
4567
+ self.setBundleStatus(id: nextId, status: BundleStatus.PENDING)
4568
+ self.sendStats(action: "set_next", versionName: newBundle.getVersionName(), oldVersionName: self.getCurrentBundle().getVersionName())
4569
+ self.notifyListeners("setNext", ["bundle": newBundle.toJSON()])
4570
+ return true
4571
+ }
4572
+ }