@onekeyfe/react-native-sni-connect 6.7.0-6 → 6.7.0-60
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 +111 -65
- package/android/src/main/java/com/sniconnect/SniConnectLogger.kt +13 -1
- package/android/src/main/java/com/sniconnect/SniConnectModule.kt +159 -28
- package/android/src/main/java/com/sniconnect/SniConnectValidation.kt +68 -0
- package/android/src/main/java/com/sniconnect/SniPinnedTransport.kt +89 -1
- package/android/src/test/java/com/sniconnect/SniConnectValidationTest.kt +235 -1
- package/ios/SniConnect.mm +27 -0
- package/ios/SniConnect.swift +67 -4
- package/ios/SniConnectClient.swift +46 -23
- package/ios/SniConnectCore.swift +1 -1
- package/ios/SniConnectLog.swift +14 -1
- package/ios/SniConnectValidation.swift +72 -1
- package/ios/Tests/SniConnectValidationTests/SniConnectValidationTests.swift +130 -0
- package/lib/module/NativeSniConnect.js +6 -0
- package/lib/module/index.js +11 -0
- package/lib/typescript/src/NativeSniConnect.d.ts +15 -0
- package/lib/typescript/src/index.d.ts +4 -2
- package/package.json +7 -7
- package/src/NativeSniConnect.ts +20 -0
- package/src/index.tsx +18 -0
|
@@ -112,7 +112,7 @@ final class SniConnectSessionInvalidationDelegate: NSObject, URLSessionDataDeleg
|
|
|
112
112
|
let releasedResolver = resolverLease.release()
|
|
113
113
|
SniConnectLog.info(SniConnectLog.event("sni_session_invalidated", [
|
|
114
114
|
("hostname", hostname),
|
|
115
|
-
("
|
|
115
|
+
("ip", ip),
|
|
116
116
|
("releasedResolver", releasedResolver),
|
|
117
117
|
("success", error == nil),
|
|
118
118
|
]))
|
|
@@ -259,6 +259,8 @@ final class SniConnectClient {
|
|
|
259
259
|
let headers: [String: String]
|
|
260
260
|
let body: String?
|
|
261
261
|
let timeout: TimeInterval
|
|
262
|
+
// Set only by uploadFile(); already resolved inside the app sandbox.
|
|
263
|
+
var bodyFileURL: URL? = nil
|
|
262
264
|
|
|
263
265
|
// Advanced timeout configurations
|
|
264
266
|
let connectTimeout: TimeInterval? // Connection establishment timeout
|
|
@@ -408,7 +410,7 @@ final class SniConnectClient {
|
|
|
408
410
|
)
|
|
409
411
|
SniConnectLog.info(SniConnectLog.event("sni_transport_config", [
|
|
410
412
|
("hostname", hostname),
|
|
411
|
-
("
|
|
413
|
+
("ip", ip),
|
|
412
414
|
("ipFamily", SniConnectLog.ipFamily(ip)),
|
|
413
415
|
("proxyMode", "no_proxy"),
|
|
414
416
|
("pinnedResolver", true),
|
|
@@ -457,7 +459,7 @@ final class SniConnectClient {
|
|
|
457
459
|
case .waitForResolverSlots(let resolverLeases):
|
|
458
460
|
SniConnectLog.info(SniConnectLog.event("sni_resolver_slot_wait", [
|
|
459
461
|
("hostname", key.hostname),
|
|
460
|
-
("
|
|
462
|
+
("ip", config.ip),
|
|
461
463
|
("waitCount", resolverLeases.count),
|
|
462
464
|
]))
|
|
463
465
|
for resolverLease in resolverLeases {
|
|
@@ -508,7 +510,7 @@ final class SniConnectClient {
|
|
|
508
510
|
}
|
|
509
511
|
SniConnectLog.info(SniConnectLog.event("sni_cache_evict", [
|
|
510
512
|
("hostname", evictedKey.hostname),
|
|
511
|
-
("
|
|
513
|
+
("ip", evictedKey.canonicalIP),
|
|
512
514
|
("cacheSize", sessionCache.count),
|
|
513
515
|
("limit", Self.maxCachedSessions),
|
|
514
516
|
("reason", forPendingInsert ? "max_cached_sessions_pending_insert" : "max_cached_sessions"),
|
|
@@ -579,14 +581,14 @@ final class SniConnectClient {
|
|
|
579
581
|
guard let self = self, let token = self.requestTokensById.removeValue(forKey: requestId),
|
|
580
582
|
let task = self.activeTasksByToken.removeValue(forKey: token) else {
|
|
581
583
|
SniConnectLog.warn(SniConnectLog.event("sni_cancel", [
|
|
582
|
-
("
|
|
584
|
+
("requestId", requestId),
|
|
583
585
|
("success", false),
|
|
584
586
|
]))
|
|
585
587
|
return false
|
|
586
588
|
}
|
|
587
589
|
task.cancel()
|
|
588
590
|
SniConnectLog.info(SniConnectLog.event("sni_cancel", [
|
|
589
|
-
("
|
|
591
|
+
("requestId", requestId),
|
|
590
592
|
("success", true),
|
|
591
593
|
]))
|
|
592
594
|
return true
|
|
@@ -636,7 +638,7 @@ final class SniConnectClient {
|
|
|
636
638
|
let previousTask = self.activeTasksByToken.removeValue(forKey: previousToken) {
|
|
637
639
|
previousTask.cancel()
|
|
638
640
|
SniConnectLog.warn(SniConnectLog.event("sni_duplicate_request_id", [
|
|
639
|
-
("
|
|
641
|
+
("requestId", requestId),
|
|
640
642
|
("action", "cancel_previous"),
|
|
641
643
|
]))
|
|
642
644
|
}
|
|
@@ -678,17 +680,24 @@ final class SniConnectClient {
|
|
|
678
680
|
method = try SniConnectValidation.normalizeMethod(config.method)
|
|
679
681
|
normalizedPath = try SniConnectValidation.normalizePath(config.path)
|
|
680
682
|
try SniConnectValidation.validateTimeout(config.effectiveTotalTimeout)
|
|
681
|
-
|
|
682
|
-
|
|
683
|
+
if config.bodyFileURL != nil {
|
|
684
|
+
try SniConnectValidation.validateUploadMethod(method)
|
|
685
|
+
if config.body != nil {
|
|
686
|
+
throw SniConnectValidation.ValidationError.invalidBody
|
|
687
|
+
}
|
|
688
|
+
} else {
|
|
689
|
+
try SniConnectValidation.validateBody(config.body)
|
|
690
|
+
try SniConnectValidation.validateMethodBody(method: method, body: config.body)
|
|
691
|
+
}
|
|
683
692
|
} catch {
|
|
684
693
|
let sniError = SniConnectError.invalidConfig("\(error)")
|
|
685
694
|
SniConnectLog.error(SniConnectLog.event("sni_request_result", [
|
|
686
695
|
("result", "error"),
|
|
687
696
|
("code", sniError.code),
|
|
688
697
|
("nativeErrorClass", String(describing: type(of: error))),
|
|
689
|
-
("
|
|
698
|
+
("requestId", config.requestId),
|
|
690
699
|
("hostname", config.hostname.lowercased()),
|
|
691
|
-
("
|
|
700
|
+
("ip", config.ip),
|
|
692
701
|
("ipFamily", SniConnectLog.ipFamily(config.ip)),
|
|
693
702
|
("method", config.method.uppercased()),
|
|
694
703
|
("timeoutMs", Int(config.effectiveTotalTimeout)),
|
|
@@ -719,9 +728,9 @@ final class SniConnectClient {
|
|
|
719
728
|
("result", "error"),
|
|
720
729
|
("code", sniError.code),
|
|
721
730
|
("nativeErrorClass", String(describing: type(of: error))),
|
|
722
|
-
("
|
|
731
|
+
("requestId", config.requestId),
|
|
723
732
|
("hostname", config.hostname.lowercased()),
|
|
724
|
-
("
|
|
733
|
+
("ip", config.ip),
|
|
725
734
|
("ipFamily", SniConnectLog.ipFamily(config.ip)),
|
|
726
735
|
("method", method),
|
|
727
736
|
("timeoutMs", Int(config.effectiveTotalTimeout)),
|
|
@@ -763,8 +772,20 @@ final class SniConnectClient {
|
|
|
763
772
|
mutableRequest.setValue(config.hostname, forHTTPHeaderField: "Host")
|
|
764
773
|
mutableRequest.setValue("identity", forHTTPHeaderField: "Accept-Encoding")
|
|
765
774
|
|
|
766
|
-
|
|
775
|
+
var bodyBytes = 0
|
|
776
|
+
if let bodyFileURL = config.bodyFileURL {
|
|
777
|
+
let fileData: Data
|
|
778
|
+
do {
|
|
779
|
+
// Bound consumption even if the file grew while waiting for admission.
|
|
780
|
+
fileData = try SniConnectValidation.readUploadFile(bodyFileURL)
|
|
781
|
+
} catch {
|
|
782
|
+
throw SniConnectError.invalidConfig("Upload file is not readable")
|
|
783
|
+
}
|
|
784
|
+
mutableRequest.httpBody = fileData
|
|
785
|
+
bodyBytes = fileData.count
|
|
786
|
+
} else if let bodyString = config.body, let bodyData = bodyString.data(using: .utf8) {
|
|
767
787
|
mutableRequest.httpBody = bodyData
|
|
788
|
+
bodyBytes = bodyData.count
|
|
768
789
|
}
|
|
769
790
|
|
|
770
791
|
// Per-request connect timeout (avoids the process-global setter race).
|
|
@@ -772,16 +793,17 @@ final class SniConnectClient {
|
|
|
772
793
|
let request = mutableRequest as URLRequest
|
|
773
794
|
|
|
774
795
|
SniConnectLog.info(SniConnectLog.event("sni_request_start", [
|
|
775
|
-
("
|
|
796
|
+
("requestId", config.requestId),
|
|
776
797
|
("hostname", config.hostname.lowercased()),
|
|
777
|
-
("
|
|
798
|
+
("ip", config.ip),
|
|
778
799
|
("ipFamily", SniConnectLog.ipFamily(config.ip)),
|
|
779
800
|
("method", method),
|
|
780
801
|
("timeoutMs", Int(config.effectiveTotalTimeout)),
|
|
781
802
|
("connectTimeoutMs", Int(config.effectiveConnectTimeout)),
|
|
782
803
|
("queueWaitMs", queueWaitMilliseconds),
|
|
783
804
|
("headerCount", normalizedHeaders.count),
|
|
784
|
-
("bodyBytes",
|
|
805
|
+
("bodyBytes", bodyBytes),
|
|
806
|
+
("bodySource", config.bodyFileURL != nil ? "file" : "string"),
|
|
785
807
|
]))
|
|
786
808
|
|
|
787
809
|
do {
|
|
@@ -811,12 +833,13 @@ final class SniConnectClient {
|
|
|
811
833
|
let resultLog = SniConnectLog.event("sni_request_result", [
|
|
812
834
|
("result", "response"),
|
|
813
835
|
("status", status),
|
|
814
|
-
("
|
|
836
|
+
("requestId", config.requestId),
|
|
815
837
|
("hostname", config.hostname.lowercased()),
|
|
816
|
-
("
|
|
838
|
+
("ip", config.ip),
|
|
817
839
|
("ipFamily", SniConnectLog.ipFamily(config.ip)),
|
|
818
840
|
("method", method),
|
|
819
841
|
("timeoutMs", Int(config.effectiveTotalTimeout)),
|
|
842
|
+
("bodyBytes", bodyBytes),
|
|
820
843
|
("responseBytes", data.count),
|
|
821
844
|
("elapsedMs", SniConnectLog.elapsedMs(since: startedAt)),
|
|
822
845
|
])
|
|
@@ -839,9 +862,9 @@ final class SniConnectClient {
|
|
|
839
862
|
("result", "error"),
|
|
840
863
|
("code", error.code),
|
|
841
864
|
("nativeErrorClass", String(describing: type(of: error))),
|
|
842
|
-
("
|
|
865
|
+
("requestId", config.requestId),
|
|
843
866
|
("hostname", config.hostname.lowercased()),
|
|
844
|
-
("
|
|
867
|
+
("ip", config.ip),
|
|
845
868
|
("ipFamily", SniConnectLog.ipFamily(config.ip)),
|
|
846
869
|
("method", method),
|
|
847
870
|
("timeoutMs", Int(config.effectiveTotalTimeout)),
|
|
@@ -855,9 +878,9 @@ final class SniConnectClient {
|
|
|
855
878
|
("result", "error"),
|
|
856
879
|
("code", sniError.code),
|
|
857
880
|
("nativeErrorClass", String(describing: type(of: error))),
|
|
858
|
-
("
|
|
881
|
+
("requestId", config.requestId),
|
|
859
882
|
("hostname", config.hostname.lowercased()),
|
|
860
|
-
("
|
|
883
|
+
("ip", config.ip),
|
|
861
884
|
("ipFamily", SniConnectLog.ipFamily(config.ip)),
|
|
862
885
|
("method", method),
|
|
863
886
|
("timeoutMs", Int(config.effectiveTotalTimeout)),
|
package/ios/SniConnectCore.swift
CHANGED
|
@@ -114,7 +114,7 @@ final class SniConnectPinnedResolverRegistry {
|
|
|
114
114
|
guard domain.caseInsensitiveCompare(config.hostname) == .orderedSame else {
|
|
115
115
|
SniConnectCoreDiagnostics.warn(SniConnectCoreDiagnostics.event("sni_pinned_dns_unexpected_host", [
|
|
116
116
|
("expectedHost", config.hostname),
|
|
117
|
-
("
|
|
117
|
+
("requestedHost", domain.lowercased()),
|
|
118
118
|
("result", "fail_closed"),
|
|
119
119
|
]))
|
|
120
120
|
return nil
|
package/ios/SniConnectLog.swift
CHANGED
|
@@ -23,7 +23,20 @@ enum SniConnectLog {
|
|
|
23
23
|
static func event(_ name: String, _ fields: [(String, Any?)]) -> String {
|
|
24
24
|
let normalizedFields: [(String, Any?)] = [("event", name)] + fields
|
|
25
25
|
let pairs = normalizedFields.map { key, value in
|
|
26
|
-
|
|
26
|
+
let logValue = sanitize(value)
|
|
27
|
+
// Keep long diagnostic IDs recoverable without matching the logger's private-key filter.
|
|
28
|
+
var displayedValue = logValue
|
|
29
|
+
var formatSuffix = ""
|
|
30
|
+
if key == "requestId", let requestId = value as? String,
|
|
31
|
+
requestId != logValue || requestId.range(of: "[0-9a-fA-F]{64}", options: .regularExpression) != nil {
|
|
32
|
+
let allowed = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.")
|
|
33
|
+
displayedValue = (requestId.addingPercentEncoding(withAllowedCharacters: allowed) ?? "unavailable")
|
|
34
|
+
.replacingOccurrences(
|
|
35
|
+
of: "([0-9a-fA-F]{32})(?=[0-9a-fA-F]{32})", with: "$1-", options: .regularExpression
|
|
36
|
+
)
|
|
37
|
+
formatSuffix = " requestIdFormat=uri-hex32"
|
|
38
|
+
}
|
|
39
|
+
return "\(key)=\(displayedValue)\(formatSuffix)"
|
|
27
40
|
}
|
|
28
41
|
return pairs.joined(separator: " ")
|
|
29
42
|
}
|
|
@@ -18,6 +18,7 @@ enum SniConnectValidation {
|
|
|
18
18
|
case invalidRequestId(String)
|
|
19
19
|
case invalidTimeout(Double)
|
|
20
20
|
case invalidBody
|
|
21
|
+
case invalidUploadFile(String)
|
|
21
22
|
case resourceLimit(String)
|
|
22
23
|
}
|
|
23
24
|
|
|
@@ -26,6 +27,7 @@ enum SniConnectValidation {
|
|
|
26
27
|
static let maxPathBytes = 8 * 1024
|
|
27
28
|
static let maxRequestBodyBytes = 1024 * 1024
|
|
28
29
|
static let maxResponseBodyBytes = 10 * 1024 * 1024
|
|
30
|
+
static let maxUploadFileBytes = 20 * 1024 * 1024
|
|
29
31
|
static let maxHeaderCount = 64
|
|
30
32
|
static let maxHeaderNameBytes = 128
|
|
31
33
|
static let maxHeaderValueBytes = 8 * 1024
|
|
@@ -88,6 +90,75 @@ enum SniConnectValidation {
|
|
|
88
90
|
}
|
|
89
91
|
}
|
|
90
92
|
|
|
93
|
+
/// File uploads always carry a body, so only body-bearing write methods apply.
|
|
94
|
+
static func validateUploadMethod(_ method: String) throws {
|
|
95
|
+
if method != "POST" && method != "PUT" {
|
|
96
|
+
throw ValidationError.invalidMethod(method)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/// Resolve a caller-supplied upload path to a regular file inside one of
|
|
101
|
+
/// `allowedRoots` (the app's own sandbox). Symlinks are resolved before the
|
|
102
|
+
/// containment check so a link cannot point the upload at another file.
|
|
103
|
+
static func resolveUploadFile(
|
|
104
|
+
_ rawPath: String,
|
|
105
|
+
allowedRoots: [URL]
|
|
106
|
+
) throws -> (url: URL, sizeBytes: Int) {
|
|
107
|
+
if rawPath.isEmpty || containsControlCharacters(rawPath) {
|
|
108
|
+
throw ValidationError.invalidUploadFile("Invalid file path")
|
|
109
|
+
}
|
|
110
|
+
let fileURL: URL
|
|
111
|
+
if rawPath.hasPrefix("file:") {
|
|
112
|
+
guard let parsed = URL(string: rawPath), parsed.isFileURL else {
|
|
113
|
+
throw ValidationError.invalidUploadFile("Invalid file URL")
|
|
114
|
+
}
|
|
115
|
+
fileURL = parsed
|
|
116
|
+
} else if rawPath.hasPrefix("/") {
|
|
117
|
+
fileURL = URL(fileURLWithPath: rawPath)
|
|
118
|
+
} else {
|
|
119
|
+
throw ValidationError.invalidUploadFile("File path must be absolute")
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
let resolvedPath = fileURL.standardizedFileURL.resolvingSymlinksInPath().path
|
|
123
|
+
let isInsideAllowedRoot = allowedRoots.contains { root in
|
|
124
|
+
let rootPath = root.standardizedFileURL.resolvingSymlinksInPath().path
|
|
125
|
+
let prefix = rootPath.hasSuffix("/") ? rootPath : rootPath + "/"
|
|
126
|
+
return resolvedPath.hasPrefix(prefix)
|
|
127
|
+
}
|
|
128
|
+
if !isInsideAllowedRoot {
|
|
129
|
+
throw ValidationError.invalidUploadFile("File is outside the app sandbox")
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
let attributes: [FileAttributeKey: Any]
|
|
133
|
+
do {
|
|
134
|
+
attributes = try FileManager.default.attributesOfItem(atPath: resolvedPath)
|
|
135
|
+
} catch {
|
|
136
|
+
throw ValidationError.invalidUploadFile("File is not readable")
|
|
137
|
+
}
|
|
138
|
+
guard (attributes[.type] as? FileAttributeType) == .typeRegular else {
|
|
139
|
+
throw ValidationError.invalidUploadFile("Not a regular file")
|
|
140
|
+
}
|
|
141
|
+
let sizeBytes = (attributes[.size] as? NSNumber)?.intValue ?? 0
|
|
142
|
+
if sizeBytes <= 0 {
|
|
143
|
+
throw ValidationError.invalidUploadFile("File is empty")
|
|
144
|
+
}
|
|
145
|
+
if sizeBytes > maxUploadFileBytes {
|
|
146
|
+
throw ValidationError.invalidUploadFile("File is too large")
|
|
147
|
+
}
|
|
148
|
+
return (URL(fileURLWithPath: resolvedPath), sizeBytes)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/// Bound the actual read as well as the earlier path/metadata validation.
|
|
152
|
+
static func readUploadFile(_ url: URL) throws -> Data {
|
|
153
|
+
let handle = try FileHandle(forReadingFrom: url)
|
|
154
|
+
defer { try? handle.close() }
|
|
155
|
+
let data = try handle.read(upToCount: maxUploadFileBytes + 1) ?? Data()
|
|
156
|
+
guard !data.isEmpty, data.count <= maxUploadFileBytes else {
|
|
157
|
+
throw ValidationError.invalidUploadFile("File size is out of range")
|
|
158
|
+
}
|
|
159
|
+
return data
|
|
160
|
+
}
|
|
161
|
+
|
|
91
162
|
/// Validate and uppercase the HTTP method.
|
|
92
163
|
static func normalizeMethod(_ method: String) throws -> String {
|
|
93
164
|
if containsControlCharacters(method) {
|
|
@@ -455,7 +526,7 @@ final class SniConnectRequestLimiter: @unchecked Sendable {
|
|
|
455
526
|
("limit", maxPendingRequests),
|
|
456
527
|
("reason", "max_pending_requests"),
|
|
457
528
|
("hostname", hostname.lowercased()),
|
|
458
|
-
("
|
|
529
|
+
("ip", ip),
|
|
459
530
|
]))
|
|
460
531
|
immediateError = SniConnectValidation.ValidationError.resourceLimit(
|
|
461
532
|
"Too many pending SNI requests"
|
|
@@ -3,6 +3,23 @@ import XCTest
|
|
|
3
3
|
|
|
4
4
|
final class SniConnectValidationTests: XCTestCase {
|
|
5
5
|
|
|
6
|
+
func testUnexpectedResolverHostIsLoggedInPlaintextAndStillRejected() throws {
|
|
7
|
+
let registry = SniConnectPinnedResolverRegistry()
|
|
8
|
+
let resolverClass: AnyClass = try registry.resolverClass(hostname: "example.com", ip: "93.184.216.34") {
|
|
9
|
+
NSObject.self
|
|
10
|
+
}
|
|
11
|
+
var messages: [String] = []
|
|
12
|
+
let previousSink = SniConnectCoreDiagnostics.warnSink
|
|
13
|
+
SniConnectCoreDiagnostics.warnSink = { messages.append($0) }
|
|
14
|
+
defer { SniConnectCoreDiagnostics.warnSink = previousSink }
|
|
15
|
+
|
|
16
|
+
XCTAssertNil(registry.resolve(domain: "Unexpected.example.com", resolverClass: resolverClass))
|
|
17
|
+
XCTAssertEqual(messages.count, 1)
|
|
18
|
+
XCTAssertTrue(messages[0].contains("requestedHost=unexpected.example.com"))
|
|
19
|
+
XCTAssertTrue(messages[0].contains("result=fail_closed"))
|
|
20
|
+
XCTAssertFalse(messages[0].contains("requestedHostHash="))
|
|
21
|
+
}
|
|
22
|
+
|
|
6
23
|
func testSessionWithoutForwardingDataDelegateAllowsResponse() {
|
|
7
24
|
switch SniConnectSessionDelegatePolicy.responseDispositionWithoutForwardingDelegate {
|
|
8
25
|
case .allow:
|
|
@@ -550,6 +567,119 @@ final class SniConnectValidationTests: XCTestCase {
|
|
|
550
567
|
])
|
|
551
568
|
}
|
|
552
569
|
|
|
570
|
+
func testUploadMethodAllowsOnlyPostAndPut() {
|
|
571
|
+
XCTAssertNoThrow(try SniConnectValidation.validateUploadMethod("POST"))
|
|
572
|
+
XCTAssertNoThrow(try SniConnectValidation.validateUploadMethod("PUT"))
|
|
573
|
+
["GET", "HEAD", "PATCH", "DELETE", "OPTIONS"].forEach { method in
|
|
574
|
+
assertValidationFails {
|
|
575
|
+
try SniConnectValidation.validateUploadMethod(method)
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
func testResolveUploadFileAcceptsSandboxFileByPathAndFileURL() throws {
|
|
581
|
+
let root = try makeUploadRoot()
|
|
582
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
583
|
+
let file = root.appendingPathComponent("logs.zip")
|
|
584
|
+
try Data([0x50, 0x4B, 0x03, 0x04, 0xFF]).write(to: file)
|
|
585
|
+
|
|
586
|
+
let byPath = try SniConnectValidation.resolveUploadFile(file.path, allowedRoots: [root])
|
|
587
|
+
XCTAssertEqual(byPath.sizeBytes, 5)
|
|
588
|
+
XCTAssertEqual(
|
|
589
|
+
byPath.url.path,
|
|
590
|
+
file.standardizedFileURL.resolvingSymlinksInPath().path
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
let byURL = try SniConnectValidation.resolveUploadFile(
|
|
594
|
+
file.absoluteString,
|
|
595
|
+
allowedRoots: [root]
|
|
596
|
+
)
|
|
597
|
+
XCTAssertEqual(byURL.url.path, byPath.url.path)
|
|
598
|
+
|
|
599
|
+
let bySingleSlashURL = try SniConnectValidation.resolveUploadFile(
|
|
600
|
+
"file:" + file.path,
|
|
601
|
+
allowedRoots: [root]
|
|
602
|
+
)
|
|
603
|
+
XCTAssertEqual(bySingleSlashURL.url.path, byPath.url.path)
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
func testResolveUploadFileRejectsInvalidOrOutOfSandboxFiles() throws {
|
|
607
|
+
let root = try makeUploadRoot()
|
|
608
|
+
let outside = try makeUploadRoot()
|
|
609
|
+
defer {
|
|
610
|
+
try? FileManager.default.removeItem(at: root)
|
|
611
|
+
try? FileManager.default.removeItem(at: outside)
|
|
612
|
+
}
|
|
613
|
+
let outsideFile = outside.appendingPathComponent("secret.bin")
|
|
614
|
+
try Data([1, 2, 3]).write(to: outsideFile)
|
|
615
|
+
let emptyFile = root.appendingPathComponent("empty.zip")
|
|
616
|
+
try Data().write(to: emptyFile)
|
|
617
|
+
let link = root.appendingPathComponent("link.zip")
|
|
618
|
+
try FileManager.default.createSymbolicLink(at: link, withDestinationURL: outsideFile)
|
|
619
|
+
|
|
620
|
+
[
|
|
621
|
+
"",
|
|
622
|
+
"relative/logs.zip",
|
|
623
|
+
"https://example.com/logs.zip",
|
|
624
|
+
outsideFile.path,
|
|
625
|
+
root.appendingPathComponent("../\(outside.lastPathComponent)/secret.bin").path,
|
|
626
|
+
link.path,
|
|
627
|
+
emptyFile.path,
|
|
628
|
+
root.path,
|
|
629
|
+
root.appendingPathComponent("missing.zip").path,
|
|
630
|
+
root.path + "/logs\n.zip",
|
|
631
|
+
].forEach { path in
|
|
632
|
+
assertValidationFails {
|
|
633
|
+
_ = try SniConnectValidation.resolveUploadFile(path, allowedRoots: [root])
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
func testResolveUploadFileRejectsFilesOverTheSizeLimit() throws {
|
|
639
|
+
let root = try makeUploadRoot()
|
|
640
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
641
|
+
let file = root.appendingPathComponent("big.zip")
|
|
642
|
+
FileManager.default.createFile(atPath: file.path, contents: nil)
|
|
643
|
+
let handle = try FileHandle(forWritingTo: file)
|
|
644
|
+
try handle.truncate(atOffset: UInt64(SniConnectValidation.maxUploadFileBytes + 1))
|
|
645
|
+
try handle.close()
|
|
646
|
+
|
|
647
|
+
assertValidationFails {
|
|
648
|
+
_ = try SniConnectValidation.resolveUploadFile(file.path, allowedRoots: [root])
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
func testReadUploadFileAcceptsExactLimitBinaryData() throws {
|
|
653
|
+
let root = try makeUploadRoot()
|
|
654
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
655
|
+
let file = root.appendingPathComponent("exact.zip")
|
|
656
|
+
let expected = Data(repeating: 0xFF, count: SniConnectValidation.maxUploadFileBytes)
|
|
657
|
+
try expected.write(to: file)
|
|
658
|
+
XCTAssertEqual(try SniConnectValidation.readUploadFile(file), expected)
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
func testReadUploadFileRejectsGrowthAndTruncationAfterValidation() throws {
|
|
662
|
+
let root = try makeUploadRoot()
|
|
663
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
664
|
+
let file = root.appendingPathComponent("changing.zip")
|
|
665
|
+
try Data([1]).write(to: file)
|
|
666
|
+
let validated = try SniConnectValidation.resolveUploadFile(file.path, allowedRoots: [root])
|
|
667
|
+
let handle = try FileHandle(forWritingTo: file)
|
|
668
|
+
defer { try? handle.close() }
|
|
669
|
+
// A sparse file exercises the consumption bound without a large fixture.
|
|
670
|
+
try handle.truncate(atOffset: UInt64(SniConnectValidation.maxUploadFileBytes * 4))
|
|
671
|
+
XCTAssertThrowsError(try SniConnectValidation.readUploadFile(validated.url))
|
|
672
|
+
try handle.truncate(atOffset: 0)
|
|
673
|
+
XCTAssertThrowsError(try SniConnectValidation.readUploadFile(validated.url))
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
private func makeUploadRoot() throws -> URL {
|
|
677
|
+
let root = FileManager.default.temporaryDirectory
|
|
678
|
+
.appendingPathComponent("sni-upload-\(UUID().uuidString)", isDirectory: true)
|
|
679
|
+
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
|
680
|
+
return root
|
|
681
|
+
}
|
|
682
|
+
|
|
553
683
|
private func assertValidationFails(_ block: () throws -> Void, file: StaticString = #filePath, line: UInt = #line) {
|
|
554
684
|
XCTAssertThrowsError(try block(), file: file, line: line)
|
|
555
685
|
}
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
3
|
import { NativeModules, Platform, TurboModuleRegistry } from 'react-native';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Sends the raw bytes of an app-sandbox file as the request body over the same
|
|
7
|
+
* pinned-IP/SNI transport as `request()`. Set `content-type` in `headers`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
4
10
|
const LINKING_ERROR = `The package '@onekeyfe/react-native-sni-connect' doesn't seem to be linked. Make sure:\n\n` + Platform.select({
|
|
5
11
|
ios: "- You have run 'pod install'\n",
|
|
6
12
|
default: ''
|
package/lib/module/index.js
CHANGED
|
@@ -4,6 +4,17 @@ import NativeSniConnect from "./NativeSniConnect.js";
|
|
|
4
4
|
export function request(config) {
|
|
5
5
|
return NativeSniConnect.request(config);
|
|
6
6
|
}
|
|
7
|
+
export function isUploadFileSupported() {
|
|
8
|
+
return typeof NativeSniConnect.uploadFile === 'function';
|
|
9
|
+
}
|
|
10
|
+
export async function uploadFile(config) {
|
|
11
|
+
if (!isUploadFileSupported()) {
|
|
12
|
+
throw Object.assign(new Error('Native SNI file upload is not supported'), {
|
|
13
|
+
code: 'SNI_UNSUPPORTED'
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return NativeSniConnect.uploadFile(config);
|
|
17
|
+
}
|
|
7
18
|
export function cancelRequest(requestId) {
|
|
8
19
|
return NativeSniConnect.cancelRequest(requestId);
|
|
9
20
|
}
|
|
@@ -18,6 +18,20 @@ type NativeSniConnectRequest = SniConnectRequestBase & {
|
|
|
18
18
|
method: string;
|
|
19
19
|
body?: string | null;
|
|
20
20
|
};
|
|
21
|
+
type NativeSniConnectUploadFileRequest = SniConnectRequestBase & {
|
|
22
|
+
method: string;
|
|
23
|
+
filePath: string;
|
|
24
|
+
};
|
|
25
|
+
export type SniConnectUploadFileMethod = 'POST' | 'PUT';
|
|
26
|
+
/**
|
|
27
|
+
* Sends the raw bytes of an app-sandbox file as the request body over the same
|
|
28
|
+
* pinned-IP/SNI transport as `request()`. Set `content-type` in `headers`.
|
|
29
|
+
*/
|
|
30
|
+
export type SniConnectUploadFileRequest = SniConnectRequestBase & {
|
|
31
|
+
method: SniConnectUploadFileMethod;
|
|
32
|
+
/** Absolute path or `file://` URL inside the app sandbox, at most 20 MiB. */
|
|
33
|
+
filePath: string;
|
|
34
|
+
};
|
|
21
35
|
export type SniConnectBodylessMethod = 'GET' | 'HEAD';
|
|
22
36
|
export type SniConnectRequiredBodyMethod = 'POST' | 'PUT' | 'PATCH';
|
|
23
37
|
export type SniConnectOptionalBodyMethod = 'DELETE' | 'OPTIONS';
|
|
@@ -53,6 +67,7 @@ export type SniConnectDebugSnapshot = {
|
|
|
53
67
|
};
|
|
54
68
|
export interface Spec extends TurboModule {
|
|
55
69
|
request(config: NativeSniConnectRequest): Promise<SniConnectResponse>;
|
|
70
|
+
uploadFile(config: NativeSniConnectUploadFileRequest): Promise<SniConnectResponse>;
|
|
56
71
|
cancelRequest(requestId: string): Promise<{
|
|
57
72
|
success: boolean;
|
|
58
73
|
}>;
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { type SniConnectDebugSnapshot, type SniConnectDebugTarget, type SniConnectRequest, type SniConnectResponse } from './NativeSniConnect';
|
|
1
|
+
import { type SniConnectDebugSnapshot, type SniConnectDebugTarget, type SniConnectRequest, type SniConnectResponse, type SniConnectUploadFileRequest } from './NativeSniConnect';
|
|
2
2
|
export declare function request(config: SniConnectRequest): Promise<SniConnectResponse>;
|
|
3
|
+
export declare function isUploadFileSupported(): boolean;
|
|
4
|
+
export declare function uploadFile(config: SniConnectUploadFileRequest): Promise<SniConnectResponse>;
|
|
3
5
|
export declare function cancelRequest(requestId: string): Promise<{
|
|
4
6
|
success: boolean;
|
|
5
7
|
}>;
|
|
@@ -11,5 +13,5 @@ export declare function clearDNSCache(): Promise<{
|
|
|
11
13
|
}>;
|
|
12
14
|
export declare function getDebugSnapshot(target: SniConnectDebugTarget): Promise<SniConnectDebugSnapshot>;
|
|
13
15
|
export declare function isProxyActiveForUrl(url: string): Promise<boolean>;
|
|
14
|
-
export type { SniConnectBodylessMethod, SniConnectDebugSnapshot, SniConnectDebugTarget, SniConnectMethod, SniConnectOptionalBodyMethod, SniConnectRequest, SniConnectRequiredBodyMethod, SniConnectResponse, } from './NativeSniConnect';
|
|
16
|
+
export type { SniConnectBodylessMethod, SniConnectDebugSnapshot, SniConnectDebugTarget, SniConnectMethod, SniConnectOptionalBodyMethod, SniConnectRequest, SniConnectRequiredBodyMethod, SniConnectResponse, SniConnectUploadFileMethod, SniConnectUploadFileRequest, } from './NativeSniConnect';
|
|
15
17
|
//# sourceMappingURL=index.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@onekeyfe/react-native-sni-connect",
|
|
3
|
-
"version": "6.7.0-
|
|
3
|
+
"version": "6.7.0-60",
|
|
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",
|
|
@@ -65,11 +65,11 @@
|
|
|
65
65
|
"@eslint/compat": "^1.3.2",
|
|
66
66
|
"@eslint/eslintrc": "^3.3.1",
|
|
67
67
|
"@eslint/js": "^9.35.0",
|
|
68
|
-
"@react-native/babel-preset": "0.
|
|
69
|
-
"@react-native/eslint-config": "0.
|
|
68
|
+
"@react-native/babel-preset": "0.88.0",
|
|
69
|
+
"@react-native/eslint-config": "0.88.0",
|
|
70
70
|
"@release-it/conventional-changelog": "^10.0.1",
|
|
71
71
|
"@types/jest": "^29.5.14",
|
|
72
|
-
"@types/react": "^19.
|
|
72
|
+
"@types/react": "^19.3.0",
|
|
73
73
|
"commitlint": "^19.8.1",
|
|
74
74
|
"del-cli": "^6.0.0",
|
|
75
75
|
"eslint": "^9.35.0",
|
|
@@ -78,8 +78,8 @@
|
|
|
78
78
|
"jest": "^29.7.0",
|
|
79
79
|
"lefthook": "^2.0.3",
|
|
80
80
|
"prettier": "^2.8.8",
|
|
81
|
-
"react": "19.
|
|
82
|
-
"react-native": "patch:react-native@npm%3A0.
|
|
81
|
+
"react": "19.3.0",
|
|
82
|
+
"react-native": "patch:react-native@npm%3A0.88.0#~/.yarn/patches/react-native-npm-0.88.0-60c6201dd2.patch",
|
|
83
83
|
"react-native-builder-bob": "^0.40.17",
|
|
84
84
|
"release-it": "^19.0.4",
|
|
85
85
|
"turbo": "^2.5.6",
|
|
@@ -128,7 +128,7 @@
|
|
|
128
128
|
"useTabs": false
|
|
129
129
|
},
|
|
130
130
|
"jest": {
|
|
131
|
-
"preset": "react-native",
|
|
131
|
+
"preset": "@react-native/jest-preset",
|
|
132
132
|
"modulePathIgnorePatterns": [
|
|
133
133
|
"<rootDir>/example/node_modules",
|
|
134
134
|
"<rootDir>/lib/"
|
package/src/NativeSniConnect.ts
CHANGED
|
@@ -28,6 +28,23 @@ type NativeSniConnectRequest = SniConnectRequestBase & {
|
|
|
28
28
|
body?: string | null;
|
|
29
29
|
};
|
|
30
30
|
|
|
31
|
+
type NativeSniConnectUploadFileRequest = SniConnectRequestBase & {
|
|
32
|
+
method: string;
|
|
33
|
+
filePath: string;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export type SniConnectUploadFileMethod = 'POST' | 'PUT';
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Sends the raw bytes of an app-sandbox file as the request body over the same
|
|
40
|
+
* pinned-IP/SNI transport as `request()`. Set `content-type` in `headers`.
|
|
41
|
+
*/
|
|
42
|
+
export type SniConnectUploadFileRequest = SniConnectRequestBase & {
|
|
43
|
+
method: SniConnectUploadFileMethod;
|
|
44
|
+
/** Absolute path or `file://` URL inside the app sandbox, at most 20 MiB. */
|
|
45
|
+
filePath: string;
|
|
46
|
+
};
|
|
47
|
+
|
|
31
48
|
export type SniConnectBodylessMethod = 'GET' | 'HEAD';
|
|
32
49
|
export type SniConnectRequiredBodyMethod = 'POST' | 'PUT' | 'PATCH';
|
|
33
50
|
export type SniConnectOptionalBodyMethod = 'DELETE' | 'OPTIONS';
|
|
@@ -74,6 +91,9 @@ export type SniConnectDebugSnapshot = {
|
|
|
74
91
|
|
|
75
92
|
export interface Spec extends TurboModule {
|
|
76
93
|
request(config: NativeSniConnectRequest): Promise<SniConnectResponse>;
|
|
94
|
+
uploadFile(
|
|
95
|
+
config: NativeSniConnectUploadFileRequest
|
|
96
|
+
): Promise<SniConnectResponse>;
|
|
77
97
|
cancelRequest(requestId: string): Promise<{ success: boolean }>;
|
|
78
98
|
cancelAllRequests(): Promise<{ success: boolean }>;
|
|
79
99
|
clearDNSCache(): Promise<{ success: boolean }>;
|
package/src/index.tsx
CHANGED
|
@@ -3,6 +3,7 @@ import NativeSniConnect, {
|
|
|
3
3
|
type SniConnectDebugTarget,
|
|
4
4
|
type SniConnectRequest,
|
|
5
5
|
type SniConnectResponse,
|
|
6
|
+
type SniConnectUploadFileRequest,
|
|
6
7
|
} from './NativeSniConnect';
|
|
7
8
|
|
|
8
9
|
export function request(
|
|
@@ -11,6 +12,21 @@ export function request(
|
|
|
11
12
|
return NativeSniConnect.request(config);
|
|
12
13
|
}
|
|
13
14
|
|
|
15
|
+
export function isUploadFileSupported(): boolean {
|
|
16
|
+
return typeof NativeSniConnect.uploadFile === 'function';
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function uploadFile(
|
|
20
|
+
config: SniConnectUploadFileRequest
|
|
21
|
+
): Promise<SniConnectResponse> {
|
|
22
|
+
if (!isUploadFileSupported()) {
|
|
23
|
+
throw Object.assign(new Error('Native SNI file upload is not supported'), {
|
|
24
|
+
code: 'SNI_UNSUPPORTED',
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
return NativeSniConnect.uploadFile(config);
|
|
28
|
+
}
|
|
29
|
+
|
|
14
30
|
export function cancelRequest(
|
|
15
31
|
requestId: string
|
|
16
32
|
): Promise<{ success: boolean }> {
|
|
@@ -44,4 +60,6 @@ export type {
|
|
|
44
60
|
SniConnectRequest,
|
|
45
61
|
SniConnectRequiredBodyMethod,
|
|
46
62
|
SniConnectResponse,
|
|
63
|
+
SniConnectUploadFileMethod,
|
|
64
|
+
SniConnectUploadFileRequest,
|
|
47
65
|
} from './NativeSniConnect';
|