@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.
Files changed (34) hide show
  1. package/LICENSE +21 -0
  2. package/MobileInspectReactNative.podspec +27 -0
  3. package/README.md +51 -2
  4. package/android/build.gradle +79 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/com/mobileinspect/reactnative/MobileInspectModule.kt +36 -0
  7. package/android/src/main/java/com/mobileinspect/reactnative/MobileInspectPackage.kt +52 -0
  8. package/ios/MobileInspectCore/ConsoleCapture.swift +113 -0
  9. package/ios/MobileInspectCore/HARExporter.swift +72 -0
  10. package/ios/MobileInspectCore/InspectorCore.swift +173 -0
  11. package/ios/MobileInspectCore/InspectorDatabase.swift +337 -0
  12. package/ios/MobileInspectCore/InspectorPresenter.swift +74 -0
  13. package/ios/MobileInspectCore/InspectorRootView.swift +167 -0
  14. package/ios/MobileInspectCore/InspectorViewModel.swift +80 -0
  15. package/ios/MobileInspectCore/MobileInspect.swift +78 -0
  16. package/ios/MobileInspectCore/MobileInspectConfig.swift +63 -0
  17. package/ios/MobileInspectCore/MobileInspectURLProtocol.swift +225 -0
  18. package/ios/MobileInspectCore/Models.swift +96 -0
  19. package/ios/MobileInspectCore/NetworkDetailView.swift +204 -0
  20. package/ios/MobileInspectCore/Redactor.swift +87 -0
  21. package/ios/MobileInspectCore/SessionExporter.swift +70 -0
  22. package/ios/MobileInspectCore/UISupport.swift +86 -0
  23. package/ios/MobileInspectCore/URLSessionSwizzler.swift +55 -0
  24. package/ios/MobileInspectCore/ZipWriter.swift +75 -0
  25. package/ios/MobileInspectModule.mm +85 -0
  26. package/ios/PrivacyInfo.xcprivacy +23 -0
  27. package/lib/NativeMobileInspect.d.ts +10 -0
  28. package/lib/NativeMobileInspect.js +2 -0
  29. package/lib/index.d.ts +38 -0
  30. package/lib/index.js +102 -0
  31. package/package.json +71 -4
  32. package/scripts/sync-native.js +41 -0
  33. package/src/NativeMobileInspect.ts +12 -0
  34. package/src/index.ts +117 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MobileInspect contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,27 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "MobileInspectReactNative"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.homepage = package["homepage"]
