@onekeyfe/react-native-sni-connect 6.7.0-alpha.475 → 6.8.0-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.
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,85 +71,88 @@ Android autolinks.
36
71
  import {
37
72
  request,
38
73
  cancelRequest,
39
- cancelAllRequests,
40
- clearDNSCache,
41
- getDebugSnapshot,
42
74
  isProxyActiveForUrl,
43
- uploadFile,
44
- isUploadFileSupported,
45
75
  } from '@onekeyfe/react-native-sni-connect';
46
76
 
47
77
  const proxyActive = await isProxyActiveForUrl('https://example.com/api/v1/ping');
48
- if (proxyActive) {
49
- // Product adapters should avoid entering SNI mode when a per-URL/system proxy
50
- // is active. Low-level SNI requests still bypass proxies directly.
51
- }
78
+ // Adapters should avoid SNI mode while a per-URL/system proxy is active.
52
79
 
53
80
  const res = await request({
54
- // requestId is optional; required only if you want to cancel the request.
55
- requestId: 'health-check-1',
56
- ip: '93.184.216.34', // must be a public IP literal (private/loopback/metadata are rejected)
57
- 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
58
84
  method: 'GET',
59
- path: '/api/v1/ping', // relative path only — absolute URLs are rejected
85
+ path: '/api/v1/ping', // relative path only; absolute URLs are rejected
60
86
  headers: { 'Content-Type': 'application/json' },
61
87
  timeout: 30_000,
62
88
  });
63
89
 
64
90
  console.log(res.status, res.headers, res.data);
65
91
 
66
- // Cancellation (requires requestId on the request)
67
92
  await cancelRequest('health-check-1');
