@capgo/capacitor-updater 6.51.23 → 6.53.0

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 (29) hide show
  1. package/CapgoCapacitorUpdater.podspec +0 -3
  2. package/Package.swift +3 -11
  3. package/README.md +201 -66
  4. package/android/build.gradle +2 -3
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +593 -176
  6. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +775 -162
  7. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +2 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +226 -106
  9. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +107 -30
  10. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +325 -0
  11. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +63 -4
  12. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  14. package/dist/docs.json +394 -27
  15. package/dist/esm/definitions.d.ts +220 -7
  16. package/dist/esm/definitions.js.map +1 -1
  17. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +104 -52
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +472 -144
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  20. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +392 -82
  21. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +2 -1
  22. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +204 -93
  23. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +75 -5
  24. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  25. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +53 -0
  26. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +5 -2
  27. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  28. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  29. package/package.json +7 -3
@@ -5,8 +5,6 @@
5
5
  */
6
6
 
7
7
  import Foundation
8
- import ZIPFoundation
9
- import Alamofire
10
8
  import Compression
11
9
  import UIKit
12
10
 
@@ -120,7 +118,7 @@ import UIKit
120
118
  let timedOut: Bool
121
119
  }
122
120
 
123
- private struct DownloadRequestResult {
121
+ struct DownloadRequestResult {
124
122
  let fileURL: URL?
125
123
  let response: HTTPURLResponse?
126
124
  let error: Error?
@@ -194,6 +192,9 @@ import UIKit
194
192
  }
195
193
 
196
194
  private func isTimedOutError(_ error: Error?) -> Bool {
195
+ if case let .sessionTaskFailed(underlying)? = error as? NetworkError {
196
+ return isTimedOutError(underlying)
197
+ }
197
198
  guard let nsError = error as NSError? else {
198
199
  return false
199
200
  }
@@ -201,13 +202,49 @@ import UIKit
201
202
  return nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorTimedOut
202
203
  }
203
204
 
205
+ /// Errors produced by the URLSession transport. Descriptions intentionally match the messages the
206
+ /// previous Alamofire transport surfaced so logs and JS-facing error strings stay the same.
207
+ enum NetworkError: LocalizedError {
208
+ case sessionTaskFailed(Error)
209
+ case emptyResponse
210
+ case invalidURL(String)
211
+ case bodyEncodingFailed(Error?)
212
+ case downloadedFileMoveFailed(Error, source: URL, destination: URL)
213
+
214
+ var errorDescription: String? {
215
+ switch self {
216
+ case let .sessionTaskFailed(error):
217
+ return "URLSessionTask failed with error: \(error.localizedDescription)"
218
+ case .emptyResponse:
219
+ return "Response could not be serialized, input data was nil or zero length."
220
+ case let .invalidURL(url):
221
+ return "URL is not valid: \(url)"
222
+ case let .bodyEncodingFailed(error):
223
+ return "JSON could not be encoded because of error:\n\(error?.localizedDescription ?? "Invalid JSON object provided for parameter or object encoding.")"
224
+ case let .downloadedFileMoveFailed(error, source, destination):
225
+ return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)"
226
+ }
227
+ }
228
+ }
229
+
230
+ /// Mirrors Alamofire's `responseData` serializer: an empty body is an error unless the status allows it.
231
+ static func emptyResponseError(data: Data?, response: HTTPURLResponse?, method: String?) -> Error? {
232
+ if let data, !data.isEmpty {
233
+ return nil
234
+ }
235
+ if method?.uppercased() == "HEAD" || [204, 205].contains(response?.statusCode ?? 0) {
236
+ return nil
237
+ }
238
+ return NetworkError.emptyResponse
239
+ }
240
+
204
241
  // lazy var is not thread-safe; concurrent manifest downloads can race first access when statsUrl is empty.
