@capgo/capacitor-updater 9.0.0 → 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 (109) hide show
  1. package/CapgoCapacitorUpdater.podspec +3 -6
  2. package/Package.swift +30 -0
  3. package/README.md +2406 -291
  4. package/android/build.gradle +37 -17
  5. package/android/consumer-rules.pro +48 -0
  6. package/android/proguard-rules.pro +23 -0
  7. package/android/src/main/AndroidManifest.xml +0 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +92 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +115 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +227 -195
  11. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +24 -23
  12. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +7927 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5785 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +564 -121
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +43 -49
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +4 -4
  19. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
  20. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +230 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +2041 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +301 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +569 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +436 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +604 -0
  26. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +79 -0
  27. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +419 -0
  28. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  29. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
  30. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +963 -0
  31. package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
  32. package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +323 -0
  33. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  34. package/dist/docs.json +4431 -840
  35. package/dist/esm/definitions.d.ts +2641 -225
  36. package/dist/esm/definitions.js +103 -1
  37. package/dist/esm/definitions.js.map +1 -1
  38. package/dist/esm/history.d.ts +1 -0
  39. package/dist/esm/history.js +283 -0
  40. package/dist/esm/history.js.map +1 -0
  41. package/dist/esm/index.d.ts +3 -2
  42. package/dist/esm/index.js +5 -4
  43. package/dist/esm/index.js.map +1 -1
  44. package/dist/esm/web.d.ts +53 -42
  45. package/dist/esm/web.js +180 -37
  46. package/dist/esm/web.js.map +1 -1
  47. package/dist/plugin.cjs.js +570 -37
  48. package/dist/plugin.cjs.js.map +1 -1
  49. package/dist/plugin.js +570 -37
  50. package/dist/plugin.js.map +1 -1
  51. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
  52. package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
  53. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
  54. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
  55. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +6813 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +200 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +5099 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +387 -0
  60. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
  61. package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
  62. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +452 -0
  63. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +380 -0
  64. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  65. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
  66. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +97 -0
  67. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +876 -0
  68. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
  69. package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
  70. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +304 -0
  71. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  72. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  73. package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
  74. package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
  75. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +6533 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +156 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +314 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +653 -0
  80. package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
  81. package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
  82. package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
  83. package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
  84. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1109 -0
  85. package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
  86. package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
  87. package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
  88. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +196 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +470 -0
  91. package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
  92. package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
  93. package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
  94. package/package.json +80 -43
  95. package/scripts/builtin-hashes-lib.mjs +148 -0
  96. package/scripts/capacitor-builtin-hashes-hook.mjs +65 -0
  97. package/scripts/resolve-real-path.mjs +25 -0
  98. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +0 -1130
  99. package/ios/Plugin/BundleInfo.swift +0 -113
  100. package/ios/Plugin/BundleStatus.swift +0 -48
  101. package/ios/Plugin/CapacitorUpdater.swift +0 -858
  102. package/ios/Plugin/CapacitorUpdaterPlugin.h +0 -10
  103. package/ios/Plugin/CapacitorUpdaterPlugin.m +0 -27
  104. package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -677
  105. package/ios/Plugin/CryptoCipher.swift +0 -240
  106. /package/{LICENCE → LICENSE} +0 -0
  107. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
  108. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
  109. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
