@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,553 @@
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
+ package ee.forgr.capacitor_updater;
7
+
8
+ import android.content.Context;
9
+ import android.net.http.HttpEngine;
10
+ import android.net.http.HttpException;
11
+ import android.net.http.NetworkException;
12
+ import android.net.http.UrlRequest;
13
+ import android.net.http.UrlResponseInfo;
14
+ import android.os.Build;
15
+ import androidx.annotation.NonNull;
16
+ import androidx.annotation.Nullable;
17
+ import androidx.annotation.RequiresExtension;
18
+ import java.io.File;
19
+ import java.io.IOException;
20
+ import java.io.InputStream;
21
+ import java.io.InterruptedIOException;
22
+ import java.net.ConnectException;
23
+ import java.net.SocketException;
24
+ import java.net.SocketTimeoutException;
25
+ import java.net.UnknownHostException;
26
+ import java.nio.ByteBuffer;
27
+ import java.util.concurrent.BlockingQueue;
28
+ import java.util.concurrent.ConcurrentHashMap;
29
+ import java.util.concurrent.Executor;
30
+ import java.util.concurrent.ExecutorService;
31
+ import java.util.concurrent.Executors;
32
+ import java.util.concurrent.LinkedBlockingQueue;
33
+ import java.util.concurrent.TimeUnit;
34
+ import java.util.concurrent.atomic.AtomicLong;
35
+ import okhttp3.Call;
36
+ import okhttp3.Headers;
37
+ import okhttp3.MediaType;
38
+ import okhttp3.Request;
39
+ import okhttp3.Response;
40
+ import okhttp3.ResponseBody;
41
+ import okio.Okio;
42
+
43
+ /**
44
+ * {@link Http3.Transport} on the platform HttpEngine. Uses the UrlRequest callback API rather than the engine's
45
+ * HttpURLConnection so every redirect hop goes through the updater's https policy, timeouts are enforced (the
46
+ * engine ignores connect timeouts), and the negotiated protocol can be logged.
47
+ */
48
+ @RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
49
+ final class HttpEngineTransport implements Http3.Transport {
50
+
51
+ static final String STORAGE_DIR = "capgo_httpengine";
52
+ // Room for Alt-Svc, QUIC server info and host cache only: DISK_NO_HTTP never stores a response body.
53
+ private static final long STORAGE_BYTES = 1024 * 1024;
54
+ private static final int READ_BUFFER_BYTES = 32 * 1024;
55
+ // Poll slice so a cancelled OkHttp call (WorkManager stop) stops waiting promptly and a stall is seen within
56
+ // 50 ms of the stall window.
57
+ private static final long POLL_MS = 50;
58
+
59
+ private final HttpEngine engine;
60
+ private final Executor callbackExecutor;
61
+ private final Liveness liveness = new Liveness();
62
+
63
+ /** Time source and event wait. Tests replace it so stall timing never depends on thread scheduling. */
64
+ interface Clock {
65
+ long nanoTime();
66
+
67
+ /** Waits up to {@code timeoutMs} for the next event, null when none arrived. */
68
+ @Nullable
69
+ Object poll(@NonNull BlockingQueue<Object> events, long timeoutMs) throws InterruptedException;
70
+ }
71
+
72
+ static final Clock SYSTEM_CLOCK = new Clock() {
73
+ @Override
74
+ public long nanoTime() {
75
+ return System.nanoTime();
76
+ }
77
+
78
+ @Nullable
79
+ @Override
80
+ public Object poll(@NonNull BlockingQueue<Object> events, long timeoutMs) throws InterruptedException {
81
+ return events.poll(timeoutMs, TimeUnit.MILLISECONDS);
82
+ }
83
+ };
84
+
85
+ private HttpEngineTransport(HttpEngine engine, Executor callbackExecutor) {
86
+ this.engine = engine;
87
+ this.callbackExecutor = callbackExecutor;
88
+ }
89
+
90
+ @NonNull
91
+ static Http3.Transport create(@NonNull Context context, @Nullable Logger logger) {
92
+ // noBackupFilesDir: kept across launches (unlike a cache dir the OS may clear) and never restored onto
93
+ // another device or network by Auto Backup.
94
+ File storage = new File(context.getNoBackupFilesDir(), STORAGE_DIR);
95
+ if (!storage.isDirectory() && !storage.mkdirs()) {
96
+ throw new IllegalStateException("cannot create " + storage.getAbsolutePath());
97
+ }
98
+ HttpEngine engine = new HttpEngine.Builder(context)
99
+ .setStoragePath(storage.getAbsolutePath())
100
+ .setEnableHttpCache(HttpEngine.Builder.HTTP_CACHE_DISK_NO_HTTP, STORAGE_BYTES)
101
+ .setEnableQuic(true)
102
+ .setEnableHttp2(true)
103
+ .build();
104
+ ExecutorService executor = Executors.newSingleThreadExecutor((runnable) -> {
105
+ Thread thread = new Thread(runnable, "capgo-httpengine");
106
+ thread.setDaemon(true);
107
+ return thread;
108
+ });
109
+ return new HttpEngineTransport(engine, executor);
110
+ }
111
+
112
+ @NonNull
113
+ @Override
114
+ public Response execute(@NonNull Request request, int connectTimeoutMs, int readTimeoutMs, @Nullable Call call) throws IOException {
115
+ EngineCall engineCall = new EngineCall(request.url().toString(), call, liveness, Http3.STALL_MS);
116
+ UrlRequest.Builder builder = engine.newUrlRequestBuilder(request.url().toString(), callbackExecutor, engineCall);
117
+ builder.setHttpMethod("GET");
118
+ Headers headers = request.headers();
119
+ for (int i = 0; i < headers.size(); i++) {
120
+ builder.addHeader(headers.name(i), headers.value(i));
121
+ }
122
+ UrlRequest urlRequest = builder.build();
123
+ engineCall.start(urlRequest);
124
+ // OkHttp: connect timeout for the connection, then read timeout for the response headers.
125
+ UrlResponseInfo info = engineCall.awaitResponse(headerWaitBudgetMs(connectTimeoutMs, readTimeoutMs));
126
+ String negotiated = info.getNegotiatedProtocol();
127
+ Http3.logProtocol("HttpEngine", negotiated, request.url(), info.getHttpStatusCode());
128
+
129
+ Headers responseHeaders = Http3.responseHeaders(info.getHeaders().getAsList());
130
+ String contentType = responseHeaders.get("Content-Type");
131
+ String contentLength = responseHeaders.get("Content-Length");
132
+ long length = -1;
133
+ if (contentLength != null) {
134
+ try {
135
+ length = Long.parseLong(contentLength.trim());
136
+ } catch (NumberFormatException ignored) {}
137
+ }
138
+ String message = info.getHttpStatusText();
139
+ Request finalRequest = request;
140
+ String finalUrl = info.getUrl();
141
+ if (finalUrl != null && !finalUrl.equals(request.url().toString())) {
142
+ okhttp3.HttpUrl parsed = okhttp3.HttpUrl.parse(finalUrl);
143
+ if (parsed != null) {
144
+ finalRequest = request.newBuilder().url(parsed).build();
145
+ }
146
+ }
147
+ InputStream body = engineCall.bodyStream(readTimeoutMs);
148
+ return new Response.Builder()
149
+ .request(finalRequest)
150
+ .protocol(Http3.protocolFor(negotiated))
151
+ .code(info.getHttpStatusCode())
152
+ .message(message != null ? message : "")
153
+ .headers(responseHeaders)
154
+ .body(ResponseBody.create(Okio.buffer(Okio.source(body)), contentType != null ? MediaType.parse(contentType) : null, length))
155
+ .build();
156
+ }
157
+
158
+ static IOException translate(@NonNull HttpException error) {
159
+ if (error instanceof NetworkException) {
160
+ return networkError(((NetworkException) error).getErrorCode(), error.getMessage(), error);
161
+ }
162
+ return new IOException("HttpEngine request failed: " + error.getMessage(), error);
163
+ }
164
+
165
+ /**
166
+ * Maps HttpEngine network errors onto the java.net exceptions OkHttp throws for the same failure, so the
167
+ * download retry logic ({@link DownloadService#isRetryableManifestError}) treats them the same way.
168
+ * TLS and any other engine error stay a plain IOException, which is not retried.
169
+ */
170
+ @NonNull
171
+ static IOException networkError(int errorCode, @Nullable String message, @Nullable Throwable cause) {
172
+ String text = "HttpEngine request failed: " + message;
173
+ IOException mapped;
174
+ switch (errorCode) {
175
+ case NetworkException.ERROR_HOSTNAME_NOT_RESOLVED:
176
+ mapped = new UnknownHostException(text);
177
+ break;
178
+ case NetworkException.ERROR_TIMED_OUT:
179
+ case NetworkException.ERROR_CONNECTION_TIMED_OUT:
180
+ mapped = new SocketTimeoutException(text);
181
+ break;
182
+ case NetworkException.ERROR_CONNECTION_REFUSED:
183
+ mapped = new ConnectException(text);
184
+ break;
185
+ case NetworkException.ERROR_INTERNET_DISCONNECTED:
186
+ case NetworkException.ERROR_NETWORK_CHANGED:
187
+ case NetworkException.ERROR_CONNECTION_CLOSED:
188
+ case NetworkException.ERROR_CONNECTION_RESET:
189
+ case NetworkException.ERROR_ADDRESS_UNREACHABLE:
190
+ case NetworkException.ERROR_QUIC_PROTOCOL_FAILED:
191
+ mapped = new SocketException(text);
192
+ break;
193
+ default:
194
+ return new IOException(text, cause);
195
+ }
196
+ if (cause != null) {
197
+ mapped.initCause(cause);
198
+ }
199
+ return mapped;
200
+ }
201
+
202
+ /** Longest wait for response headers, whatever the configured timeouts add up to (AGENTS.md: 10 minutes max). */
203
+ static final long MAX_HEADER_WAIT_MS = 600_000;
204
+
205
+ /** OkHttp waits connect timeout then read timeout for headers; the engine has one wait, so it gets the sum, capped. */
206
+ static long headerWaitBudgetMs(int connectTimeoutMs, int readTimeoutMs) {
207
+ // 0 means no timeout in OkHttp.
208
+ if (connectTimeoutMs <= 0 || readTimeoutMs <= 0) {
209
+ return 0;
210
+ }
211
+ return Math.min(MAX_HEADER_WAIT_MS, (long) connectTimeoutMs + (long) readTimeoutMs);
212
+ }
213
+
214
+ /** Wait for each body chunk: the read timeout, capped like the header wait (AGENTS.md: 10 minutes max). */
215
+ static int bodyReadTimeoutMs(int readTimeoutMs) {
216
+ // 0 means no timeout in OkHttp.
217
+ if (readTimeoutMs <= 0) {
218
+ return 0;
219
+ }
220
+ return (int) Math.min(MAX_HEADER_WAIT_MS, readTimeoutMs);
221
+ }
222
+
223
+ /**
224
+ * Last time any request on the shared engine got a callback (one engine, one picture of whether it is alive),
225
+ * and the last time per host, which tells a request on a warm connection from one still setting up a new one.
226
+ */
227
+ static final class Liveness {
228
+
229
+ private final AtomicLong lastNanos = new AtomicLong();
230
+ // A handful of download hosts per process (update server, CDN, redirect targets), so this stays tiny.
231
+ private final ConcurrentHashMap<String, Long> hostNanos = new ConcurrentHashMap<>();
232
+ // False until the first callback: a new engine has not proven it is alive, so nothing can stall yet.
233
+ private volatile boolean seen;
234
+ final Clock clock;
235
+
236
+ Liveness() {
237
+ this(SYSTEM_CLOCK);
238
+ }
239
+
240
+ Liveness(@NonNull Clock clock) {
241
+ this.clock = clock;
242
+ }
243
+
244
+ void mark(@NonNull String host) {
245
+ long now = clock.nanoTime();
246
+ lastNanos.set(now);
247
+ hostNanos.put(host, now);
248
+ seen = true;
249
+ }
250
+
251
+ /** Last callback for a request to {@code host}, or null when the engine has not talked to it yet. */
252
+ @Nullable
253
+ Long lastNanos(@NonNull String host) {
254
+ return hostNanos.get(host);
255
+ }
256
+
257
+ boolean seen() {
258
+ return seen;
259
+ }
260
+
261
+ long lastNanos() {
262
+ return lastNanos.get();
263
+ }
264
+ }
265
+
266
+ /** Bridges the engine callbacks to a blocking response and body stream. */
267
+ static final class EngineCall implements UrlRequest.Callback {
268
+
269
+ private static final Object SUCCEEDED = new Object();
270
+
271
+ private static final class Started {
272
+
273
+ final UrlResponseInfo info;
274
+
275
+ Started(UrlResponseInfo info) {
276
+ this.info = info;
277
+ }
278
+ }
279
+
280
+ private static final class ReadDone {
281
+
282
+ final ByteBuffer buffer;
283
+
284
+ ReadDone(ByteBuffer buffer) {
285
+ this.buffer = buffer;
286
+ }
287
+ }
288
+
289
+ private static final class Failed {
290
+
291
+ final IOException error;
292
+
293
+ Failed(IOException error) {
294
+ this.error = error;
295
+ }
296
+ }
297
+
298
+ private final BlockingQueue<Object> events = new LinkedBlockingQueue<>();
299
+ private final String url;
300
+
301
+ @Nullable
302
+ private final Call call;
303
+
304
+ private volatile UrlRequest request;
305
+ private volatile String currentUrl;
306
+ private volatile String currentHost;
307
+ private volatile IOException redirectError;
308
+
309
+ private final Liveness liveness;
310
+ private final long stallNanos;
311
+
312
+ EngineCall(String url, @Nullable Call call) {
313
+ this(url, call, new Liveness(), Http3.STALL_MS);
314
+ }
315
+
316
+ EngineCall(String url, @Nullable Call call, @NonNull Liveness liveness, long stallMs) {
317
+ this.url = url;
318
+ this.currentUrl = url;
319
+ this.currentHost = Http3.safeHost(url);
320
+ this.call = call;
321
+ this.liveness = liveness;
322
+ this.stallNanos = TimeUnit.MILLISECONDS.toNanos(stallMs);
323
+ }
324
+
325
+ void start(UrlRequest urlRequest) {
326
+ this.request = urlRequest;
327
+ urlRequest.start();
328
+ }
329
+
330
+ @Override
331
+ public void onRedirectReceived(@NonNull UrlRequest urlRequest, @NonNull UrlResponseInfo info, @NonNull String newLocationUrl) {
332
+ liveness.mark(currentHost);
333
+ IOException error = Http3.redirectError(currentUrl, newLocationUrl);
334
+ if (error != null) {
335
+ redirectError = error;
336
+ urlRequest.cancel();
337
+ return;
338
+ }
339
+ currentUrl = newLocationUrl;
340
+ currentHost = Http3.safeHost(newLocationUrl);
341
+ urlRequest.followRedirect();
342
+ }
343
+
344
+ @Override
345
+ public void onResponseStarted(@NonNull UrlRequest urlRequest, @NonNull UrlResponseInfo info) {
346
+ publish(new Started(info));
347
+ }
348
+
349
+ @Override
350
+ public void onReadCompleted(@NonNull UrlRequest urlRequest, @NonNull UrlResponseInfo info, @NonNull ByteBuffer byteBuffer) {
351
+ publish(new ReadDone(byteBuffer));
352
+ }
353
+
354
+ @Override
355
+ public void onSucceeded(@NonNull UrlRequest urlRequest, @NonNull UrlResponseInfo info) {
356
+ publish(SUCCEEDED);
357
+ }
358
+
359
+ @Override
360
+ public void onFailed(@NonNull UrlRequest urlRequest, @Nullable UrlResponseInfo info, @NonNull HttpException error) {
361
+ publish(new Failed(translate(error)));
362
+ }
363
+
364
+ @Override
365
+ public void onCanceled(@NonNull UrlRequest urlRequest, @Nullable UrlResponseInfo info) {
366
+ IOException error = redirectError;
367
+ events.offer(new Failed(error != null ? error : new IOException("Canceled")));
368
+ }
369
+
370
+ /**
371
+ * Marks progress and queues an event under the liveness lock, so a stall decision either sees the event or
372
+ * finishes before it was published, never in between.
373
+ */
374
+ private void publish(@NonNull Object event) {
375
+ synchronized (liveness) {
376
+ liveness.mark(currentHost);
377
+ events.offer(event);
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Next callback event, or null on timeout (0 waits forever). Cancels the request when OkHttp's call is.
383
+ * Throws {@link Http3.EngineStalledException} when the whole engine went silent for the stall window: always
384
+ * while waiting for headers (the caller can still retry on OkHttp) if the engine was busy just before, and
385
+ * while reading a body only once a stall is already confirmed, so a slow single body never trips it.
386
+ */
387
+ @Nullable
388
+ private Object next(long timeoutMs, boolean waitingForHeaders) throws IOException {
389
+ Clock clock = liveness.clock;
390
+ long start = clock.nanoTime();
391
+ long deadline = timeoutMs > 0 ? start + TimeUnit.MILLISECONDS.toNanos(timeoutMs) : Long.MAX_VALUE;
392
+ try {
393
+ while (true) {
394
+ if (call != null && call.isCanceled()) {
395
+ cancel();
396
+ throw new IOException("Canceled");
397
+ }
398
+ // An event already queued is progress, even if this thread resumed late: hand it over instead
399
+ // of cancelling a request whose response already arrived.
400
+ Object ready = pollOrDetectStall(start, waitingForHeaders);
401
+ if (ready != null) {
402
+ return ready;
403
+ }
404
+ long remainingMs = timeoutMs > 0 ? TimeUnit.NANOSECONDS.toMillis(deadline - clock.nanoTime()) : POLL_MS;
405
+ if (remainingMs <= 0) {
406
+ return null;
407
+ }
408
+ Object event = clock.poll(events, Math.min(POLL_MS, remainingMs));
409
+ if (event != null) {
410
+ return event;
411
+ }
412
+ }
413
+ } catch (InterruptedException e) {
414
+ Thread.currentThread().interrupt();
415
+ cancel();
416
+ throw new InterruptedIOException("interrupted");
417
+ }
418
+ }
419
+
420
+ /**
421
+ * A queued event, else null when the engine is not stalled. The queue check and the stall decision run under
422
+ * the same lock as {@link #publish}, so a callback can never land between them and be dropped as a stall.
423
+ */
424
+ @Nullable
425
+ private Object pollOrDetectStall(long waitStartNanos, boolean waitingForHeaders) throws Http3.EngineStalledException {
426
+ long silentMs;
427
+ synchronized (liveness) {
428
+ Object ready = events.poll();
429
+ if (ready != null) {
430
+ return ready;
431
+ }
432
+ long now = liveness.clock.nanoTime();
433
+ boolean seen = liveness.seen();
434
+ long last = seen ? liveness.lastNanos() : waitStartNanos;
435
+ // Headers: only when the engine was talking to this same host right before this wait, so the request
436
+ // rides a warm connection. The first request of a process, a lone one after a quiet period, and one to
437
+ // a host the engine has not reached recently (a redirect target, another CDN) pay a full handshake
438
+ // that can take longer on a slow network, and keep the normal timeout instead of suspending HTTP/3.
439
+ Long hostLast = liveness.lastNanos(currentHost);
440
+ boolean warm = hostLast != null && hostLast - (waitStartNanos - stallNanos) >= 0;
441
+ boolean armed = waitingForHeaders ? warm : Http3.isSuspended(now);
442
+ long silentSince = last - waitStartNanos >= 0 ? last : waitStartNanos;
443
+ if (!armed || now - silentSince < stallNanos) {
444
+ return null;
445
+ }
446
+ silentMs = TimeUnit.NANOSECONDS.toMillis(now - silentSince);
447
+ }
448
+ // Outside the lock: cancelling posts onCanceled to the callback executor.
449
+ cancel();
450
+ throw new Http3.EngineStalledException("HttpEngine made no progress for " + silentMs + " ms on " + Http3.safeHost(url));
451
+ }
452
+
453
+ UrlResponseInfo awaitResponse(long timeoutMs) throws IOException {
454
+ Object event = next(timeoutMs, true);
455
+ if (event instanceof Started) {
456
+ return ((Started) event).info;
457
+ }
458
+ if (event instanceof Failed) {
459
+ throw ((Failed) event).error;
460
+ }
461
+ cancel();
462
+ throw new SocketTimeoutException("HttpEngine timeout waiting for response headers from " + Http3.safeHost(url));
463
+ }
464
+
465
+ InputStream bodyStream(int readTimeoutMs) {
466
+ return new BodyStream(readTimeoutMs);
467
+ }
468
+
469
+ void cancel() {
470
+ UrlRequest current = request;
471
+ if (current != null && !current.isDone()) {
472
+ current.cancel();
473
+ }
474
+ }
475
+
476
+ private final class BodyStream extends InputStream {
477
+
478
+ private final int readTimeoutMs;
479
+ private final ByteBuffer buffer = ByteBuffer.allocateDirect(READ_BUFFER_BYTES);
480
+ private boolean done;
481
+ private boolean closed;
482
+
483
+ BodyStream(int readTimeoutMs) {
484
+ this.readTimeoutMs = bodyReadTimeoutMs(readTimeoutMs);
485
+ buffer.limit(0);
486
+ }
487
+
488
+ @Override
489
+ public int read() throws IOException {
490
+ byte[] one = new byte[1];
491
+ int n = read(one, 0, 1);
492
+ return n == -1 ? -1 : one[0] & 0xff;
493
+ }
494
+
495
+ @Override
496
+ public int read(@NonNull byte[] target, int offset, int length) throws IOException {
497
+ if (closed) {
498
+ throw new IOException("closed");
499
+ }
500
+ if (length == 0) {
501
+ return 0;
502
+ }
503
+ while (!buffer.hasRemaining()) {
504
+ if (done) {
505
+ return -1;
506
+ }
507
+ buffer.clear();
508
+ request.read(buffer);
509
+ Object event = next(readTimeoutMs, false);
510
+ if (event instanceof ReadDone) {
511
+ buffer.flip();
512
+ } else if (event == SUCCEEDED) {
513
+ done = true;
514
+ buffer.limit(0);
515
+ } else if (event instanceof Failed) {
516
+ done = true;
517
+ buffer.limit(0);
518
+ throw ((Failed) event).error;
519
+ } else {
520
+ done = true;
521
+ buffer.limit(0);
522
+ cancel();
523
+ // The body stalled on the engine. Skip it for the cooldown so the caller's retry, which
524
+ // starts a new request and keeps its own partial-file and checksum checks, runs on OkHttp
525
+ // instead of waiting on the same engine again. Bytes already delivered stay from this
526
+ // response; nothing switches streams mid-body.
527
+ Http3.suspendAfterStall(liveness.clock.nanoTime());
528
+ throw new SocketTimeoutException("HttpEngine read timeout");
529
+ }
530
+ }
531
+ int count = Math.min(length, buffer.remaining());
532
+ buffer.get(target, offset, count);
533
+ return count;
534
+ }
535
+
536
+ @Override
537
+ public int available() {
538
+ return buffer.remaining();
539
+ }
540
+
541
+ @Override
542
+ public void close() {
543
+ if (closed) {
544
+ return;
545
+ }
546
+ closed = true;
547
+ if (!done) {
548
+ cancel();
549
+ }
550
+ }
551
+ }
552
+ }
553
+ }
@@ -0,0 +1,79 @@
1
+ package ee.forgr.capacitor_updater;
2
+
3
+ import android.content.Context;
4
+ import android.content.pm.PackageInfo;
5
+ import android.content.pm.PackageManager;
6
+ import android.os.Build;
7
+ import com.getcapacitor.JSObject;
8
+ import com.getcapacitor.util.JSONUtils;
9
+ import java.io.BufferedReader;
10
+ import java.io.IOException;
11
+ import java.io.InputStreamReader;
12
+ import java.nio.charset.StandardCharsets;
13
+ import java.util.Map;
14
+ import org.json.JSONException;
15
+ import org.json.JSONObject;
16
+
17
+ public class InternalUtils {
18
+
19
+ static final String CAPACITOR_CONFIG_ASSET = "capacitor.config.json";
20
+
21
+ /**
22
+ * Converts a Map to JSObject for proper bridge serialization.
23
+ */
24
+ public static JSObject mapToJSObject(Map<String, Object> map) {
25
+ JSObject jsObject = new JSObject();
26
+ for (Map.Entry<String, Object> entry : map.entrySet()) {
27
+ jsObject.put(entry.getKey(), entry.getValue());
28
+ }
29
+ return jsObject;
30
+ }
31
+
32
+ public static String getPackageName(PackageManager pm, String packageName) {
33
+ try {
34
+ PackageInfo pInfo = getPackageInfoInternal(pm, packageName);
35
+ return pInfo != null ? pInfo.packageName : null;
36
+ } catch (PackageManager.NameNotFoundException e) {
37
+ // Exception is handled internally, and null is returned to indicate the package name could not be retrieved
38
+ return null;
39
+ }
40
+ }
41
+
42
+ static String readAssetAsString(final Context context, final String assetPath) throws IOException {
43
+ final StringBuilder buffer = new StringBuilder();
44
+ try (
45
+ final BufferedReader reader = new BufferedReader(
46
+ new InputStreamReader(context.getAssets().open(assetPath), StandardCharsets.UTF_8)
47
+ )
48
+ ) {
49
+ String line;
50
+ while ((line = reader.readLine()) != null) {
51
+ buffer.append(line).append('\n');
52
+ }
53
+ }
54
+ return buffer.toString();
55
+ }
56
+
57
+ /** Replaces CapConfig.getString for root keys: Capacitor 9 removed it. */
58
+ public static String getRootConfigString(Context context, String key, String defaultValue) {
59
+ try {
60
+ return JSONUtils.getString(new JSONObject(readAssetAsString(context, CAPACITOR_CONFIG_ASSET)), key, defaultValue);
61
+ } catch (IOException | JSONException e) {
62
+ return defaultValue;
63
+ }
64
+ }
65
+
66
+ private static PackageInfo getPackageInfoInternal(PackageManager pm, String packageName) throws PackageManager.NameNotFoundException {
67
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
68
+ return pm.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0));
69
+ } else {
70
+ return getPackageInfoLegacy(pm, packageName, (int) (long) 0);
71
+ }
72
+ }
73
+
74
+ @SuppressWarnings("deprecation")
75
+ private static PackageInfo getPackageInfoLegacy(PackageManager pm, String packageName, int flags)
76
+ throws PackageManager.NameNotFoundException {
77
+ return pm.getPackageInfo(packageName, flags);
78
+ }
79
+ }