@gfean/react-native-bundle-drop 0.5.1 → 0.7.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 (127) hide show
  1. package/BundleDrop.podspec +96 -0
  2. package/README.md +194 -5
  3. package/android/build.gradle +66 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropBoundedDownloader.kt +86 -0
  5. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +206 -13
  6. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +43 -13
  7. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +35 -0
  8. package/android/src/main/java/com/bundledrop/BundleDropRuntimeCrypto.kt +81 -0
  9. package/android/src/main/java/com/bundledrop/BundleDropStartupRecovery.kt +1117 -0
  10. package/ios/BundleDropBridge.m +45 -0
  11. package/ios/BundleDropLocator.swift +66 -4
  12. package/ios/BundleDropModule.swift +181 -3
  13. package/ios/BundleDropOtaResolver.swift +137 -29
  14. package/ios/BundleDropRuntimeCrypto.swift +45 -0
  15. package/ios/BundleDropStartupRecovery.swift +1108 -0
  16. package/ios/BundleDropStartupRecoveryAdapter.swift +301 -0
  17. package/lib/CLI/cli.d.ts +1 -0
  18. package/lib/CLI/cli.js +57 -6
  19. package/lib/CLI/scripts/aipowered/apply-setup-plan.js +7 -17
  20. package/lib/CLI/scripts/aipowered/backend-client.js +29 -4
  21. package/lib/CLI/scripts/aipowered/code-push-residue.d.ts +5 -0
  22. package/lib/CLI/scripts/aipowered/code-push-residue.js +126 -0
  23. package/lib/CLI/scripts/aipowered/credential-safety.d.ts +1 -0
  24. package/lib/CLI/scripts/aipowered/credential-safety.js +14 -0
  25. package/lib/CLI/scripts/aipowered/diff-preview.js +12 -4
  26. package/lib/CLI/scripts/aipowered/init-project-config.d.ts +4 -0
  27. package/lib/CLI/scripts/aipowered/init-project-config.js +221 -45
  28. package/lib/CLI/scripts/aipowered/scanner.d.ts +1 -0
  29. package/lib/CLI/scripts/aipowered/scanner.js +164 -32
  30. package/lib/CLI/scripts/aipowered/terminal-safety.d.ts +4 -0
  31. package/lib/CLI/scripts/aipowered/terminal-safety.js +124 -0
  32. package/lib/CLI/scripts/aipowered/validate-plan.d.ts +3 -0
  33. package/lib/CLI/scripts/aipowered/validate-plan.js +1080 -19
  34. package/lib/CLI/scripts/bare-metro-config.d.ts +1 -1
  35. package/lib/CLI/scripts/bare-metro-config.js +24 -32
  36. package/lib/CLI/scripts/doctor.js +162 -22
  37. package/lib/CLI/scripts/expo/configure-expo.js +52 -60
  38. package/lib/CLI/scripts/expo/package-manager.d.ts +2 -0
  39. package/lib/CLI/scripts/expo/package-manager.js +63 -25
  40. package/lib/CLI/scripts/init-config.d.ts +7 -7
  41. package/lib/CLI/scripts/init-config.js +198 -14
  42. package/lib/CLI/scripts/login-cli.js +31 -7
  43. package/lib/CLI/scripts/metro-config-authority.d.ts +8 -0
  44. package/lib/CLI/scripts/metro-config-authority.js +303 -0
  45. package/lib/CLI/scripts/native/write-runtime-identity.d.ts +19 -0
  46. package/lib/CLI/scripts/native/write-runtime-identity.js +92 -0
  47. package/lib/CLI/scripts/native-entrypoint-authority.d.ts +2 -0
  48. package/lib/CLI/scripts/native-entrypoint-authority.js +378 -0
  49. package/lib/CLI/scripts/native-setup-contract.d.ts +2 -2
  50. package/lib/CLI/scripts/native-setup-contract.js +63 -33
  51. package/lib/CLI/scripts/native-startup-validator.d.ts +3 -0
  52. package/lib/CLI/scripts/native-startup-validator.js +964 -0
  53. package/lib/CLI/scripts/safe-file-transaction.d.ts +12 -0
  54. package/lib/CLI/scripts/safe-file-transaction.js +159 -0
  55. package/lib/CLI/scripts/upload-cli.d.ts +12 -2
  56. package/lib/CLI/scripts/upload-cli.js +74 -11
  57. package/lib/CLI/serverUrl.d.ts +3 -0
  58. package/lib/CLI/serverUrl.js +31 -0
  59. package/lib/api/clientApi.d.ts +3 -1
  60. package/lib/api/clientApi.js +14 -0
  61. package/lib/api/types.d.ts +39 -0
  62. package/lib/bundleInfo.d.ts +2 -0
  63. package/lib/bundleInfo.js +16 -1
  64. package/lib/context.d.ts +1 -1
  65. package/lib/context.js +12 -2
  66. package/lib/fs/bundlePointer.d.ts +1 -17
  67. package/lib/fs/bundlePointer.js +5 -93
  68. package/lib/index.d.ts +2 -0
  69. package/lib/index.js +3 -1
  70. package/lib/install/bundleInstallShared.js +4 -4
  71. package/lib/install/installFromZip.d.ts +3 -0
  72. package/lib/install/installFromZip.js +10 -1
  73. package/lib/loadConfig.d.ts +17 -1
  74. package/lib/loadConfig.js +16 -0
  75. package/lib/manager/downloadAndInstall.d.ts +3 -2
  76. package/lib/manager/downloadAndInstall.js +134 -66
  77. package/lib/manager/reporting.d.ts +8 -1
  78. package/lib/manager/reporting.js +17 -22
  79. package/lib/manager/rollbackState.d.ts +18 -52
  80. package/lib/manager/rollbackState.js +115 -216
  81. package/lib/manager/updateCheck.d.ts +1 -0
  82. package/lib/manager/updateCheck.js +224 -78
  83. package/lib/manager/updateState.d.ts +2 -1
  84. package/lib/manager/updateState.js +59 -6
  85. package/lib/metro.d.ts +8 -1
  86. package/lib/metro.js +69 -19
  87. package/lib/native/bundleDropNative.d.ts +62 -0
  88. package/lib/native/bundleDropNative.js +268 -2
  89. package/lib/native/fs.d.ts +6 -0
  90. package/lib/native/fs.js +24 -0
  91. package/lib/patch-engine/installFromPatchSet.d.ts +2 -0
  92. package/lib/patch-engine/installFromPatchSet.js +16 -5
  93. package/lib/patch-engine/patchTransport.d.ts +2 -0
  94. package/lib/patch-engine/patchTransport.js +9 -0
  95. package/lib/runtime/initState.d.ts +5 -0
  96. package/lib/runtime/initState.js +4 -0
  97. package/lib/runtime/service.js +82 -67
  98. package/lib/runtime-delivery/artifactCapability.d.ts +1 -0
  99. package/lib/runtime-delivery/artifactCapability.js +32 -0
  100. package/lib/runtime-delivery/authorityLeaseVerifier.d.ts +3 -0
  101. package/lib/runtime-delivery/authorityLeaseVerifier.js +106 -0
  102. package/lib/runtime-delivery/bootstrapConfig.d.ts +68 -0
  103. package/lib/runtime-delivery/bootstrapConfig.js +278 -0
  104. package/lib/runtime-delivery/diagnostics.d.ts +17 -0
  105. package/lib/runtime-delivery/diagnostics.js +58 -0
  106. package/lib/runtime-delivery/encoding.d.ts +5 -0
  107. package/lib/runtime-delivery/encoding.js +132 -0
  108. package/lib/runtime-delivery/heartbeat.d.ts +3 -0
  109. package/lib/runtime-delivery/heartbeat.js +88 -0
  110. package/lib/runtime-delivery/localResolver.d.ts +23 -0
  111. package/lib/runtime-delivery/localResolver.js +81 -0
  112. package/lib/runtime-delivery/manifestState.d.ts +11 -0
  113. package/lib/runtime-delivery/manifestState.js +123 -0
  114. package/lib/runtime-delivery/manifestVerifier.d.ts +13 -0
  115. package/lib/runtime-delivery/manifestVerifier.js +335 -0
  116. package/lib/runtime-delivery/runtimeDelivery.d.ts +19 -0
  117. package/lib/runtime-delivery/runtimeDelivery.js +375 -0
  118. package/lib/runtime-delivery/types.d.ts +87 -0
  119. package/lib/runtime-delivery/types.js +6 -0
  120. package/lib/scripts/bundle.d.ts +9 -2
  121. package/lib/scripts/bundle.js +68 -18
  122. package/lib/scripts/download-bundle.d.ts +1 -0
  123. package/lib/scripts/download-bundle.js +2 -2
  124. package/lib/scripts/resolveModule.d.ts +2 -0
  125. package/lib/scripts/resolveModule.js +5 -0
  126. package/package.json +5 -2
  127. package/plugin/xcodeBuildPhase.js +2 -1
