@capgo/capacitor-updater 8.54.2 → 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 (45) hide show
  1. package/CapgoCapacitorUpdater.podspec +2 -2
  2. package/Package.swift +3 -4
  3. package/README.md +162 -417
  4. package/android/build.gradle +7 -7
  5. package/android/consumer-rules.pro +48 -0
  6. package/android/proguard-rules.pro +1 -23
  7. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +1420 -404
  8. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +1100 -308
  9. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +102 -65
  10. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +155 -18
  11. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +22 -2
  12. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +82 -21
  13. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
  14. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -0
  15. package/dist/docs.json +44 -566
  16. package/dist/esm/definitions.d.ts +97 -215
  17. package/dist/esm/definitions.js.map +1 -1
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +197 -84
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +402 -139
  20. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +81 -55
  21. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +24 -0
  22. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +2 -1
  23. package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
  24. package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
  25. package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
  26. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +3905 -0
  27. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  28. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
  29. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
  30. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -0
  31. package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
  32. package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
  33. package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
  34. package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
  35. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1095 -0
  36. package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
  37. package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
  38. package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
  39. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +192 -0
  40. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  41. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -0
  42. package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
  43. package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
  44. package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
  45. package/package.json +15 -13
@@ -48,11 +48,16 @@ import UIKit
48
48
  public var previewSession = false
49
49
  public var publicKey: String = ""
50
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
+
51
54
  public var httpsOnly: Bool = true {
52
55
  didSet { redirectPolicy.httpsOnly = httpsOnly }
53
56
  }
54
- /// When true a bundle whose version is lower than the native app version is refused. Config `builtinMinimum`.
55
- public var builtinMinimum: Bool = false
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?
56
61
  /// Error raised when `httpsOnly` is set and a URL is not https.
57
62
  public static func httpsOnlyError(_ url: URL) -> NSError {
58
63
  return NSError(
@@ -107,6 +112,8 @@ import UIKit
107
112
  private static let statsFlushInterval: TimeInterval = 1.0
108
113
  private static let maxPendingStats = 200
109
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?
110
117
 
111
118
  private struct QueuedStatsEvent {
112
119
  let event: StatsEvent
@@ -219,6 +226,8 @@ import UIKit
219
226
  let fileName: String
220
227
  let downloadUrl: String
221
228
  let finalFileHash: String
229
+ /// SHA-256 of the encrypted bytes from the signed file_hash; `nil` for unencrypted manifests.
230
+ let ciphertextHash: String?
222
231
  let isBrotli: Bool
223
232
  let destFileName: String
224
233
  let destFilePath: URL
@@ -294,6 +303,15 @@ import UIKit
294
303
  self?.logger?.error("Blocked redirect to a non-https URL (httpsOnly, or allowHttpsToHttpRedirect is false)")
295
304
  self?.logger?.debug("Redirect from \(source?.absoluteString ?? "") to \(target?.absoluteString ?? "")")
296
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
+ }
297
315
  let session = URLSession(configuration: configuration, delegate: redirectPolicy, delegateQueue: nil)
298
316
  cachedUrlSession = session
299
317
  return session
@@ -301,6 +319,8 @@ import UIKit
301
319
 
302
320
  /// Owned separately from `CapgoUpdater` because URLSession retains its delegate strongly.
303
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()
304
324
 
305
325
  /// Follow redirects from HTTPS to plain HTTP. Off by default so a redirect can never downgrade updater traffic.
306
326
  public var allowHttpsToHttpRedirect: Bool {
@@ -341,7 +361,13 @@ import UIKit
341
361
  }
342
362
  let task = self.urlSession.dataTask(with: request) { data, response, error in
343
363
  let httpResponse = response as? HTTPURLResponse
344
- let body = (data?.isEmpty ?? true) ? nil : data
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
+ }
345
371
  let resultError: Error?
346
372
  if let error {
347
373
  resultError = NetworkError.sessionTaskFailed(error)
@@ -468,11 +494,32 @@ import UIKit
468
494
  return RequestResult(data: responseData, response: httpResponse, error: requestError, timedOut: timedOut)
469
495
  }
470
496
 
471
- func performDownloadRequest(_ request: URLRequest, label: String) -> DownloadRequestResult {
472
- performDownloadRequest(request, label: label, resumeData: nil)
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
473
514
  }
474
515
 
475
- func performDownloadRequest(_ request: URLRequest, label: String, resumeData: Data?) -> DownloadRequestResult {
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 {
476
523
  if let schemeError = checkAllowedScheme(request.url) {
477
524
  return DownloadRequestResult(fileURL: nil, response: nil, error: schemeError, timedOut: false)
478
525
  }
@@ -499,9 +546,7 @@ import UIKit
499
546
  withIntermediateDirectories: true,
500
547
  attributes: nil
501
548
  )
502
- if fileManager.fileExists(atPath: temporaryDownloadURL.path) {
503
- try fileManager.removeItem(at: temporaryDownloadURL)
504
- }
549
+ self.removeFileIfPresent(at: temporaryDownloadURL)
505
550
  try fileManager.moveItem(at: location, to: temporaryDownloadURL)
506
551
  movedFileURL = temporaryDownloadURL
507
552
  } catch {
@@ -517,8 +562,57 @@ import UIKit
517
562
  semaphore.signal()
518
563
  }
519
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
520
568
  let downloadTask = resumeData.map { self.urlSession.downloadTask(withResumeData: $0, completionHandler: completion) }
521
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
+ }
522
616
  downloadTask.resume()
523
617
 
524
618
  if semaphore.wait(timeout: .now() + waitTimeout) == .timedOut {
@@ -636,9 +730,7 @@ import UIKit
636
730
  return
637
731
  }
638
732
 
639
- if fileManager.fileExists(atPath: tempPath.path) {
640
- try fileManager.removeItem(at: tempPath)
641
- }
733
+ removeFileIfPresent(at: tempPath)
642
734
  try fileManager.moveItem(at: downloadedFileURL, to: tempPath)
643
735
  }
