@fire-spark/tls-pinning 0.0.0-stage → 0.36.8

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.
@@ -0,0 +1,15 @@
1
+ plugins {
2
+ id 'com.android.library'
3
+ id 'expo-module-gradle-plugin'
4
+ }
5
+
6
+ group = 'dev.firespark.tlspin'
7
+ version = '0.1.0'
8
+
9
+ android {
10
+ namespace "dev.firespark.tlspin"
11
+ defaultConfig {
12
+ versionCode 1
13
+ versionName "0.1.0"
14
+ }
15
+ }
@@ -0,0 +1,3 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.INTERNET" />
3
+ </manifest>
@@ -0,0 +1,251 @@
1
+ package dev.firespark.tlspin
2
+
3
+ import expo.modules.kotlin.Promise
4
+ import expo.modules.kotlin.modules.Module
5
+ import expo.modules.kotlin.modules.ModuleDefinition
6
+ import java.io.BufferedInputStream
7
+ import java.io.ByteArrayOutputStream
8
+ import java.net.URL
9
+ import java.nio.charset.StandardCharsets
10
+ import java.security.MessageDigest
11
+ import java.security.SecureRandom
12
+ import java.security.cert.X509Certificate
13
+ import java.util.Locale
14
+ import java.util.concurrent.Executors
15
+ import java.util.concurrent.atomic.AtomicBoolean
16
+ import java.util.concurrent.atomic.AtomicReference
17
+ import javax.net.ssl.HostnameVerifier
18
+ import javax.net.ssl.HttpsURLConnection
19
+ import javax.net.ssl.SSLContext
20
+ import javax.net.ssl.SSLPeerUnverifiedException
21
+ import javax.net.ssl.TrustManager
22
+ import javax.net.ssl.X509TrustManager
23
+
24
+ private val HEX_CHARS = "0123456789ABCDEF".toCharArray()
25
+
26
+ private fun normalizePin(raw: String): String? {
27
+ val trimmed = raw.trim().uppercase(Locale.ROOT)
28
+ val hex = trimmed.replace(":", "")
29
+ if (hex.length != 64) return null
30
+ for (ch in hex) {
31
+ val ok = (ch in '0'..'9') || (ch in 'A'..'F')
32
+ if (!ok) return null
33
+ }
34
+ val sb = StringBuilder(95)
35
+ var i = 0
36
+ while (i < 64) {
37
+ if (i > 0) sb.append(':')
38
+ sb.append(hex[i])
39
+ sb.append(hex[i + 1])
40
+ i += 2
41
+ }
42
+ return sb.toString()
43
+ }
44
+
45
+ private fun certFingerprintSha256(cert: X509Certificate): String {
46
+ val digest = MessageDigest.getInstance("SHA-256").digest(cert.encoded)
47
+ val sb = StringBuilder(digest.size * 3 - 1)
48
+ for (i in digest.indices) {
49
+ if (i > 0) sb.append(':')
50
+ val v = digest[i].toInt() and 0xFF
51
+ sb.append(HEX_CHARS[v ushr 4])
52
+ sb.append(HEX_CHARS[v and 0x0F])
53
+ }
54
+ return sb.toString()
55
+ }
56
+
57
+ private fun matchesAnyPin(actual: String, pins: List<String>): Boolean {
58
+ val actualBytes = actual.toByteArray(StandardCharsets.UTF_8)
59
+ for (pin in pins) {
60
+ val pinBytes = pin.toByteArray(StandardCharsets.UTF_8)
61
+ if (MessageDigest.isEqual(actualBytes, pinBytes)) {
62
+ return true
63
+ }
64
+ }
65
+ return false
66
+ }
67
+
68
+ class FiresparkTlsPinningModule : Module() {
69
+ private val executor = Executors.newCachedThreadPool()
70
+
71
+ override fun definition() = ModuleDefinition {
72
+ Name("FiresparkTlsPinning")
73
+
74
+ AsyncFunction("request") { options: Map<String, Any?>, promise: Promise ->
75
+ executor.execute {
76
+ executePinnedRequest(options, promise)
77
+ }
78
+ }
79
+ }
80
+
81
+ private fun executePinnedRequest(options: Map<String, Any?>, promise: Promise) {
82
+ val rawPins = (options["pins"] as? List<*>)?.mapNotNull { it as? String } ?: emptyList()
83
+ val validPins = rawPins.mapNotNull(::normalizePin)
84
+ if (validPins.isEmpty()) {
85
+ promise.reject(
86
+ "TLS_FINGERPRINT_MISMATCH",
87
+ "TLS_FINGERPRINT_MISMATCH|expected=|actual=|Refusing local request without a valid SHA-256 TLS pin",
88
+ null
89
+ )
90
+ return
91
+ }
92
+
93
+ val urlString = options["url"] as? String ?: ""
94
+ val parsedUrl = try {
95
+ URL(urlString)
96
+ } catch (_: Exception) {
97
+ null
98
+ }
99
+ if (parsedUrl == null || !parsedUrl.protocol.equals("https", ignoreCase = true) || parsedUrl.host.isNullOrBlank()) {
100
+ promise.reject(
101
+ "TLS_FINGERPRINT_MISMATCH",
102
+ "TLS_FINGERPRINT_MISMATCH|expected=${validPins[0]}|actual=|Pinned local requests require an https:// URL",
103
+ null
104
+ )
105
+ return
106
+ }
107
+
108
+ val method = (options["method"] as? String)?.ifBlank { "GET" } ?: "GET"
109
+ val body = options["body"] as? String
110
+ val timeoutMs = ((options["timeoutMs"] as? Number)?.toInt() ?: 10000).coerceAtLeast(1000)
111
+ val headers = (options["headers"] as? Map<*, *>)
112
+ ?.entries
113
+ ?.mapNotNull { (k, v) ->
114
+ if (k is String && v is String) k to v else null
115
+ }
116
+ ?: emptyList()
117
+
118
+ val mismatchDetected = AtomicBoolean(false)
119
+ val mismatchActual = AtomicReference<String?>(null)
120
+
121
+ val trustManager = object : X509TrustManager {
122
+ override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
123
+ // Client auth not used.
124
+ }
125
+
126
+ override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
127
+ val leaf = chain.firstOrNull()
128
+ if (leaf == null) {
129
+ mismatchDetected.set(true)
130
+ mismatchActual.set(null)
131
+ throw SSLPeerUnverifiedException("Server presented no TLS certificate")
132
+ }
133
+ val actual = certFingerprintSha256(leaf)
134
+ if (!matchesAnyPin(actual, validPins)) {
135
+ mismatchDetected.set(true)
136
+ mismatchActual.set(actual)
137
+ throw SSLPeerUnverifiedException(
138
+ "Server TLS certificate SHA-256 $actual does not match pinned fingerprint"
139
+ )
140
+ }
141
+ }
142
+
143
+ override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
144
+ }
145
+
146
+ val hostnameVerifier = HostnameVerifier { _, session ->
147
+ val leaf = try {
148
+ session.peerCertificates.firstOrNull() as? X509Certificate
149
+ } catch (_: Exception) {
150
+ null
151
+ }
152
+ if (leaf == null) {
153
+ mismatchDetected.set(true)
154
+ mismatchActual.set(null)
155
+ false
156
+ } else {
157
+ val actual = certFingerprintSha256(leaf)
158
+ val ok = matchesAnyPin(actual, validPins)
159
+ if (!ok) {
160
+ mismatchDetected.set(true)
161
+ mismatchActual.set(actual)
162
+ }
163
+ ok
164
+ }
165
+ }
166
+
167
+ var conn: HttpsURLConnection? = null
168
+ try {
169
+ val sslContext = SSLContext.getInstance("TLS")
170
+ sslContext.init(null, arrayOf<TrustManager>(trustManager), SecureRandom())
171
+
172
+ conn = (parsedUrl.openConnection() as HttpsURLConnection).apply {
173
+ sslSocketFactory = sslContext.socketFactory
174
+ this.hostnameVerifier = hostnameVerifier
175
+ instanceFollowRedirects = false
176
+ useCaches = false
177
+ connectTimeout = timeoutMs
178
+ readTimeout = timeoutMs
179
+ requestMethod = method
180
+ for ((k, v) in headers) {
181
+ setRequestProperty(k, v)
182
+ }
183
+ }
184
+
185
+ val bodyBytes = body?.toByteArray(StandardCharsets.UTF_8)
186
+ if (bodyBytes != null) {
187
+ conn.doOutput = true
188
+ conn.setFixedLengthStreamingMode(bodyBytes.size)
189
+ }
190
+
191
+ // Complete and verify the pinned TLS handshake BEFORE writing any HTTP request body.
192
+ conn.connect()
193
+
194
+ if (bodyBytes != null) {
195
+ conn.outputStream.use { out ->
196
+ out.write(bodyBytes)
197
+ out.flush()
198
+ }
199
+ }
200
+
201
+ val status = conn.responseCode
202
+ val stream = if (status in 200..399) conn.inputStream else conn.errorStream
203
+ val responseBody = if (stream != null) {
204
+ BufferedInputStream(stream).use { input ->
205
+ val buffer = ByteArrayOutputStream()
206
+ val chunk = ByteArray(4096)
207
+ while (true) {
208
+ val read = input.read(chunk)
209
+ if (read == -1) break
210
+ buffer.write(chunk, 0, read)
211
+ }
212
+ buffer.toString(StandardCharsets.UTF_8.name())
213
+ }
214
+ } else {
215
+ ""
216
+ }
217
+
218
+ val responseHeaders = mutableMapOf<String, String>()
219
+ for ((key, values) in conn.headerFields) {
220
+ if (key != null && values != null && values.isNotEmpty()) {
221
+ responseHeaders[key.lowercase(Locale.ROOT)] = values.joinToString(", ")
222
+ }
223
+ }
224
+
225
+ promise.resolve(
226
+ mapOf(
227
+ "status" to status,
228
+ "headers" to responseHeaders,
229
+ "body" to responseBody
230
+ )
231
+ )
232
+ } catch (error: Exception) {
233
+ if (mismatchDetected.get() || error is SSLPeerUnverifiedException) {
234
+ val actual = mismatchActual.get() ?: ""
235
+ promise.reject(
236
+ "TLS_FINGERPRINT_MISMATCH",
237
+ "TLS_FINGERPRINT_MISMATCH|expected=${validPins[0]}|actual=$actual|Server TLS certificate SHA-256 does not match pinned fingerprint",
238
+ error
239
+ )
240
+ } else {
241
+ promise.reject(
242
+ "TLS_NETWORK_ERROR",
243
+ error.message ?: "Local TLS request failed",
244
+ error
245
+ )
246
+ }
247
+ } finally {
248
+ conn?.disconnect()
249
+ }
250
+ }
251
+ }
@@ -0,0 +1,33 @@
1
+ import { PinnedFetchFactory } from "@fire-spark/core";
2
+ //#region src/types.d.ts
3
+ interface NativePinnedRequestOptions {
4
+ url: string;
5
+ method: string;
6
+ headers: Record<string, string>;
7
+ body?: string;
8
+ pins: string[];
9
+ timeoutMs: number;
10
+ }
11
+ interface NativePinnedResponse {
12
+ status: number;
13
+ headers: Record<string, string>;
14
+ body: string;
15
+ }
16
+ interface FiresparkTlsPinningNativeModule {
17
+ request(options: NativePinnedRequestOptions): Promise<NativePinnedResponse>;
18
+ }
19
+ //#endregion
20
+ //#region src/native.d.ts
21
+ /** `null` on web, Node.js, or native builds without the TLS pinning module. */
22
+ declare const firesparkTlsPinningNative: FiresparkTlsPinningNativeModule | null;
23
+ //#endregion
24
+ //#region src/index.d.ts
25
+ declare const createNativePinnedFetchFactory: (nativeModule: FiresparkTlsPinningNativeModule) => PinnedFetchFactory;
26
+ /**
27
+ * Registers the native iOS/Android TLS-pinning transport with `@fire-spark/core`
28
+ * when running in an Expo native build that includes `FiresparkTlsPinning`.
29
+ * Returns `true` when native pinning is active, `false` otherwise.
30
+ */
31
+ declare const registerNativeLocalTlsPinning: (nativeModule?: FiresparkTlsPinningNativeModule | null) => boolean;
32
+ //#endregion
33
+ export { FiresparkTlsPinningNativeModule, NativePinnedRequestOptions, NativePinnedResponse, createNativePinnedFetchFactory, firesparkTlsPinningNative, registerNativeLocalTlsPinning };
package/dist/index.mjs ADDED
@@ -0,0 +1,95 @@
1
+ import { TlsFingerprintMismatchError, configureLocalTlsPinning, resolveLocalPins } from "@fire-spark/core";
2
+ import { requireOptionalNativeModule } from "expo";
3
+ //#region src/native.ts
4
+ /** `null` on web, Node.js, or native builds without the TLS pinning module. */
5
+ const firesparkTlsPinningNative = requireOptionalNativeModule("FiresparkTlsPinning");
6
+ //#endregion
7
+ //#region src/index.ts
8
+ const MISMATCH_CODE = "TLS_FINGERPRINT_MISMATCH";
9
+ const DEFAULT_TIMEOUT_MS = 1e4;
10
+ const errorMessage = (error) => {
11
+ if (error instanceof Error) return error.message;
12
+ if (typeof error === "string") return error;
13
+ return "";
14
+ };
15
+ const parseMismatch = (error, url, fallbackExpected) => {
16
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
17
+ const message = errorMessage(error);
18
+ if (!(code === MISMATCH_CODE || message.includes(`${MISMATCH_CODE}|`))) return null;
19
+ const expectedMatch = /expected=([^|]*)/.exec(message);
20
+ const actualMatch = /actual=([^|]*)/.exec(message);
21
+ return new TlsFingerprintMismatchError(url, expectedMatch?.[1] || fallbackExpected, actualMatch?.[1] || null);
22
+ };
23
+ const normalizeHeaders = (init) => {
24
+ const out = {};
25
+ if (!init) return out;
26
+ new Headers(init).forEach((value, key) => {
27
+ out[key] = value;
28
+ });
29
+ return out;
30
+ };
31
+ const readBody = (body) => {
32
+ if (body === void 0 || body === null) return void 0;
33
+ if (typeof body === "string") return body;
34
+ if (body instanceof URLSearchParams) return body.toString();
35
+ if (body instanceof Uint8Array) return new TextDecoder().decode(body);
36
+ if (body instanceof ArrayBuffer) return new TextDecoder().decode(new Uint8Array(body));
37
+ return String(body);
38
+ };
39
+ const resolveUrl = (input) => {
40
+ if (typeof input === "string") return input;
41
+ if (input instanceof URL) return input.toString();
42
+ return input.url;
43
+ };
44
+ const createNativePinnedFetchFactory = (nativeModule) => {
45
+ return (pins, options) => {
46
+ const validPins = resolveLocalPins({
47
+ tls_fingerprint: null,
48
+ tls_fingerprints: [...pins]
49
+ });
50
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
51
+ return (async (input, init) => {
52
+ const url = resolveUrl(input);
53
+ if (validPins.length === 0) throw new TlsFingerprintMismatchError(url, "", null);
54
+ if (!url.toLowerCase().startsWith("https://")) throw new TlsFingerprintMismatchError(url, validPins[0], null);
55
+ if (init?.signal?.aborted) {
56
+ const abortErr = /* @__PURE__ */ new Error("Aborted");
57
+ abortErr.name = "AbortError";
58
+ throw abortErr;
59
+ }
60
+ const method = (init?.method ?? "GET").toUpperCase();
61
+ const headers = normalizeHeaders(init?.headers);
62
+ const body = readBody(init?.body);
63
+ try {
64
+ const res = await nativeModule.request({
65
+ url,
66
+ method,
67
+ headers,
68
+ body,
69
+ pins: validPins,
70
+ timeoutMs
71
+ });
72
+ return new Response(res.body, {
73
+ status: res.status,
74
+ headers: res.headers
75
+ });
76
+ } catch (error) {
77
+ const mismatch = parseMismatch(error, url, validPins[0]);
78
+ if (mismatch) throw mismatch;
79
+ throw error;
80
+ }
81
+ });
82
+ };
83
+ };
84
+ /**
85
+ * Registers the native iOS/Android TLS-pinning transport with `@fire-spark/core`
86
+ * when running in an Expo native build that includes `FiresparkTlsPinning`.
87
+ * Returns `true` when native pinning is active, `false` otherwise.
88
+ */
89
+ const registerNativeLocalTlsPinning = (nativeModule = firesparkTlsPinningNative) => {
90
+ if (!nativeModule) return false;
91
+ configureLocalTlsPinning(createNativePinnedFetchFactory(nativeModule));
92
+ return true;
93
+ };
94
+ //#endregion
95
+ export { createNativePinnedFetchFactory, firesparkTlsPinningNative, registerNativeLocalTlsPinning };
@@ -0,0 +1,9 @@
1
+ {
2
+ "platforms": ["apple", "android"],
3
+ "apple": {
4
+ "modules": ["FiresparkTlsPinningModule"]
5
+ },
6
+ "android": {
7
+ "modules": ["dev.firespark.tlspin.FiresparkTlsPinningModule"]
8
+ }
9
+ }
@@ -0,0 +1,26 @@
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 = 'FiresparkTlsPinning'
7
+ s.version = package['version']
8
+ s.summary = package['description']
9
+ s.description = package['description']
10
+ s.license = 'MIT'
11
+ s.author = 'Fire Spark'
12
+ s.homepage = 'https://firespark.dev'
13
+ s.platforms = { :ios => '15.1' }
14
+ s.swift_version = '5.9'
15
+ s.source = { :git => '' }
16
+ s.static_framework = true
17
+
18
+ s.dependency 'ExpoModulesCore'
19
+
20
+ s.pod_target_xcconfig = {
21
+ 'DEFINES_MODULE' => 'YES',
22
+ 'SWIFT_COMPILATION_MODE' => 'wholemodule'
23
+ }
24
+
25
+ s.source_files = "**/*.{h,m,mm,swift,hpp,cpp}"
26
+ end
@@ -0,0 +1,212 @@
1
+ import CryptoKit
2
+ import ExpoModulesCore
3
+ import Foundation
4
+ import Security
5
+
6
+ private struct PinnedRequestOptions: Record {
7
+ @Field var url: String = ""
8
+ @Field var method: String = "GET"
9
+ @Field var headers: [String: String] = [:]
10
+ @Field var body: String? = nil
11
+ @Field var pins: [String] = []
12
+ @Field var timeoutMs: Double = 10000
13
+ }
14
+
15
+ private func normalizePin(_ raw: String) -> String? {
16
+ let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
17
+ let hex = trimmed.replacingOccurrences(of: ":", with: "")
18
+ guard hex.count == 64 else { return nil }
19
+ for scalar in hex.unicodeScalars {
20
+ let isHex =
21
+ (scalar.value >= 48 && scalar.value <= 57) ||
22
+ (scalar.value >= 65 && scalar.value <= 70)
23
+ if !isHex { return nil }
24
+ }
25
+ var pairs: [String] = []
26
+ pairs.reserveCapacity(32)
27
+ var idx = hex.startIndex
28
+ while idx < hex.endIndex {
29
+ let next = hex.index(idx, offsetBy: 2)
30
+ pairs.append(String(hex[idx..<next]))
31
+ idx = next
32
+ }
33
+ return pairs.joined(separator: ":")
34
+ }
35
+
36
+ private func constantTimeEquals(_ a: String, _ b: String) -> Bool {
37
+ let aBytes = Array(a.utf8)
38
+ let bBytes = Array(b.utf8)
39
+ guard aBytes.count == bBytes.count else { return false }
40
+ var diff: UInt8 = 0
41
+ for i in 0..<aBytes.count {
42
+ diff |= aBytes[i] ^ bBytes[i]
43
+ }
44
+ return diff == 0
45
+ }
46
+
47
+ private func leafCertFingerprint(_ trust: SecTrust) -> String? {
48
+ guard let chain = SecTrustCopyCertificateChain(trust) as? [SecCertificate],
49
+ let leaf = chain.first else {
50
+ return nil
51
+ }
52
+ let der = SecCertificateCopyData(leaf) as Data
53
+ let digest = SHA256.hash(data: der)
54
+ return digest.map { String(format: "%02X", $0) }.joined(separator: ":")
55
+ }
56
+
57
+ private final class PinnedSessionDelegate: NSObject, URLSessionDelegate, URLSessionTaskDelegate {
58
+ private let pins: [String]
59
+ private let lock = NSLock()
60
+ private var _mismatchActual: String? = nil
61
+ private var _mismatchDetected: Bool = false
62
+
63
+ var mismatchActual: String? {
64
+ lock.lock()
65
+ defer { lock.unlock() }
66
+ return _mismatchActual
67
+ }
68
+
69
+ var mismatchDetected: Bool {
70
+ lock.lock()
71
+ defer { lock.unlock() }
72
+ return _mismatchDetected
73
+ }
74
+
75
+ init(pins: [String]) {
76
+ self.pins = pins
77
+ }
78
+
79
+ func urlSession(
80
+ _ session: URLSession,
81
+ didReceive challenge: URLAuthenticationChallenge,
82
+ completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
83
+ ) {
84
+ guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
85
+ let serverTrust = challenge.protectionSpace.serverTrust else {
86
+ completionHandler(.performDefaultHandling, nil)
87
+ return
88
+ }
89
+
90
+ guard let actual = leafCertFingerprint(serverTrust) else {
91
+ lock.lock()
92
+ _mismatchDetected = true
93
+ _mismatchActual = nil
94
+ lock.unlock()
95
+ completionHandler(.cancelAuthenticationChallenge, nil)
96
+ return
97
+ }
98
+
99
+ var matched = false
100
+ for pin in pins {
101
+ if constantTimeEquals(pin, actual) {
102
+ matched = true
103
+ break
104
+ }
105
+ }
106
+
107
+ if matched {
108
+ completionHandler(.useCredential, URLCredential(trust: serverTrust))
109
+ } else {
110
+ lock.lock()
111
+ _mismatchDetected = true
112
+ _mismatchActual = actual
113
+ lock.unlock()
114
+ // Abort the TLS handshake before URLSession transmits any HTTP headers or body.
115
+ completionHandler(.cancelAuthenticationChallenge, nil)
116
+ }
117
+ }
118
+
119
+ func urlSession(
120
+ _ session: URLSession,
121
+ task: URLSessionTask,
122
+ willPerformHTTPRedirection response: HTTPURLResponse,
123
+ newRequest request: URLRequest,
124
+ completionHandler: @escaping (URLRequest?) -> Void
125
+ ) {
126
+ completionHandler(nil)
127
+ }
128
+ }
129
+
130
+ public class FiresparkTlsPinningModule: Module {
131
+ public func definition() -> ModuleDefinition {
132
+ Name("FiresparkTlsPinning")
133
+
134
+ AsyncFunction("request") { (options: PinnedRequestOptions, promise: Promise) in
135
+ let validPins = options.pins.compactMap(normalizePin)
136
+ guard !validPins.isEmpty else {
137
+ promise.reject(
138
+ "TLS_FINGERPRINT_MISMATCH",
139
+ "TLS_FINGERPRINT_MISMATCH|expected=|actual=|Refusing local request without a valid SHA-256 TLS pin"
140
+ )
141
+ return
142
+ }
143
+
144
+ guard let url = URL(string: options.url),
145
+ url.scheme?.lowercased() == "https",
146
+ url.host != nil else {
147
+ promise.reject(
148
+ "TLS_FINGERPRINT_MISMATCH",
149
+ "TLS_FINGERPRINT_MISMATCH|expected=\(validPins[0])|actual=|Pinned local requests require an https:// URL"
150
+ )
151
+ return
152
+ }
153
+
154
+ let timeoutSeconds = max(options.timeoutMs / 1000.0, 1.0)
155
+ let config = URLSessionConfiguration.ephemeral
156
+ config.urlCache = nil
157
+ config.httpCookieStorage = nil
158
+ config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
159
+ config.timeoutIntervalForRequest = timeoutSeconds
160
+ config.timeoutIntervalForResource = timeoutSeconds
161
+
162
+ let delegate = PinnedSessionDelegate(pins: validPins)
163
+ let session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil)
164
+
165
+ var req = URLRequest(url: url)
166
+ req.httpMethod = options.method.isEmpty ? "GET" : options.method
167
+ for (key, value) in options.headers {
168
+ req.setValue(value, forHTTPHeaderField: key)
169
+ }
170
+ if let body = options.body {
171
+ req.httpBody = body.data(using: .utf8)
172
+ }
173
+
174
+ let task = session.dataTask(with: req) { data, response, error in
175
+ defer { session.finishTasksAndInvalidate() }
176
+
177
+ if delegate.mismatchDetected {
178
+ let actual = delegate.mismatchActual ?? ""
179
+ promise.reject(
180
+ "TLS_FINGERPRINT_MISMATCH",
181
+ "TLS_FINGERPRINT_MISMATCH|expected=\(validPins[0])|actual=\(actual)|Server TLS certificate SHA-256 does not match pinned fingerprint"
182
+ )
183
+ return
184
+ }
185
+
186
+ if let error = error {
187
+ promise.reject("TLS_NETWORK_ERROR", error.localizedDescription)
188
+ return
189
+ }
190
+
191
+ guard let httpResponse = response as? HTTPURLResponse else {
192
+ promise.reject("TLS_NETWORK_ERROR", "Missing HTTP response from local server")
193
+ return
194
+ }
195
+
196
+ var responseHeaders: [String: String] = [:]
197
+ for (key, value) in httpResponse.allHeaderFields {
198
+ responseHeaders[String(describing: key).lowercased()] = String(describing: value)
199
+ }
200
+
201
+ let responseBody = data.flatMap { String(data: $0, encoding: .utf8) } ?? ""
202
+ promise.resolve([
203
+ "status": httpResponse.statusCode,
204
+ "headers": responseHeaders,
205
+ "body": responseBody
206
+ ])
207
+ }
208
+
209
+ task.resume()
210
+ }
211
+ }
212
+ }
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@fire-spark/tls-pinning",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.36.8",
4
+ "description": "Fire Spark Expo native TLS certificate pinning transport for iOS and Android local node connections",
5
+ "sideEffects": false,
6
+ "files": [
7
+ "dist",
8
+ "ios",
9
+ "android/build.gradle",
10
+ "android/src",
11
+ "expo-module.config.json"
12
+ ],
13
+ "main": "./dist/index.mjs",
14
+ "types": "./dist/index.d.mts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.mts",
18
+ "import": "./dist/index.mjs",
19
+ "default": "./dist/index.mjs"
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "dependencies": {
24
+ "@fire-spark/core": "^0.36.8"
25
+ },
26
+ "peerDependencies": {
27
+ "expo": ">=57"
28
+ },
29
+ "devDependencies": {
30
+ "expo": "~57.0.25",
31
+ "tsdown": "^0.22.14",
32
+ "typescript": "^7.0.2",
33
+ "vitest": "^2.1.8"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "tsdown": {
39
+ "entry": [
40
+ "src/index.ts"
41
+ ],
42
+ "format": [
43
+ "esm"
44
+ ],
45
+ "platform": "neutral",
46
+ "dts": {
47
+ "tsconfig": "tsconfig.build.json"
48
+ },
49
+ "clean": true,
50
+ "deps": {
51
+ "neverBundle": [
52
+ "expo",
53
+ "@fire-spark/core"
54
+ ]
55
+ }
56
+ },
57
+ "scripts": {
58
+ "build": "tsdown",
59
+ "dev": "tsdown --watch",
60
+ "check-types": "tsc --noEmit",
61
+ "test:utils": "vitest run",
62
+ "lint": "oxlint ./src --max-warnings=0",
63
+ "format": "oxfmt ./src",
64
+ "check-format": "oxfmt --check ./src"
65
+ }
6
66
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.