205
- private var _alamofireSession: Session?
206
- private let alamofireSessionLock = NSLock()
207
- private var alamofireSession: Session {
208
- alamofireSessionLock.lock()
209
- defer { alamofireSessionLock.unlock() }
210
- if let session = _alamofireSession {
242
+ private var cachedUrlSession: URLSession?
243
+ private let urlSessionLock = NSLock()
244
+ private var urlSession: URLSession {
245
+ urlSessionLock.lock()
246
+ defer { urlSessionLock.unlock() }
247
+ if let session = cachedUrlSession {
211
248
  return session
212
249
  }
213
250
  let configuration = URLSessionConfiguration.ephemeral
@@ -217,10 +254,92 @@ import UIKit
217
254
  configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
218
255
  configuration.urlCache = nil
219
256
  configuration.httpMaximumConnectionsPerHost = Self.manifestMaxConcurrentFiles
220
- let session = Session(configuration: configuration)
221
- _alamofireSession = session
257
+ redirectPolicy.onBlockedRedirect = { [weak self] source, target in
258
+ self?.logger?.error("Blocked HTTPS to HTTP redirect; set allowHttpsToHttpRedirect to true to allow it")
259
+ self?.logger?.debug("Redirect from \(source?.absoluteString ?? "") to \(target?.absoluteString ?? "")")
260
+ }
261
+ let session = URLSession(configuration: configuration, delegate: redirectPolicy, delegateQueue: nil)
262
+ cachedUrlSession = session
222
263
  return session
223
264
  }
265
+
266
+ /// Owned separately from `CapgoUpdater` because URLSession retains its delegate strongly.
267
+ private let redirectPolicy = RedirectPolicyDelegate()
268
+
269
+ /// Follow redirects from HTTPS to plain HTTP. Off by default so a redirect can never downgrade updater traffic.
270
+ public var allowHttpsToHttpRedirect: Bool {
271
+ get { redirectPolicy.allowHttpsToHttpRedirect }
272
+ set { redirectPolicy.allowHttpsToHttpRedirect = newValue }
273
+ }
274
+
275
+ /// Runs a raw data task on the updater session (no cookies, no cache, redirect policy applied).
276
+ @discardableResult
277
+ func startRawDataTask(_ request: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
278
+ let task = self.urlSession.dataTask(with: request, completionHandler: completion)
279
+ task.resume()
280
+ return task
281
+ }
282
+
283
+ /// Runs a data task and reports `(data, response, error)` like Alamofire's `responseData` did:
284
+ /// `data` is nil when no bytes were received, transport errors are wrapped, and an empty body is an error
285
+ /// unless the status code is 204/205 (or the request is HEAD).
286
+ @discardableResult
287
+ private func startDataTask(
288
+ _ request: URLRequest,
289
+ completionQueue: DispatchQueue,
290
+ completion: @escaping (Data?, HTTPURLResponse?, Error?) -> Void
291
+ ) -> URLSessionDataTask {
292
+ let task = self.urlSession.dataTask(with: request) { data, response, error in
293
+ let httpResponse = response as? HTTPURLResponse
294
+ let body = (data?.isEmpty ?? true) ? nil : data
295
+ let resultError: Error?
296
+ if let error {
297
+ resultError = NetworkError.sessionTaskFailed(error)
298
+ } else {
299
+ resultError = Self.emptyResponseError(data: body, response: httpResponse, method: request.httpMethod)
300
+ }
301
+ completionQueue.async {
302
+ completion(body, httpResponse, resultError)
303
+ }
304
+ }
305
+ task.resume()
306
+ return task
307
+ }
308
+
309
+ /// Builds a POST request with a JSON body (same headers as Alamofire's JSON encoders).
310
+ func makeJSONPostRequest(urlString: String, body: () throws -> Data) -> Result<URLRequest, Error> {
311
+ guard let url = URL(string: urlString) else {
312
+ return .failure(NetworkError.invalidURL(urlString))
313
+ }
314
+ var request = URLRequest(url: url)
315
+ request.httpMethod = "POST"
316
+ request.timeoutInterval = self.timeout
317
+ do {
318
+ request.httpBody = try body()
319
+ } catch let error as NetworkError {
320
+ return .failure(error)
321
+ } catch {
322
+ return .failure(NetworkError.bodyEncodingFailed(error))
323
+ }
324
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
325
+ return .success(request)
326
+ }
327
+
328
+ /// Fire-and-forget JSON POST whose completion runs on the main queue, like Alamofire's default `responseData`.
329
+ private func sendJSONPost(
330
+ urlString: String,
331
+ body: () throws -> Data,
332
+ completion: @escaping (Data?, HTTPURLResponse?, Error?) -> Void
333
+ ) {
334
+ switch makeJSONPostRequest(urlString: urlString, body: body) {
335
+ case let .success(request):
336
+ self.startDataTask(request, completionQueue: .main, completion: completion)
337
+ case let .failure(error):
338
+ DispatchQueue.main.async {
339
+ completion(nil, nil, error)
340
+ }
341
+ }
342
+ }
224
343
  private let networkResponseQueue = DispatchQueue(label: "ee.forgr.capacitor-updater.network-response", qos: .utility)
225
344
 
226
345
  public var notifyDownloadRaw: (String, Int, Bool, BundleInfo?) -> Void = { _, _, _, _ in }
@@ -278,43 +397,69 @@ import UIKit
278
397
  var responseData: Data?
279
398
  var httpResponse: HTTPURLResponse?
280
399
  var requestError: Error?
281
- let dataRequest = self.alamofireSession.request(request).responseData(queue: self.networkResponseQueue) { response in
282
- responseData = response.data
283
- httpResponse = response.response
284
- requestError = response.error
400
+ let dataTask = self.startDataTask(request, completionQueue: self.networkResponseQueue) { data, response, error in
401
+ responseData = data
402
+ httpResponse = response
403
+ requestError = error
285
404
  semaphore.signal()
286
405
  }
287
- dataRequest.resume()
288
406
 
289
407
  if semaphore.wait(timeout: .now() + waitTimeout) == .timedOut {
290
- dataRequest.cancel()
408
+ dataTask.cancel()
291
409
  logger.error("\(label) timed out after \(Int(waitTimeout))s")
292
410
  return RequestResult(data: responseData, response: httpResponse, error: requestError, timedOut: true)
293
411
  }
294
412
 
295
- return RequestResult(data: responseData, response: httpResponse, error: requestError, timedOut: false)
413
+ // URLSession can report its own timeout (NSURLErrorTimedOut) before the semaphore deadline.
414
+ let timedOut = isTimedOutError(requestError)
415
+ if timedOut {
416
+ logger.error("\(label) timed out after \(Int(request.timeoutInterval))s")
417
+ }
418
+ return RequestResult(data: responseData, response: httpResponse, error: requestError, timedOut: timedOut)
296
419
  }
297
420
 
298
- private func performDownloadRequest(_ request: URLRequest, label: String) -> DownloadRequestResult {
421
+ func performDownloadRequest(_ request: URLRequest, label: String) -> DownloadRequestResult {
299
422
  let waitTimeout = max(self.timeout + 5, 10)
300
423
  let semaphore = DispatchSemaphore(value: 0)
301
424
  var tempFileURL: URL?
302
425
  var httpResponse: HTTPURLResponse?
303
426
  var requestError: Error?
304
427
  let temporaryDownloadURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
305
- let destination: DownloadRequest.Destination = { _, _ in
306
- (temporaryDownloadURL, [.removePreviousFile, .createIntermediateDirectories])
307
- }
308
- let downloadRequest = self.alamofireSession.download(request, to: destination).response(queue: self.networkResponseQueue) { response in
309
- tempFileURL = response.fileURL
310
- httpResponse = response.response
311
- requestError = response.error
312
- semaphore.signal()
428
+ let downloadTask = self.urlSession.downloadTask(with: request) { location, response, error in
429
+ // URLSession deletes `location` once this handler returns, so move it synchronously here.
430
+ var movedFileURL: URL?
431
+ var resultError: Error?
432
+ if let error {
433
+ resultError = NetworkError.sessionTaskFailed(error)
434
+ } else if let location {
435
+ do {
436
+ let fileManager = FileManager.default
437
+ try fileManager.createDirectory(
438
+ at: temporaryDownloadURL.deletingLastPathComponent(),
439
+ withIntermediateDirectories: true,
440
+ attributes: nil
441
+ )
442
+ if fileManager.fileExists(atPath: temporaryDownloadURL.path) {
443
+ try fileManager.removeItem(at: temporaryDownloadURL)
444
+ }
445
+ try fileManager.moveItem(at: location, to: temporaryDownloadURL)
446
+ movedFileURL = temporaryDownloadURL
447
+ } catch {
448
+ resultError = NetworkError.downloadedFileMoveFailed(error, source: location, destination: temporaryDownloadURL)
449
+ }
450
+ }
451
+ let taskResponse = response as? HTTPURLResponse
452
+ self.networkResponseQueue.async {
453
+ tempFileURL = movedFileURL
454
+ httpResponse = taskResponse
455
+ requestError = resultError
456
+ semaphore.signal()
457
+ }
313
458
  }
314
- downloadRequest.resume()
459
+ downloadTask.resume()
315
460
 
316
461
  if semaphore.wait(timeout: .now() + waitTimeout) == .timedOut {
317
- downloadRequest.cancel()
462
+ downloadTask.cancel()
318
463
  logger.error("\(label) timed out after \(Int(waitTimeout))s")
319
464
  return DownloadRequestResult(
320
465
  fileURL: existingDownloadFileURL(tempFileURL, fallback: temporaryDownloadURL),
@@ -361,6 +506,18 @@ import UIKit
361
506
  return cacheFolder.appendingPathComponent("partial_\(digest)_\(token).tmp")
362
507
  }
363
508
 
509
+ private func removePartialManifestBundleDirectory(_ destFolder: URL) {
510
+ guard FileManager.default.fileExists(atPath: destFolder.path) else {
511
+ return
512
+ }
513
+ do {
514
+ try FileManager.default.removeItem(at: destFolder)
515
+ } catch {
516
+ logger.error("Failed to remove partial manifest bundle directory")
517
+ logger.debug("Path: \(destFolder.path), Error: \(error.localizedDescription)")
518
+ }
519
+ }
520
+
364
521
  private func cleanupOldManifestPartials() {
365
522
  let cutoff = Date().addingTimeInterval(-3600)
366
523
  guard let files = try? FileManager.default.contentsOfDirectory(
@@ -441,6 +598,8 @@ import UIKit
441
598
 
442
599
  deinit {
443
600
  shutdown()
601
+ // Alamofire's Session invalidated its URLSession on deinit; keep releasing the session the same way.
602
+ cachedUrlSession?.invalidateAndCancel()
444
603
  }
445
604
 
446
605
  public func shutdown() {
@@ -719,28 +878,27 @@ import UIKit
719
878
 
720
879
  // Send synchronously using semaphore (safe because we're on a background queue)
721
880
  let semaphore = DispatchSemaphore(value: 0)
722
- self.alamofireSession.request(
723
- self.statsUrl,
724
- method: .post,
725
- parameters: parameters.toParameters(),
726
- encoding: JSONEncoding.default,
727
- requestModifier: { $0.timeoutInterval = self.timeout }
728
- ).responseData { response in
729
- let statusCode = response.response?.statusCode
730
- switch response.result {
731
- case .success where (200...299).contains(statusCode ?? 0):
732
- self.logger.info("Rate limit statistic sent")
733
- case .success:
881
+ let parameterValues = parameters.toParameters()
882
+ self.sendJSONPost(urlString: self.statsUrl, body: {
883
+ guard JSONSerialization.isValidJSONObject(parameterValues) else {
884
+ throw NetworkError.bodyEncodingFailed(nil)
885
+ }
886
+ return try JSONSerialization.data(withJSONObject: parameterValues)
887
+ }, completion: { _, response, error in
888
+ let statusCode = response?.statusCode
889
+ if let error {
734
890
  CapgoUpdater.releaseRateLimitStatisticClaim()
735
891
  self.logger.error("Error sending rate limit statistic")
736
- self.logger.debug("Response code: \(statusCode.map(String.init) ?? "nil")")
737
- case let .failure(error):
892
+ self.logger.debug("Error: \(error.localizedDescription)")
893
+ } else if (200...299).contains(statusCode ?? 0) {
894
+ self.logger.info("Rate limit statistic sent")
895
+ } else {
738
896
  CapgoUpdater.releaseRateLimitStatisticClaim()
739
897
  self.logger.error("Error sending rate limit statistic")
740
- self.logger.debug("Error: \(error.localizedDescription)")
898
+ self.logger.debug("Response code: \(statusCode.map(String.init) ?? "nil")")
741
899
  }
742
900
  semaphore.signal()
743
- }
901
+ })
744
902
  semaphore.wait()
745
903
  }
746
904
 
@@ -832,7 +990,59 @@ import UIKit
832
990
  }
833
991
  }
834
992
 
835
- private func extractZipEntry(_ archive: Archive, entry: Entry, to destPath: URL, bufferSize: Int = CryptoCipher.ioBufferBytes()) throws {
993
+ // Symlink targets are paths; anything bigger than this is not a legitimate link.
994
+ private static let maxZipSymlinkTargetBytes = 64 * 1024
995
+
996
+ /// A zip symlink target must be a relative path without `..`, so a link can only point further down.
997
+ /// A lexical check alone is not enough: with `m -> .`, the target `m/..` normalizes to the link folder but
998
+ /// physically resolves to its parent.
999
+ static func isSafeZipSymlinkTarget(_ target: String) -> Bool {
1000
+ if target.isEmpty || target.contains("\0") || target.contains("\\") {
1001
+ return false
1002
+ }
1003
+ if (target as NSString).isAbsolutePath {
1004
+ return false
1005
+ }
1006
+ return !containsPathTraversalSegment(target)
1007
+ }
1008
+
1009
+ private static func realPath(_ path: String) -> String? {
1010
+ guard let resolved = Darwin.realpath(path, nil) else {
1011
+ return nil
1012
+ }
1013
+ defer { free(resolved) }
1014
+ return String(cString: resolved)
1015
+ }
1016
+
1017
+ /// Resolves symlinks on the deepest existing ancestor of `url` and throws when it is outside `root`.
1018
+ /// Run before creating anything, so a symlinked folder can never redirect a write out of the bundle.
1019
+ static func assertPhysicallyInsideDirectory(_ url: URL, root: URL) throws {
1020
+ guard let rootPath = realPath(root.path) else {
1021
+ throw SecurePathError.pathTraversal
1022
+ }
1023
+ let normalizedRoot = rootPath.hasSuffix("/") ? rootPath : "\(rootPath)/"
1024
+ var candidate = url.standardizedFileURL.path
1025
+ while true {
1026
+ if let resolved = realPath(candidate) {
1027
+ if resolved != rootPath && !resolved.hasPrefix(normalizedRoot) {
1028
+ throw SecurePathError.pathTraversal
1029
+ }
1030
+ return
1031
+ }
1032
+ let parent = (candidate as NSString).deletingLastPathComponent
1033
+ if parent == candidate || parent.isEmpty {
1034
+ throw SecurePathError.pathTraversal
1035
+ }
1036
+ candidate = parent
1037
+ }
1038
+ }
1039
+
1040
+ /// `fileExists` follows symlinks, so a dangling link would be missed; this does not follow the last component.
1041
+ private static func itemExistsWithoutFollowingLink(at url: URL) -> Bool {
1042
+ return (try? FileManager.default.attributesOfItem(atPath: url.path)) != nil
1043
+ }
1044
+
1045
+ private func extractZipEntry(_ archive: ZipArchiveReader, entry: ZipEntry, to destPath: URL, bufferSize: Int = CryptoCipher.ioBufferBytes()) throws {
836
1046
  let fileManager = FileManager.default
837
1047
 
838
1048
  switch entry.type {
@@ -842,7 +1052,7 @@ import UIKit
842
1052
  let parentDir = destPath.deletingLastPathComponent()
843
1053
  try fileManager.createDirectory(at: parentDir, withIntermediateDirectories: true, attributes: nil)
844
1054
 
845
- if fileManager.fileExists(atPath: destPath.path) {
1055
+ if Self.itemExistsWithoutFollowingLink(at: destPath) {
846
1056
  try fileManager.removeItem(at: destPath)
847
1057
  }
848
1058
 
@@ -855,18 +1065,18 @@ import UIKit
855
1065
  fileHandle.closeFile()
856
1066
  }
857
1067
 
858
- _ = try archive.extract(entry, bufferSize: bufferSize, skipCRC32: true) { data in
1068
+ try archive.extract(entry, bufferSize: bufferSize) { data in
859
1069
  if !data.isEmpty {
860
1070
  fileHandle.write(data)
861
1071
  }
862
1072
  }
863
1073
  case .symlink:
864
- var linkData = Data()
865
- _ = try archive.extract(entry, bufferSize: bufferSize, skipCRC32: true) { data in
866
- linkData.append(data)
867
- }
1074
+ let linkData = try archive.readSmallEntry(entry, maxBytes: Self.maxZipSymlinkTargetBytes, bufferSize: bufferSize)
868
1075
 
869
- guard let linkPath = String(data: linkData, encoding: .utf8) else {
1076
+ guard let linkPath = String(data: linkData, encoding: .utf8), Self.isSafeZipSymlinkTarget(linkPath) else {
1077
+ logger.error("Unzip failed: unsafe symlink target")
1078
+ logger.debug("Entry: \(entry.path)")
1079
+ self.sendStats(action: "canonical_path_fail")
870
1080
  throw CustomError.cannotUnzip
871
1081
  }
872
1082
 
@@ -883,7 +1093,7 @@ import UIKit
883
1093
  throw CustomError.cannotUnzip
884
1094
  }
885
1095
 
886
- if fileManager.fileExists(atPath: destPath.path) {
1096
+ if Self.itemExistsWithoutFollowingLink(at: destPath) {
887
1097
  try fileManager.removeItem(at: destPath)
888
1098
  }
889
1099
 
@@ -900,9 +1110,9 @@ import UIKit
900
1110
  self.notifyDownload(id: id, percent: 75)
901
1111
 
902
1112
  // Open the archive
903
- let archive: Archive
1113
+ let archive: ZipArchiveReader
904
1114
  do {
905
- archive = try Archive(url: sourceZip, accessMode: .read)
1115
+ archive = try ZipArchiveReader(url: sourceZip)
906
1116
  } catch {
907
1117
  self.sendStats(action: "unzip_fail")
908
1118
  throw CustomError.cannotUnzip
@@ -912,12 +1122,21 @@ import UIKit
912
1122
  try FileManager.default.createDirectory(at: destUnZip, withIntermediateDirectories: true, attributes: nil)
913
1123
 
914
1124
  // Count total entries for progress
915
- let totalEntries = archive.reduce(0) { count, _ in count + 1 }
1125
+ let totalEntries = archive.entries.count
916
1126
  var processedEntries = 0
917
1127
 
918
1128
  do {
919
- for entry in archive {
1129
+ for entry in archive.entries {
920
1130
  let destPath = try resolveZipEntry(path: entry.path, destUnZip: destUnZip)
1131
+ do {
1132
+ // Symlinks extracted earlier must not move this entry out of the bundle folder.
1133
+ try Self.assertPhysicallyInsideDirectory(destPath.deletingLastPathComponent(), root: destUnZip)
1134
+ } catch {
1135
+ logger.error("Unzip failed: entry resolves outside the bundle folder")
1136
+ logger.debug("Entry: \(entry.path)")
1137
+ self.sendStats(action: "canonical_path_fail")
1138
+ throw CustomError.cannotUnzip
1139
+ }
921
1140
 
922
1141
  if entry.type == .directory {
923
1142
  try FileManager.default.createDirectory(at: destPath, withIntermediateDirectories: true, attributes: nil)
@@ -1609,17 +1828,26 @@ import UIKit
1609
1828
  )
1610
1829
  let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
1611
1830
  self.saveBundleInfo(id: id, bundle: errorBundle)
1831
+ removePartialManifestBundleDirectory(destFolder)
1612
1832
  throw resolvedError
1613
1833
  }
1614
1834
 
1615
1835
  var operations: [Operation] = []
1616
1836
 
1617
1837
  for task in tasks {
1618
- try FileManager.default.createDirectory(
1619
- at: task.destFilePath.deletingLastPathComponent(),
1620
- withIntermediateDirectories: true,
1621
- attributes: nil
1622
- )
1838
+ do {
1839
+ try FileManager.default.createDirectory(
1840
+ at: task.destFilePath.deletingLastPathComponent(),
1841
+ withIntermediateDirectories: true,
1842
+ attributes: nil
1843
+ )
1844
+ } catch {
1845
+ let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
1846
+ self.saveBundleInfo(id: id, bundle: errorBundle)
1847
+ removePartialManifestBundleDirectory(destFolder)
1848
+ self.notifyDownload(id: id, percent: 0, bundle: errorBundle)
1849
+ throw error
1850
+ }
1623
1851
 
1624
1852
  let operation = BlockOperation { [weak self] in
1625
1853
  guard let self = self else { return }
@@ -1687,6 +1915,7 @@ import UIKit
1687
1915
  // Update bundle status to ERROR if download failed
1688
1916
  let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
1689
1917
  self.saveBundleInfo(id: id, bundle: errorBundle)
1918
+ removePartialManifestBundleDirectory(destFolder)
1690
1919
  throw resolvedError
1691
1920
  }
1692
1921
 
@@ -2106,8 +2335,47 @@ import UIKit
2106
2335
  return hasher.hex()
2107
2336
  }
2108
2337
 
2338
+ /// Resolves the checksum a zip bundle must match: required, and RSA-decrypted when a public key is set.
2339
+ func resolveExpectedBundleChecksum(_ checksum: String, versionName: String) throws -> String {
2340
+ if checksum.isEmpty {
2341
+ logger.error("No checksum provided")
2342
+ self.sendStats(action: "checksum_required", versionName: versionName)
2343
+ throw NSError(domain: "ChecksumError", code: 2, userInfo: [NSLocalizedDescriptionKey: "Checksum required"])
2344
+ }
2345
+ return try CryptoCipher.decryptChecksum(checksum: checksum, publicKey: self.publicKey)
2346
+ }
2347
+
2348
+ /// Downloads and extracts a zip bundle without checking its checksum; the caller must verify it.
2349
+ /// Prefer `downloadVerified`, which rejects a bad archive before extracting it.
2109
2350
  public func download(url: URL, version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
2351
+ return try self.downloadZip(url: url, version: version, sessionKey: sessionKey, link: link, comment: comment, expectedChecksum: nil)
2352
+ }
2353
+
2354
+ /// Downloads a zip bundle and extracts it only when it matches `expectedChecksum`, the checksum from the
2355
+ /// update response (required, RSA-decrypted when a public key is set). The SHA-256 of the downloaded and
2356
+ /// decrypted archive is compared before anything is extracted: a mismatch deletes the archive, reports
2357
+ /// `checksum_fail` and throws `ObjectSavableError.checksum`.
2358
+ public func downloadVerified(
2359
+ url: URL,
2360
+ version: String,
2361
+ sessionKey: String,
2362
+ expectedChecksum: String,
2363
+ link: String? = nil,
2364
+ comment: String? = nil
2365
+ ) throws -> BundleInfo {
2366
+ return try self.downloadZip(url: url, version: version, sessionKey: sessionKey, link: link, comment: comment, expectedChecksum: expectedChecksum)
2367
+ }
2368
+
2369
+ private func downloadZip(
2370
+ url: URL,
2371
+ version: String,
2372
+ sessionKey: String,
2373
+ link: String?,
2374
+ comment: String?,
2375
+ expectedChecksum: String?
2376
+ ) throws -> BundleInfo {
2110
2377
  try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
2378
+ let expectedHash = try expectedChecksum.map { try self.resolveExpectedBundleChecksum($0, versionName: version) }
2111
2379
  try self.runBeforeDownload()
2112
2380
  let id: String = self.randomString(length: 10)
2113
2381
  // Each download uses its own temp files keyed by bundle ID to prevent collisions
@@ -2150,6 +2418,12 @@ import UIKit
2150
2418
  }
2151
2419
 
2152
2420
  let downloadResult = performDownloadRequest(request, label: "download \(version)")
2421
+ // Error responses (e.g. an HTTP 404 body) are also saved to a temp file; never leave them behind.
2422
+ defer {
2423
+ if let fileURL = downloadResult.fileURL {
2424
+ try? FileManager.default.removeItem(at: fileURL)
2425
+ }
2426
+ }
2153
2427
 
2154
2428
  if downloadResult.timedOut {
2155
2429
  persistPartialDownload(downloadResult, id: id, tempPath: tempPath, existingBytes: totalReceivedBytes)
@@ -2210,9 +2484,22 @@ import UIKit
2210
2484
  throw error
2211
2485
  }
2212
2486
 
2487
+ checksum = CryptoCipher.calcChecksum(filePath: finalPath)
2488
+ CryptoCipher.logChecksumInfo(label: "Calculated bundle checksum", hexChecksum: checksum)
2489
+ if let expectedHash, checksum.isEmpty || checksum != expectedHash {
2490
+ // Never extract an archive that failed verification.
2491
+ logger.error("Checksum mismatch, bundle rejected before extraction")
2492
+ CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: expectedHash)
2493
+ self.sendStats(action: "checksum_fail", versionName: version)
2494
+ try? FileManager.default.removeItem(at: finalPath)
2495
+ self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
2496
+ cleanDownloadData(for: id)
2497
+ // Drop it like the previous post-extraction check did, so the next update check downloads it again.
2498
+ _ = self.delete(id: id)
2499
+ throw ObjectSavableError.checksum
2500
+ }
2501
+
2213
2502
  do {
2214
- checksum = CryptoCipher.calcChecksum(filePath: finalPath)
2215
- CryptoCipher.logChecksumInfo(label: "Calculated bundle checksum", hexChecksum: checksum)
2216
2503
  logger.info("Downloading: 80% (unzipping)")
2217
2504
  try self.saveDownloaded(sourceZip: finalPath, id: id, base: self.libraryDir.appendingPathComponent(self.bundleDirectory), notify: true)
2218
2505
  self.populateDeltaCacheAsync(for: id)
@@ -2837,6 +3124,16 @@ import UIKit
2837
3124
  return true
2838
3125
  }
2839
3126
 
3127
+ /// Points the current bundle back at `bundle` without sending stats, after an
3128
+ /// install whose reload failed left the WebView on it.
3129
+ func restoreCurrentBundle(_ bundle: BundleInfo) {
3130
+ if bundle.isBuiltin() {
3131
+ self.setCurrentBundle(bundle: "")
3132
+ } else {
3133
+ _ = self.stagePendingReload(bundle: bundle)
3134
+ }
3135
+ }
3136
+
2840
3137
  func stagePreviewFallbackReload(bundle: BundleInfo) -> Bool {
2841
3138
  guard !bundle.isErrorStatus() else {
2842
3139
  return false
@@ -2937,9 +3234,16 @@ import UIKit
2937
3234
  self.setBundleStatus(id: bundle.getId(), status: BundleStatus.ERROR)
2938
3235
  }
2939
3236
 
2940
- func unsetChannel(defaultChannelKey: String, configDefaultChannel: String) -> SetChannel {
3237
+ func unsetChannel(defaultChannelKey: String, configDefaultChannel: String, allowSetDefaultChannel: Bool) -> SetChannel {
2941
3238
  let setChannel: SetChannel = SetChannel()
2942
3239
 
3240
+ if !allowSetDefaultChannel {
3241
+ logger.error("unsetChannel is disabled by allowSetDefaultChannel config")
3242
+ setChannel.message = "unsetChannel is disabled by configuration"
3243
+ setChannel.error = "disabled_by_config"
3244
+ return setChannel
3245
+ }
3246
+
2943
3247
  // Clear persisted defaultChannel and revert to config value
2944
3248
  UserDefaults.standard.removeObject(forKey: defaultChannelKey)
2945
3249
  UserDefaults.standard.synchronize()
@@ -3460,24 +3764,20 @@ import UIKit
3460
3764
 
3461
3765
  let operation = BlockOperation {
3462
3766
  let semaphore = DispatchSemaphore(value: 0)
3463
- self.alamofireSession.request(
3464
- self.statsUrl,
3465
- method: .post,
3466
- parameters: eventsToSend,
3467
- encoder: JSONParameterEncoder.default,
3468
- requestModifier: { $0.timeoutInterval = self.timeout }
3469
- ).responseData { response in
3767
+ self.sendJSONPost(urlString: self.statsUrl, body: {
3768
+ try JSONEncoder().encode(eventsToSend)
3769
+ }, completion: { responseData, httpResponse, responseError in
3470
3770
  if self.abandonStoppedStatsFlush() {
3471
3771
  semaphore.signal()
3472
3772
  return
3473
3773
  }
3474
- if self.checkAndHandleRateLimitResponse(statusCode: response.response?.statusCode, data: response.data, response: response.response).blocked {
3774
+ if self.checkAndHandleRateLimitResponse(statusCode: httpResponse?.statusCode, data: responseData, response: httpResponse).blocked {
3475
3775
  self.requeueStatsEvents(queuedEvents)
3476
3776
  semaphore.signal()
3477
3777
  return
3478
3778
  }
3479
3779
 
3480
- if let statusCode = response.response?.statusCode, !(200...299).contains(statusCode) {
3780
+ if let statusCode = httpResponse?.statusCode, !(200...299).contains(statusCode) {
3481
3781
  if CapgoUpdater.isTransientStatsFailure(statusCode) {
3482
3782
  self.requeueStatsEvents(queuedEvents)
3483
3783
  self.logger.error("Error sending stats batch")
@@ -3491,19 +3791,18 @@ import UIKit
3491
3791
  return
3492
3792
  }
3493
3793
 
3494
- switch response.result {
3495
- case .success:
3794
+ if let error = responseError {
3795
+ self.requeueStatsEvents(queuedEvents)
3796
+ self.logger.error("Error sending stats batch")
3797
+ self.logger.debug("Response: nil, Error: \(error.localizedDescription)")
3798
+ } else {
3496
3799
  self.clearStatsInFlight()
3497
3800
  self.logger.info("Stats batch sent successfully")
3498
3801
  self.logger.debug("Sent \(eventsToSend.count) events")
3499
3802
  self.runStatsCallbacks(queuedEvents)
3500
- case let .failure(error):
3501
- self.requeueStatsEvents(queuedEvents)
3502
- self.logger.error("Error sending stats batch")
3503
- self.logger.debug("Response: \(response.value?.debugDescription ?? "nil"), Error: \(error.localizedDescription)")
3504
3803
  }
3505
3804
  semaphore.signal()
3506
- }
3805
+ })
3507
3806
  semaphore.wait()
3508
3807
  if !self.statsStopped {
3509
3808
  self.persistStatsQueue()
@@ -3645,6 +3944,17 @@ import UIKit
3645
3944
  return self.getBundleInfo(id: id)
3646
3945
  }
3647
3946
 
3947
+ /// Clears the stored next bundle when it is already the running bundle, so nothing stays pending.
3948
+ @discardableResult
3949
+ public func clearNextBundleIfCurrent() -> Bool {
3950
+ guard let next = self.getNextBundle(), !next.isUnknown(), next.getId() == self.getCurrentBundle().getId() else {
3951
+ return false
3952
+ }
3953
+ logger?.info("Next bundle \(next.getId()) is already the current bundle. Clearing next.")
3954
+ _ = self.setNextBundle(next: Optional<String>.none)
3955
+ return true
3956
+ }
3957
+
3648
3958
  public func getPreviewFallbackBundle() -> BundleInfo? {
3649
3959
  guard let id = UserDefaults.standard.string(forKey: self.PREVIEW_FALLBACK_VERSION) else {
3650
3960
  return nil