@gfean/react-native-bundle-drop 0.4.6 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +168 -4
  2. package/android/build.gradle +1 -0
  3. package/android/src/main/java/com/bundledrop/BundleDropBoundedDownloader.kt +86 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +69 -0
  5. package/android/src/main/java/com/bundledrop/BundleDropRuntimeCrypto.kt +81 -0
  6. package/ios/BundleDropBridge.m +18 -0
  7. package/ios/BundleDropLocator.swift +48 -2
  8. package/ios/BundleDropModule.swift +75 -0
  9. package/ios/BundleDropRuntimeCrypto.swift +45 -0
  10. package/lib/CLI/cli.d.ts +1 -0
  11. package/lib/CLI/cli.js +166 -79
  12. package/lib/CLI/scripts/aipowered/apply-setup-plan.js +7 -17
  13. package/lib/CLI/scripts/aipowered/backend-client.js +29 -4
  14. package/lib/CLI/scripts/aipowered/code-push-residue.d.ts +5 -0
  15. package/lib/CLI/scripts/aipowered/code-push-residue.js +126 -0
  16. package/lib/CLI/scripts/aipowered/credential-safety.d.ts +1 -0
  17. package/lib/CLI/scripts/aipowered/credential-safety.js +14 -0
  18. package/lib/CLI/scripts/aipowered/diff-preview.js +12 -4
  19. package/lib/CLI/scripts/aipowered/init-project-config.d.ts +4 -0
  20. package/lib/CLI/scripts/aipowered/init-project-config.js +228 -43
  21. package/lib/CLI/scripts/aipowered/scanner.d.ts +1 -0
  22. package/lib/CLI/scripts/aipowered/scanner.js +164 -32
  23. package/lib/CLI/scripts/aipowered/terminal-safety.d.ts +4 -0
  24. package/lib/CLI/scripts/aipowered/terminal-safety.js +124 -0
  25. package/lib/CLI/scripts/aipowered/validate-plan.d.ts +3 -0
  26. package/lib/CLI/scripts/aipowered/validate-plan.js +1080 -19
  27. package/lib/CLI/scripts/bare-metro-config.d.ts +1 -1
  28. package/lib/CLI/scripts/bare-metro-config.js +24 -32
  29. package/lib/CLI/scripts/doctor.js +143 -22
  30. package/lib/CLI/scripts/expo/configure-expo.js +51 -60
  31. package/lib/CLI/scripts/expo/package-manager.d.ts +2 -0
  32. package/lib/CLI/scripts/expo/package-manager.js +63 -25
  33. package/lib/CLI/scripts/init-config.d.ts +7 -7
  34. package/lib/CLI/scripts/init-config.js +246 -32
  35. package/lib/CLI/scripts/login-cli.js +35 -10
  36. package/lib/CLI/scripts/metro-config-authority.d.ts +8 -0
  37. package/lib/CLI/scripts/metro-config-authority.js +303 -0
  38. package/lib/CLI/scripts/native-entrypoint-authority.d.ts +2 -0
  39. package/lib/CLI/scripts/native-entrypoint-authority.js +378 -0
  40. package/lib/CLI/scripts/native-setup-contract.d.ts +2 -2
  41. package/lib/CLI/scripts/native-setup-contract.js +63 -33
  42. package/lib/CLI/scripts/native-startup-validator.d.ts +3 -0
  43. package/lib/CLI/scripts/native-startup-validator.js +964 -0
  44. package/lib/CLI/scripts/safe-file-transaction.d.ts +12 -0
  45. package/lib/CLI/scripts/safe-file-transaction.js +159 -0
  46. package/lib/CLI/scripts/sight-artifacts.d.ts +17 -0
  47. package/lib/CLI/scripts/sight-artifacts.js +204 -0
  48. package/lib/CLI/scripts/sight-cli.d.ts +10 -0
  49. package/lib/CLI/scripts/sight-cli.js +127 -0
  50. package/lib/CLI/scripts/sight-session.d.ts +14 -0
  51. package/lib/CLI/scripts/sight-session.js +192 -0
  52. package/lib/api/clientApi.d.ts +3 -1
  53. package/lib/api/clientApi.js +14 -0
  54. package/lib/api/types.d.ts +39 -0
  55. package/lib/context.d.ts +1 -1
  56. package/lib/index.d.ts +2 -0
  57. package/lib/index.js +3 -1
  58. package/lib/install/installFromZip.d.ts +3 -0
  59. package/lib/install/installFromZip.js +10 -1
  60. package/lib/loadConfig.d.ts +17 -1
  61. package/lib/loadConfig.js +16 -0
  62. package/lib/manager/downloadAndInstall.d.ts +3 -2
  63. package/lib/manager/downloadAndInstall.js +111 -46
  64. package/lib/manager/rollbackState.d.ts +3 -1
  65. package/lib/manager/rollbackState.js +2 -2
  66. package/lib/manager/updateCheck.d.ts +1 -0
  67. package/lib/manager/updateCheck.js +218 -78
  68. package/lib/metro.d.ts +8 -1
  69. package/lib/metro.js +68 -19
  70. package/lib/native/bundleDropNative.js +2 -1
  71. package/lib/native/fs.d.ts +6 -0
  72. package/lib/native/fs.js +24 -0
  73. package/lib/patch-engine/installFromPatchSet.d.ts +2 -0
  74. package/lib/patch-engine/installFromPatchSet.js +14 -3
  75. package/lib/patch-engine/patchTransport.d.ts +2 -0
  76. package/lib/patch-engine/patchTransport.js +9 -0
  77. package/lib/runtime/initState.d.ts +5 -0
  78. package/lib/runtime/initState.js +4 -0
  79. package/lib/runtime/service.js +60 -3
  80. package/lib/runtime-delivery/artifactCapability.d.ts +1 -0
  81. package/lib/runtime-delivery/artifactCapability.js +32 -0
  82. package/lib/runtime-delivery/authorityLeaseVerifier.d.ts +3 -0
  83. package/lib/runtime-delivery/authorityLeaseVerifier.js +106 -0
  84. package/lib/runtime-delivery/bootstrapConfig.d.ts +50 -0
  85. package/lib/runtime-delivery/bootstrapConfig.js +217 -0
  86. package/lib/runtime-delivery/diagnostics.d.ts +17 -0
  87. package/lib/runtime-delivery/diagnostics.js +58 -0
  88. package/lib/runtime-delivery/encoding.d.ts +5 -0
  89. package/lib/runtime-delivery/encoding.js +132 -0
  90. package/lib/runtime-delivery/heartbeat.d.ts +3 -0
  91. package/lib/runtime-delivery/heartbeat.js +88 -0
  92. package/lib/runtime-delivery/localResolver.d.ts +23 -0
  93. package/lib/runtime-delivery/localResolver.js +81 -0
  94. package/lib/runtime-delivery/manifestState.d.ts +9 -0
  95. package/lib/runtime-delivery/manifestState.js +102 -0
  96. package/lib/runtime-delivery/manifestVerifier.d.ts +13 -0
  97. package/lib/runtime-delivery/manifestVerifier.js +329 -0
  98. package/lib/runtime-delivery/runtimeDelivery.d.ts +19 -0
  99. package/lib/runtime-delivery/runtimeDelivery.js +375 -0
  100. package/lib/runtime-delivery/types.d.ts +87 -0
  101. package/lib/runtime-delivery/types.js +6 -0
  102. package/package.json +2 -2
