@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
@@ -5,6 +5,33 @@
5
5
  RCT_EXTERN_METHOD(getDownloadedBundlePath:(RCTPromiseResolveBlock)resolve
6
6
  rejecter:(RCTPromiseRejectBlock)reject)
7
7
 
8
+ RCT_EXTERN_METHOD(activateStartupCandidate:(NSString *)hash
9
+ maxCrashCount:(nonnull NSNumber *)maxCrashCount
10
+ healthCheckMode:(NSString *)healthCheckMode
11
+ healthyAfterSec:(nonnull NSNumber *)healthyAfterSec
12
+ resolve:(RCTPromiseResolveBlock)resolve
13
+ reject:(RCTPromiseRejectBlock)reject)
14
+
15
+ RCT_EXTERN_METHOD(markStartupHealthy:(NSString *)hash
16
+ attemptId:(NSString *)attemptId
17
+ resolve:(RCTPromiseResolveBlock)resolve
18
+ reject:(RCTPromiseRejectBlock)reject)
19
+
20
+ RCT_EXTERN_METHOD(getStartupRecoveryState:(RCTPromiseResolveBlock)resolve
21
+ reject:(RCTPromiseRejectBlock)reject)
22
+
23
+ RCT_EXTERN_METHOD(setStartupRecoveryRevokedHashes:(NSArray<NSString *> *)hashes
24
+ resolve:(RCTPromiseResolveBlock)resolve
25
+ reject:(RCTPromiseRejectBlock)reject)
26
+
27
+ RCT_EXTERN_METHOD(acknowledgeStartupRecovery:(NSString *)eventId
28
+ resolve:(RCTPromiseResolveBlock)resolve
29
+ reject:(RCTPromiseRejectBlock)reject)
30
+
31
+ RCT_EXTERN_METHOD(rollbackStartupBundle:(BOOL)forceEmbedded
32
+ resolve:(RCTPromiseResolveBlock)resolve
33
+ reject:(RCTPromiseRejectBlock)reject)
34
+
8
35
  RCT_EXTERN_METHOD(restartReactNative)
9
36
 