68
- await cancelAllRequests();
69
-
70
- // Drop pinned-IP connections / cached clients
71
- await clearDNSCache();
72
-
73
- // Diagnostics for one validated hostname/IP pair
74
- const snapshot = await getDebugSnapshot({
75
- hostname: 'example.com',
76
- ip: '93.184.216.34',
77
- });
78
93
  ```
79
94
 
80
- `multiValueHeaders` preserves repeated response headers when the native transport
81
- exposes them as raw entries. On iOS, EMASCurl 1.5.5 currently hands this module a
82
- `HTTPURLResponse` dictionary view, so duplicate header names may already be
83
- collapsed by the transport before this adapter can observe them. Full duplicate
84
- header preservation on iOS requires an EMASCurl version that exposes the raw
85
- response header list.
86
-
87
- Check `isUploadFileSupported()` before uploading when JS can run with older native
88
- binaries. `uploadFile()` rejects with `code: SNI_UNSUPPORTED` when unavailable.
89
-
90
- ## Specification
91
-
92
- The behavior of the SNI connect module is governed by a normative,
93
- platform-agnostic standard that all implementations (iOS, Android, Node/Desktop,
94
- shared JS adapters, and any future platform) must conform to:
95
-
96
- **-> [OneKey SNI Connect Standard (OSCS)](https://github.com/OneKeyHQ/app-modules/blob/main/native-modules/react-native-sni-connect/SPEC.md)**
97
-
98
- The [native upload contract](docs/SPEC.md) defines capability detection and
99
- consumption-time file bounds.
100
-
101
- Any change to request validation, destination pinning, TLS validation, redirect
102
- handling, cancellation, response shape, or cache behavior must be checked
103
- against OSCS.
104
- When an implementation and the standard disagree, the implementation is wrong.
105
-
106
- ### Security notes
107
-
108
- - The request scheme is always `https` on port `443`; `path` cannot override scheme, host or port.
109
- - `isProxyActiveForUrl(url)` is a preflight probe for adapters. It does not enable proxying;
110
- native SNI transport still bypasses system proxy configuration.
111
- - `ip` must be an IPv4/IPv6 literal that routes to a public destination; loopback, private,
112
- link-local (incl. cloud metadata), CGNAT, multicast and reserved ranges are rejected.
113
- - Header names/values containing CR/LF/control characters are rejected; the `Host` header is
114
- managed by the module.
115
- - Native logs go through OneKey's native logger (with sensitive-data redaction); there is no
116
- 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)
117
155
 
118
156
  ## License
119
157
 
120
- 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 {
@@ -24,6 +24,7 @@ import okio.Buffer
24
24
  import java.io.File
25
25
  import java.io.IOException
26
26
  import java.io.InterruptedIOException
27
+ import java.net.ConnectException
27
28
  import java.net.Proxy
28
29
  import java.net.ProxySelector
29
30
  import java.net.URI
@@ -40,15 +41,29 @@ import javax.net.ssl.SSLPeerUnverifiedException
40
41
 
41
42
  private const val TAG = "SniConnect"
42
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
+ */
43
50
  internal fun classifySniFailureCode(error: Throwable): String {
44
51
  if (hasCause(error, SSLPeerUnverifiedException::class.java) ||
45
52
  hasCause(error, CertificateException::class.java)
46
53
  ) {
47
54
  return "SNI_CERT_FAILED"
48
55
  }
49
- 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)) {
50
59
  return "SNI_SECURITY_POLICY_FAILED"
51
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
+ }
52
67
  if (hasCause(error, InterruptedIOException::class.java)) {
53
68
  return "SNI_REQUEST_TIMEOUT"
54
69
  }
@@ -58,6 +73,23 @@ internal fun classifySniFailureCode(error: Throwable): String {
58
73
  return "SNI_REQUEST_FAILED"
59
74
  }
60
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
+
61
93
  internal fun classifySniResponseFailureCode(
62
94
  error: Throwable,
63
95
  explicitlyCancelled: Boolean,
@@ -119,7 +151,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
119
151
  SniConnectLogger.event(
120
152
  "sni_cache_evict",
121
153
  "hostname" to eldest.key.hostname,
122
- "ipHash" to SniConnectLogger.shortHash(eldest.key.ip),
154
+ "ip" to eldest.key.ip,
123
155
  "cacheSize" to size,
124
156
  "limit" to MAX_CLIENTS,
125
157
  "reason" to "max_cached_clients",
@@ -220,7 +252,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
220
252
  SniConnectLogger.info(
221
253
  SniConnectLogger.event(
222
254
  "sni_cancel",
223
- "requestIdHash" to SniConnectLogger.shortHash(requestId),
255
+ "requestId" to requestId,
224
256
  "success" to true,
225
257
  ),
226
258
  )
@@ -229,7 +261,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
229
261
  SniConnectLogger.warn(
230
262
  SniConnectLogger.event(
231
263
  "sni_cancel",
232
- "requestIdHash" to SniConnectLogger.shortHash(requestId),
264
+ "requestId" to requestId,
233
265
  "success" to false,
234
266
  ),
235
267
  )
@@ -302,10 +334,13 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
302
334
  private fun performRequest(config: RequestConfig, promise: Promise) {
303
335
  val startedAtMs = android.os.SystemClock.elapsedRealtime()
304
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()
305
340
  var registeredRequest: ManagedRequest? = null
306
341
  try {
307
342
  val client = getOrCreateClient(config)
308
- val request = buildRequest(config)
343
+ val request = buildRequest(config, requestTransmission)
309
344
  val call = client.newCall(request)
310
345
  val settled = AtomicBoolean(false)
311
346
  lateinit var managedRequest: ManagedRequest
@@ -313,9 +348,9 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
313
348
  SniConnectLogger.info(
314
349
  SniConnectLogger.event(
315
350
  "sni_request_start",
316
- "requestIdHash" to SniConnectLogger.shortHash(config.requestId),
351
+ "requestId" to config.requestId,
317
352
  "hostname" to config.hostname.lowercase(Locale.US),
318
- "ipHash" to SniConnectLogger.shortHash(config.ip),
353
+ "ip" to config.ip,
319
354
  "ipFamily" to SniConnectLogger.ipFamily(config.ip),
320
355
  "method" to config.method,
321
356
  "timeoutMs" to config.timeoutMillis,
@@ -334,16 +369,19 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
334
369
  if (managedRequest.wasExplicitlyCancelled()) {
335
370
  promise.reject("SNI_CANCELLED", "Request cancelled", null)
336
371
  } else {
337
- val code = classifySniFailureCode(e)
372
+ val code = gateReplaySensitiveFailureCode(
373
+ classifySniFailureCode(e),
374
+ requestTransmission.hasRequestTransmissionStarted(),
375
+ )
338
376
  SniConnectLogger.error(
339
377
  SniConnectLogger.event(
340
378
  "sni_request_result",
341
379
  "result" to "error",
342
380
  "code" to code,
343
381
  "nativeErrorClass" to e.javaClass.simpleName,
344
- "requestIdHash" to SniConnectLogger.shortHash(config.requestId),
382
+ "requestId" to config.requestId,
345
383
  "hostname" to config.hostname.lowercase(Locale.US),
346
- "ipHash" to SniConnectLogger.shortHash(config.ip),
384
+ "ip" to config.ip,
347
385
  "ipFamily" to SniConnectLogger.ipFamily(config.ip),
348
386
  "method" to config.method,
349
387
  "timeoutMs" to config.timeoutMillis,
@@ -363,9 +401,9 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
363
401
  "sni_request_result",
364
402
  "result" to "response",
365
403
  "status" to currentResponse.code,
366
- "requestIdHash" to SniConnectLogger.shortHash(config.requestId),
404
+ "requestId" to config.requestId,
367
405
  "hostname" to config.hostname.lowercase(Locale.US),
368
- "ipHash" to SniConnectLogger.shortHash(config.ip),
406
+ "ip" to config.ip,
369
407
  "ipFamily" to SniConnectLogger.ipFamily(config.ip),
370
408
  "method" to config.method,
371
409
  "timeoutMs" to config.timeoutMillis,
@@ -410,9 +448,9 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
410
448
  "result" to "error",
411
449
  "code" to code,
412
450
  "nativeErrorClass" to error.javaClass.simpleName,
413
- "requestIdHash" to SniConnectLogger.shortHash(config.requestId),
451
+ "requestId" to config.requestId,
414
452
  "hostname" to config.hostname.lowercase(Locale.US),
415
- "ipHash" to SniConnectLogger.shortHash(config.ip),
453
+ "ip" to config.ip,
416
454
  "ipFamily" to SniConnectLogger.ipFamily(config.ip),
417
455
  "method" to config.method,
418
456
  "timeoutMs" to config.timeoutMillis,
@@ -477,9 +515,9 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
477
515
  "result" to "error",
478
516
  "code" to code,
479
517
  "nativeErrorClass" to error.javaClass.simpleName,
480
- "requestIdHash" to SniConnectLogger.shortHash(config.requestId),
518
+ "requestId" to config.requestId,
481
519
  "hostname" to config.hostname.lowercase(Locale.US),
482
- "ipHash" to SniConnectLogger.shortHash(config.ip),
520
+ "ip" to config.ip,
483
521
  "ipFamily" to SniConnectLogger.ipFamily(config.ip),
484
522
  "method" to config.method,
485
523
  "timeoutMs" to config.timeoutMillis,
@@ -513,7 +551,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
513
551
  SniConnectLogger.warn(
514
552
  SniConnectLogger.event(
515
553
  "sni_duplicate_request_id",
516
- "requestIdHash" to SniConnectLogger.shortHash(requestId),
554
+ "requestId" to requestId,
517
555
  "action" to "cancel_previous",
518
556
  ),
519
557
  )
@@ -574,7 +612,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
574
612
  SniConnectLogger.event(
575
613
  "sni_transport_config",
576
614
  "hostname" to key.hostname,
577
- "ipHash" to SniConnectLogger.shortHash(key.ip),
615
+ "ip" to key.ip,
578
616
  "ipFamily" to SniConnectLogger.ipFamily(key.ip),
579
617
  "proxyMode" to "no_proxy",
580
618
  "pinnedResolver" to true,
@@ -591,9 +629,15 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
591
629
  * Build the request. Always `https://<hostname><path>` on the implicit port 443 —
