@capgo/capacitor-updater 9.0.1 → 9.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/README.md +106 -81
  2. package/android/build.gradle +1 -3
  3. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +513 -21
  4. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +675 -34
  5. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +82 -10
  6. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +23 -0
  7. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +188 -4
  8. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +81 -1
  9. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +72 -21
  10. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +5 -1
  11. package/dist/docs.json +13 -13
  12. package/dist/esm/definitions.d.ts +57 -23
  13. package/dist/esm/definitions.js.map +1 -1
  14. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1278 -107
  15. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +38 -0
  16. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +583 -56
  17. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +8 -1
  18. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +6 -1
  19. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +2705 -77
  20. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +9 -4
  21. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +67 -2
  22. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +130 -5
  23. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +22 -8
  24. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +4 -0
  25. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +19 -3
  26. package/package.json +2 -2
@@ -159,7 +159,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
159
159
  static final int APPLICATION_EXIT_REASON_USER_REQUESTED = 10;
160
160
  static final int APPLICATION_EXIT_REASON_DEPENDENCY_DIED = 12;
161
161
 
162
- static final String PLUGIN_VERSION = "9.0.1";
162
+ static final String PLUGIN_VERSION = "9.0.2";
163
163
  // Set while a plugin instance (with its bridge) runs in this process. The headless update
164
164
  // check then leaves installing to that instance instead of swapping bundles under it.
165
165
  static final Object INSTANCE_LOADED_LOCK = new Object();
@@ -876,9 +876,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
876
876
  @Override