@@ -0,0 +1,653 @@
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(statsUrl: String = "captured-by-test-double") -> StatsTrackingCapgoUpdater {
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)
27
+ updater.setLogger(Logger(withTag: "HttpsOnlyBuiltinMinimumTests", options: Logger.Options(level: .silent)))
28
+ return updater
29
+ }
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
+
47
+ /// Builds fixture URLs from the endpoint or launch-intent components required by each test.
48
+ private func makeFixtureURL(scheme: String, host: String, pathComponent: String) throws -> URL {
49
+ var components = URLComponents()
50
+ components.scheme = scheme
51
+ components.host = host
52
+ components.path = "/" + pathComponent
53
+ return try XCTUnwrap(components.url)
54
+ }
55
+
56
+ private final class ReloadTrackingPlugin: CapacitorUpdaterPlugin {
57
+ var reloadCalls = 0
58
+
59
+ /// Simulates a successful WebView reload and records whether activation reached that step.
60
+ override func reloadCurrentBundle() -> Bool {
61
+ reloadCalls += 1
62
+ return true
63
+ }
64
+
65
+ override func restoreLiveBundleStateAfterFailedReload() {
66
+ // This test has no WebView bridge to restore; it verifies the persisted bundle state instead.
67
+ }
68
+ }
69
+
70
+ /// Persists a real downloaded bundle and restores the active, fallback and pending state after the test.
71
+ private func withStoredBundle(
72
+ version: String,
73
+ _ body: (StatsTrackingCapgoUpdater, BundleInfo) throws -> Void
74
+ ) throws {
75
+ let updater = makeUpdater()
76
+ let previousState = updater.captureResetState()
77
+ let bundle = BundleInfo(id: UUID().uuidString, version: version, status: .SUCCESS, downloaded: Date(), checksum: "abc")
78
+ let directory = try updater.getBundleDirectory(id: bundle.getId())
79
+ defer {
80
+ updater.restoreResetState(previousState)
81
+ updater.saveBundleInfo(id: bundle.getId(), bundle: nil)
82
+ try? FileManager.default.removeItem(at: directory)
83
+ updater.shutdown()
84
+ }
85
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
86
+ try "<html>retained bundle</html>".write(to: directory.appendingPathComponent("index.html"), atomically: true, encoding: .utf8)
87
+ XCTAssertTrue(updater.saveBundleInfo(id: bundle.getId(), bundle: bundle))
88
+ updater.prepareResetStateForTransition()
89
+ updater.versionBuild = "2.0.0"
90
+ try body(updater, bundle)
91
+ }
92
+
93
+ func testDefaultsAreHttpsOnlyOnAndBuiltinMinimumOn() throws {
94
+ let updater = makeUpdater()
95
+ XCTAssertTrue(updater.httpsOnly)
96
+ XCTAssertTrue(updater.builtinMinimum)
97
+ XCTAssertTrue(RedirectPolicyDelegate().httpsOnly)
98
+ updater.versionBuild = "2.0.0"
99
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.0"))
100
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.0.0"))
101
+ XCTAssertNotNil(updater.checkAllowedScheme(try XCTUnwrap(URL(string: "http://example.com/a.zip"))))
102
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native"])
103
+ }
104
+
105
+ // MARK: - builtinMinimum
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
+
123
+ func testBuiltinMinimumRejectsVersionBelowNative() throws {
124
+ let updater = makeUpdater()
125
+ updater.builtinMinimum = true
126
+ updater.versionBuild = "2.0.0"
127
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9")) { error in
128
+ XCTAssertEqual((error as NSError).code, 8)
129
+ XCTAssertEqual(
130
+ (error as NSError).localizedDescription,
131
+ "Bundle version 1.9.9 is below native version 2.0.0 (builtinMinimum)"
132
+ )
133
+ }
134
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native"])
135
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.0"))
136
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.1"))
137
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.0-beta.1"))
138
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9-rc.1"))
139
+ // Dotted build metadata must not disable the floor.
140
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9+build.42"))
141
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("2.0.0+build.42"))
142
+ updater.versionBuild = "2.0.0+ci.7"
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
+ }
159
+ // Unparseable versions never block.
160
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("builtin"))
161
+ updater.versionBuild = "not-a-version"
162
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("0.0.1"))
163
+ }
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
+
210
+ func testBuiltinMinimumGatesDownloadBeforeNetwork() throws {
211
+ let updater = makeUpdater()
212
+ updater.builtinMinimum = true
213
+ updater.versionBuild = "3.0.0"
214
+ let url = try XCTUnwrap(URL(string: "https://example.com/update.zip"))
215
+ XCTAssertThrowsError(
216
+ try updater.downloadVerified(url: url, version: "2.0.0", sessionKey: "", expectedChecksum: "abc")
217
+ ) { error in
218
+ XCTAssertEqual((error as NSError).code, 8)
219
+ }
220
+ let manifest = [
221
+ ManifestEntry(file_name: "index.html", file_hash: "00", download_url: "https://example.com/f")
222
+ ]
223
+ XCTAssertThrowsError(
224
+ try updater.downloadManifest(manifest: manifest, version: "2.0.0", sessionKey: "")
225
+ ) { error in
226
+ XCTAssertEqual((error as NSError).code, 8)
227
+ }
228
+ }
229
+
230
+ /// Runs real startup preparation while preserving prior session markers between cases.
231
+ private func startRetainedBundle(
232
+ _ updater: StatsTrackingCapgoUpdater,
233
+ plugin: CapacitorUpdaterPlugin = CapacitorUpdaterPlugin(),
234
+ nativeBuildVersionChanged: Bool = true
235
+ ) throws -> Bool {
236
+ let defaults = UserDefaults.standard
237
+ let sessionKeys = [
238
+ "LatestNativeBuildVersion",
239
+ "CapacitorUpdater.appSessionId",
240
+ "CapacitorUpdater.appSessionForeground",
241
+ "CapacitorUpdater.appSessionStartedAt",
242
+ "CapacitorUpdater.lastReportedUncleanSessionId"
243
+ ]
244
+ let previousValues = sessionKeys.map { defaults.object(forKey: $0) }
245
+ defer {
246
+ for (key, value) in zip(sessionKeys, previousValues) {
247
+ if let value {
248
+ defaults.set(value, forKey: key)
249
+ } else {
250
+ defaults.removeObject(forKey: key)
251
+ }
252
+ }
253
+ defaults.synchronize()
254
+ }
255
+ sessionKeys.forEach { defaults.removeObject(forKey: $0) }
256
+ defaults.set(nativeBuildVersionChanged ? "1" : "2", forKey: "LatestNativeBuildVersion")
257
+ updater.statsUrl = try makeFixtureURL(scheme: "https", host: "example.com", pathComponent: "stats").absoluteString
258
+ install(updater, into: plugin)
259
+ plugin.setCurrentBuildVersionForTesting("2")
260
+ return plugin.resetStartupBundleAndReportAppLaunchStartForTesting(
261
+ resetWhenUpdate: false,
262
+ nativeBuildVersionChanged: nativeBuildVersionChanged
263
+ )
264
+ }
265
+
266
+ /// A native upgrade must boot builtin even when the app preserves downloaded bundles across upgrades.
267
+ func testStartupRejectsRetainedBundleBelowNativeWithoutDeletingIt() throws {
268
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
269
+ let directory = try updater.getBundleDirectory(id: bundle.getId())
270
+ updater.restoreResetState(.init(
271
+ currentBundlePath: directory.path,
272
+ fallbackBundleId: bundle.getId(),
273
+ nextBundleId: bundle.getId()
274
+ ))
275
+
276
+ XCTAssertTrue(try startRetainedBundle(updater))
277
+
278
+ XCTAssertTrue(updater.getCurrentBundle().isBuiltin())
279
+ XCTAssertTrue(updater.getFallbackBundle().isBuiltin())
280
+ XCTAssertTrue(updater.getNextBundle()?.isUnknown() ?? true)
281
+ XCTAssertTrue(updater.bundleExists(id: bundle.getId()))
282
+ XCTAssertEqual(updater.getBundleInfo(id: bundle.getId()).getStatus(), BundleStatus.SUCCESS.storedValue)
283
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native", "app_launch_start"])
284
+ XCTAssertEqual(updater.sentStatsVersions, ["1.9.9", "2.0.0"])
285
+ }
286
+ }
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
+
317
+ /// Startup preserves compatible or unparseable retained bundles and reports the version it will load.
318
+ func testStartupKeepsRetainedBundleAllowedByNativeFloor() throws {
319
+ for version in ["2.0.0", "2.0.1", "2.0.0-beta.1", "release-label"] {
320
+ try withStoredBundle(version: version) { updater, bundle in
321
+ let directory = try updater.getBundleDirectory(id: bundle.getId())
322
+ updater.restoreResetState(.init(
323
+ currentBundlePath: directory.path,
324
+ fallbackBundleId: bundle.getId(),
325
+ nextBundleId: bundle.getId()
326
+ ))
327
+
328
+ XCTAssertFalse(try startRetainedBundle(updater))
329
+
330
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
331
+ XCTAssertEqual(updater.getFallbackBundle().getId(), bundle.getId())
332
+ XCTAssertEqual(updater.getNextBundle()?.getId(), bundle.getId())
333
+ XCTAssertEqual(updater.getBundleInfo(id: bundle.getId()).getStatus(), BundleStatus.SUCCESS.storedValue)
334
+ XCTAssertEqual(updater.sentStatsActions, ["app_launch_start"])
335
+ XCTAssertEqual(updater.sentStatsVersions, [version])
336
+ }
337
+ }
338
+ }
339
+
340
+ /// Preview launch restoration must not select an older fallback after the startup floor has been checked.
341
+ func testStartupRejectsBelowNativeFallbackRestoredByPreviewLaunch() throws {
342
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
343
+ let defaults = UserDefaults.standard
344
+ let previousPreviewValues = defaults.dictionaryRepresentation().filter {
345
+ $0.key.hasPrefix("CapacitorUpdater.preview") || $0.key == "previewFallbackVersion"
346
+ }
347
+ let proxy = ApplicationDelegateProxy.shared
348
+ let previousLaunchURL = proxy.lastURL
349
+ let supportDirectory = try XCTUnwrap(FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first)
350
+ let snapshotFile = supportDirectory.appendingPathComponent("CapacitorUpdater.defaultChannelPreviewSnapshot")
351
+ let previousSnapshot = try FileManager.default.fileExists(atPath: snapshotFile.path) ? Data(contentsOf: snapshotFile) : nil
352
+ defer {
353
+ proxy.lastURL = previousLaunchURL
354
+ for key in defaults.dictionaryRepresentation().keys where key.hasPrefix("CapacitorUpdater.preview") || key == "previewFallbackVersion" {
355
+ defaults.removeObject(forKey: key)
356
+ }
357
+ previousPreviewValues.forEach { defaults.set($0.value, forKey: $0.key) }
358
+ if let previousSnapshot {
359
+ try? previousSnapshot.write(to: snapshotFile, options: .atomic)
360
+ } else {
361
+ try? FileManager.default.removeItem(at: snapshotFile)
362
+ }
363
+ defaults.synchronize()
364
+ }
365
+ previousPreviewValues.keys.forEach { defaults.removeObject(forKey: $0) }
366
+ let plugin = CapacitorUpdaterPlugin()
367
+ isolatePendingStats(plugin.implementation)
368
+ try plugin.invalidateDefaultChannelPreviewSnapshot(file: snapshotFile)
369
+ plugin.previewSessionEnabled = true
370
+ updater.previewSession = true
371
+ XCTAssertTrue(updater.setPreviewFallbackBundle(fallback: bundle.getId()))
372
+ proxy.lastURL = try makeFixtureURL(scheme: "capgo", host: "preview", pathComponent: "bundle")
373
+
374
+ XCTAssertTrue(updater.getCurrentBundle().isBuiltin())
375
+ XCTAssertTrue(try startRetainedBundle(updater, plugin: plugin, nativeBuildVersionChanged: false))
376
+
377
+ XCTAssertFalse(plugin.previewSessionEnabled)
378
+ XCTAssertTrue(updater.getCurrentBundle().isBuiltin())
379
+ XCTAssertTrue(updater.getFallbackBundle().isBuiltin())
380
+ XCTAssertTrue(updater.getNextBundle()?.isUnknown() ?? true)
381
+ XCTAssertTrue(updater.bundleExists(id: bundle.getId()))
382
+ XCTAssertEqual(updater.getBundleInfo(id: bundle.getId()).getStatus(), BundleStatus.SUCCESS.storedValue)
383
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native", "app_launch_start"])
384
+ XCTAssertEqual(updater.sentStatsVersions, ["1.9.9", "2.0.0"])
385
+ }
386
+ }
387
+
388
+ /// Explicit opt-out preserves an older stored current bundle at startup.
389
+ func testStartupAllowsRetainedBundleBelowNativeWhenMinimumDisabled() throws {
390
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
391
+ let directory = try updater.getBundleDirectory(id: bundle.getId())
392
+ updater.restoreResetState(.init(
393
+ currentBundlePath: directory.path,
394
+ fallbackBundleId: bundle.getId(),
395
+ nextBundleId: bundle.getId()
396
+ ))
397
+ updater.builtinMinimum = false
398
+
399
+ XCTAssertFalse(try startRetainedBundle(updater))
400
+
401
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
402
+ XCTAssertEqual(updater.getFallbackBundle().getId(), bundle.getId())
403
+ XCTAssertEqual(updater.getNextBundle()?.getId(), bundle.getId())
404
+ XCTAssertTrue(updater.bundleExists(id: bundle.getId()))
405
+ XCTAssertEqual(updater.sentStatsActions, ["app_launch_start"])
406
+ XCTAssertEqual(updater.sentStatsVersions, ["1.9.9"])
407
+ }
408
+ }
409
+
410
+ /// A native upgrade must not let manual set reactivate an older stored bundle or mark it corrupt.
411
+ func testManualSetRejectsRetainedBundleWithoutChangingState() throws {
412
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
413
+ let previousState = updater.captureResetState()
414
+
415
+ XCTAssertFalse(updater.set(id: bundle.getId()))
416
+
417
+ XCTAssertEqual(updater.captureResetState().currentBundlePath, previousState.currentBundlePath)
418
+ XCTAssertEqual(updater.getBundleInfo(id: bundle.getId()).getStatus(), BundleStatus.SUCCESS.storedValue)
419
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native"])
420
+ }
421
+ }
422
+
423
+ /// Explicit reload must reject an incompatible pending bundle before reloading or clearing its ID.
424
+ func testReloadRejectsRetainedBundleAndKeepsItPending() throws {
425
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
426
+ XCTAssertTrue(updater.setNextBundle(next: bundle.getId()))
427
+ let previousState = updater.captureResetState()
428
+ let plugin = ReloadTrackingPlugin()
429
+ install(updater, into: plugin)
430
+ var rejectionMessages: [String] = []
431
+ var rejectionCodes: [String?] = []
432
+ let call = try XCTUnwrap(CAPPluginCall(
433
+ callbackId: "reload-version-floor",
434
+ methodName: "reload",
435
+ options: [:],
436
+ success: { _, _ in XCTFail("Reload must reject the old bundle") },
437
+ error: { error in
438
+ rejectionMessages.append(error?.message ?? "")
439
+ rejectionCodes.append(error?.code)
440
+ }
441
+ ))
442
+
443
+ plugin.reload(call)
444
+ plugin.reload(call)
445
+
446
+ XCTAssertEqual(rejectionMessages, Array(repeating: "Bundle version 1.9.9 is below native version 2.0.0 (builtinMinimum)", count: 2))
447
+ XCTAssertEqual(rejectionCodes, ["VERSION_BELOW_NATIVE", "VERSION_BELOW_NATIVE"])
448
+ XCTAssertEqual(plugin.reloadCalls, 0)
449
+ XCTAssertEqual(updater.captureResetState().currentBundlePath, previousState.currentBundlePath)
450
+ XCTAssertEqual(updater.captureResetState().fallbackBundleId, previousState.fallbackBundleId)
451
+ XCTAssertEqual(updater.getNextBundle()?.getId(), bundle.getId())
452
+ XCTAssertEqual(updater.getBundleInfo(id: bundle.getId()).getStatus(), BundleStatus.PENDING.storedValue)
453
+ XCTAssertEqual(updater.sentStatsActions, ["set_next", "version_below_native"])
454
+ }
455
+ }
456
+
457
+ /// Manual set reports its policy rejection without reloading or reporting duplicate telemetry.
458
+ func testManualSetReportsVersionFloorRejection() throws {
459
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
460
+ let previousState = updater.captureResetState()
461
+ let plugin = ReloadTrackingPlugin()
462
+ install(updater, into: plugin)
463
+ var messages: [String] = []
464
+ var codes: [String?] = []
465
+ let call = try XCTUnwrap(CAPPluginCall(
466
+ callbackId: "set-version-floor",
467
+ methodName: "set",
468
+ options: ["id": bundle.getId()],
469
+ success: { _, _ in XCTFail("Set must reject the old bundle") },
470
+ error: { error in
471
+ messages.append(error?.message ?? "")
472
+ codes.append(error?.code)
473
+ }
474
+ ))
475
+
476
+ for status in [BundleStatus.SUCCESS, BundleStatus.ERROR] {
477
+ XCTAssertTrue(updater.saveBundleInfo(id: bundle.getId(), bundle: bundle.setStatus(status: status.storedValue)))
478
+ plugin.set(call)
479
+ XCTAssertEqual(updater.getBundleInfo(id: bundle.getId()).getStatus(), status.storedValue)
480
+ }
481
+
482
+ XCTAssertEqual(messages, Array(repeating: "Bundle version 1.9.9 is below native version 2.0.0 (builtinMinimum)", count: 2))
483
+ XCTAssertEqual(codes, ["VERSION_BELOW_NATIVE", "VERSION_BELOW_NATIVE"])
484
+ XCTAssertEqual(plugin.reloadCalls, 0)
485
+ XCTAssertEqual(updater.captureResetState().currentBundlePath, previousState.currentBundlePath)
486
+ XCTAssertEqual(updater.sentStatsActions, ["version_below_native"])
487
+ }
488
+ }
489
+
490
+ /// Below-native metadata cannot hide a genuinely missing bundle behind a version-floor error.
491
+ func testManualSetReportsMissingBundleInsteadOfVersionFloor() throws {
492
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
493
+ try FileManager.default.removeItem(at: updater.getBundleDirectory(id: bundle.getId()).appendingPathComponent("index.html"))
494
+ let plugin = ReloadTrackingPlugin()
495
+ install(updater, into: plugin)
496
+ var messages: [String] = []
497
+ var codes: [String?] = []
498
+ let call = try XCTUnwrap(CAPPluginCall(
499
+ callbackId: "set-missing-bundle",
500
+ methodName: "set",
501
+ options: ["id": bundle.getId()],
502
+ success: { _, _ in XCTFail("Set must reject the missing bundle") },
503
+ error: { error in
504
+ messages.append(error?.message ?? "")
505
+ codes.append(error?.code)
506
+ }
507
+ ))
508
+
509
+ plugin.set(call)
510
+
511
+ XCTAssertEqual(messages, ["Update failed, id \(bundle.getId()) doesn't exist"])
512
+ XCTAssertEqual(codes, [nil])
513
+ XCTAssertEqual(plugin.reloadCalls, 0)
514
+ XCTAssertTrue(updater.getCurrentBundle().isBuiltin())
515
+ XCTAssertEqual(updater.sentStatsActions, ["set_fail"])
516
+ }
517
+ }
518
+
519
+ /// Duplicate reporting is suppressed without caching validation or hiding changes to the native floor or opt-out.
520
+ func testVersionFloorStatsFollowPolicyChanges() throws {
521
+ let updater = makeUpdater()
522
+ updater.versionBuild = "2.0.0"
523
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
524
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
525
+ XCTAssertEqual(updater.sentStatsActions.count, 1)
526
+ updater.versionBuild = "3.0.0"
527
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
528
+ XCTAssertEqual(updater.sentStatsActions.count, 2)
529
+ updater.builtinMinimum = false
530
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("1.9.9"))
531
+ updater.builtinMinimum = true
532
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
533
+ XCTAssertEqual(updater.sentStatsActions.count, 3)
534
+ XCTAssertNoThrow(try updater.requireVersionNotBelowBuiltin("3.0.0"))
535
+ XCTAssertThrowsError(try updater.requireVersionNotBelowBuiltin("1.9.9"))
536
+ XCTAssertEqual(updater.sentStatsActions.count, 4)
537
+ }
538
+
539
+ /// Both activation entry points accept stored bundles at or above the native version.
540
+ func testStoredBundleActivationAcceptsEqualOrNewerVersions() throws {
541
+ for version in ["2.0.0", "2.0.1"] {
542
+ try withStoredBundle(version: version) { updater, bundle in
543
+ XCTAssertTrue(updater.set(id: bundle.getId()))
544
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
545
+ updater.prepareResetStateForTransition()
546
+ XCTAssertTrue(updater.stagePendingReload(bundle: bundle))
547
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
548
+ }
549
+ }
550
+ }
551
+
552
+ /// Independent web versioning still works when the app explicitly disables the version floor.
553
+ func testStoredBundleActivationAllowsExplicitOptOut() throws {
554
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
555
+ updater.builtinMinimum = false
556
+ XCTAssertTrue(updater.set(id: bundle.getId()))
557
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
558
+ updater.prepareResetStateForTransition()
559
+ XCTAssertTrue(updater.stagePendingReload(bundle: bundle))
560
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
561
+ }
562
+ }
563
+
564
+ /// A rejected pending update must not prevent the app from resetting to its builtin bundle.
565
+ func testBuiltinResetClearsRejectedPendingBundle() throws {
566
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
567
+ XCTAssertTrue(updater.setNextBundle(next: bundle.getId()))
568
+ XCTAssertFalse(updater.stagePendingReload(bundle: bundle))
569
+
570
+ XCTAssertTrue(updater.set(id: BundleInfo.ID_BUILTIN))
571
+
572
+ XCTAssertTrue(updater.getCurrentBundle().isBuiltin())
573
+ XCTAssertTrue(updater.getNextBundle()?.isUnknown() ?? true)
574
+ }
575
+ }
576
+
577
+ /// Restoring a WebView's previous bundle after a failed transition is not a new activation.
578
+ func testFailedReloadCanRestoreAnExistingOlderBundle() throws {
579
+ try withStoredBundle(version: "1.9.9") { updater, bundle in
580
+ updater.restoreCurrentBundle(bundle)
581
+
582
+ XCTAssertEqual(updater.getCurrentBundleId(), bundle.getId())
583
+ XCTAssertTrue(updater.sentStatsActions.isEmpty)
584
+ }
585
+ }
586
+
587
+ // MARK: - httpsOnly
588
+
589
+ func testHttpsOnlyRejectsPlainHttpBeforeNetwork() throws {
590
+ let updater = makeUpdater()
591
+ updater.httpsOnly = true
592
+ let httpUrl = try XCTUnwrap(URL(string: "http://example.com/update.zip"))
593
+ XCTAssertThrowsError(
594
+ try updater.downloadVerified(url: httpUrl, version: "1.0.0", sessionKey: "", expectedChecksum: "abc")
595
+ ) { error in
596
+ XCTAssertEqual(
597
+ (error as NSError).localizedDescription,
598
+ "httpsOnly is enabled and http://example.com/update.zip is not https"
599
+ )
600
+ }
601
+ let manifest = [
602
+ ManifestEntry(file_name: "index.html", file_hash: "00", download_url: "http://example.com/f")
603
+ ]
604
+ XCTAssertThrowsError(
605
+ try updater.downloadManifest(manifest: manifest, version: "1.0.0", sessionKey: "")
606
+ ) { error in
607
+ XCTAssertEqual((error as NSError).code, 7)
608
+ }
609
+
610
+ let done = expectation(description: "raw task rejected")
611
+ var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:1/updates")))
612
+ request.timeoutInterval = 1
613
+ updater.startRawDataTask(request) { data, _, error in
614
+ XCTAssertNil(data)
615
+ XCTAssertEqual((error as NSError?)?.code, 7)
616
+ done.fulfill()
617
+ }
618
+ wait(for: [done], timeout: 5)
619
+
620
+ updater.httpsOnly = false
621
+ XCTAssertNil(updater.checkAllowedScheme(httpUrl))
622
+ }
623
+
624
+ func testHttpsOnlyBlocksRedirectToHttpEvenWhenDowngradeAllowed() throws {
625
+ let delegate = RedirectPolicyDelegate()
626
+ delegate.allowHttpsToHttpRedirect = true
627
+ delegate.httpsOnly = true
628
+ var blocked = false
629
+ delegate.onBlockedRedirect = { _, _ in blocked = true }
630
+ let session = URLSession(configuration: .ephemeral)
631
+ let task = session.dataTask(with: try XCTUnwrap(URL(string: "https://example.com/a")))
632
+ let sourceUrl = try XCTUnwrap(URL(string: "https://example.com/a"))
633
+ let response = try XCTUnwrap(
634
+ HTTPURLResponse(url: sourceUrl, statusCode: 302, httpVersion: nil, headerFields: nil)
635
+ )
636
+ let httpRequest = URLRequest(url: try XCTUnwrap(URL(string: "http://example.com/b")))
637
+ let placeholder = try XCTUnwrap(URL(string: "https://placeholder"))
638
+ var forwarded: URLRequest? = URLRequest(url: placeholder)
639
+ delegate.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: httpRequest) {
640
+ forwarded = $0
641
+ }
642
+ XCTAssertNil(forwarded)
643
+ XCTAssertTrue(blocked)
644
+
645
+ delegate.httpsOnly = false
646
+ blocked = false
647
+ delegate.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: httpRequest) {
648
+ forwarded = $0
649
+ }
650
+ XCTAssertNotNil(forwarded)
651
+ XCTAssertFalse(blocked)
652
+ }
653
+ }