592
630
  * `path` has been validated as relative, so scheme/host/port cannot be overridden.
593
631
  */
594
- private fun buildRequest(config: RequestConfig): Request {
632
+ private fun buildRequest(
633
+ config: RequestConfig,
634
+ requestTransmission: SniRequestTransmissionState,
635
+ ): Request {
595
636
  val url = "https://${config.hostname}${config.path}"
596
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)
597
641
 
598
642
  config.headers.forEach { (key, value) ->
599
643
  builder.addHeader(key, value)
@@ -7,9 +7,12 @@ import java.net.Proxy
7
7
  import java.net.UnknownHostException
8
8
  import java.util.Locale
9
9
  import java.util.concurrent.TimeUnit
10
+ import java.util.concurrent.atomic.AtomicBoolean
11
+ import okhttp3.Call
10
12
  import okhttp3.ConnectionPool
11
13
  import okhttp3.Dispatcher
12
14
  import okhttp3.Dns
15
+ import okhttp3.EventListener
13
16
  import okhttp3.MediaType
14
17
  import okhttp3.OkHttpClient
15
18
  import okhttp3.Protocol
@@ -45,6 +48,7 @@ object SniPinnedTransport {
45
48
  HttpsURLConnection.getDefaultHostnameVerifier().verify(normalizedHostname, session)
46
49
  }
47
50
  .dns(createPinnedDns(ip, normalizedHostname))
51
+ .eventListenerFactory(SniRequestTransmissionEventListenerFactory)
48
52
  .build()
49
53
  }
50
54
 
@@ -57,13 +61,54 @@ object SniPinnedTransport {
57
61
  if (requestedHost.lowercase(Locale.US) == hostname) {
58
62
  return listOf(pinnedAddress)
59
63
  }
60
- throw UnknownHostException(
64
+ throw SniPinnedDestinationViolationException(
61
65
  "Unexpected host for pinned SNI request: $requestedHost"
62
66
  )
63
67
  }
64
68
  }
65
69
  }
