package eu.friedcutlet.yokan.services.http import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.services.http.cookies.CookieJar import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue import kotlinx.coroutines.runBlocking /** * Deterministic coverage of Yokan's Cloudflare-handling mechanism: the shared * [CookieJar] seeds a `cf_clearance` cookie (harvested by the WebView resolver * in production) and [EnhancedHttpService] must attach it to every subsequent * request for that host, and persist `Set-Cookie` clearances issued by the * server. This is the transport contract that lets extensions get past a * Cloudflare challenge once the WebView solves it. */ class CloudflareHandlingTest { private class CapturingSolver(private val response: HttpResponse) { var resolveCalls: Int = 0 var lastHeaders: Map? = null val solve: suspend (String, Map) -> HttpResponse? = { _, headers -> resolveCalls += 1 lastHeaders = headers response } } @Test fun attachesSeededClearanceCookieToRequests() = runBlocking { val database = InMemoryYokanDatabase() val cookieJar = CookieJar(database) cookieJar.put("animepahe.pw", "cf_clearance=SEEDED-TOKEN") val delegate = RecordingHttpService { HttpResponse(statusCode = 200, body = "ok") } val http = EnhancedHttpService(delegate, database, cookieJar) http.request(HttpRequest(url = "https://animepahe.pw/api?m=airing")) val sent = assertNotNull(delegate.requests.lastOrNull()) val cookie = sent.headers.entries.firstOrNull { it.key.equals("Cookie", ignoreCase = true) }?.value.orEmpty() assertTrue(cookie.contains("cf_clearance=SEEDED-TOKEN"), "clearance cookie not attached: '$cookie'") assertTrue( sent.headers.keys.any { it.equals("User-Agent", ignoreCase = true) }, "default User-Agent not applied", ) } @Test fun persistsClearanceFromSetCookie() = runBlocking { val database = InMemoryYokanDatabase() val cookieJar = CookieJar(database) val delegate = HttpService { HttpResponse( statusCode = 200, body = "ok", setCookies = listOf("cf_clearance=FRESH-TOKEN; Path=/; Domain=animepahe.pw"), ) } val http = EnhancedHttpService(delegate, database, cookieJar) http.request(HttpRequest(url = "https://animepahe.pw/")) val header = cookieJar.cookieHeader("https://animepahe.pw/api") assertEquals(true, header?.contains("cf_clearance=FRESH-TOKEN"), "clearance not persisted: '$header'") } @Test fun clearanceIsScopedToItsHost() = runBlocking { val database = InMemoryYokanDatabase() val cookieJar = CookieJar(database) cookieJar.put("animepahe.pw", "cf_clearance=SCOPED") val delegate = RecordingHttpService { HttpResponse(statusCode = 200, body = "ok") } val http = EnhancedHttpService(delegate, database, cookieJar) http.request(HttpRequest(url = "https://mangadex.org/api")) val cookie = delegate.requests.lastOrNull()?.headers?.entries ?.firstOrNull { it.key.equals("Cookie", ignoreCase = true) }?.value.orEmpty() assertTrue(!cookie.contains("cf_clearance"), "clearance leaked to a foreign host: '$cookie'") } @Test fun forcedResolutionHeaderIsNotSentToTheServer() = runBlocking { val database = InMemoryYokanDatabase() val cookieJar = CookieJar(database) cookieJar.put("kwik.cx", "kwik_session=EXISTING") val delegate = RecordingHttpService { HttpResponse(statusCode = 200, body = "blocked") } val webView = CapturingSolver(HttpResponse(statusCode = 200, body = "stream page")) val http = EnhancedHttpService(delegate, database, cookieJar).apply { cloudflareSolver = webView.solve } val response = http.request( HttpRequest( url = "https://kwik.cx/e/example", headers = mapOf("X-Yokan-Resolve-Cloudflare" to "1"), ), ) assertEquals("stream page", response.body) assertEquals(1, webView.resolveCalls) assertTrue(webView.lastHeaders?.get("Cookie")?.contains("kwik_session=EXISTING") == true) assertTrue(delegate.requests.lastOrNull()?.headers?.keys?.none { it.equals("X-Yokan-Resolve-Cloudflare", ignoreCase = true) } == true) } @Test fun solvesChallengeViaCfProxyWhenConfigured() = runBlocking { val database = InMemoryYokanDatabase() database.updateSettings( database.settings().copy(cloudflareBypassProxyUrl = "http://127.0.0.1:8191/v1") ) val cookieJar = CookieJar(database) val router = RecordingHttpService { req -> when { req.url == "http://127.0.0.1:8191/v1" -> { assertEquals("POST", req.method) assertTrue(req.body.orEmpty().contains("request.get")) assertTrue(req.body.orEmpty().contains("https://protected.domain/page")) HttpResponse( statusCode = 200, body = """ { "status": "ok", "message": "Challenge solved!", "solution": { "cookies": [ { "name": "cf_clearance", "value": "SOLVED_PROXY_TOKEN", "domain": ".protected.domain" } ], "userAgent": "FlareSolverr-Browser/1.0" } } """.trimIndent(), ) } req.url == "https://protected.domain/page" -> { val cookie = req.headers["Cookie"].orEmpty() if (cookie.contains("cf_clearance=SOLVED_PROXY_TOKEN")) { HttpResponse(statusCode = 200, body = "success page") } else { HttpResponse( statusCode = 403, body = "Just a moment...", headers = mapOf("Server" to "cloudflare"), ) } } else -> HttpResponse(statusCode = 404, body = "not found") } } val http = EnhancedHttpService(router, database, cookieJar) val res = http.request(HttpRequest(url = "https://protected.domain/page")) assertEquals(200, res.statusCode) assertEquals("success page", res.body) assertEquals("SOLVED_PROXY_TOKEN", cookieJar.cookieHeader("https://protected.domain/page")?.substringAfter("cf_clearance=")?.substringBefore(";")) assertEquals("FlareSolverr-Browser/1.0", cookieJar.userAgent("https://protected.domain/page")) } @Test fun cfProxyCookiesStayOnTheirOwnDomains() = runBlocking { val database = InMemoryYokanDatabase() database.updateSettings( database.settings().copy(cloudflareBypassProxyUrl = "http://127.0.0.1:8191/v1") ) val cookieJar = CookieJar(database) val router = RecordingHttpService { req -> when { req.url == "http://127.0.0.1:8191/v1" -> HttpResponse( statusCode = 200, body = """ { "status": "ok", "solution": { "cookies": [ { "name": "cf_clearance", "value": "CLEAR", "domain": ".protected.domain" }, { "name": "tracker", "value": "OTHER", "domain": "cdn.other.domain" } ] } } """.trimIndent(), ) req.headers["Cookie"].orEmpty().contains("cf_clearance=CLEAR") -> HttpResponse(statusCode = 200, body = "success page") else -> HttpResponse( statusCode = 403, body = "Just a moment...", headers = mapOf("Server" to "cloudflare"), ) } } val res = EnhancedHttpService(router, database, cookieJar) .request(HttpRequest(url = "https://www.protected.domain/page")) assertEquals(200, res.statusCode) val target = cookieJar.cookieHeader("https://www.protected.domain/page").orEmpty() val other = cookieJar.cookieHeader("https://cdn.other.domain/x").orEmpty() assertTrue("cf_clearance=CLEAR" in target && "tracker" !in target, "target cookies: '$target'") assertTrue("tracker=OTHER" in other && "cf_clearance" !in other, "other-domain cookies: '$other'") } @Test fun fallsBackToWebViewWhenProxyFails() = runBlocking { val database = InMemoryYokanDatabase() database.updateSettings( database.settings().copy(cloudflareBypassProxyUrl = "http://127.0.0.1:8191/v1") ) val cookieJar = CookieJar(database) val router = RecordingHttpService { req -> when (req.url) { "http://127.0.0.1:8191/v1" -> { HttpResponse( statusCode = 500, body = """{"status": "error", "message": "Browser timeout"}""", ) } "https://protected.domain/page" -> { HttpResponse( statusCode = 503, body = "Just a moment...", headers = mapOf("Server" to "cloudflare"), ) } else -> HttpResponse(statusCode = 404, body = "not found") } } val webView = CapturingSolver(HttpResponse(statusCode = 200, body = "cleared by webview")) val http = EnhancedHttpService(router, database, cookieJar).apply { cloudflareSolver = webView.solve } val res = http.request(HttpRequest(url = "https://protected.domain/page")) assertEquals(200, res.statusCode) assertEquals("cleared by webview", res.body) assertEquals(1, webView.resolveCalls) } }