@capgo/capacitor-updater 9.0.1 → 9.0.2

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 (26) hide show
  1. package/README.md +106 -81
  2. package/android/build.gradle +1 -3
  3. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +513 -21
  4. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +675 -34
  5. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +82 -10
  6. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +23 -0
  7. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +188 -4
  8. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +81 -1
  9. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +72 -21
  10. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +5 -1
  11. package/dist/docs.json +13 -13
  12. package/dist/esm/definitions.d.ts +57 -23
  13. package/dist/esm/definitions.js.map +1 -1
  14. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1278 -107
  15. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +38 -0
  16. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +583 -56
  17. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +8 -1
  18. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +6 -1
  19. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +2705 -77
  20. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +9 -4
  21. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +67 -2
  22. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +130 -5
  23. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +22 -8
  24. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +4 -0
  25. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +19 -3
  26. package/package.json +2 -2
@@ -18,15 +18,17 @@ final class ChecksumRequiredTests: XCTestCase {
18
18
  super.init()
19
19
  }
20
20
 
21
- override func downloadVerified(
21
+ override func downloadVerifiedWithTransferHook(
22
22
  url _: URL,
23
23
  version _: String,
24
24
  sessionKey _: String,
25
25
  expectedChecksum _: String,
26
- link _: String? = nil,
27
- comment _: String? = nil
26
+ link _: String?,
27
+ comment _: String?,
28
+ beforeTransfer: (() throws -> Void)?
28
29
  ) throws -> BundleInfo {
29
- downloadedBundle
30
+ try beforeTransfer?()
31
+ return downloadedBundle
30
32
  }
31
33
  }
32
34
 
@@ -57,9 +59,12 @@ final class ChecksumRequiredTests: XCTestCase {
57
59
  implementation = StatsTrackingCapgoUpdater()
58
60
  implementation.setLogger(Logger(withTag: "ChecksumRequiredTests", options: Logger.Options(level: .silent)))
59
61
  implementation.setPublicKey("")
62
+ implementation.resetIncompleteDownloadRetryCount(version: "2.0.0")
60
63
  }
61
64
 
