@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,470 @@
1
+ import XCTest
2
+ @testable import CapacitorUpdaterPlugin
3
+ import Capacitor
4
+
5
+ private final class LifecycleCapgoUpdater: CapgoUpdater {
6
+ var currentBundleValue = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "abc")
7
+ var nextBundleValue: BundleInfo?
8
+ var downloadedBundleValue: BundleInfo?
9
+ var latestResponse = AppVersion()
10
+ var getLatestCalls = 0
11
+ var downloadCalls = 0
12
+ var setErrorCalls = 0
13
+ private let statsLock = NSLock()
14
+ private var sentStats: [String] = []
15
+
16
+ func statCount(_ action: String) -> Int {
17
+ statsLock.lock()
18
+ defer { statsLock.unlock() }
19
+ return sentStats.filter { $0 == action }.count
20
+ }
21
+
22
+ private func record(_ action: String) {
23
+ statsLock.lock()
24
+ sentStats.append(action)
25
+ statsLock.unlock()
26
+ }
27
+
28
+ override func getLatest(url: URL, channel: String?, appIdOverride: String? = nil) -> AppVersion {
29
+ getLatestCalls += 1
30
+ return latestResponse
31
+ }
32
+
33
+ override func getCurrentBundle() -> BundleInfo {
34
+ currentBundleValue
35
+ }
36
+
37
+ override func getNextBundle() -> BundleInfo? {
38
+ nextBundleValue
39
+ }
40
+
41
+ var setBundleCalls: [String] = []
42
+
43
+ override func setNextBundle(next: String?) -> Bool {
44
+ if next == nil {
45
+ nextBundleValue = nil
46
+ } else if let downloadedBundleValue, downloadedBundleValue.getId() == next {
47
+ nextBundleValue = downloadedBundleValue
48
+ }
49
+ return true
50
+ }
51
+
52
+ override func set(bundle: BundleInfo) -> Bool {
53
+ setBundleCalls.append(bundle.getId())
54
+ currentBundleValue = bundle
55
+ return true
56
+ }
57
+
58
+ private var savedCurrentForReset: BundleInfo?
59
+ private var savedNextForReset: BundleInfo?
60
+
61
+ override func captureResetState() -> ResetState {
62
+ savedCurrentForReset = currentBundleValue
63
+ savedNextForReset = nextBundleValue
64
+ return ResetState(
65
+ currentBundlePath: currentBundleValue.getId(),
66
+ fallbackBundleId: BundleInfo.ID_BUILTIN,
67
+ nextBundleId: nextBundleValue?.getId()
68
+ )
69
+ }
70
+
71
+ override func restoreResetState(_ state: ResetState) {
72
+ if let savedCurrentForReset {
73
+ currentBundleValue = savedCurrentForReset
74
+ }
75
+ nextBundleValue = savedNextForReset
76
+ }
77
+
78
+ override func getBundleInfo(id: String?) -> BundleInfo {
79
+ currentBundleValue
80
+ }
81
+
82
+ override func getBundleInfoByVersionName(version: String) -> BundleInfo? {
83
+ nil
84
+ }
85
+
86
+ override func getBundleInfosByVersionName(version: String) -> [BundleInfo] {
87
+ []
88
+ }
89
+
90
+ override func download(url: URL, version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
91
+ try downloadVerified(
92
+ url: url,
93
+ version: version,
94
+ sessionKey: sessionKey,
95
+ expectedChecksum: "",
96
+ link: link,
97
+ comment: comment
98
+ )
99
+ }
100
+
101
+ override func downloadVerifiedWithTransferHook(
102
+ url _: URL,
103
+ version _: String,
104
+ sessionKey _: String,
105
+ expectedChecksum _: String,
106
+ link _: String?,
107
+ comment _: String?,
108
+ beforeTransfer: (() throws -> Void)?
109
+ ) throws -> BundleInfo {
110
+ try beforeTransfer?()
111
+ downloadCalls += 1
112
+ guard let downloadedBundleValue else {
113
+ throw NSError(domain: "UpdateLifecycleTests", code: 1)
114
+ }
115
+ return downloadedBundleValue
116
+ }
117
+
118
+ override func setError(bundle: BundleInfo) {
119
+ setErrorCalls += 1
120
+ currentBundleValue = bundle.setStatus(status: BundleStatus.ERROR.storedValue)
121
+ }
122
+
123
+ override func saveBundleInfo(id: String, bundle: BundleInfo?) -> Bool {
124
+ true
125
+ }
126
+
127
+ override func delete(id: String, removeInfo: Bool) -> Bool {
128
+ true
129
+ }
130
+
131
+ override func persistPendingStats() {}
132
+
133
+ override func sendStats(action: String, versionName: String? = nil, oldVersionName: String? = "") {
134
+ record(action)
135
+ }
136
+
137
+ override func sendStats(action: String, versionName: String?, oldVersionName: String?, metadata: [String: String]) {
138
+ record(action)
139
+ }
140
+
141
+ override func sendStats(action: String, versionName: String?, oldVersionName: String?, metadata: [String: String], onSent: @escaping () -> Void) {
142
+ record(action)
143
+ }
144
+ }
145
+
146
+ private final class LifecyclePlugin: CapacitorUpdaterPlugin {
147
+ private(set) var events: [String] = []
148
+ private(set) var payloads: [String: [String: Any]] = [:]
149
+ private(set) var readyMessages: [String] = []
150
+ // Matches the real plugin without a bridge: reloads fail unless a test opts in.
151
+ var reloadResult = false
152
+
153
+ override func reloadCurrentBundle() -> Bool {
154
+ reloadResult
155
+ }
156
+
157
+ /// Records the decoded updaterEvent type and payload.
158
+ override func notifyListeners(_ eventName: String, data: [String: Any]?, retainUntilConsumed retain: Bool) {
159
+ let event = decodeUpdaterEvent(eventName, data: data)
160
+ events.append(event.name)
161
+ if let payload = event.data {
162
+ payloads[event.name] = payload
163
+ }
164
+ }
165
+
166
+ override func endBackGroundTask() {}
167
+
168
+ override func beginDownloadBackgroundTask() {}
169
+
170
+ override func runBackgroundDownloadWork(_ work: @escaping () -> Void) {
171
+ work()
172
+ }
173
+
174
+ override func runGetLatestWork(_ work: @escaping () -> Void) {
175
+ work()
176
+ }
177
+
178
+ override func sendReadyToJs(current: BundleInfo, msg: String) {
179
+ readyMessages.append(msg)
180
+ }
181
+ }
182
+
183
+ final class UpdateLifecycleTests: XCTestCase {
184
+ private var plugin = LifecyclePlugin()
185
+ private var updater = LifecycleCapgoUpdater()
186
+ private let delayPreferencesKey = DelayUpdateUtils.DELAY_CONDITION_PREFERENCES
187
+ private let delayConditionModeKey = DelayUpdateUtils.DELAY_CONDITION_MODE_PREFERENCES
188
+ private let updateUrl = URL(string: "https://example.com/updates")!
189
+ private let lastFailedBundleKey = "CapacitorUpdater.lastFailedBundle"
190
+
191
+ override func setUpWithError() throws {
192
+ try super.setUpWithError()
193
+ let testLogger = Logger(withTag: "UpdateLifecycleTests", options: Logger.Options(level: .silent))
194
+ CryptoCipher.setLogger(testLogger)
195
+ updater = LifecycleCapgoUpdater()
196
+ updater.setLogger(testLogger)
197
+ plugin = LifecyclePlugin()
198
+ plugin.implementation = updater
199
+ plugin.setUpdateUrlForTesting(updateUrl.absoluteString)
200
+ plugin.setDelayUpdateUtilsForTesting(
201
+ DelayUpdateUtils(currentVersionNative: try CapgoSemanticVersion("1.0.0"), logger: Logger(withTag: "UpdateLifecycleTests"))
202
+ )
203
+ UserDefaults.standard.removeObject(forKey: delayPreferencesKey)
204
+ UserDefaults.standard.removeObject(forKey: delayConditionModeKey)
205
+ resetRetryState()
206
+ }
207
+
208
+ override func tearDown() {
209
+ UserDefaults.standard.removeObject(forKey: delayPreferencesKey)
210
+ UserDefaults.standard.removeObject(forKey: delayConditionModeKey)
211
+ UserDefaults.standard.removeObject(forKey: lastFailedBundleKey)
212
+ resetRetryState()
213
+ super.tearDown()
214
+ }
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
+
224
+ private func pendingBundle() -> BundleInfo {
225
+ BundleInfo(id: "bundle-2", version: "2.0.0", status: .PENDING, downloaded: Date(), checksum: "abc")
226
+ }
227
+
228
+ private func latest(version: String) -> AppVersion {
229
+ let latest = AppVersion()
230
+ latest.version = version
231
+ latest.url = "https://example.com/update.zip"
232
+ latest.checksum = "abc"
233
+ return latest
234
+ }
235
+
236
+ private func spinMainRunLoop(seconds: TimeInterval) {
237
+ let done = expectation(description: "main run loop")
238
+ DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
239
+ done.fulfill()
240
+ }
241
+ wait(for: [done], timeout: max(seconds + 5, 10))
242
+ }
243
+
244
+ // set() activated the pending next bundle but left it stored, so getNextBundle() kept
245
+ // returning the bundle that was already running.
246
+ func testClearNextBundleIfCurrentDropsTheRunningBundle() {
247
+ updater.currentBundleValue = pendingBundle()
248
+ updater.nextBundleValue = pendingBundle()
249
+
250
+ XCTAssertTrue(updater.clearNextBundleIfCurrent())
251
+ XCTAssertNil(updater.nextBundleValue)
252
+ }
253
+
254
+ func testClearNextBundleIfCurrentKeepsADifferentNextBundle() {
255
+ updater.nextBundleValue = pendingBundle()
256
+
257
+ XCTAssertFalse(updater.clearNextBundleIfCurrent())
258
+ XCTAssertEqual(updater.nextBundleValue?.getId(), "bundle-2")
259
+ }
260
+
261
+ // A suspended app can resume with the rollback timer already expired, before
262
+ // willEnterForeground re-arms it: the bundle must not be rolled back in background.
263
+ func testRollbackCheckWaitsForTheNextForegroundWhileInBackground() {
264
+ updater.currentBundleValue = pendingBundle()
265
+ plugin.setAppReadyTimeoutForTesting(10)
266
+
267
+ plugin.appMovedToBackground()
268
+ plugin.DeferredNotifyAppReadyCheck()
269
+
270
+ XCTAssertFalse(plugin.events.contains("updateFailed"))
271
+ XCTAssertEqual(updater.setErrorCalls, 0)
272
+
273
+ // The next foreground arms a fresh check, which rolls back a page that never confirmed.
274
+ plugin.appMovedToForeground()
275
+ spinMainRunLoop(seconds: 0.5)
276
+
277
+ XCTAssertTrue(plugin.events.contains("updateFailed"))
278
+ XCTAssertEqual(updater.setErrorCalls, 1)
279
+ }
280
+
281
+ func testRollbackCheckStillRunsInForeground() {
282
+ updater.currentBundleValue = pendingBundle()
283
+
284
+ plugin.DeferredNotifyAppReadyCheck()
285
+
286
+ XCTAssertTrue(plugin.events.contains("updateFailed"))
287
+ XCTAssertEqual(updater.setErrorCalls, 1)
288
+ }
289
+
290
+ // app_launch_timeout used to be sent on every rollback of the launch.
291
+ func testLaunchTimeoutIsReportedOncePerLaunch() {
292
+ updater.statsUrl = "https://stats.example.com"
293
+ updater.currentBundleValue = pendingBundle()
294
+ plugin.checkRevert()
295
+ updater.currentBundleValue = BundleInfo(id: "bundle-3", version: "3.0.0", status: .PENDING, downloaded: Date(), checksum: "abc")
296
+ plugin.checkRevert()
297
+
298
+ XCTAssertEqual(updater.statCount("update_fail"), 2)
299
+ XCTAssertEqual(updater.statCount("app_launch_timeout"), 1)
300
+ }
301
+
302
+ // The periodic check used to download on error responses (empty version != current).
303
+ func testPeriodicCheckReportsErrorResponsesWithoutDownloading() {
304
+ plugin.setAutoUpdateModeForTesting("atBackground")
305
+ let response = AppVersion()
306
+ response.error = "no_new_version_available"
307
+ response.kind = "up_to_date"
308
+ response.message = "No new version available"
309
+ updater.latestResponse = response
310
+
311
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
312
+
313
+ XCTAssertEqual(updater.getLatestCalls, 1)
314
+ XCTAssertEqual(plugin.payloads["updateCheckResult"]?["kind"] as? String, "up_to_date")
315
+ XCTAssertFalse(plugin.events.contains("downloadFailed"))
316
+ }
317
+
318
+ func testPeriodicCheckDoesNotDownloadTheCurrentVersion() {
319
+ plugin.setAutoUpdateModeForTesting("atBackground")
320
+ updater.latestResponse = latest(version: "1.0.0")
321
+
322
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
323
+
324
+ XCTAssertEqual(updater.getLatestCalls, 1)
325
+ XCTAssertFalse(plugin.events.contains("updateCheckResult"))
326
+ }
327
+
328
+ func testPeriodicCheckDownloadsANewVersion() {
329
+ plugin.setAutoUpdateModeForTesting("atBackground")
330
+ updater.latestResponse = latest(version: "2.0.0")
331
+ updater.downloadedBundleValue = pendingBundle()
332
+
333
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
334
+
335
+ XCTAssertEqual(updater.getLatestCalls, 2)
336
+ XCTAssertEqual(updater.downloadCalls, 1)
337
+ }
338
+
339
+ // A silent push downloaded the update in the background but only queued it, so the
340
+ // user opened the old bundle: the install waited for a didEnterBackground that a
341
+ // background launch never posts.
342
+ func testBackgroundDownloadInstallsRightAwayWhileInBackground() {
343
+ plugin.setAutoUpdateModeForTesting("atBackground")
344
+ updater.latestResponse = latest(version: "2.0.0")
345
+ updater.downloadedBundleValue = pendingBundle()
346
+ plugin.reloadResult = true
347
+ plugin.appMovedToBackground()
348
+
349
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
350
+
351
+ XCTAssertEqual(updater.setBundleCalls, ["bundle-2"])
352
+ XCTAssertEqual(updater.currentBundleValue.getId(), "bundle-2")
353
+ XCTAssertNil(updater.nextBundleValue)
354
+ let reported = plugin.payloads["noNeedUpdate"]?["bundle"] as? [String: Any]
355
+ XCTAssertEqual(reported?["id"] as? String, "bundle-2")
356
+ XCTAssertEqual(plugin.readyMessages.last, "update downloaded and installed in background")
357
+ }
358
+
359
+ func testFailedBackgroundReloadKeepsThePreviousBundleActive() {
360
+ plugin.setAutoUpdateModeForTesting("atBackground")
361
+ updater.latestResponse = latest(version: "2.0.0")
362
+ updater.downloadedBundleValue = pendingBundle()
363
+ plugin.appMovedToBackground()
364
+
365
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
366
+
367
+ XCTAssertEqual(updater.setBundleCalls, ["bundle-2"])
368
+ XCTAssertEqual(updater.currentBundleValue.getId(), "current-id")
369
+ XCTAssertEqual(updater.nextBundleValue?.getId(), "bundle-2")
370
+ let reported = plugin.payloads["noNeedUpdate"]?["bundle"] as? [String: Any]
371
+ XCTAssertEqual(reported?["id"] as? String, "current-id")
372
+ XCTAssertEqual(plugin.readyMessages.last, "update downloaded, will install next background")
373
+ }
374
+
375
+ func testForegroundDownloadWaitsForTheNextBackground() {
376
+ plugin.setAutoUpdateModeForTesting("atBackground")
377
+ updater.latestResponse = latest(version: "2.0.0")
378
+ updater.downloadedBundleValue = pendingBundle()
379
+
380
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
381
+
382
+ XCTAssertEqual(updater.setBundleCalls, [])
383
+ XCTAssertEqual(updater.nextBundleValue?.getId(), "bundle-2")
384
+ }
385
+
386
+ func testAlwaysModeDoesNotInstallQueuedBundleWhileInBackground() {
387
+ plugin.setAutoUpdateModeForTesting("always")
388
+ updater.latestResponse = latest(version: "2.0.0")
389
+ updater.downloadedBundleValue = pendingBundle()
390
+ plugin.appMovedToBackground()
391
+
392
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
393
+
394
+ XCTAssertEqual(updater.setBundleCalls, [])
395
+ XCTAssertEqual(updater.nextBundleValue?.getId(), "bundle-2")
396
+ }
397
+
398
+ func testOnLaunchRetriesQueuedBundleOnForegroundAfterFailedDirectReload() {
399
+ plugin.setAutoUpdateModeForTesting("onLaunch")
400
+ updater.latestResponse = latest(version: "2.0.0")
401
+ updater.downloadedBundleValue = pendingBundle()
402
+ plugin.reloadResult = false
403
+
404
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
405
+
406
+ XCTAssertEqual(updater.currentBundleValue.getId(), "current-id")
407
+ XCTAssertEqual(updater.nextBundleValue?.getId(), "bundle-2")
408
+
409
+ plugin.reloadResult = true
410
+ plugin.appMovedToForeground()
411
+
412
+ XCTAssertEqual(updater.setBundleCalls, ["bundle-2"])
413
+ XCTAssertEqual(updater.currentBundleValue.getId(), "bundle-2")
414
+ XCTAssertNil(updater.nextBundleValue)
415
+ }
416
+
417
+ // triggerUpdateCheck returned "preview_session" (not in the TS union) and never "unavailable".
418
+ func testTriggerUpdateCheckIsUnavailableWhenAutoUpdateIsDisabled() {
419
+ XCTAssertEqual(plugin.triggerBackgroundUpdateCheck(), "unavailable")
420
+ XCTAssertEqual(updater.getLatestCalls, 0)
421
+ }
422
+
423
+ func testTriggerUpdateCheckIsUnavailableDuringAPreviewSession() {
424
+ plugin.setAutoUpdateModeForTesting("atBackground")
425
+ plugin.previewSessionEnabled = true
426
+
427
+ XCTAssertEqual(plugin.triggerBackgroundUpdateCheck(), "unavailable")
428
+ XCTAssertEqual(updater.getLatestCalls, 0)
429
+ }
430
+
431
+ func testTriggerUpdateCheckQueuesWhenAutoUpdateIsEnabled() {
432
+ plugin.setAutoUpdateModeForTesting("atBackground")
433
+ updater.latestResponse = latest(version: "1.0.0")
434
+
435
+ XCTAssertEqual(plugin.triggerBackgroundUpdateCheck(), "queued")
436
+ XCTAssertEqual(updater.getLatestCalls, 1)
437
+ }
438
+
439
+ // Malformed stored delay conditions used to crash on `kind as! String`.
440
+ func testParseDelayConditionsDropsMalformedEntries() {
441
+ let json = #"[{"value":"1"},{"kind":1},"text",3,{"kind":"kill","value":""},{"kind":"background"}]"#
442
+
443
+ let conditions = DelayUpdateUtils.parseDelayConditions(json: json)
444
+
445
+ XCTAssertEqual(conditions.map { $0.getKind() }, ["kill", "background"])
446
+ XCTAssertTrue(DelayUpdateUtils.parseDelayConditions(json: "not json").isEmpty)
447
+ XCTAssertTrue(DelayUpdateUtils.parseDelayConditions(json: #"{"kind":"kill"}"#).isEmpty)
448
+ }
449
+
450
+ func testCheckCancelDelaySurvivesMalformedStoredConditions() throws {
451
+ UserDefaults.standard.set(#"[1,{"value":"1"},{"kind":"kill","value":""}]"#, forKey: delayPreferencesKey)
452
+
453
+ plugin.appMovedToBackground()
454
+
455
+ let stored = try XCTUnwrap(UserDefaults.standard.string(forKey: delayPreferencesKey))
456
+ XCTAssertEqual(DelayUpdateUtils.parseDelayConditions(json: stored).map { $0.getKind() }, ["kill"])
457
+ }
458
+
459
+ func testDirectUpdateSurvivesMalformedStoredConditions() {
460
+ plugin.configureDirectUpdateModeForTesting("always")
461
+ updater.latestResponse = latest(version: "2.0.0")
462
+ updater.downloadedBundleValue = pendingBundle()
463
+ UserDefaults.standard.set(#"[{"value":"1"},{"kind":"kill","value":""}]"#, forKey: delayPreferencesKey)
464
+
465
+ plugin.backgroundDownload()
466
+
467
+ XCTAssertEqual(updater.downloadCalls, 1)
468
+ XCTAssertEqual(plugin.readyMessages, ["Update delayed until delay conditions met"])
469
+ }
470
+ }
@@ -0,0 +1,32 @@
1
+ import XCTest
2
+
3
+ final class WebKitOverlayGuardTests: XCTestCase {
4
+ func testPluginSourcesAvoidSwiftWebKitOverlayCallAsyncJavaScript() throws {
5
+ let testsDir = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
6
+ let pluginSources = testsDir
7
+ .deletingLastPathComponent()
8
+ .deletingLastPathComponent()
9
+ .appendingPathComponent("Sources/CapacitorUpdaterPlugin", isDirectory: true)
10
+
11
+ let files = try FileManager.default.contentsOfDirectory(
12
+ at: pluginSources,
13
+ includingPropertiesForKeys: nil
14
+ ).filter { $0.pathExtension == "swift" }
15
+
16
+ var violations: [String] = []
17
+ for file in files {
18
+ let lines = try String(contentsOf: file, encoding: .utf8).split(separator: "\n", omittingEmptySubsequences: false)
19
+ for (index, line) in lines.enumerated() {
20
+ let trimmed = line.trimmingCharacters(in: .whitespaces)
21
+ if trimmed.hasPrefix("//") || trimmed.hasPrefix("*") {
22
+ continue
23
+ }
24
+ if line.contains("callAsyncJavaScript("), !line.contains("__callAsyncJavaScript(") {
25
+ violations.append("\(file.lastPathComponent):\(index + 1)")
26
+ }
27
+ }
28
+ }
29
+
30
+ XCTAssertTrue(violations.isEmpty, "Swift WebKit overlay callAsyncJavaScript found: \(violations.joined(separator: ", "))")
31
+ }
32
+ }