@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
@@ -0,0 +1,528 @@
1
+ import XCTest
2
+ @testable import Capacitor
3
+ @testable import CapacitorUpdaterPlugin
4
+
5
+ /// `httpsOnly` download gates and `builtinMinimum` download and activation gates.
6
+ final class HttpsOnlyBuiltinMinimumTests: XCTestCase {
7
+ private final class StatsTrackingCapgoUpdater: CapgoUpdater {
8
+ var sentStatsActions: [String] = []
9
+ var sentStatsVersions: [String?] = []
10
+
11
+ override func sendStats(action: String, versionName: String? = nil, oldVersionName _: String? = "") {
12
+ sentStatsActions.append(action)
13
+ sentStatsVersions.append(versionName)
14
+ }
15
+
16
+ override func sendStats(action: String, versionName: String?, oldVersionName _: String?, metadata _: [String: String]) {
17
+ sentStatsActions.append(action)
18
+ sentStatsVersions.append(versionName)
19
+ }
20
+ }
21
+
22
+ private func makeUpdater() -> StatsTrackingCapgoUpdater {
23
+ let updater = StatsTrackingCapgoUpdater()
24
+ updater.setLogger(Logger(withTag: "HttpsOnlyBuiltinMinimumTests", options: Logger.Options(level: .silent)))
25
+ return updater
26
+ }
27
+
28
+ /// Builds fixture URLs from the endpoint or launch-intent components required by each test.
29
+ private func makeFixtureURL(scheme: String, host: String, pathComponent: String) throws -> URL {
30
+ var components = URLComponents()
31
+ components.scheme = scheme
32
+ components.host = host
33
+ components.path = "/" + pathComponent
34
+ return try XCTUnwrap(components.url)
35
+ }
36
+
37
+ private final class ReloadTrackingPlugin: CapacitorUpdaterPlugin {
38
+ var reloadCalls = 0
39
+
40
+ /// Simulates a successful WebView reload and records whether activation reached that step.
41
+ override func reloadCurrentBundle() -> Bool {
42
+ reloadCalls += 1
43
+ return true
44
+ }
45
+
46
+ override func restoreLiveBundleStateAfterFailedReload() {
47
+ // This test has no WebView bridge to restore; it verifies the persisted bundle state instead.
48
+ }
49
+ }
50
+
51
+ /// Persists a real downloaded bundle and restores the active, fallback and pending state after the test.
52
+ private func withStoredBundle(
53
+ version: String,
54
+ _ body: (StatsTrackingCapgoUpdater, BundleInfo) throws -> Void
55
+ ) throws {
56
+ let updater = makeUpdater()
57
+ let previousState = updater.captureResetState()
58
+ let bundle = BundleInfo(id: UUID().uuidString, version: version, status: .SUCCESS, downloaded: Date(), checksum: "abc")
59
+ let directory = try updater.getBundleDirectory(id: bundle.getId())
60
+ defer {
61
+ updater.restoreResetState(previousState)
62
+ updater.saveBundleInfo(id: bundle.getId(), bundle: nil)
63
+ try? FileManager.default.removeItem(at: directory)
64
+ updater.shutdown()
65
+ }
66
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
67
+ try "<html>retained bundle</html>".write(to: directory.appendingPathComponent("index.html"), atomically: true, encoding: .utf8)
68
+ XCTAssertTrue(updater.saveBundleInfo(id: bundle.getId(), bundle: bundle))
69
+ updater.prepareResetStateForTransition()
70
+ updater.versionBuild = "2.0.0"
71
+ try body(updater, bundle)
72
+ }
73
+
74
+ func testDefaultsAreHttpsOnlyOnAndBuiltinMinimumOn() throws {
75
+ let updater = makeUpdater()
76
+ XCTAssertTrue(updater.httpsOnly)
77
+ XCTAssertTrue(updater.builtinMinimum)
78
+ XCTAssertTrue(RedirectPolicyDelegate().httpsOnly)
79
+ updater.versionBuild = "2.0.0"
80
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.0"))
81
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.0.0"))
82
+ XCTAssertNotNil(updater.checkAllowedScheme(try XCTUnwrap(URL(string: "http://example.com/a.zip"))))
83
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native"])
84
+ }
85
+
86
+ // MARK: - builtinMinimum
87
+
88
+ func testBuiltinMinimumRejectsVersionBelowNative() throws {
89
+ let updater = makeUpdater()
90
+ updater.builtinMinimum = true
91
+ updater.versionBuild = "2.0.0"
92
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9")) { error in
93
+ XCTAssertEqual((error as NSError).code, 8)
94
+ XCTAssertEqual(
95
+ (error as NSError).localizedDescription,
96
+ "Bundle version 1.9.9 is below native version 2.0.0 (builtinMinimum)"
97
+ )
98
+ }
99
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native"])
100
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.0"))
101
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.1"))
102
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.0-beta.1"))
103
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9-rc.1"))
104
+ // Dotted build metadata must not disable the floor.
105
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9+build.42"))
106
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.0+build.42"))
107
+ updater.versionBuild = "2.0.0+ci.7"
108
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
109
+ // Unparseable versions never block.
110
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("builtin"))
111
+ updater.versionBuild = "not-a-version"
112
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("0.0.1"))
113
+ }
114
+
115
+ func testBuiltinMinimumGatesDownloadBeforeNetwork() throws {
116
+ let updater = makeUpdater()
117
+ updater.builtinMinimum = true
118
+ updater.versionBuild = "3.0.0"
119
+ let url = try XCTUnwrap(URL(string: "https://example.com/update.zip"))
120
+ XCTAssertThrowsError(
121
+ try updater.downloadVerified(url: url, version: "2.0.0", sessionKey: "", expectedChecksum: "abc")
122
+ ) { error in
123
+ XCTAssertEqual((error as NSError).code, 8)
124
+ }
125
+ let manifest = [
126
+ ManifestEntry(file_name: "index.html", file_hash: "00", download_url: "https://example.com/f")
127
+ ]
128
+ XCTAssertThrowsError(
129
+ try updater.downloadManifest(manifest: manifest, version: "2.0.0", sessionKey: "")
130
+ ) { error in
131
+ XCTAssertEqual((error as NSError).code, 8)
132
+ }
133
+ }
134
+
135
+ /// Runs real startup preparation while preserving prior session markers between cases.
136
+ private func startRetainedBundle(
137
+ _ updater: StatsTrackingCapgoUpdater,
138
+ plugin: CapacitorUpdaterPlugin = CapacitorUpdaterPlugin(),
139
+ nativeBuildVersionChanged: Bool = true
140
+ ) throws -> Bool {
141
+ let defaults = UserDefaults.standard
142
+ let sessionKeys = [
143
+ "LatestNativeBuildVersion",
144
+ "CapacitorUpdater.appSessionId",
145
+ "CapacitorUpdater.appSessionForeground",
146
+ "CapacitorUpdater.appSessionStartedAt",
147
+ "CapacitorUpdater.lastReportedUncleanSessionId"
148
+ ]
149
+ let previousValues = sessionKeys.map { defaults.object(forKey: $0) }
150
+ defer {
151
+ for (key, value) in zip(sessionKeys, previousValues) {
152
+ if let value {
153
+ defaults.set(value, forKey: key)
154
+ } else {
155
+ defaults.removeObject(forKey: key)
156
+ }
157
+ }
158
+ defaults.synchronize()
159
+ }
160
+ sessionKeys.forEach { defaults.removeObject(forKey: $0) }
161
+ defaults.set(nativeBuildVersionChanged ? "1" : "2", forKey: "LatestNativeBuildVersion")
162
+ updater.statsUrl = try makeFixtureURL(scheme: "https", host: "example.com", pathComponent: "stats").absoluteString
163
+ plugin.implementation = updater
164
+ plugin.setCurrentBuildVersionForTesting("2")
165
+ return plugin.resetStartupBundleAndReportAppLaunchStartForTesting(
166
+ resetWhenUpdate: false,
167
+ nativeBuildVersionChanged: nativeBuildVersionChanged
168
+ )
169
+ }
170
+
171
+ /// A native upgrade must boot builtin even when the app preserves downloaded bundles across upgrades.
172
+ func testStartupRejectsRetainedBundleBelowNativeWithoutDeletingIt() throws {
173
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
174
+ let directory = try updater.getBundleDirectory(id: bundle.getId())
175
+ updater.restoreResetState(.init(
176
+ currentBundlePath: directory.path,
177
+ fallbackBundleId: bundle.getId(),
178
+ nextBundleId: bundle.getId()
179
+ ))
180
+
181
+ XCTAssertTrue(try startRetainedBundle(updater))
182
+
183
+ XCTAssertTrue(updater.getCurrentBundle().isBuiltin())
184
+ XCTAssertTrue(updater.getFallbackBundle().isBuiltin())
185
+ XCTAssertTrue(updater.getNextBundle()?.isUnknown() ?? true)
186
+ XCTAssertTrue(updater.bundleExists(id: bundle.getId()))
187
+ XCTAssertEqual(updater.getBundleInfo(id: bundle.getId()).getStatus(), BundleStatus.SUCCESS.storedValue)
188
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native", "app_launch_start"])
189
+ XCTAssertEqual(updater.sentStatsVersions, ["1.9.9", "2.0.0"])
190
+ }
191
+ }
192
+
193
+ /// Startup preserves compatible or unparseable retained bundles and reports the version it will load.
194
+ func testStartupKeepsRetainedBundleAllowedByNativeFloor() throws {
195
+ for version in ["2.0.0", "2.0.1", "2.0.0-beta.1", "release-label"] {
196
+ try withStoredBundle(version: version) { updater, bundle in
197
+ let directory = try updater.getBundleDirectory(id: bundle.getId())
198
+ updater.restoreResetState(.init(
199
+ currentBundlePath: directory.path,
200
+ fallbackBundleId: bundle.getId(),
201
+ nextBundleId: bundle.getId()
202
+ ))
203
+
204
+ XCTAssertFalse(try startRetainedBundle(updater))
205
+
206
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
207
+ XCTAssertEqual(updater.getFallbackBundle().getId(), bundle.getId())
208
+ XCTAssertEqual(updater.getNextBundle()?.getId(), bundle.getId())
209
+ XCTAssertEqual(updater.getBundleInfo(id: bundle.getId()).getStatus(), BundleStatus.SUCCESS.storedValue)
210
+ XCTAssertEqual(updater.sentStatsActions, ["app_launch_start"])
211
+ XCTAssertEqual(updater.sentStatsVersions, [version])
212
+ }
213
+ }
214
+ }
215
+
216
+ /// Preview launch restoration must not select an older fallback after the startup floor has been checked.
217
+ func testStartupRejectsBelowNativeFallbackRestoredByPreviewLaunch() throws {
218
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
219
+ let defaults = UserDefaults.standard
220
+ let previousPreviewValues = defaults.dictionaryRepresentation().filter {
221
+ $0.key.hasPrefix("CapacitorUpdater.preview") || $0.key == "previewFallbackVersion"
222
+ }
223
+ let proxy = ApplicationDelegateProxy.shared
224
+ let previousLaunchURL = proxy.lastURL
225
+ let supportDirectory = try XCTUnwrap(FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first)
226
+ let snapshotFile = supportDirectory.appendingPathComponent("CapacitorUpdater.defaultChannelPreviewSnapshot")
227
+ let previousSnapshot = try FileManager.default.fileExists(atPath: snapshotFile.path) ? Data(contentsOf: snapshotFile) : nil
228
+ defer {
229
+ proxy.lastURL = previousLaunchURL
230
+ for key in defaults.dictionaryRepresentation().keys where key.hasPrefix("CapacitorUpdater.preview") || key == "previewFallbackVersion" {
231
+ defaults.removeObject(forKey: key)
232
+ }
233
+ previousPreviewValues.forEach { defaults.set($0.value, forKey: $0.key) }
234
+ if let previousSnapshot {
235
+ try? previousSnapshot.write(to: snapshotFile, options: .atomic)
236
+ } else {
237
+ try? FileManager.default.removeItem(at: snapshotFile)
238
+ }
239
+ defaults.synchronize()
240
+ }
241
+ previousPreviewValues.keys.forEach { defaults.removeObject(forKey: $0) }
242
+ let plugin = CapacitorUpdaterPlugin()
243
+ try plugin.invalidateDefaultChannelPreviewSnapshot(file: snapshotFile)
244
+ plugin.previewSessionEnabled = true
245
+ updater.previewSession = true
246
+ XCTAssertTrue(updater.setPreviewFallbackBundle(fallback: bundle.getId()))
247
+ proxy.lastURL = try makeFixtureURL(scheme: "capgo", host: "preview", pathComponent: "bundle")
248
+
249
+ XCTAssertTrue(updater.getCurrentBundle().isBuiltin())
250
+ XCTAssertTrue(try startRetainedBundle(updater, plugin: plugin, nativeBuildVersionChanged: false))
251
+
252
+ XCTAssertFalse(plugin.previewSessionEnabled)
253
+ XCTAssertTrue(updater.getCurrentBundle().isBuiltin())
254
+ XCTAssertTrue(updater.getFallbackBundle().isBuiltin())
255
+ XCTAssertTrue(updater.getNextBundle()?.isUnknown() ?? true)
256
+ XCTAssertTrue(updater.bundleExists(id: bundle.getId()))
257
+ XCTAssertEqual(updater.getBundleInfo(id: bundle.getId()).getStatus(), BundleStatus.SUCCESS.storedValue)
258
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native", "app_launch_start"])
259
+ XCTAssertEqual(updater.sentStatsVersions, ["1.9.9", "2.0.0"])
260
+ }
261
+ }
262
+
263
+ /// Explicit opt-out preserves an older stored current bundle at startup.
264
+ func testStartupAllowsRetainedBundleBelowNativeWhenMinimumDisabled() throws {
265
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
266
+ let directory = try updater.getBundleDirectory(id: bundle.getId())
267
+ updater.restoreResetState(.init(
268
+ currentBundlePath: directory.path,
269
+ fallbackBundleId: bundle.getId(),
270
+ nextBundleId: bundle.getId()
271
+ ))
272
+ updater.builtinMinimum = false
273
+
274
+ XCTAssertFalse(try startRetainedBundle(updater))
275
+
276
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
277
+ XCTAssertEqual(updater.getFallbackBundle().getId(), bundle.getId())
278
+ XCTAssertEqual(updater.getNextBundle()?.getId(), bundle.getId())
279
+ XCTAssertTrue(updater.bundleExists(id: bundle.getId()))
280
+ XCTAssertEqual(updater.sentStatsActions, ["app_launch_start"])
281
+ XCTAssertEqual(updater.sentStatsVersions, ["1.9.9"])
282
+ }
283
+ }
284
+
285
+ /// A native upgrade must not let manual set reactivate an older stored bundle or mark it corrupt.
286
+ func testManualSetRejectsRetainedBundleWithoutChangingState() throws {
287
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
288
+ let previousState = updater.captureResetState()
289
+
290
+ XCTAssertFalse(updater.set(id: bundle.getId()))
291
+
292
+ XCTAssertEqual(updater.captureResetState().currentBundlePath, previousState.currentBundlePath)
293
+ XCTAssertEqual(updater.getBundleInfo(id: bundle.getId()).getStatus(), BundleStatus.SUCCESS.storedValue)
294
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native"])
295
+ }
296
+ }
297
+
298
+ /// Explicit reload must reject an incompatible pending bundle before reloading or clearing its ID.
299
+ func testReloadRejectsRetainedBundleAndKeepsItPending() throws {
300
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
301
+ XCTAssertTrue(updater.setNextBundle(next: bundle.getId()))
302
+ let previousState = updater.captureResetState()
303
+ let plugin = ReloadTrackingPlugin()
304
+ plugin.implementation = updater
305
+ var rejectionMessages: [String] = []
306
+ var rejectionCodes: [String?] = []
307
+ let call = try XCTUnwrap(CAPPluginCall(
308
+ callbackId: "reload-version-floor",
309
+ methodName: "reload",
310
+ options: [:],
311
+ success: { _, _ in XCTFail("Reload must reject the old bundle") },
312
+ error: { error in
313
+ rejectionMessages.append(error?.message ?? "")
314
+ rejectionCodes.append(error?.code)
315
+ }
316
+ ))
317
+
318
+ plugin.reload(call)
319
+ plugin.reload(call)
320
+
321
+ XCTAssertEqual(rejectionMessages, Array(repeating: "Bundle version 1.9.9 is below native version 2.0.0 (builtinMinimum)", count: 2))
322
+ XCTAssertEqual(rejectionCodes, ["VERSION_BELOW_NATIVE", "VERSION_BELOW_NATIVE"])
323
+ XCTAssertEqual(plugin.reloadCalls, 0)
324
+ XCTAssertEqual(updater.captureResetState().currentBundlePath, previousState.currentBundlePath)
325
+ XCTAssertEqual(updater.captureResetState().fallbackBundleId, previousState.fallbackBundleId)
326
+ XCTAssertEqual(updater.getNextBundle()?.getId(), bundle.getId())
327
+ XCTAssertEqual(updater.getBundleInfo(id: bundle.getId()).getStatus(), BundleStatus.PENDING.storedValue)
328
+ XCTAssertEqual(updater.sentStatsActions, ["set_next", "version_below_native"])
329
+ }
330
+ }
331
+
332
+ /// Manual set reports its policy rejection without reloading or reporting duplicate telemetry.
333
+ func testManualSetReportsVersionFloorRejection() throws {
334
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
335
+ let previousState = updater.captureResetState()
336
+ let plugin = ReloadTrackingPlugin()
337
+ plugin.implementation = updater
338
+ var messages: [String] = []
339
+ var codes: [String?] = []
340
+ let call = try XCTUnwrap(CAPPluginCall(
341
+ callbackId: "set-version-floor",
342
+ methodName: "set",
343
+ options: ["id": bundle.getId()],
344
+ success: { _, _ in XCTFail("Set must reject the old bundle") },
345
+ error: { error in
346
+ messages.append(error?.message ?? "")
347
+ codes.append(error?.code)
348
+ }
349
+ ))
350
+
351
+ for status in [BundleStatus.SUCCESS, BundleStatus.ERROR] {
352
+ XCTAssertTrue(updater.saveBundleInfo(id: bundle.getId(), bundle: bundle.setStatus(status: status.storedValue)))
353
+ plugin.set(call)
354
+ XCTAssertEqual(updater.getBundleInfo(id: bundle.getId()).getStatus(), status.storedValue)
355
+ }
356
+
357
+ XCTAssertEqual(messages, Array(repeating: "Bundle version 1.9.9 is below native version 2.0.0 (builtinMinimum)", count: 2))
358
+ XCTAssertEqual(codes, ["VERSION_BELOW_NATIVE", "VERSION_BELOW_NATIVE"])
359
+ XCTAssertEqual(plugin.reloadCalls, 0)
360
+ XCTAssertEqual(updater.captureResetState().currentBundlePath, previousState.currentBundlePath)
361
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native"])
362
+ }
363
+ }
364
+
365
+ /// Below-native metadata cannot hide a genuinely missing bundle behind a version-floor error.
366
+ func testManualSetReportsMissingBundleInsteadOfVersionFloor() throws {
367
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
368
+ try FileManager.default.removeItem(at: updater.getBundleDirectory(id: bundle.getId()).appendingPathComponent("index.html"))
369
+ let plugin = ReloadTrackingPlugin()
370
+ plugin.implementation = updater
371
+ var messages: [String] = []
372
+ var codes: [String?] = []
373
+ let call = try XCTUnwrap(CAPPluginCall(
374
+ callbackId: "set-missing-bundle",
375
+ methodName: "set",
376
+ options: ["id": bundle.getId()],
377
+ success: { _, _ in XCTFail("Set must reject the missing bundle") },
378
+ error: { error in
379
+ messages.append(error?.message ?? "")
380
+ codes.append(error?.code)
381
+ }
382
+ ))
383
+
384
+ plugin.set(call)
385
+
386
+ XCTAssertEqual(messages, ["Update failed, id \(bundle.getId()) doesn't exist"])
387
+ XCTAssertEqual(codes, [nil])
388
+ XCTAssertEqual(plugin.reloadCalls, 0)
389
+ XCTAssertTrue(updater.getCurrentBundle().isBuiltin())
390
+ XCTAssertEqual(updater.sentStatsActions, ["set_fail"])
391
+ }
392
+ }
393
+
394
+ /// Duplicate reporting is suppressed without caching validation or hiding changes to the native floor or opt-out.
395
+ func testVersionFloorStatsFollowPolicyChanges() throws {
396
+ let updater = makeUpdater()
397
+ updater.versionBuild = "2.0.0"
398
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
399
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
400
+ XCTAssertEqual(updater.sentStatsActions.count, 1)
401
+ updater.versionBuild = "3.0.0"
402
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
403
+ XCTAssertEqual(updater.sentStatsActions.count, 2)
404
+ updater.builtinMinimum = false
405
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("1.9.9"))
406
+ updater.builtinMinimum = true
407
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
408
+ XCTAssertEqual(updater.sentStatsActions.count, 3)
409
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("3.0.0"))
410
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
411
+ XCTAssertEqual(updater.sentStatsActions.count, 4)
412
+ }
413
+
414
+ /// Both activation entry points accept stored bundles at or above the native version.
415
+ func testStoredBundleActivationAcceptsEqualOrNewerVersions() throws {
416
+ for version in ["2.0.0", "2.0.1"] {
417
+ try withStoredBundle(version: version) { updater, bundle in
418
+ XCTAssertTrue(updater.set(id: bundle.getId()))
419
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
420
+ updater.prepareResetStateForTransition()
421
+ XCTAssertTrue(updater.stagePendingReload(bundle: bundle))
422
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
423
+ }
424
+ }
425
+ }
426
+
427
+ /// Independent web versioning still works when the app explicitly disables the version floor.
428
+ func testStoredBundleActivationAllowsExplicitOptOut() throws {
429
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
430
+ updater.builtinMinimum = false
431
+ XCTAssertTrue(updater.set(id: bundle.getId()))
432
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
433
+ updater.prepareResetStateForTransition()
434
+ XCTAssertTrue(updater.stagePendingReload(bundle: bundle))
435
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
436
+ }
437
+ }
438
+
439
+ /// A rejected pending update must not prevent the app from resetting to its builtin bundle.
440
+ func testBuiltinResetClearsRejectedPendingBundle() throws {
441
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
442
+ XCTAssertTrue(updater.setNextBundle(next: bundle.getId()))
443
+ XCTAssertFalse(updater.stagePendingReload(bundle: bundle))
444
+
445
+ XCTAssertTrue(updater.set(id: BundleInfo.ID_BUILTIN))
446
+
447
+ XCTAssertTrue(updater.getCurrentBundle().isBuiltin())
448
+ XCTAssertTrue(updater.getNextBundle()?.isUnknown() ?? true)
449
+ }
450
+ }
451
+
452
+ /// Restoring a WebView's previous bundle after a failed transition is not a new activation.
453
+ func testFailedReloadCanRestoreAnExistingOlderBundle() throws {
454
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
455
+ updater.restoreCurrentBundle(bundle)
456
+
457
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
458
+ XCTAssertTrue(updater.sentStatsActions.isEmpty)
459
+ }
460
+ }
461
+
462
+ // MARK: - httpsOnly
463
+
464
+ func testHttpsOnlyRejectsPlainHttpBeforeNetwork() throws {
465
+ let updater = makeUpdater()
466
+ updater.httpsOnly = true
467
+ let httpUrl = try XCTUnwrap(URL(string: "http://example.com/update.zip"))
468
+ XCTAssertThrowsError(
469
+ try updater.downloadVerified(url: httpUrl, version: "1.0.0", sessionKey: "", expectedChecksum: "abc")
470
+ ) { error in
471
+ XCTAssertEqual(
472
+ (error as NSError).localizedDescription,
473
+ "httpsOnly is enabled and http://example.com/update.zip is not https"
474
+ )
475
+ }
476
+ let manifest = [
477
+ ManifestEntry(file_name: "index.html", file_hash: "00", download_url: "http://example.com/f")
478
+ ]
479
+ XCTAssertThrowsError(
480
+ try updater.downloadManifest(manifest: manifest, version: "1.0.0", sessionKey: "")
481
+ ) { error in
482
+ XCTAssertEqual((error as NSError).code, 7)
483
+ }
484
+
485
+ let done = expectation(description: "raw task rejected")
486
+ var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:1/updates")))
487
+ request.timeoutInterval = 1
488
+ updater.startRawDataTask(request) { data, _, error in
489
+ XCTAssertNil(data)
490
+ XCTAssertEqual((error as NSError?)?.code, 7)
491
+ done.fulfill()
492
+ }
493
+ wait(for: [done], timeout: 5)
494
+
495
+ updater.httpsOnly = false
496
+ XCTAssertNil(updater.checkAllowedScheme(httpUrl))
497
+ }
498
+
499
+ func testHttpsOnlyBlocksRedirectToHttpEvenWhenDowngradeAllowed() throws {
500
+ let delegate = RedirectPolicyDelegate()
501
+ delegate.allowHttpsToHttpRedirect = true
502
+ delegate.httpsOnly = true
503
+ var blocked = false
504
+ delegate.onBlockedRedirect = { _, _ in blocked = true }
505
+ let session = URLSession(configuration: .ephemeral)
506
+ let task = session.dataTask(with: try XCTUnwrap(URL(string: "https://example.com/a")))
507
+ let sourceUrl = try XCTUnwrap(URL(string: "https://example.com/a"))
508
+ let response = try XCTUnwrap(
509
+ HTTPURLResponse(url: sourceUrl, statusCode: 302, httpVersion: nil, headerFields: nil)
510
+ )
511
+ let httpRequest = URLRequest(url: try XCTUnwrap(URL(string: "http://example.com/b")))
512
+ let placeholder = try XCTUnwrap(URL(string: "https://placeholder"))
513
+ var forwarded: URLRequest? = URLRequest(url: placeholder)
514
+ delegate.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: httpRequest) {
515
+ forwarded = $0
516
+ }
517
+ XCTAssertNil(forwarded)
518
+ XCTAssertTrue(blocked)
519
+
520
+ delegate.httpsOnly = false
521
+ blocked = false
522
+ delegate.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: httpRequest) {
523
+ forwarded = $0
524
+ }
525
+ XCTAssertNotNil(forwarded)
526
+ XCTAssertFalse(blocked)
527
+ }
528
+ }