@capgo/capacitor-updater 9.0.1 → 9.0.4

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 (28) 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 +521 -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/CryptoCipher.java +10 -2
  6. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +82 -10
  7. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +23 -0
  8. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +188 -4
  9. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +81 -1
  10. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +72 -21
  11. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +5 -2
  12. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +5 -1
  13. package/dist/docs.json +13 -13
  14. package/dist/esm/definitions.d.ts +57 -23
  15. package/dist/esm/definitions.js.map +1 -1
  16. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1278 -107
  17. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +38 -0
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +583 -56
  19. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +8 -1
  20. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +6 -1
  21. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +2718 -77
  22. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +9 -4
  23. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +67 -2
  24. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +130 -5
  25. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +259 -119
  26. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +4 -0
  27. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +19 -3
  28. 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(