@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,380 @@
1
+ import Capacitor
2
+ import Foundation
3
+ import os.log
4
+ import WebKit
5
+
6
+ public class Logger {
7
+ static let maxWebViewLogPayloadChars = 4096
8
+
9
+ public enum LogLevel: Int {
10
+ case silent = 0
11
+ case error
12
+ case warn
13
+ case info
14
+ case debug
15
+
16
+ public static subscript(_ str: String) -> LogLevel? {
17
+ var index = 0
18
+
19
+ while let item = LogLevel(rawValue: index) {
20
+ if str == "\(item)" {
21
+ return item
22
+ }
23
+
24
+ index += 1
25
+ }
26
+
27
+ return nil
28
+ }
29
+
30
+ public func asOSLogType() -> OSLogType {
31
+ switch self {
32
+ case .debug:
33
+ return OSLogType.debug
34
+ case .info:
35
+ return OSLogType.info
36
+ case .warn:
37
+ return OSLogType.default
38
+ case .error:
39
+ return OSLogType.error
40
+ case .silent:
41
+ return OSLogType.info // Compiler wants this, it will never be used
42
+ }
43
+ }
44
+ public func asString() -> String {
45
+ switch self {
46
+ case .debug:
47
+ return "debug"
48
+ case .info:
49
+ return "info"
50
+ case .warn:
51
+ return "warn"
52
+ case .error:
53
+ return "error"
54
+ case .silent:
55
+ return "info"
56
+ }
57
+ }
58
+ }
59
+
60
+ public struct Options {
61
+ public var level: LogLevel
62
+ public var labels: [String: String]
63
+ public var useSyslog: Bool
64
+
65
+ public init(level: LogLevel = LogLevel.info, labels: [String: String] = [:], useSyslog: Bool = false) {
66
+ self.level = level
67
+ self.labels = labels
68
+ self.useSyslog = useSyslog
69
+ }
70
+ }
71
+
72
+ private var _labels: [LogLevel: String] = [
73
+ LogLevel.silent: "",
74
+ LogLevel.error: "🔴",
75
+ LogLevel.warn: "🟠",
76
+ LogLevel.info: "🟢",
77
+ LogLevel.debug: "🔎"
78
+ ]
79
+
80
+ public var labels: [String: String] {
81
+ get {
82
+ var result: [String: String] = [:]
83
+
84
+ for (level, label) in _labels {
85
+ result[String(describing: level)] = label
86
+ }
87
+
88
+ return result
89
+ }
90
+
91
+ set {
92
+ for (level, label) in newValue {
93
+ if let logLevel = LogLevel[level] {
94
+ _labels[logLevel] = label
95
+ }
96
+ }
97
+ }
98
+ }
99
+
100
+ public var level = LogLevel.info
101
+
102
+ public var levelName: String {
103
+ get {
104
+ String(describing: level)
105
+ }
106
+ set {
107
+ if let newLevel = LogLevel[newValue] {
108
+ level = newLevel
109
+ }
110
+ }
111
+ }
112
+
113
+ private var _tag = ""
114
+
115
+ public var tag: String {
116
+ get {
117
+ _tag
118
+ }
119
+ set {
120
+ if !newValue.isEmpty {
121
+ _tag = newValue
122
+ }
123
+ }
124
+ }
125
+
126
+ private let kDefaultTimerLabel = "default"
127
+ private var timers: [String: Date] = [:]
128
+ public var useSyslog = false
129
+ public var webView: WKWebView?
130
+
131
+ public func setWebView(webView: WKWebView) {
132
+ self.webView = webView
133
+ }
134
+
135
+ public init(
136
+ withTag tag: String,
137
+ config: InstanceConfiguration? = nil,
138
+ options: Options? = nil
139
+ ) {
140
+ self.tag = tag
141
+ if let config = config {
142
+ // The logger plugin's name is LoggerBridge, we want to look at the config
143
+ // named "Logger", so we can't use the Capacitor plugin config helper.
144
+ if let configLevel = instanceConfigValue("level", from: config) as? String,
145
+ let logLevel = LogLevel[configLevel] {
146
+ level = logLevel
147
+ }
148
+
149
+ if let configLabels = instanceConfigValue("labels", from: config) as? [String: String] {
150
+ labels = configLabels
151
+ }
152
+
153
+ if let configSyslog = instanceConfigValue("useSyslog", from: config) as? Bool {
154
+ useSyslog = configSyslog
155
+ }
156
+ }
157
+
158
+ if let options = options {
159
+ self.level = options.level
160
+ self.labels = options.labels
161
+ self.useSyslog = options.useSyslog
162
+ }
163
+ }
164
+
165
+ private func instanceConfigValue(_ configKey: String, from config: InstanceConfiguration) -> Any? {
166
+ if let config = config.pluginConfigurations as? JSObject {
167
+ return config[keyPath: KeyPath(stringLiteral: "Logger.\(configKey)")]
168
+ }
169
+
170
+ return nil
171
+ }
172
+
173
+ public func error(_ message: String) {
174
+ log(atLevel: LogLevel.error, message: message)
175
+ }
176
+
177
+ public func warn(_ message: String) {
178
+ log(atLevel: LogLevel.warn, message: message)
179
+ }
180
+
181
+ public func info(_ message: String) {
182
+ log(atLevel: LogLevel.info, message: message)
183
+ }
184
+
185
+ public func log(_ message: String) {
186
+ log(atLevel: LogLevel.info, message: message)
187
+ }
188
+
189
+ public func debug(_ message: String) {
190
+ log(atLevel: LogLevel.debug, message: message)
191
+ }
192
+
193
+ public func dir(_ value: Any?) {
194
+ // Check the log level here to avoid conversion to string
195
+ if canLog(atLevel: LogLevel.info) {
196
+ log(atLevel: LogLevel.info, message: String(describing: value))
197
+ }
198
+ }
199
+
200
+ public func log(atLevel level: LogLevel, message: String) {
201
+ // This will never fail, but we have to keep swift happy
202
+ if let label = _labels[level] {
203
+ log(atLevel: level, label: label, tag: tag, message: message)
204
+ if let webView = self.webView, let script = buildWebViewConsoleScript(level: level, label: label, tag: tag, message: message) {
205
+ DispatchQueue.main.async {
206
+ webView.evaluateJavaScript(script, completionHandler: nil)
207
+ }
208
+ }
209
+ }
210
+ }
211
+
212
+ func consoleMethodName(for level: LogLevel) -> String? {
213
+ switch level {
214
+ case .error:
215
+ return "error"
216
+ case .warn:
217
+ return "warn"
218
+ case .info:
219
+ return "info"
220
+ case .debug:
221
+ return "debug"
222
+ case .silent:
223
+ return nil
224
+ }
225
+ }
226
+
227
+ private func utf8SequenceLength(_ lead: UInt8) -> Int {
228
+ if (lead & 0x80) == 0 {
229
+ return 1
230
+ }
231
+ if (lead & 0xE0) == 0xC0 {
232
+ return 2
233
+ }
234
+ if (lead & 0xF0) == 0xE0 {
235
+ return 3
236
+ }
237
+ if (lead & 0xF8) == 0xF0 {
238
+ return 4
239
+ }
240
+ return 0
241
+ }
242
+
243
+ func capWebViewLogPayload(_ payload: String) -> String {
244
+ let suffix = "..."
245
+ let maxPayloadBytes = Logger.maxWebViewLogPayloadChars
246
+ let payloadBytes = Array(payload.utf8.prefix(maxPayloadBytes + 1))
247
+ if payloadBytes.count <= maxPayloadBytes {
248
+ return payload
249
+ }
250
+
251
+ var end = maxPayloadBytes
252
+ while end > 0 && (payloadBytes[end - 1] & 0xC0) == 0x80 {
253
+ end -= 1
254
+ }
255
+ while end > 0 {
256
+ let leadIndex = end - 1
257
+ let lead = payloadBytes[leadIndex]
258
+ let seqLength = utf8SequenceLength(lead)
259
+ if seqLength == 0 {
260
+ end -= 1
261
+ continue
262
+ }
263
+ if leadIndex + seqLength <= maxPayloadBytes {
264
+ end = leadIndex + seqLength
265
+ break
266
+ }
267
+ end -= 1
268
+ }
269
+
270
+ return String(decoding: payloadBytes[0..<end], as: UTF8.self) + suffix
271
+ }
272
+
273
+ func buildWebViewConsoleScript(level: LogLevel, label: String, tag: String, message: String) -> String? {
274
+ guard let consoleMethod = consoleMethodName(for: level) else {
275
+ return nil
276
+ }
277
+
278
+ let payload = capWebViewLogPayload("\(label) \(tag) : \(message)")
279
+ return "console.\(consoleMethod)(\(toJSStringLiteral(payload)))"
280
+ }
281
+
282
+ func toJSStringLiteral(_ value: String) -> String {
283
+ // Prefer JSON encoding to produce a valid JS string literal
284
+ if let data = try? JSONEncoder().encode(value),
285
+ let encoded = String(data: data, encoding: .utf8) {
286
+ return encoded
287
+ }
288
+
289
+ // Fallback manual escaping (unlikely to be used)
290
+ var escaped = value
291
+ escaped = escaped.replacingOccurrences(of: "\\", with: "\\\\")
292
+ escaped = escaped.replacingOccurrences(of: "\"", with: "\\\"")
293
+ escaped = escaped.replacingOccurrences(of: "'", with: "\\'")
294
+ escaped = escaped.replacingOccurrences(of: "\n", with: "\\n")
295
+ escaped = escaped.replacingOccurrences(of: "\r", with: "\\r")
296
+ escaped = escaped.replacingOccurrences(of: "\u{2028}", with: "\\u2028")
297
+ escaped = escaped.replacingOccurrences(of: "\u{2029}", with: "\\u2029")
298
+ return "\"\(escaped)\""
299
+ }
300
+
301
+ public func log(atLevel level: LogLevel, label: String?, tag: String, message: String) {
302
+ // This will never fail, but we have to keep swift happy
303
+ if let label = label ?? _labels[level] {
304
+ print(atLevel: level, label: label, tag: tag, message: message)
305
+ // eval
306
+ }
307
+ }
308
+
309
+ private func canLog(atLevel level: LogLevel) -> Bool {
310
+ self.level.rawValue >= level.rawValue
311
+ }
312
+
313
+ private func print(atLevel level: LogLevel, label: String, tag: String, message: String) {
314
+ guard canLog(atLevel: level) else {
315
+ return
316
+ }
317
+
318
+ var msg = message
319
+
320
+ if !label.isEmpty {
321
+ // If the label is ASCII, put it after the tag, otherwise before.
322
+ if label[label.startIndex].isASCII {
323
+ msg = "[\(tag)] \(label): \(message)"
324
+ } else {
325
+ msg = "\(label) [\(tag)]: \(message)"
326
+ }
327
+ } else {
328
+ msg = "[\(tag)]: \(message)"
329
+ }
330
+
331
+ if useSyslog {
332
+ os_log("%{public}@", type: level.asOSLogType(), msg)
333
+ } else {
334
+ Swift.print(msg)
335
+ }
336
+ }
337
+
338
+ public func time(_ label: String?) {
339
+ timers[label ?? ""] = Date()
340
+ }
341
+
342
+ public func timeLog(_ label: String?) {
343
+ if let timer = timers[label ?? ""] {
344
+ info(formatTimeInterval(timer.timeIntervalSinceNow))
345
+ } else {
346
+ warn("timer \(label ?? kDefaultTimerLabel) does not exist")
347
+ }
348
+ }
349
+
350
+ public func timeEnd(_ label: String?) {
351
+ timeLog(label)
352
+ timers.removeValue(forKey: label ?? kDefaultTimerLabel)
353
+ }
354
+
355
+ private func formatTimeInterval(_ interval: TimeInterval) -> String {
356
+ let int = Int(interval)
357
+ let millis = Int(((1 + interval.remainder(dividingBy: 1)) * 1000).rounded())
358
+ let seconds = int % 60
359
+ let minutes = (int / 60) % 60
360
+ let hours = (int / 3600)
361
+
362
+ if seconds < 1 {
363
+ return "\(millis)ms"
364
+ }
365
+
366
+ if minutes < 1 {
367
+ return "\(seconds).\(String(format: "%0.3d", millis))s"
368
+ }
369
+
370
+ if hours < 1 {
371
+ return "\(minutes):\(String(format: "%0.2d", seconds)).\(String(format: "%0.3d", millis)) (min:sec.ms)"
372
+ }
373
+
374
+ return "\(hours):\(String(format: "%0.2d", minutes)):\(String(format: "%0.2d", seconds)) (hr:min:sec)"
375
+ }
376
+
377
+ public func trace() {
378
+ info(String(format: "%@", Thread.callStackSymbols))
379
+ }
380
+ }
@@ -0,0 +1,183 @@
1
+ import Foundation
2
+ import UIKit
3
+
4
+ final class NativeUpdatePromptCoordinator {
5
+ static let lastNativeVersionDefaultsKey = "CapacitorUpdater.nativeUpdatePromptLastNativeVersion"
6
+ static let lastShownMsDefaultsKey = "CapacitorUpdater.nativeUpdatePromptLastShownMs"
7
+
8
+ private static var sessionShownNativeVersions = Set<String>()
9
+
10
+ static func resetSessionStateForTesting() {
11
+ sessionShownNativeVersions.removeAll()
12
+ }
13
+
14
+ private let enabled: Bool
15
+ private let onStoreCheck: Bool
16
+ private let title: String?
17
+ private let message: String?
18
+ private let updateButton: String?
19
+ private let laterButton: String?
20
+ private let countryFilter: String?
21
+ private let cooldownMs: TimeInterval
22
+ private weak var plugin: CapacitorUpdaterPlugin?
23
+
24
+ convenience init(plugin: CapacitorUpdaterPlugin) {
25
+ let config = plugin.getConfig()
26
+ self.init(
27
+ plugin: plugin,
28
+ enabled: config.getBoolean("nativeUpdatePrompt", false),
29
+ onStoreCheck: config.getBoolean("nativeUpdatePromptOnStoreCheck", false),
30
+ title: config.getString("nativeUpdatePromptTitle"),
31
+ message: config.getString("nativeUpdatePromptMessage"),
32
+ updateButton: config.getString("nativeUpdatePromptUpdateButton"),
33
+ laterButton: config.getString("nativeUpdatePromptLaterButton"),
34
+ countryFilter: config.getString("nativeUpdatePromptCountry"),
35
+ cooldownHours: config.getInt("nativeUpdatePromptCooldownHours", 24)
36
+ )
37
+ }
38
+
39
+ init(
40
+ plugin: CapacitorUpdaterPlugin?,
41
+ enabled: Bool = false,
42
+ onStoreCheck: Bool = false,
43
+ title: String? = nil,
44
+ message: String? = nil,
45
+ updateButton: String? = nil,
46
+ laterButton: String? = nil,
47
+ countryFilter: String? = nil,
48
+ cooldownHours: Int = 24
49
+ ) {
50
+ self.plugin = plugin
51
+ self.enabled = enabled
52
+ self.onStoreCheck = onStoreCheck
53
+ self.title = title
54
+ self.message = message
55
+ self.updateButton = updateButton
56
+ self.laterButton = laterButton
57
+ self.countryFilter = countryFilter
58
+ let normalizedCooldownHours = max(1, cooldownHours)
59
+ self.cooldownMs = TimeInterval(normalizedCooldownHours) * 60 * 60
60
+ }
61
+
62
+ var isOnStoreCheckEnabled: Bool {
63
+ enabled && onStoreCheck
64
+ }
65
+
66
+ static func isNativeStoreUpdateBlock(response: AppVersion) -> Bool {
67
+ if response.breaking == true {
68
+ return true
69
+ }
70
+ if response.message == "store_update_required" {
71
+ return true
72
+ }
73
+ let error = response.error ?? ""
74
+ return error.hasPrefix("disable_auto_update")
75
+ }
76
+
77
+ func maybeShowForUpdateBlock(response: AppVersion) {
78
+ guard enabled, Self.isNativeStoreUpdateBlock(response: response) else {
79
+ return
80
+ }
81
+ scheduleShow()
82
+ }
83
+
84
+ func maybeShowForStoreUpdateAvailable() {
85
+ guard isOnStoreCheckEnabled else {
86
+ return
87
+ }
88
+ scheduleShow()
89
+ }
90
+
91
+ private func scheduleShow() {
92
+ guard matchesCountryFilter() else {
93
+ return
94
+ }
95
+ guard let plugin = plugin else {
96
+ return
97
+ }
98
+ let nativeVersion = plugin.currentBuildVersionForNativeUpdatePrompt()
99
+ guard !nativeVersion.isEmpty else {
100
+ return
101
+ }
102
+ guard shouldShowForNativeVersion(nativeVersion) else {
103
+ return
104
+ }
105
+
106
+ DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(600)) {
107
+ self.showDialog(nativeVersion: nativeVersion)
108
+ }
109
+ }
110
+
111
+ func shouldShowForNativeVersion(_ nativeVersion: String) -> Bool {
112
+ if Self.sessionShownNativeVersions.contains(nativeVersion) {
113
+ return false
114
+ }
115
+ let lastVersion = UserDefaults.standard.string(forKey: Self.lastNativeVersionDefaultsKey) ?? ""
116
+ let lastShown = UserDefaults.standard.double(forKey: Self.lastShownMsDefaultsKey)
117
+ if nativeVersion == lastVersion, lastShown > 0 {
118
+ let elapsed = Date().timeIntervalSince1970 - lastShown
119
+ if elapsed < cooldownMs {
120
+ return false
121
+ }
122
+ }
123
+ return true
124
+ }
125
+
126
+ func matchesCountryFilter() -> Bool {
127
+ guard let filter = countryFilter?.trimmingCharacters(in: .whitespacesAndNewlines), !filter.isEmpty else {
128
+ return true
129
+ }
130
+ let deviceCountry = Self.currentDeviceRegionCode()
131
+ if deviceCountry.isEmpty {
132
+ return false
133
+ }
134
+ let normalizedDevice = deviceCountry.uppercased()
135
+ return filter
136
+ .split(separator: ",")
137
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() }
138
+ .contains(normalizedDevice)
139
+ }
140
+
141
+ private func showDialog(nativeVersion: String) {
142
+ guard let plugin = plugin else {
143
+ return
144
+ }
145
+ if let topVC = UIApplication.topViewController(plugin.bridge?.viewController),
146
+ topVC.isKind(of: UIAlertController.self) {
147
+ return
148
+ }
149
+
150
+ let dialogTitle = (title?.isEmpty == false ? title : nil) ?? "Update available"
151
+ let dialogMessage = (message?.isEmpty == false ? message : nil)
152
+ ?? "A new version of this app is available in the store. Update now to continue receiving live updates."
153
+ let positive = (updateButton?.isEmpty == false ? updateButton : nil) ?? "Update"
154
+ let negative = (laterButton?.isEmpty == false ? laterButton : nil) ?? "Not now"
155
+
156
+ let alert = UIAlertController(title: dialogTitle, message: dialogMessage, preferredStyle: .alert)
157
+ alert.addAction(UIAlertAction(title: negative, style: .cancel) { _ in
158
+ self.recordShown(nativeVersion: nativeVersion)
159
+ })
160
+ alert.addAction(UIAlertAction(title: positive, style: .default) { _ in
161
+ self.recordShown(nativeVersion: nativeVersion)
162
+ plugin.openAppStoreFromNativeUpdatePrompt()
163
+ })
164
+
165
+ if let topVC = UIApplication.topViewController(plugin.bridge?.viewController) {
166
+ topVC.present(alert, animated: true)
167
+ }
168
+ }
169
+
170
+ func recordShown(nativeVersion: String) {
171
+ Self.sessionShownNativeVersions.insert(nativeVersion)
172
+ UserDefaults.standard.set(nativeVersion, forKey: Self.lastNativeVersionDefaultsKey)
173
+ UserDefaults.standard.set(Date().timeIntervalSince1970, forKey: Self.lastShownMsDefaultsKey)
174
+ UserDefaults.standard.synchronize()
175
+ }
176
+
177
+ private static func currentDeviceRegionCode() -> String {
178
+ if #available(iOS 16, *) {
179
+ return Locale.current.region?.identifier ?? ""
180
+ }
181
+ return Locale.current.regionCode ?? ""
182
+ }
183
+ }
@@ -0,0 +1,96 @@
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 Security
9
+ import os.log
10
+
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.
14
+ public struct RSAPublicKey {
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)?
21
+
22
+ public static func load(rsaPublicKey: String) -> RSAPublicKey? {
23
+ guard let der = pemToDer(rsaPublicKey) else {
24
+ os_log("RSA key import failed: invalid PEM/base64", log: Self.log, type: .error)
25
+ return nil
26
+ }
27
+
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
+ )
46
+ return nil
47
+ }
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
+ )
54
+ return nil
55
+ }
56
+ cachedKey = (der, key)
57
+ return RSAPublicKey(key: key)
58
+ }
59
+
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 {
67
+ return nil
68
+ }
69
+ return Self.unpadSignature(recovered, blockSize: blockSize)
70
+ }
71
+
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
79
+ }
80
+ guard separator >= 10, separator < bytes.count - 1, bytes[separator] == 0 else {
81
+ return nil
82
+ }
83
+ return Data(bytes[(separator + 1)...])
84
+ }
85
+
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)
95
+ }
96
+ }