@capgo/capacitor-updater 9.0.1 → 9.0.4

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 (28) 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 +521 -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/CryptoCipher.java +10 -2
  6. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +82 -10
  7. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +23 -0
  8. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +188 -4
  9. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +81 -1
  10. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +72 -21
  11. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +5 -2
  12. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +5 -1
  13. package/dist/docs.json +13 -13
  14. package/dist/esm/definitions.d.ts +57 -23
  15. package/dist/esm/definitions.js.map +1 -1
  16. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1278 -107
  17. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +38 -0
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +583 -56
  19. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +8 -1
  20. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +6 -1
  21. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +2718 -77
  22. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +9 -4
  23. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +67 -2
  24. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +130 -5
  25. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +259 -119
  26. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +4 -0
  27. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +19 -3
  28. package/package.json +2 -2
@@ -159,7 +159,15 @@ 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
+ // The release bump (capacitor-plugin-standard-version) rewrites only a private final String field named
163
+ // pluginVersion that holds a string literal, so the version lives in that form below. PLUGIN_VERSION
164
+ // exposes it to code that runs without a plugin instance.
165
+ private static final class VersionHolder {
166
+
167
+ private final String pluginVersion = "9.0.4";
168
+ }
169
+
170
+ static final String PLUGIN_VERSION = new VersionHolder().pluginVersion;
163
171
  // Set while a plugin instance (with its bridge) runs in this process. The headless update
164
172
  // check then leaves installing to that instance instead of swapping bundles under it.
165
173
  static final Object INSTANCE_LOADED_LOCK = new Object();
@@ -876,9 +884,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
876
884
  @Override
