@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,235 @@
1
+ import Compression
2
+ import Foundation
3
+
4
+ /// Test-only ZIP writer used to build fixtures for the in-repo ZIP reader.
5
+ /// Supports stored and deflate entries, unix modes (directories, symlinks) and optional ZIP64 records.
6
+ struct TestZipWriter {
7
+ enum Method: UInt16 {
8
+ case stored = 0
9
+ case deflate = 8
10
+ }
11
+
12
+ struct EntrySpec {
13
+ var path: String
14
+ var data: Data
15
+ var method: Method = .stored
16
+ /// Unix mode stored in the high 16 bits of the external attributes (e.g. 0o100644, 0o040755, 0o120777).
17
+ var unixMode: UInt32?
18
+ var generalPurposeFlags: UInt16 = 0x0800 // UTF-8 names
19
+ var forceZip64: Bool = false
20
+ /// Raw name bytes, used instead of the UTF-8 encoding of `path` when set.
21
+ var rawName: Data?
22
+ }
23
+
24
+ private(set) var entries: [EntrySpec] = []
25
+
26
+ mutating func addFile(_ path: String, _ data: Data, method: Method = .stored, unixMode: UInt32? = 0o100644) {
27
+ entries.append(EntrySpec(path: path, data: data, method: method, unixMode: unixMode))
28
+ }
29
+
30
+ mutating func addDirectory(_ path: String) {
31
+ entries.append(EntrySpec(path: path.hasSuffix("/") ? path : "\(path)/", data: Data(), unixMode: 0o040755))
32
+ }
33
+
34
+ mutating func addSymlink(_ path: String, target: String, method: Method = .stored) {
35
+ entries.append(EntrySpec(path: path, data: Data(target.utf8), method: method, unixMode: 0o120777))
36
+ }
37
+
38
+ mutating func add(_ spec: EntrySpec) {
39
+ entries.append(spec)
40
+ }
41
+
42
+ func build(zip64: Bool = false, comment: String = "") -> Data {
43
+ var output = Data()
44
+ var central = Data()
45
+ for entry in entries {
46
+ let offset = UInt64(output.count)
47
+ let record = Record(entry: entry, zip64: zip64 || entry.forceZip64)
48
+ output.append(record.localHeaderAndPayload())
49
+ central.append(record.centralDirectoryEntry(localHeaderOffset: offset))
50
+ }
51
+
52
+ let centralOffset = UInt64(output.count)
53
+ output.append(central)
54
+ if zip64 {
55
+ output.append(zip64EndRecords(centralSize: central.count, centralOffset: centralOffset, recordOffset: UInt64(output.count)))
56
+ }
57
+
58
+ let commentData = Data(comment.utf8)
59
+ output.appendUInt32(0x0605_4b50)
60
+ output.appendUInt16(0)
61
+ output.appendUInt16(0)
62
+ output.appendUInt16(zip64 ? 0xFFFF : UInt16(entries.count))
63
+ output.appendUInt16(zip64 ? 0xFFFF : UInt16(entries.count))
64
+ output.appendUInt32(zip64 ? 0xFFFF_FFFF : UInt32(central.count))
65
+ output.appendUInt32(zip64 ? 0xFFFF_FFFF : UInt32(centralOffset))
66
+ output.appendUInt16(UInt16(commentData.count))
67
+ output.append(commentData)
68
+ return output
69
+ }
70
+
71
+ private func zip64EndRecords(centralSize: Int, centralOffset: UInt64, recordOffset: UInt64) -> Data {
72
+ var output = Data()
73
+ output.appendUInt32(0x0606_4b50)
74
+ output.appendUInt64(44)
75
+ output.appendUInt16((3 << 8) | 63)
76
+ output.appendUInt16(45)
77
+ output.appendUInt32(0)
78
+ output.appendUInt32(0)
79
+ output.appendUInt64(UInt64(entries.count))
80
+ output.appendUInt64(UInt64(entries.count))
81
+ output.appendUInt64(UInt64(centralSize))
82
+ output.appendUInt64(centralOffset)
83
+
84
+ output.appendUInt32(0x0706_4b50)
85
+ output.appendUInt32(0)
86
+ output.appendUInt64(recordOffset)
87
+ output.appendUInt32(1)
88
+ return output
89
+ }
90
+
91
+ private struct Record {
92
+ let entry: EntrySpec
93
+ let zip64: Bool
94
+ let nameData: Data
95
+ let payload: Data
96
+ let crc: UInt32
97
+
98
+ init(entry: EntrySpec, zip64: Bool) {
99
+ self.entry = entry
100
+ self.zip64 = zip64
101
+ self.nameData = entry.rawName ?? Data(entry.path.utf8)
102
+ self.payload = entry.method == .deflate ? TestZipWriter.deflate(entry.data) : entry.data
103
+ self.crc = TestZipWriter.crc32(entry.data)
104
+ }
105
+
106
+ func localHeaderAndPayload() -> Data {
107
+ var extra = Data()
108
+ if zip64 {
109
+ extra.appendUInt16(0x0001)
110
+ extra.appendUInt16(16)
111
+ extra.appendUInt64(UInt64(entry.data.count))
112
+ extra.appendUInt64(UInt64(payload.count))
113
+ }
114
+ var output = Data()
115
+ output.appendUInt32(0x0403_4b50)
116
+ output.appendUInt16(zip64 ? 45 : 20)
117
+ output.appendUInt16(entry.generalPurposeFlags)
118
+ output.appendUInt16(entry.method.rawValue)
119
+ output.appendUInt32(0) // time + date
120
+ output.appendUInt32(crc)
121
+ output.appendUInt32(zip64 ? 0xFFFF_FFFF : UInt32(payload.count))
122
+ output.appendUInt32(zip64 ? 0xFFFF_FFFF : UInt32(entry.data.count))
123
+ output.appendUInt16(UInt16(nameData.count))
124
+ output.appendUInt16(UInt16(extra.count))
125
+ output.append(nameData)
126
+ output.append(extra)
127
+ output.append(payload)
128
+ return output
129
+ }
130
+
131
+ func centralDirectoryEntry(localHeaderOffset: UInt64) -> Data {
132
+ var extra = Data()
133
+ if zip64 {
134
+ extra.appendUInt16(0x0001)
135
+ extra.appendUInt16(24)
136
+ extra.appendUInt64(UInt64(entry.data.count))
137
+ extra.appendUInt64(UInt64(payload.count))
138
+ extra.appendUInt64(localHeaderOffset)
139
+ }
140
+ var output = Data()
141
+ output.appendUInt32(0x0201_4b50)
142
+ output.appendUInt16(entry.unixMode != nil ? (3 << 8) | 63 : 20)
143
+ output.appendUInt16(zip64 ? 45 : 20)
144
+ output.appendUInt16(entry.generalPurposeFlags)
145
+ output.appendUInt16(entry.method.rawValue)
146
+ output.appendUInt32(0) // time + date
147
+ output.appendUInt32(crc)
148
+ output.appendUInt32(zip64 ? 0xFFFF_FFFF : UInt32(payload.count))
149
+ output.appendUInt32(zip64 ? 0xFFFF_FFFF : UInt32(entry.data.count))
150
+ output.appendUInt16(UInt16(nameData.count))
151
+ output.appendUInt16(UInt16(extra.count))
152
+ output.appendUInt16(0) // comment length
153
+ output.appendUInt16(0) // disk number
154
+ output.appendUInt16(0) // internal attributes
155
+ output.appendUInt32((entry.unixMode ?? 0) << 16)
156
+ output.appendUInt32(zip64 ? 0xFFFF_FFFF : UInt32(localHeaderOffset))
157
+ output.append(nameData)
158
+ output.append(extra)
159
+ return output
160
+ }
161
+ }
162
+
163
+ func write(to url: URL, zip64: Bool = false) throws {
164
+ try build(zip64: zip64).write(to: url)
165
+ }
166
+
167
+ /// Raw DEFLATE (RFC 1951) encoding via Apple's Compression framework, streamed so large inputs work.
168
+ static func deflate(_ data: Data) -> Data {
169
+ let stream = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
170
+ defer { stream.deallocate() }
171
+ guard compression_stream_init(stream, COMPRESSION_STREAM_ENCODE, COMPRESSION_ZLIB) == COMPRESSION_STATUS_OK else {
172
+ fatalError("compression_stream_init failed")
173
+ }
174
+ defer { compression_stream_destroy(stream) }
175
+
176
+ let bufferSize = 64 * 1024
177
+ let destination = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
178
+ defer { destination.deallocate() }
179
+ var output = Data()
180
+
181
+ data.withUnsafeBytes { (raw: UnsafeRawBufferPointer) in
182
+ let base = raw.bindMemory(to: UInt8.self).baseAddress
183
+ // An empty input still needs a valid source pointer.
184
+ var emptyByte: UInt8 = 0
185
+ withUnsafePointer(to: &emptyByte) { emptyPointer in
186
+ stream.pointee.src_ptr = base ?? emptyPointer
187
+ stream.pointee.src_size = data.count
188
+ var status = COMPRESSION_STATUS_OK
189
+ repeat {
190
+ stream.pointee.dst_ptr = destination
191
+ stream.pointee.dst_size = bufferSize
192
+ status = compression_stream_process(stream, Int32(COMPRESSION_STREAM_FINALIZE.rawValue))
193
+ output.append(destination, count: bufferSize - stream.pointee.dst_size)
194
+ } while status == COMPRESSION_STATUS_OK
195
+ precondition(status == COMPRESSION_STATUS_END, "deflate failed")
196
+ }
197
+ }
198
+ return output
199
+ }
200
+
201
+ private static let crcTable: [UInt32] = (0..<256).map { index -> UInt32 in
202
+ var value = UInt32(index)
203
+ for _ in 0..<8 {
204
+ value = (value & 1) != 0 ? (0xEDB8_8320 ^ (value >> 1)) : (value >> 1)
205
+ }
206
+ return value
207
+ }
208
+
209
+ static func crc32(_ data: Data) -> UInt32 {
210
+ var crc: UInt32 = 0xFFFF_FFFF
211
+ for byte in data {
212
+ crc = crcTable[Int((crc ^ UInt32(byte)) & 0xFF)] ^ (crc >> 8)
213
+ }
214
+ return crc ^ 0xFFFF_FFFF
215
+ }
216
+ }
217
+
218
+ extension Data {
219
+ mutating func appendUInt16(_ value: UInt16) {
220
+ append(UInt8(value & 0xFF))
221
+ append(UInt8((value >> 8) & 0xFF))
222
+ }
223
+
224
+ mutating func appendUInt32(_ value: UInt32) {
225
+ for shift in stride(from: 0, to: 32, by: 8) {
226
+ append(UInt8((value >> UInt32(shift)) & 0xFF))
227
+ }
228
+ }
229
+
230
+ mutating func appendUInt64(_ value: UInt64) {
231
+ for shift in stride(from: 0, to: 64, by: 8) {
232
+ append(UInt8((value >> UInt64(shift)) & 0xFF))
233
+ }
234
+ }
235
+ }
@@ -0,0 +1,454 @@
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 download(url: URL, version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
87
+ try downloadVerified(
88
+ url: url,
89
+ version: version,
90
+ sessionKey: sessionKey,
91
+ expectedChecksum: "",
92
+ link: link,
93
+ comment: comment
94
+ )
95
+ }
96
+
97
+ override func downloadVerified(
98
+ url _: URL,
99
+ version _: String,
100
+ sessionKey _: String,
101
+ expectedChecksum _: String,
102
+ link _: String? = nil,
103
+ comment _: String? = nil
104
+ ) throws -> BundleInfo {
105
+ downloadCalls += 1
106
+ guard let downloadedBundleValue else {
107
+ throw NSError(domain: "UpdateLifecycleTests", code: 1)
108
+ }
109
+ return downloadedBundleValue
110
+ }
111
+
112
+ override func setError(bundle: BundleInfo) {
113
+ setErrorCalls += 1
114
+ currentBundleValue = bundle.setStatus(status: BundleStatus.ERROR.storedValue)
115
+ }
116
+
117
+ override func saveBundleInfo(id: String, bundle: BundleInfo?) -> Bool {
118
+ true
119
+ }
120
+
121
+ override func delete(id: String, removeInfo: Bool) -> Bool {
122
+ true
123
+ }
124
+
125
+ override func persistPendingStats() {}
126
+
127
+ override func sendStats(action: String, versionName: String? = nil, oldVersionName: String? = "") {
128
+ record(action)
129
+ }
130
+
131
+ override func sendStats(action: String, versionName: String?, oldVersionName: String?, metadata: [String: String]) {
132
+ record(action)
133
+ }
134
+
135
+ override func sendStats(action: String, versionName: String?, oldVersionName: String?, metadata: [String: String], onSent: @escaping () -> Void) {
136
+ record(action)
137
+ }
138
+ }
139
+
140
+ private final class LifecyclePlugin: CapacitorUpdaterPlugin {
141
+ private(set) var events: [String] = []
142
+ private(set) var payloads: [String: [String: Any]] = [:]
143
+ private(set) var readyMessages: [String] = []
144
+ // Matches the real plugin without a bridge: reloads fail unless a test opts in.
145
+ var reloadResult = false
146
+
147
+ override func reloadCurrentBundle() -> Bool {
148
+ reloadResult
149
+ }
150
+
151
+ /// Records the decoded updaterEvent type and payload.
152
+ override func notifyListeners(_ eventName: String, data: [String: Any]?, retainUntilConsumed retain: Bool) {
153
+ let event = decodeUpdaterEvent(eventName, data: data)
154
+ events.append(event.name)
155
+ if let payload = event.data {
156
+ payloads[event.name] = payload
157
+ }
158
+ }
159
+
160
+ override func endBackGroundTask() {}
161
+
162
+ override func beginDownloadBackgroundTask() {}
163
+
164
+ override func runBackgroundDownloadWork(_ work: @escaping () -> Void) {
165
+ work()
166
+ }
167
+
168
+ override func runGetLatestWork(_ work: @escaping () -> Void) {
169
+ work()
170
+ }
171
+
172
+ override func sendReadyToJs(current: BundleInfo, msg: String) {
173
+ readyMessages.append(msg)
174
+ }
175
+ }
176
+
177
+ final class UpdateLifecycleTests: XCTestCase {
178
+ private var plugin = LifecyclePlugin()
179
+ private var updater = LifecycleCapgoUpdater()
180
+ private let delayPreferencesKey = DelayUpdateUtils.DELAY_CONDITION_PREFERENCES
181
+ private let delayConditionModeKey = DelayUpdateUtils.DELAY_CONDITION_MODE_PREFERENCES
182
+ private let updateUrl = URL(string: "https://example.com/updates")!
183
+ private let lastFailedBundleKey = "CapacitorUpdater.lastFailedBundle"
184
+
185
+ override func setUpWithError() throws {
186
+ try super.setUpWithError()
187
+ let testLogger = Logger(withTag: "UpdateLifecycleTests", options: Logger.Options(level: .silent))
188
+ CryptoCipher.setLogger(testLogger)
189
+ updater = LifecycleCapgoUpdater()
190
+ updater.setLogger(testLogger)
191
+ plugin = LifecyclePlugin()
192
+ plugin.implementation = updater
193
+ plugin.setUpdateUrlForTesting(updateUrl.absoluteString)
194
+ plugin.setDelayUpdateUtilsForTesting(
195
+ DelayUpdateUtils(currentVersionNative: try CapgoSemanticVersion("1.0.0"), logger: Logger(withTag: "UpdateLifecycleTests"))
196
+ )
197
+ UserDefaults.standard.removeObject(forKey: delayPreferencesKey)
198
+ UserDefaults.standard.removeObject(forKey: delayConditionModeKey)
199
+ }
200
+
201
+ override func tearDown() {
202
+ UserDefaults.standard.removeObject(forKey: delayPreferencesKey)
203
+ UserDefaults.standard.removeObject(forKey: delayConditionModeKey)
204
+ UserDefaults.standard.removeObject(forKey: lastFailedBundleKey)
205
+ super.tearDown()
206
+ }
207
+
208
+ private func pendingBundle() -> BundleInfo {
209
+ BundleInfo(id: "bundle-2", version: "2.0.0", status: .PENDING, downloaded: Date(), checksum: "abc")
210
+ }
211
+
212
+ private func latest(version: String) -> AppVersion {
213
+ let latest = AppVersion()
214
+ latest.version = version
215
+ latest.url = "https://example.com/update.zip"
216
+ latest.checksum = "abc"
217
+ return latest
218
+ }
219
+
220
+ private func spinMainRunLoop(seconds: TimeInterval) {
221
+ let done = expectation(description: "main run loop")
222
+ DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
223
+ done.fulfill()
224
+ }
225
+ wait(for: [done], timeout: max(seconds + 5, 10))
226
+ }
227
+
228
+ // set() activated the pending next bundle but left it stored, so getNextBundle() kept
229
+ // returning the bundle that was already running.
230
+ func testClearNextBundleIfCurrentDropsTheRunningBundle() {
231
+ updater.currentBundleValue = pendingBundle()
232
+ updater.nextBundleValue = pendingBundle()
233
+
234
+ XCTAssertTrue(updater.clearNextBundleIfCurrent())
235
+ XCTAssertNil(updater.nextBundleValue)
236
+ }
237
+
238
+ func testClearNextBundleIfCurrentKeepsADifferentNextBundle() {
239
+ updater.nextBundleValue = pendingBundle()
240
+
241
+ XCTAssertFalse(updater.clearNextBundleIfCurrent())
242
+ XCTAssertEqual(updater.nextBundleValue?.getId(), "bundle-2")
243
+ }
244
+
245
+ // A suspended app can resume with the rollback timer already expired, before
246
+ // willEnterForeground re-arms it: the bundle must not be rolled back in background.
247
+ func testRollbackCheckWaitsForTheNextForegroundWhileInBackground() {
248
+ updater.currentBundleValue = pendingBundle()
249
+ plugin.setAppReadyTimeoutForTesting(10)
250
+
251
+ plugin.appMovedToBackground()
252
+ plugin.DeferredNotifyAppReadyCheck()
253
+
254
+ XCTAssertFalse(plugin.events.contains("updateFailed"))
255
+ XCTAssertEqual(updater.setErrorCalls, 0)
256
+
257
+ // The next foreground arms a fresh check, which rolls back a page that never confirmed.
258
+ plugin.appMovedToForeground()
259
+ spinMainRunLoop(seconds: 0.5)
260
+
261
+ XCTAssertTrue(plugin.events.contains("updateFailed"))
262
+ XCTAssertEqual(updater.setErrorCalls, 1)
263
+ }
264
+
265
+ func testRollbackCheckStillRunsInForeground() {
266
+ updater.currentBundleValue = pendingBundle()
267
+
268
+ plugin.DeferredNotifyAppReadyCheck()
269
+
270
+ XCTAssertTrue(plugin.events.contains("updateFailed"))
271
+ XCTAssertEqual(updater.setErrorCalls, 1)
272
+ }
273
+
274
+ // app_launch_timeout used to be sent on every rollback of the launch.
275
+ func testLaunchTimeoutIsReportedOncePerLaunch() {
276
+ updater.statsUrl = "https://stats.example.com"
277
+ updater.currentBundleValue = pendingBundle()
278
+ plugin.checkRevert()
279
+ updater.currentBundleValue = BundleInfo(id: "bundle-3", version: "3.0.0", status: .PENDING, downloaded: Date(), checksum: "abc")
280
+ plugin.checkRevert()
281
+
282
+ XCTAssertEqual(updater.statCount("update_fail"), 2)
283
+ XCTAssertEqual(updater.statCount("app_launch_timeout"), 1)
284
+ }
285
+
286
+ // The periodic check used to download on error responses (empty version != current).
287
+ func testPeriodicCheckReportsErrorResponsesWithoutDownloading() {
288
+ plugin.setAutoUpdateModeForTesting("atBackground")
289
+ let response = AppVersion()
290
+ response.error = "no_new_version_available"
291
+ response.kind = "up_to_date"
292
+ response.message = "No new version available"
293
+ updater.latestResponse = response
294
+
295
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
296
+
297
+ XCTAssertEqual(updater.getLatestCalls, 1)
298
+ XCTAssertEqual(plugin.payloads["updateCheckResult"]?["kind"] as? String, "up_to_date")
299
+ XCTAssertFalse(plugin.events.contains("downloadFailed"))
300
+ }
301
+
302
+ func testPeriodicCheckDoesNotDownloadTheCurrentVersion() {
303
+ plugin.setAutoUpdateModeForTesting("atBackground")
304
+ updater.latestResponse = latest(version: "1.0.0")
305
+
306
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
307
+
308
+ XCTAssertEqual(updater.getLatestCalls, 1)
309
+ XCTAssertFalse(plugin.events.contains("updateCheckResult"))
310
+ }
311
+
312
+ func testPeriodicCheckDownloadsANewVersion() {
313
+ plugin.setAutoUpdateModeForTesting("atBackground")
314
+ updater.latestResponse = latest(version: "2.0.0")
315
+ updater.downloadedBundleValue = pendingBundle()
316
+
317
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
318
+
319
+ XCTAssertEqual(updater.getLatestCalls, 2)
320
+ XCTAssertEqual(updater.downloadCalls, 1)
321
+ }
322
+
323
+ // A silent push downloaded the update in the background but only queued it, so the
324
+ // user opened the old bundle: the install waited for a didEnterBackground that a
325
+ // background launch never posts.
326
+ func testBackgroundDownloadInstallsRightAwayWhileInBackground() {
327
+ plugin.setAutoUpdateModeForTesting("atBackground")
328
+ updater.latestResponse = latest(version: "2.0.0")
329
+ updater.downloadedBundleValue = pendingBundle()
330
+ plugin.reloadResult = true
331
+ plugin.appMovedToBackground()
332
+
333
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
334
+
335
+ XCTAssertEqual(updater.setBundleCalls, ["bundle-2"])
336
+ XCTAssertEqual(updater.currentBundleValue.getId(), "bundle-2")
337
+ XCTAssertNil(updater.nextBundleValue)
338
+ let reported = plugin.payloads["noNeedUpdate"]?["bundle"] as? [String: Any]
339
+ XCTAssertEqual(reported?["id"] as? String, "bundle-2")
340
+ XCTAssertEqual(plugin.readyMessages.last, "update downloaded and installed in background")
341
+ }
342
+
343
+ func testFailedBackgroundReloadKeepsThePreviousBundleActive() {
344
+ plugin.setAutoUpdateModeForTesting("atBackground")
345
+ updater.latestResponse = latest(version: "2.0.0")
346
+ updater.downloadedBundleValue = pendingBundle()
347
+ plugin.appMovedToBackground()
348
+
349
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
350
+
351
+ XCTAssertEqual(updater.setBundleCalls, ["bundle-2"])
352
+ XCTAssertEqual(updater.currentBundleValue.getId(), "current-id")
353
+ XCTAssertEqual(updater.nextBundleValue?.getId(), "bundle-2")
354
+ let reported = plugin.payloads["noNeedUpdate"]?["bundle"] as? [String: Any]
355
+ XCTAssertEqual(reported?["id"] as? String, "current-id")
356
+ XCTAssertEqual(plugin.readyMessages.last, "update downloaded, will install next background")
357
+ }
358
+
359
+ func testForegroundDownloadWaitsForTheNextBackground() {
360
+ plugin.setAutoUpdateModeForTesting("atBackground")
361
+ updater.latestResponse = latest(version: "2.0.0")
362
+ updater.downloadedBundleValue = pendingBundle()
363
+
364
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
365
+
366
+ XCTAssertEqual(updater.setBundleCalls, [])
367
+ XCTAssertEqual(updater.nextBundleValue?.getId(), "bundle-2")
368
+ }
369
+
370
+ func testAlwaysModeDoesNotInstallQueuedBundleWhileInBackground() {
371
+ plugin.setAutoUpdateModeForTesting("always")
372
+ updater.latestResponse = latest(version: "2.0.0")
373
+ updater.downloadedBundleValue = pendingBundle()
374
+ plugin.appMovedToBackground()
375
+
376
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
377
+
378
+ XCTAssertEqual(updater.setBundleCalls, [])
379
+ XCTAssertEqual(updater.nextBundleValue?.getId(), "bundle-2")
380
+ }
381
+
382
+ func testOnLaunchRetriesQueuedBundleOnForegroundAfterFailedDirectReload() {
383
+ plugin.setAutoUpdateModeForTesting("onLaunch")
384
+ updater.latestResponse = latest(version: "2.0.0")
385
+ updater.downloadedBundleValue = pendingBundle()
386
+ plugin.reloadResult = false
387
+
388
+ plugin.runPeriodicUpdateCheck(url: updateUrl)
389
+
390
+ XCTAssertEqual(updater.currentBundleValue.getId(), "current-id")
391
+ XCTAssertEqual(updater.nextBundleValue?.getId(), "bundle-2")
392
+
393
+ plugin.reloadResult = true
394
+ plugin.appMovedToForeground()
395
+
396
+ XCTAssertEqual(updater.setBundleCalls, ["bundle-2"])
397
+ XCTAssertEqual(updater.currentBundleValue.getId(), "bundle-2")
398
+ XCTAssertNil(updater.nextBundleValue)
399
+ }
400
+
401
+ // triggerUpdateCheck returned "preview_session" (not in the TS union) and never "unavailable".
402
+ func testTriggerUpdateCheckIsUnavailableWhenAutoUpdateIsDisabled() {
403
+ XCTAssertEqual(plugin.triggerBackgroundUpdateCheck(), "unavailable")
404
+ XCTAssertEqual(updater.getLatestCalls, 0)
405
+ }
406
+
407
+ func testTriggerUpdateCheckIsUnavailableDuringAPreviewSession() {
408
+ plugin.setAutoUpdateModeForTesting("atBackground")
409
+ plugin.previewSessionEnabled = true
410
+
411
+ XCTAssertEqual(plugin.triggerBackgroundUpdateCheck(), "unavailable")
412
+ XCTAssertEqual(updater.getLatestCalls, 0)
413
+ }
414
+
415
+ func testTriggerUpdateCheckQueuesWhenAutoUpdateIsEnabled() {
416
+ plugin.setAutoUpdateModeForTesting("atBackground")
417
+ updater.latestResponse = latest(version: "1.0.0")
418
+
419
+ XCTAssertEqual(plugin.triggerBackgroundUpdateCheck(), "queued")
420
+ XCTAssertEqual(updater.getLatestCalls, 1)
421
+ }
422
+
423
+ // Malformed stored delay conditions used to crash on `kind as! String`.
424
+ func testParseDelayConditionsDropsMalformedEntries() {
425
+ let json = #"[{"value":"1"},{"kind":1},"text",3,{"kind":"kill","value":""},{"kind":"background"}]"#
426
+
427
+ let conditions = DelayUpdateUtils.parseDelayConditions(json: json)
428
+
429
+ XCTAssertEqual(conditions.map { $0.getKind() }, ["kill", "background"])
430
+ XCTAssertTrue(DelayUpdateUtils.parseDelayConditions(json: "not json").isEmpty)
431
+ XCTAssertTrue(DelayUpdateUtils.parseDelayConditions(json: #"{"kind":"kill"}"#).isEmpty)
432
+ }
433
+
434
+ func testCheckCancelDelaySurvivesMalformedStoredConditions() throws {
435
+ UserDefaults.standard.set(#"[1,{"value":"1"},{"kind":"kill","value":""}]"#, forKey: delayPreferencesKey)
436
+
437
+ plugin.appMovedToBackground()
438
+
439
+ let stored = try XCTUnwrap(UserDefaults.standard.string(forKey: delayPreferencesKey))
440
+ XCTAssertEqual(DelayUpdateUtils.parseDelayConditions(json: stored).map { $0.getKind() }, ["kill"])
441
+ }
442
+
443
+ func testDirectUpdateSurvivesMalformedStoredConditions() {
444
+ plugin.configureDirectUpdateModeForTesting("always")
445
+ updater.latestResponse = latest(version: "2.0.0")
446
+ updater.downloadedBundleValue = pendingBundle()
447
+ UserDefaults.standard.set(#"[{"value":"1"},{"kind":"kill","value":""}]"#, forKey: delayPreferencesKey)
448
+
449
+ plugin.backgroundDownload()
450
+
451
+ XCTAssertEqual(updater.downloadCalls, 1)
452
+ XCTAssertEqual(plugin.readyMessages, ["Update delayed until delay conditions met"])
453
+ }
454
+ }