@elurjs/android 0.0.0-stage → 0.2.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 (145) hide show
  1. package/README.md +10 -2
  2. package/index.mjs +11 -0
  3. package/package.json +29 -4
  4. package/template/.gitkeep +0 -0
  5. package/template/app/build.gradle.kts +192 -0
  6. package/template/app/proguard-rules-elur.pro +12 -0
  7. package/template/app/proguard-rules.pro +3 -0
  8. package/template/app/src/main/AndroidManifest.xml +81 -0
  9. package/template/app/src/main/assets/oss-notices.txt +153 -0
  10. package/template/app/src/main/assets/tck_pixel.png +0 -0
  11. package/template/app/src/main/cpp/CMakeLists.txt +117 -0
  12. package/template/app/src/main/cpp/dlEncoder.h +117 -0
  13. package/template/app/src/main/cpp/dlEncoderJsi.cpp +315 -0
  14. package/template/app/src/main/cpp/dlEncoderQjs.cpp +394 -0
  15. package/template/app/src/main/cpp/dlOps.inc +145 -0
  16. package/template/app/src/main/cpp/elurBridge.cpp +1350 -0
  17. package/template/app/src/main/cpp/elurBridgeHermes.cpp +1294 -0
  18. package/template/app/src/main/cpp/elurSkia.cpp +287 -0
  19. package/template/app/src/main/cpp/elurSkiaTree.cpp +448 -0
  20. package/template/app/src/main/cpp/elurUiWorklet.cpp +1233 -0
  21. package/template/app/src/main/cpp/elurYoga.cpp +1060 -0
  22. package/template/app/src/main/cpp/elurYoga.h +82 -0
  23. package/template/app/src/main/cpp/hermes-libs/LICENSE +21 -0
  24. package/template/app/src/main/cpp/hermes-libs/arm64-v8a/libhermesvm.so +0 -0
  25. package/template/app/src/main/cpp/hermes-libs/include/hermes/AsyncDebuggerAPI.h +276 -0
  26. package/template/app/src/main/cpp/hermes-libs/include/hermes/CompileJS.h +97 -0
  27. package/template/app/src/main/cpp/hermes-libs/include/hermes/DebuggerAPI.h +502 -0
  28. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/CrashManager.h +107 -0
  29. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/CtorConfig.h +145 -0
  30. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/DebuggerTypes.h +193 -0
  31. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/GCConfig.h +211 -0
  32. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/GCTripwireContext.h +40 -0
  33. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/HermesExport.h +14 -0
  34. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/JSOutOfMemoryError.h +27 -0
  35. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/RuntimeConfig.h +141 -0
  36. package/template/app/src/main/cpp/hermes-libs/include/hermes/Public/SamplingProfiler.h +270 -0
  37. package/template/app/src/main/cpp/hermes-libs/include/hermes/RuntimeTaskRunner.h +64 -0
  38. package/template/app/src/main/cpp/hermes-libs/include/hermes/SynthTrace.h +1566 -0
  39. package/template/app/src/main/cpp/hermes-libs/include/hermes/SynthTraceParser.h +37 -0
  40. package/template/app/src/main/cpp/hermes-libs/include/hermes/ThreadSafetyAnalysis.h +75 -0
  41. package/template/app/src/main/cpp/hermes-libs/include/hermes/TimerStats.h +23 -0
  42. package/template/app/src/main/cpp/hermes-libs/include/hermes/TraceInterpreter.h +334 -0
  43. package/template/app/src/main/cpp/hermes-libs/include/hermes/TracingRuntime.h +328 -0
  44. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/CDPAgent.h +131 -0
  45. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/CDPDebugAPI.h +73 -0
  46. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/CallbackOStream.h +89 -0
  47. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/ConsoleMessage.h +135 -0
  48. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/DebuggerDomainAgent.h +280 -0
  49. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/DebuggerDomainCoordinator.h +137 -0
  50. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/DomainAgent.h +107 -0
  51. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/DomainState.h +140 -0
  52. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/HeapProfilerDomainAgent.h +71 -0
  53. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/JSONValueInterfaces.h +40 -0
  54. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageConverters.h +82 -0
  55. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageInterfaces.h +72 -0
  56. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageTypes.h +1279 -0
  57. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/MessageTypesInlines.h +313 -0
  58. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/ProfilerDomainAgent.h +38 -0
  59. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/RemoteObjectConverters.h +77 -0
  60. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/RemoteObjectsTable.h +127 -0
  61. package/template/app/src/main/cpp/hermes-libs/include/hermes/cdp/RuntimeDomainAgent.h +138 -0
  62. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/Dummy.h +24 -0
  63. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/Extensions.h +20 -0
  64. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/ExtensionsBytecode.h +23 -0
  65. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/Intrinsics.h +44 -0
  66. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/JSIUtils.h +123 -0
  67. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/TextEncoder.h +29 -0
  68. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/ContribDummy.h +24 -0
  69. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/ContribExtensions.h +23 -0
  70. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/TextDecoder.h +30 -0
  71. package/template/app/src/main/cpp/hermes-libs/include/hermes/extensions/contrib/TextDecoderUtils.h +113 -0
  72. package/template/app/src/main/cpp/hermes-libs/include/hermes/hermes.h +242 -0
  73. package/template/app/src/main/cpp/hermes-libs/include/hermes/hermes_tracing.h +52 -0
  74. package/template/app/src/main/cpp/hermes-libs/include/hermes_abi/HermesABIHelpers.h +295 -0
  75. package/template/app/src/main/cpp/hermes-libs/include/hermes_abi/HermesABIRuntimeWrapper.h +25 -0
  76. package/template/app/src/main/cpp/hermes-libs/include/hermes_abi/hermes_abi.h +642 -0
  77. package/template/app/src/main/cpp/hermes-libs/include/hermes_abi/hermes_vtable.h +29 -0
  78. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/HermesSandboxRuntime.h +41 -0
  79. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_compiled.h +12 -0
  80. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_dbg_compiled-impl.h +8516 -0
  81. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_dbg_compiled.h +137 -0
  82. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_opt_compiled-impl.h +3945 -0
  83. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/hermes_sandbox_impl_opt_compiled.h +119 -0
  84. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt-fb.h +124 -0
  85. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt-impl.h +66 -0
  86. package/template/app/src/main/cpp/hermes-libs/include/hermes_sandbox/external/wasm-rt.h +456 -0
  87. package/template/app/src/main/cpp/hermes-libs/include/jsi/JSIDynamic.h +26 -0
  88. package/template/app/src/main/cpp/hermes-libs/include/jsi/decorator.h +1157 -0
  89. package/template/app/src/main/cpp/hermes-libs/include/jsi/hermes-interfaces.h +242 -0
  90. package/template/app/src/main/cpp/hermes-libs/include/jsi/instrumentation.h +132 -0
  91. package/template/app/src/main/cpp/hermes-libs/include/jsi/jsi-inl.h +434 -0
  92. package/template/app/src/main/cpp/hermes-libs/include/jsi/jsi.h +2266 -0
  93. package/template/app/src/main/cpp/hermes-libs/include/jsi/jsilib.h +59 -0
  94. package/template/app/src/main/cpp/hermes-libs/include/jsi/threadsafe.h +79 -0
  95. package/template/app/src/main/cpp/hermes-libs/jsi-impl/jsi.cpp +1111 -0
  96. package/template/app/src/main/cpp/hermes-libs/x86_64/libhermesvm.so +0 -0
  97. package/template/app/src/main/java/com/elur/universal/BinaryCodec.kt +121 -0
  98. package/template/app/src/main/java/com/elur/universal/DlDecoder.kt +260 -0
  99. package/template/app/src/main/java/com/elur/universal/DlOpsDecode.kt +158 -0
  100. package/template/app/src/main/java/com/elur/universal/ElurBoxDrawable.kt +161 -0
  101. package/template/app/src/main/java/com/elur/universal/ElurBridge.kt +238 -0
  102. package/template/app/src/main/java/com/elur/universal/ElurBridgeHermes.kt +223 -0
  103. package/template/app/src/main/java/com/elur/universal/ElurCanvasView.kt +202 -0
  104. package/template/app/src/main/java/com/elur/universal/ElurCryptoModule.kt +206 -0
  105. package/template/app/src/main/java/com/elur/universal/ElurCustomLayout.kt +185 -0
  106. package/template/app/src/main/java/com/elur/universal/ElurEditText.kt +17 -0
  107. package/template/app/src/main/java/com/elur/universal/ElurFontRegistry.kt +190 -0
  108. package/template/app/src/main/java/com/elur/universal/ElurHttpModule.kt +306 -0
  109. package/template/app/src/main/java/com/elur/universal/ElurImageService.kt +348 -0
  110. package/template/app/src/main/java/com/elur/universal/ElurLicensesActivity.kt +84 -0
  111. package/template/app/src/main/java/com/elur/universal/ElurListView.kt +954 -0
  112. package/template/app/src/main/java/com/elur/universal/ElurManifest.kt +117 -0
  113. package/template/app/src/main/java/com/elur/universal/ElurMetrics.kt +325 -0
  114. package/template/app/src/main/java/com/elur/universal/ElurModuleRegistrar.kt +14 -0
  115. package/template/app/src/main/java/com/elur/universal/ElurPermissionGate.kt +36 -0
  116. package/template/app/src/main/java/com/elur/universal/ElurRenderer.kt +6164 -0
  117. package/template/app/src/main/java/com/elur/universal/ElurRowYoga.kt +130 -0
  118. package/template/app/src/main/java/com/elur/universal/ElurScrollView.kt +240 -0
  119. package/template/app/src/main/java/com/elur/universal/ElurShellView.kt +117 -0
  120. package/template/app/src/main/java/com/elur/universal/ElurSkiaCanvasView.kt +162 -0
  121. package/template/app/src/main/java/com/elur/universal/ElurSkiaTreeRenderer.kt +968 -0
  122. package/template/app/src/main/java/com/elur/universal/ElurStateModule.kt +69 -0
  123. package/template/app/src/main/java/com/elur/universal/ElurSwipeDriver.kt +34 -0
  124. package/template/app/src/main/java/com/elur/universal/ElurTckModule.kt +99 -0
  125. package/template/app/src/main/java/com/elur/universal/ElurTextMeasure.kt +16 -0
  126. package/template/app/src/main/java/com/elur/universal/ElurTrace.kt +24 -0
  127. package/template/app/src/main/java/com/elur/universal/ElurUiModule.kt +48 -0
  128. package/template/app/src/main/java/com/elur/universal/ElurUiWorklet.kt +305 -0
  129. package/template/app/src/main/java/com/elur/universal/JsBridge.kt +67 -0
  130. package/template/app/src/main/java/com/elur/universal/JsThread.kt +189 -0
  131. package/template/app/src/main/java/com/elur/universal/MainActivity.kt +844 -0
  132. package/template/app/src/main/java/com/elur/universal/ModuleRegistry.kt +701 -0
  133. package/template/app/src/main/java/com/elur/universal/YogaRowScope.kt +97 -0
  134. package/template/app/src/main/res/values/ids.xml +10 -0
  135. package/template/app/src/main/res/values/strings.xml +8 -0
  136. package/template/app/src/main/res/values-es/strings.xml +5 -0
  137. package/template/app/src/main/res/xml/network_security_config.xml +10 -0
  138. package/template/build.gradle.kts +5 -0
  139. package/template/gradle/libs.versions.toml +12 -0
  140. package/template/gradle/wrapper/gradle-wrapper.jar +0 -0
  141. package/template/gradle/wrapper/gradle-wrapper.properties +8 -0
  142. package/template/gradle.properties +23 -0
  143. package/template/gradlew +251 -0
  144. package/template/gradlew.bat +94 -0
  145. package/template/settings.gradle.kts +32 -0