644
736
 
@@ -670,11 +762,12 @@ import UIKit
670
762
 
671
763
  public func shutdown() {
672
764
  statsPersistLock.lock()
765
+ defer { statsPersistLock.unlock() }
766
+ guard !statsStopped else { return }
673
767
  statsStopped = true
674
- statsPersistLock.unlock()
675
768
  statsFlushTimer?.invalidate()
676
769
  statsFlushTimer = nil
677
- persistStatsQueue(force: true)
770
+ persistStatsQueueLocked()
678
771
  }
679
772
 
680
773
  private func calcTotalPercent(percent: Int, min: Int, max: Int) -> Int {
@@ -700,8 +793,10 @@ import UIKit
700
793
 
701
794
  /// `builtinMinimum`: refuse any bundle version lower than the native app version (`versionBuild`).
702
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.
703
797
  func requireVersionNotBelowBuiltin(_ version: String) throws {
704
798
  guard self.builtinMinimum else {
799
+ _ = self.recordVersionFloorRejection(nil)
705
800
  return
706
801
  }
707
802
  // Build metadata (+...) never takes part in ordering, and may contain dots the parser rejects.
@@ -709,6 +804,7 @@ import UIKit
709
804
  let nativeCore = String(self.versionBuild.split(separator: "+", maxSplits: 1).first ?? "")
710
805
  guard let parsedBundle = try? CapgoSemanticVersion(bundleCore),
711
806
  let parsedNative = try? CapgoSemanticVersion(nativeCore) else {
807
+ _ = self.recordVersionFloorRejection(nil)
712
808
  logger?.debug("builtinMinimum skipped: cannot parse bundle version \(version) or native version \(self.versionBuild)")
713
809
  return
714
810
  }
@@ -716,14 +812,27 @@ import UIKit
716
812
  let bundleVersion = CapgoSemanticVersion(major: parsedBundle.major, minor: parsedBundle.minor, patch: parsedBundle.patch)
717
813
  let nativeVersion = CapgoSemanticVersion(major: parsedNative.major, minor: parsedNative.minor, patch: parsedNative.patch)
718
814
  if bundleVersion < nativeVersion {
719
- logger?.error("Bundle version \(version) is below native version \(self.versionBuild) (builtinMinimum)")
720
- self.sendStats(action: "version_below_native", versionName: version)
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
+ }
721
820
  throw NSError(
722
821
  domain: "CapgoUpdater",
723
822
  code: 8,
724
- userInfo: [NSLocalizedDescriptionKey: "Bundle version \(version) is below native version \(self.versionBuild) (builtinMinimum)"]
823
+ userInfo: [NSLocalizedDescriptionKey: message]
725
824
  )
726
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
727
836
  }
728
837
 
729
838
  public func setPublicKey(_ publicKey: String) {
@@ -1833,48 +1942,91 @@ import UIKit
1833
1942
  }
1834
1943
 
1835
1944
  public func downloadManifest(manifest: [ManifestEntry], version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
1836
- let decryptionSession = CryptoCipher.DecryptionSession(publicKey: self.publicKey, sessionKey: sessionKey)
1837
- try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
1838
- try self.requireVersionNotBelowBuiltin(version)
1839
- for entry in manifest {
1840
- if let downloadUrl = entry.download_url, let url = URL(string: downloadUrl) {
1841
- try self.assertAllowedScheme(url)
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
1842
1981
  }
1982
+ hasError.value = true
1843
1983
  }
1844
- try self.runBeforeDownload()
1845
- let id = self.randomString(length: 10)
1846
- logger.info("downloadManifest start \(id)")
1847
- let destFolder = try self.getBundleDirectory(id: id)
1984
+
1985
+ let decryptionSession = CryptoCipher.DecryptionSession(publicKey: self.publicKey, sessionKey: sessionKey)
1848
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)
1849
2004
 
1850
- // Check disk space before starting manifest download (estimate 100KB per file, minimum 50MB)
1851
- let estimatedSize = Int64(max(manifest.count * 100 * 1024, 50 * 1024 * 1024))
1852
- try checkDiskSpace(estimatedSize: estimatedSize)
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)
1853
2008
 