10
+ s.license = package["license"]
11
+ s.authors = package["author"]
12
+
13
+ s.platforms = { :ios => "15.1" }
14
+ s.source = { :git => "https://github.com/mobileinspect/mobile-inspect.git", :tag => "v#{s.version}" }
15
+
16
+ # The podspec sits at the package root because React Native autolinking only discovers `*.podspec` there.
17
+ # ios/MobileInspectCore is a copy of ../ios/Sources/MobileInspect made by `npm run sync:native`
18
+ # (runs on prepack). Every file is wrapped in `#if DEBUG`, so Release builds compile it to nothing.
19
+ s.source_files = "ios/*.{h,m,mm}", "ios/MobileInspectCore/**/*.swift"
20
+ s.resource_bundles = { "MobileInspectPrivacy" => ["ios/PrivacyInfo.xcprivacy"] }
21
+
22
+ s.swift_version = "6.0"
23
+ s.libraries = "sqlite3"
24
+ s.pod_target_xcconfig = { "DEFINES_MODULE" => "YES" }
25
+
26
+ install_modules_dependencies(s)
27
+ end
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # @mobileinspect/react-native
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ On-device network and console inspector for React Native (New Architecture, RN 0.76+). It is a thin TurboModule over the MobileInspect native SDKs: capture, storage and the inspector UI are native.
4
+
5
+ - Captures `fetch`/XHR traffic (tagged `react-native`) and `console.log/info/warn/error/debug`.
6
+ - Opens with a device shake or `MobileInspect.open()`.
7
+ - Debug only: `enabled` defaults to `__DEV__`. On iOS the inspector is compiled only in Debug builds; on Android release builds link a no-op artifact.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install @mobileinspect/react-native
13
+ cd ios && pod install
14
+ ```
15
+
16
+ Autolinking handles the rest. The Android module pulls `io.github.mobileinspect:mobile-inspect` (debug) and `mobile-inspect-no-op` (release) from Maven Central.
17
+
18
+ ## Use
19
+
20
+ ```js
21
+ // index.js, before AppRegistry.registerComponent
22
+ import MobileInspect from '@mobileinspect/react-native';
23
+
24
+ MobileInspect.configure({
25
+ ignoredHosts: ['localhost', '127.0.0.1', '10.0.2.2'], // keep Metro out of the network tab
26
+ });
27
+
28
+ MobileInspect.open(); // show the inspector
29
+ MobileInspect.clearAll(); // delete captured data
30
+ ```
31
+
32
+ ## Config
33
+
34
+ | Option | Default |
35
+ |---|---|
36
+ | `enabled` | `__DEV__` |
37
+ | `shakeToOpen` | `true` |
38
+ | `maxNetworkRecords` | `500` |
39
+ | `maxLogRecords` | `5000` |
40
+ | `maxBodySizeBytes` | `262144` |
41
+ | `redactedHeaders` | `Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key` |
42
+ | `redactedBodyKeys` | `password`, `token`, `secret`, `access_token`, `refresh_token` |
43
+ | `ignoredHosts` | `[]` |
44
+
45
+ Sensitive values are masked as `***REDACTED***` before anything is stored.
46
+
47
+ ## Notes
48
+
49
+ - If your app installs its own `OkHttpClientFactory` (Android) or `RCTSetCustomNSURLSessionConfigurationProvider` (iOS), it replaces the one this package installs. Add `MobileInspect.okhttpInterceptor("react-native")` to your Android client to keep capture there.
50
+ - In debug builds a shake also opens the React Native Dev Menu.
51
+
52
+ Source and docs: https://github.com/mobileinspect/mobile-inspect
@@ -0,0 +1,79 @@
1
+ buildscript {
2
+ // Defaults used only when this module is built on its own. Inside an app the app's values win.
3
+ ext.MobileInspectDefaults = [
4
+ kotlinVersion : "2.2.0",
5
+ minSdkVersion : 24,
6
+ compileSdkVersion : 35,
7
+ targetSdkVersion : 35,
8
+ ]
9
+ ext.getExtOrDefault = { name ->
10
+ rootProject.ext.has(name) ? rootProject.ext.get(name) : MobileInspectDefaults[name]
11
+ }
12
+
13
+ repositories {
14
+ google()
15
+ mavenCentral()
16
+ }
17
+
18
+ if (project == rootProject) {
19
+ dependencies {
20
+ classpath "com.android.tools.build:gradle:8.13.0"
21
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}"
22
+ }
23
+ }
24
+ }
25
+
26
+ apply plugin: "com.android.library"
27
+ apply plugin: "kotlin-android"
28
+ apply plugin: "com.facebook.react"
29
+
30
+ android {
31
+ namespace "com.mobileinspect.reactnative"
32
+ compileSdkVersion getExtOrDefault("compileSdkVersion")
33
+
34
+ defaultConfig {
35
+ minSdkVersion getExtOrDefault("minSdkVersion")
36
+ targetSdkVersion getExtOrDefault("targetSdkVersion")
37
+ }
38
+
39
+ buildTypes {
40
+ release {
41
+ minifyEnabled false
42
+ }
43
+ }
44
+
45
+ compileOptions {
46
+ sourceCompatibility JavaVersion.VERSION_17
47
+ targetCompatibility JavaVersion.VERSION_17
48
+ }
49
+
50
+ kotlinOptions {
51
+ jvmTarget = "17"
52
+ }
53
+ }
54
+
55
+ repositories {
56
+ // Local publishing target of ../../android (`./gradlew publishToMavenLocal`), then Maven Central.
57
+ mavenLocal()
58
+ mavenCentral()
59
+ google()
60
+ }
61
+
62
+ // The native SDK is released with the same version as this npm package.
63
+ def mobileInspectVersion = new groovy.json.JsonSlurper().parse(file("../package.json")).version
64
+ // Must match GROUP in ../../android/gradle.properties.
65
+ def mobileInspectGroup = "io.github.mobileinspect"
66
+
67
+ dependencies {
68
+ implementation "com.facebook.react:react-android"
69
+
70
+ // Debug builds get the real inspector, release builds get the zero-overhead stub (same API).
71
+ debugImplementation "${mobileInspectGroup}:mobile-inspect:${mobileInspectVersion}"
72
+ releaseImplementation "${mobileInspectGroup}:mobile-inspect-no-op:${mobileInspectVersion}"
73
+ }
74
+
75
+ react {
76
+ jsRootDir = file("../src/")
77
+ libraryName = "MobileInspect"
78
+ codegenJavaPackageName = "com.mobileinspect.reactnative"
79
+ }
@@ -0,0 +1,2 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <manifest />
@@ -0,0 +1,36 @@
1
+ package com.mobileinspect.reactnative
2
+
3
+ import com.facebook.react.bridge.ReactApplicationContext
4
+ import com.facebook.react.module.annotations.ReactModule
5
+ import com.mobileinspect.MobileInspect
6
+
7
+ /** TurboModule bridging JS to the native MobileInspect Android SDK. Holds no storage or UI of its own. */
8
+ @ReactModule(name = MobileInspectModule.NAME)
9
+ class MobileInspectModule(private val reactContext: ReactApplicationContext) : NativeMobileInspectSpec(reactContext) {
10
+
11
+ override fun getName(): String = NAME
12
+
13
+ override fun configure(configJson: String) {
14
+ MobileInspect.initFromJson(reactContext.applicationContext, configJson)
15
+ }
16
+
17
+ override fun openInspector() {
18
+ MobileInspect.open(reactContext.currentActivity ?: reactContext.applicationContext)
19
+ }
20
+
21
+ override fun closeInspector() {
22
+ MobileInspect.close()
23
+ }
24
+
25
+ override fun clearAll() {
26
+ MobileInspect.clearAll()
27
+ }
28
+
29
+ override fun logConsoleMessage(level: String, tag: String, message: String) {
30
+ MobileInspect.logConsoleMessage(level, tag, message)
31
+ }
32
+
33
+ companion object {
34
+ const val NAME = "MobileInspectModule"
35
+ }
36
+ }
@@ -0,0 +1,52 @@
1
+ package com.mobileinspect.reactnative
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfo
7
+ import com.facebook.react.module.model.ReactModuleInfoProvider
8
+ import com.facebook.react.modules.network.OkHttpClientFactory
9
+ import com.facebook.react.modules.network.OkHttpClientProvider
10
+ import com.mobileinspect.MobileInspect
11
+ import okhttp3.OkHttpClient
12
+
13
+ class MobileInspectPackage : BaseReactPackage() {
14
+
15
+ init {
16
+ installNetworkInterceptor()
17
+ }
18
+
19
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =
20
+ if (name == MobileInspectModule.NAME) MobileInspectModule(reactContext) else null
21
+
22
+ override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {
23
+ mapOf(
24
+ MobileInspectModule.NAME to ReactModuleInfo(
25
+ MobileInspectModule.NAME,
26
+ MobileInspectModule.NAME,
27
+ false, // canOverrideExistingModule
28
+ false, // needsEagerInit
29
+ false, // isCxxModule
30
+ true, // isTurboModule
31
+ ),
32
+ )
33
+ }
34
+
35
+ private companion object {
36
+ /**
37
+ * React Native's fetch/XHR runs on its own OkHttp client. Hooking its factory here (the package is created
38
+ * before any JS runs) puts the inspector in front of every JS request, tagged "react-native".
39
+ * Apps that install their own factory afterwards replace this one and should add
40
+ * `MobileInspect.okhttpInterceptor("react-native")` themselves.
41
+ */
42
+ fun installNetworkInterceptor() {
43
+ OkHttpClientProvider.setOkHttpClientFactory(object : OkHttpClientFactory {
44
+ override fun createNewNetworkModuleClient(): OkHttpClient =
45
+ OkHttpClientProvider.createClientBuilder()
46
+ .addInterceptor(MobileInspect.okhttpInterceptor("react-native"))
47
+ .eventListenerFactory(MobileInspect.okhttpEventListenerFactory())
48
+ .build()
49
+ })
50
+ }
51
+ }
52
+ }
@@ -0,0 +1,113 @@
1
+ #if DEBUG
2
+ import Foundation
3
+ import Darwin
4
+ import os
5
+
6
+ /// Marker prefix: lines starting with it are dropped by the capture sink (recursion guard).
7
+ let mobileInspectInternalPrefix = "[MobileInspect]"
8
+
9
+ /// Buffers partial lines. Only touched from the capture queue.
10
+ private final class LineBuffer: @unchecked Sendable {
11
+ private var pending = Data()
12
+ func append(_ bytes: UnsafeBufferPointer<UInt8>) -> [String] {
13
+ pending.append(contentsOf: bytes)
14
+ var lines: [String] = []
15
+ while let nl = pending.firstIndex(of: 0x0A) {
16
+ let lineData = pending[pending.startIndex..<nl]
17
+ pending.removeSubrange(pending.startIndex...nl)
18
+ lines.append(String(decoding: lineData, as: UTF8.self))
19
+ }
20
+ // Avoid unbounded growth for output without newlines.
21
+ if pending.count > 64 * 1024 {
22
+ lines.append(String(decoding: pending, as: UTF8.self))
23
+ pending.removeAll()
24
+ }
25
+ return lines
26
+ }
27
+ }
28
+
29
+ /// Redirects STDOUT/STDERR through pipes (FR-3). The original descriptors are duplicated and every byte is
30
+ /// written back to them, so Xcode's console still prints normally.
31
+ final class ConsoleCapture: @unchecked Sendable {
32
+ static let shared = ConsoleCapture()
33
+
34
+ typealias Sink = @Sendable (_ level: String, _ line: String) -> Void
35
+
36
+ private struct Redirect {
37
+ let fd: Int32
38
+ let original: Int32
39
+ let source: DispatchSourceRead
40
+ }
41
+
42
+ private let queue = DispatchQueue(label: "com.mobileinspect.console", qos: .utility)
43
+ private let lock = NSLock()
44
+ private var redirects: [Redirect] = []
45
+ private let log = Logger(subsystem: "com.mobileinspect", category: "console")
46
+
47
+ var isRunning: Bool { lock.lock(); defer { lock.unlock() }; return !redirects.isEmpty }
48
+
49
+ func start(sink: @escaping Sink) {
50
+ lock.lock(); defer { lock.unlock() }
51
+ guard redirects.isEmpty else { return }
52
+ // Line-buffer stdout so output reaches the pipe promptly even when stdout is not a TTY.
53
+ setLineBuffered()
54
+ for (fd, level) in [(STDOUT_FILENO, "info"), (STDERR_FILENO, "error")] {
55
+ if let r = redirect(fd: fd, level: level, sink: sink) { redirects.append(r) }
56
+ }
57
+ }
58
+
59
+ func stop() {
60
+ lock.lock(); defer { lock.unlock() }
61
+ for r in redirects {
62
+ dup2(r.original, r.fd)
63
+ r.source.cancel()
64
+ }
65
+ redirects.removeAll()
66
+ }
67
+
68
+ private func setLineBuffered() {
69
+ // `stdout` is a mutable C global; fdopen would create a different FILE, so resolve it once here.
70
+ setvbuf(__stdoutp, nil, _IOLBF, 0)
71
+ }
72
+
73
+ private func redirect(fd: Int32, level: String, sink: @escaping Sink) -> Redirect? {
74
+ var fds: [Int32] = [0, 0]
75
+ guard pipe(&fds) == 0 else { return nil }
76
+ let readFD = fds[0], writeFD = fds[1]
77
+ let original = dup(fd)
78
+ guard original >= 0, dup2(writeFD, fd) >= 0 else {
79
+ close(readFD); close(writeFD)
80
+ if original >= 0 { close(original) }
81
+ log.error("redirect failed for fd \(fd)")
82
+ return nil
83
+ }
84
+ close(writeFD) // fd itself now owns the write end
85
+
86
+ let source = DispatchSource.makeReadSource(fileDescriptor: readFD, queue: queue)
87
+ let buffer = LineBuffer()
88
+ source.setEventHandler {
89
+ var bytes = [UInt8](repeating: 0, count: 8192)
90
+ let n = read(readFD, &bytes, bytes.count)
91
+ guard n > 0 else { return }
92
+ bytes.withUnsafeBufferPointer { ptr in
93
+ // Tee to the real console first.
94
+ var offset = 0
95
+ while offset < n {
96
+ let w = write(original, ptr.baseAddress! + offset, n - offset)
97
+ if w <= 0 { break }
98
+ offset += w
99
+ }
100
+ for line in buffer.append(UnsafeBufferPointer(rebasing: ptr[0..<n])) {
101
+ let trimmed = line.trimmingCharacters(in: .newlines)
102
+ if trimmed.isEmpty || trimmed.hasPrefix(mobileInspectInternalPrefix) { continue }
103
+ sink(level, trimmed)
104
+ }
105
+ }
106
+ }
107
+ source.setCancelHandler { close(readFD) }
108
+ source.resume()
109
+ return Redirect(fd: fd, original: original, source: source)
110
+ }
111
+ }
112
+
113
+ #endif
@@ -0,0 +1,72 @@
1
+ #if DEBUG
2
+ import Foundation
3
+
4
+ /// Builds a HAR 1.2 document from stored calls.
5
+ enum HARExporter {
6
+ static func build(calls: [NetworkCall], version: String = MobileInspect.sdkVersion) -> Data {
7
+ let iso = ISO8601DateFormatter()
8
+ iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
9
+
10
+ func pairs(_ headers: [String: String]) -> [[String: String]] {
11
+ headers.keys.sorted().map { ["name": $0, "value": headers[$0] ?? ""] }
12
+ }
13
+
14
+ let entries: [[String: Any]] = calls.sorted { $0.timestampStart < $1.timestampStart }.map { c in
15
+ let query = URLComponents(string: c.url)?.queryItems?.map { ["name": $0.name, "value": $0.value ?? ""] } ?? []
16
+ var request: [String: Any] = [
17
+ "method": c.method, "url": c.url, "httpVersion": "HTTP/1.1",
18
+ "cookies": [Any](), "headers": pairs(JSONHelper.decodeHeaders(c.requestHeaders)),
19
+ "queryString": query, "headersSize": -1, "bodySize": c.requestSizeBytes,
20
+ ]
21
+ if let body = c.requestBody, !body.isEmpty {
22
+ request["postData"] = ["mimeType": c.requestContentType ?? "", "text": body]
23
+ }
24
+ let response: [String: Any] = [
25
+ "status": c.statusCode, "statusText": c.statusMessage ?? c.errorDescription ?? "",
26
+ "httpVersion": "HTTP/1.1", "cookies": [Any](),
27
+ "headers": pairs(JSONHelper.decodeHeaders(c.responseHeaders)),
28
+ "content": ["size": c.responseSizeBytes, "mimeType": c.responseContentType ?? "", "text": c.responseBody ?? ""],
29
+ "redirectURL": "", "headersSize": -1, "bodySize": c.responseSizeBytes,
30
+ ]
31
+ return [
32
+ "startedDateTime": iso.string(from: Date(timeIntervalSince1970: Double(c.timestampStart) / 1000)),
33
+ "time": c.durationMs, "request": request, "response": response, "cache": [String: Any](),
34
+ "timings": harTimings(c),
35
+ "_sourceLayer": c.sourceLayer,
36
+ ]
37
+ }
38
+ let har: [String: Any] = [
39
+ "log": [
40
+ "version": "1.2",
41
+ "creator": ["name": "MobileInspect", "version": version],
42
+ "entries": entries,
43
+ ] as [String: Any],
44
+ ]
45
+ return (try? JSONSerialization.data(withJSONObject: har, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])) ?? Data("{}".utf8)
46
+ }
47
+ }
48
+
49
+ /// HAR `timings`: measured phases when available, otherwise the whole duration counted as `wait`.
50
+ func harTimings(_ c: NetworkCall) -> [String: Double] {
51
+ guard let t = Timings.decode(c.timings) else {
52
+ return ["send": 0, "wait": Double(c.durationMs), "receive": 0]
53
+ }
54
+ return ["blocked": t.blocked, "dns": t.dns, "connect": t.connect, "ssl": t.ssl,
55
+ "send": t.send, "wait": t.wait, "receive": t.receive]
56
+ }
57
+
58
+ enum CurlBuilder {
59
+ static func curl(for c: NetworkCall) -> String {
60
+ func q(_ s: String) -> String { "'" + s.replacingOccurrences(of: "'", with: "'\\''") + "'" }
61
+ var parts = ["curl", "-X", c.method, q(c.url)]
62
+ for (k, v) in JSONHelper.decodeHeaders(c.requestHeaders).sorted(by: { $0.key < $1.key }) {
63
+ parts.append("-H"); parts.append(q("\(k): \(v)"))
64
+ }
65
+ if let body = c.requestBody, !body.isEmpty, !body.hasPrefix("<Binary:") {
66
+ parts.append("--data-raw"); parts.append(q(body.replacingOccurrences(of: "[TRUNCATED]", with: "")))
67
+ }
68
+ return parts.joined(separator: " ")
69
+ }
70
+ }
71
+
72
+ #endif
@@ -0,0 +1,173 @@
1
+ #if DEBUG
2
+ import Foundation
3
+
4
+ /// Small lock-protected box so global state stays Sendable under Swift 6.
5
+ final class Locked<Value>: @unchecked Sendable {
6
+ private var value: Value
7
+ private let lock = NSLock()
8
+ init(_ value: Value) { self.value = value }
9
+ func withLock<R>(_ body: (inout Value) -> R) -> R {
10
+ lock.lock(); defer { lock.unlock() }
11
+ return body(&value)
12
+ }
13
+ }
14
+
15
+ /// Captured body before redaction. `text` already holds `<Binary: N bytes>` for binary payloads.
16
+ struct BodyCapture: Sendable {
17
+ var text: String?
18
+ var truncated: Bool
19
+ var size: Int64
20
+
21
+ static let empty = BodyCapture(text: nil, truncated: false, size: 0)
22
+
23
+ static func isBinary(contentType: String?) -> Bool {
24
+ guard let ct = contentType?.lowercased() else { return false }
25
+ let textual = ["json", "text/", "xml", "javascript", "x-www-form-urlencoded", "graphql", "html", "csv", "yaml"]
26
+ if textual.contains(where: { ct.contains($0) }) { return false }
27
+ return ct.hasPrefix("image/") || ct.hasPrefix("video/") || ct.hasPrefix("audio/")
28
+ || ct.contains("octet-stream") || ct.contains("pdf") || ct.contains("zip")
29
+ || ct.contains("protobuf") || ct.contains("font")
30
+ }
31
+
32
+ /// - Parameters:
33
+ /// - data: at most `maxBytes + 1` bytes of the payload (extra byte signals truncation).
34
+ /// - totalSize: real payload size.
35
+ static func make(data: Data?, totalSize: Int64, contentType: String?, maxBytes: Int) -> BodyCapture {
36
+ guard totalSize > 0 || (data?.isEmpty == false) else { return .empty }
37
+ if isBinary(contentType: contentType) {
38
+ return BodyCapture(text: "<Binary: \(totalSize) bytes>", truncated: false, size: totalSize)
39
+ }
40
+ guard var data, !data.isEmpty else {
41
+ return BodyCapture(text: "<Binary: \(totalSize) bytes>", truncated: false, size: totalSize)
42
+ }
43
+ var truncated = false
44
+ if data.count > maxBytes {
45
+ data = data.prefix(maxBytes)
46
+ truncated = true
47
+ }
48
+ var string = String(data: data, encoding: .utf8)
49
+ if string == nil, truncated {
50
+ // The cut may have split a multi-byte character.
51
+ var trimmed = data
52
+ for _ in 0..<3 where string == nil && !trimmed.isEmpty {
53
+ trimmed.removeLast()
54
+ string = String(data: trimmed, encoding: .utf8)
55
+ }
56
+ }
57
+ guard let string else {
58
+ return BodyCapture(text: "<Binary: \(totalSize) bytes>", truncated: false, size: totalSize)
59
+ }
60
+ return BodyCapture(text: string, truncated: truncated, size: totalSize)
61
+ }
62
+ }
63
+
64
+ /// A finished HTTP exchange as observed by a hook, before redaction/truncation.
65
+ struct NetworkDraft: Sendable {
66
+ var id = UUID().uuidString
67
+ var timestampStart: Int64
68
+ var durationMs: Int64
69
+ var method: String
70
+ var url: URL?
71
+ var statusCode: Int
72
+ var statusMessage: String?
73
+ var requestHeaders: [String: String]
74
+ var requestBody: BodyCapture
75
+ var requestContentType: String?
76
+ var responseHeaders: [String: String]
77
+ var responseBody: BodyCapture
78
+ var responseContentType: String?
79
+ var errorDescription: String?
80
+ var sourceLayer = SourceLayer.native
81
+ var timings: Timings? = nil
82
+ }
83
+
84
+ /// Owns config, storage and redaction for one `start()` call.
85
+ final class InspectorCore: Sendable {
86
+ let config: MobileInspectConfig
87
+ let sessionId = UUID().uuidString
88
+ let database: InspectorDatabase
89
+ private let redactor: Redactor
90
+ private let ignored: Set<String>
91
+
92
+ init(config: MobileInspectConfig, database: InspectorDatabase) {
93
+ self.config = config
94
+ self.database = database
95
+ self.redactor = Redactor(headers: config.redactedHeaders, bodyKeys: config.redactedBodyKeys)
96
+ self.ignored = Set(config.ignoredHosts.map { $0.lowercased() })
97
+ }
98
+
99
+ func isIgnored(host: String?) -> Bool {
100
+ guard let host else { return false }
101
+ return ignored.contains(host.lowercased())
102
+ }
103
+
104
+ func record(_ d: NetworkDraft) {
105
+ guard config.enabled, let url = d.url, !isIgnored(host: url.host) else { return }
106
+ let marker = "[TRUNCATED]"
107
+ func finish(_ body: BodyCapture) -> String? {
108
+ guard var text = redactor.redactBody(body.text) else { return nil }
109
+ if body.truncated { text += marker }
110
+ return text
111
+ }
112
+ let call = NetworkCall(
113
+ id: d.id, sessionId: sessionId,
114
+ timestampStart: d.timestampStart, durationMs: d.durationMs,
115
+ method: d.method.uppercased(), url: redactedURLString(url), host: url.host ?? "", path: url.path.isEmpty ? "/" : url.path,
116
+ statusCode: d.statusCode, statusMessage: d.statusMessage,
117
+ requestHeaders: JSONHelper.encode(redactor.redactHeaders(d.requestHeaders)),
118
+ requestBody: finish(d.requestBody), requestContentType: d.requestContentType,
119
+ requestSizeBytes: d.requestBody.size,
120
+ responseHeaders: JSONHelper.encode(redactor.redactHeaders(d.responseHeaders)),
121
+ responseBody: finish(d.responseBody), responseContentType: d.responseContentType,
122
+ responseSizeBytes: d.responseBody.size,
123
+ errorDescription: d.errorDescription, sourceLayer: d.sourceLayer,
124
+ timings: d.timings?.json()
125
+ )
126
+ database.insert(call)
127
+ }
128
+
129
+ func updateTimings(id: String, _ timings: Timings) {
130
+ guard config.enabled else { return }
131
+ database.updateTimings(id: id, timings: timings.json())
132
+ }
133
+
134
+ func recordLog(level: String, tag: String?, message: String, sourceLayer: String) {
135
+ guard config.enabled else { return }
136
+ let entry = ConsoleLog(
137
+ id: UUID().uuidString, sessionId: sessionId,
138
+ timestamp: Int64(Date().timeIntervalSince1970 * 1000),
139
+ level: Self.normalizeLevel(level), tag: tag,
140
+ message: message, sourceLayer: sourceLayer
141
+ )
142
+ database.insert(entry)
143
+ }
144
+
145
+ static func normalizeLevel(_ level: String) -> String {
146
+ switch level.lowercased() {
147
+ case "warn", "warning": return "warn"
148
+ case "error", "fatal", "assert": return "error"
149
+ case "debug", "trace", "verbose": return "debug"
150
+ default: return "info"
151
+ }
152
+ }
153
+
154
+ /// Query parameters can carry secrets, so mask values whose names match a redacted body key.
155
+ private func redactedURLString(_ url: URL) -> String {
156
+ guard var comps = URLComponents(url: url, resolvingAgainstBaseURL: false),
157
+ let items = comps.queryItems, !items.isEmpty else { return url.absoluteString }
158
+ let keys = Set(config.redactedBodyKeys.map { $0.lowercased() })
159
+ comps.queryItems = items.map { item in
160
+ keys.contains(item.name.lowercased()) ? URLQueryItem(name: item.name, value: Redactor.placeholder) : item
161
+ }
162
+ return comps.url?.absoluteString ?? url.absoluteString
163
+ }
164
+ }
165
+
166
+ /// Process-wide pointer to the active core. Hooks read it on every event.
167
+ enum CoreHolder {
168
+ private static let box = Locked<InspectorCore?>(nil)
169
+ static var current: InspectorCore? { box.withLock { $0 } }
170
+ static func set(_ core: InspectorCore?) { box.withLock { $0 = core } }
171
+ }
172
+
173
+ #endif