@gfean/react-native-bundle-drop 0.3.8 → 0.4.1

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 (77) hide show
  1. package/BundleDrop.podspec +9 -2
  2. package/README.md +19 -0
  3. package/android/build.gradle +25 -4
  4. package/android/src/main/cpp/CMakeLists.txt +33 -0
  5. package/android/src/main/cpp/bundle_drop_xdelta_jni.c +55 -0
  6. package/android/src/main/java/com/bundledrop/BundleDropBundleVerifier.kt +73 -0
  7. package/android/src/main/java/com/bundledrop/BundleDropFileOps.kt +193 -8
  8. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +60 -7
  9. package/android/src/main/java/com/bundledrop/BundleDropOtaPrefs.kt +2 -12
  10. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +208 -3
  11. package/android/src/main/java/com/bundledrop/BundleDropXdeltaNative.kt +57 -0
  12. package/ios/BundleDropBridge.m +27 -0
  13. package/ios/BundleDropBundleVerifier.swift +106 -0
  14. package/ios/BundleDropFileOps.swift +149 -0
  15. package/ios/BundleDropModule.swift +100 -11
  16. package/ios/BundleDropOtaResolver.swift +149 -3
  17. package/ios/BundleDropZipExtractor.m +75 -3
  18. package/lib/CLI/cli.js +1 -8
  19. package/lib/CLI/scripts/upload-cli.d.ts +0 -1
  20. package/lib/CLI/scripts/upload-cli.js +26 -20
  21. package/lib/api/client.d.ts +11 -1
  22. package/lib/api/client.js +84 -17
  23. package/lib/api/clientApi.d.ts +2 -1
  24. package/lib/api/clientApi.js +9 -0
  25. package/lib/api/types.d.ts +65 -13
  26. package/lib/bundleInfo.d.ts +2 -0
  27. package/lib/fs/bundlePointer.d.ts +2 -1
  28. package/lib/fs/bundlePointer.js +34 -6
  29. package/lib/fs/fsUtils.js +4 -1
  30. package/lib/injectImageResolver.js +135 -45
  31. package/lib/install/bundleInstallShared.d.ts +8 -0
  32. package/lib/install/bundleInstallShared.js +97 -0
  33. package/lib/install/bundleVerification.d.ts +5 -0
  34. package/lib/install/bundleVerification.js +34 -0
  35. package/lib/install/installFromZip.d.ts +2 -5
  36. package/lib/install/installFromZip.js +33 -62
  37. package/lib/loadConfig.js +12 -1
  38. package/lib/manager/downloadAndInstall.d.ts +9 -0
  39. package/lib/manager/downloadAndInstall.js +84 -24
  40. package/lib/manager/reporting.js +26 -2
  41. package/lib/manager/rollbackState.js +21 -12
  42. package/lib/manager/updateCheck.js +89 -11
  43. package/lib/manager/updateState.js +3 -9
  44. package/lib/manifest/bundleManifest.d.ts +33 -0
  45. package/lib/manifest/bundleManifest.js +298 -0
  46. package/lib/native/bundleDropNative.js +1 -2
  47. package/lib/native/fs.d.ts +14 -0
  48. package/lib/native/fs.js +35 -0
  49. package/lib/patch-engine/installFromPatchSet.d.ts +16 -0
  50. package/lib/patch-engine/installFromPatchSet.js +143 -0
  51. package/lib/patch-engine/patchOperations.d.ts +33 -0
  52. package/lib/patch-engine/patchOperations.js +77 -0
  53. package/lib/patch-engine/patchTransport.d.ts +18 -0
  54. package/lib/patch-engine/patchTransport.js +81 -0
  55. package/lib/patchAlgorithms.d.ts +4 -0
  56. package/lib/patchAlgorithms.js +9 -0
  57. package/lib/runtime/service.js +43 -9
  58. package/lib/scripts/bundle.d.ts +3 -0
  59. package/lib/scripts/bundle.js +184 -36
  60. package/lib/scripts/download-bundle.js +18 -7
  61. package/lib/scripts/upload-bundle.js +25 -28
  62. package/package.json +44 -5
  63. package/third_party/xdelta/NOTICE +7 -0
  64. package/third_party/xdelta/PROVENANCE.md +10 -0
  65. package/third_party/xdelta/bundle_drop_xdelta.c +252 -0
  66. package/third_party/xdelta/bundle_drop_xdelta.h +26 -0
  67. package/third_party/xdelta/xdelta3/LICENSE +176 -0
  68. package/third_party/xdelta/xdelta3/config.h +34 -0
  69. package/third_party/xdelta/xdelta3/xdelta3-cfgs.h +171 -0
  70. package/third_party/xdelta/xdelta3/xdelta3-decode.h +1219 -0
  71. package/third_party/xdelta/xdelta3/xdelta3-hash.h +159 -0
  72. package/third_party/xdelta/xdelta3/xdelta3-internal.h +385 -0
  73. package/third_party/xdelta/xdelta3/xdelta3-list.h +127 -0
  74. package/third_party/xdelta/xdelta3/xdelta3.c +4819 -0
  75. package/third_party/xdelta/xdelta3/xdelta3.h +1476 -0
  76. package/lib/CLI/scripts/init-native-config.d.ts +0 -18
  77. package/lib/CLI/scripts/init-native-config.js +0 -539