1854
- try FileManager.default.createDirectory(at: cacheFolder, withIntermediateDirectories: true, attributes: nil)
1855
- cleanupOldManifestPartials()
1856
- try FileManager.default.createDirectory(at: destFolder, withIntermediateDirectories: true, attributes: nil)
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
+ }
1857
2016
 
1858
2017
  // Create and save BundleInfo before starting the download process
1859
2018
  let bundleInfo = BundleInfo(id: id, version: version, status: BundleStatus.DOWNLOADING, downloaded: Date(), checksum: "", link: link, comment: comment)
1860
2019
  self.saveBundleInfo(id: id, bundle: bundleInfo)
1861
2020
 
1862
2021
  // Send stats for manifest download start
1863
- self.sendStats(action: "download_manifest_start", versionName: version)
2022
+ self.sendStats(
2023
+ action: "download_manifest_start", versionName: version,
2024
+ oldVersionName: "", metadata: ["attempt_id": id]
2025
+ )
1864
2026
 
1865
2027
  // Notify the start of the download process
1866
2028
  self.notifyDownload(id: id, percent: 0, ignoreMultipleOfTen: true)
1867
2029
 
1868
- let totalFiles = manifest.count
1869
-
1870
- // Thread-safe counters for concurrent operations
1871
- let progressLock = NSLock()
1872
- var completedFiles = 0
1873
- var lastProgressPercent = -1
1874
- let hasError = AtomicBool(initialValue: false)
1875
- var downloadError: Error?
1876
- let errorLock = NSLock()
1877
-
1878
2030
  var tasks: [ManifestDownloadTask] = []
1879
2031
  var seenTargets = Set<String>()
1880
2032
 
@@ -1888,12 +2040,7 @@ import UIKit
1888
2040
  NSLocalizedDescriptionKey: "Manifest entry is missing file_name or download_url"
1889
2041
  ]
1890
2042
  )
1891
- errorLock.lock()
1892
- if downloadError == nil {
1893
- downloadError = error
1894
- }
1895
- errorLock.unlock()
1896
- hasError.value = true
2043
+ recordInvalidEntry(error, entry.file_name)
1897
2044
  logger.error("Manifest entry is missing file_name or download_url")
1898
2045
  continue
1899
2046
  }
@@ -1906,15 +2053,11 @@ import UIKit
1906
2053
  NSLocalizedDescriptionKey: "Manifest entry is missing file_hash for \(entry.file_name ?? "unknown")"
1907
2054
  ]
1908
2055
  )
1909
- errorLock.lock()
1910
- if downloadError == nil {
1911
- downloadError = error
1912
- }
1913
- errorLock.unlock()
1914
- hasError.value = true
2056
+ recordInvalidEntry(error, entry.file_name)
1915
2057
  continue
1916
2058
  }
1917
2059
  var fileHash = entryFileHash
2060
+ var ciphertextHash: String?
1918
2061
 
1919
2062
  // Decrypt checksum if needed (done before creating operation)
1920
2063
  if !self.publicKey.isEmpty {
@@ -1925,22 +2068,16 @@ import UIKit
1925
2068
  userInfo: [NSLocalizedDescriptionKey: "Session key required when public key is present"]
1926
2069
  )
1927
2070
  self.sendStats(action: "session_key_required", versionName: version)
1928
- errorLock.lock()
1929
- if downloadError == nil {
1930
- downloadError = error
1931
- }
1932
- errorLock.unlock()
1933
- hasError.value = true
2071
+ recordInvalidEntry(error, entry.file_name)
1934
2072
  logger.error("Public key present but no valid session key provided")
1935
2073
  continue
1936
2074
  }
