@capgo/capacitor-updater 8.54.2 → 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.
- package/CapgoCapacitorUpdater.podspec +2 -2
- package/Package.swift +3 -4
- package/README.md +162 -417
- package/android/build.gradle +7 -7
- package/android/consumer-rules.pro +48 -0
- package/android/proguard-rules.pro +1 -23
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +1420 -404
- package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +1100 -308
- package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +102 -65
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +155 -18
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +22 -2
- package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +82 -21
- package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -0
- package/dist/docs.json +44 -566
- package/dist/esm/definitions.d.ts +97 -215
- package/dist/esm/definitions.js.map +1 -1
- package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +197 -84
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +402 -139
- package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +81 -55
- package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +24 -0
- package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +2 -1
- package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +3905 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1095 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +192 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
- package/package.json +15 -13
|
@@ -143,12 +143,43 @@ public class CryptoCipher {
|
|
|
143
143
|
return sessionKeyParts.length == 2 && !sessionKeyParts[0].isEmpty() && !sessionKeyParts[1].isEmpty();
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
-
|
|
146
|
+
/**
|
|
147
|
+
* Decrypts {@code file} in place. {@code expectedCiphertextSha256} is the SHA-256 of the encrypted bytes taken from
|
|
148
|
+
* the signed checksum ({@link BundleChecksum#ciphertext}): the file is hashed and rejected before any AES work when
|
|
149
|
+
* it does not match, so tampered ciphertext never reaches the cipher.
|
|
150
|
+
*/
|
|
151
|
+
public static void decryptFile(
|
|
152
|
+
final File file,
|
|
153
|
+
final String publicKey,
|
|
154
|
+
final String ivSessionKey,
|
|
155
|
+
final String expectedCiphertextSha256
|
|
156
|
+
) throws IOException {
|
|
147
157
|
if (publicKey.isEmpty() || !isValidSessionKey(ivSessionKey)) {
|
|
148
158
|
if (logger != null) logger.info("Encryption not set, no public key or session, ignored");
|
|
149
159
|
return;
|
|
150
160
|
}
|
|
151
|
-
new DecryptionSession(publicKey, ivSessionKey).decryptFile(file);
|
|
161
|
+
new DecryptionSession(publicKey, ivSessionKey).decryptFile(file, expectedCiphertextSha256);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
static final String CIPHERTEXT_CHECKSUM_MISMATCH = "Checksum verification failed: encrypted bytes do not match the signed checksum";
|
|
165
|
+
|
|
166
|
+
/** Rejects {@code file} unless its SHA-256 equals the signed ciphertext checksum. Runs before decryption. */
|
|
167
|
+
static void verifyCiphertextChecksum(final File file, final String expectedCiphertextSha256) throws IOException {
|
|
168
|
+
if (!isSha256Hex(expectedCiphertextSha256)) {
|
|
169
|
+
throw new IOException("Encrypted bundle has no signed ciphertext checksum. Re-upload the bundle with a current Capgo CLI.");
|
|
170
|
+
}
|
|
171
|
+
final String actual = calcChecksumOrThrow(file);
|
|
172
|
+
if (!expectedCiphertextSha256.equalsIgnoreCase(actual)) {
|
|
173
|
+
if (logger != null) {
|
|
174
|
+
logger.error("Encrypted file checksum mismatch, refusing to decrypt");
|
|
175
|
+
logger.debug("Expected: " + expectedCiphertextSha256 + ", Got: " + actual);
|
|
176
|
+
}
|
|
177
|
+
throw new IOException(CIPHERTEXT_CHECKSUM_MISMATCH);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
static boolean isSha256Hex(final String value) {
|
|
182
|
+
return value != null && value.length() == 64 && value.matches("^[0-9a-fA-F]+$");
|
|
152
183
|
}
|
|
153
184
|
|
|
154
185
|
// A manifest shares key setup, while each file still creates its own CBC cipher.
|
|
@@ -185,11 +216,13 @@ public class CryptoCipher {
|
|
|
185
216
|
return publicKey != null && !publicKey.isEmpty();
|
|
186
217
|
}
|
|
187
218
|
|
|
188
|
-
void decryptFile(File file) throws IOException {
|
|
219
|
+
void decryptFile(File file, String expectedCiphertextSha256) throws IOException {
|
|
189
220
|
if (!isEncrypted()) {
|
|
190
221
|
if (logger != null) logger.info("Encryption not set, no public key or session, ignored");
|
|
191
222
|
return;
|
|
192
223
|
}
|
|
224
|
+
// Authenticate the encrypted bytes first: CBC padding is only ever checked on signed ciphertext.
|
|
225
|
+
verifyCiphertextChecksum(file, expectedCiphertextSha256);
|
|
193
226
|
PreparedKey key = key();
|
|
194
227
|
decryptAesFile(file, key.key, key.iv);
|
|
195
228
|
}
|
|
@@ -311,36 +344,44 @@ public class CryptoCipher {
|
|
|
311
344
|
return data;
|
|
312
345
|
}
|
|
313
346
|
|
|
314
|
-
|
|
347
|
+
/** Plaintext and ciphertext SHA-256 digests recovered from a signed bundle checksum, as lowercase hex. */
|
|
348
|
+
public static final class BundleChecksum {
|
|
349
|
+
|
|
350
|
+
/** SHA-256 of the decrypted bundle or file, the value compared after decryption. */
|
|
351
|
+
public final String plain;
|
|
352
|
+
/** SHA-256 of the encrypted bytes as served, checked before decryption. {@code null} without a public key. */
|
|
353
|
+
public final String ciphertext;
|
|
354
|
+
|
|
355
|
+
BundleChecksum(final String plain, final String ciphertext) {
|
|
356
|
+
this.plain = plain;
|
|
357
|
+
this.ciphertext = ciphertext;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** Size of the signed checksum payload: SHA-256 of the plaintext followed by SHA-256 of the ciphertext. */
|
|
362
|
+
static final int SIGNED_CHECKSUM_PAYLOAD_BYTES = 64;
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Decrypts the RSA encrypted bundle checksum. Since 9.0.0 the signed payload is 64 bytes: the SHA-256 of the
|
|
366
|
+
* plaintext followed by the SHA-256 of the encrypted bytes (Capgo CLI "V4" checksum). Returns {@code checksum}
|
|
367
|
+
* as the plain digest when no public key is configured. Throws for anything that is not an even-length hex
|
|
368
|
+
* string of 256 bytes signed with the matching private key, and for the 32-byte payload of older CLIs.
|
|
369
|
+
*/
|
|
370
|
+
public static BundleChecksum decryptBundleChecksum(String checksum, String publicKey) throws IOException {
|
|
315
371
|
if (publicKey.isEmpty()) {
|
|
316
372
|
logger.error("No encryption set (public key) ignored");
|
|
317
|
-
return checksum;
|
|
373
|
+
return new BundleChecksum(checksum, null);
|
|
318
374
|
}
|
|
319
375
|
try {
|
|
320
|
-
//
|
|
321
|
-
//
|
|
322
|
-
//
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
// Hex encoded (new format from CLI for plugin versions >= 5.30.0, 6.30.0, 7.30.0)
|
|
327
|
-
checksumBytes = hexStringToByteArray(checksum);
|
|
328
|
-
detectedFormat = "hex";
|
|
329
|
-
} else {
|
|
330
|
-
// TODO: remove backwards compatibility
|
|
331
|
-
// Base64 encoded (old format for backwards compatibility)
|
|
332
|
-
checksumBytes = Base64.decode(checksum, Base64.DEFAULT);
|
|
333
|
-
detectedFormat = "base64";
|
|
376
|
+
// The encrypted checksum is hex encoded. The base64 format of CLI uploads made for plugin
|
|
377
|
+
// versions older than 5.30.0 / 6.30.0 / 7.30.0 is no longer accepted since 9.0.0.
|
|
378
|
+
// An odd length is rejected too: hexStringToByteArray would read past the last digit.
|
|
379
|
+
if (checksum.length() % 2 != 0 || !checksum.matches("^[0-9a-fA-F]+$")) {
|
|
380
|
+
logger.error("Cannot decode checksum as hex. Re-upload the bundle with a current Capgo CLI.");
|
|
381
|
+
throw new IOException("Bundle checksum is not hex encoded. Re-upload the bundle with a current Capgo CLI.");
|
|
334
382
|
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
detectedFormat +
|
|
338
|
-
" (length: " +
|
|
339
|
-
checksum.length() +
|
|
340
|
-
" chars, " +
|
|
341
|
-
checksumBytes.length +
|
|
342
|
-
" bytes)"
|
|
343
|
-
);
|
|
383
|
+
final byte[] checksumBytes = hexStringToByteArray(checksum);
|
|
384
|
+
logger.debug("Received checksum format: hex (length: " + checksum.length() + " chars, " + checksumBytes.length + " bytes)");
|
|
344
385
|
|
|
345
386
|
// RSA-2048 encrypted data must be exactly 256 bytes
|
|
346
387
|
// If the checksum is not 256 bytes, the bundle was not encrypted properly
|
|
@@ -355,36 +396,19 @@ public class CryptoCipher {
|
|
|
355
396
|
|
|
356
397
|
PublicKey pKey = CryptoCipher.stringToPublicKey(publicKey);
|
|
357
398
|
byte[] decryptedChecksum = CryptoCipher.decryptRSA(checksumBytes, pKey);
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
// Detect checksum algorithm based on length
|
|
368
|
-
String detectedAlgorithm;
|
|
369
|
-
if (decryptedChecksum.length == 32) {
|
|
370
|
-
detectedAlgorithm = "SHA-256";
|
|
371
|
-
} else if (decryptedChecksum.length == 4) {
|
|
372
|
-
detectedAlgorithm = "CRC32 (deprecated)";
|
|
373
|
-
logger.error("CRC32 checksum detected - deprecated algorithm");
|
|
374
|
-
} else {
|
|
375
|
-
detectedAlgorithm = "unknown (" + decryptedChecksum.length + " bytes)";
|
|
376
|
-
logger.error("Unknown checksum algorithm detected");
|
|
377
|
-
logger.debug("Byte count: " + decryptedChecksum.length + ", Expected: 32 (SHA-256)");
|
|
399
|
+
if (decryptedChecksum == null || decryptedChecksum.length != SIGNED_CHECKSUM_PAYLOAD_BYTES) {
|
|
400
|
+
int size = decryptedChecksum == null ? 0 : decryptedChecksum.length;
|
|
401
|
+
logger.error("Signed checksum has no ciphertext digest. Re-upload the bundle with a Capgo CLI that supports updater 9.");
|
|
402
|
+
logger.debug("Decrypted checksum bytes: " + size + ", expected: " + SIGNED_CHECKSUM_PAYLOAD_BYTES);
|
|
403
|
+
throw new IOException(
|
|
404
|
+
"Bundle checksum has no signed ciphertext digest (" +
|
|
405
|
+
size +
|
|
406
|
+
" bytes). Re-upload the bundle with a Capgo CLI that supports updater 9."
|
|
407
|
+
);
|
|
378
408
|
}
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
" hex format (length: " +
|
|
383
|
-
result.length() +
|
|
384
|
-
" chars, " +
|
|
385
|
-
decryptedChecksum.length +
|
|
386
|
-
" bytes)"
|
|
387
|
-
);
|
|
409
|
+
final String hex = bytesToHex(decryptedChecksum);
|
|
410
|
+
final BundleChecksum result = new BundleChecksum(hex.substring(0, 64), hex.substring(64));
|
|
411
|
+
logger.debug("Decrypted checksum: SHA-256 of plaintext and ciphertext (64 bytes)");
|
|
388
412
|
return result;
|
|
389
413
|
} catch (GeneralSecurityException e) {
|
|
390
414
|
logger.error("Checksum decryption failed");
|
|
@@ -393,10 +417,27 @@ public class CryptoCipher {
|
|
|
393
417
|
}
|
|
394
418
|
}
|
|
395
419
|
|
|
420
|
+
/**
|
|
421
|
+
* Returns the SHA-256 of the plaintext from the signed bundle checksum, or {@code checksum} unchanged when no
|
|
422
|
+
* public key is configured. See {@link #decryptBundleChecksum(String, String)}.
|
|
423
|
+
*/
|
|
424
|
+
public static String decryptChecksum(String checksum, String publicKey) throws IOException {
|
|
425
|
+
return decryptBundleChecksum(checksum, publicKey).plain;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
private static String bytesToHex(final byte[] bytes) {
|
|
429
|
+
StringBuilder hexString = new StringBuilder(bytes.length * 2);
|
|
430
|
+
for (byte b : bytes) {
|
|
431
|
+
String hex = Integer.toHexString(0xff & b);
|
|
432
|
+
if (hex.length() == 1) hexString.append('0');
|
|
433
|
+
hexString.append(hex);
|
|
434
|
+
}
|
|
435
|
+
return hexString.toString();
|
|
436
|
+
}
|
|
437
|
+
|
|
396
438
|
/**
|
|
397
439
|
* Detect checksum algorithm based on hex string length.
|
|
398
|
-
* SHA-256 = 64 hex chars (32 bytes)
|
|
399
|
-
* CRC32 = 8 hex chars (4 bytes)
|
|
440
|
+
* SHA-256 = 64 hex chars (32 bytes). It is the only supported algorithm.
|
|
400
441
|
*/
|
|
401
442
|
public static String detectChecksumAlgorithm(String hexChecksum) {
|
|
402
443
|
if (hexChecksum == null || hexChecksum.isEmpty()) {
|
|
@@ -405,22 +446,18 @@ public class CryptoCipher {
|
|
|
405
446
|
int len = hexChecksum.length();
|
|
406
447
|
if (len == 64) {
|
|
407
448
|
return "SHA-256";
|
|
408
|
-
} else if (len == 8) {
|
|
409
|
-
return "CRC32 (deprecated)";
|
|
410
449
|
} else {
|
|
411
450
|
return "unknown (" + len + " hex chars)";
|
|
412
451
|
}
|
|
413
452
|
}
|
|
414
453
|
|
|
415
454
|
/**
|
|
416
|
-
* Log checksum info and warn if
|
|
455
|
+
* Log checksum info and warn if the checksum is not SHA-256.
|
|
417
456
|
*/
|
|
418
457
|
public static void logChecksumInfo(String label, String hexChecksum) {
|
|
419
458
|
String algorithm = detectChecksumAlgorithm(hexChecksum);
|
|
420
459
|
logger.debug(label + ": " + algorithm + " hex format (length: " + hexChecksum.length() + " chars)");
|
|
421
|
-
if (algorithm.contains("
|
|
422
|
-
logger.error("CRC32 checksum detected - deprecated algorithm");
|
|
423
|
-
} else if (algorithm.contains("unknown")) {
|
|
460
|
+
if (algorithm.contains("unknown")) {
|
|
424
461
|
logger.error("Unknown checksum algorithm detected");
|
|
425
462
|
logger.debug("Char count: " + hexChecksum.length() + ", Expected: 64 (SHA-256)");
|
|
426
463
|
}
|
|
@@ -97,10 +97,33 @@ public class DownloadService extends Worker {
|
|
|
97
97
|
}
|
|
98
98
|
}
|
|
99
99
|
|
|
100
|
-
private static Logger logger;
|
|
100
|
+
private static volatile Logger logger;
|
|
101
|
+
private static final Object LOGGER_LOCK = new Object();
|
|
102
|
+
|
|
103
|
+
@androidx.annotation.Nullable
|
|
104
|
+
static Logger logger() {
|
|
105
|
+
return logger;
|
|
106
|
+
}
|
|
101
107
|
|
|
102
108
|
public static void setLogger(Logger loggerInstance) {
|
|
103
|
-
|
|
109
|
+
synchronized (LOGGER_LOCK) {
|
|
110
|
+
logger = loggerInstance;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
public static void setLoggerIfAbsent(Logger loggerInstance) {
|
|
115
|
+
if (loggerInstance == null) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
synchronized (LOGGER_LOCK) {
|
|
119
|
+
if (logger == null) {
|
|
120
|
+
logger = loggerInstance;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
public static Logger getLogger() {
|
|
126
|
+
return logger;
|
|
104
127
|
}
|
|
105
128
|
|
|
106
129
|
public static final String URL = "URL";
|
|
@@ -126,6 +149,7 @@ public class DownloadService extends Worker {
|
|
|
126
149
|
public static final String DEFAULT_CHANNEL = "default_channel";
|
|
127
150
|
public static final String IS_PROD = "is_prod";
|
|
128
151
|
public static final String IS_EMULATOR = "is_emulator";
|
|
152
|
+
public static final String HTTP3 = "http3";
|
|
129
153
|
// 32 files in flight on every device. Fewer leaves 2-core phones waiting on per-request latency;
|
|
130
154
|
// capping by CPU count (8 on 4 cores) was 2-4x slower on emulators limited to 2, 4 and 8 cores.
|
|
131
155
|
// Keep the global cap at 64 so API calls on another host are not starved by manifest downloads.
|
|
@@ -170,6 +194,8 @@ public class DownloadService extends Worker {
|
|
|
170
194
|
Request requestWithUserAgent = originalRequest.newBuilder().header("User-Agent", userAgent).build();
|
|
171
195
|
return chain.proceed(requestWithUserAgent);
|
|
172
196
|
})
|
|
197
|
+
// Last application interceptor: tagged https downloads go over HttpEngine (HTTP/3) when available.
|
|
198
|
+
.addInterceptor(new Http3.EngineInterceptor())
|
|
173
199
|
.addNetworkInterceptor((chain) -> {
|
|
174
200
|
// Network interceptor: runs once per hop, so a redirect to http is rejected here too.
|
|
175
201
|
assertHttpsAllowed(chain.request());
|
|
@@ -194,6 +220,10 @@ public class DownloadService extends Worker {
|
|
|
194
220
|
allowHttpsToHttpRedirect = allow;
|
|
195
221
|
}
|
|
196
222
|
|
|
223
|
+
static boolean isAllowHttpsToHttpRedirect() {
|
|
224
|
+
return allowHttpsToHttpRedirect;
|
|
225
|
+
}
|
|
226
|
+
|
|
197
227
|
static void setHttpsOnly(boolean enabled) {
|
|
198
228
|
httpsOnly = enabled;
|
|
199
229
|
}
|
|
@@ -450,6 +480,8 @@ public class DownloadService extends Worker {
|
|
|
450
480
|
|
|
451
481
|
final String fileName;
|
|
452
482
|
final String finalFileHash;
|
|
483
|
+
/** SHA-256 of the encrypted bytes from the signed file_hash; {@code null} for unencrypted manifests. */
|
|
484
|
+
final String ciphertextHash;
|
|
453
485
|
final String downloadUrl;
|
|
454
486
|
final boolean isBrotli;
|
|
455
487
|
final File targetFile;
|
|
@@ -460,6 +492,7 @@ public class DownloadService extends Worker {
|
|
|
460
492
|
ManifestDownloadTask(
|
|
461
493
|
final String fileName,
|
|
462
494
|
final String finalFileHash,
|
|
495
|
+
final String ciphertextHash,
|
|
463
496
|
final String downloadUrl,
|
|
464
497
|
final boolean isBrotli,
|
|
465
498
|
final File targetFile,
|
|
@@ -469,6 +502,7 @@ public class DownloadService extends Worker {
|
|
|
469
502
|
) {
|
|
470
503
|
this.fileName = fileName;
|
|
471
504
|
this.finalFileHash = finalFileHash;
|
|
505
|
+
this.ciphertextHash = ciphertextHash;
|
|
472
506
|
this.downloadUrl = downloadUrl;
|
|
473
507
|
this.isBrotli = isBrotli;
|
|
474
508
|
this.targetFile = targetFile;
|
|
@@ -692,10 +726,20 @@ public class DownloadService extends Worker {
|
|
|
692
726
|
@NonNull
|
|
693
727
|
@Override
|
|
694
728
|
public Result doWork() {
|
|
729
|
+
if (logger == null) {
|
|
730
|
+
setLoggerIfAbsent(new Logger("CapgoUpdater", new Logger.Options(true)));
|
|
731
|
+
}
|
|
695
732
|
final String documentsDir = getInputData().getString(DOCDIR);
|
|
696
733
|
final String dest = getInputData().getString(FILEDEST);
|
|
697
734
|
final String version = getInputData().getString(VERSION);
|
|
698
735
|
final boolean isManifest = getInputData().getBoolean(IS_MANIFEST, false);
|
|
736
|
+
// Every bundle download runs here, possibly in a fresh process where no config was loaded yet:
|
|
737
|
+
// fall back to the http3 option saved with the job (absent on older jobs, keep the default), then
|
|
738
|
+
// build the shared HttpEngine once. A config already loaded in this process always wins.
|
|
739
|
+
if (getInputData().hasKeyWithValueOfType(HTTP3, Boolean.class)) {
|
|
740
|
+
Http3.restoreSavedOption(getInputData().getBoolean(HTTP3, true));
|
|
741
|
+
}
|
|
742
|
+
Http3.init(getApplicationContext(), logger);
|
|
699
743
|
try {
|
|
700
744
|
String url = getInputData().getString(URL);
|
|
701
745
|
String id = getInputData().getString(ID);
|
|
@@ -703,7 +747,9 @@ public class DownloadService extends Worker {
|
|
|
703
747
|
String checksum = getInputData().getString(CHECKSUM);
|
|
704
748
|
String publicKey = getInputData().getString(PUBLIC_KEY);
|
|
705
749
|
|
|
706
|
-
logger
|
|
750
|
+
if (logger != null) {
|
|
751
|
+
logger.debug("doWork isManifest: " + isManifest);
|
|
752
|
+
}
|
|
707
753
|
|
|
708
754
|
if (isManifest) {
|
|
709
755
|
JSONArray manifest = DataManager.getInstance().getAndClearManifest(id);
|
|
@@ -714,7 +760,9 @@ public class DownloadService extends Worker {
|
|
|
714
760
|
CapgoUpdater.deleteManifestStagingFolderAt(documentsDir != null ? new File(documentsDir) : null, dest, logger);
|
|
715
761
|
return createFailureResult("download_cancelled", version, dest, true);
|
|
716
762
|
} else {
|
|
717
|
-
logger
|
|
763
|
+
if (logger != null) {
|
|
764
|
+
logger.error("Manifest is null");
|
|
765
|
+
}
|
|
718
766
|
CapgoUpdater.deleteManifestStagingFolderAt(documentsDir != null ? new File(documentsDir) : null, dest, logger);
|
|
719
767
|
return createFailureResult("Manifest is null", version, dest, true);
|
|
720
768
|
}
|
|
@@ -746,6 +794,10 @@ public class DownloadService extends Worker {
|
|
|
746
794
|
}
|
|
747
795
|
|
|
748
796
|
private void sendStatsAsync(String action, String version) {
|
|
797
|
+
sendStatsAsync(action, version, null);
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
private void sendStatsAsync(String action, String version, Map<String, String> metadata) {
|
|
749
801
|
try {
|
|
750
802
|
String statsUrl = getInputData().getString(STATS_URL);
|
|
751
803
|
if (statsUrl == null || statsUrl.isEmpty()) {
|
|
@@ -760,6 +812,7 @@ public class DownloadService extends Worker {
|
|
|
760
812
|
json.put("version_name", version != null ? version : "");
|
|
761
813
|
json.put("old_version_name", "");
|
|
762
814
|
json.put("action", action);
|
|
815
|
+
if (metadata != null) json.put("metadata", new JSONObject(metadata));
|
|
763
816
|
json.put("device_id", getInputString(DEVICE_ID, ""));
|
|
764
817
|
json.put("custom_id", getInputString(CUSTOM_ID, ""));
|
|
765
818
|
json.put("version_build", getInputString(VERSION_BUILD, ""));
|
|
@@ -810,6 +863,11 @@ public class DownloadService extends Worker {
|
|
|
810
863
|
String publicKey,
|
|
811
864
|
JSONArray manifest
|
|
812
865
|
) {
|
|
866
|
+
final long started = android.os.SystemClock.elapsedRealtime();
|
|
867
|
+
final AtomicLong completedFiles = new AtomicLong(0);
|
|
868
|
+
final AtomicLong failedFiles = new AtomicLong(0);
|
|
869
|
+
final Map<String, String> summary = new HashMap<>();
|
|
870
|
+
summary.put("attempt_id", id);
|
|
813
871
|
try {
|
|
814
872
|
logger.debug("handleManifestDownload");
|
|
815
873
|
|
|
@@ -820,7 +878,7 @@ public class DownloadService extends Worker {
|
|
|
820
878
|
}
|
|
821
879
|
|
|
822
880
|
// Send stats for manifest download start
|
|
823
|
-
sendStatsAsync("download_manifest_start", version);
|
|
881
|
+
sendStatsAsync("download_manifest_start", version, java.util.Collections.singletonMap("attempt_id", id));
|
|
824
882
|
|
|
825
883
|
File destFolder = new File(documentsDir, dest);
|
|
826
884
|
File cacheFolder = new File(getApplicationContext().getCacheDir(), "capgo_downloads");
|
|
@@ -837,7 +895,6 @@ public class DownloadService extends Worker {
|
|
|
837
895
|
}
|
|
838
896
|
|
|
839
897
|
int totalFiles = manifest.length();
|
|
840
|
-
final AtomicLong completedFiles = new AtomicLong(0);
|
|
841
898
|
final AtomicBoolean hasError = new AtomicBoolean(false);
|
|
842
899
|
final List<ManifestDownloadTask> tasks = new ArrayList<>();
|
|
843
900
|
final Set<String> seenTargets = new HashSet<>();
|
|
@@ -847,9 +904,11 @@ public class DownloadService extends Worker {
|
|
|
847
904
|
String fileName = entry.getString("file_name");
|
|
848
905
|
String fileHash = entry.optString("file_hash", "");
|
|
849
906
|
String downloadUrl = entry.getString("download_url");
|
|
907
|
+
String ciphertextHash = null;
|
|
850
908
|
|
|
851
909
|
if (fileHash.isEmpty()) {
|
|
852
910
|
logger.error("Missing file_hash for manifest entry: " + fileName);
|
|
911
|
+
recordManifestFileFailure(summary, failedFiles, fileName, "prepare_or_schedule", new IOException("Missing file hash"));
|
|
853
912
|
hasError.set(true);
|
|
854
913
|
continue;
|
|
855
914
|
}
|
|
@@ -858,13 +917,23 @@ public class DownloadService extends Worker {
|
|
|
858
917
|
if (!CryptoCipher.isValidSessionKey(sessionKey)) {
|
|
859
918
|
logger.error("Public key present but no valid session key provided");
|
|
860
919
|
sendStatsAsync("session_key_required", version);
|
|
920
|
+
recordManifestFileFailure(
|
|
921
|
+
summary,
|
|
922
|
+
failedFiles,
|
|
923
|
+
fileName,
|
|
924
|
+
"prepare_or_schedule",
|
|
925
|
+
new IOException("Invalid session key")
|
|
926
|
+
);
|
|
861
927
|
hasError.set(true);
|
|
862
928
|
continue;
|
|
863
929
|
}
|
|
864
930
|
try {
|
|
865
|
-
|
|
931
|
+
final CryptoCipher.BundleChecksum signed = CryptoCipher.decryptBundleChecksum(fileHash, publicKey);
|
|
932
|
+
fileHash = signed.plain;
|
|
933
|
+
ciphertextHash = signed.ciphertext;
|
|
866
934
|
} catch (Exception e) {
|
|
867
935
|
logger.error("Error decrypting checksum for " + fileName + "fileHash: " + fileHash);
|
|
936
|
+
recordManifestFileFailure(summary, failedFiles, fileName, "prepare_or_schedule", e);
|
|
868
937
|
hasError.set(true);
|
|
869
938
|
continue;
|
|
870
939
|
}
|
|
@@ -884,12 +953,20 @@ public class DownloadService extends Worker {
|
|
|
884
953
|
if (!rememberManifestTarget(seenTargets, targetFile)) {
|
|
885
954
|
logger.error("Duplicate manifest target path: " + fileName);
|
|
886
955
|
sendStatsAsync("manifest_path_fail", version + ":" + fileName);
|
|
956
|
+
recordManifestFileFailure(
|
|
957
|
+
summary,
|
|
958
|
+
failedFiles,
|
|
959
|
+
fileName,
|
|
960
|
+
"prepare_or_schedule",
|
|
961
|
+
new IOException("Duplicate target path")
|
|
962
|
+
);
|
|
887
963
|
hasError.set(true);
|
|
888
964
|
continue;
|
|
889
965
|
}
|
|
890
966
|
} catch (IOException e) {
|
|
891
967
|
logger.error("Invalid manifest file path: " + fileName);
|
|
892
968
|
sendStatsAsync("manifest_path_fail", version + ":" + fileName);
|
|
969
|
+
recordManifestFileFailure(summary, failedFiles, fileName, "prepare_or_schedule", e);
|
|
893
970
|
hasError.set(true);
|
|
894
971
|
continue;
|
|
895
972
|
}
|
|
@@ -904,6 +981,7 @@ public class DownloadService extends Worker {
|
|
|
904
981
|
new ManifestDownloadTask(
|
|
905
982
|
fileName,
|
|
906
983
|
finalFileHash,
|
|
984
|
+
ciphertextHash,
|
|
907
985
|
downloadUrl,
|
|
908
986
|
isBrotli,
|
|
909
987
|
targetFile,
|
|
@@ -947,6 +1025,7 @@ public class DownloadService extends Worker {
|
|
|
947
1025
|
task.targetFile,
|
|
948
1026
|
task.cacheFile,
|
|
949
1027
|
task.finalFileHash,
|
|
1028
|
+
task.ciphertextHash,
|
|
950
1029
|
decryptionSession,
|
|
951
1030
|
task.isBrotli,
|
|
952
1031
|
task.fileName
|
|
@@ -958,7 +1037,7 @@ public class DownloadService extends Worker {
|
|
|
958
1037
|
setProgress(percent);
|
|
959
1038
|
} catch (Exception e) {
|
|
960
1039
|
logger.error("Error processing file: " + task.fileName + " " + e.getMessage());
|
|
961
|
-
|
|
1040
|
+
recordManifestFileFailure(summary, failedFiles, task.fileName, "process_file", e);
|
|
962
1041
|
hasError.set(true);
|
|
963
1042
|
}
|
|
964
1043
|
});
|
|
@@ -991,13 +1070,54 @@ public class DownloadService extends Worker {
|
|
|
991
1070
|
}
|
|
992
1071
|
|
|
993
1072
|
// Send stats for manifest download complete
|
|
994
|
-
sendStatsAsync("download_manifest_complete", version);
|
|
1073
|
+
sendStatsAsync("download_manifest_complete", version, java.util.Collections.singletonMap("attempt_id", id));
|
|
995
1074
|
} catch (Exception e) {
|
|
1075
|
+
synchronized (summary) {
|
|
1076
|
+
if (!summary.containsKey("error_type")) {
|
|
1077
|
+
summary.put("failure_stage", "prepare_or_schedule");
|
|
1078
|
+
recordManifestError(summary, e);
|
|
1079
|
+
}
|
|
1080
|
+
summary.put("files_completed", String.valueOf(completedFiles.get()));
|
|
1081
|
+
summary.put("files_total", String.valueOf(manifest.length()));
|
|
1082
|
+
summary.put(
|
|
1083
|
+
"last_percent",
|
|
1084
|
+
String.valueOf(completedFiles.get() == 0 ? 0 : calcTotalPercent(completedFiles.get(), manifest.length()))
|
|
1085
|
+
);
|
|
1086
|
+
summary.put("files_failed", String.valueOf(failedFiles.get()));
|
|
1087
|
+
summary.put("elapsed_ms", String.valueOf(android.os.SystemClock.elapsedRealtime() - started));
|
|
1088
|
+
sendStatsAsync("download_manifest_file_fail", version, summary);
|
|
1089
|
+
}
|
|
996
1090
|
logger.error("Error in handleManifestDownload " + e.getMessage());
|
|
997
1091
|
throw new RuntimeException(e.getLocalizedMessage());
|
|
998
1092
|
}
|
|
999
1093
|
}
|
|
1000
1094
|
|
|
1095
|
+
private static void recordManifestFileFailure(
|
|
1096
|
+
Map<String, String> summary,
|
|
1097
|
+
AtomicLong failedFiles,
|
|
1098
|
+
String fileName,
|
|
1099
|
+
String stage,
|
|
1100
|
+
Exception error
|
|
1101
|
+
) {
|
|
1102
|
+
synchronized (summary) {
|
|
1103
|
+
if (failedFiles.incrementAndGet() == 1) {
|
|
1104
|
+
summary.put("first_file", fileName);
|
|
1105
|
+
summary.put("failure_stage", stage);
|
|
1106
|
+
recordManifestError(summary, error);
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
static void recordManifestError(Map<String, String> summary, Throwable error) {
|
|
1112
|
+
while (error.getCause() != null && error != error.getCause()) error = error.getCause();
|
|
1113
|
+
summary.put("error_type", error.getClass().getSimpleName());
|
|
1114
|
+
String message = error.getMessage();
|
|
1115
|
+
if (message != null && message.matches("Unexpected response code: [0-9]{3}")) {
|
|
1116
|
+
summary.put("http_status", message.substring(message.length() - 3));
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
/** Downloads and verifies a single zip bundle archive while reporting progress from 10% to 70%. */
|
|
1001
1121
|
private void handleSingleFileDownload(
|
|
1002
1122
|
String url,
|
|
1003
1123
|
String id,
|
|
@@ -1020,7 +1140,7 @@ public class DownloadService extends Worker {
|
|
|
1020
1140
|
}
|
|
1021
1141
|
|
|
1022
1142
|
// Send stats for zip download start
|
|
1023
|
-
sendStatsAsync("download_zip_start", version);
|
|
1143
|
+
sendStatsAsync("download_zip_start", version, java.util.Collections.singletonMap("attempt_id", id));
|
|
1024
1144
|
|
|
1025
1145
|
File target = new File(documentsDir, dest);
|
|
1026
1146
|
// Use bundle ID in temp file names to prevent collisions when multiple downloads run concurrently
|
|
@@ -1108,9 +1228,9 @@ public class DownloadService extends Worker {
|
|
|
1108
1228
|
String contentRangeHeader = response.header("Content-Range");
|
|
1109
1229
|
writeHttpBody(tempFile, inputStream, writePlan.statusCode, writePlan.writeOffset, this::isStopped, (written) -> {
|
|
1110
1230
|
int percent = calcTotalPercent(written, totalContentLength);
|
|
1111
|
-
if (percent
|
|
1112
|
-
lastNotifiedPercent[0] =
|
|
1113
|
-
setProgress(
|
|
1231
|
+
if (percent > lastNotifiedPercent[0]) {
|
|
1232
|
+
lastNotifiedPercent[0] = percent;
|
|
1233
|
+
setProgress(percent);
|
|
1114
1234
|
}
|
|
1115
1235
|
});
|
|
1116
1236
|
|
|
@@ -1132,7 +1252,7 @@ public class DownloadService extends Worker {
|
|
|
1132
1252
|
infoFile.delete();
|
|
1133
1253
|
|
|
1134
1254
|
// Send stats for zip download complete
|
|
1135
|
-
sendStatsAsync("download_zip_complete", version);
|
|
1255
|
+
sendStatsAsync("download_zip_complete", version, java.util.Collections.singletonMap("attempt_id", id));
|
|
1136
1256
|
} catch (OutOfMemoryError e) {
|
|
1137
1257
|
logger.error("Out of memory during download: " + e.getMessage());
|
|
1138
1258
|
// Try to free some memory
|
|
@@ -1206,7 +1326,7 @@ public class DownloadService extends Worker {
|
|
|
1206
1326
|
.readTimeout(zipTimeoutMs, TimeUnit.MILLISECONDS)
|
|
1207
1327
|
.writeTimeout(zipTimeoutMs, TimeUnit.MILLISECONDS)
|
|
1208
1328
|
.build();
|
|
1209
|
-
Request.Builder builder = new Request.Builder().url(url);
|
|
1329
|
+
Request.Builder builder = Http3.markDownload(new Request.Builder().url(url));
|
|
1210
1330
|
if (downloadedBytes > 0) {
|
|
1211
1331
|
builder.header("Range", "bytes=" + downloadedBytes + "-");
|
|
1212
1332
|
}
|
|
@@ -1400,6 +1520,7 @@ public class DownloadService extends Worker {
|
|
|
1400
1520
|
File targetFile,
|
|
1401
1521
|
File cacheFile,
|
|
1402
1522
|
String expectedHash,
|
|
1523
|
+
String expectedCiphertextHash,
|
|
1403
1524
|
CryptoCipher.DecryptionSession decryptionSession,
|
|
1404
1525
|
boolean isBrotli,
|
|
1405
1526
|
String relativeName
|
|
@@ -1407,7 +1528,16 @@ public class DownloadService extends Worker {
|
|
|
1407
1528
|
for (int attempt = 1; ; attempt++) {
|
|
1408
1529
|
if (isStopped()) throw new IOException("download_stopped");
|
|
1409
1530
|
try {
|
|
1410
|
-
downloadAndVerifyOnce(
|
|
1531
|
+
downloadAndVerifyOnce(
|
|
1532
|
+
downloadUrl,
|
|
1533
|
+
targetFile,
|
|
1534
|
+
cacheFile,
|
|
1535
|
+
expectedHash,
|
|
1536
|
+
expectedCiphertextHash,
|
|
1537
|
+
decryptionSession,
|
|
1538
|
+
isBrotli,
|
|
1539
|
+
relativeName
|
|
1540
|
+
);
|
|
1411
1541
|
return;
|
|
1412
1542
|
} catch (Exception error) {
|
|
1413
1543
|
if (attempt >= 3 || !isRetryableManifestError(error)) throw error;
|
|
@@ -1439,6 +1569,7 @@ public class DownloadService extends Worker {
|
|
|
1439
1569
|
File targetFile,
|
|
1440
1570
|
File cacheFile,
|
|
1441
1571
|
String expectedHash,
|
|
1572
|
+
String expectedCiphertextHash,
|
|
1442
1573
|
CryptoCipher.DecryptionSession decryptionSession,
|
|
1443
1574
|
boolean isBrotli,
|
|
1444
1575
|
String relativeName
|
|
@@ -1457,7 +1588,7 @@ public class DownloadService extends Worker {
|
|
|
1457
1588
|
boolean resumed = false;
|
|
1458
1589
|
try {
|
|
1459
1590
|
long existing = partial.isFile() ? partial.length() : 0;
|
|
1460
|
-
Request.Builder builder = new Request.Builder().url(downloadUrl);
|
|
1591
|
+
Request.Builder builder = Http3.markDownload(new Request.Builder().url(downloadUrl));
|
|
1461
1592
|
if (existing > 0) {
|
|
1462
1593
|
builder.header("Range", "bytes=" + existing + "-");
|
|
1463
1594
|
}
|
|
@@ -1507,11 +1638,17 @@ public class DownloadService extends Worker {
|
|
|
1507
1638
|
copyFile(partial, workFile);
|
|
1508
1639
|
try {
|
|
1509
1640
|
logger.debug("Decrypting file " + targetFile.getName());
|
|
1510
|
-
decryptionSession.decryptFile(workFile);
|
|
1641
|
+
decryptionSession.decryptFile(workFile, expectedCiphertextHash);
|
|
1511
1642
|
source = workFile;
|
|
1512
1643
|
} catch (Exception e) {
|
|
1513
1644
|
keepPartial = false;
|
|
1514
1645
|
if (resumed) throw new DownloadRetryException("resumed_partial_failed_decryption", e);
|
|
1646
|
+
if (CryptoCipher.CIPHERTEXT_CHECKSUM_MISMATCH.equals(e.getMessage())) {
|
|
1647
|
+
sendStatsAsync(
|
|
1648
|
+
"download_manifest_checksum_fail",
|
|
1649
|
+
getInputData().getString(VERSION) + ":" + finalTargetFile.getName()
|
|
1650
|
+
);
|
|
1651
|
+
}
|
|
1515
1652
|
throw e;
|
|
1516
1653
|
}
|
|
1517
1654
|
}
|