native-update-capacitor 0.0.0-stage → 4.4.0

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 (140) hide show
  1. package/AI-INTEGRATION-GUIDE.md +578 -0
  2. package/LICENSE +25 -0
  3. package/NativeUpdate.podspec +19 -0
  4. package/README.md +574 -2
  5. package/android/build.gradle +125 -0
  6. package/android/consumer-rules.pro +9 -0
  7. package/android/gradle/wrapper/gradle-wrapper.properties +8 -0
  8. package/android/gradle.properties +17 -0
  9. package/android/manifest-additions.xml +28 -0
  10. package/android/proguard-rules.pro +26 -0
  11. package/android/settings.gradle +2 -0
  12. package/android/src/main/AndroidManifest.xml +13 -0
  13. package/android/src/main/java/com/aoneahsan/nativeupdate/AppReviewPlugin.kt +159 -0
  14. package/android/src/main/java/com/aoneahsan/nativeupdate/AppUpdatePlugin.kt +314 -0
  15. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundNotificationManager.kt +406 -0
  16. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateManager.kt +48 -0
  17. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdatePlugin.kt +343 -0
  18. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateWorker.kt +236 -0
  19. package/android/src/main/java/com/aoneahsan/nativeupdate/JsonOptional.kt +26 -0
  20. package/android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt +1249 -0
  21. package/android/src/main/java/com/aoneahsan/nativeupdate/NativeUpdatePlugin.kt +404 -0
  22. package/android/src/main/java/com/aoneahsan/nativeupdate/NotificationActionReceiver.kt +107 -0
  23. package/android/src/main/java/com/aoneahsan/nativeupdate/SecurityManager.kt +240 -0
  24. package/android/variables.gradle +5 -0
  25. package/cli/commands/backend-create.js +623 -0
  26. package/cli/commands/bundle-create.js +145 -0
  27. package/cli/commands/bundle-sign.js +64 -0
  28. package/cli/commands/bundle-verify.js +58 -0
  29. package/cli/commands/flutter-patch.js +107 -0
  30. package/cli/commands/init.js +146 -0
  31. package/cli/commands/keys-generate.js +58 -0
  32. package/cli/commands/monitor.js +89 -0
  33. package/cli/commands/remote-shared.js +264 -0
  34. package/cli/commands/remote.js +634 -0
  35. package/cli/commands/server-start.js +96 -0
  36. package/cli/index.js +625 -0
  37. package/cli/package.json +21 -0
  38. package/dist/esm/app-review/app-review-manager.d.ts +24 -0
  39. package/dist/esm/app-review/app-review-manager.js +194 -0
  40. package/dist/esm/app-review/index.d.ts +5 -0
  41. package/dist/esm/app-review/index.js +5 -0
  42. package/dist/esm/app-review/platform-review-handler.d.ts +20 -0
  43. package/dist/esm/app-review/platform-review-handler.js +137 -0
  44. package/dist/esm/app-review/review-conditions-checker.d.ts +22 -0
  45. package/dist/esm/app-review/review-conditions-checker.js +154 -0
  46. package/dist/esm/app-review/review-rate-limiter.d.ts +23 -0
  47. package/dist/esm/app-review/review-rate-limiter.js +163 -0
  48. package/dist/esm/app-review/types.d.ts +41 -0
  49. package/dist/esm/app-review/types.js +1 -0
  50. package/dist/esm/app-update/app-update-checker.d.ts +58 -0
  51. package/dist/esm/app-update/app-update-checker.js +227 -0
  52. package/dist/esm/app-update/app-update-installer.d.ts +20 -0
  53. package/dist/esm/app-update/app-update-installer.js +134 -0
  54. package/dist/esm/app-update/app-update-manager.d.ts +28 -0
  55. package/dist/esm/app-update/app-update-manager.js +198 -0
  56. package/dist/esm/app-update/app-update-notifier.d.ts +14 -0
  57. package/dist/esm/app-update/app-update-notifier.js +99 -0
  58. package/dist/esm/app-update/index.d.ts +6 -0
  59. package/dist/esm/app-update/index.js +6 -0
  60. package/dist/esm/app-update/platform-app-update.d.ts +19 -0
  61. package/dist/esm/app-update/platform-app-update.js +138 -0
  62. package/dist/esm/app-update/types.d.ts +58 -0
  63. package/dist/esm/app-update/types.js +11 -0
  64. package/dist/esm/background-update/background-scheduler.d.ts +63 -0
  65. package/dist/esm/background-update/background-scheduler.js +332 -0
  66. package/dist/esm/background-update/index.d.ts +3 -0
  67. package/dist/esm/background-update/index.js +2 -0
  68. package/dist/esm/background-update/notification-manager.d.ts +29 -0
  69. package/dist/esm/background-update/notification-manager.js +88 -0
  70. package/dist/esm/config/support.d.ts +9 -0
  71. package/dist/esm/config/support.js +9 -0
  72. package/dist/esm/core/analytics.d.ts +83 -0
  73. package/dist/esm/core/analytics.js +151 -0
  74. package/dist/esm/core/cache-manager.d.ts +72 -0
  75. package/dist/esm/core/cache-manager.js +274 -0
  76. package/dist/esm/core/config.d.ts +69 -0
  77. package/dist/esm/core/config.js +107 -0
  78. package/dist/esm/core/errors.d.ts +56 -0
  79. package/dist/esm/core/errors.js +85 -0
  80. package/dist/esm/core/event-emitter.d.ts +30 -0
  81. package/dist/esm/core/event-emitter.js +80 -0
  82. package/dist/esm/core/logger.d.ts +21 -0
  83. package/dist/esm/core/logger.js +108 -0
  84. package/dist/esm/core/performance.d.ts +53 -0
  85. package/dist/esm/core/performance.js +153 -0
  86. package/dist/esm/core/plugin-manager.d.ts +88 -0
  87. package/dist/esm/core/plugin-manager.js +224 -0
  88. package/dist/esm/core/security.d.ts +123 -0
  89. package/dist/esm/core/security.js +361 -0
  90. package/dist/esm/core/update-check.d.ts +121 -0
  91. package/dist/esm/core/update-check.js +127 -0
  92. package/dist/esm/definitions.d.ts +872 -0
  93. package/dist/esm/definitions.js +104 -0
  94. package/dist/esm/index.d.ts +14 -0
  95. package/dist/esm/index.js +18 -0
  96. package/dist/esm/live-update/bundle-manager.d.ts +102 -0
  97. package/dist/esm/live-update/bundle-manager.js +344 -0
  98. package/dist/esm/live-update/certificate-pinning.d.ts +38 -0
  99. package/dist/esm/live-update/certificate-pinning.js +77 -0
  100. package/dist/esm/live-update/delta-processor.d.ts +84 -0
  101. package/dist/esm/live-update/delta-processor.js +257 -0
  102. package/dist/esm/live-update/download-manager.d.ts +106 -0
  103. package/dist/esm/live-update/download-manager.js +412 -0
  104. package/dist/esm/live-update/rollout-checker.d.ts +86 -0
  105. package/dist/esm/live-update/rollout-checker.js +304 -0
  106. package/dist/esm/live-update/update-manager.d.ts +63 -0
  107. package/dist/esm/live-update/update-manager.js +321 -0
  108. package/dist/esm/live-update/version-manager.d.ts +93 -0
  109. package/dist/esm/live-update/version-manager.js +390 -0
  110. package/dist/esm/plugin.d.ts +3 -0
  111. package/dist/esm/plugin.js +848 -0
  112. package/dist/esm/security/crypto.d.ts +88 -0
  113. package/dist/esm/security/crypto.js +228 -0
  114. package/dist/esm/security/validator.d.ts +60 -0
  115. package/dist/esm/security/validator.js +142 -0
  116. package/dist/esm/types/app-identity.d.ts +36 -0
  117. package/dist/esm/types/app-identity.js +1 -0
  118. package/dist/esm/types/rollout.d.ts +91 -0
  119. package/dist/esm/types/rollout.js +25 -0
  120. package/dist/esm/web.d.ts +130 -0
  121. package/dist/esm/web.js +981 -0
  122. package/dist/plugin.cjs +1 -0
  123. package/dist/plugin.esm.js +1 -0
  124. package/dist/plugin.js +2 -0
  125. package/docs/CHANGELOG.md +1016 -0
  126. package/docs/KNOWN_LIMITATIONS.md +240 -0
  127. package/docs/MIGRATION.md +391 -0
  128. package/docs/protocol/CLIENT-PROTOCOL.md +199 -0
  129. package/docs/server-requirements.md +211 -0
  130. package/ios/Plugin/AppReview/AppReviewPlugin.swift +158 -0
  131. package/ios/Plugin/AppUpdate/AppUpdatePlugin.swift +249 -0
  132. package/ios/Plugin/BackgroundUpdate/BackgroundNotificationManager.swift +333 -0
  133. package/ios/Plugin/BackgroundUpdate/BackgroundUpdatePlugin.swift +464 -0
  134. package/ios/Plugin/Info.plist +43 -0
  135. package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +1286 -0
  136. package/ios/Plugin/LiveUpdate/WebViewConfiguration.swift +45 -0
  137. package/ios/Plugin/NativeUpdatePlugin.m +53 -0
  138. package/ios/Plugin/NativeUpdatePlugin.swift +315 -0
  139. package/ios/Plugin/Security/SecurityManager.swift +289 -0
  140. package/package.json +133 -4