@@ -4,23 +4,21 @@ 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
9
+ import org.json.JSONArray
10
+ import org.json.JSONObject
8
11
 
9
12
  class BundleDropModule(reactContext: ReactApplicationContext) :
10
13
  ReactContextBaseJavaModule(reactContext) {
11
14
 
12
- private var downloadedBundlePath: String? = null
13
-
14
15
  companion object {
15
- var latestBundlePath: String? = null
16
- private set
17
-
18
16
  fun getDownloadedBundlePath(context: Context): String? =
19
- BundleDropNativePaths.getDownloadedBundlePath(context)
17
+ BundleDropNativePaths.getDownloadedBundlePathPassive(context)
20
18
 
21
19
  @JvmStatic
22
20
  fun resolveJSBundleFile(context: Context, fallback: String?): String? {
23
- val path = getDownloadedBundlePath(context)
21
+ val path = BundleDropNativePaths.getDownloadedBundlePath(context)
24
22
  return if (!path.isNullOrEmpty()) path else fallback
25
23
  }
26
24
  }
@@ -29,10 +27,7 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
29
27
 
30
28
  @ReactMethod
31
29
  fun getDownloadedBundlePath(promise: Promise) {
32
- val path = getDownloadedBundlePath(reactApplicationContext)
33
- downloadedBundlePath = path
34
- latestBundlePath = path
35
- promise.resolve(path)
30
+ promise.resolve(getDownloadedBundlePath(reactApplicationContext))
36
31
  }
37
32
 
38
33
  @ReactMethod
@@ -68,6 +63,95 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
68
63
  }
