@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,343 @@
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
+ //
8
+ // DelayUpdateUtils.swift
9
+ // Plugin
10
+ //
11
+ // Created by Auto-generated based on Android implementation
12
+ // Copyright © 2024 Capgo. All rights reserved.
13
+ //
14
+
15
+ import Foundation
16
+
17
+ public class DelayUpdateUtils {
18
+
19
+ // swiftlint:disable identifier_name
20
+ static let DELAY_CONDITION_PREFERENCES = "DELAY_CONDITION_PREFERENCES_CAPGO"
21
+ static let DELAY_CONDITION_MODE_PREFERENCES = "DELAY_CONDITION_MODE_PREFERENCES_CAPGO"
22
+ static let DELAY_CONDITION_MODE_AND = "and"
23
+ static let DELAY_CONDITION_MODE_OR = "or"
24
+ static let BACKGROUND_TIMESTAMP_KEY = "BACKGROUND_TIMESTAMP_KEY_CAPGO"
25
+ // swiftlint:enable identifier_name
26
+ private let logger: Logger
27
+
28
+ private let currentVersionNative: CapgoSemanticVersion
29
+
30
+ public enum CancelDelaySource {
31
+ case killed
32
+ case background
33
+ case foreground
34
+
35
+ var description: String {
36
+ switch self {
37
+ case .killed: return "KILLED"
38
+ case .background: return "BACKGROUND"
39
+ case .foreground: return "FOREGROUND"
40
+ }
41
+ }
42
+ }
43
+
44
+ public init(currentVersionNative: CapgoSemanticVersion, logger: Logger) {
45
+ self.currentVersionNative = currentVersionNative
46
+ self.logger = logger
47
+ }
48
+
49
+ public func checkCancelDelay(source: CancelDelaySource) {
50
+ let delayUpdatePreferences = UserDefaults.standard.string(
51
+ forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
52
+ let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
53
+ if delayConditionList.isEmpty {
54
+ return
55
+ }
56
+
57
+ let useOrMode = isOrConditionMode()
58
+ var delayConditionListToKeep: [DelayCondition] = []
59
+ var index = 0
60
+ var anyConditionMet = false
61
+
62
+ for condition in delayConditionList {
63
+ let result = evaluateCondition(condition, source: source, index: index)
64
+ if result.met {
65
+ anyConditionMet = true
66
+ if !useOrMode, let logMessage = result.logMessage {
67
+ logger.info(logMessage)
68
+ }
69
+ } else {
70
+ if result.keep {
71
+ delayConditionListToKeep.append(condition)
72
+ }
73
+ if let logMessage = result.logMessage, !useOrMode || result.error {
74
+ if result.error {
75
+ logger.error(logMessage)
76
+ } else if !useOrMode {
77
+ logger.info(logMessage)
78
+ }
79
+ }
80
+ }
81
+ index += 1
82
+ }
83
+
84
+ if useOrMode {
85
+ if anyConditionMet {
86
+ logger.info("Delay condition met in OR mode (source: \(source.description)), canceling delay")
87
+ _ = cancelDelay(source: "checkCancelDelay")
88
+ } else if delayConditionListToKeep.isEmpty {
89
+ _ = cancelDelay(source: "checkCancelDelay")
90
+ } else if delayConditionListToKeep.count != delayConditionList.count {
91
+ let json = toJson(object: delayConditionListToKeep.map { $0.toJSON() })
92
+ _ = setMultiDelay(delayConditions: json)
93
+ }
94
+ return
95
+ }
96
+
97
+ if !delayConditionListToKeep.isEmpty {
98
+ let json = toJson(object: delayConditionListToKeep.map { $0.toJSON() })
99
+ _ = setMultiDelay(delayConditions: json)
100
+ } else {
101
+ _ = cancelDelay(source: "checkCancelDelay")
102
+ }
103
+ }
104
+
105
+ private struct ConditionCheckResult {
106
+ let met: Bool
107
+ let keep: Bool
108
+ let error: Bool
109
+ let logMessage: String?
110
+ }
111
+
112
+ private func evaluateCondition(_ condition: DelayCondition, source: CancelDelaySource, index: Int) -> ConditionCheckResult {
113
+ let kind = condition.getKind()
114
+ let value = condition.getValue()
115
+
116
+ switch kind {
117
+ case "background":
118
+ if source == .foreground {
119
+ let backgroundedAt = getBackgroundTimestamp()
120
+ let now = Int64(Date().timeIntervalSince1970 * 1000)
121
+ let delta = max(0, now - backgroundedAt)
122
+ var longValue: Int64 = 0
123
+ if let value = value, !value.isEmpty {
124
+ longValue = Int64(value) ?? 0
125
+ }
126
+
127
+ if delta > longValue {
128
+ return ConditionCheckResult(
129
+ met: true,
130
+ keep: false,
131
+ error: false,
132
+ logMessage: "Background condition (value: \(value ?? "")) deleted at index \(index). Delta: \(delta), longValue: \(longValue)"
133
+ )
134
+ }
135
+ return ConditionCheckResult(
136
+ met: false,
137
+ keep: true,
138
+ error: false,
139
+ logMessage: "Background delay (value: \(value ?? "")) condition kept at index \(index) (source: \(source.description))"
140
+ )
141
+ }
142
+ return ConditionCheckResult(
143
+ met: false,
144
+ keep: true,
145
+ error: false,
146
+ logMessage: "Background delay (value: \(value ?? "")) condition kept at index \(index) (source: \(source.description))"
147
+ )
148
+
149
+ case "kill":
150
+ if source == .killed {
151
+ return ConditionCheckResult(
152
+ met: true,
153
+ keep: false,
154
+ error: false,
155
+ logMessage: "Kill delay (value: \(value ?? "")) removed at index \(index) after app kill"
156
+ )
157
+ }
158
+ return ConditionCheckResult(
159
+ met: false,
160
+ keep: true,
161
+ error: false,
162
+ logMessage: "Kill delay (value: \(value ?? "")) condition kept at index \(index) (source: \(source.description))"
163
+ )
164
+
165
+ case "date":
166
+ if let value = value, !value.isEmpty {
167
+ if let date = parseDateCondition(value) {
168
+ if Date() > date {
169
+ return ConditionCheckResult(
170
+ met: true,
171
+ keep: false,
172
+ error: false,
173
+ logMessage: "Date delay (value: \(value)) condition removed due to expired date at index \(index)"
174
+ )
175
+ }
176
+ return ConditionCheckResult(met: false, keep: true, error: false, logMessage: "Date delay (value: \(value)) kept at index \(index)")
177
+ }
178
+ return ConditionCheckResult(
179
+ met: false,
180
+ keep: false,
181
+ error: true,
182
+ logMessage: "Date delay (value: \(value)) condition removed due to parsing issue at index \(index)"
183
+ )
184
+ }
185
+ return ConditionCheckResult(
186
+ met: false,
187
+ keep: false,
188
+ error: true,
189
+ logMessage: "Date delay (value: \(value ?? "")) condition removed due to empty value at index \(index)"
190
+ )
191
+
192
+ case "nativeVersion":
193
+ if let value = value, !value.isEmpty {
194
+ do {
195
+ let versionLimit = try CapgoSemanticVersion(value)
196
+ if currentVersionNative >= versionLimit {
197
+ return ConditionCheckResult(
198
+ met: true,
199
+ keep: false,
200
+ error: false,
201
+ logMessage: "Native version delay (value: \(value)) condition removed due to above limit at index \(index)"
202
+ )
203
+ }
204
+ return ConditionCheckResult(met: false, keep: true, error: false, logMessage: "Native version delay (value: \(value)) kept at index \(index)")
205
+ } catch {
206
+ return ConditionCheckResult(
207
+ met: false,
208
+ keep: false,
209
+ error: true,
210
+ logMessage: "Native version delay (value: \(value)) condition removed due to parsing issue at index \(index): \(error)"
211
+ )
212
+ }
213
+ }
214
+ return ConditionCheckResult(
215
+ met: false,
216
+ keep: false,
217
+ error: true,
218
+ logMessage: "Native version delay (value: \(value ?? "")) condition removed due to empty value at index \(index)"
219
+ )
220
+
221
+ default:
222
+ return ConditionCheckResult(met: false, keep: false, error: true, logMessage: "Unknown delay condition kind: \(kind) at index \(index)")
223
+ }
224
+ }
225
+
226
+ public func isOrConditionMode() -> Bool {
227
+ return getConditionMode() == DelayUpdateUtils.DELAY_CONDITION_MODE_OR
228
+ }
229
+
230
+ public func getConditionMode() -> String {
231
+ let mode = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_MODE_PREFERENCES)
232
+ ?? DelayUpdateUtils.DELAY_CONDITION_MODE_AND
233
+ return mode == DelayUpdateUtils.DELAY_CONDITION_MODE_OR
234
+ ? DelayUpdateUtils.DELAY_CONDITION_MODE_OR
235
+ : DelayUpdateUtils.DELAY_CONDITION_MODE_AND
236
+ }
237
+
238
+ public func setConditionMode(_ conditionMode: String) -> Bool {
239
+ let normalized = conditionMode == DelayUpdateUtils.DELAY_CONDITION_MODE_OR
240
+ ? DelayUpdateUtils.DELAY_CONDITION_MODE_OR
241
+ : DelayUpdateUtils.DELAY_CONDITION_MODE_AND
242
+ if conditionMode != DelayUpdateUtils.DELAY_CONDITION_MODE_AND
243
+ && conditionMode != DelayUpdateUtils.DELAY_CONDITION_MODE_OR {
244
+ logger.warn("Unknown delay condition mode '\(conditionMode)', defaulting to '\(DelayUpdateUtils.DELAY_CONDITION_MODE_AND)'")
245
+ }
246
+ UserDefaults.standard.set(normalized, forKey: DelayUpdateUtils.DELAY_CONDITION_MODE_PREFERENCES)
247
+ let synchronized = UserDefaults.standard.synchronize()
248
+ if synchronized {
249
+ logger.info("Delay condition mode saved: \(normalized)")
250
+ } else {
251
+ logger.error("Failed to save delay condition mode: synchronize returned false")
252
+ }
253
+ return synchronized
254
+ }
255
+
256
+ public func setMultiDelay(delayConditions: String) -> Bool {
257
+ UserDefaults.standard.set(delayConditions, forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES)
258
+ let synchronized = UserDefaults.standard.synchronize()
259
+ if synchronized {
260
+ logger.info("Delay update saved")
261
+ } else {
262
+ logger.error("Failed to delay update: synchronize returned false")
263
+ }
264
+ return synchronized
265
+ }
266
+
267
+ public func setBackgroundTimestamp(_ backgroundTimestamp: Int64) {
268
+ UserDefaults.standard.set(backgroundTimestamp, forKey: DelayUpdateUtils.BACKGROUND_TIMESTAMP_KEY)
269
+ UserDefaults.standard.synchronize()
270
+ logger.info("Background timestamp saved")
271
+ }
272
+
273
+ public func unsetBackgroundTimestamp() {
274
+ UserDefaults.standard.removeObject(forKey: DelayUpdateUtils.BACKGROUND_TIMESTAMP_KEY)
275
+ UserDefaults.standard.synchronize()
276
+ logger.info("Background timestamp removed")
277
+ }
278
+
279
+ private func getBackgroundTimestamp() -> Int64 {
280
+ let key = DelayUpdateUtils.BACKGROUND_TIMESTAMP_KEY
281
+ return UserDefaults.standard.object(forKey: key) as? Int64 ?? 0
282
+ }
283
+
284
+ public func cancelDelay(source: String) -> Bool {
285
+ UserDefaults.standard.removeObject(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES)
286
+ UserDefaults.standard.removeObject(forKey: DelayUpdateUtils.DELAY_CONDITION_MODE_PREFERENCES)
287
+ UserDefaults.standard.synchronize()
288
+ logger.info("All delays canceled from \(source)")
289
+ return true
290
+ }
291
+
292
+ // MARK: - Helper methods
293
+
294
+ private func parseDateCondition(_ value: String) -> Date? {
295
+ let withFractionalSeconds = ISO8601DateFormatter()
296
+ withFractionalSeconds.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
297
+ if let date = withFractionalSeconds.date(from: value) {
298
+ return date
299
+ }
300
+
301
+ let withoutFractionalSeconds = ISO8601DateFormatter()
302
+ withoutFractionalSeconds.formatOptions = [.withInternetDateTime]
303
+ if let date = withoutFractionalSeconds.date(from: value) {
304
+ return date
305
+ }
306
+
307
+ // Legacy fallback for strings without timezone.
308
+ for format in ["yyyy-MM-dd'T'HH:mm:ss.SSS", "yyyy-MM-dd'T'HH:mm:ss"] {
309
+ let formatter = DateFormatter()
310
+ formatter.locale = Locale(identifier: "en_US_POSIX")
311
+ formatter.calendar = Calendar(identifier: .gregorian)
312
+ formatter.timeZone = .current
313
+ formatter.isLenient = false
314
+ formatter.dateFormat = format
315
+ if let date = formatter.date(from: value) {
316
+ return date
317
+ }
318
+ }
319
+
320
+ return nil
321
+ }
322
+
323
+ private func toJson(object: Any) -> String {
324
+ guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
325
+ return ""
326
+ }
327
+ return String(data: data, encoding: String.Encoding.utf8) ?? ""
328
+ }
329
+
330
+ /// Parses stored delay conditions. Malformed JSON and entries without a string `kind` are dropped.
331
+ static func parseDelayConditions(json: String) -> [DelayCondition] {
332
+ guard let jsonData = json.data(using: .utf8),
333
+ let entries = (try? JSONSerialization.jsonObject(with: jsonData)) as? [Any] else {
334
+ return []
335
+ }
336
+ return entries.compactMap { entry in
337
+ guard let object = entry as? [String: Any], let kind = object["kind"] as? String else {
338
+ return nil
339
+ }
340
+ return DelayCondition(kind: kind, value: object["value"] as? String)
341
+ }
342
+ }
343
+ }
@@ -0,0 +1,120 @@
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
+
10
+ /**
11
+ * Helper class to manage device ID persistence across app installations.
12
+ * Uses iOS Keychain to persist the device ID.
13
+ */
14
+ class DeviceIdHelper {
15
+ private static let keychainService = "app.capgo.updater"
16
+ private static let keychainAccount = "deviceId"
17
+ private static let legacyDefaultsKey = "appUUID"
18
+
19
+ /**
20
+ * Gets or creates a device ID that persists across reinstalls.
21
+ *
22
+ * This method:
23
+ * 1. First checks for an existing ID in Keychain (persists across reinstalls)
24
+ * 2. Falls back to UserDefaults (for migration from older versions)
25
+ * 3. Generates a new UUID if neither exists
26
+ * 4. Stores the ID in Keychain for future use
27
+ *
28
+ * @return Device ID as a lowercase UUID string
29
+ */
30
+ static func getOrCreateDeviceId() -> String {
31
+ // Try to get device ID from Keychain first
32
+ if let keychainDeviceId = getDeviceIdFromKeychain() {
33
+ return keychainDeviceId.lowercased()
34
+ }
35
+
36
+ // Migration: Check UserDefaults for existing device ID
37
+ var deviceId = UserDefaults.standard.string(forKey: legacyDefaultsKey)
38
+
39
+ if deviceId == nil || deviceId!.isEmpty {
40
+ // Generate new device ID if none exists
41
+ deviceId = UUID().uuidString
42
+ }
43
+
44
+ // Ensure lowercase for consistency
45
+ deviceId = deviceId!.lowercased()
46
+
47
+ // Save to Keychain for persistence across reinstalls
48
+ saveDeviceIdToKeychain(deviceId: deviceId!)
49
+
50
+ return deviceId!
51
+ }
52
+
53
+ /**
54
+ * Retrieves the device ID from iOS Keychain.
55
+ *
56
+ * @return Device ID string or nil if not found
57
+ */
58
+ private static func getDeviceIdFromKeychain() -> String? {
59
+ let query: [String: Any] = [
60
+ kSecClass as String: kSecClassGenericPassword,
61
+ kSecAttrService as String: keychainService,
62
+ kSecAttrAccount as String: keychainAccount,
63
+ kSecReturnData as String: true,
64
+ kSecMatchLimit as String: kSecMatchLimitOne
65
+ ]
66
+
67
+ var result: AnyObject?
68
+ let status = SecItemCopyMatching(query as CFDictionary, &result)
69
+
70
+ guard status == errSecSuccess,
71
+ let data = result as? Data,
72
+ let deviceId = String(data: data, encoding: .utf8) else {
73
+ return nil
74
+ }
75
+
76
+ return deviceId
77
+ }
78
+
79
+ /**
80
+ * Saves the device ID to iOS Keychain with appropriate accessibility settings.
81
+ *
82
+ * Uses kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly:
83
+ * - Data persists across reinstalls
84
+ * - Data is NOT synced to iCloud
85
+ * - Data is accessible after first device unlock
86
+ * - Data stays on this device only (privacy-friendly)
87
+ *
88
+ * @param deviceId The device ID to save
89
+ */
90
+ private static func saveDeviceIdToKeychain(deviceId: String) {
91
+ guard let data = deviceId.data(using: .utf8) else {
92
+ return
93
+ }
94
+
95
+ // Delete any existing entry first
96
+ let deleteQuery: [String: Any] = [
97
+ kSecClass as String: kSecClassGenericPassword,
98
+ kSecAttrService as String: keychainService,
99
+ kSecAttrAccount as String: keychainAccount
100
+ ]
101
+ SecItemDelete(deleteQuery as CFDictionary)
102
+
103
+ // Add new entry with appropriate accessibility
104
+ let addQuery: [String: Any] = [
105
+ kSecClass as String: kSecClassGenericPassword,
106
+ kSecAttrService as String: keychainService,
107
+ kSecAttrAccount as String: keychainAccount,
108
+ kSecValueData as String: data,
109
+ // This ensures data persists across reinstalls but stays on device (not synced)
110
+ kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
111
+ ]
112
+
113
+ let status = SecItemAdd(addQuery as CFDictionary, nil)
114
+
115
+ if status != errSecSuccess {
116
+ // Log error but don't crash - we'll fall back to UserDefaults on next launch
117
+ print("Failed to save device ID to Keychain: \(status)")
118
+ }
119
+ }
120
+ }