@agimon-ai/po-native 0.0.1-alpha.50 → 0.0.1-alpha.51
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/app.config.ts +1 -0
- package/modules/po-lan-tls/android/build.gradle +20 -0
- package/modules/po-lan-tls/android/src/main/java/expo/modules/polantls/PoLanTlsModule.kt +521 -0
- package/modules/po-lan-tls/expo-module.config.json +5 -0
- package/modules/po-lan-tls/index.ts +538 -0
- package/modules/po-lan-tls/ios/PoLanTls.podspec +17 -0
- package/modules/po-lan-tls/ios/PoLanTlsModule.swift +593 -0
- package/package.json +12 -12
- package/src/adapters/remoteHttp.ts +36 -2
- package/src/app/hostRuntimes.ts +66 -4
- package/src/app/liveRuntime.ts +10 -3
- package/src/components/SessionSheets.stories.tsx +32 -8
- package/src/components/SessionSheets.tsx +56 -26
- package/src/components/richActivity/AuthorMediaHost.tsx +69 -90
- package/src/components/richActivity/AuthorVideoTransport.stories.tsx +95 -0
- package/src/components/richActivity/AuthorVideoTransport.tsx +144 -0
- package/src/services/deviceTrust/index.ts +127 -18
- package/src/services/hostActions/index.ts +4 -2
- package/src/services/pairing/index.ts +27 -2
- package/src/services/relayTransport/index.ts +258 -0
- package/src/services/relayTransport/route.ts +19 -0
package/app.config.ts
CHANGED
|
@@ -36,6 +36,7 @@ const config: ExpoConfig = {
|
|
|
36
36
|
ios: {
|
|
37
37
|
bundleIdentifier: 'ai.po.app',
|
|
38
38
|
usesAppleSignIn: true,
|
|
39
|
+
infoPlist: { NSLocalNetworkUsageDescription: 'Connect to your paired Po computer on your local network.' },
|
|
39
40
|
// Export compliance answer on App Store Connect: no non-exempt encryption.
|
|
40
41
|
config: { usesNonExemptEncryption: false },
|
|
41
42
|
...(iosBuildNumber ? { buildNumber: iosBuildNumber } : {}),
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
plugins {
|
|
2
|
+
id 'com.android.library'
|
|
3
|
+
id 'expo-module-gradle-plugin'
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
group = 'ai.agimon.po'
|
|
7
|
+
version = '1.0.0'
|
|
8
|
+
|
|
9
|
+
android {
|
|
10
|
+
namespace 'expo.modules.polantls'
|
|
11
|
+
defaultConfig {
|
|
12
|
+
versionCode 1
|
|
13
|
+
versionName '1.0.0'
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
dependencies {
|
|
18
|
+
// React Native already ships OkHttp at runtime. This only names it for compilation.
|
|
19
|
+
compileOnly 'com.squareup.okhttp3:okhttp:4.9.2'
|
|
20
|
+
}
|
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
package expo.modules.polantls
|
|
2
|
+
|
|
3
|
+
import android.util.Base64
|
|
4
|
+
import expo.modules.kotlin.Promise
|
|
5
|
+
import expo.modules.kotlin.modules.Module
|
|
6
|
+
import expo.modules.kotlin.modules.ModuleDefinition
|
|
7
|
+
import okhttp3.Call
|
|
8
|
+
import okhttp3.Callback
|
|
9
|
+
import okhttp3.ConnectionPool
|
|
10
|
+
import okhttp3.ConnectionSpec
|
|
11
|
+
import okhttp3.CookieJar
|
|
12
|
+
import okhttp3.HttpUrl
|
|
13
|
+
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
|
14
|
+
import okhttp3.OkHttpClient
|
|
15
|
+
import okhttp3.Protocol
|
|
16
|
+
import okhttp3.Request
|
|
17
|
+
import okhttp3.RequestBody.Companion.toRequestBody
|
|
18
|
+
import okhttp3.Response
|
|
19
|
+
import okhttp3.WebSocket
|
|
20
|
+
import okhttp3.WebSocketListener
|
|
21
|
+
import okio.ByteString
|
|
22
|
+
import okio.ByteString.Companion.toByteString
|
|
23
|
+
import java.io.IOException
|
|
24
|
+
import java.security.KeyStore
|
|
25
|
+
import java.security.MessageDigest
|
|
26
|
+
import java.security.SecureRandom
|
|
27
|
+
import java.security.cert.CertPathValidatorException
|
|
28
|
+
import java.security.cert.CertificateException
|
|
29
|
+
import java.security.cert.X509Certificate
|
|
30
|
+
import java.util.concurrent.ConcurrentHashMap
|
|
31
|
+
import java.util.concurrent.TimeUnit
|
|
32
|
+
import javax.net.ssl.SSLContext
|
|
33
|
+
import javax.net.ssl.SSLPeerUnverifiedException
|
|
34
|
+
import javax.net.ssl.TrustManagerFactory
|
|
35
|
+
import javax.net.ssl.X509TrustManager
|
|
36
|
+
|
|
37
|
+
private const val TRUST = "ERR_PO_LAN_TLS_TRUST"
|
|
38
|
+
private const val FAILURE = "ERR_PO_LAN_TLS"
|
|
39
|
+
private const val MAX_BYTES = 8 * 1024 * 1024
|
|
40
|
+
private const val MAX_HEADERS = 128
|
|
41
|
+
private const val MAX_HEADER_BYTES = 16 * 1024
|
|
42
|
+
private const val MAX_TRANSPORTS = 8
|
|
43
|
+
private const val MAX_SOCKETS = 4
|
|
44
|
+
private const val SOCKET_PATH = "/api/ws"
|
|
45
|
+
private val METHODS = setOf("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE")
|
|
46
|
+
|
|
47
|
+
/** The relay speaks sealed records of at most 128 KiB, so its sockets never need the LAN body ceiling. */
|
|
48
|
+
private const val RELAY_MAX_BYTES = 256 * 1024
|
|
49
|
+
|
|
50
|
+
/** The only address a relay transport reaches: wss, no user info, the exact route shape and the client role. */
|
|
51
|
+
private val RELAY_ADDRESS =
|
|
52
|
+
Regex("^wss://[^/?#@]+/api/private-relay/[A-Za-z0-9_-]{1,128}/[A-Za-z0-9._:-]{1,128}\\?role=client$")
|
|
53
|
+
|
|
54
|
+
/** A refusal JavaScript can tell apart: the trust code is part of the message too, so it survives any wrapper. */
|
|
55
|
+
private class Refusal(val code: String, detail: String) :
|
|
56
|
+
Exception(if (code == TRUST) "$TRUST: $detail" else detail) {
|
|
57
|
+
companion object {
|
|
58
|
+
fun trust(detail: String) = Refusal(TRUST, detail)
|
|
59
|
+
fun failure(detail: String) = Refusal(FAILURE, detail)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The pin picks the certificate. Validation then runs with that certificate as the only anchor, so its
|
|
65
|
+
* dates are still checked. The host name is still checked by OkHttp's own verifier, which is left in place.
|
|
66
|
+
*/
|
|
67
|
+
private class PinnedTrust(private val pin: ByteArray) : X509TrustManager {
|
|
68
|
+
@Volatile var rejected = false
|
|
69
|
+
|
|
70
|
+
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
|
|
71
|
+
throw CertificateException("Client certificates are not accepted.")
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
|
|
75
|
+
try {
|
|
76
|
+
val leaf = chain?.firstOrNull() ?: throw CertificateException("The server sent no certificate.")
|
|
77
|
+
val digest = MessageDigest.getInstance("SHA-256").digest(leaf.encoded)
|
|
78
|
+
if (!MessageDigest.isEqual(digest, pin)) throw CertificateException("This is not the paired certificate.")
|
|
79
|
+
leaf.checkValidity()
|
|
80
|
+
val store = KeyStore.getInstance(KeyStore.getDefaultType()).apply {
|
|
81
|
+
load(null, null)
|
|
82
|
+
setCertificateEntry("paired", leaf)
|
|
83
|
+
}
|
|
84
|
+
val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply { init(store) }
|
|
85
|
+
factory.trustManagers.filterIsInstance<X509TrustManager>().first()
|
|
86
|
+
.checkServerTrusted(arrayOf(leaf), authType ?: "RSA")
|
|
87
|
+
} catch (error: CertificateException) {
|
|
88
|
+
rejected = true
|
|
89
|
+
throw error
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private fun decode(value: String): ByteArray {
|
|
97
|
+
val bytes = try {
|
|
98
|
+
Base64.decode(value, Base64.NO_WRAP)
|
|
99
|
+
} catch (error: IllegalArgumentException) {
|
|
100
|
+
throw Refusal.failure("Invalid body encoding.")
|
|
101
|
+
}
|
|
102
|
+
if (bytes.size > MAX_BYTES) throw Refusal.failure("The body is too large.")
|
|
103
|
+
return bytes
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* One paired computer: its own client, its own certificate rule, nothing shared with another host.
|
|
108
|
+
* A LAN transport always has a pin and no relay address. A relay transport has the opposite: the platform
|
|
109
|
+
* trust store and one exact socket address, and it carries no HTTP. The two never mix on one transport.
|
|
110
|
+
*/
|
|
111
|
+
private class Transport(
|
|
112
|
+
private val transportId: String,
|
|
113
|
+
val host: String,
|
|
114
|
+
val port: Int,
|
|
115
|
+
val pin: ByteArray?,
|
|
116
|
+
val relayUrl: String?,
|
|
117
|
+
private val emit: (Map<String, Any?>) -> Unit,
|
|
118
|
+
) {
|
|
119
|
+
init {
|
|
120
|
+
require((pin == null) != (relayUrl == null)) { "A transport is either pinned or a relay." }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private val trust = pin?.let { PinnedTrust(it) }
|
|
124
|
+
private val frameLimit = if (relayUrl == null) MAX_BYTES else RELAY_MAX_BYTES
|
|
125
|
+
private val calls = ConcurrentHashMap<String, Call>()
|
|
126
|
+
private val sockets = ConcurrentHashMap<String, WebSocket>()
|
|
127
|
+
private val closing = ConcurrentHashMap.newKeySet<String>()
|
|
128
|
+
@Volatile private var closed = false
|
|
129
|
+
|
|
130
|
+
// No cookie jar, cache or redirects, TLS 1.2+ only, and the default host name verifier stays.
|
|
131
|
+
private val http: OkHttpClient = run {
|
|
132
|
+
val builder = OkHttpClient.Builder()
|
|
133
|
+
if (trust != null) {
|
|
134
|
+
val context = SSLContext.getInstance("TLS")
|
|
135
|
+
context.init(null, arrayOf(trust), SecureRandom())
|
|
136
|
+
builder.sslSocketFactory(context.socketFactory, trust)
|
|
137
|
+
}
|
|
138
|
+
builder
|
|
139
|
+
.connectionSpecs(listOf(ConnectionSpec.MODERN_TLS))
|
|
140
|
+
.protocols(listOf(Protocol.HTTP_1_1))
|
|
141
|
+
.followRedirects(false)
|
|
142
|
+
.followSslRedirects(false)
|
|
143
|
+
.cookieJar(CookieJar.NO_COOKIES)
|
|
144
|
+
.cache(null)
|
|
145
|
+
.connectionPool(ConnectionPool(2, 30, TimeUnit.SECONDS))
|
|
146
|
+
.connectTimeout(10, TimeUnit.SECONDS)
|
|
147
|
+
.readTimeout(30, TimeUnit.SECONDS)
|
|
148
|
+
.callTimeout(120, TimeUnit.SECONDS)
|
|
149
|
+
.build()
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// The same trust and pool, but an idle socket is healthy: pings keep it, not a read timeout.
|
|
153
|
+
private val socketClient: OkHttpClient = http.newBuilder()
|
|
154
|
+
.callTimeout(0, TimeUnit.SECONDS)
|
|
155
|
+
.readTimeout(0, TimeUnit.SECONDS)
|
|
156
|
+
.pingInterval(30, TimeUnit.SECONDS)
|
|
157
|
+
.build()
|
|
158
|
+
|
|
159
|
+
private fun target(url: String, socket: Boolean): HttpUrl {
|
|
160
|
+
val prefix = if (socket) "wss://" else "https://"
|
|
161
|
+
if (!url.startsWith(prefix)) throw Refusal.failure("This LAN transport only reaches its paired host.")
|
|
162
|
+
val parsed = ("https://" + url.removePrefix(prefix)).toHttpUrlOrNull()
|
|
163
|
+
?: throw Refusal.failure("Invalid LAN address.")
|
|
164
|
+
if (!parsed.host.equals(host, ignoreCase = true) || parsed.port != port || parsed.username.isNotEmpty() ||
|
|
165
|
+
parsed.password.isNotEmpty() || parsed.fragment != null
|
|
166
|
+
) throw Refusal.failure("This LAN transport only reaches its paired host.")
|
|
167
|
+
// A relay address is matched exactly against the one given at open, so only the LAN path is checked here.
|
|
168
|
+
if (socket && relayUrl == null && (parsed.encodedPath != SOCKET_PATH || parsed.query != null))
|
|
169
|
+
throw Refusal.failure("Expected the Po protocol socket path.")
|
|
170
|
+
return parsed
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
private fun build(url: HttpUrl, headers: List<List<String>>): Request.Builder {
|
|
174
|
+
if (headers.size > MAX_HEADERS) throw Refusal.failure("Too many request headers.")
|
|
175
|
+
val builder = Request.Builder().url(url)
|
|
176
|
+
for (pair in headers) {
|
|
177
|
+
if (pair.size != 2 || pair[0].length + pair[1].length > MAX_HEADER_BYTES) throw Refusal.failure("Invalid request header.")
|
|
178
|
+
try {
|
|
179
|
+
builder.addHeader(pair[0], pair[1])
|
|
180
|
+
} catch (error: IllegalArgumentException) {
|
|
181
|
+
throw Refusal.failure("Invalid request header.")
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return builder
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** A trust failure is a certificate, pin, host name or validity refusal. A dropped connection is not. */
|
|
188
|
+
private fun refusal(error: Throwable, call: Call?): Refusal {
|
|
189
|
+
val subject = if (relayUrl == null) "LAN" else "relay"
|
|
190
|
+
if (call?.isCanceled() == true) return Refusal.failure("The $subject request was cancelled.")
|
|
191
|
+
var cause: Throwable? = error
|
|
192
|
+
var depth = 0
|
|
193
|
+
while (cause != null && depth < 8) {
|
|
194
|
+
if (cause is CertificateException || cause is CertPathValidatorException || cause is SSLPeerUnverifiedException)
|
|
195
|
+
return Refusal.trust("The $subject certificate is not valid for the paired computer.")
|
|
196
|
+
cause = cause.cause
|
|
197
|
+
depth += 1
|
|
198
|
+
}
|
|
199
|
+
val pinned = trust
|
|
200
|
+
if (pinned != null && pinned.rejected) {
|
|
201
|
+
pinned.rejected = false
|
|
202
|
+
return Refusal.trust("The $subject certificate does not match the paired computer.")
|
|
203
|
+
}
|
|
204
|
+
return Refusal.failure(if (relayUrl == null) "The LAN computer could not be reached." else "The relay could not be reached.")
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
fun request(requestId: String, method: String, url: String, headers: List<List<String>>, body: String?, promise: Promise) {
|
|
208
|
+
val call: Call
|
|
209
|
+
try {
|
|
210
|
+
if (relayUrl != null) throw Refusal.failure("A relay transport carries only its socket.")
|
|
211
|
+
if (closed) throw Refusal.failure("The LAN transport is closed.")
|
|
212
|
+
if (method !in METHODS) throw Refusal.failure("Unsupported request method.")
|
|
213
|
+
val builder = build(target(url, false), headers)
|
|
214
|
+
val bytes = body?.let { decode(it) }
|
|
215
|
+
val payload = when {
|
|
216
|
+
method == "GET" || method == "HEAD" -> null
|
|
217
|
+
bytes != null -> bytes.toRequestBody(null)
|
|
218
|
+
else -> ByteArray(0).toRequestBody(null)
|
|
219
|
+
}
|
|
220
|
+
call = http.newCall(builder.method(method, payload).build())
|
|
221
|
+
} catch (refusal: Refusal) {
|
|
222
|
+
promise.reject(refusal.code, refusal.message, null)
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
calls[requestId] = call
|
|
226
|
+
call.enqueue(object : Callback {
|
|
227
|
+
override fun onFailure(call: Call, e: IOException) {
|
|
228
|
+
calls.remove(requestId)
|
|
229
|
+
val refusal = refusal(e, call)
|
|
230
|
+
promise.reject(refusal.code, refusal.message, null)
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
override fun onResponse(call: Call, response: Response) {
|
|
234
|
+
calls.remove(requestId)
|
|
235
|
+
response.use { settle(it, promise) }
|
|
236
|
+
}
|
|
237
|
+
})
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
private fun settle(response: Response, promise: Promise) {
|
|
241
|
+
// A redirect is a trust failure. It is refused here, and OkHttp was told never to follow it.
|
|
242
|
+
if (response.code in 300..399) {
|
|
243
|
+
promise.reject(TRUST, Refusal.trust("The LAN host redirected the request.").message, null)
|
|
244
|
+
return
|
|
245
|
+
}
|
|
246
|
+
val body = response.body
|
|
247
|
+
if (response.code !in 200..599 || body == null || body.contentLength() > MAX_BYTES) {
|
|
248
|
+
promise.reject(FAILURE, "The LAN host sent an invalid or oversized response.", null)
|
|
249
|
+
return
|
|
250
|
+
}
|
|
251
|
+
val bytes = try {
|
|
252
|
+
val source = body.source()
|
|
253
|
+
if (source.request(MAX_BYTES + 1L)) null else source.readByteArray()
|
|
254
|
+
} catch (error: IOException) {
|
|
255
|
+
null
|
|
256
|
+
}
|
|
257
|
+
if (bytes == null) {
|
|
258
|
+
promise.reject(FAILURE, "The LAN host sent an invalid or oversized response.", null)
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
val merged = LinkedHashMap<String, MutableList<String>>()
|
|
262
|
+
for ((name, value) in response.headers) merged.getOrPut(name.lowercase()) { mutableListOf() }.add(value)
|
|
263
|
+
promise.resolve(
|
|
264
|
+
mapOf(
|
|
265
|
+
"status" to response.code,
|
|
266
|
+
"headers" to merged.map { listOf(it.key, it.value.joinToString(", ")) },
|
|
267
|
+
"bodyBase64" to Base64.encodeToString(bytes, Base64.NO_WRAP),
|
|
268
|
+
),
|
|
269
|
+
)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
fun cancel(requestId: String) {
|
|
273
|
+
calls[requestId]?.cancel()
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
fun openSocket(socketId: String, url: String, headers: List<List<String>>) {
|
|
277
|
+
if (relayUrl != null) throw Refusal.failure("A relay transport opens only its relay socket.")
|
|
278
|
+
if (closed) throw Refusal.failure("The LAN transport is closed.")
|
|
279
|
+
start(socketId, build(target(url, true), headers).build())
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* No header, cookie, protocol or credential is sent: the capability travels only as the first message, and
|
|
284
|
+
* only after `onOpen` has confirmed the socket is at this exact address. Redirects are off on this client.
|
|
285
|
+
*/
|
|
286
|
+
fun openRelaySocket(socketId: String, url: String) {
|
|
287
|
+
if (relayUrl == null || url != relayUrl) throw Refusal.trust("This transport only reaches its exact relay address.")
|
|
288
|
+
if (closed) throw Refusal.failure("The relay transport is closed.")
|
|
289
|
+
start(socketId, Request.Builder().url(target(url, true)).build())
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
private fun start(socketId: String, request: Request) {
|
|
293
|
+
// Callbacks end a socket under the same lock, so one cannot finish before it is registered.
|
|
294
|
+
synchronized(this) {
|
|
295
|
+
if (sockets.size >= MAX_SOCKETS || sockets.containsKey(socketId)) throw Refusal.failure("Too many LAN sockets.")
|
|
296
|
+
sockets[socketId] = socketClient.newWebSocket(request, listener(socketId))
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
private fun event(socketId: String, kind: String): Map<String, Any?> =
|
|
301
|
+
mapOf("transportId" to transportId, "socketId" to socketId, "kind" to kind)
|
|
302
|
+
|
|
303
|
+
private fun listener(socketId: String) = object : WebSocketListener() {
|
|
304
|
+
override fun onOpen(webSocket: WebSocket, response: Response) {
|
|
305
|
+
if (relayUrl == null) return emit(event(socketId, "open"))
|
|
306
|
+
// A redirect is already refused, but the socket that opened must still be the exact address asked for.
|
|
307
|
+
val opened = "wss://" + response.request.url.toString().removePrefix("https://")
|
|
308
|
+
if (opened != relayUrl) {
|
|
309
|
+
end(socketId, Refusal.trust("The relay socket did not stay at its exact address."), 1008)
|
|
310
|
+
webSocket.cancel()
|
|
311
|
+
return
|
|
312
|
+
}
|
|
313
|
+
emit(event(socketId, "open") + ("url" to relayUrl))
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
override fun onMessage(webSocket: WebSocket, text: String) {
|
|
317
|
+
if (text.length > frameLimit) return overflow(webSocket, socketId)
|
|
318
|
+
emit(event(socketId, "message") + ("text" to text))
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
|
|
322
|
+
if (bytes.size > frameLimit) return overflow(webSocket, socketId)
|
|
323
|
+
emit(event(socketId, "message") + ("base64" to bytes.base64()))
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
|
|
327
|
+
webSocket.close(1000, null)
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
|
331
|
+
end(socketId, null, code)
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
|
335
|
+
// A handshake answered with a redirect is refused as a trust failure, never followed.
|
|
336
|
+
val refusal = if (response != null && response.code in 300..399) {
|
|
337
|
+
Refusal.trust("The LAN host redirected the request.")
|
|
338
|
+
} else {
|
|
339
|
+
refusal(t, null)
|
|
340
|
+
}
|
|
341
|
+
end(socketId, refusal, 1006)
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
private fun overflow(webSocket: WebSocket, socketId: String) {
|
|
346
|
+
end(socketId, Refusal.failure("The LAN socket sent an invalid or oversized frame."), 1009)
|
|
347
|
+
webSocket.cancel()
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** The one place a socket ends, whichever callback arrives first. */
|
|
351
|
+
private fun end(socketId: String, refusal: Refusal?, closeCode: Int) {
|
|
352
|
+
synchronized(this) {
|
|
353
|
+
if (sockets.remove(socketId) == null) return
|
|
354
|
+
}
|
|
355
|
+
val requested = closing.remove(socketId)
|
|
356
|
+
if (!requested && refusal != null) {
|
|
357
|
+
emit(event(socketId, "error") + mapOf("code" to refusal.code, "message" to refusal.message))
|
|
358
|
+
}
|
|
359
|
+
// The relay tells a refused join (a policy close) from a dropped connection by this code.
|
|
360
|
+
emit(if (relayUrl == null) event(socketId, "close") else event(socketId, "close") + ("code" to closeCode))
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
fun send(socketId: String, base64: String, promise: Promise) {
|
|
364
|
+
val socket = sockets[socketId]
|
|
365
|
+
val bytes = try {
|
|
366
|
+
decode(base64)
|
|
367
|
+
} catch (refusal: Refusal) {
|
|
368
|
+
null
|
|
369
|
+
}
|
|
370
|
+
if (socket == null || bytes == null || bytes.size > frameLimit || !socket.send(bytes.toByteString())) {
|
|
371
|
+
promise.reject(FAILURE, "The LAN socket send failed.", null)
|
|
372
|
+
} else {
|
|
373
|
+
promise.resolve()
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Text frames exist for the relay's join message only. */
|
|
378
|
+
fun sendText(socketId: String, text: String, promise: Promise) {
|
|
379
|
+
val socket = sockets[socketId]
|
|
380
|
+
if (relayUrl == null || socket == null || text.toByteArray(Charsets.UTF_8).size > RELAY_MAX_BYTES || !socket.send(text)) {
|
|
381
|
+
promise.reject(FAILURE, "The relay socket send failed.", null)
|
|
382
|
+
} else {
|
|
383
|
+
promise.resolve()
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
fun closeSocket(socketId: String) {
|
|
388
|
+
val socket = sockets[socketId] ?: return
|
|
389
|
+
closing.add(socketId)
|
|
390
|
+
socket.close(1000, null)
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
fun close() {
|
|
394
|
+
closed = true
|
|
395
|
+
calls.values.forEach { it.cancel() }
|
|
396
|
+
calls.clear()
|
|
397
|
+
val open = synchronized(this) {
|
|
398
|
+
val all = sockets.values.toList()
|
|
399
|
+
sockets.clear()
|
|
400
|
+
all
|
|
401
|
+
}
|
|
402
|
+
open.forEach { it.cancel() }
|
|
403
|
+
http.dispatcher.executorService.shutdown()
|
|
404
|
+
http.connectionPool.evictAll()
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
class PoLanTlsModule : Module() {
|
|
409
|
+
private val transports = ConcurrentHashMap<String, Transport>()
|
|
410
|
+
|
|
411
|
+
override fun definition() = ModuleDefinition {
|
|
412
|
+
Name("PoLanTls")
|
|
413
|
+
Events("onSocket")
|
|
414
|
+
|
|
415
|
+
OnDestroy {
|
|
416
|
+
transports.values.forEach { it.close() }
|
|
417
|
+
transports.clear()
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
Function("openTransport") { transportId: String, origin: String, certificateSha256: String ->
|
|
421
|
+
val url = origin.toHttpUrlOrNull()
|
|
422
|
+
val pin = decodePin(certificateSha256)
|
|
423
|
+
if (url == null || url.scheme != "https" || url.encodedPath != "/" || url.query != null || url.fragment != null ||
|
|
424
|
+
url.username.isNotEmpty() || url.password.isNotEmpty() || pin == null
|
|
425
|
+
) throw Refusal.failure("Invalid LAN origin or certificate pin.")
|
|
426
|
+
synchronized(transports) {
|
|
427
|
+
val existing = transports[transportId]
|
|
428
|
+
if (existing != null) {
|
|
429
|
+
if (existing.relayUrl != null || !existing.host.equals(url.host, ignoreCase = true) || existing.port != url.port ||
|
|
430
|
+
existing.pin?.contentEquals(pin) != true
|
|
431
|
+
) throw Refusal.failure("This LAN transport is already bound to another host.")
|
|
432
|
+
} else {
|
|
433
|
+
if (transports.size >= MAX_TRANSPORTS) throw Refusal.failure("Too many LAN transports.")
|
|
434
|
+
transports[transportId] = Transport(transportId, url.host, url.port, pin, null) { body -> sendEvent("onSocket", body) }
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
Unit
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
Function("openRelayTransport") { transportId: String, relayUrl: String ->
|
|
441
|
+
val url = if (RELAY_ADDRESS.matches(relayUrl)) ("https://" + relayUrl.removePrefix("wss://")).toHttpUrlOrNull() else null
|
|
442
|
+
if (url == null || url.username.isNotEmpty() || url.password.isNotEmpty() || url.fragment != null)
|
|
443
|
+
throw Refusal.trust("Invalid relay address.")
|
|
444
|
+
synchronized(transports) {
|
|
445
|
+
val existing = transports[transportId]
|
|
446
|
+
if (existing != null) {
|
|
447
|
+
if (existing.relayUrl != relayUrl) throw Refusal.failure("This transport is already bound to another address.")
|
|
448
|
+
} else {
|
|
449
|
+
if (transports.size >= MAX_TRANSPORTS) throw Refusal.failure("Too many LAN transports.")
|
|
450
|
+
transports[transportId] = Transport(transportId, url.host, url.port, null, relayUrl) { body -> sendEvent("onSocket", body) }
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
Unit
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
Function("closeTransport") { transportId: String ->
|
|
457
|
+
transports.remove(transportId)?.close()
|
|
458
|
+
Unit
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
AsyncFunction("request") { transportId: String, requestId: String, method: String, url: String,
|
|
462
|
+
headers: List<List<String>>, body: String?, promise: Promise ->
|
|
463
|
+
val transport = transports[transportId]
|
|
464
|
+
if (transport == null) {
|
|
465
|
+
promise.reject(FAILURE, "The LAN transport is closed.", null)
|
|
466
|
+
} else {
|
|
467
|
+
transport.request(requestId, method, url, headers, body, promise)
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
Function("cancelRequest") { transportId: String, requestId: String ->
|
|
472
|
+
transports[transportId]?.cancel(requestId)
|
|
473
|
+
Unit
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
Function("openSocket") { transportId: String, socketId: String, url: String, headers: List<List<String>> ->
|
|
477
|
+
val transport = transports[transportId] ?: throw Refusal.failure("The LAN transport is closed.")
|
|
478
|
+
transport.openSocket(socketId, url, headers)
|
|
479
|
+
Unit
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
Function("openRelaySocket") { transportId: String, socketId: String, url: String ->
|
|
483
|
+
val transport = transports[transportId] ?: throw Refusal.failure("The relay transport is closed.")
|
|
484
|
+
transport.openRelaySocket(socketId, url)
|
|
485
|
+
Unit
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
AsyncFunction("sendSocketText") { transportId: String, socketId: String, text: String, promise: Promise ->
|
|
489
|
+
val transport = transports[transportId]
|
|
490
|
+
if (transport == null) {
|
|
491
|
+
promise.reject(FAILURE, "The relay socket is not open.", null)
|
|
492
|
+
} else {
|
|
493
|
+
transport.sendText(socketId, text, promise)
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
AsyncFunction("sendSocket") { transportId: String, socketId: String, bodyBase64: String, promise: Promise ->
|
|
498
|
+
val transport = transports[transportId]
|
|
499
|
+
if (transport == null) {
|
|
500
|
+
promise.reject(FAILURE, "The LAN socket is not open.", null)
|
|
501
|
+
} else {
|
|
502
|
+
transport.send(socketId, bodyBase64, promise)
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
Function("closeSocket") { transportId: String, socketId: String ->
|
|
507
|
+
transports[transportId]?.closeSocket(socketId)
|
|
508
|
+
Unit
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** A base64url SHA-256 of the leaf certificate's DER bytes, exactly 32 bytes once decoded. */
|
|
513
|
+
private fun decodePin(value: String): ByteArray? {
|
|
514
|
+
if (value.length != 43) return null
|
|
515
|
+
return try {
|
|
516
|
+
Base64.decode(value, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING).takeIf { it.size == 32 }
|
|
517
|
+
} catch (error: IllegalArgumentException) {
|
|
518
|
+
null
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
}
|