package eu.friedcutlet.yokan.services.webview import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.cookies.CookieJar import eu.friedcutlet.yokan.services.notifications.InAppNotifications import eu.friedcutlet.yokan.services.system.openSystemBrowser import java.io.File import java.net.InetAddress import java.net.ServerSocket import java.net.URI import java.net.http.HttpClient import java.net.http.WebSocket import java.util.Locale import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage import java.util.concurrent.TimeUnit import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.doubleOrNull import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put internal data class DesktopBrowserChallengeResult( val userAgent: String, val response: HttpResponse, ) internal object DesktopBrowserChallengeSession { private val json = Json { ignoreUnknownKeys = true } private val client = HttpClient.newBuilder() .followRedirects(HttpClient.Redirect.NORMAL) .build() private const val INTERACTIVE_TIMEOUT_SECONDS = 300L fun solve(url: String, cookieJar: CookieJar, cacheRoot: String): DesktopBrowserChallengeResult? { val uri = runCatching { URI(url) }.getOrNull() ?: return null val host = uri.host?.lowercase(Locale.US)?.takeIf { it.isNotBlank() } ?: return null val browser = browserCandidates().firstOrNull(::canLaunchBrowser) if (browser == null) { InAppNotifications.post( title = "Browser not found", message = "Install Chrome, Edge, Brave, or Chromium, then retry the Cloudflare resolver.", ) openSystemBrowser(url) return null } val profileDir = File( cacheRoot, "browser-challenge/sessions/$host", ).apply { mkdirs() } val logFile = File(profileDir, "browser.log") // Chromium sets navigator.webdriver when port 0 is requested. Reserve a // fixed non-zero loopback port so anti-bot checks see the normal browser. val remotePort = availableLoopbackPort() ?: return null val command = listOf( browser, "--user-data-dir=${profileDir.absolutePath}", "--remote-debugging-port=$remotePort", "--no-first-run", "--no-default-browser-check", "--disable-background-mode", "--disable-features=Translate", "--app=$url", ) InAppNotifications.post( title = "Solve challenge in browser", message = "Complete the challenge. Yokan will close this dedicated window after the protected page loads.", ) val process = runCatching { ProcessBuilder(command) .redirectErrorStream(true) .redirectOutput(ProcessBuilder.Redirect.appendTo(logFile)) .start() }.getOrElse { error -> AppLogger.warn("[webview] browser challenge launch failed: ${error.message.orEmpty()}") openSystemBrowser(url) return null } val browserResult = try { val browserWsUrl = waitForDevToolsUrl(remotePort, process) ?: return null val snapshot = awaitPageSnapshot(remotePort, host, process) ?: return null val matching = readBrowserCookies(browserWsUrl) .filter { it.matches(host) && it.name.isNotBlank() && it.value.isNotBlank() } if (matching.isNotEmpty()) { cookieJar.setFromResponse(url, matching.map { it.toSetCookieHeader() }) } val userAgent = readBrowserUserAgent(browserWsUrl) ?: return null DesktopBrowserChallengeResult(userAgent, snapshot.toHttpResponse()) } finally { runCatching { process.destroy() if (!process.waitFor(2, TimeUnit.SECONDS)) { process.destroyForcibly() process.waitFor(2, TimeUnit.SECONDS) } } } InAppNotifications.post( title = "Challenge session verified", message = "Loaded $host through the verified browser session.", ) return browserResult } private fun availableLoopbackPort(): Int? = runCatching { ServerSocket(0, 1, InetAddress.getLoopbackAddress()).use { it.localPort } }.getOrNull() private fun waitForDevToolsUrl(port: Int, process: Process): String? { repeat(150) { if (!process.isAlive) return null val version = readDevToolsJson(port, "/json/version")?.jsonObjectOrNull() val webSocketUrl = version ?.get("webSocketDebuggerUrl") ?.jsonPrimitive ?.contentOrNull if (!webSocketUrl.isNullOrBlank()) return webSocketUrl Thread.sleep(100L) } return null } private fun awaitPageSnapshot(port: Int, host: String, process: Process): BrowserPageSnapshot? { val deadline = System.currentTimeMillis() + INTERACTIVE_TIMEOUT_SECONDS * 1_000L while (System.currentTimeMillis() < deadline && process.isAlive) { val snapshot = pageWebSocketUrl(port)?.let(::readPageSnapshot) val pageHost = snapshot?.url ?.let { runCatching { URI(it).host?.lowercase(Locale.US) }.getOrNull() } if ( snapshot != null && pageHost == host && snapshot.readyState == "complete" && snapshot.body.isNotBlank() && !snapshot.isChallenge() ) { return snapshot } Thread.sleep(500L) } return null } private fun pageWebSocketUrl(port: Int): String? { val targets = readDevToolsJson(port, "/json/list")?.jsonArrayOrNull() ?: return null return targets.firstNotNullOfOrNull { element -> val target = element.jsonObjectOrNull() ?: return@firstNotNullOfOrNull null if (target["type"]?.jsonPrimitive?.contentOrNull != "page") { return@firstNotNullOfOrNull null } target["webSocketDebuggerUrl"]?.jsonPrimitive?.contentOrNull } } private fun readDevToolsJson(port: Int, path: String): kotlinx.serialization.json.JsonElement? = runCatching { val request = java.net.http.HttpRequest.newBuilder( URI("http://127.0.0.1:$port$path"), ).GET().build() val body = client.send( request, java.net.http.HttpResponse.BodyHandlers.ofString(), ).body() json.parseToJsonElement(body) }.onFailure { if (it is InterruptedException) throw it }.getOrNull() private fun readPageSnapshot(pageWsUrl: String): BrowserPageSnapshot? { val expression = """ (() => JSON.stringify({ url: location.href, readyState: document.readyState || "", title: document.title || "", contentType: document.contentType || "", status: performance.getEntriesByType("navigation")[0]?.responseStatus || 0, body: ((document.contentType || "").includes("json") || (document.contentType || "").startsWith("text/plain")) ? (document.body?.innerText || "") : (document.documentElement?.outerHTML || "") }))() """.trimIndent() val response = sendCdpCommand( pageWsUrl, "Runtime.evaluate", buildJsonObject { put("expression", expression) put("returnByValue", true) }, ) ?: return null val serialized = response["result"] ?.jsonObjectOrNull() ?.get("result") ?.jsonObjectOrNull() ?.get("value") ?.jsonPrimitive ?.contentOrNull ?: return null val value = runCatching { json.parseToJsonElement(serialized).jsonObject }.getOrNull() ?: return null return value.toBrowserPageSnapshot() } private data class BrowserPageSnapshot( val url: String, val readyState: String, val title: String, val contentType: String, val status: Int, val body: String, ) { fun isChallenge(): Boolean { val normalizedTitle = title.trim().lowercase() val normalizedBody = body.lowercase() return normalizedTitle.contains("just a moment") || normalizedTitle.contains("attention required") || normalizedTitle.contains("verification required") || normalizedBody.contains("cf-chl-") || normalizedBody.contains("performing security verification") || normalizedBody.contains("verify you are human") } fun toHttpResponse(): HttpResponse = HttpResponse( statusCode = status.takeIf { it > 0 } ?: 200, body = body, headers = mapOf("Content-Type" to contentType), ) } private fun JsonObject.toBrowserPageSnapshot(): BrowserPageSnapshot? { val url = this["url"]?.jsonPrimitive?.contentOrNull ?: return null return BrowserPageSnapshot( url = url, readyState = this["readyState"]?.jsonPrimitive?.contentOrNull.orEmpty(), title = this["title"]?.jsonPrimitive?.contentOrNull.orEmpty(), contentType = this["contentType"]?.jsonPrimitive?.contentOrNull.orEmpty(), status = this["status"]?.jsonPrimitive?.intOrNull ?: 0, body = this["body"]?.jsonPrimitive?.contentOrNull.orEmpty(), ) } private fun readBrowserUserAgent(browserWsUrl: String): String? = sendCdpCommand(browserWsUrl, "Browser.getVersion") ?.get("result") ?.jsonObjectOrNull() ?.get("userAgent") ?.jsonPrimitive ?.contentOrNull ?.takeIf { it.isNotBlank() } private fun readBrowserCookies(browserWsUrl: String): List { for (method in listOf("Storage.getCookies", "Network.getAllCookies")) { val cookies = sendCdpCommand(browserWsUrl, method)?.browserCookies() if (cookies != null) return cookies } return emptyList() } private fun sendCdpCommand( browserWsUrl: String, method: String, params: JsonObject? = null, ): JsonObject? { val listener = CdpListener(1) val webSocket = client.newWebSocketBuilder() .buildAsync(URI.create(browserWsUrl), listener) .get(5, TimeUnit.SECONDS) val payload = buildJsonObject { put("id", 1) put("method", method) if (params != null) put("params", params) }.toString() return try { webSocket.sendText(payload, true).get(5, TimeUnit.SECONDS) listener.response.get(5, TimeUnit.SECONDS) } finally { runCatching { webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "done") } } } private class CdpListener(private val expectedId: Int) : WebSocket.Listener { val response: CompletableFuture = CompletableFuture() private val buffer = StringBuilder() override fun onOpen(webSocket: WebSocket) { webSocket.request(1) } override fun onText(webSocket: WebSocket, data: CharSequence, last: Boolean): CompletionStage<*> { buffer.append(data) if (last) { val message = buffer.toString() buffer.clear() val parsed = runCatching { json.parseToJsonElement(message).jsonObject }.getOrNull() val id = parsed?.get("id")?.jsonPrimitive?.intOrNull if (id == expectedId) { response.complete(parsed) } } webSocket.request(1) return CompletableFuture.completedFuture(null) } override fun onError(webSocket: WebSocket, error: Throwable) { response.completeExceptionally(error) } } private data class BrowserCookie( val name: String, val value: String, val domain: String, val path: String, val expires: Double?, val secure: Boolean, val httpOnly: Boolean, ) { fun matches(host: String): Boolean { val cookieDomain = domain.removePrefix(".").lowercase(Locale.US) if (cookieDomain.isBlank()) return false return if (domain.startsWith(".")) { host == cookieDomain || host.endsWith(".$cookieDomain") } else { host == cookieDomain } } fun toSetCookieHeader(): String { val attributes = mutableListOf("$name=$value") if (domain.startsWith(".")) attributes += "Domain=$domain" attributes += "Path=${path.ifBlank { "/" }}" val expiresAt = expires?.takeIf { it > 0.0 }?.let { (it * 1_000L).toLong() } if (expiresAt != null) { val maxAge = ((expiresAt - System.currentTimeMillis()) / 1_000L).coerceAtLeast(0L) attributes += "Max-Age=$maxAge" } if (secure) attributes += "Secure" if (httpOnly) attributes += "HttpOnly" return attributes.joinToString("; ") } fun isChallengeClearanceCookie(): Boolean = name.equals("cf_clearance", ignoreCase = true) || name.equals("__ddg2_", ignoreCase = true) } private fun JsonObject.toBrowserCookie(): BrowserCookie? { val name = this["name"]?.jsonPrimitive?.contentOrNull ?: return null val value = this["value"]?.jsonPrimitive?.contentOrNull ?: return null val domain = this["domain"]?.jsonPrimitive?.contentOrNull ?: return null return BrowserCookie( name = name, value = value, domain = domain, path = this["path"]?.jsonPrimitive?.contentOrNull ?: "/", expires = this["expires"]?.jsonPrimitive?.doubleOrNull, secure = this["secure"]?.jsonPrimitive?.booleanOrNull ?: false, httpOnly = this["httpOnly"]?.jsonPrimitive?.booleanOrNull ?: false, ) } private fun JsonObject.browserCookies(): List? { val result = this["result"]?.jsonObjectOrNull() ?: return null val cookies = result["cookies"]?.jsonArrayOrNull() ?: return null return cookies.mapNotNull { it.jsonObjectOrNull()?.toBrowserCookie() } } private fun browserCandidates(): List { val os = System.getProperty("os.name").orEmpty().lowercase(Locale.US) val home = System.getProperty("user.home").orEmpty() return when { "mac" in os || "darwin" in os -> listOf( "$home/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "$home/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", "$home/Applications/Brave Browser.app/Contents/MacOS/Brave Browser", "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser", "$home/Applications/Chromium.app/Contents/MacOS/Chromium", "/Applications/Chromium.app/Contents/MacOS/Chromium", ) "win" in os -> listOf( "chrome.exe", "msedge.exe", "brave.exe", "chromium.exe", ) else -> listOf( "google-chrome", "google-chrome-stable", "microsoft-edge", "brave-browser", "chromium", "chromium-browser", ) } } private fun canLaunchBrowser(command: String): Boolean = if (command.contains(File.separatorChar)) { File(command).canExecute() } else { true } private fun kotlinx.serialization.json.JsonElement.jsonObjectOrNull(): JsonObject? = this as? JsonObject private fun kotlinx.serialization.json.JsonElement.jsonArrayOrNull(): JsonArray? = this as? JsonArray }