@capgo/capacitor-updater 6.51.21 → 6.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/CapgoCapacitorUpdater.podspec +0 -3
  2. package/Package.swift +3 -11
  3. package/README.md +202 -67
  4. package/android/build.gradle +2 -3
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +610 -177
  6. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +909 -196
  7. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +53 -19
  8. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +226 -106
  9. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +210 -58
  10. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +325 -0
  11. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +63 -4
  12. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  14. package/dist/docs.json +394 -27
  15. package/dist/esm/definitions.d.ts +220 -7
  16. package/dist/esm/definitions.js.map +1 -1
  17. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +104 -52
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +562 -187
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  20. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +564 -109
  21. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +11 -2
  22. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +204 -93
  23. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +75 -5
  24. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  25. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +53 -0
  26. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +9 -3
  27. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  28. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  29. package/package.json +7 -3
@@ -11,8 +11,11 @@ import android.content.Context;
11
11
  import android.content.SharedPreferences;
12
12
  import android.content.pm.PackageManager;
13
13
  import android.os.Build;
14
+ import android.os.Handler;
15
+ import android.os.Looper;
14
16
  import androidx.annotation.NonNull;
15
- import androidx.lifecycle.LifecycleOwner;
17
+ import androidx.lifecycle.LiveData;
18
+ import androidx.lifecycle.Observer;
16
19
  import androidx.work.Constraints;
17
20
  import androidx.work.Data;
18
21
  import androidx.work.ExistingPeriodicWorkPolicy;
@@ -33,6 +36,7 @@ import java.io.FilenameFilter;
33
36
  import java.io.IOException;
34
37
  import java.io.InputStreamReader;
35
38
  import java.nio.charset.StandardCharsets;
39
+ import java.nio.file.Files;
36
40
  import java.security.SecureRandom;
37
41
  import java.util.ArrayList;
38
42
  import java.util.Date;
@@ -49,8 +53,10 @@ import java.util.concurrent.ConcurrentHashMap;
49
53
  import java.util.concurrent.CopyOnWriteArrayList;
50
54
  import java.util.concurrent.ExecutorService;
51
55
  import java.util.concurrent.Executors;
56
+ import java.util.concurrent.LinkedBlockingQueue;
52
57
  import java.util.concurrent.ScheduledExecutorService;
53
58
  import java.util.concurrent.ScheduledFuture;
59
+ import java.util.concurrent.ThreadPoolExecutor;
54
60
  import java.util.concurrent.TimeUnit;
55
61
  import java.util.concurrent.atomic.AtomicBoolean;
56
62
  import java.util.zip.ZipEntry;