69
64
  }
70
65
 
66
+ @ReactMethod
67
+ fun activateStartupCandidate(
68
+ hash: String,
69
+ maxCrashCount: Double,
70
+ healthCheckMode: String,
71
+ healthyAfterSec: Double,
72
+ promise: Promise,
73
+ ) {
74
+ try {
75
+ require(maxCrashCount.isFinite() && maxCrashCount >= 0 && maxCrashCount % 1.0 == 0.0) {
76
+ "maxCrashCount must be a non-negative integer"
77
+ }
78
+ require(maxCrashCount <= Int.MAX_VALUE) { "maxCrashCount is outside the supported range" }
79
+ val result = BundleDropStartupRecovery.controller(reactApplicationContext)
80
+ .activateCandidate(hash, maxCrashCount.toInt(), healthCheckMode, healthyAfterSec)
81
+ promise.resolve(Arguments.createMap().apply {
82
+ putString("hash", result.hash)
83
+ putString("bundlePath", result.bundlePath)
84
+ })
85
+ } catch (error: Exception) {
86
+ promise.reject("ERR_STARTUP_RECOVERY_ACTIVATE", error.message, error)
87
+ }
88
+ }
89
+
90
+ @ReactMethod
91
+ fun markStartupHealthy(hash: String, attemptId: String, promise: Promise) {
92
+ try {
93
+ val marked = BundleDropStartupRecovery.controller(reactApplicationContext)
94
+ .markHealthy(hash, attemptId)
95
+ promise.resolve(marked)
96
+ } catch (error: Exception) {
97
+ promise.reject("ERR_STARTUP_RECOVERY_HEALTH", error.message, error)
98
+ }
99
+ }
100
+
101
+ @ReactMethod
102
+ fun getStartupRecoveryState(promise: Promise) {
103
+ try {
104
+ val state = BundleDropStartupRecovery.controller(reactApplicationContext).snapshot()
105
+ promise.resolve(jsonObjectToWritableMap(state))
106
+ } catch (error: Exception) {
107
+ promise.reject("ERR_STARTUP_RECOVERY_STATE", error.message, error)
108
+ }
109
+ }
110
+
111
+ @ReactMethod
112
+ fun setStartupRecoveryRevokedHashes(hashes: ReadableArray, promise: Promise) {
113
+ try {
114
+ val values = buildSet {
115
+ for (index in 0 until hashes.size()) {
116
+ val hash = hashes.getString(index)
117
+ ?: throw IllegalArgumentException("Revoked bundle hashes must be strings")
118
+ add(hash)
119
+ }
120
+ }
121
+ BundleDropStartupRecovery.controller(reactApplicationContext).setRevokedHashes(values)
122
+ promise.resolve(true)
123
+ } catch (error: Exception) {
124
+ promise.reject("ERR_STARTUP_RECOVERY_REVOKE", error.message, error)
125
+ }
126
+ }
127
+
128
+ @ReactMethod
129
+ fun acknowledgeStartupRecovery(eventId: String, promise: Promise) {
130
+ try {
131
+ promise.resolve(
132
+ BundleDropStartupRecovery.controller(reactApplicationContext)
133
+ .acknowledgeRecovery(eventId),
134
+ )
135
+ } catch (error: Exception) {
136
+ promise.reject("ERR_STARTUP_RECOVERY_ACK", error.message, error)
137
+ }
138
+ }
139
+
140
+ @ReactMethod
141
+ fun rollbackStartupBundle(forceEmbedded: Boolean, promise: Promise) {
142
+ try {
143
+ val result = BundleDropStartupRecovery.controller(reactApplicationContext)
144
+ .rollbackStartupBundle(forceEmbedded)
145
+ promise.resolve(Arguments.createMap().apply {
146
+ putBoolean("rolledBack", result.rolledBack)
147
+ putBoolean("toEmbedded", result.toEmbedded)
148
+ result.hash?.let { putString("hash", it) }
149
+ })
150
+ } catch (error: Exception) {
151
+ promise.reject("ERR_STARTUP_RECOVERY_ROLLBACK", error.message, error)
152
+ }
153
+ }
154
+
71
155
  @ReactMethod(isBlockingSynchronousMethod = true)
