@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,281 @@
1
+ import Foundation
2
+ import Security
3
+ import XCTest
4
+ @testable import CapacitorUpdaterPlugin
5
+
6
+ final class RsaContractTests: XCTestCase {
7
+ private static let contract: [String: Any] = {
8
+ do {
9
+ let data = try Data(contentsOf: contractFileURL())
10
+ let value = try JSONSerialization.jsonObject(with: data)
11
+ guard let contract = value as? [String: Any] else {
12
+ throw ContractError.invalidRoot
13
+ }
14
+ return contract
15
+ } catch {
16
+ XCTFail("Unable to load RSA contract fixture: \(error)")
17
+ return [:]
18
+ }
19
+ }()
20
+
21
+ private enum ContractError: Error {
22
+ case missingFixture
23
+ case invalidRoot
24
+ case invalidCases(String)
25
+ case invalidCase(String)
26
+ }
27
+
28
+ private struct SignedVector {
29
+ let key: String
30
+ let ciphertext: Data
31
+ let plaintext: Data
32
+ }
33
+
34
+ override class func setUp() {
35
+ super.setUp()
36
+ CryptoCipher.setLogger(Logger(withTag: "RsaContractTests", options: Logger.Options(level: .silent)))
37
+ }
38
+
39
+ private static func contractFileURL() throws -> URL {
40
+ let fileManager = FileManager.default
41
+ let roots = [
42
+ URL(fileURLWithPath: fileManager.currentDirectoryPath),
43
+ URL(fileURLWithPath: #filePath)
44
+ ]
45
+
46
+ for root in roots {
47
+ var current = root
48
+ while current.path != "/" {
49
+ let candidate = current
50
+ .appendingPathComponent("native-contract-tests")
51
+ .appendingPathComponent("crypto-rsa.json")
52
+ if fileManager.fileExists(atPath: candidate.path) {
53
+ return candidate
54
+ }
55
+ current.deleteLastPathComponent()
56
+ }
57
+ }
58
+ throw ContractError.missingFixture
59
+ }
60
+
61
+ private func contractCases(_ key: String) throws -> [[String: Any]] {
62
+ guard let cases = Self.contract[key] as? [[String: Any]] else {
63
+ throw ContractError.invalidCases(key)
64
+ }
65
+ return cases
66
+ }
67
+
68
+ private func dictionary(_ source: [String: Any], _ key: String, id: String) throws -> [String: Any] {
69
+ guard let value = source[key] as? [String: Any] else {
70
+ throw ContractError.invalidCase("\(id).\(key)")
71
+ }
72
+ return value
73
+ }
74
+
75
+ private func string(_ source: [String: Any], _ key: String, id: String) throws -> String {
76
+ guard let value = source[key] as? String else {
77
+ throw ContractError.invalidCase("\(id).\(key)")
78
+ }
79
+ return value
80
+ }
81
+
82
+ private func bool(_ source: [String: Any], _ key: String, id: String) throws -> Bool {
83
+ guard let value = source[key] as? Bool else {
84
+ throw ContractError.invalidCase("\(id).\(key)")
85
+ }
86
+ return value
87
+ }
88
+
89
+ private func fixturePublicKey() throws -> String {
90
+ if let key = Self.contract["publicKeyPem"] as? String {
91
+ return key
92
+ }
93
+ throw ContractError.invalidRoot
94
+ }
95
+
96
+ private func hexToData(_ hex: String) -> Data? {
97
+ var data = Data()
98
+ var iterator = hex.makeIterator()
99
+ while let char1 = iterator.next(), let char2 = iterator.next() {
100
+ guard let byte = UInt8(String([char1, char2]), radix: 16) else {
101
+ return nil
102
+ }
103
+ data.append(byte)
104
+ }
105
+ return data
106
+ }
107
+
108
+ private func dataToHex(_ data: Data) -> String {
109
+ data.map { String(format: "%02x", $0) }.joined()
110
+ }
111
+
112
+ func testRsaPublicDecryptMatchesNativeContract() throws {
113
+ let publicKey = try fixturePublicKey()
114
+ guard let rsaPublicKey = RSAPublicKey.load(rsaPublicKey: publicKey) else {
115
+ XCTFail("Fixture public key must load")
116
+ return
117
+ }
118
+
119
+ for testCase in try contractCases("rsaPublicDecrypt") {
120
+ let id = try string(testCase, "id", id: "rsaPublicDecrypt")
121
+ let input = try dictionary(testCase, "input", id: id)
122
+ let expect = try dictionary(testCase, "expect", id: id)
123
+ let ciphertextHex = try string(input, "ciphertextHex", id: id)
124
+ let expectedPlaintextHex = try string(expect, "plaintextHex", id: id)
125
+
126
+ guard let ciphertext = hexToData(ciphertextHex) else {
127
+ XCTFail("\(id): invalid ciphertext hex")
128
+ continue
129
+ }
130
+
131
+ guard let decrypted = rsaPublicKey.decrypt(data: ciphertext) else {
132
+ XCTFail("\(id): RSA public decrypt returned nil")
133
+ continue
134
+ }
135
+
136
+ XCTAssertEqual(dataToHex(decrypted), expectedPlaintextHex, id)
137
+ }
138
+ }
139
+
140
+ func testDecryptChecksumMatchesNativeContract() throws {
141
+ let publicKey = try fixturePublicKey()
142
+
143
+ for testCase in try contractCases("decryptChecksum") {
144
+ let id = try string(testCase, "id", id: "decryptChecksum")
145
+ let input = try dictionary(testCase, "input", id: id)
146
+ let expect = try dictionary(testCase, "expect", id: id)
147
+ let checksumHex = try string(input, "checksumHex", id: id)
148
+ let expectedDecryptedHex = try string(expect, "decryptedHex", id: id)
149
+
150
+ let expectedCiphertextHex = try string(expect, "ciphertextHex", id: id)
151
+
152
+ let result = try CryptoCipher.decryptChecksum(checksum: checksumHex, publicKey: publicKey)
153
+ XCTAssertEqual(result, expectedDecryptedHex, id)
154
+ let signed = try CryptoCipher.decryptBundleChecksum(checksum: checksumHex, publicKey: publicKey)
155
+ XCTAssertEqual(signed.plain, expectedDecryptedHex, id)
156
+ XCTAssertEqual(signed.ciphertext, expectedCiphertextHex, id)
157
+ }
158
+ }
159
+
160
+ func testDecryptChecksumInvalidMatchesNativeContract() throws {
161
+ let publicKey = try fixturePublicKey()
162
+
163
+ for testCase in try contractCases("decryptChecksumInvalid") {
164
+ let id = try string(testCase, "id", id: "decryptChecksumInvalid")
165
+ let input = try dictionary(testCase, "input", id: id)
166
+ let expect = try dictionary(testCase, "expect", id: id)
167
+ let checksumHex = try string(input, "checksumHex", id: id)
168
+ let shouldThrow = try bool(expect, "throws", id: id)
169
+
170
+ if shouldThrow {
171
+ XCTAssertThrowsError(
172
+ try CryptoCipher.decryptChecksum(checksum: checksumHex, publicKey: publicKey),
173
+ id
174
+ )
175
+ } else {
176
+ XCTAssertNoThrow(
177
+ try CryptoCipher.decryptChecksum(checksum: checksumHex, publicKey: publicKey),
178
+ id
179
+ )
180
+ }
181
+ }
182
+ }
183
+
184
+ func testCalcKeyIdMatchesNativeContract() throws {
185
+ for testCase in try contractCases("calcKeyId") {
186
+ let id = try string(testCase, "id", id: "calcKeyId")
187
+ let input = try dictionary(testCase, "input", id: id)
188
+ let expect = try dictionary(testCase, "expect", id: id)
189
+ let publicKey = try string(input, "publicKeyPem", id: id)
190
+ let expectedKeyId = try string(expect, "keyId", id: id)
191
+
192
+ XCTAssertEqual(CryptoCipher.calcKeyId(publicKey: publicKey), expectedKeyId, id)
193
+ }
194
+ }
195
+
196
+ func testRsaPublicKeyLoadMatchesNativeContract() throws {
197
+ for testCase in try contractCases("rsaPublicKeyLoad") {
198
+ let id = try string(testCase, "id", id: "rsaPublicKeyLoad")
199
+ let input = try dictionary(testCase, "input", id: id)
200
+ let expect = try dictionary(testCase, "expect", id: id)
201
+ let publicKey = try string(input, "publicKeyPem", id: id)
202
+ let shouldLoad = try bool(expect, "loads", id: id)
203
+
204
+ let loaded = RSAPublicKey.load(rsaPublicKey: publicKey) != nil
205
+ XCTAssertEqual(loaded, shouldLoad, id)
206
+ }
207
+ }
208
+
209
+ private func signedVector() throws -> SignedVector {
210
+ let testCase = try XCTUnwrap(contractCases("rsaPublicDecrypt").first)
211
+ let input = try dictionary(testCase, "input", id: "signedVector")
212
+ let expect = try dictionary(testCase, "expect", id: "signedVector")
213
+ let ciphertext = try XCTUnwrap(hexToData(string(input, "ciphertextHex", id: "signedVector")))
214
+ let plaintext = try XCTUnwrap(hexToData(string(expect, "plaintextHex", id: "signedVector")))
215
+ return SignedVector(key: try fixturePublicKey(), ciphertext: ciphertext, plaintext: plaintext)
216
+ }
217
+
218
+ func testPublicDecryptRejectsModifiedAndWrongLengthSignatures() throws {
219
+ let vector = try signedVector()
220
+ let key = try XCTUnwrap(RSAPublicKey.load(rsaPublicKey: vector.key))
221
+ XCTAssertNil(key.decrypt(data: Data()))
222
+ XCTAssertNil(key.decrypt(data: Data(vector.ciphertext.dropLast())))
223
+ XCTAssertNil(key.decrypt(data: vector.ciphertext + Data([0])))
224
+ for index in vector.ciphertext.indices {
225
+ var changed = vector.ciphertext
226
+ changed[index] ^= 1
227
+ XCTAssertNil(key.decrypt(data: changed), "Modified signature byte \(index)")
228
+ }
229
+ }
230
+
231
+ func testTypeOnePaddingRequiresCompleteValidBlock() {
232
+ let payload = [UInt8](repeating: 0xab, count: 32)
233
+ let valid = Data([0, 1] + [UInt8](repeating: 0xff, count: 221) + [0] + payload)
234
+ XCTAssertEqual(RSAPublicKey.unpadSignature(valid), Data(payload))
235
+
236
+ // RFC 8017 permits a minimum of eight padding bytes.
237
+ let longestPayload = Data(repeating: 0xab, count: 245)
238
+ let minimumPadding = Data([0, 1] + [UInt8](repeating: 0xff, count: 8) + [0]) + longestPayload
239
+ XCTAssertEqual(RSAPublicKey.unpadSignature(minimumPadding), longestPayload)
240
+ let shortPadding = Data([0, 1] + [UInt8](repeating: 0xff, count: 7) + [0]) + Data(repeating: 0xab, count: 246)
241
+ XCTAssertNil(RSAPublicKey.unpadSignature(shortPadding))
242
+
243
+ for (index, replacement) in [(0, UInt8(1)), (1, UInt8(2)), (2, UInt8(0x7f))] {
244
+ var malformed = valid
245
+ malformed[index] = replacement
246
+ XCTAssertNil(RSAPublicKey.unpadSignature(malformed))
247
+ }
248
+ XCTAssertNil(RSAPublicKey.unpadSignature(Data([0, 1] + [UInt8](repeating: 0xff, count: 254))))
249
+ XCTAssertNil(RSAPublicKey.unpadSignature(Data([0, 1] + [UInt8](repeating: 0xff, count: 253) + [0])))
250
+ XCTAssertNil(RSAPublicKey.unpadSignature(Data(valid.dropLast())))
251
+ XCTAssertNil(RSAPublicKey.unpadSignature(valid + Data([0])))
252
+ }
253
+
254
+ func testKeyCacheHandlesInvalidKeysRotationAndConcurrentCallers() throws {
255
+ let vector = try signedVector()
256
+ let original = try XCTUnwrap(RSAPublicKey.load(rsaPublicKey: vector.key))
257
+ XCTAssertEqual(original.decrypt(data: vector.ciphertext), vector.plaintext)
258
+ XCTAssertNil(RSAPublicKey.load(rsaPublicKey: "not-a-public-key"))
259
+ XCTAssertNil(RSAPublicKey.load(rsaPublicKey: "YWJj"))
260
+
261
+ let attributes: [CFString: Any] = [kSecAttrKeyType: kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits: 2048]
262
+ let privateKey = try XCTUnwrap(SecKeyCreateRandomKey(attributes as CFDictionary, nil))
263
+ let publicKey = try XCTUnwrap(SecKeyCopyPublicKey(privateKey))
264
+ let encoded = try XCTUnwrap(SecKeyCopyExternalRepresentation(publicKey, nil)) as Data
265
+ let otherPem = "-----BEGIN RSA PUBLIC KEY-----\n\(encoded.base64EncodedString())\n-----END RSA PUBLIC KEY-----"
266
+ let other = try XCTUnwrap(RSAPublicKey.load(rsaPublicKey: otherPem))
267
+ XCTAssertNil(other.decrypt(data: vector.ciphertext))
268
+ XCTAssertEqual(original.decrypt(data: vector.ciphertext), vector.plaintext, "Imported instances retain their own key")
269
+
270
+ DispatchQueue.concurrentPerform(iterations: 128) { index in
271
+ let useOriginal = index.isMultiple(of: 2)
272
+ let loaded = RSAPublicKey.load(rsaPublicKey: useOriginal ? vector.key : otherPem)
273
+ XCTAssertNotNil(loaded)
274
+ XCTAssertEqual(loaded?.decrypt(data: vector.ciphertext), useOriginal ? vector.plaintext : nil)
275
+ }
276
+
277
+ let escaped = vector.key.replacingOccurrences(of: "\n", with: "\\n")
278
+ let reloaded = try XCTUnwrap(RSAPublicKey.load(rsaPublicKey: escaped))
279
+ XCTAssertEqual(reloaded.decrypt(data: vector.ciphertext), vector.plaintext)
280
+ }
281
+ }
@@ -0,0 +1,192 @@
1
+ import XCTest
2
+ @testable import CapacitorUpdaterPlugin
3
+
4
+ final class SessionKeyRequiredTests: XCTestCase {
5
+ private enum Fixture {
6
+ static let contract: [String: Any] = {
7
+ guard let url = try? locateContractFile(),
8
+ let data = try? Data(contentsOf: url),
9
+ let value = try? JSONSerialization.jsonObject(with: data),
10
+ let dict = value as? [String: Any] else {
11
+ XCTFail("Unable to load RSA contract fixture")
12
+ return [:]
13
+ }
14
+ return dict
15
+ }()
16
+
17
+ static var publicKeyPem: String {
18
+ contract["publicKeyPem"] as? String ?? ""
19
+ }
20
+
21
+ private static func locateContractFile() throws -> URL {
22
+ let fileManager = FileManager.default
23
+ let roots = [
24
+ URL(fileURLWithPath: fileManager.currentDirectoryPath),
25
+ URL(fileURLWithPath: #filePath)
26
+ ]
27
+
28
+ for root in roots {
29
+ var current = root
30
+ while current.path != "/" {
31
+ let candidate = current
32
+ .appendingPathComponent("native-contract-tests")
33
+ .appendingPathComponent("crypto-rsa.json")
34
+ if fileManager.fileExists(atPath: candidate.path) {
35
+ return candidate
36
+ }
37
+ current.deleteLastPathComponent()
38
+ }
39
+ }
40
+ throw NSError(domain: "SessionKeyRequiredTests", code: 1)
41
+ }
42
+ }
43
+
44
+ private class StatsTrackingCapgoUpdater: CapgoUpdater {
45
+ var sentStatsActions: [String] = []
46
+
47
+ override func sendStats(action: String, versionName: String? = nil, oldVersionName: String? = "") {
48
+ sentStatsActions.append(action)
49
+ }
50
+ }
51
+
52
+ private final class AutoUpdateSessionKeyCapgoUpdater: StatsTrackingCapgoUpdater {
53
+ override func getLatest(url: URL, channel: String?, appIdOverride: String? = nil) -> AppVersion {
54
+ let latest = AppVersion()
55
+ latest.version = "2.0.0"
56
+ latest.url = "https://example.com/update.zip"
57
+ return latest
58
+ }
59
+
60
+ override func getCurrentBundle() -> BundleInfo {
61
+ BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "abc")
62
+ }
63
+ }
64
+
65
+ private final class PendingBundleAutoUpdateCapgoUpdater: StatsTrackingCapgoUpdater {
66
+ override func getLatest(url: URL, channel: String?, appIdOverride: String? = nil) -> AppVersion {
67
+ let latest = AppVersion()
68
+ latest.version = "2.0.0"
69
+ latest.url = "https://example.com/update.zip"
70
+ latest.checksum = "abc123"
71
+ return latest
72
+ }
73
+
74
+ override func getCurrentBundle() -> BundleInfo {
75
+ BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "abc")
76
+ }
77
+
78
+ override func getBundleInfoByVersionName(version: String) -> BundleInfo? {
79
+ if version == "2.0.0" {
80
+ return BundleInfo(
81
+ id: "pending-id",
82
+ version: "2.0.0",
83
+ status: .PENDING,
84
+ downloaded: Date(),
85
+ checksum: "abc123"
86
+ )
87
+ }
88
+ return nil
89
+ }
90
+ }
91
+
92
+ private final class TestableCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
93
+ override func runBackgroundDownloadWork(_ work: @escaping () -> Void) {
94
+ work()
95
+ }
96
+ }
97
+
98
+ private var implementation: StatsTrackingCapgoUpdater!
99
+
100
+ override func setUp() {
101
+ super.setUp()
102
+ implementation = StatsTrackingCapgoUpdater()
103
+ implementation.setLogger(Logger(withTag: "SessionKeyRequiredTests", options: Logger.Options(level: .silent)))
104
+ implementation.setPublicKey(Fixture.publicKeyPem)
105
+ }
106
+
107
+ override func tearDown() {
108
+ implementation.shutdown()
109
+ implementation = nil
110
+ super.tearDown()
111
+ }
112
+
113
+ func testDownloadManifestRejectsWhenSessionKeyMissing() {
114
+ let manifest = [ManifestEntry(file_name: "index.html", file_hash: "abc", download_url: "https://example.com/index.html")]
115
+
116
+ XCTAssertThrowsError(try implementation.downloadManifest(manifest: manifest, version: "1.0.0", sessionKey: "")) { error in
117
+ XCTAssertEqual((error as NSError).domain, "CapgoUpdater")
118
+ XCTAssertEqual((error as NSError).code, 1)
119
+ }
120
+ XCTAssertTrue(implementation.sentStatsActions.contains("session_key_required"))
121
+ }
122
+
123
+ func testDownloadRejectsWhenSessionKeyMissing() {
124
+ let url = URL(string: "https://example.com/update.zip")!
125
+
126
+ XCTAssertThrowsError(try implementation.download(url: url, version: "1.0.0", sessionKey: "")) { error in
127
+ XCTAssertEqual((error as NSError).domain, "CapgoUpdater")
128
+ XCTAssertEqual((error as NSError).code, 1)
129
+ }
130
+ XCTAssertTrue(implementation.sentStatsActions.contains("session_key_required"))
131
+ }
132
+
133
+ func testDownloadRejectsWhenSessionKeyFormatInvalid() {
134
+ let url = URL(string: "https://example.com/update.zip")!
135
+
136
+ XCTAssertThrowsError(try implementation.download(url: url, version: "1.0.0", sessionKey: "invalid-format")) { error in
137
+ XCTAssertEqual((error as NSError).domain, "CapgoUpdater")
138
+ XCTAssertEqual((error as NSError).code, 1)
139
+ }
140
+ XCTAssertTrue(implementation.sentStatsActions.contains("session_key_required"))
141
+ }
142
+
143
+ func testIsValidSessionKeyRejectsEmptyComponents() {
144
+ XCTAssertFalse(CryptoCipher.isValidSessionKey(""))
145
+ XCTAssertFalse(CryptoCipher.isValidSessionKey(":"))
146
+ XCTAssertFalse(CryptoCipher.isValidSessionKey("abc:"))
147
+ XCTAssertFalse(CryptoCipher.isValidSessionKey(":xyz"))
148
+ XCTAssertFalse(CryptoCipher.isValidSessionKey("invalid-format"))
149
+ XCTAssertTrue(CryptoCipher.isValidSessionKey("abc:def"))
150
+ }
151
+
152
+ func testAutoUpdateRejectsMissingSessionKeyWhenPendingBundleExists() {
153
+ let updater = PendingBundleAutoUpdateCapgoUpdater()
154
+ updater.setLogger(Logger(withTag: "SessionKeyRequiredTests", options: Logger.Options(level: .silent)))
155
+ updater.setPublicKey(Fixture.publicKeyPem)
156
+
157
+ let plugin = TestableCapacitorUpdaterPlugin()
158
+ plugin.implementation = updater
159
+ plugin.setAutoUpdateModeForTesting("onlyDownload")
160
+ plugin.setUpdateUrlForTesting("https://example.com/channel")
161
+
162
+ plugin.backgroundDownload()
163
+
164
+ XCTAssertTrue(updater.sentStatsActions.contains("session_key_required"))
165
+ updater.shutdown()
166
+ }
167
+
168
+ func testAutoUpdateBackgroundDownloadRejectsWhenSessionKeyMissing() {
169
+ let updater = AutoUpdateSessionKeyCapgoUpdater()
170
+ updater.setLogger(Logger(withTag: "SessionKeyRequiredTests", options: Logger.Options(level: .silent)))
171
+ updater.setPublicKey(Fixture.publicKeyPem)
172
+
173
+ let plugin = TestableCapacitorUpdaterPlugin()
174
+ plugin.implementation = updater
175
+ plugin.setAutoUpdateModeForTesting("onlyDownload")
176
+ plugin.setUpdateUrlForTesting("https://example.com/channel")
177
+
178
+ plugin.backgroundDownload()
179
+
180
+ XCTAssertTrue(updater.sentStatsActions.contains("session_key_required"))
181
+ updater.shutdown()
182
+ }
183
+
184
+ func testAllowsUpdateWhenNoPublicKeyConfigured() throws {
185
+ implementation.setPublicKey("")
186
+ let manifest = [ManifestEntry(file_name: "index.html", file_hash: "abc", download_url: "http://[")]
187
+
188
+ // Invalid URL fails fast after the session-key gate, proving the gate did not block.
189
+ XCTAssertThrowsError(try implementation.downloadManifest(manifest: manifest, version: "1.0.0", sessionKey: ""))
190
+ XCTAssertFalse(implementation.sentStatsActions.contains("session_key_required"))
191
+ }
192
+ }