@exodus/react-native-bundle-loader 0.2.0-exodus.1 → 0.2.0-exodus.3

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 CHANGED
@@ -9,7 +9,7 @@ Loads a remote React Native JS bundle, with optional **hash-pinned integrity ver
9
9
 
10
10
  Loading a remote JS bundle is, by construction, remote code execution inside the host app. **This library is intended for internal/development builds only — do not ship it in store builds without an out-of-band, statically-stripped feature flag.** See `SECURITY.md`.
11
11
 
12
- The `loadVerified()` API closes the dominant runtime risk: it fetches the bundle bytes itself, hashes them with `@exodus/crypto`, compares the hash to a caller-supplied digest in constant time, and only then asks the bridge to reload from the verified bytes. Anything that mutates the response between fetch and reload is rejected.
12
+ The `loadVerified()` API closes the dominant runtime risk: it downloads the bundle natively, hashes the bytes with platform crypto (iOS: `CommonCrypto CC_SHA256`, Android: `MessageDigest SHA-256`), compares the hash to a caller-supplied digest in constant time, and only then loads the verified bytes from app-private storage. Anything that mutates the response between fetch and reload is rejected.
13
13
 
14
14
  ## Installation
15
15
 
@@ -23,7 +23,7 @@ iOS:
23
23
  cd ios && pod install
24
24
  ```
25
25
 
26
- Android: `BundleLoaderPackage` is autolinked.
26
+ Android: requires both Gradle wiring and host app changes — see [Android integration](#android-integration) below.
27
27
 
28
28
  ## Usage
29
29
 
@@ -43,11 +43,12 @@ Behavior:
43
43
 
44
44
  - The URL must use the `https:` scheme.
45
45
  - The expected sha256 must be a 64-character hex string.
46
- - The bytes are fetched, hashed in JS using `@exodus/crypto/hash`, and compared to the expected hash with a constant-time comparison.
47
- - On match, the bytes are written to the platform's app-private cache (iOS: `NSTemporaryDirectory()` with `NSDataWritingFileProtectionComplete`; Android: `Context.getCacheDir()`) and the bridge is reloaded from the local file path.
48
- - On mismatch, an error is thrown and the bridge is left untouched.
46
+ - Download, SHA-256 hashing, and constant-time comparison all happen in native code. This avoids the Hermes `RangeError` that JS-side `response.arrayBuffer()` causes on large bundles (≥ ~70 MB).
47
+ - On match, the bytes are written to app-private storage and the bundle is loaded (see platform notes below).
48
+ - On mismatch, an error is thrown and the current bundle is left untouched.
49
+ - The remote bundle is active for **one session only**. The next cold start returns to the local bundle — matching the behaviour consumers expect from a developer preview tool.
49
50
 
50
- Works on iOS and Android. The hash check happens in JS before any native call, so the integrity contract is identical on both platforms.
51
+ Works on iOS and Android.
51
52
 
52
53
  ### Unverified loading
53
54
 
@@ -87,12 +88,105 @@ Example: `https://example.ngrok.io/index.bundle?dev=false&platform=ios&excludeSo
87
88
  | `loadVerified(url, sha256)` | ✅ | ✅ |
88
89
  | `runningMode()` | ✅ | ✅ |
89
90
 
90
- ### How the in-process swap works
91
+ ### How bundle loading works
91
92
 
92
- - **iOS** writes the bundle to `NSTemporaryDirectory()` and sets the bridge's `bundleURL` via KVC (`[bridge setValue:url forKey:@"bundleURL"]`), then calls `[bridge reload]`.
93
- - **Android** writes the bundle to `Context.getCacheDir()`, builds a `JSBundleLoader.createFileLoader(path)`, swaps it into the private `mBundleLoader` field on `ReactInstanceManager` via reflection, and calls `recreateReactContextInBackground()`.
93
+ **iOS** downloads and verifies the bundle natively via `NSURLSession` + `CommonCrypto CC_SHA256`, writes it to `NSTemporaryDirectory()` with `NSDataWritingFileProtectionComplete`, then sets the bridge's `bundleURL` via KVC (`[bridge setValue:url forKey:@"bundleURL"]`) and calls `[bridge reload]`. This is an in-process reload: the old bridge is torn down and a new one is created with the cached file. Because iOS uses ARC, the old bridge's memory (including the Hermes runtime) is freed immediately when the bridge reference is released, before the new runtime allocates — no double-memory peak.
94
94
 
