@onekeyfe/react-native-sni-connect 6.8.0-2 → 6.8.0-20

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
@@ -16,8 +16,8 @@ Connects to a literal IP address you already resolved while preserving the real
16
16
  hostname's TLS SNI, `Host` header and certificate validation, so the certificate
17
17
  chain is checked against the hostname rather than the IP. Requests are text-only:
18
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
19
+ transport uses EMASCurl (libcurl) on iOS, OkHttp on Android, and Node HTTPS
20
+ in Electron's main process. Each connection uses HTTPS on port 443 and is
21
21
  pinned to a validated public destination.
22
22
 
23
23
  ## Features
@@ -95,36 +95,91 @@ await cancelRequest('health-check-1');
95
95
  HTTP `4xx` and `5xx` resolve as normal responses; inspect `status`. The caller
96
96
  owns the target IP, the request id lifecycle and higher-level retry policy.
97
97
 
98
+ ### Node/Desktop uploads
99
+
100
+ Import `SniNodeClient` from the `/node` entry and configure
101
+ `getAllowedUploadRoots` to return the directories where your app writes its
102
+ archives. With no usable roots, uploads reject with `SNI_INVALID_CONFIG`.
103
+
104
+ ```ts
105
+ import { join } from 'node:path';
106
+ import { app } from 'electron';
107
+ import { SniNodeClient } from '@onekeyfe/react-native-sni-connect/node';
108
+
109
+ const archiveRoot = join(app.getPath('userData'), 'log-archives');
110
+ const client = new SniNodeClient({
111
+ getAllowedUploadRoots: () => [archiveRoot],
112
+ });
113
+
114
+ async function uploadLogArchive(ip: string, fileName: string) {
115
+ return client.uploadFile({
116
+ ip, // Public IP resolved for wallet.onekeycn.com
117
+ hostname: 'wallet.onekeycn.com',
118
+ path: '/wallet/v1/client/log',
119
+ method: 'POST',
120
+ headers: { 'content-type': 'application/zip' },
121
+ filePath: join(archiveRoot, fileName),
122
+ timeout: 30_000,
123
+ });
124
+ }
125
+ ```
126
+
127
+ The defaults allow `POST` and `PUT` to `/wallet/v1/client/log` on
128
+ `https://wallet.onekeycn.com` and `https://wallet.onekeytest.com`. The resolved
129
+ file must be a readable `.zip` directly under a configured root, between
130
+ 1 byte and 20 MiB. Use `verifyUploadFile` for additional app-specific checks.
131
+
98
132
  ## API
99
133
 
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).
134
+ ### React Native
135
+
136
+ Import these functions and types from `@onekeyfe/react-native-sni-connect`.
137
+
138
+ | Export | Signature | Description |
139
+ | --- | --- | --- |
140
+ | `request` | `(config: SniConnectRequest) => Promise<SniConnectResponse>` | Sends an HTTPS request over the pinned SNI transport. |
141
+ | `uploadFile` | `(config: SniConnectUploadFileRequest) => Promise<SniConnectResponse>` | Sends a local file body (`POST` or `PUT`, 1 byte–20 MiB). |
142
+ | `isUploadFileSupported` | `() => boolean` | Reports whether the loaded native module exposes `uploadFile`. |
143
+ | `getUploadProgress` | `(requestId: string) => Promise<SniConnectUploadProgress \| null>` | Reads the active upload progress for an ID. |
144
+ | `getDebugSnapshot` | `(target: SniConnectDebugTarget) => Promise<SniConnectDebugSnapshot>` | Reads active and pending counters and request IDs for one pair. |
145
+
146
+ ### Node/Desktop
147
+
148
+ Import `SniNodeClient` and these types from
149
+ `@onekeyfe/react-native-sni-connect/node`. Call the methods on a client
150
+ instance. Use `body: null` for a GET or HEAD request.
151
+
152
+ | Method | Signature | Description |
153
+ | --- | --- | --- |
154
+ | `request` | `(config: SniNodeRequestConfig) => Promise<SniNodeResponse>` | Sends an HTTPS request over the pinned SNI transport. |
155
+ | `uploadFile` | `(config: SniNodeUploadFileConfig) => Promise<SniNodeResponse>` | Streams a file from a configured app directory. |
156
+ | `getUploadProgress` | `(requestId: string) => Promise<SniNodeUploadProgress \| null>` | Reads the active upload progress for an ID. |
157
+ | `getDebugSnapshot` | `(target: Pick<SniNodeRequestConfig, 'hostname' \| 'ip'>) => Promise<SniNodeDebugSnapshot>` | Reads active and pending request counters for one pair. |
158
+
159
+ ### Shared methods
160
+
161
+ | Method | Signature | Description |
162
+ | --- | --- | --- |
163
+ | `cancelRequest` | `(requestId: string) => Promise<{ success: boolean }>` | Cancels the active request with that ID. |
164
+ | `cancelAllRequests` | `() => Promise<{ success: boolean }>` | Cancels requests owned by the module or client instance. |
165
+ | `clearDNSCache` | `() => Promise<{ success: boolean }>` | Evicts cached pinned destinations, clients and idle connections. |
166
+ | `isProxyActiveForUrl` | `(url: string) => Promise<boolean>` | Reports whether the URL would use a proxy. |
167
+
168
+ Responses contain `data` (string), `status`, `statusText`, `headers` and
169
+ optional `multiValueHeaders`. Limits are 1 MiB for string bodies, 8 KiB for
170
+ path/query, 64 headers and 32 KiB total header bytes, and 10 MiB for responses.
116
171
 