72
156
  fun getImageManifestSync(): String? {
73
157
  return readImageManifestRaw()
@@ -193,6 +277,37 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
193
277
  }
194
278
  }
195
279
 
280
+ @ReactMethod
281
+ fun fsSha256String(value: String, promise: Promise) {
282
+ try {
283
+ promise.resolve(BundleDropRuntimeCrypto.sha256String(value))
284
+ } catch (e: Exception) {
285
+ promise.reject("ERR_SHA256", e.message, e)
286
+ }
287
+ }
288
+
289
+ @ReactMethod
290
+ fun fsVerifyEs256Signature(
291
+ signingInput: String,
292
+ signatureBase64Url: String,
293
+ xBase64Url: String,
294
+ yBase64Url: String,
295
+ promise: Promise,
296
+ ) {
297
+ try {
298
+ promise.resolve(
299
+ BundleDropRuntimeCrypto.verifyEs256Signature(
300
+ signingInput,
301
+ signatureBase64Url,
302
+ xBase64Url,
303
+ yBase64Url,
304
+ ),
305
+ )
306
+ } catch (e: Exception) {
307
+ promise.reject("ERR_ES256_VERIFY", e.message, e)
308
+ }
309
+ }
310
+
196
311
  @ReactMethod
197
312
  fun fsFileSize(path: String, promise: Promise) {
198
313
  try {
@@ -261,14 +376,92 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
261
376
  }.start()
262
377
  }
