@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,380 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+
7
+ import Foundation
8
+ import CryptoKit
9
+
10
+ public struct CryptoCipher {
11
+ private static var logger: Logger!
12
+
13
+ public static func setLogger(_ logger: Logger) {
14
+ self.logger = logger
15
+ }
16
+
17
+ private static func hexStringToData(_ hex: String) -> Data? {
18
+ var data = Data()
19
+ var hexIterator = hex.makeIterator()
20
+ while let char1 = hexIterator.next(), let char2 = hexIterator.next() {
21
+ guard let byte = UInt8(String([char1, char2]), radix: 16) else {
22
+ return nil
23
+ }
24
+ data.append(byte)
25
+ }
26
+ return data
27
+ }
28
+
29
+ private static func isHexString(_ str: String) -> Bool {
30
+ let hexCharacterSet = CharacterSet(charactersIn: "0123456789abcdefABCDEF")
31
+ return str.unicodeScalars.allSatisfy { hexCharacterSet.contains($0) }
32
+ }
33
+
34
+ /// Plaintext and ciphertext SHA-256 digests recovered from a signed bundle checksum, as lowercase hex.
35
+ public struct BundleChecksum {
36
+ /// SHA-256 of the decrypted bundle or file, compared after decryption.
37
+ public let plain: String
38
+ /// SHA-256 of the encrypted bytes as served, checked before decryption. `nil` without a public key.
39
+ public let ciphertext: String?
40
+ }
41
+
42
+ /// Size of the signed checksum payload: SHA-256 of the plaintext followed by SHA-256 of the ciphertext.
43
+ static let signedChecksumPayloadBytes = 64
44
+
45
+ /// Thrown when encrypted bytes do not match the signed ciphertext checksum. Nothing was decrypted.
46
+ enum CiphertextChecksumError: Error, LocalizedError {
47
+ case missing
48
+ case mismatch
49
+
50
+ var errorDescription: String? {
51
+ switch self {
52
+ case .missing:
53
+ return "Encrypted bundle has no signed ciphertext checksum. Re-upload the bundle with a current Capgo CLI."
54
+ case .mismatch:
55
+ return "Checksum verification failed: encrypted bytes do not match the signed checksum"
56
+ }
57
+ }
58
+ }
59
+
60
+ /// Decrypts the RSA encrypted bundle checksum. Since 9.0.0 the signed payload is 64 bytes: the SHA-256 of the
61
+ /// plaintext followed by the SHA-256 of the encrypted bytes (Capgo CLI "V4" checksum). Returns `checksum` as the
62
+ /// plain digest when no public key is configured. Throws for anything that is not an even-length hex string of
63
+ /// 256 bytes signed with the matching private key, and for the 32-byte payload of older CLIs.
64
+ public static func decryptBundleChecksum(checksum: String, publicKey: String) throws -> BundleChecksum {
65
+ if publicKey.isEmpty {
66
+ logger.info("No encryption set (public key) ignored")
67
+ return BundleChecksum(plain: checksum, ciphertext: nil)
68
+ }
69
+ do {
70
+ // The encrypted checksum is hex encoded. The base64 format of CLI uploads made for plugin
71
+ // versions older than 5.30.0 / 6.30.0 / 7.30.0 is no longer accepted since 9.0.0.
72
+ // An odd length is rejected too: hexStringToData would silently drop the last digit.
73
+ guard checksum.count.isMultiple(of: 2), isHexString(checksum), let checksumBytes = hexStringToData(checksum) else {
74
+ logger.error("Cannot decode checksum as hex. Re-upload the bundle with a current Capgo CLI.")
75
+ logger.debug("Checksum value: \(checksum)")
76
+ throw CustomError.cannotDecode
77
+ }
78
+ logger.debug("Received checksum format: hex (length: \(checksum.count) chars, \(checksumBytes.count) bytes)")
79
+
80
+ if checksumBytes.isEmpty {
81
+ logger.error("Decoded checksum is empty")
82
+ throw CustomError.cannotDecode
83
+ }
84
+
85
+ // RSA-2048 encrypted data must be exactly 256 bytes
86
+ // If the checksum is not 256 bytes, the bundle was not encrypted properly
87
+ if checksumBytes.count != 256 {
88
+ // swiftlint:disable:next line_length
89
+ logger.error("Checksum is not RSA encrypted (size: \(checksumBytes.count) bytes, expected 256 for RSA-2048). Bundle must be uploaded with encryption when public key is configured.")
90
+ throw CustomError.cannotDecode
91
+ }
92
+
93
+ guard let rsaPublicKey = RSAPublicKey.load(rsaPublicKey: publicKey) else {
94
+ logger.error("The public key is not a valid RSA Public key")
95
+ throw CustomError.cannotDecode
96
+ }
97
+
98
+ guard let decryptedChecksum = rsaPublicKey.decrypt(data: checksumBytes) else {
99
+ logger.error("decryptChecksum fail")
100
+ throw NSError(domain: "Failed to decrypt session key data", code: 2, userInfo: nil)
101
+ }
102
+
103
+ guard decryptedChecksum.count == signedChecksumPayloadBytes else {
104
+ logger.error("Signed checksum has no ciphertext digest. Re-upload the bundle with a Capgo CLI that supports updater 9.")
105
+ logger.debug("Decrypted checksum bytes: \(decryptedChecksum.count), expected: \(signedChecksumPayloadBytes)")
106
+ throw CustomError.cannotDecode
107
+ }
108
+
109
+ let hex = decryptedChecksum.map { String(format: "%02x", $0) }.joined()
110
+ logger.debug("Decrypted checksum: SHA-256 of plaintext and ciphertext (64 bytes)")
111
+ return BundleChecksum(plain: String(hex.prefix(64)), ciphertext: String(hex.suffix(64)))
112
+ } catch {
113
+ logger.error("Checksum decryption failed")
114
+ logger.debug("Error: \(error.localizedDescription)")
115
+ throw CustomError.cannotDecode
116
+ }
117
+ }
118
+
119
+ /// Returns the SHA-256 of the plaintext from the signed bundle checksum, or `checksum` unchanged when no public
120
+ /// key is configured. See `decryptBundleChecksum(checksum:publicKey:)`.
121
+ public static func decryptChecksum(checksum: String, publicKey: String) throws -> String {
122
+ try decryptBundleChecksum(checksum: checksum, publicKey: publicKey).plain
123
+ }
124
+
125
+ /// Rejects `filePath` unless its SHA-256 equals the signed ciphertext checksum. Runs before decryption, so
126
+ /// CBC padding is only ever checked on signed ciphertext.
127
+ static func verifyCiphertextChecksum(filePath: URL, expectedCiphertextSha256: String?) throws {
128
+ guard let expected = expectedCiphertextSha256, expected.count == 64, isHexString(expected) else {
129
+ throw CiphertextChecksumError.missing
130
+ }
131
+ let actual = try calcChecksumOrThrow(filePath: filePath)
132
+ if actual.lowercased() != expected.lowercased() {
133
+ logger.error("Encrypted file checksum mismatch, refusing to decrypt")
134
+ logger.debug("Expected: \(expected), Got: \(actual)")
135
+ throw CiphertextChecksumError.mismatch
136
+ }
137
+ }
138
+
139
+ /// Detect checksum algorithm based on hex string length.
140
+ /// SHA-256 = 64 hex chars (32 bytes). It is the only supported algorithm.
141
+ public static func detectChecksumAlgorithm(_ hexChecksum: String) -> String {
142
+ if hexChecksum.isEmpty {
143
+ return "empty"
144
+ }
145
+ let len = hexChecksum.count
146
+ if len == 64 {
147
+ return "SHA-256"
148
+ } else {
149
+ return "unknown (\(len) hex chars)"
150
+ }
151
+ }
152
+
153
+ /// Log checksum info and warn if the checksum is not SHA-256.
154
+ public static func logChecksumInfo(label: String, hexChecksum: String) {
155
+ let algorithm = detectChecksumAlgorithm(hexChecksum)
156
+ logger.debug("\(label): \(algorithm) hex format (length: \(hexChecksum.count) chars)")
157
+ if algorithm.contains("unknown") {
158
+ logger.error("Unknown checksum algorithm detected")
159
+ logger.debug("Char count: \(hexChecksum.count), Expected: 64 (SHA-256)")
160
+ }
161
+ }
162
+
163
+ /// 256 KiB: one size for checksum, copy, and decode.
164
+ /// 64 workers * 256 KiB = 16 MiB for one buffer; AES/Brotli hold two (~32 MiB).
165
+ static let ioBufferBytesValue = 256 * 1024
166
+
167
+ static func ioBufferBytes() -> Int {
168
+ return ioBufferBytesValue
169
+ }
170
+
171
+ static func checksumBufferBytes() -> Int {
172
+ return ioBufferBytesValue
173
+ }
174
+
175
+ static func copyBufferBytes() -> Int {
176
+ return ioBufferBytesValue
177
+ }
178
+
179
+ public static func calcChecksum(filePath: URL) -> String {
180
+ do {
181
+ return try calcChecksumOrThrow(filePath: filePath)
182
+ } catch {
183
+ logger.error("Cannot calculate checksum")
184
+ logger.debug("Path: \(filePath.path), Error: \(error)")
185
+ return ""
186
+ }
187
+ }
188
+
189
+ static func calcChecksumOrThrow(filePath: URL) throws -> String {
190
+ let file = try FileHandle(forReadingFrom: filePath)
191
+ defer { try? file.close() }
192
+ var sha256 = SHA256()
193
+ while true {
194
+ let count = try autoreleasepool {
195
+ let data = try file.read(upToCount: checksumBufferBytes()) ?? Data()
196
+ sha256.update(data: data)
197
+ return data.count
198
+ }
199
+ if count == 0 { break }
200
+ }
201
+ return hexString(from: sha256)
202
+ }
203
+
204
+ final class RunningChecksum {
205
+ private var sha256 = SHA256()
206
+
207
+ func update(_ data: Data) {
208
+ guard !data.isEmpty else {
209
+ return
210
+ }
211
+ sha256.update(data: data)
212
+ }
213
+
214
+ func hex() -> String {
215
+ CryptoCipher.hexString(from: sha256)
216
+ }
217
+ }
218
+
219
+ static func hexString(from sha256: SHA256) -> String {
220
+ return sha256.finalize().compactMap { String(format: "%02x", $0) }.joined()
221
+ }
222
+
223
+ static func shortPathKey(_ fileName: String) -> String {
224
+ var sha256 = SHA256()
225
+ sha256.update(data: Data(fileName.utf8))
226
+ return String(hexString(from: sha256).prefix(16))
227
+ }
228
+
229
+ public static func isValidSessionKey(_ sessionKey: String) -> Bool {
230
+ if sessionKey.isEmpty {
231
+ return false
232
+ }
233
+ let sessionKeyParts = sessionKey.components(separatedBy: ":")
234
+ return sessionKeyParts.count == 2 && !sessionKeyParts[0].isEmpty && !sessionKeyParts[1].isEmpty
235
+ }
236
+
237
+ /// Decrypts `filePath` in place. `expectedCiphertextSha256` is `BundleChecksum.ciphertext`: the file is hashed
238
+ /// and rejected before any AES work when it does not match.
239
+ public static func decryptFile(
240
+ filePath: URL, publicKey: String, sessionKey: String, version: String, expectedCiphertextSha256: String?
241
+ ) throws {
242
+ if publicKey.isEmpty || !isValidSessionKey(sessionKey) {
243
+ logger.info("Encryption not set, no public key or session, ignored")
244
+ return
245
+ }
246
+ try DecryptionSession(publicKey: publicKey, sessionKey: sessionKey)
247
+ .decryptFile(filePath: filePath, expectedCiphertextSha256: expectedCiphertextSha256)
248
+ }
249
+
250
+ // Scoped to one manifest. Key material is immutable; CBC state stays local to each file.
251
+ final class DecryptionSession {
252
+ private let publicKey: String
253
+ private let sessionKey: String
254
+ private let lock = NSLock()
255
+ private var prepared: Result<AES128Key, Error>?
256
+
257
+ init(publicKey: String, sessionKey: String) {
258
+ self.publicKey = publicKey
259
+ self.sessionKey = sessionKey
260
+ }
261
+
262
+ private func key() throws -> AES128Key {
263
+ lock.lock()
264
+ defer { lock.unlock() }
265
+ if let prepared { return try prepared.get() }
266
+ let result = Result { try CryptoCipher.prepareDecryptionKey(publicKey: publicKey, sessionKey: sessionKey) }
267
+ prepared = result
268
+ return try result.get()
269
+ }
270
+
271
+ var isEncrypted: Bool {
272
+ !publicKey.isEmpty
273
+ }
274
+
275
+ func decryptFile(filePath: URL, expectedCiphertextSha256: String?) throws {
276
+ guard isEncrypted else {
277
+ CryptoCipher.logger.info("Encryption not set, no public key or session, ignored")
278
+ return
279
+ }
280
+ // Authenticate the encrypted bytes first: tampered ciphertext never reaches the cipher.
281
+ try CryptoCipher.verifyCiphertextChecksum(filePath: filePath, expectedCiphertextSha256: expectedCiphertextSha256)
282
+ try CryptoCipher.decryptPreparedFile(filePath: filePath, aesPrivateKey: key())
283
+ }
284
+ }
285
+
286
+ private static func prepareDecryptionKey(publicKey: String, sessionKey: String) throws -> AES128Key {
287
+ guard isValidSessionKey(sessionKey) else { throw CustomError.cannotDecode }
288
+ // The bundle is encrypted from here on: an unusable key must fail, never leave it encrypted.
289
+ if !publicKey.hasPrefix("-----BEGIN RSA PUBLIC KEY-----") {
290
+ logger.error("The public key is not a valid RSA Public key")
291
+ throw CustomError.cannotDecode
292
+ }
293
+
294
+ do {
295
+ guard let rsaPublicKey = RSAPublicKey.load(rsaPublicKey: publicKey) else {
296
+ logger.error("The public key is not a valid RSA Public key")
297
+ throw CustomError.cannotDecode
298
+ }
299
+
300
+ let sessionKeyComponents = sessionKey.components(separatedBy: ":")
301
+ let ivBase64 = sessionKeyComponents[0]
302
+ let encryptedKeyBase64 = sessionKeyComponents[1]
303
+
304
+ guard let ivData = Data(base64Encoded: ivBase64) else {
305
+ logger.error("Cannot decode sessionKey IV")
306
+ logger.debug("IV value: \(ivBase64)")
307
+ throw CustomError.cannotDecode
308
+ }
309
+
310
+ if ivData.count != 16 {
311
+ logger.error("IV data has invalid length")
312
+ logger.debug("Length: \(ivData.count), Expected: 16")
313
+ throw CustomError.cannotDecode
314
+ }
315
+
316
+ guard let sessionKeyDataEncrypted = Data(base64Encoded: encryptedKeyBase64) else {
317
+ logger.error("Cannot decode sessionKey data")
318
+ logger.debug("Key value: \(encryptedKeyBase64)")
319
+ throw NSError(domain: "Invalid session key data", code: 1, userInfo: nil)
320
+ }
321
+
322
+ guard let sessionKeyDataDecrypted = rsaPublicKey.decrypt(data: sessionKeyDataEncrypted) else {
323
+ logger.error("Failed to decrypt session key data")
324
+ throw NSError(domain: "Failed to decrypt session key data", code: 2, userInfo: nil)
325
+ }
326
+
327
+ if sessionKeyDataDecrypted.count != 16 {
328
+ logger.error("Decrypted session key has invalid length")
329
+ logger.debug("Length: \(sessionKeyDataDecrypted.count), Expected: 16")
330
+ throw NSError(domain: "Invalid decrypted session key", code: 5, userInfo: nil)
331
+ }
332
+
333
+ return AES128Key(iv: ivData, aes128Key: sessionKeyDataDecrypted, logger: logger)
334
+ } catch {
335
+ logger.error("File decryption failed")
336
+ throw CustomError.cannotDecode
337
+ }
338
+ }
339
+
340
+ private static func decryptPreparedFile(filePath: URL, aesPrivateKey: AES128Key) throws {
341
+ do {
342
+ let encryptedSize = (try FileManager.default.attributesOfItem(atPath: filePath.path)[.size] as? NSNumber)?.uint64Value ?? 0
343
+ if encryptedSize == 0 {
344
+ logger.error("Encrypted file data is empty")
345
+ throw NSError(domain: "Empty encrypted data", code: 6, userInfo: nil)
346
+ }
347
+
348
+ try aesPrivateKey.decrypt(from: filePath, to: filePath)
349
+ let decryptedSize = (try FileManager.default.attributesOfItem(atPath: filePath.path)[.size] as? NSNumber)?.uint64Value ?? 0
350
+ if decryptedSize == 0 {
351
+ logger.error("Decrypted data is empty")
352
+ throw NSError(domain: "Empty decrypted data", code: 7, userInfo: nil)
353
+ }
354
+ } catch {
355
+ logger.error("File decryption failed")
356
+ throw CustomError.cannotDecode
357
+ }
358
+ }
359
+
360
+ /// Get first 20 characters of the public key for identification
361
+ /// Returns 20-character string or empty string if key is invalid/empty
362
+ /// The first 12 chars are always "MIIBCgKCAQEA" for RSA 2048-bit keys,
363
+ /// so the unique part starts at character 13
364
+ public static func calcKeyId(publicKey: String) -> String {
365
+ if publicKey.isEmpty {
366
+ return ""
367
+ }
368
+
369
+ // Remove PEM headers and whitespace to get the raw key data
370
+ let cleanedKey = publicKey
371
+ .replacingOccurrences(of: "-----BEGIN RSA PUBLIC KEY-----", with: "")
372
+ .replacingOccurrences(of: "-----END RSA PUBLIC KEY-----", with: "")
373
+ .replacingOccurrences(of: "\n", with: "")
374
+ .replacingOccurrences(of: "\r", with: "")
375
+ .replacingOccurrences(of: " ", with: "")
376
+
377
+ // Return first 20 characters of the base64-encoded key
378
+ return String(cleanedKey.prefix(20))
379
+ }
380
+ }