95
- Both mechanisms touch private/internal React Native surface and could break on a major RN upgrade. See `SECURITY.md`. The Android implementation requires the host app to implement `ReactApplication` (the standard React Native template does).
95
+ **Android** uses a process restart instead of an in-process bridge swap. The reason: Android's ART garbage collector is non-deterministic. When a new React context is created alongside an existing one, ART does not guarantee the old Hermes runtime's native heap is freed before the new runtime allocates. On real-world bundle sizes (~50 MB of Hermes bytecode) this causes OOM. The process restart avoids the problem entirely by ensuring only one runtime is ever live.
96
+
97
+ After download and hash verification, the module:
98
+
99
+ 1. Writes the bundle to `Context.getCacheDir()/verified-bundle.jsbundle`.
100
+ 2. Sets a one-shot flag in `SharedPreferences` (`"BundleLoader"` / `"pending_remote_bundle"`), using a synchronous `commit()` so the flag survives the imminent process kill.
101
+ 3. Restarts the process via `startActivity` + `Process.killProcess`.
102
+
103
+ On the next launch, the host app reads the flag, disables Metro (so `ReactInstanceManager` does not query the packager and ignore the file — confirmed necessary by bytecode analysis of RN 0.78), and serves `verified-bundle.jsbundle` as the JS bundle for this session. The flag is consumed on first use so subsequent restarts return to Metro.
104
+
105
+ ## Android integration
106
+
107
+ Because Android requires host app changes that cannot be encapsulated in the module itself, the following manual steps are required.
108
+
109
+ ### 1. Gradle wiring
110
+
111
+ `settings.gradle` — include the subproject conditionally (the module is a `devDependency`; prod CI runs `yarn install --production` and the directory won't exist):
112
+
113
+ ```groovy
114
+ def bundleLoaderDir = new File(rootProject.projectDir, '../node_modules/@exodus/react-native-bundle-loader/android')
115
+ if (bundleLoaderDir.exists()) {
116
+ include ':@exodus_react-native-bundle-loader'
117
+ project(':@exodus_react-native-bundle-loader').projectDir = bundleLoaderDir
118
+ }
119
+ ```
120
+
121
+ `app/build.gradle` — depend only in debug builds:
122
+
123
+ ```groovy
124
+ if (new File("$rootDir/../node_modules/@exodus/react-native-bundle-loader/android").exists()) {
125
+ debugImplementation project(':@exodus_react-native-bundle-loader')
126
+ }
127
+ ```
128
+
129
+ ### 2. Register the package
130
+
131
+ In `MainApplication.java`, inside `getPackages()`, add the package via reflection so a missing module (absent in prod CI) doesn't cause a compile-time error:
132
+
133
+ ```java
134
+ if (BuildConfig.DEBUG) {
135
+ // devDependency absent in prod CI (yarn install --production); reflection avoids a compile-time import
136
+ try {
137
+ packages.add((ReactPackage) Class.forName("com.reactnativebundleloader.BundleLoaderPackage")
138
+ .getDeclaredConstructor().newInstance());
139
+ } catch (ReflectiveOperationException e) {
140
+ throw new RuntimeException(e);
141
+ }
142
+ }
143
+ ```
144
+
145
+ ### 3. Hook bundle loading into ReactNativeHost
146
+
147
+ Add these three methods to your `ReactNativeHost` anonymous subclass in `MainApplication.java`:
148
+
149
+ ```java
150
+ import java.io.File;
151
+
152
+ // ...
153
+
154
+ @Override
155
+ public boolean getUseDeveloperSupport() {
156
+ if (BuildConfig.DEBUG && hasPendingRemoteBundle()) {
157
+ // Must disable dev support: when enabled and Metro is reachable,
158
+ // ReactInstanceManager queries the packager and ignores getJSBundleFile().
159
+ return false;
160
+ }
161
+ // No pending bundle — clear the active flag so runningMode() returns LOCAL.
162
+ getSharedPreferences("BundleLoader", MODE_PRIVATE)
163
+ .edit().remove("active_remote_bundle").apply();
164
+ return BuildConfig.DEBUG;
165
+ }
166
+
167
+ @Override
168
+ protected String getJSBundleFile() {
169
+ if (BuildConfig.DEBUG && hasPendingRemoteBundle()) {
170
+ File cachedBundle = new File(getCacheDir(), "verified-bundle.jsbundle");
171
+ if (cachedBundle.exists()) {
172
+ // Consume the one-shot latch: next restart goes back to Metro.
173
+ getSharedPreferences("BundleLoader", MODE_PRIVATE).edit()
174
+ .remove("pending_remote_bundle")
175
+ .putBoolean("active_remote_bundle", true)
176
+ .apply();
177
+ return cachedBundle.getAbsolutePath();
178
+ }
179
+ }
180
+ return null;
181
+ }
182
+
183
+ private boolean hasPendingRemoteBundle() {
184
+ return getSharedPreferences("BundleLoader", MODE_PRIVATE)
185
+ .getBoolean("pending_remote_bundle", false);
186
+ }
187
+ ```
188
+
189
+ The SharedPreferences keys (`"BundleLoader"`, `"pending_remote_bundle"`, `"active_remote_bundle"`) must match the constants defined in `BundleLoaderModule` (`PREFS_NAME`, `PREFS_PENDING_KEY`, `PREFS_ACTIVE_KEY`).
96
190
 
97
191
  ## Provenance
98
192
 
package/SECURITY.md CHANGED
@@ -15,9 +15,9 @@ This library exists to load and execute a remote JavaScript bundle inside the ho
15
15
 
16
16
  | Surface | Upstream `0.1.0` | This fork |
17
17
  | ------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
18
- | Bundle integrity | None — bridge fetches whatever the URL serves | `loadVerified(url, sha256)` fetches bytes in JS, hashes with `@exodus/crypto`, compares constant-time, only then reloads from disk |
18
+ | Bundle integrity | None — bridge fetches whatever the URL serves | `loadVerified(url, sha256)` downloads bytes natively (iOS: `NSURLSession`, Android: `HttpURLConnection`), hashes with platform crypto (iOS: `CommonCrypto CC_SHA256`, Android: `MessageDigest SHA-256`), compares in constant-time, writes to app-private storage, and reloads the bridge from the local file — closing the TOCTOU window between fetch and load |
19
19
  | `BundlePrompt` default URL | Hardcoded `cdn.jsdelivr.net/gh/jusbrasil/...` (deleted) | Empty — operator must type a URL |
20
- | Scheme enforcement | None — accepts `http://`, `file://`, etc. | `https://` required at the JS boundary; native iOS `load:` re-checks |
20
+ | Scheme enforcement | None — accepts `http://`, `file://`, etc. | `https://` required at the JS boundary; both native `load` implementations re-check before touching the network |
21
21
  | Verified bundle on-disk protection (iOS) | n/a | Written with `NSDataWritingFileProtectionComplete` |
22
22
  | Lockfile | Not shipped | `yarn.lock` committed; `.yarnrc` enforces `--frozen-lockfile` |
23
23
  | Dependency version pinning | Carets (`^`) | All direct deps pinned to exact versions; `.npmrc` `save-exact=true` |
@@ -35,15 +35,15 @@ This library exists to load and execute a remote JavaScript bundle inside the ho
35
35
 
36
36
  - **The bridge `bundleURL` setter is a KVC write** on iOS (`[bridge setValue:url forKey:@"bundleURL"]`) to a non-public RN property. Behavior could change on an RN upgrade and silently no-op the loader.
37
37
  - **The Android bundle swap reflects on a private field.** `ReactInstanceManager.mBundleLoader` has no public setter, so we use `Field.setAccessible(true)` to install a fresh `JSBundleLoader.createFileLoader(...)` before calling `recreateReactContextInBackground()`. The field name has been stable across RN 0.62–0.74 but is not part of the public API; an RN upgrade could rename or remove it, in which case `loadVerified`/`load` will throw `NoSuchFieldException` rather than silently no-op.
38
- - **`@exodus/crypto/hash` runs in JS on the JS thread.** Bundles are typically a few MB; hashing time is acceptable. We deliberately keep hashing in JS so the threat-model contract "Exodus crypto verifies, and the verified bytes are what we hand to native" is auditable in TypeScript and identical on iOS and Android.
39
- - **`timingSafeEqual()` is currently inlined** as a small constant-time XOR loop. The threat model anticipates this moving to a future `@exodus/crypto` export. The inlined version is functionally equivalent and lives in `src/index.tsx`.
38
+ - **Hash verification runs in native code, not JS.** `loadVerifiedFromUrl` uses `CommonCrypto CC_SHA256` (iOS) and `MessageDigest SHA-256` (Android) with a constant-time XOR comparison loop in native code. This avoids a Hermes `RangeError: Maximum regex stack depth reached` that the previous JS-side `response.arrayBuffer()` path hit on bundles ~70 MB. The trade-off is that the integrity contract is no longer auditable as TypeScript.
39
+ - **`timingSafeEqual` is an inlined XOR loop in native code.** Both `ios/BundleLoader.m` and `android/src/main/java/com/reactnativebundleloader/BundleLoaderModule.java` XOR all byte pairs into an accumulator and reject the bundle if the accumulator is non-zero.
40
40
 
41
41
  ## Release process
42
42
 
43
43
  This package has no CI/CD. Maintainers cut releases manually from a developer machine:
44
44
 
45
45
  ```sh
46
- yarn preflight # lint + typecheck + test + verify-pack
46
+ yarn preflight # lint + typecheck + JS tests + Android JVM tests + iOS XCTests + verify-pack
47
47
  npm publish --access public
48
48
  ```
49
49
 
@@ -116,4 +116,7 @@ def reactNativeArtifactVersion = rootProject.ext.has('reactNativeVersion') ? roo
116
116
 
117
117
  dependencies {
118
118
  api "com.facebook.react:react-native:${reactNativeArtifactVersion}"
119
+
120
+ testImplementation 'junit:junit:4.13.2'
121
+ testImplementation 'com.squareup.okhttp3:mockwebserver:4.12.0'
119
122
  }
@@ -1,3 +1,4 @@
1
1
  BundleLoader_compileSdkVersion=33
2
2
  BundleLoader_buildToolsVersion=33.0.2
3
3
  BundleLoader_targetSdkVersion=33
4
+ android.useAndroidX=true
@@ -1,13 +1,13 @@
1
1
  package com.reactnativebundleloader;
2
2
 
3
- import android.util.Base64;
3
+ import android.content.Context;
4
+ import android.content.Intent;
5
+ import android.content.SharedPreferences;
4
6
  import android.util.Log;
5
7
 
6
8
  import androidx.annotation.NonNull;
7
9
 
8
10
  import com.facebook.react.ReactApplication;
9
- import com.facebook.react.ReactInstanceManager;
10
- import com.facebook.react.bridge.JSBundleLoader;
11
11
  import com.facebook.react.bridge.Promise;
12
12
  import com.facebook.react.bridge.ReactApplicationContext;
13
13
  import com.facebook.react.bridge.ReactContextBaseJavaModule;
@@ -17,19 +17,25 @@ import java.io.File;
17
17
  import java.io.FileOutputStream;
18
18
  import java.io.IOException;
19
19
  import java.io.InputStream;
20
- import java.lang.reflect.Field;
21
20
  import java.net.HttpURLConnection;
22
21
  import java.net.URL;
22
+ import java.security.MessageDigest;
23
+ import java.security.NoSuchAlgorithmException;
23
24
 
24
25
  public class BundleLoaderModule extends ReactContextBaseJavaModule {
25
26
 
26
27
  private static final String TAG = "BundleLoader";
27
- private static final String BUNDLE_FILENAME = "verified-bundle.jsbundle";
28
+ // Host app references these as string literals (library is debugImplementation only).
29
+ static final String BUNDLE_FILENAME = "verified-bundle.jsbundle";
30
+ static final String PREFS_NAME = "BundleLoader";
31
+ static final String PREFS_PENDING_KEY = "pending_remote_bundle";
32
+ static final String PREFS_ACTIVE_KEY = "active_remote_bundle";
33
+ // Metro/APK source URL captured at load time for correct asset resolution after restart.
34
+ static final String PREFS_METRO_SOURCE_URL_KEY = "metro_source_url";
35
+
28
36
  private static final int CONNECT_TIMEOUT_MS = 30_000;
29
37
  private static final int READ_TIMEOUT_MS = 30_000;
30
- private static final int MAX_BUNDLE_BYTES = 64 * 1024 * 1024;
31
-
32
- private static volatile boolean remoteLoaded = false;
38
+ static final long MAX_BUNDLE_BYTES = 64L * 1024L * 1024L;
33
39
 
34
40
  BundleLoaderModule(ReactApplicationContext context) {
35
41
  super(context);
@@ -43,7 +49,7 @@ public class BundleLoaderModule extends ReactContextBaseJavaModule {
43
49
 
44
50
  @ReactMethod
45
51
  public void load(final String url) {
46
- if (url == null || !url.startsWith("https://")) {
52
+ if (!isHttps(url)) {
47
53
  Log.e(TAG, "Bundle URL must use the https scheme");
48
54
  return;
49
55
  }
@@ -51,8 +57,19 @@ public class BundleLoaderModule extends ReactContextBaseJavaModule {
51
57
  @Override
52
58
  public void run() {
53
59
  try {
54
- File bundleFile = downloadToCache(url);
55
- swapBundleLoaderAndReload(bundleFile);
60
+ File targetFile = new File(
61
+ getReactApplicationContext().getCacheDir(),
62
+ BUNDLE_FILENAME
63
+ );
64
+ downloadToCache(
65
+ url,
66
+ targetFile,
67
+ CONNECT_TIMEOUT_MS,
68
+ READ_TIMEOUT_MS,
69
+ MAX_BUNDLE_BYTES
70
+ );
71
+ setPendingFlag();
72
+ restartApp();
56
73
  } catch (Exception e) {
57
74
  Log.e(TAG, "load(" + url + ") failed", e);
58
75
  }
@@ -61,92 +78,218 @@ public class BundleLoaderModule extends ReactContextBaseJavaModule {
61
78
  }
62
79
 
63
80
  @ReactMethod
64
- public void loadFromBase64(String base64, Promise promise) {
81
+ public void loadVerifiedFromUrl(final String url, final String expectedSha256, final Promise promise) {
82
+ if (!isHttps(url)) {
83
+ promise.reject("E_INVALID_URL", "Bundle URL must use the https scheme");
84
+ return;
85
+ }
86
+
87
+ final byte[] expectedDigest;
65
88
  try {
66
- byte[] data = Base64.decode(base64, Base64.DEFAULT);
67
- if (data == null || data.length == 0) {
68
- promise.reject("E_INVALID_BASE64", "Invalid base64 input");
69
- return;
70
- }
71
- File bundleFile = new File(
72
- getReactApplicationContext().getCacheDir(),
73
- BUNDLE_FILENAME
74
- );
75
- try (FileOutputStream out = new FileOutputStream(bundleFile)) {
76
- out.write(data);
77
- }
78
- swapBundleLoaderAndReload(bundleFile);
79
- promise.resolve(null);
80
- } catch (Exception e) {
81
- promise.reject("E_LOAD_FAILED", e.getMessage(), e);
89
+ expectedDigest = parseHexSha256(expectedSha256);
90
+ } catch (IllegalArgumentException e) {
91
+ promise.reject("E_INVALID_HASH", e.getMessage());
92
+ return;
82
93
  }
94
+
95
+ new Thread(new Runnable() {
96
+ @Override
97
+ public void run() {
98
+ try {
99
+ File targetFile = new File(
100
+ getReactApplicationContext().getCacheDir(),
101
+ BUNDLE_FILENAME
102
+ );
103
+ byte[] actualDigest = downloadAndHashToCache(
104
+ url,
105
+ targetFile,
106
+ CONNECT_TIMEOUT_MS,
107
+ READ_TIMEOUT_MS,
108
+ MAX_BUNDLE_BYTES
109
+ );
110
+ if (!timingSafeEquals(actualDigest, expectedDigest)) {
111
+ promise.reject("E_HASH_MISMATCH", "Bundle hash mismatch — refusing to load");
112
+ return;
113
+ }
114
+ // Resolve before killing the process so the JS side receives the result.
115
+ promise.resolve(null);
116
+ setPendingFlag();
117
+ restartApp();
118
+ } catch (Exception e) {
119
+ promise.reject("E_LOAD_FAILED", e.getMessage(), e);
120
+ }
121
+ }
122
+ }, "BundleLoader-loadVerifiedFromUrl").start();
83
123
  }
84
124
 
85
125
  @ReactMethod
86
126
  public void runningMode(Promise promise) {
87
- promise.resolve(remoteLoaded ? "REMOTE" : "LOCAL");
127
+ SharedPreferences prefs = getReactApplicationContext()
128
+ .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
129
+ promise.resolve(prefs.getBoolean(PREFS_ACTIVE_KEY, false) ? "REMOTE" : "LOCAL");
130
+ }
131
+
132
+ private void setPendingFlag() {
133
+ SharedPreferences.Editor editor = getReactApplicationContext()
134
+ .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
135
+ .edit()
136
+ .putBoolean(PREFS_PENDING_KEY, true);
137
+
138
+ // Store scriptURL for asset resolution after restart: Metro URL if available,
139
+ // asset:/// otherwise (genesis/release — assets served from APK).
140
+ String sourceUrl = getMetroSourceUrl();
141
+ editor.putString(PREFS_METRO_SOURCE_URL_KEY,
142
+ sourceUrl != null ? sourceUrl : "asset:///index.android.bundle");
143
+
144
+ // commit() not apply() — write must reach disk before killProcess().
145
+ editor.commit();
146
+ }
147
+
148
+ private String getMetroSourceUrl() {
149
+ try {
150
+ ReactApplication app = (ReactApplication) getReactApplicationContext().getApplicationContext();
151
+ String url = app.getReactNativeHost()
152
+ .getReactInstanceManager()
153
+ .getDevSupportManager()
154
+ .getSourceUrl();
155
+ return (url != null && !url.isEmpty()) ? url : null;
156
+ } catch (Exception e) {
157
+ return null;
158
+ }
88
159
  }
89
160
 
90
- private File downloadToCache(String urlString) throws IOException {
161
+ /** Kills and relaunches the process. Avoids running two Hermes runtimes simultaneously. */
162
+ private void restartApp() {
163
+ Context context = getReactApplicationContext();
164
+ Intent intent = context.getPackageManager()
165
+ .getLaunchIntentForPackage(context.getPackageName());
166
+ if (intent != null) {
167
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
168
+ context.startActivity(intent);
169
+ }
170
+ android.os.Process.killProcess(android.os.Process.myPid());
171
+ }
172
+
173
+ /** Package-private for testing. */
174
+ static boolean isHttps(String url) {
175
+ return url != null && url.startsWith("https://");
176
+ }
177
+
178
+ /** Parses a 64-char hex string into a 32-byte digest. Package-private for testing. */
179
+ static byte[] parseHexSha256(String hex) {
180
+ if (hex == null || hex.length() != 64) {
181
+ throw new IllegalArgumentException("Expected SHA-256 must be a 64-character hex string");
182
+ }
183
+ byte[] out = new byte[32];
184
+ for (int i = 0; i < 32; i++) {
185
+ int hi = Character.digit(hex.charAt(i * 2), 16);
186
+ int lo = Character.digit(hex.charAt(i * 2 + 1), 16);
187
+ if (hi < 0 || lo < 0) {
188
+ throw new IllegalArgumentException("Expected SHA-256 contains invalid hex characters");
189
+ }
190
+ out[i] = (byte) ((hi << 4) | lo);
191
+ }
192
+ return out;
193
+ }
194
+
195
+ /** Constant-time equality check to prevent timing attacks. Package-private for testing. */
196
+ static boolean timingSafeEquals(byte[] a, byte[] b) {
197
+ if (a.length != b.length) return false;
198
+ int diff = 0;
199
+ for (int i = 0; i < a.length; i++) {
200
+ diff |= a[i] ^ b[i];
201
+ }
202
+ return diff == 0;
203
+ }
204
+
205
+ /**
206
+ * Downloads into {@code targetFile} and returns its SHA-256 digest.
207
+ * No redirects; non-200 throws; body capped at {@code maxBytes}. Package-private for testing.
208
+ */
209
+ static byte[] downloadAndHashToCache(
210
+ String urlString,
211
+ File targetFile,
212
+ int connectTimeoutMs,
213
+ int readTimeoutMs,
214
+ long maxBytes
215
+ ) throws IOException {
216
+ MessageDigest digest;
217
+ try {
218
+ digest = MessageDigest.getInstance("SHA-256");
219
+ } catch (NoSuchAlgorithmException e) {
220
+ throw new IOException("SHA-256 not available: " + e.getMessage(), e);
221
+ }
222
+
91
223
  URL url = new URL(urlString);
92
224
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
93
- conn.setConnectTimeout(CONNECT_TIMEOUT_MS);
94
- conn.setReadTimeout(READ_TIMEOUT_MS);
95
- // Disallow follow-redirects so an HTTPS URL cannot transparently downgrade to HTTP.
225
+ conn.setConnectTimeout(connectTimeoutMs);
226
+ conn.setReadTimeout(readTimeoutMs);
96
227
  conn.setInstanceFollowRedirects(false);
97
228
  try {
98
229
  int code = conn.getResponseCode();
99
230
  if (code != HttpURLConnection.HTTP_OK) {
100
231
  throw new IOException("Bundle fetch failed: HTTP " + code);
101
232
  }
102
- File file = new File(
103
- getReactApplicationContext().getCacheDir(),
104
- BUNDLE_FILENAME
105
- );
106
233
  long total = 0;
107
234
  try (InputStream in = conn.getInputStream();
108
- FileOutputStream out = new FileOutputStream(file)) {
235
+ FileOutputStream out = new FileOutputStream(targetFile)) {
109
236
  byte[] buf = new byte[8192];
110
237
  int n;
111
238
  while ((n = in.read(buf)) != -1) {
112
239
  total += n;
113
- if (total > MAX_BUNDLE_BYTES) {
114
- throw new IOException(
115
- "Bundle exceeds " + MAX_BUNDLE_BYTES + " bytes"
116
- );
240
+ if (total > maxBytes) {
241
+ throw new IOException("Bundle exceeds " + maxBytes + " bytes");
117
242
  }
118
243
  out.write(buf, 0, n);
244
+ digest.update(buf, 0, n);
119
245
  }
120
246
  }
121
- return file;
247
+ return digest.digest();
122
248
  } finally {
123
249
  conn.disconnect();
124
250
  }
125
251
  }
126
252
 
127
- private void swapBundleLoaderAndReload(File bundleFile) throws Exception {
128
- ReactApplication app = (ReactApplication)
129
- getReactApplicationContext().getApplicationContext();
130
- final ReactInstanceManager instanceManager =
131
- app.getReactNativeHost().getReactInstanceManager();
132
-
133
- JSBundleLoader bundleLoader =
134
- JSBundleLoader.createFileLoader(bundleFile.getAbsolutePath());
135
-
136
- // mBundleLoader is private on ReactInstanceManager and there is no public
137
- // setter. The host app's ReactNativeHost wires the initial loader at
138
- // construction; we swap it in-place so the next reload picks up our file.
139
- Field field = ReactInstanceManager.class.getDeclaredField("mBundleLoader");
140
- field.setAccessible(true);
141
- field.set(instanceManager, bundleLoader);
142
-
143
- remoteLoaded = true;
144
-
145
- getReactApplicationContext().runOnUiQueueThread(new Runnable() {
146
- @Override
147
- public void run() {
148
- instanceManager.recreateReactContextInBackground();
253
+ /**
254
+ * Downloads into {@code targetFile}. No redirects; non-200 throws; body capped at
255
+ * {@code maxBytes}. Package-private for testing.
256
+ */
257
+ static File downloadToCache(
258
+ String urlString,
259
+ File targetFile,
260
+ int connectTimeoutMs,
261
+ int readTimeoutMs,
262
+ long maxBytes
263
+ ) throws IOException {
264
+ URL url = new URL(urlString);
265
+ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
266
+ conn.setConnectTimeout(connectTimeoutMs);
267
+ conn.setReadTimeout(readTimeoutMs);
268
+ // Disallow follow-redirects so an HTTPS URL cannot transparently downgrade to HTTP.
269
+ conn.setInstanceFollowRedirects(false);
270
+ try {
271
+ int code = conn.getResponseCode();
272
+ if (code != HttpURLConnection.HTTP_OK) {
273
+ throw new IOException("Bundle fetch failed: HTTP " + code);
274
+ }
275
+ long total = 0;
276
+ try (InputStream in = conn.getInputStream();
277
+ FileOutputStream out = new FileOutputStream(targetFile)) {
278
+ byte[] buf = new byte[8192];
279
+ int n;
280
+ while ((n = in.read(buf)) != -1) {
281
+ total += n;
282
+ if (total > maxBytes) {
283
+ throw new IOException(
284
+ "Bundle exceeds " + maxBytes + " bytes"
285
+ );
286
+ }
287
+ out.write(buf, 0, n);
288
+ }
149
289
  }
150
- });
290
+ return targetFile;
291
+ } finally {
292
+ conn.disconnect();
293
+ }
151
294
  }
152
295
  }
@@ -1,6 +1,9 @@
1
1
  #import <React/RCTBridgeModule.h>
2
2
  #import <React/RCTRootView.h>
3
3
 
4
+ // NSUserDefaults key storing the pending remote bundle URL for loadSourceForBridge:.
5
+ extern NSString * const RNBundleLoaderPendingURLKey;
6
+
4
7
  @interface BundleLoader : NSObject <RCTBridgeModule>
5
8
 
6
9
  @end
@@ -1,4 +1,7 @@
1
1
  #import "BundleLoader.h"
2
+ #import <CommonCrypto/CommonDigest.h>
3
+
4
+ NSString * const RNBundleLoaderPendingURLKey = @"RNBundleLoaderPendingURL";
2
5
 
3
6
  @implementation BundleLoader
4
7
 
@@ -8,16 +11,16 @@ RCT_EXPORT_MODULE()
8
11
 
9
12
  - (void)setBundleURLAndReload:(NSURL *)url
10
13
  {
11
- [_bridge setValue:url forKey:@"bundleURL"];
14
+ [[NSUserDefaults standardUserDefaults] setURL:url forKey:RNBundleLoaderPendingURLKey];
15
+ [[NSUserDefaults standardUserDefaults] synchronize];
12
16
  [_bridge reload];
13
17
  }
14
18
 
15
19
  RCT_EXPORT_METHOD(runningMode:(RCTPromiseResolveBlock)resolve
16
20
  rejecter:(RCTPromiseRejectBlock)reject)
17
21
  {
18
- NSString *scheme = [[_bridge bundleURL] scheme];
19
- BOOL isRemote = [scheme isEqualToString:@"https"];
20
- resolve(isRemote ? @"REMOTE" : @"LOCAL");
22
+ NSURL *pending = [[NSUserDefaults standardUserDefaults] URLForKey:RNBundleLoaderPendingURLKey];
23
+ resolve(pending ? @"REMOTE" : @"LOCAL");
21
24
  }
22
25
 
23
26
  RCT_EXPORT_METHOD(load:(NSURL *)url)
@@ -30,32 +33,92 @@ RCT_EXPORT_METHOD(load:(NSURL *)url)
30
33
  });
31
34
  }
32
35
 
33
- RCT_EXPORT_METHOD(loadFromBase64:(NSString *)base64
36
+ // Downloads the bundle at `urlString`, verifies its SHA-256 digest against
37
+ // `expectedHex` using a constant-time byte comparison, then writes it to the
38
+ // sandbox temp directory and reloads the bridge — all in native code to avoid
39
+ // the Hermes RangeError that JS-side response.arrayBuffer() causes on large
40
+ // bundles (~70 MB+).
41
+ RCT_EXPORT_METHOD(loadVerifiedFromUrl:(NSString *)urlString
42
+ expectedSha256:(NSString *)expectedHex
34
43
  resolver:(RCTPromiseResolveBlock)resolve
35
44
  rejecter:(RCTPromiseRejectBlock)reject)
36
45
  {
37
- NSData *data = [[NSData alloc] initWithBase64EncodedString:base64
38
- options:0];
39
- if (data == nil) {
40
- reject(@"E_INVALID_BASE64", @"Invalid base64 input", nil);
46
+ NSURL *url = [NSURL URLWithString:urlString];
47
+ if (![[url scheme] isEqualToString:@"https"]) {
48
+ reject(@"E_INVALID_URL", @"Bundle URL must use the https scheme", nil);
41
49
  return;
42
50
  }
43
51
 
44
- NSString *path = [NSTemporaryDirectory()
45
- stringByAppendingPathComponent:@"verified-bundle.jsbundle"];
46
- NSError *err = nil;
47
- if (![data writeToFile:path
48
- options:NSDataWritingAtomic | NSDataWritingFileProtectionComplete
49
- error:&err]) {
50
- reject(@"E_WRITE_FAILED", err.localizedDescription, err);
52
+ if (expectedHex.length != 64) {
53
+ reject(@"E_INVALID_HASH", @"Expected SHA-256 must be a 64-character hex string", nil);
51
54
  return;
52
55
  }
53
56
 
54
- NSURL *fileURL = [NSURL fileURLWithPath:path];
55
- dispatch_async(dispatch_get_main_queue(), ^{
56
- [self setBundleURLAndReload:fileURL];
57
- resolve(nil);
58
- });
57
+ // Parse hex string to raw bytes up-front so we can reject early on bad input.
58
+ const char *cStr = [expectedHex UTF8String];
59
+ uint8_t expectedDigestBuf[CC_SHA256_DIGEST_LENGTH];
60
+ for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
61
+ char buf[3] = { cStr[i * 2], cStr[i * 2 + 1], '\0' };
62
+ char *end;
63
+ unsigned long val = strtoul(buf, &end, 16);
64
+ if (end != buf + 2) {
65
+ reject(@"E_INVALID_HASH", @"Expected SHA-256 contains invalid hex characters", nil);
66
+ return;
67
+ }
68
+ expectedDigestBuf[i] = (uint8_t)val;
69
+ }
70
+ // Wrap in NSData so the block can capture it as an object pointer.
71
+ NSData *expectedData = [NSData dataWithBytes:expectedDigestBuf length:CC_SHA256_DIGEST_LENGTH];
72
+
73
+ NSURLSessionDataTask *task = [[NSURLSession sharedSession]
74
+ dataTaskWithURL:url
75
+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
76
+ if (error) {
77
+ reject(@"E_FETCH_FAILED", error.localizedDescription, error);
78
+ return;
79
+ }
80
+
81
+ NSHTTPURLResponse *http = (NSHTTPURLResponse *)response;
82
+ if (http.statusCode < 200 || http.statusCode >= 300) {
83
+ reject(@"E_FETCH_FAILED",
84
+ [NSString stringWithFormat:@"Bundle fetch failed: HTTP %ld", (long)http.statusCode],
85
+ nil);
86
+ return;
87
+ }
88
+
89
+ // Compute SHA-256 of the downloaded bytes.
90
+ uint8_t actualDigest[CC_SHA256_DIGEST_LENGTH];
91
+ CC_SHA256(data.bytes, (CC_LONG)data.length, actualDigest);
92
+
93
+ // Constant-time comparison: XOR all byte pairs and check the accumulator.
94
+ const uint8_t *expected = (const uint8_t *)expectedData.bytes;
95
+ uint8_t diff = 0;
96
+ for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
97
+ diff |= actualDigest[i] ^ expected[i];
98
+ }
99
+ if (diff != 0) {
100
+ reject(@"E_HASH_MISMATCH", @"Bundle hash mismatch — refusing to load", nil);
101
+ return;
102
+ }
103
+
104
+ NSString *path = [NSTemporaryDirectory()
105
+ stringByAppendingPathComponent:@"verified-bundle.jsbundle"];
106
+ NSError *writeError = nil;
107
+ if (![data writeToFile:path
108
+ options:NSDataWritingAtomic | NSDataWritingFileProtectionComplete
109
+ error:&writeError]) {
110
+ reject(@"E_WRITE_FAILED", writeError.localizedDescription, writeError);
111
+ return;
112
+ }
113
+
114
+ NSURL *fileURL = [NSURL fileURLWithPath:path];
115
+ dispatch_async(dispatch_get_main_queue(), ^{
116
+ [self setBundleURLAndReload:fileURL];
117
+ resolve(nil);
118
+ });
119
+ }];
120
+
121
+ [task resume];
59
122
  }
60
123
 
61
124
  @end
@@ -7,9 +7,11 @@
7
7
  objects = {
8
8
 
9
9
  /* Begin PBXBuildFile section */
10
-
11
-
10
+ 24CE545938292C60A5CCE9C6 /* BundleLoader.m in Sources */ = {isa = PBXBuildFile; fileRef = D86256900CD7CE9D4230C8F0 /* BundleLoader.m */; };
12
11
  5E555C0D2413F4C50049A1A2 /* BundleLoader.mm in Sources */ = {isa = PBXBuildFile; fileRef = B3E7B5891CC2AC0600A0062D /* BundleLoader.mm */; };
12
+ 92B2598D965DC32AAF3C04DC /* RCTShim.m in Sources */ = {isa = PBXBuildFile; fileRef = 57BC896F9AB3CF10CC9A982D /* RCTShim.m */; };
13
+ B69ED17115D9C485D9548941 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8D436DEAC2A4CBEA60395C01 /* Foundation.framework */; };
14
+ E40411861DEA09400E90C294 /* BundleLoaderTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 652EEA1023B3EC9464EE6AB7 /* BundleLoaderTests.m */; };
13
15
  /* End PBXBuildFile section */
14
16
 
15
17
  /* Begin PBXCopyFilesBuildPhase section */
@@ -26,14 +28,25 @@
26
28
 
27
29
  /* Begin PBXFileReference section */
28
30
  134814201AA4EA6300B7C361 /* libBundleLoader.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libBundleLoader.a; sourceTree = BUILT_PRODUCTS_DIR; };
29
-
30
-
31
+ 41DDBD47E9DE312B7A311653 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
32
+ 57BC896F9AB3CF10CC9A982D /* RCTShim.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = RCTShim.m; sourceTree = "<group>"; };
33
+ 652EEA1023B3EC9464EE6AB7 /* BundleLoaderTests.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = BundleLoaderTests.m; sourceTree = "<group>"; };
34
+ 8D436DEAC2A4CBEA60395C01 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS18.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; };
35
+ A2704714B0CBE9056A0C7575 /* BundleLoaderTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = BundleLoaderTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
31
36
  B3E7B5881CC2AC0600A0062D /* BundleLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BundleLoader.h; sourceTree = "<group>"; };
32
37
  B3E7B5891CC2AC0600A0062D /* BundleLoader.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = BundleLoader.mm; sourceTree = "<group>"; };
33
-
38
+ D86256900CD7CE9D4230C8F0 /* BundleLoader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = BundleLoader.m; path = ../BundleLoader.m; sourceTree = "<group>"; };
34
39
  /* End PBXFileReference section */
35
40
 
36
41
  /* Begin PBXFrameworksBuildPhase section */
42
+ 4B47E8930D88164ED0964EE4 /* Frameworks */ = {
43
+ isa = PBXFrameworksBuildPhase;
44
+ buildActionMask = 2147483647;
45
+ files = (
46
+ B69ED17115D9C485D9548941 /* Foundation.framework in Frameworks */,
47
+ );
48
+ runOnlyForDeploymentPostprocessing = 0;
49
+ };
37
50
  58B511D81A9E6C8500147676 /* Frameworks */ = {
38
51
  isa = PBXFrameworksBuildPhase;
39
52
  buildActionMask = 2147483647;
@@ -44,6 +57,14 @@
44
57
  /* End PBXFrameworksBuildPhase section */
45
58
 
46
59
  /* Begin PBXGroup section */
60
+ 0ED20A3ECAA42A9D0C0DF4B7 /* Frameworks */ = {
61
+ isa = PBXGroup;
62
+ children = (
63
+ 84C5FDD66827346FEB6301E0 /* iOS */,
64
+ );
65
+ name = Frameworks;
66
+ sourceTree = "<group>";
67
+ };
47
68
  134814211AA4EA7D00B7C361 /* Products */ = {
48
69
  isa = PBXGroup;
49
70
  children = (
@@ -55,15 +76,35 @@
55
76
  58B511D21A9E6C8500147676 = {
56
77
  isa = PBXGroup;
57
78
  children = (
58
-
59
-
60
79
  B3E7B5881CC2AC0600A0062D /* BundleLoader.h */,
61
80
  B3E7B5891CC2AC0600A0062D /* BundleLoader.mm */,
62
-
63
81
  134814211AA4EA7D00B7C361 /* Products */,
82
+ 8561C764A29C0D1EEB7A96AF /* BundleLoaderTests */,
83
+ A2704714B0CBE9056A0C7575 /* BundleLoaderTests.xctest */,
84
+ 0ED20A3ECAA42A9D0C0DF4B7 /* Frameworks */,
64
85
  );
65
86
  sourceTree = "<group>";
66
87
  };
88
+ 84C5FDD66827346FEB6301E0 /* iOS */ = {
89
+ isa = PBXGroup;
90
+ children = (
91
+ 8D436DEAC2A4CBEA60395C01 /* Foundation.framework */,
92
+ );
93
+ name = iOS;
94
+ sourceTree = "<group>";
95
+ };
96
+ 8561C764A29C0D1EEB7A96AF /* BundleLoaderTests */ = {
97
+ isa = PBXGroup;
98
+ children = (
99
+ D86256900CD7CE9D4230C8F0 /* BundleLoader.m */,
100
+ 652EEA1023B3EC9464EE6AB7 /* BundleLoaderTests.m */,
101
+ 57BC896F9AB3CF10CC9A982D /* RCTShim.m */,
102
+ 41DDBD47E9DE312B7A311653 /* Info.plist */,
103
+ );
104
+ name = BundleLoaderTests;
105
+ path = BundleLoaderTests;
106
+ sourceTree = "<group>";
107
+ };
67
108
  /* End PBXGroup section */
68
109
 
69
110
  /* Begin PBXNativeTarget section */
@@ -84,6 +125,24 @@
84
125
  productReference = 134814201AA4EA6300B7C361 /* libBundleLoader.a */;
85
126
  productType = "com.apple.product-type.library.static";
86
127
  };
128
+ 907A5308750D4F32A1FEED66 /* BundleLoaderTests */ = {
129
+ isa = PBXNativeTarget;
130
+ buildConfigurationList = F1BFF3F804D83A453070B922 /* Build configuration list for PBXNativeTarget "BundleLoaderTests" */;
131
+ buildPhases = (
132
+ A1532518EC7CA226B14679F7 /* Generate React header shim */,
133
+ B462B17BA89D4AE0FF1ECED6 /* Sources */,
134
+ 4B47E8930D88164ED0964EE4 /* Frameworks */,
135
+ 0E0C7AEDC338098073E25692 /* Resources */,
136
+ );
137
+ buildRules = (
138
+ );
139
+ dependencies = (
140
+ );
141
+ name = BundleLoaderTests;
142
+ productName = BundleLoaderTests;
143
+ productReference = A2704714B0CBE9056A0C7575 /* BundleLoaderTests.xctest */;
144
+ productType = "com.apple.product-type.bundle.unit-test";
145
+ };
87
146
  /* End PBXNativeTarget section */
88
147
 
89
148
  /* Begin PBXProject section */
@@ -112,19 +171,58 @@
112
171
  projectRoot = "";
113
172
  targets = (
114
173
  58B511DA1A9E6C8500147676 /* BundleLoader */,
174
+ 907A5308750D4F32A1FEED66 /* BundleLoaderTests */,
115
175
  );
116
176
  };
117
177
  /* End PBXProject section */
118
178
 
179
+ /* Begin PBXResourcesBuildPhase section */
180
+ 0E0C7AEDC338098073E25692 /* Resources */ = {
181
+ isa = PBXResourcesBuildPhase;
182
+ buildActionMask = 2147483647;
183
+ files = (
184
+ );
185
+ runOnlyForDeploymentPostprocessing = 0;
186
+ };
187
+ /* End PBXResourcesBuildPhase section */
188
+
189
+ /* Begin PBXShellScriptBuildPhase section */
190
+ A1532518EC7CA226B14679F7 /* Generate React header shim */ = {
191
+ isa = PBXShellScriptBuildPhase;
192
+ buildActionMask = 2147483647;
193
+ files = (
194
+ );
195
+ inputFileListPaths = (
196
+ );
197
+ inputPaths = (
198
+ );
199
+ name = "Generate React header shim";
200
+ outputFileListPaths = (
201
+ );
202
+ outputPaths = (
203
+ );
204
+ runOnlyForDeploymentPostprocessing = 0;
205
+ shellPath = /bin/sh;
206
+ shellScript = "#!/bin/bash\nset -euo pipefail\nRN_HEADERS_ROOT=\"${SRCROOT}/../node_modules/react-native/React\"\nOUT=\"${DERIVED_FILE_DIR}/RNHeaders/React\"\nmkdir -p \"$OUT\"\nif [ ! -d \"$RN_HEADERS_ROOT\" ]; then\n echo \"error: react-native headers not found at $RN_HEADERS_ROOT\" >&2\n exit 1\nfi\n# Flatten every .h under React/{Base,Modules,...} into the shim dir as symlinks.\nfind \"$RN_HEADERS_ROOT\" -type f -name '*.h' | while read -r f; do\n name=$(basename \"$f\")\n # Only link the first occurrence we encounter -- duplicates would error otherwise.\n if [ ! -e \"$OUT/$name\" ]; then\n ln -sf \"$f\" \"$OUT/$name\"\n fi\ndone\n";
207
+ };
208
+ /* End PBXShellScriptBuildPhase section */
209
+
119
210
  /* Begin PBXSourcesBuildPhase section */
120
211
  58B511D71A9E6C8500147676 /* Sources */ = {
121
212
  isa = PBXSourcesBuildPhase;
122
213
  buildActionMask = 2147483647;
123
214
  files = (
124
-
125
-
126
215
  5E555C0D2413F4C50049A1A2 /* BundleLoader.mm in Sources */,
127
-
216
+ );
217
+ runOnlyForDeploymentPostprocessing = 0;
218
+ };
219
+ B462B17BA89D4AE0FF1ECED6 /* Sources */ = {
220
+ isa = PBXSourcesBuildPhase;
221
+ buildActionMask = 2147483647;
222
+ files = (
223
+ 24CE545938292C60A5CCE9C6 /* BundleLoader.m in Sources */,
224
+ E40411861DEA09400E90C294 /* BundleLoaderTests.m in Sources */,
225
+ 92B2598D965DC32AAF3C04DC /* RCTShim.m in Sources */,
128
226
  );
129
227
  runOnlyForDeploymentPostprocessing = 0;
130
228
  };
@@ -237,7 +335,6 @@
237
335
  OTHER_LDFLAGS = "-ObjC";
238
336
  PRODUCT_NAME = BundleLoader;
239
337
  SKIP_INSTALL = YES;
240
-
241
338
  };
242
339
  name = Debug;
243
340
  };
@@ -254,7 +351,63 @@
254
351
  OTHER_LDFLAGS = "-ObjC";
255
352
  PRODUCT_NAME = BundleLoader;
256
353
  SKIP_INSTALL = YES;
257
-
354
+ };
355
+ name = Release;
356
+ };
357
+ 6B16E681D8B4E49389D63BCC /* Debug */ = {
358
+ isa = XCBuildConfiguration;
359
+ buildSettings = {
360
+ ALWAYS_SEARCH_USER_PATHS = NO;
361
+ CLANG_ENABLE_MODULES = YES;
362
+ CLANG_ENABLE_OBJC_ARC = YES;
363
+ CLANG_ENABLE_OBJC_WEAK = NO;
364
+ GCC_PREPROCESSOR_DEFINITIONS = (
365
+ "DEBUG=1",
366
+ "$(inherited)",
367
+ );
368
+ GCC_WARN_INHIBIT_ALL_WARNINGS = NO;
369
+ GENERATE_INFOPLIST_FILE = NO;
370
+ HEADER_SEARCH_PATHS = (
371
+ "$(inherited)",
372
+ "$(SRCROOT)",
373
+ "$(DERIVED_FILE_DIR)/RNHeaders",
374
+ );
375
+ INFOPLIST_FILE = BundleLoaderTests/Info.plist;
376
+ IPHONEOS_DEPLOYMENT_TARGET = 13.0;
377
+ ONLY_ACTIVE_ARCH = YES;
378
+ PRODUCT_BUNDLE_IDENTIFIER = "com.exodus.react-native-bundle-loader.tests";
379
+ PRODUCT_NAME = "$(TARGET_NAME)";
380
+ SDKROOT = iphoneos;
381
+ SUPPORTED_PLATFORMS = "iphonesimulator iphoneos";
382
+ TARGETED_DEVICE_FAMILY = "1,2";
383
+ USE_HEADERMAP = YES;
384
+ };
385
+ name = Debug;
386
+ };
387
+ DEB50DA86E5EBCD7FE39B7FF /* Release */ = {
388
+ isa = XCBuildConfiguration;
389
+ buildSettings = {
390
+ ALWAYS_SEARCH_USER_PATHS = NO;
391
+ CLANG_ENABLE_MODULES = YES;
392
+ CLANG_ENABLE_OBJC_ARC = YES;
393
+ CLANG_ENABLE_OBJC_WEAK = NO;
394
+ GCC_WARN_INHIBIT_ALL_WARNINGS = NO;
395
+ GENERATE_INFOPLIST_FILE = NO;
396
+ HEADER_SEARCH_PATHS = (
397
+ "$(inherited)",
398
+ "$(SRCROOT)",
399
+ "$(DERIVED_FILE_DIR)/RNHeaders",
400
+ );
401
+ INFOPLIST_FILE = BundleLoaderTests/Info.plist;
402
+ IPHONEOS_DEPLOYMENT_TARGET = 13.0;
403
+ ONLY_ACTIVE_ARCH = YES;
404
+ PRODUCT_BUNDLE_IDENTIFIER = "com.exodus.react-native-bundle-loader.tests";
405
+ PRODUCT_NAME = "$(TARGET_NAME)";
406
+ SDKROOT = iphoneos;
407
+ SUPPORTED_PLATFORMS = "iphonesimulator iphoneos";
408
+ TARGETED_DEVICE_FAMILY = "1,2";
409
+ USE_HEADERMAP = YES;
410
+ VALIDATE_PRODUCT = YES;
258
411
  };
259
412
  name = Release;
260
413
  };
@@ -279,6 +432,15 @@
279
432
  defaultConfigurationIsVisible = 0;
280
433
  defaultConfigurationName = Release;
281
434
  };
435
+ F1BFF3F804D83A453070B922 /* Build configuration list for PBXNativeTarget "BundleLoaderTests" */ = {
436
+ isa = XCConfigurationList;
437
+ buildConfigurations = (
438
+ DEB50DA86E5EBCD7FE39B7FF /* Release */,
439
+ 6B16E681D8B4E49389D63BCC /* Debug */,
440
+ );
441
+ defaultConfigurationIsVisible = 0;
442
+ defaultConfigurationName = Release;
443
+ };
282
444
  /* End XCConfigurationList section */
283
445
  };
284
446
  rootObject = 58B511D31A9E6C8500147676 /* Project object */;
@@ -11,12 +11,6 @@ var _react = _interopRequireWildcard(require("react"));
11
11
 
12
12
  var _reactNative = require("react-native");
13
13
 
14
- var _hash = require("@exodus/crypto/hash");
15
-
16
- var _hex = require("@exodus/bytes/hex.js");
17
-
18
- var _base = require("@exodus/bytes/base64.js");
19
-
20
14
  function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
21
15
 
22
16
  function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
@@ -42,18 +36,6 @@ function assertSafeUrl(url) {
42
36
  }
43
37
  }
44
38
 
45
- function timingSafeEqualBytes(a, b) {
46
- if (a.length !== b.length) return false;
47
- let diff = 0;
48
- /* eslint-disable no-bitwise */
49
-
50
- for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
51
- /* eslint-enable no-bitwise */
52
-
53
-
54
- return diff === 0;
55
- }
56
-
57
39
  async function loadVerified(url, expectedSha256Hex) {
58
40
  assertSafeUrl(url);
59
41
 
@@ -61,28 +43,13 @@ async function loadVerified(url, expectedSha256Hex) {
61
43
  throw new Error('Expected sha256 must be a 64-character hex string');
62
44
  }
63
45
 
64
- const expected = (0, _hex.fromHex)(expectedSha256Hex);
65
- const response = await fetch(url);
66
-
67
- if (!response.ok) {
68
- throw new Error("Bundle fetch failed: HTTP ".concat(response.status));
69
- }
70
-
71
- const buffer = await response.arrayBuffer();
72
- const bytes = new Uint8Array(buffer);
73
- const actual = await (0, _hash.hash)('sha256', bytes, 'uint8');
74
-
75
- if (!timingSafeEqualBytes(actual, expected)) {
76
- throw new Error('Bundle hash mismatch — refusing to load');
77
- }
78
-
79
46
  const native = getNative();
80
47
 
81
- if (typeof native.loadFromBase64 !== 'function') {
82
- throw new Error('Native loadFromBase64 not available. Rebuild the host app after upgrading.');
48
+ if (typeof native.loadVerifiedFromUrl !== 'function') {
49
+ throw new Error('loadVerifiedFromUrl is not available on this platform. Rebuild the host app with the latest native module.');
83
50
  }
84
51
 
85
- await native.loadFromBase64((0, _base.toBase64)(bytes));
52
+ await native.loadVerifiedFromUrl(url, expectedSha256Hex);
86
53
  }
87
54
 
88
55
  function loadUnverified(url) {
@@ -1,9 +1,6 @@
1
1
  /** @format */
2
2
  import React, { useCallback, useState } from 'react';
3
3
  import { Alert, Modal, NativeModules, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
4
- import { hash } from '@exodus/crypto/hash';
5
- import { fromHex } from '@exodus/bytes/hex.js';
6
- import { toBase64 } from '@exodus/bytes/base64.js';
7
4
 
8
5
  function getNative() {
9
6
  const m = NativeModules.BundleLoader;
@@ -25,18 +22,6 @@ function assertSafeUrl(url) {
25
22
  }
26
23
  }
27
24
 
28
- function timingSafeEqualBytes(a, b) {
29
- if (a.length !== b.length) return false;
30
- let diff = 0;
31
- /* eslint-disable no-bitwise */
32
-
33
- for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
34
- /* eslint-enable no-bitwise */
35
-
36
-
37
- return diff === 0;
38
- }
39
-
40
25
  export async function loadVerified(url, expectedSha256Hex) {
41
26
  assertSafeUrl(url);
42
27
 
@@ -44,28 +29,13 @@ export async function loadVerified(url, expectedSha256Hex) {
44
29
  throw new Error('Expected sha256 must be a 64-character hex string');
45
30
  }
46
31
 
47
- const expected = fromHex(expectedSha256Hex);
48
- const response = await fetch(url);
49
-
50
- if (!response.ok) {
51
- throw new Error("Bundle fetch failed: HTTP ".concat(response.status));
52
- }
53
-
54
- const buffer = await response.arrayBuffer();
55
- const bytes = new Uint8Array(buffer);
56
- const actual = await hash('sha256', bytes, 'uint8');
57
-
58
- if (!timingSafeEqualBytes(actual, expected)) {
59
- throw new Error('Bundle hash mismatch — refusing to load');
60
- }
61
-
62
32
  const native = getNative();
63
33
 
64
- if (typeof native.loadFromBase64 !== 'function') {
65
- throw new Error('Native loadFromBase64 not available. Rebuild the host app after upgrading.');
34
+ if (typeof native.loadVerifiedFromUrl !== 'function') {
35
+ throw new Error('loadVerifiedFromUrl is not available on this platform. Rebuild the host app with the latest native module.');
66
36
  }
67
37
 
68
- await native.loadFromBase64(toBase64(bytes));
38
+ await native.loadVerifiedFromUrl(url, expectedSha256Hex);
69
39
  }
70
40
 
71
41
  function loadUnverified(url) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/react-native-bundle-loader",
3
- "version": "0.2.0-exodus.1",
3
+ "version": "0.2.0-exodus.3",
4
4
  "description": "Loads a remote React Native JS bundle.",
5
5
  "main": "lib/commonjs/index",
6
6
  "module": "lib/module/index",
@@ -40,11 +40,13 @@
40
40
  ],
41
41
  "scripts": {
42
42
  "test": "jest",
43
+ "test:android": "cd android && ./gradlew test",
44
+ "test:ios": "xcodebuild test -project ios/BundleLoader.xcodeproj -scheme BundleLoaderTests -destination 'platform=iOS Simulator,OS=18.4,name=iPhone 16' CODE_SIGNING_ALLOWED=NO -quiet",
43
45
  "typescript": "tsc --noEmit",
44
46
  "lint": "eslint \"**/*.{js,ts,tsx}\"",
45
47
  "prepare": "bob build",
46
48
  "verify-pack": "rm -rf _pack && mkdir _pack && yarn prepare && npm pack --pack-destination _pack && tar -tzf _pack/*.tgz | LC_ALL=C sort | sed 's|^package/||' | diff -u .npm-tarball-allowlist -",
47
- "preflight": "yarn lint && yarn typescript && yarn test --ci --runInBand && yarn verify-pack"
49
+ "preflight": "yarn lint && yarn typescript && yarn test --ci --runInBand && yarn test:android && yarn test:ios && yarn verify-pack"
48
50
  },
49
51
  "engines": {
50
52
  "node": ">=18.18"
@@ -74,10 +76,7 @@
74
76
  "url": "https://github.com/ExodusForks/react-native-bundle-loader/issues"
75
77
  },
76
78
  "homepage": "https://github.com/ExodusForks/react-native-bundle-loader#readme",
77
- "dependencies": {
78
- "@exodus/bytes": "1.15.0",
79
- "@exodus/crypto": "1.0.0-rc.34"
80
- },
79
+ "dependencies": {},
81
80
  "devDependencies": {
82
81
  "@react-native-community/bob": "0.16.2",
83
82
  "@react-native-community/eslint-config": "2.0.0",
@@ -14,6 +14,11 @@ Pod::Spec.new do |s|
14
14
  s.source = { :git => "https://github.com/ExodusForks/react-native-bundle-loader.git", :tag => "v#{s.version}" }
15
15
 
16
16
  s.source_files = "ios/**/*.{h,m,mm}"
17
+ # Exclude unit-test sources so consumers don't get test code in their app.
18
+ # Note: npm consumers never see these files (the package.json `files`
19
+ # allowlist excludes `ios/BundleLoaderTests/`); this guard is for
20
+ # CocoaPods consumers that fetch from git.
21
+ s.exclude_files = "ios/BundleLoaderTests/**/*"
17
22
 
18
23
  s.dependency "React-Core"
19
24
  end
package/src/index.tsx CHANGED
@@ -12,15 +12,12 @@ import {
12
12
  TouchableOpacity,
13
13
  View,
14
14
  } from 'react-native';
15
- import { hash } from '@exodus/crypto/hash';
16
- import { fromHex } from '@exodus/bytes/hex.js';
17
- import { toBase64 } from '@exodus/bytes/base64.js';
18
15
 
19
16
  export type RunningMode = 'LOCAL' | 'REMOTE';
20
17
 
21
18
  type NativeBundleLoader = {
22
19
  load(url: string): void;
23
- loadFromBase64?(base64: string): Promise<void>;
20
+ loadVerifiedFromUrl?(url: string, sha256: string): Promise<void>;
24
21
  runningMode(): Promise<RunningMode>;
25
22
  };
26
23
 
@@ -46,15 +43,6 @@ function assertSafeUrl(url: string): void {
46
43
  }
47
44
  }
48
45
 
49
- function timingSafeEqualBytes(a: Uint8Array, b: Uint8Array): boolean {
50
- if (a.length !== b.length) return false;
51
- let diff = 0;
52
- /* eslint-disable no-bitwise */
53
- for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
54
- /* eslint-enable no-bitwise */
55
- return diff === 0;
56
- }
57
-
58
46
  export async function loadVerified(
59
47
  url: string,
60
48
  expectedSha256Hex: string
@@ -66,27 +54,16 @@ export async function loadVerified(
66
54
  ) {
67
55
  throw new Error('Expected sha256 must be a 64-character hex string');
68
56
  }
69
- const expected = fromHex(expectedSha256Hex);
70
-
71
- const response = await fetch(url);
72
- if (!response.ok) {
73
- throw new Error(`Bundle fetch failed: HTTP ${response.status}`);
74
- }
75
- const buffer = await response.arrayBuffer();
76
- const bytes = new Uint8Array(buffer);
77
- const actual = await hash('sha256', bytes, 'uint8');
78
-
79
- if (!timingSafeEqualBytes(actual, expected)) {
80
- throw new Error('Bundle hash mismatch — refusing to load');
81
- }
82
57
 
83
58
  const native = getNative();
84
- if (typeof native.loadFromBase64 !== 'function') {
59
+
60
+ if (typeof native.loadVerifiedFromUrl !== 'function') {
85
61
  throw new Error(
86
- 'Native loadFromBase64 not available. Rebuild the host app after upgrading.'
62
+ 'loadVerifiedFromUrl is not available on this platform. Rebuild the host app with the latest native module.'
87
63
  );
88
64
  }
89
- await native.loadFromBase64(toBase64(bytes));
65
+
66
+ await native.loadVerifiedFromUrl(url, expectedSha256Hex);
90
67
  }
91
68
 
92
69
  function loadUnverified(url: string): void {