1937
2075
  do {
1938
- fileHash = try CryptoCipher.decryptChecksum(checksum: fileHash, publicKey: self.publicKey)
2076
+ let signed = try CryptoCipher.decryptBundleChecksum(checksum: fileHash, publicKey: self.publicKey)
2077
+ fileHash = signed.plain
2078
+ ciphertextHash = signed.ciphertext
1939
2079
  } catch {
1940
- errorLock.lock()
1941
- downloadError = error
1942
- errorLock.unlock()
1943
- hasError.value = true
2080
+ recordInvalidEntry(error, entry.file_name)
1944
2081
  logger.error("Checksum decryption failed")
1945
2082
  logger.debug("Bundle: \(id), File: \(fileName), Error: \(error)")
1946
2083
  continue
@@ -1974,23 +2111,13 @@ import UIKit
1974
2111
  NSLocalizedDescriptionKey: "Duplicate manifest target path for \(fileName)"
1975
2112
  ]
1976
2113
  )
1977
- errorLock.lock()
1978
- if downloadError == nil {
1979
- downloadError = error
1980
- }
1981
- errorLock.unlock()
1982
- hasError.value = true
2114
+ recordInvalidEntry(error, entry.file_name)
1983
2115
  continue
1984
2116
  }
1985
2117
  } catch {
1986
2118
  logger.error("Invalid manifest file path: \(fileName)")
1987
2119
  self.sendStats(action: "manifest_path_fail", versionName: "\(version):\(fileName)")
1988
- errorLock.lock()
1989
- if downloadError == nil {
1990
- downloadError = error
1991
- }
1992
- errorLock.unlock()
1993
- hasError.value = true
2120
+ recordInvalidEntry(error, entry.file_name)
1994
2121
  continue
1995
2122
  }
1996
2123
 
@@ -1999,6 +2126,7 @@ import UIKit
1999
2126
  fileName: fileName,
2000
2127
  downloadUrl: downloadUrl,
2001
2128
  finalFileHash: finalFileHash,
2129
+ ciphertextHash: ciphertextHash,
2002
2130
  isBrotli: isBrotli,
2003
2131
  destFileName: destFileName,
2004
2132
  destFilePath: destFilePath,
@@ -2018,6 +2146,7 @@ import UIKit
2018
2146
  let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
2019
2147
  self.saveBundleInfo(id: id, bundle: errorBundle)
2020
2148
  removePartialManifestBundleDirectory(destFolder)
2149
+ reportFailure(resolvedError)
2021
2150
  throw resolvedError
2022
2151
  }
2023
2152
 
@@ -2035,6 +2164,8 @@ import UIKit
2035
2164
  self.saveBundleInfo(id: id, bundle: errorBundle)
2036
2165
  removePartialManifestBundleDirectory(destFolder)
2037
2166
  self.notifyDownload(id: id, percent: 0, bundle: errorBundle)
2167
+ recordInvalidEntry(error, task.fileName)
2168
+ reportFailure(error)
2038
2169
  throw error
2039
2170
  }
2040
2171
 
@@ -2074,8 +2205,11 @@ import UIKit
2074
2205
 
2075
2206
  } catch {
2076
2207
  errorLock.lock()
2208
+ failureStage = "process_file"
2209
+ failedFiles += 1
2077
2210
  if downloadError == nil {
2078
2211
  downloadError = error
2212
+ firstFile = task.fileName
2079
2213
  }
2080
2214
  errorLock.unlock()
2081
2215
  hasError.value = true
@@ -2100,6 +2234,7 @@ import UIKit
2100
2234
  let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
2101
2235
  self.saveBundleInfo(id: id, bundle: errorBundle)
2102
2236
  removePartialManifestBundleDirectory(destFolder)
2237
+ reportFailure(resolvedError)
2103
2238
  throw resolvedError
2104
2239
  }
2105
2240
 
@@ -2108,7 +2243,10 @@ import UIKit
2108
2243
  self.saveBundleInfo(id: id, bundle: updatedBundle)
2109
2244
 
2110
2245
  // Send stats for manifest download complete
2111
- self.sendStats(action: "download_manifest_complete", versionName: version)
2246
+ self.sendStats(
2247
+ action: "download_manifest_complete", versionName: version,
2248
+ oldVersionName: "", metadata: ["attempt_id": id]
2249
+ )
2112
2250
 
2113
2251
  self.notifyDownload(id: id, percent: 100, bundle: updatedBundle)
2114
2252
  logger.info("downloadManifest done \(id)")
@@ -2128,10 +2266,6 @@ import UIKit
2128
2266
  return
2129
2267
  } catch {
2130
2268
  guard attempt < 3 && Self.isRetryableManifestError(error) else {
2131
- // One failure stat per file, after the last attempt.
2132
- if Self.isManifestTransferError(error) {
2133
- self.sendStats(action: "download_manifest_file_fail", versionName: "\(version):\(task.fileName)")
2134
- }
2135
2269
  throw error
2136
2270
  }
2137
2271
  // Back off in short steps so a failed or cancelled manifest stops retrying promptly.
@@ -2144,11 +2278,15 @@ import UIKit
2144
2278
  }
2145
2279
 
