@capgo/capacitor-updater 8.53.1 → 8.54.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.
- package/README.md +55 -15
- package/android/build.gradle +1 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +187 -16
- package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +278 -25
- package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +82 -19
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +314 -30
- package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
- package/dist/docs.json +34 -2
- package/dist/esm/definitions.d.ts +46 -2
- package/dist/esm/definitions.js.map +1 -1
- package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +44 -1
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +368 -61
- package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +59 -33
- package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +0 -19
- package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +20 -0
- package/package.json +8 -4
- package/scripts/builtin-hashes-lib.mjs +148 -0
- package/scripts/capacitor-builtin-hashes-hook.mjs +65 -0
- package/scripts/resolve-real-path.mjs +25 -0
|
@@ -19,8 +19,11 @@ import java.nio.channels.FileChannel;
|
|
|
19
19
|
import java.security.MessageDigest;
|
|
20
20
|
import java.util.ArrayList;
|
|
21
21
|
import java.util.Arrays;
|
|
22
|
+
import java.util.HashMap;
|
|
22
23
|
import java.util.HashSet;
|
|
24
|
+
import java.util.Iterator;
|
|
23
25
|
import java.util.List;
|
|
26
|
+
import java.util.Map;
|
|
24
27
|
import java.util.Objects;
|
|
25
28
|
import java.util.Set;
|
|
26
29
|
import java.util.UUID;
|
|
@@ -123,9 +126,10 @@ public class DownloadService extends Worker {
|
|
|
123
126
|
public static final String DEFAULT_CHANNEL = "default_channel";
|
|
124
127
|
public static final String IS_PROD = "is_prod";
|
|
125
128
|
public static final String IS_EMULATOR = "is_emulator";
|
|
126
|
-
//
|
|
129
|
+
// 32 files in flight on every device. Fewer leaves 2-core phones waiting on per-request latency;
|
|
130
|
+
// capping by CPU count (8 on 4 cores) was 2-4x slower on emulators limited to 2, 4 and 8 cores.
|
|
127
131
|
// Keep the global cap at 64 so API calls on another host are not starved by manifest downloads.
|
|
128
|
-
|
|
132
|
+
static final int MANIFEST_MAX_CONCURRENT_FILES = 32;
|
|
129
133
|
private static final int SHARED_MAX_REQUESTS = 64;
|
|
130
134
|
private static final String UPDATE_FILE = "update.dat";
|
|
131
135
|
|
|
@@ -137,6 +141,9 @@ public class DownloadService extends Worker {
|
|
|
137
141
|
private static volatile int httpTimeoutMs = 20_000;
|
|
138
142
|
// Off by default: a redirect must never downgrade updater traffic from HTTPS to plain HTTP.
|
|
139
143
|
private static volatile boolean allowHttpsToHttpRedirect = false;
|
|
144
|
+
// Config httpsOnly (default true): every request and every redirect hop through sharedClient must be https.
|
|
145
|
+
// When true it overrides allowHttpsToHttpRedirect: an https -> http redirect is rejected even if that flag is set.
|
|
146
|
+
static volatile boolean httpsOnly = true;
|
|
140
147
|
private static String currentAppId = "unknown";
|
|
141
148
|
private static String currentPluginVersion = "unknown";
|
|
142
149
|
private static String currentVersionOs = "unknown";
|
|
@@ -157,15 +164,26 @@ public class DownloadService extends Worker {
|
|
|
157
164
|
.writeTimeout(httpTimeoutMs, TimeUnit.MILLISECONDS)
|
|
158
165
|
.addInterceptor((chain) -> {
|
|
159
166
|
Request originalRequest = chain.request();
|
|
167
|
+
// Reject plain http before OkHttp opens a connection (the network interceptor below covers redirect hops).
|
|
168
|
+
assertHttpsAllowed(originalRequest);
|
|
160
169
|
String userAgent = buildUserAgent(currentAppId, currentPluginVersion, currentVersionOs);
|
|
161
170
|
Request requestWithUserAgent = originalRequest.newBuilder().header("User-Agent", userAgent).build();
|
|
162
171
|
return chain.proceed(requestWithUserAgent);
|
|
163
172
|
})
|
|
164
173
|
.addNetworkInterceptor((chain) -> {
|
|
174
|
+
// Network interceptor: runs once per hop, so a redirect to http is rejected here too.
|
|
175
|
+
assertHttpsAllowed(chain.request());
|
|
165
176
|
Response response = chain.proceed(chain.request());
|
|
166
|
-
if (
|
|
167
|
-
|
|
168
|
-
|
|
177
|
+
if (isHttpsToHttpRedirect(response)) {
|
|
178
|
+
if (httpsOnly) {
|
|
179
|
+
String location = response.header("Location");
|
|
180
|
+
response.close();
|
|
181
|
+
throw new IOException(CapgoUpdater.httpsOnlyMessage(location));
|
|
182
|
+
}
|
|
183
|
+
if (!allowHttpsToHttpRedirect) {
|
|
184
|
+
response.close();
|
|
185
|
+
throw new BlockedRedirectException();
|
|
186
|
+
}
|
|
169
187
|
}
|
|
170
188
|
return response;
|
|
171
189
|
})
|
|
@@ -176,6 +194,21 @@ public class DownloadService extends Worker {
|
|
|
176
194
|
allowHttpsToHttpRedirect = allow;
|
|
177
195
|
}
|
|
178
196
|
|
|
197
|
+
static void setHttpsOnly(boolean enabled) {
|
|
198
|
+
httpsOnly = enabled;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** httpsOnly gate shared by both interceptors; throws for any non-https request when enabled. */
|
|
202
|
+
static void assertHttpsAllowed(Request request) throws IOException {
|
|
203
|
+
if (httpsOnly && !request.isHttps()) {
|
|
204
|
+
String message = CapgoUpdater.httpsOnlyMessage(request.url().toString());
|
|
205
|
+
if (logger != null) {
|
|
206
|
+
logger.error(message);
|
|
207
|
+
}
|
|
208
|
+
throw new IOException(message);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
179
212
|
static boolean isHttpsToHttpRedirect(Response response) {
|
|
180
213
|
if (!response.isRedirect() || !response.request().isHttps()) {
|
|
181
214
|
return false;
|
|
@@ -215,12 +248,7 @@ public class DownloadService extends Worker {
|
|
|
215
248
|
}
|
|
216
249
|
|
|
217
250
|
static int manifestMaxConcurrentFiles() {
|
|
218
|
-
return
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
static int manifestMaxConcurrentFiles(int processors) {
|
|
222
|
-
int cores = Math.max(1, processors);
|
|
223
|
-
return Math.min(64, Math.max(8, cores * 2));
|
|
251
|
+
return MANIFEST_MAX_CONCURRENT_FILES;
|
|
224
252
|
}
|
|
225
253
|
|
|
226
254
|
static String buildUserAgent(String appId, String pluginVersion, String versionOs) {
|
|
@@ -262,6 +290,8 @@ public class DownloadService extends Worker {
|
|
|
262
290
|
}
|
|
263
291
|
}
|
|
264
292
|
|
|
293
|
+
private int lastProgressPercent = -1;
|
|
294
|
+
|
|
265
295
|
public DownloadService(@NonNull Context context, @NonNull WorkerParameters params) {
|
|
266
296
|
super(context, params);
|
|
267
297
|
// Use shared client - no need to create new instances
|
|
@@ -271,7 +301,9 @@ public class DownloadService extends Worker {
|
|
|
271
301
|
cleanupOldTempFiles(new File(getApplicationContext().getCacheDir(), "capgo_downloads"));
|
|
272
302
|
}
|
|
273
303
|
|
|
274
|
-
private void setProgress(int percent) {
|
|
304
|
+
private synchronized void setProgress(int percent) {
|
|
305
|
+
if (percent <= lastProgressPercent) return;
|
|
306
|
+
lastProgressPercent = percent;
|
|
275
307
|
Data progress = new Data.Builder().putInt(PERCENT, percent).build();
|
|
276
308
|
setProgressAsync(progress);
|
|
277
309
|
}
|
|
@@ -446,14 +478,170 @@ public class DownloadService extends Worker {
|
|
|
446
478
|
}
|
|
447
479
|
}
|
|
448
480
|
|
|
481
|
+
// Precomputed builtin hashes: `public/ota-builtin-hashes.json` (written by the Capacitor sync hook).
|
|
482
|
+
// Loaded lazily once per process; missing or invalid JSON is cached as an empty map.
|
|
483
|
+
static final String BUILTIN_HASHES_ASSET = "public/ota-builtin-hashes.json";
|
|
484
|
+
private static volatile Map<String, BuiltinHashEntry> builtinHashes;
|
|
485
|
+
private static final Object BUILTIN_HASHES_LOCK = new Object();
|
|
486
|
+
|
|
487
|
+
static final class BuiltinHashEntry {
|
|
488
|
+
|
|
489
|
+
final String hash;
|
|
490
|
+
/** {@code -1} when the manifest entry has no size (legacy string entries). */
|
|
491
|
+
final long size;
|
|
492
|
+
|
|
493
|
+
BuiltinHashEntry(final String hash, final long size) {
|
|
494
|
+
this.hash = hash;
|
|
495
|
+
this.size = size;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
static boolean isSha256Hex(final String value) {
|
|
500
|
+
if (value == null || value.length() != 64) {
|
|
501
|
+
return false;
|
|
502
|
+
}
|
|
503
|
+
for (int i = 0; i < 64; i++) {
|
|
504
|
+
final char c = value.charAt(i);
|
|
505
|
+
if ((c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F')) {
|
|
506
|
+
return false;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
return true;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
static Map<String, BuiltinHashEntry> builtinHashes(final AssetManager assets) {
|
|
513
|
+
Map<String, BuiltinHashEntry> hashes = builtinHashes;
|
|
514
|
+
if (hashes != null) {
|
|
515
|
+
return hashes;
|
|
516
|
+
}
|
|
517
|
+
synchronized (BUILTIN_HASHES_LOCK) {
|
|
518
|
+
if (builtinHashes != null) {
|
|
519
|
+
return builtinHashes;
|
|
520
|
+
}
|
|
521
|
+
final Map<String, BuiltinHashEntry> loaded = new HashMap<>();
|
|
522
|
+
try (InputStream in = assets.open(BUILTIN_HASHES_ASSET)) {
|
|
523
|
+
final ByteArrayOutputStream out = new ByteArrayOutputStream();
|
|
524
|
+
final byte[] buffer = new byte[64 * 1024];
|
|
525
|
+
int length;
|
|
526
|
+
while ((length = in.read(buffer)) != -1) {
|
|
527
|
+
out.write(buffer, 0, length);
|
|
528
|
+
}
|
|
529
|
+
final JSONObject files = new JSONObject(out.toString("UTF-8")).getJSONObject("files");
|
|
530
|
+
final Iterator<String> keys = files.keys();
|
|
531
|
+
while (keys.hasNext()) {
|
|
532
|
+
final String key = keys.next();
|
|
533
|
+
final Object raw = files.opt(key);
|
|
534
|
+
if (raw instanceof String) {
|
|
535
|
+
final String hash = (String) raw;
|
|
536
|
+
if (isSha256Hex(hash)) {
|
|
537
|
+
loaded.put(key, new BuiltinHashEntry(hash, -1L));
|
|
538
|
+
}
|
|
539
|
+
continue;
|
|
540
|
+
}
|
|
541
|
+
if (!(raw instanceof JSONObject)) {
|
|
542
|
+
continue;
|
|
543
|
+
}
|
|
544
|
+
final JSONObject obj = (JSONObject) raw;
|
|
545
|
+
final String hash = obj.optString("sha256", "");
|
|
546
|
+
if (!isSha256Hex(hash)) {
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
final long size;
|
|
550
|
+
if (!obj.has("size") || obj.isNull("size")) {
|
|
551
|
+
size = -1L;
|
|
552
|
+
} else {
|
|
553
|
+
final Object rawSize = obj.get("size");
|
|
554
|
+
if (!(rawSize instanceof Integer || rawSize instanceof Long)) {
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
final long parsedSize = ((Number) rawSize).longValue();
|
|
558
|
+
if (parsedSize < 0) {
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
size = parsedSize;
|
|
562
|
+
}
|
|
563
|
+
loaded.put(key, new BuiltinHashEntry(hash, size));
|
|
564
|
+
}
|
|
565
|
+
} catch (Exception ignored) {
|
|
566
|
+
loaded.clear();
|
|
567
|
+
// No table (older build): every lookup falls back to hashing.
|
|
568
|
+
}
|
|
569
|
+
builtinHashes = loaded;
|
|
570
|
+
return loaded;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
static long builtinAssetLength(final AssetManager assets, final String assetPath) throws IOException {
|
|
575
|
+
try (android.content.res.AssetFileDescriptor afd = assets.openFd(assetPath)) {
|
|
576
|
+
return afd.getLength();
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
static Boolean builtinHashVerdictForEntry(
|
|
581
|
+
final AssetManager assets,
|
|
582
|
+
final String assetPath,
|
|
583
|
+
final BuiltinHashEntry entry,
|
|
584
|
+
final String expectedHash
|
|
585
|
+
) {
|
|
586
|
+
if (entry == null || expectedHash == null) {
|
|
587
|
+
return null;
|
|
588
|
+
}
|
|
589
|
+
if (entry.size >= 0) {
|
|
590
|
+
try {
|
|
591
|
+
if (builtinAssetLength(assets, assetPath) != entry.size) {
|
|
592
|
+
return null;
|
|
593
|
+
}
|
|
594
|
+
} catch (IOException e) {
|
|
595
|
+
return null;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
return entry.hash.equalsIgnoreCase(expectedHash) ? Boolean.TRUE : Boolean.FALSE;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** TRUE/FALSE from the table, or null when the table cannot answer. */
|
|
602
|
+
static Boolean builtinHashVerdict(final AssetManager assets, final String assetPath, final String expectedHash) {
|
|
603
|
+
if (assets == null || assetPath == null || !assetPath.startsWith("public/") || expectedHash == null) {
|
|
604
|
+
return null;
|
|
605
|
+
}
|
|
606
|
+
final BuiltinHashEntry known = builtinHashes(assets).get(assetPath.substring("public/".length()));
|
|
607
|
+
return known == null ? null : builtinHashVerdictForEntry(assets, assetPath, known, expectedHash);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
static boolean copyStreamUnchecked(final InputStream input, final File dest) throws IOException {
|
|
611
|
+
final File parent = dest.getParentFile();
|
|
612
|
+
if (parent == null) {
|
|
613
|
+
throw new IOException("Destination has no parent: " + dest.getAbsolutePath());
|
|
614
|
+
}
|
|
615
|
+
if (!parent.exists() && !parent.mkdirs()) {
|
|
616
|
+
throw new IOException("Failed to create parent directory: " + parent.getAbsolutePath());
|
|
617
|
+
}
|
|
618
|
+
final File tempFile = File.createTempFile("capgo_asset_", ".tmp", parent);
|
|
619
|
+
try {
|
|
620
|
+
try (FileOutputStream outStream = new FileOutputStream(tempFile)) {
|
|
621
|
+
final byte[] buffer = new byte[CryptoCipher.ioBufferBytes()];
|
|
622
|
+
int length;
|
|
623
|
+
while ((length = input.read(buffer)) != -1) {
|
|
624
|
+
outStream.write(buffer, 0, length);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
return replaceFile(tempFile, dest);
|
|
628
|
+
} finally {
|
|
629
|
+
deleteQuietly(tempFile);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
449
633
|
static boolean tryCopyBuiltinAsset(final AssetManager assets, final String fileName, final File dest, final String expectedHash) {
|
|
450
634
|
if (assets == null || fileName == null || dest == null) {
|
|
451
635
|
return false;
|
|
452
636
|
}
|
|
453
637
|
try {
|
|
454
638
|
final String assetPath = resolveBuiltinAssetPath(fileName);
|
|
639
|
+
final Boolean verdict = builtinHashVerdict(assets, assetPath, expectedHash);
|
|
640
|
+
if (Boolean.FALSE.equals(verdict)) {
|
|
641
|
+
return false;
|
|
642
|
+
}
|
|
455
643
|
try (InputStream in = assets.open(assetPath)) {
|
|
456
|
-
return copyStreamIfChecksumMatches(in, dest, expectedHash);
|
|
644
|
+
return verdict != null ? copyStreamUnchecked(in, dest) : copyStreamIfChecksumMatches(in, dest, expectedHash);
|
|
457
645
|
}
|
|
458
646
|
} catch (IOException e) {
|
|
459
647
|
return false;
|
|
@@ -466,7 +654,14 @@ public class DownloadService extends Worker {
|
|
|
466
654
|
}
|
|
467
655
|
try {
|
|
468
656
|
final String assetPath = resolveBuiltinAssetPath(fileName);
|
|
657
|
+
final Boolean verdict = builtinHashVerdict(assets, assetPath, expectedHash);
|
|
658
|
+
if (Boolean.FALSE.equals(verdict)) {
|
|
659
|
+
return false;
|
|
660
|
+
}
|
|
469
661
|
try (InputStream in = assets.open(assetPath)) {
|
|
662
|
+
if (verdict != null) {
|
|
663
|
+
return verdict;
|
|
664
|
+
}
|
|
470
665
|
return expectedHash.equalsIgnoreCase(CryptoCipher.calcChecksum(in));
|
|
471
666
|
}
|
|
472
667
|
} catch (IOException e) {
|
|
@@ -715,6 +910,7 @@ public class DownloadService extends Worker {
|
|
|
715
910
|
}
|
|
716
911
|
}
|
|
717
912
|
|
|
913
|
+
CryptoCipher.DecryptionSession decryptionSession = new CryptoCipher.DecryptionSession(publicKey, sessionKey);
|
|
718
914
|
ExecutorService executor = Executors.newFixedThreadPool(Math.min(MANIFEST_MAX_CONCURRENT_FILES, Math.max(1, totalFiles)));
|
|
719
915
|
List<Future<?>> futures = new ArrayList<>();
|
|
720
916
|
|
|
@@ -736,8 +932,7 @@ public class DownloadService extends Worker {
|
|
|
736
932
|
task.targetFile,
|
|
737
933
|
task.cacheFile,
|
|
738
934
|
task.finalFileHash,
|
|
739
|
-
|
|
740
|
-
publicKey,
|
|
935
|
+
decryptionSession,
|
|
741
936
|
task.isBrotli,
|
|
742
937
|
task.fileName
|
|
743
938
|
);
|
|
@@ -1119,7 +1314,7 @@ public class DownloadService extends Worker {
|
|
|
1119
1314
|
// Hash is in the cache file name and was verified when written.
|
|
1120
1315
|
// Re-hashing here would re-read every reused file on low-RAM devices.
|
|
1121
1316
|
try {
|
|
1122
|
-
|
|
1317
|
+
linkOrCopyImmutableFile(source, dest);
|
|
1123
1318
|
return true;
|
|
1124
1319
|
} catch (IOException e) {
|
|
1125
1320
|
// File was deleted between check and copy, or other IO error - caller should download instead
|
|
@@ -1128,6 +1323,27 @@ public class DownloadService extends Worker {
|
|
|
1128
1323
|
}
|
|
1129
1324
|
}
|
|
1130
1325
|
|
|
1326
|
+
// Only updater-owned verified bundle/cache files, which are never rewritten in place.
|
|
1327
|
+
static void linkOrCopyImmutableFile(File source, File dest) throws IOException {
|
|
1328
|
+
File parent = dest.getParentFile();
|
|
1329
|
+
if (parent != null && !parent.isDirectory() && !parent.mkdirs()) throw new IOException("Cannot create cache directory");
|
|
1330
|
+
File temp = File.createTempFile("capgo-link-", ".tmp", parent);
|
|
1331
|
+
try {
|
|
1332
|
+
if (!temp.delete()) throw new IOException("Cannot prepare cache link");
|
|
1333
|
+
try {
|
|
1334
|
+
android.system.Os.link(source.getCanonicalPath(), temp.getAbsolutePath());
|
|
1335
|
+
} catch (Exception unsupported) {
|
|
1336
|
+
try (FileInputStream input = new FileInputStream(source)) {
|
|
1337
|
+
writeFileAtomic(dest, input, null);
|
|
1338
|
+
}
|
|
1339
|
+
return;
|
|
1340
|
+
}
|
|
1341
|
+
CryptoCipher.replaceFile(temp, dest);
|
|
1342
|
+
} finally {
|
|
1343
|
+
if (temp.exists() && !temp.delete()) temp.deleteOnExit();
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1131
1347
|
private void copyFile(File source, File dest) throws IOException {
|
|
1132
1348
|
copyFileChannel(source, dest);
|
|
1133
1349
|
}
|
|
@@ -1169,8 +1385,46 @@ public class DownloadService extends Worker {
|
|
|
1169
1385
|
File targetFile,
|
|
1170
1386
|
File cacheFile,
|
|
1171
1387
|
String expectedHash,
|
|
1172
|
-
|
|
1173
|
-
|
|
1388
|
+
CryptoCipher.DecryptionSession decryptionSession,
|
|
1389
|
+
boolean isBrotli,
|
|
1390
|
+
String relativeName
|
|
1391
|
+
) throws Exception {
|
|
1392
|
+
for (int attempt = 1; ; attempt++) {
|
|
1393
|
+
if (isStopped()) throw new IOException("download_stopped");
|
|
1394
|
+
try {
|
|
1395
|
+
downloadAndVerifyOnce(downloadUrl, targetFile, cacheFile, expectedHash, decryptionSession, isBrotli, relativeName);
|
|
1396
|
+
return;
|
|
1397
|
+
} catch (Exception error) {
|
|
1398
|
+
if (attempt >= 3 || !isRetryableManifestError(error)) throw error;
|
|
1399
|
+
for (int tick = 0; tick < 5 * attempt; tick++) {
|
|
1400
|
+
if (isStopped()) throw new IOException("download_stopped");
|
|
1401
|
+
Thread.sleep(50);
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
static boolean isRetryableManifestError(Throwable error) {
|
|
1408
|
+
for (Throwable cause = error; cause != null; cause = cause.getCause()) {
|
|
1409
|
+
if (cause instanceof BlockedRedirectException || cause instanceof javax.net.ssl.SSLException) return false;
|
|
1410
|
+
if (
|
|
1411
|
+
cause instanceof DownloadRetryException ||
|
|
1412
|
+
cause instanceof java.net.SocketException ||
|
|
1413
|
+
cause instanceof java.net.SocketTimeoutException ||
|
|
1414
|
+
cause instanceof java.net.UnknownHostException ||
|
|
1415
|
+
cause instanceof java.net.ProtocolException ||
|
|
1416
|
+
cause instanceof java.io.EOFException
|
|
1417
|
+
) return true;
|
|
1418
|
+
}
|
|
1419
|
+
return false;
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
private void downloadAndVerifyOnce(
|
|
1423
|
+
String downloadUrl,
|
|
1424
|
+
File targetFile,
|
|
1425
|
+
File cacheFile,
|
|
1426
|
+
String expectedHash,
|
|
1427
|
+
CryptoCipher.DecryptionSession decryptionSession,
|
|
1174
1428
|
boolean isBrotli,
|
|
1175
1429
|
String relativeName
|
|
1176
1430
|
) throws Exception {
|
|
@@ -1181,9 +1435,11 @@ public class DownloadService extends Worker {
|
|
|
1181
1435
|
if (!cacheFolder.exists() && !cacheFolder.mkdirs()) {
|
|
1182
1436
|
throw new IOException("Failed to create cache directory: " + cacheFolder.getAbsolutePath());
|
|
1183
1437
|
}
|
|
1184
|
-
File partial = manifestPartialFile(cacheFolder, expectedHash, relativeName);
|
|
1438
|
+
File partial = manifestPartialFile(cacheFolder, getInputData().getString(ID), expectedHash, relativeName);
|
|
1185
1439
|
File workFile = null;
|
|
1186
1440
|
boolean keepPartial = partial.isFile();
|
|
1441
|
+
// True while the bytes on disk come from more than one response; a bad result then earns a clean GET.
|
|
1442
|
+
boolean resumed = false;
|
|
1187
1443
|
try {
|
|
1188
1444
|
long existing = partial.isFile() ? partial.length() : 0;
|
|
1189
1445
|
Request.Builder builder = new Request.Builder().url(downloadUrl);
|
|
@@ -1195,16 +1451,32 @@ public class DownloadService extends Worker {
|
|
|
1195
1451
|
if (code == 416 && existing > 0) {
|
|
1196
1452
|
logger.debug("Range not satisfiable, using existing partial " + partial.getName());
|
|
1197
1453
|
keepPartial = true;
|
|
1454
|
+
resumed = true;
|
|
1198
1455
|
} else if (code != HttpURLConnection.HTTP_OK && code != HttpURLConnection.HTTP_PARTIAL) {
|
|
1199
|
-
|
|
1456
|
+
// Reported once after the last attempt by the task catch in handleManifestDownload.
|
|
1457
|
+
if (code != 429 && isRetryableHttpStatus(code)) {
|
|
1458
|
+
throw new DownloadRetryException("Unexpected response code: " + code);
|
|
1459
|
+
}
|
|
1200
1460
|
throw new IOException("Unexpected response code: " + code);
|
|
1201
1461
|
} else {
|
|
1202
1462
|
ResponseBody responseBody = response.body();
|
|
1203
1463
|
if (responseBody == null) {
|
|
1204
1464
|
throw new IOException("Response body is null");
|
|
1205
1465
|
}
|
|
1466
|
+
int writeCode = code;
|
|
1467
|
+
if (code == HttpURLConnection.HTTP_PARTIAL && existing > 0) {
|
|
1468
|
+
long rangeStart = parseContentRangeStart(response.header("Content-Range"));
|
|
1469
|
+
if (rangeStart == 0) {
|
|
1470
|
+
writeCode = HttpURLConnection.HTTP_OK;
|
|
1471
|
+
} else if (rangeStart == existing) {
|
|
1472
|
+
resumed = true;
|
|
1473
|
+
} else {
|
|
1474
|
+
keepPartial = false;
|
|
1475
|
+
throw new DownloadRetryException("invalid_content_range");
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1206
1478
|
try {
|
|
1207
|
-
writeHttpBody(partial, responseBody.byteStream(),
|
|
1479
|
+
writeHttpBody(partial, responseBody.byteStream(), writeCode, existing);
|
|
1208
1480
|
keepPartial = true;
|
|
1209
1481
|
} catch (Exception e) {
|
|
1210
1482
|
keepPartial = true;
|
|
@@ -1213,17 +1485,18 @@ public class DownloadService extends Worker {
|
|
|
1213
1485
|
}
|
|
1214
1486
|
}
|
|
1215
1487
|
|
|
1216
|
-
boolean needDecrypt =
|
|
1488
|
+
boolean needDecrypt = decryptionSession.isEncrypted();
|
|
1217
1489
|
File source = partial;
|
|
1218
1490
|
if (needDecrypt) {
|
|
1219
1491
|
workFile = new File(cacheFolder, "work_" + UUID.randomUUID() + "_" + targetFile.getName() + ".tmp");
|
|
1220
1492
|
copyFile(partial, workFile);
|
|
1221
1493
|
try {
|
|
1222
1494
|
logger.debug("Decrypting file " + targetFile.getName());
|
|
1223
|
-
|
|
1495
|
+
decryptionSession.decryptFile(workFile);
|
|
1224
1496
|
source = workFile;
|
|
1225
1497
|
} catch (Exception e) {
|
|
1226
1498
|
keepPartial = false;
|
|
1499
|
+
if (resumed) throw new DownloadRetryException("resumed_partial_failed_decryption", e);
|
|
1227
1500
|
throw e;
|
|
1228
1501
|
}
|
|
1229
1502
|
}
|
|
@@ -1238,10 +1511,17 @@ public class DownloadService extends Worker {
|
|
|
1238
1511
|
}
|
|
1239
1512
|
} catch (IOException e) {
|
|
1240
1513
|
String msg = e.getMessage();
|
|
1241
|
-
|
|
1514
|
+
boolean checksumFailed = msg != null && msg.contains("Checksum verification failed");
|
|
1515
|
+
boolean brotliFailed = isBrotli && msg != null && msg.toLowerCase(java.util.Locale.US).contains("brotli");
|
|
1516
|
+
// Only bad bytes earn a clean GET; local storage errors stay permanent.
|
|
1517
|
+
if (resumed && (checksumFailed || brotliFailed)) {
|
|
1518
|
+
keepPartial = false;
|
|
1519
|
+
throw new DownloadRetryException("resumed_partial_failed_verification", e);
|
|
1520
|
+
}
|
|
1521
|
+
if (checksumFailed) {
|
|
1242
1522
|
sendStatsAsync("download_manifest_checksum_fail", getInputData().getString(VERSION) + ":" + finalTargetFile.getName());
|
|
1243
1523
|
keepPartial = false;
|
|
1244
|
-
} else if (
|
|
1524
|
+
} else if (brotliFailed) {
|
|
1245
1525
|
sendStatsAsync("download_manifest_brotli_fail", getInputData().getString(VERSION) + ":" + finalTargetFile.getName());
|
|
1246
1526
|
keepPartial = false;
|
|
1247
1527
|
}
|
|
@@ -1252,8 +1532,10 @@ public class DownloadService extends Worker {
|
|
|
1252
1532
|
CryptoCipher.logChecksumInfo("Expected checksum", expectedHash);
|
|
1253
1533
|
|
|
1254
1534
|
if (cacheFile != null) {
|
|
1255
|
-
try
|
|
1256
|
-
|
|
1535
|
+
try {
|
|
1536
|
+
linkOrCopyImmutableFile(finalTargetFile, cacheFile);
|
|
1537
|
+
} catch (IOException error) {
|
|
1538
|
+
logger.debug("Delta cache write failed: " + error.getMessage());
|
|
1257
1539
|
}
|
|
1258
1540
|
}
|
|
1259
1541
|
keepPartial = false;
|
|
@@ -1273,13 +1555,15 @@ public class DownloadService extends Worker {
|
|
|
1273
1555
|
return CryptoCipher.shortPathKey(fileName);
|
|
1274
1556
|
}
|
|
1275
1557
|
|
|
1276
|
-
|
|
1558
|
+
// Scoped to one download so concurrent downloads of the same file never write one partial.
|
|
1559
|
+
static File manifestPartialFile(File cacheDir, String downloadId, String hash, String fileName) {
|
|
1560
|
+
String owner = CryptoCipher.shortPathKey(downloadId == null ? "" : downloadId);
|
|
1277
1561
|
String token = safePartialToken(fileName);
|
|
1278
1562
|
if (CapgoUpdater.isSafeCacheHash(hash) && hash.length() == 64) {
|
|
1279
|
-
return new File(cacheDir, "partial_" + hash + "_" + token + ".tmp");
|
|
1563
|
+
return new File(cacheDir, "partial_" + owner + "_" + hash + "_" + token + ".tmp");
|
|
1280
1564
|
}
|
|
1281
1565
|
String digest = CryptoCipher.shortPathKey((hash == null ? "" : hash) + "\0" + (fileName == null ? "" : fileName));
|
|
1282
|
-
return new File(cacheDir, "partial_" + digest + "_" + token + ".tmp");
|
|
1566
|
+
return new File(cacheDir, "partial_" + owner + "_" + digest + "_" + token + ".tmp");
|
|
1283
1567
|
}
|
|
1284
1568
|
|
|
1285
1569
|
static boolean shouldAppendHttpBody(int statusCode, long existingBytes) {
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
package ee.forgr.capacitor_updater;
|
|
2
|
+
|
|
3
|
+
import androidx.annotation.NonNull;
|
|
4
|
+
import okhttp3.HttpUrl;
|
|
5
|
+
|
|
6
|
+
final class StatsBatchFailureDiagnostics {
|
|
7
|
+
|
|
8
|
+
static final String STATUS_UNAVAILABLE = "unavailable";
|
|
9
|
+
|
|
10
|
+
private StatsBatchFailureDiagnostics() {}
|
|
11
|
+
|
|
12
|
+
@NonNull
|
|
13
|
+
private static String hostForOrigin(@NonNull final String host) {
|
|
14
|
+
if (host.indexOf(':') >= 0) {
|
|
15
|
+
return "[" + host + "]";
|
|
16
|
+
}
|
|
17
|
+
return host;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
@NonNull
|
|
21
|
+
static String safeDestinationUrl(@NonNull HttpUrl url) {
|
|
22
|
+
final String scheme = url.scheme();
|
|
23
|
+
final int port = url.port();
|
|
24
|
+
final String host = hostForOrigin(url.host());
|
|
25
|
+
if (port == HttpUrl.defaultPort(scheme)) {
|
|
26
|
+
return scheme + "://" + host;
|
|
27
|
+
}
|
|
28
|
+
return scheme + "://" + host + ":" + port;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
@NonNull
|
|
32
|
+
static String formatFailureMessage(
|
|
33
|
+
@NonNull final String messagePrefix,
|
|
34
|
+
@NonNull final String safeDestination,
|
|
35
|
+
@NonNull final String status,
|
|
36
|
+
final long elapsedMs
|
|
37
|
+
) {
|
|
38
|
+
return messagePrefix + " destination=" + safeDestination + " status=" + status + " elapsedMs=" + elapsedMs;
|
|
39
|
+
}
|
|
40
|
+
}
|
package/dist/docs.json
CHANGED
|
@@ -4934,7 +4934,7 @@
|
|
|
4934
4934
|
"name": "since"
|
|
4935
4935
|
}
|
|
4936
4936
|
],
|
|
4937
|
-
"docs": "Configure the public key for end to end live update encryption Version 2\n\nOnly available for Android and iOS.",
|
|
4937
|
+
"docs": "Configure the public key for end to end live update encryption Version 2.\n\nWhat it guarantees: a bundle can only be installed when its checksum and session key were produced with\nthe matching private key. Capgo never holds that key, so Capgo cannot create, modify or decrypt an update\nfor your app. It does NOT make the bundle unreadable to someone who has your app binary: the public key\nships inside the app, and anyone holding the app can recover the session key and read the bundle. If you\nalso need Capgo to be unable to find your app (and so its public key), use a Capgo app id that is not your\nstore bundle id (`appId` in this plugin config) so the app is not identifiable from the dashboard.\n\nOnly available for Android and iOS.",
|
|
4938
4938
|
"complexTypes": [],
|
|
4939
4939
|
"type": "string | undefined"
|
|
4940
4940
|
},
|
|
@@ -5182,7 +5182,39 @@
|
|
|
5182
5182
|
"name": "since"
|
|
5183
5183
|
}
|
|
5184
5184
|
],
|
|
5185
|
-
"docs": "Allow the plugin to follow redirects from HTTPS to plain HTTP for its own network requests\n(update checks, stats, channel calls, and bundle/manifest downloads).\n\nBlocked by default so a redirect can never downgrade updater traffic to an unencrypted connection.\nOnly enable this if your self-hosted update server or CDN must redirect to an HTTP URL.\
|
|
5185
|
+
"docs": "Allow the plugin to follow redirects from HTTPS to plain HTTP for its own network requests\n(update checks, stats, channel calls, and bundle/manifest downloads).\n\nBlocked by default so a redirect can never downgrade updater traffic to an unencrypted connection.\nOnly enable this if your self-hosted update server or CDN must redirect to an HTTP URL.\n`httpsOnly` (default `true`) rejects every non-https URL and redirect hop regardless of this setting, so an\nHTTP redirect also needs `httpsOnly: false`. Direct HTTP URLs (for example `localApi` during development) are\nonly allowed with `httpsOnly: false` as well.\n\nOnly available for Android and iOS.",
|
|
5186
|
+
"complexTypes": [],
|
|
5187
|
+
"type": "boolean | undefined"
|
|
5188
|
+
},
|
|
5189
|
+
{
|
|
5190
|
+
"name": "httpsOnly",
|
|
5191
|
+
"tags": [
|
|
5192
|
+
{
|
|
5193
|
+
"text": "true",
|
|
5194
|
+
"name": "default"
|
|
5195
|
+
},
|
|
5196
|
+
{
|
|
5197
|
+
"text": "8.54.0",
|
|
5198
|
+
"name": "since"
|
|
5199
|
+
}
|
|
5200
|
+
],
|
|
5201
|
+
"docs": "Require https for every URL the plugin talks to: `updateUrl`, `statsUrl`, `channelUrl` (from config,\npersisted values and `setUpdateUrl` / `setStatsUrl` / `setChannelUrl`), bundle zip URLs, every manifest\n`download_url`, preview payload URLs and every redirect hop. When enabled it overrides\n`allowHttpsToHttpRedirect`. A non-https URL fails the call or download with\n`httpsOnly is enabled and <url> is not https`.\n\nSet to `false` only for local development servers (for example a plain-http `localApi` on loopback) or a\nself-hosted plain-http update server you control. Upgrading with a plain-http `updateUrl`, `statsUrl`,\n`channelUrl` or `allowHttpsToHttpRedirect: true` requires setting this to `false` explicitly.\n\nOnly available for Android and iOS.",
|
|
5202
|
+
"complexTypes": [],
|
|
5203
|
+
"type": "boolean | undefined"
|
|
5204
|
+
},
|
|
5205
|
+
{
|
|
5206
|
+
"name": "builtinMinimum",
|
|
5207
|
+
"tags": [
|
|
5208
|
+
{
|
|
5209
|
+
"text": "false",
|
|
5210
|
+
"name": "default"
|
|
5211
|
+
},
|
|
5212
|
+
{
|
|
5213
|
+
"text": "8.54.0",
|
|
5214
|
+
"name": "since"
|
|
5215
|
+
}
|
|
5216
|
+
],
|
|
5217
|
+
"docs": "Refuse to download or install a bundle whose version is lower than the native app version\n(`version` config override, else `CFBundleShortVersionString` / `versionName`). This is the on-device\ncounterpart of the Capgo channel setting \"disable auto update under native\" and protects against a\nreplayed old update response rolling the app back below its store version. Only the numeric\n`major.minor.patch` part is compared (a `1.2.3-beta.1` bundle is accepted on native `1.2.3`), and\nversions that do not parse as semver skip the check. Rejections are reported as the\n`version_below_native` stat. Keep it off if you version web bundles independently of the native app\n(for example native `2.0.0` with bundle `1.4.7`).\n\nFuture-major default candidate: `true`.\n\nOnly available for Android and iOS.",
|
|
5186
5218
|
"complexTypes": [],
|
|
5187
5219
|
"type": "boolean | undefined"
|
|
5188
5220
|
},
|