@capgo/capacitor-updater 8.53.1 → 8.54.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.
@@ -117,6 +117,13 @@ public class CapgoUpdater {
117
117
  public String publicKey = "";
118
118
  public String deviceID = "";
119
119
  public int timeout = 20000;
120
+ /** Refuse bundles whose version is below the native app version (versionBuild). Config builtinMinimum, default false. */
121
+ public volatile boolean builtinMinimum = false;
122
+ /**
123
+ * Require https for every URL the updater downloads from. Config httpsOnly, default true. Mirrors
124
+ * DownloadService.httpsOnly (the OkHttp interceptor); this field gates URLs before any network IO.
125
+ */
126
+ public volatile boolean httpsOnly = true;
120
127
 
121
128
  // Cached key ID calculated once from publicKey
122
129
  private String cachedKeyId = "";
@@ -144,6 +151,10 @@ public class CapgoUpdater {
144
151
  private final AtomicBoolean statsFlushInFlight = new AtomicBoolean(false);
145
152
  private final AtomicBoolean statsStopped = new AtomicBoolean(false);
146
153
  private static final long STATS_FLUSH_INTERVAL_MS = 1000;
154
+ private static volatile Long statsFlushIntervalOverrideMs = null;
155
+ private static volatile boolean statsFlushSchedulingDisabledForTests = false;
156
+ /** Unit tests only: runs after queue mutation and before the stats owner check. */
157
+ static volatile Runnable statsAdoptionBeforeOwnerCheckForTests = null;
147
158
  private static final String PENDING_STATS_FILE = "capgo_pending_stats.json";
148
159
  private static final int MAX_PENDING_STATS = 200;
149
160
  // The live plugin instance owns the stats file. A headless worker hands its unsent events to it
@@ -640,6 +651,96 @@ public class CapgoUpdater {
640
651
  }
641
652
  }
642
653
 
654
+ static boolean isHttpsUrl(final String url) {
655
+ if (url == null) {
656
+ return false;
657
+ }
658
+ final String trimmed = url.trim();
659
+ return trimmed.regionMatches(true, 0, "https://", 0, "https://".length());
660
+ }
661
+
662
+ static String httpsOnlyMessage(final String url) {
663
+ return "httpsOnly is enabled and " + url + " is not https";
664
+ }
665
+
666
+ /** httpsOnly gate for the zip url and every manifest download_url, run before any network IO. */
667
+ void requireHttpsUrls(final String url, final JSONArray manifest) throws IOException {
668
+ if (!this.httpsOnly) {
669
+ return;
670
+ }
671
+ if (manifest == null || manifest.length() == 0) {
672
+ if (!isHttpsUrl(url)) {
673
+ logger.error(httpsOnlyMessage(url));
674
+ throw new IOException(httpsOnlyMessage(url));
675
+ }
676
+ return;
677
+ }
678
+ for (int i = 0; i < manifest.length(); i++) {
679
+ final JSONObject entry = manifest.optJSONObject(i);
680
+ final String downloadUrl = entry == null ? null : entry.optString("download_url", "");
681
+ if (!isHttpsUrl(downloadUrl)) {
682
+ logger.error(httpsOnlyMessage(downloadUrl));
683
+ throw new IOException(httpsOnlyMessage(downloadUrl));
684
+ }
685
+ }
686
+ }
687
+
688
+ static String stripBuildMetadata(final String version) {
689
+ if (version == null) {
690
+ return null;
691
+ }
692
+ final int plus = version.indexOf('+');
693
+ return plus >= 0 ? version.substring(0, plus) : version;
694
+ }
695
+
696
+ /** Compares major.minor.patch only (missing components count as 0); suffix and extra components are ignored. */
697
+ static int compareCoreVersion(final Version left, final Version right) {
698
+ for (int i = 0; i < 3; i++) {
699
+ final long a = i < left.getSubversionNumbers().size() ? left.getSubversionNumbers().get(i) : 0L;
700
+ final long b = i < right.getSubversionNumbers().size() ? right.getSubversionNumbers().get(i) : 0L;
701
+ if (a != b) {
702
+ return Long.compare(a, b);
703
+ }
704
+ }
705
+ return 0;
706
+ }
707
+
708
+ static boolean isParsableVersion(final Version version) {
709
+ return version != null && version.getOriginalString() != null && !version.getSubversionNumbers().isEmpty();
710
+ }
711
+
712
+ /**
713
+ * builtinMinimum gate: a bundle may never roll the app below its native version. Skipped (debug log) when
714
+ * either version string does not parse, so unversioned bundles keep working.
715
+ */
716
+ void requireVersionNotBelowBuiltin(final String version) throws IOException {
717
+ if (!this.builtinMinimum) {
718
+ return;
719
+ }
720
+ // Build metadata (+...) never takes part in ordering.
721
+ final Version bundle = new Version(stripBuildMetadata(version));
722
+ final Version nativeVersion = new Version(stripBuildMetadata(this.versionBuild));
723
+ if (!isParsableVersion(bundle) || !isParsableVersion(nativeVersion)) {
724
+ logger.debug(
725
+ "builtinMinimum skipped: cannot parse bundle version '" + version + "' or native version '" + this.versionBuild + "'"
726
+ );
727
+ return;
728
+ }
729
+ // Only major.minor.patch matter: prerelease suffixes and a fourth component are not a rollback.
730
+ if (compareCoreVersion(bundle, nativeVersion) < 0) {
731
+ final String message = "Bundle version " + version + " is below native version " + this.versionBuild + " (builtinMinimum)";
732
+ logger.error(message);
733
+ this.sendStats("version_below_native", version);
734
+ throw new IOException(message);
735
+ }
736
+ }
737
+
738
+ /** Pre-network download gates shared by every entry point: httpsOnly and builtinMinimum. */
739
+ void runPreDownloadSecurityGates(final String url, final String version, final JSONArray manifest) throws IOException {
740
+ this.requireHttpsUrls(url, manifest);
741
+ this.requireVersionNotBelowBuiltin(version);
742
+ }
743
+
643
744
  static boolean containsPathTraversalSegment(final String relativePath) {
644
745
  for (final String segment : relativePath.split("/")) {
645
746
  if ("..".equals(segment)) {
@@ -828,7 +929,7 @@ public class CapgoUpdater {
828
929
  continue;
829
930
  }
830
931
  try {
831
- copyFileAtomically(file, cacheFile);
932
+ DownloadService.linkOrCopyImmutableFile(file, cacheFile);
832
933
  } catch (IOException e) {
833
934
  logger.debug("Delta cache copy failed: " + file.getPath());
834
935
  }
@@ -1854,6 +1955,7 @@ public class CapgoUpdater {
1854
1955
  if (manifest == null) {
1855
1956
  this.requireBundleChecksum(checksum);
1856
1957
  }
1958
+ this.runPreDownloadSecurityGates(url, version, manifest);
1857
1959
  } catch (final IOException e) {
1858
1960
  logger.error("Download blocked: " + e.getMessage());
1859
1961
  return null;
@@ -1910,6 +2012,7 @@ public class CapgoUpdater {
1910
2012
  public BundleInfo download(final String url, final String version, final String sessionKey, final String checksum) throws IOException {
1911
2013
  this.requireSessionKeyForEncryptedUpdate(sessionKey);
1912
2014
  this.requireBundleChecksum(checksum);
2015
+ this.runPreDownloadSecurityGates(url, version, null);
1913
2016
  this.runDownloadGate();
1914
2017
  // Check for existing bundle with same version and clean up if in error state
1915
2018
  BundleInfo existingBundle = this.getBundleInfoByName(version);
@@ -1967,6 +2070,7 @@ public class CapgoUpdater {
1967
2070
  if (manifest == null) {
1968
2071
  return download(url, version, sessionKey, checksum);
1969
2072
  }
2073
+ this.runPreDownloadSecurityGates(url, version, manifest);
1970
2074
 
1971
2075
  // Check for existing bundle with same version and clean up if in error state
1972
2076
  BundleInfo existingBundle = this.getBundleInfoByName(version);
@@ -2274,6 +2378,13 @@ public class CapgoUpdater {
2274
2378
  state.fallbackBundleId == null || state.fallbackBundleId.isEmpty() ? BundleInfo.ID_BUILTIN : state.fallbackBundleId;
2275
2379
 
2276
2380
  this.editor.putString(this.CAP_SERVER_PATH, currentBundlePath);
2381
+ this.restoreResetStateRollbackTargets(state);
2382
+ }
2383
+
2384
+ void restoreResetStateRollbackTargets(final ResetState state) {
2385
+ final String fallbackBundleId =
2386
+ state.fallbackBundleId == null || state.fallbackBundleId.isEmpty() ? BundleInfo.ID_BUILTIN : state.fallbackBundleId;
2387
+
2277
2388
  this.editor.putString(FALLBACK_VERSION, fallbackBundleId);
2278
2389
  if (state.nextBundleId == null || state.nextBundleId.isEmpty()) {
2279
2390
  this.editor.remove(NEXT_VERSION);
@@ -2283,6 +2394,13 @@ public class CapgoUpdater {
2283
2394
  this.editor.commit();
2284
2395
  }
2285
2396
 
2397
+ void preserveFallbackForWatchdog(final ResetState state) {
2398
+ final String fallbackBundleId =
2399
+ state.fallbackBundleId == null || state.fallbackBundleId.isEmpty() ? BundleInfo.ID_BUILTIN : state.fallbackBundleId;
2400
+ this.editor.putString(FALLBACK_VERSION, fallbackBundleId);
2401
+ this.editor.commit();
2402
+ }
2403
+
2286
2404
  void prepareResetStateForTransition() {
2287
2405
  this.setCurrentBundle(new File("public"));
2288
2406
  this.setFallbackBundle(null);
@@ -2299,7 +2417,7 @@ public class CapgoUpdater {
2299
2417
  }
2300
2418
 
2301
2419
  boolean canSet(final BundleInfo bundle) {
2302
- return bundle != null && (bundle.isBuiltin() || this.bundleExists(bundle.getId()));
2420
+ return bundle != null && !bundle.isErrorStatus() && (bundle.isBuiltin() || this.bundleExists(bundle.getId()));
2303
2421
  }
2304
2422
 
2305
2423
  public Boolean set(final BundleInfo bundle) {
@@ -3553,20 +3671,30 @@ public class CapgoUpdater {
3553
3671
  return true;
3554
3672
  }
3555
3673
  final List<QueuedStatsEvent> displaced = new ArrayList<>();
3674
+ final List<QueuedStatsEvent> adopted = new ArrayList<>();
3556
3675
  synchronized (statsQueue) {
3557
3676
  if (statsStopped.get()) {
3558
3677
  return false;
3559
3678
  }
3560
3679
  for (final JSONObject event : events) {
3561
3680
  while (statsQueue.size() >= MAX_PENDING_STATS) {
3562
- displaced.add(0, statsQueue.remove(0));
3681
+ final QueuedStatsEvent removed = statsQueue.remove(0);
3682
+ if (!adopted.contains(removed)) {
3683
+ displaced.add(removed);
3684
+ }
3563
3685
  }
3564
- statsQueue.add(new QueuedStatsEvent(event, null));
3686
+ final QueuedStatsEvent queued = new QueuedStatsEvent(event, null);
3687
+ statsQueue.add(queued);
3688
+ adopted.add(queued);
3565
3689
  }
3566
3690
  }
3691
+ final Runnable beforeOwnerCheck = statsAdoptionBeforeOwnerCheckForTests;
3692
+ if (beforeOwnerCheck != null) {
3693
+ beforeOwnerCheck.run();
3694
+ }
3567
3695
  synchronized (statsOwnerLock) {
3568
3696
  if (statsOwner != null && statsOwner != this) {
3569
- rollbackAdoptedEvents(events.size(), displaced);
3697
+ rollbackAdoptedEvents(adopted, displaced);
3570
3698
  return false;
3571
3699
  }
3572
3700
  }
@@ -3575,21 +3703,58 @@ public class CapgoUpdater {
3575
3703
  return true;
3576
3704
  }
3577
3705
 
3578
- private void rollbackAdoptedEvents(final int adoptedCount, final List<QueuedStatsEvent> displaced) {
3706
+ private void rollbackAdoptedEvents(final List<QueuedStatsEvent> adopted, final List<QueuedStatsEvent> displaced) {
3579
3707
  synchronized (statsQueue) {
3580
- for (int removed = 0; removed < adoptedCount && !statsQueue.isEmpty(); removed++) {
3581
- statsQueue.remove(statsQueue.size() - 1);
3582
- }
3583
- for (int i = 0; i < displaced.size(); i++) {
3584
- statsQueue.add(i, displaced.get(i));
3708
+ statsQueue.removeAll(adopted);
3709
+ if (!displaced.isEmpty()) {
3710
+ statsQueue.addAll(0, displaced);
3585
3711
  }
3586
3712
  }
3587
3713
  }
3588
3714
 
3715
+ /** Unit tests only: disable scheduling or override the flush interval. */
3716
+ static void configureStatsFlushForTests(final Long intervalMs, final boolean schedulingEnabled) {
3717
+ statsFlushIntervalOverrideMs = intervalMs;
3718
+ statsFlushSchedulingDisabledForTests = !schedulingEnabled;
3719
+ }
3720
+
3721
+ /** Unit tests only: restore default stats flush scheduling. */
3722
+ static void resetStatsFlushForTests() {
3723
+ statsFlushIntervalOverrideMs = null;
3724
+ statsFlushSchedulingDisabledForTests = false;
3725
+ }
3726
+
3589
3727
  int pendingStatsCount() {
3590
3728
  return statsQueue.size();
3591
3729
  }
3592
3730
 
3731
+ void enqueuePendingStatsEventForTests(final String action) {
3732
+ try {
3733
+ final JSONObject json = new JSONObject();
3734
+ json.put("action", action);
3735
+ json.put("timestamp", 1);
3736
+ synchronized (statsQueue) {
3737
+ statsQueue.add(new QueuedStatsEvent(json, null));
3738
+ }
3739
+ } catch (final JSONException e) {
3740
+ throw new IllegalStateException(e);
3741
+ }
3742
+ }
3743
+
3744
+ List<String> pendingStatsActionsForTests() {
3745
+ final List<String> actions = new ArrayList<>();
3746
+ synchronized (statsQueue) {
3747
+ for (final QueuedStatsEvent queued : statsQueue) {
3748
+ try {
3749
+ actions.add(queued.event.getString("action"));
3750
+ } catch (final JSONException ignored) {
3751
+ actions.add("");
3752
+ }
3753
+ }
3754
+ }
3755
+ return actions;
3756
+ }
3757
+
3593
3758
  public void persistPendingStats() {
3594
3759
  persistStatsQueue();
3595
3760
  }
@@ -3708,16 +3873,12 @@ public class CapgoUpdater {
3708
3873
  }
3709
3874
 
3710
3875
  private synchronized void ensureStatsTimerStarted() {
3711
- if (statsStopped.get()) {
3876
+ if (statsStopped.get() || statsFlushSchedulingDisabledForTests) {
3712
3877
  return;
3713
3878
  }
3879
+ final long intervalMs = statsFlushIntervalOverrideMs != null ? statsFlushIntervalOverrideMs : STATS_FLUSH_INTERVAL_MS;
3714
3880
  if (statsFlushTask == null || statsFlushTask.isCancelled() || statsFlushTask.isDone()) {
3715
- statsFlushTask = statsScheduler.scheduleAtFixedRate(
3716
- this::flushStatsQueue,
3717
- STATS_FLUSH_INTERVAL_MS,
3718
- STATS_FLUSH_INTERVAL_MS,
3719
- TimeUnit.MILLISECONDS
3720
- );
3881
+ statsFlushTask = statsScheduler.scheduleAtFixedRate(this::flushStatsQueue, intervalMs, intervalMs, TimeUnit.MILLISECONDS);
3721
3882
  }
3722
3883
  }
3723
3884
 
@@ -145,11 +145,69 @@ public class CryptoCipher {
145
145
 
146
146
  public static void decryptFile(final File file, final String publicKey, final String ivSessionKey) throws IOException {
147
147
  if (publicKey.isEmpty() || !isValidSessionKey(ivSessionKey)) {
148
- if (logger != null) {
149
- logger.info("Encryption not set, no public key or session, ignored");
150
- }
148
+ if (logger != null) logger.info("Encryption not set, no public key or session, ignored");
151
149
  return;
152
150
  }
151
+ new DecryptionSession(publicKey, ivSessionKey).decryptFile(file);
152
+ }
153
+
154
+ // A manifest shares key setup, while each file still creates its own CBC cipher.
155
+ static final class DecryptionSession {
156
+
157
+ private final String publicKey;
158
+ private final String ivSessionKey;
159
+ private PreparedKey prepared;
160
+ private IOException failure;
161
+
162
+ DecryptionSession(String publicKey, String ivSessionKey) {
163
+ this.publicKey = publicKey;
164
+ this.ivSessionKey = ivSessionKey;
165
+ }
166
+
167
+ private synchronized PreparedKey key() throws IOException {
168
+ if (failure != null) throw new IOException(failure.getMessage(), failure);
169
+ if (prepared == null) {
170
+ try {
171
+ prepared = prepareDecryptionKey(publicKey, ivSessionKey);
172
+ } catch (IOException error) {
173
+ failure = error;
174
+ throw error;
175
+ } catch (RuntimeException error) {
176
+ // Malformed Base64 throws IllegalArgumentException: cache it like any other bad key.
177
+ failure = new IOException("AES file decryption failed: invalid session key", error);
178
+ throw failure;
179
+ }
180
+ }
181
+ return prepared;
182
+ }
183
+
184
+ boolean isEncrypted() {
185
+ return publicKey != null && !publicKey.isEmpty();
186
+ }
187
+
188
+ void decryptFile(File file) throws IOException {
189
+ if (!isEncrypted()) {
190
+ if (logger != null) logger.info("Encryption not set, no public key or session, ignored");
191
+ return;
192
+ }
193
+ PreparedKey key = key();
194
+ decryptAesFile(file, key.key, key.iv);
195
+ }
196
+ }
197
+
198
+ private static final class PreparedKey {
199
+
200
+ final SecretKey key;
201
+ final byte[] iv;
202
+
203
+ PreparedKey(SecretKey key, byte[] iv) {
204
+ this.key = key;
205
+ this.iv = iv;
206
+ }
207
+ }
208
+
209
+ private static PreparedKey prepareDecryptionKey(String publicKey, String ivSessionKey) throws IOException {
210
+ if (!isValidSessionKey(ivSessionKey)) throw new IOException("AES file decryption failed: session key is required");
153
211
  // The bundle is encrypted from here on: an unusable key must fail, never leave it encrypted.
154
212
  if (!publicKey.startsWith("-----BEGIN RSA PUBLIC KEY-----")) {
155
213
  if (logger != null) {
@@ -173,7 +231,7 @@ public class CryptoCipher {
173
231
  }
174
232
 
175
233
  SecretKey sKey = CryptoCipher.byteToSessionKey(decryptedSessionKey);
176
- decryptAesFile(file, sKey, iv);
234
+ return new PreparedKey(sKey, iv);
177
235
  } catch (GeneralSecurityException e) {
178
236
  if (logger != null) {
179
237
  logger.info("decryptFile fail");
@@ -395,27 +453,32 @@ public class CryptoCipher {
395
453
  }
396
454
 
397
455
  public static String calcChecksum(InputStream inputStream) {
398
- final int BUFFER_SIZE = checksumBufferBytes();
399
- MessageDigest digest;
400
456
  try {
401
- digest = MessageDigest.getInstance("SHA-256");
402
- } catch (java.security.NoSuchAlgorithmException e) {
403
- logger.error("SHA-256 algorithm not available");
457
+ return calcChecksumOrThrow(inputStream);
458
+ } catch (IOException error) {
459
+ logger.error("Cannot calculate checksum");
460
+ logger.debug("Error: " + error.getMessage());
404
461
  return "";
405
462
  }
463
+ }
464
+
465
+ static String calcChecksumOrThrow(File file) throws IOException {
466
+ try (FileInputStream input = new FileInputStream(file)) {
467
+ return calcChecksumOrThrow(input);
468
+ }
469
+ }
406
470
 
471
+ static String calcChecksumOrThrow(InputStream input) throws IOException {
472
+ final MessageDigest digest;
407
473
  try {
408
- byte[] buffer = new byte[BUFFER_SIZE];
409
- int length;
410
- while ((length = inputStream.read(buffer)) != -1) {
411
- digest.update(buffer, 0, length);
412
- }
413
- return digestToHex(digest);
414
- } catch (IOException e) {
415
- logger.error("Cannot calculate checksum");
416
- logger.debug("Error: " + e.getMessage());
417
- return "";
474
+ digest = MessageDigest.getInstance("SHA-256");
475
+ } catch (java.security.NoSuchAlgorithmException error) {
476
+ throw new IOException("SHA-256 algorithm not available", error);
418
477
  }
478
+ byte[] buffer = new byte[checksumBufferBytes()];
479
+ int length;
480
+ while ((length = input.read(buffer)) != -1) digest.update(buffer, 0, length);
481
+ return digestToHex(digest);
419
482
  }
420
483
 
421
484
  static String digestToHex(MessageDigest digest) {