native-update 4.2.3 → 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.
package/README.md CHANGED
@@ -28,7 +28,7 @@ are available as an HTTP API for CI and coding agents.
28
28
 
29
29
  | | |
30
30
  |---|---|
31
- | **Version** | `4.2.3` |
31
+ | **Version** | `4.3.0` |
32
32
  | **License** | Proprietary — free to use in your apps ([LICENSE](./LICENSE)) |
33
33
  | **Node** | `>=24.16.0` (install + CLI toolchain) |
34
34
  | **Platforms** | iOS 14+ · Android 8.0+ (API 26) · Web |
@@ -513,10 +513,9 @@ indexed at [`/raw/manifest.json`](https://nativeupdate-docs.aoneahsan.com/raw/ma
513
513
  <a id="changelog"></a>
514
514
  ## 🔄 Changelog&nbsp;[#](#changelog)
515
515
 
516
- Latest release: **`4.2.3`**, a maintenance release with no API change. The release CLI moves to
517
- commander 15, and the bundles are rebuilt with current build tools on Node 26.13.1 LTS. The package still
518
- supports Capacitor 8, Node.js 24.16+ and Android API 26+. The release before it made every Capacitor
519
- package external, so no plugin registers twice in your app.
516
+ Latest release: **`4.3.0`**. Every update check now says which SDK is asking (`X-Client-Sdk: capacitor`) and its
517
+ version, so the server only ever offers a Capacitor app a web bundle, never a native asset set built for another
518
+ platform. No API change; 4.2.4's Android fixes are included.
520
519
 
521
520
  Full history ships inside the package at `docs/CHANGELOG.md`, so it always matches the version you
522
521
  installed. It is also published as the
@@ -45,6 +45,7 @@ class AppReviewPlugin(
45
45
  if (!canRequestResult.first) {
46
46
  val result = JSObject()
47
47
  result.put("shown", false)
48
+ result.put("displayed", false)
48
49
  result.put("error", canRequestResult.second)
49
50
  call.resolve(result)
50
51
  return
@@ -60,6 +61,7 @@ class AppReviewPlugin(
60
61
  } else {
61
62
  val result = JSObject()
62
63
  result.put("shown", false)
64
+ result.put("displayed", false)
63
65
  result.put("error", "Failed to request review flow")
64
66
  call.resolve(result)
65
67
  }
@@ -71,6 +73,8 @@ class AppReviewPlugin(
71
73
 
72
74
  val result = JSObject()
73
75
  result.put("allowed", allowed)
76
+ // The typed name (CanRequestReviewResult.canRequest); "allowed" stays for one minor release (ISSUE-11).
77
+ result.put("canRequest", allowed)
74
78
  if (!allowed) {
75
79
  result.put("reason", reason)
76
80
  }
@@ -93,10 +97,12 @@ class AppReviewPlugin(
93
97
 
94
98
  val result = JSObject()
95
99
  result.put("shown", true)
100
+ result.put("displayed", true)
96
101
  call.resolve(result)
97
102
  }.addOnFailureListener { e ->
98
103
  val result = JSObject()
99
104
  result.put("shown", false)
105
+ result.put("displayed", false)
100
106
  result.put("error", e.message)
101
107
  call.resolve(result)
102
108
  }
@@ -195,9 +195,9 @@ data class BackgroundUpdateConfig(
195
195
  ) {
196
196
  companion object {
197
197
  fun fromJSObject(obj: JSObject): BackgroundUpdateConfig {
198
- val enabled = obj.getBoolean("enabled") ?: false
199
- val checkInterval = obj.getInt("checkInterval") ?: (24 * 60 * 60 * 1000)
200
- val updateTypesArray = obj.getJSONArray("updateTypes")
198
+ val enabled = obj.boolOrNull("enabled") ?: false
199
+ val checkInterval = obj.intOrNull("checkInterval") ?: (24 * 60 * 60 * 1000)
200
+ val updateTypesArray = obj.arrayOrNull("updateTypes") ?: org.json.JSONArray()
201
201
  val updateTypes = mutableListOf<BackgroundUpdateType>()
202
202
 
203
203
  for (i in 0 until updateTypesArray.length()) {
@@ -211,14 +211,14 @@ data class BackgroundUpdateConfig(
211
211
  enabled = enabled,
212
212
  checkInterval = checkInterval,
213
213
  updateTypes = updateTypes,
214
- autoInstall = obj.getBoolean("autoInstall") ?: false,
214
+ autoInstall = obj.boolOrNull("autoInstall") ?: false,
215
215
  notificationPreferences = notificationPrefs?.let { NotificationPreferences.fromJSObject(it) },
216
- respectBatteryOptimization = obj.getBoolean("respectBatteryOptimization") ?: true,
217
- allowMeteredConnection = obj.getBoolean("allowMeteredConnection") ?: false,
218
- minimumBatteryLevel = obj.getInt("minimumBatteryLevel") ?: 20,
219
- requireWifi = obj.getBoolean("requireWifi") ?: false,
220
- maxRetries = obj.getInt("maxRetries") ?: 3,
221
- retryDelay = obj.getInt("retryDelay") ?: 5000,
216
+ respectBatteryOptimization = obj.boolOrNull("respectBatteryOptimization") ?: true,
217
+ allowMeteredConnection = obj.boolOrNull("allowMeteredConnection") ?: false,
218
+ minimumBatteryLevel = obj.intOrNull("minimumBatteryLevel") ?: 20,
219
+ requireWifi = obj.boolOrNull("requireWifi") ?: false,
220
+ maxRetries = obj.intOrNull("maxRetries") ?: 3,
221
+ retryDelay = obj.intOrNull("retryDelay") ?: 5000,
222
222
  taskIdentifier = obj.getString("taskIdentifier")
223
223
  )
224
224
  }
@@ -0,0 +1,26 @@
1
+ package com.aoneahsan.nativeupdate
2
+
3
+ import org.json.JSONArray
4
+ import org.json.JSONObject
5
+
6
+ /*
7
+ * Null-safe reads for OPTIONAL configuration fields.
8
+ *
9
+ * Capacitor's JSObject overrides getString/getInteger/getBool/getJSObject to return null for a missing key, but
10
+ * getLong, getInt, getBoolean and getJSONArray are org.json's and THROW JSONException instead. A `?.let` or `?:`
11
+ * after them compiles and reads as optional, yet a consumer that simply omits the field gets a failed configure()
12
+ * and OTA switched off (ISSUE-14: every flat-config consumer that left out maxBundleSize). Optional fields are read
13
+ * only through these helpers.
14
+ */
15
+
16
+ /** The field as a Long, or null when it is absent, JSON null or not a number. */
17
+ internal fun JSONObject.longOrNull(name: String): Long? = (opt(name) as? Number)?.toLong()
18
+
19
+ /** The field as an Int, or null when it is absent, JSON null or not a number. */
20
+ internal fun JSONObject.intOrNull(name: String): Int? = (opt(name) as? Number)?.toInt()
21
+
22
+ /** The field as a Boolean, or null when it is absent, JSON null or not a boolean. */
23
+ internal fun JSONObject.boolOrNull(name: String): Boolean? = opt(name) as? Boolean
24
+
25
+ /** The field as a JSONArray, or null when it is absent or not an array. */
26
+ internal fun JSONObject.arrayOrNull(name: String): JSONArray? = optJSONArray(name)
@@ -4,6 +4,7 @@ import android.app.Activity
4
4
  import android.content.Context
5
5
  import android.content.pm.ApplicationInfo
6
6
  import android.util.Base64
7
+ import com.getcapacitor.JSArray
7
8
  import com.getcapacitor.JSObject
8
9
  import com.getcapacitor.PluginCall
9
10
  import kotlinx.coroutines.*
@@ -22,6 +23,8 @@ class LiveUpdatePlugin(
22
23
  private var config: JSObject? = null
23
24
  // Billing hold from the last update check (server says a release exists but is not served).
24
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
25
28
  private var progressListener: ((JSObject) -> Unit)? = null
26
29
  private var stateChangeListener: ((JSObject) -> Unit)? = null
27
30
  /**
@@ -57,6 +60,9 @@ class LiveUpdatePlugin(
57
60
  private val appSigningSha1: String? get() = signingCertFingerprints.second
58
61
 
59
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
+
60
66
  // SharedPreferences keys. Kept as constants so A2 (boot-time
61
67
  // re-verification) and A3 (crash-loop auto-rollback) stay in sync
62
68
  // with the call-sites in setActiveBundle / notifyAppReady.
@@ -65,6 +71,8 @@ class LiveUpdatePlugin(
65
71
  private const val PREVIOUS_BUNDLE_KEY = "previous_active_bundle"
66
72
  private const val PENDING_BUNDLE_KEY = "pending_verify_bundle"
67
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"
68
76
 
69
77
  // Activation of a new bundle is "pending" until JS calls
70
78
  // notifyAppReady(). Each cold start before that bumps the counter.
@@ -298,6 +306,7 @@ class LiveUpdatePlugin(
298
306
  }
299
307
 
300
308
  setActiveBundle(bundleId)
309
+ persistWebViewBasePath(extractedPath)
301
310
  // Hop to UI thread; setServerBasePath must run on the WebView's
302
311
  // thread per Capacitor's Bridge contract.
303
312
  activity.runOnUiThread {
@@ -344,7 +353,9 @@ class LiveUpdatePlugin(
344
353
  fun list(call: PluginCall) {
345
354
  val bundles = getAllBundles()
346
355
  val result = JSObject()
347
- result.put("bundles", bundles)
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))
348
359
  call.resolve(result)
349
360
  }
350
361
 
@@ -394,6 +405,9 @@ class LiveUpdatePlugin(
394
405
  result.put("size", latestVersion.optLong("size", 0))
395
406
  result.put("mandatory", latestVersion.optBoolean("mandatory", false))
396
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")
397
411
  } else {
398
412
  val result = JSObject()
399
413
  result.put("available", false)
@@ -570,6 +584,9 @@ class LiveUpdatePlugin(
570
584
  .header("X-Device-ID", getOrCreateDeviceId())
571
585
  .header("X-Current-Version", getCurrentVersion())
572
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)
573
590
  .header("X-Android-Package", context.packageName)
574
591
  getBinaryVersion()?.let { requestBuilder.header("X-App-Version", it) }
575
592
  // App-identity headers for API-key client restrictions. Best-effort:
@@ -577,6 +594,7 @@ class LiveUpdatePlugin(
577
594
  appSigningSha256?.let { requestBuilder.header("X-Android-Cert-Sha256", it) }
578
595
  appSigningSha1?.let { requestBuilder.header("X-Android-Cert-Sha1", it) }
579
596
 
597
+ lastCheckError = null
580
598
  val response = okHttpClient.newCall(requestBuilder.build()).execute()
581
599
  if (response.isSuccessful) {
582
600
  val body = response.body?.string()
@@ -586,11 +604,15 @@ class LiveUpdatePlugin(
586
604
  } else {
587
605
  android.util.Log.w(
588
606
  "NativeUpdate",
589
- "Update check returned HTTP ${response.code} — treating as no update"
607
+ "Update check returned HTTP ${response.code}"
590
608
  )
609
+ lastCheckError = "Update check returned HTTP ${response.code}"
591
610
  null
592
611
  }
593
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}"
594
616
  null
595
617
  }
596
618
  }
@@ -885,9 +907,33 @@ class LiveUpdatePlugin(
885
907
  // attempt counter and eventually triggers auto-rollback.
886
908
  editor.putString(PENDING_BUNDLE_KEY, bundleId)
887
909
  editor.putInt(PENDING_ATTEMPTS_KEY, 0)
910
+ binaryIdentity()?.let { editor.putString(ACTIVE_BINARY_KEY, it) }
888
911
  editor.apply()
889
912
  }
890
-
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
+
891
937
  private fun clearAllBundles() {
892
938
  val updateDir = File(context.filesDir, "updates")
893
939
  updateDir.deleteRecursively()
@@ -897,6 +943,7 @@ class LiveUpdatePlugin(
897
943
 
898
944
  val activePrefs = context.getSharedPreferences("native_update", Context.MODE_PRIVATE)
899
945
  activePrefs.edit().remove("active_bundle").apply()
946
+ persistWebViewBasePath("")
900
947
  }
901
948
 
902
949
  private fun getCurrentBundleInfo(): JSObject {
@@ -946,13 +993,54 @@ class LiveUpdatePlugin(
946
993
  }
947
994
 
948
995
  private fun cleanupOldBundles(keepVersions: Int) {
949
- val bundles = getAllBundles().sortedByDescending { it.getLong("downloadTime") }
950
- if (bundles.size > keepVersions) {
951
- bundles.drop(keepVersions).forEach { bundle ->
952
- bundle.getString("bundleId")?.let { deleteBundle(it) }
953
- }
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) }
954
1003
  }
955
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
+ }
956
1044
 
957
1045
  fun cleanup() {
958
1046
  // Clean up any resources
@@ -971,6 +1059,12 @@ class LiveUpdatePlugin(
971
1059
  .remove(PENDING_BUNDLE_KEY)
972
1060
  .remove(PENDING_ATTEMPTS_KEY)
973
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
+ }
974
1068
  }
975
1069
 
976
1070
  /**
@@ -995,14 +1089,29 @@ class LiveUpdatePlugin(
995
1089
  * last-set bundle survives process death.
996
1090
  */
997
1091
  fun applyActiveBundlePathIfPresent() {
998
- val activeBundleId = context
999
- .getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
1000
- .getString(ACTIVE_BUNDLE_KEY, null) ?: return
1092
+ val prefs = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
1093
+ val activeBundleId = prefs.getString(ACTIVE_BUNDLE_KEY, null) ?: return
1001
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
+ }
1002
1110
  val info = getBundleInfoById(activeBundleId) ?: return
1003
1111
  val extractedPath = info.optString("extractedPath", "")
1004
1112
  if (extractedPath.isEmpty()) return
1005
1113
  if (!File(extractedPath).exists()) return
1114
+ persistWebViewBasePath(extractedPath)
1006
1115
  activity.runOnUiThread {
1007
1116
  webViewPathListener?.invoke(extractedPath)
1008
1117
  }
@@ -1078,6 +1187,9 @@ class LiveUpdatePlugin(
1078
1187
  editor.remove(ACTIVE_BUNDLE_KEY)
1079
1188
  }
1080
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 ?: "")
1081
1193
 
1082
1194
  // Re-point the WebView at whatever we rolled back to. If we
1083
1195
  // rolled all the way back to the bundled-in www/ (no previous
@@ -18,6 +18,9 @@ class NativeUpdatePlugin : Plugin() {
18
18
  private lateinit var backgroundUpdatePlugin: BackgroundUpdatePlugin
19
19
  private lateinit var securityManager: SecurityManager
20
20
  private var isInitialized = false
21
+
22
+ /** The configuration that took the lock, so an identical repeat can be told apart from a change (ISSUE-16). */
23
+ private var appliedConfiguration: String? = null
21
24
 
22
25
  override fun load() {
23
26
  super.load()
@@ -80,12 +83,13 @@ class NativeUpdatePlugin : Plugin() {
80
83
  @PluginMethod
81
84
  fun initialize(call: PluginCall) {
82
85
  try {
86
+ val config = call.getObject("config") ?: call.data
83
87
  if (isInitialized) {
84
- call.reject("Configuration is locked after initialization; call reset() first")
88
+ rejectUnlessSameConfiguration(call, config)
85
89
  return
86
90
  }
87
- val config = call.getObject("config") ?: call.data
88
91
  applyConfiguration(config)
92
+ appliedConfiguration = configurationFingerprint(config)
89
93
  isInitialized = true
90
94
  call.resolve()
91
95
  } catch (e: Exception) {
@@ -118,14 +122,15 @@ class NativeUpdatePlugin : Plugin() {
118
122
  // configure(UpdateConfig) — nested sections
119
123
  // Before this fix, only the wrapped shape reached native, so the
120
124
  // flat initialize() every consumer uses configured NOTHING here.
125
+ val config = call.getObject("config") ?: call.data
121
126
  if (isInitialized) {
122
- call.reject("Configuration is locked after initialization; call reset() first")
127
+ rejectUnlessSameConfiguration(call, config)
123
128
  return
124
129
  }
125
- val config = call.getObject("config") ?: call.data
126
130
 
127
131
  try {
128
132
  applyConfiguration(config)
133
+ appliedConfiguration = configurationFingerprint(config)
129
134
  isInitialized = true
130
135
  call.resolve()
131
136
  } catch (e: Exception) {
@@ -133,6 +138,22 @@ class NativeUpdatePlugin : Plugin() {
133
138
  }
134
139
  }
135
140
 
141
+ /**
142
+ * The lock refuses a CHANGED configuration only. An OTA apply reloads the WebView while this plugin instance
143
+ * lives on, so the new bundle's boot sends the same configure() again; rejecting it switched OTA off in every
144
+ * freshly applied bundle and skipped its notifyAppReady() (ISSUE-16).
145
+ */
146
+ private fun rejectUnlessSameConfiguration(call: PluginCall, config: JSObject) {
147
+ if (configurationFingerprint(config) == appliedConfiguration) {
148
+ call.resolve()
149
+ } else {
150
+ call.reject("Configuration is locked after initialization; call reset() first")
151
+ }
152
+ }
153
+
154
+ /** A stable comparison form; injected JS objects (filesystem, preferences) arrive as {} and compare equal. */
155
+ private fun configurationFingerprint(config: JSObject): String = config.toString()
156
+
136
157
  private fun applyConfiguration(config: JSObject) {
137
158
  securityManager.configure(config)
138
159
  normalizeLiveUpdateConfig(config)?.let(liveUpdatePlugin::configure)
@@ -164,12 +185,12 @@ class NativeUpdatePlugin : Plugin() {
164
185
  liveUpdate.put("allowUnsignedDevelopmentUpdates", it)
165
186
  }
166
187
  config.getString("checksumAlgorithm")?.let { liveUpdate.put("checksumAlgorithm", it) }
167
- config.getLong("maxBundleSize")?.let { liveUpdate.put("maxBundleSize", it) }
168
- config.getLong("maxUncompressedBundleSize")?.let {
188
+ config.longOrNull("maxBundleSize")?.let { liveUpdate.put("maxBundleSize", it) }
189
+ config.longOrNull("maxUncompressedBundleSize")?.let {
169
190
  liveUpdate.put("maxUncompressedBundleSize", it)
170
191
  }
171
192
  config.getBool("enableDeltaUpdates")?.let { liveUpdate.put("enableDeltaUpdates", it) }
172
- config.getJSONArray("allowedHosts")?.let { liveUpdate.put("allowedHosts", it) }
193
+ config.arrayOrNull("allowedHosts")?.let { liveUpdate.put("allowedHosts", it) }
173
194
  config.getJSObject("security")?.let { liveUpdate.put("security", it) }
174
195
  return liveUpdate
175
196
  }
@@ -192,7 +213,7 @@ class NativeUpdatePlugin : Plugin() {
192
213
  }
193
214
  }
194
215
  if (!liveUpdate.has("maxUncompressedBundleSize")) {
195
- config.getLong("maxUncompressedBundleSize")?.let {
216
+ config.longOrNull("maxUncompressedBundleSize")?.let {
196
217
  liveUpdate.put("maxUncompressedBundleSize", it)
197
218
  }
198
219
  }
@@ -236,6 +257,7 @@ class NativeUpdatePlugin : Plugin() {
236
257
  // Reset plugin state
237
258
  liveUpdatePlugin.reset(call)
238
259
  isInitialized = false
260
+ appliedConfiguration = null
239
261
  } catch (e: Exception) {
240
262
  call.reject("Reset failed", e)
241
263
  }
@@ -5,6 +5,7 @@ import android.net.Uri
5
5
  import android.security.keystore.KeyGenParameterSpec
6
6
  import android.security.keystore.KeyProperties
7
7
  import android.util.Base64
8
+ import com.getcapacitor.JSArray
8
9
  import com.getcapacitor.JSObject
9
10
  import okhttp3.CertificatePinner
10
11
  import java.io.File
@@ -42,7 +43,7 @@ class SecurityManager(private val context: Context) {
42
43
 
43
44
  val pinning = security?.takeIf { it.has("certificatePinning") }?.getJSObject("certificatePinning")
44
45
  if (pinning?.getBool("enabled") == true) {
45
- val pins = pinning.getJSONArray("pins")
46
+ val pins = pinning.arrayOrNull("pins")
46
47
  require(pins != null && pins.length() > 0) {
47
48
  "Certificate pinning requires at least one host pin"
48
49
  }
@@ -73,17 +74,17 @@ class SecurityManager(private val context: Context) {
73
74
  val pinningConfig = security?.takeIf { it.has("certificatePinning") }?.getJSObject("certificatePinning")
74
75
  certificatePinning.put("enabled", pinningConfig?.getBool("enabled") ?: false)
75
76
  val pins = mutableListOf<JSObject>()
76
- val pinsArray = pinningConfig?.getJSONArray("pins")
77
+ val pinsArray = pinningConfig?.arrayOrNull("pins")
77
78
  if (pinsArray != null) {
78
79
  for (index in 0 until pinsArray.length()) {
79
80
  val pin = pinsArray.getJSONObject(index)
80
81
  pins.add(JSObject().apply {
81
82
  put("hostname", pin.getString("hostname"))
82
- put("sha256", pin.getJSONArray("sha256"))
83
+ put("sha256", pin.arrayOrNull("sha256") ?: org.json.JSONArray())
83
84
  })
84
85
  }
85
86
  }
86
- certificatePinning.put("pins", pins.toTypedArray())
87
+ certificatePinning.put("pins", JSArray(pins))
87
88
  result.put("certificatePinning", certificatePinning)
88
89
  result.put("validateInputs", security?.optBoolean("validateInputs", true) ?: true)
89
90
  result.put("secureStorage", true)
@@ -107,12 +108,12 @@ class SecurityManager(private val context: Context) {
107
108
  fun getCertificatePinner(): CertificatePinner? {
108
109
  val pinning = securityConfig()?.getJSObject("certificatePinning") ?: return null
109
110
  if (pinning.getBool("enabled") != true) return null
110
- val pins = pinning.getJSONArray("pins") ?: return null
111
+ val pins = pinning.arrayOrNull("pins") ?: return null
111
112
  val builder = CertificatePinner.Builder()
112
113
  for (index in 0 until pins.length()) {
113
114
  val pin = pins.getJSONObject(index)
114
115
  val hostname = pin.getString("hostname") ?: continue
115
- val hashes = pin.getJSONArray("sha256") ?: continue
116
+ val hashes = pin.arrayOrNull("sha256") ?: continue
116
117
  for (hashIndex in 0 until hashes.length()) {
117
118
  builder.add(hostname, hashes.getString(hashIndex))
118
119
  }
@@ -100,7 +100,14 @@ export async function deploy(target, options) {
100
100
  console.log(chalk.gray(` Signed: yes (${signature.source})`));
101
101
  }
102
102
 
103
+ const payloadType = options.payloadType ?? 'web_bundle';
104
+ if (!['web_bundle', 'assets'].includes(payloadType)) {
105
+ throw new Error(`--payload-type must be web_bundle or assets, not "${payloadType}"`);
106
+ }
107
+ console.log(chalk.gray(` Payload: ${payloadType}`));
108
+
103
109
  const { data } = await client.upload(`/apps/${options.app}/builds`, bundle.path, {
110
+ payload_type: payloadType,
104
111
  version,
105
112
  channel: options.channel,
106
113
  release_notes: options.notes,
package/cli/index.js CHANGED
@@ -234,6 +234,11 @@ ${chalk.bold('Examples:')}
234
234
  .option('-n, --notes <text>', 'Release notes')
235
235
  .option('-r, --rollout <percent>', 'Initial rollout percentage (1-100)')
236
236
  .option('--min-native <version>', 'Minimum native app version required')
237
+ .option(
238
+ '--payload-type <type>',
239
+ 'web_bundle (Capacitor / React Native code) or assets (files a native Android or Flutter app reads)',
240
+ 'web_bundle'
241
+ )
237
242
  .option('--signature <file>', 'Detached signature from `bundle sign` (auto-detects a sibling .sig)')
238
243
  .option('-w, --wait', 'Wait for processing to finish (exit non-zero if it fails)', false)
239
244
  ).action(async (target, options) => {
@@ -18,6 +18,8 @@
18
18
  * X-Current-Version: the currently-installed bundle version
19
19
  * X-Platform: ios | android | web
20
20
  * X-App-Version: native app version (optional)
21
+ * X-Client-Sdk: capacitor (the server then offers only `web_bundle` builds)
22
+ * X-Sdk-Version: this plugin's version (SDK_VERSION)
21
23
  * X-Android-Package: applicationId (optional; sent when identity.platform === 'android')
22
24
  * X-Android-Cert-Sha256: signing cert SHA-256, hex (optional)
23
25
  * X-Android-Cert-Sha1: signing cert SHA-1, hex (optional)
@@ -54,6 +56,11 @@
54
56
  * `docs/server-requirements.md`.
55
57
  */
56
58
  import type { AppIdentity } from '../types/app-identity';
59
+ /**
60
+ * This plugin's version, sent as `X-Sdk-Version`. Kept equal to package.json (and to the Kotlin and Swift
61
+ * constants) by tests/sdk-version.test.ts.
62
+ */
63
+ export declare const SDK_VERSION = "4.3.0";
57
64
  /** Request inputs for a single backend update check. */
58
65
  export interface UpdateCheckRequest {
59
66
  /** API key issued by the dashboard; sent as `X-API-Key`. Required. */
@@ -96,6 +103,8 @@ export interface BackendUpdateCheckResponse {
96
103
  releaseNotes?: string | null;
97
104
  minNativeVersion?: string | null;
98
105
  expiresAt?: string;
106
+ /** `web_bundle` for every build this client is offered (the server filters by X-Client-Sdk). */
107
+ payloadType?: 'web_bundle' | 'assets';
99
108
  message?: string;
100
109
  /** Billing hold: a newer release exists but is not served (see `CheckForUpdateResult.held`). */
101
110
  held?: boolean;
@@ -18,6 +18,8 @@
18
18
  * X-Current-Version: the currently-installed bundle version
19
19
  * X-Platform: ios | android | web
20
20
  * X-App-Version: native app version (optional)
21
+ * X-Client-Sdk: capacitor (the server then offers only `web_bundle` builds)
22
+ * X-Sdk-Version: this plugin's version (SDK_VERSION)
21
23
  * X-Android-Package: applicationId (optional; sent when identity.platform === 'android')
22
24
  * X-Android-Cert-Sha256: signing cert SHA-256, hex (optional)
23
25
  * X-Android-Cert-Sha1: signing cert SHA-1, hex (optional)
@@ -53,6 +55,11 @@
53
55
  * Custom backends must return these exact field names — see
54
56
  * `docs/server-requirements.md`.
55
57
  */
58
+ /**
59
+ * This plugin's version, sent as `X-Sdk-Version`. Kept equal to package.json (and to the Kotlin and Swift
60
+ * constants) by tests/sdk-version.test.ts.
61
+ */
62
+ export const SDK_VERSION = '4.3.0';
56
63
  /**
57
64
  * Perform one update check against the Native Update backend.
58
65
  *
@@ -70,6 +77,8 @@ export async function checkForUpdate(baseUrl, req) {
70
77
  'X-Device-ID': req.deviceId,
71
78
  'X-Current-Version': req.currentVersion,
72
79
  'X-Platform': req.platform,
80
+ 'X-Client-Sdk': 'capacitor',
81
+ 'X-Sdk-Version': SDK_VERSION,
73
82
  };
74
83
  if (req.appVersion) {
75
84
  headers['X-App-Version'] = req.appVersion;
@@ -110,6 +119,7 @@ export async function checkForUpdate(baseUrl, req) {
110
119
  releaseNotes: (_d = data.releaseNotes) !== null && _d !== void 0 ? _d : undefined,
111
120
  minNativeVersion: (_e = data.minNativeVersion) !== null && _e !== void 0 ? _e : undefined,
112
121
  expiresAt: data.expiresAt,
122
+ payloadType: data.payloadType,
113
123
  message: data.message,
114
124
  held: data.held === true ? true : undefined,
115
125
  code: data.code,