@gfean/react-native-bundle-drop 0.3.9 → 0.4.2

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 (80) hide show
  1. package/BundleDrop.podspec +9 -2
  2. package/README.md +19 -0
  3. package/android/build.gradle +43 -4
  4. package/android/src/main/cpp/CMakeLists.txt +45 -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 +98 -36
  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 +82 -75
  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 -68
  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 +197 -43
  60. package/lib/scripts/download-bundle.js +18 -7
  61. package/package.json +44 -6
  62. package/third_party/xdelta/NOTICE +7 -0
  63. package/third_party/xdelta/PROVENANCE.md +10 -0
  64. package/third_party/xdelta/bundle_drop_xdelta.c +252 -0
  65. package/third_party/xdelta/bundle_drop_xdelta.h +26 -0
  66. package/third_party/xdelta/xdelta3/LICENSE +176 -0
  67. package/third_party/xdelta/xdelta3/config.h +34 -0
  68. package/third_party/xdelta/xdelta3/xdelta3-cfgs.h +171 -0
  69. package/third_party/xdelta/xdelta3/xdelta3-decode.h +1219 -0
  70. package/third_party/xdelta/xdelta3/xdelta3-hash.h +159 -0
  71. package/third_party/xdelta/xdelta3/xdelta3-internal.h +385 -0
  72. package/third_party/xdelta/xdelta3/xdelta3-list.h +127 -0
  73. package/third_party/xdelta/xdelta3/xdelta3.c +4819 -0
  74. package/third_party/xdelta/xdelta3/xdelta3.h +1476 -0
  75. package/lib/CLI/scripts/init-native-config.d.ts +0 -18
  76. package/lib/CLI/scripts/init-native-config.js +0 -539
  77. package/lib/assetExtensions.d.ts +0 -4
  78. package/lib/assetExtensions.js +0 -35
  79. package/lib/scripts/upload-bundle.d.ts +0 -9
  80. package/lib/scripts/upload-bundle.js +0 -320
@@ -1,6 +1,7 @@
1
1
  package com.bundledrop
2
2
 
3
3
  import java.io.File
4
+ import java.security.MessageDigest
4
5
  import org.json.JSONObject
5
6
 
6
7
  /**
@@ -8,6 +9,7 @@ import org.json.JSONObject
8
9
  * All file system operations go through the provided root directory.
9
10
  */