117
172
  ## Platform support
118
173
 
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 | ✅ | — |
174
+ | Capability | iOS | Android | Node/Desktop | Web |
175
+ | --- | :-: | :-: | :-: | :-: |
176
+ | Pinned-IP request with hostname TLS | ✅ | ✅ | ✅ | — |
177
+ | String request body | ✅ | ✅ | ✅ | — |
178
+ | Binary file upload (`uploadFile`) | ✅ | ✅ | ✅ | — |
179
+ | Per-request and bulk cancellation | ✅ | ✅ | ✅ | — |
180
+ | Cache clear and debug snapshot | ✅ | ✅ | ✅ | — |
181
+ | Proxy preflight | ✅ | ✅ | Requires a session resolver | — |
182
+ | Repeated response headers (`multiValueHeaders`) | ⚠️ may collapse | ✅ | ✅ | — |
128
183
 
129
184
  ## Caveats
130
185
 
@@ -165,6 +165,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
165
165
  private class ManagedRequest(
166
166
  val call: Call,
167
167
  val settled: AtomicBoolean,
168
+ val uploadProgress: UploadProgress?,
168
169
  ) {
169
170
  lateinit var admissionTicket: SniConnectRequestAdmission.Ticket
170
171
  private val explicitlyCancelled = AtomicBoolean(false)
@@ -183,6 +184,20 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
183
184
  fun wasExplicitlyCancelled(): Boolean = explicitlyCancelled.get()
184
185
  }
185
186
 
187
+ private class UploadProgress {
188
+ private var bytesSent = 0L
189
+ private var totalBytes = 0L
190
+
191
+ @Synchronized
192
+ fun record(sent: Long, total: Long) {
193
+ totalBytes = total
194
+ bytesSent = maxOf(bytesSent, sent.coerceIn(0, total))
195
+ }
196
+
197
+ @Synchronized
198
+ fun snapshot(): Pair<Long, Long> = bytesSent to totalBytes
199
+ }
200
+
186
201
  // Cancellation ownership is per module, so cancelAllRequests only affects its RN runtime.
187
202
  private val activeCalls = ConcurrentHashMap<String, ManagedRequest>()
188
203
  private val allActiveCalls = Collections.newSetFromMap(
@@ -242,6 +257,20 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
242
257
  }
243
258
  }
244
259
 
260
+ @ReactMethod
261
+ override fun getUploadProgress(requestId: String, promise: Promise) {
262
+ val progress = synchronized(activeCallsLock) {
263
+ activeCalls[requestId]?.takeUnless { it.settled.get() }?.uploadProgress
264
+ }
265
+ val snapshot = progress?.snapshot()
266
+ promise.resolve(snapshot?.let { (sent, total) ->
267
+ Arguments.createMap().apply {
268
+ putDouble("bytesSent", sent.toDouble())
269
+ putDouble("totalBytes", total.toDouble())
270
+ }
271
+ })
272
+ }
273
+
245
274
  @ReactMethod