263
378
 
379
+ @ReactMethod
380
+ fun fsDownloadFileBounded(
381
+ url: String,
382
+ destPath: String,
383
+ maxBytes: Double,
384
+ timeoutMs: Double,
385
+ promise: Promise,
386
+ ) {
387
+ Thread {
388
+ try {
389
+ require(maxBytes.isFinite() && maxBytes >= 1) { "maxBytes must be positive" }
390
+ require(timeoutMs.isFinite() && timeoutMs >= 1 && timeoutMs <= Int.MAX_VALUE) {
391
+ "timeoutMs is outside the supported range"
392
+ }
393
+ val parsedUrl = BundleDropFileOps.validateHttpUrl(url)
394
+ BundleDropBoundedDownloader.downloadToFile(
395
+ OkHttpClientProvider.getOkHttpClient(),
396
+ parsedUrl,
397
+ File(destPath),
398
+ maxBytes = maxBytes.toLong(),
399
+ timeoutMs = timeoutMs.toLong(),
400
+ )
401
+ promise.resolve(null)
402
+ } catch (e: Exception) {
403
+ try { File(destPath).delete() } catch (_: Exception) {}
404
+ val code = when {
405
+ e is BundleDropBoundedDownloadTimeoutException -> "ERR_DOWNLOAD_TIMEOUT"
406
+ e is BundleDropBoundedDownloadTooLargeException -> "ERR_DOWNLOAD_TOO_LARGE"
407
+ e is BundleDropBoundedDownloadHttpException -> "ERR_DOWNLOAD_HTTP"
408
+ else -> "ERR_DOWNLOAD_NETWORK"
409
+ }
410
+ val message = e.message.orEmpty()
411
+ promise.reject(code, message.ifEmpty { "Manifest download failed" }, e)
412
+ }
413
+ }.start()
414
+ }
415
+
264
416
  override fun getConstants(): MutableMap<String, Any> {
265
417
  val map = mutableMapOf<String, Any>()
266
- downloadedBundlePath?.let {
267
- map["downloadedBundlePath"] = it
418
+ map["startupRecoveryProtocolVersion"] = BundleDropStartupRecoveryController.PROTOCOL_VERSION
419
+ @Suppress("UNCHECKED_CAST")
420
+ (map as MutableMap<String, Any?>)["startupRecoverySelectedHash"] =
421
+ BundleDropStartupRecovery.startupSelectedHash()
422
+ BundleDropStartupRecovery.startupAttempt()?.let { (hash, attemptId) ->
423
+ map["startupRecoveryAttemptHash"] = hash
424
+ map["startupRecoveryAttemptId"] = attemptId
268
425
  }
269
426
  val context = reactApplicationContext
270
427
  map["DocumentDirectoryPath"] = context.filesDir.absolutePath
271
428
  map["LibraryDirectoryPath"] = context.filesDir.absolutePath
272
429
  return map
273
430
  }
431
+
432
+ private fun jsonObjectToWritableMap(json: JSONObject): WritableMap {
433
+ val map = Arguments.createMap()
434
+ val keys = json.keys()
435
+ while (keys.hasNext()) {
436
+ val key = keys.next()
437
+ putJsonValue(map, key, json.opt(key))
438
+ }
439
+ return map
440
+ }
441
+
442
+ private fun jsonArrayToWritableArray(json: JSONArray): WritableArray {
443
+ val array = Arguments.createArray()
444
+ for (index in 0 until json.length()) {
445
+ when (val value = json.opt(index)) {
446
+ null, JSONObject.NULL -> array.pushNull()
447
+ is JSONObject -> array.pushMap(jsonObjectToWritableMap(value))
448
+ is JSONArray -> array.pushArray(jsonArrayToWritableArray(value))
449
+ is Boolean -> array.pushBoolean(value)
450
+ is Number -> array.pushDouble(value.toDouble())
451
+ else -> array.pushString(value.toString())
452
+ }
453
+ }
454
+ return array
455
+ }
456
+
457
+ private fun putJsonValue(map: WritableMap, key: String, value: Any?) {
458
+ when (value) {
459
+ null, JSONObject.NULL -> map.putNull(key)
460
+ is JSONObject -> map.putMap(key, jsonObjectToWritableMap(value))
461
+ is JSONArray -> map.putArray(key, jsonArrayToWritableArray(value))
462
+ is Boolean -> map.putBoolean(key, value)
463
+ is Number -> map.putDouble(key, value.toDouble())
464
+ else -> map.putString(key, value.toString())
465
+ }
466
+ }
274
467
  }