10
37
  RCT_EXTERN_METHOD(setOtaEnabled:(BOOL)enabled
@@ -53,6 +80,17 @@ RCT_EXTERN_METHOD(fsSha256File:(NSString *)path
53
80
  resolve:(RCTPromiseResolveBlock)resolve
54
81
  reject:(RCTPromiseRejectBlock)reject)
55
82
 
83
+ RCT_EXTERN_METHOD(fsSha256String:(NSString *)value
84
+ resolve:(RCTPromiseResolveBlock)resolve
85
+ reject:(RCTPromiseRejectBlock)reject)
86
+
87
+ RCT_EXTERN_METHOD(fsVerifyEs256Signature:(NSString *)signingInput
88
+ signatureBase64Url:(NSString *)signatureBase64Url
89
+ xBase64Url:(NSString *)xBase64Url
90
+ yBase64Url:(NSString *)yBase64Url
91
+ resolve:(RCTPromiseResolveBlock)resolve
92
+ reject:(RCTPromiseRejectBlock)reject)
93
+
56
94
  RCT_EXTERN_METHOD(fsFileSize:(NSString *)path
57
95
  resolve:(RCTPromiseResolveBlock)resolve
58
96
  reject:(RCTPromiseRejectBlock)reject)
@@ -81,6 +119,13 @@ RCT_EXTERN_METHOD(fsDownloadFile:(NSString *)url
81
119
  resolve:(RCTPromiseResolveBlock)resolve
82
120
  reject:(RCTPromiseRejectBlock)reject)
83
121
 
122
+ RCT_EXTERN_METHOD(fsDownloadFileBounded:(NSString *)url
123
+ destPath:(NSString *)destPath
124
+ maxBytes:(nonnull NSNumber *)maxBytes
125
+ timeoutMs:(nonnull NSNumber *)timeoutMs
126
+ resolve:(RCTPromiseResolveBlock)resolve
127
+ reject:(RCTPromiseRejectBlock)reject)
128
+
84
129
  + (BOOL)requiresMainQueueSetup
85
130
  {
86
131
  return NO;
@@ -4,6 +4,15 @@ 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
+ static let bareEmbeddedBuildIdentityFilename = "bundle-drop-build-identity.json"
10
+
11
+ private struct EmbeddedBuildIdentity: Decodable {
12
+ let schemaVersion: Int
13
+ let platform: String
14
+ let runtimeVersion: String
15
+ }
7
16
 
8
17
  /// Matches Android `BundleDropOtaPrefs.KEY_OTA_ENABLED` for cross-platform debugging.
9
18
  static let otaEnabledKey = "bundledrop_ota_enabled"
@@ -17,14 +26,60 @@ import Foundation
17
26
  let version = bundle.infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown"
18
27
  let build = bundle.infoDictionary?["CFBundleVersion"] as? String ?? "0"
19
28
  let binaryVersion = "\(version)-\(build)"
20
- guard let runtimeVersion = bundle.infoDictionary?[runtimeVersionInfoKey] as? String,
21
- !runtimeVersion.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
29
+ guard let runtimeVersion = getRuntimeVersion(bundle: bundle) else {
22
30
  return binaryVersion
23
31
  }
24
32
  return "runtime:\(runtimeVersion)|binary:\(binaryVersion)"
25
33
  }
26
34
 
35
+ static func getRuntimeVersion(bundle: Bundle = .main) -> String? {
36
+ if let embeddedRuntimeVersion = getEmbeddedRuntimeVersion(bundle: bundle) {
37
+ return embeddedRuntimeVersion
38
+ }
39
+ return normalizeRuntimeVersion(bundle.infoDictionary?[runtimeVersionInfoKey] as? String)
40
+ }
41
+
42
+ static func hasRuntimeIdentityForOta(bundle: Bundle = .main) -> Bool {
43
+ let isExpoBuild = bundle.infoDictionary?[expoEnabledInfoKey] as? Bool == true
44
+ return !isExpoBuild || getEmbeddedRuntimeVersion(bundle: bundle) != nil
45
+ }
46
+
47
+ private static func getEmbeddedRuntimeVersion(bundle: Bundle) -> String? {
48
+ for filename in [embeddedBuildIdentityFilename, bareEmbeddedBuildIdentityFilename] {
49
+ let candidateURL = bundle.bundleURL.appendingPathComponent(filename)
50
+ guard let attributes = try? FileManager.default.attributesOfItem(atPath: candidateURL.path),
51
+ let fileType = attributes[.type] as? FileAttributeType,
52
+ fileType == .typeRegular,
53
+ let fileSize = attributes[.size] as? NSNumber,
54
+ fileSize.intValue > 0,
55
+ fileSize.intValue <= 64 * 1024,
56
+ let data = try? Data(contentsOf: candidateURL),
57
+ let candidate = try? JSONDecoder().decode(EmbeddedBuildIdentity.self, from: data),
58
+ candidate.schemaVersion == 1,
59
+ candidate.platform == "ios" else {
60
+ continue
61
+ }
62
+ return normalizeRuntimeVersion(candidate.runtimeVersion)
63
+ }
64
+ return nil
65
+ }
66
+
67
+ private static func normalizeRuntimeVersion(_ runtimeVersion: String?) -> String? {
68
+ guard let runtimeVersion else { return nil }
69
+ let normalized = runtimeVersion.trimmingCharacters(in: .whitespacesAndNewlines)
70
+ return normalized.isEmpty ? nil : normalized
71
+ }
72
+
27
73
  @objc public static func bundleURL() -> URL? {
74
+ guard hasRuntimeIdentityForOta() else {
75
+ BundleDropStartupRecoveryAdapter.clearCapturedSelection()
76
+ print("BundleDrop: Expo runtime identity is missing; using the embedded bundle")
77
+ return nil
78
+ }
79
+ guard isOtaEnabled() else {
80
+ BundleDropStartupRecoveryAdapter.clearCapturedSelection()
81
+ return nil
82
+ }
28
83
  let fm = FileManager.default
29
84
  guard let lib = fm.urls(for: .libraryDirectory, in: .userDomainMask).first else { return nil }
30
85
  guard let docs = fm.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil }
@@ -34,7 +89,10 @@ import Foundation
34
89
  return bundleURL(
35
90
  bundleDropRoot: root,
36
91
  documentsDirectory: docs,
37
- currentBinaryVersion: currentVersion
92
+ currentBinaryVersion: currentVersion,
93
+ startupSelection: {
94
+ BundleDropStartupRecoveryAdapter.selectStartupBundle(bundleDropRoot: root)
95
+ }
38
96
  )
39
97
  }
