@capgo/capacitor-updater 5.51.15 → 5.51.21

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 (29) hide show
  1. package/CapgoCapacitorUpdater.podspec +0 -2
  2. package/Package.swift +2 -4
  3. package/README.md +50 -41
  4. package/android/build.gradle +6 -6
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +45 -36
  6. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +302 -318
  7. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +11 -0
  8. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +227 -64
  9. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +12 -1
  10. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +12 -16
  11. package/dist/docs.json +4 -4
  12. package/dist/esm/definitions.d.ts +12 -9
  13. package/dist/esm/definitions.js.map +1 -1
  14. package/dist/esm/history.js +7 -7
  15. package/dist/esm/history.js.map +1 -1
  16. package/dist/plugin.cjs.js +7 -7
  17. package/dist/plugin.cjs.js.map +1 -1
  18. package/dist/plugin.js +7 -7
  19. package/dist/plugin.js.map +1 -1
  20. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +177 -55
  21. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  22. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +27 -13
  23. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +30 -30
  24. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +16 -41
  25. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +5 -5
  26. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +73 -251
  27. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +2 -2
  28. package/package.json +8 -9
  29. package/ios/Sources/CapacitorUpdaterPlugin/BigInt.swift +0 -39
@@ -172,7 +172,15 @@ import UIKit
172
172
  return nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorTimedOut
173
173
  }
174
174
 
175
- private lazy var alamofireSession: Session = {
175
+ // lazy var is not thread-safe; concurrent manifest downloads can race first access when statsUrl is empty.
176
+ private var _alamofireSession: Session?
177
+ private let alamofireSessionLock = NSLock()
178
+ private var alamofireSession: Session {
179
+ alamofireSessionLock.lock()
180
+ defer { alamofireSessionLock.unlock() }
181
+ if let session = _alamofireSession {
182
+ return session
183
+ }
176
184
  let configuration = URLSessionConfiguration.ephemeral
177
185
  configuration.httpAdditionalHeaders = ["User-Agent": self.userAgent]
178
186
  configuration.httpCookieStorage = nil
@@ -180,8 +188,10 @@ import UIKit
180
188
  configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
181
189
  configuration.urlCache = nil
182
190
  configuration.httpMaximumConnectionsPerHost = Self.manifestMaxConcurrentFiles
183
- return Session(configuration: configuration)
184
- }()
191
+ let session = Session(configuration: configuration)
192
+ _alamofireSession = session
193
+ return session
194
+ }
185
195
  private let networkResponseQueue = DispatchQueue(label: "ee.forgr.capacitor-updater.network-response", qos: .utility)
186
196
 
187
197
  public var notifyDownloadRaw: (String, Int, Bool, BundleInfo?) -> Void = { _, _, _, _ in }
@@ -928,10 +938,7 @@ import UIKit
928
938
 
929
939
  struct ManifestLookupEntry {
930
940
  let hash: String
931
- /// The manifest's own file name, `.br` suffix included when present. The
932
- /// built-in bundle stores files under this exact name (see
933
- /// isManifestEntryAvailableLocally), unlike the extracted/cached copy which
934
- /// is always named without the suffix.
941
+ /// The manifest's own file name, `.br` suffix included when present.
935
942
  let originalFileName: String
936
943
  }
937
944
 
@@ -994,10 +1001,14 @@ import UIKit
994
1001
 
995
1002
  // Builtin is already a permanent reuse source (see isManifestEntryAvailableLocally),
996
1003
  // so there's no need to also duplicate this file into the delta cache
997
- let builtinRelativePath = knownEntry?.originalFileName ?? relativePath
998
- let builtinFilePath = builtinFolder.appendingPathComponent(builtinRelativePath)
999
- let isBuiltinOrigin = fileManager.fileExists(atPath: builtinFilePath.path) &&
1000
- verifyChecksum(file: builtinFilePath, expectedHash: checksum)
1004
+ let builtinLookupName = knownEntry?.originalFileName ?? relativePath
1005
+ let isBuiltinOrigin: Bool
1006
+ if let builtinFilePath = try? Self.resolveManifestTargetPath(baseDirectory: builtinFolder, fileName: builtinLookupName) {
1007
+ isBuiltinOrigin = fileManager.fileExists(atPath: builtinFilePath.path) &&
1008
+ verifyChecksum(file: builtinFilePath, expectedHash: checksum)
1009
+ } else {
1010
+ isBuiltinOrigin = false
1011
+ }
1001
1012
  if isBuiltinOrigin {
1002
1013
  continue
1003
1014
  }