@@ -0,0 +1,1286 @@
1
+ import Foundation
2
+ import Capacitor
3
+ import CommonCrypto
4
+ import UIKit
5
+ import ZIPFoundation
6
+
7
+ class LiveUpdatePlugin: @unchecked Sendable {
8
+ private weak var plugin: CAPPlugin?
9
+ private var config: [String: Any]?
10
+ // Billing hold from the last update check (server says a release exists but is not served).
11
+ private var lastHeld: [String: Any]?
12
+ private var progressListener: (([String: Any]) -> Void)?
13
+ private var stateChangeListener: (([String: Any]) -> Void)?
14
+ private var session: URLSession!
15
+ private var downloadTask: URLSessionDownloadTask?
16
+ private var activeDownloadBundleId: String?
17
+ private let securityManager = SecurityManager()
18
+
19
+ // UserDefaults keys for the A2 (boot-time re-verify) and A3
20
+ // (crash-loop auto-rollback) defenses. Mirrors the Android constants
21
+ // in LiveUpdatePlugin.kt so the two platforms stay in lockstep.
22
+ /// This plugin's version, sent as X-Sdk-Version. Kept equal to package.json by tests/sdk-version.test.ts.
23
+ static let sdkVersion = "4.4.0"
24
+ private static let activeBundleKey = "native_update_active_bundle"
25
+ private static let previousBundleKey = "native_update_previous_active_bundle"
26
+ private static let pendingBundleKey = "native_update_pending_verify_bundle"
27
+ private static let pendingAttemptsKey = "native_update_pending_verify_attempts"
28
+ private static let maxPendingAttempts = 2
29
+
30
+ init(plugin: CAPPlugin) {
31
+ self.plugin = plugin
32
+
33
+ // Create initial session with default configuration
34
+ self.session = createURLSession()
35
+ }
36
+
37
+ private func createURLSession() -> URLSession {
38
+ let config = URLSessionConfiguration.default
39
+ config.timeoutIntervalForRequest = 30
40
+ config.timeoutIntervalForResource = 300
41
+ config.tlsMinimumSupportedProtocolVersion = .TLSv12
42
+
43
+ // Configure certificate pinning if available
44
+ if let securityConfig = self.config?["security"] as? [String: Any],
45
+ let certificatePinning = securityConfig["certificatePinning"] as? [String: Any],
46
+ certificatePinning["enabled"] as? Bool == true {
47
+
48
+ return URLSession(configuration: config, delegate: CertificatePinningDelegate(securityManager: securityManager), delegateQueue: nil)
49
+ }
50
+
51
+ return URLSession(configuration: config)
52
+ }
53
+
54
+ func configure(_ config: [String: Any]) throws {
55
+ self.config = config
56
+
57
+ // Configure security manager
58
+ try securityManager.configure(config)
59
+
60
+ // Recreate URLSession with new configuration
61
+ self.session = createURLSession()
62
+
63
+ // Validate configuration
64
+ if let serverUrl = config["serverUrl"] as? String,
65
+ !securityManager.validateUrl(serverUrl) {
66
+ throw NSError(domain: "LiveUpdatePlugin", code: 1, userInfo: [
67
+ NSLocalizedDescriptionKey: "Server URL must be an allowed HTTPS URL"
68
+ ])
69
+ }
70
+ let requireSignature = config["requireSignature"] as? Bool ?? true
71
+ let publicKey = config["publicKey"] as? String
72
+ if requireSignature && (publicKey?.isEmpty != false) {
73
+ throw NSError(domain: "LiveUpdatePlugin", code: 2, userInfo: [
74
+ NSLocalizedDescriptionKey: "publicKey is required when requireSignature is enabled"
75
+ ])
76
+ }
77
+ if !requireSignature && !unsignedDevelopmentUpdatesAllowed() {
78
+ throw NSError(domain: "LiveUpdatePlugin", code: 3, userInfo: [
79
+ NSLocalizedDescriptionKey: "Unsigned updates are allowed only in debug builds with allowUnsignedDevelopmentUpdates enabled"
80
+ ])
81
+ }
82
+ }
83
+
84
+ func setProgressListener(_ listener: @escaping ([String: Any]) -> Void) {
85
+ self.progressListener = listener
86
+ }
87
+
88
+ func setStateChangeListener(_ listener: @escaping ([String: Any]) -> Void) {
89
+ self.stateChangeListener = listener
90
+ }
91
+
92
+ func sync(_ call: CAPPluginCall) {
93
+ Task {
94
+ do {
95
+ let channel = call.getString("channel") ?? config?["channel"] as? String ?? "production"
96
+ guard let serverUrl = config?["serverUrl"] as? String else {
97
+ call.reject("Server URL not configured")
98
+ return
99
+ }
100
+
101
+ // Check for updates
102
+ if let latestVersion = try await checkForUpdates(serverUrl: serverUrl, channel: channel) {
103
+ call.resolve([
104
+ "status": "UPDATE_AVAILABLE",
105
+ "version": latestVersion["version"] ?? "",
106
+ // v3 wire contract field (legacy shape was "description")
107
+ "description": latestVersion["releaseNotes"] ?? "",
108
+ "mandatory": latestVersion["mandatory"] as? Bool ?? false
109
+ ])
110
+ } else {
111
+ call.resolve([
112
+ "status": "UP_TO_DATE",
113
+ "version": getCurrentVersion()
114
+ ])
115
+ }
116
+ } catch {
117
+ call.resolve([
118
+ "status": "ERROR",
119
+ "error": [
120
+ "code": "NETWORK_ERROR",
121
+ "message": error.localizedDescription
122
+ ]
123
+ ])
124
+ }
125
+ }
126
+ }
127
+
128
+ func download(_ call: CAPPluginCall) {
129
+ guard let url = call.getString("url") else {
130
+ call.reject("URL is required")
131
+ return
132
+ }
133
+
134
+ guard let version = call.getString("version") else {
135
+ call.reject("Version is required")
136
+ return
137
+ }
138
+
139
+ guard let checksum = call.getString("checksum") else {
140
+ call.reject("Checksum is required")
141
+ return
142
+ }
143
+
144
+ // Validate URL
145
+ if !securityManager.validateUrl(url) {
146
+ call.reject("INSECURE_URL", "Download URL must be an allowed HTTPS URL")
147
+ return
148
+ }
149
+
150
+ Task {
151
+ let bundleId = "bundle-\(Date().timeIntervalSince1970)"
152
+ let downloadDir = getUpdatesDirectory().appendingPathComponent(bundleId)
153
+ var downloadSucceeded = false
154
+ defer {
155
+ // Remove the download directory if anything in download/
156
+ // verify/extract failed. Without this, every failed
157
+ // download leaks an empty bundle-<ts>/ directory that
158
+ // never gets cleaned up.
159
+ if !downloadSucceeded {
160
+ try? FileManager.default.removeItem(at: downloadDir)
161
+ }
162
+ }
163
+ do {
164
+ try FileManager.default.createDirectory(at: downloadDir, withIntermediateDirectories: true)
165
+
166
+ let downloadedFile: URL
167
+ if let deltaFile = try await applyDeltaIfAvailable(call, to: downloadDir, bundleId: bundleId) {
168
+ downloadedFile = deltaFile
169
+ } else {
170
+ downloadedFile = try await downloadBundle(from: url, to: downloadDir, bundleId: bundleId)
171
+ }
172
+
173
+ let calculatedChecksum = try calculateChecksum(for: downloadedFile)
174
+ if checksum.range(of: "^[a-fA-F0-9]{64}$", options: .regularExpression) == nil ||
175
+ calculatedChecksum.caseInsensitiveCompare(checksum) != .orderedSame {
176
+ call.reject("CHECKSUM_ERROR", "Bundle checksum validation failed")
177
+ return
178
+ }
179
+
180
+ let signature = call.getString("signature")
181
+ let publicKey = config?["publicKey"] as? String
182
+ let requireSignature = config?["requireSignature"] as? Bool ?? true
183
+ let signatureAlgorithm = call.getString("signatureAlgorithm") ?? "RSA-SHA256"
184
+ if signatureAlgorithm != "RSA-SHA256" {
185
+ call.reject("SIGNATURE_ERROR", "Unsupported signature algorithm")
186
+ return
187
+ }
188
+ if requireSignature && (signature?.isEmpty != false) {
189
+ call.reject("SIGNATURE_ERROR", "Bundle signature is required")
190
+ return
191
+ }
192
+ if let signature = signature, !signature.isEmpty {
193
+ guard let publicKey = publicKey, !publicKey.isEmpty else {
194
+ call.reject("SIGNATURE_ERROR", "Public key is not configured")
195
+ return
196
+ }
197
+ if !securityManager.verifySignature(fileURL: downloadedFile, signature: signature, publicKeyString: publicKey) {
198
+ call.reject("SIGNATURE_ERROR", "Bundle signature validation failed")
199
+ return
200
+ }
201
+ }
202
+
203
+ // Extract immediately so the bundle is bootable, but DO
204
+ // NOT swap the WebView's serverBasePath here. set() does
205
+ // that. This matches Android's contract — download stages
206
+ // a verified bundle, set() activates it.
207
+ try extractZipBundleForBundle(bundleId: bundleId, zipUrl: downloadedFile)
208
+
209
+ let extractedPath = getUpdatesDirectory()
210
+ .appendingPathComponent(bundleId)
211
+ .appendingPathComponent("www")
212
+ .path
213
+
214
+ var bundleInfo: [String: Any] = [
215
+ "bundleId": bundleId,
216
+ "version": version,
217
+ "path": downloadedFile.path,
218
+ "extractedPath": extractedPath,
219
+ "downloadTime": Date().timeIntervalSince1970 * 1000,
220
+ "size": try FileManager.default.attributesOfItem(atPath: downloadedFile.path)[.size] ?? 0,
221
+ "status": "READY",
222
+ "checksum": checksum,
223
+ "verified": true
224
+ ]
225
+ if let signature = call.getString("signature") {
226
+ bundleInfo["signature"] = signature
227
+ bundleInfo["signatureAlgorithm"] = "RSA-SHA256"
228
+ }
229
+ saveBundleInfo(bundleInfo)
230
+
231
+ stateChangeListener?([
232
+ "status": "READY",
233
+ "bundleId": bundleId,
234
+ "version": version
235
+ ])
236
+
237
+ downloadSucceeded = true
238
+ call.resolve(bundleInfo)
239
+ } catch {
240
+ call.reject("DOWNLOAD_ERROR", error.localizedDescription)
241
+ }
242
+ }
243
+ }
244
+
245
+ func set(_ call: CAPPluginCall) {
246
+ guard let bundleId = call.getString("bundleId") else {
247
+ call.reject("Bundle ID is required")
248
+ return
249
+ }
250
+
251
+ // Activation = update the active-bundle pointer AND swap the
252
+ // WebView's serverBasePath. Previously the swap happened in
253
+ // download(), which auto-activated bundles before the host app
254
+ // had a chance to call set(). That broke parity with Android
255
+ // and meant a partially-completed download could end up live.
256
+ let bundles = UserDefaults.standard.dictionary(forKey: "native_update_bundles") ?? [:]
257
+ guard let bundleInfo = bundles[bundleId] as? [String: Any],
258
+ let extractedPath = bundleInfo["extractedPath"] as? String else {
259
+ call.reject("Bundle not found or not extracted: \(bundleId)")
260
+ return
261
+ }
262
+
263
+ setActiveBundle(bundleId)
264
+ configureWebViewPath(extractedPath)
265
+ call.resolve()
266
+ }
267
+
268
+ func reload(_ call: CAPPluginCall) {
269
+ // In iOS, we need to reload the WebView with the new bundle path
270
+ DispatchQueue.main.async { [weak self] in
271
+ guard let self = self,
272
+ let webView = self.plugin?.webView else {
273
+ return
274
+ }
275
+
276
+ // Get the active bundle path
277
+ if let activeBundleId = UserDefaults.standard.string(forKey: "native_update_active_bundle"),
278
+ let bundles = UserDefaults.standard.dictionary(forKey: "native_update_bundles"),
279
+ let bundleInfo = bundles[activeBundleId] as? [String: Any],
280
+ let extractedPath = bundleInfo["extractedPath"] as? String {
281
+
282
+ // Load from extracted bundle path
283
+ let indexPath = URL(fileURLWithPath: extractedPath).appendingPathComponent("index.html")
284
+ webView.load(URLRequest(url: indexPath))
285
+ } else {
286
+ // Fallback to regular reload
287
+ webView.reload()
288
+ }
289
+ }
290
+ call.resolve()
291
+ }
292
+
293
+ func reset(_ call: CAPPluginCall) {
294
+ clearAllBundles()
295
+ call.resolve()
296
+ }
297
+
298
+ func current(_ call: CAPPluginCall) {
299
+ let currentBundle = getCurrentBundleInfo()
300
+ call.resolve(currentBundle)
301
+ }
302
+
303
+ func list(_ call: CAPPluginCall) {
304
+ let bundles = getAllBundles()
305
+ call.resolve(["bundles": bundles])
306
+ }
307
+
308
+ func delete(_ call: CAPPluginCall) {
309
+ if let bundleId = call.getString("bundleId") {
310
+ deleteBundle(bundleId)
311
+ } else if let keepVersions = call.getInt("keepVersions") {
312
+ cleanupOldBundles(keepVersions: keepVersions)
313
+ }
314
+ call.resolve()
315
+ }
316
+
317
+ func notifyAppReady(_ call: CAPPluginCall) {
318
+ markBundleAsVerified()
319
+ call.resolve()
320
+ }
321
+
322
+ func getLatest(_ call: CAPPluginCall) {
323
+ Task {
324
+ do {
325
+ guard let serverUrl = config?["serverUrl"] as? String else {
326
+ call.reject("Server URL not configured")
327
+ return
328
+ }
329
+
330
+ let channel = config?["channel"] as? String ?? "production"
331
+
332
+ if let latestVersion = try await checkForUpdates(serverUrl: serverUrl, channel: channel) {
333
+ call.resolve([
334
+ "available": true,
335
+ "version": latestVersion["version"] ?? "",
336
+ // v3 wire contract fields (legacy shape was url/notes)
337
+ "url": latestVersion["downloadUrl"] ?? "",
338
+ "notes": latestVersion["releaseNotes"] ?? "",
339
+ "checksum": latestVersion["checksum"] ?? "",
340
+ "signature": latestVersion["signature"] ?? NSNull(),
341
+ "signatureAlgorithm": latestVersion["signatureAlgorithm"] ?? "RSA-SHA256",
342
+ "delta": latestVersion["delta"] ?? NSNull(),
343
+ "size": latestVersion["size"] as? Int ?? 0,
344
+ "mandatory": latestVersion["mandatory"] as? Bool ?? false
345
+ ])
346
+ } else if let held = lastHeld {
347
+ var result: [String: Any] = ["available": false, "held": true]
348
+ if let version = held["version"] as? String { result["version"] = version }
349
+ if let message = held["message"] as? String { result["heldMessage"] = message }
350
+ call.resolve(result)
351
+ } else {
352
+ call.resolve(["available": false])
353
+ }
354
+ } catch {
355
+ call.reject("NETWORK_ERROR", error.localizedDescription)
356
+ }
357
+ }
358
+ }
359
+
360
+ func setChannel(_ call: CAPPluginCall) {
361
+ guard let channel = call.getString("channel") else {
362
+ call.reject("Channel is required")
363
+ return
364
+ }
365
+
366
+ config?["channel"] = channel
367
+ call.resolve()
368
+ }
369
+
370
+ func setUpdateUrl(_ call: CAPPluginCall) {
371
+ guard call.getString("url") != nil else {
372
+ call.reject("URL is required")
373
+ return
374
+ }
375
+
376
+ CAPLog.print("[NativeUpdate] setUpdateUrl() is deprecated and ignored; the update URL is locked after initialize()")
377
+ call.resolve()
378
+ }
379
+
380
+ func validateUpdate(_ call: CAPPluginCall) {
381
+ guard let bundlePath = call.getString("bundlePath") else {
382
+ call.reject("Bundle path is required")
383
+ return
384
+ }
385
+
386
+ guard let checksum = call.getString("checksum") else {
387
+ call.reject("Checksum is required")
388
+ return
389
+ }
390
+
391
+ do {
392
+ let url = URL(fileURLWithPath: bundlePath)
393
+ let calculatedChecksum = try calculateChecksum(for: url)
394
+ let isValid = calculatedChecksum == checksum
395
+
396
+ call.resolve([
397
+ "isValid": isValid,
398
+ "details": [
399
+ "checksumValid": isValid
400
+ ]
401
+ ])
402
+ } catch {
403
+ call.reject("VALIDATION_ERROR", error.localizedDescription)
404
+ }
405
+ }
406
+
407
+ func cancelDownload(_ call: CAPPluginCall) {
408
+ guard let bundleId = call.getString("bundleId") else {
409
+ call.reject("Bundle ID is required")
410
+ return
411
+ }
412
+ if activeDownloadBundleId == bundleId {
413
+ downloadTask?.cancel()
414
+ downloadTask = nil
415
+ activeDownloadBundleId = nil
416
+ }
417
+ call.resolve()
418
+ }
419
+
420
+ func cancelAllDownloads(_ call: CAPPluginCall) {
421
+ downloadTask?.cancel()
422
+ downloadTask = nil
423
+ activeDownloadBundleId = nil
424
+ call.resolve()
425
+ }
426
+
427
+ func isDownloading(_ call: CAPPluginCall) {
428
+ guard let bundleId = call.getString("bundleId") else {
429
+ call.reject("Bundle ID is required")
430
+ return
431
+ }
432
+ call.resolve(["isDownloading": activeDownloadBundleId == bundleId && downloadTask != nil])
433
+ }
434
+
435
+ func getActiveDownloadCount(_ call: CAPPluginCall) {
436
+ call.resolve(["count": downloadTask == nil ? 0 : 1])
437
+ }
438
+
439
+ // MARK: - Async Methods for Background Updates
440
+
441
+ func getLatestVersionAsync() async -> LatestVersion? {
442
+ do {
443
+ guard let serverUrl = config?["serverUrl"] as? String else {
444
+ NSLog("Server URL not configured")
445
+ return nil
446
+ }
447
+
448
+ let channel = config?["channel"] as? String ?? "production"
449
+
450
+ if let latestVersion = try await checkForUpdates(serverUrl: serverUrl, channel: channel) {
451
+ return LatestVersion(
452
+ available: true,
453
+ version: latestVersion["version"] as? String
454
+ )
455
+ } else {
456
+ return LatestVersion(
457
+ available: false,
458
+ version: nil
459
+ )
460
+ }
461
+ } catch {
462
+ NSLog("Failed to check live update: \(error.localizedDescription)")
463
+ return nil
464
+ }
465
+ }
466
+
467
+ /// The app's client identity for API-key client restrictions: the bundle
468
+ /// identifier. Consumed by the dashboard "Restrictions" UI and attached as
469
+ /// the X-Ios-Bundle-Id header on native update checks. Team id is not
470
+ /// populated (no provisioning-profile parsing).
471
+ func getAppIdentity(_ call: CAPPluginCall) {
472
+ var result: [String: Any] = ["platform": "ios"]
473
+ if let bundleId = Bundle.main.bundleIdentifier {
474
+ result["bundleId"] = bundleId
475
+ }
476
+ call.resolve(result)
477
+ }
478
+
479
+ // MARK: - Private Methods
480
+
481
+ /// v3 wire contract (mirrors src/core/update-check.ts):
482
+ /// GET {serverUrl}/v1/updates/check?channel={channel}
483
+ /// Headers: X-API-Key, X-Device-ID, X-Current-Version, X-Platform
484
+ /// (+ X-App-Version when the binary version is known)
485
+ /// Returns the parsed response when a newer bundle is AVAILABLE, else
486
+ /// nil ("up to date", auth failures, non-2xx — matching the TS
487
+ /// helper's behavior). Callers consume the v3 response fields:
488
+ /// version, downloadUrl, checksum, signature, size, mandatory,
489
+ /// releaseNotes.
490
+ private func checkForUpdates(serverUrl: String, channel: String) async throws -> [String: Any]? {
491
+ guard let apiKey = config?["apiKey"] as? String, !apiKey.isEmpty else {
492
+ NSLog("NativeUpdate: update check skipped — no apiKey configured (pass it via initialize({ apiKey }) or configure({ liveUpdate: { apiKey } }))")
493
+ return nil
494
+ }
495
+
496
+ let base = serverUrl.hasSuffix("/") ? String(serverUrl.dropLast()) : serverUrl
497
+ let encodedChannel = channel.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? channel
498
+ guard let url = URL(string: "\(base)/v1/updates/check?channel=\(encodedChannel)") else {
499
+ throw NSError(domain: "LiveUpdatePlugin", code: 2, userInfo: [
500
+ NSLocalizedDescriptionKey: "Invalid server URL"
501
+ ])
502
+ }
503
+
504
+ var request = URLRequest(url: url)
505
+ request.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
506
+ request.setValue(getOrCreateDeviceId(), forHTTPHeaderField: "X-Device-ID")
507
+ request.setValue(getCurrentVersion(), forHTTPHeaderField: "X-Current-Version")
508
+ request.setValue("ios", forHTTPHeaderField: "X-Platform")
509
+ // SDK identity: the server offers this WebView only web bundles (docs/protocol/CLIENT-PROTOCOL.md).
510
+ request.setValue("capacitor", forHTTPHeaderField: "X-Client-Sdk")
511
+ request.setValue(LiveUpdatePlugin.sdkVersion, forHTTPHeaderField: "X-Sdk-Version")
512
+ // App-identity header for API-key client restrictions (bundle id only;
513
+ // team id is intentionally not sent by the plugin).
514
+ if let bundleId = Bundle.main.bundleIdentifier {
515
+ request.setValue(bundleId, forHTTPHeaderField: "X-Ios-Bundle-Id")
516
+ }
517
+ if let binaryVersion = getBinaryVersion() {
518
+ request.setValue(binaryVersion, forHTTPHeaderField: "X-App-Version")
519
+ }
520
+
521
+ let (data, response) = try await session.data(for: request)
522
+
523
+ if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) {
524
+ NSLog("NativeUpdate: update check returned HTTP %d — treating as no update", http.statusCode)
525
+ return nil
526
+ }
527
+
528
+ let parsed = try JSONSerialization.jsonObject(with: data) as? [String: Any]
529
+ lastHeld = (parsed?["held"] as? Bool) == true ? parsed : nil
530
+ if let json = parsed,
531
+ let available = json["available"] as? Bool,
532
+ available {
533
+ return json
534
+ }
535
+
536
+ return nil
537
+ }
538
+
539
+ /// Native binary version (sent as X-App-Version).
540
+ private func getBinaryVersion() -> String? {
541
+ return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
542
+ }
543
+
544
+ /// Stable per-install device id (sent as X-Device-ID; the backend uses
545
+ /// it for rollout bucketing). identifierForVendor when available, else
546
+ /// a minted UUID — persisted either way so it never changes.
547
+ private func getOrCreateDeviceId() -> String {
548
+ let defaults = UserDefaults.standard
549
+ if let existing = defaults.string(forKey: "native_update_device_id") {
550
+ return existing
551
+ }
552
+
553
+ let deviceId = UIDevice.current.identifierForVendor?.uuidString ?? UUID().uuidString
554
+ defaults.set(deviceId, forKey: "native_update_device_id")
555
+ return deviceId
556
+ }
557
+
558
+ private func downloadBundle(
559
+ from urlString: String,
560
+ to directory: URL,
561
+ bundleId: String,
562
+ filename: String = "bundle.zip"
563
+ ) async throws -> URL {
564
+ guard let url = URL(string: urlString) else {
565
+ throw NSError(domain: "LiveUpdatePlugin", code: 3, userInfo: [
566
+ NSLocalizedDescriptionKey: "Invalid download URL"
567
+ ])
568
+ }
569
+
570
+ let destinationURL = directory.appendingPathComponent(filename)
571
+
572
+ return try await withCheckedThrowingContinuation { continuation in
573
+ let task = session.downloadTask(with: url) { [weak self] tempURL, response, error in
574
+ defer {
575
+ self?.downloadTask = nil
576
+ self?.activeDownloadBundleId = nil
577
+ }
578
+ if let error = error {
579
+ continuation.resume(throwing: error)
580
+ return
581
+ }
582
+
583
+ guard let tempURL = tempURL else {
584
+ continuation.resume(throwing: NSError(domain: "LiveUpdatePlugin", code: 4, userInfo: [
585
+ NSLocalizedDescriptionKey: "Download failed"
586
+ ]))
587
+ return
588
+ }
589
+
590
+ do {
591
+ let maxBytes = (self?.config?["maxBundleSize"] as? NSNumber)?.int64Value ?? 100 * 1024 * 1024
592
+ let responseSize = response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
593
+ if responseSize > maxBytes {
594
+ throw NSError(domain: "LiveUpdatePlugin", code: 12, userInfo: [
595
+ NSLocalizedDescriptionKey: "Bundle exceeds maximum download size"
596
+ ])
597
+ }
598
+ try FileManager.default.moveItem(at: tempURL, to: destinationURL)
599
+ let actualSize = (try FileManager.default.attributesOfItem(atPath: destinationURL.path)[.size] as? NSNumber)?.int64Value ?? 0
600
+ if actualSize > maxBytes {
601
+ try? FileManager.default.removeItem(at: destinationURL)
602
+ throw NSError(domain: "LiveUpdatePlugin", code: 13, userInfo: [
603
+ NSLocalizedDescriptionKey: "Bundle exceeds maximum download size"
604
+ ])
605
+ }
606
+ continuation.resume(returning: destinationURL)
607
+ } catch {
608
+ continuation.resume(throwing: error)
609
+ }
610
+ }
611
+
612
+ // Track progress
613
+ _ = task.progress.observe(\.fractionCompleted) { [weak self] progress, _ in
614
+ let percent = Int(progress.fractionCompleted * 100)
615
+ self?.progressListener?([
616
+ "percent": percent,
617
+ "bytesDownloaded": progress.completedUnitCount,
618
+ "totalBytes": progress.totalUnitCount,
619
+ "bundleId": bundleId
620
+ ])
621
+ }
622
+
623
+ task.resume()
624
+ self.downloadTask = task
625
+ self.activeDownloadBundleId = bundleId
626
+ }
627
+ }
628
+
629
+ private func applyDeltaIfAvailable(
630
+ _ call: CAPPluginCall,
631
+ to directory: URL,
632
+ bundleId: String
633
+ ) async throws -> URL? {
634
+ guard (config?["enableDeltaUpdates"] as? Bool) != false else { return nil }
635
+ guard let delta = call.getObject("delta"),
636
+ delta["format"] as? String == "NUDELTA/1",
637
+ delta["fromVersion"] as? String == getCurrentVersion(),
638
+ let activeId = UserDefaults.standard.string(forKey: Self.activeBundleKey),
639
+ let basePath = getBundleInfoById(activeId)?["path"] as? String,
640
+ FileManager.default.fileExists(atPath: basePath),
641
+ let patchUrl = delta["patchUrl"] as? String,
642
+ securityManager.validateUrl(patchUrl),
643
+ let patchChecksum = delta["patchChecksum"] as? String,
644
+ let targetChecksum = delta["targetChecksum"] as? String else { return nil }
645
+
646
+ do {
647
+ let patchURL = try await downloadBundle(
648
+ from: patchUrl,
649
+ to: directory,
650
+ bundleId: bundleId,
651
+ filename: "patch.nudelta.json"
652
+ )
653
+ guard try calculateChecksum(for: patchURL).caseInsensitiveCompare(patchChecksum) == .orderedSame else {
654
+ return nil
655
+ }
656
+ let data = try Data(contentsOf: patchURL)
657
+ guard let document = try JSONSerialization.jsonObject(with: data) as? [String: Any],
658
+ document["format"] as? String == "NUDELTA/1",
659
+ document["fromVersion"] as? String == delta["fromVersion"] as? String,
660
+ document["targetChecksum"] as? String == targetChecksum,
661
+ let baseChecksum = document["baseChecksum"] as? String,
662
+ let targetSize = (document["targetSize"] as? NSNumber)?.intValue,
663
+ targetSize > 0,
664
+ targetSize <= ((config?["maxBundleSize"] as? NSNumber)?.intValue ?? 100 * 1024 * 1024),
665
+ let operations = document["operations"] as? [[String: Any]],
666
+ !operations.isEmpty, operations.count <= 100_000 else { return nil }
667
+ let baseURL = URL(fileURLWithPath: basePath)
668
+ guard try calculateChecksum(for: baseURL).caseInsensitiveCompare(baseChecksum) == .orderedSame else { return nil }
669
+ let base = try Data(contentsOf: baseURL, options: [.mappedIfSafe])
670
+ var result = Data()
671
+ result.reserveCapacity(targetSize)
672
+ for operation in operations {
673
+ switch operation["op"] as? String {
674
+ case "copy":
675
+ guard let offset = (operation["offset"] as? NSNumber)?.intValue,
676
+ let length = (operation["length"] as? NSNumber)?.intValue,
677
+ offset >= 0, length > 0, length <= base.count,
678
+ offset <= base.count - length else { return nil }
679
+ result.append(base.subdata(in: offset..<(offset + length)))
680
+ case "literal":
681
+ guard let encoded = operation["data"] as? String,
682
+ let literal = Data(base64Encoded: encoded) else { return nil }
683
+ result.append(literal)
684
+ default: return nil
685
+ }
686
+ if result.count > targetSize { return nil }
687
+ }
688
+ guard result.count == targetSize else { return nil }
689
+ let output = directory.appendingPathComponent("bundle.zip")
690
+ try result.write(to: output, options: .atomic)
691
+ guard try calculateChecksum(for: output).caseInsensitiveCompare(targetChecksum) == .orderedSame else {
692
+ try? FileManager.default.removeItem(at: output)
693
+ return nil
694
+ }
695
+ try? FileManager.default.removeItem(at: patchURL)
696
+ return output
697
+ } catch {
698
+ try? FileManager.default.removeItem(at: directory.appendingPathComponent("patch.nudelta.json"))
699
+ try? FileManager.default.removeItem(at: directory.appendingPathComponent("bundle.zip"))
700
+ return nil
701
+ }
702
+ }
703
+
704
+ private func calculateChecksum(for url: URL) throws -> String {
705
+ guard let stream = InputStream(url: url) else {
706
+ throw NSError(domain: "LiveUpdatePlugin", code: 14, userInfo: [NSLocalizedDescriptionKey: "Unable to read bundle"])
707
+ }
708
+ stream.open()
709
+ defer { stream.close() }
710
+ var context = CC_SHA256_CTX()
711
+ CC_SHA256_Init(&context)
712
+ let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 64 * 1024)
713
+ defer { buffer.deallocate() }
714
+ while stream.hasBytesAvailable {
715
+ let read = stream.read(buffer, maxLength: 64 * 1024)
716
+ if read < 0 { throw stream.streamError ?? NSError(domain: "LiveUpdatePlugin", code: 15) }
717
+ if read == 0 { break }
718
+ CC_SHA256_Update(&context, buffer, CC_LONG(read))
719
+ }
720
+ var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
721
+ CC_SHA256_Final(&digest, &context)
722
+ return digest.map { String(format: "%02x", $0) }.joined()
723
+ }
724
+
725
+ private func getUpdatesDirectory() -> URL {
726
+ let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
727
+ return documentsDirectory.appendingPathComponent("updates")
728
+ }
729
+
730
+ private func getCurrentVersion() -> String {
731
+ // First check if we have an active bundle with version
732
+ let defaults = UserDefaults.standard
733
+ if let activeBundleId = defaults.string(forKey: "native_update_active_bundle"),
734
+ let bundles = defaults.dictionary(forKey: "native_update_bundles"),
735
+ let bundleInfo = bundles[activeBundleId] as? [String: Any],
736
+ let version = bundleInfo["version"] as? String {
737
+ return version
738
+ }
739
+ // Fall back to app version
740
+ return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.0"
741
+ }
742
+
743
+ private func saveBundleInfo(_ bundleInfo: [String: Any]) {
744
+ guard let bundleId = bundleInfo["bundleId"] as? String else { return }
745
+
746
+ let defaults = UserDefaults.standard
747
+ var bundles = defaults.dictionary(forKey: "native_update_bundles") ?? [:]
748
+ bundles[bundleId] = bundleInfo
749
+ defaults.set(bundles, forKey: "native_update_bundles")
750
+ }
751
+
752
+ private func setActiveBundle(_ bundleId: String) {
753
+ let defaults = UserDefaults.standard
754
+ let currentActive = defaults.string(forKey: Self.activeBundleKey)
755
+
756
+ defaults.set(bundleId, forKey: Self.activeBundleKey)
757
+
758
+ // Preserve the previous active bundle as a rollback target. Skip
759
+ // self-activation so we don't nuke a real previous-bundle pointer.
760
+ if let previous = currentActive, previous != bundleId {
761
+ defaults.set(previous, forKey: Self.previousBundleKey)
762
+ }
763
+
764
+ // Mark this activation as pending-verify. notifyAppReady() clears
765
+ // it; otherwise the next cold start counts against the bundle and
766
+ // eventually rolls back to the previous known-good bundle.
767
+ defaults.set(bundleId, forKey: Self.pendingBundleKey)
768
+ defaults.set(0, forKey: Self.pendingAttemptsKey)
769
+ }
770
+
771
+ private func clearAllBundles() {
772
+ let updateDir = getUpdatesDirectory()
773
+ try? FileManager.default.removeItem(at: updateDir)
774
+
775
+ UserDefaults.standard.removeObject(forKey: "native_update_bundles")
776
+ UserDefaults.standard.removeObject(forKey: "native_update_active_bundle")
777
+ }
778
+
779
+ private func getCurrentBundleInfo() -> [String: Any] {
780
+ let defaults = UserDefaults.standard
781
+
782
+ if let activeBundleId = defaults.string(forKey: "native_update_active_bundle"),
783
+ let bundles = defaults.dictionary(forKey: "native_update_bundles"),
784
+ let bundleInfo = bundles[activeBundleId] as? [String: Any] {
785
+ return bundleInfo
786
+ }
787
+
788
+ // Return default bundle
789
+ return [
790
+ "bundleId": "default",
791
+ "version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.0",
792
+ "path": "/",
793
+ "downloadTime": Date().timeIntervalSince1970 * 1000,
794
+ "size": 0,
795
+ "status": "ACTIVE",
796
+ "checksum": "",
797
+ "verified": true
798
+ ]
799
+ }
800
+
801
+ private func getAllBundles() -> [[String: Any]] {
802
+ let defaults = UserDefaults.standard
803
+ let bundles = defaults.dictionary(forKey: "native_update_bundles") ?? [:]
804
+ return bundles.values.compactMap { $0 as? [String: Any] }
805
+ }
806
+
807
+ private func deleteBundle(_ bundleId: String) {
808
+ // Delete bundle files
809
+ let bundleDir = getUpdatesDirectory().appendingPathComponent(bundleId)
810
+ try? FileManager.default.removeItem(at: bundleDir)
811
+
812
+ // Remove from UserDefaults
813
+ let defaults = UserDefaults.standard
814
+ var bundles = defaults.dictionary(forKey: "native_update_bundles") ?? [:]
815
+ bundles.removeValue(forKey: bundleId)
816
+ defaults.set(bundles, forKey: "native_update_bundles")
817
+ }
818
+
819
+ func cleanup() {
820
+ // Clean up any resources
821
+ downloadTask?.cancel()
822
+ downloadTask = nil
823
+ }
824
+
825
+ private func cleanupOldBundles(keepVersions: Int) {
826
+ let bundles = getAllBundles().sorted { bundle1, bundle2 in
827
+ let time1 = bundle1["downloadTime"] as? Double ?? 0
828
+ let time2 = bundle2["downloadTime"] as? Double ?? 0
829
+ return time1 > time2
830
+ }
831
+
832
+ if bundles.count > keepVersions {
833
+ let bundlesToDelete = bundles.dropFirst(keepVersions)
834
+ for bundle in bundlesToDelete {
835
+ if let bundleId = bundle["bundleId"] as? String {
836
+ deleteBundle(bundleId)
837
+ }
838
+ }
839
+ }
840
+ }
841
+
842
+ private func markBundleAsVerified() {
843
+ // notifyAppReady() is the host app's "I booted clean on this bundle"
844
+ // signal. Clear the pending-verify state so cold starts after this
845
+ // no longer count against the bundle.
846
+ let defaults = UserDefaults.standard
847
+ defaults.set(true, forKey: "native_update_current_bundle_verified")
848
+ defaults.removeObject(forKey: Self.pendingBundleKey)
849
+ defaults.removeObject(forKey: Self.pendingAttemptsKey)
850
+ }
851
+
852
+ /// Called from NativeUpdatePlugin.load() on every cold start. Runs two
853
+ /// independent defenses, both silent when no OTA bundle is active:
854
+ ///
855
+ /// A2 — re-hash the active bundle and verify it still matches the
856
+ /// checksum stored at install time. If signature + publicKey are
857
+ /// configured, also re-verify the signature. Catches on-disk
858
+ /// tampering on jailbroken devices.
859
+ /// A3 — if the active bundle was never confirmed by notifyAppReady()
860
+ /// on the previous launch, treat this cold start as a failed
861
+ /// boot. After maxPendingAttempts failures, rollback to the
862
+ /// previous known-good bundle to break the crash loop.
863
+ ///
864
+ /// On any failure the method rolls back and fires an
865
+ /// updateStateChanged event with status "ROLLBACK" so the host app
866
+ /// and analytics layer can observe it.
867
+ func verifyActiveBundleOnBoot() {
868
+ let defaults = UserDefaults.standard
869
+
870
+ // A3: crash-loop detection.
871
+ if let pendingBundleId = defaults.string(forKey: Self.pendingBundleKey) {
872
+ let nextAttempt = defaults.integer(forKey: Self.pendingAttemptsKey) + 1
873
+ if nextAttempt > Self.maxPendingAttempts {
874
+ rollbackToPrevious(
875
+ reason: "auto-rollback after \(nextAttempt) failed cold starts",
876
+ fromBundleId: pendingBundleId
877
+ )
878
+ defaults.removeObject(forKey: Self.pendingBundleKey)
879
+ defaults.removeObject(forKey: Self.pendingAttemptsKey)
880
+ return
881
+ }
882
+ defaults.set(nextAttempt, forKey: Self.pendingAttemptsKey)
883
+ }
884
+
885
+ // A2: integrity re-verify. Only for non-default active bundles.
886
+ guard let activeBundleId = defaults.string(forKey: Self.activeBundleKey),
887
+ activeBundleId != "default" else {
888
+ return
889
+ }
890
+
891
+ guard let bundleInfo = getBundleInfoById(activeBundleId) else {
892
+ rollbackToPrevious(
893
+ reason: "active bundle info missing from UserDefaults",
894
+ fromBundleId: activeBundleId
895
+ )
896
+ return
897
+ }
898
+
899
+ guard let bundlePath = bundleInfo["path"] as? String, !bundlePath.isEmpty,
900
+ let expectedChecksum = bundleInfo["checksum"] as? String, !expectedChecksum.isEmpty else {
901
+ return
902
+ }
903
+
904
+ let bundleURL = URL(fileURLWithPath: bundlePath)
905
+ guard FileManager.default.fileExists(atPath: bundlePath) else {
906
+ rollbackToPrevious(
907
+ reason: "bundle file missing on disk",
908
+ fromBundleId: activeBundleId
909
+ )
910
+ return
911
+ }
912
+
913
+ do {
914
+ let actualChecksum = try calculateChecksum(for: bundleURL)
915
+ if actualChecksum != expectedChecksum {
916
+ rollbackToPrevious(
917
+ reason: "bundle checksum mismatch on boot",
918
+ fromBundleId: activeBundleId
919
+ )
920
+ return
921
+ }
922
+ } catch {
923
+ rollbackToPrevious(
924
+ reason: "bundle checksum computation failed: \(error.localizedDescription)",
925
+ fromBundleId: activeBundleId
926
+ )
927
+ return
928
+ }
929
+
930
+ // Signature re-verify when both a signature and a public key are
931
+ // available. Absence of either is treated as "not configured" and
932
+ // skipped — Phase A1 already enforces fail-closed at download time.
933
+ if let signature = bundleInfo["signature"] as? String, !signature.isEmpty,
934
+ let publicKey = config?["publicKey"] as? String,
935
+ !publicKey.isEmpty {
936
+ do {
937
+ let bytes = try Data(contentsOf: bundleURL, options: [.mappedIfSafe])
938
+ if !securityManager.verifySignature(
939
+ data: bytes,
940
+ signature: signature,
941
+ publicKeyString: publicKey
942
+ ) {
943
+ rollbackToPrevious(
944
+ reason: "bundle signature mismatch on boot",
945
+ fromBundleId: activeBundleId
946
+ )
947
+ }
948
+ } catch {
949
+ rollbackToPrevious(
950
+ reason: "bundle signature check failed: \(error.localizedDescription)",
951
+ fromBundleId: activeBundleId
952
+ )
953
+ }
954
+ }
955
+ }
956
+
957
+ private func rollbackToPrevious(reason: String, fromBundleId: String) {
958
+ let defaults = UserDefaults.standard
959
+ let previous = defaults.string(forKey: Self.previousBundleKey)
960
+ if let previous = previous {
961
+ defaults.set(previous, forKey: Self.activeBundleKey)
962
+ } else {
963
+ defaults.removeObject(forKey: Self.activeBundleKey)
964
+ }
965
+ defaults.removeObject(forKey: Self.previousBundleKey)
966
+
967
+ stateChangeListener?([
968
+ "status": "ROLLBACK",
969
+ "bundleId": fromBundleId,
970
+ "rolledBackTo": previous ?? "default",
971
+ "reason": reason
972
+ ])
973
+ }
974
+
975
+ private func getBundleInfoById(_ bundleId: String) -> [String: Any]? {
976
+ let defaults = UserDefaults.standard
977
+ let bundles = defaults.dictionary(forKey: "native_update_bundles") ?? [:]
978
+ return bundles[bundleId] as? [String: Any]
979
+ }
980
+
981
+ // MARK: - Bundle Extraction and WebView Configuration
982
+
983
+ /// Extract a downloaded zip into `bundles/{bundleId}/www/`. Does NOT
984
+ /// touch `setServerBasePath` — activation is owned by set().
985
+ private func extractZipBundleForBundle(bundleId: String, zipUrl: URL) throws {
986
+ let extractedPath = getUpdatesDirectory()
987
+ .appendingPathComponent(bundleId)
988
+ .appendingPathComponent("www")
989
+ do {
990
+ try extractZipBundle(from: zipUrl, to: extractedPath)
991
+ } catch {
992
+ // Roll back the partial extraction so a re-download is clean.
993
+ try? FileManager.default.removeItem(at: extractedPath)
994
+ throw error
995
+ }
996
+ }
997
+
998
+ private func extractAndApplyBundle(_ bundleUrl: URL, bundleId: String) throws {
999
+ // Legacy path retained for any caller still using it. Extracts
1000
+ // and immediately activates — equivalent to the old behavior.
1001
+ try extractZipBundleForBundle(bundleId: bundleId, zipUrl: bundleUrl)
1002
+ let extractedPath = getUpdatesDirectory()
1003
+ .appendingPathComponent(bundleId)
1004
+ .appendingPathComponent("www")
1005
+ var bundleInfo = getAllBundles().first { $0["bundleId"] as? String == bundleId } ?? [:]
1006
+ bundleInfo["extractedPath"] = extractedPath.path
1007
+ bundleInfo["status"] = "READY"
1008
+ saveBundleInfo(bundleInfo)
1009
+ configureWebViewPath(extractedPath.path)
1010
+ }
1011
+
1012
+ /// Hard cap on total uncompressed size of an OTA bundle. Protects
1013
+ /// against zip-bombs (a small zip that expands to gigabytes and fills
1014
+ /// the device). Chosen as 5x the default 100MB downloaded-bundle limit
1015
+ /// — enough headroom for typical web-app bundles after minification
1016
+ /// reverses, below a threshold that would be hostile on mobile.
1017
+ private var maxUncompressedBundleBytes: UInt64 {
1018
+ let configured = (config?["maxUncompressedBundleSize"] as? NSNumber)?.uint64Value
1019
+ return min(max(configured ?? 500 * 1024 * 1024, 1), 2 * 1024 * 1024 * 1024)
1020
+ }
1021
+
1022
+ private func extractZipBundle(from zipUrl: URL, to destinationUrl: URL) throws {
1023
+ // Ensure destination directory exists.
1024
+ try FileManager.default.createDirectory(at: destinationUrl, withIntermediateDirectories: true, attributes: nil)
1025
+
1026
+ // Inspect every entry before extracting anything. Three defenses:
1027
+ // 1. zip-slip — an entry whose destination path resolves outside
1028
+ // the intended directory would let a malicious bundle write
1029
+ // over any file in the app sandbox (e.g. overwriting
1030
+ // built-in code) when unzipItem later runs.
1031
+ // 2. symlink attack — symlinks in the archive can redirect
1032
+ // subsequent writes outside the sandbox even if the entry
1033
+ // itself resolves cleanly.
1034
+ // 3. zip-bomb — sum of uncompressed sizes capped; refuses to
1035
+ // extract an archive that would exhaust device storage.
1036
+ let archive = try Archive(url: zipUrl, accessMode: .read)
1037
+
1038
+ let canonicalDestination = destinationUrl
1039
+ .standardizedFileURL
1040
+ .resolvingSymlinksInPath()
1041
+ .path
1042
+ let destinationPrefix = canonicalDestination.hasSuffix("/")
1043
+ ? canonicalDestination
1044
+ : canonicalDestination + "/"
1045
+
1046
+ var totalUncompressed: UInt64 = 0
1047
+
1048
+ for entry in archive {
1049
+ if entry.type == .symlink {
1050
+ throw NSError(domain: "LiveUpdatePlugin", code: 8, userInfo: [
1051
+ NSLocalizedDescriptionKey: "Bundle contains symlink entry (refused): \(entry.path)"
1052
+ ])
1053
+ }
1054
+
1055
+ if entry.path.hasPrefix("/") {
1056
+ throw NSError(domain: "LiveUpdatePlugin", code: 9, userInfo: [
1057
+ NSLocalizedDescriptionKey: "Bundle entry has absolute path (refused): \(entry.path)"
1058
+ ])
1059
+ }
1060
+
1061
+ let entryURL = destinationUrl
1062
+ .appendingPathComponent(entry.path)
1063
+ .standardizedFileURL
1064
+ let entryPath = entryURL.resolvingSymlinksInPath().path
1065
+
1066
+ if entryPath != canonicalDestination && !entryPath.hasPrefix(destinationPrefix) {
1067
+ throw NSError(domain: "LiveUpdatePlugin", code: 10, userInfo: [
1068
+ NSLocalizedDescriptionKey: "Bundle entry escapes destination (zip-slip refused): \(entry.path)"
1069
+ ])
1070
+ }
1071
+
1072
+ let (newTotal, overflow) = totalUncompressed.addingReportingOverflow(entry.uncompressedSize)
1073
+ if overflow || newTotal > maxUncompressedBundleBytes {
1074
+ throw NSError(domain: "LiveUpdatePlugin", code: 11, userInfo: [
1075
+ NSLocalizedDescriptionKey: "Bundle exceeds maximum uncompressed size (\(maxUncompressedBundleBytes) bytes) — possible zip-bomb"
1076
+ ])
1077
+ }
1078
+ totalUncompressed = newTotal
1079
+ }
1080
+
1081
+ // All entries passed inspection — safe to extract.
1082
+ try FileManager.default.unzipItem(at: zipUrl, to: destinationUrl)
1083
+
1084
+ // Verify extraction succeeded by checking for index.html.
1085
+ let indexPath = destinationUrl.appendingPathComponent("index.html")
1086
+ guard FileManager.default.fileExists(atPath: indexPath.path) else {
1087
+ throw NSError(domain: "LiveUpdatePlugin", code: 6, userInfo: [
1088
+ NSLocalizedDescriptionKey: "Bundle extraction failed: index.html not found in extracted bundle"
1089
+ ])
1090
+ }
1091
+
1092
+ // Keep the verified ZIP so cold-start integrity/signature checks can
1093
+ // re-verify the exact signed bytes. It is removed with the bundle.
1094
+ }
1095
+
1096
+ private func configureWebViewPath(_ path: String) {
1097
+ // Store the active bundle path
1098
+ UserDefaults.standard.set(path, forKey: "native_update_webview_path")
1099
+
1100
+ // Configure Capacitor WebView to use the new bundle path
1101
+ DispatchQueue.main.async { [weak self] in
1102
+ guard let bridge = self?.plugin?.bridge else { return }
1103
+
1104
+ // Set the server base path to the extracted bundle directory
1105
+ bridge.setServerBasePath(path)
1106
+
1107
+ // Optionally trigger a WebView reload (commented out by default)
1108
+ // Uncomment if you want automatic reload after bundle extraction
1109
+ // bridge.webView?.reload()
1110
+ }
1111
+ }
1112
+
1113
+ private func rollbackToSafeBundle(currentPath: String, safePath: String) throws {
1114
+ // Remove the failed bundle directory
1115
+ let currentUrl = URL(fileURLWithPath: currentPath)
1116
+ try? FileManager.default.removeItem(at: currentUrl)
1117
+
1118
+ // Restore to the safe bundle
1119
+ DispatchQueue.main.async { [weak self] in
1120
+ guard let bridge = self?.plugin?.bridge else { return }
1121
+ bridge.setServerBasePath(safePath)
1122
+ bridge.webView?.reload()
1123
+ }
1124
+
1125
+ // Update stored path
1126
+ UserDefaults.standard.set(safePath, forKey: "native_update_webview_path")
1127
+ }
1128
+
1129
+ private func unsignedDevelopmentUpdatesAllowed() -> Bool {
1130
+ _isDebugAssertConfiguration() &&
1131
+ (config?["allowUnsignedDevelopmentUpdates"] as? Bool == true)
1132
+ }
1133
+ }
1134
+
1135
+ // MARK: - Data Models
1136
+
1137
+ public struct LatestVersion {
1138
+ public let available: Bool
1139
+ public let version: String?
1140
+
1141
+ public func toDictionary() -> [String: Any] {
1142
+ var obj: [String: Any] = [
1143
+ "available": available
1144
+ ]
1145
+
1146
+ if let version = version {
1147
+ obj["version"] = version
1148
+ }
1149
+
1150
+ return obj
1151
+ }
1152
+ }
1153
+
1154
+ // MARK: - Certificate Pinning Delegate
1155
+
1156
+ class CertificatePinningDelegate: NSObject, URLSessionDelegate {
1157
+ private let securityManager: SecurityManager
1158
+
1159
+ init(securityManager: SecurityManager) {
1160
+ self.securityManager = securityManager
1161
+ super.init()
1162
+ }
1163
+
1164
+ func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
1165
+ guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
1166
+ let serverTrust = challenge.protectionSpace.serverTrust else {
1167
+ completionHandler(.performDefaultHandling, nil)
1168
+ return
1169
+ }
1170
+
1171
+ // Get certificate pins from security manager configuration
1172
+ let certificatePins = getCertificatePins(for: challenge.protectionSpace.host)
1173
+
1174
+ if certificatePins.isEmpty {
1175
+ // No pins configured for this host, use default handling
1176
+ completionHandler(.performDefaultHandling, nil)
1177
+ return
1178
+ }
1179
+
1180
+ // Evaluate server trust
1181
+ var error: CFError?
1182
+ let isValid = SecTrustEvaluateWithError(serverTrust, &error)
1183
+
1184
+ if !isValid {
1185
+ print("Certificate validation failed: \(error?.localizedDescription ?? "Unknown error")")
1186
+ completionHandler(.cancelAuthenticationChallenge, nil)
1187
+ return
1188
+ }
1189
+
1190
+ // Check certificate pinning
1191
+ if validateCertificatePins(serverTrust: serverTrust, expectedPins: certificatePins) {
1192
+ let credential = URLCredential(trust: serverTrust)
1193
+ completionHandler(.useCredential, credential)
1194
+ } else {
1195
+ print("Certificate pinning validation failed for host: \(challenge.protectionSpace.host)")
1196
+ completionHandler(.cancelAuthenticationChallenge, nil)
1197
+ }
1198
+ }
1199
+
1200
+ private func getCertificatePins(for host: String) -> [String] {
1201
+ // Get pins from security manager configuration
1202
+ let securityInfo = securityManager.getSecurityInfo()
1203
+ guard let certificatePinning = securityInfo["certificatePinning"] as? [String: Any],
1204
+ certificatePinning["enabled"] as? Bool == true,
1205
+ let hostPins = certificatePinning["pins"] as? [String: [String]] else {
1206
+ return []
1207
+ }
1208
+
1209
+ // Return pins for the specific host
1210
+ return hostPins[host] ?? []
1211
+ }
1212
+
1213
+ private func validateCertificatePins(serverTrust: SecTrust, expectedPins: [String]) -> Bool {
1214
+ let certificateCount = SecTrustGetCertificateCount(serverTrust)
1215
+
1216
+ for i in 0..<certificateCount {
1217
+ guard let certificate = SecTrustGetCertificateAtIndex(serverTrust, i),
1218
+ let key = SecCertificateCopyKey(certificate),
1219
+ let spki = subjectPublicKeyInfo(for: key) else { continue }
1220
+
1221
+ let hash = spki.sha256()
1222
+ let pin = "sha256/" + hash.base64EncodedString()
1223
+
1224
+ if expectedPins.contains(pin) {
1225
+ return true
1226
+ }
1227
+ }
1228
+
1229
+ return false
1230
+ }
1231
+
1232
+ /** Build DER SubjectPublicKeyInfo so pins match OkHttp/curl/browser semantics. */
1233
+ private func subjectPublicKeyInfo(for key: SecKey) -> Data? {
1234
+ guard let attributes = SecKeyCopyAttributes(key) as? [CFString: Any],
1235
+ let keyType = attributes[kSecAttrKeyType],
1236
+ let bits = attributes[kSecAttrKeySizeInBits] as? Int,
1237
+ let rawKey = SecKeyCopyExternalRepresentation(key, nil) as Data? else { return nil }
1238
+
1239
+ let algorithm: Data
1240
+ if CFEqual(keyType as CFTypeRef, kSecAttrKeyTypeRSA) {
1241
+ algorithm = Data([0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
1242
+ 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00])
1243
+ } else if CFEqual(keyType as CFTypeRef, kSecAttrKeyTypeECSECPrimeRandom) {
1244
+ let curveOID: [UInt8]
1245
+ switch bits {
1246
+ case 256: curveOID = [0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]
1247
+ case 384: curveOID = [0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22]
1248
+ case 521: curveOID = [0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x23]
1249
+ default: return nil
1250
+ }
1251
+ algorithm = derSequence(Data([0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01]) + Data(curveOID))
1252
+ } else {
1253
+ return nil
1254
+ }
1255
+
1256
+ let bitString = Data([0x03]) + derLength(rawKey.count + 1) + Data([0x00]) + rawKey
1257
+ return derSequence(algorithm + bitString)
1258
+ }
1259
+
1260
+ private func derSequence(_ content: Data) -> Data {
1261
+ Data([0x30]) + derLength(content.count) + content
1262
+ }
1263
+
1264
+ private func derLength(_ length: Int) -> Data {
1265
+ if length < 128 { return Data([UInt8(length)]) }
1266
+ var value = length
1267
+ var bytes: [UInt8] = []
1268
+ while value > 0 {
1269
+ bytes.insert(UInt8(value & 0xff), at: 0)
1270
+ value >>= 8
1271
+ }
1272
+ return Data([0x80 | UInt8(bytes.count)] + bytes)
1273
+ }
1274
+ }
1275
+
1276
+ // MARK: - Data Extension for SHA256
1277
+
1278
+ extension Data {
1279
+ func sha256() -> Data {
1280
+ var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
1281
+ self.withUnsafeBytes { bytes in
1282
+ _ = CC_SHA256(bytes.baseAddress, CC_LONG(self.count), &hash)
1283
+ }
1284
+ return Data(hash)
1285
+ }
1286
+ }