@capgo/capacitor-updater 9.0.0 → 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 (109) hide show
  1. package/CapgoCapacitorUpdater.podspec +3 -6
  2. package/Package.swift +30 -0
  3. package/README.md +2382 -292
  4. package/android/build.gradle +37 -15
  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 +7435 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5144 -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 +1969 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +278 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +385 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -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 +959 -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 +2607 -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 +5642 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +4572 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +380 -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 +871 -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 +3905 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -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 +1095 -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 +192 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -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,64 @@
1
+ import Foundation
2
+ import XCTest
3
+ @testable import CapacitorUpdaterPlugin
4
+
5
+ final class CapgoSemanticVersionTests: XCTestCase {
6
+ private func version(_ string: String) throws -> CapgoSemanticVersion {
7
+ return try CapgoSemanticVersion(string)
8
+ }
9
+
10
+ func testParsesComponents() throws {
11
+ let full = try version("1.2.3-beta.1+build5")
12
+ XCTAssertEqual(full.major, 1)
13
+ XCTAssertEqual(full.minor, 2)
14
+ XCTAssertEqual(full.patch, 3)
15
+ XCTAssertEqual(full.prerelease, "beta.1")
16
+ XCTAssertEqual(full.build, "build5")
17
+ XCTAssertEqual(full.description, "1.2.3-beta.1+build5")
18
+
19
+ // Lenient parsing like the previous Version package: minor/patch optional, leading zeros allowed.
20
+ XCTAssertEqual(try version("7").description, "7")
21
+ XCTAssertEqual(try version("7.1").description, "7.1")
22
+ XCTAssertEqual(try version("01.002.0003").description, "1.2.3")
23
+ XCTAssertEqual(try version("1.0.0-rc-1.x-y").prerelease, "rc-1.x-y")
24
+ }
25
+
26
+ func testRejectsInvalidStrings() {
27
+ let invalid = [
28
+ "", " 1.0.0", "1.0.0 ", "v1.0.0", "1.0.0.0", "1..0", "1.0.", "a.b.c", "1.0.0-", "1.0.0+", "1.0.0+build.1",
29
+ "1.0.0-be ta", "1.0.0-β", "99999999999999999999.0.0", "1.99999999999999999999.0", "1.0.99999999999999999999"
30
+ ]
31
+ for string in invalid {
32
+ XCTAssertThrowsError(try version(string), "\(string) must not parse")
33
+ }
34
+ }
35
+
36
+ func testOrdering() throws {
37
+ XCTAssertTrue(try version("1.0.0") < version("1.0.1"))
38
+ XCTAssertTrue(try version("1.0.9") < version("1.0.10"))
39
+ XCTAssertTrue(try version("1.9.0") < version("1.10.0"))
40
+ XCTAssertTrue(try version("1.99.99") < version("2.0.0"))
41
+ XCTAssertTrue(try version("1.0.0-alpha") < version("1.0.0"))
42
+ XCTAssertTrue(try version("1.0.0-alpha") < version("1.0.0-alpha.1"))
43
+ XCTAssertTrue(try version("1.0.0-alpha.1") < version("1.0.0-beta"))
44
+ XCTAssertTrue(try version("1.0.0-beta.2") < version("1.0.0-beta.11"))
45
+ XCTAssertTrue(try version("1.0.0-rc.1") < version("1.0.0"))
46
+ XCTAssertFalse(try version("1.0.0") < version("1.0.0-rc.1"))
47
+ XCTAssertTrue(try version("2.1.0") > version("2.0.9"))
48
+ XCTAssertTrue(try version("1.0.0+a") >= version("1.0.0+b"))
49
+ XCTAssertTrue(try version("1") <= version("1.0.0"))
50
+ }
51
+
52
+ func testMissingComponentsCompareAsZeroAndBuildIsIgnored() throws {
53
+ XCTAssertEqual(try version("1"), try version("1.0.0"))
54
+ XCTAssertEqual(try version("1.2"), try version("1.2.0"))
55
+ XCTAssertEqual(try version("1.0.0+a"), try version("1.0.0+b"))
56
+ XCTAssertFalse(try version("1.0.0+a") < version("1.0.0+b"))
57
+ XCTAssertEqual(Set([try version("1.0"), try version("1.0.0+x")]).count, 1)
58
+ XCTAssertNotEqual(try version("1.0.0-a"), try version("1.0.0"))
59
+ }
60
+
61
+ func testDefaultVersionDescription() {
62
+ XCTAssertEqual(CapgoSemanticVersion(major: 0, minor: 0, patch: 0).description, "0.0.0")
63
+ }
64
+ }
@@ -0,0 +1,151 @@
1
+ import XCTest
2
+ @testable import CapacitorUpdaterPlugin
3
+
4
+ final class ChecksumRequiredTests: XCTestCase {
5
+ private class StatsTrackingCapgoUpdater: CapgoUpdater {
6
+ var sentStatsActions: [String] = []
7
+
8
+ override func sendStats(action: String, versionName: String? = nil, oldVersionName: String? = "") {
9
+ sentStatsActions.append(action)
10
+ }
11
+ }
12
+
13
+ private final class DownloadStubCapgoUpdater: StatsTrackingCapgoUpdater {
14
+ private let downloadedBundle: BundleInfo
15
+
16
+ init(downloadedBundle: BundleInfo) {
17
+ self.downloadedBundle = downloadedBundle
18
+ super.init()
19
+ }
20
+
21
+ override func downloadVerified(
22
+ url _: URL,
23
+ version _: String,
24
+ sessionKey _: String,
25
+ expectedChecksum _: String,
26
+ link _: String? = nil,
27
+ comment _: String? = nil
28
+ ) throws -> BundleInfo {
29
+ downloadedBundle
30
+ }
31
+ }
32
+
33
+ private final class AutoUpdateChecksumCapgoUpdater: StatsTrackingCapgoUpdater {
34
+ override func getLatest(url: URL, channel: String?, appIdOverride: String? = nil) -> AppVersion {
35
+ let latest = AppVersion()
36
+ latest.version = "2.0.0"
37
+ latest.url = "https://example.com/update.zip"
38
+ latest.checksum = ""
39
+ return latest
40
+ }
41
+
42
+ override func getCurrentBundle() -> BundleInfo {
43
+ BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "abc")
44
+ }
45
+ }
46
+
47
+ private final class TestableCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
48
+ override func runBackgroundDownloadWork(_ work: @escaping () -> Void) {
49
+ work()
50
+ }
51
+ }
52
+
53
+ private var implementation: StatsTrackingCapgoUpdater!
54
+
55
+ override func setUp() {
56
+ super.setUp()
57
+ implementation = StatsTrackingCapgoUpdater()
58
+ implementation.setLogger(Logger(withTag: "ChecksumRequiredTests", options: Logger.Options(level: .silent)))
59
+ implementation.setPublicKey("")
60
+ }
61
+
62
+ override func tearDown() {
63
+ implementation.shutdown()
64
+ implementation = nil
65
+ super.tearDown()
66
+ }
67
+
68
+ func testDownloadBundleRejectsWhenChecksumMissing() {
69
+ let plugin = TestableCapacitorUpdaterPlugin()
70
+ plugin.implementation = implementation
71
+
72
+ XCTAssertThrowsError(
73
+ try plugin.downloadBundleForTesting(
74
+ urlString: "https://example.com/update.zip",
75
+ version: "1.0.0",
76
+ sessionKey: "",
77
+ checksum: "",
78
+ manifestEntries: nil
79
+ )
80
+ )
81
+ XCTAssertTrue(implementation.sentStatsActions.contains("checksum_required"))
82
+ }
83
+
84
+ func testDownloadBundleRejectsWhenChecksumMismatch() throws {
85
+ let plugin = TestableCapacitorUpdaterPlugin()
86
+ let downloaded = BundleInfo(
87
+ id: "downloaded-id",
88
+ version: "1.0.0",
89
+ status: .PENDING,
90
+ downloaded: Date(),
91
+ checksum: "actual-checksum"
92
+ )
93
+ let downloadingImplementation = DownloadStubCapgoUpdater(downloadedBundle: downloaded)
94
+ downloadingImplementation.setLogger(Logger(withTag: "ChecksumRequiredTests", options: Logger.Options(level: .silent)))
95
+ plugin.implementation = downloadingImplementation
96
+
97
+ XCTAssertThrowsError(
98
+ try plugin.downloadBundleForTesting(
99
+ urlString: "https://example.com/update.zip",
100
+ version: "1.0.0",
101
+ sessionKey: "",
102
+ checksum: "expected-checksum",
103
+ manifestEntries: nil
104
+ )
105
+ )
106
+ XCTAssertTrue(downloadingImplementation.sentStatsActions.contains("checksum_fail"))
107
+ downloadingImplementation.shutdown()
108
+ }
109
+
110
+ func testDownloadBundleAcceptsWhenChecksumMatches() throws {
111
+ let plugin = TestableCapacitorUpdaterPlugin()
112
+ let downloaded = BundleInfo(
113
+ id: "downloaded-id",
114
+ version: "1.0.0",
115
+ status: .PENDING,
116
+ downloaded: Date(),
117
+ checksum: "matching-checksum"
118
+ )
119
+ let downloadingImplementation = DownloadStubCapgoUpdater(downloadedBundle: downloaded)
120
+ downloadingImplementation.setLogger(Logger(withTag: "ChecksumRequiredTests", options: Logger.Options(level: .silent)))
121
+ plugin.implementation = downloadingImplementation
122
+
123
+ let bundle = try plugin.downloadBundleForTesting(
124
+ urlString: "https://example.com/update.zip",
125
+ version: "1.0.0",
126
+ sessionKey: "",
127
+ checksum: "matching-checksum",
128
+ manifestEntries: nil
129
+ )
130
+
131
+ XCTAssertEqual(bundle.getChecksum(), "matching-checksum")
132
+ XCTAssertFalse(downloadingImplementation.sentStatsActions.contains("checksum_required"))
133
+ XCTAssertFalse(downloadingImplementation.sentStatsActions.contains("checksum_fail"))
134
+ downloadingImplementation.shutdown()
135
+ }
136
+
137
+ func testAutoUpdateBackgroundDownloadRejectsWhenChecksumMissing() {
138
+ let updater = AutoUpdateChecksumCapgoUpdater()
139
+ updater.setLogger(Logger(withTag: "ChecksumRequiredTests", options: Logger.Options(level: .silent)))
140
+
141
+ let plugin = TestableCapacitorUpdaterPlugin()
142
+ plugin.implementation = updater
143
+ plugin.setAutoUpdateModeForTesting("onlyDownload")
144
+ plugin.setUpdateUrlForTesting("https://example.com/channel")
145
+
146
+ plugin.backgroundDownload()
147
+
148
+ XCTAssertTrue(updater.sentStatsActions.contains("checksum_required"))
149
+ updater.shutdown()
150
+ }
151
+ }
@@ -0,0 +1,249 @@
1
+ import Foundation
2
+ import XCTest
3
+ @testable import CapacitorUpdaterPlugin
4
+
5
+ /// Decrypts bundles encrypted by the real Capgo CLI (native-contract-tests/cli, written by
6
+ /// scripts/generate-cli-crypto-fixtures.mjs) through the plugin's own download path.
7
+ /// CI also writes a fresh set into native-contract-tests/cli-fresh before the run, so the committed
8
+ /// fixtures and a fresh encryption by the latest CLI are both checked in one xcodebuild invocation.
9
+ final class CliCryptoFixtureTests: XCTestCase {
10
+ private struct InstalledFile {
11
+ let path: String
12
+ let sha256: String
13
+ }
14
+
15
+ private struct Bundle {
16
+ let id: String
17
+ let zip: Data
18
+ let encrypted: Data
19
+ let sha256: String
20
+ let checksum: String
21
+ let ivSessionKey: String
22
+ let files: [InstalledFile]
23
+ }
24
+
25
+ private var root = URL(fileURLWithPath: NSTemporaryDirectory())
26
+ private let libraryDir = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first
27
+ ?? URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library")
28
+
29
+ override func setUpWithError() throws {
30
+ root = FileManager.default.temporaryDirectory.appendingPathComponent("capgo-cli-fixtures-\(UUID().uuidString)")
31
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
32
+ // Zip downloads are staged in Documents, which a fresh simulator without a host app may not have yet.
33
+ if let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
34
+ try FileManager.default.createDirectory(at: documents, withIntermediateDirectories: true)
35
+ }
36
+ CryptoCipher.setLogger(Logger(withTag: "cli-fixture-tests", options: Logger.Options(level: .silent)))
37
+ }
38
+
39
+ override func tearDownWithError() throws {
40
+ try? FileManager.default.removeItem(at: root)
41
+ }
42
+
43
+ private struct Fixture {
44
+ let label: String
45
+ let publicKey: String
46
+ let bundles: [Bundle]
47
+ }
48
+
49
+ private static let fixtureFolders = ["native-contract-tests/cli", "native-contract-tests/cli-fresh"]
50
+
51
+ private static func fixtureDirectories() throws -> [URL] {
52
+ let fileManager = FileManager.default
53
+ for start in [URL(fileURLWithPath: fileManager.currentDirectoryPath), URL(fileURLWithPath: #filePath)] {
54
+ var current = start
55
+ while current.path != "/" {
56
+ let found = fixtureFolders
57
+ .map { current.appendingPathComponent($0) }
58
+ .filter { fileManager.fileExists(atPath: $0.appendingPathComponent("cli-crypto.json").path) }
59
+ if found.first?.lastPathComponent == "cli" {
60
+ return found
61
+ }
62
+ current.deleteLastPathComponent()
63
+ }
64
+ }
65
+ throw NSError(domain: "CliCryptoFixtureTests", code: 1, userInfo: [NSLocalizedDescriptionKey: "native-contract-tests/cli not found"])
66
+ }
67
+
68
+ private func loadFixtures() throws -> [Fixture] {
69
+ try Self.fixtureDirectories().map { try loadFixture(from: $0) }
70
+ }
71
+
72
+ private func loadFixture(from dir: URL) throws -> Fixture {
73
+ let label = dir.lastPathComponent
74
+ let json = try JSONSerialization.jsonObject(with: Data(contentsOf: dir.appendingPathComponent("cli-crypto.json")))
75
+ let fixture = try XCTUnwrap(json as? [String: Any])
76
+ let publicKey = try XCTUnwrap(fixture["publicKey"] as? String)
77
+ let entries = try XCTUnwrap(fixture["bundles"] as? [[String: Any]])
78
+ let bundles = try entries.map { entry -> Bundle in
79
+ let files = try XCTUnwrap(entry["files"] as? [[String: Any]]).map { file in
80
+ InstalledFile(path: try XCTUnwrap(file["path"] as? String), sha256: try XCTUnwrap(file["sha256"] as? String))
81
+ }
82
+ let rawId = try XCTUnwrap(entry["id"] as? String)
83
+ return Bundle(
84
+ id: "\(label)-\(rawId)",
85
+ zip: try Data(contentsOf: dir.appendingPathComponent(try XCTUnwrap(entry["zip"] as? String))),
86
+ encrypted: try Data(contentsOf: dir.appendingPathComponent(try XCTUnwrap(entry["encrypted"] as? String))),
87
+ sha256: try XCTUnwrap(entry["sha256"] as? String),
88
+ checksum: try XCTUnwrap(entry["checksum"] as? String),
89
+ ivSessionKey: try XCTUnwrap(entry["ivSessionKey"] as? String),
90
+ files: files
91
+ )
92
+ }
93
+ XCTAssertFalse(bundles.isEmpty, "\(label): fixture has bundles")
94
+ return Fixture(label: label, publicKey: publicKey, bundles: bundles)
95
+ }
96
+
97
+ func testEveryCliEncryptedBundleDecryptsToItsZip() throws {
98
+ for fixture in try loadFixtures() {
99
+ for bundle in fixture.bundles {
100
+ let file = root.appendingPathComponent("\(bundle.id).zip")
101
+ try bundle.encrypted.write(to: file)
102
+
103
+ XCTAssertTrue(CryptoCipher.isValidSessionKey(bundle.ivSessionKey), bundle.id)
104
+ let signed = try CryptoCipher.decryptBundleChecksum(checksum: bundle.checksum, publicKey: fixture.publicKey)
105
+ XCTAssertEqual(signed.ciphertext, CryptoCipher.calcChecksum(filePath: file), "\(bundle.id): signed ciphertext checksum")
106
+ try CryptoCipher.decryptFile(
107
+ filePath: file,
108
+ publicKey: fixture.publicKey,
109
+ sessionKey: bundle.ivSessionKey,
110
+ version: "1.0.0",
111
+ expectedCiphertextSha256: signed.ciphertext
112
+ )
113
+ let expectedChecksum = signed.plain
114
+
115
+ XCTAssertEqual(try Data(contentsOf: file), bundle.zip, "\(bundle.id): decrypted bytes")
116
+ XCTAssertEqual(expectedChecksum, bundle.sha256, "\(bundle.id): decrypted checksum")
117
+ XCTAssertEqual(CryptoCipher.calcChecksum(filePath: file), expectedChecksum, "\(bundle.id): file checksum")
118
+ }
119
+ }
120
+ }
121
+
122
+ /// Serves the CLI-encrypted payload instead of fetching the URL.
123
+ private final class FixtureDownloadCapgoUpdater: CapgoUpdater {
124
+ var payload = Data()
125
+
126
+ override func sendStats(action _: String, versionName _: String? = nil, oldVersionName _: String? = "") {}
127
+
128
+ override func performDownloadRequest(
129
+ _ request: URLRequest,
130
+ label _: String,
131
+ resumeData _: Data? = nil,
132
+ onProgress _: ((Int64, Int64) -> Void)? = nil
133
+ ) -> DownloadRequestResult {
134
+ let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent("capgo-cli-fixture-\(UUID().uuidString).zip")
135
+ do {
136
+ try payload.write(to: fileURL)
137
+ } catch {
138
+ return DownloadRequestResult(fileURL: nil, response: nil, error: error, timedOut: false)
139
+ }
140
+ let response = HTTPURLResponse(url: request.url ?? fileURL, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil)
141
+ return DownloadRequestResult(fileURL: fileURL, response: response, error: nil, timedOut: false)
142
+ }
143
+ }
144
+
145
+ func testDownloadVerifiedInstallsEveryCliEncryptedBundle() throws {
146
+ for fixture in try loadFixtures() {
147
+ for bundle in fixture.bundles {
148
+ let updater = FixtureDownloadCapgoUpdater()
149
+ updater.setLogger(Logger(withTag: "cli-fixture-tests", options: Logger.Options(level: .silent)))
150
+ // Payloads are served from file:// URLs.
151
+ updater.httpsOnly = false
152
+ updater.setPublicKey(fixture.publicKey)
153
+ updater.payload = bundle.encrypted
154
+ defer { updater.shutdown() }
155
+
156
+ // The raw update response values: encrypted checksum and ivSessionKey from the CLI.
157
+ let installed = try updater.downloadVerified(
158
+ url: root.appendingPathComponent("\(bundle.id).zip"),
159
+ version: "9.9.9-cli-\(bundle.id)",
160
+ sessionKey: bundle.ivSessionKey,
161
+ expectedChecksum: bundle.checksum
162
+ )
163
+ defer { _ = updater.delete(id: installed.getId()) }
164
+
165
+ XCTAssertEqual(installed.getChecksum(), bundle.sha256, bundle.id)
166
+ let bundleDir = libraryDir.appendingPathComponent("NoCloud/ionic_built_snapshots").appendingPathComponent(installed.getId())
167
+ for file in bundle.files {
168
+ let path = bundleDir.appendingPathComponent(file.path)
169
+ XCTAssertEqual(CryptoCipher.calcChecksum(filePath: path), file.sha256, "\(bundle.id): \(file.path)")
170
+ }
171
+ }
172
+ }
173
+ }
174
+ func testConcurrentManifestSessionsResetCipherAndKeepKeysSeparate() throws {
175
+ for fixture in try loadFixtures() {
176
+ let (publicKey, bundles) = (fixture.publicKey, fixture.bundles)
177
+ let sessions = bundles.map { CryptoCipher.DecryptionSession(publicKey: publicKey, sessionKey: $0.ivSessionKey) }
178
+ let lock = NSLock()
179
+ var failures: [String] = []
180
+ DispatchQueue.concurrentPerform(iterations: 24) { index in
181
+ do {
182
+ let selected = index % bundles.count
183
+ let file = root.appendingPathComponent("session-file-\(index)")
184
+ try bundles[selected].encrypted.write(to: file)
185
+ try sessions[selected].decryptFile(filePath: file, expectedCiphertextSha256: CryptoCipher.calcChecksum(filePath: file))
186
+ let actual = try Data(contentsOf: file)
187
+ if actual != bundles[selected].zip {
188
+ throw NSError(domain: "SessionTest", code: 1)
189
+ }
190
+ } catch {
191
+ lock.lock()
192
+ failures.append(error.localizedDescription)
193
+ lock.unlock()
194
+ }
195
+ }
196
+ XCTAssertTrue(failures.isEmpty, "\(fixture.label): " + failures.joined(separator: "; "))
197
+ }
198
+ }
199
+
200
+ func testInvalidSessionDoesNotModifyFilesOrPoisonAnotherSession() throws {
201
+ for fixture in try loadFixtures() {
202
+ let (publicKey, bundles) = (fixture.publicKey, fixture.bundles)
203
+ let bundle = try XCTUnwrap(bundles.first)
204
+ let file = root.appendingPathComponent("invalid-session")
205
+ try bundle.encrypted.write(to: file)
206
+ let encryptedSha256 = CryptoCipher.calcChecksum(filePath: file)
207
+ XCTAssertThrowsError(
208
+ try CryptoCipher.DecryptionSession(publicKey: publicKey, sessionKey: "")
209
+ .decryptFile(filePath: file, expectedCiphertextSha256: encryptedSha256)
210
+ )
211
+ XCTAssertEqual(try Data(contentsOf: file), bundle.encrypted)
212
+ let invalid = CryptoCipher.DecryptionSession(publicKey: publicKey, sessionKey: "AAAA:AAAA")
213
+ for _ in 0..<2 {
214
+ XCTAssertThrowsError(try invalid.decryptFile(filePath: file, expectedCiphertextSha256: encryptedSha256))
215
+ XCTAssertEqual(try Data(contentsOf: file), bundle.encrypted)
216
+ }
217
+ try CryptoCipher.DecryptionSession(publicKey: publicKey, sessionKey: bundle.ivSessionKey)
218
+ .decryptFile(filePath: file, expectedCiphertextSha256: encryptedSha256)
219
+ XCTAssertEqual(try Data(contentsOf: file), bundle.zip)
220
+ }
221
+ }
222
+
223
+ func testTamperedCiphertextIsRejectedBeforeAnyDecryption() throws {
224
+ for fixture in try loadFixtures() {
225
+ let bundle = try XCTUnwrap(fixture.bundles.first)
226
+ let signed = try CryptoCipher.decryptBundleChecksum(checksum: bundle.checksum, publicKey: fixture.publicKey)
227
+ // Flip a bit in the second to last block: in CBC this only changes the final padding byte.
228
+ var tampered = bundle.encrypted
229
+ tampered[tampered.count - 17] ^= 1
230
+ let file = root.appendingPathComponent("tampered")
231
+ try tampered.write(to: file)
232
+ // An invalid session key would fail the moment the key is unwrapped: the mismatch error proves the
233
+ // encrypted bytes were rejected first.
234
+ let session = CryptoCipher.DecryptionSession(publicKey: fixture.publicKey, sessionKey: bundle.ivSessionKey)
235
+ XCTAssertThrowsError(try session.decryptFile(filePath: file, expectedCiphertextSha256: signed.ciphertext)) { error in
236
+ guard case CryptoCipher.CiphertextChecksumError.mismatch = error else {
237
+ return XCTFail("\(fixture.label): expected a ciphertext checksum mismatch, got \(error)")
238
+ }
239
+ }
240
+ XCTAssertEqual(try Data(contentsOf: file), tampered)
241
+ XCTAssertThrowsError(try session.decryptFile(filePath: file, expectedCiphertextSha256: nil)) { error in
242
+ guard case CryptoCipher.CiphertextChecksumError.missing = error else {
243
+ return XCTFail("\(fixture.label): expected a missing ciphertext checksum, got \(error)")
244
+ }
245
+ }
246
+ XCTAssertEqual(try Data(contentsOf: file), tampered)
247
+ }
248
+ }
249
+ }