66
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
+
67
112
  /** Reads from disk only during transmission, with a fixed, bounded body length. */
68
113
  internal class SniUploadFileRequestBody(
69
114
  private val file: File,
@@ -2,8 +2,12 @@ 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
6
7
  import org.junit.Assert.assertThrows
8
+ import okhttp3.Call
9
+ import okhttp3.OkHttpClient
10
+ import okhttp3.Request
7
11
  import okio.Buffer
8
12
  import okio.ForwardingSink
9
13
  import okio.buffer
@@ -15,6 +19,7 @@ import java.io.IOException
15
19
  import java.io.RandomAccessFile
16
20
  import java.nio.file.Files
17
21
  import java.io.InterruptedIOException
22
+ import java.net.ConnectException
18
23
  import java.net.SocketTimeoutException
19
24
  import java.net.UnknownHostException
20
25
  import java.security.cert.CertificateException
@@ -337,7 +342,15 @@ class SniConnectValidationTest {
337
342
  )
338
343
  assertEquals(
339
344
  "SNI_SECURITY_POLICY_FAILED",
340
- 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
+ }),
341
354
  )
342
355
  assertEquals(
343
356
  "SNI_REQUEST_TIMEOUT",
@@ -367,6 +380,103 @@ class SniConnectValidationTest {
367
380
  )
368
381
  }
