@capgo/capacitor-updater 9.0.0 → 9.0.1

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 (109) hide show
  1. package/CapgoCapacitorUpdater.podspec +3 -6
  2. package/Package.swift +30 -0
  3. package/README.md +2382 -292
  4. package/android/build.gradle +37 -15
  5. package/android/consumer-rules.pro +48 -0
  6. package/android/proguard-rules.pro +23 -0
  7. package/android/src/main/AndroidManifest.xml +0 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +92 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +115 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +227 -195
  11. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +24 -23
  12. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +7435 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5144 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +564 -121
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +43 -49
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +4 -4
  19. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
  20. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +230 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +1969 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +278 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +385 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -0
  26. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +79 -0
  27. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +419 -0
  28. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  29. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
  30. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +959 -0
  31. package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
  32. package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +323 -0
  33. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  34. package/dist/docs.json +4431 -840
  35. package/dist/esm/definitions.d.ts +2607 -225
  36. package/dist/esm/definitions.js +103 -1
  37. package/dist/esm/definitions.js.map +1 -1
  38. package/dist/esm/history.d.ts +1 -0
  39. package/dist/esm/history.js +283 -0
  40. package/dist/esm/history.js.map +1 -0
  41. package/dist/esm/index.d.ts +3 -2
  42. package/dist/esm/index.js +5 -4
  43. package/dist/esm/index.js.map +1 -1
  44. package/dist/esm/web.d.ts +53 -42
  45. package/dist/esm/web.js +180 -37
  46. package/dist/esm/web.js.map +1 -1
  47. package/dist/plugin.cjs.js +570 -37
  48. package/dist/plugin.cjs.js.map +1 -1
  49. package/dist/plugin.js +570 -37
  50. package/dist/plugin.js.map +1 -1
  51. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
  52. package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
  53. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
  54. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
  55. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +5642 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +4572 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +380 -0
  60. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
  61. package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
  62. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +452 -0
  63. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +380 -0
  64. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  65. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
  66. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +97 -0
  67. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +871 -0
  68. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
  69. package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
  70. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +304 -0
  71. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  72. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  73. package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
  74. package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
  75. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +3905 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -0
  80. package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
  81. package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
  82. package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
  83. package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
  84. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1095 -0
  85. package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
  86. package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
  87. package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
  88. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +192 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -0
  91. package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
  92. package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
  93. package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
  94. package/package.json +80 -43
  95. package/scripts/builtin-hashes-lib.mjs +148 -0
  96. package/scripts/capacitor-builtin-hashes-hook.mjs +65 -0
  97. package/scripts/resolve-real-path.mjs +25 -0
  98. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +0 -1130
  99. package/ios/Plugin/BundleInfo.swift +0 -113
  100. package/ios/Plugin/BundleStatus.swift +0 -48
  101. package/ios/Plugin/CapacitorUpdater.swift +0 -858
  102. package/ios/Plugin/CapacitorUpdaterPlugin.h +0 -10
  103. package/ios/Plugin/CapacitorUpdaterPlugin.m +0 -27
  104. package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -677
  105. package/ios/Plugin/CryptoCipher.swift +0 -240
  106. /package/{LICENCE → LICENSE} +0 -0
  107. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
  108. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
  109. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