877
877
  public void notifyListeners(final String id, final Map<String, Object> res) {
878
878
  if (activity != null) {
879
- activity.runOnUiThread(() -> {
880
- CapacitorUpdaterPlugin.this.notifyListeners(id, InternalUtils.mapToJSObject(res), false);
881
- });
879
+ activity.runOnUiThread(() -> CapacitorUpdaterPlugin.this.emitCoreEvent(id, res));
882
880
  } else {
883
881
  logger.warn("notifyListeners: Activity is null, skipping notification for event: " + id);
884
882
  }
@@ -2697,6 +2695,20 @@ public class CapacitorUpdaterPlugin extends Plugin {
2697
2695
  return SHAKE_MENU_GESTURE_SHAKE.equals(normalized) || SHAKE_MENU_GESTURE_THREE_FINGER_PINCH.equals(normalized);
2698
2696
  }
2699
2697
 
2698
+ /**
2699
+ * Events from the updater core that wait for a listener. In onlyDownload mode the app applies a fresh download
2700
+ * itself, so its updateAvailable must reach a listener that attaches later (as on iOS and the already-downloaded
2701
+ * path). Every other core event is delivered only to current listeners.
2702
+ */
2703
+ /** Forwards an event raised by {@link CapgoUpdater}, retaining it when {@link #retainsUpdaterEvent} says so. */
2704
+ void emitCoreEvent(final String eventName, final Map<String, Object> res) {
2705
+ this.notifyListeners(eventName, InternalUtils.mapToJSObject(res), this.retainsUpdaterEvent(eventName));
2706
+ }
2707
+
2708
+ boolean retainsUpdaterEvent(final String eventName) {
2709
+ return "updateAvailable".equals(eventName) && AUTO_UPDATE_MODE_ONLY_DOWNLOAD.equals(this.autoUpdateMode);
2710
+ }
2711
+
2700
2712
  static String directUpdateModeForAutoUpdateMode(final String autoUpdateMode) {
2701
2713
  switch (autoUpdateMode) {
2702
2714
  case AUTO_UPDATE_MODE_INSTALL:
@@ -2793,6 +2805,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
2793
2805
  return this.onLaunchDirectUpdateUsed;
2794
2806
  }
2795
2807
 
2808
+ boolean shouldRetryIncompleteDownloadForTesting(final BundleInfo bundle, final String latestVersionName, final BundleInfo current) {
2809
+ return this.shouldRetryIncompleteDownload(bundle, latestVersionName, current);
2810
+ }
2811
+
2796
2812
  boolean isVersionDownloadInProgress(final String version) {
2797
2813
  return (
2798
2814
  version != null &&
@@ -2803,6 +2819,119 @@ public class CapacitorUpdaterPlugin extends Plugin {
2803
2819
  );
2804
2820
  }
2805
2821
 
2822
+ private BundleInfo preferredAutoUpdateBundle(final BundleInfo existing, final String latestVersionName) {
2823
+ if (existing == null) {
2824
+ return null;
2825
+ }
2826
+ final BundleInfo queued = this.implementation.getNextBundle();
2827
+ if (
2828
+ queued != null &&
2829
+ latestVersionName.equals(queued.getVersionName()) &&
2830
+ !existing.getId().equals(queued.getId()) &&
2831
+ !queued.isDeleted() &&
2832
+ !queued.isDeleting() &&
2833
+ (!existing.isErrorStatus() || this.isInstallableBundle(queued))
2834
+ ) {
2835
+ // A failed row keeps its ERROR stop unless the queued same-version bundle is itself installable.
2836
+ return queued;
2837
+ }
2838
+ if (existing.isDeleted() || existing.isDeleting()) {
2839
+ return null;
2840
+ }
2841
+ return existing;
2842
+ }
2843
+
2844
+ private boolean isInstallableBundle(final BundleInfo bundle) {
2845
+ return (
2846
+ bundle.isDownloaded() &&
2847
+ !bundle.isErrorStatus() &&
2848
+ BundleStatus.DOWNLOADING != bundle.getStatus() &&
2849
+ this.implementation.isBundleOnDisk(bundle.getId())
2850
+ );
2851
+ }
2852
+
2853
+ private boolean shouldRetryIncompleteDownload(final BundleInfo bundle, final String latestVersionName, final BundleInfo current) {
2854
+ if (
2855
+ bundle != null &&
2856
+ BundleStatus.DOWNLOADING != bundle.getStatus() &&
2857
+ this.implementation.isVersionDownloadActive(latestVersionName)
2858
+ ) {
2859
+ // Another live download (e.g. a manual download()) owns this version: deleting the old row would
2860
+ // run a version-wide cancel and kill it.
2861
+ return false;
2862
+ }
2863
+ if (
2864
+ bundle != null &&
2865
+ BundleStatus.DOWNLOADING == bundle.getStatus() &&
2866
+ this.isVersionDownloadInProgress(latestVersionName) &&
2867
+ !this.implementation.isInterruptedDownloadBundle(bundle.getId())
2868
+ ) {
2869
+ return false;
2870
+ }
2871
+ if (bundle != null && BundleStatus.DOWNLOADING == bundle.getStatus()) {
2872
+ if (!this.implementation.isInterruptedDownloadBundle(bundle.getId())) {
2873
+ return false;
2874
+ }
2875
+ }
2876
+ final BundleInfo next = this.implementation.getNextBundle();
2877
+ if (
2878
+ bundle != null &&
2879
+ (bundle.isDeleted() || bundle.isDeleting()) &&
2880
+ next != null &&
2881
+ latestVersionName.equals(next.getVersionName()) &&
2882
+ !bundle.getId().equals(next.getId()) &&
2883
+ !next.isDeleted() &&
2884
+ !next.isDeleting()
2885
+ ) {
2886
+ return false;
2887
+ }
2888
+ if (
2889
+ bundle != null &&
2890
+ bundle.isDownloaded() &&
2891
+ BundleStatus.DOWNLOADING != bundle.getStatus() &&
2892
+ !bundle.isErrorStatus() &&
2893
+ this.implementation.isBundleOnDisk(bundle.getId())
2894
+ ) {
2895
+ return false;
2896
+ }
2897
+ if (bundle != null && (bundle.isDeleted() || bundle.isDeleting())) {
2898
+ if (this.isVersionDownloadInProgress(latestVersionName)) {
2899
+ return false;
2900
+ }
2901
+ final BundleInfo liveSameVersion = this.implementation.findRegistryBundleByVersionName(latestVersionName);
2902
+ if (
2903
+ liveSameVersion != null &&
2904
+ !liveSameVersion.getId().equals(bundle.getId()) &&
2905
+ !liveSameVersion.isDeleted() &&
2906
+ !liveSameVersion.isDeleting()
2907
+ ) {
2908
+ return false;
2909
+ }
2910
+ if (
2911
+ !this.implementation.isInterruptedDownloadBundle(bundle.getId()) &&
2912
+ this.implementation.incompleteDownloadRetryCount(latestVersionName) == 0
2913
+ ) {
2914
+ return false;
2915
+ }
2916
+ }
2917
+ final boolean isQueuedNext = bundle != null && next != null && bundle.getId().equals(next.getId());
2918
+ final boolean isCurrent =
2919
+ bundle != null &&
2920
+ bundle.getId().equals(current.getId()) &&
2921
+ BundleStatus.SUCCESS == current.getStatus() &&
2922
+ latestVersionName.equals(current.getVersionName());
2923
+ final boolean interrupted = bundle != null && this.implementation.isInterruptedDownloadBundle(bundle.getId());
2924
+ return CapgoUpdater.shouldRetryDownloadForExistingBundle(
2925
+ bundle,
2926
+ bundle != null && this.implementation.isBundleOnDisk(bundle.getId()),
2927
+ this.implementation.incompleteDownloadRetryCount(latestVersionName),
2928
+ this.implementation.isIntegrityBlockedVersion(latestVersionName),
2929
+ interrupted,
2930
+ isCurrent,
2931
+ isQueuedNext
2932
+ );
2933
+ }
2934
+
2806
2935
  void setLoggerForTesting(final Logger logger) {
2807
2936
  this.logger = logger;
2808
2937
  }
@@ -3122,6 +3251,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
3122
3251
  this.implementation.cleanupOrphanedManifestStagingFolders(null);
3123
3252
 
3124
3253
  this.persistCurrentNativeBuildVersion();
3254
+ if (this.implementation != null) {
3255
+ this.implementation.reconcileInterruptedDownloadsOnLaunch();
3256
+ }
3125
3257
  } catch (Exception e) {
3126
3258
  logger.error("Error during cleanupObsoleteVersions: " + e.getMessage());
3127
3259
  } finally {
@@ -4388,7 +4520,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
4388
4520
  }
4389
4521
 
4390
4522
  private boolean leavePreviewSessionWithoutReload(final boolean keepPreviewGuard) {
4391
- final BundleInfo previewFallbackBundle = this.resolvePreviewFallbackBundle("preview deeplink launch");
4523
+ // Launch-time routing: the startup version floor runs afterwards and reports a below-native fallback.
4524
+ final BundleInfo previewFallbackBundle = this.resolvePreviewFallbackBundle("preview deeplink launch", false);
4392
4525
  if (previewFallbackBundle == null) {
4393
4526
  return false;
4394
4527
  }
@@ -4441,8 +4574,15 @@ public class CapacitorUpdaterPlugin extends Plugin {
4441
4574
  }
4442
4575
 
4443
4576
  private BundleInfo resolvePreviewFallbackBundle(final String reason) {
4577
+ return this.resolvePreviewFallbackBundle(reason, true);
4578
+ }
4579
+
4580
+ private BundleInfo resolvePreviewFallbackBundle(final String reason, final boolean enforceVersionFloor) {
4444
4581
  final BundleInfo fallback = this.implementation.getPreviewFallbackBundle();
4445
- if (fallback != null && !fallback.isErrorStatus() && this.implementation.canSet(fallback)) {
4582
+ final boolean usable = fallback != null && !fallback.isErrorStatus() && this.implementation.canSet(fallback);
4583
+ // A native upgrade during preview can leave the fallback below the version floor; never reactivate it.
4584
+ final boolean meetsFloor = usable && (!enforceVersionFloor || this.fallbackMeetsVersionFloor(fallback));
4585
+ if (meetsFloor) {
4446
4586
  return fallback;
4447
4587
  }
4448
4588
 
@@ -4450,6 +4590,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
4450
4590
  logger.warn("No preview fallback bundle available for " + reason + ". Falling back to builtin bundle.");
4451
4591
  } else if (fallback.isErrorStatus()) {
4452
4592
  logger.warn("Preview fallback bundle is in error state for " + reason + ". Falling back to builtin bundle.");
4593
+ } else if (usable) {
4594
+ logger.warn("Preview fallback bundle is below the native version for " + reason + ". Falling back to builtin bundle.");
4453
4595
  } else {
4454
4596
  logger.warn("Preview fallback bundle is not installable for " + reason + ". Falling back to builtin bundle.");
4455
4597
  }
@@ -4463,6 +4605,18 @@ public class CapacitorUpdaterPlugin extends Plugin {
4463
4605
  return null;
4464
4606
  }
4465
4607
 
4608
+ boolean fallbackMeetsVersionFloor(final BundleInfo fallback) {
4609
+ if (fallback.isBuiltin()) {
4610
+ return true;
4611
+ }
4612
+ try {
4613
+ this.implementation.requireVersionNotBelowBuiltin(fallback.getVersionName());
4614
+ return true;
4615
+ } catch (IOException e) {
4616
+ return false;
4617
+ }
4618
+ }
4619
+
4466
4620
  private void endPreviewSession() {
4467
4621
  this.endPreviewSession(false);
4468
4622
  }
@@ -5107,6 +5261,14 @@ public class CapacitorUpdaterPlugin extends Plugin {
5107
5261
  logger.error("Pending bundle is not installable");
5108
5262
  return false;
5109
5263
  }
5264
+ if (!pending.isBuiltin()) {
5265
+ try {
5266
+ this.implementation.requireVersionNotBelowBuiltin(pending.getVersionName());
5267
+ } catch (IOException e) {
5268
+ logger.error(e.getMessage());
5269
+ return false;
5270
+ }
5271
+ }
5110
5272
  this.implementation.prepareResetStateForTransition();
5111
5273
  logger.info("Resetting to pending bundle: " + pending.getVersionName());
5112
5274
  final boolean didApplyPendingBundle;
@@ -5144,7 +5306,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
5144
5306
  }
5145
5307
 
5146
5308
  if (Boolean.TRUE.equals(toLastSuccessful) && !fallback.isBuiltin()) {
5147
- if (this.implementation.canSet(fallback)) {
5309
+ // A last successful bundle below the native version floor cannot be activated: use builtin instead.
5310
+ if (this.implementation.canSet(fallback) && this.fallbackMeetsVersionFloor(fallback)) {
5148
5311
  this.implementation.prepareResetStateForTransition();
5149
5312
  logger.info("Resetting to: " + fallback);
5150
5313
  if (this.implementation.set(fallback)) {
@@ -5903,8 +6066,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
5903
6066
  if (!this.ownsBackgroundDownload(downloadContext)) {
5904
6067
  return false;
5905
6068
  }
5906
- // Admit delivery before another thread can replace this check's ownership.
5907
- this.notifyListeners(event, data, false);
6069
+ // Admit delivery before another thread can replace this check's ownership. noNeedUpdate is retained like
6070
+ // updateAvailable/appReady: the check can finish before the JS listener attaches.
6071
+ this.notifyListeners(event, data, "noNeedUpdate".equals(event));
5908
6072
  return true;
5909
6073
  }
5910
6074
 
@@ -6107,10 +6271,44 @@ public class CapacitorUpdaterPlugin extends Plugin {
6107
6271
  }
6108
6272
 
6109
6273
  /**
6110
- * Security gates of an auto-update download, checked before it starts. Returns the cycle status
6111
- * when the download must not start (after sending its stat), or null.
6274
+ * The checksum a ZIP offer expects of the bundle, decrypted the way the download path does; null for a manifest
6275
+ * offer or when it cannot be resolved (then no same-version substitute is accepted on checksum grounds).
6112
6276
  */
6113
- private String autoUpdateDownloadBlockedReason(final JSObject latest, final String latestVersionName) {
6277
+ String offeredZipChecksum(final JSObject latest) {
6278
+ if (latest == null || latest.optJSONArray("manifest") != null) {
6279
+ return null;
6280
+ }
6281
+ final String checksum = latest.optString("checksum", "");
6282
+ if (checksum.isEmpty()) {
6283
+ return "";
6284
+ }
6285
+ final String sessionKey = latest.optString("sessionKey", "");
6286
+ if (!CryptoCipher.isValidSessionKey(sessionKey)) {
6287
+ return checksum;
6288
+ }
6289
+ try {
6290
+ return CryptoCipher.decryptChecksum(checksum, this.implementation.publicKey);
6291
+ } catch (final Exception e) {
6292
+ return "";
6293
+ }
6294
+ }
6295
+
6296
+ /**
6297
+ * A same-version bundle substituted for a failed row is reused only when its stored checksum is the one the ZIP
6298
+ * offer expects; a manifest offer (null) leaves the decision to the manifest and session gates.
6299
+ */
6300
+ static boolean matchesOfferedChecksum(final BundleInfo candidate, final String offeredZipChecksum) {
6301
+ if (offeredZipChecksum == null) {
6302
+ return true;
6303
+ }
6304
+ final String stored = candidate.getChecksum();
6305
+ return !offeredZipChecksum.isEmpty() && stored != null && stored.equalsIgnoreCase(offeredZipChecksum);
6306
+ }
6307
+
6308
+ /**
6309
+ * Session/checksum checks before reusing an on-device bundle (does not re-run transport gates).
6310
+ */
6311
+ private String autoUpdateReuseBlockedReason(final JSObject latest, final String latestVersionName) {
6114
6312
  final String sessionKey = latest.getString("sessionKey", "");
6115
6313
  if (!this.implementation.publicKey.isEmpty() && !CryptoCipher.isValidSessionKey(sessionKey)) {
6116
6314
  logger.error("Public key present but no valid session key provided");
@@ -6118,11 +6316,23 @@ public class CapacitorUpdaterPlugin extends Plugin {
6118
6316
  return "Session key required when public key is present";
6119
6317
  }
6120
6318
  final String checksum = latest.getString("checksum", "");
6121
- if (!latest.has("manifest") && (checksum == null || checksum.isEmpty())) {
6319
+ if (latest.optJSONArray("manifest") == null && (checksum == null || checksum.isEmpty())) {
6122
6320
  logger.error("No checksum provided");
6123
6321
  this.implementation.sendStats("checksum_required", latestVersionName);
6124
6322
  return "Checksum required";
6125
6323
  }
6324
+ return null;
6325
+ }
6326
+
6327
+ /**
6328
+ * Security gates of an auto-update download, checked before it starts. Returns the cycle status
6329
+ * when the download must not start (after sending its stat), or null.
6330
+ */
6331
+ private String autoUpdateDownloadBlockedReason(final JSObject latest, final String latestVersionName) {
6332
+ final String reuseBlockedReason = this.autoUpdateReuseBlockedReason(latest, latestVersionName);
6333
+ if (reuseBlockedReason != null) {
6334
+ return reuseBlockedReason;
6335
+ }
6126
6336
  try {
6127
6337
  this.implementation.runPreDownloadSecurityGates(
6128
6338
  latest.getString("url", ""),
@@ -6295,7 +6505,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
6295
6505
  if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6296
6506
  return;
6297
6507
  }
6298
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
6508
+ // Retained as on iOS: in onlyDownload mode the app applies this bundle itself, so a late listener must see it.
6509
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, true);
6299
6510
  }
6300
6511
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6301
6512
  "Latest version is builtin, autoUpdate onlyDownload",
@@ -6349,26 +6560,119 @@ public class CapacitorUpdaterPlugin extends Plugin {
6349
6560
  logger.info("Reusing automatic download for version: " + latestVersionName);
6350
6561
  return;
6351
6562
  }
6352
- final BundleInfo latest = CapacitorUpdaterPlugin.this.implementation.getBundleInfoByName(latestVersionName);
6563
+ BundleInfo latest = CapacitorUpdaterPlugin.this.implementation.getBundleInfoByName(latestVersionName);
6564
+ if (latest == null) {
6565
+ latest = CapacitorUpdaterPlugin.this.implementation.findRegistryBundleByVersionName(latestVersionName);
6566
+ } else if (latest.isDeleted() || latest.isDeleting()) {
6567
+ final BundleInfo liveSameVersion =
6568
+ CapacitorUpdaterPlugin.this.implementation.findRegistryBundleByVersionName(latestVersionName);
6569
+ if (liveSameVersion != null && !liveSameVersion.isDeleted() && !liveSameVersion.isDeleting()) {
6570
+ latest = liveSameVersion;
6571
+ }
6572
+ }
6573
+ boolean retryDownloadSlot = false;
6574
+ boolean substitutedCandidate = false;
6575
+ final String offeredZipChecksum = CapacitorUpdaterPlugin.this.offeredZipChecksum(jsRes);
6353
6576
  if (latest != null) {
6354
- final JSObject ret = new JSObject();
6355
- ret.put("bundle", InternalUtils.mapToJSObject(latest.toJSONMap()));
6356
- if (latest.isErrorStatus()) {
6357
- logger.error("Latest bundle already exists, and is in error state. Aborting update.");
6577
+ if (latest.isDeleted() || latest.isDeleting() || latest.isErrorStatus()) {
6578
+ final BundleInfo preferredBeforeRetry = CapacitorUpdaterPlugin.this.preferredAutoUpdateBundle(
6579
+ latest,
6580
+ latestVersionName
6581
+ );
6582
+ if (
6583
+ preferredBeforeRetry != null &&
6584
+ (preferredBeforeRetry.getId() == null ||
6585
+ preferredBeforeRetry.getId().equals(latest.getId()) ||
6586
+ CapacitorUpdaterPlugin.matchesOfferedChecksum(preferredBeforeRetry, offeredZipChecksum))
6587
+ ) {
6588
+ substitutedCandidate =
6589
+ preferredBeforeRetry.getId() != null && !preferredBeforeRetry.getId().equals(latest.getId());
6590
+ latest = preferredBeforeRetry;
6591
+ }
6592
+ }
6593
+ if (
6594
+ latest != null &&
6595
+ (!latest.isDownloaded() ||
6596
+ latest.isErrorStatus() ||
6597
+ latest.isDeleted() ||
6598
+ latest.isDeleting() ||
6599
+ BundleStatus.DOWNLOADING == latest.getStatus() ||
6600
+ !CapacitorUpdaterPlugin.this.implementation.isBundleOnDisk(latest.getId()))
6601
+ ) {
6602
+ // The disk lookup returns the first matching directory: prefer an installable same-version
6603
+ // bundle over a failed one so it goes through the reuse gates instead of a charged retry.
6604
+ final String failedId = latest.getId();
6605
+ // Examine every installable same-version bundle: the first one whose checksum
6606
+ // matches the offer is reused, a non-matching one does not end the search.
6607
+ final BundleInfo reusable = CapacitorUpdaterPlugin.this.implementation.findReusableBundleByVersionName(
6608
+ latestVersionName,
6609
+ (candidate) ->
6610
+ candidate.getId() != null &&
6611
+ !candidate.getId().equals(failedId) &&
6612
+ CapacitorUpdaterPlugin.matchesOfferedChecksum(candidate, offeredZipChecksum)
6613
+ );
6614
+ if (
6615
+ reusable != null &&
6616
+ reusable.getId() != null &&
6617
+ !reusable.getId().equals(latest.getId()) &&
6618
+ CapacitorUpdaterPlugin.matchesOfferedChecksum(reusable, offeredZipChecksum)
6619
+ ) {
6620
+ latest = reusable;
6621
+ substitutedCandidate = true;
6622
+ }
6623
+ }
6624
+ if (
6625
+ latest != null &&
6626
+ latest.isErrorStatus() &&
6627
+ !CapacitorUpdaterPlugin.this.shouldRetryIncompleteDownload(latest, latestVersionName, current)
6628
+ ) {
6629
+ logger.error("Latest bundle is in error state after incomplete retries. Aborting update.");
6630
+ // No transfer starts here, so no new download_fail is reported.
6358
6631
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6359
- "Latest bundle already exists, and is in error state. Aborting update.",
6632
+ "Latest version is in error state. Aborting update.",
6360
6633
  latestVersionName,
6361
6634
  current,
6362
6635
  true,
6363
6636
  plannedDirectUpdate,
6637
+ "download_fail",
6638
+ "downloadFailed",
6639
+ false,
6364
6640
  downloadContext
6365
6641
  );
6366
6642
  return;
6367
6643
  }
6644
+ final JSObject ret = new JSObject();
6645
+ ret.put("bundle", InternalUtils.mapToJSObject(latest.toJSONMap()));
6368
6646
  final String latestSessionKey = jsRes.has("sessionKey") ? jsRes.getString("sessionKey") : "";
6647
+ final boolean reusableOnDisk =
6648
+ latest.isDownloaded() &&
6649
+ !latest.isErrorStatus() &&
6650
+ BundleStatus.DOWNLOADING != latest.getStatus() &&
6651
+ CapacitorUpdaterPlugin.this.implementation.isBundleOnDisk(latest.getId());
6652
+ if (reusableOnDisk && substitutedCandidate) {
6653
+ // A queued bundle substituted for a failed row must pass the session/checksum gates
6654
+ // before reuse; previously the failed row aborted this check.
6655
+ final String reuseBlockedReason = CapacitorUpdaterPlugin.this.autoUpdateReuseBlockedReason(
6656
+ jsRes,
6657
+ latestVersionName
6658
+ );
6659
+ if (reuseBlockedReason != null) {
6660
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6661
+ reuseBlockedReason,
6662
+ latestVersionName,
6663
+ current,
6664
+ true,
6665
+ plannedDirectUpdate,
6666
+ downloadContext
6667
+ );
6668
+ return;
6669
+ }
6670
+ }
6369
6671
  if (
6370
6672
  latest.isDownloaded() &&
6673
+ !latest.isErrorStatus() &&
6371
6674
  BundleStatus.DOWNLOADING != latest.getStatus() &&
6675
+ CapacitorUpdaterPlugin.this.implementation.isBundleOnDisk(latest.getId()) &&
6372
6676
  (CapacitorUpdaterPlugin.this.implementation.publicKey.isEmpty() ||
6373
6677
  CryptoCipher.isValidSessionKey(latestSessionKey))
6374
6678
  ) {
@@ -6384,6 +6688,16 @@ public class CapacitorUpdaterPlugin extends Plugin {
6384
6688
  );
6385
6689
  if (!delayConditionList.isEmpty()) {
6386
6690
  logger.info("Update delayed until delay conditions met");
6691
+ if (
6692
+ CapacitorUpdaterPlugin.this.shouldAutoSetNextBundle() &&
6693
+ CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)
6694
+ ) {
6695
+ CapacitorUpdaterPlugin.this.queueBackgroundUpdateResponse(
6696
+ latest.getId(),
6697
+ plannedDirectUpdate,
6698
+ downloadContext
6699
+ );
6700
+ }
6387
6701
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6388
6702
  "Update delayed until delay conditions met",
6389
6703
  latestVersionName,
@@ -6429,7 +6743,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
6429
6743
  if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6430
6744
  return;
6431
6745
  }
6432
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
6746
+ // Retained as on iOS: in onlyDownload mode the app applies this bundle itself, so a late listener must see it.
6747
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, true);
6433
6748
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6434
6749
  "update downloaded, autoUpdate onlyDownload",
6435
6750
  latestVersionName,
@@ -6450,6 +6765,17 @@ public class CapacitorUpdaterPlugin extends Plugin {
6450
6765
  if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6451
6766
  return;
6452
6767
  }
6768
+ // An interrupted tombstone can be the only record linking this version to a failed
6769
+ // download: persist the retry before removing it. A plain retired tombstone has no
6770
+ // retry history, so the next transfer stays an uncharged first download.
6771
+ if (
6772
+ CapacitorUpdaterPlugin.this.implementation.isInterruptedDownloadBundle(latest.getId()) ||
6773
+ CapacitorUpdaterPlugin.this.implementation.incompleteDownloadRetryCount(latestVersionName) > 0 ||
6774
+ CapacitorUpdaterPlugin.this.implementation.isIntegrityBlockedVersion(latestVersionName)
6775
+ ) {
6776
+ CapacitorUpdaterPlugin.this.implementation.reserveIncompleteDownloadRetry(latestVersionName);
6777
+ retryDownloadSlot = true;
6778
+ }
6453
6779
  try {
6454
6780
  final boolean deleted = CapacitorUpdaterPlugin.this.implementation.deleteDeletedBundle(
6455
6781
  latest.getId()
@@ -6464,6 +6790,86 @@ public class CapacitorUpdaterPlugin extends Plugin {
6464
6790
  return;
6465
6791
  }
6466
6792
  }
6793
+ if (
6794
+ latest != null &&
6795
+ (!latest.isDownloaded() ||
6796
+ !CapacitorUpdaterPlugin.this.implementation.isBundleOnDisk(latest.getId()) ||
6797
+ BundleStatus.DOWNLOADING == latest.getStatus() ||
6798
+ latest.isErrorStatus() ||
6799
+ latest.isDeleted() ||
6800
+ latest.isDeleting()) &&
6801
+ CapacitorUpdaterPlugin.this.shouldRetryIncompleteDownload(latest, latestVersionName, current)
6802
+ ) {
6803
+ logger.info(
6804
+ "Latest bundle already exists in incomplete state (" +
6805
+ latest.getStatus() +
6806
+ ") and will be deleted, download will overwrite it."
6807
+ );
6808
+ // Every replacement of a stored record for this version consumes a retry slot.
6809
+ retryDownloadSlot = true;
6810
+ synchronized (CapacitorUpdaterPlugin.this) {
6811
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6812
+ return;
6813
+ }
6814
+ // Compare and clear under nextBundleLock so a concurrent next(B) is preserved.
6815
+ if (latest.getId() != null) {
6816
+ CapacitorUpdaterPlugin.this.implementation.clearNextBundleIfMatches(latest.getId());
6817
+ }
6818
+ }
6819
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6820
+ return;
6821
+ }
6822
+ // Persist the retry before deleting the record that proves it, so process death
6823
+ // between the delete and the download start cannot hand out a free retry.
6824
+ CapacitorUpdaterPlugin.this.implementation.reserveIncompleteDownloadRetry(latestVersionName);
6825
+ boolean incompleteDeleted = false;
6826
+ try {
6827
+ incompleteDeleted = Boolean.TRUE.equals(
6828
+ CapacitorUpdaterPlugin.this.implementation.delete(latest.getId(), true)
6829
+ );
6830
+ if (incompleteDeleted) {
6831
+ logger.info("Incomplete bundle deleted: " + latest.toString());
6832
+ } else {
6833
+ logger.error("Failed to delete incomplete bundle: " + latest.toString());
6834
+ }
6835
+ } catch (final IOException e) {
6836
+ logger.error(
6837
+ "Failed to delete incomplete bundle: " + latest.getVersionName() + " " + e.getMessage()
6838
+ );
6839
+ }
6840
+ if (
6841
+ !incompleteDeleted &&
6842
+ !CapacitorUpdaterPlugin.this.implementation.hasStoredBundleInfoForRetry(latest.getId())
6843
+ ) {
6844
+ // Already removed in this check (e.g. a DELETED tombstone cleaned just above).
6845
+ incompleteDeleted = true;
6846
+ }
6847
+ if (!incompleteDeleted) {
6848
+ // A pending deletion resumes with a version-wide cancel and would kill the
6849
+ // replacement. End this cycle; the reservation keeps the retry charged.
6850
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6851
+ "Incomplete bundle deletion is still pending. Retrying later.",
6852
+ latestVersionName,
6853
+ current,
6854
+ true,
6855
+ plannedDirectUpdate,
6856
+ "download_fail",
6857
+ "downloadFailed",
6858
+ false,
6859
+ downloadContext
6860
+ );
6861
+ return;
6862
+ }
6863
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6864
+ return;
6865
+ }
6866
+ latest = CapacitorUpdaterPlugin.this.implementation.getBundleInfoByName(latestVersionName);
6867
+ if (latest == null) {
6868
+ latest = CapacitorUpdaterPlugin.this.implementation.findRegistryBundleByVersionName(
6869
+ latestVersionName
6870
+ );
6871
+ }
6872
+ }
6467
6873
  }
6468
6874
  // The store refuses these downloads without a callback, so end the cycle here
6469
6875
  // (appReady, splash hide) like iOS does.
@@ -6482,6 +6888,25 @@ public class CapacitorUpdaterPlugin extends Plugin {
6482
6888
  );
6483
6889
  return;
6484
6890
  }
6891
+ if (
6892
+ CapacitorUpdaterPlugin.this.implementation.incompleteDownloadRetryCount(latestVersionName) >=
6893
+ CapgoUpdater.MAX_INCOMPLETE_DOWNLOAD_RETRIES
6894
+ ) {
6895
+ logger.error("Latest bundle exceeded incomplete download retries. Aborting update.");
6896
+ // No transfer starts here, so no new download_fail is reported.
6897
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6898
+ "Latest version is in error state. Aborting update.",
6899
+ latestVersionName,
6900
+ current,
6901
+ true,
6902
+ plannedDirectUpdate,
6903
+ "download_fail",
6904
+ "downloadFailed",
6905
+ false,
6906
+ downloadContext
6907
+ );
6908
+ return;
6909
+ }
6485
6910
  final boolean retryingInFlightDownload =
6486
6911
  latest != null &&
6487
6912
  BundleStatus.DOWNLOADING == latest.getStatus() &&
@@ -6500,7 +6925,17 @@ public class CapacitorUpdaterPlugin extends Plugin {
6500
6925
  directUpdateStillAllowed
6501
6926
  : directUpdateStillAllowed;
6502
6927
  }
6928
+ // Any download after an earlier failed attempt of this version is a charged retry,
6929
+ // whether or not a stored row was left behind.
6930
+ if (
6931
+ CapacitorUpdaterPlugin.this.implementation.incompleteDownloadRetryCount(latestVersionName) > 0 ||
6932
+ CapacitorUpdaterPlugin.this.implementation.isIntegrityBlockedVersion(latestVersionName)
6933
+ ) {
6934
+ retryDownloadSlot = true;
6935
+ }
6936
+ final boolean consumeRetrySlotOnStart = retryDownloadSlot;
6503
6937
  startNewThread(() -> {
6938
+ boolean retryCharged = false;
6504
6939
  try {
6505
6940
  if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6506
6941
  return;
@@ -6523,6 +6958,50 @@ public class CapacitorUpdaterPlugin extends Plugin {
6523
6958
  final String checksum = jsRes.has("checksum") ? jsRes.getString("checksum") : "";
6524
6959
 
6525
6960
  final JSONArray manifest = jsRes.has("manifest") ? jsRes.getJSONArray("manifest") : null;
6961
+ if (
6962
+ manifest == null &&
6963
+ (consumeRetrySlotOnStart ||
6964
+ CapacitorUpdaterPlugin.this.implementation.hasIncompleteDownloadRetryReservation(
6965
+ latestVersionName
6966
+ )) &&
6967
+ !CapacitorUpdaterPlugin.this.implementation.hasDiskSpaceForZipDownload()
6968
+ ) {
6969
+ // The ZIP worker would refuse before any request: do not spend a retry slot on it.
6970
+ logger.error("Insufficient disk space for retry download of " + latestVersionName);
6971
+ CapacitorUpdaterPlugin.this.implementation.sendStats("insufficient_disk_space", latestVersionName);
6972
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6973
+ "Insufficient disk space. Retrying later.",
6974
+ latestVersionName,
6975
+ current,
6976
+ true,
6977
+ plannedDirectUpdate,
6978
+ "download_fail",
6979
+ "downloadFailed",
6980
+ false,
6981
+ downloadContext
6982
+ );
6983
+ return;
6984
+ }
6985
+ final int retryCharge = CapacitorUpdaterPlugin.this.implementation.chargeIncompleteDownloadRetry(
6986
+ latestVersionName,
6987
+ consumeRetrySlotOnStart
6988
+ );
6989
+ if (retryCharge == CapgoUpdater.RETRY_REFUSED) {
6990
+ logger.error("Latest bundle exceeded incomplete download retries. Aborting update.");
6991
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6992
+ "Latest version is in error state. Aborting update.",
6993
+ latestVersionName,
6994
+ current,
6995
+ true,
6996
+ plannedDirectUpdate,
6997
+ "download_fail",
6998
+ "downloadFailed",
6999
+ false,
7000
+ downloadContext
7001
+ );
7002
+ return;
7003
+ }
7004
+ retryCharged = retryCharge == CapgoUpdater.RETRY_CHARGED;
6526
7005
  final CapgoUpdater.BackgroundDownloadResult result =
6527
7006
  CapacitorUpdaterPlugin.this.implementation.downloadBackground(
6528
7007
  url,
@@ -6533,6 +7012,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
6533
7012
  CapacitorUpdaterPlugin.this.shouldAutoSetNextBundle(),
6534
7013
  downloadContext
6535
7014
  );
7015
+ CapacitorUpdaterPlugin.this.implementation.settleIncompleteDownloadRetry(
7016
+ latestVersionName,
7017
+ retryCharged,
7018
+ result.status == CapgoUpdater.BackgroundDownloadResult.Status.STARTED,
7019
+ result.status == CapgoUpdater.BackgroundDownloadResult.Status.REUSED
7020
+ );
7021
+ retryCharged = false;
6536
7022
  if (result.status == CapgoUpdater.BackgroundDownloadResult.Status.NOT_STARTED) {
6537
7023
  CapacitorUpdaterPlugin.this.endFailedBackgroundDownload(
6538
7024
  latestVersionName,
@@ -6542,6 +7028,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
6542
7028
  }
6543
7029
  } catch (final Exception e) {
6544
7030
  logger.error("error downloading file " + e.getMessage());
7031
+ CapacitorUpdaterPlugin.this.implementation.settleIncompleteDownloadRetry(
7032
+ latestVersionName,
7033
+ retryCharged,
7034
+ false,
7035
+ false
7036
+ );
6545
7037
  CapacitorUpdaterPlugin.this.endFailedBackgroundDownload(
6546
7038
  latestVersionName,
6547
7039
  plannedDirectUpdate,