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

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.
package/README.md CHANGED
@@ -1,21 +1,52 @@
1
- # @onekeyfe/react-native-sni-connect
1
+ <div align="center">
2
2
 
3
- OneKey SNI HTTP client for React Native. Performs HTTPS requests to a caller-supplied
4
- IP address while preserving the original TLS SNI / `Host` of a hostname, so certificate
5
- chain and hostname verification are still enforced against the real hostname (not the IP).
3
+ # @onekeyfe/react-native-sni-connect
6
4
 
7
- Backed by EMASCurl (libcurl) on iOS and OkHttp on Android.
5
+ **HTTPS requests to a caller-supplied IP while TLS still validates the real hostname.**
6
+
7
+ [![npm](https://img.shields.io/npm/v/%40onekeyfe%2Freact-native-sni-connect?label=npm&color=4D6BFE)](https://www.npmjs.com/package/@onekeyfe/react-native-sni-connect)
8
+ [![license](https://img.shields.io/npm/l/%40onekeyfe%2Freact-native-sni-connect?label=license&color=4D6BFE)](LICENSE)
9
+ ![iOS](https://img.shields.io/badge/iOS-000000?logo=apple&logoColor=white)
10
+ ![Android](https://img.shields.io/badge/Android-3DDC84?logo=android&logoColor=white)
11
+ ![TurboModule](https://img.shields.io/badge/TurboModule-4D6BFE)
12
+
13
+ </div>
14
+
15
+ Connects to a literal IP address you already resolved while preserving the real
16
+ hostname's TLS SNI, `Host` header and certificate validation, so the certificate
17
+ chain is checked against the hostname rather than the IP. Requests are text-only:
18
+ send a UTF-8 body or stream an app-sandbox file through `uploadFile()`. The
19
+ transport is EMASCurl (libcurl) on iOS and OkHttp on Android; there is no Web
20
+ implementation, every request is `https` on port 443, and each connection is
21
+ pinned to a validated public destination.
22
+
23
+ ## Features
24
+
25
+ - **Pinned destination, real TLS identity** — SNI, `Host` and certificate
26
+ verification use `hostname`; `ip` only chooses the socket target.
27
+ - **Strict request validation** — public IP literals only, relative paths only,
28
+ control characters and module-owned routing headers rejected before I/O.
29
+ - **Bounded concurrency** — 64 active requests per process, 16 per
30
+ `(hostname, ip)` pair, a 256-request queue and `SNI_RESOURCE_LIMIT` on overflow.
31
+ - **Request-id cancellation** — cancel one in-flight request or every request
32
+ owned by the current runtime.
33
+ - **Binary uploads** — `uploadFile()` streams a local file up to 20 MiB;
34
+ `isUploadFileSupported()` feature-detects older native binaries.
35
+ - **Operational hooks** — `clearDNSCache()`, per-pair `getDebugSnapshot()` and a
36
+ `isProxyActiveForUrl()` preflight for adapters.
8
37
 
9
38
  ## Installation
10
39
 
11
- This package is published as part of the OneKey `app-modules` workspace:
12
-
13
40
  ```sh
14
41
  yarn add @onekeyfe/react-native-sni-connect
15
42
  ```
16
43
 
17
- iOS: add Aliyun's spec repo and make `EMASCurl` modular in your app Podfile,
18
- then run `pod install`:
44
+ Rebuild the native application after installing; the TurboModule is resolved at
45
+ import time and throws a linking error when the pods or Android native build are
46
+ missing. Android links through autolinking.
47
+
48
+ **iOS.** The pod depends on `EMASCurl`, which lives in Aliyun's spec repo. Add that source
49
+ and keep `EMASCurl` modular in the `Podfile`, then run `pod install`:
19
50
 
20
51
  ```ruby
21
52
  source 'https://github.com/CocoaPods/Specs.git'
@@ -28,7 +59,11 @@ target 'YourApp' do
28
59
  end
29
60
  ```
30
61
 
31
- Android autolinks.
62
+ **Android.** The application must declare the normal `INTERNET` permission:
63
+
64
+ ```xml
65
+ <uses-permission android:name="android.permission.INTERNET" />
66
+ ```
32
67
 
33
68
  ## Usage
34
69
 
@@ -36,77 +71,88 @@ Android autolinks.
36
71
  import {
37
72
  request,
38
73
  cancelRequest,
39
- cancelAllRequests,
40
- clearDNSCache,
41
- getDebugSnapshot,
42
74
  isProxyActiveForUrl,
43
75
  } from '@onekeyfe/react-native-sni-connect';
44
76
 
45
77
  const proxyActive = await isProxyActiveForUrl('https://example.com/api/v1/ping');
46
- if (proxyActive) {
47
- // Product adapters should avoid entering SNI mode when a per-URL/system proxy
48
- // is active. Low-level SNI requests still bypass proxies directly.
49
- }
78
+ // Adapters should avoid SNI mode while a per-URL/system proxy is active.
50
79
 
51
80
  const res = await request({
52
- // requestId is optional; required only if you want to cancel the request.
53
- requestId: 'health-check-1',
54
- ip: '93.184.216.34', // must be a public IP literal (private/loopback/metadata are rejected)
55
- hostname: 'example.com', // used for SNI, Host header and certificate validation
81
+ requestId: 'health-check-1', // required only if you want to cancel it
82
+ ip: '93.184.216.34', // public IP literal; private/loopback/metadata are rejected
83
+ hostname: 'example.com', // SNI, Host header and certificate validation
56
84
  method: 'GET',
57
- path: '/api/v1/ping', // relative path only — absolute URLs are rejected
85
+ path: '/api/v1/ping', // relative path only; absolute URLs are rejected
58
86
  headers: { 'Content-Type': 'application/json' },
59
87
  timeout: 30_000,
60
88
  });
61
89
 
62
90
  console.log(res.status, res.headers, res.data);
63
91
 
64
- // Cancellation (requires requestId on the request)
65
92
  await cancelRequest('health-check-1');
66
- await cancelAllRequests();
67
-
68
- // Drop pinned-IP connections / cached clients
69
- await clearDNSCache();
70
-
71
- // Diagnostics for one validated hostname/IP pair
72
- const snapshot = await getDebugSnapshot({
73
- hostname: 'example.com',
74
- ip: '93.184.216.34',
75
- });
76
93
  ```
77
94
 
78
- `multiValueHeaders` preserves repeated response headers when the native transport
79
- exposes them as raw entries. On iOS, EMASCurl 1.5.5 currently hands this module a
80
- `HTTPURLResponse` dictionary view, so duplicate header names may already be
81
- collapsed by the transport before this adapter can observe them. Full duplicate
82
- header preservation on iOS requires an EMASCurl version that exposes the raw
83
- response header list.
84
-
85
- ## Specification
86
-
87
- The behavior of the SNI connect module is governed by a normative,
88
- platform-agnostic standard that all implementations (iOS, Android, Node/Desktop,
89
- shared JS adapters, and any future platform) must conform to:
90
-
91
- **-> [OneKey SNI Connect Standard (OSCS)](https://github.com/OneKeyHQ/app-modules/blob/main/native-modules/react-native-sni-connect/SPEC.md)**
92
-
93
- Any change to request validation, destination pinning, TLS validation, redirect
94
- handling, cancellation, response shape, or cache behavior must be checked
95
- against OSCS.
96
- When an implementation and the standard disagree, the implementation is wrong.
97
-
98
- ### Security notes
99
-
100
- - The request scheme is always `https` on port `443`; `path` cannot override scheme, host or port.
101
- - `isProxyActiveForUrl(url)` is a preflight probe for adapters. It does not enable proxying;
102
- native SNI transport still bypasses system proxy configuration.
103
- - `ip` must be an IPv4/IPv6 literal that routes to a public destination; loopback, private,
104
- link-local (incl. cloud metadata), CGNAT, multicast and reserved ranges are rejected.
105
- - Header names/values containing CR/LF/control characters are rejected; the `Host` header is
106
- managed by the module.
107
- - Native logs go through OneKey's native logger (with sensitive-data redaction); there is no
108
- JS log event channel.
95
+ HTTP `4xx` and `5xx` resolve as normal responses; inspect `status`. The caller
96
+ owns the target IP, the request id lifecycle and higher-level retry policy.
97
+
98
+ ## API
99
+
100
+ | Export | Signature | Platforms | Description |
101
+ | --- | --- | :-: | --- |
102
+ | `request` | `(config: SniConnectRequest) => Promise<SniConnectResponse>` | iOS, Android | Sends one HTTPS request over the pinned SNI transport. |
103
+ | `uploadFile` | `(config: SniConnectUploadFileRequest) => Promise<SniConnectResponse>` | iOS, Android | Sends a local file body (`POST`/`PUT`, 1 byte–20 MiB). |
104
+ | `isUploadFileSupported` | `() => boolean` | iOS, Android | Reports whether the loaded native module exposes `uploadFile`. |
105
+ | `cancelRequest` | `(requestId: string) => Promise<{ success: boolean }>` | iOS, Android | Cancels the active request with that id. |
106
+ | `cancelAllRequests` | `() => Promise<{ success: boolean }>` | iOS, Android | Cancels every request owned by the current runtime. |
107
+ | `clearDNSCache` | `() => Promise<{ success: boolean }>` | iOS, Android | Evicts cached pinned destinations, clients and idle connections. |
108
+ | `getDebugSnapshot` | `({ hostname, ip }) => Promise<SniConnectDebugSnapshot>` | iOS, Android | Reads active/pending counters and request ids for one pair. |
109
+ | `isProxyActiveForUrl` | `(url: string) => Promise<boolean>` | iOS, Android | Preflight proxy probe; does not enable proxying for SNI requests. |
110
+
111
+ `SniConnectResponse` contains `data` (string), `status`, `statusText`, `headers`
112
+ and an optional `multiValueHeaders`. Limits: 1 MiB body, 8 KiB path/query, 64
113
+ headers / 32 KiB total, 10 MiB response. Exported types include
114
+ `SniConnectRequest`, `SniConnectResponse` and `SniConnectUploadFileRequest`; see
115
+ [`src/NativeSniConnect.ts`](src/NativeSniConnect.ts).
116
+
117
+ ## Platform support
118
+
119
+ | Capability | iOS | Android | Web |
120
+ | --- | :-: | :-: | :-: |
121
+ | Pinned-IP request with hostname TLS | ✅ | ✅ | — |
122
+ | String request body | ✅ | ✅ | — |
123
+ | Binary file upload (`uploadFile`) | ✅ | ✅ | — |
124
+ | Per-request and bulk cancellation | ✅ | ✅ | — |
125
+ | Cache clear and debug snapshot | ✅ | ✅ | — |
126
+ | Proxy preflight | ✅ | ✅ | — |
127
+ | Repeated response headers (`multiValueHeaders`) | ⚠️ may collapse | ✅ | — |
128
+
129
+ ## Caveats
130
+
131
+ > [!IMPORTANT]
132
+ > `ip` must be a public IP literal — loopback, private, link-local (including
133
+ > cloud metadata), CGNAT, multicast and reserved ranges are rejected. `path`
134
+ > cannot carry a scheme, host or port, and `Host` / `Content-Length` stay
135
+ > module-owned.
136
+
137
+ > [!WARNING]
138
+ > This is a text-response API with a 10 MiB response cap; binary response
139
+ > transport is out of scope. Send binary request bodies with `uploadFile()` and
140
+ > feature-detect it with `isUploadFileSupported()` before use.
141
+
142
+ > [!NOTE]
143
+ > On iOS the EMASCurl version used here exposes response headers as a dictionary
144
+ > view, so repeated headers may already be collapsed before `multiValueHeaders`
145
+ > is built. `isProxyActiveForUrl()` only reports proxy state; SNI transport
146
+ > always bypasses system proxy configuration.
147
+
148
+ ## References
149
+
150
+ - [OSCS standard](SPEC.md)
151
+ - [Native upload contract](docs/SPEC.md)
152
+ - [Native interface](src/NativeSniConnect.ts)
153
+ - [npm package](https://www.npmjs.com/package/@onekeyfe/react-native-sni-connect)
154
+ - [Changelog](../../CHANGELOG.md)
109
155
 
110
156
  ## License
111
157
 
112
- MIT
158
+ MIT. See [LICENSE](LICENSE).
@@ -9,6 +9,7 @@ package com.sniconnect
9
9
  */
10
10
  internal object SniConnectLogger {
11
11
  private const val TAG = "SniConnect"
12
+ private val requestIdHexRun = Regex("([0-9a-fA-F]{32})(?=[0-9a-fA-F]{32})")
12
13
 
13
14
  private val logClass: Class<*>? by lazy {
14
15
  try {
@@ -42,7 +43,18 @@ internal object SniConnectLogger {
42
43
 
43
44
  fun event(name: String, vararg fields: Pair<String, Any?>): String =
44
45
  (listOf("event" to name) + fields).joinToString(separator = " ") { (key, value) ->
45
- "$key=${sanitize(value)}"
46
+ val logValue = sanitize(value)
47
+ // Keep long diagnostic IDs recoverable without matching the logger's private-key filter.
48
+ var displayedValue = logValue
49
+ var formatSuffix = ""
50
+ if (key == "requestId" && value is String &&
51
+ (value != logValue || requestIdHexRun.containsMatchIn(value))) {
52
+ displayedValue = java.net.URLEncoder.encode(value, "UTF-8")
53
+ .replace("+", "%20").replace("-", "%2D").replace("*", "%2A")
54
+ .replace(requestIdHexRun, "$1-")
55
+ formatSuffix = " requestIdFormat=uri-hex32"
56
+ }
57
+ "$key=$displayedValue$formatSuffix"
46
58
  }
47
59
 
48
60
  fun shortHash(value: String?): String {
@@ -21,8 +21,10 @@ import okhttp3.RequestBody.Companion.toRequestBody
21
21
  import okhttp3.Response
22
22
  import okhttp3.ResponseBody
23
23
  import okio.Buffer
24
+ import java.io.File
24
25
  import java.io.IOException
25
26
  import java.io.InterruptedIOException
27
+ import java.net.ConnectException
26
28
  import java.net.Proxy
27
29
  import java.net.ProxySelector
28
30
  import java.net.URI
@@ -39,15 +41,29 @@ import javax.net.ssl.SSLPeerUnverifiedException
39
41
 
40
42
  private const val TAG = "SniConnect"
41
43
 
44
+ /**
45
+ * Classifies a request-phase failure for the JS-facing error code. The result
46
+ * is not yet replay-safe: callers MUST pass it through
47
+ * [gateReplaySensitiveFailureCode] with the logical request's transmission
48
+ * evidence.
49
+ */
42
50
  internal fun classifySniFailureCode(error: Throwable): String {
43
51
  if (hasCause(error, SSLPeerUnverifiedException::class.java) ||
44
52
  hasCause(error, CertificateException::class.java)
45
53
  ) {
46
54
  return "SNI_CERT_FAILED"
47
55
  }
48
- if (hasCause(error, UnknownHostException::class.java)) {
56
+ // The pinned resolver never performs system DNS, so this is a destination
57
+ // escape and stays fail-closed instead of becoming a transient DNS failure.
58
+ if (hasCause(error, SniPinnedDestinationViolationException::class.java)) {
49
59
  return "SNI_SECURITY_POLICY_FAILED"
50
60
  }
61
+ if (hasCause(error, UnknownHostException::class.java)) {
62
+ return "SNI_DNS_FAILED"
63
+ }
64
+ if (hasCause(error, ConnectException::class.java)) {
65
+ return "SNI_CONNECTION_REFUSED"
66
+ }
51
67
  if (hasCause(error, InterruptedIOException::class.java)) {
52
68
  return "SNI_REQUEST_TIMEOUT"
53
69
  }
@@ -57,6 +73,23 @@ internal fun classifySniFailureCode(error: Throwable): String {
57
73
  return "SNI_REQUEST_FAILED"
58
74
  }
59
75
 
76
+ /**
77
+ * OkHttp can recover and retry inside one logical request. A final connect
78
+ * failure only proves no request was transmitted when no attempt ever started
79
+ * sending request headers; after a started attempt the outcome is ambiguous, so
80
+ * the pre-write code must not authorize a caller replay. Bodyless methods (for
81
+ * example `DELETE`) are covered by the same request-level evidence.
82
+ */
83
+ internal fun gateReplaySensitiveFailureCode(
84
+ code: String,
85
+ requestTransmissionStarted: Boolean,
86
+ ): String =
87
+ if (code == "SNI_CONNECTION_REFUSED" && requestTransmissionStarted) {
88
+ "SNI_REQUEST_FAILED"
89
+ } else {
90
+ code
91
+ }
92
+
60
93
  internal fun classifySniResponseFailureCode(
61
94
  error: Throwable,
62
95
  explicitlyCancelled: Boolean,
@@ -118,7 +151,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
118
151
  SniConnectLogger.event(
119
152
  "sni_cache_evict",
120
153
  "hostname" to eldest.key.hostname,
121
- "ipHash" to SniConnectLogger.shortHash(eldest.key.ip),
154
+ "ip" to eldest.key.ip,
122
155
  "cacheSize" to size,
123
156
  "limit" to MAX_CLIENTS,
124
157
  "reason" to "max_cached_clients",
@@ -191,6 +224,24 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
191
224
  }
192
225
  }
193
226
 
227
+ override fun uploadFile(config: ReadableMap, promise: Promise) {
228
+ try {
229
+ val requestConfig = config.toUploadFileConfig()
230
+ performRequest(requestConfig, promise)
231
+ } catch (error: Exception) {
232
+ SniConnectLogger.error(
233
+ SniConnectLogger.event(
234
+ "sni_request_result",
235
+ "result" to "error",
236
+ "code" to "SNI_INVALID_CONFIG",
237
+ "nativeErrorClass" to error.javaClass.simpleName,
238
+ "stage" to "parse_upload_config",
239
+ ),
240
+ )
241
+ promise.reject("SNI_INVALID_CONFIG", error.message, error)
242
+ }
243
+ }
244
+
194
245
  @ReactMethod
195
246
  override fun cancelRequest(requestId: String, promise: Promise) {
196
247
  val request = synchronized(activeCallsLock) {
@@ -201,7 +252,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
201
252
  SniConnectLogger.info(
202
253
  SniConnectLogger.event(
203
254
  "sni_cancel",
204
- "requestIdHash" to SniConnectLogger.shortHash(requestId),
255
+ "requestId" to requestId,
205
256
  "success" to true,
206
257
  ),
207
258
  )
@@ -210,7 +261,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
210
261
  SniConnectLogger.warn(
211
262
  SniConnectLogger.event(
212
263
  "sni_cancel",
213
- "requestIdHash" to SniConnectLogger.shortHash(requestId),
264
+ "requestId" to requestId,
214
265
  "success" to false,
215
266
  ),
216
267
  )
@@ -283,10 +334,13 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
283
334
  private fun performRequest(config: RequestConfig, promise: Promise) {
284
335
  val startedAtMs = android.os.SystemClock.elapsedRealtime()
285
336
  val startedAtNanos = System.nanoTime()
337
+ // Shared by every OkHttp attempt of this logical request. The client's
338
+ // EventListener marks it once any attempt starts sending request headers.
339
+ val requestTransmission = SniRequestTransmissionState()
286
340
  var registeredRequest: ManagedRequest? = null
287
341
  try {
288
342
  val client = getOrCreateClient(config)
289
- val request = buildRequest(config)
343
+ val request = buildRequest(config, requestTransmission)
290
344
  val call = client.newCall(request)
291
345
  val settled = AtomicBoolean(false)
292
346
  lateinit var managedRequest: ManagedRequest
@@ -294,14 +348,15 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
294
348
  SniConnectLogger.info(
295
349
  SniConnectLogger.event(
296
350
  "sni_request_start",
297
- "requestIdHash" to SniConnectLogger.shortHash(config.requestId),
351
+ "requestId" to config.requestId,
298
352
  "hostname" to config.hostname.lowercase(Locale.US),
299
- "ipHash" to SniConnectLogger.shortHash(config.ip),
353
+ "ip" to config.ip,
300
354
  "ipFamily" to SniConnectLogger.ipFamily(config.ip),
301
355
  "method" to config.method,
302
356
  "timeoutMs" to config.timeoutMillis,
303
357
  "headerCount" to config.headers.size,
304
- "bodyBytes" to (config.body?.toByteArray(StandardCharsets.UTF_8)?.size ?: 0),
358
+ "bodyBytes" to config.bodyBytes(),
359
+ "bodySource" to if (config.bodyFile != null) "file" else "string",
305
360
  ),
306
361
  )
307
362
 
@@ -314,16 +369,19 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
314
369
  if (managedRequest.wasExplicitlyCancelled()) {
315
370
  promise.reject("SNI_CANCELLED", "Request cancelled", null)
316
371
  } else {
317
- val code = classifySniFailureCode(e)
372
+ val code = gateReplaySensitiveFailureCode(
373
+ classifySniFailureCode(e),
374
+ requestTransmission.hasRequestTransmissionStarted(),
375
+ )
318
376
  SniConnectLogger.error(
319
377
  SniConnectLogger.event(
320
378
  "sni_request_result",
321
379
  "result" to "error",
322
380
  "code" to code,
323
381
  "nativeErrorClass" to e.javaClass.simpleName,
324
- "requestIdHash" to SniConnectLogger.shortHash(config.requestId),
382
+ "requestId" to config.requestId,
325
383
  "hostname" to config.hostname.lowercase(Locale.US),
326
- "ipHash" to SniConnectLogger.shortHash(config.ip),
384
+ "ip" to config.ip,
327
385
  "ipFamily" to SniConnectLogger.ipFamily(config.ip),
328
386
  "method" to config.method,
329
387
  "timeoutMs" to config.timeoutMillis,
@@ -343,12 +401,13 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
343
401
  "sni_request_result",
344
402
  "result" to "response",
345
403
  "status" to currentResponse.code,
346
- "requestIdHash" to SniConnectLogger.shortHash(config.requestId),
404
+ "requestId" to config.requestId,
347
405
  "hostname" to config.hostname.lowercase(Locale.US),
348
- "ipHash" to SniConnectLogger.shortHash(config.ip),
406
+ "ip" to config.ip,
349
407
  "ipFamily" to SniConnectLogger.ipFamily(config.ip),
350
408
  "method" to config.method,
351
409
  "timeoutMs" to config.timeoutMillis,
410
+ "bodyBytes" to config.bodyBytes(),
352
411
  "responseBytes" to bodyString.toByteArray(StandardCharsets.UTF_8).size,
353
412
  "elapsedMs" to SniConnectLogger.elapsedMs(startedAtMs),
354
413
  )
@@ -389,9 +448,9 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
389
448
  "result" to "error",
390
449
  "code" to code,
391
450
  "nativeErrorClass" to error.javaClass.simpleName,
392
- "requestIdHash" to SniConnectLogger.shortHash(config.requestId),
451
+ "requestId" to config.requestId,
393
452
  "hostname" to config.hostname.lowercase(Locale.US),
394
- "ipHash" to SniConnectLogger.shortHash(config.ip),
453
+ "ip" to config.ip,
395
454
  "ipFamily" to SniConnectLogger.ipFamily(config.ip),
396
455
  "method" to config.method,
397
456
  "timeoutMs" to config.timeoutMillis,
@@ -456,9 +515,9 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
456
515
  "result" to "error",
457
516
  "code" to code,
458
517
  "nativeErrorClass" to error.javaClass.simpleName,
459
- "requestIdHash" to SniConnectLogger.shortHash(config.requestId),
518
+ "requestId" to config.requestId,
460
519
  "hostname" to config.hostname.lowercase(Locale.US),
461
- "ipHash" to SniConnectLogger.shortHash(config.ip),
520
+ "ip" to config.ip,
462
521
  "ipFamily" to SniConnectLogger.ipFamily(config.ip),
463
522
  "method" to config.method,
464
523
  "timeoutMs" to config.timeoutMillis,
@@ -492,7 +551,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
492
551
  SniConnectLogger.warn(
493
552
  SniConnectLogger.event(
494
553
  "sni_duplicate_request_id",
495
- "requestIdHash" to SniConnectLogger.shortHash(requestId),
554
+ "requestId" to requestId,
496
555
  "action" to "cancel_previous",
497
556
  ),
498
557
  )
@@ -553,7 +612,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
553
612
  SniConnectLogger.event(
554
613
  "sni_transport_config",
555
614
  "hostname" to key.hostname,
556
- "ipHash" to SniConnectLogger.shortHash(key.ip),
615
+ "ip" to key.ip,
557
616
  "ipFamily" to SniConnectLogger.ipFamily(key.ip),
558
617
  "proxyMode" to "no_proxy",
559
618
  "pinnedResolver" to true,
@@ -570,9 +629,15 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
570
629
  * Build the request. Always `https://<hostname><path>` on the implicit port 443 —
571
630
  * `path` has been validated as relative, so scheme/host/port cannot be overridden.
572
631
  */
573
- private fun buildRequest(config: RequestConfig): Request {
632
+ private fun buildRequest(
633
+ config: RequestConfig,
634
+ requestTransmission: SniRequestTransmissionState,
635
+ ): Request {
574
636
  val url = "https://${config.hostname}${config.path}"
575
637
  val builder = Request.Builder().url(url)
638
+ // The transport's EventListener reads this tag on every OkHttp attempt,
639
+ // including bodyless methods that never write a request body.
640
+ builder.tag(SniRequestTransmissionState::class.java, requestTransmission)
576
641
 
577
642
  config.headers.forEach { (key, value) ->
578
643
  builder.addHeader(key, value)
@@ -581,13 +646,13 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
581
646
  builder.header("Accept-Encoding", "identity")
582
647
 
583
648
  val method = config.method
584
- val requestBody = config.body?.let { bodyContent ->
585
- val mediaType = config.headers.entries
586
- .firstOrNull { it.key.equals("Content-Type", ignoreCase = true) }
587
- ?.value
588
- ?.toMediaTypeOrNull()
589
- bodyContent.toRequestBody(mediaType)
590
- }
649
+ val mediaType = config.headers.entries
650
+ .firstOrNull { it.key.equals("Content-Type", ignoreCase = true) }
651
+ ?.value
652
+ ?.toMediaTypeOrNull()
653
+ // Enforce the body bound when OkHttp consumes the file, after admission.
654
+ val requestBody = config.bodyFile?.let { SniUploadFileRequestBody(it, mediaType) }
655
+ ?: config.body?.toRequestBody(mediaType)
591
656
 
592
657
  when (method) {
593
658
  "GET" -> builder.get()
@@ -713,6 +778,67 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
713
778
  )
714
779
  }
715
780
 
781
+ /** Uploads may only read files from this app's own storage. */
782
+ private fun uploadFileAllowedRoots(): List<File> {
783
+ val context = reactApplicationContext
784
+ return listOfNotNull(
785
+ File(context.applicationInfo.dataDir),
786
+ context.filesDir,
787
+ context.cacheDir,
788
+ context.externalCacheDir,
789
+ context.getExternalFilesDir(null),
790
+ )
791
+ }
792
+
793
+ private fun ReadableMap.toUploadFileConfig(): RequestConfig {
794
+ if (hasKey("body") && !isNull("body")) {
795
+ throw IllegalArgumentException("uploadFile does not accept body")
796
+ }
797
+ val filePath = if (hasKey("filePath") && !isNull("filePath")) getString("filePath") else null
798
+ if (filePath.isNullOrEmpty()) {
799
+ throw IllegalArgumentException("filePath is required")
800
+ }
801
+ val rawHeadersMap = if (hasKey("headers") && !isNull("headers")) {
802
+ getMap("headers")?.toHashMap()
803
+ ?.mapValues { (_, value) -> value?.toString() ?: "" }
804
+ ?: emptyMap()
805
+ } else {
806
+ emptyMap()
807
+ }
808
+ val timeoutMillis = if (hasKey("timeout") && !isNull("timeout")) {
809
+ SniConnectValidation.parseTimeoutMillis(getDouble("timeout"))
810
+ } else {
811
+ 30_000L
812
+ }
813
+ val requestId = if (hasKey("requestId") && !isNull("requestId")) getString("requestId") else null
814
+ val rawIp = getString("ip") ?: throw IllegalArgumentException("ip is required")
815
+ val hostname = getString("hostname") ?: throw IllegalArgumentException("hostname is required")
816
+ val method = getString("method") ?: "POST"
817
+ val path = getString("path") ?: "/"
818
+
819
+ SniConnectValidation.validateRequestId(requestId)
820
+ val ip = SniConnectValidation.canonicalizePublicIp(rawIp)
821
+ SniConnectValidation.validateHostname(hostname)
822
+ val headersMap = SniConnectValidation.normalizeHeaders(rawHeadersMap)
823
+ val normalizedMethod = SniConnectValidation.normalizeMethod(method)
824
+ SniConnectValidation.validateUploadMethod(normalizedMethod)
825
+ val normalizedPath = SniConnectValidation.normalizePath(path)
826
+ SniConnectValidation.validateTimeout(timeoutMillis)
827
+ val bodyFile = SniConnectValidation.resolveUploadFile(filePath, uploadFileAllowedRoots())
828
+
829
+ return RequestConfig(
830
+ requestId = requestId,
831
+ ip = ip,
832
+ hostname = hostname,
833
+ method = normalizedMethod,
834
+ path = normalizedPath,
835
+ headers = headersMap,
836
+ body = null,
837
+ timeoutMillis = timeoutMillis,
838
+ bodyFile = bodyFile,
839
+ )
840
+ }
841
+
716
842
  private data class RequestConfig(
717
843
  val requestId: String?,
718
844
  val ip: String,
@@ -722,7 +848,12 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
722
848
  val headers: Map<String, String>,
723
849
  val body: String?,
724
850
  val timeoutMillis: Long,
725
- )
851
+ // Set only by uploadFile(); already resolved inside the app sandbox.
852
+ val bodyFile: File? = null,
853
+ ) {
854
+ fun bodyBytes(): Long =
855
+ bodyFile?.length() ?: (body?.toByteArray(StandardCharsets.UTF_8)?.size?.toLong() ?: 0L)
856
+ }
726
857
 
727
858
  private data class HeaderMaps(
728
859
  val singleValueHeaders: Map<String, String>,