877
885
  public void notifyListeners(final String id, final Map<String, Object> res) {
878
886
  if (activity != null) {
879
- activity.runOnUiThread(() -> {
880
- CapacitorUpdaterPlugin.this.notifyListeners(id, InternalUtils.mapToJSObject(res), false);
881
- });
887
+ activity.runOnUiThread(() -> CapacitorUpdaterPlugin.this.emitCoreEvent(id, res));
882
888
  } else {
883
889
  logger.warn("notifyListeners: Activity is null, skipping notification for event: " + id);
884
890
  }
@@ -2697,6 +2703,20 @@ public class CapacitorUpdaterPlugin extends Plugin {
2697
2703
  return SHAKE_MENU_GESTURE_SHAKE.equals(normalized) || SHAKE_MENU_GESTURE_THREE_FINGER_PINCH.equals(normalized);
2698
2704
  }
2699
2705
 
2706
+ /**
2707
+ * Events from the updater core that wait for a listener. In onlyDownload mode the app applies a fresh download
2708
+ * itself, so its updateAvailable must reach a listener that attaches later (as on iOS and the already-downloaded
2709
+ * path). Every other core event is delivered only to current listeners.
2710
+ */
2711
+ /** Forwards an event raised by {@link CapgoUpdater}, retaining it when {@link #retainsUpdaterEvent} says so. */
2712
+ void emitCoreEvent(final String eventName, final Map<String, Object> res) {
2713
+ this.notifyListeners(eventName, InternalUtils.mapToJSObject(res), this.retainsUpdaterEvent(eventName));
2714
+ }
2715
+
2716
+ boolean retainsUpdaterEvent(final String eventName) {
2717
+ return "updateAvailable".equals(eventName) && AUTO_UPDATE_MODE_ONLY_DOWNLOAD.equals(this.autoUpdateMode);
2718
+ }
2719
+
2700
2720
  static String directUpdateModeForAutoUpdateMode(final String autoUpdateMode) {
2701
2721
  switch (autoUpdateMode) {
2702
2722
  case AUTO_UPDATE_MODE_INSTALL:
@@ -2793,6 +2813,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
2793
2813
  return this.onLaunchDirectUpdateUsed;
2794
2814
  }
2795
2815
 
2816
+ boolean shouldRetryIncompleteDownloadForTesting(final BundleInfo bundle, final String latestVersionName, final BundleInfo current) {
2817
+ return this.shouldRetryIncompleteDownload(bundle, latestVersionName, current);
2818
+ }
2819
+
2796
2820
  boolean isVersionDownloadInProgress(final String version) {
2797
2821
  return (
2798
2822
  version != null &&
@@ -2803,6 +2827,119 @@ public class CapacitorUpdaterPlugin extends Plugin {
2803
2827
  );
2804
2828
  }
2805
2829
 
2830
+ private BundleInfo preferredAutoUpdateBundle(final BundleInfo existing, final String latestVersionName) {
2831
+ if (existing == null) {
2832
+ return null;
2833
+ }
2834
+ final BundleInfo queued = this.implementation.getNextBundle();
2835
+ if (
2836
+ queued != null &&
2837
+ latestVersionName.equals(queued.getVersionName()) &&
2838
+ !existing.getId().equals(queued.getId()) &&
2839
+ !queued.isDeleted() &&
2840
+ !queued.isDeleting() &&
2841
+ (!existing.isErrorStatus() || this.isInstallableBundle(queued))
2842
+ ) {
2843
+ // A failed row keeps its ERROR stop unless the queued same-version bundle is itself installable.
2844
+ return queued;
2845
+ }
2846
+ if (existing.isDeleted() || existing.isDeleting()) {
2847
+ return null;
2848
+ }
2849
+ return existing;
2850
+ }
2851
+
2852
+ private boolean isInstallableBundle(final BundleInfo bundle) {
2853
+ return (
2854
+ bundle.isDownloaded() &&
2855
+ !bundle.isErrorStatus() &&
2856
+ BundleStatus.DOWNLOADING != bundle.getStatus() &&
2857
+ this.implementation.isBundleOnDisk(bundle.getId())
2858
+ );
2859
+ }
2860
+
2861
+ private boolean shouldRetryIncompleteDownload(final BundleInfo bundle, final String latestVersionName, final BundleInfo current) {
2862
+ if (
2863
+ bundle != null &&
2864
+ BundleStatus.DOWNLOADING != bundle.getStatus() &&
2865
+ this.implementation.isVersionDownloadActive(latestVersionName)
2866
+ ) {
2867
+ // Another live download (e.g. a manual download()) owns this version: deleting the old row would
2868
+ // run a version-wide cancel and kill it.
2869
+ return false;
2870
+ }
2871
+ if (
2872
+ bundle != null &&
2873
+ BundleStatus.DOWNLOADING == bundle.getStatus() &&
2874
+ this.isVersionDownloadInProgress(latestVersionName) &&
2875
+ !this.implementation.isInterruptedDownloadBundle(bundle.getId())
2876
+ ) {
2877
+ return false;
2878
+ }
2879
+ if (bundle != null && BundleStatus.DOWNLOADING == bundle.getStatus()) {
2880
+ if (!this.implementation.isInterruptedDownloadBundle(bundle.getId())) {
2881
+ return false;
2882
+ }
2883
+ }
2884
+ final BundleInfo next = this.implementation.getNextBundle();
2885
+ if (
2886
+ bundle != null &&
2887
+ (bundle.isDeleted() || bundle.isDeleting()) &&
2888
+ next != null &&
2889
+ latestVersionName.equals(next.getVersionName()) &&
2890
+ !bundle.getId().equals(next.getId()) &&
2891
+ !next.isDeleted() &&
2892
+ !next.isDeleting()
2893
+ ) {
2894
+ return false;
2895
+ }
2896
+ if (
2897
+ bundle != null &&
2898
+ bundle.isDownloaded() &&
2899
+ BundleStatus.DOWNLOADING != bundle.getStatus() &&
2900
+ !bundle.isErrorStatus() &&
2901
+ this.implementation.isBundleOnDisk(bundle.getId())
2902
+ ) {
2903
+ return false;
2904
+ }
2905
+ if (bundle != null && (bundle.isDeleted() || bundle.isDeleting())) {
2906
+ if (this.isVersionDownloadInProgress(latestVersionName)) {
2907
+ return false;
2908
+ }
2909
+ final BundleInfo liveSameVersion = this.implementation.findRegistryBundleByVersionName(latestVersionName);
2910
+ if (
2911
+ liveSameVersion != null &&
2912
+ !liveSameVersion.getId().equals(bundle.getId()) &&
2913
+ !liveSameVersion.isDeleted() &&
2914
+ !liveSameVersion.isDeleting()
2915
+ ) {
2916
+ return false;
2917
+ }
2918
+ if (
2919
+ !this.implementation.isInterruptedDownloadBundle(bundle.getId()) &&
2920
+ this.implementation.incompleteDownloadRetryCount(latestVersionName) == 0
2921
+ ) {
2922
+ return false;
2923
+ }
2924
+ }
2925
+ final boolean isQueuedNext = bundle != null && next != null && bundle.getId().equals(next.getId());
2926
+ final boolean isCurrent =
2927
+ bundle != null &&
2928
+ bundle.getId().equals(current.getId()) &&
2929
+ BundleStatus.SUCCESS == current.getStatus() &&
2930
+ latestVersionName.equals(current.getVersionName());
2931
+ final boolean interrupted = bundle != null && this.implementation.isInterruptedDownloadBundle(bundle.getId());
2932
+ return CapgoUpdater.shouldRetryDownloadForExistingBundle(
2933
+ bundle,
2934
+ bundle != null && this.implementation.isBundleOnDisk(bundle.getId()),
2935
+ this.implementation.incompleteDownloadRetryCount(latestVersionName),
2936
+ this.implementation.isIntegrityBlockedVersion(latestVersionName),
2937
+ interrupted,
2938
+ isCurrent,
2939
+ isQueuedNext
2940
+ );
2941
+ }
2942
+
2806
2943
  void setLoggerForTesting(final Logger logger) {
2807
2944
  this.logger = logger;
2808
2945
  }
@@ -3122,6 +3259,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
3122
3259
  this.implementation.cleanupOrphanedManifestStagingFolders(null);
3123
3260
 
3124
3261
  this.persistCurrentNativeBuildVersion();
3262
+ if (this.implementation != null) {
3263
+ this.implementation.reconcileInterruptedDownloadsOnLaunch();
3264
+ }
3125
3265
  } catch (Exception e) {
3126
3266
  logger.error("Error during cleanupObsoleteVersions: " + e.getMessage());
3127
3267
  } finally {
@@ -4388,7 +4528,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
4388
4528
  }
4389
4529
 
4390
4530
  private boolean leavePreviewSessionWithoutReload(final boolean keepPreviewGuard) {
4391
- final BundleInfo previewFallbackBundle = this.resolvePreviewFallbackBundle("preview deeplink launch");
4531
+ // Launch-time routing: the startup version floor runs afterwards and reports a below-native fallback.
4532
+ final BundleInfo previewFallbackBundle = this.resolvePreviewFallbackBundle("preview deeplink launch", false);
4392
4533
  if (previewFallbackBundle == null) {
4393
4534
  return false;
4394
4535
  }
@@ -4441,8 +4582,15 @@ public class CapacitorUpdaterPlugin extends Plugin {
4441
4582
  }
4442
4583
 
4443
4584
  private BundleInfo resolvePreviewFallbackBundle(final String reason) {
4585
+ return this.resolvePreviewFallbackBundle(reason, true);
4586
+ }
4587
+
4588
+ private BundleInfo resolvePreviewFallbackBundle(final String reason, final boolean enforceVersionFloor) {
4444
4589
  final BundleInfo fallback = this.implementation.getPreviewFallbackBundle();
4445
- if (fallback != null && !fallback.isErrorStatus() && this.implementation.canSet(fallback)) {
4590
+ final boolean usable = fallback != null && !fallback.isErrorStatus() && this.implementation.canSet(fallback);
4591
+ // A native upgrade during preview can leave the fallback below the version floor; never reactivate it.
4592
+ final boolean meetsFloor = usable && (!enforceVersionFloor || this.fallbackMeetsVersionFloor(fallback));
4593
+ if (meetsFloor) {
4446
4594
  return fallback;
4447
4595
  }
4448
4596
 
@@ -4450,6 +4598,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
4450
4598
  logger.warn("No preview fallback bundle available for " + reason + ". Falling back to builtin bundle.");
4451
4599
  } else if (fallback.isErrorStatus()) {
4452
4600
  logger.warn("Preview fallback bundle is in error state for " + reason + ". Falling back to builtin bundle.");
4601
+ } else if (usable) {
4602
+ logger.warn("Preview fallback bundle is below the native version for " + reason + ". Falling back to builtin bundle.");
4453
4603
  } else {
4454
4604
  logger.warn("Preview fallback bundle is not installable for " + reason + ". Falling back to builtin bundle.");
4455
4605
  }
@@ -4463,6 +4613,18 @@ public class CapacitorUpdaterPlugin extends Plugin {
4463
4613
  return null;
4464
4614
  }
4465
4615
 
4616
+ boolean fallbackMeetsVersionFloor(final BundleInfo fallback) {
4617
+ if (fallback.isBuiltin()) {
4618
+ return true;
4619
+ }
4620
+ try {
4621
+ this.implementation.requireVersionNotBelowBuiltin(fallback.getVersionName());
4622
+ return true;
4623
+ } catch (IOException e) {
4624
+ return false;
4625
+ }
4626
+ }
4627
+
4466
4628
  private void endPreviewSession() {
4467
4629
  this.endPreviewSession(false);
4468
4630
  }
@@ -5107,6 +5269,14 @@ public class CapacitorUpdaterPlugin extends Plugin {
5107
5269
  logger.error("Pending bundle is not installable");
5108
5270
  return false;
5109
5271
  }
5272
+ if (!pending.isBuiltin()) {
5273
+ try {
5274
+ this.implementation.requireVersionNotBelowBuiltin(pending.getVersionName());
5275
+ } catch (IOException e) {
5276
+ logger.error(e.getMessage());
5277
+ return false;
5278
+ }
5279
+ }
5110
5280
  this.implementation.prepareResetStateForTransition();
5111
5281
  logger.info("Resetting to pending bundle: " + pending.getVersionName());
5112
5282
  final boolean didApplyPendingBundle;
@@ -5144,7 +5314,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
5144
5314
  }
5145
5315
 
5146
5316
  if (Boolean.TRUE.equals(toLastSuccessful) && !fallback.isBuiltin()) {
5147
- if (this.implementation.canSet(fallback)) {
5317
+ // A last successful bundle below the native version floor cannot be activated: use builtin instead.
5318
+ if (this.implementation.canSet(fallback) && this.fallbackMeetsVersionFloor(fallback)) {
5148
5319
  this.implementation.prepareResetStateForTransition();
5149
5320
  logger.info("Resetting to: " + fallback);
5150
5321
  if (this.implementation.set(fallback)) {
@@ -5903,8 +6074,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
5903
6074
  if (!this.ownsBackgroundDownload(downloadContext)) {
5904
6075
  return false;
5905
6076
  }
5906
- // Admit delivery before another thread can replace this check's ownership.
5907
- this.notifyListeners(event, data, false);
6077
+ // Admit delivery before another thread can replace this check's ownership. noNeedUpdate is retained like
6078
+ // updateAvailable/appReady: the check can finish before the JS listener attaches.
6079
+ this.notifyListeners(event, data, "noNeedUpdate".equals(event));
5908
6080
  return true;
5909
6081
  }
5910
6082
 
@@ -6107,10 +6279,44 @@ public class CapacitorUpdaterPlugin extends Plugin {
6107
6279
  }
6108
6280
 
6109
6281
  /**
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.
6282
+ * The checksum a ZIP offer expects of the bundle, decrypted the way the download path does; null for a manifest
6283
+ * offer or when it cannot be resolved (then no same-version substitute is accepted on checksum grounds).
6112
6284
  */
6113
- private String autoUpdateDownloadBlockedReason(final JSObject latest, final String latestVersionName) {
6285
+ String offeredZipChecksum(final JSObject latest) {
6286
+ if (latest == null || latest.optJSONArray("manifest") != null) {
6287
+ return null;
6288
+ }
6289
+ final String checksum = latest.optString("checksum", "");
6290
+ if (checksum.isEmpty()) {
6291
+ return "";
6292
+ }
6293
+ final String sessionKey = latest.optString("sessionKey", "");
6294
+ if (!CryptoCipher.isValidSessionKey(sessionKey)) {
6295
+ return checksum;
6296
+ }
6297
+ try {
6298
+ return CryptoCipher.decryptChecksum(checksum, this.implementation.publicKey);
6299
+ } catch (final Exception e) {
6300
+ return "";
6301
+ }
6302
+ }
6303
+
6304
+ /**
6305
+ * A same-version bundle substituted for a failed row is reused only when its stored checksum is the one the ZIP
6306
+ * offer expects; a manifest offer (null) leaves the decision to the manifest and session gates.
6307
+ */
6308
+ static boolean matchesOfferedChecksum(final BundleInfo candidate, final String offeredZipChecksum) {
6309
+ if (offeredZipChecksum == null) {
6310
+ return true;
6311
+ }
6312
+ final String stored = candidate.getChecksum();
6313
+ return !offeredZipChecksum.isEmpty() && stored != null && stored.equalsIgnoreCase(offeredZipChecksum);
6314
+ }
6315
+
6316
+ /**
6317
+ * Session/checksum checks before reusing an on-device bundle (does not re-run transport gates).
6318
+ */
6319
+ private String autoUpdateReuseBlockedReason(final JSObject latest, final String latestVersionName) {
6114
6320
  final String sessionKey = latest.getString("sessionKey", "");
6115
6321
  if (!this.implementation.publicKey.isEmpty() && !CryptoCipher.isValidSessionKey(sessionKey)) {
6116
6322
  logger.error("Public key present but no valid session key provided");
@@ -6118,11 +6324,23 @@ public class CapacitorUpdaterPlugin extends Plugin {
6118
6324
  return "Session key required when public key is present";
6119
6325
  }
6120
6326
  final String checksum = latest.getString("checksum", "");
6121
- if (!latest.has("manifest") && (checksum == null || checksum.isEmpty())) {
6327
+ if (latest.optJSONArray("manifest") == null && (checksum == null || checksum.isEmpty())) {
6122
6328
  logger.error("No checksum provided");
6123
6329
  this.implementation.sendStats("checksum_required", latestVersionName);
6124
6330
  return "Checksum required";
6125
6331
  }
6332
+ return null;
6333
+ }
6334
+
6335
+ /**
6336
+ * Security gates of an auto-update download, checked before it starts. Returns the cycle status
6337
+ * when the download must not start (after sending its stat), or null.
6338
+ */
6339
+ private String autoUpdateDownloadBlockedReason(final JSObject latest, final String latestVersionName) {
6340
+ final String reuseBlockedReason = this.autoUpdateReuseBlockedReason(latest, latestVersionName);
6341
+ if (reuseBlockedReason != null) {
6342
+ return reuseBlockedReason;
6343
+ }
6126
6344
  try {
6127
6345
  this.implementation.runPreDownloadSecurityGates(
6128
6346
  latest.getString("url", ""),
@@ -6295,7 +6513,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
6295
6513
  if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6296
6514
  return;
6297
6515
  }
6298
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
6516
+ // Retained as on iOS: in onlyDownload mode the app applies this bundle itself, so a late listener must see it.
6517
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, true);
6299
6518
  }
6300
6519
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6301
6520
  "Latest version is builtin, autoUpdate onlyDownload",
@@ -6349,26 +6568,119 @@ public class CapacitorUpdaterPlugin extends Plugin {
6349
6568
  logger.info("Reusing automatic download for version: " + latestVersionName);
6350
6569
  return;
6351
6570
  }
6352
- final BundleInfo latest = CapacitorUpdaterPlugin.this.implementation.getBundleInfoByName(latestVersionName);
6571
+ BundleInfo latest = CapacitorUpdaterPlugin.this.implementation.getBundleInfoByName(latestVersionName);
6572
+ if (latest == null) {
6573
+ latest = CapacitorUpdaterPlugin.this.implementation.findRegistryBundleByVersionName(latestVersionName);
6574
+ } else if (latest.isDeleted() || latest.isDeleting()) {
6575
+ final BundleInfo liveSameVersion =
6576
+ CapacitorUpdaterPlugin.this.implementation.findRegistryBundleByVersionName(latestVersionName);
6577
+ if (liveSameVersion != null && !liveSameVersion.isDeleted() && !liveSameVersion.isDeleting()) {
6578
+ latest = liveSameVersion;
6579
+ }
6580
+ }
6581
+ boolean retryDownloadSlot = false;
6582
+ boolean substitutedCandidate = false;
6583
+ final String offeredZipChecksum = CapacitorUpdaterPlugin.this.offeredZipChecksum(jsRes);
6353
6584
  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.");
6585
+ if (latest.isDeleted() || latest.isDeleting() || latest.isErrorStatus()) {
6586
+ final BundleInfo preferredBeforeRetry = CapacitorUpdaterPlugin.this.preferredAutoUpdateBundle(
6587
+ latest,
6588
+ latestVersionName
6589
+ );
6590
+ if (
6591
+ preferredBeforeRetry != null &&
6592
+ (preferredBeforeRetry.getId() == null ||
6593
+ preferredBeforeRetry.getId().equals(latest.getId()) ||
6594
+ CapacitorUpdaterPlugin.matchesOfferedChecksum(preferredBeforeRetry, offeredZipChecksum))
6595
+ ) {
6596
+ substitutedCandidate =
6597
+ preferredBeforeRetry.getId() != null && !preferredBeforeRetry.getId().equals(latest.getId());
6598
+ latest = preferredBeforeRetry;
6599
+ }
6600
+ }
6601
+ if (
6602
+ latest != null &&
6603
+ (!latest.isDownloaded() ||
6604
+ latest.isErrorStatus() ||
6605
+ latest.isDeleted() ||
6606
+ latest.isDeleting() ||
6607
+ BundleStatus.DOWNLOADING == latest.getStatus() ||
6608
+ !CapacitorUpdaterPlugin.this.implementation.isBundleOnDisk(latest.getId()))
6609
+ ) {
6610
+ // The disk lookup returns the first matching directory: prefer an installable same-version
6611
+ // bundle over a failed one so it goes through the reuse gates instead of a charged retry.
6612
+ final String failedId = latest.getId();
6613
+ // Examine every installable same-version bundle: the first one whose checksum
6614
+ // matches the offer is reused, a non-matching one does not end the search.
6615
+ final BundleInfo reusable = CapacitorUpdaterPlugin.this.implementation.findReusableBundleByVersionName(
6616
+ latestVersionName,
6617
+ (candidate) ->
6618
+ candidate.getId() != null &&
6619
+ !candidate.getId().equals(failedId) &&
6620
+ CapacitorUpdaterPlugin.matchesOfferedChecksum(candidate, offeredZipChecksum)
6621
+ );
6622
+ if (
6623
+ reusable != null &&
6624
+ reusable.getId() != null &&
6625
+ !reusable.getId().equals(latest.getId()) &&
6626
+ CapacitorUpdaterPlugin.matchesOfferedChecksum(reusable, offeredZipChecksum)
6627
+ ) {
6628
+ latest = reusable;
6629
+ substitutedCandidate = true;
6630
+ }
6631
+ }
6632
+ if (
6633
+ latest != null &&
6634
+ latest.isErrorStatus() &&
6635
+ !CapacitorUpdaterPlugin.this.shouldRetryIncompleteDownload(latest, latestVersionName, current)
6636
+ ) {
6637
+ logger.error("Latest bundle is in error state after incomplete retries. Aborting update.");
6638
+ // No transfer starts here, so no new download_fail is reported.
6358
6639
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6359
- "Latest bundle already exists, and is in error state. Aborting update.",
6640
+ "Latest version is in error state. Aborting update.",
6360
6641
  latestVersionName,
6361
6642
  current,
6362
6643
  true,
6363
6644
  plannedDirectUpdate,
6645
+ "download_fail",
6646
+ "downloadFailed",
6647
+ false,
6364
6648
  downloadContext
6365
6649
  );
6366
6650
  return;
6367
6651
  }
6652
+ final JSObject ret = new JSObject();
6653
+ ret.put("bundle", InternalUtils.mapToJSObject(latest.toJSONMap()));
6368
6654
  final String latestSessionKey = jsRes.has("sessionKey") ? jsRes.getString("sessionKey") : "";
6655
+ final boolean reusableOnDisk =
6656
+ latest.isDownloaded() &&
6657
+ !latest.isErrorStatus() &&
6658
+ BundleStatus.DOWNLOADING != latest.getStatus() &&
6659
+ CapacitorUpdaterPlugin.this.implementation.isBundleOnDisk(latest.getId());
6660
+ if (reusableOnDisk && substitutedCandidate) {
6661
+ // A queued bundle substituted for a failed row must pass the session/checksum gates
6662
+ // before reuse; previously the failed row aborted this check.
6663
+ final String reuseBlockedReason = CapacitorUpdaterPlugin.this.autoUpdateReuseBlockedReason(
6664
+ jsRes,
6665
+ latestVersionName
6666
+ );
6667
+ if (reuseBlockedReason != null) {
6668
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6669
+ reuseBlockedReason,
6670
+ latestVersionName,
6671
+ current,
6672
+ true,
6673
+ plannedDirectUpdate,
6674
+ downloadContext
6675
+ );
6676
+ return;
6677
+ }
6678
+ }
6369
6679
  if (
6370
6680
  latest.isDownloaded() &&
6681
+ !latest.isErrorStatus() &&
6371
6682
  BundleStatus.DOWNLOADING != latest.getStatus() &&
6683
+ CapacitorUpdaterPlugin.this.implementation.isBundleOnDisk(latest.getId()) &&
6372
6684
  (CapacitorUpdaterPlugin.this.implementation.publicKey.isEmpty() ||
6373
6685
  CryptoCipher.isValidSessionKey(latestSessionKey))
6374
6686
  ) {
@@ -6384,6 +6696,16 @@ public class CapacitorUpdaterPlugin extends Plugin {
6384
6696
  );
6385
6697
  if (!delayConditionList.isEmpty()) {
6386
6698
  logger.info("Update delayed until delay conditions met");
6699
+ if (
6700
+ CapacitorUpdaterPlugin.this.shouldAutoSetNextBundle() &&
6701
+ CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)
6702
+ ) {
6703
+ CapacitorUpdaterPlugin.this.queueBackgroundUpdateResponse(
6704
+ latest.getId(),
6705
+ plannedDirectUpdate,
6706
+ downloadContext
6707
+ );
6708
+ }
6387
6709
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6388
6710
  "Update delayed until delay conditions met",
6389
6711
  latestVersionName,
@@ -6429,7 +6751,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
6429
6751
  if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6430
6752
  return;
6431
6753
  }
6432
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
6754
+ // Retained as on iOS: in onlyDownload mode the app applies this bundle itself, so a late listener must see it.
6755
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, true);
6433
6756
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6434
6757
  "update downloaded, autoUpdate onlyDownload",
6435
6758
  latestVersionName,
@@ -6450,6 +6773,17 @@ public class CapacitorUpdaterPlugin extends Plugin {
6450
6773
  if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6451
6774
  return;
6452
6775
  }
6776
+ // An interrupted tombstone can be the only record linking this version to a failed
6777
+ // download: persist the retry before removing it. A plain retired tombstone has no
6778
+ // retry history, so the next transfer stays an uncharged first download.
6779
+ if (
6780
+ CapacitorUpdaterPlugin.this.implementation.isInterruptedDownloadBundle(latest.getId()) ||
6781
+ CapacitorUpdaterPlugin.this.implementation.incompleteDownloadRetryCount(latestVersionName) > 0 ||
6782
+ CapacitorUpdaterPlugin.this.implementation.isIntegrityBlockedVersion(latestVersionName)
6783
+ ) {
6784
+ CapacitorUpdaterPlugin.this.implementation.reserveIncompleteDownloadRetry(latestVersionName);
6785
+ retryDownloadSlot = true;
6786
+ }
6453
6787
  try {
6454
6788
  final boolean deleted = CapacitorUpdaterPlugin.this.implementation.deleteDeletedBundle(
6455
6789
  latest.getId()
@@ -6464,6 +6798,86 @@ public class CapacitorUpdaterPlugin extends Plugin {
6464
6798
  return;
6465
6799
  }
6466
6800
  }
6801
+ if (
6802
+ latest != null &&
6803
+ (!latest.isDownloaded() ||
6804
+ !CapacitorUpdaterPlugin.this.implementation.isBundleOnDisk(latest.getId()) ||
6805
+ BundleStatus.DOWNLOADING == latest.getStatus() ||
6806
+ latest.isErrorStatus() ||
6807
+ latest.isDeleted() ||
6808
+ latest.isDeleting()) &&
6809
+ CapacitorUpdaterPlugin.this.shouldRetryIncompleteDownload(latest, latestVersionName, current)
6810
+ ) {
6811
+ logger.info(
6812
+ "Latest bundle already exists in incomplete state (" +
6813
+ latest.getStatus() +
6814
+ ") and will be deleted, download will overwrite it."
6815
+ );
6816
+ // Every replacement of a stored record for this version consumes a retry slot.
6817
+ retryDownloadSlot = true;
6818
+ synchronized (CapacitorUpdaterPlugin.this) {
6819
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6820
+ return;
6821
+ }
6822
+ // Compare and clear under nextBundleLock so a concurrent next(B) is preserved.
6823
+ if (latest.getId() != null) {
6824
+ CapacitorUpdaterPlugin.this.implementation.clearNextBundleIfMatches(latest.getId());
6825
+ }
6826
+ }
6827
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6828
+ return;
6829
+ }
6830
+ // Persist the retry before deleting the record that proves it, so process death
6831
+ // between the delete and the download start cannot hand out a free retry.
6832
+ CapacitorUpdaterPlugin.this.implementation.reserveIncompleteDownloadRetry(latestVersionName);
6833
+ boolean incompleteDeleted = false;
6834
+ try {
6835
+ incompleteDeleted = Boolean.TRUE.equals(
6836
+ CapacitorUpdaterPlugin.this.implementation.delete(latest.getId(), true)
6837
+ );
6838
+ if (incompleteDeleted) {
6839
+ logger.info("Incomplete bundle deleted: " + latest.toString());
6840
+ } else {
6841
+ logger.error("Failed to delete incomplete bundle: " + latest.toString());
6842
+ }
6843
+ } catch (final IOException e) {
6844
+ logger.error(
6845
+ "Failed to delete incomplete bundle: " + latest.getVersionName() + " " + e.getMessage()
6846
+ );
6847
+ }
6848
+ if (
6849
+ !incompleteDeleted &&
6850
+ !CapacitorUpdaterPlugin.this.implementation.hasStoredBundleInfoForRetry(latest.getId())
6851
+ ) {
6852
+ // Already removed in this check (e.g. a DELETED tombstone cleaned just above).
6853
+ incompleteDeleted = true;
6854
+ }
6855
+ if (!incompleteDeleted) {
6856
+ // A pending deletion resumes with a version-wide cancel and would kill the
6857
+ // replacement. End this cycle; the reservation keeps the retry charged.
6858
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6859
+ "Incomplete bundle deletion is still pending. Retrying later.",
6860
+ latestVersionName,
6861
+ current,
6862
+ true,
6863
+ plannedDirectUpdate,
6864
+ "download_fail",
6865
+ "downloadFailed",
6866
+ false,
6867
+ downloadContext
6868
+ );
6869
+ return;
6870
+ }
6871
+ if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6872
+ return;
6873
+ }
6874
+ latest = CapacitorUpdaterPlugin.this.implementation.getBundleInfoByName(latestVersionName);
6875
+ if (latest == null) {
6876
+ latest = CapacitorUpdaterPlugin.this.implementation.findRegistryBundleByVersionName(
6877
+ latestVersionName
6878
+ );
6879
+ }
6880
+ }
6467
6881
  }
6468
6882
  // The store refuses these downloads without a callback, so end the cycle here
6469
6883
  // (appReady, splash hide) like iOS does.
@@ -6482,6 +6896,25 @@ public class CapacitorUpdaterPlugin extends Plugin {
6482
6896
  );
6483
6897
  return;
6484
6898
  }
6899
+ if (
6900
+ CapacitorUpdaterPlugin.this.implementation.incompleteDownloadRetryCount(latestVersionName) >=
6901
+ CapgoUpdater.MAX_INCOMPLETE_DOWNLOAD_RETRIES
6902
+ ) {
6903
+ logger.error("Latest bundle exceeded incomplete download retries. Aborting update.");
6904
+ // No transfer starts here, so no new download_fail is reported.
6905
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6906
+ "Latest version is in error state. Aborting update.",
6907
+ latestVersionName,
6908
+ current,
6909
+ true,
6910
+ plannedDirectUpdate,
6911
+ "download_fail",
6912
+ "downloadFailed",
6913
+ false,
6914
+ downloadContext
6915
+ );
6916
+ return;
6917
+ }
6485
6918
  final boolean retryingInFlightDownload =