@@ -11,10 +11,17 @@ Pod::Spec.new do |s|
11
11
  s.license = package["license"]
12
12
  s.authors = package["author"]
13
13
 
14
- s.platforms = { :ios => min_ios_version_supported }
14
+ s.platforms = { :ios => "13.0" }
15
15
  s.source = { :git => ".git", :tag => "#{s.version}" }
16
16
 
17
- s.source_files = "ios/**/*.{h,m,mm,swift}"
17
+ s.source_files = "ios/**/*.{h,m,mm,swift}", "third_party/xdelta/**/*.{c,h}"
18
+ s.public_header_files = "ios/BundleDropLocator.h", "ios/BundleDropZipExtractor.h"
19
+ s.private_header_files = "third_party/xdelta/**/*.h"
20
+ s.pod_target_xcconfig = {
21
+ "GCC_C_LANGUAGE_STANDARD" => "c11",
22
+ "GCC_PREPROCESSOR_DEFINITIONS" => "$(inherited) HAVE_CONFIG_H=1",
23
+ "HEADER_SEARCH_PATHS" => "$(inherited) \"${PODS_TARGET_SRCROOT}/third_party/xdelta\" \"${PODS_TARGET_SRCROOT}/third_party/xdelta/xdelta3\""
24
+ }
18
25
  s.libraries = "z"
19
26
  s.swift_version = "5.0"
20
27
 
package/README.md CHANGED
@@ -94,6 +94,23 @@ Choose how updates are applied:
94
94
 
95
95
  `on-next-launch` is the safest default for most apps.
96
96
 
97
+ ## Hybrid OTA Delivery
98
+
99
+ BundleDrop installs complete immutable bundle folders, identified by a canonical
100
+ `bundleHash` for the full reconstructed file tree. Patch transports are only a
101
+ download optimization: the SDK reconstructs a complete target folder, validates
102
+ the manifest contract in JS, verifies file hashes/sizes with native batch
103
+ verification, then promotes `bundle-drop/bundles/{bundleHash}`.
104
+ The SDK always supports `asset-only-v1` patch sets and advertises
105
+ `xdelta3-vcdiff` when native xdelta support passes its probe.
106
+
107
+ The current production manifest contract is `manifestVersion: 1`. This is not a
108
+ legacy compatibility mode; it is the only accepted canonical manifest after the
109
+ hard shift. `jsBundleHash` is retained as metadata only.
110
+
111
+ When patch transport is unavailable or fails, the SDK falls back to the signed
112
+ full ZIP. Rollback remains a local pointer switch between verified bundle hashes.
113
+
97
114
  ---
98
115
 
99
116
  ## Why Not App Store Updates?
@@ -136,6 +153,8 @@ Full documentation:
136
153
 
137
154
  - Requires a BundleDrop backend and project setup
138
155
  - Supports React Native on iOS and Android
156
+ - Requires iOS 13.0 or newer
157
+ - Native package changes require rebuilding the host app; `nativeVersion` tracks that boundary
139
158
  - Best suited for bare React Native apps
140
159
 
141
160
  ---
