Yokan / rebuild
Course 1 8624561

DesktopBrowserChallengeSession.desktop.kt

composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/webview/DesktopBrowserChallengeSession.desktop.kt

implementation420 lines
1package eu.friedcutlet.yokan.services.webview23import eu.friedcutlet.yokan.services.logging.AppLogger4import eu.friedcutlet.yokan.services.http.HttpResponse5import eu.friedcutlet.yokan.services.http.cookies.CookieJar6import eu.friedcutlet.yokan.services.notifications.InAppNotifications7import eu.friedcutlet.yokan.services.system.openSystemBrowser8import java.io.File9import java.net.InetAddress10import java.net.ServerSocket11import java.net.URI12import java.net.http.HttpClient13import java.net.http.WebSocket14import java.util.Locale15import java.util.concurrent.CompletableFuture16import java.util.concurrent.CompletionStage17import java.util.concurrent.TimeUnit18import kotlinx.serialization.json.Json19import kotlinx.serialization.json.JsonArray20import kotlinx.serialization.json.JsonObject21import kotlinx.serialization.json.booleanOrNull22import kotlinx.serialization.json.buildJsonObject23import kotlinx.serialization.json.contentOrNull24import kotlinx.serialization.json.doubleOrNull25import kotlinx.serialization.json.intOrNull26import kotlinx.serialization.json.jsonObject27import kotlinx.serialization.json.jsonPrimitive28import kotlinx.serialization.json.put2930internal data class DesktopBrowserChallengeResult(31    val userAgent: String,32    val response: HttpResponse,33)3435internal object DesktopBrowserChallengeSession {36    private val json = Json { ignoreUnknownKeys = true }37    private val client = HttpClient.newBuilder()38        .followRedirects(HttpClient.Redirect.NORMAL)39        .build()40    private const val INTERACTIVE_TIMEOUT_SECONDS = 300L4142    fun solve(url: String, cookieJar: CookieJar, cacheRoot: String): DesktopBrowserChallengeResult? {43        val uri = runCatching { URI(url) }.getOrNull() ?: return null44        val host = uri.host?.lowercase(Locale.US)?.takeIf { it.isNotBlank() } ?: return null45        val browser = browserCandidates().firstOrNull(::canLaunchBrowser)46        if (browser == null) {47            InAppNotifications.post(48                title = "Browser not found",49                message = "Install Chrome, Edge, Brave, or Chromium, then retry the Cloudflare resolver.",50            )51            openSystemBrowser(url)52            return null53        }5455        val profileDir = File(56            cacheRoot,57            "browser-challenge/sessions/$host",58        ).apply { mkdirs() }59        val logFile = File(profileDir, "browser.log")60        // Chromium sets navigator.webdriver when port 0 is requested. Reserve a61        // fixed non-zero loopback port so anti-bot checks see the normal browser.62        val remotePort = availableLoopbackPort() ?: return null63        val command = listOf(64            browser,65            "--user-data-dir=${profileDir.absolutePath}",66            "--remote-debugging-port=$remotePort",67            "--no-first-run",68            "--no-default-browser-check",69            "--disable-background-mode",70            "--disable-features=Translate",71            "--app=$url",72        )7374        InAppNotifications.post(75            title = "Solve challenge in browser",76            message = "Complete the challenge. Yokan will close this dedicated window after the protected page loads.",77        )7879        val process = runCatching {80            ProcessBuilder(command)81                .redirectErrorStream(true)82                .redirectOutput(ProcessBuilder.Redirect.appendTo(logFile))83                .start()84        }.getOrElse { error ->85            AppLogger.warn("[webview] browser challenge launch failed: ${error.message.orEmpty()}")86            openSystemBrowser(url)87            return null88        }8990        val browserResult = try {91            val browserWsUrl = waitForDevToolsUrl(remotePort, process) ?: return null92            val snapshot = awaitPageSnapshot(remotePort, host, process) ?: return null93            val matching = readBrowserCookies(browserWsUrl)94                .filter { it.matches(host) && it.name.isNotBlank() && it.value.isNotBlank() }95            if (matching.isNotEmpty()) {96                cookieJar.setFromResponse(url, matching.map { it.toSetCookieHeader() })97            }98            val userAgent = readBrowserUserAgent(browserWsUrl) ?: return null99            DesktopBrowserChallengeResult(userAgent, snapshot.toHttpResponse())100        } finally {101            runCatching {102                process.destroy()103                if (!process.waitFor(2, TimeUnit.SECONDS)) {104                    process.destroyForcibly()105                    process.waitFor(2, TimeUnit.SECONDS)106                }107            }108        }109        InAppNotifications.post(110            title = "Challenge session verified",111            message = "Loaded $host through the verified browser session.",112        )113        return browserResult114    }115116    private fun availableLoopbackPort(): Int? =117        runCatching {118            ServerSocket(0, 1, InetAddress.getLoopbackAddress()).use { it.localPort }119        }.getOrNull()120121    private fun waitForDevToolsUrl(port: Int, process: Process): String? {122        repeat(150) {123            if (!process.isAlive) return null124            val version = readDevToolsJson(port, "/json/version")?.jsonObjectOrNull()125            val webSocketUrl = version126                ?.get("webSocketDebuggerUrl")127                ?.jsonPrimitive128                ?.contentOrNull129            if (!webSocketUrl.isNullOrBlank()) return webSocketUrl130            Thread.sleep(100L)131        }132        return null133    }134135    private fun awaitPageSnapshot(port: Int, host: String, process: Process): BrowserPageSnapshot? {136        val deadline = System.currentTimeMillis() + INTERACTIVE_TIMEOUT_SECONDS * 1_000L137        while (System.currentTimeMillis() < deadline && process.isAlive) {138            val snapshot = pageWebSocketUrl(port)?.let(::readPageSnapshot)139            val pageHost = snapshot?.url140                ?.let { runCatching { URI(it).host?.lowercase(Locale.US) }.getOrNull() }141            if (142                snapshot != null &&143                pageHost == host &&144                snapshot.readyState == "complete" &&145                snapshot.body.isNotBlank() &&146                !snapshot.isChallenge()147            ) {148                return snapshot149            }150            Thread.sleep(500L)151        }152        return null153    }154155    private fun pageWebSocketUrl(port: Int): String? {156        val targets = readDevToolsJson(port, "/json/list")?.jsonArrayOrNull() ?: return null157        return targets.firstNotNullOfOrNull { element ->158            val target = element.jsonObjectOrNull() ?: return@firstNotNullOfOrNull null159            if (target["type"]?.jsonPrimitive?.contentOrNull != "page") {160                return@firstNotNullOfOrNull null161            }162            target["webSocketDebuggerUrl"]?.jsonPrimitive?.contentOrNull163        }164    }165166    private fun readDevToolsJson(port: Int, path: String): kotlinx.serialization.json.JsonElement? =167        runCatching {168            val request = java.net.http.HttpRequest.newBuilder(169                URI("http://127.0.0.1:$port$path"),170            ).GET().build()171            val body = client.send(172                request,173                java.net.http.HttpResponse.BodyHandlers.ofString(),174            ).body()175            json.parseToJsonElement(body)176        }.onFailure { if (it is InterruptedException) throw it }.getOrNull()177178    private fun readPageSnapshot(pageWsUrl: String): BrowserPageSnapshot? {179        val expression = """180            (() => JSON.stringify({181              url: location.href,182              readyState: document.readyState || "",183              title: document.title || "",184              contentType: document.contentType || "",185              status: performance.getEntriesByType("navigation")[0]?.responseStatus || 0,186              body: ((document.contentType || "").includes("json") ||187                     (document.contentType || "").startsWith("text/plain"))188                ? (document.body?.innerText || "")189                : (document.documentElement?.outerHTML || "")190            }))()191        """.trimIndent()192        val response = sendCdpCommand(193            pageWsUrl,194            "Runtime.evaluate",195            buildJsonObject {196                put("expression", expression)197                put("returnByValue", true)198            },199        ) ?: return null200        val serialized = response["result"]201            ?.jsonObjectOrNull()202            ?.get("result")203            ?.jsonObjectOrNull()204            ?.get("value")205            ?.jsonPrimitive206            ?.contentOrNull207            ?: return null208        val value = runCatching { json.parseToJsonElement(serialized).jsonObject }.getOrNull()209            ?: return null210        return value.toBrowserPageSnapshot()211    }212213    private data class BrowserPageSnapshot(214        val url: String,215        val readyState: String,216        val title: String,217        val contentType: String,218        val status: Int,219        val body: String,220    ) {221        fun isChallenge(): Boolean {222            val normalizedTitle = title.trim().lowercase()223            val normalizedBody = body.lowercase()224            return normalizedTitle.contains("just a moment") ||225                normalizedTitle.contains("attention required") ||226                normalizedTitle.contains("verification required") ||227                normalizedBody.contains("cf-chl-") ||228                normalizedBody.contains("performing security verification") ||229                normalizedBody.contains("verify you are human")230        }231232        fun toHttpResponse(): HttpResponse =233            HttpResponse(234                statusCode = status.takeIf { it > 0 } ?: 200,235                body = body,236                headers = mapOf("Content-Type" to contentType),237            )238    }239240    private fun JsonObject.toBrowserPageSnapshot(): BrowserPageSnapshot? {241        val url = this["url"]?.jsonPrimitive?.contentOrNull ?: return null242        return BrowserPageSnapshot(243            url = url,244            readyState = this["readyState"]?.jsonPrimitive?.contentOrNull.orEmpty(),245            title = this["title"]?.jsonPrimitive?.contentOrNull.orEmpty(),246            contentType = this["contentType"]?.jsonPrimitive?.contentOrNull.orEmpty(),247            status = this["status"]?.jsonPrimitive?.intOrNull ?: 0,248            body = this["body"]?.jsonPrimitive?.contentOrNull.orEmpty(),249        )250    }251252    private fun readBrowserUserAgent(browserWsUrl: String): String? =253        sendCdpCommand(browserWsUrl, "Browser.getVersion")254            ?.get("result")255            ?.jsonObjectOrNull()256            ?.get("userAgent")257            ?.jsonPrimitive258            ?.contentOrNull259            ?.takeIf { it.isNotBlank() }260261    private fun readBrowserCookies(browserWsUrl: String): List<BrowserCookie> {262        for (method in listOf("Storage.getCookies", "Network.getAllCookies")) {263            val cookies = sendCdpCommand(browserWsUrl, method)?.browserCookies()264            if (cookies != null) return cookies265        }266        return emptyList()267    }268269    private fun sendCdpCommand(270        browserWsUrl: String,271        method: String,272        params: JsonObject? = null,273    ): JsonObject? {274        val listener = CdpListener(1)275        val webSocket = client.newWebSocketBuilder()276            .buildAsync(URI.create(browserWsUrl), listener)277            .get(5, TimeUnit.SECONDS)278        val payload = buildJsonObject {279            put("id", 1)280            put("method", method)281            if (params != null) put("params", params)282        }.toString()283        return try {284            webSocket.sendText(payload, true).get(5, TimeUnit.SECONDS)285            listener.response.get(5, TimeUnit.SECONDS)286        } finally {287            runCatching { webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "done") }288        }289    }290291    private class CdpListener(private val expectedId: Int) : WebSocket.Listener {292        val response: CompletableFuture<JsonObject?> = CompletableFuture()293        private val buffer = StringBuilder()294295        override fun onOpen(webSocket: WebSocket) {296            webSocket.request(1)297        }298299        override fun onText(webSocket: WebSocket, data: CharSequence, last: Boolean): CompletionStage<*> {300            buffer.append(data)301            if (last) {302                val message = buffer.toString()303                buffer.clear()304                val parsed = runCatching { json.parseToJsonElement(message).jsonObject }.getOrNull()305                val id = parsed?.get("id")?.jsonPrimitive?.intOrNull306                if (id == expectedId) {307                    response.complete(parsed)308                }309            }310            webSocket.request(1)311            return CompletableFuture.completedFuture(null)312        }313314        override fun onError(webSocket: WebSocket, error: Throwable) {315            response.completeExceptionally(error)316        }317    }318319    private data class BrowserCookie(320        val name: String,321        val value: String,322        val domain: String,323        val path: String,324        val expires: Double?,325        val secure: Boolean,326        val httpOnly: Boolean,327    ) {328        fun matches(host: String): Boolean {329            val cookieDomain = domain.removePrefix(".").lowercase(Locale.US)330            if (cookieDomain.isBlank()) return false331            return if (domain.startsWith(".")) {332                host == cookieDomain || host.endsWith(".$cookieDomain")333            } else {334                host == cookieDomain335            }336        }337338        fun toSetCookieHeader(): String {339            val attributes = mutableListOf("$name=$value")340            if (domain.startsWith(".")) attributes += "Domain=$domain"341            attributes += "Path=${path.ifBlank { "/" }}"342            val expiresAt = expires?.takeIf { it > 0.0 }?.let { (it * 1_000L).toLong() }343            if (expiresAt != null) {344                val maxAge = ((expiresAt - System.currentTimeMillis()) / 1_000L).coerceAtLeast(0L)345                attributes += "Max-Age=$maxAge"346            }347            if (secure) attributes += "Secure"348            if (httpOnly) attributes += "HttpOnly"349            return attributes.joinToString("; ")350        }351352        fun isChallengeClearanceCookie(): Boolean =353            name.equals("cf_clearance", ignoreCase = true) ||354                name.equals("__ddg2_", ignoreCase = true)355    }356357    private fun JsonObject.toBrowserCookie(): BrowserCookie? {358        val name = this["name"]?.jsonPrimitive?.contentOrNull ?: return null359        val value = this["value"]?.jsonPrimitive?.contentOrNull ?: return null360        val domain = this["domain"]?.jsonPrimitive?.contentOrNull ?: return null361        return BrowserCookie(362            name = name,363            value = value,364            domain = domain,365            path = this["path"]?.jsonPrimitive?.contentOrNull ?: "/",366            expires = this["expires"]?.jsonPrimitive?.doubleOrNull,367            secure = this["secure"]?.jsonPrimitive?.booleanOrNull ?: false,368            httpOnly = this["httpOnly"]?.jsonPrimitive?.booleanOrNull ?: false,369        )370    }371372    private fun JsonObject.browserCookies(): List<BrowserCookie>? {373        val result = this["result"]?.jsonObjectOrNull() ?: return null374        val cookies = result["cookies"]?.jsonArrayOrNull() ?: return null375        return cookies.mapNotNull { it.jsonObjectOrNull()?.toBrowserCookie() }376    }377378    private fun browserCandidates(): List<String> {379        val os = System.getProperty("os.name").orEmpty().lowercase(Locale.US)380        val home = System.getProperty("user.home").orEmpty()381        return when {382            "mac" in os || "darwin" in os -> listOf(383                "$home/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",384                "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",385                "$home/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",386                "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",387                "$home/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",388                "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",389                "$home/Applications/Chromium.app/Contents/MacOS/Chromium",390                "/Applications/Chromium.app/Contents/MacOS/Chromium",391            )392393            "win" in os -> listOf(394                "chrome.exe",395                "msedge.exe",396                "brave.exe",397                "chromium.exe",398            )399400            else -> listOf(401                "google-chrome",402                "google-chrome-stable",403                "microsoft-edge",404                "brave-browser",405                "chromium",406                "chromium-browser",407            )408        }409    }410411    private fun canLaunchBrowser(command: String): Boolean =412        if (command.contains(File.separatorChar)) {413            File(command).canExecute()414        } else {415            true416        }417418    private fun kotlinx.serialization.json.JsonElement.jsonObjectOrNull(): JsonObject? = this as? JsonObject419    private fun kotlinx.serialization.json.JsonElement.jsonArrayOrNull(): JsonArray? = this as? JsonArray420}421

Search chapters, reference and source filenames.