369
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
+
370
480
  private fun assertValidationFails(block: () -> Unit) {
371
481
  try {
372
482
  block()
@@ -74,9 +74,9 @@ final class SniConnectImpl: NSObject {
74
74
  ("code", "SNI_INVALID_CONFIG"),
75
75
  ("nativeErrorClass", String(describing: type(of: error))),
76
76
  ("stage", "validate_config"),
77
- ("requestIdHash", SniConnectLog.shortHash(config.requestId)),
77
+ ("requestId", config.requestId),
78
78
  ("hostname", config.hostname.lowercased()),
79
- ("ipHash", SniConnectLog.shortHash(config.ip)),
79
+ ("ip", config.ip),
80
80
  ("ipFamily", SniConnectLog.ipFamily(config.ip)),
81
81
  ("method", config.method.uppercased()),
82
82
  ("timeoutMs", Int(config.effectiveTotalTimeout)),
@@ -118,9 +118,9 @@ final class SniConnectImpl: NSObject {
118
118
  ("result", "error"),
119
119
  ("code", "SNI_UNKNOWN_ERROR"),
120
120
  ("nativeErrorClass", String(describing: type(of: error))),
121
- ("requestIdHash", SniConnectLog.shortHash(config.requestId)),
121
+ ("requestId", config.requestId),
122
122
  ("hostname", config.hostname.lowercased()),
123
- ("ipHash", SniConnectLog.shortHash(config.ip)),
123
+ ("ip", config.ip),
124
124
  ("ipFamily", SniConnectLog.ipFamily(config.ip)),
125
125
  ("method", config.method.uppercased()),
126
126
  ("timeoutMs", Int(config.effectiveTotalTimeout)),
@@ -112,7 +112,7 @@ final class SniConnectSessionInvalidationDelegate: NSObject, URLSessionDataDeleg
112
112
  let releasedResolver = resolverLease.release()
113
113
  SniConnectLog.info(SniConnectLog.event("sni_session_invalidated", [
114
114
  ("hostname", hostname),
115
- ("ipHash", SniConnectLog.shortHash(ip)),
115
+ ("ip", ip),
116
116
  ("releasedResolver", releasedResolver),
117
117
  ("success", error == nil),
118
118
  ]))
@@ -410,7 +410,7 @@ final class SniConnectClient {
410
410
  )
411
411
  SniConnectLog.info(SniConnectLog.event("sni_transport_config", [
412
412
  ("hostname", hostname),
413
- ("ipHash", SniConnectLog.shortHash(ip)),
413
+ ("ip", ip),
414
414
  ("ipFamily", SniConnectLog.ipFamily(ip)),
415
415
  ("proxyMode", "no_proxy"),
416
416
  ("pinnedResolver", true),
@@ -459,7 +459,7 @@ final class SniConnectClient {
459
459
  case .waitForResolverSlots(let resolverLeases):
460
460
  SniConnectLog.info(SniConnectLog.event("sni_resolver_slot_wait", [
461
461
  ("hostname", key.hostname),
462
- ("ipHash", SniConnectLog.shortHash(config.ip)),
462
+ ("ip", config.ip),
463
463
  ("waitCount", resolverLeases.count),
464
464
  ]))
465
465
  for resolverLease in resolverLeases {
@@ -510,7 +510,7 @@ final class SniConnectClient {
510
510
  }
511
511
  SniConnectLog.info(SniConnectLog.event("sni_cache_evict", [
512
512
  ("hostname", evictedKey.hostname),
513
- ("ipHash", SniConnectLog.shortHash(evictedKey.canonicalIP)),
513
+ ("ip", evictedKey.canonicalIP),
514
514
  ("cacheSize", sessionCache.count),
515
515
  ("limit", Self.maxCachedSessions),
516
516
  ("reason", forPendingInsert ? "max_cached_sessions_pending_insert" : "max_cached_sessions"),
@@ -581,14 +581,14 @@ final class SniConnectClient {
581
581
  guard let self = self, let token = self.requestTokensById.removeValue(forKey: requestId),
582
582
  let task = self.activeTasksByToken.removeValue(forKey: token) else {
583
583
  SniConnectLog.warn(SniConnectLog.event("sni_cancel", [
584
- ("requestIdHash", SniConnectLog.shortHash(requestId)),
584
+ ("requestId", requestId),
585
585
  ("success", false),
586
586
  ]))
587
587
  return false
588
588
  }
589
589
  task.cancel()
590
590
  SniConnectLog.info(SniConnectLog.event("sni_cancel", [
591
- ("requestIdHash", SniConnectLog.shortHash(requestId)),
591
+ ("requestId", requestId),
592
592
  ("success", true),
593
593
  ]))
594
594
  return true
@@ -638,7 +638,7 @@ final class SniConnectClient {
638
638
  let previousTask = self.activeTasksByToken.removeValue(forKey: previousToken) {
639
639
  previousTask.cancel()
640
640
  SniConnectLog.warn(SniConnectLog.event("sni_duplicate_request_id", [
641
- ("requestIdHash", SniConnectLog.shortHash(requestId)),
641
+ ("requestId", requestId),
642
642
  ("action", "cancel_previous"),
643
643
  ]))
644
644
  }
@@ -695,9 +695,9 @@ final class SniConnectClient {
695
695
  ("result", "error"),
696
696
  ("code", sniError.code),
697
697
  ("nativeErrorClass", String(describing: type(of: error))),
698
- ("requestIdHash", SniConnectLog.shortHash(config.requestId)),
698
+ ("requestId", config.requestId),
699
699
  ("hostname", config.hostname.lowercased()),
700
- ("ipHash", SniConnectLog.shortHash(config.ip)),
700
+ ("ip", config.ip),
701
701
  ("ipFamily", SniConnectLog.ipFamily(config.ip)),
702
702
  ("method", config.method.uppercased()),
703
703
  ("timeoutMs", Int(config.effectiveTotalTimeout)),
@@ -728,9 +728,9 @@ final class SniConnectClient {
728
728
  ("result", "error"),
729
729
  ("code", sniError.code),
730
730
  ("nativeErrorClass", String(describing: type(of: error))),
731
- ("requestIdHash", SniConnectLog.shortHash(config.requestId)),
731
+ ("requestId", config.requestId),
732
732
  ("hostname", config.hostname.lowercased()),
733
- ("ipHash", SniConnectLog.shortHash(config.ip)),
733
+ ("ip", config.ip),
734
734
  ("ipFamily", SniConnectLog.ipFamily(config.ip)),
735
735
  ("method", method),
736
736
  ("timeoutMs", Int(config.effectiveTotalTimeout)),
@@ -793,9 +793,9 @@ final class SniConnectClient {
793
793
  let request = mutableRequest as URLRequest
794
794
 
795
795
  SniConnectLog.info(SniConnectLog.event("sni_request_start", [
796
- ("requestIdHash", SniConnectLog.shortHash(config.requestId)),
796
+ ("requestId", config.requestId),
797
797
  ("hostname", config.hostname.lowercased()),
798
- ("ipHash", SniConnectLog.shortHash(config.ip)),
798
+ ("ip", config.ip),
799
799
  ("ipFamily", SniConnectLog.ipFamily(config.ip)),
800
800
  ("method", method),
801
801
  ("timeoutMs", Int(config.effectiveTotalTimeout)),
@@ -833,9 +833,9 @@ final class SniConnectClient {
833
833
  let resultLog = SniConnectLog.event("sni_request_result", [
834
834
  ("result", "response"),
835
835
  ("status", status),
836
- ("requestIdHash", SniConnectLog.shortHash(config.requestId)),
836
+ ("requestId", config.requestId),
837
837
  ("hostname", config.hostname.lowercased()),
838
- ("ipHash", SniConnectLog.shortHash(config.ip)),
838
+ ("ip", config.ip),
839
839
  ("ipFamily", SniConnectLog.ipFamily(config.ip)),
840
840
  ("method", method),
841
841
  ("timeoutMs", Int(config.effectiveTotalTimeout)),
@@ -862,9 +862,9 @@ final class SniConnectClient {
862
862
  ("result", "error"),
863
863
  ("code", error.code),
864
864
  ("nativeErrorClass", String(describing: type(of: error))),
865
- ("requestIdHash", SniConnectLog.shortHash(config.requestId)),
865
+ ("requestId", config.requestId),
866
866
  ("hostname", config.hostname.lowercased()),
867
- ("ipHash", SniConnectLog.shortHash(config.ip)),
867
+ ("ip", config.ip),
868
868
  ("ipFamily", SniConnectLog.ipFamily(config.ip)),
869
869
  ("method", method),
870
870
  ("timeoutMs", Int(config.effectiveTotalTimeout)),
@@ -878,9 +878,9 @@ final class SniConnectClient {
878
878
  ("result", "error"),
879
879
  ("code", sniError.code),
880
880
  ("nativeErrorClass", String(describing: type(of: error))),
881
- ("requestIdHash", SniConnectLog.shortHash(config.requestId)),
881
+ ("requestId", config.requestId),
882
882
  ("hostname", config.hostname.lowercased()),
883
- ("ipHash", SniConnectLog.shortHash(config.ip)),
883
+ ("ip", config.ip),
884
884
  ("ipFamily", SniConnectLog.ipFamily(config.ip)),
885
885
  ("method", method),
886
886
  ("timeoutMs", Int(config.effectiveTotalTimeout)),
@@ -114,7 +114,7 @@ final class SniConnectPinnedResolverRegistry {
114
114
  guard domain.caseInsensitiveCompare(config.hostname) == .orderedSame else {
115
115
  SniConnectCoreDiagnostics.warn(SniConnectCoreDiagnostics.event("sni_pinned_dns_unexpected_host", [
116
116
  ("expectedHost", config.hostname),
117
- ("requestedHostHash", SniConnectCoreDiagnostics.shortHash(domain.lowercased())),
117
+ ("requestedHost", domain.lowercased()),
118
118
  ("result", "fail_closed"),
119
119
  ]))
120
120
  return nil
@@ -23,7 +23,20 @@ enum SniConnectLog {
23
23
  static func event(_ name: String, _ fields: [(String, Any?)]) -> String {
24
24
  let normalizedFields: [(String, Any?)] = [("event", name)] + fields
25
25
  let pairs = normalizedFields.map { key, value in
26
- "\(key)=\(sanitize(value))"
26
+ let logValue = sanitize(value)
27
+ // Keep long diagnostic IDs recoverable without matching the logger's private-key filter.
28
+ var displayedValue = logValue
29
+ var formatSuffix = ""
30
+ if key == "requestId", let requestId = value as? String,
31
+ requestId != logValue || requestId.range(of: "[0-9a-fA-F]{64}", options: .regularExpression) != nil {
32
+ let allowed = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.")
33
+ displayedValue = (requestId.addingPercentEncoding(withAllowedCharacters: allowed) ?? "unavailable")
34
+ .replacingOccurrences(
35
+ of: "([0-9a-fA-F]{32})(?=[0-9a-fA-F]{32})", with: "$1-", options: .regularExpression
36
+ )
37
+ formatSuffix = " requestIdFormat=uri-hex32"
38
+ }
39
+ return "\(key)=\(displayedValue)\(formatSuffix)"
27
40
  }
28
41
  return pairs.joined(separator: " ")
29
42
  }
@@ -526,7 +526,7 @@ final class SniConnectRequestLimiter: @unchecked Sendable {
526
526
  ("limit", maxPendingRequests),
527
527
  ("reason", "max_pending_requests"),
528
528
  ("hostname", hostname.lowercased()),
529
- ("ipHash", SniConnectCoreDiagnostics.shortHash(ip)),
529
+ ("ip", ip),
530
530
  ]))
531
531
  immediateError = SniConnectValidation.ValidationError.resourceLimit(
532
532
  "Too many pending SNI requests"
@@ -3,6 +3,23 @@ import XCTest
3
3
 
4
4
  final class SniConnectValidationTests: XCTestCase {
5
5
 
6
+ func testUnexpectedResolverHostIsLoggedInPlaintextAndStillRejected() throws {
7
+ let registry = SniConnectPinnedResolverRegistry()
8
+ let resolverClass: AnyClass = try registry.resolverClass(hostname: "example.com", ip: "93.184.216.34") {
9
+ NSObject.self
10
+ }
11
+ var messages: [String] = []
12
+ let previousSink = SniConnectCoreDiagnostics.warnSink
13
+ SniConnectCoreDiagnostics.warnSink = { messages.append($0) }
14
+ defer { SniConnectCoreDiagnostics.warnSink = previousSink }
15
+
16
+ XCTAssertNil(registry.resolve(domain: "Unexpected.example.com", resolverClass: resolverClass))
17
+ XCTAssertEqual(messages.count, 1)
18
+ XCTAssertTrue(messages[0].contains("requestedHost=unexpected.example.com"))
19
+ XCTAssertTrue(messages[0].contains("result=fail_closed"))
20
+ XCTAssertFalse(messages[0].contains("requestedHostHash="))
21
+ }
22
+
6
23
  func testSessionWithoutForwardingDataDelegateAllowsResponse() {
7
24
  switch SniConnectSessionDelegatePolicy.responseDispositionWithoutForwardingDelegate {
8
25
  case .allow:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/react-native-sni-connect",
3
- "version": "6.7.0-alpha.475",
3
+ "version": "6.8.0-2",
4
4
  "description": "A React Native library for SNI-based HTTP requests with DNS caching and request management",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",