@capgo/capacitor-updater 8.54.0 → 8.54.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.
- package/README.md +24 -0
- package/android/build.gradle +1 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +99 -7
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +182 -1
- package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1 -1
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +90 -5
- 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
package/README.md
CHANGED
|
@@ -212,6 +212,20 @@ npm install @capgo/capacitor-updater@lts-v5
|
|
|
212
212
|
npm install @capgo/capacitor-updater@lts-v4
|
|
213
213
|
```
|
|
214
214
|
|
|
215
|
+
### Android: builtin hash table and compressed assets
|
|
216
|
+
|
|
217
|
+
On `npx cap copy`, the plugin writes `ota-builtin-hashes.json` next to your web assets so the native code can reuse builtin files without hashing them. On Android each sized row checks that the asset's uncompressed length still matches the manifest before trusting the stored SHA-256 (same integrity model as iOS file size checks). `AssetManager.openFd()` only works for uncompressed APK assets; when it fails, the plugin reads the uncompressed length via `AssetManager.open()` instead, so the fast path works for default aapt-compressed web bundles (`.js`, `.css`, `.html`, and similar) without `noCompress`.
|
|
218
|
+
|
|
219
|
+
Optional: listing extensions in `androidResources { noCompress += [...] }` avoids opening a stream for the length check on those files, but increases installed APK size. Without it, updates still verify every builtin file by checksum when the table cannot answer.
|
|
220
|
+
|
|
221
|
+
```groovy
|
|
222
|
+
android {
|
|
223
|
+
androidResources {
|
|
224
|
+
noCompress += ['html', 'js', 'css', 'json', 'svg', 'woff', 'woff2', 'ttf', 'eot', 'map', 'png', 'jpg', 'jpeg', 'webp', 'gif', 'ico', 'wasm', 'txt', 'xml']
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
```
|
|
228
|
+
|
|
215
229
|
## Auto-update setup
|
|
216
230
|
|
|
217
231
|
Create your account in [capgo.app](https://capgo.app) and get your [API key](https://console.capgo.app/dashboard/apikeys)
|
|
@@ -327,6 +341,16 @@ To further remain in compliance with Apple's guidelines, we suggest that App Sto
|
|
|
327
341
|
|
|
328
342
|
This is not a problem for the default behavior of background update, since it won't force the user to apply the new version until the next app close, but at least you should be aware of that ruling if you decide to show it.
|
|
329
343
|
|
|
344
|
+
#### Prevent live updates during Apple and Google review
|
|
345
|
+
|
|
346
|
+
Keep the app on the web assets shipped in the submitted native binary throughout Apple App Store and Google Play review. Applying a live update during review can reload the app, interrupt the reviewer's session, or change the behavior they are reviewing.
|
|
347
|
+
|
|
348
|
+
Capgo Cloud blocks update requests from known Apple and Google datacenter networks by default to prevent live updates from reaching review devices on those networks. Keep the app's **Block provider infrastructure requests** setting enabled. This protection runs on Capgo's server and depends on recognizing the request's network; it does not detect every review session or pause updates for all users while a store review is in progress.
|
|
349
|
+
|
|
350
|
+
If you self-host, manage updates manually, or disable this protection, you must provide your own way to prevent live updates from disturbing review. The same applies if review traffic does not use a recognized network. For example, pause update delivery for the submitted native version or use a dedicated channel that serves no live updates until review is complete. In manual flows, guard calls such as `download()`, `next()`, and `set()`, and prevent already downloaded or queued bundles from being applied during review. Hiding an update message does not prevent the update itself.
|
|
351
|
+
|
|
352
|
+
Before submitting, test a fresh install and an upgrade from the previous store version. Confirm that the submitted build keeps running its bundled web assets across launches and background/foreground transitions while the review hold is active.
|
|
353
|
+
|
|
330
354
|
#### Good practice for App Store review
|
|
331
355
|
|
|
332
356
|
Do not tell the user the app is updating. In any UI the user can see, including copy on top of the splash screen, settings, and buttons, do not say "update", "live update", "remote update", "OTA", "downloading", or "installing". A progress bar is fine when its label describes tailoring the experience, for example "Tailoring your experience…". Calling that wait an update reads as the app installing behavior that was not in the reviewed binary.
|
package/android/build.gradle
CHANGED
|
@@ -65,6 +65,7 @@ dependencies {
|
|
|
65
65
|
testImplementation 'org.json:json:20250517'
|
|
66
66
|
testImplementation 'org.robolectric:robolectric:4.17'
|
|
67
67
|
testImplementation 'androidx.arch.core:core-testing:2.2.0'
|
|
68
|
+
testImplementation "com.squareup.okhttp3:mockwebserver:$okhttpVersion"
|
|
68
69
|
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
|
|
69
70
|
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
|
|
70
71
|
implementation 'org.brotli:dec:0.1.2'
|
|
@@ -13,6 +13,7 @@ import android.content.pm.PackageManager;
|
|
|
13
13
|
import android.os.Build;
|
|
14
14
|
import android.os.Handler;
|
|
15
15
|
import android.os.Looper;
|
|
16
|
+
import android.os.SystemClock;
|
|
16
17
|
import androidx.annotation.NonNull;
|
|
17
18
|
import androidx.lifecycle.LiveData;
|
|
18
19
|
import androidx.lifecycle.Observer;
|
|
@@ -153,6 +154,7 @@ public class CapgoUpdater {
|
|
|
153
154
|
private static final long STATS_FLUSH_INTERVAL_MS = 1000;
|
|
154
155
|
private static volatile Long statsFlushIntervalOverrideMs = null;
|
|
155
156
|
private static volatile boolean statsFlushSchedulingDisabledForTests = false;
|
|
157
|
+
private static volatile boolean statsFailureElapsedRealtimeStubForTests = false;
|
|
156
158
|
/** Unit tests only: runs after queue mutation and before the stats owner check. */
|
|
157
159
|
static volatile Runnable statsAdoptionBeforeOwnerCheckForTests = null;
|
|
158
160
|
private static final String PENDING_STATS_FILE = "capgo_pending_stats.json";
|
|
@@ -3722,12 +3724,21 @@ public class CapgoUpdater {
|
|
|
3722
3724
|
static void resetStatsFlushForTests() {
|
|
3723
3725
|
statsFlushIntervalOverrideMs = null;
|
|
3724
3726
|
statsFlushSchedulingDisabledForTests = false;
|
|
3727
|
+
statsFailureElapsedRealtimeStubForTests = false;
|
|
3728
|
+
}
|
|
3729
|
+
|
|
3730
|
+
static void stubStatsFailureElapsedRealtimeForTests(final boolean enabled) {
|
|
3731
|
+
statsFailureElapsedRealtimeStubForTests = enabled;
|
|
3725
3732
|
}
|
|
3726
3733
|
|
|
3727
3734
|
int pendingStatsCount() {
|
|
3728
3735
|
return statsQueue.size();
|
|
3729
3736
|
}
|
|
3730
3737
|
|
|
3738
|
+
void flushStatsQueueForTests() {
|
|
3739
|
+
flushStatsQueue();
|
|
3740
|
+
}
|
|
3741
|
+
|
|
3731
3742
|
void enqueuePendingStatsEventForTests(final String action) {
|
|
3732
3743
|
try {
|
|
3733
3744
|
final JSONObject json = new JSONObject();
|
|
@@ -3934,6 +3945,7 @@ public class CapgoUpdater {
|
|
|
3934
3945
|
.build();
|
|
3935
3946
|
|
|
3936
3947
|
final int eventCount = eventsToSend.size();
|
|
3948
|
+
final long requestStartElapsedRealtime = statsFailureElapsedRealtimeStubForTests ? 0L : SystemClock.elapsedRealtime();
|
|
3937
3949
|
DownloadService.sharedClient.newCall(request).enqueue(
|
|
3938
3950
|
new okhttp3.Callback() {
|
|
3939
3951
|
@Override
|
|
@@ -3941,10 +3953,19 @@ public class CapgoUpdater {
|
|
|
3941
3953
|
if (abandonStoppedStatsFlush()) {
|
|
3942
3954
|
return;
|
|
3943
3955
|
}
|
|
3956
|
+
final long elapsedMs = statsFailureElapsedRealtimeStubForTests
|
|
3957
|
+
? 0L
|
|
3958
|
+
: SystemClock.elapsedRealtime() - requestStartElapsedRealtime;
|
|
3944
3959
|
requeueStatsEvents(eventsToSend);
|
|
3945
3960
|
if (logger != null) {
|
|
3946
|
-
logger.error(
|
|
3947
|
-
|
|
3961
|
+
logger.error(
|
|
3962
|
+
StatsBatchFailureDiagnostics.formatFailureMessage(
|
|
3963
|
+
"Failed to send stats batch",
|
|
3964
|
+
StatsBatchFailureDiagnostics.safeDestinationUrl(call.request().url()),
|
|
3965
|
+
StatsBatchFailureDiagnostics.STATUS_UNAVAILABLE,
|
|
3966
|
+
elapsedMs
|
|
3967
|
+
)
|
|
3968
|
+
);
|
|
3948
3969
|
}
|
|
3949
3970
|
statsFlushInFlight.set(false);
|
|
3950
3971
|
}
|
|
@@ -3955,9 +3976,68 @@ public class CapgoUpdater {
|
|
|
3955
3976
|
if (abandonStoppedStatsFlush()) {
|
|
3956
3977
|
return;
|
|
3957
3978
|
}
|
|
3958
|
-
final String
|
|
3979
|
+
final String safeDestination = StatsBatchFailureDiagnostics.safeDestinationUrl(response.request().url());
|
|
3980
|
+
final String responseData;
|
|
3981
|
+
try {
|
|
3982
|
+
responseData = responseBody != null ? responseBody.string() : "";
|
|
3983
|
+
} catch (IOException readEx) {
|
|
3984
|
+
final long readFailureElapsedMs = statsFailureElapsedRealtimeStubForTests
|
|
3985
|
+
? 0L
|
|
3986
|
+
: SystemClock.elapsedRealtime() - requestStartElapsedRealtime;
|
|
3987
|
+
checkAndHandleRateLimitResponse(response, "");
|
|
3988
|
+
if (response.isSuccessful()) {
|
|
3989
|
+
synchronized (statsQueue) {
|
|
3990
|
+
statsInFlight.clear();
|
|
3991
|
+
}
|
|
3992
|
+
persistStatsQueue();
|
|
3993
|
+
runStatsCallbacks(eventsToSend);
|
|
3994
|
+
return;
|
|
3995
|
+
}
|
|
3996
|
+
if (!isTransientStatsFailure(response.code())) {
|
|
3997
|
+
synchronized (statsQueue) {
|
|
3998
|
+
statsInFlight.clear();
|
|
3999
|
+
}
|
|
4000
|
+
persistStatsQueue();
|
|
4001
|
+
if (logger != null) {
|
|
4002
|
+
logger.error(
|
|
4003
|
+
StatsBatchFailureDiagnostics.formatFailureMessage(
|
|
4004
|
+
"Dropping stats batch after permanent error",
|
|
4005
|
+
safeDestination,
|
|
4006
|
+
String.valueOf(response.code()),
|
|
4007
|
+
readFailureElapsedMs
|
|
4008
|
+
)
|
|
4009
|
+
);
|
|
4010
|
+
}
|
|
4011
|
+
return;
|
|
4012
|
+
}
|
|
4013
|
+
requeueStatsEvents(eventsToSend);
|
|
4014
|
+
if (logger != null) {
|
|
4015
|
+
logger.error(
|
|
4016
|
+
StatsBatchFailureDiagnostics.formatFailureMessage(
|
|
4017
|
+
"Error sending stats batch",
|
|
4018
|
+
safeDestination,
|
|
4019
|
+
String.valueOf(response.code()),
|
|
4020
|
+
readFailureElapsedMs
|
|
4021
|
+
)
|
|
4022
|
+
);
|
|
4023
|
+
}
|
|
4024
|
+
return;
|
|
4025
|
+
}
|
|
4026
|
+
final long normalElapsedMs = statsFailureElapsedRealtimeStubForTests
|
|
4027
|
+
? 0L
|
|
4028
|
+
: SystemClock.elapsedRealtime() - requestStartElapsedRealtime;
|
|
3959
4029
|
if (checkAndHandleRateLimitResponse(response, responseData).blocked) {
|
|
3960
4030
|
requeueStatsEvents(eventsToSend);
|
|
4031
|
+
if (logger != null) {
|
|
4032
|
+
logger.error(
|
|
4033
|
+
StatsBatchFailureDiagnostics.formatFailureMessage(
|
|
4034
|
+
"Error sending stats batch",
|
|
4035
|
+
safeDestination,
|
|
4036
|
+
String.valueOf(response.code()),
|
|
4037
|
+
normalElapsedMs
|
|
4038
|
+
)
|
|
4039
|
+
);
|
|
4040
|
+
}
|
|
3961
4041
|
return;
|
|
3962
4042
|
}
|
|
3963
4043
|
|
|
@@ -3974,8 +4054,14 @@ public class CapgoUpdater {
|
|
|
3974
4054
|
} else if (isTransientStatsFailure(response.code())) {
|
|
3975
4055
|
requeueStatsEvents(eventsToSend);
|
|
3976
4056
|
if (logger != null) {
|
|
3977
|
-
logger.error(
|
|
3978
|
-
|
|
4057
|
+
logger.error(
|
|
4058
|
+
StatsBatchFailureDiagnostics.formatFailureMessage(
|
|
4059
|
+
"Error sending stats batch",
|
|
4060
|
+
safeDestination,
|
|
4061
|
+
String.valueOf(response.code()),
|
|
4062
|
+
normalElapsedMs
|
|
4063
|
+
)
|
|
4064
|
+
);
|
|
3979
4065
|
}
|
|
3980
4066
|
} else {
|
|
3981
4067
|
synchronized (statsQueue) {
|
|
@@ -3983,8 +4069,14 @@ public class CapgoUpdater {
|
|
|
3983
4069
|
}
|
|
3984
4070
|
persistStatsQueue();
|
|
3985
4071
|
if (logger != null) {
|
|
3986
|
-
logger.error(
|
|
3987
|
-
|
|
4072
|
+
logger.error(
|
|
4073
|
+
StatsBatchFailureDiagnostics.formatFailureMessage(
|
|
4074
|
+
"Dropping stats batch after permanent error",
|
|
4075
|
+
safeDestination,
|
|
4076
|
+
String.valueOf(response.code()),
|
|
4077
|
+
normalElapsedMs
|
|
4078
|
+
)
|
|
4079
|
+
);
|
|
3988
4080
|
}
|
|
3989
4081
|
}
|
|
3990
4082
|
} finally {
|
|
@@ -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;
|
|
@@ -475,14 +478,185 @@ public class DownloadService extends Worker {
|
|
|
475
478
|
}
|
|
476
479
|
}
|
|
477
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
|
+
} catch (IOException openFdFailed) {
|
|
578
|
+
// Compressed APK assets cannot use openFd(); length is still the uncompressed byte count.
|
|
579
|
+
try (InputStream in = assets.open(assetPath)) {
|
|
580
|
+
final long fromAvailable = in.available();
|
|
581
|
+
if (fromAvailable > 0) {
|
|
582
|
+
return fromAvailable;
|
|
583
|
+
}
|
|
584
|
+
long total = 0;
|
|
585
|
+
final byte[] buffer = new byte[CryptoCipher.ioBufferBytes()];
|
|
586
|
+
int read;
|
|
587
|
+
while ((read = in.read(buffer)) != -1) {
|
|
588
|
+
total += read;
|
|
589
|
+
}
|
|
590
|
+
return total;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
static Boolean builtinHashVerdictForEntry(
|
|
596
|
+
final AssetManager assets,
|
|
597
|
+
final String assetPath,
|
|
598
|
+
final BuiltinHashEntry entry,
|
|
599
|
+
final String expectedHash
|
|
600
|
+
) {
|
|
601
|
+
if (entry == null || expectedHash == null) {
|
|
602
|
+
return null;
|
|
603
|
+
}
|
|
604
|
+
if (entry.size >= 0) {
|
|
605
|
+
try {
|
|
606
|
+
if (builtinAssetLength(assets, assetPath) != entry.size) {
|
|
607
|
+
return null;
|
|
608
|
+
}
|
|
609
|
+
} catch (IOException e) {
|
|
610
|
+
return null;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
return entry.hash.equalsIgnoreCase(expectedHash) ? Boolean.TRUE : Boolean.FALSE;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** TRUE/FALSE from the table, or null when the table cannot answer. */
|
|
617
|
+
static Boolean builtinHashVerdict(final AssetManager assets, final String assetPath, final String expectedHash) {
|
|
618
|
+
if (assets == null || assetPath == null || !assetPath.startsWith("public/") || expectedHash == null) {
|
|
619
|
+
return null;
|
|
620
|
+
}
|
|
621
|
+
final BuiltinHashEntry known = builtinHashes(assets).get(assetPath.substring("public/".length()));
|
|
622
|
+
return known == null ? null : builtinHashVerdictForEntry(assets, assetPath, known, expectedHash);
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
static boolean copyStreamUnchecked(final InputStream input, final File dest) throws IOException {
|
|
626
|
+
final File parent = dest.getParentFile();
|
|
627
|
+
if (parent == null) {
|
|
628
|
+
throw new IOException("Destination has no parent: " + dest.getAbsolutePath());
|
|
629
|
+
}
|
|
630
|
+
if (!parent.exists() && !parent.mkdirs()) {
|
|
631
|
+
throw new IOException("Failed to create parent directory: " + parent.getAbsolutePath());
|
|
632
|
+
}
|
|
633
|
+
final File tempFile = File.createTempFile("capgo_asset_", ".tmp", parent);
|
|
634
|
+
try {
|
|
635
|
+
try (FileOutputStream outStream = new FileOutputStream(tempFile)) {
|
|
636
|
+
final byte[] buffer = new byte[CryptoCipher.ioBufferBytes()];
|
|
637
|
+
int length;
|
|
638
|
+
while ((length = input.read(buffer)) != -1) {
|
|
639
|
+
outStream.write(buffer, 0, length);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
return replaceFile(tempFile, dest);
|
|
643
|
+
} finally {
|
|
644
|
+
deleteQuietly(tempFile);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
478
648
|
static boolean tryCopyBuiltinAsset(final AssetManager assets, final String fileName, final File dest, final String expectedHash) {
|
|
479
649
|
if (assets == null || fileName == null || dest == null) {
|
|
480
650
|
return false;
|
|
481
651
|
}
|
|
482
652
|
try {
|
|
483
653
|
final String assetPath = resolveBuiltinAssetPath(fileName);
|
|
654
|
+
final Boolean verdict = builtinHashVerdict(assets, assetPath, expectedHash);
|
|
655
|
+
if (Boolean.FALSE.equals(verdict)) {
|
|
656
|
+
return false;
|
|
657
|
+
}
|
|
484
658
|
try (InputStream in = assets.open(assetPath)) {
|
|
485
|
-
return copyStreamIfChecksumMatches(in, dest, expectedHash);
|
|
659
|
+
return verdict != null ? copyStreamUnchecked(in, dest) : copyStreamIfChecksumMatches(in, dest, expectedHash);
|
|
486
660
|
}
|
|
487
661
|
} catch (IOException e) {
|
|
488
662
|
return false;
|
|
@@ -495,7 +669,14 @@ public class DownloadService extends Worker {
|
|
|
495
669
|
}
|
|
496
670
|
try {
|
|
497
671
|
final String assetPath = resolveBuiltinAssetPath(fileName);
|
|
672
|
+
final Boolean verdict = builtinHashVerdict(assets, assetPath, expectedHash);
|
|
673
|
+
if (Boolean.FALSE.equals(verdict)) {
|
|
674
|
+
return false;
|
|
675
|
+
}
|
|
498
676
|
try (InputStream in = assets.open(assetPath)) {
|
|
677
|
+
if (verdict != null) {
|
|
678
|
+
return verdict;
|
|
679
|
+
}
|
|
499
680
|
return expectedHash.equalsIgnoreCase(CryptoCipher.calcChecksum(in));
|
|
500
681
|
}
|
|
501
682
|
} catch (IOException e) {
|
|
@@ -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
|
+
}
|
|
@@ -95,7 +95,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
|
|
|
95
95
|
deinit {
|
|
96
96
|
implementation.shutdown()
|
|
97
97
|
}
|
|
98
|
-
private let pluginVersion: String = "8.54.
|
|
98
|
+
private let pluginVersion: String = "8.54.2"
|
|
99
99
|
private let launchStartedAtMs = Int64(Date().timeIntervalSince1970 * 1000)
|
|
100
100
|
static let updateUrlDefault = "https://plugin.capgo.app/updates"
|
|
101
101
|
static let statsUrlDefault = "https://plugin.capgo.app/stats"
|
|
@@ -1364,8 +1364,7 @@ import UIKit
|
|
|
1364
1364
|
let builtinLookupName = knownEntry?.originalFileName ?? relativePath
|
|
1365
1365
|
let isBuiltinOrigin: Bool
|
|
1366
1366
|
if let builtinFilePath = try? Self.resolveManifestTargetPath(baseDirectory: builtinFolder, fileName: builtinLookupName) {
|
|
1367
|
-
isBuiltinOrigin =
|
|
1368
|
-
verifyChecksum(file: builtinFilePath, expectedHash: checksum)
|
|
1367
|
+
isBuiltinOrigin = builtinFileMatches(builtinFilePath, expectedHash: checksum)
|
|
1369
1368
|
} else {
|
|
1370
1369
|
isBuiltinOrigin = false
|
|
1371
1370
|
}
|
|
@@ -1579,6 +1578,93 @@ import UIKit
|
|
|
1579
1578
|
Bundle.main.bundleURL.appendingPathComponent("public")
|
|
1580
1579
|
}
|
|
1581
1580
|
|
|
1581
|
+
// Precomputed builtin hashes: `ota-builtin-hashes.json` in the web assets dir (Capacitor sync hook).
|
|
1582
|
+
// Loaded lazily once per process; missing or invalid JSON is cached as an empty map.
|
|
1583
|
+
static let builtinHashesFileName = "ota-builtin-hashes.json"
|
|
1584
|
+
private static func isSha256Hex(_ value: String) -> Bool {
|
|
1585
|
+
guard value.count == 64 else { return false }
|
|
1586
|
+
let hex = CharacterSet(charactersIn: "0123456789abcdefABCDEF")
|
|
1587
|
+
return value.unicodeScalars.allSatisfy { hex.contains($0) }
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
private struct BuiltinHashEntry {
|
|
1591
|
+
let hash: String
|
|
1592
|
+
/// `nil` for legacy string-only manifest entries (no size gate).
|
|
1593
|
+
let size: Int64?
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
private var cachedBuiltinHashes: [String: BuiltinHashEntry]?
|
|
1597
|
+
private let builtinHashesLock = NSLock()
|
|
1598
|
+
/// Disk reads of `ota-builtin-hashes.json` (lazy once per updater instance / process).
|
|
1599
|
+
private(set) var builtinHashesTableLoadCount = 0
|
|
1600
|
+
|
|
1601
|
+
private func builtinHashes() -> [String: BuiltinHashEntry] {
|
|
1602
|
+
builtinHashesLock.lock()
|
|
1603
|
+
defer { builtinHashesLock.unlock() }
|
|
1604
|
+
if let hashes = cachedBuiltinHashes {
|
|
1605
|
+
return hashes
|
|
1606
|
+
}
|
|
1607
|
+
var hashes: [String: BuiltinHashEntry] = [:]
|
|
1608
|
+
let tableURL = builtinFolderURL().appendingPathComponent(Self.builtinHashesFileName)
|
|
1609
|
+
builtinHashesTableLoadCount += 1
|
|
1610
|
+
if let data = try? Data(contentsOf: tableURL),
|
|
1611
|
+
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
1612
|
+
let files = json["files"] as? [String: Any] {
|
|
1613
|
+
for (key, value) in files {
|
|
1614
|
+
if let hash = value as? String, Self.isSha256Hex(hash) {
|
|
1615
|
+
hashes[key] = BuiltinHashEntry(hash: hash, size: nil)
|
|
1616
|
+
continue
|
|
1617
|
+
}
|
|
1618
|
+
guard let obj = value as? [String: Any],
|
|
1619
|
+
let hash = obj["sha256"] as? String,
|
|
1620
|
+
Self.isSha256Hex(hash) else { continue }
|
|
1621
|
+
let sizeValue: Int64?
|
|
1622
|
+
if obj["size"] == nil || obj["size"] is NSNull {
|
|
1623
|
+
sizeValue = nil
|
|
1624
|
+
} else if let size = obj["size"] as? NSNumber,
|
|
1625
|
+
CFGetTypeID(size) != CFBooleanGetTypeID(),
|
|
1626
|
+
let exact = Int64(exactly: size.doubleValue),
|
|
1627
|
+
exact >= 0 {
|
|
1628
|
+
sizeValue = exact
|
|
1629
|
+
} else {
|
|
1630
|
+
continue
|
|
1631
|
+
}
|
|
1632
|
+
hashes[key] = BuiltinHashEntry(hash: hash, size: sizeValue)
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
cachedBuiltinHashes = hashes
|
|
1636
|
+
return hashes
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
private func builtinTableVerdict(relativePath: String, fileURL: URL, expectedHash: String) -> Bool? {
|
|
1640
|
+
guard let entry = builtinHashes()[relativePath] else {
|
|
1641
|
+
return nil
|
|
1642
|
+
}
|
|
1643
|
+
guard FileManager.default.fileExists(atPath: fileURL.path) else {
|
|
1644
|
+
return false
|
|
1645
|
+
}
|
|
1646
|
+
if let expectedSize = entry.size {
|
|
1647
|
+
let actualSize = (try? fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize).map { Int64($0) }
|
|
1648
|
+
if actualSize != expectedSize {
|
|
1649
|
+
return nil
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
return entry.hash.lowercased() == expectedHash.lowercased()
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
private func builtinFileMatches(_ builtinFilePath: URL, expectedHash: String) -> Bool {
|
|
1656
|
+
let basePath = builtinFolderURL().standardizedFileURL.path
|
|
1657
|
+
let filePath = builtinFilePath.standardizedFileURL.path
|
|
1658
|
+
if filePath.hasPrefix(basePath + "/") {
|
|
1659
|
+
let relativePath = String(filePath.dropFirst(basePath.count + 1))
|
|
1660
|
+
if let verdict = builtinTableVerdict(relativePath: relativePath, fileURL: builtinFilePath, expectedHash: expectedHash) {
|
|
1661
|
+
return verdict
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
return FileManager.default.fileExists(atPath: builtinFilePath.path) &&
|
|
1665
|
+
verifyChecksum(file: builtinFilePath, expectedHash: expectedHash)
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1582
1668
|
private func resolveManifestFileHash(entry: ManifestEntry, sessionKey: String) -> String? {
|
|
1583
1669
|
guard var fileHash = entry.file_hash, !fileHash.isEmpty else {
|
|
1584
1670
|
return nil
|
|
@@ -1609,7 +1695,7 @@ import UIKit
|
|
|
1609
1695
|
guard let builtinFilePath = try? Self.resolveManifestTargetPath(baseDirectory: builtinFolder, fileName: fileName) else {
|
|
1610
1696
|
return false
|
|
1611
1697
|
}
|
|
1612
|
-
if
|
|
1698
|
+
if builtinFileMatches(builtinFilePath, expectedHash: fileHash) {
|
|
1613
1699
|
return true
|
|
1614
1700
|
}
|
|
1615
1701
|
|
|
@@ -1958,8 +2044,7 @@ import UIKit
|
|
|
1958
2044
|
|
|
1959
2045
|
do {
|
|
1960
2046
|
// Try builtin first
|
|
1961
|
-
if
|
|
1962
|
-
self.verifyChecksum(file: task.builtinFilePath, expectedHash: task.finalFileHash) {
|
|
2047
|
+
if self.builtinFileMatches(task.builtinFilePath, expectedHash: task.finalFileHash) {
|
|
1963
2048
|
try self.copyItemReplacing(from: task.builtinFilePath, to: task.destFilePath)
|
|
1964
2049
|
self.logger.info("downloadManifest \(task.fileName) using builtin file \(id)")
|
|
1965
2050
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capgo/capacitor-updater",
|
|
3
|
-
"version": "8.54.
|
|
3
|
+
"version": "8.54.2",
|
|
4
4
|
"license": "MPL-2.0",
|
|
5
5
|
"description": "Live update for capacitor apps",
|
|
6
6
|
"main": "dist/plugin.cjs.js",
|
|
@@ -14,7 +14,10 @@
|
|
|
14
14
|
"dist/",
|
|
15
15
|
"ios/Sources/",
|
|
16
16
|
"CapgoCapacitorUpdater.podspec",
|
|
17
|
-
"Package.swift"
|
|
17
|
+
"Package.swift",
|
|
18
|
+
"scripts/builtin-hashes-lib.mjs",
|
|
19
|
+
"scripts/capacitor-builtin-hashes-hook.mjs",
|
|
20
|
+
"scripts/resolve-real-path.mjs"
|
|
18
21
|
],
|
|
19
22
|
"author": "Martin Donadieu <martin@capgo.app>",
|
|
20
23
|
"repository": {
|
|
@@ -71,7 +74,7 @@
|
|
|
71
74
|
"clean": "rimraf ./dist",
|
|
72
75
|
"watch": "tsc --watch",
|
|
73
76
|
"prepublishOnly": "bun run build",
|
|
74
|
-
"check:wiring": "node scripts/check-capacitor-plugin-wiring.mjs && bun scripts/test-cli-crypto-output-guard.mjs",
|
|
77
|
+
"check:wiring": "node scripts/check-capacitor-plugin-wiring.mjs && bun scripts/test-cli-crypto-output-guard.mjs && node scripts/test-builtin-hashes-hook.mjs",
|
|
75
78
|
"check:cap9-deprecated": "bun scripts/check-cap9-deprecated.mjs",
|
|
76
79
|
"changelog:ai": "node scripts/generate-ai-changelog.mjs",
|
|
77
80
|
"example:install": "cd example-app && bun install --frozen-lockfile",
|
|
@@ -82,7 +85,8 @@
|
|
|
82
85
|
"native:contract:cli:ios": "./scripts/test-ios.sh -only-testing:CapacitorUpdaterPluginTests/CliCryptoFixtureTests",
|
|
83
86
|
"native:contract:cli:android": "cd android && ./gradlew testDebugUnitTest --tests ee.forgr.capacitor_updater.CliCryptoFixtureTest && cd ..",
|
|
84
87
|
"generate:rsa-contract": "bun scripts/generate-rsa-contract-fixtures.mjs",
|
|
85
|
-
"generate:cli-crypto": "bun scripts/generate-cli-crypto-fixtures.mjs"
|
|
88
|
+
"generate:cli-crypto": "bun scripts/generate-cli-crypto-fixtures.mjs",
|
|
89
|
+
"capacitor:copy:after": "node scripts/capacitor-builtin-hashes-hook.mjs"
|
|
86
90
|
},
|
|
87
91
|
"devDependencies": {
|
|
88
92
|
"@capacitor/android": "^8.5.0",
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import process from 'node:process';
|
|
5
|
+
import { resolveRealPath } from './resolve-real-path.mjs';
|
|
6
|
+
|
|
7
|
+
export const BUILTIN_HASHES_FILE_NAME = 'ota-builtin-hashes.json';
|
|
8
|
+
|
|
9
|
+
/** On Android, sized manifest rows compare against uncompressed asset length (openFd when stored uncompressed, otherwise InputStream). */
|
|
10
|
+
|
|
11
|
+
export function sha256File(file) {
|
|
12
|
+
const hash = createHash('sha256');
|
|
13
|
+
const fd = fs.openSync(file, 'r');
|
|
14
|
+
try {
|
|
15
|
+
const chunk = Buffer.alloc(1024 * 1024);
|
|
16
|
+
let bytesRead;
|
|
17
|
+
while ((bytesRead = fs.readSync(fd, chunk, 0, chunk.length, null)) > 0) {
|
|
18
|
+
hash.update(chunk.subarray(0, bytesRead));
|
|
19
|
+
}
|
|
20
|
+
} finally {
|
|
21
|
+
fs.closeSync(fd);
|
|
22
|
+
}
|
|
23
|
+
return hash.digest('hex');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Walk `webDir` and collect relativePath -> sha256 hex. Skips the manifest output file,
|
|
28
|
+
* symlinks (does not follow), and non-regular files.
|
|
29
|
+
*/
|
|
30
|
+
export function collectWebBundleHashes(webDir, { outputFileAbs = null } = {}) {
|
|
31
|
+
const base = fs.realpathSync(webDir);
|
|
32
|
+
const resolvedOutput = outputFileAbs ? resolveRealPath(outputFileAbs) : null;
|
|
33
|
+
const skipNames = new Set([BUILTIN_HASHES_FILE_NAME]);
|
|
34
|
+
const files = {};
|
|
35
|
+
|
|
36
|
+
function recordRegularFile(resolvedFull) {
|
|
37
|
+
if (resolvedOutput && resolvedFull === resolvedOutput) {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (!pathContains(base, resolvedFull)) {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const rel = path.relative(base, resolvedFull).split(path.sep).join('/');
|
|
44
|
+
const stat = fs.statSync(resolvedFull);
|
|
45
|
+
files[rel] = { sha256: sha256File(resolvedFull), size: stat.size };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function visitName(name, realDir, ancestors) {
|
|
49
|
+
if (skipNames.has(name)) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const full = path.join(realDir, name);
|
|
53
|
+
let stat;
|
|
54
|
+
try {
|
|
55
|
+
stat = fs.lstatSync(full);
|
|
56
|
+
} catch {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
if (stat.isSymbolicLink()) {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (stat.isDirectory()) {
|
|
63
|
+
walk(full, ancestors);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (!stat.isFile()) {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
recordRegularFile(fs.realpathSync(full));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function walk(dir, ancestors = new Set()) {
|
|
73
|
+
const realDir = fs.realpathSync(dir);
|
|
74
|
+
if (ancestors.has(realDir)) {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
ancestors.add(realDir);
|
|
78
|
+
try {
|
|
79
|
+
for (const name of fs.readdirSync(realDir)) {
|
|
80
|
+
visitName(name, realDir, ancestors);
|
|
81
|
+
}
|
|
82
|
+
} finally {
|
|
83
|
+
ancestors.delete(realDir);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
walk(base);
|
|
88
|
+
return files;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function pathContains(parent, descendant) {
|
|
92
|
+
const relative = path.relative(parent, descendant);
|
|
93
|
+
if (relative === '') {
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
if (path.isAbsolute(relative) || relative === '..' || relative.startsWith(`..${path.sep}`)) {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function resolveIosPublicDir(rootDir, extConfig = {}) {
|
|
103
|
+
const platformDir = extConfig.ios?.path ?? 'ios';
|
|
104
|
+
const platformDirAbs = path.resolve(rootDir, platformDir);
|
|
105
|
+
const nativeProjectDirAbs = path.join(platformDirAbs, 'App');
|
|
106
|
+
const nativeTargetDirAbs = path.join(platformDirAbs, 'App', 'App');
|
|
107
|
+
const pbxprojPath = path.join(platformDirAbs, 'App', 'App.xcodeproj', 'project.pbxproj');
|
|
108
|
+
try {
|
|
109
|
+
const pbxproj = fs.readFileSync(pbxprojPath, 'utf8');
|
|
110
|
+
const re = /path\s=\spublic[\s\S]+?sourceTree\s=\s([^;]+)/;
|
|
111
|
+
const match = pbxproj.match(re);
|
|
112
|
+
if (match?.[1] === 'SOURCE_ROOT') {
|
|
113
|
+
return path.join(nativeProjectDirAbs, 'public');
|
|
114
|
+
}
|
|
115
|
+
} catch {
|
|
116
|
+
// ignore
|
|
117
|
+
}
|
|
118
|
+
return path.join(nativeTargetDirAbs, 'public');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function resolveAndroidPublicDir(rootDir, extConfig = {}) {
|
|
122
|
+
const platformDir = extConfig.android?.path ?? 'android';
|
|
123
|
+
const platformDirAbs = path.resolve(rootDir, platformDir);
|
|
124
|
+
return path.join(platformDirAbs, 'app', 'src', 'main', 'assets', 'public');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function resolveNativePublicDir(rootDir, platformName, extConfig = {}) {
|
|
128
|
+
if (platformName === 'android') {
|
|
129
|
+
return resolveAndroidPublicDir(rootDir, extConfig);
|
|
130
|
+
}
|
|
131
|
+
if (platformName === 'ios') {
|
|
132
|
+
return resolveIosPublicDir(rootDir, extConfig);
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function writeBuiltinHashesManifest(outputFile, files) {
|
|
138
|
+
const payload = `${JSON.stringify({ files }, null, 2)}\n`;
|
|
139
|
+
fs.mkdirSync(path.dirname(outputFile), { recursive: true });
|
|
140
|
+
const tmpFile = `${outputFile}.${process.pid}.tmp`;
|
|
141
|
+
try {
|
|
142
|
+
fs.writeFileSync(tmpFile, payload, 'utf8');
|
|
143
|
+
fs.renameSync(tmpFile, outputFile);
|
|
144
|
+
} catch (err) {
|
|
145
|
+
fs.rmSync(tmpFile, { force: true });
|
|
146
|
+
throw err;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Capacitor plugin hook: runs on capacitor:copy:after (covers standalone copy and sync, which invokes copy).
|
|
4
|
+
* Writes ota-builtin-hashes.json into the native web public folder for the active platform.
|
|
5
|
+
*/
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import process from 'node:process';
|
|
9
|
+
import {
|
|
10
|
+
BUILTIN_HASHES_FILE_NAME,
|
|
11
|
+
collectWebBundleHashes,
|
|
12
|
+
resolveNativePublicDir,
|
|
13
|
+
writeBuiltinHashesManifest,
|
|
14
|
+
} from './builtin-hashes-lib.mjs';
|
|
15
|
+
|
|
16
|
+
function readExtConfig() {
|
|
17
|
+
const raw = process.env.CAPACITOR_CONFIG;
|
|
18
|
+
if (!raw) {
|
|
19
|
+
return {};
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
return JSON.parse(raw);
|
|
23
|
+
} catch {
|
|
24
|
+
return {};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function main() {
|
|
29
|
+
try {
|
|
30
|
+
const platformName = process.env.CAPACITOR_PLATFORM_NAME;
|
|
31
|
+
if (!platformName || platformName === 'web') {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const rootDir = process.env.CAPACITOR_ROOT_DIR;
|
|
36
|
+
if (!rootDir) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const extConfig = readExtConfig();
|
|
41
|
+
const nativePublicDir = resolveNativePublicDir(rootDir, platformName, extConfig);
|
|
42
|
+
if (!nativePublicDir) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (!fs.existsSync(nativePublicDir)) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const outputFile = path.join(nativePublicDir, BUILTIN_HASHES_FILE_NAME);
|
|
51
|
+
fs.rmSync(outputFile, { force: true });
|
|
52
|
+
try {
|
|
53
|
+
const files = collectWebBundleHashes(nativePublicDir, { outputFileAbs: outputFile });
|
|
54
|
+
writeBuiltinHashesManifest(outputFile, files);
|
|
55
|
+
} catch (err) {
|
|
56
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
57
|
+
console.warn(`[capgo] ${BUILTIN_HASHES_FILE_NAME} not generated: ${message}`);
|
|
58
|
+
}
|
|
59
|
+
} catch (err) {
|
|
60
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
61
|
+
console.warn(`[capgo] ${BUILTIN_HASHES_FILE_NAME} hook failed: ${message}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
main();
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
/** Resolve symlinks; walk up to the nearest existing ancestor when target does not exist yet. */
|
|
5
|
+
export function resolveRealPath(target) {
|
|
6
|
+
const normalized = path.resolve(target);
|
|
7
|
+
const suffix = [];
|
|
8
|
+
let cursor = normalized;
|
|
9
|
+
while (true) {
|
|
10
|
+
try {
|
|
11
|
+
const real = fs.realpathSync(cursor);
|
|
12
|
+
return suffix.length === 0 ? real : path.join(real, ...suffix);
|
|
13
|
+
} catch (err) {
|
|
14
|
+
if (err?.code !== 'ENOENT') {
|
|
15
|
+
throw err;
|
|
16
|
+
}
|
|
17
|
+
suffix.unshift(path.basename(cursor));
|
|
18
|
+
const parent = path.dirname(cursor);
|
|
19
|
+
if (parent === cursor) {
|
|
20
|
+
throw err;
|
|
21
|
+
}
|
|
22
|
+
cursor = parent;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|