40
98
 
@@ -45,7 +103,8 @@ import Foundation
45
103
  userDefaults: UserDefaults = .standard,
46
104
  fileManager: FileManager = .default,
47
105
  shouldLogBinaryUpdate: Bool = true,
48
- log: (String) -> Void = { print($0) }
106
+ log: (String) -> Void = { print($0) },
107
+ startupSelection: (() -> URL?)? = nil
49
108
  ) -> URL? {
50
109
  // Single gate for public and internal entrypoints (tests inject `userDefaults`).
51
110
  if !isOtaEnabled(userDefaults: userDefaults) { return nil }
@@ -63,6 +122,9 @@ import Foundation
63
122
  }
64
123
 
65
124
  userDefaults.set(result.storedVersion, forKey: binaryVersionKey)
125
+ if let startupSelection {
126
+ return startupSelection()
127
+ }
66
128
  return result.bundleURL
67
129
  }
68
130
 
@@ -30,7 +30,7 @@ final class BundleDropModule: NSObject {
30
30
  _ resolve: @escaping RCTPromiseResolveBlock,
31
31
  rejecter reject: @escaping RCTPromiseRejectBlock
32
32
  ) {
33
- if let url = BundleDropLocatorCore.bundleURL() {
33
+ if let url = BundleDropStartupRecoveryAdapter.downloadedBundleURL() {
34
34
  print("📦 Found downloaded bundle at: \(url.path)")
35
35
  resolve(url.path)
36
36
  return
@@ -39,6 +39,99 @@ final class BundleDropModule: NSObject {
39
39
  resolve(nil)
40
40
  }
41
41
 
42
+ @objc
43
+ func activateStartupCandidate(
44
+ _ hash: String,
45
+ maxCrashCount: NSNumber,
46
+ healthCheckMode: String,
47
+ healthyAfterSec: NSNumber,
48
+ resolve: @escaping RCTPromiseResolveBlock,
49
+ reject: @escaping RCTPromiseRejectBlock
50
+ ) {
51
+ runFileOperation(errorCode: "ERR_STARTUP_RECOVERY_ACTIVATE", resolve: resolve, reject: reject) {
52
+ let crashCount = maxCrashCount.doubleValue
53
+ let healthDelay = healthyAfterSec.doubleValue
54
+ guard crashCount.isFinite,
55
+ crashCount >= 0,
56
+ crashCount.rounded(.towardZero) == crashCount,
57
+ crashCount <= Double(Int32.max),
58
+ healthDelay.isFinite,
59
+ healthDelay >= 0 else {
60
+ throw BundleDropStartupRecoveryError.invalidPolicy
61
+ }
62
+ let result = try BundleDropStartupRecoveryAdapter.activateCandidate(
63
+ hash: hash,
64
+ maxCrashCount: Int(crashCount),
65
+ healthCheckMode: healthCheckMode,
66
+ healthyAfterSec: healthDelay
67
+ )
68
+ return ["hash": result.hash, "bundlePath": result.bundleURL.path]
69
+ }
70
+ }
71
+
72
+ @objc
73
+ func markStartupHealthy(
74
+ _ hash: String,
75
+ attemptId: String,
76
+ resolve: @escaping RCTPromiseResolveBlock,
77
+ reject: @escaping RCTPromiseRejectBlock
78
+ ) {
79
+ runFileOperation(errorCode: "ERR_STARTUP_RECOVERY_HEALTH", resolve: resolve, reject: reject) {
80
+ BundleDropStartupRecoveryAdapter.markHealthy(hash: hash, attemptId: attemptId)
81
+ }
82
+ }
83
+
84
+ @objc
85
+ func getStartupRecoveryState(
86
+ _ resolve: @escaping RCTPromiseResolveBlock,
87
+ reject: @escaping RCTPromiseRejectBlock
88
+ ) {
89
+ runFileOperation(errorCode: "ERR_STARTUP_RECOVERY_STATE", resolve: resolve, reject: reject) {
90
+ try BundleDropStartupRecoveryAdapter.snapshot()
91
+ }
92
+ }
93
+
94
+ @objc
95
+ func setStartupRecoveryRevokedHashes(
96
+ _ hashes: [String],
97
+ resolve: @escaping RCTPromiseResolveBlock,
98
+ reject: @escaping RCTPromiseRejectBlock
99
+ ) {
100
+ runFileOperation(errorCode: "ERR_STARTUP_RECOVERY_REVOKE", resolve: resolve, reject: reject) {
101
+ try BundleDropStartupRecoveryAdapter.setRevokedHashes(hashes)
102
+ }
103
+ }
104
+
105
+ @objc
106
+ func acknowledgeStartupRecovery(
107
+ _ eventId: String,
108
+ resolve: @escaping RCTPromiseResolveBlock,
109
+ reject: @escaping RCTPromiseRejectBlock
110
+ ) {
111
+ runFileOperation(errorCode: "ERR_STARTUP_RECOVERY_ACK", resolve: resolve, reject: reject) {
112
+ try BundleDropStartupRecoveryAdapter.acknowledgeRecovery(eventId: eventId)
113
+ }
114
+ }
115
+
116
+ @objc
117
+ func rollbackStartupBundle(
118
+ _ forceEmbedded: Bool,
119
+ resolve: @escaping RCTPromiseResolveBlock,
120
+ reject: @escaping RCTPromiseRejectBlock
121
+ ) {
122
+ runFileOperation(errorCode: "ERR_STARTUP_RECOVERY_ROLLBACK", resolve: resolve, reject: reject) {
123
+ let result = try BundleDropStartupRecoveryAdapter.rollback(forceEmbedded: forceEmbedded)
124
+ var response: [String: Any] = [
125
+ "rolledBack": result.rolledBack,
126
+ "toEmbedded": result.toEmbedded,
127
+ ]
128
+ if let hash = result.hash {
129
+ response["hash"] = hash
130
+ }
131
+ return response
132
+ }
133
+ }
134
+
42
135
  @objc
43
136
  func setOtaEnabled(
44
137
  _ enabled: Bool,
@@ -57,17 +150,22 @@ final class BundleDropModule: NSObject {
57
150
  return
58
151
  }
59
152
 
60
- guard let url = BundleDropLocatorCore.bundleURL() else {
153
+ guard let stagedURL = BundleDropStartupRecoveryAdapter.downloadedBundleURL() else {
61
154
  print("⚠️ No downloaded bundle found; skipping restart.")
62
155
  return
63
156
  }
64
157
 
65
- let size = BundleDropLocatorCore.fileSize(at: url)
158
+ let size = BundleDropLocatorCore.fileSize(at: stagedURL)
66
159
  if size < 1024 {
67
160
  print("⚠️ Bundle exists but looks invalid (size=\(size)). Skipping restart.")
68
161
  return
69
162
  }
70
163
 
164
+ guard let url = BundleDropStartupRecoveryAdapter.beginReload() else {
165
+ print("⚠️ Downloaded bundle became unavailable; skipping restart.")
166
+ return
167
+ }
168
+
71
169
  Self.isReloading = true
72
170
  print("🔄 Restarting RN from \(url.path) size=\(size)")
73
171
 
@@ -87,9 +185,14 @@ final class BundleDropModule: NSObject {
87
185
  let fm = FileManager.default
88
186
  let docs = fm.urls(for: .documentDirectory, in: .userDomainMask).first?.path ?? ""
89
187
  let lib = fm.urls(for: .libraryDirectory, in: .userDomainMask).first?.path ?? ""
188
+ let attempt = BundleDropStartupRecoveryAdapter.capturedAttempt()
90
189
  return [
91
190
  "DocumentDirectoryPath": docs,
92
191
  "LibraryDirectoryPath": lib,
192
+ "startupRecoveryProtocolVersion": BundleDropStartupRecoveryAdapter.protocolVersion,
193
+ "startupRecoverySelectedHash": BundleDropStartupRecoveryAdapter.capturedSelectedHash() ?? NSNull(),
194
+ "startupRecoveryAttemptHash": attempt.hash ?? NSNull(),
195
+ "startupRecoveryAttemptId": attempt.attemptId ?? NSNull(),
93
196
  ]
94
197
  }
95
198
 
@@ -239,6 +342,36 @@ final class BundleDropModule: NSObject {
239
342
  }
240
343
  }
241
344
 
345
+ @objc
346
+ func fsSha256String(
347
+ _ value: String,
348
+ resolve: @escaping RCTPromiseResolveBlock,
349
+ reject: @escaping RCTPromiseRejectBlock
350
+ ) {
351
+ resolve(BundleDropRuntimeCrypto.sha256String(value))
352
+ }
353
+
354
+ @objc
355
+ func fsVerifyEs256Signature(
356
+ _ signingInput: String,
357
+ signatureBase64Url: String,
358
+ xBase64Url: String,
359
+ yBase64Url: String,
360
+ resolve: @escaping RCTPromiseResolveBlock,
361
+ reject: @escaping RCTPromiseRejectBlock
362
+ ) {
363
+ do {
364
+ resolve(try BundleDropRuntimeCrypto.verifyEs256Signature(
365
+ signingInput: signingInput,
366
+ signatureBase64Url: signatureBase64Url,
367
+ xBase64Url: xBase64Url,
368
+ yBase64Url: yBase64Url
369
+ ))
370
+ } catch {
371
+ reject("ERR_ES256_VERIFY", error.localizedDescription, error)
372
+ }
373
+ }
374
+
242
375
  @objc
243
376
  func fsFileSize(
244
377
  _ path: String,
@@ -332,4 +465,49 @@ final class BundleDropModule: NSObject {
332
465
  }
333
466
  }
334
467
  }
468
+
469
+ @objc
470
+ func fsDownloadFileBounded(
471
+ _ url: String,
472
+ destPath: String,
473
+ maxBytes: NSNumber,
474
+ timeoutMs: NSNumber,
475
+ resolve: @escaping RCTPromiseResolveBlock,
476
+ reject: @escaping RCTPromiseRejectBlock
477
+ ) {
478
+ let maxByteCount = maxBytes.int64Value
479
+ let timeoutSeconds = timeoutMs.doubleValue / 1000
480
+ guard maxByteCount > 0, timeoutSeconds > 0 else {
481
+ reject("ERR_DOWNLOAD_NETWORK", "Invalid bounded download limits", nil)
482
+ return
483
+ }
484
+
485
+ let config = URLSessionConfiguration.default
486
+ config.timeoutIntervalForRequest = timeoutSeconds
487
+ config.timeoutIntervalForResource = timeoutSeconds
488
+ BundleDropFileOps.downloadToFile(
489
+ urlString: url,
490
+ destPath: destPath,
491
+ maxBytes: maxByteCount,
492
+ configuration: config
493
+ ) { result in
494
+ switch result {
495
+ case .success:
496
+ resolve(nil)
497
+ case .failure(let error):
498
+ let message = error.localizedDescription
499
+ let errorCode: String
500
+ if (error as? URLError)?.code == .timedOut {
501
+ errorCode = "ERR_DOWNLOAD_TIMEOUT"
502
+ } else if message.hasPrefix("Download exceeds ") {
503
+ errorCode = "ERR_DOWNLOAD_TOO_LARGE"
504
+ } else if message.range(of: #"^HTTP \d{3}(?:\b|:)"#, options: .regularExpression) != nil {
505
+ errorCode = "ERR_DOWNLOAD_HTTP"
506
+ } else {
507
+ errorCode = "ERR_DOWNLOAD_NETWORK"
508
+ }
509
+ reject(errorCode, message, error)
510
+ }
511
+ }
512
+ }
335
513
  }
@@ -7,50 +7,152 @@ struct BundleDropOtaResolveResult {
7
7
  let storedVersion: String
8
8
  }
9
9
 
10
+ struct BundleDropOtaPointer {
11
+ let hash: String
12
+ let bundleURL: URL
13
+ let runtimeVersion: String
14
+ }
15
+
10
16
  enum BundleDropOtaResolver {
11
17
  static func readCurrentPointer(
12
18
  bundleDropRoot: URL,
19
+ expectedRuntimeVersion: String? = nil,
13
20
  fileManager: FileManager = .default
14
21
  ) -> URL? {
15
- let current = bundleDropRoot.appendingPathComponent("current.json")
16
- guard fileManager.fileExists(atPath: current.path) else { return nil }
22
+ readPointer(
23
+ named: "current.json",
24
+ bundleDropRoot: bundleDropRoot,
25
+ expectedRuntimeVersion: expectedRuntimeVersion,
26
+ fileManager: fileManager
27
+ )?.bundleURL
28
+ }
29
+
30
+ static func readPointer(
31
+ named filename: String,
32
+ bundleDropRoot: URL,
33
+ expectedRuntimeVersion: String? = nil,
34
+ fileManager: FileManager = .default
35
+ ) -> BundleDropOtaPointer? {
36
+ let pointerURL = bundleDropRoot.appendingPathComponent(filename)
37
+ guard fileManager.fileExists(atPath: pointerURL.path) else { return nil }
17
38
 
18
39
  do {
19
- let data = try Data(contentsOf: current)
40
+ let data = try Data(contentsOf: pointerURL)
20
41
  let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any]
21
42
  guard let hash = obj?["hash"] as? String,
22
43
  hash.range(of: "^[a-f0-9]{64}$", options: .regularExpression) != nil else {
23
44
  return nil
24
45
  }
25
-
26
- let expectedURL = bundleDropRoot
27
- .appendingPathComponent("bundles")
28
- .appendingPathComponent(hash)
29
- .appendingPathComponent("main.jsbundle")
30
- let manifestURL = expectedURL
31
- .deletingLastPathComponent()
32
- .appendingPathComponent("bundle-manifest.json")
33
- guard fileManager.fileExists(atPath: manifestURL.path),
34
- let manifestData = try? Data(contentsOf: manifestURL),
35
- let manifest = try? JSONSerialization.jsonObject(with: manifestData) as? [String: Any],
36
- (manifest["manifestVersion"] as? NSNumber)?.intValue == 1,
37
- manifest["bundleHash"] as? String == hash else {
38
- return nil
39
- }
40
- guard verifyBundleDir(
41
- bundleDir: expectedURL.deletingLastPathComponent(),
42
- manifest: manifest,
43
- expectedHash: hash,
46
+ return verifiedBundle(
47
+ hash: hash,
48
+ bundleDropRoot: bundleDropRoot,
49
+ expectedRuntimeVersion: expectedRuntimeVersion,
44
50
  fileManager: fileManager
45
- ) else {
46
- return nil
47
- }
48
- return fileManager.fileExists(atPath: expectedURL.path) ? expectedURL : nil
51
+ )
49
52
  } catch {
50
53
  return nil
51
54
  }
52
55
  }
53
56
 
57
+ static func readBundle(
58
+ hash: String,
59
+ bundleDropRoot: URL,
60
+ expectedRuntimeVersion: String? = nil,
61
+ fileManager: FileManager = .default
62
+ ) -> BundleDropOtaPointer? {
63
+ guard hash.range(of: "^[a-f0-9]{64}$", options: .regularExpression) != nil else {
64
+ return nil
65
+ }
66
+ return verifiedBundle(
67
+ hash: hash,
68
+ bundleDropRoot: bundleDropRoot,
69
+ expectedRuntimeVersion: expectedRuntimeVersion,
70
+ fileManager: fileManager
71
+ )
72
+ }
73
+
74
+ private static func verifiedBundle(
75
+ hash: String,
76
+ bundleDropRoot: URL,
77
+ expectedRuntimeVersion: String?,
78
+ fileManager: FileManager
79
+ ) -> BundleDropOtaPointer? {
80
+ let bundleURL = bundleDropRoot
81
+ .appendingPathComponent("bundles")
82
+ .appendingPathComponent(hash)
83
+ .appendingPathComponent("main.jsbundle")
84
+ let manifestURL = bundleURL
85
+ .deletingLastPathComponent()
86
+ .appendingPathComponent("bundle-manifest.json")
87
+ guard fileManager.fileExists(atPath: manifestURL.path),
88
+ let manifestData = try? Data(contentsOf: manifestURL),
89
+ let manifest = try? JSONSerialization.jsonObject(with: manifestData) as? [String: Any],
90
+ (manifest["manifestVersion"] as? NSNumber)?.intValue == 1,
91
+ manifest["bundleHash"] as? String == hash,
92
+ let runtimeVersion = manifest["runtimeVersion"] as? String,
93
+ expectedRuntimeVersion == nil || runtimeVersion == expectedRuntimeVersion,
94
+ verifyBundleDir(
95
+ bundleDir: bundleURL.deletingLastPathComponent(),
96
+ manifest: manifest,
97
+ expectedHash: hash,
98
+ fileManager: fileManager
99
+ ),
100
+ fileManager.fileExists(atPath: bundleURL.path) else {
101
+ return nil
102
+ }
103
+ return BundleDropOtaPointer(hash: hash, bundleURL: bundleURL, runtimeVersion: runtimeVersion)
104
+ }
105
+
106
+ static func writePointer(
107
+ named filename: String,
108
+ hash: String,
109
+ bundleDropRoot: URL,
110
+ fileManager: FileManager = .default
111
+ ) throws {
112
+ guard hash.range(of: "^[a-f0-9]{64}$", options: .regularExpression) != nil else {
113
+ throw NSError(
114
+ domain: "BundleDropStartupRecovery",
115
+ code: 1,
116
+ userInfo: [NSLocalizedDescriptionKey: "Bundle pointer hash is invalid"]
117
+ )
118
+ }
119
+ try fileManager.createDirectory(at: bundleDropRoot, withIntermediateDirectories: true)
120
+ let pointerURL = bundleDropRoot.appendingPathComponent(filename)
121
+ let pointer: [String: Any] = [
122
+ "hash": hash,
123
+ "updatedAt": ISO8601DateFormatter().string(from: Date()),
124
+ ]
125
+ let temporaryURL = bundleDropRoot.appendingPathComponent(
126
+ ".\(filename)-\(UUID().uuidString).tmp"
127
+ )
128
+ do {
129
+ try JSONSerialization.data(withJSONObject: pointer, options: [.sortedKeys])
130
+ .write(to: temporaryURL)
131
+ let handle = try FileHandle(forWritingTo: temporaryURL)
132
+ try handle.synchronize()
133
+ try handle.close()
134
+ if fileManager.fileExists(atPath: pointerURL.path) {
135
+ _ = try fileManager.replaceItemAt(pointerURL, withItemAt: temporaryURL)
136
+ } else {
137
+ try fileManager.moveItem(at: temporaryURL, to: pointerURL)
138
+ }
139
+ } catch {
140
+ try? fileManager.removeItem(at: temporaryURL)
141
+ throw error
142
+ }
143
+ }
144
+
145
+ static func deletePointer(
146
+ named filename: String,
147
+ bundleDropRoot: URL,
148
+ fileManager: FileManager = .default
149
+ ) throws {
150
+ let pointerURL = bundleDropRoot.appendingPathComponent(filename)
151
+ if fileManager.fileExists(atPath: pointerURL.path) {
152
+ try fileManager.removeItem(at: pointerURL)
153
+ }
154
+ }
155
+
54
156
  private static func verifyBundleDir(
55
157
  bundleDir: URL,
56
158
  manifest: [String: Any],
@@ -174,27 +276,32 @@ enum BundleDropOtaResolver {
174
276
  return String(encoded.dropFirst().dropLast()).replacingOccurrences(of: "\\/", with: "/")
175
277
  }
176
278
 
279
+ @discardableResult
177
280
  static func clearOtaState(
178
281
  bundleDropRoot: URL,
179
282
  documentsDirectory: URL,
180
283
  fileManager: FileManager = .default
181
- ) {
284
+ ) -> Bool {
182
285
  let filesToClear = [
183
286
  bundleDropRoot.appendingPathComponent("current.json"),
184
287
  bundleDropRoot.appendingPathComponent("previous.json"),
185
288
  bundleDropRoot.appendingPathComponent("state.json"),
289
+ bundleDropRoot.appendingPathComponent("recovery-ledger.json"),
186
290
  documentsDirectory.appendingPathComponent("bundle-info.json"),
187
291
  ]
188
292
 
293
+ var clearedAllFiles = true
189
294
  filesToClear.forEach { url in
190
295
  do {
191
296
  if fileManager.fileExists(atPath: url.path) {
192
297
  try fileManager.removeItem(at: url)
193
298
  }
194
299
  } catch {
300
+ clearedAllFiles = false
195
301
  // Best effort cleanup; a single bad file should not block native fallback.
196
302
  }
197
303
  }
304
+ return clearedAllFiles
198
305
  }
199
306
 
200
307
  static func hasOtaState(
@@ -206,6 +313,7 @@ enum BundleDropOtaResolver {
206
313
  bundleDropRoot.appendingPathComponent("current.json"),
207
314
  bundleDropRoot.appendingPathComponent("previous.json"),
208
315
  bundleDropRoot.appendingPathComponent("state.json"),
316
+ bundleDropRoot.appendingPathComponent("recovery-ledger.json"),
209
317
  documentsDirectory.appendingPathComponent("bundle-info.json"),
210
318
  ].contains { url in
211
319
  fileManager.fileExists(atPath: url.path)
@@ -226,7 +334,7 @@ enum BundleDropOtaResolver {
226
334
  documentsDirectory: documentsDirectory,
227
335
  fileManager: fileManager
228
336
  )
229
- clearOtaState(
337
+ let clearedAllFiles = clearOtaState(
230
338
  bundleDropRoot: bundleDropRoot,
231
339
  documentsDirectory: documentsDirectory,
232
340
  fileManager: fileManager
@@ -234,7 +342,7 @@ enum BundleDropOtaResolver {
234
342
  return BundleDropOtaResolveResult(
235
343
  bundleURL: nil,
236
344
  clearedOta: hadOtaState,
237
- storedVersion: currentBinaryVersion
345
+ storedVersion: clearedAllFiles ? currentBinaryVersion : storedBinaryVersion
238
346
  )
239
347
  }
240
348
 
@@ -0,0 +1,45 @@
1
+ import CryptoKit
2
+ import Foundation
3
+
4
+ enum BundleDropRuntimeCrypto {
5
+ static func sha256String(_ value: String) -> String {
6
+ SHA256.hash(data: Data(value.utf8)).map { String(format: "%02x", $0) }.joined()
7
+ }
8
+
9
+ static func verifyEs256Signature(
10
+ signingInput: String,
11
+ signatureBase64Url: String,
12
+ xBase64Url: String,
13
+ yBase64Url: String
14
+ ) throws -> Bool {
15
+ let signatureBytes = try decodeBase64Url(signatureBase64Url)
16
+ let x = try decodeBase64Url(xBase64Url)
17
+ let y = try decodeBase64Url(yBase64Url)
18
+ guard signatureBytes.count == 64 else {
19
+ throw error("ES256 signature must be 64 bytes")
20
+ }
21
+ guard x.count == 32 && y.count == 32 else {
22
+ throw error("P-256 coordinates must be 32 bytes")
23
+ }
24
+
25
+ let publicKey = try P256.Signing.PublicKey(
26
+ x963Representation: Data([0x04]) + x + y
27
+ )
28
+ let signature = try P256.Signing.ECDSASignature(rawRepresentation: signatureBytes)
29
+ return publicKey.isValidSignature(signature, for: Data(signingInput.utf8))
30
+ }
31
+
32
+ private static func decodeBase64Url(_ value: String) throws -> Data {
33
+ var normalized = value.replacingOccurrences(of: "-", with: "+")
34
+ .replacingOccurrences(of: "_", with: "/")
35
+ normalized += String(repeating: "=", count: (4 - normalized.count % 4) % 4)
36
+ guard let data = Data(base64Encoded: normalized) else {
37
+ throw error("Invalid base64url value")
38
+ }
39
+ return data
40
+ }
41
+
42
+ private static func error(_ message: String) -> NSError {
43
+ NSError(domain: "BundleDrop", code: 1, userInfo: [NSLocalizedDescriptionKey: message])
44
+ }
45
+ }