@@ -8,8 +8,8 @@ import org.json.JSONObject
8
8
  /**
9
9
  * Resolves the on-disk OTA JS bundle path (no React / bridge types).
10
10
  *
11
- * Shared by [BundleDropModule] so cold-start `resolveJSBundleFile`, the JS bridge
12
- * `getDownloadedBundlePath`, and tests use the same logic — including the OTA-disabled gate.
11
+ * Cold-start resolution records a launch attempt, while bridge lookups are passive and never
12
+ * change the attempt selected for the current React runtime.
13
13
  */
14
14
  object BundleDropNativePaths {
15
15
  private const val KEY_BINARY_VERSION = "binary_version"
@@ -40,6 +40,9 @@ object BundleDropNativePaths {
40
40
  return binaryVersionKey(versionName, versionCode, runtimeVersion)
41
41
  }
42
42
 
43
+ internal fun currentBinaryIdentity(context: Context): String =
44
+ getBinaryVersionKey(context, readEmbeddedRuntimeVersion(context))
45
+
43
46
  internal fun readEmbeddedRuntimeVersion(context: Context): String? {
44
47
  return try {
45
48
  context.assets.open(BUILD_IDENTITY_ASSET).bufferedReader().use { reader ->
@@ -64,11 +67,37 @@ object BundleDropNativePaths {
64
67
 
65
68
  @JvmStatic
66
69
  fun getDownloadedBundlePath(context: Context): String? {
67
- if (!BundleDropOtaPrefs.isOtaEnabled(context)) return null
68
- return getDownloadedBundlePath(context, readEmbeddedRuntimeVersion(context))
70
+ if (!BundleDropOtaPrefs.isOtaEnabled(context)) {
71
+ BundleDropStartupRecovery.clearStartupSelection()
72
+ return null
73
+ }
74
+ resolveForBinary(context, readEmbeddedRuntimeVersion(context))
75
+ val selection = BundleDropStartupRecovery.selectForStartup(context)
76
+ logResolvedPath(selection.bundlePath)
77
+ return selection.bundlePath
69
78
  }
70
79
 
71
80
  internal fun getDownloadedBundlePath(context: Context, runtimeVersion: String?): String? {
81
+ if (!BundleDropOtaPrefs.isOtaEnabled(context)) {
82
+ BundleDropStartupRecovery.clearStartupSelection()
83
+ return null
84
+ }
85
+ resolveForBinary(context, runtimeVersion)
86
+ val selection = BundleDropStartupRecovery.selectForStartup(context)
87
+ logResolvedPath(selection.bundlePath)
88
+ return selection.bundlePath
89
+ }
90
+
91
+ internal fun getDownloadedBundlePathPassive(context: Context): String? {
92
+ if (!BundleDropOtaPrefs.isOtaEnabled(context)) return null
93
+ val resolved = resolveForBinary(context, readEmbeddedRuntimeVersion(context))
94
+ if (resolved == null) return null
95
+ val path = BundleDropStartupRecovery.controller(context).resolvePassive()
96
+ logResolvedPath(path)
97
+ return path
98
+ }
99
+
100
+ private fun resolveForBinary(context: Context, runtimeVersion: String?): String? {
72
101
  val bundleDropRoot = File(context.filesDir, "bundle-drop")
73
102
  val result = BundleDropOtaResolver.resolve(
74
103
  bundleDropRoot = bundleDropRoot,
@@ -79,16 +108,17 @@ object BundleDropNativePaths {
79
108
 
80
109
  result.storedVersion?.let { setStoredBinaryVersion(context, it) }
81
110
 
82
- if (result.bundlePath == null) {
83
- if (result.clearedOta) {
84
- Log.d("BundleDrop", "Binary updated, clearing OTA bundle")
85
- } else {
86
- Log.d("BundleDrop", "📦 No OTA bundle found.")
87
- }
88
- } else {
89
- Log.d("BundleDrop", "🔁 Using OTA bundle at: ${result.bundlePath}")
111
+ if (result.clearedOta) {
112
+ Log.d("BundleDrop", "Binary updated, clearing OTA bundle")
90
113
  }
91
-
92
114
  return result.bundlePath
93
115
  }
116
+
117
+ private fun logResolvedPath(path: String?) {
118
+ if (path == null) {
119
+ Log.d("BundleDrop", "📦 No OTA bundle found.")
120
+ } else {
121
+ Log.d("BundleDrop", "🔁 Using OTA bundle at: $path")
122
+ }
123
+ }
94
124
  }
@@ -43,6 +43,39 @@ object BundleDropOtaResolver {
43
43
  }
44
44
  }
45
45
 
46
+ /** Verify an installed bundle independently of the active pointer. */
47
+ internal fun readBundleForHash(bundleDropRoot: File, hash: String): String? {
48
+ if (!bundleHashPattern.matches(hash)) return null
49
+ return try {
50
+ val bundleDir = File(File(bundleDropRoot, "bundles"), hash)
51
+ val bundleFile = File(bundleDir, "main.jsbundle")
52
+ val manifestFile = File(bundleDir, "bundle-manifest.json")
53
+ if (!bundleFile.exists() || !manifestFile.exists()) return null
54
+ val manifest = JSONObject(manifestFile.readText())
55
+ if (
56
+ manifest.optInt("manifestVersion", -1) != 1 ||
57
+ manifest.optString("bundleHash", "") != hash ||
58
+ !verifyBundleDir(bundleDir, manifest, hash)
59
+ ) {
60
+ return null
61
+ }
62
+ bundleFile.absolutePath
63
+ } catch (_: Exception) {
64
+ null
65
+ }
66
+ }
67
+
68
+ internal fun readBundleRuntimeVersion(bundleDropRoot: File, hash: String): String? {
69
+ readBundleForHash(bundleDropRoot, hash) ?: return null
70
+ return try {
71
+ JSONObject(File(File(File(bundleDropRoot, "bundles"), hash), "bundle-manifest.json").readText())
72
+ .optString("runtimeVersion", "")
73
+ .takeIf(String::isNotEmpty)
74
+ } catch (_: Exception) {
75
+ null
76
+ }
77
+ }
78
+
46
79
  private fun verifyBundleDir(bundleDir: File, manifest: JSONObject, expectedHash: String): Boolean {
47
80
  val files = manifest.optJSONArray("files") ?: return false
48
81
  if (manifest.optString("platform", "") != "android") {
@@ -184,6 +217,7 @@ object BundleDropOtaResolver {
184
217
  File(bundleDropRoot, "current.json"),
185
218
  File(bundleDropRoot, "previous.json"),
186
219
  File(bundleDropRoot, "state.json"),
220
+ File(bundleDropRoot, BundleDropStartupRecoveryController.RECOVERY_LEDGER),
187
221
  File(filesDir, "bundle-info.json"),
188
222
  )
189
223
  filesToClear.forEach {
@@ -196,6 +230,7 @@ object BundleDropOtaResolver {
196
230
  File(bundleDropRoot, "current.json"),
197
231
  File(bundleDropRoot, "previous.json"),
198
232
  File(bundleDropRoot, "state.json"),
233
+ File(bundleDropRoot, BundleDropStartupRecoveryController.RECOVERY_LEDGER),
199
234
  File(filesDir, "bundle-info.json"),
200
235
  ).any { it.exists() }
201
236
  }
@@ -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
+ }