@onekeyfe/react-native-sni-connect 6.7.0-41 → 6.7.0-42

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.
@@ -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,
@@ -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
@@ -334,7 +369,10 @@ 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",
@@ -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()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/react-native-sni-connect",
3
- "version": "6.7.0-41",
3
+ "version": "6.7.0-42",
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",