@onekeyfe/react-native-sni-connect 6.7.0-5 → 6.7.0-50

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).
@@ -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,
@@ -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) {
@@ -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
@@ -301,7 +355,8 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
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,7 +369,10 @@ 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",
@@ -349,6 +407,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
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
  )
@@ -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>,
@@ -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")