@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,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,156 @@
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 downloadVerifiedWithTransferHook(
22
+ url _: URL,
23
+ version _: String,
24
+ sessionKey _: String,
25
+ expectedChecksum _: String,
26
+ link _: String?,
27
+ comment _: String?,
28
+ beforeTransfer: (() throws -> Void)?
29
+ ) throws -> BundleInfo {
30
+ try beforeTransfer?()
31
+ return downloadedBundle
32
+ }
33
+ }
34
+
35
+ private final class AutoUpdateChecksumCapgoUpdater: StatsTrackingCapgoUpdater {
36
+ override func getLatest(url: URL, channel: String?, appIdOverride: String? = nil) -> AppVersion {
37
+ let latest = AppVersion()
38
+ latest.version = "2.0.0"
39
+ latest.url = "https://example.com/update.zip"
40
+ latest.checksum = ""
41
+ return latest
42
+ }
43
+
44
+ override func getCurrentBundle() -> BundleInfo {
45
+ BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "abc")
46
+ }
47
+ }
48
+
49
+ private final class TestableCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
50
+ override func runBackgroundDownloadWork(_ work: @escaping () -> Void) {
51
+ work()
52
+ }
53
+ }
54
+
55
+ private var implementation: StatsTrackingCapgoUpdater!
56
+
57
+ override func setUp() {
58
+ super.setUp()
59
+ implementation = StatsTrackingCapgoUpdater()
60
+ implementation.setLogger(Logger(withTag: "ChecksumRequiredTests", options: Logger.Options(level: .silent)))
61
+ implementation.setPublicKey("")
62
+ implementation.resetIncompleteDownloadRetryCount(version: "2.0.0")
63
+ }
64
+
65
+ override func tearDown() {
66
+ // Checksum failures leave a persisted integrity block and retry budget for the version.
67
+ implementation.resetIncompleteDownloadRetryCount(version: "2.0.0")
68
+ implementation.shutdown()
69
+ implementation = nil
70
+ super.tearDown()
71
+ }
72
+
73
+ func testDownloadBundleRejectsWhenChecksumMissing() {
74
+ let plugin = TestableCapacitorUpdaterPlugin()
75
+ plugin.implementation = implementation
76
+
77
+ XCTAssertThrowsError(
78
+ try plugin.downloadBundleForTesting(
79
+ urlString: "https://example.com/update.zip",
80
+ version: "1.0.0",
81
+ sessionKey: "",
82
+ checksum: "",
83
+ manifestEntries: nil
84
+ )
85
+ )
86
+ XCTAssertTrue(implementation.sentStatsActions.contains("checksum_required"))
87
+ }
88
+
89
+ func testDownloadBundleRejectsWhenChecksumMismatch() throws {
90
+ let plugin = TestableCapacitorUpdaterPlugin()
91
+ let downloaded = BundleInfo(
92
+ id: "downloaded-id",
93
+ version: "1.0.0",
94
+ status: .PENDING,
95
+ downloaded: Date(),
96
+ checksum: "actual-checksum"
97
+ )
98
+ let downloadingImplementation = DownloadStubCapgoUpdater(downloadedBundle: downloaded)
99
+ downloadingImplementation.setLogger(Logger(withTag: "ChecksumRequiredTests", options: Logger.Options(level: .silent)))
100
+ plugin.implementation = downloadingImplementation
101
+
102
+ XCTAssertThrowsError(
103
+ try plugin.downloadBundleForTesting(
104
+ urlString: "https://example.com/update.zip",
105
+ version: "1.0.0",
106
+ sessionKey: "",
107
+ checksum: "expected-checksum",
108
+ manifestEntries: nil
109
+ )
110
+ )
111
+ XCTAssertTrue(downloadingImplementation.sentStatsActions.contains("checksum_fail"))
112
+ downloadingImplementation.shutdown()
113
+ }
114
+
115
+ func testDownloadBundleAcceptsWhenChecksumMatches() throws {
116
+ let plugin = TestableCapacitorUpdaterPlugin()
117
+ let downloaded = BundleInfo(
118
+ id: "downloaded-id",
119
+ version: "1.0.0",
120
+ status: .PENDING,
121
+ downloaded: Date(),
122
+ checksum: "matching-checksum"
123
+ )
124
+ let downloadingImplementation = DownloadStubCapgoUpdater(downloadedBundle: downloaded)
125
+ downloadingImplementation.setLogger(Logger(withTag: "ChecksumRequiredTests", options: Logger.Options(level: .silent)))
126
+ plugin.implementation = downloadingImplementation
127
+
128
+ let bundle = try plugin.downloadBundleForTesting(
129
+ urlString: "https://example.com/update.zip",
130
+ version: "1.0.0",
131
+ sessionKey: "",
132
+ checksum: "matching-checksum",
133
+ manifestEntries: nil
134
+ )
135
+
136
+ XCTAssertEqual(bundle.getChecksum(), "matching-checksum")
137
+ XCTAssertFalse(downloadingImplementation.sentStatsActions.contains("checksum_required"))
138
+ XCTAssertFalse(downloadingImplementation.sentStatsActions.contains("checksum_fail"))
139
+ downloadingImplementation.shutdown()
140
+ }
141
+
142
+ func testAutoUpdateBackgroundDownloadRejectsWhenChecksumMissing() {
143
+ let updater = AutoUpdateChecksumCapgoUpdater()
144
+ updater.setLogger(Logger(withTag: "ChecksumRequiredTests", options: Logger.Options(level: .silent)))
145
+
146
+ let plugin = TestableCapacitorUpdaterPlugin()
147
+ plugin.implementation = updater
148
+ plugin.setAutoUpdateModeForTesting("onlyDownload")
149
+ plugin.setUpdateUrlForTesting("https://example.com/channel")
150
+
151
+ plugin.backgroundDownload()
152
+
153
+ XCTAssertTrue(updater.sentStatsActions.contains("checksum_required"))
154
+ updater.shutdown()
155
+ }
156
+ }
@@ -0,0 +1,314 @@
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
+ 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
+ var downloadRequests = 0
126
+ var sentStatsActions: [String] = []
127
+
128
+ override func sendStats(action: String, versionName _: String? = nil, oldVersionName _: String? = "") {
129
+ sentStatsActions.append(action)
130
+ }
131
+
132
+ override func performDownloadRequest(
133
+ _ request: URLRequest,
134
+ label _: String,
135
+ resumeData _: Data? = nil,
136
+ onProgress _: ((Int64, Int64) -> Void)? = nil
137
+ ) -> DownloadRequestResult {
138
+ downloadRequests += 1
139
+ let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent("capgo-cli-fixture-\(UUID().uuidString).zip")
140
+ do {
141
+ try payload.write(to: fileURL)
142
+ } catch {
143
+ return DownloadRequestResult(fileURL: nil, response: nil, error: error, timedOut: false)
144
+ }
145
+ let response = HTTPURLResponse(url: request.url ?? fileURL, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil)
146
+ return DownloadRequestResult(fileURL: fileURL, response: response, error: nil, timedOut: false)
147
+ }
148
+ }
149
+
150
+ func testDownloadVerifiedInstallsEveryCliEncryptedBundle() throws {
151
+ for fixture in try loadFixtures() {
152
+ for bundle in fixture.bundles {
153
+ let updater = FixtureDownloadCapgoUpdater()
154
+ updater.setLogger(Logger(withTag: "cli-fixture-tests", options: Logger.Options(level: .silent)))
155
+ // Payloads are served from file:// URLs.
156
+ updater.httpsOnly = false
157
+ updater.setPublicKey(fixture.publicKey)
158
+ updater.payload = bundle.encrypted
159
+ defer { updater.shutdown() }
160
+
161
+ // The raw update response values: encrypted checksum and ivSessionKey from the CLI.
162
+ let installed = try updater.downloadVerified(
163
+ url: root.appendingPathComponent("\(bundle.id).zip"),
164
+ version: "9.9.9-cli-\(bundle.id)",
165
+ sessionKey: bundle.ivSessionKey,
166
+ expectedChecksum: bundle.checksum
167
+ )
168
+ defer { _ = updater.delete(id: installed.getId()) }
169
+
170
+ XCTAssertEqual(installed.getChecksum(), bundle.sha256, bundle.id)
171
+ let bundleDir = libraryDir.appendingPathComponent("NoCloud/ionic_built_snapshots").appendingPathComponent(installed.getId())
172
+ for file in bundle.files {
173
+ let path = bundleDir.appendingPathComponent(file.path)
174
+ XCTAssertEqual(CryptoCipher.calcChecksum(filePath: path), file.sha256, "\(bundle.id): \(file.path)")
175
+ }
176
+ }
177
+ }
178
+ }
179
+ /// Encrypted bytes that miss the signed digest surface the same checksum error as a plaintext mismatch.
180
+ func testDownloadVerifiedMapsCiphertextMismatchToChecksumError() throws {
181
+ for fixture in try loadFixtures() {
182
+ let bundle = try XCTUnwrap(fixture.bundles.first)
183
+ let updater = FixtureDownloadCapgoUpdater()
184
+ updater.setLogger(Logger(withTag: "cli-fixture-tests", options: Logger.Options(level: .silent)))
185
+ updater.httpsOnly = false
186
+ updater.setPublicKey(fixture.publicKey)
187
+ var tampered = bundle.encrypted
188
+ tampered[tampered.count - 17] ^= 1
189
+ updater.payload = tampered
190
+ defer { updater.shutdown() }
191
+ let tamperedVersion = "9.9.9-cli-tampered-\(bundle.id)"
192
+ // Bundle records live in the shared UserDefaults, so drop any left by earlier runs first.
193
+ for stale in updater.list(raw: true) where stale.getVersionName() == tamperedVersion {
194
+ _ = updater.saveBundleInfo(id: stale.getId(), bundle: nil)
195
+ }
196
+
197
+ XCTAssertThrowsError(
198
+ try updater.downloadVerified(
199
+ url: root.appendingPathComponent("\(bundle.id)-tampered.zip"),
200
+ version: tamperedVersion,
201
+ sessionKey: bundle.ivSessionKey,
202
+ expectedChecksum: bundle.checksum
203
+ )
204
+ ) { error in
205
+ XCTAssertEqual(error as? ObjectSavableError, .checksum, "\(fixture.label): \(error)")
206
+ }
207
+ XCTAssertTrue(updater.sentStatsActions.contains("checksum_fail"), fixture.label)
208
+ // No ERROR record may stay behind, or the next automatic check would not download this version again.
209
+ let leftover = updater.list(raw: true).filter { $0.getVersionName() == tamperedVersion && $0.isErrorStatus() }
210
+ XCTAssertTrue(leftover.isEmpty, "\(fixture.label): \(leftover)")
211
+ }
212
+ }
213
+
214
+ /// The unchecked entry point cannot decrypt, so it rejects an encrypted download before any network I/O.
215
+ func testUncheckedDownloadRejectsEncryptedBundleBeforeNetwork() throws {
216
+ for fixture in try loadFixtures() {
217
+ let bundle = try XCTUnwrap(fixture.bundles.first)
218
+ let updater = FixtureDownloadCapgoUpdater()
219
+ updater.setLogger(Logger(withTag: "cli-fixture-tests", options: Logger.Options(level: .silent)))
220
+ updater.httpsOnly = false
221
+ updater.setPublicKey(fixture.publicKey)
222
+ updater.payload = bundle.encrypted
223
+ defer { updater.shutdown() }
224
+
225
+ XCTAssertThrowsError(
226
+ try updater.download(
227
+ url: root.appendingPathComponent("\(bundle.id).zip"),
228
+ version: "9.9.9-cli-unchecked-\(bundle.id)",
229
+ sessionKey: bundle.ivSessionKey
230
+ )
231
+ ) { error in
232
+ XCTAssertEqual((error as NSError).domain, "ChecksumError", fixture.label)
233
+ XCTAssertEqual((error as NSError).code, 2, fixture.label)
234
+ }
235
+ XCTAssertEqual(updater.downloadRequests, 0, fixture.label)
236
+ }
237
+ }
238
+
239
+ func testConcurrentManifestSessionsResetCipherAndKeepKeysSeparate() throws {
240
+ for fixture in try loadFixtures() {
241
+ let (publicKey, bundles) = (fixture.publicKey, fixture.bundles)
242
+ let sessions = bundles.map { CryptoCipher.DecryptionSession(publicKey: publicKey, sessionKey: $0.ivSessionKey) }
243
+ let lock = NSLock()
244
+ var failures: [String] = []
245
+ DispatchQueue.concurrentPerform(iterations: 24) { index in
246
+ do {
247
+ let selected = index % bundles.count
248
+ let file = root.appendingPathComponent("session-file-\(index)")
249
+ try bundles[selected].encrypted.write(to: file)
250
+ try sessions[selected].decryptFile(filePath: file, expectedCiphertextSha256: CryptoCipher.calcChecksum(filePath: file))
251
+ let actual = try Data(contentsOf: file)
252
+ if actual != bundles[selected].zip {
253
+ throw NSError(domain: "SessionTest", code: 1)
254
+ }
255
+ } catch {
256
+ lock.lock()
257
+ failures.append(error.localizedDescription)
258
+ lock.unlock()
259
+ }
260
+ }
261
+ XCTAssertTrue(failures.isEmpty, "\(fixture.label): " + failures.joined(separator: "; "))
262
+ }
263
+ }
264
+
265
+ func testInvalidSessionDoesNotModifyFilesOrPoisonAnotherSession() throws {
266
+ for fixture in try loadFixtures() {
267
+ let (publicKey, bundles) = (fixture.publicKey, fixture.bundles)
268
+ let bundle = try XCTUnwrap(bundles.first)
269
+ let file = root.appendingPathComponent("invalid-session")
270
+ try bundle.encrypted.write(to: file)
271
+ let encryptedSha256 = CryptoCipher.calcChecksum(filePath: file)
272
+ XCTAssertThrowsError(
273
+ try CryptoCipher.DecryptionSession(publicKey: publicKey, sessionKey: "")
274
+ .decryptFile(filePath: file, expectedCiphertextSha256: encryptedSha256)
275
+ )
276
+ XCTAssertEqual(try Data(contentsOf: file), bundle.encrypted)
277
+ let invalid = CryptoCipher.DecryptionSession(publicKey: publicKey, sessionKey: "AAAA:AAAA")
278
+ for _ in 0..<2 {
279
+ XCTAssertThrowsError(try invalid.decryptFile(filePath: file, expectedCiphertextSha256: encryptedSha256))
280
+ XCTAssertEqual(try Data(contentsOf: file), bundle.encrypted)
281
+ }
282
+ try CryptoCipher.DecryptionSession(publicKey: publicKey, sessionKey: bundle.ivSessionKey)
283
+ .decryptFile(filePath: file, expectedCiphertextSha256: encryptedSha256)
284
+ XCTAssertEqual(try Data(contentsOf: file), bundle.zip)
285
+ }
286
+ }
287
+
288
+ func testTamperedCiphertextIsRejectedBeforeAnyDecryption() throws {
289
+ for fixture in try loadFixtures() {
290
+ let bundle = try XCTUnwrap(fixture.bundles.first)
291
+ let signed = try CryptoCipher.decryptBundleChecksum(checksum: bundle.checksum, publicKey: fixture.publicKey)
292
+ // Flip a bit in the second to last block: in CBC this only changes the final padding byte.
293
+ var tampered = bundle.encrypted
294
+ tampered[tampered.count - 17] ^= 1
295
+ let file = root.appendingPathComponent("tampered")
296
+ try tampered.write(to: file)
297
+ // An invalid session key would fail the moment the key is unwrapped: the mismatch error proves the
298
+ // encrypted bytes were rejected first.
299
+ let session = CryptoCipher.DecryptionSession(publicKey: fixture.publicKey, sessionKey: bundle.ivSessionKey)
300
+ XCTAssertThrowsError(try session.decryptFile(filePath: file, expectedCiphertextSha256: signed.ciphertext)) { error in
301
+ guard case CryptoCipher.CiphertextChecksumError.mismatch = error else {
302
+ return XCTFail("\(fixture.label): expected a ciphertext checksum mismatch, got \(error)")
303
+ }
304
+ }
305
+ XCTAssertEqual(try Data(contentsOf: file), tampered)
306
+ XCTAssertThrowsError(try session.decryptFile(filePath: file, expectedCiphertextSha256: nil)) { error in
307
+ guard case CryptoCipher.CiphertextChecksumError.missing = error else {
308
+ return XCTFail("\(fixture.label): expected a missing ciphertext checksum, got \(error)")
309
+ }
310
+ }
311
+ XCTAssertEqual(try Data(contentsOf: file), tampered)
312
+ }
313
+ }
314
+ }