2146
2280
  /// Transport errors arrive wrapped in NetworkError.sessionTaskFailed; classify the underlying error.
2147
- static func isRetryableManifestError(_ error: Error) -> Bool {
2281
+ static func manifestFailureCause(_ error: Error) -> NSError {
2148
2282
  if case let .sessionTaskFailed(underlying)? = error as? NetworkError {
2149
- return isRetryableManifestError(underlying)
2283
+ return manifestFailureCause(underlying)
2150
2284
  }
2151
- let failure = error as NSError
2285
+ return error as NSError
2286
+ }
2287
+
2288
+ static func isRetryableManifestError(_ error: Error) -> Bool {
2289
+ let failure = manifestFailureCause(error)
2152
2290
  if failure.domain == manifestResumeErrorDomain {
2153
2291
  return true
2154
2292
  }
@@ -2161,16 +2299,6 @@ import UIKit
2161
2299
  ].contains(failure.code)
2162
2300
  }
2163
2301
 
2164
- /// Failures that reach the server or network, as opposed to checksum, decryption or storage errors.
2165
- private static func isManifestTransferError(_ error: Error) -> Bool {
2166
- if error is NetworkError {
2167
- return true
2168
- }
2169
- let failure = error as NSError
2170
- return failure.domain == NSURLErrorDomain || failure.domain == "StatusCodeError" || failure.domain == manifestResumeErrorDomain ||
2171
- (failure.domain == "ManifestDownloadError" && failure.code == 3)
2172
- }
2173
-
2174
2302
  /// A resumed transfer that cannot be trusted: drop the partial and fetch the whole file on the next attempt.
2175
2303
  static let manifestResumeErrorDomain = "ManifestResumeError"
2176
2304
 
@@ -2302,11 +2430,15 @@ import UIKit
2302
2430
  try FileManager.default.copyItem(at: partialURL, to: work)
2303
2431
  workURL = work
2304
2432
  do {
2305
- try decryptionSession.decryptFile(filePath: work)
2433
+ try decryptionSession.decryptFile(filePath: work, expectedCiphertextSha256: task.ciphertextHash)
2306
2434
  } catch {
2307
2435
  try? FileManager.default.removeItem(at: partialURL)
2308
2436
  if resumed { throw Self.resumeVerificationError(error, fileName: fileName) }
2309
- self.sendStats(action: "decrypt_fail", versionName: version)
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
+ }
2310
2442
  throw error
2311
2443
  }
2312
2444
  source = work
@@ -2463,6 +2595,14 @@ import UIKit
2463
2595
  }
2464
2596
  }
2465
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
+
2466
2606
  /// Atomically try to copy a file from cache - returns true if successful, false if file doesn't exist or copy failed
2467
2607
  /// This handles the race condition where OS can delete cache files between exists() check and copy
2468
2608
  private func tryCopyFromCache(from source: URL, to destination: URL, expectedHash: String) -> Bool {
@@ -2640,17 +2780,19 @@ import UIKit
2640
2780
  return hasher.hex()
2641
2781
  }
2642
2782
 