@@ -1231,7 +1242,10 @@ import UIKit
1231
1242
  }
1232
1243
 
1233
1244
  let builtinFolder = self.builtinFolderURL()
1234
- let builtinFilePath = builtinFolder.appendingPathComponent(fileName)
1245
+ // The .br suffix describes transport; builtin assets are uncompressed.
1246
+ guard let builtinFilePath = try? Self.resolveManifestTargetPath(baseDirectory: builtinFolder, fileName: fileName) else {
1247
+ return false
1248
+ }
1235
1249
  if FileManager.default.fileExists(atPath: builtinFilePath.path) && verifyChecksum(file: builtinFilePath, expectedHash: fileHash) {
1236
1250
  return true
1237
1251
  }
@@ -1474,7 +1488,7 @@ import UIKit
1474
1488
  let builtinFilePath: URL
1475
1489
  do {
1476
1490
  destFilePath = try Self.resolveManifestTargetPath(baseDirectory: destFolder, fileName: fileName)
1477
- builtinFilePath = try Self.resolvePathInsideDirectory(baseDirectory: builtinFolder, relativePath: fileName)
1491
+ builtinFilePath = try Self.resolveManifestTargetPath(baseDirectory: builtinFolder, fileName: fileName)
1478
1492
  } catch {
1479
1493
  logger.error("Invalid manifest file path: \(fileName)")
1480
1494
  self.sendStats(action: "manifest_path_fail", versionName: "\(version):\(fileName)")
@@ -161,42 +161,43 @@ public struct CryptoCipher {
161
161
  let bufferSize = checksumBufferBytes()
162
162
  var sha256 = SHA256()
163
163
 
164
+ let fileHandle: FileHandle
164
165
  do {
165
- let fileHandle: FileHandle
166
+ fileHandle = try FileHandle(forReadingFrom: filePath)
167
+ } catch {
168
+ logger.error("Cannot open file for checksum calculation")
169
+ logger.debug("Path: \(filePath.path), Error: \(error)")
170
+ return ""
171
+ }
172
+
173
+ defer {
166
174
  do {
167
- fileHandle = try FileHandle(forReadingFrom: filePath)
175
+ try fileHandle.close()
168
176
  } catch {
169
- logger.error("Cannot open file for checksum calculation")
170
- logger.debug("Path: \(filePath.path), Error: \(error)")
171
- return ""
177
+ logger.error("Error closing file during checksum")
178
+ logger.debug("Error: \(error)")
172
179
  }
180
+ }
173
181
 
174
- defer {
175
- do {
176
- try fileHandle.close()
177
- } catch {
178
- logger.error("Error closing file during checksum")
179
- logger.debug("Error: \(error)")
180
- }
182
+ while autoreleasepool(invoking: {
183
+ let fileData: Data
184
+ do {
185
+ fileData = try fileHandle.read(upToCount: bufferSize) ?? Data()
186
+ } catch {
187
+ logger.error("Error reading file during checksum")
188
+ logger.debug("Error: \(error)")
189
+ return false
181
190
  }
182
191
 
183
- while autoreleasepool(invoking: {
184
- let fileData = fileHandle.readData(ofLength: bufferSize)
185
-
186
- if fileData.count > 0 {
187
- sha256.update(data: fileData)
188
- return true // Continue
189
- } else {
190
- return false // End of file
191
- }
192
- }) {}
192
+ if fileData.count > 0 {
193
+ sha256.update(data: fileData)
194
+ return true // Continue
195
+ } else {
196
+ return false // End of file
197
+ }
198
+ }) {}
193
199
 
194
- return hexString(from: sha256)
195
- } catch {
196
- logger.error("Cannot calculate checksum")
197
- logger.debug("Path: \(filePath.path), Error: \(error)")
198
- return ""
199
- }
200
+ return hexString(from: sha256)
200
201
  }
201
202
 
202
203
  final class RunningChecksum {
@@ -215,8 +216,7 @@ public struct CryptoCipher {
215
216
  }
216
217
 
217
218
  static func hexString(from sha256: SHA256) -> String {
218
- var copy = sha256
219
- return copy.finalize().compactMap { String(format: "%02x", $0) }.joined()
219
+ return sha256.finalize().compactMap { String(format: "%02x", $0) }.joined()
220
220
  }
221
221
 
222
222
  static func shortPathKey(_ fileName: String) -> String {
@@ -151,59 +151,34 @@ public class DelayUpdateUtils {
151
151
  }
152
152
 
153
153
  public func setMultiDelay(delayConditions: String) -> Bool {
154
- do {
155
- UserDefaults.standard.set(delayConditions, forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES)
156
- UserDefaults.standard.synchronize()
157
- logger.info("Delay update saved")
158
- return true
159
- } catch {
160
- logger.error("Failed to delay update, [Error calling 'setMultiDelay()']: \(error)")
161
- return false
162
- }
154
+ UserDefaults.standard.set(delayConditions, forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES)
155
+ UserDefaults.standard.synchronize()
156
+ logger.info("Delay update saved")
157
+ return true
163
158
  }
164
159
 
165
160
  public func setBackgroundTimestamp(_ backgroundTimestamp: Int64) {
166
- do {
167
- UserDefaults.standard.set(backgroundTimestamp, forKey: DelayUpdateUtils.BACKGROUND_TIMESTAMP_KEY)
168
- UserDefaults.standard.synchronize()
169
- logger.info("Background timestamp saved")
170
- } catch {
171
- logger.error("Failed to save background timestamp, [Error calling 'setBackgroundTimestamp()']: \(error)")
172
- }
161
+ UserDefaults.standard.set(backgroundTimestamp, forKey: DelayUpdateUtils.BACKGROUND_TIMESTAMP_KEY)
162
+ UserDefaults.standard.synchronize()
163
+ logger.info("Background timestamp saved")
173
164
  }
174
165
 
175
166
  public func unsetBackgroundTimestamp() {
176
- do {
177
- UserDefaults.standard.removeObject(forKey: DelayUpdateUtils.BACKGROUND_TIMESTAMP_KEY)
178
- UserDefaults.standard.synchronize()
179
- logger.info("Background timestamp removed")
180
- } catch {
181
- // swiftlint:disable:next line_length
182
- logger.error("Failed to remove background timestamp, [Error calling 'unsetBackgroundTimestamp()']: \(error)")
183
- }
167
+ UserDefaults.standard.removeObject(forKey: DelayUpdateUtils.BACKGROUND_TIMESTAMP_KEY)
168
+ UserDefaults.standard.synchronize()
169
+ logger.info("Background timestamp removed")
184
170
  }
185
171
 
186
172
  private func getBackgroundTimestamp() -> Int64 {
187
- do {
188
- let key = DelayUpdateUtils.BACKGROUND_TIMESTAMP_KEY
189
- let timestamp = UserDefaults.standard.object(forKey: key) as? Int64 ?? 0
190
- return timestamp
191
- } catch {
192
- logger.error("Failed to get background timestamp, [Error calling 'getBackgroundTimestamp()']: \(error)")
193
- return 0
194
- }
173
+ let key = DelayUpdateUtils.BACKGROUND_TIMESTAMP_KEY
174
+ return UserDefaults.standard.object(forKey: key) as? Int64 ?? 0
195
175
  }
196
176
 
197
177
  public func cancelDelay(source: String) -> Bool {
198
- do {
199
- UserDefaults.standard.removeObject(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES)
200
- UserDefaults.standard.synchronize()
201
- logger.info("All delays canceled from \(source)")
202
- return true
203
- } catch {
204
- logger.error("Failed to cancel update delay: \(error)")
205
- return false
206
- }
178
+ UserDefaults.standard.removeObject(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES)
179
+ UserDefaults.standard.synchronize()
180
+ logger.info("All delays canceled from \(source)")
181
+ return true
207
182
  }
208
183
 
209
184
  // MARK: - Helper methods
@@ -138,17 +138,17 @@ public class Logger {
138
138
  self.tag = tag
139
139
  if let config = config {
140
140
  // The logger plugin's name is LoggerBridge, we want to look at the config
141
- // named "Logger", so we can't use plugin.getConfigValue().
142
- if let configLevel = getConfigValue("level", from: config) as? String,
141
+ // named "Logger", so we can't use the Capacitor plugin config helper.
142
+ if let configLevel = instanceConfigValue("level", from: config) as? String,
143
143
  let logLevel = LogLevel[configLevel] {
144
144
  level = logLevel
145
145
  }
146
146
 
147
- if let configLabels = getConfigValue("labels", from: config) as? [String: String] {
147
+ if let configLabels = instanceConfigValue("labels", from: config) as? [String: String] {
148
148
  labels = configLabels
149
149
  }
150
150
 
151
- if let configSyslog = getConfigValue("useSyslog", from: config) as? Bool {
151
+ if let configSyslog = instanceConfigValue("useSyslog", from: config) as? Bool {
152
152
  useSyslog = configSyslog
153
153
  }
154
154
  }
@@ -160,7 +160,7 @@ public class Logger {
160
160
  }
161
161
  }
162
162
 
163
- private func getConfigValue(_ configKey: String, from config: InstanceConfiguration) -> Any? {
163
+ private func instanceConfigValue(_ configKey: String, from config: InstanceConfiguration) -> Any? {
164
164
  if let config = config.pluginConfigurations as? JSObject {
165
165
  return config[keyPath: KeyPath(stringLiteral: "Logger.\(configKey)")]
166
166
  }
@@ -1,274 +1,96 @@
1
- import BigInt
2
- import Foundation
3
- import CommonCrypto
4
- import CryptoKit
5
-
6
- ///
7
- /// Constants
8
- ///
9
- private enum RSAConstants {
10
- static let rsaKeySizeInBits: NSNumber = 2048
11
- static let rsaAlgorithm: SecKeyAlgorithm = .rsaEncryptionOAEPSHA256
12
- }
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
+ */
13
6
 
14
- // We do all this stuff because ios is shit and open source libraries allow to do decryption with public key
15
- // So we have to do it manually, while in nodejs or Java it's ok and done at language level.
7
+ import Foundation
8
+ import Security
9
+ import os.log
16
10
 
17
- ///
18
- /// The RSA public key.
19
- ///
11
+ /// Capgo v2 uses Node's privateEncrypt with PKCS#1 v1.5 type-1 padding for
12
+ /// checksums and session keys. Recover the signed payload using Apple's RSA
13
+ /// implementation instead of custom modular exponentiation.
20
14
  public struct RSAPublicKey {
21
- private let manualKey: ManualRSAPublicKey
22
-
23
- fileprivate init(manualKey: ManualRSAPublicKey) {
24
- self.manualKey = manualKey
25
- }
26
-
27
- ///
28
- /// Takes the data and uses the public key to decrypt it.
29
- /// Returns the decrypted data.
30
- ///
31
- public func decrypt(data: Data) -> Data? {
32
- return manualKey.decrypt(data)
33
- }
15
+ private let key: SecKey
16
+ private static let keyLock = NSLock()
17
+ private static let log = OSLog(subsystem: "ee.forgr.capacitor_updater", category: "RSA")
18
+ // One public key only: bounded storage, invalid/rotated keys never fall back
19
+ // to a cached key with different material. SecKey is immutable after import.
20
+ private static var cachedKey: (der: Data, key: SecKey)?
34
21
 
35
- ///
36
- /// Allows you to load an RSA public key (i.e. one downloaded from the net).
37
- ///
38
22
  public static func load(rsaPublicKey: String) -> RSAPublicKey? {
39
- // Clean up the key string
40
- var pubKey: String = rsaPublicKey
41
- pubKey = pubKey.replacingOccurrences(of: "-----BEGIN RSA PUBLIC KEY-----", with: "")
42
- pubKey = pubKey.replacingOccurrences(of: "-----END RSA PUBLIC KEY-----", with: "")
43
- pubKey = pubKey.replacingOccurrences(of: "-----BEGIN PUBLIC KEY-----", with: "")
44
- pubKey = pubKey.replacingOccurrences(of: "-----END PUBLIC KEY-----", with: "")
45
- pubKey = pubKey.replacingOccurrences(of: "\\n+", with: "", options: .regularExpression)
46
- pubKey = pubKey.replacingOccurrences(of: "\n", with: "")
47
- pubKey = pubKey.trimmingCharacters(in: .whitespacesAndNewlines)
48
-
49
- do {
50
- guard let rsaPublicKeyData: Data = Data(base64Encoded: String(pubKey)) else {
51
- throw CustomError.cannotDecode
52
- }
53
-
54
- // Try parsing as PKCS#1
55
- if let manualKey = ManualRSAPublicKey.fromPKCS1(rsaPublicKeyData) {
56
- return RSAPublicKey(manualKey: manualKey)
57
- }
58
-
59
- // Most common public exponent is 65537 (0x010001)
60
- let commonExponent = Data([0x01, 0x00, 0x01]) // 65537 in big-endian
61
-
62
- // Assume the entire key data is the modulus
63
- let lastResortKey = ManualRSAPublicKey(modulus: rsaPublicKeyData, exponent: commonExponent)
64
- return RSAPublicKey(manualKey: lastResortKey)
65
- } catch {
66
- return nil
67
- }
68
- }
69
- }
70
-
71
- // Manual RSA Public Key Implementation using the BigInt library
72
- struct ManualRSAPublicKey {
73
- let modulus: BigInt
74
- let exponent: BigInt
75
-
76
- init(modulus: Data, exponent: Data) {
77
- // Create positive BigInts from Data
78
- let modulusBytes = [UInt8](modulus)
79
- var modulusValue = BigUInt(0)
80
- for byte in modulusBytes {
81
- modulusValue = (modulusValue << 8) | BigUInt(byte)
82
- }
83
- self.modulus = BigInt(modulusValue)
84
- let exponentBytes = [UInt8](exponent)
85
- var exponentValue = BigUInt(0)
86
- for byte in exponentBytes {
87
- exponentValue = (exponentValue << 8) | BigUInt(byte)
88
- }
89
- self.exponent = BigInt(exponentValue)
90
- }
91
-
92
- // Parse PKCS#1 format public key
93
- static func fromPKCS1(_ publicKeyData: Data) -> ManualRSAPublicKey? {
94
- // Parse ASN.1 DER encoded RSA public key
95
- // Format: RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }
96
-
97
- guard publicKeyData.count > 0 else {
98
- return nil
99
- }
100
-
101
- let bytes = [UInt8](publicKeyData)
102
-
103
- // Check for sequence tag (0x30)
104
- guard bytes[0] == 0x30 else {
105
- // Try direct modulus/exponent approach as fallback
106
- if publicKeyData.count >= 3 {
107
- // Assume this is a raw RSA public key with modulus + exponent
108
- // Most common: modulus is 256 bytes (2048 bits), exponent is 3 bytes (0x010001 = 65537)
109
- let modulusSize = publicKeyData.count - 3
110
- if modulusSize > 0 {
111
- let modulusData = publicKeyData.prefix(modulusSize)
112
- let exponentData = publicKeyData.suffix(3)
113
- return ManualRSAPublicKey(modulus: modulusData, exponent: exponentData)
114
- }
115
- }
116
-
117
- return nil
118
- }
119
-
120
- var index = 1
121
-
122
- // Skip length
123
- if bytes[index] & 0x80 != 0 {
124
- let lenBytes = Int(bytes[index] & 0x7F)
125
- if (index + 1 + lenBytes) >= bytes.count {
126
- return nil
127
- }
128
- index += 1 + lenBytes
129
- } else {
130
- index += 1
131
- }
132
-
133
- // Check for INTEGER tag for modulus (0x02)
134
- if index >= bytes.count {
135
- return nil
136
- }
137
-
138
- guard bytes[index] == 0x02 else {
139
- return nil
140
- }
141
- index += 1
142
-
143
- // Get modulus length
144
- if index >= bytes.count {
145
- return nil
146
- }
147
-
148
- var modulusLength = 0
149
- if bytes[index] & 0x80 != 0 {
150
- let lenBytes = Int(bytes[index] & 0x7F)
151
- if (index + 1 + lenBytes) >= bytes.count {
152
- return nil
153
- }
154
- index += 1
155
- for i in 0..<lenBytes {
156
- modulusLength = (modulusLength << 8) | Int(bytes[index + i])
157
- }
158
- index += lenBytes
159
- } else {
160
- modulusLength = Int(bytes[index])
161
- index += 1
162
- }
163
-
164
- // Skip any leading zero in modulus (for unsigned integer)
165
- if index < bytes.count && bytes[index] == 0x00 {
166
- index += 1
167
- modulusLength -= 1
168
- }
169
-
170
- // Extract modulus
171
- if (index + modulusLength) > bytes.count {
172
- return nil
173
- }
174
-
175
- let modulusData = Data(bytes[index..<(index + modulusLength)])
176
- index += modulusLength
177
-
178
- // Check for INTEGER tag for exponent
179
- if index >= bytes.count {
23
+ guard let der = pemToDer(rsaPublicKey) else {
24
+ os_log("RSA key import failed: invalid PEM/base64", log: Self.log, type: .error)
180
25
  return nil
181
26
  }
182
27
 
183
- guard bytes[index] == 0x02 else {
28
+ keyLock.lock()
29
+ defer { keyLock.unlock() }
30
+ if let cached = cachedKey, cached.der == der {
31
+ return RSAPublicKey(key: cached.key)
32
+ }
33
+
34
+ let attributes: [CFString: Any] = [
35
+ kSecAttrKeyType: kSecAttrKeyTypeRSA,
36
+ kSecAttrKeyClass: kSecAttrKeyClassPublic
37
+ ]
38
+ var error: Unmanaged<CFError>?
39
+ guard let key = SecKeyCreateWithData(der as CFData, attributes as CFDictionary, &error) else {
40
+ os_log(
41
+ "RSA key import failed: %{public}@",
42
+ log: Self.log,
43
+ type: .error,
44
+ String(describing: error?.takeRetainedValue())
45
+ )
184
46
  return nil
185
47
  }
186
- index += 1
187
-
188
- // Get exponent length
189
- if index >= bytes.count {
48
+ guard CapgoRawRsa.supportsCapgoRecovery(key: key) else {
49
+ os_log(
50
+ "RSA key import failed: unsupported key (Capgo requires RSA-2048 with raw encryption)",
51
+ log: Self.log,
52
+ type: .error
53
+ )
190
54
  return nil
191
55
  }
56
+ cachedKey = (der, key)
57
+ return RSAPublicKey(key: key)
58
+ }
192
59
 
193
- var exponentLength = 0
194
- if bytes[index] & 0x80 != 0 {
195
- let lenBytes = Int(bytes[index] & 0x7F)
196
- if (index + 1 + lenBytes) >= bytes.count {
197
- return nil
198
- }
199
- index += 1
200
- for i in 0..<lenBytes {
201
- exponentLength = (exponentLength << 8) | Int(bytes[index + i])
202
- }
203
- index += lenBytes
204
- } else {
205
- exponentLength = Int(bytes[index])
206
- index += 1
207
- }
208
-
209
- // Extract exponent
210
- if (index + exponentLength) > bytes.count {
60
+ public func decrypt(data: Data) -> Data? {
61
+ let blockSize = SecKeyGetBlockSize(key)
62
+ guard data.count == blockSize else { return nil }
63
+ // Raw public-key encryption is the same c^e mod n operation as Node's
64
+ // publicDecrypt. Do NOT use encryption PKCS#1 padding here: the recovered
65
+ // block already contains signature (type-1) padding, checked below.
66
+ guard let recovered = CapgoRawRsa.recoverSignatureBlock(key: key, data: data) else {
211
67
  return nil
212
68
  }
213
-
214
- let exponentData = Data(bytes[index..<(index + exponentLength)])
215
- return ManualRSAPublicKey(modulus: modulusData, exponent: exponentData)
69
+ return Self.unpadSignature(recovered, blockSize: blockSize)
216
70
  }
217
71
 
218
- // Decrypt data using raw RSA operation (c^d mod n)
219
- func decrypt(_ encryptedData: Data) -> Data? {
220
- // Create positive BigInt from encrypted data
221
- let encryptedBytes = [UInt8](encryptedData)
222
- var encryptedValue = BigUInt(0)
223
- for byte in encryptedBytes {
224
- encryptedValue = (encryptedValue << 8) | BigUInt(byte)
72
+ static func unpadSignature(_ block: Data, blockSize: Int = 256) -> Data? {
73
+ let bytes = [UInt8](block)
74
+ // RFC 8017: 00 01, at least eight FF bytes, 00, then the payload.
75
+ guard bytes.count == blockSize, bytes[0] == 0, bytes[1] == 1 else { return nil }
76
+ var separator = 2
77
+ while separator < bytes.count && bytes[separator] == 0xff {
78
+ separator += 1
225
79
  }
226
- let encrypted = BigInt(encryptedValue)
227
-
228
- // In Node.js:
229
- // privateEncrypt uses the private key (d) to encrypt
230
- // publicDecrypt uses the public key (e) to decrypt
231
- // The operation we want is: ciphertext^e mod n
232
-
233
- // RSA operation: c^e mod n
234
- let decrypted = encrypted.manualPower(exponent, modulus: modulus)
235
-
236
- // Convert to bytes with proper padding
237
- guard let bigUIntValue = decrypted.magnitude as? BigUInt else {
80
+ guard separator >= 10, separator < bytes.count - 1, bytes[separator] == 0 else {
238
81
  return nil
239
82
  }
83
+ return Data(bytes[(separator + 1)...])
84
+ }
240
85
 
241
- // Convert BigUInt to bytes with padding
242
- var resultBytes = [UInt8]()
243
- var tempValue = bigUIntValue
244
- while tempValue > 0 {
245
- let byte = UInt8(tempValue & 0xFF)
246
- resultBytes.insert(byte, at: 0) // Prepend to get big-endian
247
- tempValue >>= 8
248
- }
249
-
250
- // Ensure we have at least 256 bytes (2048 bits) with leading zeros
251
- let paddedBytes = [UInt8](repeating: 0, count: max(0, 256 - resultBytes.count)) + resultBytes
252
-
253
- // For PKCS1 padding from Node.js privateEncrypt, the format is:
254
- // 0x00 || 0x01 || PS || 0x00 || actual data
255
- // where PS is a string of 0xFF bytes
256
-
257
- // Check for privateEncrypt padding format (0x00 || 0x01 || PS || 0x00)
258
- var startIndex = 0
259
- if paddedBytes.count > 2 && paddedBytes[0] == 0x00 && paddedBytes[1] == 0x01 {
260
- for i in 2..<paddedBytes.count {
261
- if paddedBytes[i] == 0x00 {
262
- startIndex = i + 1
263
- break
264
- }
265
- }
266
- }
267
- if startIndex < paddedBytes.count {
268
- let result = Data(paddedBytes[startIndex...])
269
- return result
270
- } else {
271
- return Data(paddedBytes)
272
- }
86
+ private static func pemToDer(_ pem: String) -> Data? {
87
+ let encoded = pem
88
+ .replacingOccurrences(of: "-----BEGIN RSA PUBLIC KEY-----", with: "")
89
+ .replacingOccurrences(of: "-----END RSA PUBLIC KEY-----", with: "")
90
+ .replacingOccurrences(of: "-----BEGIN PUBLIC KEY-----", with: "")
91
+ .replacingOccurrences(of: "-----END PUBLIC KEY-----", with: "")
92
+ .replacingOccurrences(of: "\\n", with: "")
93
+ .components(separatedBy: .whitespacesAndNewlines).joined()
94
+ return Data(base64Encoded: encoded)
273
95
  }
274
96
  }
@@ -792,9 +792,9 @@ extension UIWindow {
792
792
  message: "Update downloaded! Reload to apply version \(latest.version)?",
793
793
  plugin: plugin,
794
794
  bridge: bridge,
795
- onReload: { [weak plugin] in
795
+ onReload: {
796
796
  _ = updater.set(bundle: bundle)
797
- _ = plugin?._reload()
797
+ _ = plugin._reload()
798
798
  }
799
799
  )
800
800
  }