@mobileinspect/react-native 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/MobileInspectReactNative.podspec +27 -0
- package/README.md +51 -2
- package/android/build.gradle +79 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/java/com/mobileinspect/reactnative/MobileInspectModule.kt +36 -0
- package/android/src/main/java/com/mobileinspect/reactnative/MobileInspectPackage.kt +52 -0
- package/ios/MobileInspectCore/ConsoleCapture.swift +113 -0
- package/ios/MobileInspectCore/HARExporter.swift +72 -0
- package/ios/MobileInspectCore/InspectorCore.swift +173 -0
- package/ios/MobileInspectCore/InspectorDatabase.swift +337 -0
- package/ios/MobileInspectCore/InspectorPresenter.swift +74 -0
- package/ios/MobileInspectCore/InspectorRootView.swift +167 -0
- package/ios/MobileInspectCore/InspectorViewModel.swift +80 -0
- package/ios/MobileInspectCore/MobileInspect.swift +78 -0
- package/ios/MobileInspectCore/MobileInspectConfig.swift +63 -0
- package/ios/MobileInspectCore/MobileInspectURLProtocol.swift +225 -0
- package/ios/MobileInspectCore/Models.swift +96 -0
- package/ios/MobileInspectCore/NetworkDetailView.swift +204 -0
- package/ios/MobileInspectCore/Redactor.swift +87 -0
- package/ios/MobileInspectCore/SessionExporter.swift +70 -0
- package/ios/MobileInspectCore/UISupport.swift +86 -0
- package/ios/MobileInspectCore/URLSessionSwizzler.swift +55 -0
- package/ios/MobileInspectCore/ZipWriter.swift +75 -0
- package/ios/MobileInspectModule.mm +85 -0
- package/ios/PrivacyInfo.xcprivacy +23 -0
- package/lib/NativeMobileInspect.d.ts +10 -0
- package/lib/NativeMobileInspect.js +2 -0
- package/lib/index.d.ts +38 -0
- package/lib/index.js +102 -0
- package/package.json +71 -4
- package/scripts/sync-native.js +41 -0
- package/src/NativeMobileInspect.ts +12 -0
- package/src/index.ts +117 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
#if DEBUG
|
|
2
|
+
import Foundation
|
|
3
|
+
|
|
4
|
+
/// Public entry point. Link `MobileInspect` in Debug builds and `MobileInspectNoOp` in Release.
|
|
5
|
+
@objcMembers public final class MobileInspect: NSObject, @unchecked Sendable {
|
|
6
|
+
public static let sdkVersion = "0.1.0"
|
|
7
|
+
|
|
8
|
+
private static let reactNativeActive = Locked(false)
|
|
9
|
+
|
|
10
|
+
private override init() { super.init() }
|
|
11
|
+
|
|
12
|
+
/// Starts capture and, if configured, shake-to-open. Calling it again replaces the configuration.
|
|
13
|
+
public static func start(config: MobileInspectConfig = MobileInspectConfig()) {
|
|
14
|
+
guard config.enabled else {
|
|
15
|
+
CoreHolder.set(nil)
|
|
16
|
+
return
|
|
17
|
+
}
|
|
18
|
+
let db = InspectorDatabase(maxNetworkRecords: config.maxNetworkRecords, maxLogRecords: config.maxLogRecords)
|
|
19
|
+
CoreHolder.set(InspectorCore(config: config, database: db))
|
|
20
|
+
|
|
21
|
+
URLSessionSwizzler.install()
|
|
22
|
+
ConsoleCapture.shared.start { level, line in
|
|
23
|
+
guard let core = CoreHolder.current else { return }
|
|
24
|
+
// RN already forwards JS console.* itself; skip the native echo to avoid duplicates.
|
|
25
|
+
if reactNativeActive.withLock({ $0 }), line.contains("com.facebook.react.JavaScript") { return }
|
|
26
|
+
core.recordLog(level: level, tag: nil, message: line, sourceLayer: SourceLayer.native)
|
|
27
|
+
}
|
|
28
|
+
#if canImport(UIKit)
|
|
29
|
+
if config.shakeToOpen {
|
|
30
|
+
Task { @MainActor in ShakeDetector.install() }
|
|
31
|
+
}
|
|
32
|
+
#endif
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// Objective-C / React Native entry point taking the config as a JSON string.
|
|
36
|
+
public static func start(withJSON json: String) {
|
|
37
|
+
start(config: MobileInspectConfig(json: json))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// Shows the inspector overlay.
|
|
41
|
+
public static func open() {
|
|
42
|
+
#if canImport(UIKit)
|
|
43
|
+
Task { @MainActor in
|
|
44
|
+
guard let core = CoreHolder.current else { return }
|
|
45
|
+
InspectorPresenter.open(core: core)
|
|
46
|
+
}
|
|
47
|
+
#endif
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// Hides the inspector overlay.
|
|
51
|
+
public static func close() {
|
|
52
|
+
#if canImport(UIKit)
|
|
53
|
+
Task { @MainActor in InspectorPresenter.close() }
|
|
54
|
+
#endif
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/// Deletes all captured network calls and console logs.
|
|
58
|
+
public static func clearAll() {
|
|
59
|
+
CoreHolder.current?.database.clearAll()
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/// Used by the React Native bridge: makes `configuration` tag its traffic as `react-native`.
|
|
63
|
+
/// Pass the configuration React Native's networking will use (see `RCTSetCustomNSURLSessionConfigurationProvider`).
|
|
64
|
+
@objc(injectReactNativeCaptureInto:)
|
|
65
|
+
public static func injectReactNativeCapture(into configuration: URLSessionConfiguration) {
|
|
66
|
+
var classes = (configuration.protocolClasses ?? []).filter { $0 != ReactNativeURLProtocol.self }
|
|
67
|
+
classes.insert(ReactNativeURLProtocol.self, at: 0)
|
|
68
|
+
configuration.protocolClasses = classes
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/// Used by the React Native bridge to record a JS `console.*` call.
|
|
72
|
+
public static func logConsoleMessage(level: String, tag: String, message: String) {
|
|
73
|
+
reactNativeActive.withLock { $0 = true }
|
|
74
|
+
CoreHolder.current?.recordLog(level: level, tag: tag.isEmpty ? nil : tag, message: message, sourceLayer: SourceLayer.reactNative)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
#endif
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
#if DEBUG
|
|
2
|
+
import Foundation
|
|
3
|
+
|
|
4
|
+
/// Runtime configuration. Defaults follow the product spec (FR-1).
|
|
5
|
+
public struct MobileInspectConfig: Sendable, Equatable {
|
|
6
|
+
public static let defaultRedactedHeaders = ["Authorization", "Cookie", "Set-Cookie", "X-Api-Key"]
|
|
7
|
+
public static let defaultRedactedBodyKeys = ["password", "token", "secret", "access_token", "refresh_token"]
|
|
8
|
+
|
|
9
|
+
public var enabled: Bool
|
|
10
|
+
public var shakeToOpen: Bool
|
|
11
|
+
public var maxNetworkRecords: Int
|
|
12
|
+
public var maxLogRecords: Int
|
|
13
|
+
public var maxBodySizeBytes: Int
|
|
14
|
+
public var redactedHeaders: [String]
|
|
15
|
+
public var redactedBodyKeys: [String]
|
|
16
|
+
public var ignoredHosts: [String]
|
|
17
|
+
|
|
18
|
+
public init(
|
|
19
|
+
enabled: Bool = MobileInspectConfig.defaultEnabled,
|
|
20
|
+
shakeToOpen: Bool = true,
|
|
21
|
+
maxNetworkRecords: Int = 500,
|
|
22
|
+
maxLogRecords: Int = 5000,
|
|
23
|
+
maxBodySizeBytes: Int = 262_144,
|
|
24
|
+
redactedHeaders: [String] = MobileInspectConfig.defaultRedactedHeaders,
|
|
25
|
+
redactedBodyKeys: [String] = MobileInspectConfig.defaultRedactedBodyKeys,
|
|
26
|
+
ignoredHosts: [String] = []
|
|
27
|
+
) {
|
|
28
|
+
self.enabled = enabled
|
|
29
|
+
self.shakeToOpen = shakeToOpen
|
|
30
|
+
self.maxNetworkRecords = max(1, maxNetworkRecords)
|
|
31
|
+
self.maxLogRecords = max(1, maxLogRecords)
|
|
32
|
+
self.maxBodySizeBytes = max(0, maxBodySizeBytes)
|
|
33
|
+
self.redactedHeaders = redactedHeaders
|
|
34
|
+
self.redactedBodyKeys = redactedBodyKeys
|
|
35
|
+
self.ignoredHosts = ignoredHosts
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
#if DEBUG
|
|
39
|
+
public static let defaultEnabled = true
|
|
40
|
+
#else
|
|
41
|
+
public static let defaultEnabled = false
|
|
42
|
+
#endif
|
|
43
|
+
|
|
44
|
+
/// Builds a config from the JSON string sent by the React Native layer.
|
|
45
|
+
/// Unknown or missing keys fall back to defaults.
|
|
46
|
+
public init(json: String) {
|
|
47
|
+
var cfg = MobileInspectConfig()
|
|
48
|
+
if let data = json.data(using: .utf8),
|
|
49
|
+
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
|
|
50
|
+
if let v = obj["enabled"] as? Bool { cfg.enabled = v }
|
|
51
|
+
if let v = obj["shakeToOpen"] as? Bool { cfg.shakeToOpen = v }
|
|
52
|
+
if let v = (obj["maxNetworkRecords"] as? NSNumber)?.intValue { cfg.maxNetworkRecords = max(1, v) }
|
|
53
|
+
if let v = (obj["maxLogRecords"] as? NSNumber)?.intValue { cfg.maxLogRecords = max(1, v) }
|
|
54
|
+
if let v = (obj["maxBodySizeBytes"] as? NSNumber)?.intValue { cfg.maxBodySizeBytes = max(0, v) }
|
|
55
|
+
if let v = obj["redactedHeaders"] as? [String] { cfg.redactedHeaders = v }
|
|
56
|
+
if let v = obj["redactedBodyKeys"] as? [String] { cfg.redactedBodyKeys = v }
|
|
57
|
+
if let v = obj["ignoredHosts"] as? [String] { cfg.ignoredHosts = v }
|
|
58
|
+
}
|
|
59
|
+
self = cfg
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
#endif
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
#if DEBUG
|
|
2
|
+
import Foundation
|
|
3
|
+
|
|
4
|
+
/// Forwards an auth-challenge decision made by the host session back to our internal task.
|
|
5
|
+
private final class ChallengeSender: NSObject, URLAuthenticationChallengeSender, @unchecked Sendable {
|
|
6
|
+
private let completion: @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
|
|
7
|
+
init(completion: @escaping @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
|
|
8
|
+
self.completion = completion
|
|
9
|
+
}
|
|
10
|
+
func use(_ credential: URLCredential, for challenge: URLAuthenticationChallenge) { completion(.useCredential, credential) }
|
|
11
|
+
func continueWithoutCredential(for challenge: URLAuthenticationChallenge) { completion(.useCredential, nil) }
|
|
12
|
+
func cancel(_ challenge: URLAuthenticationChallenge) { completion(.cancelAuthenticationChallenge, nil) }
|
|
13
|
+
func performDefaultHandling(for challenge: URLAuthenticationChallenge) { completion(.performDefaultHandling, nil) }
|
|
14
|
+
func rejectProtectionSpaceAndContinue(with challenge: URLAuthenticationChallenge) { completion(.rejectProtectionSpace, nil) }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/// Records HTTP(S) traffic (FR-2). Requests are re-issued on an internal session. Responses stream straight to the
|
|
18
|
+
/// host client; only up to `maxBodySizeBytes` of textual bodies are retained, and binary bodies are only counted.
|
|
19
|
+
/// Auth challenges are relayed to the host session so custom TLS pinning keeps working.
|
|
20
|
+
class MobileInspectURLProtocol: URLProtocol, URLSessionDataDelegate, @unchecked Sendable {
|
|
21
|
+
static let handledKey = "MobileInspectHandled"
|
|
22
|
+
|
|
23
|
+
/// Value stored in `source_layer`. Subclasses tag traffic from other stacks (see `ReactNativeURLProtocol`).
|
|
24
|
+
class var sourceLayer: String { SourceLayer.native }
|
|
25
|
+
|
|
26
|
+
private var internalSession: URLSession?
|
|
27
|
+
private var internalTask: URLSessionDataTask?
|
|
28
|
+
private var startTime = Date()
|
|
29
|
+
private var response: HTTPURLResponse?
|
|
30
|
+
private var responseData = Data()
|
|
31
|
+
private var responseSize: Int64 = 0
|
|
32
|
+
private var requestBody: Data?
|
|
33
|
+
private var captureLimit = 0
|
|
34
|
+
private var finished = false
|
|
35
|
+
private var recordedID: String?
|
|
36
|
+
private var timings: Timings?
|
|
37
|
+
|
|
38
|
+
// MARK: URLProtocol
|
|
39
|
+
|
|
40
|
+
override class func canInit(with request: URLRequest) -> Bool {
|
|
41
|
+
guard let core = CoreHolder.current, core.config.enabled else { return false }
|
|
42
|
+
guard let scheme = request.url?.scheme?.lowercased(), scheme == "http" || scheme == "https" else { return false }
|
|
43
|
+
if URLProtocol.property(forKey: handledKey, in: request) != nil { return false }
|
|
44
|
+
if core.isIgnored(host: request.url?.host) { return false }
|
|
45
|
+
return true
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
|
49
|
+
|
|
50
|
+
override func startLoading() {
|
|
51
|
+
startTime = Date()
|
|
52
|
+
guard let core = CoreHolder.current else {
|
|
53
|
+
client?.urlProtocol(self, didFailWithError: URLError(.cancelled))
|
|
54
|
+
return
|
|
55
|
+
}
|
|
56
|
+
captureLimit = core.config.maxBodySizeBytes + 1
|
|
57
|
+
|
|
58
|
+
guard let mutable = (request as NSURLRequest).mutableCopy() as? NSMutableURLRequest else { return }
|
|
59
|
+
URLProtocol.setProperty(true, forKey: Self.handledKey, in: mutable)
|
|
60
|
+
|
|
61
|
+
// URLSession hands bodies to protocols as streams. Read it once so we can record and forward it.
|
|
62
|
+
var body = request.httpBody
|
|
63
|
+
if body == nil, let stream = request.httpBodyStream {
|
|
64
|
+
body = Self.read(stream)
|
|
65
|
+
mutable.httpBodyStream = nil
|
|
66
|
+
mutable.httpBody = body
|
|
67
|
+
}
|
|
68
|
+
requestBody = body
|
|
69
|
+
|
|
70
|
+
let config = URLSessionConfiguration.ephemeral
|
|
71
|
+
config.protocolClasses = (config.protocolClasses ?? []).filter { !($0 is MobileInspectURLProtocol.Type) }
|
|
72
|
+
config.urlCache = nil
|
|
73
|
+
config.requestCachePolicy = .reloadIgnoringLocalCacheData
|
|
74
|
+
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
|
|
75
|
+
internalSession = session
|
|
76
|
+
let t = session.dataTask(with: mutable as URLRequest)
|
|
77
|
+
internalTask = t
|
|
78
|
+
t.resume()
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
override func stopLoading() {
|
|
82
|
+
internalTask?.cancel()
|
|
83
|
+
if !finished { finished = true; record(error: URLError(.cancelled)) }
|
|
84
|
+
internalSession?.invalidateAndCancel()
|
|
85
|
+
internalSession = nil
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// MARK: URLSessionDataDelegate
|
|
89
|
+
|
|
90
|
+
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,
|
|
91
|
+
completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
|
|
92
|
+
self.response = response as? HTTPURLResponse
|
|
93
|
+
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed)
|
|
94
|
+
completionHandler(.allow)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
|
|
98
|
+
client?.urlProtocol(self, didLoad: data)
|
|
99
|
+
responseSize += Int64(data.count)
|
|
100
|
+
let binary = BodyCapture.isBinary(contentType: response?.value(forHTTPHeaderField: "Content-Type"))
|
|
101
|
+
if !binary, responseData.count < captureLimit {
|
|
102
|
+
responseData.append(data.prefix(captureLimit - responseData.count))
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
|
107
|
+
guard !finished else { return }
|
|
108
|
+
finished = true
|
|
109
|
+
// Record first so the row is queued before the caller sees completion.
|
|
110
|
+
record(error: error)
|
|
111
|
+
if let error {
|
|
112
|
+
client?.urlProtocol(self, didFailWithError: error)
|
|
113
|
+
} else {
|
|
114
|
+
client?.urlProtocolDidFinishLoading(self)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
|
|
119
|
+
guard let t = Self.timings(from: metrics) else { return }
|
|
120
|
+
timings = t
|
|
121
|
+
// Metrics can arrive after the row was written (e.g. redirect hops); patch it in place.
|
|
122
|
+
if let id = recordedID { CoreHolder.current?.updateTimings(id: id, t) }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
static func timings(from metrics: URLSessionTaskMetrics) -> Timings? {
|
|
126
|
+
guard let m = metrics.transactionMetrics.last(where: { $0.resourceFetchType == .networkLoad }) ?? metrics.transactionMetrics.last else { return nil }
|
|
127
|
+
func ms(_ a: Date?, _ b: Date?) -> Double {
|
|
128
|
+
guard let a, let b else { return -1 }
|
|
129
|
+
return Timings.round(b.timeIntervalSince(a) * 1000)
|
|
130
|
+
}
|
|
131
|
+
var t = Timings()
|
|
132
|
+
let firstNetwork = m.domainLookupStartDate ?? m.connectStartDate ?? m.requestStartDate
|
|
133
|
+
t.blocked = ms(m.fetchStartDate, firstNetwork)
|
|
134
|
+
t.dns = ms(m.domainLookupStartDate, m.domainLookupEndDate)
|
|
135
|
+
t.connect = ms(m.connectStartDate, m.connectEndDate)
|
|
136
|
+
t.ssl = ms(m.secureConnectionStartDate, m.secureConnectionEndDate)
|
|
137
|
+
t.send = max(0, ms(m.requestStartDate, m.requestEndDate))
|
|
138
|
+
t.wait = max(0, ms(m.requestEndDate, m.responseStartDate))
|
|
139
|
+
t.receive = max(0, ms(m.responseStartDate, m.responseEndDate))
|
|
140
|
+
return t
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
|
|
144
|
+
newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {
|
|
145
|
+
// Record the redirect hop itself, then let the host session follow it (which comes back through us).
|
|
146
|
+
self.response = response
|
|
147
|
+
finished = true
|
|
148
|
+
record(error: nil)
|
|
149
|
+
var clean = request
|
|
150
|
+
// Strip our marker so the host-issued follow-up request is captured again.
|
|
151
|
+
let m = (clean as NSURLRequest).mutableCopy() as? NSMutableURLRequest
|
|
152
|
+
if let m { URLProtocol.removeProperty(forKey: Self.handledKey, in: m); clean = m as URLRequest }
|
|
153
|
+
client?.urlProtocol(self, wasRedirectedTo: clean, redirectResponse: response)
|
|
154
|
+
completionHandler(nil)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge,
|
|
158
|
+
completionHandler: @escaping @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
|
|
159
|
+
guard let client else { completionHandler(.performDefaultHandling, nil); return }
|
|
160
|
+
let sender = ChallengeSender(completion: completionHandler)
|
|
161
|
+
let forwarded = URLAuthenticationChallenge(authenticationChallenge: challenge, sender: sender)
|
|
162
|
+
client.urlProtocol(self, didReceive: forwarded)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// MARK: Recording
|
|
166
|
+
|
|
167
|
+
private func record(error: Error?) {
|
|
168
|
+
guard let core = CoreHolder.current else { return }
|
|
169
|
+
let end = Date()
|
|
170
|
+
let req = request
|
|
171
|
+
let reqType = req.value(forHTTPHeaderField: "Content-Type")
|
|
172
|
+
let limit = core.config.maxBodySizeBytes
|
|
173
|
+
let reqData = requestBody.map { $0.count > limit ? $0.prefix(limit + 1) : $0 }
|
|
174
|
+
let resType = response?.value(forHTTPHeaderField: "Content-Type") ?? response?.mimeType
|
|
175
|
+
|
|
176
|
+
var reqHeaders = req.allHTTPHeaderFields ?? [:]
|
|
177
|
+
if let cookies = req.url.flatMap({ HTTPCookieStorage.shared.cookies(for: $0) }), req.httpShouldHandleCookies,
|
|
178
|
+
reqHeaders["Cookie"] == nil, !cookies.isEmpty {
|
|
179
|
+
reqHeaders["Cookie"] = HTTPCookie.requestHeaderFields(with: cookies)["Cookie"]
|
|
180
|
+
}
|
|
181
|
+
var resHeaders: [String: String] = [:]
|
|
182
|
+
response?.allHeaderFields.forEach { k, v in resHeaders["\(k)"] = "\(v)" }
|
|
183
|
+
|
|
184
|
+
let draft = NetworkDraft(
|
|
185
|
+
timestampStart: Int64(startTime.timeIntervalSince1970 * 1000),
|
|
186
|
+
durationMs: Int64(end.timeIntervalSince(startTime) * 1000),
|
|
187
|
+
method: req.httpMethod ?? "GET",
|
|
188
|
+
url: req.url,
|
|
189
|
+
statusCode: response?.statusCode ?? 0,
|
|
190
|
+
statusMessage: response.map { HTTPURLResponse.localizedString(forStatusCode: $0.statusCode) },
|
|
191
|
+
requestHeaders: reqHeaders,
|
|
192
|
+
requestBody: BodyCapture.make(data: reqData, totalSize: Int64(requestBody?.count ?? 0), contentType: reqType, maxBytes: limit),
|
|
193
|
+
requestContentType: reqType,
|
|
194
|
+
responseHeaders: resHeaders,
|
|
195
|
+
responseBody: BodyCapture.make(data: responseData, totalSize: responseSize, contentType: resType, maxBytes: limit),
|
|
196
|
+
responseContentType: resType,
|
|
197
|
+
errorDescription: error?.localizedDescription,
|
|
198
|
+
sourceLayer: type(of: self).sourceLayer,
|
|
199
|
+
timings: timings
|
|
200
|
+
)
|
|
201
|
+
recordedID = draft.id
|
|
202
|
+
core.record(draft)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
private static func read(_ stream: InputStream) -> Data {
|
|
206
|
+
var data = Data()
|
|
207
|
+
stream.open()
|
|
208
|
+
defer { stream.close() }
|
|
209
|
+
var buffer = [UInt8](repeating: 0, count: 16 * 1024)
|
|
210
|
+
while stream.hasBytesAvailable {
|
|
211
|
+
let n = stream.read(&buffer, maxLength: buffer.count)
|
|
212
|
+
if n <= 0 { break }
|
|
213
|
+
data.append(buffer, count: n)
|
|
214
|
+
}
|
|
215
|
+
return data
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/// Same capture, tagged `react-native`. The React Native bridge puts it first in the session configuration
|
|
220
|
+
/// that React Native's networking uses, so JS `fetch`/XHR traffic is labelled correctly.
|
|
221
|
+
final class ReactNativeURLProtocol: MobileInspectURLProtocol, @unchecked Sendable {
|
|
222
|
+
override class var sourceLayer: String { SourceLayer.reactNative }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
#endif
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
#if DEBUG
|
|
2
|
+
import Foundation
|
|
3
|
+
|
|
4
|
+
/// One persisted HTTP exchange. Mirrors the `network_calls` table.
|
|
5
|
+
public struct NetworkCall: Sendable, Identifiable, Hashable {
|
|
6
|
+
public var id: String
|
|
7
|
+
public var sessionId: String
|
|
8
|
+
public var timestampStart: Int64
|
|
9
|
+
public var durationMs: Int64
|
|
10
|
+
public var method: String
|
|
11
|
+
public var url: String
|
|
12
|
+
public var host: String
|
|
13
|
+
public var path: String
|
|
14
|
+
public var statusCode: Int
|
|
15
|
+
public var statusMessage: String?
|
|
16
|
+
public var requestHeaders: String?
|
|
17
|
+
public var requestBody: String?
|
|
18
|
+
public var requestContentType: String?
|
|
19
|
+
public var requestSizeBytes: Int64
|
|
20
|
+
public var responseHeaders: String?
|
|
21
|
+
public var responseBody: String?
|
|
22
|
+
public var responseContentType: String?
|
|
23
|
+
public var responseSizeBytes: Int64
|
|
24
|
+
public var errorDescription: String?
|
|
25
|
+
public var sourceLayer: String
|
|
26
|
+
/// HAR-style timing breakdown as JSON (see `Timings`), nil when not measured.
|
|
27
|
+
public var timings: String? = nil
|
|
28
|
+
|
|
29
|
+
public var isError: Bool { statusCode == 0 || statusCode >= 400 }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/// Phase durations in milliseconds, using HAR 1.2 semantics: `connect` includes `ssl`; -1 means not applicable
|
|
33
|
+
/// (for example a reused connection has no dns/connect/ssl).
|
|
34
|
+
public struct Timings: Sendable, Equatable, Codable {
|
|
35
|
+
public var blocked: Double = -1
|
|
36
|
+
public var dns: Double = -1
|
|
37
|
+
public var connect: Double = -1
|
|
38
|
+
public var ssl: Double = -1
|
|
39
|
+
public var send: Double = 0
|
|
40
|
+
public var wait: Double = 0
|
|
41
|
+
public var receive: Double = 0
|
|
42
|
+
|
|
43
|
+
public init() {}
|
|
44
|
+
|
|
45
|
+
/// Ordered phases for display. `ssl` is shown separately, so `connect` is shown without it.
|
|
46
|
+
var phases: [(name: String, ms: Double)] {
|
|
47
|
+
let tcp = connect >= 0 ? max(0, connect - max(0, ssl)) : -1
|
|
48
|
+
return [("Blocked", blocked), ("DNS", dns), ("Connect", tcp), ("TLS", ssl), ("Send", send), ("Wait", wait), ("Receive", receive)]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
func json() -> String {
|
|
52
|
+
let enc = JSONEncoder()
|
|
53
|
+
enc.outputFormatting = [.sortedKeys]
|
|
54
|
+
return (try? enc.encode(self)).flatMap { String(data: $0, encoding: .utf8) } ?? "{}"
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
static func decode(_ json: String?) -> Timings? {
|
|
58
|
+
guard let json, let data = json.data(using: .utf8) else { return nil }
|
|
59
|
+
return try? JSONDecoder().decode(Timings.self, from: data)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
static func round(_ v: Double) -> Double { v < 0 ? -1 : (v * 10).rounded() / 10 }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/// One persisted console line. Mirrors the `console_logs` table.
|
|
66
|
+
public struct ConsoleLog: Sendable, Identifiable, Hashable {
|
|
67
|
+
public var id: String
|
|
68
|
+
public var sessionId: String
|
|
69
|
+
public var timestamp: Int64
|
|
70
|
+
public var level: String
|
|
71
|
+
public var tag: String?
|
|
72
|
+
public var message: String
|
|
73
|
+
public var sourceLayer: String
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
enum SourceLayer {
|
|
77
|
+
static let native = "native"
|
|
78
|
+
static let reactNative = "react-native"
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
enum JSONHelper {
|
|
82
|
+
static func encode(_ dict: [String: String]) -> String {
|
|
83
|
+
guard JSONSerialization.isValidJSONObject(dict),
|
|
84
|
+
let data = try? JSONSerialization.data(withJSONObject: dict, options: [.sortedKeys, .withoutEscapingSlashes]),
|
|
85
|
+
let s = String(data: data, encoding: .utf8) else { return "{}" }
|
|
86
|
+
return s
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
static func decodeHeaders(_ json: String?) -> [String: String] {
|
|
90
|
+
guard let json, let data = json.data(using: .utf8),
|
|
91
|
+
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: String] else { return [:] }
|
|
92
|
+
return obj
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
#endif
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
#if DEBUG
|
|
2
|
+
#if canImport(UIKit)
|
|
3
|
+
import SwiftUI
|
|
4
|
+
import UIKit
|
|
5
|
+
|
|
6
|
+
struct NetworkDetailView: View {
|
|
7
|
+
enum Section: String, CaseIterable, Identifiable {
|
|
8
|
+
case overview = "Overview", request = "Request", response = "Response"
|
|
9
|
+
var id: String { rawValue }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
let core: InspectorCore
|
|
13
|
+
let summary: NetworkCall
|
|
14
|
+
|
|
15
|
+
@State private var call: NetworkCall?
|
|
16
|
+
@State private var section: Section = .overview
|
|
17
|
+
@State private var rawBody = false
|
|
18
|
+
@State private var shareItem: ShareItem?
|
|
19
|
+
@State private var replayMessage: String?
|
|
20
|
+
@State private var image: UIImage?
|
|
21
|
+
|
|
22
|
+
private var current: NetworkCall { call ?? summary }
|
|
23
|
+
|
|
24
|
+
var body: some View {
|
|
25
|
+
VStack(spacing: 0) {
|
|
26
|
+
Picker("Section", selection: $section) {
|
|
27
|
+
ForEach(Section.allCases) { Text($0.rawValue).tag($0) }
|
|
28
|
+
}
|
|
29
|
+
.pickerStyle(.segmented)
|
|
30
|
+
.padding()
|
|
31
|
+
|
|
32
|
+
ScrollView {
|
|
33
|
+
VStack(alignment: .leading, spacing: 12) {
|
|
34
|
+
switch section {
|
|
35
|
+
case .overview: overview
|
|
36
|
+
case .request: payload(headers: current.requestHeaders, body: current.requestBody, type: current.requestContentType, isResponse: false)
|
|
37
|
+
case .response: payload(headers: current.responseHeaders, body: current.responseBody, type: current.responseContentType, isResponse: true)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
.padding(.horizontal)
|
|
41
|
+
.frame(maxWidth: .infinity, alignment: .leading)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
.navigationTitle("\(current.method) \(current.path)")
|
|
45
|
+
.navigationBarTitleDisplayMode(.inline)
|
|
46
|
+
.toolbar {
|
|
47
|
+
ToolbarItemGroup(placement: .navigationBarTrailing) {
|
|
48
|
+
Button("cURL") { UIPasteboard.general.string = CurlBuilder.curl(for: current); replayMessage = "cURL copied" }
|
|
49
|
+
Button { shareItem = ShareItem(items: [shareText()]) } label: { Image(systemName: "square.and.arrow.up") }
|
|
50
|
+
Button("Replay") { replay() }
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
.sheet(item: $shareItem) { ShareSheet(items: $0.items) }
|
|
54
|
+
.alert(item: Binding(get: { replayMessage.map { AlertText(text: $0) } }, set: { _ in replayMessage = nil })) {
|
|
55
|
+
Alert(title: Text($0.text))
|
|
56
|
+
}
|
|
57
|
+
.task {
|
|
58
|
+
call = await core.database.networkCall(id: summary.id)
|
|
59
|
+
await loadImageIfNeeded()
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// MARK: Sections
|
|
64
|
+
|
|
65
|
+
private var overview: some View {
|
|
66
|
+
VStack(alignment: .leading, spacing: 8) {
|
|
67
|
+
HStack {
|
|
68
|
+
Badge(text: current.statusCode == 0 ? "ERR" : "\(current.statusCode)", color: Palette.status(current.statusCode))
|
|
69
|
+
Text(current.statusMessage ?? "").foregroundColor(.secondary)
|
|
70
|
+
}
|
|
71
|
+
kv("URL", current.url)
|
|
72
|
+
kv("Method", current.method)
|
|
73
|
+
kv("Started", Format.time(current.timestampStart))
|
|
74
|
+
kv("Duration", "\(current.durationMs) ms")
|
|
75
|
+
kv("Request size", Format.bytes(current.requestSizeBytes))
|
|
76
|
+
kv("Response size", Format.bytes(current.responseSizeBytes))
|
|
77
|
+
kv("Source", current.sourceLayer)
|
|
78
|
+
if let e = current.errorDescription { kv("Error", e) }
|
|
79
|
+
if let t = Timings.decode(current.timings) {
|
|
80
|
+
TimingView(timings: t).padding(.top, 4)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
@ViewBuilder
|
|
86
|
+
private func payload(headers: String?, body: String?, type: String?, isResponse: Bool) -> some View {
|
|
87
|
+
Text("Headers").font(.headline)
|
|
88
|
+
let h = JSONHelper.decodeHeaders(headers)
|
|
89
|
+
if h.isEmpty {
|
|
90
|
+
Text("None").foregroundColor(.secondary)
|
|
91
|
+
} else {
|
|
92
|
+
ForEach(h.keys.sorted(), id: \.self) { k in
|
|
93
|
+
(Text(k + ": ").bold() + Text(h[k] ?? "")).font(.system(size: 12, design: .monospaced)).textSelection(.enabled)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if isResponse, let image {
|
|
97
|
+
Text("Preview").font(.headline)
|
|
98
|
+
Image(uiImage: image).resizable().scaledToFit().frame(maxHeight: 240)
|
|
99
|
+
}
|
|
100
|
+
HStack {
|
|
101
|
+
Text("Body").font(.headline)
|
|
102
|
+
Spacer()
|
|
103
|
+
if Format.pretty(json: body) != nil {
|
|
104
|
+
Picker("Mode", selection: $rawBody) {
|
|
105
|
+
Text("Pretty").tag(false); Text("Raw").tag(true)
|
|
106
|
+
}
|
|
107
|
+
.pickerStyle(.segmented).frame(width: 150)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if let body, !body.isEmpty {
|
|
111
|
+
Text(rawBody ? body : (Format.pretty(json: body) ?? body))
|
|
112
|
+
.font(.system(size: 12, design: .monospaced))
|
|
113
|
+
.textSelection(.enabled)
|
|
114
|
+
} else {
|
|
115
|
+
Text("Empty").foregroundColor(.secondary)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
private func kv(_ k: String, _ v: String) -> some View {
|
|
120
|
+
VStack(alignment: .leading, spacing: 2) {
|
|
121
|
+
Text(k).font(.caption).foregroundColor(.secondary)
|
|
122
|
+
Text(v).font(.system(size: 13, design: .monospaced)).textSelection(.enabled)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// MARK: Actions
|
|
127
|
+
|
|
128
|
+
private func shareText() -> String {
|
|
129
|
+
var s = "\(current.method) \(current.url)\nStatus: \(current.statusCode)\n\n"
|
|
130
|
+
s += CurlBuilder.curl(for: current)
|
|
131
|
+
if let b = current.responseBody { s += "\n\nResponse:\n" + b }
|
|
132
|
+
return s
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// Replays through the host app's own URLSession stack. Redacted header values are replayed as stored.
|
|
136
|
+
private func replay() {
|
|
137
|
+
guard let url = URL(string: current.url) else { return }
|
|
138
|
+
var req = URLRequest(url: url)
|
|
139
|
+
req.httpMethod = current.method
|
|
140
|
+
for (k, v) in JSONHelper.decodeHeaders(current.requestHeaders) { req.setValue(v, forHTTPHeaderField: k) }
|
|
141
|
+
if let b = current.requestBody, !b.hasPrefix("<Binary:") {
|
|
142
|
+
req.httpBody = Data(b.replacingOccurrences(of: "[TRUNCATED]", with: "").utf8)
|
|
143
|
+
}
|
|
144
|
+
Task {
|
|
145
|
+
do {
|
|
146
|
+
let (_, resp) = try await URLSession.shared.data(for: req)
|
|
147
|
+
replayMessage = "Replayed: HTTP \((resp as? HTTPURLResponse)?.statusCode ?? 0)"
|
|
148
|
+
} catch {
|
|
149
|
+
replayMessage = "Replay failed: \(error.localizedDescription)"
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/// Image bodies are not stored (spec: `<Binary: N bytes>`), so previews refetch the URL without being re-captured.
|
|
155
|
+
private func loadImageIfNeeded() async {
|
|
156
|
+
guard current.responseContentType?.lowercased().hasPrefix("image/") == true,
|
|
157
|
+
current.method == "GET", let url = URL(string: current.url) else { return }
|
|
158
|
+
let m = NSMutableURLRequest(url: url)
|
|
159
|
+
URLProtocol.setProperty(true, forKey: MobileInspectURLProtocol.handledKey, in: m)
|
|
160
|
+
if let (data, _) = try? await URLSession.shared.data(for: m as URLRequest) {
|
|
161
|
+
image = UIImage(data: data)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/// Waterfall-style breakdown: each phase as a bar offset by the phases before it.
|
|
167
|
+
struct TimingView: View {
|
|
168
|
+
let timings: Timings
|
|
169
|
+
|
|
170
|
+
var body: some View {
|
|
171
|
+
let phases = timings.phases
|
|
172
|
+
let total = max(1, phases.reduce(0) { $0 + max(0, $1.ms) })
|
|
173
|
+
VStack(alignment: .leading, spacing: 6) {
|
|
174
|
+
Text("Timing").font(.caption).foregroundColor(.secondary)
|
|
175
|
+
ForEach(Array(phases.enumerated()), id: \.offset) { index, phase in
|
|
176
|
+
let before = phases[..<index].reduce(0) { $0 + max(0, $1.ms) }
|
|
177
|
+
HStack(spacing: 8) {
|
|
178
|
+
Text(phase.name).font(.system(size: 12)).frame(width: 64, alignment: .leading)
|
|
179
|
+
GeometryReader { geo in
|
|
180
|
+
if phase.ms > 0 {
|
|
181
|
+
RoundedRectangle(cornerRadius: 2)
|
|
182
|
+
.fill(Palette.phase(phase.name))
|
|
183
|
+
.frame(width: max(2, geo.size.width * phase.ms / total))
|
|
184
|
+
.offset(x: geo.size.width * before / total)
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
.frame(height: 10)
|
|
188
|
+
Text(phase.ms < 0 ? "–" : String(format: "%.1f ms", phase.ms))
|
|
189
|
+
.font(.system(size: 12, design: .monospaced))
|
|
190
|
+
.foregroundColor(.secondary)
|
|
191
|
+
.frame(width: 76, alignment: .trailing)
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private struct AlertText: Identifiable {
|
|
199
|
+
let text: String
|
|
200
|
+
var id: String { text }
|
|
201
|
+
}
|
|
202
|
+
#endif
|
|
203
|
+
|
|
204
|
+
#endif
|