react-native-nitro-sse 3.0.0-beta.1 → 3.0.0
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 +43 -23
- package/android/build.gradle +4 -1
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +110 -64
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +32 -23
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +3 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +29 -2
- package/ios/NitroSse.swift +53 -17
- package/ios/SseConfig+CopyWith.swift +35 -19
- package/lib/module/MockSseEngine.js +0 -5
- package/lib/module/NitroSseClient.js +55 -7
- package/lib/module/createNitroSse.js +24 -0
- package/lib/module/index.js +1 -22
- package/lib/module/useNitroSse.js +22 -5
- package/lib/typescript/src/NitroSse.nitro.d.ts +2 -2
- package/lib/typescript/src/NitroSseClient.d.ts +7 -3
- package/lib/typescript/src/SseInterface.d.ts +14 -7
- package/lib/typescript/src/createNitroSse.d.ts +9 -0
- package/lib/typescript/src/index.d.ts +1 -8
- package/lib/typescript/src/useNitroSse.d.ts +2 -2
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +8 -8
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -18
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +4 -3
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +4 -13
- package/nitrogen/generated/android/nitrosseOnLoad.cpp +2 -2
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +8 -8
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +104 -104
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +4 -4
- package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -1
- package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +34 -1
- package/nitrogen/generated/ios/swift/SseConfig.swift +1 -48
- package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +3 -1
- package/nitrogen/generated/shared/c++/SseConfig.hpp +2 -8
- package/package.json +1 -1
|
@@ -7,13 +7,14 @@ import android.net.NetworkCapabilities
|
|
|
7
7
|
import android.net.NetworkRequest
|
|
8
8
|
import android.util.Log
|
|
9
9
|
|
|
10
|
-
typealias NetworkChangeHandler = (isAvailable: Boolean, capabilities: NetworkCapabilities?) -> Unit
|
|
10
|
+
typealias NetworkChangeHandler = (isAvailable: Boolean, interfaceChanged: Boolean, capabilities: NetworkCapabilities?) -> Unit
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Monitors system connectivity changes using Android's [ConnectivityManager].
|
|
14
14
|
*
|
|
15
15
|
* Emits network availability and capability updates to enable automatic stream reconnection
|
|
16
16
|
* upon network restoration or interface handovers (e.g. Wi-Fi to cellular transition).
|
|
17
|
+
* Initial network detection is captured internally without flagging a false interface change.
|
|
17
18
|
*/
|
|
18
19
|
class SseNetworkMonitor(
|
|
19
20
|
private val context: Context,
|
|
@@ -22,6 +23,7 @@ class SseNetworkMonitor(
|
|
|
22
23
|
) {
|
|
23
24
|
private val lock = Any()
|
|
24
25
|
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
|
26
|
+
private var lastCapabilities: NetworkCapabilities? = null
|
|
25
27
|
|
|
26
28
|
companion object {
|
|
27
29
|
private const val TAG = "SseNetworkMonitor"
|
|
@@ -39,7 +41,31 @@ class SseNetworkMonitor(
|
|
|
39
41
|
|
|
40
42
|
val callback = object : ConnectivityManager.NetworkCallback() {
|
|
41
43
|
private fun dispatchChange(isAvailable: Boolean, capabilities: NetworkCapabilities?) {
|
|
42
|
-
|
|
44
|
+
val interfaceChanged: Boolean
|
|
45
|
+
if (isAvailable && capabilities != null) {
|
|
46
|
+
val prev = lastCapabilities
|
|
47
|
+
if (prev != null) {
|
|
48
|
+
val isWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|
|
49
|
+
val isCellular = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
|
|
50
|
+
val lastWifi = prev.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|
|
51
|
+
val lastCellular = prev.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
|
|
52
|
+
interfaceChanged = (isWifi && !lastWifi) || (isCellular && !lastCellular)
|
|
53
|
+
} else {
|
|
54
|
+
interfaceChanged = false
|
|
55
|
+
}
|
|
56
|
+
lastCapabilities = capabilities
|
|
57
|
+
} else {
|
|
58
|
+
interfaceChanged = false
|
|
59
|
+
if (!isAvailable) {
|
|
60
|
+
lastCapabilities = null
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (dispatcher == null || dispatcher.isCurrentDispatcher()) {
|
|
65
|
+
onChange(isAvailable, interfaceChanged, capabilities)
|
|
66
|
+
} else {
|
|
67
|
+
dispatcher.post { onChange(isAvailable, interfaceChanged, capabilities) }
|
|
68
|
+
}
|
|
43
69
|
}
|
|
44
70
|
|
|
45
71
|
override fun onAvailable(network: Network) {
|
|
@@ -77,6 +103,7 @@ class SseNetworkMonitor(
|
|
|
77
103
|
|
|
78
104
|
fun stop() {
|
|
79
105
|
synchronized(lock) {
|
|
106
|
+
lastCapabilities = null
|
|
80
107
|
val callback = networkCallback ?: return
|
|
81
108
|
try {
|
|
82
109
|
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
package/ios/NitroSse.swift
CHANGED
|
@@ -32,7 +32,11 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
32
32
|
|
|
33
33
|
private var eventSource: EventSource?
|
|
34
34
|
private var config: SseConfig?
|
|
35
|
+
/// Dynamic request interceptor decoupled from SseConfig (v3.0) to prevent JSI closure re-wrapping and retain leaks.
|
|
36
|
+
private var requestInterceptor: (() -> Promise<Promise<Dictionary<String, String>>>)?
|
|
35
37
|
private var isRunning: Bool = false
|
|
38
|
+
private var isDisposed: Bool = false
|
|
39
|
+
/// Indicates whether the JS Dispatcher/CallInvoker has been destroyed to prevent invoking dead callbacks.
|
|
36
40
|
private var isDispatcherDestroyed: Bool = false
|
|
37
41
|
internal var connectionAttemptVersion: Int = 0
|
|
38
42
|
private var requestId: String? = nil
|
|
@@ -67,19 +71,28 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
67
71
|
/// Synchronously cleans up all active network sockets, timers, and lifecycle observers.
|
|
68
72
|
func dispose() {
|
|
69
73
|
let cleanup = {
|
|
74
|
+
// Note: Thread safety on isDisposed is guaranteed without atomics because cleanup is serialized
|
|
75
|
+
// on the underlying serial DispatchQueue (`dispatcher.sync`), acting as a mutex.
|
|
76
|
+
guard !self.isDisposed else { return }
|
|
77
|
+
self.isDisposed = true
|
|
70
78
|
self.stopInternal(emitClosed: false)
|
|
79
|
+
self.requestInterceptor = nil
|
|
80
|
+
self.config = nil
|
|
81
|
+
self.currentInterceptorToken?.isCancelled = true
|
|
82
|
+
self.currentInterceptorToken = nil
|
|
71
83
|
self.eventBuffer.clearCallback()
|
|
72
84
|
self.eventBuffer.clear()
|
|
73
85
|
self.networkMonitor?.stop()
|
|
74
86
|
self.networkMonitor = nil
|
|
87
|
+
// Serialized on dispatcher to prevent race conditions with background execution
|
|
88
|
+
self.lifecycleManager?.stopObserving()
|
|
89
|
+
self.lifecycleManager = nil
|
|
75
90
|
}
|
|
76
91
|
if dispatcher.isCurrentDispatcher() {
|
|
77
92
|
cleanup()
|
|
78
93
|
} else {
|
|
79
94
|
dispatcher.sync(cleanup)
|
|
80
95
|
}
|
|
81
|
-
lifecycleManager?.stopObserving()
|
|
82
|
-
lifecycleManager = nil
|
|
83
96
|
}
|
|
84
97
|
|
|
85
98
|
deinit {
|
|
@@ -90,9 +103,16 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
90
103
|
// MARK: - HybridNitroSseSpec
|
|
91
104
|
|
|
92
105
|
/// Configures the SSE client parameters, event buffer, backoff strategy, and lifecycle observers.
|
|
93
|
-
|
|
106
|
+
/// In v3.0, `onBeforeRequest` is decoupled from `SseConfig` to keep `SseConfig` as a pure data struct,
|
|
107
|
+
/// preventing closure re-wrapping and retain leaks across `copyWith` calls.
|
|
108
|
+
func setup(
|
|
109
|
+
config: SseConfig,
|
|
110
|
+
onEvent: @escaping ((_ events: [SseEvent]) -> Void),
|
|
111
|
+
onBeforeRequest: (() -> Promise<Promise<Dictionary<String, String>>>)? = nil
|
|
112
|
+
) throws {
|
|
94
113
|
dispatcher.async {
|
|
95
114
|
self.config = config
|
|
115
|
+
self.requestInterceptor = onBeforeRequest
|
|
96
116
|
|
|
97
117
|
self.eventBuffer.configure(
|
|
98
118
|
batchingIntervalMs: config.batchingIntervalMs ?? 0,
|
|
@@ -184,6 +204,9 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
184
204
|
print("[NitroSse] start() invoked while reconnecting. Resetting backoff and retrying immediately.")
|
|
185
205
|
self.reconnectStrategy.reset()
|
|
186
206
|
self.consecutiveAuthErrors = 0
|
|
207
|
+
// Note: Incrementing connectionAttemptVersion invalidates in-flight callbacks from the prior attempt.
|
|
208
|
+
// `establishConnection` will cancel `currentInterceptorToken`. If an older JS interceptor Promise is still
|
|
209
|
+
// running in JS runtime, its eventual completion will be dropped when comparing versions.
|
|
187
210
|
self.connectionAttemptVersion += 1
|
|
188
211
|
self.updateState(.connecting)
|
|
189
212
|
self.establishConnection(attemptVersion: self.connectionAttemptVersion)
|
|
@@ -215,10 +238,15 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
215
238
|
|
|
216
239
|
/// Stops active network streaming and invalidates pending reconnection timers by incrementing attempt version.
|
|
217
240
|
func stop() {
|
|
218
|
-
|
|
241
|
+
let task = {
|
|
219
242
|
self.connectionAttemptVersion += 1
|
|
220
243
|
self.stopInternal()
|
|
221
244
|
}
|
|
245
|
+
if dispatcher.isCurrentDispatcher() {
|
|
246
|
+
task()
|
|
247
|
+
} else {
|
|
248
|
+
dispatcher.async(task)
|
|
249
|
+
}
|
|
222
250
|
}
|
|
223
251
|
|
|
224
252
|
/// Immediately flushes all buffered events to JavaScript via the bridge callback.
|
|
@@ -230,7 +258,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
230
258
|
|
|
231
259
|
/// Teardown existing connection and initiate a new request attempt.
|
|
232
260
|
func restart() {
|
|
233
|
-
|
|
261
|
+
let task = {
|
|
234
262
|
guard self.config != nil else { return }
|
|
235
263
|
self.stopInternal(emitClosed: false)
|
|
236
264
|
self.isRunning = true
|
|
@@ -239,6 +267,11 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
239
267
|
self.updateState(.reconnecting)
|
|
240
268
|
self.establishConnection(attemptVersion: self.connectionAttemptVersion)
|
|
241
269
|
}
|
|
270
|
+
if dispatcher.isCurrentDispatcher() {
|
|
271
|
+
task()
|
|
272
|
+
} else {
|
|
273
|
+
dispatcher.async(task)
|
|
274
|
+
}
|
|
242
275
|
}
|
|
243
276
|
|
|
244
277
|
/// Indicates whether the client is currently running or reconnecting.
|
|
@@ -370,7 +403,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
370
403
|
dispatcher.assertOnQueue()
|
|
371
404
|
guard isRunning, let config = config, attemptVersion == self.connectionAttemptVersion else { return }
|
|
372
405
|
|
|
373
|
-
if let interceptor =
|
|
406
|
+
if let interceptor = self.requestInterceptor {
|
|
374
407
|
self.currentInterceptorToken?.isCancelled = true
|
|
375
408
|
let token = InterceptorCancellationToken()
|
|
376
409
|
self.currentInterceptorToken = token
|
|
@@ -414,19 +447,19 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
414
447
|
if !flag.isCompleted {
|
|
415
448
|
flag.isCompleted = true
|
|
416
449
|
token.isCancelled = true
|
|
417
|
-
let
|
|
418
|
-
var mergedHeaders =
|
|
450
|
+
let baseConfig = self.config ?? capturedConfig
|
|
451
|
+
var mergedHeaders = baseConfig.headers ?? [:]
|
|
419
452
|
for (k, v) in newHeaders {
|
|
420
453
|
mergedHeaders[k] = v
|
|
421
454
|
}
|
|
422
|
-
|
|
423
|
-
self.performEstablishConnection(attemptVersion: attemptVersion)
|
|
455
|
+
let connectionConfig = baseConfig.copyWith(headers: mergedHeaders)
|
|
456
|
+
self.performEstablishConnection(attemptVersion: attemptVersion, connectionConfig: connectionConfig)
|
|
424
457
|
}
|
|
425
458
|
}
|
|
426
459
|
}.catch(safeHandleError)
|
|
427
460
|
}.catch(safeHandleError)
|
|
428
461
|
} else {
|
|
429
|
-
self.performEstablishConnection(attemptVersion: attemptVersion)
|
|
462
|
+
self.performEstablishConnection(attemptVersion: attemptVersion, connectionConfig: nil)
|
|
430
463
|
}
|
|
431
464
|
}
|
|
432
465
|
|
|
@@ -437,18 +470,19 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
437
470
|
// react-native-nitro-modules throws a generic std::runtime_error from C++ when the Dispatcher is destroyed.
|
|
438
471
|
// Message inspection is required as no specialized exception type is surfaced to Swift.
|
|
439
472
|
if desc.contains("Dispatcher has already been destroyed") {
|
|
440
|
-
print("[NitroSse] JS Dispatcher destroyed.
|
|
473
|
+
print("[NitroSse] JS Dispatcher destroyed. Disposing NitroSse instance.")
|
|
441
474
|
self.isDispatcherDestroyed = true
|
|
442
|
-
self.
|
|
475
|
+
self.dispose()
|
|
443
476
|
return
|
|
444
477
|
}
|
|
445
478
|
self.eventBuffer.push(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Interceptor Error: \(error.localizedDescription)", statusCode: -1, retry: nil, state: nil))
|
|
446
479
|
self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
|
|
447
480
|
}
|
|
448
481
|
|
|
449
|
-
private func performEstablishConnection(attemptVersion: Int) {
|
|
482
|
+
private func performEstablishConnection(attemptVersion: Int, connectionConfig: SseConfig? = nil) {
|
|
450
483
|
dispatcher.assertOnQueue()
|
|
451
|
-
|
|
484
|
+
let activeConfig = connectionConfig ?? self.config
|
|
485
|
+
guard isRunning, let config = activeConfig, attemptVersion == self.connectionAttemptVersion else { return }
|
|
452
486
|
guard let url = URL(string: config.url), let scheme = url.scheme, ["http", "https"].contains(scheme.lowercased()) else {
|
|
453
487
|
print("[NitroSse] Invalid SSE URL: \(config.url)")
|
|
454
488
|
self.failAndStop(message: "Invalid URL: \(config.url)", statusCode: -1)
|
|
@@ -555,6 +589,8 @@ extension NitroSse: SseConnectionDelegate {
|
|
|
555
589
|
self.consecutiveAuthErrors = 0
|
|
556
590
|
self.updateState(.open)
|
|
557
591
|
|
|
592
|
+
// Note: WHATWG SSE spec does not expose HTTP response headers to client JS event listeners (`open` event only carries statusCode).
|
|
593
|
+
// LDSwiftEventSource does not expose HTTPURLResponse to `EventHandler.onOpened()`, so headers are reported empty to DevTools Inspector.
|
|
558
594
|
NitroSseNetworkInspector.reportResponseStart(
|
|
559
595
|
self.requestId,
|
|
560
596
|
url: self.config?.url,
|
|
@@ -633,13 +669,13 @@ extension NitroSse: SseConnectionDelegate {
|
|
|
633
669
|
// HTTP 401/403 Auth errors trigger token refresh via onBeforeRequest interceptor up to maxAuthRetries.
|
|
634
670
|
let limit = Int(self.config?.maxAuthRetries ?? Double(Self.defaultMaxAuthRetries))
|
|
635
671
|
if statusCode == 401 || statusCode == 403 {
|
|
636
|
-
if self.
|
|
672
|
+
if self.requestInterceptor == nil {
|
|
637
673
|
self.failAndStop(message: "Auth Error (\(statusCode)) - No interceptor provided. Stopping.", statusCode: Double(statusCode))
|
|
638
674
|
return
|
|
639
675
|
}
|
|
640
676
|
|
|
641
677
|
self.consecutiveAuthErrors += 1
|
|
642
|
-
if self.consecutiveAuthErrors
|
|
678
|
+
if self.consecutiveAuthErrors > limit {
|
|
643
679
|
self.failAndStop(message: "Auth Error (\(statusCode)) - Retry limit reached (\(limit)). Stopping.", statusCode: Double(statusCode))
|
|
644
680
|
return
|
|
645
681
|
}
|
|
@@ -20,28 +20,44 @@ extension SseConfig {
|
|
|
20
20
|
maxAuthRetries: Double?? = nil,
|
|
21
21
|
autoParseJSON: Bool?? = nil,
|
|
22
22
|
monitorNetwork: Bool?? = nil,
|
|
23
|
-
onBeforeRequest: (() -> Promise<Promise<Dictionary<String, String>>>)?? = nil,
|
|
24
23
|
mock: SseMockConfig?? = nil
|
|
25
24
|
) -> SseConfig {
|
|
25
|
+
let newUrl: String = url ?? self.url
|
|
26
|
+
let newMethod: HttpMethod? = method ?? self.method
|
|
27
|
+
let newHeaders: [String: String]? = headers ?? self.headers
|
|
28
|
+
let newBody: String? = body ?? self.body
|
|
29
|
+
let newBackgroundExecution: Bool? = backgroundExecution ?? self.backgroundExecution
|
|
30
|
+
let newBatchingIntervalMs: Double? = batchingIntervalMs ?? self.batchingIntervalMs
|
|
31
|
+
let newMaxBufferSize: Double? = maxBufferSize ?? self.maxBufferSize
|
|
32
|
+
let newConnectionTimeoutMs: Double? = connectionTimeoutMs ?? self.connectionTimeoutMs
|
|
33
|
+
let newReadTimeoutMs: Double? = readTimeoutMs ?? self.readTimeoutMs
|
|
34
|
+
let newRetryIntervalMs: Double? = retryIntervalMs ?? self.retryIntervalMs
|
|
35
|
+
let newMaxRetryIntervalMs: Double? = maxRetryIntervalMs ?? self.maxRetryIntervalMs
|
|
36
|
+
let newJitterFactor: Double? = jitterFactor ?? self.jitterFactor
|
|
37
|
+
let newMaxReconnectAttempts: Double? = maxReconnectAttempts ?? self.maxReconnectAttempts
|
|
38
|
+
let newMaxAuthRetries: Double? = maxAuthRetries ?? self.maxAuthRetries
|
|
39
|
+
let newAutoParseJSON: Bool? = autoParseJSON ?? self.autoParseJSON
|
|
40
|
+
let newMonitorNetwork: Bool? = monitorNetwork ?? self.monitorNetwork
|
|
41
|
+
let newMock: SseMockConfig? = mock ?? self.mock
|
|
42
|
+
|
|
26
43
|
return SseConfig(
|
|
27
|
-
url:
|
|
28
|
-
method:
|
|
29
|
-
headers:
|
|
30
|
-
body:
|
|
31
|
-
backgroundExecution:
|
|
32
|
-
batchingIntervalMs:
|
|
33
|
-
maxBufferSize:
|
|
34
|
-
connectionTimeoutMs:
|
|
35
|
-
readTimeoutMs:
|
|
36
|
-
retryIntervalMs:
|
|
37
|
-
maxRetryIntervalMs:
|
|
38
|
-
jitterFactor:
|
|
39
|
-
maxReconnectAttempts:
|
|
40
|
-
maxAuthRetries:
|
|
41
|
-
autoParseJSON:
|
|
42
|
-
monitorNetwork:
|
|
43
|
-
|
|
44
|
-
mock: mock ?? self.mock
|
|
44
|
+
url: newUrl,
|
|
45
|
+
method: newMethod,
|
|
46
|
+
headers: newHeaders,
|
|
47
|
+
body: newBody,
|
|
48
|
+
backgroundExecution: newBackgroundExecution,
|
|
49
|
+
batchingIntervalMs: newBatchingIntervalMs,
|
|
50
|
+
maxBufferSize: newMaxBufferSize,
|
|
51
|
+
connectionTimeoutMs: newConnectionTimeoutMs,
|
|
52
|
+
readTimeoutMs: newReadTimeoutMs,
|
|
53
|
+
retryIntervalMs: newRetryIntervalMs,
|
|
54
|
+
maxRetryIntervalMs: newMaxRetryIntervalMs,
|
|
55
|
+
jitterFactor: newJitterFactor,
|
|
56
|
+
maxReconnectAttempts: newMaxReconnectAttempts,
|
|
57
|
+
maxAuthRetries: newMaxAuthRetries,
|
|
58
|
+
autoParseJSON: newAutoParseJSON,
|
|
59
|
+
monitorNetwork: newMonitorNetwork,
|
|
60
|
+
mock: newMock
|
|
45
61
|
)
|
|
46
62
|
}
|
|
47
63
|
}
|
|
@@ -21,6 +21,37 @@ export function sanitizeHeaders(headers) {
|
|
|
21
21
|
}
|
|
22
22
|
return clean;
|
|
23
23
|
}
|
|
24
|
+
const SENSITIVE_HEADER_REGEX = /^(authorization|cookie|proxy-authorization|x-api-key|api-key)$/i;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Checks whether a URL points to a loopback/local address (localhost, 127.0.0.1, [::1]).
|
|
28
|
+
*/
|
|
29
|
+
function isLoopbackUrl(url) {
|
|
30
|
+
try {
|
|
31
|
+
const parsed = new URL(url);
|
|
32
|
+
const hostname = parsed.hostname.toLowerCase();
|
|
33
|
+
return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' || hostname === '::1' || hostname === '10.0.2.2' || hostname === '10.0.3.3' || hostname.endsWith('.localhost');
|
|
34
|
+
} catch {
|
|
35
|
+
const lower = url.toLowerCase();
|
|
36
|
+
return lower.includes('://localhost') || lower.includes('://127.0.0.1') || lower.includes('://[::1]') || lower.includes('://10.0.2.2') || lower.includes('://10.0.3.3');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Warns in development when credential headers are transmitted over insecure cleartext HTTP (non-loopback).
|
|
42
|
+
*/
|
|
43
|
+
export function warnInsecureCredentials(url, headers) {
|
|
44
|
+
if (typeof __DEV__ === 'undefined' || !__DEV__) return;
|
|
45
|
+
if (!url || typeof url !== 'string' || !headers || typeof headers !== 'object') return;
|
|
46
|
+
const trimmedUrl = url.trim();
|
|
47
|
+
const lowerUrl = trimmedUrl.toLowerCase();
|
|
48
|
+
if (lowerUrl.startsWith('http://') && !isLoopbackUrl(trimmedUrl)) {
|
|
49
|
+
const hasSensitiveHeader = Object.keys(headers).some(key => SENSITIVE_HEADER_REGEX.test(key.trim()));
|
|
50
|
+
if (hasSensitiveHeader) {
|
|
51
|
+
console.warn(`[NitroSse] Security Warning: Sensitive credential header(s) detected over an insecure, unencrypted HTTP connection ("${trimmedUrl}"). Transmitting credentials over plaintext HTTP is vulnerable to interception and token theft. Use HTTPS in production.`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
24
55
|
|
|
25
56
|
/**
|
|
26
57
|
* Defensively validates and normalizes the SSE configuration object.
|
|
@@ -61,6 +92,7 @@ export function validateConfig(config) {
|
|
|
61
92
|
received: config.headers
|
|
62
93
|
});
|
|
63
94
|
}
|
|
95
|
+
warnInsecureCredentials(trimmedUrl, config.headers);
|
|
64
96
|
}
|
|
65
97
|
let lowerMethod;
|
|
66
98
|
if (config.method !== undefined) {
|
|
@@ -261,6 +293,7 @@ export class NitroSseClient {
|
|
|
261
293
|
try {
|
|
262
294
|
const h = await rawOnBeforeRequest();
|
|
263
295
|
if (h && typeof h === 'object' && !Array.isArray(h)) {
|
|
296
|
+
warnInsecureCredentials(validatedConfig.url, h);
|
|
264
297
|
return sanitizeHeaders(h);
|
|
265
298
|
}
|
|
266
299
|
if (typeof __DEV__ !== 'undefined' && __DEV__ && h !== undefined && h !== null) {
|
|
@@ -272,13 +305,14 @@ export class NitroSseClient {
|
|
|
272
305
|
throw err;
|
|
273
306
|
}
|
|
274
307
|
} : undefined;
|
|
308
|
+
const pureConfig = {
|
|
309
|
+
...validatedConfig
|
|
310
|
+
};
|
|
311
|
+
delete pureConfig.onBeforeRequest;
|
|
275
312
|
this._config = {
|
|
276
|
-
...
|
|
313
|
+
...pureConfig,
|
|
277
314
|
...(cleanHeaders !== undefined ? {
|
|
278
315
|
headers: cleanHeaders
|
|
279
|
-
} : {}),
|
|
280
|
-
...(safeOnBeforeRequest !== undefined ? {
|
|
281
|
-
onBeforeRequest: safeOnBeforeRequest
|
|
282
316
|
} : {})
|
|
283
317
|
};
|
|
284
318
|
this._pendingHeaders = {};
|
|
@@ -300,9 +334,15 @@ export class NitroSseClient {
|
|
|
300
334
|
|
|
301
335
|
// Wrap the native setup to dispatch events to typed listeners when native streaming is active
|
|
302
336
|
if (mockConfig?.mode !== 'replace') {
|
|
303
|
-
|
|
304
|
-
this.
|
|
305
|
-
|
|
337
|
+
if (safeOnBeforeRequest !== undefined) {
|
|
338
|
+
this._native.setup(this._config, events => {
|
|
339
|
+
this._dispatchEvents(events);
|
|
340
|
+
}, safeOnBeforeRequest);
|
|
341
|
+
} else {
|
|
342
|
+
this._native.setup(this._config, events => {
|
|
343
|
+
this._dispatchEvents(events);
|
|
344
|
+
});
|
|
345
|
+
}
|
|
306
346
|
}
|
|
307
347
|
}
|
|
308
348
|
addEventListener(type, listener) {
|
|
@@ -383,6 +423,13 @@ export class NitroSseClient {
|
|
|
383
423
|
if (event.event && event.event !== event.type) {
|
|
384
424
|
this._emit(event.event, event);
|
|
385
425
|
}
|
|
426
|
+
if (event.type === 'state' && event.state === 'closed') {
|
|
427
|
+
this._emit('close', {
|
|
428
|
+
type: 'close',
|
|
429
|
+
statusCode: event.statusCode ?? 200,
|
|
430
|
+
state: 'closed'
|
|
431
|
+
});
|
|
432
|
+
}
|
|
386
433
|
}
|
|
387
434
|
}
|
|
388
435
|
start() {
|
|
@@ -439,6 +486,7 @@ export class NitroSseClient {
|
|
|
439
486
|
};
|
|
440
487
|
this._driver.updateHeaders(clean);
|
|
441
488
|
} else {
|
|
489
|
+
warnInsecureCredentials(this._config.url, clean);
|
|
442
490
|
this._config.headers = {
|
|
443
491
|
...this._config.headers,
|
|
444
492
|
...clean
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
import { NitroModules } from 'react-native-nitro-modules';
|
|
4
|
+
import { NitroSseClient } from "./NitroSseClient.js";
|
|
5
|
+
import { NitroSseModuleNotFoundError } from "./NitroSseError.js";
|
|
6
|
+
/**
|
|
7
|
+
* Creates a high-performance SSE client that supports typed event listeners (`addEventListener`) and legacy batching.
|
|
8
|
+
*
|
|
9
|
+
* @returns An SseClient instance wrapping the native NitroSse implementation.
|
|
10
|
+
* @throws {NitroSseModuleNotFoundError} If the native NitroSse module cannot be found. Ensure the library is linked and the app is built for iOS/Android.
|
|
11
|
+
*/
|
|
12
|
+
export function createNitroSse() {
|
|
13
|
+
let nativeSse;
|
|
14
|
+
try {
|
|
15
|
+
nativeSse = NitroModules.createHybridObject('NitroSse');
|
|
16
|
+
} catch {
|
|
17
|
+
console.debug('Native NitroSse not found. This might be a test environment or web.');
|
|
18
|
+
}
|
|
19
|
+
if (!nativeSse) {
|
|
20
|
+
throw new NitroSseModuleNotFoundError('NitroSse: Native module not found. Ensure you have linked the library and built the app for iOS/Android.');
|
|
21
|
+
}
|
|
22
|
+
return new NitroSseClient(nativeSse);
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=createNitroSse.js.map
|
package/lib/module/index.js
CHANGED
|
@@ -1,29 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
import { NitroModules } from 'react-native-nitro-modules';
|
|
4
|
-
import { NitroSseClient } from "./NitroSseClient.js";
|
|
5
|
-
import { NitroSseModuleNotFoundError } from "./NitroSseError.js";
|
|
6
3
|
export * from "./SseInterface.js";
|
|
7
4
|
export * from "./useNitroSse.js";
|
|
8
5
|
export * from "./NitroSseClient.js";
|
|
9
6
|
export * from "./NitroSseError.js";
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Creates a high-performance SSE client that supports typed event listeners (`addEventListener`) and legacy batching.
|
|
13
|
-
*
|
|
14
|
-
* @returns An SseClient instance wrapping the native NitroSse implementation.
|
|
15
|
-
* @throws {NitroSseModuleNotFoundError} If the native NitroSse module cannot be found. Ensure the library is linked and the app is built for iOS/Android.
|
|
16
|
-
*/
|
|
17
|
-
export function createNitroSse() {
|
|
18
|
-
let nativeSse;
|
|
19
|
-
try {
|
|
20
|
-
nativeSse = NitroModules.createHybridObject('NitroSse');
|
|
21
|
-
} catch {
|
|
22
|
-
console.debug('Native NitroSse not found. This might be a test environment or web.');
|
|
23
|
-
}
|
|
24
|
-
if (!nativeSse) {
|
|
25
|
-
throw new NitroSseModuleNotFoundError('NitroSse: Native module not found. Ensure you have linked the library and built the app for iOS/Android.');
|
|
26
|
-
}
|
|
27
|
-
return new NitroSseClient(nativeSse);
|
|
28
|
-
}
|
|
7
|
+
export * from "./createNitroSse.js";
|
|
29
8
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
3
|
import { useEffect, useRef, useState, useCallback } from 'react';
|
|
4
|
-
import { createNitroSse } from "./
|
|
4
|
+
import { createNitroSse } from "./createNitroSse.js";
|
|
5
5
|
/**
|
|
6
6
|
* Safely serializes an object into a stable JSON string:
|
|
7
7
|
* - Sorts object keys to avoid reconnection on equivalent configs with reordered keys.
|
|
@@ -123,6 +123,19 @@ export function useNitroSse(options) {
|
|
|
123
123
|
};
|
|
124
124
|
}, [onMessage, onError, onOpen, onClose, onHeartbeat, onStateChange, events, onBeforeRequest]);
|
|
125
125
|
const hasBeforeRequest = Boolean(onBeforeRequest);
|
|
126
|
+
// Track undefined transition or key removal to recreate client and purge stale headers (e.g. on logout)
|
|
127
|
+
const isHeadersUndefined = headers === undefined;
|
|
128
|
+
const currentHeaderKeys = headers && typeof headers === 'object' ? Object.keys(headers).sort() : [];
|
|
129
|
+
const prevHeaderKeysRef = useRef(undefined);
|
|
130
|
+
const headerRemovalTokenRef = useRef(0);
|
|
131
|
+
if (prevHeaderKeysRef.current !== undefined && headers !== undefined) {
|
|
132
|
+
const currentKeysSet = new Set(currentHeaderKeys);
|
|
133
|
+
const isKeyRemoved = prevHeaderKeysRef.current.some(k => !currentKeysSet.has(k));
|
|
134
|
+
if (isKeyRemoved) {
|
|
135
|
+
headerRemovalTokenRef.current++;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
prevHeaderKeysRef.current = currentHeaderKeys;
|
|
126
139
|
const configKey = safeSerializeConfig(restConfig);
|
|
127
140
|
const headersKey = safeSerializeConfig(headers);
|
|
128
141
|
|
|
@@ -163,9 +176,12 @@ export function useNitroSse(options) {
|
|
|
163
176
|
}
|
|
164
177
|
if (e.event && e.event !== e.type) {
|
|
165
178
|
try {
|
|
166
|
-
const
|
|
167
|
-
if (
|
|
168
|
-
handler
|
|
179
|
+
const customEvents = callbacksRef.current.events;
|
|
180
|
+
if (customEvents && typeof customEvents === 'object' && Object.prototype.hasOwnProperty.call(customEvents, e.event)) {
|
|
181
|
+
const handler = customEvents[e.event];
|
|
182
|
+
if (typeof handler === 'function') {
|
|
183
|
+
handler(e);
|
|
184
|
+
}
|
|
169
185
|
}
|
|
170
186
|
} catch (err) {
|
|
171
187
|
console.error(`[useNitroSse] Unhandled error in events['${e.event}'] callback:`, err);
|
|
@@ -222,8 +238,9 @@ export function useNitroSse(options) {
|
|
|
222
238
|
clientRef.current = null;
|
|
223
239
|
setClient(null);
|
|
224
240
|
};
|
|
241
|
+
// Recreate client if headers becomes undefined or keys are removed to purge stale native headers
|
|
225
242
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
226
|
-
}, [configKey, autoStart, hasBeforeRequest, hasValidUrl]);
|
|
243
|
+
}, [configKey, autoStart, hasBeforeRequest, hasValidUrl, isHeadersUndefined, headerRemovalTokenRef.current]);
|
|
227
244
|
|
|
228
245
|
// Synchronize headers dynamically without reconnecting or tearing down active socket
|
|
229
246
|
const isInitialMount = useRef(true);
|
|
@@ -28,9 +28,9 @@ export interface NitroSse extends HybridObject<{
|
|
|
28
28
|
android: 'kotlin';
|
|
29
29
|
}> {
|
|
30
30
|
/**
|
|
31
|
-
* Configure SSE and
|
|
31
|
+
* Configure SSE, event callback, and optional dynamic request interceptor.
|
|
32
32
|
*/
|
|
33
|
-
setup(config: SseConfig, onEvent: (events: SseEvent[]) => void): void;
|
|
33
|
+
setup(config: SseConfig, onEvent: (events: SseEvent[]) => void, onBeforeRequest?: () => Promise<Record<string, string>>): void;
|
|
34
34
|
/**
|
|
35
35
|
* Start the SSE connection.
|
|
36
36
|
*/
|
|
@@ -1,17 +1,21 @@
|
|
|
1
1
|
import type { AnyMap } from 'react-native-nitro-modules';
|
|
2
2
|
import type { NitroSse } from './NitroSse.nitro';
|
|
3
|
-
import type { SseClient,
|
|
3
|
+
import type { SseClient, SseClientOptions, SseEvent, SseListener, SseStats, SseState } from './SseInterface';
|
|
4
4
|
/**
|
|
5
5
|
* Sanitizes HTTP headers by stripping carriage returns, newlines, null bytes,
|
|
6
6
|
* converting non-string values to strings, and pruning null/undefined values.
|
|
7
7
|
*/
|
|
8
8
|
export declare function sanitizeHeaders(headers?: Record<string, unknown>): Record<string, string>;
|
|
9
|
+
/**
|
|
10
|
+
* Warns in development when credential headers are transmitted over insecure cleartext HTTP (non-loopback).
|
|
11
|
+
*/
|
|
12
|
+
export declare function warnInsecureCredentials(url?: string, headers?: Record<string, unknown>): void;
|
|
9
13
|
/**
|
|
10
14
|
* Defensively validates and normalizes the SSE configuration object.
|
|
11
15
|
* Throws NitroSseValidationError if essential requirements (e.g. valid URL) are violated.
|
|
12
16
|
* Clamps numeric properties to safe boundaries and warns in __DEV__.
|
|
13
17
|
*/
|
|
14
|
-
export declare function validateConfig(config:
|
|
18
|
+
export declare function validateConfig(config: SseClientOptions): SseClientOptions;
|
|
15
19
|
/**
|
|
16
20
|
* Public facade and typed event emitter for NitroSse, delegating streaming execution to an SseDriver strategy.
|
|
17
21
|
*/
|
|
@@ -26,7 +30,7 @@ export declare class NitroSseClient implements SseClient {
|
|
|
26
30
|
constructor(native: NitroSse);
|
|
27
31
|
get isDisposed(): boolean;
|
|
28
32
|
private _checkDisposed;
|
|
29
|
-
setup(config:
|
|
33
|
+
setup(config: SseClientOptions, onEvent?: (events: SseEvent[]) => void): void;
|
|
30
34
|
addEventListener<TData = AnyMap>(type: string, listener: SseListener<TData>): void;
|
|
31
35
|
removeEventListener<TData = AnyMap>(type: string, listener: SseListener<TData>): void;
|
|
32
36
|
removeAllEventListeners(type?: string): void;
|
|
@@ -104,17 +104,22 @@ export interface SseConfig {
|
|
|
104
104
|
* @default true
|
|
105
105
|
*/
|
|
106
106
|
monitorNetwork?: boolean;
|
|
107
|
+
/**
|
|
108
|
+
* Configuration for mock streaming data.
|
|
109
|
+
* Used for local testing and debugging.
|
|
110
|
+
*/
|
|
111
|
+
mock?: SseMockConfig;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Public client setup options, combining connection config with dynamic request interceptor.
|
|
115
|
+
*/
|
|
116
|
+
export interface SseClientOptions extends SseConfig {
|
|
107
117
|
/**
|
|
108
118
|
* Async interceptor called before every connection attempt (including auto-reconnects).
|
|
109
119
|
* Use this to refresh tokens or calculate dynamic headers.
|
|
110
120
|
* Note: This is protected by a native timeout to prevent the app from hanging.
|
|
111
121
|
*/
|
|
112
122
|
onBeforeRequest?: () => Promise<Record<string, string>>;
|
|
113
|
-
/**
|
|
114
|
-
* Configuration for mock streaming data.
|
|
115
|
-
* Used for local testing and debugging.
|
|
116
|
-
*/
|
|
117
|
-
mock?: SseMockConfig;
|
|
118
123
|
}
|
|
119
124
|
export type SseMockMode = 'replace' | 'inject';
|
|
120
125
|
/**
|
|
@@ -216,12 +221,14 @@ export type SseListener<TData = AnyMap> = (event: SseEvent<TData>) => void;
|
|
|
216
221
|
* Public interface for the NitroSse client, supporting typed event listeners.
|
|
217
222
|
*/
|
|
218
223
|
export interface SseClient {
|
|
224
|
+
/** Whether the client instance has been disposed. */
|
|
225
|
+
readonly isDisposed: boolean;
|
|
219
226
|
/**
|
|
220
227
|
* Configure SSE and setup event callback.
|
|
221
|
-
* @param config The SSE configuration.
|
|
228
|
+
* @param config The SSE configuration and client options.
|
|
222
229
|
* @param onEvent Optional legacy batch callback for all events.
|
|
223
230
|
*/
|
|
224
|
-
setup(config:
|
|
231
|
+
setup(config: SseClientOptions, onEvent?: (events: SseEvent[]) => void): void;
|
|
225
232
|
/**
|
|
226
233
|
* Register a listener for a specific event type ('message', 'open', etc.)
|
|
227
234
|
* or a custom SSE event name (from the 'event:' field).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SseClient } from './SseInterface';
|
|
2
|
+
/**
|
|
3
|
+
* Creates a high-performance SSE client that supports typed event listeners (`addEventListener`) and legacy batching.
|
|
4
|
+
*
|
|
5
|
+
* @returns An SseClient instance wrapping the native NitroSse implementation.
|
|
6
|
+
* @throws {NitroSseModuleNotFoundError} If the native NitroSse module cannot be found. Ensure the library is linked and the app is built for iOS/Android.
|
|
7
|
+
*/
|
|
8
|
+
export declare function createNitroSse(): SseClient;
|
|
9
|
+
//# sourceMappingURL=createNitroSse.d.ts.map
|