62
65
  override func tearDown() {
66
+ // Checksum failures leave a persisted integrity block and retry budget for the version.
67
+ implementation.resetIncompleteDownloadRetryCount(version: "2.0.0")
63
68
  implementation.shutdown()
64
69
  implementation = nil
65
70
  super.tearDown()
@@ -48,7 +48,7 @@ final class CliCryptoFixtureTests: XCTestCase {
48
48
 
49
49
  private static let fixtureFolders = ["native-contract-tests/cli", "native-contract-tests/cli-fresh"]
50
50
 
51
- private static func fixtureDirectories() throws -> [URL] {
51
+ static func fixtureDirectories() throws -> [URL] {
52
52
  let fileManager = FileManager.default
53
53
  for start in [URL(fileURLWithPath: fileManager.currentDirectoryPath), URL(fileURLWithPath: #filePath)] {
54
54
  var current = start
@@ -122,8 +122,12 @@ final class CliCryptoFixtureTests: XCTestCase {
122
122
  /// Serves the CLI-encrypted payload instead of fetching the URL.
123
123
  private final class FixtureDownloadCapgoUpdater: CapgoUpdater {
124
124
  var payload = Data()
125
+ var downloadRequests = 0
126
+ var sentStatsActions: [String] = []
125
127
 
126
- override func sendStats(action _: String, versionName _: String? = nil, oldVersionName _: String? = "") {}
128
+ override func sendStats(action: String, versionName _: String? = nil, oldVersionName _: String? = "") {
129
+ sentStatsActions.append(action)
130
+ }
127
131
 
128
132
  override func performDownloadRequest(
129
133
  _ request: URLRequest,
@@ -131,6 +135,7 @@ final class CliCryptoFixtureTests: XCTestCase {
131
135
  resumeData _: Data? = nil,
132
136
  onProgress _: ((Int64, Int64) -> Void)? = nil
133
137
  ) -> DownloadRequestResult {
138
+ downloadRequests += 1
134
139
  let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent("capgo-cli-fixture-\(UUID().uuidString).zip")
135
140
  do {
136
141
  try payload.write(to: fileURL)
@@ -171,6 +176,66 @@ final class CliCryptoFixtureTests: XCTestCase {
171
176
  }
172
177
  }
173
178
  }
179
+ /// Encrypted bytes that miss the signed digest surface the same checksum error as a plaintext mismatch.
180
+ func testDownloadVerifiedMapsCiphertextMismatchToChecksumError() throws {
181
+ for fixture in try loadFixtures() {
182
+ let bundle = try XCTUnwrap(fixture.bundles.first)
183
+ let updater = FixtureDownloadCapgoUpdater()
184
+ updater.setLogger(Logger(withTag: "cli-fixture-tests", options: Logger.Options(level: .silent)))
185
+ updater.httpsOnly = false
186
+ updater.setPublicKey(fixture.publicKey)
187
+ var tampered = bundle.encrypted
188
+ tampered[tampered.count - 17] ^= 1
189
+ updater.payload = tampered
190
+ defer { updater.shutdown() }
191
+ let tamperedVersion = "9.9.9-cli-tampered-\(bundle.id)"
192
+ // Bundle records live in the shared UserDefaults, so drop any left by earlier runs first.
193
+ for stale in updater.list(raw: true) where stale.getVersionName() == tamperedVersion {
194
+ _ = updater.saveBundleInfo(id: stale.getId(), bundle: nil)
195
+ }
196
+
197
+ XCTAssertThrowsError(
198
+ try updater.downloadVerified(
199
+ url: root.appendingPathComponent("\(bundle.id)-tampered.zip"),
200
+ version: tamperedVersion,
201
+ sessionKey: bundle.ivSessionKey,
202
+ expectedChecksum: bundle.checksum
203
+ )
204
+ ) { error in
205
+ XCTAssertEqual(error as? ObjectSavableError, .checksum, "\(fixture.label): \(error)")
206
+ }
207
+ XCTAssertTrue(updater.sentStatsActions.contains("checksum_fail"), fixture.label)
208
+ // No ERROR record may stay behind, or the next automatic check would not download this version again.
209
+ let leftover = updater.list(raw: true).filter { $0.getVersionName() == tamperedVersion && $0.isErrorStatus() }
210
+ XCTAssertTrue(leftover.isEmpty, "\(fixture.label): \(leftover)")
211
+ }
212
+ }
213
+
214
+ /// The unchecked entry point cannot decrypt, so it rejects an encrypted download before any network I/O.
215
+ func testUncheckedDownloadRejectsEncryptedBundleBeforeNetwork() throws {
216
+ for fixture in try loadFixtures() {
217
+ let bundle = try XCTUnwrap(fixture.bundles.first)
218
+ let updater = FixtureDownloadCapgoUpdater()
219
+ updater.setLogger(Logger(withTag: "cli-fixture-tests", options: Logger.Options(level: .silent)))
220
+ updater.httpsOnly = false
221
+ updater.setPublicKey(fixture.publicKey)
222
+ updater.payload = bundle.encrypted
223
+ defer { updater.shutdown() }
224
+
225
+ XCTAssertThrowsError(
226
+ try updater.download(
227
+ url: root.appendingPathComponent("\(bundle.id).zip"),
228
+ version: "9.9.9-cli-unchecked-\(bundle.id)",
229
+ sessionKey: bundle.ivSessionKey
230
+ )
231
+ ) { error in
232
+ XCTAssertEqual((error as NSError).domain, "ChecksumError", fixture.label)
233
+ XCTAssertEqual((error as NSError).code, 2, fixture.label)
234
+ }
235
+ XCTAssertEqual(updater.downloadRequests, 0, fixture.label)
236
+ }
237
+ }
238
+
174
239
  func testConcurrentManifestSessionsResetCipherAndKeepKeysSeparate() throws {
175
240
  for fixture in try loadFixtures() {
176
241
  let (publicKey, bundles) = (fixture.publicKey, fixture.bundles)
@@ -19,12 +19,31 @@ final class HttpsOnlyBuiltinMinimumTests: XCTestCase {
19
19
  }
20
20
  }
21
21
 
22
- private func makeUpdater() -> StatsTrackingCapgoUpdater {
22
+ private func makeUpdater(statsUrl: String = "captured-by-test-double") -> StatsTrackingCapgoUpdater {
23
23
  let updater = StatsTrackingCapgoUpdater()
24
+ // Stats are captured by the overrides above; a configured URL lets the floor queue its stat.
25
+ updater.statsUrl = statsUrl
26
+ isolatePendingStats(updater)
24
27
  updater.setLogger(Logger(withTag: "HttpsOnlyBuiltinMinimumTests", options: Logger.Options(level: .silent)))
25
28
  return updater
26
29
  }
27
30
 
31
+ /// shutdown() (also run from deinit) persists the stats queue: keep it away from the real capgo_pending_stats.json.
32
+ private func isolatePendingStats(_ updater: CapgoUpdater) {
33
+ let statsDirectory = FileManager.default.temporaryDirectory
34
+ .appendingPathComponent("HttpsOnlyBuiltinMinimumTests-\(UUID().uuidString)", isDirectory: true)
35
+ updater.pendingStatsDirectoryOverride = statsDirectory
36
+ addTeardownBlock {
37
+ try? FileManager.default.removeItem(at: statsDirectory)
38
+ }
39
+ }
40
+
41
+ /// The plugin creates its own updater; isolate it before replacing it, since its deinit shuts it down.
42
+ private func install(_ updater: CapgoUpdater, into plugin: CapacitorUpdaterPlugin) {
43
+ isolatePendingStats(plugin.implementation)
44
+ plugin.implementation = updater
45
+ }
46
+
28
47
  /// Builds fixture URLs from the endpoint or launch-intent components required by each test.
29
48
  private func makeFixtureURL(scheme: String, host: String, pathComponent: String) throws -> URL {
30
49
  var components = URLComponents()
@@ -85,6 +104,22 @@ final class HttpsOnlyBuiltinMinimumTests: XCTestCase {
85
104
 
86
105
  // MARK: - builtinMinimum
87
106
 
107
+ /// A native upgrade during preview must not let leaving preview reactivate a fallback below the new floor.
108
+ func testPreviewFallbackBelowNativeFloorIsNotReactivated() {
109
+ let updater = makeUpdater()
110
+ updater.versionBuild = "2.0.0"
111
+ let plugin = CapacitorUpdaterPlugin()
112
+ install(updater, into: plugin)
113
+ let fallback = { (version: String) in
114
+ BundleInfo(id: UUID().uuidString, version: version, status: .SUCCESS, downloaded: Date(), checksum: "abc")
115
+ }
116
+ XCTAssertFalse(plugin.fallbackMeetsVersionFloor(fallback("1.9.9")))
117
+ XCTAssertTrue(plugin.fallbackMeetsVersionFloor(fallback("2.0.0")))
118
+ XCTAssertTrue(plugin.fallbackMeetsVersionFloor(updater.getBundleInfo(id: BundleInfo.ID_BUILTIN)))
119
+ updater.builtinMinimum = false
120
+ XCTAssertTrue(plugin.fallbackMeetsVersionFloor(fallback("1.9.9")))
121
+ }
122
+
88
123
  func testBuiltinMinimumRejectsVersionBelowNative() throws {
89
124
  let updater = makeUpdater()
90
125
  updater.builtinMinimum = true
@@ -106,12 +141,72 @@ final class HttpsOnlyBuiltinMinimumTests: XCTestCase {
106
141
  XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.0+build.42"))
107
142
  updater.versionBuild = "2.0.0+ci.7"
108
143
  XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
144
+ // Same numeric-core reading as Android: the prerelease never supplies a patch, extra components are ignored.
145
+ updater.versionBuild = "1.2.5"
146
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.2-rc.7"))
147
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("1.2.5-rc.7"))
148
+ updater.versionBuild = "2.0.0.4"
149
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
150
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.0"))
151
+ // Whitespace is dropped before the digit check, like Android: padded and plain versions decide the same way.
152
+ for nativeVersion in ["2.0.0", " 2.0.0"] {
153
+ updater.versionBuild = nativeVersion
154
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
155
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin(" 1.9.9"))
156
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.0"))
157
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin(" 2.0.0"))
158
+ }
109
159
  // Unparseable versions never block.
110
160
  XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("builtin"))
111
161
  updater.versionBuild = "not-a-version"
112
162
  XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("0.0.1"))
113
163
  }
114
164
 
165
+ /// Numeric components larger than Int still take part in the floor, matching Android.
166
+ func testBuiltinMinimumSkipsEmptyNumericCore() {
167
+ let updater = makeUpdater()
168
+ updater.versionBuild = "+2.0.0"
169
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("1.9.9"))
170
+ XCTAssertTrue(updater.sentStatsActions.isEmpty)
171
+ }
172
+
173
+ func testBuiltinMinimumComparesComponentsBeyondIntRange() {
174
+ let updater = makeUpdater()
175
+ updater.versionBuild = "2.0.0"
176
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9223372036854775808.0")) { error in
177
+ XCTAssertEqual(
178
+ (error as NSError).localizedDescription,
179
+ "Bundle version 1.9223372036854775808.0 is below native version 2.0.0 (builtinMinimum)"
180
+ )
181
+ }
182
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("9223372036854775808.0.0"))
183
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("002.0.0"))
184
+ updater.versionBuild = "1.0.0"
185
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("1.9223372036854775808.0"))
186
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native"])
187
+ }
188
+
189
+ /// A rejection whose stat is dropped must not suppress the first report once stats can be queued.
190
+ func testBuiltinMinimumReportsRejectionDroppedByPreviewOrMissingStatsUrl() {
191
+ let updater = makeUpdater()
192
+ updater.versionBuild = "2.0.0"
193
+ updater.previewSession = true
194
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
195
+ XCTAssertEqual(updater.sentStatsActions, [])
196
+ updater.previewSession = false
197
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
198
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
199
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native"])
200
+
201
+ let withoutStatsUrl = makeUpdater(statsUrl: "")
202
+ withoutStatsUrl.versionBuild = "2.0.0"
203
+ XCTAssertThrowsError(try withoutStatsUrl.requireVersionNotBelowBuiltin("1.9.9"))
204
+ XCTAssertEqual(withoutStatsUrl.sentStatsActions, [])
205
+ withoutStatsUrl.statsUrl = updater.statsUrl
206
+ XCTAssertThrowsError(try withoutStatsUrl.requireVersionNotBelowBuiltin("1.9.9"))
207
+ XCTAssertEqual(withoutStatsUrl.sentStatsActions, ["version_below_native"])
208
+ }
209
+
115
210
  func testBuiltinMinimumGatesDownloadBeforeNetwork() throws {
116
211
  let updater = makeUpdater()
117
212
  updater.builtinMinimum = true
@@ -160,7 +255,7 @@ final class HttpsOnlyBuiltinMinimumTests: XCTestCase {
160
255
  sessionKeys.forEach { defaults.removeObject(forKey: $0) }
161
256
  defaults.set(nativeBuildVersionChanged ? "1" : "2", forKey: "LatestNativeBuildVersion")
162
257
  updater.statsUrl = try makeFixtureURL(scheme: "https", host: "example.com", pathComponent: "stats").absoluteString
163
- plugin.implementation = updater
258
+ install(updater, into: plugin)
164
259
  plugin.setCurrentBuildVersionForTesting("2")
165
260
  return plugin.resetStartupBundleAndReportAppLaunchStartForTesting(
166
261
  resetWhenUpdate: false,
@@ -190,6 +285,35 @@ final class HttpsOnlyBuiltinMinimumTests: XCTestCase {
190
285
  }
191
286
  }
192
287
 
288
+ /// The startup fallback keeps a distinct compatible queued update; its activation runs its own floor check.
289
+ func testStartupRejectsRetainedBundleBelowNativeAndKeepsDistinctPendingUpdate() throws {
290
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
291
+ let queued = BundleInfo(id: UUID().uuidString, version: "2.2.0", status: .SUCCESS, downloaded: Date(), checksum: "abc")
292
+ let queuedDirectory = try updater.getBundleDirectory(id: queued.getId())
293
+ defer {
294
+ updater.saveBundleInfo(id: queued.getId(), bundle: nil)
295
+ try? FileManager.default.removeItem(at: queuedDirectory)
296
+ }
297
+ try FileManager.default.createDirectory(at: queuedDirectory, withIntermediateDirectories: true)
298
+ try "<html>queued bundle</html>".write(to: queuedDirectory.appendingPathComponent("index.html"), atomically: true, encoding: .utf8)
299
+ XCTAssertTrue(updater.saveBundleInfo(id: queued.getId(), bundle: queued))
300
+ let directory = try updater.getBundleDirectory(id: bundle.getId())
301
+ updater.restoreResetState(.init(
302
+ currentBundlePath: directory.path,
303
+ fallbackBundleId: bundle.getId(),
304
+ nextBundleId: queued.getId()
305
+ ))
306
+
307
+ XCTAssertTrue(try startRetainedBundle(updater))
308
+
309
+ XCTAssertTrue(updater.getCurrentBundle().isBuiltin())
310
+ XCTAssertTrue(updater.getFallbackBundle().isBuiltin())
311
+ XCTAssertEqual(updater.getNextBundle()?.getId(), queued.getId())
312
+ XCTAssertTrue(updater.bundleExists(id: bundle.getId()))
313
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native", "app_launch_start"])
314
+ }
315
+ }
316
+
193
317
  /// Startup preserves compatible or unparseable retained bundles and reports the version it will load.
194
318
  func testStartupKeepsRetainedBundleAllowedByNativeFloor() throws {
195
319
  for version in ["2.0.0", "2.0.1", "2.0.0-beta.1", "release-label"] {
@@ -240,6 +364,7 @@ final class HttpsOnlyBuiltinMinimumTests: XCTestCase {
240
364
  }
241
365
  previousPreviewValues.keys.forEach { defaults.removeObject(forKey: $0) }
242
366
  let plugin = CapacitorUpdaterPlugin()
367
+ isolatePendingStats(plugin.implementation)
243
368
  try plugin.invalidateDefaultChannelPreviewSnapshot(file: snapshotFile)
244
369
  plugin.previewSessionEnabled = true
245
370
  updater.previewSession = true
@@ -301,7 +426,7 @@ final class HttpsOnlyBuiltinMinimumTests: XCTestCase {
301
426
  XCTAssertTrue(updater.setNextBundle(next: bundle.getId()))
302
427
  let previousState = updater.captureResetState()
303
428
  let plugin = ReloadTrackingPlugin()
304
- plugin.implementation = updater
429
+ install(updater, into: plugin)
305
430
  var rejectionMessages: [String] = []
306
431
  var rejectionCodes: [String?] = []
307
432
  let call = try XCTUnwrap(CAPPluginCall(
@@ -334,7 +459,7 @@ final class HttpsOnlyBuiltinMinimumTests: XCTestCase {
334
459
  try withStoredBundle(version: "1.9.9") { updater, bundle in
335
460
  let previousState = updater.captureResetState()
336
461
  let plugin = ReloadTrackingPlugin()
337
- plugin.implementation = updater
462
+ install(updater, into: plugin)
338
463
  var messages: [String] = []
339
464
  var codes: [String?] = []
340
465
  let call = try XCTUnwrap(CAPPluginCall(
@@ -367,7 +492,7 @@ final class HttpsOnlyBuiltinMinimumTests: XCTestCase {
367
492
  try withStoredBundle(version: "1.9.9") { updater, bundle in
368
493
  try FileManager.default.removeItem(at: updater.getBundleDirectory(id: bundle.getId()).appendingPathComponent("index.html"))
369
494
  let plugin = ReloadTrackingPlugin()
370
- plugin.implementation = updater
495
+ install(updater, into: plugin)
371
496
  var messages: [String] = []
372
497
  var codes: [String?] = []
373
498
  let call = try XCTUnwrap(CAPPluginCall(
@@ -795,6 +795,7 @@ final class NetworkTransportTests: XCTestCase {
795
795
  func testPerformRequestWrapsTransportErrors() throws {
796
796
  let port = server.baseURL.port
797
797
  server.stop()
798
+ server.drain(timeout: 0.5)
798
799
  var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(port ?? 1)/closed")))
799
800
  request.timeoutInterval = 5
800
801
 
@@ -808,16 +809,16 @@ final class NetworkTransportTests: XCTestCase {
808
809
 
809
810
  func testPerformRequestClassifiesURLSessionTimeouts() {
810
811
  server.respond { _ in
811
- Thread.sleep(forTimeInterval: 3)
812
+ Thread.sleep(forTimeInterval: 2)
812
813
  return .init(status: 200, body: Data("late".utf8))
813
814
  }
814
815
  var slowRequest = request("slow")
815
- slowRequest.timeoutInterval = 1
816
+ slowRequest.timeoutInterval = 0.2
816
817
 
817
818
  let result = makeUpdater().performRequest(slowRequest, label: "test")
818
819
 
819
820
  XCTAssertTrue(result.timedOut, "a wrapped NSURLErrorTimedOut must be reported as a timeout")
820
- XCTAssertNotNil(result.error)
821
+ XCTAssertNotNil(result.error, "a timed-out request must still carry its error")
821
822
  }
822
823
 
823
824
  func testPerformDownloadRequestMovesBodyToTemporaryFile() throws {
@@ -874,7 +875,11 @@ final class NetworkTransportTests: XCTestCase {
874
875
 
875
876
  let lock = NSLock()
876
877
  var samples: [(Int64, Int64)] = []
877
- let result = makeUpdater().performDownloadRequest(request("missing.zip"), label: "test") { received, expected in
878
+ var errorRequest = request("missing.zip")
879
+ errorRequest.timeoutInterval = 30
880
+ let updater = makeUpdater()
881
+ updater.timeout = 30
882
+ let result = updater.performDownloadRequest(errorRequest, label: "test") { received, expected in
878
883
  lock.lock()
879
884
  samples.append((received, expected))
880
885
  lock.unlock()
@@ -958,7 +963,8 @@ final class NetworkTransportTests: XCTestCase {
958
963
  let flowLock = NSLock()
959
964
  var resumeBody = false
960
965
  server.respond { _ in
961
- var response = LoopbackHTTPServer.Response(status: 206, body: tail, chunkSize: 5_000, chunkDelay: 0.02)
966
+ var response = LoopbackHTTPServer.Response(status: 206, body: tail, chunkSize: 5_000, chunkDelay: 0.01)
967
+ response.waitBeforeContinuingBodyTimeout = 8
962
968
  response.waitBeforeContinuingBody = {
963
969
  flowLock.lock()
964
970
  let go = resumeBody
@@ -969,13 +975,16 @@ final class NetworkTransportTests: XCTestCase {
969
975
  }
970
976
  var rangeRequest = request("partial.zip")
971
977
  rangeRequest.setValue("bytes=10-", forHTTPHeaderField: "Range")
978
+ rangeRequest.timeoutInterval = 45
972
979
 
980
+ let updater = makeUpdater()
981
+ updater.timeout = 45
973
982
  let sampleLock = NSLock()
974
983
  var partialSamples: [(Int64, Int64)] = []
975
- let result = makeUpdater().performDownloadRequest(rangeRequest, label: "test") { received, expected in
984
+ let result = updater.performDownloadRequest(rangeRequest, label: "test") { received, expected in
976
985
  sampleLock.lock()
977
986
  partialSamples.append((received, expected))
978
- if received > 10 {
987
+ if received > 0 {
979
988
  flowLock.lock()
980
989
  resumeBody = true
981
990
  flowLock.unlock()
@@ -985,6 +994,7 @@ final class NetworkTransportTests: XCTestCase {
985
994
  if let fileURL = result.fileURL {
986
995
  try? FileManager.default.removeItem(at: fileURL)
987
996
  }
997
+ releaseUpdater(updater)
988
998
 
989
999
  XCTAssertEqual(result.response?.statusCode, 206)
990
1000
  XCTAssertEqual(server.requests.first?.headers["range"], "bytes=10-")
@@ -1001,7 +1011,10 @@ final class NetworkTransportTests: XCTestCase {
1001
1011
 
1002
1012
  server.respond { _ in .init(status: 200, body: tail, chunkSize: 50_000, chunkDelay: 0.01) }
1003
1013
  var fullSamples: [(Int64, Int64)] = []
1004
- let fullResult = makeUpdater().performDownloadRequest(rangeRequest, label: "test") { received, expected in
1014
+ let fullUpdater = makeUpdater()
1015
+ fullUpdater.timeout = 45
1016
+ rangeRequest.timeoutInterval = 45
1017
+ let fullResult = fullUpdater.performDownloadRequest(rangeRequest, label: "test") { received, expected in
1005
1018
  sampleLock.lock()
1006
1019
  fullSamples.append((received, expected))
1007
1020
  sampleLock.unlock()
@@ -1009,6 +1022,7 @@ final class NetworkTransportTests: XCTestCase {
1009
1022
  if let fileURL = fullResult.fileURL {
1010
1023
  try? FileManager.default.removeItem(at: fileURL)
1011
1024
  }
1025
+ releaseUpdater(fullUpdater)
1012
1026
  XCTAssertFalse(fullSamples.isEmpty)
1013
1027
  if let lastFull = fullSamples.last {
1014
1028
  XCTAssertEqual(lastFull.1, Int64(tail.count))
@@ -87,6 +87,10 @@ final class SessionKeyRequiredTests: XCTestCase {
87
87
  }
88
88
  return nil
89
89
  }
90
+
91
+ override func getBundleInfosByVersionName(version: String) -> [BundleInfo] {
92
+ getBundleInfoByVersionName(version: version).map { [$0] } ?? []
93
+ }
90
94
  }
91
95
 
92
96
  private final class TestableCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
@@ -83,6 +83,10 @@ private final class LifecycleCapgoUpdater: CapgoUpdater {
83
83
  nil
84
84
  }
85
85
 
86
+ override func getBundleInfosByVersionName(version: String) -> [BundleInfo] {
87
+ []
88
+ }
89
+
86
90
  override func download(url: URL, version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
87
91
  try downloadVerified(
88
92
  url: url,
@@ -94,14 +98,16 @@ private final class LifecycleCapgoUpdater: CapgoUpdater {
94
98
  )
95
99
  }
96
100
 
97
- override func downloadVerified(
101
+ override func downloadVerifiedWithTransferHook(
98
102
  url _: URL,
99
103
  version _: String,
100
104
  sessionKey _: String,
101
105
  expectedChecksum _: String,
102
- link _: String? = nil,
103
- comment _: String? = nil
106
+ link _: String?,
107
+ comment _: String?,
108
+ beforeTransfer: (() throws -> Void)?
104
109
  ) throws -> BundleInfo {
110
+ try beforeTransfer?()
105
111
  downloadCalls += 1
106
112
  guard let downloadedBundleValue else {
107
113
  throw NSError(domain: "UpdateLifecycleTests", code: 1)
@@ -196,15 +202,25 @@ final class UpdateLifecycleTests: XCTestCase {
196
202
  )
197
203
  UserDefaults.standard.removeObject(forKey: delayPreferencesKey)
198
204
  UserDefaults.standard.removeObject(forKey: delayConditionModeKey)
205
+ resetRetryState()
199
206
  }
200
207
 
201
208
  override func tearDown() {
202
209
  UserDefaults.standard.removeObject(forKey: delayPreferencesKey)
203
210
  UserDefaults.standard.removeObject(forKey: delayConditionModeKey)
204
211
  UserDefaults.standard.removeObject(forKey: lastFailedBundleKey)
212
+ resetRetryState()
205
213
  super.tearDown()
206
214
  }
207
215
 
216
+ /// Retry budgets and integrity blocks persist in UserDefaults until a successful install; other suites
217
+ /// (checksum failures, invalid manifests) use the same versions, so start each test from a clean budget.
218
+ private func resetRetryState() {
219
+ for version in ["1.0.0", "2.0.0", "3.0.0"] {
220
+ updater.resetIncompleteDownloadRetryCount(version: version)
221
+ }
222
+ }
223
+
208
224
  private func pendingBundle() -> BundleInfo {
209
225
  BundleInfo(id: "bundle-2", version: "2.0.0", status: .PENDING, downloaded: Date(), checksum: "abc")
210
226
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/capacitor-updater",
3
- "version": "9.0.1",
3
+ "version": "9.0.2",
4
4
  "license": "MPL-2.0",
5
5
  "description": "Live update for capacitor apps",
6
6
  "main": "dist/plugin.cjs.js",
@@ -76,7 +76,7 @@
76
76
  "clean": "rimraf ./dist",
77
77
  "watch": "tsc --watch",
78
78
  "prepublishOnly": "bun run build",
79
- "check:wiring": "node scripts/check-capacitor-plugin-wiring.mjs && bun scripts/test-release-workflows.mjs && bun scripts/test-cli-crypto-output-guard.mjs && node scripts/test-builtin-hashes-hook.mjs && node scripts/check-ios-test-shards.mjs && node scripts/maestro/test-helpers.mjs && node scripts/maestro/test-smoke-sequence.mjs && bun scripts/maestro/test-deferred-flow.mjs && bun scripts/maestro/test-startup-update-flow.mjs && bun scripts/maestro/test-local-plugin-manifest.mjs",
79
+ "check:wiring": "node scripts/check-capacitor-plugin-wiring.mjs && bun scripts/test-release-workflows.mjs && bun scripts/test-cli-crypto-output-guard.mjs && node scripts/test-builtin-hashes-hook.mjs && node scripts/check-ios-test-shards.mjs && node scripts/maestro/test-helpers.mjs && node scripts/maestro/test-smoke-sequence.mjs && bun scripts/maestro/test-deferred-flow.mjs && bun scripts/maestro/test-startup-update-flow.mjs && node scripts/maestro/test-local-plugin-manifest.mjs && node scripts/maestro/test-runner-attempt-cleanup.mjs",
80
80
  "check:cap9-deprecated": "bun scripts/check-cap9-deprecated.mjs",
81
81
  "changelog:ai": "node scripts/generate-ai-changelog.mjs",
82
82
  "example:install": "cd example-app && bun install --frozen-lockfile",