package/README.md CHANGED
@@ -96,7 +96,8 @@ npx bundle-drop login
96
96
  npx bundle-drop doctor
97
97
  ```
98
98
 
99
- `login` signs you in, creates `bundle.drop.config.js` when needed, detects Expo or
99
+ `login` signs you in, creates `bundle.drop.config.js` when needed, pins the
100
+ authenticated runtime-delivery bootstrap under `.bundle-drop/`, detects Expo or
100
101
  bare React Native, previews the integration changes, and completes setup. `doctor`
101
102
  then validates configuration, runtime identity, native integration, and startup
102
103
  ownership.
@@ -113,6 +114,86 @@ npx bundle-drop init --project-type bare
113
114
  Run `npx bundle-drop doctor` again after changing native integration, Metro, Expo
114
115
  configuration, or runtime versions.
115
116
 
117
+ When Bundle Drop rotates manifest verification keys or changes the public manifest
118
+ route, refresh the pinned client-visible bootstrap explicitly:
119
+
120
+ ```bash
121
+ npx bundle-drop sync
122
+ npx bundle-drop doctor
123
+ ```
124
+
125
+ Apps upgrading from an inline `runtimeDelivery` block or a direct Metro alias should
126
+ remove that stale block and run `npx bundle-drop init` once to install the
127
+ package-managed Metro wrapper. Inline delivery data is ignored: the validated
128
+ generated bootstrap is the sole trust source. After that one-time migration, `sync`
129
+ is the narrow command for refreshing trust data.
130
+
131
+ The generated bootstrap is not a secret and should be committed. Setup keeps the
132
+ generated Metro wrapper, build receipts, and other transient `.bundle-drop` files
133
+ ignored while allowing `.bundle-drop/runtime-delivery.generated.json` into source
134
+ control.
135
+
136
+ ### Manual setup without AI planning
137
+
138
+ You can configure Bundle Drop without sending project files to the AI setup planner.
139
+ Create `bundle.drop.config.js` with the project identity and public project API key
140
+ shown in the developer dashboard:
141
+
142
+ ```js
143
+ module.exports = {
144
+ serverUrl: 'https://api.bundledrop.app',
145
+ defaultChannel: 'develop',
146
+ runtimeVersion: { ios: '1.0.0', android: '1.0.0' },
147
+ org: { slug: 'your-org' },
148
+ project: {
149
+ name: 'Your App',
150
+ slug: 'your-app',
151
+ apiKey: 'your-public-project-key',
152
+ },
153
+ };
154
+ ```
155
+
156
+ Wrap the final exported Metro config. For bare React Native:
157
+
158
+ ```js
159
+ const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
160
+ const { withBundleDrop } = require('@gfean/react-native-bundle-drop/metro');
161
+
162
+ const config = mergeConfig(getDefaultConfig(__dirname), {});
163
+ module.exports = withBundleDrop(config, { projectRoot: __dirname });
164
+ ```
165
+
166
+ For Expo:
167
+
168
+ ```js
169
+ const { getDefaultConfig } = require('expo/metro-config');
170
+ const { withBundleDropExpo } = require('@gfean/react-native-bundle-drop/metro');
171
+
172
+ module.exports = withBundleDropExpo(getDefaultConfig(__dirname), {
173
+ projectRoot: __dirname,
174
+ });
175
+ ```
176
+
177
+ Expo projects must also add `@gfean/react-native-bundle-drop` to the app config's
178
+ `plugins` array. Bare projects must connect Bundle Drop to the Release bundle URL in
179
+ their Android and iOS entrypoints. Follow the
180
+ [manual native setup guide](https://bundledrop.app/docs/manual-setup) because the
181
+ entrypoint shape varies across React Native versions.
182
+
183
+ Finish every manual setup by authenticating, generating the public trust bootstrap,
184
+ and validating the complete integration:
185
+
186
+ ```bash
187
+ npx bundle-drop login
188
+ npx bundle-drop sync
189
+ npx bundle-drop doctor
190
+ ```
191
+
192
+ `sync` creates `.bundle-drop/runtime-delivery.generated.json`, recreates it if it or
193
+ the entire `.bundle-drop` directory was deleted, and repairs the corresponding
194
+ `.gitignore` rules. The bootstrap contains public identity and verification material,
195
+ not secrets, so commit it with the application.
196
+
116
197
  ## Initialize the Runtime
117
198
 
118
199
  Call `BundleDrop.init` once, as early as possible in the app process.
@@ -239,6 +320,85 @@ example, an iOS-only native change should bump `runtimeVersion.ios`; Android can
239
320
  its existing value. This makes the compatibility boundary explicit and prevents an
240
321
  update from reaching a binary that cannot run it.
241
322
 
323
+ ## Managed Runtime Delivery
324
+
325
+ Runtime delivery is package-managed. `bundle.drop.config.js` stays focused on
326
+ application-owned values such as project identity, channel, runtime versions, and
327
+ rollback policy; it does not contain manifest hosts, access routes, public keys, or
328
+ a delivery-mode switch.
329
+
330
+ `bundle-drop login` and `bundle-drop init` synchronize the trust bootstrap during
331
+ setup. `bundle-drop sync` performs the same narrow operation later for repair or key
332
+ rotation. Each command validates authenticated project credentials and writes the
333
+ identity-bound `.bundle-drop/runtime-delivery.generated.json`. Metro confirms that
334
+ the bootstrap belongs to the same server, organization, and project before merging
335
+ it into the runtime module. Malformed, copied, unsupported, or private-key-bearing
336
+ data is rejected.
337
+
338
+ Older apps with an inline `runtimeDelivery` block keep their ordinary project
339
+ configuration, but the inline block is ignored and should be removed during
340
+ migration. Only the identity-bound generated bootstrap can enable managed delivery.
341
+ If the server explicitly disables delivery for a project, synchronization removes a
342
+ stale bootstrap and the SDK continues through the compatible `/ota/resolve` path.
343
+
344
+ The SDK resolves a complete public lane locally. Invalid, expired, incomplete,
345
+ dynamic, unavailable, or network-failed manifests safely fall back to `/ota/resolve`.
346
+ Artifact download authorization remains API-key authenticated and uses opaque
347
+ release and artifact references rather than URLs embedded in the manifest.
348
+
349
+ Lane manifests are signed state and are not themselves the revocation clock. Every
350
+ local check also fetches a small environment-wide signed publisher lease. The SDK
351
+ verifies its key, exact manifest origin, issue time, and short absolute expiry before
352
+ it verifies or persists lane generation state. A missing, invalid, expired, or
353
+ operator-disabled lease therefore falls back to `/ota/resolve`, even when cached
354
+ manifest bytes remain cryptographically valid.
355
+
356
+ Artifact download capabilities are intentionally short-lived. If an artifact URL is
357
+ rejected with HTTP 401 or 403 during download, the SDK reauthorizes the original
358
+ signed selection once and retries only when its generation, target, transport,
359
+ artifact references, and signed hashes are unchanged. Verification, reconstruction,
360
+ and installation failures are never retried this way.
361
+
362
+ With managed delivery, install through `downloadUpdate`, or use the React hook's
363
+ `fetchBundles` and `installBundle(bundle)` list-item flow. Direct named
364
+ `installBundle(hash, url, ...)` calls are rejected because they bypass the fresh
365
+ resolve and artifact-authorization decision.
366
+
367
+ Unchanged install state is reported at most once every seven days. A current bundle
368
+ hash, app environment, or user-property change is reported immediately; successful
369
+ installs continue to use the separate idempotent installed receipt.
370
+
371
+ The manifest URL is derived from `manifestBaseUrl`, `manifestAccessId`, channel,
372
+ platform, and runtime version. `manifestAccessId` is an opaque URL-routing value,
373
+ not a signing secret. `publicKeys` contains public P-256 JWK coordinates keyed by
374
+ the manifest JWS `kid`, which permits signing-key rotation.
375
+
376
+ Pass `onRuntimeDeliveryDiagnostic` to `BundleDrop.init` to export the fast-path
377
+ signals to your metrics system. Events contain a bounded counter name, cumulative
378
+ process count, timestamp, and optional channel/reason/status metadata; they never
379
+ contain access IDs, install IDs, JWS bodies, user properties, or artifact URLs.
380
+ `getRuntimeDeliveryDiagnosticCounters()` returns a process-local snapshot. The
381
+ counter names are `manifest_hit`, `dynamic_manifest`, `origin_fallback`,
382
+ `invalid_signature`, `unknown_key`, `lane_mismatch`,
383
+ `generation_regression`, `generation_equivocation`,
384
+ `manifest_http_error`, `manifest_network_error`, `manifest_timeout`,
385
+ `manifest_too_large`, `manifest_invalid`, `manifest_stream_unavailable`,
386
+ `authority_lease_http_error`, `authority_lease_network_error`,
387
+ `authority_lease_timeout`, `authority_lease_too_large`,
388
+ `authority_lease_invalid`, `authority_lease_invalid_signature`,
389
+ `authority_lease_unknown_key`, `authority_lease_expired`,
390
+ `authority_lease_origin_mismatch`, and `authority_lease_disabled`.
391
+
392
+ Manifest responses are read incrementally and cancelled as soon as they exceed
393
+ 1 MiB. A runtime without a readable response stream fails closed to `/ota/resolve`
394
+ instead of buffering an unbounded body.
395
+
396
+ Managed runtime delivery uses native SHA-256 and ES256 verification. After upgrading to
397
+ an SDK release whose `nativeVersion` includes this support (`0.5.0` or newer), run
398
+ Pods/prebuild as appropriate and ship a new native binary before enabling runtime
399
+ delivery for the project. Bundle Drop's native-version validation will reject a JavaScript/native
400
+ adapter mismatch.
401
+
242
402
  ## Upload an Update
243
403
 
244
404
  With the default literal runtime configuration, Expo uploads resolve the app version
@@ -381,6 +541,7 @@ Import the runtime API from `@gfean/react-native-bundle-drop`.
381
541
  | `policy` | `'manual' \| 'immediate' \| 'on-next-launch'` | `'manual'` | Startup behavior after hydration. |
382
542
  | `checkOnly` | `boolean` | `false` | Startup resolves updates without downloading or applying them. |
383
543
  | `onStatusUpdate` | `(status: string) => void` | — | Listener for human-readable status messages. |
544
+ | `onRuntimeDeliveryDiagnostic` | `(event: RuntimeDeliveryDiagnosticEvent) => void` | — | Listener for bounded runtime-delivery counter events suitable for metrics export. |
384
545
 
385
546
  **Update actions** — `checkForUpdate`, `downloadUpdate`, `installBundle`,
386
547
  `applyUpdate`, `getUpdateState`, `getInstalledBundleInfo`, `getAvailableBundles`,
@@ -395,10 +556,13 @@ plus update actions.
395
556
 
396
557
  **Errors** — `BundleDropError`, `isBundleDropError`.
397
558
 
398
- **Metro** — import `withBundleDropExpo` from
399
- `@gfean/react-native-bundle-drop/metro` when configuring Expo Metro manually.
559
+ **Runtime delivery diagnostics** — `getRuntimeDeliveryDiagnosticCounters` returns
560
+ the current process-local counter snapshot.
561
+
562
+ **Metro** — import `withBundleDropExpo` for Expo or `withBundleDrop` for bare React
563
+ Native from `@gfean/react-native-bundle-drop/metro` when configuring Metro manually.
400
564
 
401
- **CLI** (`npx bundle-drop <command>`) — `login`, `logout`, `whoami`, `init`,
565
+ **CLI** (`npx bundle-drop <command>`) — `login`, `logout`, `whoami`, `init`, `sync`,
402
566
  `doctor`, `eas-receipt <ios|android>`, and `upload <ios|android>`.
403
567
 
404
568
  ## Good to Know
@@ -132,6 +132,7 @@ dependencies {
132
132
 
133
133
  if (project.hasProperty("standalone")) {
134
134
  testImplementation "junit:junit:4.13.2"
135
+ testImplementation "com.squareup.okhttp3:okhttp:4.12.0"
135
136
  testImplementation "org.json:json:20231013"
136
137
  testImplementation "androidx.test:core:1.6.1"
137
138
  testImplementation "org.robolectric:robolectric:4.14.1"
@@ -0,0 +1,86 @@
1
+ package com.bundledrop
2
+
3
+ import java.io.File
4
+ import java.io.FileOutputStream
5
+ import java.io.InterruptedIOException
6
+ import java.net.URL
7
+ import java.util.concurrent.TimeUnit
8
+ import okhttp3.OkHttpClient
9
+ import okhttp3.Request
10
+
11
+ internal class BundleDropBoundedDownloadHttpException(
12
+ val status: Int,
13
+ message: String,
14
+ ) : java.io.IOException(message)
15
+
16
+ internal class BundleDropBoundedDownloadTooLargeException(message: String) :
17
+ java.io.IOException(message)
18
+
19
+ internal class BundleDropBoundedDownloadTimeoutException(cause: Throwable) :
20
+ java.io.IOException("Download timed out", cause)
21
+
22
+ internal object BundleDropBoundedDownloader {
23
+ fun downloadToFile(
24
+ baseClient: OkHttpClient,
25
+ parsedUrl: URL,
26
+ destFile: File,
27
+ maxBytes: Long,
28
+ timeoutMs: Long,
29
+ ) {
30
+ require(maxBytes > 0) { "maxBytes must be positive" }
31
+ require(timeoutMs > 0) { "timeoutMs must be positive" }
32
+
33
+ val client = baseClient.newBuilder()
34
+ .callTimeout(timeoutMs, TimeUnit.MILLISECONDS)
35
+ .build()
36
+ val request = Request.Builder()
37
+ .url(parsedUrl)
38
+ .get()
39
+ .header("Accept", "application/jose+json, application/json")
40
+ .build()
41
+
42
+ try {
43
+ client.newCall(request).execute().use { response ->
44
+ if (!response.isSuccessful) {
45
+ throw BundleDropBoundedDownloadHttpException(
46
+ response.code,
47
+ "HTTP ${response.code}: ${response.message}",
48
+ )
49
+ }
50
+
51
+ val body = response.body
52
+ ?: throw java.io.IOException("Manifest response body is missing")
53
+ if (body.contentLength() > maxBytes) {
54
+ throw tooLarge(maxBytes)
55
+ }
56
+
57
+ destFile.parentFile?.mkdirs()
58
+ body.byteStream().use { input ->
59
+ FileOutputStream(destFile).use { output ->
60
+ val buffer = ByteArray(8192)
61
+ var totalRead = 0L
62
+ while (true) {
63
+ val bytesRead = input.read(buffer)
64
+ if (bytesRead < 0) break
65
+ if (bytesRead.toLong() > maxBytes - totalRead) {
66
+ throw tooLarge(maxBytes)
67
+ }
68
+ output.write(buffer, 0, bytesRead)
69
+ totalRead += bytesRead
70
+ }
71
+ }
72
+ }
73
+ }
74
+ } catch (error: InterruptedIOException) {
75
+ try { destFile.delete() } catch (_: Exception) {}
76
+ throw BundleDropBoundedDownloadTimeoutException(error)
77
+ } catch (error: Exception) {
78
+ try { destFile.delete() } catch (_: Exception) {}
79
+ throw error
80
+ }
81
+ }
82
+
83
+ private fun tooLarge(maxBytes: Long) = BundleDropBoundedDownloadTooLargeException(
84
+ "Download exceeds $maxBytes byte limit",
85
+ )
86
+ }
@@ -4,6 +4,7 @@ import android.content.Context
4
4
  import android.content.Intent
5
5
  import android.util.Log
6
6
  import com.facebook.react.bridge.*
7
+ import com.facebook.react.modules.network.OkHttpClientProvider
7
8
  import java.io.File
8
9
 
9
10
  class BundleDropModule(reactContext: ReactApplicationContext) :
@@ -193,6 +194,37 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
193
194
  }
194
195
  }
195
196
 
197
+ @ReactMethod
198
+ fun fsSha256String(value: String, promise: Promise) {
199
+ try {
200
+ promise.resolve(BundleDropRuntimeCrypto.sha256String(value))
201
+ } catch (e: Exception) {
202
+ promise.reject("ERR_SHA256", e.message, e)
203
+ }
204
+ }
205
+
206
+ @ReactMethod
207
+ fun fsVerifyEs256Signature(
208
+ signingInput: String,
209
+ signatureBase64Url: String,
210
+ xBase64Url: String,
211
+ yBase64Url: String,
212
+ promise: Promise,
213
+ ) {
214
+ try {
215
+ promise.resolve(
216
+ BundleDropRuntimeCrypto.verifyEs256Signature(
217
+ signingInput,
218
+ signatureBase64Url,
219
+ xBase64Url,
220
+ yBase64Url,
221
+ ),
222
+ )
223
+ } catch (e: Exception) {
224
+ promise.reject("ERR_ES256_VERIFY", e.message, e)
225
+ }
226
+ }
227
+
196
228
  @ReactMethod
197
229
  fun fsFileSize(path: String, promise: Promise) {
198
230
  try {
@@ -261,6 +293,43 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
261
293
  }.start()
262
294
  }
263
295
 
296
+ @ReactMethod
297
+ fun fsDownloadFileBounded(
298
+ url: String,
299
+ destPath: String,
300
+ maxBytes: Double,
301
+ timeoutMs: Double,
302
+ promise: Promise,
303
+ ) {
304
+ Thread {
305
+ try {
306
+ require(maxBytes.isFinite() && maxBytes >= 1) { "maxBytes must be positive" }
307
+ require(timeoutMs.isFinite() && timeoutMs >= 1 && timeoutMs <= Int.MAX_VALUE) {
308
+ "timeoutMs is outside the supported range"
309
+ }
310
+ val parsedUrl = BundleDropFileOps.validateHttpUrl(url)
311
+ BundleDropBoundedDownloader.downloadToFile(
312
+ OkHttpClientProvider.getOkHttpClient(),
313
+ parsedUrl,
314
+ File(destPath),
315
+ maxBytes = maxBytes.toLong(),
316
+ timeoutMs = timeoutMs.toLong(),
317
+ )
318
+ promise.resolve(null)
319
+ } catch (e: Exception) {
320
+ try { File(destPath).delete() } catch (_: Exception) {}
321
+ val code = when {
322
+ e is BundleDropBoundedDownloadTimeoutException -> "ERR_DOWNLOAD_TIMEOUT"
323
+ e is BundleDropBoundedDownloadTooLargeException -> "ERR_DOWNLOAD_TOO_LARGE"
324
+ e is BundleDropBoundedDownloadHttpException -> "ERR_DOWNLOAD_HTTP"
325
+ else -> "ERR_DOWNLOAD_NETWORK"
326
+ }
327
+ val message = e.message.orEmpty()
328
+ promise.reject(code, message.ifEmpty { "Manifest download failed" }, e)
329
+ }
330
+ }.start()
331
+ }
332
+
264
333
  override fun getConstants(): MutableMap<String, Any> {
265
334
  val map = mutableMapOf<String, Any>()
266
335
  downloadedBundlePath?.let {
@@ -0,0 +1,81 @@
1
+ package com.bundledrop
2
+
3
+ import java.math.BigInteger
4
+ import java.nio.charset.StandardCharsets
5
+ import java.security.AlgorithmParameters
6
+ import java.security.KeyFactory
7
+ import java.security.MessageDigest
8
+ import java.security.Signature
9
+ import java.security.spec.ECGenParameterSpec
10
+ import java.security.spec.ECParameterSpec
11
+ import java.security.spec.ECPoint
12
+ import java.security.spec.ECPublicKeySpec
13
+
14
+ object BundleDropRuntimeCrypto {
15
+ private const val BASE64_URL_ALPHABET =
16
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
17
+ fun sha256String(value: String): String =
18
+ MessageDigest.getInstance("SHA-256")
19
+ .digest(value.toByteArray(StandardCharsets.UTF_8))
20
+ .joinToString("") { "%02x".format(it) }
21
+
22
+ fun verifyEs256Signature(
23
+ signingInput: String,
24
+ signatureBase64Url: String,
25
+ xBase64Url: String,
26
+ yBase64Url: String,
27
+ ): Boolean {
28
+ val signature = decodeBase64Url(signatureBase64Url)
29
+ val x = decodeBase64Url(xBase64Url)
30
+ val y = decodeBase64Url(yBase64Url)
31
+ require(signature.size == 64) { "ES256 signature must be 64 bytes" }
32
+ require(x.size == 32 && y.size == 32) { "P-256 coordinates must be 32 bytes" }
33
+
34
+ val parameters = AlgorithmParameters.getInstance("EC").apply {
35
+ init(ECGenParameterSpec("secp256r1"))
36
+ }.getParameterSpec(ECParameterSpec::class.java)
37
+ val publicKey = KeyFactory.getInstance("EC").generatePublic(
38
+ ECPublicKeySpec(ECPoint(BigInteger(1, x), BigInteger(1, y)), parameters),
39
+ )
40
+ return Signature.getInstance("SHA256withECDSA").run {
41
+ initVerify(publicKey)
42
+ update(signingInput.toByteArray(StandardCharsets.UTF_8))
43
+ verify(joseSignatureToDer(signature))
44
+ }
45
+ }
46
+
47
+ private fun decodeBase64Url(value: String): ByteArray {
48
+ require(value.length % 4 != 1) { "Invalid base64url value" }
49
+ require(value.all { BASE64_URL_ALPHABET.indexOf(it) >= 0 }) { "Invalid base64url value" }
50
+ val output = ArrayList<Byte>((value.length * 3) / 4)
51
+ var index = 0
52
+ while (index < value.length) {
53
+ val remaining = value.length - index
54
+ val a = BASE64_URL_ALPHABET.indexOf(value[index])
55
+ val b = BASE64_URL_ALPHABET.indexOf(value[index + 1])
56
+ val c = if (remaining > 2) BASE64_URL_ALPHABET.indexOf(value[index + 2]) else 0
57
+ val d = if (remaining > 3) BASE64_URL_ALPHABET.indexOf(value[index + 3]) else 0
58
+ val bits = (a shl 18) or (b shl 12) or (c shl 6) or d
59
+ output.add(((bits shr 16) and 0xff).toByte())
60
+ if (remaining > 2) output.add(((bits shr 8) and 0xff).toByte())
61
+ if (remaining > 3) output.add((bits and 0xff).toByte())
62
+ index += 4
63
+ }
64
+ return output.toByteArray()
65
+ }
66
+
67
+ private fun joseSignatureToDer(signature: ByteArray): ByteArray {
68
+ val r = positiveDerInteger(signature.copyOfRange(0, 32))
69
+ val s = positiveDerInteger(signature.copyOfRange(32, 64))
70
+ val sequenceLength = 2 + r.size + 2 + s.size
71
+ return byteArrayOf(0x30, sequenceLength.toByte(), 0x02, r.size.toByte()) +
72
+ r + byteArrayOf(0x02, s.size.toByte()) + s
73
+ }
74
+
75
+ private fun positiveDerInteger(value: ByteArray): ByteArray {
76
+ var first = 0
77
+ while (first < value.lastIndex && value[first] == 0.toByte()) first += 1
78
+ val trimmed = value.copyOfRange(first, value.size)
79
+ return if ((trimmed[0].toInt() and 0x80) != 0) byteArrayOf(0) + trimmed else trimmed
80
+ }
81
+ }
@@ -53,6 +53,17 @@ RCT_EXTERN_METHOD(fsSha256File:(NSString *)path
53
53
  resolve:(RCTPromiseResolveBlock)resolve
54
54
  reject:(RCTPromiseRejectBlock)reject)
55
55
 
56
+ RCT_EXTERN_METHOD(fsSha256String:(NSString *)value
57
+ resolve:(RCTPromiseResolveBlock)resolve
58
+ reject:(RCTPromiseRejectBlock)reject)
59
+
60
+ RCT_EXTERN_METHOD(fsVerifyEs256Signature:(NSString *)signingInput
61
+ signatureBase64Url:(NSString *)signatureBase64Url
62
+ xBase64Url:(NSString *)xBase64Url
63
+ yBase64Url:(NSString *)yBase64Url
64
+ resolve:(RCTPromiseResolveBlock)resolve
65
+ reject:(RCTPromiseRejectBlock)reject)
66
+
56
67
  RCT_EXTERN_METHOD(fsFileSize:(NSString *)path
57
68
  resolve:(RCTPromiseResolveBlock)resolve
58
69
  reject:(RCTPromiseRejectBlock)reject)
@@ -81,6 +92,13 @@ RCT_EXTERN_METHOD(fsDownloadFile:(NSString *)url
81
92
  resolve:(RCTPromiseResolveBlock)resolve
82
93
  reject:(RCTPromiseRejectBlock)reject)
83
94
 
95
+ RCT_EXTERN_METHOD(fsDownloadFileBounded:(NSString *)url
96
+ destPath:(NSString *)destPath
97
+ maxBytes:(nonnull NSNumber *)maxBytes
98
+ timeoutMs:(nonnull NSNumber *)timeoutMs
99
+ resolve:(RCTPromiseResolveBlock)resolve
100
+ reject:(RCTPromiseRejectBlock)reject)
101
+
84
102
  + (BOOL)requiresMainQueueSetup
85
103
  {
86
104
  return NO;
@@ -4,6 +4,14 @@ import Foundation
4
4
 
5
5
  static let binaryVersionKey = "BundleDropBinaryVersion"
6
6
  static let runtimeVersionInfoKey = "BundleDropRuntimeVersion"
7
+ static let expoEnabledInfoKey = "BundleDropExpoEnabled"
8
+ static let embeddedBuildIdentityFilename = ".bundle-drop-build-identity.json"
9
+
10
+ private struct EmbeddedBuildIdentity: Decodable {
11
+ let schemaVersion: Int
12
+ let platform: String
13
+ let runtimeVersion: String
14
+ }
7
15
 
8
16
  /// Matches Android `BundleDropOtaPrefs.KEY_OTA_ENABLED` for cross-platform debugging.
9
17
  static let otaEnabledKey = "bundledrop_ota_enabled"
@@ -17,14 +25,52 @@ import Foundation
17
25
  let version = bundle.infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown"
18
26
  let build = bundle.infoDictionary?["CFBundleVersion"] as? String ?? "0"
19
27
  let binaryVersion = "\(version)-\(build)"
20
- guard let runtimeVersion = bundle.infoDictionary?[runtimeVersionInfoKey] as? String,
21
- !runtimeVersion.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
28
+ guard let runtimeVersion = getRuntimeVersion(bundle: bundle) else {
22
29
  return binaryVersion
23
30
  }
24
31
  return "runtime:\(runtimeVersion)|binary:\(binaryVersion)"
25
32
  }
26
33
 
34
+ static func getRuntimeVersion(bundle: Bundle = .main) -> String? {
35
+ if let embeddedRuntimeVersion = getEmbeddedRuntimeVersion(bundle: bundle) {
36
+ return embeddedRuntimeVersion
37
+ }
38
+ return normalizeRuntimeVersion(bundle.infoDictionary?[runtimeVersionInfoKey] as? String)
39
+ }
40
+
41
+ static func hasRuntimeIdentityForOta(bundle: Bundle = .main) -> Bool {
42
+ let isExpoBuild = bundle.infoDictionary?[expoEnabledInfoKey] as? Bool == true
43
+ return !isExpoBuild || getEmbeddedRuntimeVersion(bundle: bundle) != nil
44
+ }
45
+
46
+ private static func getEmbeddedRuntimeVersion(bundle: Bundle) -> String? {
47
+ let candidateURL = bundle.bundleURL.appendingPathComponent(embeddedBuildIdentityFilename)
48
+ guard let attributes = try? FileManager.default.attributesOfItem(atPath: candidateURL.path),
49
+ let fileType = attributes[.type] as? FileAttributeType,
50
+ fileType == .typeRegular,
51
+ let fileSize = attributes[.size] as? NSNumber,
52
+ fileSize.intValue > 0,
53
+ fileSize.intValue <= 64 * 1024,
54
+ let data = try? Data(contentsOf: candidateURL),
55
+ let candidate = try? JSONDecoder().decode(EmbeddedBuildIdentity.self, from: data),
56
+ candidate.schemaVersion == 1,
57
+ candidate.platform == "ios" else {
58
+ return nil
59
+ }
60
+ return normalizeRuntimeVersion(candidate.runtimeVersion)
61
+ }
62
+
63
+ private static func normalizeRuntimeVersion(_ runtimeVersion: String?) -> String? {
64
+ guard let runtimeVersion else { return nil }
65
+ let normalized = runtimeVersion.trimmingCharacters(in: .whitespacesAndNewlines)
66
+ return normalized.isEmpty ? nil : normalized
67
+ }
68
+
27
69
  @objc public static func bundleURL() -> URL? {
70
+ guard hasRuntimeIdentityForOta() else {
71
+ print("BundleDrop: Expo runtime identity is missing; using the embedded bundle")
72
+ return nil
73
+ }
28
74
  let fm = FileManager.default
29
75
  guard let lib = fm.urls(for: .libraryDirectory, in: .userDomainMask).first else { return nil }
30
76
  guard let docs = fm.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil }
@@ -239,6 +239,36 @@ final class BundleDropModule: NSObject {
239
239
  }
240
240
  }
241
241
 
242
+ @objc
243
+ func fsSha256String(
244
+ _ value: String,
245
+ resolve: @escaping RCTPromiseResolveBlock,
246
+ reject: @escaping RCTPromiseRejectBlock
247
+ ) {
248
+ resolve(BundleDropRuntimeCrypto.sha256String(value))
249
+ }
250
+
251
+ @objc
252
+ func fsVerifyEs256Signature(
253
+ _ signingInput: String,
254
+ signatureBase64Url: String,
255
+ xBase64Url: String,
256
+ yBase64Url: String,
257
+ resolve: @escaping RCTPromiseResolveBlock,
258
+ reject: @escaping RCTPromiseRejectBlock
259
+ ) {
260
+ do {
261
+ resolve(try BundleDropRuntimeCrypto.verifyEs256Signature(
262
+ signingInput: signingInput,
263
+ signatureBase64Url: signatureBase64Url,
264
+ xBase64Url: xBase64Url,
265
+ yBase64Url: yBase64Url
266
+ ))
267
+ } catch {
268
+ reject("ERR_ES256_VERIFY", error.localizedDescription, error)
269
+ }
270
+ }
271
+
242
272
  @objc
243
273
  func fsFileSize(
244
274
  _ path: String,
@@ -332,4 +362,49 @@ final class BundleDropModule: NSObject {
332
362
  }
333
363
  }
334
364
  }
365
+
366
+ @objc
367
+ func fsDownloadFileBounded(
368
+ _ url: String,
369
+ destPath: String,
370
+ maxBytes: NSNumber,
371
+ timeoutMs: NSNumber,
372
+ resolve: @escaping RCTPromiseResolveBlock,
373
+ reject: @escaping RCTPromiseRejectBlock
374
+ ) {
375
+ let maxByteCount = maxBytes.int64Value
376
+ let timeoutSeconds = timeoutMs.doubleValue / 1000
377
+ guard maxByteCount > 0, timeoutSeconds > 0 else {
378
+ reject("ERR_DOWNLOAD_NETWORK", "Invalid bounded download limits", nil)
379
+ return
380
+ }
381
+
382
+ let config = URLSessionConfiguration.default
383
+ config.timeoutIntervalForRequest = timeoutSeconds
384
+ config.timeoutIntervalForResource = timeoutSeconds
385
+ BundleDropFileOps.downloadToFile(
386
+ urlString: url,
387
+ destPath: destPath,
388
+ maxBytes: maxByteCount,
389
+ configuration: config
390
+ ) { result in
391
+ switch result {
392
+ case .success:
393
+ resolve(nil)
394
+ case .failure(let error):
395
+ let message = error.localizedDescription
396
+ let errorCode: String
397
+ if (error as? URLError)?.code == .timedOut {
398
+ errorCode = "ERR_DOWNLOAD_TIMEOUT"
399
+ } else if message.hasPrefix("Download exceeds ") {
400
+ errorCode = "ERR_DOWNLOAD_TOO_LARGE"
401
+ } else if message.range(of: #"^HTTP \d{3}(?:\b|:)"#, options: .regularExpression) != nil {
402
+ errorCode = "ERR_DOWNLOAD_HTTP"
403
+ } else {
404
+ errorCode = "ERR_DOWNLOAD_NETWORK"
405
+ }
406
+ reject(errorCode, message, error)
407
+ }
408
+ }
409
+ }
335
410
  }