246
275
  override fun cancelRequest(requestId: String, promise: Promise) {
247
276
  val request = synchronized(activeCallsLock) {
@@ -337,10 +366,15 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
337
366
  // Shared by every OkHttp attempt of this logical request. The client's
338
367
  // EventListener marks it once any attempt starts sending request headers.
339
368
  val requestTransmission = SniRequestTransmissionState()
369
+ val uploadProgress = if (config.bodyFile != null && config.requestId != null) {
370
+ UploadProgress()
371
+ } else {
372
+ null
373
+ }
340
374
  var registeredRequest: ManagedRequest? = null
341
375
  try {
342
376
  val client = getOrCreateClient(config)
343
- val request = buildRequest(config, requestTransmission)
377
+ val request = buildRequest(config, requestTransmission, uploadProgress)
344
378
  val call = client.newCall(request)
345
379
  val settled = AtomicBoolean(false)
346
380
  lateinit var managedRequest: ManagedRequest
@@ -493,7 +527,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
493
527
  }
494
528
  },
495
529
  )
496
- managedRequest = ManagedRequest(call, settled).apply {
530
+ managedRequest = ManagedRequest(call, settled, uploadProgress).apply {
497
531
  this.admissionTicket = admissionTicket
498
532
  }
499
533
  registerRequest(config.requestId, managedRequest)
@@ -632,6 +666,7 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
632
666
  private fun buildRequest(
633
667
  config: RequestConfig,
634
668
  requestTransmission: SniRequestTransmissionState,
669
+ uploadProgress: UploadProgress?,
635
670
  ): Request {
636
671
  val url = "https://${config.hostname}${config.path}"
637
672
  val builder = Request.Builder().url(url)
@@ -651,7 +686,11 @@ class SniConnectModule(reactContext: ReactApplicationContext) :
651
686
  ?.value
652
687
  ?.toMediaTypeOrNull()
653
688
  // Enforce the body bound when OkHttp consumes the file, after admission.
654
- val requestBody = config.bodyFile?.let { SniUploadFileRequestBody(it, mediaType) }
689
+ val requestBody = config.bodyFile?.let {
690
+ SniUploadFileRequestBody(it, mediaType) { sent, total ->
691
+ uploadProgress?.record(sent, total)
692
+ }.also { body -> uploadProgress?.record(0, body.contentLength()) }
693
+ }
655
694
  ?: config.body?.toRequestBody(mediaType)
656
695
 
657
696
  when (method) {
@@ -113,6 +113,7 @@ internal object SniRequestTransmissionEventListenerFactory : EventListener.Facto
113
113
  internal class SniUploadFileRequestBody(
114
114
  private val file: File,
115
115
  private val mediaType: MediaType?,
116
+ private val onProgress: ((Long, Long) -> Unit)? = null,
116
117
  ) : RequestBody() {
117
118
  private val length = file.length().also {
118
119
  if (it <= 0 || it > SniConnectValidation.MAX_UPLOAD_FILE_BYTES) {
@@ -125,6 +126,7 @@ internal class SniUploadFileRequestBody(
125
126
  override fun contentLength(): Long = length
126
127
 
127
128
  override fun writeTo(sink: BufferedSink) {
129
+ onProgress?.invoke(0, length)
128
130
  file.source().use { source ->
129
131
  val buffer = Buffer()
130
132
  var totalBytes = 0L
@@ -137,6 +139,7 @@ internal class SniUploadFileRequestBody(
137
139
  }
138
140
  sink.write(buffer, read)
139
141
  totalBytes += read
142
+ onProgress?.invoke(totalBytes, length)
140
143
  }
141
144
  if (totalBytes != length) {
142
145
  throw IOException("Upload file was truncated during transmission")
@@ -99,6 +99,21 @@ class SniConnectValidationTest {
99
99
  assertTrue(expected.contentEquals(sink.readByteArray()))
100
100
  }
101
101
 
102
+ @Test
103
+ fun uploadBodyReportsOnlyAcceptedPayloadBytesPerWrite() {
104
+ val file = tempFolder.newFile("progress.zip").apply { writeBytes(ByteArray(16 * 1024) { 1 }) }
105
+ val progress = mutableListOf<Pair<Long, Long>>()
106
+ val body = SniUploadFileRequestBody(file, null) { sent, total ->
107
+ progress.add(sent to total)
108
+ }
109
+ val sink = Buffer()
110
+ body.writeTo(sink)
111
+ assertEquals(0L to file.length(), progress.first())
112
+ assertEquals(file.length() to file.length(), progress.last())
113
+ assertTrue(progress.zipWithNext().all { (before, after) -> after.first >= before.first })
114
+ assertEquals(file.length(), sink.size)
115
+ }
116
+
102
117
  @Test
103
118
  fun uploadBodyRejectsGrowthAfterValidation() {
104
119
  val root = tempFolder.newFolder("sandbox")
package/ios/SniConnect.mm CHANGED
@@ -16,6 +16,9 @@
16
16
  - (void)uploadFile:(NSDictionary *)config
17
17
  resolve:(RCTPromiseResolveBlock)resolve
18
18
  reject:(RCTPromiseRejectBlock)reject;
19
+ - (void)getUploadProgress:(NSString *)requestId
20
+ resolve:(RCTPromiseResolveBlock)resolve
21
+ reject:(RCTPromiseRejectBlock)reject;
19
22
  - (void)cancelRequest:(NSString *)requestId
20
23
  resolve:(RCTPromiseResolveBlock)resolve
21
24
  reject:(RCTPromiseRejectBlock)reject;
@@ -103,6 +106,12 @@ RCT_EXPORT_MODULE(SniConnect)
103
106
  [_implementation uploadFile:configDict resolve:resolve reject:reject];
104
107
  }
105
108
 
109
+ - (void)getUploadProgress:(NSString *)requestId
110
+ resolve:(RCTPromiseResolveBlock)resolve
111
+ reject:(RCTPromiseRejectBlock)reject {
112
+ [_implementation getUploadProgress:requestId resolve:resolve reject:reject];
113
+ }
114
+
106
115
  - (void)cancelRequest:(NSString *)requestId
107
116
  resolve:(RCTPromiseResolveBlock)resolve
108
117
  reject:(RCTPromiseRejectBlock)reject {
@@ -154,6 +163,12 @@ RCT_EXPORT_METHOD(uploadFile:(NSDictionary *)config
154
163
  [_implementation uploadFile:config resolve:resolve reject:reject];
155
164
  }
156
165
 
166
+ RCT_EXPORT_METHOD(getUploadProgress:(NSString *)requestId
167
+ resolver:(RCTPromiseResolveBlock)resolve
168
+ rejecter:(RCTPromiseRejectBlock)reject) {
169
+ [_implementation getUploadProgress:requestId resolve:resolve reject:reject];
170
+ }
171
+
157
172
  RCT_EXPORT_METHOD(cancelRequest:(NSString *)requestId
158
173
  resolver:(RCTPromiseResolveBlock)resolve
159
174
  rejecter:(RCTPromiseRejectBlock)reject) {
@@ -61,11 +61,29 @@ final class SniConnectImpl: NSObject {
61
61
  }
62
62
  }
63
63
 
64
+ @objc
65
+ public func getUploadProgress(
66
+ _ requestId: String,
67
+ resolve: @escaping RCTPromiseResolveBlock,
68
+ reject: @escaping RCTPromiseRejectBlock
69
+ ) {
70
+ if let progress = client.getUploadProgress(requestId: requestId) {
71
+ resolve(progress)
72
+ } else {
73
+ resolve(NSNull())
74
+ }
75
+ }
76
+
64
77
  private func handleRequest(
65
- config: SniConnectClient.RequestConfig,
78
+ config originalConfig: SniConnectClient.RequestConfig,
66
79
  resolve: @escaping RCTPromiseResolveBlock,
67
80
  reject: @escaping RCTPromiseRejectBlock
68
81
  ) {
82
+ var configured = originalConfig
83
+ if configured.bodyFileURL != nil && configured.requestId != nil {
84
+ configured.uploadProgress = SniConnectUploadProgress()
85
+ }
86
+ let config = configured
69
87
  do {
70
88
  try Self.validate(config)
71
89
  } catch {
@@ -92,7 +110,11 @@ final class SniConnectImpl: NSObject {
92
110
  return try await client.performRequest(config: config)
93
111
  }
94
112
 
95
- let registrationToken = client.registerTask(task, for: config.requestId)
113
+ let registrationToken = client.registerTask(
114
+ task,
115
+ for: config.requestId,
116
+ uploadProgress: config.uploadProgress
117
+ )
96
118
 
97
119
  // Handle the task result asynchronously
98
120
  Task {
@@ -102,6 +124,7 @@ final class SniConnectImpl: NSObject {
102
124
 
103
125
  do {
104
126
  let result = try await task.value
127
+ client.finishUploadProgress(token: registrationToken)
105
128
  resolve([
106
129
  "data": result.data,
107
130
  "status": result.status,
@@ -110,10 +133,13 @@ final class SniConnectImpl: NSObject {
110
133
  "multiValueHeaders": result.multiValueHeaders,
111
134
  ])
112
135
  } catch let error as SniConnectClient.SniConnectError {
136
+ client.finishUploadProgress(token: registrationToken)
113
137
  reject(error.code, error.message, error)
114
138
  } catch is CancellationError {
139
+ client.finishUploadProgress(token: registrationToken)
115
140
  reject("SNI_CANCELLED", "Request cancelled", nil)
116
141
  } catch {
142
+ client.finishUploadProgress(token: registrationToken)
117
143
  SniConnectLog.error(SniConnectLog.event("sni_request_result", [
118
144
  ("result", "error"),
119
145
  ("code", "SNI_UNKNOWN_ERROR"),
@@ -186,6 +186,7 @@ final class SniConnectClient {
186
186
  // token so cancelAllRequests() also covers requests that do not have a requestId.
187
187
  private var activeTasksByToken: [UUID: Task<Response, Error>] = [:]
188
188
  private var requestTokensById: [String: UUID] = [:]
189
+ private var uploadProgressByToken: [UUID: SniConnectUploadProgress] = [:]
189
190
  private var invalidated = false
190
191
  private let tasksQueue = DispatchQueue(label: "com.onekey.sni.connect.tasks", attributes: .concurrent)
191
192
  private let requestLimiter = SniConnectRequestLimiter.shared
@@ -261,6 +262,7 @@ final class SniConnectClient {
261
262
  let timeout: TimeInterval
262
263
  // Set only by uploadFile(); already resolved inside the app sandbox.
263
264
  var bodyFileURL: URL? = nil
265
+ var uploadProgress: SniConnectUploadProgress? = nil
264
266
 
265
267
  // Advanced timeout configurations
266
268
  let connectTimeout: TimeInterval? // Connection establishment timeout
@@ -586,6 +588,7 @@ final class SniConnectClient {
586
588
  ]))
587
589
  return false
588
590
  }
591
+ self.uploadProgressByToken.removeValue(forKey: token)
589
592
  task.cancel()
590
593
  SniConnectLog.info(SniConnectLog.event("sni_cancel", [
591
594
  ("requestId", requestId),
@@ -617,6 +620,7 @@ final class SniConnectClient {
617
620
  }
618
621
  self.activeTasksByToken.removeAll()
619
622
  self.requestTokensById.removeAll()
623
+ self.uploadProgressByToken.removeAll()
620
624
  SniConnectLog.info(SniConnectLog.event(logAction, [
621
625
  ("cancelledCount", tasks.count),
622
626
  ("success", true),
@@ -625,7 +629,11 @@ final class SniConnectClient {
625
629
  }
626
630
 
627
631
  /// Register an active task immediately after creation, before JS can cancel it.
628
- func registerTask(_ task: Task<Response, Error>, for requestId: String?) -> UUID {
632
+ func registerTask(
633
+ _ task: Task<Response, Error>,
634
+ for requestId: String?,
635
+ uploadProgress: SniConnectUploadProgress? = nil
636
+ ) -> UUID {
629
637
  let token = UUID()
630
638
  var shouldCancel = false
631
639
  tasksQueue.sync(flags: .barrier) { [weak self] in
@@ -636,6 +644,7 @@ final class SniConnectClient {
636
644
  }
637
645
  if let requestId = requestId, let previousToken = self.requestTokensById[requestId],
638
646
  let previousTask = self.activeTasksByToken.removeValue(forKey: previousToken) {
647
+ self.uploadProgressByToken.removeValue(forKey: previousToken)
639
648
  previousTask.cancel()
640
649
  SniConnectLog.warn(SniConnectLog.event("sni_duplicate_request_id", [
641
650
  ("requestId", requestId),
@@ -643,6 +652,9 @@ final class SniConnectClient {
643
652
  ]))
644
653
  }
645
654
  self.activeTasksByToken[token] = task
655
+ if let uploadProgress = uploadProgress {
656
+ self.uploadProgressByToken[token] = uploadProgress
657
+ }
646
658
  if let requestId = requestId {
647
659
  self.requestTokensById[requestId] = token
648
660
  }
@@ -655,14 +667,31 @@ final class SniConnectClient {
655
667
 
656
668
  /// Unregister a completed or failed task
657
669
  func unregisterTask(requestId: String?, token: UUID) {
658
- tasksQueue.async(flags: .barrier) { [weak self] in
670
+ tasksQueue.sync(flags: .barrier) { [weak self] in
659
671
  self?.activeTasksByToken.removeValue(forKey: token)
672
+ self?.uploadProgressByToken.removeValue(forKey: token)
660
673
  if let requestId = requestId, self?.requestTokensById[requestId] == token {
661
674
  self?.requestTokensById.removeValue(forKey: requestId)
662
675
  }
663
676
  }
664
677
  }
665
678
 
679
+ func getUploadProgress(requestId: String) -> [String: Int64]? {
680
+ return tasksQueue.sync { () -> [String: Int64]? in
681
+ guard let token = requestTokensById[requestId],
682
+ let progress = uploadProgressByToken[token] else {
683
+ return nil
684
+ }
685
+ return progress.snapshot()
686
+ }
687
+ }
688
+
689
+ func finishUploadProgress(token: UUID) {
690
+ _ = tasksQueue.sync(flags: .barrier) {
691
+ uploadProgressByToken.removeValue(forKey: token)
692
+ }
693
+ }
694
+
666
695
  func performRequest(config: RequestConfig) async throws -> Response {
667
696
  let startedAt = Date()
668
697
  // Check if task is cancelled
@@ -783,6 +812,7 @@ final class SniConnectClient {
783
812
  }
784
813
  mutableRequest.httpBody = fileData
785
814
  bodyBytes = fileData.count
815
+ config.uploadProgress?.setTotal(fileData.count)
786
816
  } else if let bodyString = config.body, let bodyData = bodyString.data(using: .utf8) {
787
817
  mutableRequest.httpBody = bodyData
788
818
  bodyBytes = bodyData.count
@@ -790,6 +820,11 @@ final class SniConnectClient {
790
820
 
791
821
  // Per-request connect timeout (avoids the process-global setter race).
792
822
  EMASCurlProtocol.setConnectTimeoutIntervalFor(mutableRequest, connectTimeoutInterval: connectTimeoutSeconds)
823
+ if let uploadProgress = config.uploadProgress {
824
+ EMASCurlProtocol.setUploadProgressUpdateBlockFor(mutableRequest) { _, _, totalBytesSent, _ in
825
+ uploadProgress.record(totalBytesSent)
826
+ }
827
+ }
793
828
  let request = mutableRequest as URLRequest
794
829
 
795
830
  SniConnectLog.info(SniConnectLog.event("sni_request_start", [
@@ -1,5 +1,29 @@
1
1
  import Foundation
2
2
 
3
+ final class SniConnectUploadProgress {
4
+ private let lock = NSLock()
5
+ private var sent: Int64 = 0
6
+ private var total: Int64 = 0
7
+
8
+ func setTotal(_ bytes: Int) {
9
+ lock.lock()
10
+ total = Int64(bytes)
11
+ lock.unlock()
12
+ }
13
+
14
+ func record(_ bytes: Int64) {
15
+ lock.lock()
16
+ sent = max(sent, min(max(bytes, 0), total))
17
+ lock.unlock()
18
+ }
19
+
20
+ func snapshot() -> [String: Int64] {
21
+ lock.lock()
22
+ defer { lock.unlock() }
23
+ return ["bytesSent": sent, "totalBytes": total]
24
+ }
25
+ }
26
+
3
27
  enum SniConnectSessionDelegatePolicy {
4
28
  static let responseDispositionWithoutForwardingDelegate: URLSession.ResponseDisposition = .allow
5
29
  }
@@ -3,6 +3,17 @@ import XCTest
3
3
 
4
4
  final class SniConnectValidationTests: XCTestCase {
5
5
 
6
+ func testUploadProgressKeepsMonotonicCountWithinBodyLength() {
7
+ let progress = SniConnectUploadProgress()
8
+ XCTAssertEqual(progress.snapshot(), ["bytesSent": 0, "totalBytes": 0])
9
+ progress.setTotal(10)
10
+ progress.record(4)
11
+ progress.record(1) // Delayed or lower transport callbacks cannot move it backward.
12
+ XCTAssertEqual(progress.snapshot(), ["bytesSent": 4, "totalBytes": 10])
13
+ progress.record(20)
14
+ XCTAssertEqual(progress.snapshot(), ["bytesSent": 10, "totalBytes": 10])
15
+ }
16
+
6
17
  func testUnexpectedResolverHostIsLoggedInPlaintextAndStillRejected() throws {
7
18
  let registry = SniConnectPinnedResolverRegistry()
8
19
  let resolverClass: AnyClass = try registry.resolverClass(hostname: "example.com", ip: "93.184.216.34") {
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ //# sourceMappingURL=react-native-codegen.d.js.map
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _reactNative = require("react-native");
8
+ /**
9
+ * Sends the raw bytes of an app-sandbox file as the request body over the same
10
+ * pinned-IP/SNI transport as `request()`. Set `content-type` in `headers`.
11
+ */
12
+
13
+ const LINKING_ERROR = `The package '@onekeyfe/react-native-sni-connect' doesn't seem to be linked. Make sure:\n\n` + _reactNative.Platform.select({
14
+ ios: "- You have run 'pod install'\n",
15
+ default: ''
16
+ }) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo Go; create a custom dev client instead\n';
17
+ const turboModuleResult = _reactNative.TurboModuleRegistry.get('SniConnect');
18
+ const turboModule = turboModuleResult ?? null;
19
+ const bridgeModule = _reactNative.NativeModules.SniConnect ?? null;
20
+ const nativeModule = turboModule ?? bridgeModule;
21
+ if (nativeModule == null) {
22
+ throw new Error(LINKING_ERROR);
23
+ }
24
+ const NativeSniConnect = nativeModule;
25
+ var _default = exports.default = NativeSniConnect;
26
+ //# sourceMappingURL=NativeSniConnect.js.map
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.cancelAllRequests = cancelAllRequests;
7
+ exports.cancelRequest = cancelRequest;
8
+ exports.clearDNSCache = clearDNSCache;
9
+ exports.getDebugSnapshot = getDebugSnapshot;
10
+ exports.getUploadProgress = getUploadProgress;
11
+ exports.isProxyActiveForUrl = isProxyActiveForUrl;
12
+ exports.isUploadFileSupported = isUploadFileSupported;
13
+ exports.request = request;
14
+ exports.uploadFile = uploadFile;
15
+ var _NativeSniConnect = _interopRequireDefault(require("./NativeSniConnect.js"));
16
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
17
+ function request(config) {
18
+ return _NativeSniConnect.default.request(config);
19
+ }
20
+ function isUploadFileSupported() {
21
+ return typeof _NativeSniConnect.default.uploadFile === 'function';
22
+ }
23
+ async function uploadFile(config) {
24
+ if (!isUploadFileSupported()) {
25
+ throw Object.assign(new Error('Native SNI file upload is not supported'), {
26
+ code: 'SNI_UNSUPPORTED'
27
+ });
28
+ }
29
+ return _NativeSniConnect.default.uploadFile(config);
30
+ }
31
+ function getUploadProgress(requestId) {
32
+ return _NativeSniConnect.default.getUploadProgress(requestId);
33
+ }
34
+ function cancelRequest(requestId) {
35
+ return _NativeSniConnect.default.cancelRequest(requestId);
36
+ }
37
+ function cancelAllRequests() {
38
+ return _NativeSniConnect.default.cancelAllRequests();
39
+ }
40
+ function clearDNSCache() {
41
+ return _NativeSniConnect.default.clearDNSCache();
42
+ }
43
+ function getDebugSnapshot(target) {
44
+ return _NativeSniConnect.default.getDebugSnapshot(target);
45
+ }
46
+ function isProxyActiveForUrl(url) {
47
+ return _NativeSniConnect.default.isProxyActiveForUrl(url);
48
+ }
49
+ //# sourceMappingURL=index.js.map