6486
6919
  latest != null &&
6487
6920
  BundleStatus.DOWNLOADING == latest.getStatus() &&
@@ -6500,7 +6933,17 @@ public class CapacitorUpdaterPlugin extends Plugin {
6500
6933
  directUpdateStillAllowed
6501
6934
  : directUpdateStillAllowed;
6502
6935
  }
6936
+ // Any download after an earlier failed attempt of this version is a charged retry,
6937
+ // whether or not a stored row was left behind.
6938
+ if (
6939
+ CapacitorUpdaterPlugin.this.implementation.incompleteDownloadRetryCount(latestVersionName) > 0 ||
6940
+ CapacitorUpdaterPlugin.this.implementation.isIntegrityBlockedVersion(latestVersionName)
6941
+ ) {
6942
+ retryDownloadSlot = true;
6943
+ }
6944
+ final boolean consumeRetrySlotOnStart = retryDownloadSlot;
6503
6945
  startNewThread(() -> {
6946
+ boolean retryCharged = false;
6504
6947
  try {
6505
6948
  if (!CapacitorUpdaterPlugin.this.ownsBackgroundDownload(downloadContext)) {
6506
6949
  return;
@@ -6523,6 +6966,50 @@ public class CapacitorUpdaterPlugin extends Plugin {
6523
6966
  final String checksum = jsRes.has("checksum") ? jsRes.getString("checksum") : "";
6524
6967
 
6525
6968
  final JSONArray manifest = jsRes.has("manifest") ? jsRes.getJSONArray("manifest") : null;
6969
+ if (
6970
+ manifest == null &&
6971
+ (consumeRetrySlotOnStart ||
6972
+ CapacitorUpdaterPlugin.this.implementation.hasIncompleteDownloadRetryReservation(
6973
+ latestVersionName
6974
+ )) &&
6975
+ !CapacitorUpdaterPlugin.this.implementation.hasDiskSpaceForZipDownload()
6976
+ ) {
6977
+ // The ZIP worker would refuse before any request: do not spend a retry slot on it.
6978
+ logger.error("Insufficient disk space for retry download of " + latestVersionName);
6979
+ CapacitorUpdaterPlugin.this.implementation.sendStats("insufficient_disk_space", latestVersionName);
6980
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
6981
+ "Insufficient disk space. Retrying later.",
6982
+ latestVersionName,
6983
+ current,
6984
+ true,
6985
+ plannedDirectUpdate,
6986
+ "download_fail",
6987
+ "downloadFailed",
6988
+ false,
6989
+ downloadContext
6990
+ );
6991
+ return;
6992
+ }
6993
+ final int retryCharge = CapacitorUpdaterPlugin.this.implementation.chargeIncompleteDownloadRetry(
6994
+ latestVersionName,
6995
+ consumeRetrySlotOnStart
6996
+ );
6997
+ if (retryCharge == CapgoUpdater.RETRY_REFUSED) {
6998
+ logger.error("Latest bundle exceeded incomplete download retries. Aborting update.");
6999
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
7000
+ "Latest version is in error state. Aborting update.",
7001
+ latestVersionName,
7002
+ current,
7003
+ true,
7004
+ plannedDirectUpdate,
7005
+ "download_fail",
7006
+ "downloadFailed",
7007
+ false,
7008
+ downloadContext
7009
+ );
7010
+ return;
7011
+ }
7012
+ retryCharged = retryCharge == CapgoUpdater.RETRY_CHARGED;
6526
7013
  final CapgoUpdater.BackgroundDownloadResult result =
6527
7014
  CapacitorUpdaterPlugin.this.implementation.downloadBackground(
6528
7015
  url,
@@ -6533,6 +7020,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
6533
7020
  CapacitorUpdaterPlugin.this.shouldAutoSetNextBundle(),
6534
7021
  downloadContext
6535
7022
  );
7023
+ CapacitorUpdaterPlugin.this.implementation.settleIncompleteDownloadRetry(
7024
+ latestVersionName,
7025
+ retryCharged,
7026
+ result.status == CapgoUpdater.BackgroundDownloadResult.Status.STARTED,
7027
+ result.status == CapgoUpdater.BackgroundDownloadResult.Status.REUSED
7028
+ );
7029
+ retryCharged = false;
6536
7030
  if (result.status == CapgoUpdater.BackgroundDownloadResult.Status.NOT_STARTED) {
6537
7031
  CapacitorUpdaterPlugin.this.endFailedBackgroundDownload(
6538
7032
  latestVersionName,
@@ -6542,6 +7036,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
6542
7036
  }
6543
7037
  } catch (final Exception e) {
6544
7038
  logger.error("error downloading file " + e.getMessage());
7039
+ CapacitorUpdaterPlugin.this.implementation.settleIncompleteDownloadRetry(
7040
+ latestVersionName,
7041
+ retryCharged,
7042
+ false,
7043
+ false
7044
+ );
6545
7045
  CapacitorUpdaterPlugin.this.endFailedBackgroundDownload(
6546
7046
  latestVersionName,
6547
7047
  plannedDirectUpdate,