@capgo/capacitor-updater 9.0.0 → 9.0.2

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 +2406 -291
  4. package/android/build.gradle +37 -17
  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 +7927 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5785 -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 +2041 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +301 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +569 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +436 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +604 -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 +963 -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 +2641 -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 +6813 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +200 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +5099 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +387 -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 +876 -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 +6533 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +156 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +314 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +653 -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 +1109 -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 +196 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +470 -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,436 @@
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.os.Build;
10
+ import android.os.ext.SdkExtensions;
11
+ import androidx.annotation.NonNull;
12
+ import androidx.annotation.Nullable;
13
+ import java.io.IOException;
14
+ import java.net.SocketTimeoutException;
15
+ import java.util.List;
16
+ import java.util.Locale;
17
+ import java.util.Map;
18
+ import java.util.concurrent.TimeUnit;
19
+ import okhttp3.Call;
20
+ import okhttp3.Headers;
21
+ import okhttp3.HttpUrl;
22
+ import okhttp3.Interceptor;
23
+ import okhttp3.Protocol;
24
+ import okhttp3.Request;
25
+ import okhttp3.Response;
26
+
27
+ /**
28
+ * HTTP/3 for bundle and manifest downloads.
29
+ *
30
+ * <p>Where the device has the platform {@code android.net.http.HttpEngine} (Android 14+, or Android 12 and 13
31
+ * with the S extension at level 7), https downloads tagged with {@link #markDownload} run on one shared engine.
32
+ * The engine speaks HTTP/3 when the server advertises it through Alt-Svc and falls back to HTTP/2 on its own when
33
+ * QUIC is blocked. Its storage path and {@code HTTP_CACHE_DISK_NO_HTTP} cache keep the Alt-Svc entries across
34
+ * launches without caching any response, so the next process goes straight to HTTP/3 (finding from
35
+ * https://github.com/Cap-go/capacitor-updater/issues/1027, credit autopylotben).
36
+ *
37
+ * <p>Everything else stays on OkHttp: API calls, requests with a body, plain http, devices without HttpEngine,
38
+ * an engine that failed to start, and apps that set {@code http3: false}.
39
+ */
40
+ final class Http3 {
41
+
42
+ /** Request tag for downloads allowed to run on HttpEngine. */
43
+ static final class Download {
44
+
45
+ static final Download TAG = new Download();
46
+
47
+ private Download() {}
48
+ }
49
+
50
+ /** Request tag on responses HttpEngine served, so a caller can tell an engine body from an OkHttp one. */
51
+ static final class ServedByEngine {
52
+
53
+ static final ServedByEngine TAG = new ServedByEngine();
54
+
55
+ private ServedByEngine() {}
56
+ }
57
+
58
+ static boolean servedByEngine(@Nullable Response response) {
59
+ return response != null && response.request().tag(ServedByEngine.class) != null;
60
+ }
61
+
62
+ /** Runs one tagged download outside OkHttp's network stack. */
63
+ interface Transport {
64
+ @NonNull
65
+ Response execute(@NonNull Request request, int connectTimeoutMs, int readTimeoutMs, @Nullable Call call) throws IOException;
66
+ }
67
+
68
+ interface TransportFactory {
69
+ @NonNull
70
+ Transport create(@NonNull Context context, @Nullable Logger logger);
71
+ }
72
+
73
+ /**
74
+ * The engine made no progress at all (no callback for any request) for {@link #STALL_MS} while a download
75
+ * waited on it. Seen on an Android 16 emulator (HttpEngine 133): right after a large receive burst the QUIC session
76
+ * stops answering, and the engine only gives up on it after its own 6 to 40 s timeout.
77
+ */
78
+ static final class EngineStalledException extends SocketTimeoutException {
79
+
80
+ EngineStalledException(String message) {
81
+ super(message);
82
+ }
83
+ }
84
+
85
+ /**
86
+ * No response headers within the full header-wait budget, without an engine stall (a cold host still setting up
87
+ * its connection). Nothing reached the caller, so the download retries once on OkHttp, but HTTP/3 stays on for
88
+ * other downloads: a slow handshake to one host is not an engine failure.
89
+ */
90
+ static final class EngineHeaderTimeoutException extends SocketTimeoutException {
91
+
92
+ EngineHeaderTimeoutException(String message) {
93
+ super(message);
94
+ }
95
+ }
96
+
97
+ /**
98
+ * How long the whole engine may stay silent, while downloads wait on it, before they move to OkHttp. A live
99
+ * connection with requests in flight answers in a few round trips, far below this.
100
+ */
101
+ static final long STALL_MS = 500;
102
+ /** After a stall, new downloads skip the engine for this long instead of each paying the stall again. */
103
+ static final long STALL_COOLDOWN_MS = 60_000;
104
+
105
+ private static volatile Transport transport;
106
+ private static volatile boolean enabled = true;
107
+ // System.nanoTime() until which downloads skip the engine after a stall; only read while stalledOnce is true.
108
+ private static volatile long suspendedUntilNanos;
109
+ private static volatile boolean stalledOnce;
110
+ // Same cooldown, but set only by a confirmed engine stall (no progress while requests waited on it). Only this
111
+ // arms early cancellation of bodies already streaming; an ordinary body read timeout just reroutes new requests.
112
+ private static volatile long stallConfirmedUntilNanos;
113
+ private static volatile boolean stallConfirmedOnce;
114
+ // Serializes cooldown writes so a delayed writer never replaces a later deadline with an earlier one.
115
+ private static final Object COOLDOWN_LOCK = new Object();
116
+ // True once the plugin or the headless worker applied the http3 config in this process.
117
+ private static volatile boolean configured;
118
+ // Guards the configured check plus the enabled write, kept apart from init() so it never waits on engine setup.
119
+ private static final Object OPTION_LOCK = new Object();
120
+ private static boolean initialized;
121
+
122
+ private Http3() {}
123
+
124
+ /** The http3 config value, applied by plugin load and the headless worker. Wins over saved job values. */
125
+ static void setEnabled(boolean value) {
126
+ synchronized (OPTION_LOCK) {
127
+ enabled = value;
128
+ configured = true;
129
+ }
130
+ }
131
+
132
+ /**
133
+ * The http3 value saved with a WorkManager job. Only used when this process has not loaded the config yet
134
+ * (a job resumed in a fresh process), so a stale job never overrides the current config.
135
+ */
136
+ static void restoreSavedOption(boolean value) {
137
+ synchronized (OPTION_LOCK) {
138
+ if (!configured) {
139
+ enabled = value;
140
+ }
141
+ }
142
+ }
143
+
144
+ static boolean isEnabled() {
145
+ return enabled;
146
+ }
147
+
148
+ /** HttpEngine is public API from 34, and ships to 31-33 through the S extension at level 7. */
149
+ static boolean isHttpEngineAvailable(int sdkInt, int sExtensionVersion) {
150
+ return sdkInt >= 34 || (sdkInt >= 31 && sExtensionVersion >= 7);
151
+ }
152
+
153
+ private static int sExtensionVersion() {
154
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
155
+ return 0;
156
+ }
157
+ return SdkExtensions.getExtensionVersion(Build.VERSION_CODES.S);
158
+ }
159
+
160
+ /** Builds the shared engine once per process. Safe to call before every download. */
161
+ static void init(@NonNull Context context, @Nullable Logger logger) {
162
+ if (transport != null || !enabled) {
163
+ return;
164
+ }
165
+ int sdkInt = Build.VERSION.SDK_INT;
166
+ int extension;
167
+ try {
168
+ extension = sExtensionVersion();
169
+ } catch (RuntimeException e) {
170
+ extension = 0;
171
+ }
172
+ init(context, logger, sdkInt, extension, HttpEngineTransport::create);
173
+ }
174
+
175
+ static synchronized void init(
176
+ @NonNull Context context,
177
+ @Nullable Logger logger,
178
+ int sdkInt,
179
+ int sExtensionVersion,
180
+ @NonNull TransportFactory factory
181
+ ) {
182
+ if (initialized || !enabled) {
183
+ return;
184
+ }
185
+ initialized = true;
186
+ if (!isHttpEngineAvailable(sdkInt, sExtensionVersion)) {
187
+ debug(logger, "HttpEngine not available (API " + sdkInt + "), downloads stay on OkHttp");
188
+ return;
189
+ }
190
+ try {
191
+ transport = factory.create(context.getApplicationContext() != null ? context.getApplicationContext() : context, logger);
192
+ debug(logger, "HttpEngine ready, HTTP/3 enabled for bundle downloads");
193
+ } catch (RuntimeException | LinkageError e) {
194
+ // LinkageError: a device that reports the extension but cannot load the engine classes.
195
+ transport = null;
196
+ if (logger != null) {
197
+ logger.warn("HttpEngine failed to start, downloads stay on OkHttp: " + e.getMessage());
198
+ }
199
+ }
200
+ }
201
+
202
+ @Nullable
203
+ static Transport transport() {
204
+ return transport;
205
+ }
206
+
207
+ /** Called when the engine stalled: downloads use OkHttp for {@link #STALL_COOLDOWN_MS}. */
208
+ static void suspendAfterStall(long nowNanos) {
209
+ long until = nowNanos + TimeUnit.MILLISECONDS.toNanos(STALL_COOLDOWN_MS);
210
+ synchronized (COOLDOWN_LOCK) {
211
+ extendSuspension(until);
212
+ if (!stallConfirmedOnce || until - stallConfirmedUntilNanos > 0) {
213
+ stallConfirmedUntilNanos = until;
214
+ }
215
+ stallConfirmedOnce = true;
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Called when a body read timed out: new downloads use OkHttp for {@link #STALL_COOLDOWN_MS}, but bodies already
221
+ * streaming on the engine keep their normal read timeout, because one slow response does not prove the engine stalled.
222
+ */
223
+ static void suspendAfterBodyTimeout(long nowNanos) {
224
+ long until = nowNanos + TimeUnit.MILLISECONDS.toNanos(STALL_COOLDOWN_MS);
225
+ synchronized (COOLDOWN_LOCK) {
226
+ extendSuspension(until);
227
+ }
228
+ }
229
+
230
+ /** Keeps the later reroute deadline; callers hold {@link #COOLDOWN_LOCK}. */
231
+ private static void extendSuspension(long untilNanos) {
232
+ if (!stalledOnce || untilNanos - suspendedUntilNanos > 0) {
233
+ suspendedUntilNanos = untilNanos;
234
+ }
235
+ stalledOnce = true;
236
+ }
237
+
238
+ /** Whether new downloads skip the engine (after a confirmed stall or a body read timeout). */
239
+ static boolean isSuspended(long nowNanos) {
240
+ return stalledOnce && nowNanos - suspendedUntilNanos < 0;
241
+ }
242
+
243
+ /** Whether a confirmed engine stall is recent enough to cancel silent bodies early. */
244
+ static boolean isStallConfirmed(long nowNanos) {
245
+ return stallConfirmedOnce && nowNanos - stallConfirmedUntilNanos < 0;
246
+ }
247
+
248
+ /** Test hook: forget the engine so the next init() starts over. */
249
+ static synchronized void resetForTest() {
250
+ transport = null;
251
+ initialized = false;
252
+ stalledOnce = false;
253
+ stallConfirmedOnce = false;
254
+ synchronized (OPTION_LOCK) {
255
+ enabled = true;
256
+ configured = false;
257
+ }
258
+ }
259
+
260
+ @NonNull
261
+ static Request.Builder markDownload(@NonNull Request.Builder builder) {
262
+ return builder.tag(Download.class, Download.TAG);
263
+ }
264
+
265
+ static boolean shouldUseEngine(@NonNull Request request) {
266
+ return (
267
+ enabled &&
268
+ request.tag(Download.class) != null &&
269
+ "GET".equals(request.method()) &&
270
+ request.body() == null &&
271
+ // HTTP/3 only exists over TLS, so plain http (local dev servers) keeps the OkHttp path.
272
+ request.isHttps() &&
273
+ !isSuspended(System.nanoTime())
274
+ );
275
+ }
276
+
277
+ /**
278
+ * Last application interceptor on the shared client, so User-Agent and the httpsOnly gate already ran.
279
+ * The engine follows redirects itself, and checks every hop with {@link #redirectError}.
280
+ */
281
+ static final class EngineInterceptor implements Interceptor {
282
+
283
+ @NonNull
284
+ @Override
285
+ public Response intercept(@NonNull Chain chain) throws IOException {
286
+ Request request = chain.request();
287
+ Transport current = transport;
288
+ if (current == null || !shouldUseEngine(request)) {
289
+ Response response = chain.proceed(request);
290
+ if (request.tag(Download.class) != null) {
291
+ logProtocol("OkHttp", response.protocol().toString(), request.url(), response.code());
292
+ }
293
+ return response;
294
+ }
295
+ try {
296
+ return current.execute(request, chain.connectTimeoutMillis(), chain.readTimeoutMillis(), chain.call());
297
+ } catch (EngineStalledException stall) {
298
+ // No response headers yet, so nothing reached the caller: retry this download on OkHttp right away.
299
+ suspendAfterStall(System.nanoTime());
300
+ Logger logger = DownloadService.logger();
301
+ if (logger != null) {
302
+ logger.warn("HttpEngine stalled, download moved to OkHttp: " + stall.getMessage());
303
+ }
304
+ Response response = chain.proceed(request);
305
+ logProtocol("OkHttp", response.protocol().toString(), request.url(), response.code());
306
+ return response;
307
+ } catch (SocketTimeoutException timeout) {
308
+ // Same recovery for a cold host that never answered, without suspending HTTP/3 for other downloads.
309
+ Logger logger = DownloadService.logger();
310
+ if (logger != null) {
311
+ logger.warn("HttpEngine header timeout, download moved to OkHttp: " + timeout.getMessage());
312
+ }
313
+ Response response = chain.proceed(request);
314
+ logProtocol("OkHttp", response.protocol().toString(), request.url(), response.code());
315
+ return response;
316
+ }
317
+ }
318
+ }
319
+
320
+ /** Maps HttpEngine's ALPN name (h3, h2, http/1.1, quic/1+spdy/3...) to the closest OkHttp protocol. */
321
+ @NonNull
322
+ static Protocol protocolFor(@Nullable String negotiated) {
323
+ if (negotiated == null) {
324
+ return Protocol.HTTP_1_1;
325
+ }
326
+ String value = negotiated.toLowerCase(Locale.ROOT);
327
+ if (value.startsWith("h3") || value.startsWith("quic")) {
328
+ return Protocol.QUIC;
329
+ }
330
+ if (value.equals("h2")) {
331
+ return Protocol.HTTP_2;
332
+ }
333
+ if (value.equals("http/1.0")) {
334
+ return Protocol.HTTP_1_0;
335
+ }
336
+ return Protocol.HTTP_1_1;
337
+ }
338
+
339
+ /**
340
+ * HttpEngine always negotiates gzip/br and hands back the decoded body, but keeps the encoded headers. Drop
341
+ * Content-Encoding and Content-Length then, as OkHttp does after transparent gzip, so callers see an unknown
342
+ * length instead of a wrong one (the checksum still verifies the bytes).
343
+ */
344
+ @NonNull
345
+ static Headers responseHeaders(@NonNull List<Map.Entry<String, String>> fields) {
346
+ boolean decoded = false;
347
+ for (Map.Entry<String, String> field : fields) {
348
+ if (field.getKey() != null && field.getKey().equalsIgnoreCase("Content-Encoding") && isContentCoding(field.getValue())) {
349
+ decoded = true;
350
+ break;
351
+ }
352
+ }
353
+ Headers.Builder headers = new Headers.Builder();
354
+ for (Map.Entry<String, String> field : fields) {
355
+ String name = field.getKey();
356
+ if (name == null || field.getValue() == null) {
357
+ continue;
358
+ }
359
+ if (decoded && (name.equalsIgnoreCase("Content-Encoding") || name.equalsIgnoreCase("Content-Length"))) {
360
+ continue;
361
+ }
362
+ headers.addUnsafeNonAscii(name, field.getValue());
363
+ }
364
+ return headers.build();
365
+ }
366
+
367
+ /** {@code identity} (or an empty value) means no coding was applied, so the Content-Length stays valid. */
368
+ private static boolean isContentCoding(@Nullable String value) {
369
+ if (value == null) {
370
+ return false;
371
+ }
372
+ String coding = value.trim();
373
+ return !coding.isEmpty() && !coding.equalsIgnoreCase("identity");
374
+ }
375
+
376
+ /** Host only, for log and error messages: a signed download URL carries credentials in its query. */
377
+ @NonNull
378
+ static String safeHost(@Nullable String url) {
379
+ HttpUrl parsed = url == null ? null : HttpUrl.parse(url);
380
+ return parsed != null ? parsed.host() : "unknown host";
381
+ }
382
+
383
+ /**
384
+ * Connection identity for warmth tracking: scheme, host and effective port, so a redirect to another port of the
385
+ * same host is judged as a new connection. Logs keep {@link #safeHost(String)}.
386
+ */
387
+ static String connectionKey(@Nullable String url) {
388
+ HttpUrl parsed = url == null ? null : HttpUrl.parse(url);
389
+ return parsed != null ? parsed.scheme() + "://" + parsed.host() + ":" + parsed.port() : "unknown";
390
+ }
391
+
392
+ /** Same policy as the shared client's network interceptor, for redirects the engine follows itself. */
393
+ @Nullable
394
+ static IOException redirectError(@Nullable String from, @Nullable String to) {
395
+ return redirectError(from, to, DownloadService.httpsOnly, DownloadService.isAllowHttpsToHttpRedirect());
396
+ }
397
+
398
+ @Nullable
399
+ static IOException redirectError(@Nullable String from, @Nullable String to, boolean httpsOnly, boolean allowHttpsToHttp) {
400
+ HttpUrl target = to == null ? null : HttpUrl.parse(to);
401
+ if (target == null) {
402
+ return new IOException("Invalid redirect location");
403
+ }
404
+ if (httpsOnly && !target.isHttps()) {
405
+ return new IOException(CapgoUpdater.httpsOnlyMessage(to));
406
+ }
407
+ HttpUrl source = from == null ? null : HttpUrl.parse(from);
408
+ if (source != null && source.isHttps() && !target.isHttps() && !allowHttpsToHttp) {
409
+ return new DownloadService.BlockedRedirectException();
410
+ }
411
+ return null;
412
+ }
413
+
414
+ static void logProtocol(String transportName, @Nullable String protocol, @NonNull HttpUrl url, int code) {
415
+ Logger logger = DownloadService.logger();
416
+ if (logger != null) {
417
+ logger.debug(
418
+ "Download protocol " +
419
+ (protocol == null || protocol.isEmpty() ? "unknown" : protocol) +
420
+ " via " +
421
+ transportName +
422
+ " (HTTP " +
423
+ code +
424
+ ") " +
425
+ url.host() +
426
+ url.encodedPath()
427
+ );
428
+ }
429
+ }
430
+
431
+ private static void debug(@Nullable Logger logger, String message) {
432
+ if (logger != null) {
433
+ logger.debug(message);
434
+ }
435
+ }
436
+ }