10
11
  object BundleDropOtaResolver {
12
+ private val bundleHashPattern = Regex("^[a-f0-9]{64}$")
11
13
 
12
14
  data class ResolveResult(
13
15
  val bundlePath: String?,
@@ -21,13 +23,162 @@ object BundleDropOtaResolver {
21
23
  if (!jsonFile.exists()) return null
22
24
  val raw = jsonFile.readText()
23
25
  val parsed = JSONObject(raw)
24
- val path = parsed.optString("bundlePath", null)
25
- if (!path.isNullOrEmpty() && File(path).exists()) path else null
26
+ val hash = parsed.optString("hash", "")
27
+ if (!bundleHashPattern.matches(hash)) return null
28
+ val expectedBundle = File(File(File(bundleDropRoot, "bundles"), hash), "main.jsbundle")
29
+ val bundleDir = expectedBundle.parentFile ?: return null
30
+ val manifestFile = File(bundleDir, "bundle-manifest.json")
31
+ if (!manifestFile.exists()) return null
32
+ val manifest = JSONObject(manifestFile.readText())
33
+ if (manifest.optInt("manifestVersion", -1) != 1) {
34
+ return null
35
+ }
36
+ if (manifest.optString("bundleHash", "") != hash) {
37
+ return null
38
+ }
39
+ if (!verifyBundleDir(bundleDir, manifest, hash)) return null
40
+ expectedBundle.absolutePath
26
41
  } catch (_: Exception) {
27
42
  null
28
43
  }
29
44
  }
30
45
 
46
+ private fun verifyBundleDir(bundleDir: File, manifest: JSONObject, expectedHash: String): Boolean {
47
+ val files = manifest.optJSONArray("files") ?: return false
48
+ if (manifest.optString("platform", "") != "android") {
49
+ return false
50
+ }
51
+ var mainBundleHash: String? = null
52
+ var jsBundleRoleCount = 0
53
+ var metadataRoleCount = 0
54
+ var metadataPathMatches = false
55
+ var androidImageManifestRoleCount = 0
56
+ var androidImageManifestPathMatches = false
57
+
58
+ for (i in 0 until files.length()) {
59
+ val file = files.optJSONObject(i) ?: return false
60
+ val relativePath = file.optString("path", "")
61
+ val role = file.optString("role", "")
62
+ if (!BundleDropBundleVerifier.isSafeManifestPath(relativePath)) return false
63
+ when (role) {
64
+ "jsbundle" -> {
65
+ jsBundleRoleCount += 1
66
+ if (relativePath == "main.jsbundle") {
67
+ mainBundleHash = file.optString("sha256", "")
68
+ }
69
+ }
70
+ "metadata" -> {
71
+ metadataRoleCount += 1
72
+ if (relativePath == "metadata-android.json") {
73
+ metadataPathMatches = true
74
+ }
75
+ }
76
+ "androidImageManifest" -> {
77
+ androidImageManifestRoleCount += 1
78
+ if (relativePath == "image-manifest.json") {
79
+ androidImageManifestPathMatches = true
80
+ }
81
+ }
82
+ }
83
+ }
84
+
85
+ if (jsBundleRoleCount != 1 || mainBundleHash != manifest.optString("jsBundleHash", "")) return false
86
+ if (metadataRoleCount != 1 || !metadataPathMatches) return false
87
+ if (androidImageManifestRoleCount != 1 || !androidImageManifestPathMatches) return false
88
+ if (calculateBundleHash(files) != expectedHash) return false
89
+ if (!verifyManifestHash(manifest, files)) return false
90
+ try {
91
+ BundleDropBundleVerifier.verifyManifestFiles(bundleDir, files)
92
+ } catch (_: Exception) {
93
+ return false
94
+ }
95
+ return true
96
+ }
97
+
98
+ private fun calculateBundleHash(files: org.json.JSONArray): String {
99
+ val sortedEntries = canonicalFileEntries(files)
100
+ return sha256String("{\"files\":[${sortedEntries.joinToString(",")}],\"manifestVersion\":1}")
101
+ }
102
+
103
+ private fun verifyManifestHash(manifest: JSONObject, files: org.json.JSONArray): Boolean {
104
+ val manifestHash = manifest.optString("manifestHash", "")
105
+ if (!bundleHashPattern.matches(manifestHash)) return false
106
+ val requiredFields = listOf(
107
+ "bundleHash",
108
+ "jsBundleHash",
109
+ "platform",
110
+ "runtimeVersion",
111
+ "version",
112
+ )
113
+ if (requiredFields.any { manifest.optString(it, "").isBlank() }) return false
114
+ val canonical = listOf(
115
+ "\"bundleHash\":${quoteCanonicalString(manifest.optString("bundleHash", ""))}",
116
+ "\"files\":[${canonicalFileEntries(files).joinToString(",")}]",
117
+ "\"jsBundleHash\":${quoteCanonicalString(manifest.optString("jsBundleHash", ""))}",
118
+ "\"manifestVersion\":1",
119
+ "\"platform\":${quoteCanonicalString(manifest.optString("platform", ""))}",
120
+ "\"runtimeVersion\":${quoteCanonicalString(manifest.optString("runtimeVersion", ""))}",
121
+ "\"version\":${quoteCanonicalString(manifest.optString("version", ""))}",
122
+ ).joinToString(",", prefix = "{", postfix = "}")
123
+ return sha256String(canonical) == manifestHash
124
+ }
125
+
126
+ private fun canonicalFileEntries(files: org.json.JSONArray): List<String> {
127
+ val entries = mutableListOf<Pair<String, String>>()
128
+ for (i in 0 until files.length()) {
129
+ val file = files.getJSONObject(i)
130
+ val relativePath = file.getString("path")
131
+ val executable = if (file.optBoolean("executable", false)) "\"executable\":true," else ""
132
+ entries.add(
133
+ relativePath to "{$executable\"path\":${quoteCanonicalString(relativePath)},\"role\":${quoteCanonicalString(file.getString("role"))},\"sha256\":${quoteCanonicalString(file.getString("sha256"))},\"size\":${file.getLong("size")}}"
134
+ )
135
+ }
136
+ return entries.sortedWith { left, right -> compareUtf8(left.first, right.first) }.map { it.second }
137
+ }
138
+
139
+ private fun quoteCanonicalString(value: String): String {
140
+ val result = StringBuilder(value.length + 2)
141
+ result.append('"')
142
+ value.forEach { char ->
143
+ when (char) {
144
+ '"' -> result.append("\\\"")
145
+ '\\' -> result.append("\\\\")
146
+ '\b' -> result.append("\\b")
147
+ '\u000c' -> result.append("\\f")
148
+ '\n' -> result.append("\\n")
149
+ '\r' -> result.append("\\r")
150
+ '\t' -> result.append("\\t")
151
+ else -> {
152
+ if (char.code < 0x20) {
153
+ result.append("\\u")
154
+ result.append(char.code.toString(16).padStart(4, '0'))
155
+ } else {
156
+ result.append(char)
157
+ }
158
+ }
159
+ }
160
+ }
161
+ result.append('"')
162
+ return result.toString()
163
+ }
164
+
165
+ private fun compareUtf8(left: String, right: String): Int {
166
+ val leftBytes = left.toByteArray(Charsets.UTF_8)
167
+ val rightBytes = right.toByteArray(Charsets.UTF_8)
168
+ val length = minOf(leftBytes.size, rightBytes.size)
169
+ for (i in 0 until length) {
170
+ val leftByte = leftBytes[i].toInt() and 0xff
171
+ val rightByte = rightBytes[i].toInt() and 0xff
172
+ if (leftByte != rightByte) return leftByte - rightByte
173
+ }
174
+ return leftBytes.size - rightBytes.size
175
+ }
176
+
177
+ private fun sha256String(value: String): String {
178
+ val digest = MessageDigest.getInstance("SHA-256").digest(value.toByteArray(Charsets.UTF_8))
179
+ return digest.joinToString("") { "%02x".format(it) }
180
+ }
181
+
31
182
  fun clearOtaState(bundleDropRoot: File, filesDir: File) {
32
183
  val filesToClear = listOf(
33
184
  File(bundleDropRoot, "current.json"),
@@ -83,11 +234,65 @@ object BundleDropOtaResolver {
83
234
  fun readImageManifest(bundlePath: String): String? {
84
235
  return try {
85
236
  val bundleDir = File(bundlePath).parentFile ?: return null
237
+ val bundleHash = bundleDir.name
238
+ if (!bundleHashPattern.matches(bundleHash)) return null
86
239
  val file = File(bundleDir, "image-manifest.json")
87
- if (file.exists()) file.readText() else null
240
+ if (!file.exists()) return null
241
+ rootImageManifestPaths(JSONObject(file.readText()), bundleDir, bundleHash).toString()
88
242
  } catch (_: Exception) {
89
243
  null
90
244
  }
91
245
  }
92
246
 
247
+ private fun rootImageManifestPaths(
248
+ manifest: JSONObject,
249
+ bundleDir: File,
250
+ bundleHash: String,
251
+ ): JSONObject {
252
+ val rooted = JSONObject()
253
+ val keys = manifest.keys()
254
+ while (keys.hasNext()) {
255
+ val key = keys.next()
256
+ if (!BundleDropBundleVerifier.isSafeManifestPath(key)) throw IllegalArgumentException("Invalid image manifest key")
257
+ val value = manifest.opt(key) as? String ?: throw IllegalArgumentException("Invalid image manifest value")
258
+ rooted.put(key, rootImageManifestPath(value, bundleDir, bundleHash))
259
+ }
260
+ return rooted
261
+ }
262
+
263
+ private fun rootImageManifestPath(path: String, bundleDir: File, bundleHash: String): String {
264
+ if (path.contains("\\") || path.contains("\u0000")) {
265
+ throw IllegalArgumentException("Invalid image manifest value")
266
+ }
267
+
268
+ val normalizedPath = path
269
+ val rootedPrefix = "bundle-drop/bundles/$bundleHash/"
270
+ if (normalizedPath.startsWith(rootedPrefix)) {
271
+ val relativePath = normalizedPath.removePrefix(rootedPrefix)
272
+ if (!BundleDropBundleVerifier.isSafeManifestPath(relativePath)) throw IllegalArgumentException("Invalid image manifest value")
273
+ return normalizedPath
274
+ }
275
+
276
+ val bundleDirMarker = "/bundle-drop/bundles/$bundleHash/"
277
+ val markerIndex = normalizedPath.indexOf(bundleDirMarker)
278
+ if (markerIndex >= 0) {
279
+ val relativePath = normalizedPath.substring(markerIndex + bundleDirMarker.length)
280
+ if (!BundleDropBundleVerifier.isSafeManifestPath(relativePath)) throw IllegalArgumentException("Invalid image manifest value")
281
+ return "$rootedPrefix$relativePath"
282
+ }
283
+
284
+ val absoluteBundleDir = bundleDir.absolutePath.replace('\\', '/')
285
+ if (normalizedPath.startsWith("$absoluteBundleDir/")) {
286
+ val relativePath = normalizedPath.removePrefix("$absoluteBundleDir/")
287
+ if (!BundleDropBundleVerifier.isSafeManifestPath(relativePath)) throw IllegalArgumentException("Invalid image manifest value")
288
+ return "$rootedPrefix$relativePath"
289
+ }
290
+
291
+ if (normalizedPath.startsWith("/")) {
292
+ throw IllegalArgumentException("Invalid image manifest value")
293
+ }
294
+ if (!BundleDropBundleVerifier.isSafeManifestPath(normalizedPath)) throw IllegalArgumentException("Invalid image manifest value")
295
+ return "$rootedPrefix$normalizedPath"
296
+ }
297
+
93
298
  }
@@ -0,0 +1,57 @@
1
+ package com.bundledrop
2
+
3
+ import java.io.File
4
+ import java.io.IOException
5
+
6
+ internal object BundleDropXdeltaNative {
7
+ private val loadError: Throwable?
8
+
9
+ init {
10
+ var error: Throwable? = null
11
+ try {
12
+ System.loadLibrary("bundledropxdelta")
13
+ } catch (e: Throwable) {
14
+ error = e
15
+ }
16
+ loadError = error
17
+ }
18
+
19
+ private external fun nativeSupportsXdelta(): Boolean
20
+ private external fun nativeVersion(): String
21
+ private external fun nativeApplyXdelta(basePath: String, patchPath: String, outputPath: String): String?
22
+
23
+ fun supportsXdelta(): Boolean {
24
+ if (loadError != null) return false
25
+ return try {
26
+ nativeSupportsXdelta()
27
+ } catch (_: Throwable) {
28
+ false
29
+ }
30
+ }
31
+
32
+ fun version(): String? {
33
+ if (loadError != null) return null
34
+ return try {
35
+ nativeVersion()
36
+ } catch (_: Throwable) {
37
+ null
38
+ }
39
+ }
40
+
41
+ fun applyXdelta(base: File, patch: File, output: File) {
42
+ if (loadError != null) {
43
+ throw IOException("xdelta3-vcdiff native apply is not linked", loadError)
44
+ }
45
+ output.parentFile?.mkdirs()
46
+ val error = try {
47
+ nativeApplyXdelta(base.absolutePath, patch.absolutePath, output.absolutePath)
48
+ } catch (e: Throwable) {
49
+ try { output.delete() } catch (_: Exception) {}
50
+ throw IOException("xdelta3-vcdiff native apply failed", e)
51
+ }
52
+ if (error != null) {
53
+ try { output.delete() } catch (_: Exception) {}
54
+ throw IOException(error)
55
+ }
56
+ }
57
+ }
@@ -44,6 +44,33 @@ RCT_EXTERN_METHOD(fsMoveFile:(NSString *)src
44
44
  resolve:(RCTPromiseResolveBlock)resolve
45
45
  reject:(RCTPromiseRejectBlock)reject)
46
46
 
47
+ RCT_EXTERN_METHOD(fsCopyFile:(NSString *)src
48
+ dest:(NSString *)dest
49
+ resolve:(RCTPromiseResolveBlock)resolve
50
+ reject:(RCTPromiseRejectBlock)reject)
51
+
52
+ RCT_EXTERN_METHOD(fsSha256File:(NSString *)path
53
+ resolve:(RCTPromiseResolveBlock)resolve
54
+ reject:(RCTPromiseRejectBlock)reject)
55
+
56
+ RCT_EXTERN_METHOD(fsFileSize:(NSString *)path
57
+ resolve:(RCTPromiseResolveBlock)resolve
58
+ reject:(RCTPromiseRejectBlock)reject)
59
+
60
+ RCT_EXTERN_METHOD(fsApplyXdelta:(NSString *)basePath
61
+ patchPath:(NSString *)patchPath
62
+ outputPath:(NSString *)outputPath
63
+ resolve:(RCTPromiseResolveBlock)resolve
64
+ reject:(RCTPromiseRejectBlock)reject)
65
+
66
+ RCT_EXTERN_METHOD(fsVerifyBundleFiles:(NSString *)bundleDir
67
+ manifestPath:(NSString *)manifestPath
68
+ resolve:(RCTPromiseResolveBlock)resolve
69
+ reject:(RCTPromiseRejectBlock)reject)
70
+
71
+ RCT_EXTERN_METHOD(fsSupportsXdelta:(RCTPromiseResolveBlock)resolve
72
+ reject:(RCTPromiseRejectBlock)reject)
73
+
47
74
  RCT_EXTERN_METHOD(fsUnzip:(NSString *)zipPath
48
75
  destPath:(NSString *)destPath
49
76
  resolve:(RCTPromiseResolveBlock)resolve
@@ -0,0 +1,106 @@
1
+ import Foundation
2
+
3
+ enum BundleDropBundleVerifier {
4
+ private static let manifestFileName = "bundle-manifest.json"
5
+
6
+ static func verifyBundleFiles(
7
+ bundleDir: URL,
8
+ manifestURL: URL,
9
+ fileManager: FileManager = .default
10
+ ) throws {
11
+ let manifest: [String: Any]
12
+ do {
13
+ let data = try Data(contentsOf: manifestURL)
14
+ guard let parsed = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
15
+ throw BundleDropFileOps.error("Malformed bundle manifest")
16
+ }
17
+ manifest = parsed
18
+ } catch {
19
+ throw BundleDropFileOps.error("Malformed bundle manifest")
20
+ }
21
+
22
+ guard let files = manifest["files"] as? [[String: Any]] else {
23
+ throw error("Bundle manifest must include files")
24
+ }
25
+ try verifyManifestFiles(bundleDir: bundleDir, files: files, fileManager: fileManager)
26
+ }
27
+
28
+ static func verifyManifestFiles(
29
+ bundleDir: URL,
30
+ files: [[String: Any]],
31
+ fileManager: FileManager = .default
32
+ ) throws {
33
+ var allowed = Set([manifestFileName])
34
+
35
+ for (index, file) in files.enumerated() {
36
+ guard let path = file["path"] as? String else {
37
+ throw error("Invalid manifest file entry at index \(index)")
38
+ }
39
+ guard isSafeManifestPath(path) else {
40
+ throw error("Invalid manifest path: \(path)")
41
+ }
42
+ guard allowed.insert(path).inserted else {
43
+ throw error("Duplicate manifest file path: \(path)")
44
+ }
45
+ guard let size = file["size"] as? NSNumber,
46
+ let expectedSha = file["sha256"] as? String else {
47
+ throw error("Invalid manifest file entry for \(path)")
48
+ }
49
+
50
+ let fileURL = bundleDir.appendingPathComponent(path)
51
+ var isDirectory: ObjCBool = false
52
+ guard fileManager.fileExists(atPath: fileURL.path, isDirectory: &isDirectory) else {
53
+ throw error("Manifest file missing: \(path)")
54
+ }
55
+ guard !isDirectory.boolValue else {
56
+ throw error("Manifest file is a directory: \(path)")
57
+ }
58
+ guard let attrs = try? fileManager.attributesOfItem(atPath: fileURL.path),
59
+ let actualSize = attrs[.size] as? NSNumber,
60
+ actualSize.int64Value == size.int64Value else {
61
+ throw error("Manifest file size mismatch for \(path)")
62
+ }
63
+ guard try BundleDropFileOps.sha256File(fileURL.path) == expectedSha else {
64
+ throw error("Manifest file hash mismatch for \(path)")
65
+ }
66
+ }
67
+
68
+ let actualFiles = listRelativeFiles(root: bundleDir, fileManager: fileManager)
69
+ if let extraFile = actualFiles.first(where: { !allowed.contains($0) }) {
70
+ throw error("Unmanifested file in bundle archive: \(extraFile)")
71
+ }
72
+ }
73
+
74
+ static func isSafeManifestPath(_ path: String) -> Bool {
75
+ !path.isEmpty &&
76
+ !path.hasPrefix("/") &&
77
+ !path.contains("\\") &&
78
+ !path.contains("\u{0000}") &&
79
+ !path.split(separator: "/", omittingEmptySubsequences: false).contains { part in
80
+ part.isEmpty || part == "." || part == ".."
81
+ }
82
+ }
83
+
84
+ private static func listRelativeFiles(
85
+ root: URL,
86
+ current: URL? = nil,
87
+ prefix: String = "",
88
+ fileManager: FileManager
89
+ ) -> [String] {
90
+ let directory = current ?? root
91
+ guard let entries = try? fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.isDirectoryKey]) else {
92
+ return []
93
+ }
94
+ return entries.flatMap { entry -> [String] in
95
+ let relativePath = prefix.isEmpty ? entry.lastPathComponent : "\(prefix)/\(entry.lastPathComponent)"
96
+ let isDirectory = (try? entry.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false
97
+ return isDirectory
98
+ ? listRelativeFiles(root: root, current: entry, prefix: relativePath, fileManager: fileManager)
99
+ : [relativePath]
100
+ }
101
+ }
102
+
103
+ private static func error(_ message: String) -> NSError {
104
+ BundleDropFileOps.error(message)
105
+ }
106
+ }
@@ -1,7 +1,22 @@
1
1
  import Foundation
2
+ import CryptoKit
3
+
4
+ @_silgen_name("bd_xdelta_apply")
5
+ private func bdXdeltaApply(
6
+ _ basePath: UnsafePointer<CChar>,
7
+ _ patchPath: UnsafePointer<CChar>,
8
+ _ outputPath: UnsafePointer<CChar>,
9
+ _ errorBuffer: UnsafeMutablePointer<CChar>,
10
+ _ errorBufferLen: Int
11
+ ) -> Int32
12
+
13
+ @_silgen_name("bd_xdelta_self_test")
14
+ private func bdXdeltaSelfTest() -> Int32
2
15
 
3
16
  enum BundleDropFileOps {
4
17
  static let defaultMaxDownloadBytes: Int64 = 256 * 1024 * 1024
18
+ private static let patchTargetDirPrefix = "_patch_target_"
19
+ private static let bundleHashPattern = #"^[a-f0-9]{64}$"#
5
20
 
6
21
  static func validateHttpUrl(_ urlString: String) throws -> URL {
7
22
  guard let url = URL(string: urlString),
@@ -46,6 +61,140 @@ enum BundleDropFileOps {
46
61
  )
47
62
  }
48
63
 
64
+ static func copyFile(
65
+ srcPath: String,
66
+ destPath: String,
67
+ fileManager: FileManager = .default
68
+ ) throws {
69
+ let destURL = URL(fileURLWithPath: destPath)
70
+ let destDir = destURL.deletingLastPathComponent()
71
+ if !fileManager.fileExists(atPath: destDir.path) {
72
+ try fileManager.createDirectory(
73
+ at: destDir,
74
+ withIntermediateDirectories: true
75
+ )
76
+ }
77
+ if fileManager.fileExists(atPath: destPath) {
78
+ try fileManager.removeItem(atPath: destPath)
79
+ }
80
+ try fileManager.copyItem(
81
+ at: URL(fileURLWithPath: srcPath),
82
+ to: destURL
83
+ )
84
+ }
85
+
86
+ static func sha256File(_ path: String) throws -> String {
87
+ let handle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path))
88
+ defer {
89
+ if #available(iOS 13.0, macOS 10.15, *) {
90
+ try? handle.close()
91
+ } else {
92
+ handle.closeFile()
93
+ }
94
+ }
95
+
96
+ var hasher = SHA256()
97
+ while autoreleasepool(invoking: {
98
+ let data = handle.readData(ofLength: 64 * 1024)
99
+ if data.isEmpty { return false }
100
+ hasher.update(data: data)
101
+ return true
102
+ }) {}
103
+
104
+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()
105
+ }
106
+
107
+ static func fileSize(
108
+ _ path: String,
109
+ fileManager: FileManager = .default
110
+ ) throws -> Int64 {
111
+ let attrs = try fileManager.attributesOfItem(atPath: path)
112
+ guard let size = attrs[.size] as? NSNumber else {
113
+ throw error("File size is unavailable: \(path)")
114
+ }
115
+ return size.int64Value
116
+ }
117
+
118
+ static func supportsXdelta() -> Bool {
119
+ bdXdeltaSelfTest() == 1
120
+ }
121
+
122
+ static func applyXdelta(
123
+ basePath: String,
124
+ patchPath: String,
125
+ outputPath: String
126
+ ) throws {
127
+ try validateXdeltaOutputPath(outputPath)
128
+
129
+ try FileManager.default.createDirectory(
130
+ atPath: URL(fileURLWithPath: outputPath).deletingLastPathComponent().path,
131
+ withIntermediateDirectories: true
132
+ )
133
+
134
+ var errorBuffer = [CChar](repeating: 0, count: 512)
135
+ let result = basePath.withCString { baseCString in
136
+ patchPath.withCString { patchCString in
137
+ outputPath.withCString { outputCString in
138
+ bdXdeltaApply(
139
+ baseCString,
140
+ patchCString,
141
+ outputCString,
142
+ &errorBuffer,
143
+ errorBuffer.count
144
+ )
145
+ }
146
+ }
147
+ }
148
+
149
+ if result != 0 {
150
+ try? FileManager.default.removeItem(atPath: outputPath)
151
+ let message = String(cString: errorBuffer)
152
+ throw error(message.isEmpty ? "xdelta3-vcdiff native apply failed" : message)
153
+ }
154
+ }
155
+
156
+ private static func validateXdeltaOutputPath(_ outputPath: String) throws {
157
+ if outputPath.contains("\0") {
158
+ throw error("xdelta output path contains a null byte")
159
+ }
160
+ if outputPath.contains("\\") {
161
+ throw error("xdelta output path must not contain unsafe separators")
162
+ }
163
+ if outputPath.split(separator: "/").contains("..") {
164
+ throw error("xdelta output path must not contain traversal segments")
165
+ }
166
+
167
+ let outputURL = URL(fileURLWithPath: outputPath).standardizedFileURL
168
+ let components = outputURL.pathComponents.filter { $0 != "/" }
169
+ guard components.count >= 4 else {
170
+ throw error("xdelta output path must be inside bundle-drop/bundles/_patch_target_<bundleHash>")
171
+ }
172
+
173
+ for index in 0..<(components.count - 3) {
174
+ guard components[index] == "bundle-drop",
175
+ components[index + 1] == "bundles" else {
176
+ continue
177
+ }
178
+
179
+ let patchTargetDir = components[index + 2]
180
+ guard patchTargetDir.hasPrefix(patchTargetDirPrefix) else {
181
+ throw error("xdelta output path must not target an active bundle folder")
182
+ }
183
+
184
+ let targetHash = String(patchTargetDir.dropFirst(patchTargetDirPrefix.count))
185
+ guard targetHash.range(
186
+ of: bundleHashPattern,
187
+ options: .regularExpression
188
+ ) != nil else {
189
+ throw error("xdelta output path must use a valid patch target temp directory")
190
+ }
191
+
192
+ return
193
+ }
194
+
195
+ throw error("xdelta output path must be inside bundle-drop/bundles/_patch_target_<bundleHash>")
196
+ }
197
+
49
198
  static func downloadToFile(
50
199
  urlString: String,
51
200
  destPath: String,