2643
- /// Resolves the checksum a zip bundle must match: required, and RSA-decrypted when a public key is set.
2644
- func resolveExpectedBundleChecksum(_ checksum: String, versionName: String) throws -> String {
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 {
2645
2786
  if checksum.isEmpty {
2646
2787
  logger.error("No checksum provided")
2647
2788
  self.sendStats(action: "checksum_required", versionName: versionName)
2648
2789
  throw NSError(domain: "ChecksumError", code: 2, userInfo: [NSLocalizedDescriptionKey: "Checksum required"])
2649
2790
  }
2650
- return try CryptoCipher.decryptChecksum(checksum: checksum, publicKey: self.publicKey)
2791
+ return try CryptoCipher.decryptBundleChecksum(checksum: checksum, publicKey: self.publicKey)
2651
2792
  }
2652
2793
 
2653
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`).
2654
2796
  /// Prefer `downloadVerified`, which rejects a bad archive before extracting it.
2655
2797
  public func download(url: URL, version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
2656
2798
  return try self.downloadZip(url: url, version: version, sessionKey: sessionKey, link: link, comment: comment, expectedChecksum: nil)
@@ -2671,6 +2813,7 @@ import UIKit
2671
2813
  return try self.downloadZip(url: url, version: version, sessionKey: sessionKey, link: link, comment: comment, expectedChecksum: expectedChecksum)
2672
2814
  }
2673
2815
 
2816
+ /// Downloads, verifies, and extracts a zip bundle while emitting progress from 0% to 100%.
2674
2817
  private func downloadZip(
2675
2818
  url: URL,
2676
2819
  version: String,
@@ -2682,7 +2825,8 @@ import UIKit
2682
2825
  try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
2683
2826
  try self.requireVersionNotBelowBuiltin(version)
2684
2827
  try self.assertAllowedScheme(url)
2685
- let expectedHash = try expectedChecksum.map { try self.resolveExpectedBundleChecksum($0, versionName: version) }
2828
+ let expectedChecksums = try expectedChecksum.map { try self.resolveExpectedBundleChecksum($0, versionName: version) }
2829
+ let expectedHash = expectedChecksums?.plain
2686
2830
  try self.runBeforeDownload()
2687
2831
  let id: String = self.randomString(length: 10)
2688
2832
  // Each download uses its own temp files keyed by bundle ID to prevent collisions
@@ -2703,7 +2847,10 @@ import UIKit
2703
2847
  self.saveBundleInfo(id: id, bundle: bundleInfo)
2704
2848
 
2705
2849
  // Send stats for zip download start
2706
- self.sendStats(action: "download_zip_start", versionName: version)
2850
+ self.sendStats(
2851
+ action: "download_zip_start", versionName: version,
2852
+ oldVersionName: "", metadata: ["attempt_id": id]
2853
+ )
2707
2854
 
2708
2855
  // Opening connection for streaming the bytes
2709
2856
  if totalReceivedBytes == 0 {
@@ -2724,7 +2871,18 @@ import UIKit
2724
2871
  request.setValue("bytes=\(totalReceivedBytes)-", forHTTPHeaderField: "Range")
2725
2872
  }
2726
2873
 
2727
- let downloadResult = performDownloadRequest(request, label: "download \(version)")
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
+ }
2728
2886
  // Error responses (e.g. an HTTP 404 body) are also saved to a temp file; never leave them behind.
2729
2887
  defer {
2730
2888
  if let fileURL = downloadResult.fileURL {
@@ -2754,10 +2912,12 @@ import UIKit
2754
2912
  do {
2755
2913
  try storeDownloadedFile(downloadedFileURL, at: tempPath, existingBytes: totalReceivedBytes, response: downloadResult.response)
2756
2914
 
2915
+ progressLock.lock()
2757
2916
  if lastSentProgress < 70 {
2758
- self.notifyDownload(id: id, percent: 70, ignoreMultipleOfTen: true)
2759
2917
  lastSentProgress = 70
2918
+ self.notifyDownload(id: id, percent: 70, ignoreMultipleOfTen: true)
2760
2919
  }
2920
+ progressLock.unlock()
2761
2921
  self.logger.info("Download complete")
2762
2922
  } catch let error as NSError {
2763
2923
  mainError = error
@@ -2781,9 +2941,19 @@ import UIKit
2781
2941
 
2782
2942
  let finalPath = tempPath.deletingLastPathComponent().appendingPathComponent("\(id)")
2783
2943
  do {
2784
- try CryptoCipher.decryptFile(filePath: tempPath, publicKey: self.publicKey, sessionKey: sessionKey, version: version)
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
+ )
2785
2952
  try FileManager.default.moveItem(at: tempPath, to: finalPath)
2786
2953
  } catch {
2954
+ if case CryptoCipher.CiphertextChecksumError.mismatch = error {
2955
+ self.sendStats(action: "checksum_fail", versionName: version)
2956
+ }
2787
2957
  logger.error("Failed to decrypt file")
2788
2958
  logger.debug("Error: \(error)")
2789
2959
  self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
@@ -2835,7 +3005,10 @@ import UIKit
2835
3005
  self.cleanDownloadData(for: id)
2836
3006
 
2837
3007
  // Send stats for zip download complete
2838
- self.sendStats(action: "download_zip_complete", versionName: version)
3008
+ self.sendStats(
3009
+ action: "download_zip_complete", versionName: version,
3010
+ oldVersionName: "", metadata: ["attempt_id": id]
3011
+ )
2839
3012
 
2840
3013
  self.notifyDownload(id: id, percent: 100, bundle: info)
2841
3014
  logger.info("Downloading: 100% (complete)")
@@ -3376,7 +3549,7 @@ import UIKit
3376
3549
  return self.set(id: bundle.getId())
3377
3550
  }
3378
3551
 
3379
- private func bundleExists(id: String) -> Bool {
3552
+ func bundleExists(id: String) -> Bool {
3380
3553
  let destPersist: URL
3381
3554
  do {
3382
3555
  destPersist = try self.getBundleDirectory(id: id)
@@ -3397,6 +3570,7 @@ import UIKit
3397
3570
  return false
3398
3571
  }
3399
3572
 
3573
+ /// Activates a stored bundle only if it meets the native version floor. Builtin reset is always allowed.
3400
3574
  public func set(id: String) -> Bool {
3401
3575
  let newBundle: BundleInfo = self.getBundleInfo(id: id)
3402
3576
  if newBundle.isBuiltin() {
@@ -3404,6 +3578,11 @@ import UIKit
3404
3578
  return true
3405
3579
  }
3406
3580
  if bundleExists(id: id) {
3581
+ do {
3582
+ try self.requireVersionNotBelowBuiltin(newBundle.getVersionName())
3583
+ } catch {
3584
+ return false
3585
+ }
3407
3586
  let currentBundleName = self.getCurrentBundle().getVersionName()
3408
3587
  guard let bundleDir = try? self.getBundleDirectory(id: id) else {
3409
3588
  self.setBundleStatus(id: id, status: BundleStatus.ERROR)
@@ -3420,15 +3599,19 @@ import UIKit
3420
3599
  return false
3421
3600
  }
3422
3601
 
3602
+ /// Stages a pending bundle without finalizing it, checking the version floor before changing the active path.
3423
3603
  func stagePendingReload(bundle: BundleInfo) -> Bool {
3424
3604
  guard !bundle.isBuiltin(), bundleExists(id: bundle.getId()) else {
3425
3605
  return false
3426
3606
  }
3427
- guard let bundleDir = try? self.getBundleDirectory(id: bundle.getId()) else {
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 {
3428
3613
  return false
3429
3614
  }
3430
- self.setCurrentBundle(bundle: bundleDir.path)
3431
- return true
3432
3615
  }
3433
3616
 
3434
3617
  /// Points the current bundle back at `bundle` without sending stats, after an
@@ -3436,8 +3619,9 @@ import UIKit
3436
3619
  func restoreCurrentBundle(_ bundle: BundleInfo) {
3437
3620
  if bundle.isBuiltin() {
3438
3621
  self.setCurrentBundle(bundle: "")
3439
- } else {
3440
- _ = self.stagePendingReload(bundle: bundle)
3622
+ } else if bundleExists(id: bundle.getId()),
3623
+ let bundleDir = try? self.getBundleDirectory(id: bundle.getId()) {
3624
+ self.setCurrentBundle(bundle: bundleDir.path)
3441
3625
  }
3442
3626
  }
3443
3627
 
@@ -3541,7 +3725,12 @@ import UIKit
3541
3725
  self.setBundleStatus(id: bundle.getId(), status: BundleStatus.ERROR)
3542
3726
  }
3543
3727
 
3544
- func unsetChannel(defaultChannelKey: String, configDefaultChannel: String, allowSetDefaultChannel: Bool) -> SetChannel {
3728
+ func unsetChannel(
3729
+ defaultChannelKey: String,
3730
+ defaultChannelFromSetChannelKey: String,
3731
+ configDefaultChannel: String,
3732
+ allowSetDefaultChannel: Bool
3733
+ ) -> SetChannel {
3545
3734
  let setChannel: SetChannel = SetChannel()
3546
3735
 
3547
3736
  if !allowSetDefaultChannel {
@@ -3553,6 +3742,7 @@ import UIKit
3553
3742
 
3554
3743
  // Clear persisted defaultChannel and revert to config value
3555
3744
  UserDefaults.standard.removeObject(forKey: defaultChannelKey)
3745
+ UserDefaults.standard.removeObject(forKey: defaultChannelFromSetChannelKey)
3556
3746
  UserDefaults.standard.synchronize()
3557
3747
  self.defaultChannel = configDefaultChannel
3558
3748
  self.logger.info("Persisted defaultChannel cleared, reverted to config value: \(configDefaultChannel)")
@@ -3565,6 +3755,7 @@ import UIKit
3565
3755
  func setChannel(
3566
3756
  channel: String,
3567
3757
  defaultChannelKey: String,
3758
+ defaultChannelFromSetChannelKey: String,
3568
3759
  allowSetDefaultChannel: Bool,
3569
3760
  configDefaultChannel: String = ""
3570
3761
  ) -> SetChannel {
@@ -3651,6 +3842,7 @@ import UIKit
3651
3842
  setChannel.error = error
3652
3843
  } else if responseValue.unset == true {
3653
3844
  UserDefaults.standard.removeObject(forKey: defaultChannelKey)
3845
+ UserDefaults.standard.removeObject(forKey: defaultChannelFromSetChannelKey)
3654
3846
  UserDefaults.standard.synchronize()
3655
3847
  self.defaultChannel = configDefaultChannel
3656
3848
  self.logger.info("Public channel requested, channel override removed")
@@ -3661,6 +3853,7 @@ import UIKit
3661
3853
  } else {
3662
3854
  self.defaultChannel = channel
3663
3855
  UserDefaults.standard.set(channel, forKey: defaultChannelKey)
3856
+ UserDefaults.standard.set(true, forKey: defaultChannelFromSetChannelKey)
3664
3857
  UserDefaults.standard.synchronize()
3665
3858
  self.logger.info("defaultChannel persisted locally: \(channel)")
3666
3859
 
@@ -3670,7 +3863,11 @@ import UIKit
3670
3863
  return setChannel
3671
3864
  }
3672
3865
 
3673
- func getChannel(defaultChannelKey: String? = nil) -> GetChannel {
3866
+ func getChannel(
3867
+ defaultChannelKey: String? = nil,
3868
+ defaultChannelFromSetChannelKey: String? = nil,
3869
+ configDefaultChannel: String = ""
3870
+ ) -> GetChannel {
3674
3871
  let getChannel: GetChannel = GetChannel()
3675
3872
  // Check if rate limit was exceeded
3676
3873
  if isRemoteBlocked() {
@@ -3762,21 +3959,77 @@ import UIKit
3762
3959
  getChannel.message = responseValue.message ?? ""
3763
3960
  getChannel.channel = responseValue.channel ?? ""
3764
3961
  getChannel.allowSet = responseValue.allowSet ?? true
3765
- persistDefaultChannelFromResponse(channel: responseValue.channel, defaultChannelKey: defaultChannelKey)
3962
+ persistDefaultChannelFromResponse(
3963
+ channel: responseValue.channel,
3964
+ status: responseValue.status,
3965
+ defaultChannelKey: defaultChannelKey,
3966
+ defaultChannelFromSetChannelKey: defaultChannelFromSetChannelKey,
3967
+ configDefaultChannel: configDefaultChannel
3968
+ )
3766
3969
  }
3767
3970
  return getChannel
3768
3971
  }
3769
3972
 
3770
- func persistDefaultChannelFromResponse(channel: String?, defaultChannelKey: String?) {
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
+ }
3771
4013
  guard let channelName = channel?.trimmingCharacters(in: .whitespacesAndNewlines),
3772
4014
  !channelName.isEmpty,
3773
4015
  channelName != BundleInfo.ID_BUILTIN else {
3774
4016
  return
3775
4017
  }
3776
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
+
3777
4027
  self.defaultChannel = channelName
3778
4028
  if let defaultChannelKey, !defaultChannelKey.isEmpty {
3779
4029
  UserDefaults.standard.set(channelName, forKey: defaultChannelKey)
4030
+ if let defaultChannelFromSetChannelKey, !defaultChannelFromSetChannelKey.isEmpty, !preserveSetChannelMarker {
4031
+ UserDefaults.standard.set(false, forKey: defaultChannelFromSetChannelKey)
4032
+ }
3780
4033
  UserDefaults.standard.synchronize()
3781
4034
  }
3782
4035
  logger.info("defaultChannel synchronized from getChannel(): \(channelName)")
@@ -3989,33 +4242,24 @@ import UIKit
3989
4242
  persistStatsQueue()
3990
4243
  }
3991
4244
 
3992
- private func pendingStatsFileURL() -> URL {
3993
- libraryDir.appendingPathComponent(pendingStatsFileName)
4245
+ private func pendingStatsRootDirectory() -> URL {
4246
+ pendingStatsDirectoryOverride ?? libraryDir
3994
4247
  }
3995
4248
 
3996
- private func persistStatsQueue(force: Bool = false) {
3997
- statsPersistLock.lock()
3998
- defer { statsPersistLock.unlock() }
3999
- if statsStopped && !force {
4000
- return
4001
- }
4002
-
4003
- statsQueueLock.lock()
4004
- var events = statsInFlight.map(\.event) + statsQueue.map(\.event)
4005
- statsQueueLock.unlock()
4006
- if events.count > CapgoUpdater.maxPendingStats {
4007
- events = Array(events.suffix(CapgoUpdater.maxPendingStats))
4008
- }
4249
+ private func pendingStatsFileURL() -> URL {
4250
+ pendingStatsRootDirectory().appendingPathComponent(pendingStatsFileName)
4251
+ }
4009
4252
 
4253
+ private func writePendingStatsFile(events: [StatsEvent]) {
4010
4254
  let fileURL = pendingStatsFileURL()
4011
- if events.isEmpty {
4012
- try? FileManager.default.removeItem(at: fileURL)
4013
- return
4014
- }
4015
-
4255
+ let root = pendingStatsRootDirectory()
4016
4256
  do {
4257
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
4017
4258
  let data = try JSONEncoder().encode(events)
4018
- try data.write(to: fileURL, options: .atomic)
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)
4019
4263
  var resourceURL = fileURL
4020
4264
  var values = URLResourceValues()
4021
4265
  values.isExcludedFromBackup = true
@@ -4026,6 +4270,25 @@ import UIKit
4026
4270
  }
4027
4271
  }
4028
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
+
4029
4292
  private func ensureStatsTimerStarted() {
4030
4293
  if statsStopped {
4031
4294
  return