Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / uniflix / src / main / java / com / vayunmathur / uniflix / data / JsPluginEngine.kt

JsPluginEngine.kt330 lines · 14.3 KiBRaw
1package com.vayunmathur.uniflix.data
2
3import com.dokar.quickjs.QuickJs
4import com.dokar.quickjs.QuickJsException
5import com.dokar.quickjs.QuickJsInterruptedException
6import com.dokar.quickjs.binding.function
7import com.dylibso.chicory.runtime.Instance
8import com.dylibso.chicory.wasm.Parser
9import com.vayunmathur.uniflix.domain.JsPluginManifest
10import kotlinx.coroutines.Dispatchers
11import kotlinx.coroutines.TimeoutCancellationException
12import kotlinx.coroutines.runBlocking
13import kotlinx.coroutines.withTimeout
14import kotlinx.serialization.builtins.ListSerializer
15import kotlinx.serialization.builtins.serializer
16import kotlinx.serialization.json.Json
17import java.security.SecureRandom
18import javax.crypto.Cipher
19import javax.crypto.spec.GCMParameterSpec
20import javax.crypto.spec.SecretKeySpec
21
22/**
23 * Wall-clock bound for one plugin call. QuickJS's [QuickJs.evaluationTimeoutMillis]
24 * hard-bounds time spent executing JavaScript; the [withTimeout] below is a
25 * backstop for it, and socket timeouts in [NetworkClientBridge] bound network.
26 */
27private const val ENGINE_TIMEOUT_MS = 15_000L
28private const val BRIDGE_CONNECT_TIMEOUT_MS = 10_000L
29private const val BRIDGE_READ_TIMEOUT_MS = 15_000L
30private const val GCM_TAG_BITS = 128
31
32/** One bridged HTTP response, mirroring NetworkClient's RawResponse. */
33data class FetchResult(
34 val status: Int,
35 val bytes: ByteArray,
36 val headers: Map<String, List<String>> = emptyMap(),
37) {
38 val isSuccess: Boolean get() = status in 200..299
39}
40
41/**
42 * Host HTTP for JS plugins. Production delegates to [NetworkClient] so the
43 * STANDARD trust bundle and pinning apply; tests inject a fake (no Robolectric).
44 */
45interface NetworkBridge {
46 suspend fun fetch(
47 url: String,
48 method: String,
49 headers: Map<String, String>,
50 body: ByteArray?,
51 ): FetchResult
52}
53
54/** Production bridge: all plugin traffic flows through NetworkClient. */
55object NetworkClientBridge : NetworkBridge {
56 override suspend fun fetch(
57 url: String,
58 method: String,
59 headers: Map<String, String>,
60 body: ByteArray?,
61 ): FetchResult {
62 val resp = com.vayunmathur.library.network.NetworkClient.execute(
63 url,
64 method = method,
65 headers = headers,
66 body = body,
67 connectTimeoutMs = BRIDGE_CONNECT_TIMEOUT_MS,
68 readTimeoutMs = BRIDGE_READ_TIMEOUT_MS,
69 )
70 return FetchResult(status = resp.status, bytes = resp.bytes, headers = resp.headers)
71 }
72}
73
74private val bridgeJson = Json { ignoreUnknownKeys = true }
75
76/** Live WASM instances for one engine invocation, keyed by small integer handles. */
77private class WasmTable {
78 private var nextId = 1
79 private val instances = mutableMapOf<Int, Instance>()
80
81 fun add(bytes: ByteArray): Int {
82 // Zero-import modules take the empty-imports path; the default memory
83 // factory is ByteBufferMemory, the Android-preferred implementation.
84 // Never select ByteArrayMemory (VarHandle/MethodHandles).
85 val instance = Instance.builder(Parser.parse(bytes)).build()
86 val id = nextId++
87 instances[id] = instance
88 return id
89 }
90
91 fun get(id: Int): Instance = instances[id] ?: error("__uwasm: unknown handle $id")
92}
93
94/**
95 * Runs one installable JS plugin inside QuickJS with generic host capabilities.
96 *
97 * The contract is fully synchronous by design: plugin functions
98 * (`resolve(args)`, `servers()`, `alternates(args)`) are plain sync functions
99 * returning JSON strings, and every host binding is a sync `function`. In
100 * particular `__ufetch` blocks the JS thread (via `runBlocking` over
101 * [NetworkBridge]) instead of returning a promise — quickjs-kt only unwraps a
102 * promise result on paths no plugin should depend on, so promises are kept
103 * out of the contract entirely.
104 *
105 * Exposed globals (capabilities only — no provider logic, origins, or keys):
106 * - `__ufetch(url, method, headersJson, body?)` -> `{status, ok, text, bytes, headers}` (blocking)
107 * - `__uwasm_embedded()` -> handle for the plugin's embedded WASM section (0 when absent)
108 * - `__uwasm_new(bytes)` / `__uwasm_alloc(handle, size)` / `__uwasm_write(handle, ptr, data)` /
109 * `__uwasm_read(handle, ptr, len)` / `__uwasm_call(handle, name, argsJson)` / `__uwasm_free(handle, ptr, size)`
110 * - `__uaesgcm_open(key, iv, aad, ctAndTag)` -> plaintext bytes (throws on auth failure)
111 * - `__urand(n)` -> n random bytes
112 *
113 * Byte arrays cross the boundary as `Uint8Array` (Kotlin `UByteArray`); inputs
114 * also accept `Int8Array` (Kotlin `ByteArray`).
115 *
116 * A fresh runtime is created per call and closed in `finally`. There is no
117 * DOM, no fetch, and no system trust — all network flows through
118 * [NetworkBridge].
119 */
120@OptIn(ExperimentalUnsignedTypes::class)
121class JsPluginEngine(
122 private val manifest: JsPluginManifest,
123 private val network: NetworkBridge,
124 private val timeoutMs: Long = ENGINE_TIMEOUT_MS,
125 private val bridgeTimeoutMs: Long = timeoutMs,
126) {
127 /** Calls `resolve(args)`; returns the plugin's JSON string. */
128 suspend fun resolve(argsJson: String): String = call("resolve", argsJson)
129
130 /** Calls `servers()`; returns the plugin's JSON string array. */
131 suspend fun servers(): String = call("servers", null)
132
133 /** Calls `alternates(args)`; `[]` when the plugin does not define it. */
134 suspend fun alternates(argsJson: String): String =
135 runCatching { call("alternates", argsJson) }.getOrDefault("[]")
136
137 private suspend fun call(function: String, argsJson: String?): String {
138 val qjs = runCatching { QuickJs.create(Dispatchers.Default) }.getOrElse {
139 error("'${manifest.name}' could not start JS runtime: ${it.message}")
140 }
141 try {
142 qjs.evaluationTimeoutMillis = timeoutMs
143 val wasm = WasmTable()
144 defineFetch(qjs)
145 defineWasm(qjs, wasm)
146 defineCrypto(qjs)
147 return withTimeout(timeoutMs) {
148 runCatching {
149 qjs.evaluate<Unit>(manifest.jsSource, "${manifest.id}.js")
150 }.getOrElse {
151 throw mapError("failed to load: ${it.message}")
152 }
153 // Args travel as a JSON string literal parsed inside JS, so
154 // object literals never hit expression-position parsing and
155 // quoting is handled by the JSON encoding, not by hand.
156 //
157 // One sync IIFE per call: the async-constructor check rejects
158 // promise-returning plugin fns up front (quickjs-kt does not
159 // unwrap promise results on the JNI path), and the typeof
160 // check keeps non-string returns as JS errors with the fn
161 // name instead of converter failures.
162 val args = if (argsJson == null) {
163 "undefined"
164 } else {
165 "JSON.parse(${bridgeJson.encodeToString(argsJson)})"
166 }
167 val expression = "(() => { if ($function.constructor.name === 'AsyncFunction') " +
168 "throw new Error('$function() must be sync and return a JSON string (no promises)'); " +
169 "var r = $function($args); " +
170 "if (typeof r !== 'string') throw new Error('$function() must return a JSON string'); " +
171 "return r; })()"
172 val raw = runCatching {
173 qjs.evaluate<String>(expression, "${manifest.id}.js")
174 }.getOrElse {
175 throw mapError(it)
176 }
177 if (raw.startsWith("Promise {")) {
178 throw mapError("$function() must be sync and return a JSON string (no promises)")
179 }
180 raw
181 }
182 } catch (e: TimeoutCancellationException) {
183 qjs.interruptEvaluation()
184 throw IllegalStateException("'${manifest.name}' timed out after ${timeoutMs}ms")
185 } finally {
186 runCatching { qjs.close() }
187 }
188 }
189
190 private fun mapError(cause: Throwable): Throwable {
191 // Structured cancellation (outer withTimeout) must propagate as-is so
192 // the caller's catch maps it to the timeout message; wrapping it here
193 // would defeat the deadline.
194 if (cause is TimeoutCancellationException) throw cause
195 if (cause is QuickJsInterruptedException) {
196 return IllegalStateException("'${manifest.name}' timed out after ${timeoutMs}ms")
197 }
198 if (cause is QuickJsException) {
199 val location = listOfNotNull(cause.fileName, cause.lineNumber?.let { ":$it" })
200 .joinToString("").ifBlank { null }
201 val detail = listOfNotNull(cause.message, location?.let { "at $it" }).joinToString(" ")
202 return IllegalStateException("'${manifest.name}' error: $detail")
203 }
204 return IllegalStateException("'${manifest.name}' error: ${cause.message}")
205 }
206
207 private fun mapError(message: String): Throwable =
208 IllegalStateException("'${manifest.name}' $message")
209
210 private fun defineFetch(qjs: QuickJs) {
211 // Sync binding over a suspend bridge: blocks the evaluating worker
212 // while the fetch runs on IO. Safe because the bridge never re-enters
213 // this QuickJs instance (it only touches NetworkClient), and the
214 // registry resolves addons sequentially so at most one worker blocks.
215 qjs.function("__ufetch") { args ->
216 val url = args.getOrNull(0) as? String ?: error("__ufetch: url must be a string")
217 val method = args.getOrNull(1) as? String ?: "GET"
218 val headersJson = args.getOrNull(2) as? String ?: "{}"
219 val body = args.bytesOrNull(3)
220 val headers = runCatching {
221 bridgeJson.decodeFromString<Map<String, String>>(headersJson)
222 }.getOrDefault(emptyMap())
223 val res = runBlocking(Dispatchers.IO) {
224 // Bounded here, not just by the outer withTimeout: the worker
225 // thread blocks inside this binding, so an unbounded fetch
226 // would wedge it past every outer deadline.
227 withTimeout(bridgeTimeoutMs) { network.fetch(url, method, headers, body) }
228 }
229 bridgeJson.encodeToString(
230 FetchResponse.serializer(),
231 FetchResponse(
232 status = res.status,
233 ok = res.isSuccess,
234 text = res.bytes.toString(Charsets.UTF_8),
235 bytes = java.util.Base64.getEncoder().encodeToString(res.bytes),
236 ),
237 )
238 }
239 }
240
241 private fun defineWasm(qjs: QuickJs, table: WasmTable) {
242 qjs.function("__uwasm_embedded") {
243 val bytes = manifest.wasmBytes ?: return@function 0
244 table.add(bytes)
245 }
246 qjs.function("__uwasm_new") { args ->
247 table.add(args.bytes(0, "__uwasm_new"))
248 }
249 qjs.function("__uwasm_alloc") { args ->
250 val handle = args.int(0, "__uwasm_alloc")
251 val size = args.int(1, "__uwasm_alloc")
252 table.get(handle).export("alloc").apply(size.toLong())[0].toInt()
253 }
254 qjs.function("__uwasm_write") { args ->
255 val handle = args.int(0, "__uwasm_write")
256 val ptr = args.int(1, "__uwasm_write")
257 val data = args.bytes(2, "__uwasm_write")
258 table.get(handle).exports().memory("memory").write(ptr, data)
259 true
260 }
261 qjs.function("__uwasm_read") { args ->
262 val handle = args.int(0, "__uwasm_read")
263 val ptr = args.int(1, "__uwasm_read")
264 val len = args.int(2, "__uwasm_read")
265 table.get(handle).exports().memory("memory").readBytes(ptr, len).asUByteArray()
266 }
267 qjs.function("__uwasm_call") { args ->
268 val handle = args.int(0, "__uwasm_call")
269 val name = args.getOrNull(1) as? String ?: error("__uwasm_call: name required")
270 val paramsJson = args.getOrNull(2) as? String ?: "[]"
271 val params = runCatching {
272 bridgeJson.decodeFromString(ListSerializer(Long.serializer()), paramsJson)
273 }.getOrElse { error("__uwasm_call: args must be a JSON array of numbers") }
274 table.get(handle).export(name).apply(*params.toLongArray())[0]
275 }
276 qjs.function("__uwasm_free") { args ->
277 val handle = args.int(0, "__uwasm_free")
278 val ptr = args.int(1, "__uwasm_free")
279 val size = args.int(2, "__uwasm_free")
280 table.get(handle).export("dealloc").apply(ptr.toLong(), size.toLong())
281 true
282 }
283 }
284
285 private fun defineCrypto(qjs: QuickJs) {
286 qjs.function("__uaesgcm_open") { args ->
287 val key = args.bytes(0, "__uaesgcm_open")
288 val iv = args.bytes(1, "__uaesgcm_open")
289 val aad = args.bytes(2, "__uaesgcm_open")
290 val ct = args.bytes(3, "__uaesgcm_open")
291 val cipher = Cipher.getInstance("AES/GCM/NoPadding")
292 cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(GCM_TAG_BITS, iv))
293 cipher.updateAAD(aad)
294 cipher.doFinal(ct).asUByteArray()
295 }
296 qjs.function("__urand") { args ->
297 val n = args.int(0, "__urand")
298 if (n < 0 || n > 1024) error("__urand: byte count out of range")
299 ByteArray(n).also { SecureRandom().nextBytes(it) }.asUByteArray()
300 }
301 }
302
303 private fun Array<Any?>.int(index: Int, what: String): Int =
304 (getOrNull(index) as? Number)?.toInt() ?: error("$what: numeric argument required")
305
306 /** Accepts `Uint8Array` (UByteArray) or `Int8Array` (ByteArray) from JS. */
307 private fun Array<Any?>.bytes(index: Int, what: String): ByteArray =
308 bytesOrNull(index) ?: error("$what: byte array required")
309
310 private fun Array<Any?>.bytesOrNull(index: Int): ByteArray? =
311 when (val value = getOrNull(index)) {
312 null -> null
313 is ByteArray -> value
314 is UByteArray -> value.asByteArray()
315 else -> null
316 }
317}
318
319/**
320 * `__ufetch` result as a JSON string (not a JS object): string returns are
321 * the proven marshalling shape, so structured host results cross as JSON the
322 * plugin parses. `bytes` is base64; decode with a tiny `b64ToBytes` helper.
323 */
324@kotlinx.serialization.Serializable
325private data class FetchResponse(
326 val status: Int,
327 val ok: Boolean,
328 val text: String,
329 val bytes: String,
330)