@onekeyfe/react-native-sni-connect 6.7.0-6 → 6.7.0-61

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.
@@ -1,6 +1,9 @@
1
1
  package com.sniconnect
2
2
 
3
+ import java.io.File
4
+ import java.io.IOException
3
5
  import java.net.Inet6Address
6
+ import java.net.URI
4
7
  import java.net.InetAddress
5
8
  import java.nio.charset.StandardCharsets
6
9
  import java.util.Locale
@@ -22,6 +25,7 @@ internal object SniConnectValidation {
22
25
  const val MAX_PATH_BYTES = 8 * 1024
23
26
  const val MAX_REQUEST_BODY_BYTES = 1024 * 1024
24
27
  const val MAX_RESPONSE_BODY_BYTES = 10 * 1024 * 1024L
28
+ const val MAX_UPLOAD_FILE_BYTES = 20 * 1024 * 1024L
25
29
  const val MAX_HEADER_COUNT = 64
26
30
  const val MAX_HEADER_NAME_BYTES = 128
27
31
  const val MAX_HEADER_VALUE_BYTES = 8 * 1024
@@ -94,6 +98,70 @@ internal object SniConnectValidation {
94
98
  }
95
99
  }
96
100
 
101
+ /** File uploads always carry a body, so only body-bearing write methods apply. */
102
+ fun validateUploadMethod(method: String) {
103
+ if (method != "POST" && method != "PUT") {
104
+ throw ValidationException("Invalid upload method: $method")
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Resolve a caller-supplied upload path to a regular file inside one of
110
+ * [allowedRoots] (the app's own storage). Canonicalization resolves symlinks
111
+ * before the containment check so a link cannot point the upload elsewhere.
112
+ */
113
+ fun resolveUploadFile(rawPath: String, allowedRoots: List<File>): File {
114
+ if (rawPath.isEmpty() || containsControlChars(rawPath)) {
115
+ throw ValidationException("Invalid file path")
116
+ }
117
+ val file = when {
118
+ rawPath.startsWith("file:") -> {
119
+ val uri = try {
120
+ URI(rawPath)
121
+ } catch (error: Exception) {
122
+ throw ValidationException("Invalid file URL")
123
+ }
124
+ val path = uri.path
125
+ if (uri.scheme != "file" || path.isNullOrEmpty()) {
126
+ throw ValidationException("Invalid file URL")
127
+ }
128
+ File(path)
129
+ }
130
+ rawPath.startsWith("/") -> File(rawPath)
131
+ else -> throw ValidationException("File path must be absolute")
132
+ }
133
+
134
+ val canonicalFile = try {
135
+ file.canonicalFile
136
+ } catch (error: IOException) {
137
+ throw ValidationException("File path cannot be resolved")
138
+ }
139
+ val canonicalPath = canonicalFile.path
140
+ val isInsideAllowedRoot = allowedRoots.any { root ->
141
+ val rootPath = try {
142
+ root.canonicalPath
143
+ } catch (error: IOException) {
144
+ return@any false
145
+ }
146
+ val prefix = if (rootPath.endsWith(File.separator)) rootPath else rootPath + File.separator
147
+ canonicalPath.startsWith(prefix)
148
+ }
149
+ if (!isInsideAllowedRoot) {
150
+ throw ValidationException("File is outside the app sandbox")
151
+ }
152
+ if (!canonicalFile.isFile || !canonicalFile.canRead()) {
153
+ throw ValidationException("Not a readable regular file")
154
+ }
155
+ val sizeBytes = canonicalFile.length()
156
+ if (sizeBytes <= 0L) {
157
+ throw ValidationException("File is empty")
158
+ }
159
+ if (sizeBytes > MAX_UPLOAD_FILE_BYTES) {
160
+ throw ValidationException("File is too large")
161
+ }
162
+ return canonicalFile
163
+ }
164
+
97
165
  fun normalizeMethod(method: String): String {
98
166
  if (containsControlChars(method)) {
99
167
  throw ValidationException("Invalid method: $method")
@@ -1,15 +1,25 @@
1
1
  package com.sniconnect
2
2
 
3
+ import java.io.File
4
+ import java.io.IOException
3
5
  import java.net.InetAddress
4
6
  import java.net.Proxy
5
7
  import java.net.UnknownHostException
6
8
  import java.util.Locale
7
9
  import java.util.concurrent.TimeUnit
10
+ import java.util.concurrent.atomic.AtomicBoolean
11
+ import okhttp3.Call
8
12
  import okhttp3.ConnectionPool
9
13
  import okhttp3.Dispatcher
10
14
  import okhttp3.Dns
15
+ import okhttp3.EventListener
16
+ import okhttp3.MediaType
11
17
  import okhttp3.OkHttpClient
12
18
  import okhttp3.Protocol
19
+ import okhttp3.RequestBody
20
+ import okio.Buffer
21
+ import okio.BufferedSink
22
+ import okio.source
13
23
  import javax.net.ssl.HttpsURLConnection
14
24
 
15
25
  object SniPinnedTransport {
@@ -38,6 +48,7 @@ object SniPinnedTransport {
38
48
  HttpsURLConnection.getDefaultHostnameVerifier().verify(normalizedHostname, session)
39
49
  }
40
50
  .dns(createPinnedDns(ip, normalizedHostname))
51
+ .eventListenerFactory(SniRequestTransmissionEventListenerFactory)
41
52
  .build()
42
53
  }
43
54
 
@@ -50,9 +61,86 @@ object SniPinnedTransport {
50
61
  if (requestedHost.lowercase(Locale.US) == hostname) {
51
62
  return listOf(pinnedAddress)
52
63
  }
53
- throw UnknownHostException(
64
+ throw SniPinnedDestinationViolationException(
54
65
  "Unexpected host for pinned SNI request: $requestedHost"
55
66
  )
56
67
  }
57
68
  }
58
69
  }
70
+
71
+ /**
72
+ * The pinned resolver never consults system DNS, so an unknown host here can
73
+ * only be an attempt to escape the caller-selected destination. It is a
74
+ * security-policy failure, not a transient DNS failure, and must fail closed.
75
+ */
76
+ internal class SniPinnedDestinationViolationException(
77
+ message: String,
78
+ ) : UnknownHostException(message)
79
+
80
+ /**
81
+ * Per-logical-request record of whether any OkHttp attempt began transmitting
82
+ * the request. A bodyless request (for example `DELETE`) can be processed by the
83
+ * server without ever writing a request body, so body tracking alone cannot
84
+ * prove that no attempt was sent.
85
+ */
86
+ internal class SniRequestTransmissionState {
87
+ private val started = AtomicBoolean(false)
88
+
89
+ fun markRequestTransmissionStarted() {
90
+ started.set(true)
91
+ }
92
+
93
+ fun hasRequestTransmissionStarted(): Boolean = started.get()
94
+ }
95
+
96
+ /**
97
+ * Marks the tagged [SniRequestTransmissionState] as soon as an attempt starts
98
+ * writing request headers. This runs after connect/TLS, so a refused connection
99
+ * before any attempt reached this point is still provably unsent, while a
100
+ * successful attempt followed by a refused recovery is ambiguous.
101
+ */
102
+ internal object SniRequestTransmissionEventListenerFactory : EventListener.Factory {
103
+ override fun create(call: Call): EventListener =
104
+ object : EventListener() {
105
+ override fun requestHeadersStart(call: Call) {
106
+ call.request().tag(SniRequestTransmissionState::class.java)
107
+ ?.markRequestTransmissionStarted()
108
+ }
109
+ }
110
+ }
111
+
112
+ /** Reads from disk only during transmission, with a fixed, bounded body length. */
113
+ internal class SniUploadFileRequestBody(
114
+ private val file: File,
115
+ private val mediaType: MediaType?,
116
+ ) : RequestBody() {
117
+ private val length = file.length().also {
118
+ if (it <= 0 || it > SniConnectValidation.MAX_UPLOAD_FILE_BYTES) {
119
+ throw IOException("Upload file size is out of range")
120
+ }
121
+ }
122
+
123
+ override fun contentType(): MediaType? = mediaType
124
+
125
+ override fun contentLength(): Long = length
126
+
127
+ override fun writeTo(sink: BufferedSink) {
128
+ file.source().use { source ->
129
+ val buffer = Buffer()
130
+ var totalBytes = 0L
131
+ while (true) {
132
+ // One extra byte detects growth without ever writing beyond the bound.
133
+ val read = source.read(buffer, minOf(8 * 1024L, length - totalBytes + 1))
134
+ if (read == -1L) break
135
+ if (totalBytes + read > length) {
136
+ throw IOException("Upload file grew during transmission")
137
+ }
138
+ sink.write(buffer, read)
139
+ totalBytes += read
140
+ }
141
+ if (totalBytes != length) {
142
+ throw IOException("Upload file was truncated during transmission")
143
+ }
144
+ }
145
+ }
146
+ }
@@ -2,10 +2,24 @@ package com.sniconnect
2
2
 
3
3
  import org.junit.Assert.assertEquals
4
4
  import org.junit.Assert.assertFalse
5
+ import org.junit.Assert.assertNull
5
6
  import org.junit.Assert.assertTrue
7
+ import org.junit.Assert.assertThrows
8
+ import okhttp3.Call
9
+ import okhttp3.OkHttpClient
10
+ import okhttp3.Request
11
+ import okio.Buffer
12
+ import okio.ForwardingSink
13
+ import okio.buffer
14
+ import org.junit.Rule
6
15
  import org.junit.Test
16
+ import org.junit.rules.TemporaryFolder
17
+ import java.io.File
7
18
  import java.io.IOException
19
+ import java.io.RandomAccessFile
20
+ import java.nio.file.Files
8
21
  import java.io.InterruptedIOException
22
+ import java.net.ConnectException
9
23
  import java.net.SocketTimeoutException
10
24
  import java.net.UnknownHostException
11
25
  import java.security.cert.CertificateException
@@ -14,6 +28,121 @@ import javax.net.ssl.SSLPeerUnverifiedException
14
28
 
15
29
  class SniConnectValidationTest {
16
30
 
31
+ @get:Rule
32
+ val tempFolder = TemporaryFolder()
33
+
34
+ @Test
35
+ fun uploadMethodAllowsOnlyPostAndPut() {
36
+ SniConnectValidation.validateUploadMethod("POST")
37
+ SniConnectValidation.validateUploadMethod("PUT")
38
+ listOf("GET", "HEAD", "PATCH", "DELETE", "OPTIONS").forEach { method ->
39
+ assertValidationFails { SniConnectValidation.validateUploadMethod(method) }
40
+ }
41
+ }
42
+
43
+ @Test
44
+ fun resolveUploadFileAcceptsSandboxFileByPathAndFileUrl() {
45
+ val root = tempFolder.newFolder("sandbox")
46
+ val file = File(root, "logs.zip").apply { writeBytes(byteArrayOf(0x50, 0x4B, 3, 4, -1)) }
47
+
48
+ val byPath = SniConnectValidation.resolveUploadFile(file.path, listOf(root))
49
+ assertEquals(file.canonicalPath, byPath.path)
50
+ val byUrl = SniConnectValidation.resolveUploadFile(file.toURI().toString(), listOf(root))
51
+ assertEquals(file.canonicalPath, byUrl.path)
52
+ val byTripleSlashUrl = SniConnectValidation.resolveUploadFile("file://${file.path}", listOf(root))
53
+ assertEquals(file.canonicalPath, byTripleSlashUrl.path)
54
+ }
55
+
56
+ @Test
57
+ fun resolveUploadFileRejectsInvalidOrOutOfSandboxFiles() {
58
+ val root = tempFolder.newFolder("sandbox")
59
+ val outside = tempFolder.newFolder("outside")
60
+ val outsideFile = File(outside, "secret.bin").apply { writeBytes(byteArrayOf(1, 2, 3)) }
61
+ val emptyFile = File(root, "empty.zip").apply { writeBytes(ByteArray(0)) }
62
+ val link = File(root, "link.zip")
63
+ Files.createSymbolicLink(link.toPath(), outsideFile.toPath())
64
+
65
+ listOf(
66
+ "",
67
+ "relative/logs.zip",
68
+ "https://example.com/logs.zip",
69
+ outsideFile.path,
70
+ "${root.path}/../outside/secret.bin",
71
+ link.path,
72
+ emptyFile.path,
73
+ root.path,
74
+ File(root, "missing.zip").path,
75
+ "${root.path}/logs\n.zip",
76
+ ).forEach { path ->
77
+ assertValidationFails { SniConnectValidation.resolveUploadFile(path, listOf(root)) }
78
+ }
79
+ }
80
+
81
+ @Test
82
+ fun resolveUploadFileRejectsFilesOverTheSizeLimit() {
83
+ val root = tempFolder.newFolder("sandbox")
84
+ val file = File(root, "big.zip")
85
+ RandomAccessFile(file, "rw").use { it.setLength(SniConnectValidation.MAX_UPLOAD_FILE_BYTES + 1) }
86
+
87
+ assertValidationFails { SniConnectValidation.resolveUploadFile(file.path, listOf(root)) }
88
+ }
89
+
90
+ @Test
91
+ fun uploadBodyStreamsExactLimitBinaryData() {
92
+ val file = tempFolder.newFile("exact.zip")
93
+ val expected = ByteArray(SniConnectValidation.MAX_UPLOAD_FILE_BYTES.toInt()) { 0xFF.toByte() }
94
+ file.writeBytes(expected)
95
+ val body = SniUploadFileRequestBody(file, null)
96
+ val sink = Buffer()
97
+ body.writeTo(sink)
98
+ assertEquals(expected.size.toLong(), body.contentLength())
99
+ assertTrue(expected.contentEquals(sink.readByteArray()))
100
+ }
101
+
102
+ @Test
103
+ fun uploadBodyRejectsGrowthAfterValidation() {
104
+ val root = tempFolder.newFolder("sandbox")
105
+ val file = File(root, "growing.zip").apply { writeBytes(byteArrayOf(1)) }
106
+ val validated = SniConnectValidation.resolveUploadFile(file.path, listOf(root))
107
+ val body = SniUploadFileRequestBody(validated, null)
108
+ RandomAccessFile(file, "rw").use { it.setLength(SniConnectValidation.MAX_UPLOAD_FILE_BYTES + 1) }
109
+ val sink = Buffer()
110
+ assertThrows(IOException::class.java) { body.writeTo(sink) }
111
+ assertTrue(sink.size <= body.contentLength())
112
+ assertThrows(IOException::class.java) { SniUploadFileRequestBody(validated, null) }
113
+ }
114
+
115
+ @Test
116
+ fun uploadBodyRejectsGrowthDuringTransmission() {
117
+ val file = tempFolder.newFile("growing-during-write.zip")
118
+ file.writeBytes(ByteArray(16 * 1024) { 1 })
119
+ val body = SniUploadFileRequestBody(file, null)
120
+ val output = Buffer()
121
+ var appended = false
122
+ val sink = object : ForwardingSink(output) {
123
+ override fun write(source: Buffer, byteCount: Long) {
124
+ super.write(source, byteCount)
125
+ if (!appended) {
126
+ file.appendBytes(byteArrayOf(2))
127
+ appended = true
128
+ }
129
+ }
130
+ }.buffer()
131
+ assertThrows(IOException::class.java) { body.writeTo(sink) }
132
+ assertTrue(appended)
133
+ assertTrue(output.size <= body.contentLength())
134
+ }
135
+
136
+ @Test
137
+ fun uploadBodyRejectsTruncationAfterValidation() {
138
+ val file = tempFolder.newFile("truncated.zip").apply { writeBytes(byteArrayOf(1, 2)) }
139
+ val body = SniUploadFileRequestBody(file, null)
140
+ file.writeBytes(byteArrayOf(1))
141
+ assertThrows(IOException::class.java) { body.writeTo(Buffer()) }
142
+ file.writeBytes(byteArrayOf())
143
+ assertThrows(IOException::class.java) { body.writeTo(Buffer()) }
144
+ }
145
+
17
146
  @Test
18
147
  fun acceptsValidRequestBoundaryValues() {
19
148
  SniConnectValidation.validateRequestId("req-1")
@@ -213,7 +342,15 @@ class SniConnectValidationTest {
213
342
  )
214
343
  assertEquals(
215
344
  "SNI_SECURITY_POLICY_FAILED",
216
- classifySniFailureCode(UnknownHostException("Unexpected host for pinned SNI request")),
345
+ classifySniFailureCode(
346
+ SniPinnedDestinationViolationException("Unexpected host for pinned SNI request"),
347
+ ),
348
+ )
349
+ assertEquals(
350
+ "SNI_SECURITY_POLICY_FAILED",
351
+ classifySniFailureCode(IOException("wrapped").apply {
352
+ initCause(SniPinnedDestinationViolationException("Unexpected host for pinned SNI request"))
353
+ }),
217
354
  )
218
355
  assertEquals(
219
356
  "SNI_REQUEST_TIMEOUT",
@@ -243,6 +380,103 @@ class SniConnectValidationTest {
243
380
  )
244
381
  }
245
382
 
383
+ @Test
384
+ fun classifiesDnsAndPreWriteConnectionFailuresForSafeFallback() {
385
+ assertEquals(
386
+ "SNI_DNS_FAILED",
387
+ classifySniFailureCode(UnknownHostException("api.example.com")),
388
+ )
389
+ assertEquals(
390
+ "SNI_CONNECTION_REFUSED",
391
+ classifySniFailureCode(ConnectException("Connection refused")),
392
+ )
393
+ assertEquals(
394
+ "SNI_CONNECTION_REFUSED",
395
+ classifySniFailureCode(IOException("connect failed").apply {
396
+ initCause(ConnectException("Connection refused"))
397
+ }),
398
+ )
399
+ }
400
+
401
+ @Test
402
+ fun gatesReplaySensitiveCodesOnRequestTransmissionEvidence() {
403
+ assertEquals(
404
+ "SNI_CONNECTION_REFUSED",
405
+ gateReplaySensitiveFailureCode("SNI_CONNECTION_REFUSED", false),
406
+ )
407
+ assertEquals(
408
+ "SNI_REQUEST_FAILED",
409
+ gateReplaySensitiveFailureCode("SNI_CONNECTION_REFUSED", true),
410
+ )
411
+ // Only the pre-write connection code is gated; other codes pass through.
412
+ assertEquals("SNI_TLS_FAILED", gateReplaySensitiveFailureCode("SNI_TLS_FAILED", true))
413
+ assertEquals(
414
+ "SNI_SECURITY_POLICY_FAILED",
415
+ gateReplaySensitiveFailureCode("SNI_SECURITY_POLICY_FAILED", true),
416
+ )
417
+ }
418
+
419
+ @Test
420
+ fun requestHeadersStartMarksTheLogicalRequestAsTransmitted() {
421
+ val state = SniRequestTransmissionState()
422
+ val call = newOkHttpCall(state)
423
+ assertFalse(state.hasRequestTransmissionStarted())
424
+
425
+ SniRequestTransmissionEventListenerFactory.create(call).requestHeadersStart(call)
426
+
427
+ assertTrue(state.hasRequestTransmissionStarted())
428
+ }
429
+
430
+ @Test
431
+ fun untaggedCallDoesNotFailOnRequestHeadersStart() {
432
+ val call = OkHttpClient().newCall(
433
+ Request.Builder().url("https://example.com/").build(),
434
+ )
435
+
436
+ SniRequestTransmissionEventListenerFactory.create(call).requestHeadersStart(call)
437
+
438
+ assertNull(call.request().tag(SniRequestTransmissionState::class.java))
439
+ }
440
+
441
+ @Test
442
+ fun processedBodylessRequestFollowedByRefusedRecoveryStaysAmbiguous() {
443
+ // A bodyless DELETE can be processed by the server without writing a body;
444
+ // only the request-headers event can prove that it was transmitted.
445
+ val state = SniRequestTransmissionState()
446
+ val call = newOkHttpCall(state, bodylessDelete = true)
447
+ SniRequestTransmissionEventListenerFactory.create(call).requestHeadersStart(call)
448
+
449
+ val code = gateReplaySensitiveFailureCode(
450
+ classifySniFailureCode(ConnectException("Connection refused")),
451
+ state.hasRequestTransmissionStarted(),
452
+ )
453
+
454
+ assertEquals("SNI_REQUEST_FAILED", code)
455
+ }
456
+
457
+ @Test
458
+ fun refusedConnectionBeforeAnyTransmissionKeepsPreWriteCode() {
459
+ val state = SniRequestTransmissionState()
460
+ val code = gateReplaySensitiveFailureCode(
461
+ classifySniFailureCode(ConnectException("Connection refused")),
462
+ state.hasRequestTransmissionStarted(),
463
+ )
464
+
465
+ assertEquals("SNI_CONNECTION_REFUSED", code)
466
+ }
467
+
468
+ private fun newOkHttpCall(
469
+ state: SniRequestTransmissionState,
470
+ bodylessDelete: Boolean = false,
471
+ ): Call {
472
+ val builder = Request.Builder()
473
+ .url("https://example.com/")
474
+ .tag(SniRequestTransmissionState::class.java, state)
475
+ return OkHttpClient().newCall(
476
+ (if (bodylessDelete) builder.delete() else builder.get()).build(),
477
+ )
478
+ }
479
+
246
480
  private fun assertValidationFails(block: () -> Unit) {
247
481
  try {
248
482
  block()
package/ios/SniConnect.mm CHANGED
@@ -13,6 +13,9 @@
13
13
  - (void)request:(NSDictionary *)config
14
14
  resolve:(RCTPromiseResolveBlock)resolve
15
15
  reject:(RCTPromiseRejectBlock)reject;
16
+ - (void)uploadFile:(NSDictionary *)config
17
+ resolve:(RCTPromiseResolveBlock)resolve
18
+ reject:(RCTPromiseRejectBlock)reject;
16
19
  - (void)cancelRequest:(NSString *)requestId
17
20
  resolve:(RCTPromiseResolveBlock)resolve
18
21
  reject:(RCTPromiseRejectBlock)reject;
@@ -82,6 +85,24 @@ RCT_EXPORT_MODULE(SniConnect)
82
85
  [_implementation request:configDict resolve:resolve reject:reject];
83
86
  }
84
87
 
88
+ - (void)uploadFile:(JS::NativeSniConnect::NativeSniConnectUploadFileRequest &)config
89
+ resolve:(RCTPromiseResolveBlock)resolve
90
+ reject:(RCTPromiseRejectBlock)reject {
91
+ NSMutableDictionary *configDict = [NSMutableDictionary dictionary];
92
+ configDict[@"ip"] = config.ip() ?: @"";
93
+ configDict[@"hostname"] = config.hostname() ?: @"";
94
+ configDict[@"method"] = config.method() ?: @"POST";
95
+ configDict[@"path"] = config.path() ?: @"/";
96
+ configDict[@"headers"] = config.headers() ?: @{};
97
+ configDict[@"timeout"] = @(config.timeout());
98
+ configDict[@"filePath"] = config.filePath() ?: @"";
99
+ if (config.requestId()) {
100
+ configDict[@"requestId"] = config.requestId();
101
+ }
102
+
103
+ [_implementation uploadFile:configDict resolve:resolve reject:reject];
104
+ }
105
+
85
106
  - (void)cancelRequest:(NSString *)requestId
86
107
  resolve:(RCTPromiseResolveBlock)resolve
87
108
  reject:(RCTPromiseRejectBlock)reject {
@@ -127,6 +148,12 @@ RCT_EXPORT_METHOD(request:(NSDictionary *)config
127
148
  [_implementation request:config resolve:resolve reject:reject];
128
149
  }
129
150
 
151
+ RCT_EXPORT_METHOD(uploadFile:(NSDictionary *)config
152
+ resolver:(RCTPromiseResolveBlock)resolve
153
+ rejecter:(RCTPromiseRejectBlock)reject) {
154
+ [_implementation uploadFile:config resolve:resolve reject:reject];
155
+ }
156
+
130
157
  RCT_EXPORT_METHOD(cancelRequest:(NSString *)requestId
131
158
  resolver:(RCTPromiseResolveBlock)resolve
132
159
  rejecter:(RCTPromiseRejectBlock)reject) {
@@ -41,6 +41,26 @@ final class SniConnectImpl: NSObject {
41
41
  }
42
42
  }
43
43
 
44
+ @objc
45
+ public func uploadFile(
46
+ _ config: NSDictionary,
47
+ resolve: @escaping RCTPromiseResolveBlock,
48
+ reject: @escaping RCTPromiseRejectBlock
49
+ ) {
50
+ do {
51
+ let parsed = try Self.parseUploadFileDictionary(config)
52
+ handleRequest(config: parsed, resolve: resolve, reject: reject)
53
+ } catch {
54
+ SniConnectLog.error(SniConnectLog.event("sni_request_result", [
55
+ ("result", "error"),
56
+ ("code", "SNI_INVALID_CONFIG"),
57
+ ("nativeErrorClass", String(describing: type(of: error))),
58
+ ("stage", "parse_upload_config"),
59
+ ]))
60
+ reject("SNI_INVALID_CONFIG", "\(error)", error)
61
+ }
62
+ }
63
+
44
64
  private func handleRequest(
45
65
  config: SniConnectClient.RequestConfig,
46
66
  resolve: @escaping RCTPromiseResolveBlock,
@@ -54,9 +74,9 @@ final class SniConnectImpl: NSObject {
54
74
  ("code", "SNI_INVALID_CONFIG"),
55
75
  ("nativeErrorClass", String(describing: type(of: error))),
56
76
  ("stage", "validate_config"),
57
- ("requestIdHash", SniConnectLog.shortHash(config.requestId)),
77
+ ("requestId", config.requestId),
58
78
  ("hostname", config.hostname.lowercased()),
59
- ("ipHash", SniConnectLog.shortHash(config.ip)),
79
+ ("ip", config.ip),
60
80
  ("ipFamily", SniConnectLog.ipFamily(config.ip)),
61
81
  ("method", config.method.uppercased()),
62
82
  ("timeoutMs", Int(config.effectiveTotalTimeout)),
@@ -98,9 +118,9 @@ final class SniConnectImpl: NSObject {
98
118
  ("result", "error"),
99
119
  ("code", "SNI_UNKNOWN_ERROR"),
100
120
  ("nativeErrorClass", String(describing: type(of: error))),
101
- ("requestIdHash", SniConnectLog.shortHash(config.requestId)),
121
+ ("requestId", config.requestId),
102
122
  ("hostname", config.hostname.lowercased()),
103
- ("ipHash", SniConnectLog.shortHash(config.ip)),
123
+ ("ip", config.ip),
104
124
  ("ipFamily", SniConnectLog.ipFamily(config.ip)),
105
125
  ("method", config.method.uppercased()),
106
126
  ("timeoutMs", Int(config.effectiveTotalTimeout)),
@@ -213,6 +233,45 @@ final class SniConnectImpl: NSObject {
213
233
  )
214
234
  }
215
235
 
236
+ /// Uploads may only read files from this app's own container.
237
+ private static var uploadFileAllowedRoots: [URL] {
238
+ [
239
+ URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true),
240
+ URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true),
241
+ ]
242
+ }
243
+
244
+ private static func parseUploadFileDictionary(
245
+ _ dictionary: NSDictionary
246
+ ) throws -> SniConnectClient.RequestConfig {
247
+ guard dictionary["body"] == nil || dictionary["body"] is NSNull else {
248
+ throw SniConnectError.invalidConfig("uploadFile does not accept body")
249
+ }
250
+ guard let filePath = dictionary["filePath"] as? String, !filePath.isEmpty else {
251
+ throw SniConnectError.invalidConfig("Missing filePath")
252
+ }
253
+ let base = try parseDictionary(dictionary)
254
+ let method = try SniConnectValidation.normalizeMethod(base.method)
255
+ try SniConnectValidation.validateUploadMethod(method)
256
+ let resolvedFile = try SniConnectValidation.resolveUploadFile(
257
+ filePath,
258
+ allowedRoots: uploadFileAllowedRoots
259
+ )
260
+ return SniConnectClient.RequestConfig(
261
+ requestId: base.requestId,
262
+ ip: base.ip,
263
+ hostname: base.hostname,
264
+ method: method,
265
+ path: base.path,
266
+ headers: base.headers,
267
+ body: nil,
268
+ timeout: base.timeout,
269
+ bodyFileURL: resolvedFile.url,
270
+ connectTimeout: base.connectTimeout,
271
+ totalTimeout: base.totalTimeout
272
+ )
273
+ }
274
+
216
275
  private static func validate(_ config: SniConnectClient.RequestConfig) throws {
217
276
  try SniConnectValidation.validatePublicIP(config.ip)
218
277
  try SniConnectValidation.validateHostname(config.hostname)
@@ -221,6 +280,10 @@ final class SniConnectImpl: NSObject {
221
280
  _ = try SniConnectValidation.normalizePath(config.path)
222
281
  try SniConnectValidation.validateRequestId(config.requestId)
223
282
  try SniConnectValidation.validateTimeout(config.effectiveTotalTimeout)
283
+ if config.bodyFileURL != nil {
284
+ try SniConnectValidation.validateUploadMethod(method)
285
+ return
286
+ }
224
287
  try SniConnectValidation.validateBody(config.body)
225
288
  try SniConnectValidation.validateMethodBody(method: method, body: config.body)
226
289
  }