native-update-capacitor 0.0.0-stage → 4.3.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 (139) 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/init.js +146 -0
  30. package/cli/commands/keys-generate.js +58 -0
  31. package/cli/commands/monitor.js +89 -0
  32. package/cli/commands/remote-shared.js +262 -0
  33. package/cli/commands/remote.js +622 -0
  34. package/cli/commands/server-start.js +96 -0
  35. package/cli/index.js +605 -0
  36. package/cli/package.json +21 -0
  37. package/dist/esm/app-review/app-review-manager.d.ts +24 -0
  38. package/dist/esm/app-review/app-review-manager.js +194 -0
  39. package/dist/esm/app-review/index.d.ts +5 -0
  40. package/dist/esm/app-review/index.js +5 -0
  41. package/dist/esm/app-review/platform-review-handler.d.ts +20 -0
  42. package/dist/esm/app-review/platform-review-handler.js +137 -0
  43. package/dist/esm/app-review/review-conditions-checker.d.ts +22 -0
  44. package/dist/esm/app-review/review-conditions-checker.js +154 -0
  45. package/dist/esm/app-review/review-rate-limiter.d.ts +23 -0
  46. package/dist/esm/app-review/review-rate-limiter.js +163 -0
  47. package/dist/esm/app-review/types.d.ts +41 -0
  48. package/dist/esm/app-review/types.js +1 -0
  49. package/dist/esm/app-update/app-update-checker.d.ts +58 -0
  50. package/dist/esm/app-update/app-update-checker.js +227 -0
  51. package/dist/esm/app-update/app-update-installer.d.ts +20 -0
  52. package/dist/esm/app-update/app-update-installer.js +134 -0
  53. package/dist/esm/app-update/app-update-manager.d.ts +28 -0
  54. package/dist/esm/app-update/app-update-manager.js +198 -0
  55. package/dist/esm/app-update/app-update-notifier.d.ts +14 -0
  56. package/dist/esm/app-update/app-update-notifier.js +99 -0
  57. package/dist/esm/app-update/index.d.ts +6 -0
  58. package/dist/esm/app-update/index.js +6 -0
  59. package/dist/esm/app-update/platform-app-update.d.ts +19 -0
  60. package/dist/esm/app-update/platform-app-update.js +138 -0
  61. package/dist/esm/app-update/types.d.ts +58 -0
  62. package/dist/esm/app-update/types.js +11 -0
  63. package/dist/esm/background-update/background-scheduler.d.ts +63 -0
  64. package/dist/esm/background-update/background-scheduler.js +332 -0
  65. package/dist/esm/background-update/index.d.ts +3 -0
  66. package/dist/esm/background-update/index.js +2 -0
  67. package/dist/esm/background-update/notification-manager.d.ts +29 -0
  68. package/dist/esm/background-update/notification-manager.js +88 -0
  69. package/dist/esm/config/support.d.ts +9 -0
  70. package/dist/esm/config/support.js +9 -0
  71. package/dist/esm/core/analytics.d.ts +83 -0
  72. package/dist/esm/core/analytics.js +151 -0
  73. package/dist/esm/core/cache-manager.d.ts +72 -0
  74. package/dist/esm/core/cache-manager.js +274 -0
  75. package/dist/esm/core/config.d.ts +69 -0
  76. package/dist/esm/core/config.js +107 -0
  77. package/dist/esm/core/errors.d.ts +56 -0
  78. package/dist/esm/core/errors.js +85 -0
  79. package/dist/esm/core/event-emitter.d.ts +30 -0
  80. package/dist/esm/core/event-emitter.js +80 -0
  81. package/dist/esm/core/logger.d.ts +21 -0
  82. package/dist/esm/core/logger.js +108 -0
  83. package/dist/esm/core/performance.d.ts +53 -0
  84. package/dist/esm/core/performance.js +153 -0
  85. package/dist/esm/core/plugin-manager.d.ts +88 -0
  86. package/dist/esm/core/plugin-manager.js +224 -0
  87. package/dist/esm/core/security.d.ts +123 -0
  88. package/dist/esm/core/security.js +361 -0
  89. package/dist/esm/core/update-check.d.ts +121 -0
  90. package/dist/esm/core/update-check.js +127 -0
  91. package/dist/esm/definitions.d.ts +872 -0
  92. package/dist/esm/definitions.js +104 -0
  93. package/dist/esm/index.d.ts +14 -0
  94. package/dist/esm/index.js +18 -0
  95. package/dist/esm/live-update/bundle-manager.d.ts +102 -0
  96. package/dist/esm/live-update/bundle-manager.js +344 -0
  97. package/dist/esm/live-update/certificate-pinning.d.ts +38 -0
  98. package/dist/esm/live-update/certificate-pinning.js +77 -0
  99. package/dist/esm/live-update/delta-processor.d.ts +84 -0
  100. package/dist/esm/live-update/delta-processor.js +257 -0
  101. package/dist/esm/live-update/download-manager.d.ts +106 -0
  102. package/dist/esm/live-update/download-manager.js +412 -0
  103. package/dist/esm/live-update/rollout-checker.d.ts +86 -0
  104. package/dist/esm/live-update/rollout-checker.js +304 -0
  105. package/dist/esm/live-update/update-manager.d.ts +63 -0
  106. package/dist/esm/live-update/update-manager.js +321 -0
  107. package/dist/esm/live-update/version-manager.d.ts +93 -0
  108. package/dist/esm/live-update/version-manager.js +390 -0
  109. package/dist/esm/plugin.d.ts +3 -0
  110. package/dist/esm/plugin.js +848 -0
  111. package/dist/esm/security/crypto.d.ts +88 -0
  112. package/dist/esm/security/crypto.js +228 -0
  113. package/dist/esm/security/validator.d.ts +60 -0
  114. package/dist/esm/security/validator.js +142 -0
  115. package/dist/esm/types/app-identity.d.ts +36 -0
  116. package/dist/esm/types/app-identity.js +1 -0
  117. package/dist/esm/types/rollout.d.ts +91 -0
  118. package/dist/esm/types/rollout.js +25 -0
  119. package/dist/esm/web.d.ts +130 -0
  120. package/dist/esm/web.js +981 -0
  121. package/dist/plugin.cjs +1 -0
  122. package/dist/plugin.esm.js +1 -0
  123. package/dist/plugin.js +2 -0
  124. package/docs/CHANGELOG.md +993 -0
  125. package/docs/KNOWN_LIMITATIONS.md +235 -0
  126. package/docs/MIGRATION.md +391 -0
  127. package/docs/protocol/CLIENT-PROTOCOL.md +178 -0
  128. package/docs/server-requirements.md +211 -0
  129. package/ios/Plugin/AppReview/AppReviewPlugin.swift +158 -0
  130. package/ios/Plugin/AppUpdate/AppUpdatePlugin.swift +249 -0
  131. package/ios/Plugin/BackgroundUpdate/BackgroundNotificationManager.swift +333 -0
  132. package/ios/Plugin/BackgroundUpdate/BackgroundUpdatePlugin.swift +464 -0
  133. package/ios/Plugin/Info.plist +43 -0
  134. package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +1286 -0
  135. package/ios/Plugin/LiveUpdate/WebViewConfiguration.swift +45 -0
  136. package/ios/Plugin/NativeUpdatePlugin.m +53 -0
  137. package/ios/Plugin/NativeUpdatePlugin.swift +315 -0
  138. package/ios/Plugin/Security/SecurityManager.swift +289 -0
  139. package/package.json +135 -4