@@ -0,0 +1,306 @@
1
+ package com.elur.universal
2
+
3
+ import java.net.HttpURLConnection
4
+ import java.net.InetAddress
5
+ import java.net.Socket
6
+ import java.net.URL
7
+ import javax.net.ssl.HostnameVerifier
8
+ import javax.net.ssl.HttpsURLConnection
9
+ import javax.net.ssl.SNIHostName
10
+ import javax.net.ssl.SSLSocket
11
+ import javax.net.ssl.SSLSocketFactory
12
+ import org.json.JSONObject
13
+
14
+ // Módulo nativo "http" (ADR-0184 §consumidor): transporte del cliente
15
+ // SDUI — el motor embebido no tiene fetch; la petición corre en la cola
16
+ // "worker" del registry y responde por reply.ok/err.
17
+ //
18
+ // Comando "request" — httpModuleDef (src/sdui/httpModule.ts):
19
+ // input { method, url, headers?, body?, allow?, allowPrivate? } —
20
+ // headers es objeto JSON plano; body texto ya serializado.
21
+ // `allow` es la lista de egreso `host[:port]` (sin esquema) que
22
+ // declara el transporte del cliente; `allowPrivate` permite
23
+ // destinos en rangos reservados (default: denegado en saltos).
24
+ // output { status, body, finalUrl } — status real (0 = sin respuesta
25
+ // no llega aquí: eso es reply.err "network"); body crudo
26
+ // (errorStream en 4xx/5xx — el status viaja igual, la política
27
+ // es del cliente); finalUrl = URL tras el último salto.
28
+ // Límites: 10 s connect+read por salto; body de respuesta acotado a
29
+ // 4 MiB — más grande → err "body_too_large", nunca OOM en el worker.
30
+ //
31
+ // ADR-0188 §egreso — redirects NO son automáticos
32
+ // (instanceFollowRedirects=false): un 302 a otro host evadía la
33
+ // allowlist del transporte, que solo veía la URL inicial. Cada salto
34
+ // re-chequea el destino:
35
+ // · esquema http(s) solamente (file:/ftp:/jar: no saltan);
36
+ // · `allow` declarado → todo salto (incluido el inicial) debe estar
37
+ // en la lista — la declaración explícita gana al chequeo de
38
+ // rangos (un host declarado puede ser privado, p.ej. 10.0.2.2);
39
+ // · `allow` ausente → en TODO salto el destino se resuelve por DNS
40
+ // (InetAddress.getAllByName) y se deniega si cualquier IP es
41
+ // loopback/any-local/link-local/site-local/multicast — el chequeo
42
+ // es sobre la IP conectada, no sobre el nombre;
43
+ // sin allow no hay destino privado implícito (SSRF de primer hop).
44
+ // · `allowPrivate:true` desactiva el chequeo de rangos — escape
45
+ // declarado, nunca implícito.
46
+ // ADR-0189 §pinning — el DNS se resuelve UNA vez por salto y la
47
+ // conexión se fija a la primera IP de ESA respuesta (pinHop): sin pin
48
+ // había una ventana TOCTOU — el chequeo validaba la respuesta A1 y
49
+ // openConnection resolvía de nuevo pudiendo recibir A2 (rebinding).
50
+ // El socket ya no vuelve a consultar DNS; Host header, SNI y la
51
+ // verificación del certificado preservan el hostname original.
52
+ // Coste declarado: se pierde el fallback multi-IP del stack (antes
53
+ // probaba la siguiente IP si la primera moría); una IP pineada caída
54
+ // da err "network".
55
+ // Violación → err "egress_denied"; más de 5 saltos → "too_many_redirects".
56
+ class ElurHttpModule : ElurModule {
57
+ override val name = "http"
58
+
59
+ override fun threading(command: String): String = if (command == "request") "worker" else "main"
60
+
61
+ override fun onCommand(callId: Int, command: String, argsJson: String, reply: ModuleReply) {
62
+ when (command) {
63
+ "request" -> {
64
+ val a = JSONObject(argsJson)
65
+ val allow =
66
+ a.optJSONArray("allow")?.let { j ->
67
+ (0 until j.length()).map { j.optString(it) }
68
+ }
69
+ doRequest(
70
+ a.optString("method", "GET"),
71
+ a.optString("url"),
72
+ a.optJSONObject("headers"),
73
+ if (a.isNull("body")) null else a.optString("body"),
74
+ allow,
75
+ a.optBoolean("allowPrivate", false),
76
+ reply,
77
+ )
78
+ }
79
+ else -> reply.err("unknown_command", "comando desconocido: $command")
80
+ }
81
+ }
82
+
83
+ private class EgressDenied(msg: String) : Exception(msg)
84
+
85
+ private fun doRequest(
86
+ method: String,
87
+ url: String,
88
+ headers: JSONObject?,
89
+ body: String?,
90
+ allow: List<String>?,
91
+ allowPrivate: Boolean,
92
+ reply: ModuleReply,
93
+ ) {
94
+ if (url.isEmpty()) {
95
+ reply.err("bad_request", "url vacía")
96
+ return
97
+ }
98
+ var current = url
99
+ var currentMethod = method.uppercase()
100
+ var currentBody = body
101
+ var hops = 0
102
+ try {
103
+ while (true) {
104
+ val target = pinHop(current, allow, allowPrivate)
105
+ val conn = URL(target.url).openConnection() as HttpURLConnection
106
+ try {
107
+ if (conn is HttpsURLConnection) {
108
+ conn.sslSocketFactory = pinningSslFactory(target.host)
109
+ conn.hostnameVerifier = HostnameVerifier { _, session ->
110
+ HttpsURLConnection.getDefaultHostnameVerifier()
111
+ .verify(target.host, session)
112
+ }
113
+ }
114
+ conn.instanceFollowRedirects = false
115
+ conn.requestMethod = currentMethod
116
+ conn.connectTimeout = TIMEOUT_MS
117
+ conn.readTimeout = TIMEOUT_MS
118
+ if (headers != null) {
119
+ for (k in headers.keys()) {
120
+ conn.setRequestProperty(k, headers.optString(k))
121
+ }
122
+ }
123
+ // El Host header va tras los headers del llamador:
124
+ // con la URL pineada a la IP, el servidor necesita
125
+ // el hostname original (vhost/TLS) — el pin manda
126
+ // sobre cualquier "Host" que viniera en headers.
127
+ conn.setRequestProperty("Host", target.authority)
128
+ if (currentBody != null) {
129
+ conn.doOutput = true
130
+ if (!headers?.has("content-type").let { it == true }) {
131
+ conn.setRequestProperty("content-type", "application/json")
132
+ }
133
+ conn.outputStream.use { it.write(currentBody.toByteArray(Charsets.UTF_8)) }
134
+ }
135
+ val status = conn.responseCode
136
+ val location = conn.getHeaderField("Location")
137
+ if (status in REDIRECT_CODES && !location.isNullOrEmpty()) {
138
+ hops++
139
+ if (hops > MAX_REDIRECTS) {
140
+ reply.err(
141
+ "too_many_redirects",
142
+ "más de $MAX_REDIRECTS saltos",
143
+ )
144
+ return
145
+ }
146
+ // 303 → GET siempre; 301/302 → GET salvo GET/HEAD
147
+ // (semántica de navegador); 307/308 conservan
148
+ // método y body.
149
+ if (status == 303 ||
150
+ ((status == 301 || status == 302) &&
151
+ currentMethod != "GET" &&
152
+ currentMethod != "HEAD")
153
+ ) {
154
+ currentMethod = "GET"
155
+ currentBody = null
156
+ }
157
+ // Location relativo resuelve contra la URL del salto.
158
+ current = URL(URL(current), location).toExternalForm()
159
+ continue
160
+ }
161
+ val stream = if (status >= 400) conn.errorStream else conn.inputStream
162
+ val text =
163
+ stream?.let { s ->
164
+ val bytes = s.readBytes()
165
+ if (bytes.size > MAX_BODY) {
166
+ reply.err(
167
+ "body_too_large",
168
+ "${bytes.size} > $MAX_BODY bytes",
169
+ )
170
+ conn.disconnect()
171
+ return
172
+ }
173
+ String(bytes, Charsets.UTF_8)
174
+ }
175
+ ?: ""
176
+ reply.ok(
177
+ JSONObject()
178
+ .put("status", status)
179
+ .put("body", text)
180
+ .put("finalUrl", current)
181
+ .toString()
182
+ )
183
+ return
184
+ } finally {
185
+ conn.disconnect()
186
+ }
187
+ }
188
+ } catch (e: EgressDenied) {
189
+ reply.err("egress_denied", e.message ?: "egreso denegado")
190
+ } catch (e: Exception) {
191
+ reply.err("network", "${e.javaClass.simpleName}: ${e.message}")
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Destino pineado de un salto: `url` ya lleva la IP literal validada; `host`/`authority`
197
+ * preservan el nombre original para SNI, el certificado y el Host header.
198
+ */
199
+ private class PinnedTarget(
200
+ val url: String,
201
+ val host: String,
202
+ val authority: String,
203
+ )
204
+
205
+ /**
206
+ * Re-chequeo + pinning por salto — el destino del 30x no hereda la confianza del origen.
207
+ * Resuelve UNA vez: la IP que se conecta es exactamente una de las validadas (TOCTOU cerrado).
208
+ */
209
+ private fun pinHop(
210
+ url: String,
211
+ allow: List<String>?,
212
+ allowPrivate: Boolean,
213
+ ): PinnedTarget {
214
+ val u =
215
+ try {
216
+ URL(url)
217
+ } catch (e: Exception) {
218
+ throw EgressDenied("url no parseable: $url")
219
+ }
220
+ val proto = u.protocol.lowercase()
221
+ if (proto != "http" && proto != "https") {
222
+ throw EgressDenied("esquema no http(s): $proto")
223
+ }
224
+ val host = u.host?.takeIf { it.isNotEmpty() } ?: throw EgressDenied("url sin host: $url")
225
+ val authority = if (u.port >= 0) "$host:${u.port}" else host
226
+ if (allow != null &&
227
+ allow.none {
228
+ it.equals(authority, ignoreCase = true) ||
229
+ it.equals(host, ignoreCase = true)
230
+ }
231
+ ) {
232
+ throw EgressDenied("host fuera de la allowlist de egreso: $authority")
233
+ }
234
+ // Una sola resolución por salto: se valida (sin allow) y se
235
+ // pinea la primera — openConnection ya no vuelve al resolver.
236
+ val ips =
237
+ try {
238
+ InetAddress.getAllByName(host)
239
+ } catch (e: Exception) {
240
+ throw EgressDenied("DNS sin respuesta: $host")
241
+ }
242
+ if (allow == null && !allowPrivate) {
243
+ for (a in ips) {
244
+ if (a.isAnyLocalAddress ||
245
+ a.isLoopbackAddress ||
246
+ a.isLinkLocalAddress ||
247
+ a.isSiteLocalAddress ||
248
+ a.isMulticastAddress
249
+ ) {
250
+ throw EgressDenied(
251
+ "redirect a dirección reservada: " + "$host → ${a.hostAddress}"
252
+ )
253
+ }
254
+ }
255
+ }
256
+ val pinned = ips[0].hostAddress.let { if (it.contains(":")) "[$it]" else it }
257
+ val port = if (u.port >= 0) ":${u.port}" else ""
258
+ val file = u.file?.takeIf { it.isNotEmpty() } ?: "/"
259
+ return PinnedTarget("$proto://$pinned$port$file", host, authority)
260
+ }
261
+
262
+ /**
263
+ * SSLSocketFactory que re-inyecta el SNI del hostname original: la URL pineada lleva una IP
264
+ * literal y Conscrypt no emitiría SNI (o lo derivaría de la IP) — sin SNI los vhosts TLS sirven
265
+ * el certificado equivocado. `SNIHostName` rechaza literales IP: en ese caso no hay SNI que
266
+ * preservar.
267
+ */
268
+ private fun pinningSslFactory(sniHost: String): SSLSocketFactory {
269
+ val delegate = HttpsURLConnection.getDefaultSSLSocketFactory()
270
+ val sni = runCatching { SNIHostName(sniHost) }.getOrNull()
271
+ return object : SSLSocketFactory() {
272
+ private fun tune(s: Socket): Socket {
273
+ if (sni != null && s is SSLSocket) {
274
+ val p = s.sslParameters
275
+ p.serverNames = listOf(sni)
276
+ s.sslParameters = p
277
+ }
278
+ return s
279
+ }
280
+
281
+ override fun getDefaultCipherSuites() = delegate.defaultCipherSuites
282
+ override fun getSupportedCipherSuites() = delegate.supportedCipherSuites
283
+ override fun createSocket(s: Socket, host: String, port: Int, autoClose: Boolean) =
284
+ tune(delegate.createSocket(s, host, port, autoClose))
285
+
286
+ override fun createSocket(host: String, port: Int) =
287
+ tune(delegate.createSocket(host, port))
288
+
289
+ override fun createSocket(host: String, port: Int, local: InetAddress, lp: Int) =
290
+ tune(delegate.createSocket(host, port, local, lp))
291
+
292
+ override fun createSocket(host: InetAddress, port: Int) =
293
+ tune(delegate.createSocket(host, port))
294
+
295
+ override fun createSocket(a: InetAddress, port: Int, l: InetAddress, lp: Int) =
296
+ tune(delegate.createSocket(a, port, l, lp))
297
+ }
298
+ }
299
+
300
+ companion object {
301
+ private const val TIMEOUT_MS = 10_000
302
+ private const val MAX_BODY = 4 * 1024 * 1024
303
+ private const val MAX_REDIRECTS = 5
304
+ private val REDIRECT_CODES = setOf(301, 302, 303, 307, 308)
305
+ }
306
+ }
@@ -0,0 +1,348 @@
1
+ package com.elur.universal
2
+
3
+ import java.util.Collections
4
+ import java.util.WeakHashMap
5
+ import java.util.concurrent.CopyOnWriteArrayList
6
+ import java.util.concurrent.atomic.AtomicInteger
7
+
8
+ /**
9
+ * ADR-0071 / U17 — ImageService: pipeline acotado de imágenes con identidad de request y holder.
10
+ *
11
+ * Clase PURA de JVM (sin tipos Android): V = vista (prod ImageView), B = bitmap decodificado (prod
12
+ * Bitmap). Toda la semántica corre en `testDebugUnitTest` sin Robolectric; el renderer solo inyecta
13
+ * las primitivas del target (fetch/decode/deliver/base64/log).
14
+ *
15
+ * Contratos que cierra la auditoría:
16
+ *
17
+ * - **Identidad de request** = (src, bucket destino): el decode se samplea al tamaño destino — dos
18
+ * vistas con distinto bucket NO comparten fetch ni cache; la URL sola no identifica el recurso.
19
+ * - **Waiters deduplicados por view**: un rebind de la misma vista con la misma src en vuelo
20
+ * reemplaza su waiter (holderId nuevo) — nunca se acumulan entregas repetidas por rebind.
21
+ * - **Purga por holder**: deleteNode(listId) pasa las vistas de los holders (pseudo-ids negativos
22
+ * fuera de `views`) — la purga va por identidad de vista.
23
+ * - **Budgets**: waiters por request acotados, bytes materializados en vuelo contados, y bytes
24
+ * entregados a vistas vivas contados — la cota de cache no ignora los bitmaps que las vistas
25
+ * retienen (deliveredBytes alimenta liveBytes).
26
+ * - **data:** el tamaño decodificado se estima del payload base64 ANTES de materializar el
27
+ * ByteArray — un data: enorme se rechaza sin decodificar un byte.
28
+ */
29
+ class ElurImageService<V : Any, B : Any>(
30
+ private val submit: (task: () -> Unit) -> Unit,
31
+ private val postMain: (action: () -> Unit) -> Unit,
32
+ private val fetchRemote: (src: String) -> ByteArray,
33
+ private val fetchLocal: (src: String) -> ByteArray,
34
+ private val decode: (bytes: ByteArray, targetPx: Int) -> B?,
35
+ private val setImage: (view: V, bmp: B?) -> Unit,
36
+ private val tagOf: (view: V) -> String?,
37
+ private val isAlive: (holderId: Int, view: V) -> Boolean,
38
+ private val byteCountOf: (bmp: B) -> Int,
39
+ private val decodeBase64: (payload: String) -> ByteArray,
40
+ private val log: (msg: String, err: Throwable?) -> Unit,
41
+ /**
42
+ * ADR-0204: entrega final con el bitmap (o null si falló). El renderer
43
+ * decide fallback/`load`/`error` — el servicio no conoce eventos ni
44
+ * props, solo el resultado de la materialización.
45
+ */
46
+ private val onDelivered: (holderId: Int, view: V, bmp: B?) -> Unit = { _, _, _ -> },
47
+ /**
48
+ * ADR-0115: fetch+decode remoto delegado (Coil). Cuando se provee, `loadRemote` lo usa en
49
+ * vez del par fetchRemote+decode — la identidad de request (src+bucket), waiters, budgets y
50
+ * purga se conservan idénticos; solo cambia quién materializa el bitmap. `null` → path
51
+ * clásico HttpURLConnection+decodeSampled.
52
+ */
53
+ private val fetchRemoteDecoded: ((src: String, targetPx: Int) -> B?)? = null,
54
+ ) {
55
+ /** Clave de request/cache: src + bucket de destino. */
56
+ private data class ReqKey(val src: String, val bucket: Int)
57
+
58
+ private class Waiter<V : Any>(var holderId: Int, val view: V)
59
+
60
+ /** LRU por bytes — LinkedHashMap access-order (puro JVM). */
61
+ private class ByteLruCache<K, B>(
62
+ private val maxBytes: Int,
63
+ private val byteCountOf: (B) -> Int,
64
+ ) {
65
+ private val map = object : LinkedHashMap<K, B>(16, 0.75f, true) {}
66
+ private var bytes = 0
67
+
68
+ @Synchronized fun get(k: K): B? = map[k]
69
+
70
+ @Synchronized
71
+ fun put(k: K, v: B) {
72
+ map.remove(k)?.let { bytes -= byteCountOf(it) }
73
+ map[k] = v
74
+ bytes += byteCountOf(v)
75
+ while (bytes > maxBytes && map.isNotEmpty()) {
76
+ val eldest = map.entries.iterator().next()
77
+ bytes -= byteCountOf(eldest.value)
78
+ map.remove(eldest.key)
79
+ }
80
+ }
81
+
82
+ @Synchronized fun size(): Int = bytes
83
+ @Synchronized fun entryCount(): Int = map.size
84
+ @Synchronized
85
+ fun evictAll() {
86
+ map.clear()
87
+ bytes = 0
88
+ }
89
+ }
90
+
91
+ private val cache = ByteLruCache<ReqKey, B>(MAX_CACHE_BYTES, byteCountOf)
92
+ private val inFlight = HashMap<ReqKey, CopyOnWriteArrayList<Waiter<V>>>()
93
+
94
+ /**
95
+ * Bytes entregados a vistas vivas — WeakHashMap: una view GC'd descuenta sola, sin purge
96
+ * manual.
97
+ */
98
+ private val deliveredBytes = WeakHashMap<V, Int>()
99
+ private val liveBytesTotal = AtomicInteger(0)
100
+
101
+ /** Bytes de fetch materializados en vuelo (métrica TCK). */
102
+ private val inFlightBytes = AtomicInteger(0)
103
+
104
+ @Volatile var destroyed = false
105
+
106
+ /**
107
+ * Punto de entrada único. `targetPx` cuantiza a bucket — la request identity incluye el destino
108
+ * (un thumb y un full de la misma src son recursos distintos).
109
+ */
110
+ fun load(holderId: Int, view: V, src: String, targetPx: Int) {
111
+ if (destroyed) return
112
+ when {
113
+ src.startsWith("http") -> loadRemote(holderId, view, src, targetPx)
114
+ src.startsWith("data:") -> loadDataUri(holderId, view, src, targetPx)
115
+ else -> loadLocal(holderId, view, src, targetPx)
116
+ }
117
+ }
118
+
119
+ private fun loadRemote(holderId: Int, view: V, src: String, targetPx: Int) {
120
+ val key = ReqKey(src, destBucket(targetPx))
121
+ cache.get(key)?.let { bmp ->
122
+ deliver(holderId, view, src, bmp)
123
+ return
124
+ }
125
+ val first: Boolean
126
+ synchronized(inFlight) {
127
+ val prev = inFlight[key]
128
+ if (prev != null) {
129
+ first = false
130
+ addWaiter(prev, holderId, view)
131
+ } else {
132
+ first = true
133
+ inFlight[key] =
134
+ CopyOnWriteArrayList<Waiter<V>>().apply { add(Waiter(holderId, view)) }
135
+ }
136
+ }
137
+ if (!first) return
138
+
139
+ try {
140
+ submit {
141
+ var bmp: B? = null
142
+ var fetched = 0
143
+ try {
144
+ if (fetchRemoteDecoded != null) {
145
+ bmp = fetchRemoteDecoded.invoke(src, key.bucket)
146
+ } else {
147
+ val bytes = fetchRemote(src)
148
+ fetched = bytes.size
149
+ inFlightBytes.addAndGet(fetched)
150
+ bmp = decode(bytes, key.bucket)
151
+ }
152
+ // Presión total: si las vistas ya retienen más que el
153
+ // presupuesto live, cachear solo degrada — se entrega
154
+ // sin cachear (la entrega no depende del cache).
155
+ if (bmp != null && liveBytesTotal.get() <= MAX_LIVE_BYTES) {
156
+ cache.put(key, bmp)
157
+ }
158
+ } catch (e: Exception) {
159
+ log("remote image failed: $src", e)
160
+ } finally {
161
+ inFlightBytes.addAndGet(-fetched)
162
+ }
163
+ flushWaiters(key, src, bmp)
164
+ }
165
+ } catch (e: java.util.concurrent.RejectedExecutionException) {
166
+ // Cola llena: la entrada sale y los waiters se liquidan con
167
+ // null (fallback/`error`), sin entrega fantasma — antes se
168
+ // descartaban en silencio y la vista quedaba sin evento.
169
+ log("image queue full: $src", e)
170
+ flushWaiters(key, src, null)
171
+ }
172
+ }
173
+
174
+ private fun loadDataUri(holderId: Int, view: V, src: String, targetPx: Int) {
175
+ if (estimateDataUriBytes(src) > MAX_IMAGE_BYTES) {
176
+ log("data: image over ${MAX_IMAGE_BYTES}B", null)
177
+ // Mismo guard que deliver: una vista rebindeada no se limpia.
178
+ // Pasa por deliverLater para que el renderer reciba el fallo
179
+ // (fallback/`error`) — antes se limpiaba la vista en silencio.
180
+ deliverLater(holderId, view, src, null)
181
+ return
182
+ }
183
+ try {
184
+ submit {
185
+ var bmp: B? = null
186
+ try {
187
+ val bytes = decodeBase64(src.substringAfter(","))
188
+ if (bytes.size <= MAX_IMAGE_BYTES) {
189
+ bmp = decode(bytes, destBucket(targetPx))
190
+ } else {
191
+ log("data: image over ${MAX_IMAGE_BYTES}B", null)
192
+ }
193
+ } catch (e: Exception) {
194
+ log("data: image decode failed", e)
195
+ }
196
+ deliverLater(holderId, view, src, bmp)
197
+ }
198
+ } catch (e: java.util.concurrent.RejectedExecutionException) {
199
+ // ADR-0204: la cola acotada rechaza también data:/local;
200
+ // el resultado null dispara fallback/`error` en vez de dejar
201
+ // la vista colgada sin evento.
202
+ log("image queue full: data uri", e)
203
+ deliverLater(holderId, view, src, null)
204
+ }
205
+ }
206
+
207
+ private fun loadLocal(holderId: Int, view: V, src: String, targetPx: Int) {
208
+ try {
209
+ submit {
210
+ var bmp: B? = null
211
+ try {
212
+ val bytes = fetchLocal(src)
213
+ bmp = decode(bytes, destBucket(targetPx))
214
+ } catch (e: Exception) {
215
+ log("local image failed: $src", e)
216
+ }
217
+ deliverLater(holderId, view, src, bmp)
218
+ }
219
+ } catch (e: java.util.concurrent.RejectedExecutionException) {
220
+ log("image queue full: $src", e)
221
+ deliverLater(holderId, view, src, null)
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Añade (holderId, view) deduplicado por view: un rebind con la misma src actualiza el holderId
227
+ * en vez de duplicar la entrega. Cota de waiters por request — el overflow descarta (el tag
228
+ * queda; el próximo bind reintenta).
229
+ */
230
+ private fun addWaiter(list: CopyOnWriteArrayList<Waiter<V>>, holderId: Int, view: V) {
231
+ for (w in list) {
232
+ if (w.view === view) {
233
+ w.holderId = holderId
234
+ return
235
+ }
236
+ }
237
+ if (list.size >= MAX_WAITERS_PER_REQUEST) return
238
+ list.add(Waiter(holderId, view))
239
+ }
240
+
241
+ private fun flushWaiters(key: ReqKey, src: String, bmp: B?) {
242
+ postMain {
243
+ if (destroyed) return@postMain
244
+ val list = synchronized(inFlight) { inFlight.remove(key) } ?: return@postMain
245
+ for (w in list) {
246
+ // Generación por contenido (tag == src) + nodo vivo:
247
+ // rebind a otra src o delete cancelan la entrega.
248
+ if (tagOf(w.view) == src && isAlive(w.holderId, w.view)) {
249
+ deliver(w.holderId, w.view, src, bmp)
250
+ }
251
+ }
252
+ }
253
+ }
254
+
255
+ private fun deliverLater(holderId: Int, view: V, src: String, bmp: B?) {
256
+ postMain {
257
+ if (destroyed) return@postMain
258
+ if (tagOf(view) == src && isAlive(holderId, view)) {
259
+ deliver(holderId, view, src, bmp)
260
+ }
261
+ }
262
+ }
263
+
264
+ private fun deliver(holderId: Int, view: V, src: String, bmp: B?) {
265
+ if (tagOf(view) != src || !isAlive(holderId, view)) return
266
+ val prev = deliveredBytes.put(view, bmp?.let(byteCountOf) ?: 0)
267
+ liveBytesTotal.addAndGet((bmp?.let(byteCountOf) ?: 0) - (prev ?: 0))
268
+ setImage(view, bmp)
269
+ onDelivered(holderId, view, bmp)
270
+ }
271
+
272
+ /** Purga waiters de una vista concreta (delete-node de imagen). */
273
+ fun removeView(view: V) {
274
+ synchronized(inFlight) {
275
+ inFlight.values.forEach { list -> list.removeAll { it.view === view } }
276
+ }
277
+ deliveredBytes.remove(view)?.let { liveBytesTotal.addAndGet(-it) }
278
+ }
279
+
280
+ /**
281
+ * Purga por conjunto de vistas de holder — deleteNode(listId) las pasa; los pseudo-ids no
282
+ * existen en `views`, la purga va por view.
283
+ */
284
+ fun removeViews(views: Collection<V>) {
285
+ val set = Collections.newSetFromMap(WeakHashMap<V, Boolean>())
286
+ set.addAll(views)
287
+ synchronized(inFlight) {
288
+ inFlight.values.forEach { list -> list.removeAll { it.view in set } }
289
+ }
290
+ for (v in views) {
291
+ deliveredBytes.remove(v)?.let { liveBytesTotal.addAndGet(-it) }
292
+ }
293
+ }
294
+
295
+ fun clear() {
296
+ destroyed = true
297
+ synchronized(inFlight) { inFlight.clear() }
298
+ deliveredBytes.clear()
299
+ liveBytesTotal.set(0)
300
+ inFlightBytes.set(0)
301
+ cache.evictAll()
302
+ }
303
+
304
+ /** Métricas para el TCK de plataforma (U17). */
305
+ fun stats(): Map<String, Int> =
306
+ mapOf(
307
+ "cacheBytes" to cache.size(),
308
+ "cacheEntries" to cache.entryCount(),
309
+ "inFlight" to synchronized(inFlight) { inFlight.size },
310
+ "inFlightBytes" to inFlightBytes.get(),
311
+ "liveBytes" to liveBytesTotal.get(),
312
+ )
313
+
314
+ companion object {
315
+ const val MAX_IMAGE_BYTES = 16 * 1024 * 1024
316
+ const val MAX_IMAGE_SIDE = 1024
317
+ const val MAX_IMAGE_QUEUE = 64
318
+ const val MAX_WAITERS_PER_REQUEST = 64
319
+ const val MAX_CACHE_BYTES = 16 * 1024 * 1024
320
+ /**
321
+ * Presupuesto de bitmaps entregados a vistas vivas — por encima el cache deja de crecer
322
+ * (las vistas ya retienen el límite).
323
+ */
324
+ const val MAX_LIVE_BYTES = 64 * 1024 * 1024
325
+
326
+ /**
327
+ * Bucket de destino: cuantiza el tamaño del view a potencias de dos (64..1024) — dos vistas
328
+ * dentro del mismo bucket comparten fetch/cache; entre buckets no (el decode difiere).
329
+ */
330
+ fun destBucket(targetPx: Int): Int {
331
+ if (targetPx <= 0) return MAX_IMAGE_SIDE
332
+ var b = 64
333
+ while (b < targetPx && b < MAX_IMAGE_SIDE) b *= 2
334
+ return minOf(b, MAX_IMAGE_SIDE)
335
+ }
336
+
337
+ /**
338
+ * Tamaño decodificado estimado de un data: URI — base64 codifica 3 bytes por cada 4 chars;
339
+ * el payload lo declara sin decodificar.
340
+ */
341
+ fun estimateDataUriBytes(src: String): Long {
342
+ val comma = src.indexOf(',')
343
+ if (comma < 0) return 0
344
+ val payloadLen = (src.length - comma - 1).toLong()
345
+ return payloadLen * 3 / 4
346
+ }
347
+ }
348
+ }