@@ -76,6 +82,9 @@ public class CapgoUpdater {
76
82
  private static final String PENDING_DELETE_IDS = "pendingDeleteIds";
77
83
  private static final String bundleDirectory = "versions";
78
84
  private static final String TEMP_UNZIP_PREFIX = "capgo_unzip_";
85
+ static final String MANIFEST_STAGING_PREFIX = "capgo_manifest_";
86
+ static final String MANIFEST_DEST_SUFFIX = "_manifest_dest";
87
+ private static final String LEGACY_MANIFEST_STAGING_FOLDER_PATTERN = "^[0-9A-Za-z]{10}$";
79
88
  private static final long DELETE_PACE_MS = 75L;
80
89
  private final Object deleteLock = new Object();
81
90
  private static final String CAPACITOR_CONFIG_ASSET = "capacitor.config.json";
@@ -93,6 +102,9 @@ public class CapgoUpdater {
93
102
  public File noBackupDir;
94
103
  public Boolean directUpdate = false;
95
104
  public Activity activity;
105
+ // Application context: lets downloads run and finish without an Activity (app in the
106
+ // background, or a process woken by a push with no UI at all).
107
+ public Context appContext;
96
108
  public String pluginVersion = "";
97
109
  public String versionBuild = "";
98
110
  public String versionCode = "";
@@ -137,20 +149,52 @@ public class CapgoUpdater {
137
149
  private static final long STATS_FLUSH_INTERVAL_MS = 1000;
138
150
  private static final String PENDING_STATS_FILE = "capgo_pending_stats.json";
139
151
  private static final int MAX_PENDING_STATS = 200;
152
+ // The live plugin instance owns the stats file. A headless worker hands its unsent events to it
153
+ // instead of writing the file; events handed over before the plugin claims ownership wait here.
154
+ private static final Object statsOwnerLock = new Object();
155
+ private static CapgoUpdater statsOwner = null;
156
+ private static final List<JSONObject> orphanedStats = new ArrayList<>();
140
157
 
141
158
  private static final class QueuedStatsEvent {
142
159
 
143
160
  private final JSONObject event;
144
161
  private final Runnable onSent;
162
+ /** True when the event was loaded from the shared pending-stats file (not created by this instance). */
163
+ private final boolean restored;
145
164
 
146
165
  private QueuedStatsEvent(final JSONObject event, final Runnable onSent) {
166
+ this(event, onSent, false);
167
+ }
168
+
169
+ private QueuedStatsEvent(final JSONObject event, final Runnable onSent, final boolean restored) {
147
170
  this.event = event;
148
171
  this.onSent = onSent;
172
+ this.restored = restored;
149
173
  }
150
174
  }
151
175
 
152
176
  private final Map<String, CompletableFuture<BundleInfo>> downloadFutures = new ConcurrentHashMap<>();
153
- private final ExecutorService io = Executors.newSingleThreadExecutor();
177
+
178
+ /** A download failure whose downloadFailed event and stats were already sent by the updater. */
179
+ static final class ReportedDownloadFailureException extends IOException {
180
+
181
+ ReportedDownloadFailureException(final String message) {
182
+ super(message);
183
+ }
184
+ }
185
+
186
+ // Versions whose WorkManager download is observed by this process. WorkManager persists work across a
187
+ // process kill, but the observer that finishes the download does not survive it.
188
+ private final Set<String> observedDownloadVersions = ConcurrentHashMap.newKeySet();
189
+ private final ExecutorService io = createIoExecutor();
190
+
191
+ private static ExecutorService createIoExecutor() {
192
+ final ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
193
+ executor.allowCoreThreadTimeOut(true);
194
+ return executor;
195
+ }
196
+
197
+ private volatile Handler mainHandler;
154
198
 
155
199
  public CapgoUpdater(Logger logger) {
156
200
  this.logger = logger;
@@ -161,12 +205,22 @@ public class CapgoUpdater {
161
205
  return !name.startsWith("__MACOSX") && !name.startsWith(".") && !name.startsWith(".DS_Store");
162
206
  };
163
207
 
208
+ /** The Activity when the app has one, otherwise the application context. */
209
+ Context context() {
210
+ final Activity current = this.activity;
211
+ if (current != null) {
212
+ return current;
213
+ }
214
+ return this.appContext;
215
+ }
216
+
164
217
  private boolean isProd() {
165
218
  try {
166
- if (activity == null) {
167
- return true; // Default to production if no activity context
219
+ final Context context = this.context();
220
+ if (context == null) {
221
+ return true; // Default to production if no context
168
222
  }
169
- return (activity.getApplicationInfo().flags & android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) == 0;
223
+ return (context.getApplicationInfo().flags & android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) == 0;
170
224
  } catch (Exception e) {
171
225
  return true; // Default to production if we can't determine
172
226
  }
@@ -194,13 +248,14 @@ public class CapgoUpdater {
194
248
 
195
249
  @SuppressWarnings("deprecation")
196
250
  private String getInstallSource() {
197
- if (activity == null) {
251
+ final Context context = this.context();
252
+ if (context == null) {
198
253
  return "";
199
254
  }
200
255
 
201
256
  try {
202
- PackageManager packageManager = activity.getPackageManager();
203
- String packageName = activity.getPackageName();
257
+ PackageManager packageManager = context.getPackageManager();
258
+ String packageName = context.getPackageName();
204
259
  String installerPackageName;
205
260
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
206
261
  android.content.pm.InstallSourceInfo installSourceInfo = packageManager.getInstallSourceInfo(packageName);
@@ -255,14 +310,301 @@ public class CapgoUpdater {
255
310
 
256
311
  void directUpdateFinish(final BundleInfo latest) {}
257
312
 
313
+ /** Launch downloads have no waiter. The plugin emits appReady from here when WorkManager settles. */
314
+ void backgroundDownloadSettled(final BundleInfo bundle, final String status) {}
315
+
258
316
  void notifyListeners(final String id, final Map<String, Object> res) {}
259
317
 
318
+ /** A downloaded bundle was stored as next bundle and waits for its install moment. */
319
+ void nextBundleReady(final BundleInfo bundle) {}
320
+
321
+ static boolean shouldNotifyLaunchDownloadReady(
322
+ final boolean awaitedByCaller,
323
+ final boolean success,
324
+ final boolean directInstall,
325
+ final boolean previewSession
326
+ ) {
327
+ if (awaitedByCaller) {
328
+ return false;
329
+ }
330
+ if (!success) {
331
+ return true;
332
+ }
333
+ return !directInstall && !previewSession;
334
+ }
335
+
336
+ static boolean shouldRestartOrphanedDownload(final boolean observedByThisProcess) {
337
+ return !observedByThisProcess;
338
+ }
339
+
340
+ static boolean shouldReleaseLaunchWhileRetrying(
341
+ final boolean awaitedByCaller,
342
+ final boolean setNext,
343
+ final boolean directUpdate,
344
+ final boolean previewSession
345
+ ) {
346
+ return !awaitedByCaller && setNext && directUpdate && !previewSession;
347
+ }
348
+
349
+ static String launchDownloadReadyStatus(final boolean success, final boolean setNext) {
350
+ if (!success) {
351
+ return "Error downloading file";
352
+ }
353
+ if (setNext) {
354
+ return "update downloaded, will install next background";
355
+ }
356
+ return "update downloaded, autoUpdate onlyDownload";
357
+ }
358
+
260
359
  public String randomString() {
261
360
  final StringBuilder sb = new StringBuilder(10);
262
361
  for (int i = 0; i < 10; i++) sb.append(AB.charAt(rnd.nextInt(AB.length())));
263
362
  return sb.toString();
264
363
  }
265
364
 
365
+ static boolean isManifestStagingFolderName(final String name) {
366
+ if (name == null || !name.startsWith(MANIFEST_STAGING_PREFIX)) {
367
+ return false;
368
+ }
369
+ final String suffix = name.substring(MANIFEST_STAGING_PREFIX.length());
370
+ return suffix.length() == 10 && suffix.matches("[0-9A-Za-z]{10}");
371
+ }
372
+
373
+ String manifestStagingDest() {
374
+ return MANIFEST_STAGING_PREFIX + this.randomString();
375
+ }
376
+
377
+ private static boolean isLegacyBareManifestStagingFolderName(final String name) {
378
+ return name != null && name.matches(LEGACY_MANIFEST_STAGING_FOLDER_PATTERN);
379
+ }
380
+
381
+ private static boolean isSymbolicLinkEntry(final File file) {
382
+ return Files.isSymbolicLink(file.toPath());
383
+ }
384
+
385
+ private static boolean isRegularFileEntry(final File file) {
386
+ return file.isFile() && !isSymbolicLinkEntry(file);
387
+ }
388
+
389
+ private static boolean isRegularDirectoryEntry(final File file) {
390
+ return file.isDirectory() && !isSymbolicLinkEntry(file);
391
+ }
392
+
393
+ private static final long LEGACY_MANIFEST_STAGING_MIN_AGE_MS = 24L * 60L * 60L * 1000L;
394
+
395
+ private static boolean looksLikeLeakedManifestStaging(final File dir) {
396
+ if (dir == null || !isRegularDirectoryEntry(dir)) {
397
+ return false;
398
+ }
399
+ if (isRegularFileEntry(new File(dir, "index.html"))) {
400
+ return true;
401
+ }
402
+ if (isRegularDirectoryEntry(new File(dir, "assets"))) {
403
+ return true;
404
+ }
405
+ return isRegularDirectoryEntry(new File(dir, "www"));
406
+ }
407
+
408
+ private static boolean isOldEnoughForLegacyManifestCleanup(final File dir) {
409
+ final long ageMs = System.currentTimeMillis() - dir.lastModified();
410
+ return ageMs >= LEGACY_MANIFEST_STAGING_MIN_AGE_MS;
411
+ }
412
+
413
+ void saveManifestStagingDest(final String bundleId, final String dest) {
414
+ if (this.editor == null || bundleId == null || dest == null || dest.isEmpty()) {
415
+ return;
416
+ }
417
+ this.editor.putString(bundleId + MANIFEST_DEST_SUFFIX, dest);
418
+ this.editor.commit();
419
+ }
420
+
421
+ void clearManifestStagingDest(final String bundleId) {
422
+ if (this.editor == null || bundleId == null) {
423
+ return;
424
+ }
425
+ this.editor.remove(bundleId + MANIFEST_DEST_SUFFIX);
426
+ this.editor.commit();
427
+ }
428
+
429
+ void cleanupManifestStagingAfterDownloadFailed(final String bundleId, final String failedDest, final boolean failedManifest) {
430
+ if (failedManifest) {
431
+ this.deleteManifestStagingFolder(failedDest);
432
+ }
433
+ this.clearManifestStagingDest(bundleId);
434
+ }
435
+
436
+ void cleanupManifestStagingAfterDownloadCancelled(final String bundleId) {
437
+ final String cancelledDest = this.prefs != null ? this.prefs.getString(bundleId + MANIFEST_DEST_SUFFIX, null) : null;
438
+ this.deleteManifestStagingFolder(cancelledDest);
439
+ this.clearManifestStagingDest(bundleId);
440
+ }
441
+
442
+ Set<String> activeManifestStagingDests() {
443
+ final Set<String> activeDests = new HashSet<>();
444
+ if (this.prefs == null) {
445
+ return activeDests;
446
+ }
447
+ for (final BundleInfo info : this.list(true)) {
448
+ if (info == null || info.getId() == null || info.getId().isEmpty()) {
449
+ continue;
450
+ }
451
+ if (info.getStatus() != BundleStatus.DOWNLOADING) {
452
+ continue;
453
+ }
454
+ final String dest = this.prefs.getString(info.getId() + MANIFEST_DEST_SUFFIX, null);
455
+ if (dest != null && !dest.isEmpty()) {
456
+ activeDests.add(dest);
457
+ }
458
+ }
459
+ return activeDests;
460
+ }
461
+
462
+ public void deleteManifestStagingFolder(final String dest) {
463
+ if (this.documentsDir == null || dest == null || dest.isEmpty() || !isManifestStagingFolderName(dest)) {
464
+ return;
465
+ }
466
+ final File folder = new File(this.documentsDir, dest);
467
+ try {
468
+ this.assertPathInsideDocumentsDir(folder);
469
+ deleteManifestStagingTree(folder);
470
+ } catch (IOException e) {
471
+ logger.warn("Failed to delete manifest staging folder: " + e.getMessage());
472
+ }
473
+ }
474
+
475
+ static void deleteManifestStagingFolderAt(final File documentsDir, final String dest, final Logger log) {
476
+ if (documentsDir == null || dest == null || dest.isEmpty() || !isManifestStagingFolderName(dest)) {
477
+ return;
478
+ }
479
+ final File folder = new File(documentsDir, dest);
480
+ if (!folder.exists()) {
481
+ return;
482
+ }
483
+ try {
484
+ final File canonicalBase = documentsDir.getCanonicalFile();
485
+ final File canonicalTarget = folder.getCanonicalFile();
486
+ final String basePath = canonicalBase.getPath();
487
+ final String normalizedBasePath = basePath.endsWith(File.separator) ? basePath : basePath + File.separator;
488
+ final String targetPath = canonicalTarget.getPath();
489
+ if (!targetPath.equals(basePath) && !targetPath.startsWith(normalizedBasePath)) {
490
+ if (log != null) {
491
+ log.warn("Refusing unsafe manifest staging delete: " + folder.getAbsolutePath());
492
+ }
493
+ return;
494
+ }
495
+ if (canonicalTarget.isDirectory()) {
496
+ deleteManifestStagingTree(canonicalTarget);
497
+ } else if (!canonicalTarget.delete()) {
498
+ if (log != null) {
499
+ log.warn("Failed to delete manifest staging file: " + canonicalTarget.getAbsolutePath());
500
+ }
501
+ }
502
+ } catch (IOException e) {
503
+ if (log != null) {
504
+ log.warn("Failed to delete manifest staging folder: " + e.getMessage());
505
+ }
506
+ }
507
+ }
508
+
509
+ private static void deleteManifestStagingTree(final File file) throws IOException {
510
+ if (isSymbolicLinkEntry(file)) {
511
+ if (!file.delete()) {
512
+ throw new IOException("Failed to delete symlink: " + file);
513
+ }
514
+ return;
515
+ }
516
+ if (file.isDirectory()) {
517
+ final File[] entries = file.listFiles();
518
+ if (entries != null) {
519
+ for (final File entry : entries) {
520
+ deleteManifestStagingTree(entry);
521
+ }
522
+ }
523
+ }
524
+ if (!file.delete()) {
525
+ throw new IOException("Failed to delete: " + file);
526
+ }
527
+ }
528
+
529
+ public void cleanupOrphanedManifestStagingFolders(final Thread threadToCheck) {
530
+ if (this.documentsDir == null) {
531
+ logger.warn("Documents directory is null, skipping manifest staging cleanup");
532
+ return;
533
+ }
534
+
535
+ final File[] entries = this.documentsDir.listFiles();
536
+ if (entries == null) {
537
+ return;
538
+ }
539
+
540
+ final Set<String> protectedDests = this.activeManifestStagingDests();
541
+
542
+ for (final File entry : entries) {
543
+ if (threadToCheck != null && threadToCheck.isInterrupted()) {
544
+ logger.warn("cleanupOrphanedManifestStagingFolders was cancelled");
545
+ return;
546
+ }
547
+ if (!entry.isDirectory()) {
548
+ continue;
549
+ }
550
+ final String folderName = entry.getName();
551
+ if (!isManifestStagingFolderName(folderName)) {
552
+ continue;
553
+ }
554
+ if (protectedDests.contains(folderName)) {
555
+ continue;
556
+ }
557
+ try {
558
+ deleteManifestStagingTree(entry);
559
+ logger.info("Deleted orphaned manifest staging folder");
560
+ logger.debug("Folder: " + folderName);
561
+ } catch (IOException e) {
562
+ logger.error("Failed to delete orphaned manifest staging folder");
563
+ logger.debug("Folder: " + folderName + ", Error: " + e.getMessage());
564
+ }
565
+ }
566
+
567
+ this.cleanupLegacyBareManifestStagingFolders(threadToCheck, protectedDests);
568
+ }
569
+
570
+ private void cleanupLegacyBareManifestStagingFolders(final Thread threadToCheck, final Set<String> protectedDests) {
571
+ final File[] entries = this.documentsDir.listFiles();
572
+ if (entries == null) {
573
+ return;
574
+ }
575
+
576
+ for (final File entry : entries) {
577
+ if (threadToCheck != null && threadToCheck.isInterrupted()) {
578
+ logger.warn("cleanupLegacyBareManifestStagingFolders was cancelled");
579
+ return;
580
+ }
581
+ if (!entry.isDirectory()) {
582
+ continue;
583
+ }
584
+ final String folderName = entry.getName();
585
+ if (!isLegacyBareManifestStagingFolderName(folderName)) {
586
+ continue;
587
+ }
588
+ if (protectedDests.contains(folderName)) {
589
+ continue;
590
+ }
591
+ if (!looksLikeLeakedManifestStaging(entry)) {
592
+ continue;
593
+ }
594
+ if (!isOldEnoughForLegacyManifestCleanup(entry)) {
595
+ continue;
596
+ }
597
+ try {
598
+ deleteManifestStagingTree(entry);
599
+ logger.info("Deleted legacy bare manifest staging folder");
600
+ logger.debug("Folder: " + folderName);
601
+ } catch (IOException e) {
602
+ logger.error("Failed to delete legacy bare manifest staging folder");
603
+ logger.debug("Folder: " + folderName + ", Error: " + e.getMessage());
604
+ }
605
+ }
606
+ }
607
+
266
608
  public void setPublicKey(String publicKey) {
267
609
  // Empty string means no encryption - proceed normally
268
610
  if (publicKey == null || publicKey.isEmpty()) {
@@ -285,6 +627,31 @@ public class CapgoUpdater {
285
627
  this.cachedKeyId = CryptoCipher.calcKeyId(publicKey);
286
628
  }
287
629
 
630
+ private void requireSessionKeyForEncryptedUpdate(final String sessionKey) throws IOException {
631
+ if (!this.publicKey.isEmpty() && !CryptoCipher.isValidSessionKey(sessionKey)) {
632
+ logger.error("Public key present but no valid session key provided");
633
+ this.sendStats("session_key_required");
634
+ throw new IOException("Session key required when public key is present");
635
+ }
636
+ }
637
+
638
+ private void requireBundleChecksum(final String checksum) throws IOException {
639
+ if (checksum == null || checksum.isEmpty()) {
640
+ logger.error("No checksum provided");
641
+ this.sendStats("checksum_required");
642
+ throw new IOException("Checksum required");
643
+ }
644
+ }
645
+
646
+ static boolean containsPathTraversalSegment(final String relativePath) {
647
+ for (final String segment : relativePath.split("/")) {
648
+ if ("..".equals(segment)) {
649
+ return true;
650
+ }
651
+ }
652
+ return false;
653
+ }
654
+
288
655
  static File resolvePathInsideDirectory(final File baseDirectory, final String relativePath) throws IOException {
289
656
  if (relativePath == null || relativePath.isEmpty()) {
290
657
  throw new IOException("Invalid empty path");
@@ -292,6 +659,9 @@ public class CapgoUpdater {
292
659
  if (relativePath.contains("\\") || relativePath.indexOf('\0') >= 0) {
293
660
  throw new IOException("Invalid path separator");
294
661
  }
662
+ if (containsPathTraversalSegment(relativePath)) {
663
+ throw new IOException("Path traversal segments are not allowed");
664
+ }
295
665
  if (new File(relativePath).isAbsolute()) {
296
666
  throw new IOException("Absolute paths are not allowed");
297
667
  }
@@ -302,13 +672,18 @@ public class CapgoUpdater {
302
672
  final String targetPath = canonicalTarget.getPath();
303
673
  final String normalizedBasePath = basePath.endsWith(File.separator) ? basePath : basePath + File.separator;
304
674
 
305
- if (!targetPath.equals(basePath) && !targetPath.startsWith(normalizedBasePath)) {
675
+ // Require a strict child of the base. Equality would accept "." and wipe/write the root.
676
+ if (!targetPath.startsWith(normalizedBasePath)) {
306
677
  throw new IOException("Path escapes base directory: " + relativePath);
307
678
  }
308
679
 
309
680
  return canonicalTarget;
310
681
  }
311
682
 
683
+ static File resolveBundleDirectory(final File documentsDir, final String bundleId) throws IOException {
684
+ return resolvePathInsideDirectory(new File(documentsDir, bundleDirectory), bundleId);
685
+ }
686
+
312
687
  public String getKeyId() {
313
688
  return this.cachedKeyId;
314
689
  }
@@ -376,11 +751,11 @@ public class CapgoUpdater {
376
751
  }
377
752
  }
378
753
 
379
- private void flattenAssets(final File sourceFile, final String dest) throws IOException {
754
+ private void flattenAssets(final File sourceFile, final File destinationFile) throws IOException {
380
755
  if (!sourceFile.exists()) {
381
756
  throw new FileNotFoundException("Source file not found: " + sourceFile.getPath());
382
757
  }
383
- final File destinationFile = new File(this.documentsDir, dest);
758
+ assertPathInsideBundleRoot(destinationFile);
384
759
  Objects.requireNonNull(destinationFile.getParentFile()).mkdirs();
385
760
  final String[] entries = sourceFile.list(this.filter);
386
761
  if (entries == null || entries.length == 0) {
@@ -404,18 +779,24 @@ public class CapgoUpdater {
404
779
  }
405
780
 
406
781
  void cacheBundleFiles(final String id) {
407
- if (this.activity == null) {
408
- logger.debug("Skip delta cache population: activity is null");
782
+ if (this.context() == null) {
783
+ logger.debug("Skip delta cache population: no context");
409
784
  return;
410
785
  }
411
786
 
412
- final File bundleDir = this.getBundleDirectory(id);
787
+ final File bundleDir;
788
+ try {
789
+ bundleDir = this.getBundleDirectory(id);
790
+ } catch (IOException e) {
791
+ logger.debug("Skip delta cache population: invalid bundle id");
792
+ return;
793
+ }
413
794
  if (!bundleDir.exists()) {
414
795
  logger.debug("Skip delta cache population: bundle dir missing");
415
796
  return;
416
797
  }
417
798
 
418
- final File cacheDir = new File(this.activity.getCacheDir(), "capgo_downloads");
799
+ final File cacheDir = new File(this.context().getCacheDir(), "capgo_downloads");
419
800
  if (cacheDir.exists() && !cacheDir.isDirectory()) {
420
801
  logger.debug("Skip delta cache population: cache dir is not a directory");
421
802
  return;
@@ -425,7 +806,7 @@ public class CapgoUpdater {
425
806
  return;
426
807
  }
427
808
 
428
- final File builtinFolder = new File(this.activity.getFilesDir(), "public");
809
+ final File builtinFolder = new File(this.context().getFilesDir(), "public");
429
810
 
430
811
  final List<File> files = new ArrayList<>();
431
812
  collectFiles(bundleDir, files);
@@ -497,7 +878,10 @@ public class CapgoUpdater {
497
878
  if (fileHash.isEmpty()) {
498
879
  return "";
499
880
  }
500
- if (this.publicKey != null && !this.publicKey.isEmpty() && sessionKey != null && !sessionKey.isEmpty()) {
881
+ if (this.publicKey != null && !this.publicKey.isEmpty()) {
882
+ if (!CryptoCipher.isValidSessionKey(sessionKey)) {
883
+ return "";
884
+ }
501
885
  try {
502
886
  fileHash = CryptoCipher.decryptChecksum(fileHash, this.publicKey);
503
887
  } catch (Exception e) {
@@ -512,16 +896,16 @@ public class CapgoUpdater {
512
896
  private boolean isManifestEntryAvailableLocally(final JSONObject entry, final String sessionKey) {
513
897
  final String fileName = entry.optString("file_name", "");
514
898
  final String fileHash = resolveManifestFileHash(entry, sessionKey);
515
- if (fileName.isEmpty() || fileHash.isEmpty() || this.activity == null) {
899
+ if (fileName.isEmpty() || fileHash.isEmpty() || this.context() == null) {
516
900
  return false;
517
901
  }
518
902
 
519
- if (DownloadService.builtinAssetMatches(this.activity.getAssets(), fileName, fileHash)) {
903
+ if (DownloadService.builtinAssetMatches(this.context().getAssets(), fileName, fileHash)) {
520
904
  return true;
521
905
  }
522
906
 
523
907
  try {
524
- final File builtinFile = DownloadService.resolveManifestBuiltinFile(new File(this.activity.getFilesDir(), "public"), fileName);
908
+ final File builtinFile = DownloadService.resolveManifestBuiltinFile(new File(this.context().getFilesDir(), "public"), fileName);
525
909
  if (verifyChecksum(builtinFile, fileHash)) {
526
910
  return true;
527
911
  }
@@ -533,7 +917,7 @@ public class CapgoUpdater {
533
917
  final String fileNameWithoutPath = new File(fileName).getName();
534
918
  final String cacheBaseName = isBrotli ? fileNameWithoutPath.substring(0, fileNameWithoutPath.length() - 3) : fileNameWithoutPath;
535
919
  if (isSafeCacheHash(fileHash)) {
536
- final File cacheFolder = new File(this.activity.getCacheDir(), "capgo_downloads");
920
+ final File cacheFolder = new File(this.context().getCacheDir(), "capgo_downloads");
537
921
  final File cacheFile = new File(cacheFolder, fileHash + "_" + cacheBaseName);
538
922
  // Cache files are named `{hash}_{filename}` and were checksum-verified
539
923
  // when written. Re-hashing every hit re-reads the whole bundle and
@@ -661,115 +1045,183 @@ public class CapgoUpdater {
661
1045
  }
662
1046
  }
663
1047
 
664
- private void observeWorkProgress(Context context, String id, boolean setNext) {
665
- if (!(context instanceof LifecycleOwner)) {
666
- logger.error("Context is not a LifecycleOwner, cannot observe work progress");
667
- return;
668
- }
669
-
670
- activity.runOnUiThread(() -> {
671
- WorkManager.getInstance(context)
672
- .getWorkInfosByTagLiveData(id)
673
- .observe((LifecycleOwner) context, (workInfos) -> {
674
- if (workInfos == null || workInfos.isEmpty()) return;
675
-
676
- WorkInfo workInfo = workInfos.get(0);
677
- Data progress = workInfo.getProgress();
678
-
679
- switch (workInfo.getState()) {
680
- case RUNNING:
681
- int percent = progress.getInt(DownloadService.PERCENT, 0);
682
- notifyDownload(id, percent);
683
- break;
684
- case SUCCEEDED:
685
- logger.info("Download succeeded: " + workInfo.getState());
686
- Data outputData = workInfo.getOutputData();
687
- String dest = outputData.getString(DownloadService.FILEDEST);
688
- String version = outputData.getString(DownloadService.VERSION);
689
- String sessionKey = outputData.getString(DownloadService.SESSIONKEY);
690
- String checksum = outputData.getString(DownloadService.CHECKSUM);
691
- boolean isManifest = outputData.getBoolean(DownloadService.IS_MANIFEST, false);
692
-
693
- io.execute(() -> {
694
- boolean success = finishDownload(id, dest, version, sessionKey, checksum, setNext, isManifest);
695
- BundleInfo resultBundle;
696
- if (!success) {
697
- logger.error("Finish download failed");
698
- logger.debug("Version: " + version);
699
- resultBundle = new BundleInfo(
700
- id,
701
- version,
702
- BundleStatus.ERROR,
703
- new Date(System.currentTimeMillis()),
704
- ""
705
- );
706
- saveBundleInfo(id, resultBundle);
707
- // Cleanup download tracking
708
- DownloadWorkerManager.cancelBundleDownload(activity, id, version);
709
- Map<String, Object> ret = new HashMap<>();
710
- ret.put("version", version);
711
- ret.put("error", "finish_download_fail");
712
- sendStats("finish_download_fail", version);
713
- notifyListeners("downloadFailed", ret);
714
- } else {
715
- // Successful download - cleanup tracking
716
- DownloadWorkerManager.cancelBundleDownload(activity, id, version);
717
- resultBundle = getBundleInfo(id);
718
- }
1048
+ private void notifyLaunchDownloadReady(
1049
+ final boolean awaitedByCaller,
1050
+ final boolean success,
1051
+ final boolean directInstall,
1052
+ final boolean previewSession,
1053
+ final boolean setNext,
1054
+ final BundleInfo bundle
1055
+ ) {
1056
+ if (!shouldNotifyLaunchDownloadReady(awaitedByCaller, success, directInstall, previewSession)) {
1057
+ return;
1058
+ }
1059
+ final BundleInfo readyBundle = bundle != null ? bundle : this.getCurrentBundle();
1060
+ this.backgroundDownloadSettled(readyBundle, launchDownloadReadyStatus(success, setNext));
1061
+ }
1062
+
1063
+ // Created on first use: plain JVM unit tests construct CapgoUpdater without a main Looper.
1064
+ private Handler mainHandler() {
1065
+ Handler handler = this.mainHandler;
1066
+ if (handler == null) {
1067
+ handler = new Handler(Looper.getMainLooper());
1068
+ this.mainHandler = handler;
1069
+ }
1070
+ return handler;
1071
+ }
1072
+
1073
+ @SuppressWarnings("unchecked")
1074
+ private void observeWorkProgress(Context context, String id, String observedVersion, boolean setNext) {
1075
+ final AtomicBoolean terminalHandled = new AtomicBoolean(false);
1076
+ final AtomicBoolean launchReleasedWhileRetrying = new AtomicBoolean(false);
1077
+ final LiveData<List<WorkInfo>> workInfosLiveData = WorkManager.getInstance(
1078
+ context.getApplicationContext()
1079
+ ).getWorkInfosByTagLiveData(id);
1080
+ // observeForever, not observe(activity): a stopped Activity pauses LiveData, so a download
1081
+ // that completes while the app is in the background would only be finished once the user
1082
+ // opens the app again. The observer removes itself on a terminal state.
1083
+ final Observer<List<WorkInfo>>[] observerRef = new Observer[1];
1084
+ final Runnable removeObserver = () -> mainHandler().post(() -> workInfosLiveData.removeObserver(observerRef[0]));
1085
+ mainHandler().post(() -> {
1086
+ observerRef[0] = (workInfos) -> {
1087
+ if (workInfos == null || workInfos.isEmpty()) return;
1088
+
1089
+ WorkInfo workInfo = workInfos.get(0);
1090
+ Data progress = workInfo.getProgress();
1091
+
1092
+ switch (workInfo.getState()) {
1093
+ case ENQUEUED:
1094
+ // A run attempt already happened, so WorkManager scheduled a retry (network lost midway,
1095
+ // 5xx, ...). Retries back off without limit, so a direct install must not keep the launch
1096
+ // (and its splashscreen) blocked until the network comes back.
1097
+ if (
1098
+ workInfo.getRunAttemptCount() > 0 &&
1099
+ shouldReleaseLaunchWhileRetrying(
1100
+ downloadFutures.containsKey(id),
1101
+ setNext,
1102
+ Boolean.TRUE.equals(CapgoUpdater.this.directUpdate),
1103
+ CapgoUpdater.this.previewSession
1104
+ ) &&
1105
+ launchReleasedWhileRetrying.compareAndSet(false, true)
1106
+ ) {
1107
+ logger.warn("Direct update download is retrying, continuing launch on the current bundle");
1108
+ // Same fallback as the autoSplashscreen timeout: a later success installs on next background.
1109
+ CapgoUpdater.this.directUpdate = false;
1110
+ io.execute(() -> backgroundDownloadSettled(getCurrentBundle(), launchDownloadReadyStatus(false, false)));
1111
+ }
1112
+ break;
1113
+ case RUNNING:
1114
+ int percent = progress.getInt(DownloadService.PERCENT, 0);
1115
+ notifyDownload(id, percent);
1116
+ break;
1117
+ case SUCCEEDED:
1118
+ if (!terminalHandled.compareAndSet(false, true)) break;
1119
+ removeObserver.run();
1120
+ observedDownloadVersions.remove(observedVersion);
1121
+ logger.info("Download succeeded: " + workInfo.getState());
1122
+ Data outputData = workInfo.getOutputData();
1123
+ String dest = outputData.getString(DownloadService.FILEDEST);
1124
+ String version = outputData.getString(DownloadService.VERSION);
1125
+ String sessionKey = outputData.getString(DownloadService.SESSIONKEY);
1126
+ String checksum = outputData.getString(DownloadService.CHECKSUM);
1127
+ boolean isManifest = outputData.getBoolean(DownloadService.IS_MANIFEST, false);
1128
+
1129
+ io.execute(() -> {
1130
+ // finishDownload clears directUpdate, so read the install plan first.
1131
+ final boolean directInstall =
1132
+ setNext && Boolean.TRUE.equals(CapgoUpdater.this.directUpdate) && !CapgoUpdater.this.previewSession;
1133
+ final boolean previewSession = CapgoUpdater.this.previewSession;
1134
+ boolean success = finishDownload(id, dest, version, sessionKey, checksum, setNext, isManifest);
1135
+ BundleInfo resultBundle;
1136
+ if (!success) {
1137
+ logger.error("Finish download failed");
1138
+ logger.debug("Version: " + version);
1139
+ resultBundle = new BundleInfo(id, version, BundleStatus.ERROR, new Date(System.currentTimeMillis()), "");
1140
+ saveBundleInfo(id, resultBundle);
1141
+ // Cleanup download tracking
1142
+ DownloadWorkerManager.cancelBundleDownload(context, id, version);
1143
+ sendStats("finish_download_fail", version);
1144
+ // finishDownload already emitted downloadFailed for this failure.
1145
+ } else {
1146
+ // Successful download - cleanup tracking
1147
+ DownloadWorkerManager.cancelBundleDownload(context, id, version);
1148
+ resultBundle = getBundleInfo(id);
1149
+ }
719
1150
 
720
- // Complete the future if it exists
721
- CompletableFuture<BundleInfo> future = downloadFutures.remove(id);
722
- if (future != null) {
723
- future.complete(resultBundle);
724
- }
725
- });
726
- break;
727
- case FAILED:
728
- Data failedData = workInfo.getOutputData();
729
- String error = failedData.getString(DownloadService.ERROR);
730
- logger.error("Download failed");
731
- logger.debug("Error: " + error + ", State: " + workInfo.getState());
732
- String failedVersion = failedData.getString(DownloadService.VERSION);
733
-
734
- io.execute(() -> {
735
- BundleInfo failedBundle = new BundleInfo(
736
- id,
737
- failedVersion,
738
- BundleStatus.ERROR,
739
- new Date(System.currentTimeMillis()),
740
- ""
741
- );
742
- saveBundleInfo(id, failedBundle);
743
- // Cleanup download tracking for failed downloads
744
- DownloadWorkerManager.cancelBundleDownload(activity, id, failedVersion);
745
- Map<String, Object> ret = new HashMap<>();
746
- ret.put("version", failedVersion);
747
- if ("low_mem_fail".equals(error)) {
748
- sendStats("low_mem_fail", failedVersion);
749
- }
750
- if ("insufficient_disk_space".equals(error)) {
751
- sendStats("insufficient_disk_space", failedVersion);
752
- }
753
- ret.put("error", error != null ? error : "download_fail");
754
- sendStats("download_fail", failedVersion);
755
- notifyListeners("downloadFailed", ret);
756
-
757
- // Complete the future with error status
758
- CompletableFuture<BundleInfo> failedFuture = downloadFutures.remove(id);
759
- if (failedFuture != null) {
760
- failedFuture.complete(failedBundle);
761
- }
762
- });
763
- break;
764
- case CANCELLED:
765
- DataManager.getInstance().clearManifest(id);
766
- CompletableFuture<BundleInfo> cancelledFuture = downloadFutures.remove(id);
767
- if (cancelledFuture != null) {
768
- cancelledFuture.cancel(true);
1151
+ CapgoUpdater.this.clearManifestStagingDest(id);
1152
+
1153
+ // Complete the future if it exists. download() waits on it.
1154
+ // downloadBackground does not, so the launch check must emit appReady here.
1155
+ CompletableFuture<BundleInfo> future = downloadFutures.remove(id);
1156
+ if (future != null) {
1157
+ future.complete(resultBundle);
769
1158
  }
770
- break;
771
- }
772
- });
1159
+ final BundleInfo readyBundle = success && setNext ? resultBundle : null;
1160
+ if (!launchReleasedWhileRetrying.get()) {
1161
+ notifyLaunchDownloadReady(future != null, success, directInstall, previewSession, setNext, readyBundle);
1162
+ }
1163
+ });
1164
+ break;
1165
+ case FAILED:
1166
+ if (!terminalHandled.compareAndSet(false, true)) break;
1167
+ removeObserver.run();
1168
+ observedDownloadVersions.remove(observedVersion);
1169
+ Data failedData = workInfo.getOutputData();
1170
+ String error = failedData.getString(DownloadService.ERROR);
1171
+ logger.error("Download failed");
1172
+ logger.debug("Error: " + error + ", State: " + workInfo.getState());
1173
+ String failedVersion = failedData.getString(DownloadService.VERSION);
1174
+ final String failedDest = failedData.getString(DownloadService.FILEDEST);
1175
+ final boolean failedManifest = failedData.getBoolean(DownloadService.IS_MANIFEST, false);
1176
+
1177
+ io.execute(() -> {
1178
+ CapgoUpdater.this.cleanupManifestStagingAfterDownloadFailed(id, failedDest, failedManifest);
1179
+ BundleInfo failedBundle = new BundleInfo(
1180
+ id,
1181
+ failedVersion,
1182
+ BundleStatus.ERROR,
1183
+ new Date(System.currentTimeMillis()),
1184
+ ""
1185
+ );
1186
+ saveBundleInfo(id, failedBundle);
1187
+ // Cleanup download tracking for failed downloads
1188
+ DownloadWorkerManager.cancelBundleDownload(context, id, failedVersion);
1189
+ Map<String, Object> ret = new HashMap<>();
1190
+ ret.put("version", failedVersion);
1191
+ if ("low_mem_fail".equals(error)) {
1192
+ sendStats("low_mem_fail", failedVersion);
1193
+ }
1194
+ if ("insufficient_disk_space".equals(error)) {
1195
+ sendStats("insufficient_disk_space", failedVersion);
1196
+ }
1197
+ ret.put("error", error != null ? error : "download_fail");
1198
+ sendStats("download_fail", failedVersion);
1199
+ notifyListeners("downloadFailed", ret);
1200
+
1201
+ // Complete the future with error status
1202
+ CompletableFuture<BundleInfo> failedFuture = downloadFutures.remove(id);
1203
+ if (failedFuture != null) {
1204
+ failedFuture.complete(failedBundle);
1205
+ }
1206
+ if (!launchReleasedWhileRetrying.get()) {
1207
+ notifyLaunchDownloadReady(failedFuture != null, false, false, false, false, null);
1208
+ }
1209
+ });
1210
+ break;
1211
+ case CANCELLED:
1212
+ if (!terminalHandled.compareAndSet(false, true)) break;
1213
+ removeObserver.run();
1214
+ observedDownloadVersions.remove(observedVersion);
1215
+ DataManager.getInstance().clearManifest(id);
1216
+ io.execute(() -> CapgoUpdater.this.cleanupManifestStagingAfterDownloadCancelled(id));
1217
+ CompletableFuture<BundleInfo> cancelledFuture = downloadFutures.remove(id);
1218
+ if (cancelledFuture != null) {
1219
+ cancelledFuture.cancel(true);
1220
+ }
1221
+ break;
1222
+ }
1223
+ };
1224
+ workInfosLiveData.observeForever(observerRef[0]);
773
1225
  });
774
1226
  }
775
1227
 
@@ -783,18 +1235,21 @@ public class CapgoUpdater {
783
1235
  final JSONArray manifest,
784
1236
  final boolean setNext
785
1237
  ) {
786
- if (this.activity == null) {
787
- logger.error("Activity is null, cannot observe work progress");
1238
+ final Context context = this.context();
1239
+ if (context == null) {
1240
+ logger.error("No context, cannot observe work progress");
788
1241
  return;
789
1242
  }
790
- observeWorkProgress(this.activity, id, setNext);
1243
+ observedDownloadVersions.add(version);
1244
+ observeWorkProgress(context, id, version, setNext);
791
1245
 
792
1246
  if (manifest != null) {
793
1247
  DataManager.getInstance().setManifest(id, manifest);
1248
+ this.saveManifestStagingDest(id, dest);
794
1249
  }
795
1250
 
796
1251
  DownloadWorkerManager.enqueueDownload(
797
- this.activity,
1252
+ context,
798
1253
  url,
799
1254
  id,
800
1255
  this.documentsDir.getAbsolutePath(),
@@ -833,40 +1288,31 @@ public class CapgoUpdater {
833
1288
  String checksum = "";
834
1289
 
835
1290
  try {
1291
+ this.requireSessionKeyForEncryptedUpdate(sessionKey);
836
1292
  this.notifyDownload(id, 71);
837
1293
  downloaded = new File(this.documentsDir, dest);
838
1294
 
839
1295
  if (!isManifest) {
840
- String checksumDecrypted = Objects.requireNonNullElse(checksumRes, "");
841
-
842
- // If public key is present but no checksum provided, refuse installation
843
- if (!this.publicKey.isEmpty() && checksumDecrypted.isEmpty()) {
844
- logger.error("Public key present but no checksum provided");
845
- this.sendStats("checksum_required");
846
- throw new IOException("Checksum required when public key is present: " + id);
847
- }
1296
+ String expectedChecksum = Objects.requireNonNullElse(checksumRes, "");
1297
+ this.requireBundleChecksum(expectedChecksum);
848
1298
 
849
- if (!sessionKey.isEmpty()) {
1299
+ if (CryptoCipher.isValidSessionKey(sessionKey)) {
850
1300
  CryptoCipher.decryptFile(downloaded, publicKey, sessionKey);
851
- checksumDecrypted = CryptoCipher.decryptChecksum(checksumRes, publicKey);
852
- checksum = CryptoCipher.calcChecksum(downloaded);
853
- } else {
854
- checksum = CryptoCipher.calcChecksum(downloaded);
1301
+ expectedChecksum = CryptoCipher.decryptChecksum(checksumRes, publicKey);
855
1302
  }
1303
+ checksum = CryptoCipher.calcChecksum(downloaded);
856
1304
  CryptoCipher.logChecksumInfo("Calculated checksum", checksum);
857
- CryptoCipher.logChecksumInfo("Expected checksum", checksumDecrypted);
858
- if ((!checksumDecrypted.isEmpty() || !this.publicKey.isEmpty()) && !checksumDecrypted.equals(checksum)) {
1305
+ CryptoCipher.logChecksumInfo("Expected checksum", expectedChecksum);
1306
+ if (!expectedChecksum.equals(checksum)) {
859
1307
  logger.error("Checksum mismatch");
860
- logger.debug("Expected: " + checksumDecrypted + ", Got: " + checksum);
1308
+ logger.debug("Expected: " + expectedChecksum + ", Got: " + checksum);
861
1309
  this.sendStats("checksum_fail");
862
1310
  throw new IOException("Checksum failed: " + id);
863
1311
  }
864
1312
  }
865
1313
  // Remove the decryption for manifest downloads
866
1314
  } catch (Exception e) {
867
- if (!isManifest) {
868
- safeDelete(downloaded);
869
- }
1315
+ safeDelete(downloaded);
870
1316
  final Boolean res = this.delete(id);
871
1317
  if (!res) {
872
1318
  logger.info("Failed to cleanup after error");
@@ -885,13 +1331,11 @@ public class CapgoUpdater {
885
1331
  if (!isManifest) {
886
1332
  extractedDir = this.unzip(id, downloaded, TEMP_UNZIP_PREFIX + this.randomString());
887
1333
  this.notifyDownload(id, 91);
888
- final String idName = bundleDirectory + "/" + id;
889
- this.flattenAssets(extractedDir, idName);
1334
+ this.flattenAssets(extractedDir, this.getBundleDirectory(id));
890
1335
  this.cacheBundleFilesAsync(id);
891
1336
  } else {
892
1337
  this.notifyDownload(id, 91);
893
- final String idName = bundleDirectory + "/" + id;
894
- this.flattenAssets(downloaded, idName);
1338
+ this.flattenAssets(downloaded, this.getBundleDirectory(id));
895
1339
  downloaded.delete();
896
1340
  }
897
1341
  // Remove old bundle info and set new one
@@ -915,14 +1359,14 @@ public class CapgoUpdater {
915
1359
  this.directUpdate = false;
916
1360
  } else {
917
1361
  logger.info("directUpdate: " + this.directUpdate);
918
- this.setNextBundle(next.getId());
1362
+ if (this.setNextBundle(next.getId())) {
1363
+ this.nextBundleReady(next);
1364
+ }
919
1365
  }
920
1366
  }
921
1367
  } catch (IOException e) {
922
- if (!isManifest) {
923
- safeDelete(extractedDir);
924
- safeDelete(downloaded);
925
- }
1368
+ safeDelete(extractedDir);
1369
+ safeDelete(downloaded);
926
1370
  e.printStackTrace();
927
1371
  final Map<String, Object> ret = new HashMap<>();
928
1372
  ret.put("version", version);
@@ -964,11 +1408,11 @@ public class CapgoUpdater {
964
1408
  }
965
1409
 
966
1410
  public void cleanupDeltaCache(final Thread threadToCheck) {
967
- if (this.activity == null) {
1411
+ if (this.context() == null) {
968
1412
  logger.warn("Activity is null, skipping delta cache cleanup");
969
1413
  return;
970
1414
  }
971
- final File cacheFolder = new File(this.activity.getCacheDir(), "capgo_downloads");
1415
+ final File cacheFolder = new File(this.context().getCacheDir(), "capgo_downloads");
972
1416
  if (!cacheFolder.exists()) {
973
1417
  return;
974
1418
  }
@@ -1110,18 +1554,44 @@ public class CapgoUpdater {
1110
1554
  }
1111
1555
  }
1112
1556
 
1557
+ private void assertPathInsideDocumentsDir(final File target) throws IOException {
1558
+ if (this.documentsDir == null) {
1559
+ throw new IOException("Documents directory unavailable");
1560
+ }
1561
+ final File canonicalBase = this.documentsDir.getCanonicalFile();
1562
+ final File canonicalTarget = target.getCanonicalFile();
1563
+ final String basePath = canonicalBase.getPath();
1564
+ final String normalizedBasePath = basePath.endsWith(File.separator) ? basePath : basePath + File.separator;
1565
+ final String targetPath = canonicalTarget.getPath();
1566
+ if (!targetPath.equals(basePath) && !targetPath.startsWith(normalizedBasePath)) {
1567
+ throw new IOException("Path escapes updater storage: " + target.getPath());
1568
+ }
1569
+ }
1570
+
1571
+ private void assertPathInsideBundleRoot(final File target) throws IOException {
1572
+ final File bundleRoot = new File(this.documentsDir, bundleDirectory).getCanonicalFile();
1573
+ final File canonicalTarget = target.getCanonicalFile();
1574
+ final String basePath = bundleRoot.getPath();
1575
+ final String normalizedBasePath = basePath.endsWith(File.separator) ? basePath : basePath + File.separator;
1576
+ final String targetPath = canonicalTarget.getPath();
1577
+ if (!targetPath.equals(basePath) && !targetPath.startsWith(normalizedBasePath)) {
1578
+ throw new IOException("Path escapes bundle storage: " + target.getPath());
1579
+ }
1580
+ }
1581
+
1113
1582
  private void safeDelete(final File target) {
1114
1583
  if (target == null || !target.exists()) {
1115
1584
  return;
1116
1585
  }
1117
1586
  try {
1587
+ this.assertPathInsideDocumentsDir(target);
1118
1588
  if (target.isDirectory()) {
1119
1589
  this.deleteDirectory(target);
1120
1590
  } else if (!target.delete()) {
1121
1591
  logger.warn("Failed to delete file: " + target.getAbsolutePath());
1122
1592
  }
1123
1593
  } catch (IOException cleanupError) {
1124
- logger.warn("Cleanup failed for " + target.getAbsolutePath() + ": " + cleanupError.getMessage());
1594
+ logger.warn("Refusing unsafe delete for " + target.getAbsolutePath() + ": " + cleanupError.getMessage());
1125
1595
  }
1126
1596
  }
1127
1597
 
@@ -1208,7 +1678,7 @@ public class CapgoUpdater {
1208
1678
  final StringBuilder buffer = new StringBuilder();
1209
1679
  try (
1210
1680
  final BufferedReader reader = new BufferedReader(
1211
- new InputStreamReader(this.activity.getAssets().open(assetPath), StandardCharsets.UTF_8)
1681
+ new InputStreamReader(this.context().getAssets().open(assetPath), StandardCharsets.UTF_8)
1212
1682
  )
1213
1683
  ) {
1214
1684
  String line;
@@ -1246,7 +1716,7 @@ public class CapgoUpdater {
1246
1716
  }
1247
1717
 
1248
1718
  private void syncBackgroundRunnerScriptFromBundle(final File bundle, final BackgroundRunnerWorkConfig config) {
1249
- if (this.activity == null || bundle == null || config == null || config.src == null || config.src.isEmpty()) {
1719
+ if (this.context() == null || bundle == null || config == null || config.src == null || config.src.isEmpty()) {
1250
1720
  return;
1251
1721
  }
1252
1722
 
@@ -1260,7 +1730,7 @@ public class CapgoUpdater {
1260
1730
  return;
1261
1731
  }
1262
1732
 
1263
- final File publicDir = new File(this.activity.getFilesDir(), "public");
1733
+ final File publicDir = new File(this.context().getFilesDir(), "public");
1264
1734
  final File dest = resolvePathInsideDirectory(publicDir, config.src);
1265
1735
  this.copyFileAtomically(source, dest);
1266
1736
  logger.info("Synced Background Runner script into native public storage before bundle switch.");
@@ -1271,7 +1741,7 @@ public class CapgoUpdater {
1271
1741
  }
1272
1742
 
1273
1743
  private void resetBackgroundRunnerWorkForBundleSwitch(final File bundle) {
1274
- if (this.activity == null) {
1744
+ if (this.context() == null) {
1275
1745
  return;
1276
1746
  }
1277
1747
 
@@ -1287,7 +1757,7 @@ public class CapgoUpdater {
1287
1757
  }
1288
1758
 
1289
1759
  try {
1290
- final WorkManager workManager = WorkManager.getInstance(this.activity.getApplicationContext());
1760
+ final WorkManager workManager = WorkManager.getInstance(this.context().getApplicationContext());
1291
1761
  workManager.cancelUniqueWork(config.label);
1292
1762
  workManager.cancelAllWorkByTag(config.label);
1293
1763
  logger.info("Cancelled Background Runner work before bundle switch.");
@@ -1317,7 +1787,7 @@ public class CapgoUpdater {
1317
1787
  .putString("event", config.event)
1318
1788
  .build();
1319
1789
  final Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
1320
- final WorkManager workManager = WorkManager.getInstance(this.activity.getApplicationContext());
1790
+ final WorkManager workManager = WorkManager.getInstance(this.context().getApplicationContext());
1321
1791
 
1322
1792
  if (!config.repeat) {
1323
1793
  final OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(workerClass)
@@ -1387,7 +1857,7 @@ public class CapgoUpdater {
1387
1857
  downloadBackground(url, version, sessionKey, checksum, manifest, true);
1388
1858
  }
1389
1859
 
1390
- public void downloadBackground(
1860
+ public String downloadBackground(
1391
1861
  final String url,
1392
1862
  final String version,
1393
1863
  final String sessionKey,
@@ -1395,25 +1865,52 @@ public class CapgoUpdater {
1395
1865
  final JSONArray manifest,
1396
1866
  final boolean setNext
1397
1867
  ) {
1868
+ try {
1869
+ this.requireSessionKeyForEncryptedUpdate(sessionKey);
1870
+ if (manifest == null) {
1871
+ this.requireBundleChecksum(checksum);
1872
+ }
1873
+ } catch (final IOException e) {
1874
+ logger.error("Download blocked: " + e.getMessage());
1875
+ return null;
1876
+ }
1398
1877
  if (!this.runDownloadGateQuiet()) {
1399
- return;
1878
+ return null;
1400
1879
  }
1401
1880
  final String id = this.randomString();
1402
1881
 
1403
1882
  // Check if version is already downloading, but allow retry if previous download failed
1404
- if (this.activity != null && DownloadWorkerManager.isVersionDownloading(this.activity, version)) {
1883
+ if (this.context() != null && DownloadWorkerManager.isVersionDownloading(this.context(), version)) {
1405
1884
  // Check if there's an existing bundle with error status that we can retry
1406
1885
  BundleInfo existingBundle = this.getBundleInfoByName(version);
1407
1886
  if (existingBundle != null && existingBundle.isErrorStatus()) {
1408
1887
  // Cancel the failed download and allow retry
1409
- if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, version)) {
1888
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), version)) {
1410
1889
  logger.error("Failed to cancel previous download before retry");
1411
- return;
1890
+ return null;
1412
1891
  }
1413
1892
  logger.info("Retrying failed download for version: " + version);
1893
+ } else if (shouldRestartOrphanedDownload(observedDownloadVersions.contains(version))) {
1894
+ // Left over from a killed process: nothing would finish it or release the launch, so start over.
1895
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), version)) {
1896
+ logger.error("Failed to cancel orphaned download before restarting it");
1897
+ return null;
1898
+ }
1899
+ BundleInfo orphanedBundle = null;
1900
+ for (final BundleInfo info : this.list(true)) {
1901
+ if (info != null && info.getStatus() == BundleStatus.DOWNLOADING && version.equals(info.getVersionName())) {
1902
+ orphanedBundle = info;
1903
+ break;
1904
+ }
1905
+ }
1906
+ if (orphanedBundle != null) {
1907
+ this.cleanupManifestStagingAfterDownloadCancelled(orphanedBundle.getId());
1908
+ this.saveBundleInfo(orphanedBundle.getId(), orphanedBundle.setStatus(BundleStatus.ERROR));
1909
+ }
1910
+ logger.info("Restarting download orphaned by a previous process for version: " + version);
1414
1911
  } else {
1415
1912
  logger.info("Version already downloading: " + version);
1416
- return;
1913
+ return null;
1417
1914
  }
1418
1915
  }
1419
1916
 
@@ -1421,10 +1918,14 @@ public class CapgoUpdater {
1421
1918
  this.notifyDownload(id, 0);
1422
1919
  this.notifyDownload(id, 5);
1423
1920
 
1424
- this.download(id, url, this.randomString(), version, sessionKey, checksum, manifest, setNext);
1921
+ final String dest = manifest != null ? this.manifestStagingDest() : this.randomString();
1922
+ this.download(id, url, dest, version, sessionKey, checksum, manifest, setNext);
1923
+ return id;
1425
1924
  }
1426
1925
 
1427
1926
  public BundleInfo download(final String url, final String version, final String sessionKey, final String checksum) throws IOException {
1927
+ this.requireSessionKeyForEncryptedUpdate(sessionKey);
1928
+ this.requireBundleChecksum(checksum);
1428
1929
  this.runDownloadGate();
1429
1930
  // Check for existing bundle with same version and clean up if in error state
1430
1931
  BundleInfo existingBundle = this.getBundleInfoByName(version);
@@ -1452,7 +1953,8 @@ public class CapgoUpdater {
1452
1953
  try {
1453
1954
  BundleInfo result = downloadFuture.get();
1454
1955
  if (result.isErrorStatus()) {
1455
- throw new IOException("Download failed with status: " + result.getStatus());
1956
+ // The download observer already emitted downloadFailed and its stats.
1957
+ throw new ReportedDownloadFailureException("Download failed with status: " + result.getStatus());
1456
1958
  }
1457
1959
  return result;
1458
1960
  } catch (Exception e) {
@@ -1476,6 +1978,7 @@ public class CapgoUpdater {
1476
1978
  final String checksum,
1477
1979
  final JSONArray manifest
1478
1980
  ) throws IOException {
1981
+ this.requireSessionKeyForEncryptedUpdate(sessionKey);
1479
1982
  this.runDownloadGate();
1480
1983
  if (manifest == null) {
1481
1984
  return download(url, version, sessionKey, checksum);
@@ -1494,7 +1997,7 @@ public class CapgoUpdater {
1494
1997
  saveBundleInfo(id, new BundleInfo(id, version, BundleStatus.DOWNLOADING, new Date(System.currentTimeMillis()), ""));
1495
1998
  this.notifyDownload(id, 0);
1496
1999
  this.notifyDownload(id, 5);
1497
- final String dest = this.randomString();
2000
+ final String dest = this.manifestStagingDest();
1498
2001
 
1499
2002
  // Create a CompletableFuture to track download completion
1500
2003
  CompletableFuture<BundleInfo> downloadFuture = new CompletableFuture<>();
@@ -1507,7 +2010,8 @@ public class CapgoUpdater {
1507
2010
  try {
1508
2011
  BundleInfo result = downloadFuture.get();
1509
2012
  if (result.isErrorStatus()) {
1510
- throw new IOException("Download failed with status: " + result.getStatus());
2013
+ // The download observer already emitted downloadFailed and its stats.
2014
+ throw new ReportedDownloadFailureException("Download failed with status: " + result.getStatus());
1511
2015
  }
1512
2016
  return result;
1513
2017
  } catch (Exception e) {
@@ -1557,6 +2061,14 @@ public class CapgoUpdater {
1557
2061
 
1558
2062
  public Boolean delete(final String id, final Boolean removeInfo, final boolean cancelActiveDownload) throws IOException {
1559
2063
  synchronized (this.deleteLock) {
2064
+ final File bundle;
2065
+ try {
2066
+ bundle = this.getBundleDirectory(id);
2067
+ } catch (IOException e) {
2068
+ logger.error("Cannot delete bundle with invalid id");
2069
+ logger.debug("Bundle ID: " + id + ", Error: " + e.getMessage());
2070
+ return false;
2071
+ }
1560
2072
  final BundleInfo deleted = this.getBundleInfo(id);
1561
2073
  if (deleted.isBuiltin() || this.getCurrentBundleId().equals(id)) {
1562
2074
  logger.error("Cannot delete current or builtin bundle");
@@ -1582,7 +2094,6 @@ public class CapgoUpdater {
1582
2094
  return false;
1583
2095
  }
1584
2096
 
1585
- final File bundle = this.getBundleDirectory(id);
1586
2097
  final boolean hadRegistry = this.hasStoredBundleInfo(id);
1587
2098
  final boolean hadFolder = bundle.exists();
1588
2099
  if (!hadRegistry && !hadFolder) {
@@ -1601,8 +2112,8 @@ public class CapgoUpdater {
1601
2112
  }
1602
2113
 
1603
2114
  // Cancel download for this version if active
1604
- if (cancelActiveDownload && this.activity != null) {
1605
- if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, deleted.getVersionName())) {
2115
+ if (cancelActiveDownload && this.context() != null) {
2116
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), deleted.getVersionName())) {
1606
2117
  logger.error("Failed to cancel active download before delete");
1607
2118
  return false;
1608
2119
  }
@@ -1730,12 +2241,17 @@ public class CapgoUpdater {
1730
2241
  this.editor.commit();
1731
2242
  }
1732
2243
 
1733
- private File getBundleDirectory(final String id) {
1734
- return new File(this.documentsDir, bundleDirectory + "/" + id);
2244
+ private File getBundleDirectory(final String id) throws IOException {
2245
+ return resolveBundleDirectory(this.documentsDir, id);
1735
2246
  }
1736
2247
 
1737
2248
  private boolean bundleExists(final String id) {
1738
- final File bundle = this.getBundleDirectory(id);
2249
+ final File bundle;
2250
+ try {
2251
+ bundle = this.getBundleDirectory(id);
2252
+ } catch (IOException e) {
2253
+ return false;
2254
+ }
1739
2255
  final BundleInfo bundleInfo = this.getBundleInfo(id);
1740
2256
  return (
1741
2257
  bundle.isDirectory() &&
@@ -1790,8 +2306,8 @@ public class CapgoUpdater {
1790
2306
  }
1791
2307
 
1792
2308
  void finalizeResetTransition(final String previousBundleName, final boolean internal) {
1793
- if (this.activity != null) {
1794
- DownloadWorkerManager.cancelAllDownloads(this.activity);
2309
+ if (this.context() != null) {
2310
+ DownloadWorkerManager.cancelAllDownloads(this.context());
1795
2311
  }
1796
2312
  if (!internal) {
1797
2313
  this.sendStats("reset", this.getCurrentBundle().getVersionName(), previousBundleName);
@@ -1812,7 +2328,16 @@ public class CapgoUpdater {
1812
2328
  this.reset();
1813
2329
  return true;
1814
2330
  }
1815
- final File bundle = this.getBundleDirectory(id);
2331
+ final File bundle;
2332
+ try {
2333
+ bundle = this.getBundleDirectory(id);
2334
+ } catch (IOException e) {
2335
+ logger.error("Invalid bundle id");
2336
+ logger.debug("Bundle ID: " + id + ", Error: " + e.getMessage());
2337
+ this.setBundleStatus(id, BundleStatus.ERROR);
2338
+ this.sendStats("set_fail", newBundle.getVersionName());
2339
+ return false;
2340
+ }
1816
2341
  logger.info("Setting next active bundle: " + id);
1817
2342
  if (this.bundleExists(id)) {
1818
2343
  var currentBundleName = this.getCurrentBundle().getVersionName();
@@ -1830,8 +2355,12 @@ public class CapgoUpdater {
1830
2355
  if (bundle == null || bundle.isBuiltin() || !this.bundleExists(bundle.getId())) {
1831
2356
  return false;
1832
2357
  }
1833
- this.setCurrentBundle(this.getBundleDirectory(bundle.getId()));
1834
- return true;
2358
+ try {
2359
+ this.setCurrentBundle(this.getBundleDirectory(bundle.getId()));
2360
+ return true;
2361
+ } catch (IOException e) {
2362
+ return false;
2363
+ }
1835
2364
  }
1836
2365
 
1837
2366
  boolean stagePreviewFallbackReload(final BundleInfo bundle) {
@@ -1845,8 +2374,12 @@ public class CapgoUpdater {
1845
2374
  if (!this.bundleExists(bundle.getId())) {
1846
2375
  return false;
1847
2376
  }
1848
- this.setCurrentBundle(this.getBundleDirectory(bundle.getId()));
1849
- return true;
2377
+ try {
2378
+ this.setCurrentBundle(this.getBundleDirectory(bundle.getId()));
2379
+ return true;
2380
+ } catch (IOException e) {
2381
+ return false;
2382
+ }
1850
2383
  }
1851
2384
 
1852
2385
  void finalizePendingReload(final BundleInfo bundle, final String previousBundleName) {
@@ -1952,8 +2485,8 @@ public class CapgoUpdater {
1952
2485
  final String asyncPreviousFallbackId = previousFallbackId;
1953
2486
  final String asyncPreviousFallbackVersion = previousFallbackVersion;
1954
2487
  io.execute(() -> {
1955
- if (this.activity != null) {
1956
- if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, asyncPreviousFallbackVersion)) {
2488
+ if (this.context() != null) {
2489
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), asyncPreviousFallbackVersion)) {
1957
2490
  logger.error("Failed to cancel previous version download before delete");
1958
2491
  return;
1959
2492
  }
@@ -2407,8 +2940,18 @@ public class CapgoUpdater {
2407
2940
  final SharedPreferences.Editor editor,
2408
2941
  final String defaultChannelKey,
2409
2942
  final String configDefaultChannel,
2943
+ final boolean allowSetDefaultChannel,
2410
2944
  final Callback callback
2411
2945
  ) {
2946
+ if (!allowSetDefaultChannel) {
2947
+ logger.error("unsetChannel is disabled by allowSetDefaultChannel config");
2948
+ final Map<String, Object> retError = new HashMap<>();
2949
+ retError.put("message", "unsetChannel is disabled by configuration");
2950
+ retError.put("error", "disabled_by_config");
2951
+ callback.callback(retError);
2952
+ return;
2953
+ }
2954
+
2412
2955
  // Clear persisted defaultChannel and revert to config value
2413
2956
  editor.remove(defaultChannelKey);
2414
2957
  editor.apply();
@@ -2896,7 +3439,7 @@ public class CapgoUpdater {
2896
3439
  if (statsQueue.size() >= MAX_PENDING_STATS) {
2897
3440
  break;
2898
3441
  }
2899
- statsQueue.add(new QueuedStatsEvent(arr.getJSONObject(i), null));
3442
+ statsQueue.add(new QueuedStatsEvent(arr.getJSONObject(i), null, true));
2900
3443
  }
2901
3444
  }
2902
3445
  if (backup.exists() && !backup.delete()) {
@@ -2918,6 +3461,147 @@ public class CapgoUpdater {
2918
3461
  }
2919
3462
  }
2920
3463
 
3464
+ /** Makes this instance the stats file owner and adopts events handed over before it loaded. */
3465
+ public void claimStatsOwnership() {
3466
+ final List<JSONObject> adopted;
3467
+ synchronized (statsOwnerLock) {
3468
+ statsOwner = this;
3469
+ adopted = new ArrayList<>(orphanedStats);
3470
+ orphanedStats.clear();
3471
+ }
3472
+ if (!adoptPendingStats(adopted)) {
3473
+ parkOrphanedStats(adopted);
3474
+ }
3475
+ }
3476
+
3477
+ public void releaseStatsOwnership() {
3478
+ synchronized (statsOwnerLock) {
3479
+ if (statsOwner == this) {
3480
+ statsOwner = null;
3481
+ }
3482
+ }
3483
+ }
3484
+
3485
+ /** Moves this instance's unsent events to the stats file owner (or parks them until one claims). */
3486
+ void handOverPendingStats() {
3487
+ // Stop first so a flush finishing later cannot requeue or persist what we hand over.
3488
+ statsStopped.set(true);
3489
+ final CapgoUpdater owner;
3490
+ synchronized (statsOwnerLock) {
3491
+ owner = statsOwner == this ? null : statsOwner;
3492
+ }
3493
+ final List<JSONObject> events = new ArrayList<>();
3494
+ synchronized (statsQueue) {
3495
+ collectHandoverEvents(statsInFlight, events, owner);
3496
+ statsInFlight.clear();
3497
+ collectHandoverEvents(statsQueue, events, owner);
3498
+ statsQueue.clear();
3499
+ }
3500
+ if (events.isEmpty()) {
3501
+ return;
3502
+ }
3503
+ // adoptPendingStats persists; never call it while holding statsOwnerLock (lock order).
3504
+ if (owner != null && owner.adoptPendingStats(events)) {
3505
+ return;
3506
+ }
3507
+ List<JSONObject> retryEvents = null;
3508
+ CapgoUpdater retryOwner = null;
3509
+ synchronized (statsOwnerLock) {
3510
+ addOrphanedStats(events);
3511
+ retryOwner = statsOwner == this ? null : statsOwner;
3512
+ if (retryOwner != null && !orphanedStats.isEmpty()) {
3513
+ retryEvents = new ArrayList<>(orphanedStats);
3514
+ orphanedStats.clear();
3515
+ }
3516
+ }
3517
+ if (retryOwner != null && retryEvents != null) {
3518
+ if (retryOwner.adoptPendingStats(retryEvents)) {
3519
+ return;
3520
+ }
3521
+ parkOrphanedStats(retryEvents);
3522
+ }
3523
+ }
3524
+
3525
+ private void collectHandoverEvents(final List<QueuedStatsEvent> source, final List<JSONObject> events, final CapgoUpdater owner) {
3526
+ for (final QueuedStatsEvent queued : source) {
3527
+ if (shouldHandOverQueuedEvent(queued, owner)) {
3528
+ events.add(queued.event);
3529
+ }
3530
+ }
3531
+ }
3532
+
3533
+ /**
3534
+ * Restored file events are not re-sent to an owner that shares the same pending-stats path
3535
+ * (the owner already loaded them from disk). They are still handed over when the paths differ.
3536
+ */
3537
+ private boolean shouldHandOverQueuedEvent(final QueuedStatsEvent queued, final CapgoUpdater owner) {
3538
+ if (!queued.restored) {
3539
+ return true;
3540
+ }
3541
+ if (owner == null) {
3542
+ return true;
3543
+ }
3544
+ return !sharesPendingStatsFileWith(owner);
3545
+ }
3546
+
3547
+ private boolean sharesPendingStatsFileWith(final CapgoUpdater other) {
3548
+ final File mine = pendingStatsFile();
3549
+ final File theirs = other.pendingStatsFile();
3550
+ return mine != null && theirs != null && mine.getAbsolutePath().equals(theirs.getAbsolutePath());
3551
+ }
3552
+
3553
+ private static void addOrphanedStats(final List<JSONObject> events) {
3554
+ orphanedStats.addAll(events);
3555
+ while (orphanedStats.size() > MAX_PENDING_STATS) {
3556
+ orphanedStats.remove(0);
3557
+ }
3558
+ }
3559
+
3560
+ private static void parkOrphanedStats(final List<JSONObject> events) {
3561
+ synchronized (statsOwnerLock) {
3562
+ addOrphanedStats(events);
3563
+ }
3564
+ }
3565
+
3566
+ /** Returns false (keeping nothing) when this instance has stopped and can no longer send the events. */
3567
+ private boolean adoptPendingStats(final List<JSONObject> events) {
3568
+ if (events.isEmpty()) {
3569
+ return true;
3570
+ }
3571
+ final List<QueuedStatsEvent> displaced = new ArrayList<>();
3572
+ synchronized (statsQueue) {
3573
+ if (statsStopped.get()) {
3574
+ return false;
3575
+ }
3576
+ for (final JSONObject event : events) {
3577
+ while (statsQueue.size() >= MAX_PENDING_STATS) {
3578
+ displaced.add(0, statsQueue.remove(0));
3579
+ }
3580
+ statsQueue.add(new QueuedStatsEvent(event, null));
3581
+ }
3582
+ }
3583
+ synchronized (statsOwnerLock) {
3584
+ if (statsOwner != null && statsOwner != this) {
3585
+ rollbackAdoptedEvents(events.size(), displaced);
3586
+ return false;
3587
+ }
3588
+ }
3589
+ persistStatsQueue();
3590
+ ensureStatsTimerStarted();
3591
+ return true;
3592
+ }
3593
+
3594
+ private void rollbackAdoptedEvents(final int adoptedCount, final List<QueuedStatsEvent> displaced) {
3595
+ synchronized (statsQueue) {
3596
+ for (int removed = 0; removed < adoptedCount && !statsQueue.isEmpty(); removed++) {
3597
+ statsQueue.remove(statsQueue.size() - 1);
3598
+ }
3599
+ for (int i = 0; i < displaced.size(); i++) {
3600
+ statsQueue.add(i, displaced.get(i));
3601
+ }
3602
+ }
3603
+ }
3604
+
2921
3605
  int pendingStatsCount() {
2922
3606
  return statsQueue.size();
2923
3607
  }
@@ -2944,6 +3628,11 @@ public class CapgoUpdater {
2944
3628
  return;
2945
3629
  }
2946
3630
  synchronized (pendingStatsPersistLock) {
3631
+ synchronized (statsOwnerLock) {
3632
+ if (statsOwner != null && statsOwner != this) {
3633
+ return;
3634
+ }
3635
+ }
2947
3636
  if (statsStopped.get() && !force) {
2948
3637
  return;
2949
3638
  }
@@ -3325,6 +4014,16 @@ public class CapgoUpdater {
3325
4014
  return this.getBundleInfo(id);
3326
4015
  }
3327
4016
 
4017
+ public boolean clearNextBundleIfCurrent() {
4018
+ final BundleInfo next = this.getNextBundle();
4019
+ if (next == null || !next.getId().equals(this.getCurrentBundle().getId())) {
4020
+ return false;
4021
+ }
4022
+ logger.info("Next bundle " + next.getId() + " is already the current bundle. Clearing next.");
4023
+ this.setNextBundle(null);
4024
+ return true;
4025
+ }
4026
+
3328
4027
  public BundleInfo getPreviewFallbackBundle() {
3329
4028
  final String id = this.prefs.getString(PREVIEW_FALLBACK_VERSION, null);
3330
4029
  if (id == null) return null;
@@ -3359,6 +4058,10 @@ public class CapgoUpdater {
3359
4058
  if (!newBundle.isBuiltin() && !this.bundleExists(next)) {
3360
4059
  return false;
3361
4060
  }
4061
+ if (next.equals(this.getCurrentBundleId()) && BundleStatus.SUCCESS == newBundle.getStatus()) {
4062
+ logger.info("Bundle " + next + " is already the current successful bundle. Skip next().");
4063
+ return true;
4064
+ }
3362
4065
  this.editor.putString(NEXT_VERSION, next);
3363
4066
  this.setBundleStatus(next, BundleStatus.PENDING);
3364
4067
  bundleToNotify = newBundle;
@@ -3378,6 +4081,14 @@ public class CapgoUpdater {
3378
4081
  * Should be called when the plugin is destroyed to prevent resource leaks.
3379
4082
  */
3380
4083
  public void shutdown() {
4084
+ shutdown(true);
4085
+ }
4086
+
4087
+ /**
4088
+ * @param persistStats false when another live instance owns the stats file (headless worker
4089
+ * handing over to the plugin): writing this instance's queue would replace the newer file.
4090
+ */
4091
+ public void shutdown(final boolean persistStats) {
3381
4092
  statsStopped.set(true);
3382
4093
  // Cancel the scheduled task
3383
4094
  if (statsFlushTask != null) {
@@ -3386,7 +4097,9 @@ public class CapgoUpdater {
3386
4097
  }
3387
4098
 
3388
4099
  // Write once, then ignore later callbacks so they cannot delete a newer instance's file.
3389
- persistStatsQueue(true);
4100
+ if (persistStats) {
4101
+ persistStatsQueue(true);
4102
+ }
3390
4103
 
3391
4104
  // Shutdown the scheduler
3392
4105
  statsScheduler.shutdown();