@@ -0,0 +1,1249 @@
1
+ package com.aoneahsan.nativeupdate
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.content.pm.ApplicationInfo
6
+ import android.util.Base64
7
+ import com.getcapacitor.JSArray
8
+ import com.getcapacitor.JSObject
9
+ import com.getcapacitor.PluginCall
10
+ import kotlinx.coroutines.*
11
+ import okhttp3.*
12
+ import java.io.File
13
+ import java.io.FileOutputStream
14
+ import java.io.IOException
15
+ import java.security.MessageDigest
16
+ import java.util.concurrent.TimeUnit
17
+ import java.util.zip.ZipFile
18
+
19
+ class LiveUpdatePlugin(
20
+ private val activity: Activity,
21
+ private val context: Context
22
+ ) {
23
+ private var config: JSObject? = null
24
+ // Billing hold from the last update check (server says a release exists but is not served).
25
+ @Volatile private var lastHeld: JSObject? = null
26
+ /** Why the last update check could not complete, or null when it reached the server (ISSUE-14). */
27
+ @Volatile private var lastCheckError: String? = null
28
+ private var progressListener: ((JSObject) -> Unit)? = null
29
+ private var stateChangeListener: ((JSObject) -> Unit)? = null
30
+ /**
31
+ * Listener wired up by the parent Capacitor plugin to call
32
+ * `bridge.setServerBasePath(path)`. set() invokes it after a
33
+ * successful activation so the WebView re-targets at the new bundle.
34
+ */
35
+ private var webViewPathListener: ((String) -> Unit)? = null
36
+ private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
37
+ private lateinit var okHttpClient: OkHttpClient
38
+ private val securityManager = SecurityManager(context)
39
+ private val activeDownloads = java.util.concurrent.ConcurrentHashMap<String, Call>()
40
+
41
+ /** Hard cap on uncompressed bundle size (zip-bomb defense). */
42
+ private val maxUncompressedBundleBytes: Long
43
+ get() = config?.optLong("maxUncompressedBundleSize", 500L * 1024 * 1024)
44
+ ?.coerceIn(1L, 2L * 1024 * 1024 * 1024)
45
+ ?: 500L * 1024 * 1024
46
+
47
+ private val maxDownloadBytes: Long
48
+ get() = config?.optLong("maxBundleSize", 100L * 1024 * 1024)
49
+ ?.coerceIn(1L, 2L * 1024 * 1024 * 1024)
50
+ ?: 100L * 1024 * 1024
51
+
52
+ /**
53
+ * The app's signing-certificate fingerprints (SHA-256, SHA-1) as lowercase
54
+ * hex with no separators, computed once. Used for API-key client
55
+ * restrictions (the X-Android-Cert-* headers + getAppIdentity()). Null on
56
+ * any failure — identity is best-effort and must NEVER break an update check.
57
+ */
58
+ private val signingCertFingerprints: Pair<String?, String?> by lazy { computeSigningCertFingerprints() }
59
+ private val appSigningSha256: String? get() = signingCertFingerprints.first
60
+ private val appSigningSha1: String? get() = signingCertFingerprints.second
61
+
62
+ companion object {
63
+ /** This plugin's version, sent as X-Sdk-Version. Kept equal to package.json by tests/sdk-version.test.ts. */
64
+ const val SDK_VERSION = "4.3.0"
65
+
66
+ // SharedPreferences keys. Kept as constants so A2 (boot-time
67
+ // re-verification) and A3 (crash-loop auto-rollback) stay in sync
68
+ // with the call-sites in setActiveBundle / notifyAppReady.
69
+ private const val PREF_FILE = "native_update"
70
+ private const val ACTIVE_BUNDLE_KEY = "active_bundle"
71
+ private const val PREVIOUS_BUNDLE_KEY = "previous_active_bundle"
72
+ private const val PENDING_BUNDLE_KEY = "pending_verify_bundle"
73
+ private const val PENDING_ATTEMPTS_KEY = "pending_verify_attempts"
74
+ /** The native binary (versionCode:versionName) the active OTA bundle was activated on. */
75
+ private const val ACTIVE_BINARY_KEY = "active_bundle_binary"
76
+
77
+ // Activation of a new bundle is "pending" until JS calls
78
+ // notifyAppReady(). Each cold start before that bumps the counter.
79
+ // Two failed cold starts is a strong signal the bundle crashes
80
+ // the app, so we auto-rollback to the previous bundle on the
81
+ // second failure.
82
+ private const val MAX_PENDING_ATTEMPTS = 2
83
+ }
84
+
85
+ init {
86
+ // Initialize OkHttp with default settings
87
+ okHttpClient = createOkHttpClient()
88
+ }
89
+
90
+ private fun createOkHttpClient(): OkHttpClient {
91
+ val builder = OkHttpClient.Builder()
92
+ .connectTimeout(30, TimeUnit.SECONDS)
93
+ .readTimeout(30, TimeUnit.SECONDS)
94
+ .writeTimeout(30, TimeUnit.SECONDS)
95
+
96
+ // Configure certificate pinning if config is available
97
+ if (config != null) {
98
+ val certificatePinner = securityManager.getCertificatePinner()
99
+ if (certificatePinner != null) {
100
+ builder.certificatePinner(certificatePinner)
101
+ }
102
+ }
103
+
104
+ return builder.build()
105
+ }
106
+
107
+ fun configure(config: JSObject) {
108
+ this.config = config
109
+
110
+ // Configure security manager
111
+ securityManager.configure(config)
112
+
113
+ // Recreate OkHttpClient with new configuration
114
+ okHttpClient = createOkHttpClient()
115
+
116
+ // Validate configuration
117
+ val serverUrl = config.optString("serverUrl").takeIf { it.isNotBlank() }
118
+ if (serverUrl != null && !securityManager.validateUrl(serverUrl)) {
119
+ throw IllegalArgumentException("Server URL must be an allowed HTTPS URL")
120
+ }
121
+
122
+ val requireSignature = config.optBoolean("requireSignature", true)
123
+ if (requireSignature && config.optString("publicKey").isBlank()) {
124
+ throw IllegalArgumentException("publicKey is required when requireSignature is enabled")
125
+ }
126
+ if (!requireSignature && !unsignedDevelopmentUpdatesAllowed()) {
127
+ throw IllegalArgumentException(
128
+ "Unsigned updates are allowed only in debuggable builds with allowUnsignedDevelopmentUpdates enabled"
129
+ )
130
+ }
131
+ }
132
+
133
+ fun setProgressListener(listener: (JSObject) -> Unit) {
134
+ progressListener = listener
135
+ }
136
+
137
+ fun setStateChangeListener(listener: (JSObject) -> Unit) {
138
+ stateChangeListener = listener
139
+ }
140
+
141
+ fun setWebViewPathListener(listener: (String) -> Unit) {
142
+ webViewPathListener = listener
143
+ }
144
+
145
+ fun sync(call: PluginCall) {
146
+ scope.launch {
147
+ try {
148
+ val channel = call.getString("channel") ?: config?.getString("channel") ?: "production"
149
+ val serverUrl = config?.getString("serverUrl") ?: run {
150
+ call.reject("Server URL not configured")
151
+ return@launch
152
+ }
153
+
154
+ // Check for updates
155
+ val latestVersion = checkForUpdates(serverUrl, channel)
156
+
157
+ if (latestVersion != null) {
158
+ val result = JSObject()
159
+ result.put("status", "UPDATE_AVAILABLE")
160
+ result.put("version", latestVersion.getString("version"))
161
+ // v3 wire contract field (was the legacy "description")
162
+ result.put("description", latestVersion.getString("releaseNotes"))
163
+ result.put("mandatory", latestVersion.optBoolean("mandatory", false))
164
+ call.resolve(result)
165
+ } else {
166
+ val result = JSObject()
167
+ result.put("status", "UP_TO_DATE")
168
+ result.put("version", getCurrentVersion())
169
+ call.resolve(result)
170
+ }
171
+ } catch (e: Exception) {
172
+ val error = JSObject()
173
+ error.put("code", "NETWORK_ERROR")
174
+ error.put("message", e.message)
175
+
176
+ val result = JSObject()
177
+ result.put("status", "ERROR")
178
+ result.put("error", error)
179
+ call.resolve(result)
180
+ }
181
+ }
182
+ }
183
+
184
+ fun download(call: PluginCall) {
185
+ scope.launch {
186
+ val bundleId = "bundle-${System.currentTimeMillis()}"
187
+ val downloadDir = File(context.filesDir, "updates/$bundleId")
188
+ var success = false
189
+ try {
190
+ val url = call.getString("url") ?: run {
191
+ call.reject("URL is required")
192
+ return@launch
193
+ }
194
+
195
+ val version = call.getString("version") ?: run {
196
+ call.reject("Version is required")
197
+ return@launch
198
+ }
199
+
200
+ val checksum = call.getString("checksum") ?: run {
201
+ call.reject("Checksum is required")
202
+ return@launch
203
+ }
204
+
205
+ if (!securityManager.validateUrl(url)) {
206
+ call.reject("INSECURE_URL", "Download URL must be an allowed HTTPS URL")
207
+ return@launch
208
+ }
209
+
210
+ downloadDir.mkdirs()
211
+
212
+ val downloadedFile = tryApplyDelta(call, downloadDir, bundleId)
213
+ ?: downloadBundle(url, downloadDir, bundleId)
214
+
215
+ if (!verifyChecksum(downloadedFile, checksum)) {
216
+ call.reject("CHECKSUM_ERROR", "Bundle checksum validation failed")
217
+ return@launch
218
+ }
219
+
220
+ val signature = call.getString("signature")
221
+ val publicKey = config?.getString("publicKey")
222
+ val requireSignature = config?.getBool("requireSignature") ?: true
223
+ val signatureAlgorithm = call.getString("signatureAlgorithm") ?: "RSA-SHA256"
224
+ if (signatureAlgorithm != "RSA-SHA256") {
225
+ call.reject("SIGNATURE_ERROR", "Unsupported signature algorithm")
226
+ return@launch
227
+ }
228
+ if (requireSignature && signature.isNullOrBlank()) {
229
+ call.reject("SIGNATURE_ERROR", "Bundle signature is required")
230
+ return@launch
231
+ }
232
+ if (!signature.isNullOrBlank()) {
233
+ if (publicKey.isNullOrBlank() || !securityManager.verifySignature(downloadedFile, signature, publicKey)) {
234
+ call.reject("SIGNATURE_ERROR", "Bundle signature validation failed")
235
+ return@launch
236
+ }
237
+ }
238
+
239
+ // Extract zip into bundles/<id>/www/. Activation (i.e.
240
+ // pointing the WebView at it) is deferred to set() —
241
+ // matches iOS contract: download stages, set activates.
242
+ val extractedDir = File(downloadDir, "www")
243
+ try {
244
+ extractZipBundle(downloadedFile, extractedDir)
245
+ } catch (e: Exception) {
246
+ call.reject("EXTRACTION_ERROR", "Bundle extraction failed: ${e.message}")
247
+ return@launch
248
+ }
249
+
250
+ val bundleInfo = JSObject()
251
+ bundleInfo.put("bundleId", bundleId)
252
+ bundleInfo.put("version", version)
253
+ bundleInfo.put("path", downloadedFile.absolutePath)
254
+ bundleInfo.put("extractedPath", extractedDir.absolutePath)
255
+ bundleInfo.put("downloadTime", System.currentTimeMillis())
256
+ bundleInfo.put("size", downloadedFile.length())
257
+ bundleInfo.put("status", "READY")
258
+ bundleInfo.put("checksum", checksum)
259
+ bundleInfo.put("verified", true)
260
+ if (signature != null) {
261
+ bundleInfo.put("signature", signature)
262
+ bundleInfo.put("signatureAlgorithm", "RSA-SHA256")
263
+ }
264
+
265
+ saveBundleInfo(bundleInfo)
266
+
267
+ stateChangeListener?.invoke(JSObject().apply {
268
+ put("status", "READY")
269
+ put("bundleId", bundleId)
270
+ put("version", version)
271
+ })
272
+
273
+ success = true
274
+ call.resolve(bundleInfo)
275
+ } catch (e: Exception) {
276
+ call.reject("DOWNLOAD_ERROR", e.message)
277
+ } finally {
278
+ // On any failure, remove the per-bundle directory so we
279
+ // don't leak partial downloads/extractions.
280
+ if (!success) {
281
+ downloadDir.deleteRecursively()
282
+ }
283
+ }
284
+ }
285
+ }
286
+
287
+ fun set(call: PluginCall) {
288
+ val bundleId = call.getString("bundleId") ?: run {
289
+ call.reject("Bundle ID is required")
290
+ return
291
+ }
292
+
293
+ val bundleInfo = getBundleInfoById(bundleId) ?: run {
294
+ call.reject("Bundle not found: $bundleId")
295
+ return
296
+ }
297
+ val extractedPath = bundleInfo.optString("extractedPath", "")
298
+ if (extractedPath.isEmpty() || !File(extractedPath).exists()) {
299
+ call.reject("Bundle not extracted: $bundleId")
300
+ return
301
+ }
302
+ val verified = bundleInfo.optBoolean("verified", false)
303
+ if (!verified) {
304
+ call.reject("Refusing to activate unverified bundle: $bundleId")
305
+ return
306
+ }
307
+
308
+ setActiveBundle(bundleId)
309
+ persistWebViewBasePath(extractedPath)
310
+ // Hop to UI thread; setServerBasePath must run on the WebView's
311
+ // thread per Capacitor's Bridge contract.
312
+ activity.runOnUiThread {
313
+ webViewPathListener?.invoke(extractedPath)
314
+ }
315
+ call.resolve()
316
+ }
317
+
318
+ fun reload(call: PluginCall) {
319
+ // Re-applying the active bundle's serverBasePath causes the
320
+ // WebView to reload from the new asset root. activity.recreate()
321
+ // also works but is heavier and can drop transient state.
322
+ val activeBundleId = context
323
+ .getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
324
+ .getString(ACTIVE_BUNDLE_KEY, null)
325
+ if (activeBundleId != null) {
326
+ val info = getBundleInfoById(activeBundleId)
327
+ val extractedPath = info?.optString("extractedPath", "") ?: ""
328
+ if (extractedPath.isNotEmpty() && File(extractedPath).exists()) {
329
+ activity.runOnUiThread {
330
+ webViewPathListener?.invoke(extractedPath)
331
+ }
332
+ call.resolve()
333
+ return
334
+ }
335
+ }
336
+ activity.runOnUiThread {
337
+ activity.recreate()
338
+ }
339
+ call.resolve()
340
+ }
341
+
342
+ fun reset(call: PluginCall) {
343
+ // Reset to original bundle
344
+ clearAllBundles()
345
+ call.resolve()
346
+ }
347
+
348
+ fun current(call: PluginCall) {
349
+ val currentBundle = getCurrentBundleInfo()
350
+ call.resolve(currentBundle)
351
+ }
352
+
353
+ fun list(call: PluginCall) {
354
+ val bundles = getAllBundles()
355
+ val result = JSObject()
356
+ // JSArray, never the Kotlin List: org.json stringifies an unknown type, so JS received a STRING and
357
+ // every list()-based lookup (applyUpdate, the cached-bundle reuse) found nothing (ISSUE-15).
358
+ result.put("bundles", JSArray(bundles))
359
+ call.resolve(result)
360
+ }
361
+
362
+ fun delete(call: PluginCall) {
363
+ val bundleId = call.getString("bundleId")
364
+ if (bundleId != null) {
365
+ deleteBundle(bundleId)
366
+ } else {
367
+ val keepVersions = call.getInt("keepVersions")
368
+ if (keepVersions != null) {
369
+ cleanupOldBundles(keepVersions)
370
+ }
371
+ }
372
+ call.resolve()
373
+ }
374
+
375
+ fun notifyAppReady(call: PluginCall) {
376
+ // Mark current bundle as verified
377
+ markBundleAsVerified()
378
+ call.resolve()
379
+ }
380
+
381
+ fun getLatest(call: PluginCall) {
382
+ scope.launch {
383
+ try {
384
+ val serverUrl = config?.getString("serverUrl") ?: run {
385
+ call.reject("Server URL not configured")
386
+ return@launch
387
+ }
388
+
389
+ val channel = config?.getString("channel") ?: "production"
390
+ val latestVersion = checkForUpdates(serverUrl, channel)
391
+
392
+ if (latestVersion != null) {
393
+ val result = JSObject()
394
+ result.put("available", true)
395
+ result.put("version", latestVersion.getString("version"))
396
+ // v3 wire contract fields (legacy shape was url/notes)
397
+ result.put("url", latestVersion.getString("downloadUrl"))
398
+ result.put("notes", latestVersion.getString("releaseNotes"))
399
+ result.put("checksum", latestVersion.getString("checksum"))
400
+ latestVersion.optString("signature", "")
401
+ .takeIf { it.isNotEmpty() }
402
+ ?.let { result.put("signature", it) }
403
+ result.put("signatureAlgorithm", latestVersion.optString("signatureAlgorithm", "RSA-SHA256"))
404
+ latestVersion.optJSONObject("delta")?.let { result.put("delta", it) }
405
+ result.put("size", latestVersion.optLong("size", 0))
406
+ result.put("mandatory", latestVersion.optBoolean("mandatory", false))
407
+ call.resolve(result)
408
+ } else if (lastCheckError != null) {
409
+ // Same contract as the web path: a check that could not complete rejects NETWORK_ERROR.
410
+ call.reject(lastCheckError, "NETWORK_ERROR")
411
+ } else {
412
+ val result = JSObject()
413
+ result.put("available", false)
414
+ lastHeld?.let { held ->
415
+ result.put("held", true)
416
+ held.optString("version", "").takeIf { it.isNotEmpty() }?.let { result.put("version", it) }
417
+ held.optString("message", "").takeIf { it.isNotEmpty() }?.let { result.put("heldMessage", it) }
418
+ }
419
+ call.resolve(result)
420
+ }
421
+ } catch (e: Exception) {
422
+ call.reject("NETWORK_ERROR", e.message)
423
+ }
424
+ }
425
+ }
426
+
427
+ fun setChannel(call: PluginCall) {
428
+ val channel = call.getString("channel") ?: run {
429
+ call.reject("Channel is required")
430
+ return
431
+ }
432
+
433
+ config?.put("channel", channel)
434
+ call.resolve()
435
+ }
436
+
437
+ fun setUpdateUrl(call: PluginCall) {
438
+ call.getString("url") ?: run {
439
+ call.reject("URL is required")
440
+ return
441
+ }
442
+
443
+ android.util.Log.w("NativeUpdate", "setUpdateUrl() is deprecated and ignored; the update URL is locked after initialize()")
444
+ call.resolve()
445
+ }
446
+
447
+ fun validateUpdate(call: PluginCall) {
448
+ scope.launch {
449
+ try {
450
+ val bundlePath = call.getString("bundlePath") ?: run {
451
+ call.reject("Bundle path is required")
452
+ return@launch
453
+ }
454
+
455
+ val checksum = call.getString("checksum") ?: run {
456
+ call.reject("Checksum is required")
457
+ return@launch
458
+ }
459
+
460
+ val file = File(bundlePath)
461
+ val checksumValid = verifyChecksum(file, checksum)
462
+
463
+ val result = JSObject()
464
+ result.put("isValid", checksumValid)
465
+
466
+ val details = JSObject()
467
+ details.put("checksumValid", checksumValid)
468
+ result.put("details", details)
469
+
470
+ call.resolve(result)
471
+ } catch (e: Exception) {
472
+ call.reject("VALIDATION_ERROR", e.message)
473
+ }
474
+ }
475
+ }
476
+
477
+ fun cancelDownload(call: PluginCall) {
478
+ val bundleId = call.getString("bundleId") ?: run {
479
+ call.reject("Bundle ID is required")
480
+ return
481
+ }
482
+ activeDownloads.remove(bundleId)?.cancel()
483
+ call.resolve()
484
+ }
485
+
486
+ fun cancelAllDownloads(call: PluginCall) {
487
+ activeDownloads.values.forEach(Call::cancel)
488
+ activeDownloads.clear()
489
+ call.resolve()
490
+ }
491
+
492
+ fun isDownloading(call: PluginCall) {
493
+ val bundleId = call.getString("bundleId") ?: run {
494
+ call.reject("Bundle ID is required")
495
+ return
496
+ }
497
+ call.resolve(JSObject().put("isDownloading", activeDownloads.containsKey(bundleId)))
498
+ }
499
+
500
+ fun getActiveDownloadCount(call: PluginCall) {
501
+ call.resolve(JSObject().put("count", activeDownloads.size))
502
+ }
503
+
504
+ /**
505
+ * The app's client identity for API-key client restrictions: applicationId
506
+ * + signing-cert SHA-256/SHA-1. Consumed by the dashboard "Restrictions"
507
+ * UI and attached as X-Android-* headers on native update checks.
508
+ */
509
+ fun getAppIdentity(call: PluginCall) {
510
+ val result = JSObject()
511
+ result.put("platform", "android")
512
+ result.put("packageName", context.packageName)
513
+ appSigningSha256?.let { result.put("certSha256", it) }
514
+ appSigningSha1?.let { result.put("certSha1", it) }
515
+ call.resolve(result)
516
+ }
517
+
518
+ // Private helper methods
519
+
520
+ /**
521
+ * Read the app's first signing certificate and return (SHA-256, SHA-1) as
522
+ * lowercase hex, no separators. Uses GET_SIGNING_CERTIFICATES on API 28+
523
+ * (v2/v3 signing) and falls back to the deprecated GET_SIGNATURES on API
524
+ * 22–27. Any failure yields (null, null) — never throws.
525
+ */
526
+ private fun computeSigningCertFingerprints(): Pair<String?, String?> {
527
+ return try {
528
+ val pm = context.packageManager
529
+ val pkg = context.packageName
530
+ val certBytes: ByteArray? = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
531
+ val info = pm.getPackageInfo(pkg, android.content.pm.PackageManager.GET_SIGNING_CERTIFICATES)
532
+ info.signingInfo?.apkContentsSigners?.firstOrNull()?.toByteArray()
533
+ } else {
534
+ @Suppress("DEPRECATION")
535
+ val info = pm.getPackageInfo(pkg, android.content.pm.PackageManager.GET_SIGNATURES)
536
+ @Suppress("DEPRECATION")
537
+ info.signatures?.firstOrNull()?.toByteArray()
538
+ }
539
+ if (certBytes == null) {
540
+ Pair(null, null)
541
+ } else {
542
+ Pair(hashHex(certBytes, "SHA-256"), hashHex(certBytes, "SHA-1"))
543
+ }
544
+ } catch (e: Exception) {
545
+ Pair(null, null)
546
+ }
547
+ }
548
+
549
+ private fun hashHex(bytes: ByteArray, algorithm: String): String {
550
+ // `it.toInt() and 0xFF` is REQUIRED: a bare Byte sign-extends in
551
+ // "%02x".format (e.g. 0xFF → "ffffffff"), which would corrupt the
552
+ // fingerprint and break cert matching.
553
+ return MessageDigest.getInstance(algorithm).digest(bytes)
554
+ .joinToString("") { "%02x".format(it.toInt() and 0xFF) }
555
+ }
556
+
557
+ /**
558
+ * v3 wire contract (mirrors src/core/update-check.ts):
559
+ * GET {serverUrl}/v1/updates/check?channel={channel}
560
+ * Headers: X-API-Key, X-Device-ID, X-Current-Version, X-Platform
561
+ * (+ X-App-Version when the binary version is known)
562
+ * Returns the parsed response when a newer bundle is AVAILABLE, else
563
+ * null (covers "up to date", auth failures, and network errors —
564
+ * matching the TS helper's non-2xx => no-update behavior).
565
+ * Response fields consumed by callers: version, downloadUrl, checksum,
566
+ * signature, size, mandatory, releaseNotes.
567
+ */
568
+ private suspend fun checkForUpdates(serverUrl: String, channel: String): JSObject? {
569
+ return withContext(Dispatchers.IO) {
570
+ try {
571
+ val apiKey = config?.getString("apiKey")
572
+ if (apiKey.isNullOrEmpty()) {
573
+ android.util.Log.w(
574
+ "NativeUpdate",
575
+ "Update check skipped: no apiKey configured (pass it via initialize({ apiKey }) or configure({ liveUpdate: { apiKey } }))"
576
+ )
577
+ return@withContext null
578
+ }
579
+
580
+ val encodedChannel = java.net.URLEncoder.encode(channel, "UTF-8")
581
+ val requestBuilder = Request.Builder()
582
+ .url("${serverUrl.trimEnd('/')}/v1/updates/check?channel=$encodedChannel")
583
+ .header("X-API-Key", apiKey)
584
+ .header("X-Device-ID", getOrCreateDeviceId())
585
+ .header("X-Current-Version", getCurrentVersion())
586
+ .header("X-Platform", "android")
587
+ // SDK identity: the server offers this WebView only web bundles (docs/protocol/CLIENT-PROTOCOL.md).
588
+ .header("X-Client-Sdk", "capacitor")
589
+ .header("X-Sdk-Version", SDK_VERSION)
590
+ .header("X-Android-Package", context.packageName)
591
+ getBinaryVersion()?.let { requestBuilder.header("X-App-Version", it) }
592
+ // App-identity headers for API-key client restrictions. Best-effort:
593
+ // null fingerprints (e.g. odd signing setup) simply omit the header.
594
+ appSigningSha256?.let { requestBuilder.header("X-Android-Cert-Sha256", it) }
595
+ appSigningSha1?.let { requestBuilder.header("X-Android-Cert-Sha1", it) }
596
+
597
+ lastCheckError = null
598
+ val response = okHttpClient.newCall(requestBuilder.build()).execute()
599
+ if (response.isSuccessful) {
600
+ val body = response.body?.string()
601
+ val json = body?.let { JSObject(it) }
602
+ lastHeld = if (json != null && json.optBoolean("held", false)) json else null
603
+ if (json != null && json.optBoolean("available", false)) json else null
604
+ } else {
605
+ android.util.Log.w(
606
+ "NativeUpdate",
607
+ "Update check returned HTTP ${response.code}"
608
+ )
609
+ lastCheckError = "Update check returned HTTP ${response.code}"
610
+ null
611
+ }
612
+ } catch (e: Exception) {
613
+ // Never silent (ISSUE-14): a failed check must not read as "no update".
614
+ android.util.Log.w("NativeUpdate", "Update check failed: ${e.javaClass.simpleName}: ${e.message}")
615
+ lastCheckError = "${e.javaClass.simpleName}: ${e.message}"
616
+ null
617
+ }
618
+ }
619
+ }
620
+
621
+ private suspend fun downloadBundle(
622
+ url: String,
623
+ downloadDir: File,
624
+ bundleId: String,
625
+ filename: String = "bundle.zip"
626
+ ): File {
627
+ return withContext(Dispatchers.IO) {
628
+ val request = Request.Builder()
629
+ .url(url)
630
+ .build()
631
+
632
+ val networkCall = okHttpClient.newCall(request)
633
+ activeDownloads[bundleId] = networkCall
634
+ try {
635
+ networkCall.execute().use { response ->
636
+ if (!response.isSuccessful) throw IOException("Download failed: ${response.code}")
637
+
638
+ val file = File(downloadDir, filename)
639
+ val totalBytes = response.body.contentLength()
640
+ if (totalBytes > maxDownloadBytes) throw IOException("Bundle exceeds maximum download size")
641
+ var downloadedBytes = 0L
642
+
643
+ response.body.byteStream().use { input ->
644
+ FileOutputStream(file).use { output ->
645
+ val buffer = ByteArray(8192)
646
+ while (true) {
647
+ val read = input.read(buffer)
648
+ if (read < 0) break
649
+ output.write(buffer, 0, read)
650
+ downloadedBytes += read
651
+ if (downloadedBytes > maxDownloadBytes) {
652
+ throw IOException("Bundle exceeds maximum download size")
653
+ }
654
+ if (totalBytes > 0) {
655
+ progressListener?.invoke(JSObject().apply {
656
+ put("percent", ((downloadedBytes * 100) / totalBytes).toInt())
657
+ put("bytesDownloaded", downloadedBytes)
658
+ put("totalBytes", totalBytes)
659
+ put("bundleId", bundleId)
660
+ })
661
+ }
662
+ }
663
+ }
664
+ }
665
+ file
666
+ }
667
+ } finally {
668
+ activeDownloads.remove(bundleId)
669
+ }
670
+ }
671
+ }
672
+
673
+ private suspend fun tryApplyDelta(call: PluginCall, directory: File, bundleId: String): File? {
674
+ if (config?.optBoolean("enableDeltaUpdates", true) == false) return null
675
+ val delta = call.getObject("delta") ?: return null
676
+ if (delta.optString("format") != "NUDELTA/1" ||
677
+ delta.optString("fromVersion") != getCurrentVersion()) return null
678
+ return try {
679
+ val activeId = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
680
+ .getString(ACTIVE_BUNDLE_KEY, null) ?: return null
681
+ val basePath = getBundleInfoById(activeId)?.optString("path", "") ?: return null
682
+ val base = File(basePath)
683
+ if (!base.isFile) return null
684
+ val patchUrl = delta.getString("patchUrl") ?: return null
685
+ if (!securityManager.validateUrl(patchUrl)) return null
686
+ val patchChecksum = delta.getString("patchChecksum") ?: return null
687
+ val targetChecksum = delta.getString("targetChecksum") ?: return null
688
+ val patch = downloadBundle(patchUrl, directory, bundleId, "patch.nudelta.json")
689
+ if (!verifyChecksum(patch, patchChecksum)) return null
690
+ val document = JSObject(patch.readText(Charsets.UTF_8))
691
+ if (document.optString("format") != "NUDELTA/1" ||
692
+ document.optString("fromVersion") != delta.optString("fromVersion") ||
693
+ document.optString("targetChecksum") != targetChecksum ||
694
+ document.optString("baseChecksum").isBlank() ||
695
+ !verifyChecksum(base, document.optString("baseChecksum"))) return null
696
+ val targetSize = document.getLong("targetSize") ?: return null
697
+ if (targetSize <= 0 || targetSize > maxDownloadBytes) return null
698
+ val output = File(directory, "bundle.zip")
699
+ java.io.RandomAccessFile(base, "r").use { source ->
700
+ FileOutputStream(output).use { destination ->
701
+ var written = 0L
702
+ val operations = document.getJSONArray("operations") ?: return null
703
+ if (operations.length() == 0 || operations.length() > 100_000) return null
704
+ for (index in 0 until operations.length()) {
705
+ val operation = operations.getJSONObject(index)
706
+ when (operation.getString("op")) {
707
+ "copy" -> {
708
+ val offset = operation.getLong("offset")
709
+ val length = operation.getLong("length")
710
+ if (offset < 0 || length <= 0 || length > source.length() ||
711
+ offset > source.length() - length) return null
712
+ source.seek(offset)
713
+ var remaining = length
714
+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
715
+ while (remaining > 0) {
716
+ val read = source.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())
717
+ if (read <= 0) return null
718
+ destination.write(buffer, 0, read)
719
+ remaining -= read
720
+ }
721
+ written += length
722
+ }
723
+ "literal" -> {
724
+ val bytes = Base64.decode(operation.getString("data"), Base64.DEFAULT)
725
+ destination.write(bytes)
726
+ written += bytes.size
727
+ }
728
+ else -> return null
729
+ }
730
+ if (written > targetSize) return null
731
+ }
732
+ if (written != targetSize) return null
733
+ }
734
+ }
735
+ if (!verifyChecksum(output, targetChecksum)) {
736
+ output.delete()
737
+ null
738
+ } else {
739
+ patch.delete()
740
+ output
741
+ }
742
+ } catch (_: Exception) {
743
+ File(directory, "patch.nudelta.json").delete()
744
+ File(directory, "bundle.zip").delete()
745
+ null
746
+ }
747
+ }
748
+
749
+ /**
750
+ * Extract a zip into [destination] with three defenses applied:
751
+ * 1. Zip-Slip: every entry's resolved canonical path must stay
752
+ * inside [destination]. Catches `../` traversal.
753
+ * 2. Symlinks/special: entries that are not regular files or
754
+ * directories are skipped (no symlinks, devices, etc.).
755
+ * 3. Zip-bomb: total uncompressed size is capped.
756
+ *
757
+ * Mirrors `extractZipBundle` in `ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift`.
758
+ */
759
+ private fun extractZipBundle(zipFile: File, destination: File) {
760
+ if (!destination.exists()) {
761
+ destination.mkdirs()
762
+ }
763
+ val canonicalDest = destination.canonicalFile
764
+
765
+ ZipFile(zipFile).use { archive ->
766
+ // Pre-flight: reject the archive entirely if it would expand
767
+ // beyond our cap, before we write any bytes to disk.
768
+ var totalUncompressed = 0L
769
+ for (entry in archive.entries()) {
770
+ if (entry.size < 0) {
771
+ throw IOException("Zip entry has unknown uncompressed size: ${entry.name}")
772
+ }
773
+ totalUncompressed += entry.size
774
+ if (totalUncompressed > maxUncompressedBundleBytes) {
775
+ throw IOException(
776
+ "Bundle exceeds maximum uncompressed size " +
777
+ "($maxUncompressedBundleBytes bytes)"
778
+ )
779
+ }
780
+ }
781
+
782
+ for (entry in archive.entries()) {
783
+ // Reject entries with absolute paths or backreferences.
784
+ val name = entry.name
785
+ if (name.startsWith("/") || name.startsWith("\\") || name.contains("..")) {
786
+ throw IOException("Zip entry has unsafe path: $name")
787
+ }
788
+
789
+ val outFile = File(destination, name)
790
+ val canonicalOut = outFile.canonicalFile
791
+ if (!canonicalOut.path.startsWith(canonicalDest.path + File.separator)
792
+ && canonicalOut.path != canonicalDest.path
793
+ ) {
794
+ throw IOException("Zip-Slip detected: $name escapes ${canonicalDest.path}")
795
+ }
796
+
797
+ if (entry.isDirectory) {
798
+ if (!outFile.exists() && !outFile.mkdirs()) {
799
+ throw IOException("Failed to create directory ${outFile.path}")
800
+ }
801
+ continue
802
+ }
803
+
804
+ // Java's ZipFile API exposes only ZipEntry, which can't
805
+ // distinguish symlinks from regular files at this level.
806
+ // We treat every non-directory entry as a regular file.
807
+ // Symlinks created by `zip --symlinks` are NOT a concern
808
+ // because ZipFile reads the symlink target as the entry
809
+ // body — it won't follow it during extraction.
810
+ outFile.parentFile?.mkdirs()
811
+
812
+ archive.getInputStream(entry).use { input ->
813
+ FileOutputStream(outFile).use { output ->
814
+ val buffer = ByteArray(8192)
815
+ var read: Int
816
+ while (input.read(buffer).also { read = it } != -1) {
817
+ output.write(buffer, 0, read)
818
+ }
819
+ }
820
+ }
821
+ }
822
+ }
823
+ }
824
+
825
+ private fun verifyChecksum(file: File, expectedChecksum: String): Boolean {
826
+ val digest = MessageDigest.getInstance("SHA-256")
827
+ file.inputStream().use { input ->
828
+ val buffer = ByteArray(8192)
829
+ var read: Int
830
+ while (input.read(buffer).also { read = it } != -1) {
831
+ digest.update(buffer, 0, read)
832
+ }
833
+ }
834
+
835
+ val calculatedChecksum = digest.digest().joinToString("") { "%02x".format(it) }
836
+ return expectedChecksum.matches(Regex("^[a-fA-F0-9]{64}$")) &&
837
+ calculatedChecksum.equals(expectedChecksum, ignoreCase = true)
838
+ }
839
+
840
+ /**
841
+ * The version sent as X-Current-Version: the ACTIVE OTA bundle's
842
+ * version when one is applied, else the binary app version, else a
843
+ * conservative "1.0.0" (was previously hardcoded to "1.0.0" always).
844
+ */
845
+ private fun getCurrentVersion(): String {
846
+ try {
847
+ val activeId = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
848
+ .getString(ACTIVE_BUNDLE_KEY, null)
849
+ if (activeId != null) {
850
+ val bundleJson = context.getSharedPreferences("native_update_bundles", Context.MODE_PRIVATE)
851
+ .getString(activeId, null)
852
+ val version = bundleJson?.let { JSObject(it).getString("version") }
853
+ if (!version.isNullOrEmpty()) {
854
+ return version
855
+ }
856
+ }
857
+ } catch (e: Exception) {
858
+ // fall through to the binary version
859
+ }
860
+
861
+ return getBinaryVersion() ?: "1.0.0"
862
+ }
863
+
864
+ /** Native binary versionName (sent as X-App-Version). */
865
+ private fun getBinaryVersion(): String? {
866
+ return try {
867
+ context.packageManager.getPackageInfo(context.packageName, 0).versionName
868
+ } catch (e: Exception) {
869
+ null
870
+ }
871
+ }
872
+
873
+ /**
874
+ * Stable per-install device id (sent as X-Device-ID; the backend uses
875
+ * it for rollout bucketing). Minted once and persisted.
876
+ */
877
+ private fun getOrCreateDeviceId(): String {
878
+ val prefs = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
879
+ prefs.getString("device_id", null)?.let { return it }
880
+
881
+ val deviceId = java.util.UUID.randomUUID().toString()
882
+ prefs.edit().putString("device_id", deviceId).apply()
883
+ return deviceId
884
+ }
885
+
886
+ private fun saveBundleInfo(bundleInfo: JSObject) {
887
+ // Save bundle info to SharedPreferences or database
888
+ val prefs = context.getSharedPreferences("native_update_bundles", Context.MODE_PRIVATE)
889
+ val bundleId = bundleInfo.getString("bundleId")
890
+ prefs.edit().putString(bundleId, bundleInfo.toString()).apply()
891
+ }
892
+
893
+ private fun setActiveBundle(bundleId: String) {
894
+ val prefs = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
895
+ val currentActive = prefs.getString(ACTIVE_BUNDLE_KEY, null)
896
+ val editor = prefs.edit().putString(ACTIVE_BUNDLE_KEY, bundleId)
897
+
898
+ // Preserve the previous active bundle as a rollback target. Skip
899
+ // self-activation (setting to the same bundle) so we don't nuke
900
+ // a real previous-bundle pointer.
901
+ if (currentActive != null && currentActive != bundleId) {
902
+ editor.putString(PREVIOUS_BUNDLE_KEY, currentActive)
903
+ }
904
+
905
+ // Mark this activation as pending-verify. notifyAppReady() in the
906
+ // host app clears it; otherwise the next cold start increments the
907
+ // attempt counter and eventually triggers auto-rollback.
908
+ editor.putString(PENDING_BUNDLE_KEY, bundleId)
909
+ editor.putInt(PENDING_ATTEMPTS_KEY, 0)
910
+ binaryIdentity()?.let { editor.putString(ACTIVE_BINARY_KEY, it) }
911
+ editor.apply()
912
+ }
913
+
914
+ /** versionCode:versionName of the installed native binary, or null when it cannot be read. */
915
+ private fun binaryIdentity(): String? = try {
916
+ val info = context.packageManager.getPackageInfo(context.packageName, 0)
917
+ "${androidx.core.content.pm.PackageInfoCompat.getLongVersionCode(info)}:${info.versionName}"
918
+ } catch (_: Exception) {
919
+ null
920
+ }
921
+
922
+ /**
923
+ * Persist the WebView root where Capacitor itself reads it at cold start.
924
+ *
925
+ * 🔴 ISSUE-17: the bundle path set while plugins load is overwritten by Capacitor's `Bridge.loadWebView()`, which
926
+ * re-hosts the built-in assets and then restores ONLY `CapWebViewSettings → serverBasePath`. Without this write an
927
+ * applied bundle survived a reload but every cold start silently booted the built-in build again. Capacitor also
928
+ * clears that value itself when a new native binary is installed. An empty path means the built-in bundle.
929
+ */
930
+ private fun persistWebViewBasePath(path: String) {
931
+ context.getSharedPreferences(com.getcapacitor.plugin.WebView.WEBVIEW_PREFS_NAME, Context.MODE_PRIVATE)
932
+ .edit()
933
+ .putString(com.getcapacitor.plugin.WebView.CAP_SERVER_PATH, path)
934
+ .apply()
935
+ }
936
+
937
+ private fun clearAllBundles() {
938
+ val updateDir = File(context.filesDir, "updates")
939
+ updateDir.deleteRecursively()
940
+
941
+ val prefs = context.getSharedPreferences("native_update_bundles", Context.MODE_PRIVATE)
942
+ prefs.edit().clear().apply()
943
+
944
+ val activePrefs = context.getSharedPreferences("native_update", Context.MODE_PRIVATE)
945
+ activePrefs.edit().remove("active_bundle").apply()
946
+ persistWebViewBasePath("")
947
+ }
948
+
949
+ private fun getCurrentBundleInfo(): JSObject {
950
+ val prefs = context.getSharedPreferences("native_update", Context.MODE_PRIVATE)
951
+ val activeBundleId = prefs.getString("active_bundle", null)
952
+
953
+ if (activeBundleId != null) {
954
+ val bundlePrefs = context.getSharedPreferences("native_update_bundles", Context.MODE_PRIVATE)
955
+ val bundleData = bundlePrefs.getString(activeBundleId, null)
956
+ if (bundleData != null) {
957
+ return JSObject(bundleData)
958
+ }
959
+ }
960
+
961
+ // Return default bundle
962
+ return JSObject().apply {
963
+ put("bundleId", "default")
964
+ put("version", getBinaryVersion() ?: "1.0.0")
965
+ put("path", "/")
966
+ put("downloadTime", System.currentTimeMillis())
967
+ put("size", 0)
968
+ put("status", "ACTIVE")
969
+ put("checksum", "")
970
+ put("verified", true)
971
+ }
972
+ }
973
+
974
+ private fun getAllBundles(): List<JSObject> {
975
+ val prefs = context.getSharedPreferences("native_update_bundles", Context.MODE_PRIVATE)
976
+ return prefs.all.mapNotNull { entry ->
977
+ try {
978
+ JSObject(entry.value as String)
979
+ } catch (e: Exception) {
980
+ null
981
+ }
982
+ }
983
+ }
984
+
985
+ private fun deleteBundle(bundleId: String) {
986
+ // Delete bundle files
987
+ val bundleDir = File(context.filesDir, "updates/$bundleId")
988
+ bundleDir.deleteRecursively()
989
+
990
+ // Remove from preferences
991
+ val prefs = context.getSharedPreferences("native_update_bundles", Context.MODE_PRIVATE)
992
+ prefs.edit().remove(bundleId).apply()
993
+ }
994
+
995
+ private fun cleanupOldBundles(keepVersions: Int) {
996
+ // The active bundle, its rollback target and a pending activation are never deleted, whatever their age.
997
+ val protectedIds = protectedBundleIds()
998
+ val bundles = getAllBundles()
999
+ .filter { it.optString("bundleId", "") !in protectedIds }
1000
+ .sortedByDescending { it.optLong("downloadTime", 0) }
1001
+ bundles.drop(maxOf(0, keepVersions - protectedIds.size)).forEach { bundle ->
1002
+ bundle.optString("bundleId", "").takeIf { it.isNotEmpty() }?.let { deleteBundle(it) }
1003
+ }
1004
+ }
1005
+
1006
+ /** Bundles that must survive any cleanup: active, its rollback target, and one awaiting its first healthy boot. */
1007
+ private fun protectedBundleIds(): Set<String> {
1008
+ val prefs = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
1009
+ return listOfNotNull(
1010
+ prefs.getString(ACTIVE_BUNDLE_KEY, null),
1011
+ prefs.getString(PREVIOUS_BUNDLE_KEY, null),
1012
+ prefs.getString(PENDING_BUNDLE_KEY, null),
1013
+ ).filter { it != "default" }.toSet()
1014
+ }
1015
+
1016
+ /**
1017
+ * After a healthy boot, keep only what can still be used: the protected bundles plus the newest downloaded one
1018
+ * (it may be staged to switch at the next background). Every older bundle was a full copy of the app left on disk
1019
+ * forever (ISSUE-18: 246 MB after five test releases on one device).
1020
+ */
1021
+ private fun pruneUnusedBundles() {
1022
+ val protectedIds = protectedBundleIds()
1023
+ val activeVersion = getCurrentVersion()
1024
+ val others = getAllBundles().filter { it.optString("bundleId", "") !in protectedIds }
1025
+ // Only a bundle NEWER than the running one can still be switched to; anything else is dead weight.
1026
+ val staged = others
1027
+ .filter { compareVersions(it.optString("version", ""), activeVersion) > 0 }
1028
+ .maxByOrNull { it.optLong("downloadTime", 0) }
1029
+ others.filter { it !== staged }.forEach { bundle ->
1030
+ bundle.optString("bundleId", "").takeIf { it.isNotEmpty() }?.let { deleteBundle(it) }
1031
+ }
1032
+ }
1033
+
1034
+ /** Numeric dotted-version comparison (1.10.0 > 1.9.0); a pre-release or build suffix is ignored. */
1035
+ private fun compareVersions(left: String, right: String): Int {
1036
+ val a = left.substringBefore('-').substringBefore('+').split('.').map { it.toIntOrNull() ?: 0 }
1037
+ val b = right.substringBefore('-').substringBefore('+').split('.').map { it.toIntOrNull() ?: 0 }
1038
+ for (index in 0 until maxOf(a.size, b.size)) {
1039
+ val difference = (a.getOrNull(index) ?: 0) - (b.getOrNull(index) ?: 0)
1040
+ if (difference != 0) return difference
1041
+ }
1042
+ return 0
1043
+ }
1044
+
1045
+ fun cleanup() {
1046
+ // Clean up any resources
1047
+ // Cancel any ongoing downloads
1048
+ activeDownloads.values.forEach(Call::cancel)
1049
+ activeDownloads.clear()
1050
+ }
1051
+
1052
+ private fun markBundleAsVerified() {
1053
+ // notifyAppReady() is the host app's "I booted clean on this bundle"
1054
+ // signal. Clear the pending-verify state so cold starts after this
1055
+ // no longer count against the bundle.
1056
+ val prefs = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
1057
+ prefs.edit()
1058
+ .putBoolean("current_bundle_verified", true)
1059
+ .remove(PENDING_BUNDLE_KEY)
1060
+ .remove(PENDING_ATTEMPTS_KEY)
1061
+ .apply()
1062
+ try {
1063
+ pruneUnusedBundles()
1064
+ } catch (e: Exception) {
1065
+ // Housekeeping only: a failed prune never affects the running bundle.
1066
+ android.util.Log.w("NativeUpdate", "Bundle cleanup failed: ${e.javaClass.simpleName}: ${e.message}")
1067
+ }
1068
+ }
1069
+
1070
+ /**
1071
+ * Called from NativeUpdatePlugin.load() on every cold start. Runs two
1072
+ * independent defenses, both silent when no OTA bundle is active:
1073
+ *
1074
+ * A2 — re-hash the active bundle and verify it still matches the
1075
+ * checksum stored at install time. If signature + publicKey are
1076
+ * configured, also re-verify the signature. This catches on-disk
1077
+ * tampering on rooted devices.
1078
+ * A3 — if the active bundle was never confirmed by notifyAppReady()
1079
+ * on the previous launch, treat this cold start as a failed
1080
+ * boot. After MAX_PENDING_ATTEMPTS failures, rollback to the
1081
+ * previous known-good bundle to break the crash loop.
1082
+ *
1083
+ * On any failure the function rolls back and fires an
1084
+ * updateStateChanged event with status "ROLLBACK" so the host app and
1085
+ * analytics layer can observe it.
1086
+ */
1087
+ /**
1088
+ * Restore the WebView's serverBasePath from SharedPreferences so the
1089
+ * last-set bundle survives process death.
1090
+ */
1091
+ fun applyActiveBundlePathIfPresent() {
1092
+ val prefs = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
1093
+ val activeBundleId = prefs.getString(ACTIVE_BUNDLE_KEY, null) ?: return
1094
+ if (activeBundleId == "default") return
1095
+ // A bundle belongs to the native binary it was applied on. After a store update the new binary's own web
1096
+ // build wins (Capacitor already dropped the path), so the old bundle is retired rather than reported.
1097
+ val recordedBinary = prefs.getString(ACTIVE_BINARY_KEY, null)
1098
+ val binary = binaryIdentity()
1099
+ if (recordedBinary != null && binary != null && recordedBinary != binary) {
1100
+ prefs.edit()
1101
+ .remove(ACTIVE_BUNDLE_KEY)
1102
+ .remove(PREVIOUS_BUNDLE_KEY)
1103
+ .remove(PENDING_BUNDLE_KEY)
1104
+ .remove(PENDING_ATTEMPTS_KEY)
1105
+ .remove(ACTIVE_BINARY_KEY)
1106
+ .apply()
1107
+ persistWebViewBasePath("")
1108
+ return
1109
+ }
1110
+ val info = getBundleInfoById(activeBundleId) ?: return
1111
+ val extractedPath = info.optString("extractedPath", "")
1112
+ if (extractedPath.isEmpty()) return
1113
+ if (!File(extractedPath).exists()) return
1114
+ persistWebViewBasePath(extractedPath)
1115
+ activity.runOnUiThread {
1116
+ webViewPathListener?.invoke(extractedPath)
1117
+ }
1118
+ }
1119
+
1120
+ fun verifyActiveBundleOnBoot() {
1121
+ val prefs = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
1122
+
1123
+ // A3: crash-loop detection. If a bundle is still pending, this
1124
+ // cold start is counted against it.
1125
+ val pendingBundleId = prefs.getString(PENDING_BUNDLE_KEY, null)
1126
+ if (pendingBundleId != null) {
1127
+ val nextAttempt = prefs.getInt(PENDING_ATTEMPTS_KEY, 0) + 1
1128
+ if (nextAttempt > MAX_PENDING_ATTEMPTS) {
1129
+ rollbackToPrevious("auto-rollback after $nextAttempt failed cold starts", pendingBundleId)
1130
+ prefs.edit()
1131
+ .remove(PENDING_BUNDLE_KEY)
1132
+ .remove(PENDING_ATTEMPTS_KEY)
1133
+ .apply()
1134
+ return
1135
+ }
1136
+ prefs.edit().putInt(PENDING_ATTEMPTS_KEY, nextAttempt).apply()
1137
+ }
1138
+
1139
+ // A2: integrity re-verify. Only runs for non-default active bundles.
1140
+ val activeBundleId = prefs.getString(ACTIVE_BUNDLE_KEY, null) ?: return
1141
+ if (activeBundleId == "default") return
1142
+
1143
+ val bundleInfo = getBundleInfoById(activeBundleId) ?: run {
1144
+ rollbackToPrevious("active bundle info missing from preferences", activeBundleId)
1145
+ return
1146
+ }
1147
+
1148
+ val bundlePath = bundleInfo.optString("path", "")
1149
+ val expectedChecksum = bundleInfo.optString("checksum", "")
1150
+ if (bundlePath.isEmpty() || expectedChecksum.isEmpty()) return
1151
+
1152
+ val bundleFile = File(bundlePath)
1153
+ if (!bundleFile.exists()) {
1154
+ rollbackToPrevious("bundle file missing on disk", activeBundleId)
1155
+ return
1156
+ }
1157
+
1158
+ if (!verifyChecksum(bundleFile, expectedChecksum)) {
1159
+ rollbackToPrevious("bundle checksum mismatch on boot", activeBundleId)
1160
+ return
1161
+ }
1162
+
1163
+ val signature = bundleInfo.optString("signature", "")
1164
+ if (signature.isNotEmpty()) {
1165
+ val publicKey = config?.getString("publicKey")
1166
+ if (!publicKey.isNullOrEmpty()) {
1167
+ if (!securityManager.verifySignature(bundleFile, signature, publicKey)) {
1168
+ rollbackToPrevious("bundle signature mismatch on boot", activeBundleId)
1169
+ return
1170
+ }
1171
+ }
1172
+ }
1173
+ }
1174
+
1175
+ private fun unsignedDevelopmentUpdatesAllowed(): Boolean {
1176
+ val debuggable = context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
1177
+ return debuggable && config?.optBoolean("allowUnsignedDevelopmentUpdates", false) == true
1178
+ }
1179
+
1180
+ private fun rollbackToPrevious(reason: String, fromBundleId: String) {
1181
+ val prefs = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
1182
+ val previous = prefs.getString(PREVIOUS_BUNDLE_KEY, null)
1183
+ val editor = prefs.edit()
1184
+ if (previous != null) {
1185
+ editor.putString(ACTIVE_BUNDLE_KEY, previous)
1186
+ } else {
1187
+ editor.remove(ACTIVE_BUNDLE_KEY)
1188
+ }
1189
+ editor.remove(PREVIOUS_BUNDLE_KEY).apply()
1190
+ val rolledBackPath = previous?.let { getBundleInfoById(it)?.optString("extractedPath", "") }
1191
+ ?.takeIf { it.isNotEmpty() && File(it).exists() }
1192
+ persistWebViewBasePath(rolledBackPath ?: "")
1193
+
1194
+ // Re-point the WebView at whatever we rolled back to. If we
1195
+ // rolled all the way back to the bundled-in www/ (no previous
1196
+ // OTA bundle), no listener call is needed — Capacitor's default
1197
+ // serverBasePath is already correct.
1198
+ if (previous != null) {
1199
+ val info = getBundleInfoById(previous)
1200
+ val extractedPath = info?.optString("extractedPath", "") ?: ""
1201
+ if (extractedPath.isNotEmpty() && File(extractedPath).exists()) {
1202
+ activity.runOnUiThread {
1203
+ webViewPathListener?.invoke(extractedPath)
1204
+ }
1205
+ }
1206
+ }
1207
+
1208
+ stateChangeListener?.invoke(JSObject().apply {
1209
+ put("status", "ROLLBACK")
1210
+ put("bundleId", fromBundleId)
1211
+ put("rolledBackTo", previous ?: "default")
1212
+ put("reason", reason)
1213
+ })
1214
+ }
1215
+
1216
+ private fun getBundleInfoById(bundleId: String): JSObject? {
1217
+ val prefs = context.getSharedPreferences("native_update_bundles", Context.MODE_PRIVATE)
1218
+ val raw = prefs.getString(bundleId, null) ?: return null
1219
+ return try {
1220
+ JSObject(raw)
1221
+ } catch (e: Exception) {
1222
+ null
1223
+ }
1224
+ }
1225
+
1226
+ // Async method for background update checks
1227
+ suspend fun getLatestVersionAsync(): LatestVersion? {
1228
+ return try {
1229
+ val serverUrl = config?.getString("serverUrl") ?: return null
1230
+ val channel = config?.getString("channel") ?: "production"
1231
+
1232
+ val latestVersion = checkForUpdates(serverUrl, channel)
1233
+
1234
+ if (latestVersion != null) {
1235
+ LatestVersion(
1236
+ available = true,
1237
+ version = latestVersion.getString("version")
1238
+ )
1239
+ } else {
1240
+ LatestVersion(
1241
+ available = false,
1242
+ version = null
1243
+ )
1244
+ }
1245
+ } catch (e: Exception) {
1246
+ null
1247
+ }
1248
+ }
1249
+ }