@@ -52,6 +52,13 @@ android {
52
52
  defaultConfig {
53
53
  minSdkVersion getExtOrIntegerDefault("minSdkVersion")
54
54
  targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
55
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
56
+
57
+ externalNativeBuild {
58
+ cmake {
59
+ arguments "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
60
+ }
61
+ }
55
62
  }
56
63
 
57
64
  buildTypes {
@@ -72,6 +79,13 @@ android {
72
79
  kotlinOptions {
73
80
  jvmTarget = "1.8"
74
81
  }
82
+
83
+ externalNativeBuild {
84
+ cmake {
85
+ path "src/main/cpp/CMakeLists.txt"
86
+ version "3.22.1"
87
+ }
88
+ }
75
89
  }
76
90
 
77
91
  afterEvaluate {
@@ -97,10 +111,17 @@ dependencies {
97
111
  implementation "com.facebook.react:react-android"
98
112
  }
99
113
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
100
- testImplementation "junit:junit:4.13.2"
101
- testImplementation "org.json:json:20231013"
102
- testImplementation "androidx.test:core:1.6.1"
103
- testImplementation "org.robolectric:robolectric:4.14.1"
114
+
115
+ if (project.hasProperty("standalone")) {
116
+ testImplementation "junit:junit:4.13.2"
117
+ testImplementation "org.json:json:20231013"
118
+ testImplementation "androidx.test:core:1.6.1"
119
+ testImplementation "org.robolectric:robolectric:4.14.1"
120
+ androidTestImplementation "junit:junit:4.13.2"
121
+ androidTestImplementation "androidx.test:core:1.6.1"
122
+ androidTestImplementation "androidx.test:runner:1.6.2"
123
+ androidTestImplementation "androidx.test.ext:junit:1.2.1"
124
+ }
104
125
  }
105
126
 
106
127
  // ---------------------------------------------------------------------------
@@ -0,0 +1,33 @@
1
+ cmake_minimum_required(VERSION 3.18.1)
2
+
3
+ project(bundledropxdelta C)
4
+
5
+ set(XDELTA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../../../third_party/xdelta")
6
+
7
+ add_library(
8
+ bundledropxdelta
9
+ SHARED
10
+ bundle_drop_xdelta_jni.c
11
+ "${XDELTA_ROOT}/bundle_drop_xdelta.c"
12
+ "${XDELTA_ROOT}/xdelta3/xdelta3.c"
13
+ )
14
+
15
+ target_include_directories(
16
+ bundledropxdelta
17
+ PRIVATE
18
+ "${XDELTA_ROOT}"
19
+ "${XDELTA_ROOT}/xdelta3"
20
+ )
21
+
22
+ set_target_properties(
23
+ bundledropxdelta
24
+ PROPERTIES
25
+ C_STANDARD 11
26
+ C_STANDARD_REQUIRED ON
27
+ )
28
+
29
+ target_compile_definitions(
30
+ bundledropxdelta
31
+ PRIVATE
32
+ HAVE_CONFIG_H=1
33
+ )
@@ -0,0 +1,55 @@
1
+ #include <jni.h>
2
+
3
+ #include "bundle_drop_xdelta.h"
4
+
5
+ JNIEXPORT jboolean JNICALL
6
+ Java_com_bundledrop_BundleDropXdeltaNative_nativeSupportsXdelta(JNIEnv *env, jobject self) {
7
+ (void)env;
8
+ (void)self;
9
+ return bd_xdelta_self_test() ? JNI_TRUE : JNI_FALSE;
10
+ }
11
+
12
+ JNIEXPORT jstring JNICALL
13
+ Java_com_bundledrop_BundleDropXdeltaNative_nativeVersion(JNIEnv *env, jobject self) {
14
+ (void)self;
15
+ return (*env)->NewStringUTF(env, bd_xdelta_version());
16
+ }
17
+
18
+ JNIEXPORT jstring JNICALL
19
+ Java_com_bundledrop_BundleDropXdeltaNative_nativeApplyXdelta(
20
+ JNIEnv *env,
21
+ jobject self,
22
+ jstring base_path,
23
+ jstring patch_path,
24
+ jstring output_path
25
+ ) {
26
+ (void)self;
27
+ const char *base = (*env)->GetStringUTFChars(env, base_path, 0);
28
+ const char *patch = (*env)->GetStringUTFChars(env, patch_path, 0);
29
+ const char *output = (*env)->GetStringUTFChars(env, output_path, 0);
30
+ char error[512] = {0};
31
+
32
+ if (base == NULL || patch == NULL || output == NULL) {
33
+ if (base != NULL) {
34
+ (*env)->ReleaseStringUTFChars(env, base_path, base);
35
+ }
36
+ if (patch != NULL) {
37
+ (*env)->ReleaseStringUTFChars(env, patch_path, patch);
38
+ }
39
+ if (output != NULL) {
40
+ (*env)->ReleaseStringUTFChars(env, output_path, output);
41
+ }
42
+ return (*env)->NewStringUTF(env, "xdelta JNI string conversion failed");
43
+ }
44
+
45
+ int result = bd_xdelta_apply(base, patch, output, error, sizeof(error));
46
+
47
+ (*env)->ReleaseStringUTFChars(env, base_path, base);
48
+ (*env)->ReleaseStringUTFChars(env, patch_path, patch);
49
+ (*env)->ReleaseStringUTFChars(env, output_path, output);
50
+
51
+ if (result == 0) {
52
+ return NULL;
53
+ }
54
+ return (*env)->NewStringUTF(env, error[0] ? error : "xdelta apply failed");
55
+ }
@@ -0,0 +1,73 @@
1
+ package com.bundledrop
2
+
3
+ import org.json.JSONObject
4
+ import java.io.File
5
+ import java.io.IOException
6
+
7
+ object BundleDropBundleVerifier {
8
+ private const val MANIFEST_FILE = "bundle-manifest.json"
9
+
10
+ fun verifyBundleFiles(bundleDir: File, manifestFile: File) {
11
+ val manifest = try {
12
+ JSONObject(manifestFile.readText(Charsets.UTF_8))
13
+ } catch (e: Exception) {
14
+ throw IOException("Malformed bundle manifest", e)
15
+ }
16
+ val files = manifest.optJSONArray("files")
17
+ ?: throw IOException("Bundle manifest must include files")
18
+ verifyManifestFiles(bundleDir, files)
19
+ }
20
+
21
+ fun verifyManifestFiles(bundleDir: File, files: org.json.JSONArray) {
22
+ val allowed = mutableSetOf(MANIFEST_FILE)
23
+
24
+ for (i in 0 until files.length()) {
25
+ val file = files.optJSONObject(i)
26
+ ?: throw IOException("Invalid manifest file entry at index $i")
27
+ val relativePath = file.optString("path", "")
28
+ if (!isSafeManifestPath(relativePath)) {
29
+ throw SecurityException("Invalid manifest path: $relativePath")
30
+ }
31
+ if (!allowed.add(relativePath)) {
32
+ throw IOException("Duplicate manifest file path: $relativePath")
33
+ }
34
+
35
+ val expectedSize = file.optLong("size", -1L)
36
+ val expectedSha = file.optString("sha256", "")
37
+ val fullPath = File(bundleDir, relativePath)
38
+ if (!fullPath.exists()) {
39
+ throw IOException("Manifest file missing: $relativePath")
40
+ }
41
+ if (fullPath.isDirectory) {
42
+ throw IOException("Manifest file is a directory: $relativePath")
43
+ }
44
+ if (fullPath.length() != expectedSize) {
45
+ throw IOException("Manifest file size mismatch for $relativePath")
46
+ }
47
+ if (BundleDropFileOps.sha256File(fullPath) != expectedSha) {
48
+ throw IOException("Manifest file hash mismatch for $relativePath")
49
+ }
50
+ }
51
+
52
+ val actualFiles = listRelativeFiles(bundleDir)
53
+ val extraFile = actualFiles.firstOrNull { !allowed.contains(it) }
54
+ if (extraFile != null) {
55
+ throw IOException("Unmanifested file in bundle archive: $extraFile")
56
+ }
57
+ }
58
+
59
+ fun isSafeManifestPath(path: String): Boolean {
60
+ return path.isNotBlank() &&
61
+ !path.startsWith("/") &&
62
+ !path.contains("\\") &&
63
+ !path.contains("\u0000") &&
64
+ path.split("/").none { it.isBlank() || it == "." || it == ".." }
65
+ }
66
+
67
+ private fun listRelativeFiles(root: File, dir: File = root, prefix: String = ""): List<String> {
68
+ return dir.listFiles()?.flatMap { file ->
69
+ val relativePath = if (prefix.isBlank()) file.name else "$prefix/${file.name}"
70
+ if (file.isDirectory) listRelativeFiles(root, file, relativePath) else listOf(relativePath)
71
+ } ?: emptyList()
72
+ }
73
+ }
@@ -3,10 +3,18 @@ package com.bundledrop
3
3
  import java.io.File
4
4
  import java.io.FileInputStream
5
5
  import java.io.FileOutputStream
6
+ import java.io.RandomAccessFile
6
7
  import java.net.URL
8
+ import java.security.MessageDigest
7
9
  import java.util.zip.ZipInputStream
8
10
 
9
11
  object BundleDropFileOps {
12
+ private const val PATCH_TARGET_DIR_PREFIX = "_patch_target_"
13
+ private const val ZIP_EOCD_SIGNATURE = 0x06054b50L
14
+ private const val ZIP_CENTRAL_DIRECTORY_SIGNATURE = 0x02014b50L
15
+ private const val ZIP_SYMLINK_FILE_TYPE = 0xA000
16
+ private const val ZIP_FILE_TYPE_MASK = 0xF000
17
+ private val BUNDLE_HASH_REGEX = Regex("^[a-f0-9]{64}$")
10
18
 
11
19
  fun validateHttpUrl(url: String): URL {
12
20
  val parsed = URL(url)
@@ -31,19 +39,26 @@ object BundleDropFileOps {
31
39
  maxTotalBytes: Long = 512L * 1024 * 1024,
32
40
  ): List<String> {
33
41
  val destDir = File(destPath)
34
- java.util.zip.ZipFile(zipPath).use { /* validate central directory before extraction */ }
42
+ validateZipCentralDirectory(zipPath)
35
43
  if (!destDir.exists()) destDir.mkdirs()
36
44
 
37
45
  val filenames = mutableListOf<String>()
46
+ val seenEntries = mutableSetOf<String>()
38
47
  val buf = ByteArray(8192)
39
48
  var totalWritten = 0L
49
+ val destCanonicalPath = destDir.canonicalPath
40
50
 
41
51
  ZipInputStream(FileInputStream(zipPath)).use { zis ->
42
52
  var entry = zis.nextEntry
43
53
  while (entry != null) {
54
+ val normalizedName = normalizeZipEntryName(entry.name)
55
+ if (!seenEntries.add(normalizedName)) {
56
+ throw SecurityException("Duplicate ZIP entry: $normalizedName")
57
+ }
58
+
44
59
  if (!entry.isDirectory) {
45
- val outFile = File(destDir, entry.name)
46
- if (!outFile.canonicalPath.startsWith(destDir.canonicalPath + File.separator)) {
60
+ val outFile = File(destDir, normalizedName)
61
+ if (!outFile.canonicalPath.startsWith(destCanonicalPath + File.separator)) {
47
62
  throw SecurityException("Zip entry outside target dir: ${entry.name}")
48
63
  }
49
64
  outFile.parentFile?.mkdirs()
@@ -62,10 +77,14 @@ object BundleDropFileOps {
62
77
  fos.write(buf, 0, len)
63
78
  }
64
79
  }
65
- filenames.add(entry.name)
80
+ if (java.nio.file.Files.isSymbolicLink(outFile.toPath())) {
81
+ try { outFile.delete() } catch (_: Exception) {}
82
+ throw SecurityException("Symlink ZIP entries are not allowed: $normalizedName")
83
+ }
84
+ filenames.add(normalizedName)
66
85
  } else {
67
- val dirFile = File(destDir, entry.name)
68
- if (!dirFile.canonicalPath.startsWith(destDir.canonicalPath + File.separator)) {
86
+ val dirFile = File(destDir, normalizedName)
87
+ if (!dirFile.canonicalPath.startsWith(destCanonicalPath + File.separator)) {
69
88
  throw SecurityException("Zip entry outside target dir: ${entry.name}")
70
89
  }
71
90
  dirFile.mkdirs()
@@ -78,12 +97,178 @@ object BundleDropFileOps {
78
97
  return filenames
79
98
  }
80
99
 
100
+ private fun normalizeZipEntryName(name: String?): String {
101
+ if (name.isNullOrEmpty() || name.indexOf('\u0000') >= 0 || name.contains('\\')) {
102
+ throw SecurityException("Unsafe ZIP entry path: $name")
103
+ }
104
+ if (name.startsWith("/") || Regex("^[A-Za-z]:[\\\\/].*").matches(name)) {
105
+ throw SecurityException("Unsafe ZIP entry path: $name")
106
+ }
107
+
108
+ val normalized = name.removeSuffix("/")
109
+ if (normalized.isEmpty()) {
110
+ throw SecurityException("Unsafe ZIP entry path: $name")
111
+ }
112
+ if (normalized.split('/').any { it.isEmpty() || it == "." || it == ".." }) {
113
+ throw SecurityException("Unsafe ZIP entry path: $name")
114
+ }
115
+ return normalized
116
+ }
117
+
118
+ private fun validateZipCentralDirectory(zipPath: String) {
119
+ RandomAccessFile(zipPath, "r").use { raf ->
120
+ val fileLength = raf.length()
121
+ if (fileLength < 22) {
122
+ throw java.io.IOException("Invalid ZIP: end-of-central-directory not found")
123
+ }
124
+
125
+ val readSize = minOf(fileLength, 22L + 65_535L).toInt()
126
+ val tail = ByteArray(readSize)
127
+ raf.seek(fileLength - readSize)
128
+ raf.readFully(tail)
129
+
130
+ var eocdOffset = -1
131
+ for (index in readSize - 22 downTo 0) {
132
+ if (readLeInt(tail, index) == ZIP_EOCD_SIGNATURE) {
133
+ eocdOffset = index
134
+ break
135
+ }
136
+ }
137
+ if (eocdOffset < 0) {
138
+ throw java.io.IOException("Invalid ZIP: end-of-central-directory not found")
139
+ }
140
+
141
+ val entryCount = readLeShort(tail, eocdOffset + 10)
142
+ val centralDirectoryOffset = readLeInt(tail, eocdOffset + 16)
143
+ raf.seek(centralDirectoryOffset)
144
+
145
+ val header = ByteArray(46)
146
+ repeat(entryCount) {
147
+ raf.readFully(header)
148
+ if (readLeInt(header, 0) != ZIP_CENTRAL_DIRECTORY_SIGNATURE) {
149
+ throw java.io.IOException("Invalid ZIP: malformed central directory")
150
+ }
151
+
152
+ val nameLength = readLeShort(header, 28)
153
+ val extraLength = readLeShort(header, 30)
154
+ val commentLength = readLeShort(header, 32)
155
+ val externalAttributes = readLeInt(header, 38)
156
+ val nameBytes = ByteArray(nameLength)
157
+ raf.readFully(nameBytes)
158
+ val entryName = String(nameBytes, Charsets.UTF_8)
159
+
160
+ if (isSymlinkExternalAttribute(externalAttributes)) {
161
+ throw SecurityException("Symlink ZIP entries are not allowed: $entryName")
162
+ }
163
+ normalizeZipEntryName(entryName)
164
+ raf.skipBytes(extraLength + commentLength)
165
+ }
166
+ }
167
+ }
168
+
169
+ private fun readLeShort(bytes: ByteArray, offset: Int): Int {
170
+ return (bytes[offset].toInt() and 0xff) or
171
+ ((bytes[offset + 1].toInt() and 0xff) shl 8)
172
+ }
173
+
174
+ private fun readLeInt(bytes: ByteArray, offset: Int): Long {
175
+ return ((bytes[offset].toLong() and 0xffL) or
176
+ ((bytes[offset + 1].toLong() and 0xffL) shl 8) or
177
+ ((bytes[offset + 2].toLong() and 0xffL) shl 16) or
178
+ ((bytes[offset + 3].toLong() and 0xffL) shl 24)) and 0xffffffffL
179
+ }
180
+
181
+ private fun isSymlinkExternalAttribute(externalAttributes: Long): Boolean {
182
+ val unixMode = ((externalAttributes shr 16) and 0xffffL).toInt()
183
+ return (unixMode and ZIP_FILE_TYPE_MASK) == ZIP_SYMLINK_FILE_TYPE
184
+ }
185
+
81
186
  fun moveFile(src: File, dest: File) {
82
187
  dest.parentFile?.mkdirs()
83
188
  if (!src.renameTo(dest)) {
84
- src.copyTo(dest, overwrite = true)
85
- src.delete()
189
+ try {
190
+ if (src.isDirectory) {
191
+ src.copyRecursively(dest, overwrite = true)
192
+ src.deleteRecursively()
193
+ } else {
194
+ src.copyTo(dest, overwrite = true)
195
+ src.delete()
196
+ }
197
+ } catch (error: Exception) {
198
+ try { if (dest.isDirectory) dest.deleteRecursively() else dest.delete() } catch (_: Exception) {}
199
+ throw error
200
+ }
201
+ }
202
+ }
203
+
204
+ fun copyFile(src: File, dest: File) {
205
+ dest.parentFile?.mkdirs()
206
+ src.copyTo(dest, overwrite = true)
207
+ }
208
+
209
+ fun sha256File(file: File): String {
210
+ val digest = MessageDigest.getInstance("SHA-256")
211
+ FileInputStream(file).use { input ->
212
+ val buffer = ByteArray(1024 * 64)
213
+ while (true) {
214
+ val read = input.read(buffer)
215
+ if (read <= 0) break
216
+ digest.update(buffer, 0, read)
217
+ }
218
+ }
219
+ return digest.digest().joinToString("") { "%02x".format(it) }
220
+ }
221
+
222
+ fun fileSize(file: File): Long {
223
+ if (!file.exists()) {
224
+ throw java.io.FileNotFoundException("File not found: ${file.absolutePath}")
86
225
  }
226
+ return file.length()
227
+ }
228
+
229
+ fun supportsXdelta(): Boolean {
230
+ return BundleDropXdeltaNative.supportsXdelta()
231
+ }
232
+
233
+ fun applyXdelta(base: File, patch: File, output: File) {
234
+ validateXdeltaOutputPath(output)
235
+ BundleDropXdeltaNative.applyXdelta(base, patch, output)
236
+ }
237
+
238
+ private fun validateXdeltaOutputPath(output: File) {
239
+ val rawPath = output.path
240
+ if (rawPath.indexOf('\u0000') >= 0) {
241
+ throw SecurityException("xdelta output path contains a null byte")
242
+ }
243
+ if (rawPath.split('/', '\\').any { it == ".." }) {
244
+ throw SecurityException("xdelta output path must not contain traversal segments")
245
+ }
246
+
247
+ val absoluteOutput = output.absoluteFile
248
+ val normalizedPath = absoluteOutput.canonicalPath
249
+ val parts = normalizedPath
250
+ .split(File.separatorChar)
251
+ .filter { it.isNotEmpty() }
252
+
253
+ for (index in 0 until parts.size - 3) {
254
+ if (parts[index] != "bundle-drop" || parts[index + 1] != "bundles") {
255
+ continue
256
+ }
257
+
258
+ val patchTargetDir = parts[index + 2]
259
+ if (!patchTargetDir.startsWith(PATCH_TARGET_DIR_PREFIX)) {
260
+ throw SecurityException("xdelta output path must not target an active bundle folder")
261
+ }
262
+
263
+ val targetHash = patchTargetDir.removePrefix(PATCH_TARGET_DIR_PREFIX)
264
+ if (!BUNDLE_HASH_REGEX.matches(targetHash)) {
265
+ throw SecurityException("xdelta output path must use a valid patch target temp directory")
266
+ }
267
+
268
+ return
269
+ }
270
+
271
+ throw SecurityException("xdelta output path must be inside bundle-drop/bundles/_patch_target_<bundleHash>")
87
272
  }
88
273
 
89
274
  fun downloadToFile(
@@ -68,12 +68,6 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
68
68
  }
69
69
  }
70
70
 
71
- // Backward compat
72
- @ReactMethod
73
- fun forceReloadJS() {
74
- restartReactNative()
75
- }
76
-
77
71
  @ReactMethod(isBlockingSynchronousMethod = true)
78
72
  fun getImageManifestSync(): String? {
79
73
  return readImageManifestRaw()
@@ -180,6 +174,65 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
180
174
  }
181
175
  }
182
176
 
177
+ @ReactMethod
178
+ fun fsCopyFile(src: String, dest: String, promise: Promise) {
179
+ try {
180
+ BundleDropFileOps.copyFile(File(src), File(dest))
181
+ promise.resolve(null)
182
+ } catch (e: Exception) {
183
+ promise.reject("ERR_COPY", e.message, e)
184
+ }
185
+ }
186
+
187
+ @ReactMethod
188
+ fun fsSha256File(path: String, promise: Promise) {
189
+ try {
190
+ promise.resolve(BundleDropFileOps.sha256File(File(path)))
191
+ } catch (e: Exception) {
192
+ promise.reject("ERR_SHA256", e.message, e)
193
+ }
194
+ }
195
+
196
+ @ReactMethod
197
+ fun fsFileSize(path: String, promise: Promise) {
198
+ try {
199
+ promise.resolve(BundleDropFileOps.fileSize(File(path)).toDouble())
200
+ } catch (e: Exception) {
201
+ promise.reject("ERR_FILE_SIZE", e.message, e)
202
+ }
203
+ }
204
+
205
+ @ReactMethod
206
+ fun fsApplyXdelta(basePath: String, patchPath: String, outputPath: String, promise: Promise) {
207
+ Thread {
208
+ try {
209
+ BundleDropFileOps.applyXdelta(File(basePath), File(patchPath), File(outputPath))
210
+ promise.resolve(null)
211
+ } catch (e: Exception) {
212
+ promise.reject("ERR_XDELTA", e.message, e)
213
+ }
214
+ }.start()
215
+ }
216
+
217
+ @ReactMethod
218
+ fun fsVerifyBundleFiles(bundleDir: String, manifestPath: String, promise: Promise) {
219
+ Thread {
220
+ try {
221
+ BundleDropBundleVerifier.verifyBundleFiles(File(bundleDir), File(manifestPath))
222
+ val result = Arguments.createMap()
223
+ result.putBoolean("verified", true)
224
+ promise.resolve(result)
225
+ } catch (e: Exception) {
226
+ promise.reject("ERR_VERIFY_BUNDLE", e.message, e)
227
+ }
228
+ }.start()
229
+ }
230
+
231
+ @ReactMethod
232
+ fun fsSupportsXdelta(promise: Promise) {
233
+ promise.resolve(BundleDropFileOps.supportsXdelta())
234
+ }
235
+
183
236
  @ReactMethod
184
237
  fun fsUnzip(zipPath: String, destPath: String, promise: Promise) {
185
238
  Thread {
@@ -218,4 +271,4 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
218
271
  map["LibraryDirectoryPath"] = context.filesDir.absolutePath
219
272
  return map
220
273
  }
221
- }
274
+ }
@@ -8,13 +8,10 @@ import android.content.SharedPreferences
8
8
  *
9
9
  * **Storage:** [PREFS_NAME] SharedPreferences file. [KEY_OTA_ENABLED] matches iOS
10
10
  * `BundleDropLocator.otaEnabledKey` (`bundledrop_ota_enabled`) for cross-platform debugging.
11
- * Older releases used [LEGACY_KEY_OTA_ENABLED]; it is still read when the new key is absent,
12
- * and is removed when JS persists a value via [writeOtaEnabled].
13
11
  */
14
12
  object BundleDropOtaPrefs {
15
13
  const val PREFS_NAME = "BundleDropPrefs"
16
14
  const val KEY_OTA_ENABLED = "bundledrop_ota_enabled"
17
- private const val LEGACY_KEY_OTA_ENABLED = "ota_enabled"
18
15
 
19
16
  fun preferences(context: Context): SharedPreferences =
20
17
  context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
@@ -22,20 +19,13 @@ object BundleDropOtaPrefs {
22
19
  fun isOtaEnabled(context: Context): Boolean = readIsOtaEnabled(preferences(context))
23
20
 
24
21
  fun readIsOtaEnabled(prefs: SharedPreferences): Boolean {
25
- val hasNew = prefs.contains(KEY_OTA_ENABLED)
26
- val hasLegacy = prefs.contains(LEGACY_KEY_OTA_ENABLED)
27
- if (!hasNew && !hasLegacy) return true
28
- return if (hasNew) {
29
- prefs.getBoolean(KEY_OTA_ENABLED, true)
30
- } else {
31
- prefs.getBoolean(LEGACY_KEY_OTA_ENABLED, true)
32
- }
22
+ if (!prefs.contains(KEY_OTA_ENABLED)) return true
23
+ return prefs.getBoolean(KEY_OTA_ENABLED, true)
33
24
  }
34
25
 
35
26
  fun writeOtaEnabled(context: Context, enabled: Boolean) {
36
27
  preferences(context).edit()
37
28
  .putBoolean(KEY_OTA_ENABLED, enabled)
38
- .remove(LEGACY_KEY_OTA_ENABLED)
39
29
  .apply()
40
30
  }
41
31
  }