@@ -0,0 +1,278 @@
1
+ package ee.forgr.capacitor_updater;
2
+
3
+ import android.content.Context;
4
+ import android.os.Build;
5
+ import androidx.work.BackoffPolicy;
6
+ import androidx.work.Configuration;
7
+ import androidx.work.Constraints;
8
+ import androidx.work.Data;
9
+ import androidx.work.ExistingWorkPolicy;
10
+ import androidx.work.NetworkType;
11
+ import androidx.work.OneTimeWorkRequest;
12
+ import androidx.work.OutOfQuotaPolicy;
13
+ import androidx.work.WorkInfo;
14
+ import androidx.work.WorkManager;
15
+ import androidx.work.WorkRequest;
16
+ import java.util.HashSet;
17
+ import java.util.List;
18
+ import java.util.Set;
19
+ import java.util.concurrent.ExecutorService;
20
+ import java.util.concurrent.Executors;
21
+ import java.util.concurrent.Future;
22
+ import java.util.concurrent.TimeUnit;
23
+ import java.util.concurrent.TimeoutException;
24
+
25
+ public class DownloadWorkerManager {
26
+
27
+ private static volatile Logger logger;
28
+ private static final Object LOGGER_LOCK = new Object();
29
+
30
+ public static void setLogger(Logger loggerInstance) {
31
+ synchronized (LOGGER_LOCK) {
32
+ logger = loggerInstance;
33
+ }
34
+ }
35
+
36
+ public static void setLoggerIfAbsent(Logger loggerInstance) {
37
+ if (loggerInstance == null) {
38
+ return;
39
+ }
40
+ synchronized (LOGGER_LOCK) {
41
+ if (logger == null) {
42
+ logger = loggerInstance;
43
+ }
44
+ }
45
+ }
46
+
47
+ public static Logger getLogger() {
48
+ return logger;
49
+ }
50
+
51
+ private static volatile boolean isInitialized = false;
52
+ private static final ExecutorService cancelExecutor = Executors.newSingleThreadExecutor();
53
+
54
+ private static synchronized void initializeIfNeeded(Context context) {
55
+ if (!isInitialized) {
56
+ try {
57
+ Configuration config = new Configuration.Builder().setMinimumLoggingLevel(android.util.Log.INFO).build();
58
+ WorkManager.initialize(context, config);
59
+ isInitialized = true;
60
+ } catch (IllegalStateException e) {
61
+ // WorkManager was already initialized, ignore
62
+ }
63
+ }
64
+ }
65
+
66
+ public static boolean isVersionDownloading(Context context, String version) {
67
+ initializeIfNeeded(context.getApplicationContext());
68
+ try {
69
+ return WorkManager.getInstance(context)
70
+ .getWorkInfosByTag(version)
71
+ .get()
72
+ .stream()
73
+ .anyMatch((workInfo) -> !workInfo.getState().isFinished());
74
+ } catch (Exception e) {
75
+ logger.error("Error checking download status: " + e.getMessage());
76
+ return false;
77
+ }
78
+ }
79
+
80
+ public static void enqueueDownload(
81
+ Context context,
82
+ String url,
83
+ String id,
84
+ String documentsDir,
85
+ String dest,
86
+ String version,
87
+ String sessionKey,
88
+ String checksum,
89
+ String publicKey,
90
+ boolean isManifest,
91
+ boolean isEmulator,
92
+ String appId,
93
+ String pluginVersion,
94
+ boolean isProd,
95
+ String installSource,
96
+ String statsUrl,
97
+ String deviceId,
98
+ String versionBuild,
99
+ String versionCode,
100
+ String versionOs,
101
+ String customId,
102
+ String defaultChannel
103
+ ) {
104
+ initializeIfNeeded(context.getApplicationContext());
105
+
106
+ // Use unique work name for this bundle to prevent duplicates
107
+ String uniqueWorkName = "bundle_" + id + "_" + version;
108
+
109
+ // Create input data
110
+ Data inputData = new Data.Builder()
111
+ .putString(DownloadService.URL, url)
112
+ .putString(DownloadService.ID, id)
113
+ .putString(DownloadService.DOCDIR, documentsDir)
114
+ .putString(DownloadService.FILEDEST, dest)
115
+ .putString(DownloadService.VERSION, version)
116
+ .putString(DownloadService.SESSIONKEY, sessionKey)
117
+ .putString(DownloadService.CHECKSUM, checksum)
118
+ .putBoolean(DownloadService.IS_MANIFEST, isManifest)
119
+ .putString(DownloadService.PUBLIC_KEY, publicKey)
120
+ .putString(DownloadService.APP_ID, appId)
121
+ .putString(DownloadService.pluginVersion, pluginVersion)
122
+ .putString(DownloadService.INSTALL_SOURCE, installSource)
123
+ .putString(DownloadService.STATS_URL, statsUrl)
124
+ .putString(DownloadService.DEVICE_ID, deviceId)
125
+ .putString(DownloadService.VERSION_BUILD, versionBuild)
126
+ .putString(DownloadService.VERSION_CODE, versionCode)
127
+ .putString(DownloadService.VERSION_OS, versionOs)
128
+ .putString(DownloadService.CUSTOM_ID, customId)
129
+ .putString(DownloadService.DEFAULT_CHANNEL, defaultChannel)
130
+ .putBoolean(DownloadService.IS_PROD, isProd)
131
+ .putBoolean(DownloadService.IS_EMULATOR, isEmulator)
132
+ // A job WorkManager resumes in a fresh process runs before any config is loaded.
133
+ .putBoolean(DownloadService.HTTP3, Http3.isEnabled())
134
+ .build();
135
+
136
+ // Create network constraints - be more lenient on emulators
137
+ Constraints.Builder constraintsBuilder = new Constraints.Builder();
138
+ if (isEmulator) {
139
+ logger.info("Emulator detected - using lenient network constraints");
140
+ // On emulators, use NOT_REQUIRED to avoid background network issues
141
+ constraintsBuilder.setRequiredNetworkType(NetworkType.NOT_REQUIRED);
142
+ } else {
143
+ constraintsBuilder.setRequiredNetworkType(NetworkType.CONNECTED);
144
+ }
145
+ Constraints constraints = constraintsBuilder.build();
146
+
147
+ // Create work request with tags for tracking
148
+ OneTimeWorkRequest.Builder workRequestBuilder = new OneTimeWorkRequest.Builder(DownloadService.class)
149
+ .setConstraints(constraints)
150
+ .setInputData(inputData)
151
+ .addTag(id)
152
+ .addTag(version)
153
+ .addTag("capacitor_updater_download");
154
+ // Android 12+ expedited jobs skip the WorkManager delay without a
155
+ // foreground service. Older APIs require getForegroundInfo().
156
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
157
+ workRequestBuilder.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST);
158
+ }
159
+
160
+ // More aggressive retry policy for emulators
161
+ if (isEmulator) {
162
+ workRequestBuilder.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS);
163
+ } else {
164
+ workRequestBuilder.setBackoffCriteria(BackoffPolicy.LINEAR, WorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS);
165
+ }
166
+
167
+ OneTimeWorkRequest workRequest = workRequestBuilder.build();
168
+
169
+ // Use beginUniqueWork to prevent duplicate downloads
170
+ WorkManager.getInstance(context)
171
+ .beginUniqueWork(
172
+ uniqueWorkName,
173
+ ExistingWorkPolicy.KEEP, // Don't start if already running
174
+ workRequest
175
+ )
176
+ .enqueue();
177
+ }
178
+
179
+ public static void cancelVersionDownload(Context context, String version) {
180
+ initializeIfNeeded(context.getApplicationContext());
181
+ cancelExecutor.execute(() -> cancelVersionDownloadInternal(context, version, false));
182
+ }
183
+
184
+ public static boolean cancelVersionDownloadAndAwait(Context context, String version) {
185
+ initializeIfNeeded(context.getApplicationContext());
186
+ Future<?> future = cancelExecutor.submit(() -> cancelVersionDownloadInternal(context, version, true));
187
+ try {
188
+ future.get(10, TimeUnit.SECONDS);
189
+ return true;
190
+ } catch (TimeoutException e) {
191
+ future.cancel(true);
192
+ logger.error("Timed out awaiting version download cancel");
193
+ return false;
194
+ } catch (Exception e) {
195
+ logger.error("Error awaiting version download cancel: " + e.getMessage());
196
+ return false;
197
+ }
198
+ }
199
+
200
+ private static Set<String> collectManifestIdsForVersion(WorkManager workManager, String version) {
201
+ Set<String> downloadIds = new HashSet<>();
202
+ try {
203
+ List<WorkInfo> workInfos = workManager.getWorkInfosByTag(version).get();
204
+ for (WorkInfo workInfo : workInfos) {
205
+ for (String tag : workInfo.getTags()) {
206
+ if (!"capacitor_updater_download".equals(tag) && !version.equals(tag)) {
207
+ downloadIds.add(tag);
208
+ }
209
+ }
210
+ }
211
+ } catch (InterruptedException e) {
212
+ Thread.currentThread().interrupt();
213
+ throw new IllegalStateException("Interrupted while collecting manifest ids before version cancel", e);
214
+ } catch (Exception e) {
215
+ logger.error("Error collecting manifest ids before version cancel: " + e.getMessage());
216
+ }
217
+ return downloadIds;
218
+ }
219
+
220
+ private static void clearManifestIds(Set<String> downloadIds) {
221
+ for (String downloadId : downloadIds) {
222
+ DataManager.getInstance().clearManifest(downloadId);
223
+ }
224
+ }
225
+
226
+ private static void cancelVersionDownloadInternal(Context context, String version, boolean awaitFinished) {
227
+ if (Thread.currentThread().isInterrupted()) {
228
+ return;
229
+ }
230
+ WorkManager workManager = WorkManager.getInstance(context);
231
+ Set<String> downloadIds = collectManifestIdsForVersion(workManager, version);
232
+ workManager.cancelAllWorkByTag(version);
233
+ clearManifestIds(downloadIds);
234
+ if (awaitFinished) {
235
+ awaitVersionWorkFinished(workManager, version);
236
+ }
237
+ }
238
+
239
+ private static void awaitVersionWorkFinished(WorkManager workManager, String version) {
240
+ for (int i = 0; i < 100; i++) {
241
+ if (Thread.currentThread().isInterrupted()) {
242
+ throw new IllegalStateException("Interrupted while waiting for version download cancel");
243
+ }
244
+ try {
245
+ boolean anyActive = workManager
246
+ .getWorkInfosByTag(version)
247
+ .get()
248
+ .stream()
249
+ .anyMatch((workInfo) -> !workInfo.getState().isFinished());
250
+ if (!anyActive) {
251
+ return;
252
+ }
253
+ Thread.sleep(100);
254
+ } catch (InterruptedException e) {
255
+ Thread.currentThread().interrupt();
256
+ throw new IllegalStateException("Interrupted while waiting for download cancel", e);
257
+ } catch (Exception e) {
258
+ throw new IllegalStateException("Error waiting for download cancel: " + e.getMessage(), e);
259
+ }
260
+ }
261
+ throw new IllegalStateException("Timed out waiting for version download cancel: " + version);
262
+ }
263
+
264
+ public static void cancelBundleDownload(Context context, String id, String version) {
265
+ String uniqueWorkName = "bundle_" + id + "_" + version;
266
+ initializeIfNeeded(context.getApplicationContext());
267
+ WorkManager workManager = WorkManager.getInstance(context);
268
+ workManager.cancelUniqueWork(uniqueWorkName);
269
+ DataManager.getInstance().clearManifest(id);
270
+ }
271
+
272
+ public static void cancelAllDownloads(Context context) {
273
+ initializeIfNeeded(context.getApplicationContext());
274
+ WorkManager workManager = WorkManager.getInstance(context);
275
+ workManager.cancelAllWorkByTag("capacitor_updater_download");
276
+ DataManager.getInstance().clearAllManifests();
277
+ }
278
+ }
@@ -0,0 +1,385 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+
7
+ package ee.forgr.capacitor_updater;
8
+
9
+ import android.app.Activity;
10
+ import android.content.Context;
11
+ import android.content.SharedPreferences;
12
+ import android.content.pm.PackageInfo;
13
+ import android.content.pm.PackageManager;
14
+ import android.os.Build;
15
+ import androidx.annotation.NonNull;
16
+ import androidx.core.content.pm.PackageInfoCompat;
17
+ import androidx.work.Constraints;
18
+ import androidx.work.ExistingWorkPolicy;
19
+ import androidx.work.NetworkType;
20
+ import androidx.work.OneTimeWorkRequest;
21
+ import androidx.work.OutOfQuotaPolicy;
22
+ import androidx.work.WorkManager;
23
+ import androidx.work.Worker;
24
+ import androidx.work.WorkerParameters;
25
+ import com.getcapacitor.CapConfig;
26
+ import com.getcapacitor.PluginConfig;
27
+ import com.getcapacitor.plugin.WebView;
28
+ import java.io.IOException;
29
+ import java.util.Map;
30
+ import java.util.concurrent.CountDownLatch;
31
+ import java.util.concurrent.TimeUnit;
32
+ import java.util.concurrent.atomic.AtomicReference;
33
+ import org.json.JSONArray;
34
+ import org.json.JSONException;
35
+
36
+ /**
37
+ * Runs a live update check with no Activity and no Capacitor bridge, for example when an
38
+ * update-check push wakes a killed app. The bundle is downloaded and, when the app has no UI,
39
+ * applied as the current bundle so the next launch opens the new version (it still has to call
40
+ * notifyAppReady). Enqueued as unique expedited work so the process stays alive until the bundle
41
+ * is unzipped and stored.
42
+ *
43
+ * When a plugin instance is running in the process, use its native trigger instead
44
+ * (CapacitorUpdaterPlugin#triggerBackgroundUpdateCheck); this worker then only stores the bundle as
45
+ * next and lets that instance install it.
46
+ */
47
+ public class HeadlessUpdateWorker extends Worker {
48
+
49
+ static final String UNIQUE_WORK_NAME = "capacitor_updater_headless_update_check";
50
+ private static final long FINISH_TIMEOUT_MINUTES = 9;
51
+
52
+ public HeadlessUpdateWorker(@NonNull final Context context, @NonNull final WorkerParameters params) {
53
+ super(context, params);
54
+ }
55
+
56
+ /** Queue a headless update check. Safe to call from any thread, including an FCM service. */
57
+ public static void enqueue(@NonNull final Context context) {
58
+ final OneTimeWorkRequest.Builder builder = new OneTimeWorkRequest.Builder(HeadlessUpdateWorker.class)
59
+ .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
60
+ .addTag(UNIQUE_WORK_NAME);
61
+ // Same as downloads: expedited work starts right away on Android 12+ without a foreground service.
62
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
63
+ builder.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST);
64
+ }
65
+ WorkManager.getInstance(context.getApplicationContext()).enqueueUniqueWork(
66
+ UNIQUE_WORK_NAME,
67
+ ExistingWorkPolicy.KEEP,
68
+ builder.build()
69
+ );
70
+ }
71
+
72
+ @NonNull
73
+ @Override
74
+ public Result doWork() {
75
+ final Context context = getApplicationContext();
76
+ final Logger logger;
77
+ try {
78
+ final PluginConfig config = CapConfig.loadDefault(context).getPluginConfiguration("CapacitorUpdater");
79
+ final boolean osLogging = config.getBoolean("osLogging", true);
80
+ logger = new Logger("CapgoUpdater", new Logger.Options(osLogging));
81
+ try {
82
+ final String status = run(context, logger);
83
+ logger.info("Headless update check finished: " + status);
84
+ } catch (final Exception e) {
85
+ logger.error("Headless update check failed: " + e.getMessage());
86
+ }
87
+ } catch (final Exception e) {
88
+ final Logger fallback = new Logger("CapgoUpdater", new Logger.Options(true));
89
+ fallback.error("Headless update check skipped: invalid Capacitor config (" + e.getMessage() + ")");
90
+ }
91
+ // Never retry: the next launch or push runs a fresh check.
92
+ return Result.success();
93
+ }
94
+
95
+ static String run(final Context context, final Logger logger) throws PackageManager.NameNotFoundException {
96
+ if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
97
+ // The running plugin instance owns downloads and installs in this process.
98
+ return "handed_over";
99
+ }
100
+ final CapConfig capConfig = CapConfig.loadDefault(context);
101
+ final PluginConfig config = capConfig.getPluginConfiguration("CapacitorUpdater");
102
+ final String serverUrl = capConfig.getServerUrl();
103
+ if (serverUrl != null && !serverUrl.isEmpty()) {
104
+ return "unavailable";
105
+ }
106
+ final String autoUpdateMode = CapacitorUpdaterPlugin.autoUpdateModeFromConfig(config, logger);
107
+ if (!CapacitorUpdaterPlugin.isAutoUpdateModeEnabled(autoUpdateMode)) {
108
+ return "unavailable";
109
+ }
110
+
111
+ final SharedPreferences prefs = context.getSharedPreferences(WebView.WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE);
112
+ final boolean allowPreview = config.getBoolean("allowPreview", false);
113
+ if (allowPreview && prefs.getBoolean(CapacitorUpdaterPlugin.PREVIEW_SESSION_PREF_KEY, false)) {
114
+ return "preview_session";
115
+ }
116
+
117
+ final PackageInfo packageInfo = getPackageInfo(context);
118
+ final String versionCode = Long.toString(PackageInfoCompat.getLongVersionCode(packageInfo));
119
+ // After a native update the launch resets bundles first (resetWhenUpdate): leave it to the launch.
120
+ if (nativeBuildChanged(prefs, versionCode)) {
121
+ return "native_update_pending";
122
+ }
123
+
124
+ final boolean setNext = CapacitorUpdaterPlugin.shouldAutoUpdateModeSetNextBundle(autoUpdateMode);
125
+ final CountDownLatch finished = new CountDownLatch(1);
126
+ final AtomicReference<String> result = new AtomicReference<>("no_update");
127
+ final CapgoUpdater updater = new CapgoUpdater(logger) {
128
+ @Override
129
+ void nextBundleReady(final BundleInfo bundle) {
130
+ result.set(applyIfNoUi(this, bundle, logger) ? "installed" : "queued");
131
+ finished.countDown();
132
+ }
133
+
134
+ @Override
135
+ void notifyListeners(final String id, final Map<String, Object> res) {
136
+ if ("downloadFailed".equals(id)) {
137
+ result.set("failed");
138
+ finished.countDown();
139
+ } else if ("updateAvailable".equals(id) && !setNext) {
140
+ result.set("downloaded");
141
+ finished.countDown();
142
+ }
143
+ }
144
+ };
145
+ configure(updater, context, config, prefs, packageInfo, versionCode, logger);
146
+ try {
147
+ String updateUrl = config.getString("updateUrl", CapacitorUpdaterPlugin.updateUrlDefault);
148
+ if (config.getBoolean("persistModifyUrl", false) && prefs.contains(CapacitorUpdaterPlugin.UPDATE_URL_PREF_KEY)) {
149
+ updateUrl = prefs.getString(CapacitorUpdaterPlugin.UPDATE_URL_PREF_KEY, updateUrl);
150
+ }
151
+ if (updateUrl == null || updateUrl.isEmpty()) {
152
+ return "unavailable";
153
+ }
154
+
155
+ final AtomicReference<Map<String, Object>> latestRef = new AtomicReference<>();
156
+ final CountDownLatch latestDone = new CountDownLatch(1);
157
+ updater.getLatest(updateUrl, null, (res) -> {
158
+ latestRef.set(res);
159
+ latestDone.countDown();
160
+ });
161
+ try {
162
+ if (!latestDone.await(updater.timeout + 5000L, TimeUnit.MILLISECONDS)) {
163
+ return "failed";
164
+ }
165
+ } catch (final InterruptedException e) {
166
+ Thread.currentThread().interrupt();
167
+ return "failed";
168
+ }
169
+ final Map<String, Object> latest = latestRef.get();
170
+ if (latest == null || latest.containsKey("error") || latest.containsKey("kind")) {
171
+ return "no_update";
172
+ }
173
+ final String version = String.valueOf(latest.get("version"));
174
+ final Object url = latest.get("url");
175
+ final BundleInfo current = updater.getCurrentBundle();
176
+ if ("builtin".equals(version) || version.isEmpty() || version.equals(current.getVersionName()) || !(url instanceof String)) {
177
+ return "no_update";
178
+ }
179
+ final String sessionKey = latest.get("sessionKey") instanceof String ? (String) latest.get("sessionKey") : "";
180
+ final String checksum = latest.get("checksum") instanceof String ? (String) latest.get("checksum") : "";
181
+
182
+ final BundleInfo existing = updater.getBundleInfoByName(version);
183
+ if (existing != null && existing.isErrorStatus()) {
184
+ return "failed";
185
+ }
186
+ final String reused = reuseDownloadedBundle(updater, existing, version, setNext, logger);
187
+ if (reused != null) {
188
+ return reused;
189
+ }
190
+
191
+ // downloadBackground returns null when it refuses the download (blocked encryption, gate,
192
+ // version already downloading): only wait for a download it started.
193
+ final String startedId = updater.downloadBackground((String) url, version, sessionKey, checksum, manifestOf(latest), setNext);
194
+ if (startedId == null) {
195
+ return "skipped";
196
+ }
197
+ final long deadline = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(FINISH_TIMEOUT_MINUTES);
198
+ try {
199
+ // Keep the worker (and so the process) alive until the bundle is stored. If the user opens
200
+ // the app meanwhile, its plugin instance takes over the download (it restarts downloads it
201
+ // does not observe), so stop waiting.
202
+ while (!finished.await(1, TimeUnit.SECONDS)) {
203
+ if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
204
+ return "handed_over";
205
+ }
206
+ if (System.currentTimeMillis() > deadline) {
207
+ return "timeout";
208
+ }
209
+ }
210
+ } catch (final InterruptedException e) {
211
+ Thread.currentThread().interrupt();
212
+ return "interrupted";
213
+ }
214
+ return result.get();
215
+ } finally {
216
+ // Once the plugin instance is up it owns the stats file: hand it our unsent events
217
+ // instead of overwriting its newer file.
218
+ synchronized (CapacitorUpdaterPlugin.INSTANCE_LOADED_LOCK) {
219
+ if (CapacitorUpdaterPlugin.instanceLoaded) {
220
+ updater.handOverPendingStats();
221
+ updater.shutdown(false);
222
+ } else {
223
+ updater.shutdown(true);
224
+ }
225
+ }
226
+ }
227
+ }
228
+
229
+ /**
230
+ * With no plugin instance (no bridge, no WebView) nothing shows the current bundle, so switching
231
+ * it is the same as installing on a background transition. Delay conditions keep it as next.
232
+ */
233
+ static boolean applyIfNoUi(final CapgoUpdater updater, final BundleInfo bundle, final Logger logger) {
234
+ if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
235
+ return false;
236
+ }
237
+ final String delays = updater.prefs.getString(DelayUpdateUtils.DELAY_CONDITION_PREFERENCES, "[]");
238
+ if (delays != null && !"[]".equals(delays.trim())) {
239
+ logger.info("Update delayed until delay conditions met");
240
+ return false;
241
+ }
242
+ if (updater.set(bundle)) {
243
+ updater.setNextBundle(null);
244
+ logger.info("Installed bundle " + bundle.getVersionName() + " for the next launch");
245
+ return true;
246
+ }
247
+ return false;
248
+ }
249
+
250
+ /**
251
+ * When builtinMinimum is on, refuse an existing downloaded bundle whose version is below the native build.
252
+ * Shared by tests and {@link #run} so removing the guard breaks a unit test.
253
+ */
254
+ static boolean builtinMinimumBlocksExistingBundle(final CapgoUpdater updater, final String bundleVersion, final Logger logger) {
255
+ try {
256
+ updater.requireVersionNotBelowBuiltin(bundleVersion);
257
+ return false;
258
+ } catch (final IOException e) {
259
+ logger.error(e.getMessage() == null ? "Download blocked" : e.getMessage());
260
+ return true;
261
+ }
262
+ }
263
+
264
+ static JSONArray manifestOf(final Map<String, Object> latest) {
265
+ final Object manifest = latest.get("manifest");
266
+ if (manifest instanceof JSONArray) {
267
+ return (JSONArray) manifest;
268
+ }
269
+ if (manifest instanceof String) {
270
+ try {
271
+ return new JSONArray((String) manifest);
272
+ } catch (final JSONException e) {
273
+ return null;
274
+ }
275
+ }
276
+ return null;
277
+ }
278
+
279
+ static boolean nativeBuildChanged(final SharedPreferences prefs, final String versionCode) {
280
+ String previous = prefs.getString("LatestNativeBuildVersion", "");
281
+ if (previous == null || previous.isEmpty()) {
282
+ previous = prefs.getString("LatestVersionNative", "");
283
+ }
284
+ return previous != null && !previous.isEmpty() && !previous.equals(versionCode);
285
+ }
286
+
287
+ private static PackageInfo getPackageInfo(final Context context) throws PackageManager.NameNotFoundException {
288
+ final PackageManager packageManager = context.getPackageManager();
289
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
290
+ return packageManager.getPackageInfo(context.getPackageName(), PackageManager.PackageInfoFlags.of(0));
291
+ }
292
+ return packageManager.getPackageInfo(context.getPackageName(), 0);
293
+ }
294
+
295
+ /**
296
+ * Reuses a bundle already downloaded for {@code version}: queues it, and installs it when no UI runs, after
297
+ * the same builtinMinimum gate a fresh download goes through. Returns null when there is nothing to reuse.
298
+ */
299
+ static String reuseDownloadedBundle(
300
+ final CapgoUpdater updater,
301
+ final BundleInfo existing,
302
+ final String version,
303
+ final boolean setNext,
304
+ final Logger logger
305
+ ) {
306
+ if (existing == null || !existing.isDownloaded() || BundleStatus.DOWNLOADING == existing.getStatus()) {
307
+ return null;
308
+ }
309
+ if (builtinMinimumBlocksExistingBundle(updater, version, logger)) {
310
+ if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
311
+ updater.handOverPendingStats();
312
+ }
313
+ return "skipped";
314
+ }
315
+ if (setNext && updater.setNextBundle(existing.getId())) {
316
+ return applyIfNoUi(updater, existing, logger) ? "installed" : "queued";
317
+ }
318
+ return "downloaded";
319
+ }
320
+
321
+ /** Mirrors the identity, URL and builtinMinimum setup of CapacitorUpdaterPlugin#load. */
322
+ private static void configure(
323
+ final CapgoUpdater updater,
324
+ final Context context,
325
+ final PluginConfig config,
326
+ final SharedPreferences prefs,
327
+ final PackageInfo packageInfo,
328
+ final String versionCode,
329
+ final Logger headlessLogger
330
+ ) {
331
+ updater.appContext = context;
332
+ updater.prefs = prefs;
333
+ updater.editor = prefs.edit();
334
+ updater.documentsDir = context.getFilesDir();
335
+ updater.noBackupDir = context.getNoBackupFilesDir();
336
+ // Shares the plugin's pending-stats file: load it first so a flush does not overwrite it.
337
+ updater.restorePendingStats();
338
+ updater.CAP_SERVER_PATH = WebView.CAP_SERVER_PATH;
339
+ updater.pluginVersion = CapacitorUpdaterPlugin.PLUGIN_VERSION;
340
+ updater.versionBuild = config.getString("version", packageInfo.versionName);
341
+ updater.versionCode = versionCode;
342
+ updater.versionOs = Build.VERSION.RELEASE;
343
+
344
+ String appId = InternalUtils.getPackageName(context.getPackageManager(), context.getPackageName());
345
+ appId = InternalUtils.getRootConfigString(context, "appId", appId);
346
+ updater.appId = config.getString("appId", appId);
347
+ updater.setPublicKey(config.getString("publicKey", ""));
348
+ // Same default as CapacitorUpdaterPlugin#load: on unless the app opts out.
349
+ updater.builtinMinimum = config.getBoolean("builtinMinimum", true);
350
+
351
+ DownloadService.setAllowHttpsToHttpRedirect(config.getBoolean("allowHttpsToHttpRedirect", false));
352
+ Http3.setEnabled(config.getBoolean("http3", true));
353
+ final boolean httpsOnly = config.getBoolean("httpsOnly", true);
354
+ updater.httpsOnly = httpsOnly;
355
+ DownloadService.setHttpsOnly(httpsOnly);
356
+ DownloadService.setLoggerIfAbsent(headlessLogger);
357
+ DownloadWorkerManager.setLoggerIfAbsent(headlessLogger);
358
+
359
+ final boolean persistModifyUrl = config.getBoolean("persistModifyUrl", false);
360
+ updater.statsUrl = config.getString("statsUrl", CapacitorUpdaterPlugin.statsUrlDefault);
361
+ updater.channelUrl = config.getString("channelUrl", CapacitorUpdaterPlugin.channelUrlDefault);
362
+ if (persistModifyUrl) {
363
+ updater.statsUrl = prefs.getString(CapacitorUpdaterPlugin.STATS_URL_PREF_KEY, updater.statsUrl);
364
+ updater.channelUrl = prefs.getString(CapacitorUpdaterPlugin.CHANNEL_URL_PREF_KEY, updater.channelUrl);
365
+ }
366
+
367
+ final String storedDefaultChannel = prefs.getString(CapacitorUpdaterPlugin.DEFAULT_CHANNEL_PREF_KEY, "");
368
+ updater.defaultChannel =
369
+ storedDefaultChannel != null && !storedDefaultChannel.isEmpty() ? storedDefaultChannel : config.getString("defaultChannel", "");
370
+
371
+ if (config.getBoolean("persistCustomId", true)) {
372
+ final String storedCustomId = prefs.getString(CapacitorUpdaterPlugin.CUSTOM_ID_PREF_KEY, "");
373
+ if (storedCustomId != null && !storedCustomId.isEmpty()) {
374
+ updater.customId = storedCustomId;
375
+ }
376
+ }
377
+ updater.deviceID = DeviceIdHelper.getOrCreateDeviceId(context, prefs);
378
+
379
+ final int responseTimeoutSeconds = config.getInt("responseTimeout", 20);
380
+ final long responseTimeoutMillis = responseTimeoutSeconds > 0 ? (long) responseTimeoutSeconds * 1000L : 20_000L;
381
+ updater.timeout = (int) Math.min(Integer.MAX_VALUE, responseTimeoutMillis);
382
+ DownloadService.applyHttpTimeouts(updater.timeout);
383
+ DownloadService.updateUserAgent(updater.appId, updater.pluginVersion, updater.versionOs);
384
+ }
385
+ }