Prerequisites: models, profile ownership and a fake transport. File workbook.
How to write this chapter
Implement transport, profile credentials and browser-assisted verification as separate layers. A source request should retain its headers and cancellation while browser solving remains an owned, bounded retry.
The 59 assigned entries are integrated below at their implementation steps. Every text listing is complete, including imports, helpers and tests. Create the displayed paths in your new project; dependencies imported from other chapters are linked beside the file. Binary assets have direct downloads.
Read each step’s explanation, write its contracts and implementation, then trace the test assertions. The final application graph has dependencies across chapters: the ordering is a construction plan, and a step is not a promise that the whole app compiles before its referenced contracts exist.
Implementation sequence:
- Step 1: Write request/response streaming contracts and raw platform clients.
- Step 2: Add profile admission, cookie matching and DNS policy.
- Step 3: Detect challenges, serialize solving and retry the original request.
- Step 4: Bind WebView delegates and the visible verification screen.
- Step 5: Exercise credential isolation, streams and cleanup with fixtures.
- Verification: recreate the full test/fixture listings and run the relevant target tasks. [chapter-content-end]: #
Step 1: define transport contracts
Write request/response and streamed-body interfaces in HttpService, then KtorHttpService and platform engine factories. Preserve method, URL, headers, binary/text bodies, response status and cancellation. Implement bounded streaming and explicit ownership of engines/clients. Closing an HttpClient does not necessarily close an externally supplied engine; await both lifetimes where required.
Implement URL normalization and server helpers. Keep redirects, header forwarding, body limits and cookie policy explicit. Build deterministic recording/mock HTTP implementations before using live services. Do not make successful parsing contingent on a live source website.
Follow the code
Write the transport values and callback-based stream contract first. The Ktor adapter translates these values without absorbing source-specific policy. Inspect who owns the engine: request jobs are tracked explicitly because their lifetime is not automatically identical to the engine job. Closing synchronously cancels, while closeAndJoin also waits for calls and the engine to finish. Platform factories select the real client/engine for each source set.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/HttpService.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/ProfileHttpEngine.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/KtorHttpService.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/PlatformHttp.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/ServerUrls.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/http/PlatformHttp.ios.ktcomposeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/http/PlatformHttp.jvm.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/http/IsolatedBrowserHttpEngine.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/http/PlatformHttp.wasm.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/HttpService.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines interface, request, stream, HttpRequest, HttpResponse, HttpStreamResponse, Map.
The source describes its contract as:
Only a 2xx body reaches [onChunk]; any other body comes back buffered in [HttpStreamResponse.body], capped at [STREAM_ERROR_BODY_LIMIT], so callers can inspect it (Cloudflare challenge pages) without the error page ever landing in the caller's file.
package eu.friedcutlet.yokan.services.http
fun interface HttpService {
suspend fun request(request: HttpRequest): HttpResponse
/**
* Only a 2xx body reaches [onChunk]; any other body comes back buffered in [HttpStreamResponse.body],
* capped at [STREAM_ERROR_BODY_LIMIT], so callers can inspect it (Cloudflare challenge pages) without
* the error page ever landing in the caller's file.
*/
suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
val response = request(request)
val success = response.statusCode in 200..299
request.onStreamResponse?.invoke(HttpStreamResponse(response.statusCode, response.headers, response.setCookies))
if (success && response.bodyBytes.isNotEmpty()) onChunk(response.bodyBytes)
return HttpStreamResponse(
statusCode = response.statusCode,
headers = response.headers,
setCookies = response.setCookies,
body = if (success) ByteArray(0) else response.bodyBytes.copyOf(minOf(response.bodyBytes.size, STREAM_ERROR_BODY_LIMIT)),
)
}
}
/** Enough for a challenge page's markers; error bodies past this are dropped, never streamed. */
const val STREAM_ERROR_BODY_LIMIT = 64 * 1024
data class HttpRequest(
val url: String,
val method: String = "GET",
val headers: Map<String, String> = emptyMap(),
val body: String? = null,
val bodyBytes: ByteArray? = null,
/** Streaming consumers validate headers before any bytes are written, including on failed transfers. */
val onStreamResponse: (suspend (HttpStreamResponse) -> Unit)? = null,
)
class HttpResponse(
val statusCode: Int,
body: String? = null,
val headers: Map<String, String> = emptyMap(),
val bodyBytes: ByteArray = body?.encodeToByteArray() ?: ByteArray(0),
/**
* Raw `Set-Cookie` response headers, one entry per cookie. Kept separate
* from [headers] because Ktor's joined-map view loses the boundaries
* between cookies whose attributes contain commas (`Expires=Mon, …`).
*/
val setCookies: List<String> = emptyList(),
) {
private val suppliedBody = body
/** Decode only for text consumers; binary callers retain one representation. */
val body: String by lazy(LazyThreadSafetyMode.NONE) {
suppliedBody ?: bodyBytes.decodeToString()
}
}
data class HttpStreamResponse(
val statusCode: Int,
val headers: Map<String, String> = emptyMap(),
val setCookies: List<String> = emptyList(),
/** The non-2xx body (see [HttpService.stream]); empty for 2xx, whose bytes went to `onChunk`. */
val body: ByteArray = ByteArray(0),
)
/** Case-insensitive header value, trimmed; null when absent or blank. */
fun Map<String, String>.header(name: String): String? =
entries.firstOrNull { it.key.equals(name, ignoreCase = true) }?.value?.trim()?.takeIf(String::isNotEmpty)
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/ProfileHttpEngine.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
execute records the actual Ktor call Job after checking admission. closeAndJoin retires admission, cancels and joins all recorded calls, releases the delegate once, then joins its engine job.
The implementation below defines ProfileHttpEngine, ensureOpen, execute, retire, release, close, closeAndJoin.
The source describes its contract as:
Ktor call jobs are parented to request execution contexts, not the engine job. Track them explicitly.
Cross-chapter imports used by this file: PlatformLock. Keep those contracts available as you connect this step.
@file:OptIn(io.ktor.utils.io.InternalAPI::class)
package eu.friedcutlet.yokan.services.http
import eu.friedcutlet.yokan.util.PlatformLock
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.callContext
import io.ktor.client.request.HttpRequestData
import io.ktor.client.request.HttpResponseData
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
/** Ktor call jobs are parented to request execution contexts, not the engine job. Track them explicitly. */
internal class ProfileHttpEngine(
private val delegate: HttpClientEngine,
private val owner: Job? = null,
private val admission: () -> Boolean = { true },
) : HttpClientEngine {
override val coroutineContext get() = delegate.coroutineContext
override val dispatcher get() = delegate.dispatcher
override val config get() = delegate.config
override val supportedCapabilities get() = delegate.supportedCapabilities
private val lock = PlatformLock()
private val retirementLock = Mutex()
private val calls = mutableSetOf<Job>()
private var retired = false
private var released = false
fun ensureOpen() {
// Admission may consult another owner lock; never invoke it while holding the engine lock.
if (!admission()) throw CancellationException("Profile transport admission has ended")
lock.withLock {
owner?.ensureActive()
if (retired) throw CancellationException("Profile transport has ended")
}
}
override suspend fun execute(data: HttpRequestData): HttpResponseData {
ensureOpen()
val call = requireNotNull(callContext()[Job])
lock.withLock {
owner?.ensureActive()
if (retired) throw CancellationException("Profile transport has ended")
call.ensureActive()
calls += call
call.invokeOnCompletion { lock.withLock { calls.remove(call) } }
}
return delegate.execute(data)
}
private fun retire(): List<Job> = lock.withLock { retired = true; calls.toList() }
private fun release() = lock.withLock {
if (!released) { delegate.close(); released = true }
}
override fun close() { retire().forEach { it.cancel() }; release() }
suspend fun closeAndJoin() = retirementLock.withLock {
withContext(NonCancellable) {
val active = retire()
active.forEach { it.cancel() }
active.forEach { it.join() }
release()
delegate.coroutineContext[Job]?.let { it.cancel(); it.join() }
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/KtorHttpService.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines KtorHttpService, request, stream, HttpRequest.parsedUrl, HttpRequestBuilder.configure, KtorHttpResponse.headerMap, close, closeAndJoin, ensureOpen.
The source describes its contract as:
Ktor 3-based [HttpService] used by every platform. Construction takes a pre-configured engine (typically the platform's preferred transport: OkHttp on JVM targets, Darwin on iOS). Shared code owns timeouts, retries, request mapping and awaited retirement. Maintains parity with the old
HttpURLConnection-based service: 15s connect / 30s read timeouts, redirects followed, no caching, error responses still surface asHttpResponse(no exception thrown for 4xx/5xx). Adds Ktor'sHttpRequestRetryplugin (3 retries, exponential backoff capped at 4s) for transient 5xx / connection errors that the old service did not handle. [stream] reads a 2xx body as it arrives (non-2xx bodies are buffered up to [STREAM_ERROR_BODY_LIMIT] instead), drops the 60s total cap (the 30s socket timeout still catches a dead connection) and skips the retry plugin: its caller, the download service, owns the retry policy so the two layers never multiply.
package eu.friedcutlet.yokan.services.http
import io.ktor.client.HttpClient
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.plugins.HttpRequestRetry
import io.ktor.client.plugins.retry
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.HttpTimeoutConfig
import io.ktor.client.plugins.timeout
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.headers
import io.ktor.client.request.prepareRequest
import io.ktor.client.request.request
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse as KtorHttpResponse
import io.ktor.client.statement.bodyAsChannel
import io.ktor.client.statement.bodyAsBytes
import io.ktor.http.HttpMethod
import io.ktor.http.URLBuilder
import io.ktor.http.Url
import io.ktor.utils.io.readAvailable
import eu.friedcutlet.yokan.services.catchingNonCancellation
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
/**
* Ktor 3-based [HttpService] used by every platform. Construction takes a pre-configured
* engine (typically the platform's preferred transport: OkHttp on JVM targets,
* Darwin on iOS). Shared code owns timeouts, retries, request mapping and awaited retirement.
*
* Maintains parity with the old `HttpURLConnection`-based service: 15s connect / 30s read
* timeouts, redirects followed, no caching, error responses still surface as `HttpResponse` (no
* exception thrown for 4xx/5xx). Adds Ktor's `HttpRequestRetry` plugin (3 retries, exponential
* backoff capped at 4s) for transient 5xx / connection errors that the old service did not handle.
* [stream] reads a 2xx body as it arrives (non-2xx bodies are buffered up to [STREAM_ERROR_BODY_LIMIT]
* instead), drops the 60s total cap (the 30s socket timeout still catches a dead connection) and skips
* the retry plugin: its caller, the download service, owns the retry policy so the two layers never multiply.
*/
class KtorHttpService(engine: HttpClientEngine, ownerJob: Job? = null) : HttpService {
private val engine = ProfileHttpEngine(engine, ownerJob)
private val retirementLock = Mutex()
private val client: HttpClient = HttpClient(this.engine) {
expectSuccess = false
followRedirects = true
install(HttpTimeout) {
connectTimeoutMillis = 15_000L
requestTimeoutMillis = 60_000L
socketTimeoutMillis = 30_000L
}
install(HttpRequestRetry) {
retryOnExceptionOrServerErrors(maxRetries = 3)
exponentialDelay(base = 2.0, maxDelayMs = 4_000L)
}
}
override suspend fun request(request: HttpRequest): HttpResponse {
ensureOpen()
val url = request.parsedUrl()
?: return HttpResponse(statusCode = 0, body = "Invalid URL: ${request.url}")
val response = client.request(url) { configure(request) }
val bytes = catchingNonCancellation { response.bodyAsBytes() }.getOrElse { ByteArray(0) }
val headerMap = response.headerMap()
return HttpResponse(
statusCode = response.status.value,
headers = headerMap,
bodyBytes = bytes,
setCookies = response.headers.getAll("Set-Cookie").orEmpty(),
)
}
override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
ensureOpen()
val url = request.parsedUrl() ?: return HttpStreamResponse(statusCode = 0)
// client.request would buffer the whole body before returning; execute {} hands over the live channel.
return client.prepareRequest(url) {
configure(request)
timeout { requestTimeoutMillis = HttpTimeoutConfig.INFINITE_TIMEOUT_MS }
retry { noRetry() }
}.execute { response ->
request.onStreamResponse?.invoke(HttpStreamResponse(response.status.value, response.headerMap(), response.headers.getAll("Set-Cookie").orEmpty()))
val channel = response.bodyAsChannel()
val success = response.status.value in 200..299
val buffer = ByteArray(if (success) STREAM_CHUNK_SIZE else STREAM_ERROR_BODY_LIMIT)
var buffered = 0
while (success || buffered < buffer.size) {
val read = channel.readAvailable(buffer, buffered, buffer.size - buffered)
if (read < 0) break
// Error bodies (challenge pages) are kept for the caller to inspect, never streamed.
if (!success) buffered += read else if (read > 0) onChunk(buffer.copyOf(read))
}
HttpStreamResponse(
statusCode = response.status.value,
headers = response.headerMap(),
setCookies = response.headers.getAll("Set-Cookie").orEmpty(),
body = buffer.copyOf(buffered),
)
}
}
private fun HttpRequest.parsedUrl(): Url? = runCatching { URLBuilder(url).build() }.getOrNull()
private fun HttpRequestBuilder.configure(request: HttpRequest) {
method = HttpMethod.parse(request.method.uppercase())
headers {
request.headers.forEach { (key, value) -> append(key, value) }
}
val bodyBytes = request.bodyBytes
val body = request.body
if (bodyBytes != null || body != null) {
val hasContentType = request.headers.keys.any { it.equals("Content-Type", ignoreCase = true) }
if (!hasContentType) {
headers { append("Content-Type", "application/json") }
}
setBody(bodyBytes ?: body.orEmpty())
}
}
private fun KtorHttpResponse.headerMap(): Map<String, String> =
headers.entries().associate { (key, values) -> key to values.joinToString(",") }
/** Closes the client and the engine; Ktor does not close an engine it was handed. */
fun close() {
client.close()
engine.close()
}
/** Join request/body finalizers even when Ktor has already detached them from their callers. */
suspend fun closeAndJoin() = retirementLock.withLock {
withContext(NonCancellable) {
val clientJob = client.coroutineContext[Job]
clientJob?.cancel()
engine.closeAndJoin()
clientJob?.join()
client.close()
}
}
private suspend fun ensureOpen() {
currentCoroutineContext().ensureActive()
client.coroutineContext[Job]?.ensureActive()
engine.ensureOpen()
}
private companion object {
const val STREAM_CHUNK_SIZE = 64 * 1024
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/PlatformHttp.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines HostResolver, createPlatformHttpService, createPlatformHttpClientEngine, createDefaultPlatformHttpClientEngine, createIsolatedPlatformHttpClientEngine.
The source describes its contract as:
Resolves a hostname to an IP literal, or null to use the system resolver. Only engines that accept a custom resolver ([platformSupportsCustomDns]) consult it.
Cross-chapter imports used by this file: ProfileId. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http
import eu.friedcutlet.yokan.domain.ProfileId
import io.ktor.client.engine.HttpClientEngine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.ensureActive
/**
* Resolves a hostname to an IP literal, or null to use the system resolver. Only engines that
* accept a custom resolver ([platformSupportsCustomDns]) consult it.
*/
typealias HostResolver = suspend (hostname: String) -> String?
fun createPlatformHttpService(
profileId: ProfileId = ProfileId.Default,
ownerScope: CoroutineScope? = null,
resolveHost: HostResolver? = null,
): KtorHttpService {
val owner = ownerScope?.let { requireNotNull(it.coroutineContext[Job]) { "Profile HTTP requires an owner job" } }
owner?.ensureActive()
return KtorHttpService(createPlatformHttpClientEngine(profileId, resolveHost), owner)
}
/** Preserve Default's transport policy; extra owners require verified credential-store isolation. */
fun createPlatformHttpClientEngine(profileId: ProfileId = ProfileId.Default, resolveHost: HostResolver? = null): HttpClientEngine {
return if (profileId == ProfileId.Default) createDefaultPlatformHttpClientEngine(resolveHost)
else createIsolatedPlatformHttpClientEngine(resolveHost)
}
/** Whether the platform engine honours a [HostResolver]; Darwin and browser engines cannot take one. */
internal expect val platformSupportsCustomDns: Boolean
internal expect fun createDefaultPlatformHttpClientEngine(resolveHost: HostResolver? = null): HttpClientEngine
/** Extra profiles never borrow the native/browser cookie, credential or response cache stores. */
internal expect fun createIsolatedPlatformHttpClientEngine(resolveHost: HostResolver? = null): HttpClientEngine
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/ServerUrls.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines normalizeHubServer, hubWebSocketBase, isLoopbackProxy.
The source describes its contract as:
yokan-hub base URL:
https://unless a scheme is given; no trailing slash.nullwhen blank.
package eu.friedcutlet.yokan.services.http
/** yokan-hub base URL: `https://` unless a scheme is given; no trailing slash. `null` when blank. */
fun normalizeHubServer(server: String?): String? {
val s = server?.trim()?.trimEnd('/') ?: return null
if (s.isBlank()) return null
return if ("://" in s) s else "https://$s"
}
/** WebSocket base for a normalized hub URL: `https` → `wss`, `http` → `ws`. */
fun hubWebSocketBase(server: String): String = when {
server.startsWith("https://") -> "wss://" + server.removePrefix("https://")
server.startsWith("http://") -> "ws://" + server.removePrefix("http://")
else -> server
}
/** Whether [url] points at this device (the embedded extension server/proxy case). */
internal fun isLoopbackProxy(url: String): Boolean =
url.contains("://127.0.0.1") ||
url.contains("://localhost") ||
url.contains("://[::1]")
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/http/PlatformHttp.ios.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines createDefaultPlatformHttpClientEngine, createIsolatedPlatformHttpClientEngine.
package eu.friedcutlet.yokan.services.http
import io.ktor.client.engine.darwin.Darwin
import platform.Foundation.*
// NSURLSession resolves hosts itself; [platformSupportsCustomDns] hides the DNS settings.
internal actual val platformSupportsCustomDns: Boolean = false
internal actual fun createDefaultPlatformHttpClientEngine(resolveHost: HostResolver?): io.ktor.client.engine.HttpClientEngine = Darwin.create()
@OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
internal actual fun createIsolatedPlatformHttpClientEngine(resolveHost: HostResolver?): io.ktor.client.engine.HttpClientEngine = Darwin.create {
configureSession {
HTTPCookieStorage = null
HTTPShouldSetCookies = false
URLCredentialStorage = null
URLCache = null
}
configureRequest { setHTTPShouldHandleCookies(false) }
handleChallenge { _, _, challenge, complete ->
// Keep normal TLS verification; never ask the OS for another profile's saved HTTP/client
// certificate credentials. Explicit profile Authorization headers still work normally.
val disposition = if (challenge.protectionSpace.authenticationMethod == platform.Foundation.NSURLAuthenticationMethodServerTrust)
platform.Foundation.NSURLSessionAuthChallengePerformDefaultHandling
else platform.Foundation.NSURLSessionAuthChallengeCancelAuthenticationChallenge
complete(disposition, null)
}
}
Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/http/PlatformHttp.jvm.kt
Create this path in your reconstruction project. Source set: jvmCommonMain. Exact file download.
The implementation below defines createDefaultPlatformHttpClientEngine, createIsolatedPlatformHttpClientEngine, HostResolverDns, lookup.
The source describes its contract as:
Asks [resolveHost] first and falls back to [Dns.SYSTEM] when it has no answer or fails. OkHttp calls [lookup] on its own connection threads, so blocking on the resolver is fine there.
package eu.friedcutlet.yokan.services.http
import eu.friedcutlet.yokan.services.catchingNonCancellation
import io.ktor.client.engine.okhttp.OkHttp
import java.net.InetAddress
import kotlinx.coroutines.runBlocking
import okhttp3.Dns
internal actual val platformSupportsCustomDns: Boolean = true
internal actual fun createDefaultPlatformHttpClientEngine(resolveHost: HostResolver?): io.ktor.client.engine.HttpClientEngine = OkHttp.create {
config {
resolveHost?.let { dns(HostResolverDns(it)) }
}
}
internal actual fun createIsolatedPlatformHttpClientEngine(resolveHost: HostResolver?): io.ktor.client.engine.HttpClientEngine = OkHttp.create {
config {
cookieJar(okhttp3.CookieJar.NO_COOKIES)
authenticator(okhttp3.Authenticator.NONE)
proxyAuthenticator(okhttp3.Authenticator.NONE)
cache(null)
resolveHost?.let { dns(HostResolverDns(it)) }
}
}
/**
* Asks [resolveHost] first and falls back to [Dns.SYSTEM] when it has no answer or fails.
* OkHttp calls [lookup] on its own connection threads, so blocking on the resolver is fine there.
*/
internal class HostResolverDns(private val resolveHost: HostResolver) : Dns {
override fun lookup(hostname: String): List<InetAddress> {
val address = runBlocking { catchingNonCancellation { resolveHost(hostname) }.getOrNull() }
?: return Dns.SYSTEM.lookup(hostname)
// An IP literal is parsed locally; getByAddress keeps the hostname for logs and errors.
return listOf(InetAddress.getByAddress(hostname, InetAddress.getByName(address).address))
}
}
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/http/IsolatedBrowserHttpEngine.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The implementation below defines IsolatedBrowserHttpEngine, execute, bodyBytes, fetchPromise, abortFetch, status, statusText, headerJson, chunkDone, chunkBody and 3 further declarations.
The source describes its contract as:
Ktor 3.1.0's browser engine cannot configure fetch credentials. This small separate transport always omits ambient cookies/HTTP authentication and disables browser response caching. Browser cookie logins and WebSockets need a separately isolated backend, so they are explicitly refused. Default retains the original Ktor engine unchanged.
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, io.ktor.utils.io.InternalAPI::class,
kotlin.io.encoding.ExperimentalEncodingApi::class)
package eu.friedcutlet.yokan.services.http
import io.ktor.client.engine.HttpClientEngineBase
import io.ktor.client.engine.HttpClientEngineConfig
import io.ktor.client.engine.HttpClientEngineCapability
import io.ktor.client.plugins.HttpTimeoutCapability
import io.ktor.client.engine.callContext
import io.ktor.client.engine.mergeHeaders
import io.ktor.client.request.HttpRequestData
import io.ktor.client.request.HttpResponseData
import io.ktor.http.Headers
import io.ktor.http.HttpProtocolVersion
import io.ktor.http.HttpStatusCode
import io.ktor.http.content.OutgoingContent
import io.ktor.util.date.GMTDate
import io.ktor.utils.io.readBuffer
import io.ktor.utils.io.ByteChannel
import io.ktor.utils.io.writeFully
import io.ktor.utils.io.writer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.launch
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.await
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import kotlinx.io.readByteArray
import kotlinx.serialization.json.Json
import kotlin.io.encoding.Base64
import kotlin.js.JsAny
import kotlin.js.Promise
/**
* Ktor 3.1.0's browser engine cannot configure fetch credentials. This small separate transport
* always omits ambient cookies/HTTP authentication and disables browser response caching. Browser
* cookie logins and WebSockets need a separately isolated backend, so they are explicitly refused.
* Default retains the original Ktor engine unchanged.
*/
internal class IsolatedBrowserHttpEngine : HttpClientEngineBase("yokan-isolated-fetch") {
override val config = HttpClientEngineConfig()
override val supportedCapabilities: Set<HttpClientEngineCapability<*>> = setOf(HttpTimeoutCapability)
override suspend fun execute(data: HttpRequestData): HttpResponseData {
check(data.body !is OutgoingContent.ProtocolUpgrade) { "Browser WebSockets are unavailable in additional profiles" }
check(data.headers["Cookie"].isNullOrBlank()) { "Cookie authentication is unavailable in additional browser profiles" }
val context = callContext()
val body = bodyBytes(data.body, context)
currentCoroutineContext().ensureActive()
val headers = mutableMapOf<String, String>()
mergeHeaders(data.headers, data.body) { name, value -> headers[name] = value }
val started = GMTDate()
val operation = startFetch(data.url.toString(), data.method.value, Json.encodeToString(headers), body?.let(Base64::encode))
val promise = fetchPromise(operation)
val abort = requireNotNull(context[Job]).invokeOnCompletion { abortFetch(operation) }
val result = try { promise.await<JsAny>().also { currentCoroutineContext().ensureActive() } }
catch (error: Throwable) {
abortFetch(operation)
withContext(NonCancellable) {
runCatching { promise.await<JsAny>() }
runCatching { finishFetch(operation).await<JsAny?>() }
}
abort.dispose()
throw error
}
// The bounded channel backpressures Fetch. Large episodes do not accumulate as one body
// in JS/Wasm memory or hit the old 64 MiB response cap.
val incoming = ByteChannel(autoFlush = true)
CoroutineScope(context).launch(start = CoroutineStart.UNDISPATCHED) {
try {
while (true) {
currentCoroutineContext().ensureActive()
val chunk = readFetchChunk(operation).await<JsAny>()
if (chunkDone(chunk)) break
incoming.writeFully(Base64.decode(chunkBody(chunk)))
}
incoming.flushAndClose()
} catch (error: Throwable) {
incoming.cancel(error)
if (error is CancellationException) throw error
} finally {
abortFetch(operation)
try { withContext(NonCancellable) { finishFetch(operation).await<JsAny?>() } }
finally { abort.dispose() }
}
}
val responseHeaders = Json.decodeFromString<List<List<String>>>(headerJson(result))
return HttpResponseData(
HttpStatusCode(status(result), statusText(result)), started,
Headers.build { responseHeaders.forEach { pair ->
// Fetch exposes decoded bytes and may hide encoding headers for cross-origin calls.
if (!pair[0].equals("Content-Encoding", true) && !pair[0].equals("Content-Length", true)) append(pair[0], pair[1])
} }, HttpProtocolVersion.HTTP_1_1, incoming, context,
)
}
private suspend fun bodyBytes(content: OutgoingContent, context: kotlin.coroutines.CoroutineContext): ByteArray? = when (content) {
is OutgoingContent.ByteArrayContent -> content.bytes()
is OutgoingContent.ReadChannelContent -> content.readFrom().readBuffer().readByteArray()
is OutgoingContent.WriteChannelContent -> CoroutineScope(context).writer {
content.writeTo(channel)
}.channel.readBuffer().readByteArray()
is OutgoingContent.ContentWrapper -> bodyBytes(content.delegate(), context)
is OutgoingContent.NoContent -> null
is OutgoingContent.ProtocolUpgrade -> error("Isolated browser WebSockets are unavailable")
}
}
private fun fetchPromise(operation: JsAny): Promise<JsAny> = js("operation.promise")
private fun abortFetch(operation: JsAny): Unit = js("operation.controller.abort()")
private fun status(result: JsAny): Int = js("result.status")
private fun statusText(result: JsAny): String = js("result.statusText")
private fun headerJson(result: JsAny): String = js("result.headers")
private fun chunkDone(result: JsAny): Boolean = js("result.done")
private fun chunkBody(result: JsAny): String = js("result.body")
private fun readFetchChunk(operation: JsAny): Promise<JsAny> = js(
"""(() => {
operation.readPromise = (async () => {
if (!operation.reader) return { done: true, body: '' };
const chunk = await operation.reader.read();
if (chunk.done) return { done: true, body: '' };
let binary = '';
for (let i = 0; i < chunk.value.length; i += 32768)
binary += String.fromCharCode(...chunk.value.subarray(i, i + 32768));
return { done: false, body: btoa(binary) };
})();
return operation.readPromise;
})()""",
)
private fun finishFetch(operation: JsAny): Promise<JsAny?> = js(
"""(async () => {
if (operation.readPromise) await operation.readPromise.catch(() => {});
if (operation.reader) {
await operation.reader.cancel().catch(() => {});
operation.reader.releaseLock();
operation.reader = null;
}
return null;
})()""",
)
private fun startFetch(url: String, method: String, headersJson: String, body: String?): JsAny = js(
"""
(() => {
const controller = new AbortController();
let bytes;
if (body !== null) {
const binary = atob(body);
bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
}
const operation = { controller, reader: null, readPromise: null, promise: null };
operation.promise = (async () => {
const response = await fetch(url, { method, headers: JSON.parse(headersJson), body: bytes,
credentials: 'omit', cache: 'no-store', signal: controller.signal });
operation.reader = response.body && response.body.getReader();
return { status: response.status, statusText: response.statusText,
headers: JSON.stringify(Array.from(response.headers.entries())) };
})();
return operation;
})()
""",
)
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/http/PlatformHttp.wasm.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The implementation below defines createDefaultPlatformHttpClientEngine, createIsolatedPlatformHttpClientEngine.
package eu.friedcutlet.yokan.services.http
import io.ktor.client.engine.js.Js
// The browser resolves hosts itself; [platformSupportsCustomDns] hides the DNS settings.
internal actual val platformSupportsCustomDns: Boolean = false
internal actual fun createDefaultPlatformHttpClientEngine(resolveHost: HostResolver?): io.ktor.client.engine.HttpClientEngine = Js.create()
internal actual fun createIsolatedPlatformHttpClientEngine(resolveHost: HostResolver?): io.ktor.client.engine.HttpClientEngine = IsolatedBrowserHttpEngine()
Check your understanding
Read a response a chunk at a time, cancel halfway, and show which object closes the call and which closes the engine. [chapter-content-end]: #
Step 2: add profile-aware HTTP and cookies
Wrap raw transport with ProfileHttpService. Recreate CookieParser and CookieJar: domain/path/expiry matching, response imports, clear operations, persisted encoding and transient solved-browser user agents. A retired jar returns no credentials and ignores updates. Serialize reads/mutations so imports and clears cannot race into lost changes.
Build EnhancedHttpService on the raw client with the jar, DNS-over-HTTPS support where implemented, challenge detection and WebView solver callback. Avoid DNS recursion: resolver requests cannot resolve through the same resolver they implement. Sync providers and user-hosted/LAN services deliberately use raw transport in several places; preserve that separation so app cookies do not swallow sync-specific JWT cookies or API keys.
Follow the code
Cookie parsing turns response strings into stored attributes; the jar decides whether a cookie matches a destination and is still valid. ProfileHttpService and the engine wrapper reject stale work before credentials can be attached. Keep jar retirement and mutation serialization around imports/clears. DNS-over-HTTPS uses a resolver path that must not invoke itself recursively. Raw sync/LAN clients remain separate from enhanced source traffic.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieParser.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieJar.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/ProfileHttpService.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/DnsService.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieJar.android.ktcomposeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieJar.desktop.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieJar.ios.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieJar.wasm.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieParser.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ParsedCookie, parseSetCookie, ParsedCookie.appliesTo, ParsedCookie.isExpired, parseCookieDate, monthIndex, epochUtcMillis, isLeap.
The source describes its contract as:
Parsed cookie record. Domain matching follows RFC 6265 §5.1.3: if the cookie was issued with an explicit
Domain=, that's used (with any leading dot stripped) and the cookie applies to that host and any subdomain. With no explicitDomain, the cookie is host-only and only matches the request host exactly.
Cross-chapter imports used by this file: nowMillis. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http.cookies
import eu.friedcutlet.yokan.util.nowMillis
/**
* Parsed cookie record. Domain matching follows RFC 6265 §5.1.3: if the cookie
* was issued with an explicit `Domain=`, that's used (with any leading dot
* stripped) and the cookie applies to that host and any subdomain. With no
* explicit `Domain`, the cookie is host-only and only matches the request host
* exactly.
*/
internal data class ParsedCookie(
val name: String,
val value: String,
val domain: String,
val path: String,
val hostOnly: Boolean,
val expiresAt: Long?,
val secure: Boolean,
val httpOnly: Boolean,
)
/**
* Parse a single `Set-Cookie` header value as it appeared on the wire. Returns
* null when the input has no `name=value` part. Unknown attributes are
* ignored (Same-Site, Priority, etc.).
*
* Date attributes are parsed loosely — `Expires=` headers historically ship in
* three different formats; we accept RFC 1123 (`Mon, 02 Jan 2006 15:04:05 GMT`),
* RFC 850 (`Monday, 02-Jan-06 …`), and the Cookie Working Group's seven-token
* variant. Anything we can't parse becomes a session cookie (no expiry).
*/
internal fun parseSetCookie(raw: String, requestHost: String): ParsedCookie? {
val trimmed = raw.trim()
if (trimmed.isEmpty()) return null
val attrs = trimmed.split(';').map { it.trim() }.filter { it.isNotEmpty() }
val pair = attrs.firstOrNull() ?: return null
val nameEnd = pair.indexOf('=')
if (nameEnd <= 0) return null
val name = pair.substring(0, nameEnd).trim()
val value = pair.substring(nameEnd + 1).trim()
if (name.isEmpty()) return null
var domain = requestHost
var hostOnly = true
var path = "/"
var expiresAt: Long? = null
var maxAgeMillis: Long? = null
var secure = false
var httpOnly = false
for (attr in attrs.drop(1)) {
val eq = attr.indexOf('=')
val key = if (eq < 0) attr else attr.substring(0, eq)
val attrValue = if (eq < 0) "" else attr.substring(eq + 1).trim()
when (key.lowercase()) {
"domain" -> {
val v = attrValue.removePrefix(".").lowercase()
if (v.isEmpty() || (requestHost != v && !requestHost.endsWith(".$v"))) return null
domain = v
hostOnly = false
}
"path" -> if (attrValue.isNotEmpty()) path = attrValue
"expires" -> expiresAt = runCatching { parseCookieDate(attrValue) }.getOrNull()
"max-age" -> {
val seconds = attrValue.toLongOrNull()
if (seconds != null) {
maxAgeMillis = if (seconds <= 0) -1L else seconds * 1_000L
}
}
"secure" -> secure = true
"httponly" -> httpOnly = true
}
}
// RFC 6265: Max-Age trumps Expires when both are present.
val finalExpiresAt = when {
maxAgeMillis != null -> if (maxAgeMillis < 0) 0L else nowMillis() + maxAgeMillis
else -> expiresAt
}
return ParsedCookie(
name = name,
value = value,
domain = domain,
path = path,
hostOnly = hostOnly,
expiresAt = finalExpiresAt,
secure = secure,
httpOnly = httpOnly,
)
}
/** Does this cookie's domain, path, and Secure flag match the request target? */
internal fun ParsedCookie.appliesTo(host: String, requestPath: String, requestSecure: Boolean): Boolean {
val target = host.lowercase()
val domainMatches = if (hostOnly) {
target == domain
} else {
target == domain || target.endsWith(".$domain")
}
if (!domainMatches || (secure && !requestSecure)) return false
val normalizedCookiePath = path.takeIf { it.startsWith('/') } ?: "/"
if (!requestPath.startsWith(normalizedCookiePath)) return false
return requestPath.length == normalizedCookiePath.length ||
normalizedCookiePath.endsWith('/') ||
requestPath.getOrNull(normalizedCookiePath.length) == '/'
}
/** Cookie is expired or signalled for deletion. */
internal fun ParsedCookie.isExpired(now: Long = nowMillis()): Boolean =
expiresAt != null && expiresAt <= now
/**
* Parse an HTTP cookie date — we accept the three common shapes plus the
* Cookie Working Group's seven-token variant. Returns null when we can't
* extract day/month/year/hour/min/sec.
*/
private fun parseCookieDate(input: String): Long? {
val raw = input.replace(',', ' ').trim()
if (raw.isEmpty()) return null
val tokens = raw.split(Regex("\\s+"))
var day = -1
var month = -1
var year = -1
var hour = -1
var minute = -1
var second = -1
for (token in tokens) {
// dd-MMM-yy / dd-MMM-yyyy style ships month + day + year glued together.
if (token.contains('-')) {
val parts = token.split('-')
if (parts.size == 3) {
val maybeDay = parts[0].toIntOrNull()
val maybeMonth = monthIndex(parts[1])
val maybeYear = parts[2].toIntOrNull()
if (maybeDay != null && maybeMonth >= 0 && maybeYear != null) {
day = maybeDay; month = maybeMonth; year = maybeYear
continue
}
}
}
// HH:MM:SS
if (token.contains(':')) {
val parts = token.split(':')
if (parts.size >= 3) {
hour = parts[0].toIntOrNull() ?: hour
minute = parts[1].toIntOrNull() ?: minute
second = parts[2].toIntOrNull() ?: second
continue
}
}
// Two-to-four digit numbers — day-of-month or year.
token.toIntOrNull()?.let { n ->
when {
n in 1..31 && day < 0 -> day = n
n in 1970..2099 && year < 0 -> year = n
n in 0..99 && year < 0 -> year = if (n >= 70) 1900 + n else 2000 + n
}
return@let
}
// Three-letter month abbreviation.
monthIndex(token).takeIf { it >= 0 }?.let { idx -> if (month < 0) month = idx }
}
if (day < 0 || month < 0 || year < 0 || hour < 0 || minute < 0 || second < 0) return null
return epochUtcMillis(year, month, day, hour, minute, second)
}
private fun monthIndex(token: String): Int {
val s = token.lowercase()
return when {
s.startsWith("jan") -> 0
s.startsWith("feb") -> 1
s.startsWith("mar") -> 2
s.startsWith("apr") -> 3
s.startsWith("may") -> 4
s.startsWith("jun") -> 5
s.startsWith("jul") -> 6
s.startsWith("aug") -> 7
s.startsWith("sep") -> 8
s.startsWith("oct") -> 9
s.startsWith("nov") -> 10
s.startsWith("dec") -> 11
else -> -1
}
}
/**
* Convert (year, monthIndex 0–11, day, hour, minute, second) at UTC to epoch
* millis without a third-party date library. Handles leap years; doesn't
* concern itself with leap seconds or sub-second precision.
*/
private fun epochUtcMillis(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): Long {
require(month in 0..11)
val y = year.toLong()
val daysFromEpochToYearStart = run {
// Counting from 1970-01-01.
var d = 0L
if (y >= 1970) {
for (i in 1970 until y.toInt()) d += if (isLeap(i)) 366 else 365
} else {
for (i in (y.toInt()) until 1970) d -= if (isLeap(i)) 366 else 365
}
d
}
val monthDays = intArrayOf(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
if (isLeap(year)) monthDays[1] = 29
var d = daysFromEpochToYearStart
for (i in 0 until month) d += monthDays[i]
d += (day - 1)
val secondsOfDay = hour * 3600L + minute * 60L + second
return d * 86_400L * 1_000L + secondsOfDay * 1_000L
}
private fun isLeap(year: Int): Boolean = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0)
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieJar.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines CookieJar, rememberUserAgent, userAgent, cookieHeader, setFromResponse, put, rawCookieFor, clear, whileOpen, storeUserAgent and 19 further declarations.
The source describes its contract as:
Persistent cookie jar. Backed by
DbSettings.cookiesList. Each [DbCookie] row stores a single host (host-only) or registered domain (subdomain-match) and a renderedname=value; name2=value2; …string for fast injection into outgoing requests. Attribute metadata (Domain,Path,Expires,Max-Age,Secure,HttpOnly) is encoded into a sibling JSON sidecar so we can drop expired cookies and respect subdomain matching without parsing the cookie name/value blob each request. The sidecar is stashed inside the sameDbCookie.cookiefield with a sentinel suffix (|meta=\<json\>) so adding it doesn't require a schema migration. If the sidecar is missing — which is the case for jars persisted by an earlier Yokan build — the jar treats the row as a session-only host-bound cookie. The jar is intentionally synchronous: it never blocks on network IO, only on the lightweightdatabase.updateSettings(…)write that the rest of the app already routes through.
Cross-chapter imports used by this file: DbCookie, YokanDatabase, ProfileId, PlatformLock, nowMillis. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http.cookies
import eu.friedcutlet.yokan.database.DbCookie
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.util.PlatformLock
import eu.friedcutlet.yokan.services.http.EnhancedHttpService
import eu.friedcutlet.yokan.util.nowMillis
/**
* Persistent cookie jar. Backed by `DbSettings.cookiesList`.
*
* Each [DbCookie] row stores a single host (`host-only`) or registered domain
* (`subdomain-match`) and a rendered `name=value; name2=value2; …` string for
* fast injection into outgoing requests. Attribute metadata (`Domain`, `Path`,
* `Expires`, `Max-Age`, `Secure`, `HttpOnly`) is encoded into a sibling JSON
* sidecar so we can drop expired cookies and respect subdomain matching
* without parsing the cookie name/value blob each request.
*
* The sidecar is stashed inside the same `DbCookie.cookie` field with a sentinel
* suffix (` |meta=<json>`) so adding it doesn't require a schema migration. If
* the sidecar is missing — which is the case for jars persisted by an earlier
* Yokan build — the jar treats the row as a session-only host-bound cookie.
*
* The jar is intentionally synchronous: it never blocks on network IO, only on
* the lightweight `database.updateSettings(…)` write that the rest of the app
* already routes through.
*/
class CookieJar(
private val database: YokanDatabase,
val profileId: ProfileId = ProfileId.Default,
private val isOpen: () -> Boolean = { true },
) {
private val lock = PlatformLock()
private var sessionUserAgents: Map<String, String> = emptyMap()
val isAvailable: Boolean get() = lock.withLock { isOpen() }
/** Native/browser stores: Default uses the platform's shared store; extras need a per-profile platform store. */
val canUseBrowserStorage: Boolean
get() = lock.withLock { isOpen() && (profileId == ProfileId.Default || platformBrowserIsolation) }
fun rememberUserAgent(url: String, userAgent: String) = whileOpen(Unit) { storeUserAgent(url, userAgent) }
fun userAgent(url: String): String? = whileOpen(null) { lookupUserAgent(url) }
fun cookieHeader(url: String): String? = whileOpen(null) { buildCookieHeader(url) }
fun setFromResponse(url: String, rawSetCookies: List<String>) = whileOpen(Unit) { persistResponseCookies(url, rawSetCookies) }
fun put(host: String, cookieString: String) = whileOpen(Unit) { persistCookieHeader(host, cookieString) }
fun rawCookieFor(host: String): String? = whileOpen(null) { lookupRawCookie(host) }
fun clear(host: String? = null) = whileOpen(Unit) { clearCookies(host) }
private fun <T> whileOpen(fallback: T, action: () -> T): T = lock.withLock {
if (isOpen()) action() else fallback
}
private fun storeUserAgent(url: String, userAgent: String) {
val host = parseHost(url) ?: return
if (userAgent.isBlank()) return
sessionUserAgents = sessionUserAgents + (host to userAgent)
}
private fun lookupUserAgent(url: String): String? {
val host = parseHost(url) ?: return null
return sessionUserAgents.entries
.filter { (domain) -> host == domain || host.endsWith(".$domain") }
.maxByOrNull { (domain) -> domain.length }
?.value
}
/**
* Build a `Cookie: name=value; name2=value2; …` header for [url], merging
* every persisted row whose domain matches the URL host. Returns null when
* nothing applies so callers can decide whether to send no Cookie header
* at all rather than send an empty one (some hosts treat the two
* differently).
*/
private fun buildCookieHeader(url: String): String? {
val target = parseCookieRequest(url) ?: return null
val rows = readRows()
if (rows.isEmpty()) return null
val now = nowMillis()
val matching = rows.flatMap { row ->
row.cookies.filter { cookie ->
cookie.appliesTo(target.host, target.path, target.secure) && !cookie.isExpired(now)
}
}
if (matching.isEmpty()) return null
// Deduplicate by name (later entries win) so a Set-Cookie on a parent
// domain doesn't shadow one set later on a subdomain.
val byName = linkedMapOf<String, ParsedCookie>()
matching.forEach { byName[it.name] = it }
return byName.values.joinToString("; ") { "${it.name}=${it.value}" }
}
/**
* Persist a freshly-received list of `Set-Cookie` headers issued by [url].
* Expired cookies in the list will displace any matching row, which is how
* servers signal a logout (e.g. `Set-Cookie: SID=; Max-Age=0`).
*/
private fun persistResponseCookies(url: String, rawSetCookies: List<String>) {
if (rawSetCookies.isEmpty()) return
val host = parseHost(url) ?: return
val parsed = rawSetCookies.mapNotNull { parseSetCookie(it, host) }
if (parsed.isEmpty()) return
val rows = readRows().associateBy { it.host }.toMutableMap()
for (cookie in parsed) {
val row = rows[cookie.domain] ?: HostRow(cookie.domain, mutableListOf())
val rebuilt = row.cookies.filterNot { it.name == cookie.name && it.domain == cookie.domain && it.path == cookie.path }
.toMutableList()
if (!cookie.isExpired()) rebuilt += cookie
if (rebuilt.isEmpty()) rows.remove(cookie.domain)
else rows[cookie.domain] = HostRow(cookie.domain, rebuilt)
}
writeRows(rows.values.toList())
}
/**
* Explicitly seed the jar from a `name=value; name2=value2; …` string —
* used when the user pastes in a cookie from an external session, or when
* a tracker callback hands one back. Domain defaults to [host] and the
* cookies are host-only.
*/
private fun persistCookieHeader(host: String, cookieString: String) {
if (cookieString.isBlank()) return
val normalisedHost = host.lowercase()
val cookies = cookieString.split(';').mapNotNull { entry ->
val trimmed = entry.trim()
val eq = trimmed.indexOf('=')
if (eq <= 0) return@mapNotNull null
ParsedCookie(
name = trimmed.substring(0, eq).trim(),
value = trimmed.substring(eq + 1).trim(),
domain = normalisedHost,
path = "/",
hostOnly = true,
expiresAt = null,
secure = false,
httpOnly = false,
)
}
if (cookies.isEmpty()) return
val rows = readRows().associateBy { it.host }.toMutableMap()
val row = rows[normalisedHost] ?: HostRow(normalisedHost, mutableListOf())
val rebuilt = row.cookies.filterNot { c -> cookies.any { it.name == c.name } }.toMutableList()
rebuilt += cookies
rows[normalisedHost] = HostRow(normalisedHost, rebuilt)
writeRows(rows.values.toList())
}
/**
* Lookup the persisted cookie string for [host] exactly — useful for code
* paths (e.g. the WebView bridge or the QuarkUc extractor) that want the
* legacy "render whatever cookie was stored on this host" semantic without
* subdomain matching.
*/
private fun lookupRawCookie(host: String): String? {
val target = host.lowercase()
val now = nowMillis()
val cookies = readRows()
.firstOrNull { it.host == target }
?.cookies
?.filter { !it.isExpired(now) }
?: return null
if (cookies.isEmpty()) return null
return cookies.joinToString("; ") { "${it.name}=${it.value}" }
}
/** Wipe the jar (no argument) or just one host. */
private fun clearCookies(host: String?) {
if (host == null) {
sessionUserAgents = emptyMap()
val settings = database.settings()
database.updateSettings(settings.copy(cookiesList = emptyList()))
return
}
val target = host.lowercase()
sessionUserAgents = sessionUserAgents - target
val rows = readRows().filterNot { it.host == target }
writeRows(rows)
}
// ─────────────────────────────────────────────────────────────────────────
// Storage internals
private data class HostRow(val host: String, val cookies: List<ParsedCookie>)
private fun readRows(): List<HostRow> {
val raw = database.settings().cookiesList.orEmpty()
return raw.mapNotNull { row ->
val host = row.host?.lowercase() ?: return@mapNotNull null
val cookies = decode(host, row.cookie.orEmpty()) ?: return@mapNotNull null
HostRow(host, cookies)
}
}
private fun writeRows(rows: List<HostRow>) {
val settings = database.settings()
val encoded = rows.mapNotNull { row ->
if (row.cookies.isEmpty()) return@mapNotNull null
DbCookie(host = row.host, cookie = encode(row.cookies))
}
database.updateSettings(settings.copy(cookiesList = encoded))
}
/**
* Encode a list of cookies into the persistent string format:
* `name=value; name=value | meta=<json>`. The `| meta=` sentinel keeps the
* left half compatible with the old EnhancedHttpService format so a
* downgrade can still ship a Cookie header (it just loses attributes).
*/
private fun encode(cookies: List<ParsedCookie>): String {
val pairs = cookies.joinToString("; ") { "${it.name}=${it.value}" }
val meta = encodeMeta(cookies)
return if (meta.isBlank()) pairs else "$pairs $META_SEPARATOR$meta"
}
private fun decode(host: String, raw: String): List<ParsedCookie>? {
if (raw.isBlank()) return emptyList()
val sepIndex = raw.lastIndexOf(META_SEPARATOR)
val pairsPart = if (sepIndex < 0) raw else raw.substring(0, sepIndex).trimEnd()
val metaPart = if (sepIndex < 0) null else raw.substring(sepIndex + META_SEPARATOR.length).trim()
val pairs = pairsPart.split(';').mapNotNull { entry ->
val trimmed = entry.trim()
val eq = trimmed.indexOf('=')
if (eq <= 0) return@mapNotNull null
trimmed.substring(0, eq).trim() to trimmed.substring(eq + 1).trim()
}
val meta = metaPart?.let(::decodeMeta).orEmpty()
return pairs.map { (name, value) ->
val m = meta[name]
ParsedCookie(
name = name,
value = value,
domain = m?.domain ?: host,
path = m?.path ?: "/",
hostOnly = m?.hostOnly ?: true,
expiresAt = m?.expiresAt,
secure = m?.secure ?: false,
httpOnly = m?.httpOnly ?: false,
)
}
}
private data class StoredMeta(
val domain: String,
val path: String,
val hostOnly: Boolean,
val expiresAt: Long?,
val secure: Boolean,
val httpOnly: Boolean,
)
private fun encodeMeta(cookies: List<ParsedCookie>): String {
val entries = cookies.joinToString(",") { c ->
// name=value attributes are already in the legacy half; encode only the
// metadata fields we need to honour on the next request.
val expires = c.expiresAt?.toString().orEmpty()
"${c.name.escapeMeta()}|${c.domain.escapeMeta()}|${c.path.escapeMeta()}|${if (c.hostOnly) "1" else "0"}|$expires|${if (c.secure) "1" else "0"}|${if (c.httpOnly) "1" else "0"}"
}
return entries
}
private fun decodeMeta(raw: String): Map<String, StoredMeta> {
if (raw.isEmpty()) return emptyMap()
return raw.split(',').mapNotNull { entry ->
val parts = entry.split('|')
if (parts.size < 7) return@mapNotNull null
val name = parts[0].unescapeMeta()
name to StoredMeta(
domain = parts[1].unescapeMeta(),
path = parts[2].unescapeMeta(),
hostOnly = parts[3] == "1",
expiresAt = parts[4].toLongOrNull(),
secure = parts[5] == "1",
httpOnly = parts[6] == "1",
)
}.toMap()
}
private fun String.escapeMeta(): String = replace("\\", "\\\\").replace("|", "\\1").replace(",", "\\2")
private fun String.unescapeMeta(): String = replace("\\2", ",").replace("\\1", "|").replace("\\\\", "\\")
private companion object {
const val META_SEPARATOR = "|meta="
}
}
/** Whether this platform can give each extra profile its own isolated browser cookie/data store. */
internal expect val platformBrowserIsolation: Boolean
/** Strip scheme + path + port off a URL to leave only the lowercase host. */
internal fun parseHost(url: String): String? {
val noProtocol = url.substringAfter("://", url)
val hostEnd = noProtocol.indexOfFirst { it == '/' || it == '?' || it == '#' }
val hostPort = if (hostEnd == -1) noProtocol else noProtocol.substring(0, hostEnd)
if (hostPort.isBlank()) return null
return hostPort.substringBefore(':').lowercase()
}
private data class CookieRequest(val host: String, val path: String, val secure: Boolean)
private fun parseCookieRequest(url: String): CookieRequest? {
val host = parseHost(url) ?: return null
val scheme = url.substringBefore("://", "").lowercase()
val afterAuthority = url.substringAfter("://", url).substringAfter('/', "")
val path = if (afterAuthority.isEmpty()) "/" else "/" + afterAuthority.substringBefore('?').substringBefore('#')
return CookieRequest(host = host, path = path, secure = scheme == "https")
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/ProfileHttpService.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ProfileHttpService, request, stream.
The source describes its contract as:
Owns the entire call, including settings/cookie access, retries, streaming and finalizers.
Cross-chapter imports used by this file: ProfileId. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.runJoined
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.ensureActive
/** Owns the entire call, including settings/cookie access, retries, streaming and finalizers. */
internal class ProfileHttpService(
val profileId: ProfileId,
private val delegate: HttpService,
ownerScope: CoroutineScope,
) : HttpService {
private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) { "Profile HTTP requires an owner job" }
private val scope = CoroutineScope(ownerScope.coroutineContext + SupervisorJob(ownerJob))
override suspend fun request(request: HttpRequest): HttpResponse = scope.runJoined { delegate.request(request) }
override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse =
scope.runJoined { callJob ->
val guardedRequest = request.onStreamResponse?.let { onResponse ->
request.copy(onStreamResponse = { response ->
callJob.ensureActive()
ownerJob.ensureActive()
onResponse(response)
})
} ?: request
delegate.stream(guardedRequest) { bytes ->
// Check the original call even if a transport invokes this from a cleanup context.
callJob.ensureActive()
ownerJob.ensureActive()
onChunk(bytes)
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/DnsService.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DohProviderOption, DohResolver, resolve, providerFor, Provider, CachedAnswer.
The source describes its contract as:
Minimal DNS-over-HTTPS resolver. When DoH is enabled in settings (read on every lookup) we query the configured provider's JSON endpoint and return the first IPv4 answer; otherwise null, so the caller uses the system resolver. [http] must not resolve through this resolver.
Cross-chapter imports used by this file: YokanDatabase, PlatformLock. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonPrimitive
const val CustomDohProviderId: Int = 999
data class DohProviderOption(val id: Int, val name: String, val url: String)
val DohProviders: List<DohProviderOption> = listOf(
DohProviderOption(0, "Cloudflare", "https://cloudflare-dns.com/dns-query"),
DohProviderOption(1, "Google", "https://dns.google/dns-query"),
DohProviderOption(2, "AdGuard", "https://dns-unfiltered.adguard.com/dns-query"),
DohProviderOption(3, "Quad9", "https://dns.quad9.net/dns-query"),
DohProviderOption(4, "AliDNS", "https://dns.alidns.com/dns-query"),
DohProviderOption(5, "DNSPod", "https://doh.pub/dns-query"),
DohProviderOption(6, "360 DNS", "https://doh.360.cn/dns-query"),
DohProviderOption(7, "Quad101", "https://dns.twnic.tw/dns-query"),
DohProviderOption(8, "Mullvad", "https://doh.mullvad.net/dns-query"),
DohProviderOption(9, "ControlD", "https://freedns.controld.com/p0"),
DohProviderOption(10, "Njalla", "https://dns.njal.la/dns-query"),
DohProviderOption(11, "Shecan", "https://free.shecan.ir/dns-query"),
)
/**
* Minimal DNS-over-HTTPS resolver. When DoH is enabled in settings (read on every lookup) we query
* the configured provider's JSON endpoint and return the first IPv4 answer; otherwise null, so the
* caller uses the system resolver. [http] must not resolve through this resolver.
*/
class DohResolver(
private val database: YokanDatabase,
private val http: HttpService,
) {
private val json = Json { ignoreUnknownKeys = true; isLenient = true }
// OkHttp resolves from several connection threads at once.
private val cacheLock = PlatformLock()
private val cache = mutableMapOf<String, CachedAnswer>()
suspend fun resolve(hostname: String): String? {
if (hostname.isBlank()) return null
val settings = database.settings()
if (!settings.dohEnabled) return null
val now = eu.friedcutlet.yokan.util.nowMillis()
cacheLock.withLock { cache[hostname]?.takeIf { it.expiresAtMillis > now } }?.let { return it.address }
val provider = providerFor(settings) ?: return null
if (provider.url.isBlank()) return null
val separator = if (provider.url.contains("?")) "&" else "?"
val response = catchingNonCancellation {
http.request(
HttpRequest(
url = "${provider.url}${separator}name=$hostname&type=A",
headers = mapOf("Accept" to "application/dns-json"),
),
)
}.getOrNull() ?: return null
if (response.statusCode !in 200..299) return null
val parsed = runCatching { json.parseToJsonElement(response.body) as? JsonObject }.getOrNull() ?: return null
val answers = parsed["Answer"] as? JsonArray ?: return null
val ip = answers.firstNotNullOfOrNull { entry ->
val obj = entry as? JsonObject ?: return@firstNotNullOfOrNull null
val type = obj["type"]?.jsonPrimitive?.intOrNull ?: return@firstNotNullOfOrNull null
if (type != 1) return@firstNotNullOfOrNull null
obj["data"]?.jsonPrimitive?.contentOrNull
} ?: return null
cacheLock.withLock { cache[hostname] = CachedAnswer(ip, now + ProviderCacheMillis) }
return ip
}
private fun providerFor(settings: eu.friedcutlet.yokan.database.DbSettings): Provider? {
if (settings.dohProviderId == CustomDohProviderId) {
val custom = settings.customDohUrl.trim()
if (custom.isBlank()) return null
return Provider("Custom", custom)
}
val match = DohProviders.firstOrNull { it.id == settings.dohProviderId } ?: DohProviders[0]
return Provider(match.name, match.url)
}
private companion object {
const val ProviderCacheMillis = 5L * 60L * 1000L
}
private data class Provider(val name: String, val url: String)
private data class CachedAnswer(val address: String, val expiresAtMillis: Long)
}
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieJar.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The source describes its contract as:
WebView profiles (androidx.webkit ProfileStore); false without a WebView provider (and in JVM unit tests).
package eu.friedcutlet.yokan.services.http.cookies
import androidx.webkit.WebViewFeature
/** WebView profiles (androidx.webkit ProfileStore); false without a WebView provider (and in JVM unit tests). */
internal actual val platformBrowserIsolation: Boolean by lazy {
runCatching { WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE) }.getOrDefault(false)
}
Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieJar.desktop.kt
Create this path in your reconstruction project. Source set: desktopMain. Exact file download.
The source describes its contract as:
JavaFX cookies are swapped per profile and challenge browsers use the profile's cache root.
package eu.friedcutlet.yokan.services.http.cookies
/** JavaFX cookies are swapped per profile and challenge browsers use the profile's cache root. */
internal actual val platformBrowserIsolation: Boolean = true
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieJar.ios.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The source describes its contract as:
Extra profiles get their own WKWebsiteDataStore (see profileDataStore).
package eu.friedcutlet.yokan.services.http.cookies
/** Extra profiles get their own WKWebsiteDataStore (see profileDataStore). */
internal actual val platformBrowserIsolation: Boolean = true
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieJar.wasm.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The source describes its contract as:
The browser tab's cookies are shared by every profile in it; extras stay without browser integrations.
package eu.friedcutlet.yokan.services.http.cookies
/** The browser tab's cookies are shared by every profile in it; extras stay without browser integrations. */
internal actual val platformBrowserIsolation: Boolean = false
Check your understanding
Use two jars with the same host and different values. Import, clear and retire one while the other performs requests; no state should cross between them. [chapter-content-end]: #
Step 3: implement challenge solving as a controlled retry
Detect the reference challenge cases in normal and streamed responses. Pause/cancel the original request correctly, invoke the owned browser solver, import accepted cookies/user agent, then retry without recursively invoking the solver forever. Preserve original source headers when appropriate. Keep a clear distinction between a user-visible browser, headless helper and pure HTTP request.
Follow the code
EnhancedHttpService enriches requests, records response cookies and decides whether a challenge is present. The per-host solve gate has a generation counter: parallel challenged requests reuse a solve completed while they were waiting. The skip marker prevents a solver's verification request from entering the solver again, and removes the caller's obsolete Cookie header. Follow normal and streamed requests separately; both preserve cancellation and retry policy.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/EnhancedHttpService.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/EnhancedHttpService.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The generation read before sending a request lets a late challenge reuse an already completed solve. The solver's skip header is consumed internally rather than forwarded as an application credential.
The implementation below defines EnhancedHttpService, request, stream, performStream, HttpRequest.skipMarked, performRequest, clearCloudflare, solveCloudflare, solveGate, solveGeneration and 11 further declarations.
The source describes its contract as:
Decorator around the platform [HttpService] that adds: - default
User-Agent(DbSettings.userAgent). - automatic Cookie injection + Set-Cookie persistence via the shared [CookieJar]. - request/response logging through [AppLogger]. - automatic Cloudflare challenge solving for GET requests and streams: a FlareSolverr-compatible proxy first, then the platform WebView (Mangayomi'sm_clientretry policy), single-flight per host.
Cross-chapter imports used by this file: YokanDatabase, AppLogger, Diagnostics. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.logging.Diagnostics
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.http.cookies.parseHost
import kotlin.concurrent.Volatile
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
/**
* Decorator around the platform [HttpService] that adds:
* - default `User-Agent` (`DbSettings.userAgent`).
* - automatic Cookie injection + Set-Cookie persistence via the shared
* [CookieJar].
* - request/response logging through [AppLogger].
* - automatic Cloudflare challenge solving for GET requests and streams: a
* FlareSolverr-compatible proxy first, then the platform WebView
* (Mangayomi's `m_client` retry policy), single-flight per host.
*/
class EnhancedHttpService(
private val delegate: HttpService,
private val database: YokanDatabase,
private val cookieJar: CookieJar,
) : HttpService {
/** Set once the platform WebView service exists (see ServiceRegistry). */
var cloudflareSolver: (suspend (url: String, headers: Map<String, String>) -> HttpResponse?)? = null
// ponytail: one gate per host ever challenged, never evicted; such hosts are few.
private val solveGatesLock = Mutex()
private val solveGates = HashMap<String, CloudflareGate>()
override suspend fun request(request: HttpRequest): HttpResponse {
request.skipMarked()?.let { return performRequest(it, allowCloudflareSolve = false) }
return performRequest(request, allowCloudflareSolve = true)
}
override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
val skipped = request.skipMarked()
if (skipped != null || !request.method.equals("GET", ignoreCase = true)) {
return performStream(skipped ?: request, onChunk)
}
val seen = solveGeneration(request.url)
val response = performStream(request, onChunk)
if (!response.isCloudflareChallenge()) return response
clearCloudflare(request.url, enrichedHeaders(request, database.settings()), seen) ?: return response
AppLogger.info("[net] Retrying stream ${request.url} with the fresh Cloudflare clearance")
return performStream(request, onChunk)
}
private suspend fun performStream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
val settings = database.settings()
val headers = enrichedHeaders(request, settings)
val startMs = eu.friedcutlet.yokan.util.nowMillis()
var received = 0L
AppLogger.info("[net] ${request.method} ${request.url} (stream)")
val response = try {
delegate.stream(request.copy(headers = headers)) { chunk ->
throttleBytes(chunk.size.toLong(), settings.networkDownloadSpeedLimitKib)
received += chunk.size
onChunk(chunk)
}
} catch (t: Throwable) {
val elapsed = eu.friedcutlet.yokan.util.nowMillis() - startMs
AppLogger.error("[net] ${request.method} ${request.url} -> ${t::class.simpleName}: ${t.message.orEmpty()} (${elapsed}ms)")
Diagnostics.recordRequestFailure()
throw t
}
cookieJar.setFromResponse(request.url, response.setCookies)
val elapsed = eu.friedcutlet.yokan.util.nowMillis() - startMs
Diagnostics.recordResponse(response.statusCode, received)
val log: (String) -> Unit = if (response.statusCode in 200..399) AppLogger::info else AppLogger::warn
log("[net] ${request.method} ${request.url} -> ${response.statusCode} (${elapsed}ms, ${received}B streamed)")
return response
}
/** Without the skip marker and the caller's Cookie (the jar's fresh clearance replaces it); null when unmarked. */
private fun HttpRequest.skipMarked(): HttpRequest? {
if (headers.keys.none { it.equals(SKIP_CLOUDFLARE_HEADER, ignoreCase = true) }) return null
return copy(headers = headers.filterKeys {
!it.equals(SKIP_CLOUDFLARE_HEADER, ignoreCase = true) && !it.equals("Cookie", ignoreCase = true)
})
}
private suspend fun performRequest(request: HttpRequest, allowCloudflareSolve: Boolean): HttpResponse {
val settings = database.settings()
val solvable = allowCloudflareSolve && request.method.equals("GET", ignoreCase = true)
val seen = if (solvable) solveGeneration(request.url) else 0
val forceCloudflareSolve = request.headers.keys.any {
it.equals(RESOLVE_CLOUDFLARE_HEADER, ignoreCase = true)
}
val headers = enrichedHeaders(request, settings)
// Network log: method + URL on entry, status + duration on success, error class
// + message on failure. Goes through AppLogger (stdout + opt-in file).
val startMs = eu.friedcutlet.yokan.util.nowMillis()
AppLogger.info("[net] ${request.method} ${request.url}")
val uploadBytes = request.bodyBytes?.size?.toLong()
?: request.body?.encodeToByteArray()?.size?.toLong()
?: 0L
throttleBytes(uploadBytes, settings.networkUploadSpeedLimitKib)
val response = try {
delegate.request(request.copy(headers = headers))
} catch (t: Throwable) {
val elapsed = eu.friedcutlet.yokan.util.nowMillis() - startMs
val cause = t.message.orEmpty().ifBlank { t::class.simpleName.orEmpty() }
AppLogger.error("[net] ${request.method} ${request.url} -> ${t::class.simpleName}: $cause (${elapsed}ms)")
Diagnostics.recordRequestFailure()
throw t
}
val elapsed = eu.friedcutlet.yokan.util.nowMillis() - startMs
Diagnostics.recordResponse(response.statusCode, response.bodyBytes.size.toLong())
val level: (String) -> Unit = if (response.statusCode in 200..399) AppLogger::info else AppLogger::warn
level("[net] ${request.method} ${request.url} -> ${response.statusCode} (${elapsed}ms, ${response.bodyBytes.size}B)")
throttleBytes(response.bodyBytes.size.toLong(), settings.networkDownloadSpeedLimitKib)
cookieJar.setFromResponse(request.url, response.setCookies)
if (solvable && (forceCloudflareSolve || response.isCloudflareChallenge())) {
val clearance = clearCloudflare(request.url, headers, seen) ?: return response
clearance.webViewResponse?.let { return it }
val retried = performRequest(request, allowCloudflareSolve = false)
if (!retried.isCloudflareChallenge()) return retried
AppLogger.warn("[net] Cloudflare challenge NOT cleared after proxy retry for ${request.url}")
val fallback = clearCloudflare(request.url, headers, solveGeneration(request.url), useProxy = false)
return fallback?.webViewResponse ?: retried
}
return response
}
/**
* Clears the Cloudflare challenge on [url]'s host, one solve at a time per host: a caller that
* waited out another caller's attempt ([seenGeneration] is stale) reuses its outcome instead of
* solving again, so N parallel page downloads trigger one solve. Null when nothing cleared it.
*/
private suspend fun clearCloudflare(
url: String,
headers: Map<String, String>,
seenGeneration: Int,
useProxy: Boolean = true,
): CloudflareClearance? {
val gate = solveGate(url)
return gate.mutex.withLock {
if (gate.generation != seenGeneration) return@withLock gate.lastClearance
solveCloudflare(url, headers, useProxy).also { cleared ->
// Waiters retry on the cookies themselves; the WebView's response answered only this caller.
gate.lastClearance = if (cleared != null) CloudflareClearance(webViewResponse = null) else null
gate.generation += 1
}
}
}
/** The FlareSolverr-compatible proxy when configured, then the WebView. Never re-enters itself. */
private suspend fun solveCloudflare(url: String, headers: Map<String, String>, useProxy: Boolean): CloudflareClearance? {
val proxyUrl = database.settings().cloudflareBypassProxyUrl.trim()
if (useProxy && proxyUrl.isNotEmpty()) {
AppLogger.info("[net] Cloudflare challenge detected for $url; solving via proxy ($proxyUrl)")
if (solveWithCfProxy(proxyUrl, url)) {
AppLogger.info("[net] Cloudflare challenge solved via proxy for $url; retrying")
return CloudflareClearance(webViewResponse = null)
}
}
val solver = cloudflareSolver ?: return null
AppLogger.info("[net] Cloudflare challenge detected for $url; solving via WebView")
// ponytail: the platform solvers re-fetch [url] through request() to verify, which buffers the
// body; fine for pages, a video stream is held in memory once. Upgrade: a verify-less solve.
val solved = catchingNonCancellation {
solver(url, headers + (SKIP_CLOUDFLARE_HEADER to "1"))
}.getOrNull()
if (solved != null && !solved.isCloudflareChallenge()) {
AppLogger.info("[net] Cloudflare challenge cleared for $url")
return CloudflareClearance(webViewResponse = solved)
}
AppLogger.warn("[net] Cloudflare challenge NOT cleared for $url")
return null
}
private suspend fun solveGate(url: String): CloudflareGate =
solveGatesLock.withLock { solveGates.getOrPut(parseHost(url).orEmpty()) { CloudflareGate() } }
/** Read before sending, so a solve that finishes while this call is in flight is reused, not repeated. */
private suspend fun solveGeneration(url: String): Int =
solveGatesLock.withLock { solveGates[parseHost(url).orEmpty()]?.generation ?: 0 }
private suspend fun solveWithCfProxy(proxyUrl: String, targetUrl: String): Boolean {
return try {
val payload = buildJsonObject {
put("cmd", "request.get")
put("url", targetUrl)
put("maxTimeout", 60000)
// Only cookies + userAgent are read; FlareSolverr >= 3.1 and Byparr skip the page body.
put("returnOnlyCookies", true)
}.toString()
val proxyResponse = delegate.request(
HttpRequest(
url = cloudflareProxyEndpoint(proxyUrl),
method = "POST",
headers = mapOf(
"Content-Type" to "application/json",
SKIP_CLOUDFLARE_HEADER to "1",
),
body = payload,
),
)
if (proxyResponse.statusCode != 200) {
AppLogger.warn("[net] Cloudflare proxy returned HTTP ${proxyResponse.statusCode}")
return false
}
val root = CfProxyJson.parseToJsonElement(proxyResponse.body) as? JsonObject ?: return false
val status = root["status"]?.jsonPrimitive?.contentOrNull
if (status != "ok") {
val message = root["message"]?.jsonPrimitive?.contentOrNull
AppLogger.warn("[net] Cloudflare proxy status: $status ($message)")
return false
}
val solution = root["solution"]?.jsonObject ?: return false
val cookiesArray = solution["cookies"]?.jsonArray ?: JsonArray(emptyList())
val cookies = cookiesArray.mapNotNull { item ->
val obj = item as? JsonObject ?: return@mapNotNull null
val name = obj["name"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
val value = obj["value"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
val domain = obj["domain"]?.jsonPrimitive?.contentOrNull?.trimStart('.')
Triple(name, value, domain)
}
if (cookies.isEmpty()) {
AppLogger.warn("[net] Cloudflare proxy returned no cookies in solution")
return false
}
// Each cookie goes to its own domain; the target host additionally gets the cookies
// whose domain covers it, so a `.example.com` clearance still reaches `www.example.com`.
val targetHost = parseHost(targetUrl)
cookies.groupBy { it.third?.takeIf(String::isNotBlank) ?: targetHost }
.forEach { (domain, group) -> if (domain != null) cookieJar.put(domain, group.cookieHeader()) }
if (targetHost != null) {
val covering = cookies.filter { (_, _, domain) ->
!domain.isNullOrBlank() && domain != targetHost && targetHost.endsWith(".$domain")
}
if (covering.isNotEmpty()) cookieJar.put(targetHost, covering.cookieHeader())
}
val ua = solution["userAgent"]?.jsonPrimitive?.contentOrNull
if (!ua.isNullOrBlank()) {
cookieJar.rememberUserAgent(targetUrl, ua)
}
true
} catch (cancelled: CancellationException) {
throw cancelled
} catch (t: Throwable) {
AppLogger.warn("[net] Cloudflare proxy solve failed: ${t.message}")
false
}
}
private fun enrichedHeaders(request: HttpRequest, settings: eu.friedcutlet.yokan.database.DbSettings): MutableMap<String, String> {
val headers = request.headers
.filterKeys {
!it.equals(RESOLVE_CLOUDFLARE_HEADER, ignoreCase = true) &&
!it.equals(SKIP_CLOUDFLARE_HEADER, ignoreCase = true)
}
.toMutableMap()
val sessionUserAgent = cookieJar.userAgent(request.url)
if (sessionUserAgent != null) {
headers.keys.filter { it.equals("User-Agent", ignoreCase = true) }.forEach(headers::remove)
headers["User-Agent"] = sessionUserAgent
} else if (headers.keys.none { it.equals("User-Agent", ignoreCase = true) }) {
headers["User-Agent"] = settings.userAgent
}
if (headers.keys.none { it.equals("Cookie", ignoreCase = true) }) {
cookieJar.cookieHeader(request.url)?.let { headers["Cookie"] = it }
}
return headers
}
private suspend fun throttleBytes(bytes: Long, kibPerSecond: Int) {
if (bytes <= 0L || kibPerSecond <= 0) return
val bytesPerSecond = kibPerSecond.toLong().coerceAtLeast(1L) * 1024L
val delayMs = (bytes * 1_000L) / bytesPerSecond
if (delayMs > 0L) delay(delayMs)
}
}
private const val SKIP_CLOUDFLARE_HEADER = "X-Yokan-Skip-Cloudflare"
private const val RESOLVE_CLOUDFLARE_HEADER = "X-Yokan-Resolve-Cloudflare"
private val CfProxyJson = Json { ignoreUnknownKeys = true }
private val CloudflareChallengeTitle =
Regex("<title[^>]*>\\s*(?:Just a moment|Attention Required)", RegexOption.IGNORE_CASE)
/** `name=value; name2=value2` for (name, value, domain) triples. */
private fun List<Triple<String, String, String?>>.cookieHeader(): String =
joinToString("; ") { "${it.first}=${it.second}" }
internal fun isCloudflareChallengePageTitle(title: String): Boolean {
val normalized = title.trim().lowercase()
return normalized.contains("just a moment") ||
normalized.contains("attention required") ||
normalized.contains("verification required") ||
normalized.contains("security verification")
}
internal fun HttpResponse.isCloudflareChallenge(): Boolean {
val challengeStatus = statusCode == 403 || statusCode == 429 || statusCode == 503
// Challenge pages are HTML: don't decode image/video bodies to text just to scan them.
val contentType = headers.header("content-type")
if (!challengeStatus && contentType != null && !contentType.contains("html", ignoreCase = true)) return false
if (hasChallengeMarkers(body)) return true
if (!challengeStatus) return false
val server = headers.header("server").orEmpty()
return server.contains("cloudflare", ignoreCase = true) ||
server.contains("ddos-guard", ignoreCase = true)
}
/**
* Stricter than the request check: an image host's plain 403 (hotlink/auth) must not trigger a solve, so a
* stream needs Cloudflare's own `cf-mitigated: challenge`, or a Cloudflare HTML page carrying the markers.
*/
private fun HttpStreamResponse.isCloudflareChallenge(): Boolean {
if (statusCode != 403 && statusCode != 429 && statusCode != 503) return false
if (headers.header("cf-mitigated")?.equals("challenge", ignoreCase = true) == true) return true
return headers.header("server")?.contains("cloudflare", ignoreCase = true) == true &&
headers.header("content-type")?.contains("html", ignoreCase = true) == true &&
hasChallengeMarkers(body.decodeToString())
}
private fun hasChallengeMarkers(body: String): Boolean =
body.contains(CloudflareChallengeTitle) ||
body.contains("cf-browser-verification", ignoreCase = true) ||
body.contains("cf-chl-widget", ignoreCase = true)
/** A cleared challenge; [webViewResponse] is the WebView solver's verified retry, null when the caller must retry. */
private class CloudflareClearance(val webViewResponse: HttpResponse?)
/** Single-flight state for one host; [generation] counts finished solve attempts, mutated under [mutex]. */
private class CloudflareGate {
val mutex = Mutex()
@Volatile var generation = 0
var lastClearance: CloudflareClearance? = null
}
/**
* The FlareSolverr/Byparr endpoint for the configured proxy: a bare `host:port` (no path) gets `/v1`,
* a missing scheme gets `http://`; an explicit path is used as typed.
*/
internal fun cloudflareProxyEndpoint(proxyUrl: String): String {
val url = proxyUrl.trim().let { if ("://" in it) it else "http://$it" }
val path = url.substringAfter("://").substringBefore('?').substringBefore('#').substringAfter('/', "")
return if (path.isEmpty()) url.trimEnd('/') + "/v1" else url
}
Check your understanding
Send several challenged requests to one host and confirm that they share one solve generation. Explain why simply retrying recursively would permit an unbounded verification loop. [chapter-content-end]: #
Step 4: implement platform browser services
Android uses profile-aware WebView configuration and cookie/session handling; iOS uses its data-store and shared WebView integration; desktop uses JavaFX browser integration; browser builds use the capabilities actually available to a web page. Implement ProfileWebViewService before platform delegates so a stale owner cannot instantiate a new browser.
Handle page navigation, load progress, error state, verification actions, redirects, URL interception and lifecycle cleanup. InAppWebViewViewModel owns business state; the platform surface owns native view details. Preserve returned URL and OAuth attempt identity. Do not let an old login page complete the new profile's authentication.
Follow the code
The profile wrapper keeps the platform factory lazy and checks admission before opening it. That matters even if no browser has yet been created when retirement happens. Native surfaces handle view details; the ViewModel holds navigation/error/verification state. OAuth and verification results are matched to the captured owner and request identity. Implement each platform's actual storage capabilities instead of inventing independent cookie stores in a web page.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/webview/WebViewService.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/webview/ProfileWebViewService.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/InAppWebViewViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/BrowserVerificationPanel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/InAppWebViewScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/PlatformWebView.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/webview/AndroidWebViewProfiles.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/webview/AndroidWebViewSettings.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/webview/WebViewService.android.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/SharedPlatformWebView.android.ktcomposeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/webview/DesktopBrowserChallengeSession.desktop.ktcomposeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/webview/WebViewService.desktop.ktcomposeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/PlatformWebView.desktop.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/webview/IosProfileDataStore.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/webview/WebViewService.ios.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/SharedPlatformWebView.ios.ktcomposeApp/src/platformWebViewMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/PlatformWebView.platformWebView.ktcomposeApp/src/platformWebViewMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/SharedPlatformWebView.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/webview/WebViewService.wasm.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/PlatformWebView.wasm.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/webview/WebViewService.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines WebViewService, open, resolveCloudflare, evaluateScript, syncCookies, WebViewRequest, createPlatformWebViewService, createSharedPlatformWebViewService.
The source describes its contract as:
Headless JS evaluation against [url]. Returns the JSON-encoded result the WebView yielded, or an empty string if WebView is not available on the current platform. The Android actual drives
android.webkit.WebView; desktop/iOS fall through to the stub unless a host app supplies one.
package eu.friedcutlet.yokan.services.webview
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
interface WebViewService {
suspend fun open(request: WebViewRequest): Boolean
suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse?
/**
* Headless JS evaluation against [url]. Returns the JSON-encoded result the WebView yielded,
* or an empty string if WebView is not available on the current platform. The Android actual
* drives `android.webkit.WebView`; desktop/iOS fall through to the stub unless a host app
* supplies one.
*/
suspend fun evaluateScript(url: String, script: String, userAgent: String? = null): String = ""
/**
* Pull the platform WebView's current cookie set for [url] and persist it
* into the shared `CookieJar`, so the next `http.request` for that host
* carries the user's session. Called after page loads in the in-app
* WebView and after every headless `evaluateScript` round-trip.
*
* Returns the rendered `name=value; …` cookie string that was harvested
* (useful for logging / callers that want to confirm), or null if the
* platform doesn't expose a cookie store.
*/
suspend fun syncCookies(url: String): String? = null
}
data class WebViewRequest(
val url: String,
val title: String,
val headers: Map<String, String> = emptyMap(),
)
/** Default adopts the shared platform store; extras get their profile's isolated store where the platform has one. */
fun createPlatformWebViewService(
http: HttpService,
cookieJar: eu.friedcutlet.yokan.services.http.cookies.CookieJar,
files: eu.friedcutlet.yokan.services.files.LocalFileService,
scope: kotlinx.coroutines.CoroutineScope? = null,
): WebViewService = ProfileWebViewService(cookieJar, scope) {
createSharedPlatformWebViewService(http, cookieJar, files)
}
internal expect fun createSharedPlatformWebViewService(
http: HttpService,
cookieJar: eu.friedcutlet.yokan.services.http.cookies.CookieJar,
files: eu.friedcutlet.yokan.services.files.LocalFileService,
): WebViewService
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/webview/ProfileWebViewService.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
A lazy delegate alone is insufficient isolation. runAllowed checks the caller, cookie-store capability and owner before evaluating the factory, and runJoined ties the call to session retirement.
The implementation below defines ProfileWebViewService, isAllowed, runAllowed, invoke, open, resolveCloudflare, evaluateScript, syncCookies.
The source describes its contract as:
Factory stays unopened for unsupported or retired owners. Production supplies its session scope.
Cross-chapter imports used by this file: PlatformLock. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.webview
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.runJoined
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
/** Factory stays unopened for unsupported or retired owners. Production supplies its session scope. */
internal class ProfileWebViewService(
private val cookieJar: CookieJar,
ownerScope: CoroutineScope?,
factory: () -> WebViewService,
) : WebViewService {
private val lock = PlatformLock()
private val ownerJob = ownerScope?.let { requireNotNull(it.coroutineContext[Job]) { "Profile browser requires an owner job" } }
private val scope = ownerScope?.let { CoroutineScope(it.coroutineContext + SupervisorJob(ownerJob)) }
private val service = lazy(factory)
private fun isAllowed() = cookieJar.canUseBrowserStorage && (ownerJob == null || ownerJob.isActive)
private suspend fun <T> runAllowed(fallback: T, action: suspend (WebViewService) -> T): T {
currentCoroutineContext().ensureActive()
if (!isAllowed()) return fallback
suspend fun invoke(): T {
currentCoroutineContext().ensureActive()
val delegate = lock.withLock { if (isAllowed()) service.value else null } ?: return fallback
return action(delegate)
}
val owner = scope ?: return invoke()
return owner.runJoined { invoke() }
}
override suspend fun open(request: WebViewRequest): Boolean = runAllowed(false) { it.open(request) }
override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? = runAllowed(null) { it.resolveCloudflare(request) }
override suspend fun evaluateScript(url: String, script: String, userAgent: String?): String =
runAllowed("") { it.evaluateScript(url, script, userAgent) }
override suspend fun syncCookies(url: String): String? = runAllowed(null) { it.syncCookies(url) }
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/InAppWebViewViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines BrowserVerificationStatus, InAppWebViewState, InAppWebViewViewModel, setProgress, requireBrowserVerification, isCurrentVerification, solveCloudflare, syncCookies, importCookies, clearCookies and 1 further declarations.
The source describes its contract as:
Page-load / Cloudflare progress; the bar shows only strictly between 0 and 1.
Cross-chapter imports used by this file: SettingsStore, InAppNotifications, InAppMessage. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.webview
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.isCloudflareChallenge
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.notifications.InAppNotifications
import eu.friedcutlet.yokan.services.notifications.InAppMessage
import eu.friedcutlet.yokan.services.webview.WebViewRequest
import eu.friedcutlet.yokan.services.webview.WebViewService
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
internal enum class BrowserVerificationStatus { Ready, Waiting, Verified, Failed }
internal data class InAppWebViewState(
/** Page-load / Cloudflare progress; the bar shows only strictly between 0 and 1. */
val progress: Float = 0f,
/** Settings user agent, used when the route does not pin one. */
val defaultUserAgent: String,
val verificationUrl: String? = null,
val verificationStatus: BrowserVerificationStatus = BrowserVerificationStatus.Ready,
)
internal class InAppWebViewViewModel(
private val webView: WebViewService,
/** Handed to the platform WebView so it seeds and harvests the shared jar. */
val cookieJar: CookieJar,
settings: SettingsStore,
) : ViewModel() {
private val _state = MutableStateFlow(InAppWebViewState(defaultUserAgent = settings.db.value.userAgent))
val state: StateFlow<InAppWebViewState> = _state.asStateFlow()
private var verificationJob: Job? = null
private var verificationRequest: Any? = null
init {
viewModelScope.launch {
settings.db.map { it.userAgent }.distinctUntilChanged().collect { userAgent ->
_state.update { it.copy(defaultUserAgent = userAgent) }
}
}
}
fun setProgress(value: Float) {
_state.update { it.copy(progress = value.coerceIn(0f, 1f)) }
}
fun requireBrowserVerification(url: String) {
if (!cookieJar.canUseBrowserStorage) return
if (_state.value.verificationUrl == url) return
verificationRequest = null
verificationJob?.cancel()
verificationJob = null
_state.update { it.copy(
verificationUrl = url, verificationStatus = BrowserVerificationStatus.Ready, progress = 1f,
) }
}
private fun isCurrentVerification(request: Any): Boolean =
verificationRequest === request && cookieJar.canUseBrowserStorage
fun solveCloudflare(url: String, userAgent: String?) {
if (!cookieJar.canUseBrowserStorage || verificationJob?.isActive == true) return
val request = Any()
verificationRequest = request
_state.update { it.copy(
verificationUrl = url, verificationStatus = BrowserVerificationStatus.Waiting, progress = 0.05f,
) }
verificationJob = viewModelScope.launch {
try {
val result = catchingNonCancellation {
webView.resolveCloudflare(
WebViewRequest(
url = url,
title = "Cloudflare",
headers = userAgent
?.takeIf { it.isNotBlank() }
?.let { mapOf("User-Agent" to it) }
.orEmpty(),
),
)
}
// A redirected page or retired profile must never consume a previous session's result.
if (!isCurrentVerification(request)) return@launch
result.onSuccess { response ->
val verified = response != null && response.statusCode in 200..299 && !response.isCloudflareChallenge()
_state.update { it.copy(verificationStatus = if (verified) BrowserVerificationStatus.Verified else BrowserVerificationStatus.Failed, progress = 1f) }
postBrowserMessage(
title = if (verified) "Cloudflare check complete" else "Cloudflare check incomplete",
message = response?.let { "HTTP ${it.statusCode}" }
?: "No response returned.",
)
}.onFailure { error ->
_state.update { it.copy(verificationStatus = BrowserVerificationStatus.Failed, progress = 1f) }
postBrowserMessage(
title = "Cloudflare check failed",
message = error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() },
)
}
} finally {
if (isCurrentVerification(request)) {
_state.update {
if (it.verificationStatus == BrowserVerificationStatus.Waiting) {
it.copy(verificationStatus = BrowserVerificationStatus.Failed, progress = 1f)
} else it
}
verificationRequest = null
}
}
}
}
/**
* Fired after every navigation so cookies set by the loaded page (especially after a tracker /
* source login) land in the shared CookieJar — the next HTTP request through `services.http`
* for that host picks them up automatically.
*/
fun syncCookies(url: String) {
viewModelScope.launch { catchingNonCancellation { webView.syncCookies(url) } }
}
/** Returns true when the cookies were saved (the import dialog closes). */
fun importCookies(url: String, raw: String): Boolean {
if (!cookieJar.isAvailable) return false
val host = hostFromUrl(url)
val cookie = normaliseCookieInput(raw)
if (host == null || cookie == null) {
postBrowserMessage(
title = "Cookies not imported",
message = "Paste a Cookie header with at least one name=value pair.",
)
return false
}
cookieJar.put(host, cookie)
postBrowserMessage(
title = "Cookies imported",
message = "Saved cookies for $host.",
)
return true
}
fun clearCookies(url: String) {
if (!cookieJar.isAvailable) return
hostFromUrl(url)?.let { host ->
cookieJar.clear(host)
postBrowserMessage(
title = "Cookies cleared",
message = "Removed cookies for $host.",
)
}
}
private fun postBrowserMessage(title: String, message: String) {
if (cookieJar.isAvailable) {
InAppNotifications.post(InAppMessage(title, message, profileId = cookieJar.profileId))
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/BrowserVerificationPanel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines BrowserVerificationPanel.
package eu.friedcutlet.yokan.ui.screens.webview
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.browser_verification_required
import yokan.composeapp.generated.resources.browser_verification_explanation
import yokan.composeapp.generated.resources.browser_verification_waiting
import yokan.composeapp.generated.resources.browser_verification_complete
import yokan.composeapp.generated.resources.browser_verification_failed
import yokan.composeapp.generated.resources.browser_verify_action
import yokan.composeapp.generated.resources.browser_return_action
@Composable
internal fun BrowserVerificationPanel(
status: BrowserVerificationStatus,
modifier: Modifier = Modifier,
onVerify: () -> Unit,
onReturn: () -> Unit,
) {
Box(modifier = modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) {
Column(
modifier = Modifier.widthIn(max = 480.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Text(
stringResource(Res.string.browser_verification_required),
style = MaterialTheme.typography.titleLarge,
textAlign = TextAlign.Center,
)
Text(
stringResource(when (status) {
BrowserVerificationStatus.Ready -> Res.string.browser_verification_explanation
BrowserVerificationStatus.Waiting -> Res.string.browser_verification_waiting
BrowserVerificationStatus.Verified -> Res.string.browser_verification_complete
BrowserVerificationStatus.Failed -> Res.string.browser_verification_failed
}),
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center,
)
if (status == BrowserVerificationStatus.Waiting) {
CircularProgressIndicator()
} else if (status == BrowserVerificationStatus.Verified) {
Button(onClick = onReturn) { Text(stringResource(Res.string.browser_return_action)) }
} else {
Button(onClick = onVerify) { Text(stringResource(Res.string.browser_verify_action)) }
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/InAppWebViewScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines InAppWebViewRoute, InAppWebViewScreen, CookieImportDialog, hostFromUrl, normaliseCookieInput.
The source describes its contract as:
Full-screen in-app WebView. Used for refreshing Cloudflare cookies or inspecting source pages without leaving the app. The actual rendering happens in the per-platform [PlatformWebView] composable (Android WebView, iOS WKWebView, desktop fallback to system browser).
Cross-chapter imports used by this file: YokanRuntime, openSystemBrowser, Navigator, Route, YokanScaffold. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.webview
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.OpenInBrowser
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Security
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.action_refresh
import yokan.composeapp.generated.resources.ui_close
@Composable
internal fun InAppWebViewRoute(route: Route.InAppWebView, nav: Navigator) {
val model = viewModel {
InAppWebViewViewModel(YokanRuntime.services.webView, YokanRuntime.services.cookieJar, YokanRuntime.settings)
}
val state by model.state.collectAsStateWithLifecycle()
val userAgent = route.userAgent ?: state.defaultUserAgent
InAppWebViewScreen(
url = route.url,
title = route.title,
progress = state.progress,
onProgress = model::setProgress,
onSolveCloudflare = { model.solveCloudflare(state.verificationUrl ?: route.url, userAgent) },
onImportCookies = { raw -> model.importCookies(route.url, raw) },
onClearCookies = { model.clearCookies(route.url) },
onOpenBrowser = { if (model.cookieJar.canUseBrowserStorage) openSystemBrowser(route.url) },
onBack = nav::back,
) { modifier, isObscuredByOverlay ->
if (state.verificationUrl != null) {
BrowserVerificationPanel(
status = state.verificationStatus,
modifier = modifier,
onVerify = { model.solveCloudflare(state.verificationUrl ?: route.url, userAgent) },
onReturn = nav::back,
)
} else PlatformWebView(
url = route.url,
cookieJar = model.cookieJar,
modifier = modifier,
userAgent = userAgent,
isObscuredByOverlay = isObscuredByOverlay,
onNavigated = model::syncCookies,
onLoadingProgress = model::setProgress,
onVerificationRequired = model::requireBrowserVerification,
)
}
}
/**
* Full-screen in-app WebView. Used for refreshing Cloudflare cookies or
* inspecting source pages without leaving the app. The actual rendering
* happens in the per-platform [PlatformWebView] composable (Android
* WebView, iOS WKWebView, desktop fallback to system browser).
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun InAppWebViewScreen(
url: String,
title: String,
progress: Float,
onProgress: (Float) -> Unit,
onSolveCloudflare: () -> Unit,
/** Returns true when the cookies were saved. */
onImportCookies: (String) -> Boolean,
onClearCookies: () -> Unit,
onOpenBrowser: () -> Unit,
onBack: () -> Unit,
/** The platform WebView; re-mounted on refresh. */
webView: @Composable (modifier: Modifier, isObscuredByOverlay: Boolean) -> Unit,
) {
var menuOpen by remember { mutableStateOf(false) }
var importCookiesDialogOpen by remember { mutableStateOf(false) }
var refreshNonce by remember { mutableStateOf(0) }
LaunchedEffect(refreshNonce) {
onProgress(0.05f)
}
if (importCookiesDialogOpen) {
CookieImportDialog(
url = url,
onDismiss = { importCookiesDialogOpen = false },
onConfirm = { raw ->
if (onImportCookies(raw)) importCookiesDialogOpen = false
},
)
}
Scaffold(
topBar = {
Column {
TopAppBar(
title = {
Column {
Text(
text = title.ifBlank { url },
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.titleMedium,
)
if (title.isNotBlank()) {
Text(
text = url,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
},
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.ui_close))
}
},
actions = {
// goBack / goForward are not exposed by the common
// PlatformWebView surface yet — render the icons in a
// disabled state to preserve the wireframe layout.
IconButton(onClick = { /* goBack */ }, enabled = false) {
Icon(
Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(Res.string.action_back),
)
}
IconButton(onClick = { /* goForward */ }, enabled = false) {
Icon(
Icons.AutoMirrored.Filled.ArrowForward,
contentDescription = "Forward",
)
}
Box {
IconButton(onClick = { menuOpen = true }) {
Icon(Icons.Filled.MoreVert, contentDescription = "More")
}
DropdownMenu(
expanded = menuOpen,
onDismissRequest = { menuOpen = false },
) {
DropdownMenuItem(
text = { Text(stringResource(Res.string.action_refresh)) },
leadingIcon = {
Icon(
Icons.Filled.Refresh,
contentDescription = null,
)
},
onClick = {
menuOpen = false
refreshNonce++
},
)
DropdownMenuItem(
text = { Text("Share") },
leadingIcon = {
Icon(
Icons.Filled.Share,
contentDescription = null,
)
},
onClick = {
menuOpen = false
onOpenBrowser()
},
)
DropdownMenuItem(
text = { Text("Open in browser") },
leadingIcon = {
Icon(
Icons.Filled.OpenInBrowser,
contentDescription = null,
)
},
onClick = {
menuOpen = false
onOpenBrowser()
},
)
DropdownMenuItem(
text = { Text("Solve Cloudflare") },
leadingIcon = {
Icon(
Icons.Filled.Security,
contentDescription = null,
)
},
onClick = {
menuOpen = false
onSolveCloudflare()
},
)
DropdownMenuItem(
text = { Text("Import cookies") },
leadingIcon = {
Icon(
Icons.Filled.Security,
contentDescription = null,
)
},
onClick = {
menuOpen = false
importCookiesDialogOpen = true
},
)
DropdownMenuItem(
text = { Text("Clear cookies") },
leadingIcon = {
Icon(
Icons.Filled.Delete,
contentDescription = null,
)
},
onClick = {
menuOpen = false
onClearCookies()
},
)
}
}
},
)
if (progress > 0f && progress < 1f) {
LinearProgressIndicator(
progress = { progress },
modifier = Modifier.fillMaxWidth(),
)
}
}
},
) { padding ->
Box(modifier = Modifier.fillMaxSize().padding(padding)) {
// The webview body is delegated to per-platform implementations.
// Wrap in a Surface so the placeholder seen on platforms without a
// bundled webview engine matches the surrounding scaffolding.
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.surface,
) {
// Re-mount the platform view when refresh is requested so the
// underlying engine reloads the URL.
key(refreshNonce) {
webView(Modifier.fillMaxSize(), menuOpen || importCookiesDialogOpen)
}
}
}
}
}
@Composable
private fun CookieImportDialog(
url: String,
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
) {
var value by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
title = { Text("Import cookies") },
text = {
Column {
Text(
text = hostFromUrl(url)?.let { "Paste a Cookie header for $it." }
?: "Paste a Cookie header.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedTextField(
value = value,
onValueChange = { value = it },
modifier = Modifier.fillMaxWidth().padding(top = 12.dp),
label = { Text("Cookie") },
minLines = 4,
maxLines = 8,
)
}
},
confirmButton = {
TextButton(onClick = { onConfirm(value) }) {
Text("Import")
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(Res.string.action_cancel))
}
},
)
}
internal fun hostFromUrl(url: String): String? {
val withoutProtocol = url.substringAfter("://", url)
val hostPort = withoutProtocol
.substringBefore('/')
.substringBefore('?')
.substringBefore('#')
return hostPort.substringBefore(':').lowercase().takeIf { it.isNotBlank() }
}
internal fun normaliseCookieInput(raw: String): String? {
val candidate = cookieHeaderRegex.find(raw)?.groupValues?.getOrNull(1)
?: raw.trim().removePrefix("Cookie:").removePrefix("cookie:").trim()
val pairs = candidate
.trim()
.trim('"', '\'')
.split(';')
.mapNotNull { entry ->
val trimmed = entry.trim()
val eq = trimmed.indexOf('=')
if (eq <= 0) return@mapNotNull null
val name = trimmed.substring(0, eq).trim()
val value = trimmed.substring(eq + 1).trim()
if (name.lowercase() in cookieAttributeNames) return@mapNotNull null
if (name.isBlank() || value.isBlank()) return@mapNotNull null
"$name=$value"
}
return pairs.joinToString("; ").takeIf { it.isNotBlank() }
}
private val cookieHeaderRegex = Regex("""(?i)(?:^|\s|['"])cookie\s*:\s*([^'"\r\n]+)""")
private val cookieAttributeNames = setOf(
"domain",
"expires",
"httponly",
"max-age",
"path",
"samesite",
"secure",
)
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/PlatformWebView.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines PlatformWebView, RenderPlatformWebView.
The source describes its contract as:
Render a fully-fledged WebView in the composition. Used by the in-app WebView screen (Cloudflare cookie refresh, manual content inspection, etc.). [cookieJar] seeds the page's cookies and receives the ones it sets. Android/iOS use compose-webview-multiplatform. Desktop embeds JavaFX WebKit for safe browsing and delegates modern challenge flows to WebViewService's external-browser resolver.
package eu.friedcutlet.yokan.ui.screens.webview
import androidx.compose.runtime.Composable
import androidx.compose.runtime.key
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.browser_profile_unavailable
/**
* Render a fully-fledged WebView in the composition. Used by the in-app
* WebView screen (Cloudflare cookie refresh, manual content inspection, etc.).
* [cookieJar] seeds the page's cookies and receives the ones it sets.
*
* Android/iOS use compose-webview-multiplatform. Desktop embeds JavaFX WebKit
* for safe browsing and delegates modern challenge flows to WebViewService's
* external-browser resolver.
*/
@Composable
fun PlatformWebView(
url: String,
cookieJar: CookieJar,
modifier: Modifier = Modifier,
userAgent: String? = null,
isObscuredByOverlay: Boolean = false,
onNavigated: (String) -> Unit = {},
onLoadingProgress: (Float) -> Unit = {},
/** Navigations (including redirects) to URLs with this prefix are cancelled and reported via [onNavigated] instead of loaded. */
interceptUrlPrefix: String? = null,
/** A page the embedded engine cannot verify; offers the interactive browser resolver. */
onVerificationRequired: (String) -> Unit = {},
) {
if (!cookieJar.canUseBrowserStorage) {
Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(stringResource(Res.string.browser_profile_unavailable))
}
return
}
// A new session must never reuse a native page whose cookie callbacks capture an old jar.
key(cookieJar) {
RenderPlatformWebView(
url, cookieJar, modifier, userAgent, isObscuredByOverlay,
onNavigated = { if (cookieJar.canUseBrowserStorage) onNavigated(it) },
onLoadingProgress = { if (cookieJar.canUseBrowserStorage) onLoadingProgress(it) },
interceptUrlPrefix = interceptUrlPrefix,
onVerificationRequired = { if (cookieJar.canUseBrowserStorage) onVerificationRequired(it) },
)
}
}
@Composable
internal expect fun RenderPlatformWebView(
url: String,
cookieJar: CookieJar,
modifier: Modifier,
userAgent: String?,
isObscuredByOverlay: Boolean,
onNavigated: (String) -> Unit,
onLoadingProgress: (Float) -> Unit,
interceptUrlPrefix: String?,
onVerificationRequired: (String) -> Unit,
)
/** Whether [PlatformWebView] reports the pages it loads through `onNavigated` (the web build only opens a tab). */
internal expect val platformWebViewReportsNavigation: Boolean
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/webview/AndroidWebViewProfiles.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines profileCookieManager, newProfileWebView, deleteProfileWebViewStorage.
The source describes its contract as:
The cookie store backing [id]'s WebViews: Default keeps the app-wide store, extras get their WebView profile's.
Cross-chapter imports used by this file: ProfileId, AppLogger. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.webview
import android.content.Context
import android.webkit.CookieManager
import android.webkit.WebView
import androidx.webkit.ProfileStore
import androidx.webkit.WebViewCompat
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.http.cookies.platformBrowserIsolation
import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
// Extra profiles only reach these when CookieJar.canUseBrowserStorage holds, i.e. WebViewFeature.MULTI_PROFILE.
// ProfileStore must be used on the main thread.
/** The cookie store backing [id]'s WebViews: Default keeps the app-wide store, extras get their WebView profile's. */
internal fun profileCookieManager(id: ProfileId): CookieManager =
if (id == ProfileId.Default) CookieManager.getInstance()
else ProfileStore.getInstance().getOrCreateProfile(id.value).cookieManager
/** A WebView bound to [id]'s WebView profile; the profile must be set before the view is used. */
internal fun newProfileWebView(context: Context, id: ProfileId): WebView =
WebView(context).also { if (id != ProfileId.Default) WebViewCompat.setProfile(it, id.value) }
/** Drops a deleted extra profile's WebView profile. Failures (still in use) are logged: profile deletion must still finish. */
internal suspend fun deleteProfileWebViewStorage(id: ProfileId) {
if (!platformBrowserIsolation) return
withContext(Dispatchers.Main) {
// deleteProfile returns false when the profile was never created.
runCatching { ProfileStore.getInstance().deleteProfile(id.value) }
.onFailure { AppLogger.warn("[profiles] Could not delete WebView profile ${id.value}: ${it.message}") }
}
}
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/webview/AndroidWebViewSettings.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines configureAndroidWebView.
Cross-chapter imports used by this file: ProfileId. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.webview
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import eu.friedcutlet.yokan.domain.ProfileId
internal fun configureAndroidWebView(
webView: WebView,
profileId: ProfileId,
userAgent: String? = null,
) {
val cookies = profileCookieManager(profileId)
cookies.setAcceptCookie(true)
cookies.setAcceptThirdPartyCookies(webView, true)
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null)
webView.isVerticalScrollBarEnabled = true
webView.isHorizontalScrollBarEnabled = true
webView.overScrollMode = View.OVER_SCROLL_IF_CONTENT_SCROLLS
with(webView.settings) {
javaScriptEnabled = true
javaScriptCanOpenWindowsAutomatically = true
domStorageEnabled = true
loadsImagesAutomatically = true
blockNetworkImage = false
blockNetworkLoads = false
mediaPlaybackRequiresUserGesture = false
useWideViewPort = true
loadWithOverviewMode = true
cacheMode = WebSettings.LOAD_DEFAULT
mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
safeBrowsingEnabled = true
setSupportZoom(true)
builtInZoomControls = true
displayZoomControls = false
setSupportMultipleWindows(false)
if (!userAgent.isNullOrBlank()) {
userAgentString = userAgent
}
}
}
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/webview/WebViewService.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines createSharedPlatformWebViewService, AndroidWebViewService, open, resolveCloudflare, solveChallenge, finish, onPageFinished, evaluateScript, syncCookies, harvestCookies.
The source describes its contract as:
Headless WebView wrapper. Loads
url, waits foronPageFinished, then evaluatesscriptand resolves with the WebView's returned value (Android quotes string results viaJSON.stringify; callers that need a structured value can wrap their script inJSON.stringify(...)). After every headless load (and on demand via [syncCookies]) we forward the platform'sCookieManagercookies for the URL's host into the shared [CookieJar], so logging in via the in-app WebView (or any redirect chain that mutates cookies during the headless flow) survives across restarts and is automatically attached to subsequentHttpServicerequests.
Cross-chapter imports used by this file: AndroidAppContext, AppLogger, LocalFileService, openSystemBrowser. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.webview
import eu.friedcutlet.yokan.AndroidAppContext
import android.os.Handler
import android.os.Looper
import android.webkit.WebView
import android.webkit.WebViewClient
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.http.EnhancedHttpService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import kotlin.coroutines.resume
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import kotlinx.coroutines.suspendCancellableCoroutine
internal actual fun createSharedPlatformWebViewService(http: HttpService, cookieJar: CookieJar, files: LocalFileService): WebViewService =
AndroidWebViewService(http, cookieJar)
/**
* Headless WebView wrapper. Loads `url`, waits for `onPageFinished`, then evaluates `script` and
* resolves with the WebView's returned value (Android quotes string results via `JSON.stringify`;
* callers that need a structured value can wrap their script in `JSON.stringify(...)`).
*
* After every headless load (and on demand via [syncCookies]) we forward the
* platform's `CookieManager` cookies for the URL's host into the shared
* [CookieJar], so logging in via the in-app WebView (or any redirect chain
* that mutates cookies during the headless flow) survives across restarts and
* is automatically attached to subsequent `HttpService` requests.
*/
private class AndroidWebViewService(
private val http: HttpService,
private val cookieJar: CookieJar,
) : WebViewService {
override suspend fun open(request: WebViewRequest): Boolean {
if (request.url.isBlank()) return false
return openSystemBrowser(request.url)
}
/**
* Mangayomi's `m_client` policy: run a headless WebView on the challenge
* URL until Cloudflare issues `cf_clearance` (or a timeout elapses),
* harvest the cookies into the shared jar, then retry the request with
* the fresh cookies. The retry carries the caller's skip-marker header so
* [EnhancedHttpService] doesn't recurse back into this solver.
*/
override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? {
if (request.url.isBlank()) return null
val freshCookies = catchingNonCancellation { solveChallenge(request.url, request.headers) }
.getOrNull()
?.takeIf { it.isNotBlank() }
?: return null
val headers = request.headers.toMutableMap()
headers["Cookie"] = freshCookies
return http.request(HttpRequest(url = request.url, headers = headers))
}
private suspend fun solveChallenge(url: String, headers: Map<String, String>): String? {
val context = AndroidAppContext.appContext ?: return null
return withContext(Dispatchers.Main.immediate) {
if (!cookieJar.canUseBrowserStorage) return@withContext null
val handler = Handler(Looper.getMainLooper())
val webView = newProfileWebView(context, cookieJar.profileId)
var poll: Runnable? = null
try {
webView.settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
useWideViewPort = true
loadWithOverviewMode = false
headers.entries
.firstOrNull { it.key.equals("User-Agent", ignoreCase = true) }
?.value
?.takeIf { it.isNotBlank() }
?.let { userAgentString = it }
}
val cookieManager = profileCookieManager(cookieJar.profileId)
cookieManager.setAcceptCookie(true)
cookieManager.setAcceptThirdPartyCookies(webView, true)
suspendCancellableCoroutine { continuation ->
var finished = false
var pageFinished = false
fun finish(cookies: String?) {
if (finished || !continuation.isActive) return
finished = true
harvestCookies(url)
continuation.resume(cookies)
}
var waitedMs = 0L
lateinit var polling: Runnable
polling = Runnable {
if (finished || !continuation.isActive || !cookieJar.canUseBrowserStorage) return@Runnable
val cookies = runCatching { cookieManager.getCookie(url) }.getOrNull().orEmpty()
when {
"cf_clearance" in cookies && pageFinished -> finish(cookies)
waitedMs >= CHALLENGE_TIMEOUT_MS -> {
val names = cookies.split(';').map { it.substringBefore('=').trim() }.filter { it.isNotEmpty() }
AppLogger.warn("[net] Cloudflare WebView timeout for $url title='${webView.title.orEmpty()}' cookies=$names")
finish(null)
}
else -> {
waitedMs += CHALLENGE_POLL_MS
handler.postDelayed(polling, CHALLENGE_POLL_MS)
}
}
}
poll = polling
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, finishedUrl: String) {
if (finished || !continuation.isActive || !cookieJar.canUseBrowserStorage) return
pageFinished = true
harvestCookies(finishedUrl)
}
}
val requestHeaders = headers.filterKeys { !it.equals(CLOUDFLARE_SKIP_HEADER, ignoreCase = true) }
webView.loadUrl(url, requestHeaders)
handler.postDelayed(polling, CHALLENGE_POLL_MS)
}
} finally {
// Await main-thread cleanup; cancellation must not leave a queued destroy behind.
withContext(NonCancellable + Dispatchers.Main.immediate) {
poll?.let(handler::removeCallbacks)
try { webView.stopLoading() } finally { webView.destroy() }
}
}
}
}
override suspend fun evaluateScript(url: String, script: String, userAgent: String?): String {
val context = AndroidAppContext.appContext ?: return ""
return withContext(Dispatchers.Main.immediate) {
if (!cookieJar.canUseBrowserStorage) return@withContext ""
val webView = newProfileWebView(context, cookieJar.profileId)
try {
configureAndroidWebView(webView, cookieJar.profileId, userAgent)
suspendCancellableCoroutine { continuation ->
var done = false
fun finish(value: String) {
if (done || !continuation.isActive) return
done = true
continuation.resume(value)
}
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, finishedUrl: String) {
if (done || !continuation.isActive || !cookieJar.canUseBrowserStorage) return
harvestCookies(finishedUrl)
view.evaluateJavascript(script) { value -> finish(value?.trim('"') ?: "") }
}
}
webView.loadUrl(url)
}
} finally {
withContext(NonCancellable + Dispatchers.Main.immediate) {
try { webView.stopLoading() } finally { webView.destroy() }
}
}
}
}
// ProfileStore (extra profiles' cookie stores) is main-thread only.
override suspend fun syncCookies(url: String): String? = withContext(Dispatchers.Main.immediate) { harvestCookies(url) }
private fun harvestCookies(url: String): String? {
if (url.isBlank() || !cookieJar.canUseBrowserStorage) return null
val cookieManager = profileCookieManager(cookieJar.profileId)
val cookieString = runCatching { cookieManager.getCookie(url) }
.getOrNull()?.takeIf { it.isNotBlank() }
?: return null
if (!cookieJar.canUseBrowserStorage) return null
val secure = if (url.startsWith("https://", ignoreCase = true)) "; Secure" else ""
val setCookies = cookieString.split(';').mapNotNull { pair ->
pair.trim().takeIf { it.substringBefore('=').isNotBlank() }?.let { "$it; Path=/$secure" }
}
cookieJar.setFromResponse(url, setCookies)
// Persist immediately so a process death after login doesn't drop the
// session (CookieManager normally batches writes).
runCatching { cookieManager.flush() }
return cookieString
}
}
private const val CHALLENGE_POLL_MS = 500L
private const val CHALLENGE_TIMEOUT_MS = 30_000L
private const val CLOUDFLARE_SKIP_HEADER = "X-Yokan-Skip-Cloudflare"
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/SharedPlatformWebView.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines profileWebViewFactory, setProfileWebViewCookie, profileWebViewSetCookies.
Cross-chapter imports used by this file: ProfileId. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.webview
import androidx.webkit.CookieManagerCompat
import androidx.webkit.WebViewFeature
import com.multiplatform.webview.cookie.Cookie
import com.multiplatform.webview.web.NativeWebView
import com.multiplatform.webview.web.WebViewFactoryParam
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.webview.newProfileWebView
import eu.friedcutlet.yokan.services.webview.profileCookieManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
internal actual fun profileWebViewFactory(profileId: ProfileId): (WebViewFactoryParam) -> NativeWebView =
{ param -> newProfileWebView(param.context, profileId) }
// ProfileStore (extra profiles' cookie stores) is main-thread only.
internal actual suspend fun setProfileWebViewCookie(profileId: ProfileId, url: String, cookie: Cookie) =
withContext(Dispatchers.Main.immediate) { profileCookieManager(profileId).setCookie(url, cookie.toString()) }
internal actual suspend fun profileWebViewSetCookies(profileId: ProfileId, url: String): List<String> =
withContext(Dispatchers.Main.immediate) {
val manager = profileCookieManager(profileId)
if (WebViewFeature.isFeatureSupported(WebViewFeature.GET_COOKIE_INFO)) {
CookieManagerCompat.getCookieInfo(manager, url)
} else {
manager.getCookie(url).orEmpty().split(';').map { "${it.trim()}; Path=/" }
}
}
Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/webview/DesktopBrowserChallengeSession.desktop.kt
Create this path in your reconstruction project. Source set: desktopMain. Exact file download.
The implementation below defines DesktopBrowserChallengeResult, DesktopBrowserChallengeSession, solve, availableLoopbackPort, waitForDevToolsUrl, awaitPageSnapshot, pageWebSocketUrl, readDevToolsJson, readPageSnapshot, BrowserPageSnapshot and 20 further declarations.
Cross-chapter imports used by this file: AppLogger, InAppNotifications, openSystemBrowser. Keep those contracts available as you connect this step.
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<BrowserCookie> {
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<JsonObject?> = 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<BrowserCookie>? {
val result = this["result"]?.jsonObjectOrNull() ?: return null
val cookies = result["cookies"]?.jsonArrayOrNull() ?: return null
return cookies.mapNotNull { it.jsonObjectOrNull()?.toBrowserCookie() }
}
private fun browserCandidates(): List<String> {
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
}
Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/webview/WebViewService.desktop.kt
Create this path in your reconstruction project. Source set: desktopMain. Exact file download.
The implementation below defines createSharedPlatformWebViewService, DesktopWebViewService, open, resolveCloudflare, evaluateScript, syncCookies.
Cross-chapter imports used by this file: AppLogger, LocalFileService, InAppNotifications, openSystemBrowser. Keep those contracts available as you connect this step.
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.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.notifications.InAppNotifications
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import java.util.concurrent.atomic.AtomicBoolean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runInterruptible
internal actual fun createSharedPlatformWebViewService(http: HttpService, cookieJar: CookieJar, files: LocalFileService): WebViewService =
DesktopWebViewService(cookieJar, files)
private class DesktopWebViewService(
private val cookieJar: CookieJar,
private val files: LocalFileService,
) : WebViewService {
override suspend fun open(request: WebViewRequest): Boolean {
if (request.url.isBlank()) return false
return openSystemBrowser(request.url)
}
override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? {
if (request.url.isBlank()) return null
// solve() blocks for up to minutes; keep it off the caller's thread and let
// cancellation interrupt it so its finally block kills the browser process.
val result = runInterruptible(Dispatchers.IO) { DesktopBrowserChallengeSession.solve(request.url, cookieJar, files.cacheRoot) }
?: return null
cookieJar.rememberUserAgent(request.url, result.userAgent)
return result.response
}
override suspend fun evaluateScript(url: String, script: String, userAgent: String?): String {
if (url.isBlank() || script.isBlank()) return ""
if (scriptWarningShown.compareAndSet(false, true)) {
val message = "Desktop WebView scripting is unavailable in this runtime. " +
"Use the Cloudflare resolver or import cookies if the source needs a browser session."
AppLogger.warn(message)
InAppNotifications.post(
title = "WebView script unavailable",
message = message,
)
}
return ""
}
override suspend fun syncCookies(url: String): String? =
cookieJar.cookieHeader(url)
}
private val scriptWarningShown = AtomicBoolean(false)
Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/PlatformWebView.desktop.kt
Create this path in your reconstruction project. Source set: desktopMain. Exact file download.
The implementation below defines RenderPlatformWebView, JavaFxWebViewPanel, update, dispose, reportChallenge, dispatchNavigated, dispatchProgress, ensureCookieManager, harvestJavaFxCookies, seedJavaFxCookies and 4 further declarations.
The source describes its contract as:
Blanks the page (stopping its scripts and network) and drops the engine.
Cross-chapter imports used by this file: ProfileId, createPlatformLocalFileService, openSystemBrowser. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.webview
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.OpenInBrowser
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.awt.SwingPanel
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.files.createPlatformLocalFileService
import eu.friedcutlet.yokan.services.http.isCloudflareChallengePageTitle
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import java.awt.BorderLayout
import java.io.File
import java.net.CookieHandler
import java.net.CookieManager
import java.net.CookiePolicy
import java.net.HttpCookie
import java.net.URI
import javafx.application.Platform
import javafx.concurrent.Worker
import javafx.embed.swing.JFXPanel
import javafx.scene.Scene
import javafx.scene.web.WebView
import javax.swing.JPanel
import javax.swing.SwingUtilities
@Composable
internal actual fun RenderPlatformWebView(
url: String,
cookieJar: CookieJar,
modifier: Modifier,
userAgent: String?,
isObscuredByOverlay: Boolean,
onNavigated: (String) -> Unit,
onLoadingProgress: (Float) -> Unit,
// Unused: JavaFX follows redirects without exposing them, so loopback callbacks are served for real
// (mangayomiOAuthRedirectUri) and reported through onNavigated once they finish loading.
@Suppress("UNUSED_PARAMETER") interceptUrlPrefix: String?,
onVerificationRequired: (String) -> Unit,
) {
var errorMessage by remember { mutableStateOf<String?>(null) }
val message = errorMessage
if (message != null) {
DesktopWebViewStatus(
url = url,
message = message,
modifier = modifier,
onLoadingProgress = onLoadingProgress,
onOpenBrowser = { if (cookieJar.canUseBrowserStorage) openSystemBrowser(url) },
)
return
}
if (isObscuredByOverlay) {
Box(modifier = modifier.fillMaxSize())
return
}
// Owned by this SwingPanel's slot: leaving composition (screen closed or an
// overlay hiding the heavyweight panel) must shut the JavaFX engine down.
val panelRef = remember { java.util.concurrent.atomic.AtomicReference<JavaFxWebViewPanel?>(null) }
DisposableEffect(panelRef) {
onDispose { panelRef.getAndSet(null)?.dispose() }
}
SwingPanel(
modifier = modifier.fillMaxSize(),
factory = {
runCatching {
JavaFxWebViewPanel(
url = url,
cookieJar = cookieJar,
userAgent = userAgent,
onNavigated = onNavigated,
onLoadingProgress = onLoadingProgress,
onVerificationRequired = onVerificationRequired,
).also(panelRef::set)
}.getOrElse { error ->
val cause = error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }
errorMessage = "Desktop WebView failed to start: $cause"
fallbackPanel()
}
},
update = { component ->
(component as? JavaFxWebViewPanel)?.update(
url = url,
userAgent = userAgent,
onNavigated = onNavigated,
onLoadingProgress = onLoadingProgress,
onVerificationRequired = onVerificationRequired,
)
},
)
}
private class JavaFxWebViewPanel(
url: String,
private val cookieJar: CookieJar,
userAgent: String?,
onNavigated: (String) -> Unit,
onLoadingProgress: (Float) -> Unit,
onVerificationRequired: (String) -> Unit,
) : JPanel(BorderLayout()) {
private val jfxPanel = JFXPanel()
private var webView: WebView? = null
private var requestedUrl: String? = null
private var requestedUserAgent: String? = null
private var onNavigatedCallback: (String) -> Unit = onNavigated
private var onLoadingProgressCallback: (Float) -> Unit = onLoadingProgress
private var onVerificationRequiredCallback: (String) -> Unit = onVerificationRequired
@Volatile private var disposed = false
private var reportedChallengeUrl: String? = null
init {
// JavaFX's default loader is the JDK HTTP/2 client, which sends `Upgrade: h2c` on plain http; Node
// servers (mangayomi-sync-server on a LAN http:// URL) drop such requests, so every load fails with
// "Unknown error". The HTTP/1.1 loader works everywhere. Read once, before the first engine loads.
System.setProperty("com.sun.webkit.useHTTP2Loader", "false")
add(jfxPanel, BorderLayout.CENTER)
ensureCookieManager(cookieJar.profileId)
Platform.setImplicitExit(false)
Platform.runLater {
if (disposed || !cookieJar.canUseBrowserStorage) return@runLater
val view = WebView()
webView = view
val engine = view.engine
// Extras keep localStorage/IndexedDB/cache in their own app-owned root; Default keeps JavaFX's default.
if (cookieJar.profileId != ProfileId.Default) {
engine.userDataDirectory = File(createPlatformLocalFileService(cookieJar.profileId).cacheRoot, "webview")
}
engine.isJavaScriptEnabled = true
engine.titleProperty().addListener { _, _, _ -> reportChallenge() }
engine.loadWorker.progressProperty().addListener { _, _, value ->
val progress = value.toDouble().takeIf { it.isFinite() && it >= 0.0 }?.toFloat() ?: 0.05f
dispatchProgress(progress.coerceIn(0f, 1f))
}
engine.loadWorker.stateProperty().addListener { _, _, state ->
when (state) {
Worker.State.SUCCEEDED -> {
if (reportChallenge()) return@addListener
val current = engine.location.orEmpty().ifBlank { requestedUrl.orEmpty() }
harvestJavaFxCookies(current, cookieJar)
dispatchProgress(1f)
dispatchNavigated(current)
}
Worker.State.FAILED,
Worker.State.CANCELLED,
-> dispatchProgress(1f)
else -> Unit
}
}
jfxPanel.scene = Scene(view)
update(url, userAgent, onNavigated, onLoadingProgress, onVerificationRequired)
}
}
fun update(
url: String,
userAgent: String?,
onNavigated: (String) -> Unit,
onLoadingProgress: (Float) -> Unit,
onVerificationRequired: (String) -> Unit,
) {
onNavigatedCallback = onNavigated
onLoadingProgressCallback = onLoadingProgress
onVerificationRequiredCallback = onVerificationRequired
Platform.runLater {
if (disposed || !cookieJar.canUseBrowserStorage) return@runLater
val engine = webView?.engine ?: return@runLater
val nextUserAgent = userAgent?.takeIf { it.isNotBlank() }
if (nextUserAgent != requestedUserAgent) {
requestedUserAgent = nextUserAgent
if (nextUserAgent != null) {
engine.userAgent = nextUserAgent
}
}
if (url.isNotBlank() && url != requestedUrl) {
requestedUrl = url
dispatchProgress(0.05f)
seedJavaFxCookies(url, cookieJar)
engine.load(url)
}
}
}
/** Blanks the page (stopping its scripts and network) and drops the engine. */
fun dispose() {
disposed = true
Platform.runLater {
webView?.engine?.load(null)
webView = null
jfxPanel.scene = null
}
}
/** JavaFX cannot reliably run modern challenge pages; let the screen offer the browser resolver. */
private fun reportChallenge(): Boolean {
if (disposed || !cookieJar.canUseBrowserStorage) return false
val engine = webView?.engine ?: return false
val url = engine.location?.takeIf { it.startsWith("https://") || it.startsWith("http://") } ?: return false
val hasChallengeMarkup = runCatching {
engine.executeScript("Boolean(window._cf_chl_opt || document.getElementById('challenge-form') || document.getElementById('cf-browser-verification'))") == true
}.getOrDefault(false)
if (!desktopPageNeedsBrowserVerification(engine.title.orEmpty(), hasChallengeMarkup)) return false
if (reportedChallengeUrl != url) {
reportedChallengeUrl = url
SwingUtilities.invokeLater {
if (!disposed && cookieJar.canUseBrowserStorage) onVerificationRequiredCallback(url)
}
}
return true
}
private fun dispatchNavigated(url: String) {
if (url.isBlank()) return
SwingUtilities.invokeLater { if (!disposed && cookieJar.canUseBrowserStorage) onNavigatedCallback(url) }
}
private fun dispatchProgress(progress: Float) {
SwingUtilities.invokeLater { if (!disposed && cookieJar.canUseBrowserStorage) onLoadingProgressCallback(progress) }
}
}
// JavaFX reads the JVM-wide CookieHandler. Panels are built on the EDT; a different profile gets a fresh
// in-memory store so one profile's cookies never reach another (its CookieJar reseeds before each load).
private var cookieHandlerOwner: ProfileId? = null
internal fun ensureCookieManager(profileId: ProfileId) {
if (cookieHandlerOwner == profileId && CookieHandler.getDefault() != null) return
CookieHandler.setDefault(CookieManager(null, CookiePolicy.ACCEPT_ALL))
cookieHandlerOwner = profileId
}
private fun harvestJavaFxCookies(url: String, cookieJar: CookieJar) {
if (!cookieJar.canUseBrowserStorage) return
val manager = CookieHandler.getDefault() as? CookieManager ?: return
val uri = runCatching { URI(url) }.getOrNull() ?: return
val host = uri.host?.lowercase()?.takeIf { it.isNotBlank() } ?: return
val cookies = manager.cookieStore.get(uri)
val header = cookies
.filter { it.name.isNotBlank() && it.value.isNotBlank() }
.joinToString("; ") { "${it.name}=${it.value}" }
.takeIf { it.isNotBlank() }
?: return
val setCookies = cookies.mapNotNull { it.toSetCookieHeader() }
if (setCookies.isNotEmpty()) {
cookieJar.setFromResponse(url, setCookies)
} else {
cookieJar.put(host, header)
}
}
private fun seedJavaFxCookies(url: String, cookieJar: CookieJar) {
if (!cookieJar.canUseBrowserStorage) return
val manager = CookieHandler.getDefault() as? CookieManager ?: return
val uri = runCatching { URI(url) }.getOrNull() ?: return
val host = uri.host?.lowercase()?.takeIf { it.isNotBlank() } ?: return
val header = cookieJar.cookieHeader(url)
?: cookieJar.rawCookieFor(host)
?: return
val secure = uri.scheme.equals("https", ignoreCase = true)
header.split(';').forEach { entry ->
val trimmed = entry.trim()
val eq = trimmed.indexOf('=')
if (eq <= 0) return@forEach
val name = trimmed.substring(0, eq).trim()
val value = trimmed.substring(eq + 1).trim()
if (name.isBlank() || value.isBlank()) return@forEach
runCatching {
val cookie = HttpCookie(name, value).apply {
domain = host
path = "/"
this.secure = secure
}
manager.cookieStore.add(uri, cookie)
}
}
}
private fun HttpCookie.toSetCookieHeader(): String? {
val cookieName = name.trim().takeIf { it.isNotBlank() } ?: return null
val cookieValue = value.trim().takeIf { it.isNotBlank() } ?: return null
val attributes = mutableListOf("$cookieName=$cookieValue")
domain?.trim()?.takeIf { it.isNotBlank() }?.let { attributes += "Domain=$it" }
attributes += "Path=${path?.takeIf { it.isNotBlank() } ?: "/"}"
if (maxAge >= 0) attributes += "Max-Age=$maxAge"
if (secure) attributes += "Secure"
if (isHttpOnly) attributes += "HttpOnly"
return attributes.joinToString("; ")
}
@Composable
private fun DesktopWebViewStatus(
url: String,
message: String,
modifier: Modifier,
onLoadingProgress: (Float) -> Unit,
onOpenBrowser: () -> Unit,
) {
LaunchedEffect(Unit) {
onLoadingProgress(1f)
}
Box(
modifier = modifier.fillMaxSize().padding(24.dp),
contentAlignment = Alignment.Center,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Text(
text = "WebView unavailable",
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.Center,
)
Text(
text = message,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
maxLines = 4,
overflow = TextOverflow.Ellipsis,
)
Button(onClick = onOpenBrowser) {
Icon(Icons.Filled.OpenInBrowser, contentDescription = null)
Text("Open in browser")
}
}
}
}
private fun fallbackPanel(): JPanel =
JPanel(BorderLayout())
internal actual val platformWebViewReportsNavigation: Boolean = true
internal fun desktopPageNeedsBrowserVerification(title: String, hasChallengeMarkup: Boolean): Boolean =
isCloudflareChallengePageTitle(title) || hasChallengeMarkup
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/webview/IosProfileDataStore.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines profileBrowserStoreUuid, profileDataStore, deleteProfileDataStore, WKWebsiteDataStore.allCookies, NSHTTPCookie.matchesHost, NSHTTPCookie.toSetCookieHeader.
The source describes its contract as:
The UUID naming [id]'s persistent WebKit store: its 32 hex digits in 8-4-4-4-12 form.
Cross-chapter imports used by this file: ProfileId, AppLogger. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.webview
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlin.coroutines.resume
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.cValue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import platform.Foundation.NSError
import platform.Foundation.NSHTTPCookie
import platform.Foundation.NSOperatingSystemVersion
import platform.Foundation.NSProcessInfo
import platform.Foundation.NSUUID
import platform.Foundation.timeIntervalSinceNow
import platform.WebKit.WKWebsiteDataStore
@OptIn(ExperimentalForeignApi::class)
private val persistentProfileStores = NSProcessInfo.processInfo.isOperatingSystemAtLeastVersion(
cValue<NSOperatingSystemVersion> { majorVersion = 17; minorVersion = 0; patchVersion = 0 },
)
// ponytail: iOS 15/16 have no identified stores, so extras browse in a per-process ephemeral store (logins last until relaunch).
private val ephemeralStores = mutableMapOf<ProfileId, WKWebsiteDataStore>()
/** The UUID naming [id]'s persistent WebKit store: its 32 hex digits in 8-4-4-4-12 form. */
internal fun profileBrowserStoreUuid(id: ProfileId): String {
require(id != ProfileId.Default)
val hex = id.value.removePrefix("p_")
return listOf(0..7, 8..11, 12..15, 16..19, 20..31).joinToString("-") { hex.substring(it) }
}
/** [id]'s WebKit data store; Default keeps the app-wide store. Main thread only. */
internal fun profileDataStore(id: ProfileId): WKWebsiteDataStore = when {
id == ProfileId.Default -> WKWebsiteDataStore.defaultDataStore()
persistentProfileStores -> WKWebsiteDataStore.dataStoreForIdentifier(NSUUID(uUIDString = profileBrowserStoreUuid(id)))
else -> ephemeralStores.getOrPut(id) { WKWebsiteDataStore.nonPersistentDataStore() }
}
/** Removes a deleted extra profile's WebKit store. Failures are logged: profile deletion must still finish. */
internal suspend fun deleteProfileDataStore(id: ProfileId): Unit = withContext(Dispatchers.Main) {
require(id != ProfileId.Default)
ephemeralStores.remove(id)
if (!persistentProfileStores) return@withContext
val uuid = NSUUID(uUIDString = profileBrowserStoreUuid(id))
val exists = suspendCancellableCoroutine<Boolean> { cont ->
WKWebsiteDataStore.fetchAllDataStoreIdentifiers { ids -> cont.resume(ids.orEmpty().any { it == uuid }) }
}
if (!exists) return@withContext
val error = suspendCancellableCoroutine<NSError?> { cont ->
WKWebsiteDataStore.removeDataStoreForIdentifier(uuid) { error -> cont.resume(error) }
}
if (error != null) AppLogger.warn("[profiles] Could not remove WebKit store for ${id.value}: ${error.localizedDescription}")
}
/** Every cookie in this store; null when WebKit refuses the read. */
internal suspend fun WKWebsiteDataStore.allCookies(): List<NSHTTPCookie>? = withContext(Dispatchers.Main) {
suspendCancellableCoroutine<List<NSHTTPCookie>?> { cont ->
runCatching {
httpCookieStore.getAllCookies { array ->
// NSArray<NSHTTPCookie> erases to List<*> at the bridge; keep only real cookies.
if (cont.isActive) cont.resume(array.orEmpty().mapNotNull { it as? NSHTTPCookie })
}
}.onFailure { if (cont.isActive) cont.resume(null) }
}
}
/**
* RFC 6265-style host match: an exact-host cookie matches when the (lowercased) domain equals [host];
* a leading-dot (domain) cookie also matches any subdomain of it.
*/
internal fun NSHTTPCookie.matchesHost(host: String): Boolean {
val rawDomain = domain.lowercase()
val cookieDomain = rawDomain.removePrefix(".")
if (cookieDomain.isEmpty()) return false
return host == cookieDomain || (rawDomain.startsWith(".") && host.endsWith(".$cookieDomain"))
}
internal fun NSHTTPCookie.toSetCookieHeader(): String = buildList {
add("$name=$value")
if (domain.startsWith(".")) add("Domain=$domain")
add("Path=${path.ifBlank { "/" }}")
expiresDate?.timeIntervalSinceNow?.let { remaining -> add("Max-Age=${remaining.toLong().coerceAtLeast(0L)}") }
if (isSecure()) add("Secure")
if (isHTTPOnly()) add("HttpOnly")
}.joinToString("; ")
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/webview/WebViewService.ios.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines createSharedPlatformWebViewService, IosWebViewService, open, resolveCloudflare, solveChallenge, syncCookies, fetchCookies.
The source describes its contract as:
iOS [WebViewService] backed by a headless [WKWebView] and the profile's
WKWebsiteDataStore([profileDataStore]). Challenge and in-app browsing cookies are harvested into [CookieJar], then attached to the retry performed by [HttpService].
Cross-chapter imports used by this file: LocalFileService, openSystemBrowser. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.webview
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.EnhancedHttpService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.http.isCloudflareChallengePageTitle
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import platform.CoreGraphics.CGRectMake
import platform.Foundation.NSURL
import platform.Foundation.NSURLRequest
import platform.WebKit.WKWebView
import platform.WebKit.WKWebViewConfiguration
internal actual fun createSharedPlatformWebViewService(http: HttpService, cookieJar: CookieJar, files: LocalFileService): WebViewService =
IosWebViewService(http, cookieJar)
/**
* iOS [WebViewService] backed by a headless [WKWebView] and the profile's
* `WKWebsiteDataStore` ([profileDataStore]). Challenge and in-app browsing cookies are harvested
* into [CookieJar], then attached to the retry performed by [HttpService].
*/
private class IosWebViewService(
private val http: HttpService,
private val cookieJar: CookieJar,
) : WebViewService {
override suspend fun open(request: WebViewRequest): Boolean {
if (request.url.isBlank()) return false
return openSystemBrowser(request.url)
}
/**
* Mangayomi's `m_client` policy on iOS: drive a headless `WKWebView` on
* the challenge URL until `cf_clearance` lands in the shared
* `WKWebsiteDataStore` (or a timeout elapses), harvest cookies into the
* jar, then retry over HTTP. The retry keeps the caller's skip-marker
* header so [EnhancedHttpService] doesn't recurse back into the solver.
*/
override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? {
if (request.url.isBlank()) return null
val userAgent = request.headers.entries
.firstOrNull { it.key.equals("User-Agent", ignoreCase = true) }
?.value
catchingNonCancellation { solveChallenge(request.url, userAgent) }
syncCookies(request.url)
val headers = request.headers.toMutableMap()
cookieJar.cookieHeader(request.url)?.let { headers["Cookie"] = it }
return http.request(HttpRequest(url = request.url, headers = headers))
}
@OptIn(ExperimentalForeignApi::class)
private suspend fun solveChallenge(url: String, userAgent: String?): Boolean {
val nsUrl = NSURL.URLWithString(url) ?: return false
val host = nsUrl.host?.lowercase() ?: return false
val webView = withContext(Dispatchers.Main) {
val configuration = WKWebViewConfiguration().apply { websiteDataStore = profileDataStore(cookieJar.profileId) }
WKWebView(frame = CGRectMake(0.0, 0.0, 1024.0, 768.0), configuration = configuration).also { view ->
if (!userAgent.isNullOrBlank()) view.customUserAgent = userAgent
view.loadRequest(NSURLRequest.requestWithURL(nsUrl))
}
}
try {
var waited = 0L
while (waited < CHALLENGE_TIMEOUT_MS) {
delay(CHALLENGE_POLL_MS)
waited += CHALLENGE_POLL_MS
val cleared = fetchCookies().orEmpty().any { cookie ->
cookie.name == "cf_clearance" && cookie.matchesHost(host)
}
val title = withContext(Dispatchers.Main) { webView.title.orEmpty() }
if (cleared && title.isNotBlank() && !isCloudflareChallengePageTitle(title)) return true
}
return false
} finally {
// NonCancellable: a cancelled caller must still stop the page load.
withContext(NonCancellable + Dispatchers.Main) { webView.stopLoading() }
}
}
override suspend fun syncCookies(url: String): String? {
if (url.isBlank()) return null
val host = NSURL.URLWithString(url)?.host?.lowercase() ?: return null
val matching = fetchCookies().orEmpty().filter { cookie -> cookie.matchesHost(host) }
if (matching.isEmpty()) return null
cookieJar.setFromResponse(url, matching.map { it.toSetCookieHeader() })
return cookieJar.cookieHeader(url)
}
private suspend fun fetchCookies() = withContext(Dispatchers.Main) { profileDataStore(cookieJar.profileId) }.allCookies()
}
private const val CHALLENGE_POLL_MS = 500L
private const val CHALLENGE_TIMEOUT_MS = 45_000L
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/SharedPlatformWebView.ios.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines profileWebViewFactory, setProfileWebViewCookie, profileWebViewSetCookies.
Cross-chapter imports used by this file: ProfileId. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.webview
import com.multiplatform.webview.cookie.Cookie
import com.multiplatform.webview.web.NativeWebView
import com.multiplatform.webview.web.WebViewFactoryParam
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.webview.allCookies
import eu.friedcutlet.yokan.services.webview.matchesHost
import eu.friedcutlet.yokan.services.webview.profileDataStore
import eu.friedcutlet.yokan.services.webview.toSetCookieHeader
import kotlin.coroutines.resume
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.readValue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import platform.CoreGraphics.CGRectZero
import platform.Foundation.NSHTTPCookie
import platform.Foundation.NSHTTPCookieDomain
import platform.Foundation.NSHTTPCookieName
import platform.Foundation.NSHTTPCookiePath
import platform.Foundation.NSHTTPCookieValue
import platform.Foundation.NSURL
import platform.WebKit.WKWebView
@OptIn(ExperimentalForeignApi::class)
internal actual fun profileWebViewFactory(profileId: ProfileId): (WebViewFactoryParam) -> NativeWebView = { param ->
param.config.websiteDataStore = profileDataStore(profileId)
WKWebView(frame = CGRectZero.readValue(), configuration = param.config)
}
internal actual suspend fun setProfileWebViewCookie(profileId: ProfileId, url: String, cookie: Cookie) {
val nsCookie = NSHTTPCookie.cookieWithProperties(
mapOf<Any?, Any>(
NSHTTPCookieName to cookie.name,
NSHTTPCookieValue to cookie.value,
NSHTTPCookieDomain to cookie.domain.orEmpty(),
NSHTTPCookiePath to (cookie.path ?: "/"),
),
) ?: return
withContext(Dispatchers.Main) {
suspendCancellableCoroutine<Unit> { cont ->
profileDataStore(profileId).httpCookieStore.setCookie(nsCookie) { if (cont.isActive) cont.resume(Unit) }
}
}
}
internal actual suspend fun profileWebViewSetCookies(profileId: ProfileId, url: String): List<String> {
val host = NSURL.URLWithString(url)?.host?.lowercase() ?: return emptyList()
val store = withContext(Dispatchers.Main) { profileDataStore(profileId) }
return store.allCookies().orEmpty().filter { it.matchesHost(host) }.map { it.toSetCookieHeader() }
}
Write composeApp/src/platformWebViewMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/PlatformWebView.platformWebView.kt
Create this path in your reconstruction project. Source set: platformWebViewMain. Exact file download.
The implementation below defines RenderPlatformWebView.
package eu.friedcutlet.yokan.ui.screens.webview
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
@Composable
internal actual fun RenderPlatformWebView(
url: String,
cookieJar: CookieJar,
modifier: Modifier,
userAgent: String?,
isObscuredByOverlay: Boolean,
onNavigated: (String) -> Unit,
onLoadingProgress: (Float) -> Unit,
interceptUrlPrefix: String?,
onVerificationRequired: (String) -> Unit,
) {
SharedPlatformWebView(
url = url,
cookieJar = cookieJar,
modifier = modifier,
userAgent = userAgent,
onNavigated = onNavigated,
onLoadingProgress = onLoadingProgress,
interceptUrlPrefix = interceptUrlPrefix,
)
}
internal actual val platformWebViewReportsNavigation: Boolean = true
Write composeApp/src/platformWebViewMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/SharedPlatformWebView.kt
Create this path in your reconstruction project. Source set: platformWebViewMain. Exact file download.
The implementation below defines SharedPlatformWebView, onInterceptUrlRequest, profileWebViewFactory, setProfileWebViewCookie, profileWebViewSetCookies, seedSharedWebViewCookies, harvestSharedWebViewCookies, parseSharedWebViewHost.
The source describes its contract as:
Creates the rendered view inside [profileId]'s platform browser store (Default: the app-wide one).
Cross-chapter imports used by this file: ProfileId. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.webview
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.remember
import com.multiplatform.webview.request.RequestInterceptor
import com.multiplatform.webview.request.WebRequest
import com.multiplatform.webview.request.WebRequestInterceptResult
import com.multiplatform.webview.web.WebViewNavigator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import com.multiplatform.webview.cookie.Cookie
import com.multiplatform.webview.web.LoadingState
import com.multiplatform.webview.web.NativeWebView
import com.multiplatform.webview.web.WebView
import com.multiplatform.webview.web.WebViewFactoryParam
import com.multiplatform.webview.web.rememberWebViewNavigator
import com.multiplatform.webview.web.rememberWebViewState
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
@Composable
internal fun SharedPlatformWebView(
url: String,
cookieJar: CookieJar,
modifier: Modifier = Modifier,
userAgent: String? = null,
onNavigated: (String) -> Unit = {},
onLoadingProgress: (Float) -> Unit = {},
interceptUrlPrefix: String? = null,
) {
val onNavigatedState by rememberUpdatedState(onNavigated)
val onLoadingProgressState by rememberUpdatedState(onLoadingProgress)
val interceptPrefix by rememberUpdatedState(interceptUrlPrefix)
val state = rememberWebViewState(url = url) {
isJavaScriptEnabled = true
if (!userAgent.isNullOrBlank()) {
customUserAgentString = userAgent
}
}
// Consulted for main-frame navigations and server redirects (Android shouldOverrideUrlLoading, iOS navigation policy).
val interceptor = remember {
object : RequestInterceptor {
override fun onInterceptUrlRequest(request: WebRequest, navigator: WebViewNavigator): WebRequestInterceptResult {
if (!cookieJar.canUseBrowserStorage) return WebRequestInterceptResult.Reject
val prefix = interceptPrefix ?: return WebRequestInterceptResult.Allow
if (!request.url.startsWith(prefix)) return WebRequestInterceptResult.Allow
onNavigatedState(request.url)
return WebRequestInterceptResult.Reject
}
}
}
val navigator = rememberWebViewNavigator(requestInterceptor = interceptor)
LaunchedEffect(url) {
seedSharedWebViewCookies(url, cookieJar)
val current = state.lastLoadedUrl
if (!current.isNullOrBlank() && current != url) {
navigator.loadUrl(url)
}
}
LaunchedEffect(state) {
snapshotFlow { state.loadingState }
.distinctUntilChanged()
.collect { loadingState ->
val progress = when (loadingState) {
is LoadingState.Loading -> loadingState.progress
is LoadingState.Finished -> 1f
else -> 0.05f
}
onLoadingProgressState(progress.coerceIn(0f, 1f))
}
}
LaunchedEffect(state) {
snapshotFlow { state.loadingState }
.filter { it is LoadingState.Finished }
.collect {
val current = state.lastLoadedUrl?.takeIf { it.isNotBlank() } ?: url
harvestSharedWebViewCookies(current, cookieJar)
onNavigatedState(current)
}
}
WebView(
state = state,
navigator = navigator,
modifier = modifier.fillMaxSize(),
factory = remember(cookieJar.profileId) { profileWebViewFactory(cookieJar.profileId) },
)
}
/** Creates the rendered view inside [profileId]'s platform browser store (Default: the app-wide one). */
internal expect fun profileWebViewFactory(profileId: ProfileId): (WebViewFactoryParam) -> NativeWebView
/** Writes [cookie] for [url] into [profileId]'s platform cookie store. */
internal expect suspend fun setProfileWebViewCookie(profileId: ProfileId, url: String, cookie: Cookie)
/** `Set-Cookie`-style lines the platform store of [profileId] holds for [url]. */
internal expect suspend fun profileWebViewSetCookies(profileId: ProfileId, url: String): List<String>
private suspend fun seedSharedWebViewCookies(url: String, cookieJar: CookieJar) {
if (!cookieJar.canUseBrowserStorage) return
val host = parseSharedWebViewHost(url) ?: return
val header = cookieJar.cookieHeader(url)
?: cookieJar.rawCookieFor(host)
?: return
val secure = url.startsWith("https://", ignoreCase = true)
header.split(';').forEach { entry ->
if (!cookieJar.canUseBrowserStorage) return
val trimmed = entry.trim()
val eq = trimmed.indexOf('=')
if (eq <= 0) return@forEach
val name = trimmed.substring(0, eq).trim()
val value = trimmed.substring(eq + 1).trim()
if (name.isBlank() || value.isBlank()) return@forEach
catchingNonCancellation {
setProfileWebViewCookie(
cookieJar.profileId,
url,
Cookie(
name = name,
value = value,
domain = host,
path = "/",
isSessionOnly = true,
isSecure = secure,
),
)
}
}
}
private suspend fun harvestSharedWebViewCookies(url: String, cookieJar: CookieJar) {
if (!cookieJar.canUseBrowserStorage) return
val setCookies = catchingNonCancellation { profileWebViewSetCookies(cookieJar.profileId, url) }.getOrNull().orEmpty()
.filter { line ->
val pair = line.substringBefore(';')
pair.substringBefore('=').isNotBlank() && pair.substringAfter('=', "").isNotBlank()
}
if (setCookies.isNotEmpty() && cookieJar.canUseBrowserStorage) cookieJar.setFromResponse(url, setCookies)
}
private fun parseSharedWebViewHost(url: String): String? {
val withoutProtocol = url.substringAfter("://", url)
val end = withoutProtocol.indexOfFirst { it == '/' || it == '?' || it == '#' }
val hostPort = if (end == -1) withoutProtocol else withoutProtocol.substring(0, end)
if (hostPort.isBlank()) return null
return hostPort.substringBefore(':').lowercase()
}
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/webview/WebViewService.wasm.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The implementation below defines createSharedPlatformWebViewService, WasmWebViewService, open, resolveCloudflare.
Cross-chapter imports used by this file: LocalFileService. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.webview
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
internal actual fun createSharedPlatformWebViewService(http: HttpService, cookieJar: CookieJar, files: LocalFileService): WebViewService =
WasmWebViewService
private object WasmWebViewService : WebViewService {
override suspend fun open(request: WebViewRequest): Boolean = false
override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? = null
}
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/PlatformWebView.wasm.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The implementation below defines RenderPlatformWebView.
The source describes its contract as:
Browsers cannot nest a controllable cross-origin browser view; the in-app WebView screen offers to open the page in a new tab instead.
Cross-chapter imports used by this file: openSystemBrowser. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.webview
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.system.openSystemBrowser
/**
* Browsers cannot nest a controllable cross-origin browser view; the in-app
* WebView screen offers to open the page in a new tab instead.
*/
@Composable
internal actual fun RenderPlatformWebView(
url: String,
cookieJar: CookieJar,
modifier: Modifier,
userAgent: String?,
isObscuredByOverlay: Boolean,
onNavigated: (String) -> Unit,
onLoadingProgress: (Float) -> Unit,
interceptUrlPrefix: String?,
onVerificationRequired: (String) -> Unit,
) {
LaunchedEffect(url, cookieJar) {
if (!cookieJar.canUseBrowserStorage) return@LaunchedEffect
onLoadingProgress(1f)
openSystemBrowser(url)
}
Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text("The in-app WebView is unavailable on the web; the page opened in a new browser tab.")
}
}
internal actual val platformWebViewReportsNavigation: Boolean = false
Check your understanding
Retire the owner before the first browser request. Verify that even factory creation is prevented, then test cancellation while a visible verification is pending. [chapter-content-end]: #
Step 5: test isolation and adverse responses
Use EnhancedHttpCloudflareTest, stream variants, cookie parser/jar tests, Ktor lifecycle tests, platform isolation tests and browser verification tests. Cover cancellation during streaming/solver work, engine closure, no-cookie extra browser transport, malformed responses and profile retirement. Explicit browser restrictions include no independent native cookie store; extra-profile transport can reject Cookie headers/WebSockets.
Follow the code
The HTTP tests use scripted responses to distinguish protocol behavior from live website availability. Recreate the ordinary-response tests before challenge tests, then add cancellation at the chunk callback, solver and engine boundaries. Cookie domain/path/expiry cases and extra-profile browser restrictions test different invariants and should stay separate.
This step connects or verifies implementations already listed in this chapter or its prerequisites. Follow the named call paths above while reading the complete tests at the end.
Check your understanding
For each failing fixture, identify whether the transport, cookie layer, challenge layer or browser delegate is responsible. [chapter-content-end]: #
Recreate the tests and verify the chapter
Run the shared HTTP/cookie suites through the desktop test target, including enhanced request and streaming challenge cases. Run platform browser-isolation and engine lifecycle tests where their source sets require it. Use controlled HTTP fixtures for deterministic behavior; live source verification is an additional manual check.
These are source tests to reproduce and run in your reconstruction. Their inclusion here is not a claim that application/native/device tests were executed while writing the guide.
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/http/EnhancedHttpCloudflareTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines EnhancedHttpCloudflareTest, service, solvesChallengeThroughWebViewAndReturnsClearedResponse, solverRetryReplacesStaleCookieHeaderWithFreshClearance, skipMarkerBypassesSolverAndIsStrippedFromWire, nonGetAndNonChallengeResponsesAreUntouched, solvesManagedChallengeDocumentReturnedWithHttp200, binaryBodiesAreNotScannedForChallengeMarkers, ignoresChallengePlatformScriptOnNormalPage.
Read the setup, action and assertions in these cases before implementing their production paths:
solvesChallengeThroughWebViewAndReturnsClearedResponsesolverRetryReplacesStaleCookieHeaderWithFreshClearanceskipMarkerBypassesSolverAndIsStrippedFromWirenonGetAndNonChallengeResponsesAreUntouchedsolvesManagedChallengeDocumentReturnedWithHttp200binaryBodiesAreNotScannedForChallengeMarkersignoresChallengePlatformScriptOnNormalPage
Cross-chapter imports used by this file: InMemoryYokanDatabase, seedDatabaseSnapshot. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
class EnhancedHttpCloudflareTest {
private val challenge = HttpResponse(
statusCode = 403,
body = "<html>Just a moment...</html>",
headers = mapOf("Server" to "cloudflare"),
)
private val ok = HttpResponse(statusCode = 200, body = "content")
private fun service(delegate: HttpService): EnhancedHttpService {
val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
return EnhancedHttpService(delegate, database, CookieJar(database))
}
@Test
fun solvesChallengeThroughWebViewAndReturnsClearedResponse() = runTest {
val http = service(HttpService { challenge })
var solverHeaders: Map<String, String> = emptyMap()
http.cloudflareSolver = { _, headers ->
solverHeaders = headers
ok
}
val response = http.request(HttpRequest(url = "https://example.org/manga"))
assertEquals(200, response.statusCode)
assertEquals("content", response.body)
// Solver receives the skip marker so its own retry can't recurse.
assertTrue(solverHeaders.keys.any { it.equals("X-Yokan-Skip-Cloudflare", ignoreCase = true) })
}
@Test
fun solverRetryReplacesStaleCookieHeaderWithFreshClearance() = runTest {
val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
val cookieJar = CookieJar(database)
cookieJar.put("example.org", "cf_clearance=STALE")
val wireCookies = mutableListOf<String>()
val wireUserAgents = mutableListOf<String>()
lateinit var http: EnhancedHttpService
val delegate = HttpService { request ->
val cookie = request.headers.entries
.firstOrNull { it.key.equals("Cookie", ignoreCase = true) }
?.value
.orEmpty()
wireCookies += cookie
wireUserAgents += request.headers.entries
.firstOrNull { it.key.equals("User-Agent", ignoreCase = true) }
?.value
.orEmpty()
if ("cf_clearance=FRESH" in cookie) ok else challenge
}
http = EnhancedHttpService(delegate, database, cookieJar)
http.cloudflareSolver = { url, headers ->
cookieJar.put("example.org", "cf_clearance=FRESH")
cookieJar.rememberUserAgent(url, "NativeBrowser/150")
http.request(HttpRequest(url = url, headers = headers))
}
val response = http.request(HttpRequest(url = "https://example.org/manga"))
assertEquals(200, response.statusCode)
assertEquals(listOf("cf_clearance=STALE", "cf_clearance=FRESH"), wireCookies)
assertEquals("NativeBrowser/150", wireUserAgents.last())
}
@Test
fun skipMarkerBypassesSolverAndIsStrippedFromWire() = runTest {
val wire = RecordingHttpService { challenge }
val http = service(wire)
var solverCalled = false
http.cloudflareSolver = { _, _ ->
solverCalled = true
ok
}
val response = http.request(
HttpRequest(
url = "https://example.org/manga",
headers = mapOf("X-Yokan-Skip-Cloudflare" to "1"),
),
)
assertEquals(403, response.statusCode)
assertFalse(solverCalled)
assertTrue(wire.requests.single().headers.keys.none { it.equals("X-Yokan-Skip-Cloudflare", ignoreCase = true) })
}
@Test
fun nonGetAndNonChallengeResponsesAreUntouched() = runTest {
val http = service(
HttpService { request ->
if (request.method == "POST") challenge else HttpResponse(statusCode = 404, body = "missing")
},
)
var solverCalled = false
http.cloudflareSolver = { _, _ ->
solverCalled = true
ok
}
assertEquals(403, http.request(HttpRequest(url = "https://example.org", method = "POST")).statusCode)
assertEquals(404, http.request(HttpRequest(url = "https://example.org")).statusCode)
assertFalse(solverCalled)
}
@Test
fun solvesManagedChallengeDocumentReturnedWithHttp200() = runTest {
val http = service(HttpService { HttpResponse(statusCode = 200, body = "<html><title>Just a moment...</title></html>") })
var solverCalled = false
http.cloudflareSolver = { _, _ ->
solverCalled = true
ok
}
val response = http.request(HttpRequest(url = "https://example.org/manga"))
assertEquals("content", response.body)
assertTrue(solverCalled)
}
@Test
fun binaryBodiesAreNotScannedForChallengeMarkers() = runTest {
val image = HttpResponse(
statusCode = 200,
headers = mapOf("Content-Type" to "image/jpeg"),
bodyBytes = "\u00FF\u00D8 cf-chl-widget".encodeToByteArray(),
)
val http = service(HttpService { image })
var solverCalled = false
http.cloudflareSolver = { _, _ ->
solverCalled = true
ok
}
assertEquals(200, http.request(HttpRequest(url = "https://example.org/page.jpg")).statusCode)
assertFalse(solverCalled)
}
@Test
fun ignoresChallengePlatformScriptOnNormalPage() = runTest {
val normal = HttpResponse(
statusCode = 200,
body = "<html><script src=\"/challenge-platform/runtime.js\"></script><main>content</main></html>",
)
val http = service(HttpService { normal })
var solverCalled = false
http.cloudflareSolver = { _, _ ->
solverCalled = true
ok
}
val response = http.request(HttpRequest(url = "https://example.org/manga"))
assertEquals(normal, response)
assertFalse(solverCalled)
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/http/EnhancedHttpStreamCloudflareTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines EnhancedHttpStreamCloudflareTest, ProtectedHost, request, stream, service, challenge, streamChallengeIsSolvedThenRetriedOnceWithFreshCookieAndUserAgent, plainForbiddenFromCloudflareIsNotSolved, parallelChallengedStreamsShareOneSolve, explicitProxyPathIsKept.
The source describes its contract as:
Serves [image] only with the proxy's clearance + UA; otherwise a Cloudflare challenge, per the stream contract.
Read the setup, action and assertions in these cases before implementing their production paths:
streamChallengeIsSolvedThenRetriedOnceWithFreshCookieAndUserAgentplainForbiddenFromCloudflareIsNotSolvedparallelChallengedStreamsShareOneSolveexplicitProxyPathIsKept
Cross-chapter imports used by this file: InMemoryYokanDatabase, seedDatabaseSnapshot. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
class EnhancedHttpStreamCloudflareTest {
private val image = byteArrayOf(1, 2, 3)
private val challengePage = "<html><head><title>Just a moment...</title></head></html>".encodeToByteArray()
/** Serves [image] only with the proxy's clearance + UA; otherwise a Cloudflare challenge, per the stream contract. */
private class ProtectedHost(
private val image: ByteArray,
private val challenge: HttpStreamResponse,
private val onChallenged: () -> Unit = {},
private val beforeSolve: suspend () -> Unit = {},
) : HttpService {
val proxyRequests = mutableListOf<HttpRequest>()
val streams = mutableListOf<HttpRequest>()
override suspend fun request(request: HttpRequest): HttpResponse {
proxyRequests += request
beforeSolve()
return HttpResponse(
statusCode = 200,
body = """{"status":"ok","solution":{"userAgent":"Solver/1",
"cookies":[{"name":"cf_clearance","value":"CLEAR","domain":".example.org"}]}}""",
)
}
override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
streams += request
val cleared = "cf_clearance=CLEAR" in request.headers["Cookie"].orEmpty() &&
request.headers["User-Agent"] == "Solver/1"
if (!cleared) {
onChallenged()
return challenge
}
onChunk(image)
return HttpStreamResponse(statusCode = 200)
}
}
private suspend fun service(delegate: HttpService, proxyUrl: String = "http://127.0.0.1:8191"): EnhancedHttpService {
val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
database.updateSettings(database.settings().copy(cloudflareBypassProxyUrl = proxyUrl))
return EnhancedHttpService(delegate, database, CookieJar(database))
}
private fun challenge(headers: Map<String, String>) = HttpStreamResponse(statusCode = 403, headers = headers, body = challengePage)
@Test
fun streamChallengeIsSolvedThenRetriedOnceWithFreshCookieAndUserAgent() = runTest {
val host = ProtectedHost(image, challenge(mapOf("cf-mitigated" to "challenge")))
val http = service(host)
val received = mutableListOf<Byte>()
val response = http.stream(HttpRequest(url = "https://img.example.org/p1.jpg")) { received += it.toList() }
assertEquals(200, response.statusCode)
assertContentEquals(image, received.toByteArray(), "challenge page bytes must never reach onChunk")
assertEquals(2, host.streams.size)
val proxy = host.proxyRequests.single()
assertEquals("http://127.0.0.1:8191/v1", proxy.url, "bare host:port posts to the FlareSolverr endpoint")
assertEquals(true, Json.parseToJsonElement(proxy.body.orEmpty()).jsonObject["returnOnlyCookies"]?.jsonPrimitive?.boolean)
}
@Test
fun plainForbiddenFromCloudflareIsNotSolved() = runTest {
val hotlinkBlock = challenge(mapOf("Server" to "cloudflare", "Content-Type" to "image/jpeg"))
val host = ProtectedHost(image, hotlinkBlock)
val http = service(host)
var webViewCalled = false
http.cloudflareSolver = { _, _ ->
webViewCalled = true
null
}
var chunks = 0
val response = http.stream(HttpRequest(url = "https://img.example.org/p1.jpg")) { chunks++ }
assertEquals(403, response.statusCode)
assertEquals(1, host.streams.size)
assertEquals(0, host.proxyRequests.size)
assertFalse(webViewCalled)
assertEquals(0, chunks)
}
@Test
fun parallelChallengedStreamsShareOneSolve() = runTest {
val pages = 5
var challenged = 0
val allChallenged = CompletableDeferred<Unit>()
val host = ProtectedHost(
image,
challenge(mapOf("Server" to "cloudflare", "Content-Type" to "text/html")),
onChallenged = { if (++challenged == pages) allChallenged.complete(Unit) },
// Hold the first solve until every page has hit the challenge and queued behind it.
beforeSolve = { allChallenged.await() },
)
val http = service(host)
val statuses = (1..pages).map { page ->
async { http.stream(HttpRequest(url = "https://img.example.org/p$page.jpg")) {}.statusCode }
}.awaitAll()
assertEquals(List(pages) { 200 }, statuses)
assertEquals(1, host.proxyRequests.size)
assertEquals(pages * 2, host.streams.size)
}
@Test
fun explicitProxyPathIsKept() {
assertEquals("http://solver:8191/v1", cloudflareProxyEndpoint("solver:8191/"))
assertEquals("https://solver.lan/api/v1", cloudflareProxyEndpoint("https://solver.lan/api/v1"))
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/http/KtorHttpServiceLifecycleTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines KtorHttpServiceLifecycleTest, close, response.
Read the setup, action and assertions in these cases before implementing their production paths:
standaloneTransportRetainsResponseMappingAndClosesOnlyOnceretirementJoinsPendingRequestFinalizersBeforeNativeReleasestreamRetirementJoinsBodyProducerAfterEngineExecuteReturnsexpiredOwnerRejectsRequestsAndStreamsBeforeUrlValidationOrDispatchawaitedCloseStillJoinsFinalizersAfterLegacyImmediateClosefailedNativeReleaseCanBeRetriedWithoutAdmittingNewCallsplatformFactoryRejectsExpiredOwnerBeforeDefaultAllocation
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, io.ktor.utils.io.InternalAPI::class)
package eu.friedcutlet.yokan.services.http
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.callContext
import io.ktor.client.request.HttpResponseData
import io.ktor.http.Headers
import io.ktor.http.HttpProtocolVersion
import io.ktor.http.HttpStatusCode
import io.ktor.util.date.GMTDate
import io.ktor.utils.io.ByteChannel
import io.ktor.utils.io.ByteReadChannel
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class KtorHttpServiceLifecycleTest {
@Test fun standaloneTransportRetainsResponseMappingAndClosesOnlyOnce() = runTest {
val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {
response(ByteReadChannel(byteArrayOf(0, -1, 1)), Headers.build {
append("Set-Cookie", "a=1"); append("Set-Cookie", "b=2")
})
}
val service = KtorHttpService(engine)
val result = service.request(HttpRequest("https://source.test/page", method = "POST", body = "payload"))
assertTrue(result.bodyBytes.contentEquals(byteArrayOf(0, -1, 1)))
assertEquals(listOf("a=1", "b=2"), result.setCookies)
assertEquals("POST", engine.requests.receive().method.value)
service.closeAndJoin(); service.closeAndJoin(); service.close()
assertEquals(1, engine.closeCalls)
assertTrue(engine.coroutineContext[Job]?.isCompleted == true)
}
@Test fun retirementJoinsPendingRequestFinalizersBeforeNativeRelease() = runTest {
val parent = SupervisorJob()
val release = CompletableDeferred<Unit>(); var finalized = false
val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {
try { awaitCancellation() }
finally { withContext(NonCancellable) { release.await(); finalized = true } }
}
val service = KtorHttpService(engine, parent)
val caller = launch { service.request(HttpRequest("https://source.test/page")) }
engine.requests.receive()
val retiring = launch { service.closeAndJoin() }
testScheduler.runCurrent()
assertFalse(retiring.isCompleted); assertFalse(finalized); assertEquals(0, engine.closeCalls)
release.complete(Unit); retiring.join(); caller.join()
assertTrue(finalized); assertEquals(1, engine.closeCalls); assertTrue(parent.isActive)
assertTrue(engine.coroutineContext[Job]?.isCompleted == true)
parent.cancelAndJoin()
}
@Test fun streamRetirementJoinsBodyProducerAfterEngineExecuteReturns() = runTest {
val producerEntered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
var finalized = false
val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {
val context = callContext()
CoroutineScope(context).launch {
try { producerEntered.complete(Unit); awaitCancellation() }
finally { withContext(NonCancellable) { release.await(); finalized = true } }
}
response(ByteChannel(), context = context)
}
val service = KtorHttpService(engine)
val caller = launch { service.stream(HttpRequest("https://source.test/page")) { error("No body was sent") } }
producerEntered.await(); engine.requests.receive()
caller.cancel(); testScheduler.runCurrent()
val retiring = launch { service.closeAndJoin() }
testScheduler.runCurrent()
assertFalse(retiring.isCompleted); assertEquals(0, engine.closeCalls)
release.complete(Unit); retiring.join(); caller.join()
assertTrue(finalized); assertEquals(1, engine.closeCalls)
}
@Test fun expiredOwnerRejectsRequestsAndStreamsBeforeUrlValidationOrDispatch() = runTest {
val parent = SupervisorJob()
val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response(ByteReadChannel("ok")) }
val service = KtorHttpService(engine, parent)
parent.cancelAndJoin()
for (url in listOf("https://source.test/page", "http://[")) {
assertFailsWith<CancellationException> { service.request(HttpRequest(url)) }
assertFailsWith<CancellationException> { service.stream(HttpRequest(url)) {} }
}
assertTrue(engine.requests.tryReceive().isFailure)
service.closeAndJoin()
}
@Test fun awaitedCloseStillJoinsFinalizersAfterLegacyImmediateClose() = runTest {
val release = CompletableDeferred<Unit>()
val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {
try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }
}
val service = KtorHttpService(engine)
val caller = launch { service.request(HttpRequest("https://source.test/page")) }
engine.requests.receive(); service.close()
val retiring = launch { service.closeAndJoin() }
testScheduler.runCurrent(); assertFalse(retiring.isCompleted)
assertFailsWith<CancellationException> { service.request(HttpRequest("http://[")) }
release.complete(Unit); retiring.join(); caller.join()
assertEquals(1, engine.closeCalls)
}
@Test fun failedNativeReleaseCanBeRetriedWithoutAdmittingNewCalls() = runTest {
val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response(ByteReadChannel("ok")) }
var attempts = 0
val failingEngine = object : HttpClientEngine by engine {
override fun close() { attempts++; check(attempts > 1) { "Native release failed" }; engine.close() }
}
val service = KtorHttpService(failingEngine)
assertFailsWith<IllegalStateException> { service.closeAndJoin() }
assertFailsWith<CancellationException> { service.request(HttpRequest("https://source.test/page")) }
service.closeAndJoin(); service.closeAndJoin()
assertEquals(2, attempts); assertEquals(1, engine.closeCalls)
assertTrue(engine.requests.tryReceive().isFailure)
}
@Test fun platformFactoryRejectsExpiredOwnerBeforeDefaultAllocation() = runTest {
val parent = SupervisorJob(); parent.cancelAndJoin()
assertFailsWith<CancellationException> {
createPlatformHttpService(ownerScope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
}
}
private suspend fun response(body: ByteReadChannel, headers: Headers = Headers.Empty,
context: kotlin.coroutines.CoroutineContext? = null) =
HttpResponseData(HttpStatusCode.OK, GMTDate(), headers, HttpProtocolVersion.HTTP_1_1, body, context ?: callContext())
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/http/ProfileHttpServiceTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ProfileHttpServiceTest, FakeHttp, request, stream.
Read the setup, action and assertions in these cases before implementing their production paths:
preservesRequestAndResponseIncludingCredentialsAndBinaryBodiesstreamsChunksInOrderAndPreservesBufferedErrorResponsesretiredOwnerRejectsBothEntryPointsBeforeDelegateAccessretirementJoinsExternalRequestFinalizersBeforeReleasecallerExpiryJoinsStreamFinalizersAndPreservesSiblingWorkstreamCleanupCannotDeliverLateBytesEvenFromNonCancellableContextretainedStreamCallbackCannotWriteAfterSuccessfulCompletionresponseHeadersCannotWriteAfterCancellationOrCompletionalreadyExpiredCallerCannotDispatchWithImmediateOwnerDispatcherqueuedRequestCannotReachTransportAfterOwnerRetirestransportOrChunkFailureDoesNotRetireAnOrdinaryParentOrSiblingsretiringOneOwnerDoesNotRetargetOrCancelAnotherOwnersTransportextraPlatformEnginesHaveIndependentLifetimes
Cross-chapter imports used by this file: ProfileId. Keep those contracts available as you connect this step.
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package eu.friedcutlet.yokan.services.http
import eu.friedcutlet.yokan.domain.ProfileId
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertSame
import kotlin.test.assertTrue
class ProfileHttpServiceTest {
@Test fun preservesRequestAndResponseIncludingCredentialsAndBinaryBodies() = runTest {
val parent = SupervisorJob()
val request = HttpRequest("https://source.test/upload", "POST", mapOf("Authorization" to "Bearer owner"), bodyBytes = byteArrayOf(0, -1))
val response = HttpResponse(401, headers = mapOf("WWW-Authenticate" to "Bearer"), bodyBytes = byteArrayOf(1, -1), setCookies = listOf("id=owner"))
val delegate = FakeHttp().apply { requestAction = { assertSame(request, it); response } }
val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
assertEquals(A, service.profileId); assertSame(response, service.request(request))
parent.cancelAndJoin()
}
@Test fun streamsChunksInOrderAndPreservesBufferedErrorResponses() = runTest {
val parent = SupervisorJob()
val delegate = FakeHttp().apply { streamAction = { request, chunk ->
assertSame(Request, request); chunk(byteArrayOf(1, 2)); chunk(byteArrayOf(-1))
HttpStreamResponse(200, setCookies = listOf("id=owner"))
} }
val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
val received = mutableListOf<Byte>()
assertEquals(listOf("id=owner"), service.stream(Request) { received.addAll(it.toList()) }.setCookies)
assertContentEquals(byteArrayOf(1, 2, -1), received.toByteArray())
val error = HttpStreamResponse(403, body = "challenge".encodeToByteArray())
delegate.streamAction = { _, _ -> error }
assertSame(error, service.stream(Request) { error("Error body streamed") })
parent.cancelAndJoin()
}
@Test fun retiredOwnerRejectsBothEntryPointsBeforeDelegateAccess() = runTest {
val parent = SupervisorJob()
val delegate = FakeHttp()
val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
parent.cancelAndJoin()
assertFailsWith<CancellationException> { service.request(Request) }
assertFailsWith<CancellationException> { service.stream(Request) { error("Expired chunk") } }
assertEquals(0, delegate.calls)
}
@Test fun retirementJoinsExternalRequestFinalizersBeforeRelease() = runTest {
val parent = SupervisorJob()
val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
var finalized = false
val delegate = FakeHttp().apply { requestAction = {
try { entered.complete(Unit); awaitCancellation() }
finally { withContext(NonCancellable) { release.await(); finalized = true } }
} }
val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
val caller = launch { service.request(Request) }
entered.await()
val retiring = launch { parent.cancelAndJoin() }
testScheduler.runCurrent(); assertFalse(retiring.isCompleted); assertFalse(caller.isCompleted)
release.complete(Unit); retiring.join(); caller.join(); assertTrue(finalized)
}
@Test fun callerExpiryJoinsStreamFinalizersAndPreservesSiblingWork() = runTest {
val parent = SupervisorJob()
val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
val delegate = FakeHttp().apply { streamAction = { _, _ ->
try { entered.complete(Unit); awaitCancellation() }
finally { withContext(NonCancellable) { release.await() } }
} }
val service = ProfileHttpService(A, delegate, scope)
val sibling = scope.launch { awaitCancellation() }
val caller = launch { service.stream(Request) {} }
entered.await(); caller.cancel(); testScheduler.runCurrent()
assertFalse(caller.isCompleted); assertTrue(parent.isActive); assertTrue(sibling.isActive)
release.complete(Unit); caller.join()
assertEquals(200, service.request(Request).statusCode)
parent.cancelAndJoin()
}
@Test fun streamCleanupCannotDeliverLateBytesEvenFromNonCancellableContext() = runTest {
val parent = SupervisorJob()
val entered = CompletableDeferred<Unit>()
var lateRejected = false; var delivered = 0
val delegate = FakeHttp().apply { streamAction = { _, chunk ->
try { chunk(byteArrayOf(1)); entered.complete(Unit); awaitCancellation() }
finally { withContext(NonCancellable) {
assertFailsWith<CancellationException> { chunk(byteArrayOf(2)) }; lateRejected = true
} }
} }
val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
val caller = launch { service.stream(Request) { delivered++ } }
entered.await(); caller.cancelAndJoin()
assertEquals(1, delivered); assertTrue(lateRejected); assertTrue(parent.isActive)
parent.cancelAndJoin()
}
@Test fun retainedStreamCallbackCannotWriteAfterSuccessfulCompletion() = runTest {
val parent = SupervisorJob()
var retained: (suspend (ByteArray) -> Unit)? = null
val delegate = FakeHttp().apply { streamAction = { _, chunk -> retained = chunk; HttpStreamResponse(200) } }
val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
service.stream(Request) { error("Detached callback wrote bytes") }
assertFailsWith<CancellationException> { requireNotNull(retained).invoke(byteArrayOf(1)) }
parent.cancelAndJoin()
}
@Test fun responseHeadersCannotWriteAfterCancellationOrCompletion() = runTest {
val parent = SupervisorJob()
val entered = CompletableDeferred<Unit>()
var retained: (suspend (HttpStreamResponse) -> Unit)? = null
var delivered = 0
val response = HttpStreamResponse(200)
val delegate = FakeHttp().apply { streamAction = { request, _ ->
retained = request.onStreamResponse
try {
requireNotNull(retained).invoke(response)
entered.complete(Unit)
awaitCancellation()
} finally {
withContext(NonCancellable) {
assertFailsWith<CancellationException> { requireNotNull(retained).invoke(response) }
}
}
} }
val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
val request = Request.copy(onStreamResponse = { delivered++ })
val caller = launch { service.stream(request) {} }
entered.await()
caller.cancelAndJoin()
assertEquals(1, delivered)
delegate.streamAction = { current, _ -> retained = current.onStreamResponse; response }
service.stream(request) {}
assertFailsWith<CancellationException> { requireNotNull(retained).invoke(response) }
assertEquals(1, delivered)
parent.cancelAndJoin()
}
@Test fun alreadyExpiredCallerCannotDispatchWithImmediateOwnerDispatcher() = runTest {
val parent = SupervisorJob(); val delegate = FakeHttp()
val service = ProfileHttpService(A, delegate, CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler)))
val caller = launch {
currentCoroutineContext().cancel()
assertFailsWith<CancellationException> { service.request(Request) }
assertFailsWith<CancellationException> { service.stream(Request) {} }
}
caller.join(); assertEquals(0, delegate.calls); assertTrue(parent.isActive)
parent.cancelAndJoin()
}
@Test fun queuedRequestCannotReachTransportAfterOwnerRetires() = runTest {
val parent = SupervisorJob(); val delegate = FakeHttp()
val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
val caller = launch(UnconfinedTestDispatcher(testScheduler)) { service.request(Request) }
parent.cancel(); testScheduler.runCurrent(); caller.join(); parent.join()
assertEquals(0, delegate.calls)
}
@Test fun transportOrChunkFailureDoesNotRetireAnOrdinaryParentOrSiblings() = runTest {
val parent = Job(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
val delegate = FakeHttp().apply { requestAction = { error("Transport failed") } }
val service = ProfileHttpService(A, delegate, scope)
val sibling = scope.launch { awaitCancellation() }
assertFailsWith<IllegalStateException> { service.request(Request) }
delegate.streamAction = { _, chunk -> chunk(byteArrayOf(1)); HttpStreamResponse(200) }
assertFailsWith<IllegalArgumentException> { service.stream(Request) { throw IllegalArgumentException("Disk failed") } }
assertTrue(parent.isActive); assertTrue(sibling.isActive)
delegate.requestAction = { HttpResponse(200) }
assertEquals(200, service.request(Request).statusCode)
parent.cancelAndJoin()
}
@Test fun retiringOneOwnerDoesNotRetargetOrCancelAnotherOwnersTransport() = runTest {
val parentA = SupervisorJob(); val parentB = SupervisorJob()
val a = FakeHttp().apply { requestAction = { HttpResponse(200, "A") } }
val b = FakeHttp().apply { requestAction = { HttpResponse(200, "B") } }
val serviceA = ProfileHttpService(A, a, CoroutineScope(parentA + StandardTestDispatcher(testScheduler)))
val serviceB = ProfileHttpService(B, b, CoroutineScope(parentB + StandardTestDispatcher(testScheduler)))
assertEquals("A", serviceA.request(Request).body); parentA.cancelAndJoin()
assertFailsWith<CancellationException> { serviceA.request(Request) }
assertEquals("B", serviceB.request(Request).body); assertTrue(parentB.isActive)
assertEquals(1, a.calls); assertEquals(1, b.calls); parentB.cancelAndJoin()
}
@Test fun extraPlatformEnginesHaveIndependentLifetimes() = runTest {
val first = createPlatformHttpClientEngine(A)
val second = createPlatformHttpClientEngine(B)
try {
kotlin.test.assertNotSame(first, second)
ProfileHttpEngine(first).closeAndJoin()
assertTrue(second.coroutineContext[Job]?.isActive == true)
} finally {
ProfileHttpEngine(first).closeAndJoin()
ProfileHttpEngine(second).closeAndJoin()
}
}
private class FakeHttp : HttpService {
var calls = 0
var requestAction: suspend (HttpRequest) -> HttpResponse = { HttpResponse(200) }
var streamAction: suspend (HttpRequest, suspend (ByteArray) -> Unit) -> HttpStreamResponse = { _, _ -> HttpStreamResponse(200) }
override suspend fun request(request: HttpRequest): HttpResponse { calls++; return requestAction(request) }
override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
calls++; return streamAction(request, onChunk)
}
}
private companion object {
val A = ProfileId("p_11111111111111111111111111111111")
val B = ProfileId("p_22222222222222222222222222222222")
val Request = HttpRequest("https://source.test/chapter")
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/http/ProfileTestEngine.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ProfileTestEngine, execute, close.
The source describes its contract as:
Executes the real Ktor pipeline with a controlled transport and no remote network.
@file:OptIn(io.ktor.utils.io.InternalAPI::class)
package eu.friedcutlet.yokan.services.http
import io.ktor.client.engine.HttpClientEngineBase
import io.ktor.client.engine.HttpClientEngineCapability
import io.ktor.client.engine.HttpClientEngineConfig
import io.ktor.client.plugins.HttpTimeoutCapability
import io.ktor.client.plugins.websocket.WebSocketCapability
import io.ktor.client.request.HttpRequestData
import io.ktor.client.request.HttpResponseData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.channels.Channel
/** Executes the real Ktor pipeline with a controlled transport and no remote network. */
internal class ProfileTestEngine(
override val dispatcher: CoroutineDispatcher,
private val action: suspend (HttpRequestData) -> HttpResponseData,
) : HttpClientEngineBase("profile-test") {
override val config = HttpClientEngineConfig()
override val supportedCapabilities: Set<HttpClientEngineCapability<*>> = setOf(HttpTimeoutCapability, WebSocketCapability)
val requests = Channel<HttpRequestData>(Channel.UNLIMITED)
var closeCalls = 0
private set
override suspend fun execute(data: HttpRequestData): HttpResponseData {
requests.send(data)
return action(data)
}
override fun close() { closeCalls++; super.close() }
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/http/RecordingHttpService.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines RecordingHttpService, request.
The source describes its contract as:
Records every buffered request before answering it with [respond].
package eu.friedcutlet.yokan.services.http
/** Records every buffered request before answering it with [respond]. */
internal class RecordingHttpService(private val respond: suspend (HttpRequest) -> HttpResponse) : HttpService {
val requests = mutableListOf<HttpRequest>()
override suspend fun request(request: HttpRequest): HttpResponse {
requests += request
return respond(request)
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/http/ServerUrlsTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ServerUrlsTest, hubServerUrlsAreNormalised.
Read the setup, action and assertions in these cases before implementing their production paths:
hubServerUrlsAreNormalised
package eu.friedcutlet.yokan.services.http
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class ServerUrlsTest {
@Test
fun hubServerUrlsAreNormalised() {
assertEquals("https://hub.test", normalizeHubServer(" hub.test/ "))
assertEquals("http://10.0.0.2:8080", normalizeHubServer("http://10.0.0.2:8080/"))
assertNull(normalizeHubServer(" "))
assertEquals("wss://hub.test", hubWebSocketBase("https://hub.test"))
assertEquals("ws://10.0.0.2:8080", hubWebSocketBase("http://10.0.0.2:8080"))
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieJarTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines CookieJarTest, respectsDomainPathAndSecureScope, keepsHostOnlyCookiesOffSubdomains, rejectsForeignDomainAttributes, scopesSolvedBrowserUserAgentToHostAndSubdomains.
Read the setup, action and assertions in these cases before implementing their production paths:
respectsDomainPathAndSecureScopekeepsHostOnlyCookiesOffSubdomainsrejectsForeignDomainAttributesscopesSolvedBrowserUserAgentToHostAndSubdomains
Cross-chapter imports used by this file: InMemoryYokanDatabase. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http.cookies
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class CookieJarTest {
@Test
fun respectsDomainPathAndSecureScope() {
val jar = CookieJar(InMemoryYokanDatabase())
jar.setFromResponse(
"https://animepahe.pw/login",
listOf("cf_clearance=token; Domain=animepahe.pw; Path=/api; Secure; HttpOnly"),
)
assertEquals("cf_clearance=token", jar.cookieHeader("https://animepahe.pw/api"))
assertEquals("cf_clearance=token", jar.cookieHeader("https://cdn.animepahe.pw/api/list"))
assertNull(jar.cookieHeader("https://animepahe.pw/apiary"))
assertNull(jar.cookieHeader("https://animepahe.pw/player"))
assertNull(jar.cookieHeader("http://animepahe.pw/api"))
assertNull(jar.cookieHeader("https://example.org/api"))
}
@Test
fun keepsHostOnlyCookiesOffSubdomains() {
val jar = CookieJar(InMemoryYokanDatabase())
jar.setFromResponse(
"https://animepahe.pw/",
listOf("session=host-only; Path=/"),
)
assertEquals("session=host-only", jar.cookieHeader("https://animepahe.pw/"))
assertNull(jar.cookieHeader("https://cdn.animepahe.pw/"))
}
@Test
fun rejectsForeignDomainAttributes() {
val jar = CookieJar(InMemoryYokanDatabase())
jar.setFromResponse(
"https://attacker.example/",
listOf("cf_clearance=stolen; Domain=animepahe.pw; Path=/"),
)
assertNull(jar.cookieHeader("https://attacker.example/"))
assertNull(jar.cookieHeader("https://animepahe.pw/"))
}
@Test
fun scopesSolvedBrowserUserAgentToHostAndSubdomains() {
val jar = CookieJar(InMemoryYokanDatabase())
jar.rememberUserAgent("https://animepahe.pw/", "NativeBrowser/150")
assertEquals("NativeBrowser/150", jar.userAgent("https://animepahe.pw/api"))
assertEquals("NativeBrowser/150", jar.userAgent("https://cdn.animepahe.pw/api"))
assertNull(jar.userAgent("https://example.org/"))
jar.clear("animepahe.pw")
assertNull(jar.userAgent("https://animepahe.pw/"))
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/http/cookies/ProfileCookieJarTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ProfileCookieJarTest, settings, updateSettings.
Read the setup, action and assertions in these cases before implementing their production paths:
defaultAdoptsLegacyCookiesAndExtraOwnersStayIndependentAcrossRestartretiredJarDoesNotReadOrMutateTheClosedDatabasereplacementSessionKeepsSavedCookiesWhileOldCallbacksCannotClearOrOverwriteThemlateHttpResponseCannotSaveCookiesToARetiredOwnercheckingBrowserCapabilityNeverReadsCredentialsFromStorage
Cross-chapter imports used by this file: ProfileId, DbCookie, DbSettings, InMemoryYokanDatabase, YokanDatabase, emptySnapshot. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http.cookies
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.DbCookie
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.http.EnhancedHttpService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class ProfileCookieJarTest {
@Test fun defaultAdoptsLegacyCookiesAndExtraOwnersStayIndependentAcrossRestart() {
val database = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(
cookiesList = listOf(DbCookie(host = "source.test", cookie = "session=legacy")),
)))
val default = CookieJar(database)
val extraDatabase = InMemoryYokanDatabase(emptySnapshot())
val extra = CookieJar(extraDatabase, Extra)
assertEquals(ProfileId.Default, default.profileId); assertEquals(Extra, extra.profileId)
assertTrue(default.canUseBrowserStorage); assertEquals(platformBrowserIsolation, extra.canUseBrowserStorage)
assertNull(extra.cookieHeader(Url))
extra.put("source.test", "session=extra")
default.rememberUserAgent(Url, "DefaultBrowser"); extra.rememberUserAgent(Url, "ExtraBrowser")
assertEquals("session=legacy", default.cookieHeader(Url))
assertEquals("session=extra", CookieJar(InMemoryYokanDatabase(extraDatabase.snapshot()), Extra).cookieHeader(Url))
assertEquals("DefaultBrowser", default.userAgent(Url)); assertEquals("ExtraBrowser", extra.userAgent(Url))
extra.clear()
assertEquals("session=legacy", default.cookieHeader(Url)); assertNull(extra.cookieHeader(Url))
}
@Test fun retiredJarDoesNotReadOrMutateTheClosedDatabase() {
val storage = InMemoryYokanDatabase(emptySnapshot())
var open = true
val database = object : YokanDatabase by storage {
override fun settings(): DbSettings { check(open) { "Closed database read" }; return storage.settings() }
override fun updateSettings(settings: DbSettings) { check(open) { "Closed database write" }; storage.updateSettings(settings) }
}
val jar = CookieJar(database, ProfileId.Default) { open }
jar.put("source.test", "session=keep"); jar.rememberUserAgent(Url, "KeepBrowser")
val before = storage.snapshot()
open = false
assertFalse(jar.isAvailable); assertFalse(jar.canUseBrowserStorage)
assertNull(jar.cookieHeader(Url)); assertNull(jar.rawCookieFor("source.test")); assertNull(jar.userAgent(Url))
jar.put("source.test", "session=late")
jar.setFromResponse(Url, listOf("session=late; Path=/"))
jar.rememberUserAgent(Url, "LateBrowser"); jar.clear("source.test"); jar.clear()
assertEquals(before, storage.snapshot())
}
@Test fun replacementSessionKeepsSavedCookiesWhileOldCallbacksCannotClearOrOverwriteThem() {
val database = InMemoryYokanDatabase(emptySnapshot())
var open = true
val old = CookieJar(database, ProfileId.Default) { open }
old.put("source.test", "session=old"); old.rememberUserAgent(Url, "OldBrowser")
open = false
val replacement = CookieJar(database)
assertEquals("session=old", replacement.cookieHeader(Url))
assertNull(replacement.userAgent(Url)) // User agents are session state, not inherited credentials.
replacement.put("source.test", "session=new")
old.setFromResponse(Url, listOf("session=late; Path=/")); old.clear()
assertEquals("session=new", replacement.cookieHeader(Url)); assertNull(old.cookieHeader(Url))
}
@Test fun lateHttpResponseCannotSaveCookiesToARetiredOwner() = runTest {
val database = InMemoryYokanDatabase(emptySnapshot())
var open = true
val jar = CookieJar(database, ProfileId.Default) { open }
jar.put("source.test", "session=original")
val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
val delegate = HttpService {
entered.complete(Unit); release.await()
HttpResponse(statusCode = 200, body = "ok", setCookies = listOf("session=late; Path=/"))
}
val http = EnhancedHttpService(delegate, database, jar)
val caller = launch { http.request(HttpRequest(Url)) }
entered.await(); open = false; release.complete(Unit); caller.join()
assertEquals("session=original", CookieJar(database).cookieHeader(Url))
}
@Test fun checkingBrowserCapabilityNeverReadsCredentialsFromStorage() {
val database = object : YokanDatabase by InMemoryYokanDatabase(emptySnapshot()) {
override fun settings(): DbSettings = error("Browser gate must not read credentials")
}
assertTrue(CookieJar(database).canUseBrowserStorage)
assertEquals(platformBrowserIsolation, CookieJar(database, Extra).canUseBrowserStorage)
assertFalse(CookieJar(database, ProfileId.Default) { false }.canUseBrowserStorage)
assertFalse(CookieJar(database, Extra) { false }.canUseBrowserStorage)
}
private companion object {
val Extra = ProfileId("p_11111111111111111111111111111111")
const val Url = "https://source.test/"
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/webview/ProfileWebViewServiceTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ProfileWebViewServiceTest, FakeBrowser, open, resolveCloudflare, evaluateScript, syncCookies.
Read the setup, action and assertions in these cases before implementing their production paths:
extraOwnersUseTheBrowserOnlyWithPlatformIsolationretiredExtraCannotConstructOrCallTheBrowserretiredDefaultCannotConstructOrCallTheBrowserdefaultUsesOneLazyBrowserAndPreservesAllRequestArgumentsownerRetirementJoinsNativeCleanupAndSuppressesLateCookieHarvestcallerExpiryJoinsBrowserCleanupWithoutRetiringTheOwneralreadyExpiredCallerCannotAccessTheBrowserWithImmediateDispatchqueuedCallCanceledBeforeDispatchCannotInitializeTheBrowserbrowserFailureDoesNotCancelAnOrdinaryParentJobOrSiblingWork
Cross-chapter imports used by this file: ProfileId, InMemoryYokanDatabase, emptySnapshot. Keep those contracts available as you connect this step.
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package eu.friedcutlet.yokan.services.webview
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.http.cookies.platformBrowserIsolation
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class ProfileWebViewServiceTest {
@Test fun extraOwnersUseTheBrowserOnlyWithPlatformIsolation() = runTest {
val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()), Extra)
val browser = FakeBrowser(); var creations = 0
val service = ProfileWebViewService(jar, null) { creations++; browser }
assertEquals(platformBrowserIsolation, service.open(Request))
assertEquals(if (platformBrowserIsolation) "result" else "", service.evaluateScript(Request.url, "script"))
assertEquals(if (platformBrowserIsolation) 1 else 0, creations)
assertEquals(platformBrowserIsolation, jar.canUseBrowserStorage)
}
@Test fun retiredExtraCannotConstructOrCallTheBrowser() = runTest {
val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()), Extra) { false }
val service = ProfileWebViewService(jar, null) { error("Browser store accessed by retired extra owner") }
assertFalse(service.open(Request)); assertNull(service.resolveCloudflare(Request))
assertEquals("", service.evaluateScript(Request.url, "script")); assertNull(service.syncCookies(Request.url))
}
@Test fun retiredDefaultCannotConstructOrCallTheBrowser() = runTest {
val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()), ProfileId.Default) { false }
val service = ProfileWebViewService(jar, null) { error("Shared store accessed by retired owner") }
assertFalse(service.open(Request)); assertNull(service.resolveCloudflare(Request))
assertEquals("", service.evaluateScript(Request.url, "script")); assertNull(service.syncCookies(Request.url))
}
@Test fun defaultUsesOneLazyBrowserAndPreservesAllRequestArguments() = runTest {
val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()))
val browser = FakeBrowser(); var creations = 0
val service = ProfileWebViewService(jar, null) { creations++; browser }
assertEquals(0, creations)
assertTrue(service.open(Request)); assertEquals(200, service.resolveCloudflare(Request)?.statusCode)
assertEquals("result", service.evaluateScript(Request.url, "script", "agent"))
assertEquals("session=cookie", service.syncCookies(Request.url))
assertEquals(1, creations)
assertEquals(listOf("open:$Request", "resolve:$Request", "script:${Request.url}:script:agent", "cookies:${Request.url}"), browser.calls)
}
@Test fun ownerRetirementJoinsNativeCleanupAndSuppressesLateCookieHarvest() = runTest {
val database = InMemoryYokanDatabase(emptySnapshot())
val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
val jar = CookieJar(database, ProfileId.Default) { parent.isActive }
jar.put("source.test", "session=original")
val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
var finalized = false
val browser = FakeBrowser().apply { action = {
try { entered.complete(Unit); awaitCancellation() }
finally { withContext(NonCancellable) {
release.await(); jar.put("source.test", "session=late"); finalized = true
} }
} }
val service = ProfileWebViewService(jar, scope) { browser }
val caller = launch { service.resolveCloudflare(Request) }
entered.await()
val retiring = launch { parent.cancelAndJoin() }
testScheduler.runCurrent(); assertFalse(retiring.isCompleted); assertFalse(caller.isCompleted)
assertNull(service.syncCookies(Request.url))
release.complete(Unit); retiring.join(); caller.join()
assertTrue(finalized)
assertEquals("session=original", CookieJar(database).cookieHeader(Request.url))
assertEquals(1, browser.calls.size)
}
@Test fun callerExpiryJoinsBrowserCleanupWithoutRetiringTheOwner() = runTest {
val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()), ProfileId.Default) { parent.isActive }
val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
val browser = FakeBrowser().apply { action = {
try { entered.complete(Unit); awaitCancellation() }
finally { withContext(NonCancellable) { release.await() } }
} }
val service = ProfileWebViewService(jar, scope) { browser }
val sibling = scope.launch { awaitCancellation() }
val caller = launch { service.evaluateScript(Request.url, "script") }
entered.await(); caller.cancel(); testScheduler.runCurrent()
assertFalse(caller.isCompleted); assertTrue(parent.isActive); assertTrue(sibling.isActive)
release.complete(Unit); caller.join(); browser.action = {}
assertTrue(service.open(Request))
parent.cancelAndJoin()
}
@Test fun alreadyExpiredCallerCannotAccessTheBrowserWithImmediateDispatch() = runTest {
val parent = SupervisorJob(); val scope = CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler))
var creations = 0
val service = ProfileWebViewService(CookieJar(InMemoryYokanDatabase(emptySnapshot())), scope) { creations++; FakeBrowser() }
val caller = launch {
currentCoroutineContext().cancel()
assertFailsWith<CancellationException> { service.open(Request) }
}
caller.join(); assertEquals(0, creations); assertTrue(parent.isActive)
parent.cancelAndJoin()
}
@Test fun queuedCallCanceledBeforeDispatchCannotInitializeTheBrowser() = runTest {
val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
var creations = 0
val service = ProfileWebViewService(CookieJar(InMemoryYokanDatabase(emptySnapshot())), scope) { creations++; FakeBrowser() }
val caller = launch(UnconfinedTestDispatcher(testScheduler)) { service.open(Request) }
parent.cancel(); testScheduler.runCurrent(); caller.join(); parent.join()
assertEquals(0, creations)
assertFalse(service.open(Request)) // The owner gate also covers standalone jars with no lifetime predicate.
}
@Test fun browserFailureDoesNotCancelAnOrdinaryParentJobOrSiblingWork() = runTest {
val parent = Job(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
val browser = FakeBrowser().apply { action = { error("Native browser failure") } }
val service = ProfileWebViewService(CookieJar(InMemoryYokanDatabase(emptySnapshot())), scope) { browser }
val sibling = scope.launch { awaitCancellation() }
assertFailsWith<IllegalStateException> { service.syncCookies(Request.url) }
assertTrue(parent.isActive); assertTrue(sibling.isActive)
browser.action = {}; assertTrue(service.open(Request)); parent.cancelAndJoin()
}
private class FakeBrowser : WebViewService {
val calls = mutableListOf<String>()
var action: suspend () -> Unit = {}
override suspend fun open(request: WebViewRequest): Boolean { calls += "open:$request"; action(); return true }
override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse { calls += "resolve:$request"; action(); return HttpResponse(200, "ok") }
override suspend fun evaluateScript(url: String, script: String, userAgent: String?): String { calls += "script:$url:$script:$userAgent"; action(); return "result" }
override suspend fun syncCookies(url: String): String { calls += "cookies:$url"; action(); return "session=cookie" }
}
private companion object {
val Extra = ProfileId("p_11111111111111111111111111111111")
val Request = WebViewRequest("https://source.test/", "Source", mapOf("Referer" to "https://source.test"))
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/webview/InAppWebViewViewModelTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines InAppWebViewViewModelTest, verificationUsesRedirectedPageAndAllowsOnlyOneBrowserSession, closedPopupAndUnsolvedPagesRemainRetryable, browserFailureDoesNotLeaveVerificationWaiting, nativeChallengeNotificationDuringManualVerificationKeepsWaiting, newChallengeIgnoresLateCompletionFromPreviousPage, cancelledBrowserSessionRemainsRetryable, TestScope.model, FakeBrowser, open and 1 further declarations.
Read the setup, action and assertions in these cases before implementing their production paths:
verificationUsesRedirectedPageAndAllowsOnlyOneBrowserSessionclosedPopupAndUnsolvedPagesRemainRetryablebrowserFailureDoesNotLeaveVerificationWaitingnativeChallengeNotificationDuringManualVerificationKeepsWaitingnewChallengeIgnoresLateCompletionFromPreviousPagecancelledBrowserSessionRemainsRetryable
Cross-chapter imports used by this file: ViewModelTestHost, DefaultYokanRepository, SettingsStore, InMemoryYokanDatabase. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.webview
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.webview.WebViewRequest
import eu.friedcutlet.yokan.services.webview.WebViewService
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
@OptIn(ExperimentalCoroutinesApi::class)
class InAppWebViewViewModelTest {
private val host = ViewModelTestHost()
private val dispatcher = host.dispatcher
@AfterTest fun tearDown() = host.close()
@Test
fun verificationUsesRedirectedPageAndAllowsOnlyOneBrowserSession() = runTest(dispatcher) {
val completion = CompletableDeferred<HttpResponse?>()
val browser = FakeBrowser { completion.await() }
val model = model(browser)
model.requireBrowserVerification(redirectUrl)
model.solveCloudflare(redirectUrl, "source-agent")
model.solveCloudflare(redirectUrl, "source-agent")
assertEquals(BrowserVerificationStatus.Waiting, model.state.value.verificationStatus)
assertEquals(1, browser.requests.size)
assertEquals(redirectUrl, browser.requests.single().url)
assertEquals("source-agent", browser.requests.single().headers["User-Agent"])
completion.complete(HttpResponse(200, "<title>Novel Updates</title>Content"))
assertEquals(BrowserVerificationStatus.Verified, model.state.value.verificationStatus)
// Repeated native notifications must not reset the completed state or start another browser.
model.requireBrowserVerification(redirectUrl)
assertEquals(BrowserVerificationStatus.Verified, model.state.value.verificationStatus)
assertEquals(1, browser.requests.size)
}
@Test
fun closedPopupAndUnsolvedPagesRemainRetryable() = runTest(dispatcher) {
for (response in listOf(null, HttpResponse(403, "Denied"), HttpResponse(200, "<title>Just a moment...</title>"))) {
val browser = FakeBrowser { response }
val model = model(browser)
model.requireBrowserVerification(redirectUrl)
model.solveCloudflare(redirectUrl, null)
assertEquals(BrowserVerificationStatus.Failed, model.state.value.verificationStatus)
model.solveCloudflare(redirectUrl, null)
assertEquals(2, browser.requests.size)
}
}
@Test
fun browserFailureDoesNotLeaveVerificationWaiting() = runTest(dispatcher) {
val model = model(FakeBrowser { error("Browser unavailable") })
model.requireBrowserVerification(redirectUrl)
model.solveCloudflare(redirectUrl, null)
assertEquals(BrowserVerificationStatus.Failed, model.state.value.verificationStatus)
}
@Test
fun nativeChallengeNotificationDuringManualVerificationKeepsWaiting() = runTest(dispatcher) {
val completion = CompletableDeferred<HttpResponse?>()
val model = model(FakeBrowser { completion.await() })
model.solveCloudflare(redirectUrl, null)
model.requireBrowserVerification(redirectUrl)
assertEquals(BrowserVerificationStatus.Waiting, model.state.value.verificationStatus)
completion.complete(HttpResponse(200, "Content"))
assertEquals(BrowserVerificationStatus.Verified, model.state.value.verificationStatus)
}
@Test
fun newChallengeIgnoresLateCompletionFromPreviousPage() = runTest(dispatcher) {
val oldCompletion = CompletableDeferred<HttpResponse?>()
val newCompletion = CompletableDeferred<HttpResponse?>()
var calls = 0
val browser = FakeBrowser {
if (++calls == 1) withContext(NonCancellable) { oldCompletion.await() }
else newCompletion.await()
}
val model = model(browser)
try {
model.requireBrowserVerification(redirectUrl)
model.solveCloudflare(redirectUrl, null)
val nextUrl = "https://translator.test/chapter/1"
model.requireBrowserVerification(nextUrl)
model.solveCloudflare(nextUrl, null)
assertEquals(2, browser.requests.size)
oldCompletion.complete(HttpResponse(200, "Previous page"))
assertEquals(nextUrl, model.state.value.verificationUrl)
assertEquals(BrowserVerificationStatus.Waiting, model.state.value.verificationStatus)
newCompletion.complete(HttpResponse(403, "Denied"))
assertEquals(BrowserVerificationStatus.Failed, model.state.value.verificationStatus)
} finally {
oldCompletion.complete(null)
newCompletion.complete(null)
}
}
@Test
fun cancelledBrowserSessionRemainsRetryable() = runTest(dispatcher) {
var calls = 0
val model = model(FakeBrowser {
if (++calls == 1) throw CancellationException("Browser closed")
HttpResponse(200, "Content")
})
model.requireBrowserVerification(redirectUrl)
model.solveCloudflare(redirectUrl, null)
assertEquals(BrowserVerificationStatus.Failed, model.state.value.verificationStatus)
assertEquals(1f, model.state.value.progress)
model.solveCloudflare(redirectUrl, null)
assertEquals(BrowserVerificationStatus.Verified, model.state.value.verificationStatus)
}
private fun TestScope.model(browser: WebViewService): InAppWebViewViewModel {
val db = InMemoryYokanDatabase()
return host.create { InAppWebViewViewModel(browser, CookieJar(db), SettingsStore(DefaultYokanRepository(db), backgroundScope) {}) }
}
private val redirectUrl = "https://www.novelupdates.com/series-finder/"
}
private class FakeBrowser(private val solve: suspend () -> HttpResponse?) : WebViewService {
val requests = mutableListOf<WebViewRequest>()
override suspend fun open(request: WebViewRequest): Boolean = false
override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? {
requests += request
return solve()
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/http/CloudflareHandlingTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines CloudflareHandlingTest, CapturingSolver, attachesSeededClearanceCookieToRequests, persistsClearanceFromSetCookie, clearanceIsScopedToItsHost, forcedResolutionHeaderIsNotSentToTheServer, solvesChallengeViaCfProxyWhenConfigured, cfProxyCookiesStayOnTheirOwnDomains, fallsBackToWebViewWhenProxyFails.
The source describes its contract as:
Deterministic coverage of Yokan's Cloudflare-handling mechanism: the shared [CookieJar] seeds a
cf_clearancecookie (harvested by the WebView resolver in production) and [EnhancedHttpService] must attach it to every subsequent request for that host, and persistSet-Cookieclearances issued by the server. This is the transport contract that lets extensions get past a Cloudflare challenge once the WebView solves it.
Read the setup, action and assertions in these cases before implementing their production paths:
attachesSeededClearanceCookieToRequestspersistsClearanceFromSetCookieclearanceIsScopedToItsHostforcedResolutionHeaderIsNotSentToTheServersolvesChallengeViaCfProxyWhenConfiguredcfProxyCookiesStayOnTheirOwnDomainsfallsBackToWebViewWhenProxyFails
Cross-chapter imports used by this file: InMemoryYokanDatabase. Keep those contracts available as you connect this step.
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<String, String>? = null
val solve: suspend (String, Map<String, String>) -> 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 = "<html>success page</html>")
} else {
HttpResponse(
statusCode = 403,
body = "<html><head><title>Just a moment...</title></head></html>",
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("<html>success page</html>", 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 = "<html>success page</html>")
else -> HttpResponse(
statusCode = 403,
body = "<html><head><title>Just a moment...</title></head></html>",
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 = "<html><head><title>Just a moment...</title></head></html>",
headers = mapOf("Server" to "cloudflare"),
)
}
else -> HttpResponse(statusCode = 404, body = "not found")
}
}
val webView = CapturingSolver(HttpResponse(statusCode = 200, body = "<html>cleared by webview</html>"))
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("<html>cleared by webview</html>", res.body)
assertEquals(1, webView.resolveCalls)
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/http/DohResolverTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines DohResolverTest, returnsNullWhenDohDisabledAndNoCustomDns, ignoresCustomDnsSoHostsAreNeverPinnedToIt, resolvesViaPresetProviderWhenEnabled, resolvesViaCustomEndpointWhenConfigured, returnsNullWhenCustomDohUrlIsBlank, cachesResolvedIpWithinTtl.
Read the setup, action and assertions in these cases before implementing their production paths:
returnsNullWhenDohDisabledAndNoCustomDnsignoresCustomDnsSoHostsAreNeverPinnedToItresolvesViaPresetProviderWhenEnabledresolvesViaCustomEndpointWhenConfiguredreturnsNullWhenCustomDohUrlIsBlankcachesResolvedIpWithinTtl
Cross-chapter imports used by this file: InMemoryYokanDatabase. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.runBlocking
class DohResolverTest {
@Test
fun returnsNullWhenDohDisabledAndNoCustomDns() = runBlocking {
val database = InMemoryYokanDatabase()
database.updateSettings(database.settings().copy(dohEnabled = false, customDns = ""))
val http = RecordingHttpService { HttpResponse(200, "{}") }
val resolver = DohResolver(database, http)
val result = resolver.resolve("example.com")
assertNull(result)
assertEquals(0, http.requests.size)
}
@Test
fun ignoresCustomDnsSoHostsAreNeverPinnedToIt() = runBlocking {
val database = InMemoryYokanDatabase()
database.updateSettings(database.settings().copy(dohEnabled = false, customDns = "1.2.3.4"))
val http = RecordingHttpService { HttpResponse(200, "{}") }
val resolver = DohResolver(database, http)
val result = resolver.resolve("example.com")
assertNull(result)
assertEquals(0, http.requests.size)
}
@Test
fun resolvesViaPresetProviderWhenEnabled() = runBlocking {
val database = InMemoryYokanDatabase()
database.updateSettings(database.settings().copy(dohEnabled = true, dohProviderId = 0))
val http = RecordingHttpService { req ->
assertTrue(req.url.startsWith("https://cloudflare-dns.com/dns-query"))
assertTrue(req.url.contains("name=manga.example"))
assertEquals("application/dns-json", req.headers["Accept"])
HttpResponse(
statusCode = 200,
body = """
{
"Status": 0,
"Answer": [
{ "name": "manga.example", "type": 1, "TTL": 300, "data": "93.184.216.34" }
]
}
""".trimIndent(),
)
}
val resolver = DohResolver(database, http)
val result = resolver.resolve("manga.example")
assertEquals("93.184.216.34", result)
assertEquals(1, http.requests.size)
}
@Test
fun resolvesViaCustomEndpointWhenConfigured() = runBlocking {
val database = InMemoryYokanDatabase()
database.updateSettings(
database.settings().copy(
dohEnabled = true,
dohProviderId = CustomDohProviderId,
customDohUrl = "https://custom.dns.example/dns-query",
)
)
val http = RecordingHttpService { req ->
assertTrue(req.url.startsWith("https://custom.dns.example/dns-query?name=custom.host&type=A"))
assertEquals("application/dns-json", req.headers["Accept"])
HttpResponse(
statusCode = 200,
body = """
{
"Status": 0,
"Answer": [
{ "name": "custom.host", "type": 1, "TTL": 300, "data": "10.0.0.42" }
]
}
""".trimIndent(),
)
}
val resolver = DohResolver(database, http)
val result = resolver.resolve("custom.host")
assertEquals("10.0.0.42", result)
assertEquals(1, http.requests.size)
}
@Test
fun returnsNullWhenCustomDohUrlIsBlank() = runBlocking {
val database = InMemoryYokanDatabase()
database.updateSettings(
database.settings().copy(
dohEnabled = true,
dohProviderId = CustomDohProviderId,
customDohUrl = "",
)
)
val http = RecordingHttpService { HttpResponse(200, "{}") }
val resolver = DohResolver(database, http)
val result = resolver.resolve("custom.host")
assertNull(result)
assertEquals(0, http.requests.size)
}
@Test
fun cachesResolvedIpWithinTtl() = runBlocking {
val database = InMemoryYokanDatabase()
database.updateSettings(database.settings().copy(dohEnabled = true, dohProviderId = 1))
val http = RecordingHttpService {
HttpResponse(
statusCode = 200,
body = """{"Answer":[{"name":"cached.org","type":1,"data":"192.168.1.1"}]}""",
)
}
val resolver = DohResolver(database, http)
val first = resolver.resolve("cached.org")
val second = resolver.resolve("cached.org")
assertEquals("192.168.1.1", first)
assertEquals("192.168.1.1", second)
assertEquals(1, http.requests.size)
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/http/HostResolverDnsTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines HostResolverDnsTest, usesTheResolverAnswerAndKeepsTheHostname, fallsBackToSystemDnsWhenTheResolverHasNoAnswerOrFails, enabledDohResolvesRequestsOfThePlatformClient.
Read the setup, action and assertions in these cases before implementing their production paths:
usesTheResolverAnswerAndKeepsTheHostnamefallsBackToSystemDnsWhenTheResolverHasNoAnswerOrFailsenabledDohResolvesRequestsOfThePlatformClient
Cross-chapter imports used by this file: InMemoryYokanDatabase. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http
import com.sun.net.httpserver.HttpServer
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import java.net.InetAddress
import java.net.InetSocketAddress
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.runBlocking
class HostResolverDnsTest {
@Test
fun usesTheResolverAnswerAndKeepsTheHostname() {
val addresses = HostResolverDns { "10.0.0.42" }.lookup("manga.example")
assertEquals(listOf("10.0.0.42"), addresses.map { it.hostAddress })
assertEquals("manga.example", addresses.single().hostName)
}
@Test
fun fallsBackToSystemDnsWhenTheResolverHasNoAnswerOrFails() {
val system = InetAddress.getAllByName("localhost").toList()
assertEquals(system, HostResolverDns { null }.lookup("localhost"))
assertEquals(system, HostResolverDns { error("database closed") }.lookup("localhost"))
}
@Test
fun enabledDohResolvesRequestsOfThePlatformClient() = runBlocking {
val server = HttpServer.create(InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0).apply {
createContext("/") { exchange ->
val body = "served".encodeToByteArray()
exchange.sendResponseHeaders(200, body.size.toLong())
exchange.responseBody.use { it.write(body) }
}
start()
}
val database = InMemoryYokanDatabase()
database.updateSettings(database.settings().copy(dohEnabled = true, dohProviderId = 0))
val doh = RecordingHttpService {
HttpResponse(200, """{"Answer":[{"name":"yokan-doh.invalid","type":1,"data":"127.0.0.1"}]}""")
}
val http = createPlatformHttpService(resolveHost = DohResolver(database, doh)::resolve)
try {
val response = http.request(HttpRequest("http://yokan-doh.invalid:${server.address.port}/"))
assertEquals("served", response.body)
assertTrue(doh.requests.single().url.contains("name=yokan-doh.invalid"), doh.requests.single().url)
} finally {
http.close()
server.stop(0)
}
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/http/IsolatedPlatformHttpTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines IsolatedPlatformHttpTest.
Read the setup, action and assertions in these cases before implementing their production paths:
isolatedEnginesDoNotReplayResponseCookiesAndRetainExplicitOwnerCredentials
Cross-chapter imports used by this file: ProfileId. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.http
import com.sun.net.httpserver.HttpServer
import eu.friedcutlet.yokan.domain.ProfileId
import kotlinx.coroutines.runBlocking
import java.net.InetSocketAddress
import kotlin.test.*
class IsolatedPlatformHttpTest {
@Test fun isolatedEnginesDoNotReplayResponseCookiesAndRetainExplicitOwnerCredentials() = runBlocking {
val received = mutableListOf<Pair<String?, String?>>()
val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
server.createContext("/") { exchange ->
synchronized(received) { received.add(exchange.requestHeaders.getFirst("Cookie") to exchange.requestHeaders.getFirst("Authorization")) }
exchange.responseHeaders.add("Set-Cookie", "ambient=shared; Path=/")
val bytes = "ok".encodeToByteArray()
exchange.sendResponseHeaders(200, bytes.size.toLong())
exchange.responseBody.use { it.write(bytes) }
}
server.start()
val a = createPlatformHttpService(ProfileId("p_${"a".repeat(32)}"))
val b = createPlatformHttpService(ProfileId("p_${"b".repeat(32)}"))
val url = "http://127.0.0.1:${server.address.port}/"
try {
assertEquals(200, a.request(HttpRequest(url)).statusCode)
assertEquals(200, a.request(HttpRequest(url)).statusCode)
b.request(HttpRequest(url, headers = mapOf("Cookie" to "owner=B", "Authorization" to "Bearer profile-B")))
a.request(HttpRequest(url, headers = mapOf("Cookie" to "owner=A", "Authorization" to "Bearer profile-A")))
assertEquals(listOf(null to null, null to null, "owner=B" to "Bearer profile-B", "owner=A" to "Bearer profile-A"), received)
a.closeAndJoin()
assertEquals("ok", b.request(HttpRequest(url)).body)
assertEquals(null to null, received.last())
} finally {
a.closeAndJoin(); b.closeAndJoin(); server.stop(0)
}
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/http/KtorHttpServiceStreamTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines KtorHttpServiceStreamTest, streamHandsOverChunksBeforeTheBodyEnds, streamLeavesServerErrorRetriesToItsCallerAndBuffersTheErrorBody, ChannelEngine, execute, UnavailableEngine.
Read the setup, action and assertions in these cases before implementing their production paths:
streamHandsOverChunksBeforeTheBodyEndsstreamLeavesServerErrorRetriesToItsCallerAndBuffersTheErrorBody
package eu.friedcutlet.yokan.services.http
import io.ktor.client.engine.HttpClientEngineBase
import io.ktor.client.engine.HttpClientEngineCapability
import io.ktor.client.engine.HttpClientEngineConfig
import io.ktor.client.engine.callContext
import io.ktor.client.plugins.HttpTimeoutCapability
import io.ktor.client.request.HttpRequestData
import io.ktor.client.request.HttpResponseData
import io.ktor.http.Headers
import io.ktor.http.HttpProtocolVersion
import io.ktor.http.HttpStatusCode
import io.ktor.util.date.GMTDate
import io.ktor.utils.io.ByteChannel
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.InternalAPI
import io.ktor.utils.io.writeFully
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
class KtorHttpServiceStreamTest {
@Test
fun streamHandsOverChunksBeforeTheBodyEnds() = runBlocking {
val body = ByteChannel()
val service = KtorHttpService(ChannelEngine(body))
val firstChunk = CompletableDeferred<ByteArray>()
val headers = CompletableDeferred<HttpStreamResponse>()
val streaming = async {
service.stream(HttpRequest(url = "https://example.test/episode.mp4", onStreamResponse = { headers.complete(it) })) {
assertEquals(true, headers.isCompleted)
firstChunk.complete(it)
}
}
try {
assertEquals(200, withTimeout(5_000) { headers.await() }.statusCode)
body.writeFully("abc".encodeToByteArray())
body.flush()
// A buffering client only returns once the body is closed, so this would time out.
assertContentEquals("abc".encodeToByteArray(), withTimeout(5_000) { firstChunk.await() })
body.flushAndClose()
assertEquals(200, withTimeout(5_000) { streaming.await() }.statusCode)
} finally {
streaming.cancel()
service.close()
}
}
@Test
fun streamLeavesServerErrorRetriesToItsCallerAndBuffersTheErrorBody() = runBlocking {
val engine = UnavailableEngine()
val service = KtorHttpService(engine)
try {
var chunks = 0
val response = withTimeout(5_000) { service.stream(HttpRequest(url = "https://example.test/page.jpg")) { chunks++ } }
assertEquals(503, response.statusCode)
assertEquals(1, engine.calls)
// The error page is handed back for inspection, never written through onChunk.
assertEquals(0, chunks)
assertContentEquals(UnavailableEngine.PAGE, response.body)
} finally {
service.close()
}
}
@OptIn(InternalAPI::class)
private class ChannelEngine(private val body: ByteReadChannel) : HttpClientEngineBase("channel-test") {
override val config = HttpClientEngineConfig()
override val supportedCapabilities: Set<HttpClientEngineCapability<*>> = setOf(HttpTimeoutCapability)
override suspend fun execute(data: HttpRequestData): HttpResponseData =
HttpResponseData(HttpStatusCode.OK, GMTDate(), Headers.Empty, HttpProtocolVersion.HTTP_1_1, body, callContext())
}
@OptIn(InternalAPI::class)
private class UnavailableEngine : HttpClientEngineBase("unavailable-test") {
var calls = 0
override val config = HttpClientEngineConfig()
override val supportedCapabilities: Set<HttpClientEngineCapability<*>> = setOf(HttpTimeoutCapability)
override suspend fun execute(data: HttpRequestData): HttpResponseData {
calls += 1
return HttpResponseData(HttpStatusCode.ServiceUnavailable, GMTDate(), Headers.Empty, HttpProtocolVersion.HTTP_1_1, ByteReadChannel(PAGE), callContext())
}
companion object {
val PAGE = "<html>Just a moment...</html>".encodeToByteArray()
}
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/webview/DesktopBrowserVerificationTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines DesktopBrowserVerificationTest, challengeTitlesAndInterstitialMarkupOfferBrowserVerification, ordinaryPagesAndLoginFormsStayInApp.
Read the setup, action and assertions in these cases before implementing their production paths:
challengeTitlesAndInterstitialMarkupOfferBrowserVerificationordinaryPagesAndLoginFormsStayInApp
package eu.friedcutlet.yokan.ui.screens.webview
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class DesktopBrowserVerificationTest {
@Test
fun challengeTitlesAndInterstitialMarkupOfferBrowserVerification() {
assertTrue(desktopPageNeedsBrowserVerification("Just a moment...", false))
assertTrue(desktopPageNeedsBrowserVerification("Attention Required! | Cloudflare", false))
assertTrue(desktopPageNeedsBrowserVerification("Novel Updates", true))
}
@Test
fun ordinaryPagesAndLoginFormsStayInApp() {
assertFalse(desktopPageNeedsBrowserVerification("Novel Updates", false))
assertFalse(desktopPageNeedsBrowserVerification("Log in", false))
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/webview/JavaFxCookieIsolationTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines JavaFxCookieIsolationTest.
Read the setup, action and assertions in these cases before implementing their production paths:
switchingProfilesReplacesTheJvmCookieStore
Cross-chapter imports used by this file: ProfileId. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.webview
import eu.friedcutlet.yokan.domain.ProfileId
import java.net.CookieHandler
import java.net.CookieManager
import java.net.HttpCookie
import java.net.URI
import kotlin.test.Test
import kotlin.test.assertSame
import kotlin.test.assertTrue
class JavaFxCookieIsolationTest {
@Test fun switchingProfilesReplacesTheJvmCookieStore() {
val uri = URI("https://source.test/")
ensureCookieManager(ProfileId.Default)
val default = CookieHandler.getDefault() as CookieManager
default.cookieStore.add(uri, HttpCookie("session", "default").apply { path = "/" })
ensureCookieManager(ProfileId.Default)
assertSame(default, CookieHandler.getDefault())
ensureCookieManager(Extra)
assertTrue((CookieHandler.getDefault() as CookieManager).cookieStore.get(uri).isEmpty())
ensureCookieManager(ProfileId.Default)
assertTrue((CookieHandler.getDefault() as CookieManager).cookieStore.get(uri).isEmpty())
}
private companion object {
val Extra = ProfileId("p_11111111111111111111111111111111")
}
}
Write composeApp/src/iosTest/kotlin/eu/friedcutlet/yokan/services/webview/IosProfileDataStoreTest.kt
Create this path in your reconstruction project. Source set: iosTest. Exact file download.
The implementation below defines IosProfileDataStoreTest.
Read the setup, action and assertions in these cases before implementing their production paths:
extraProfileMapsOneToOneOntoAPersistentStoreUuid
Cross-chapter imports used by this file: ProfileId. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.webview
import eu.friedcutlet.yokan.domain.ProfileId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotEquals
import platform.Foundation.NSUUID
class IosProfileDataStoreTest {
@Test fun extraProfileMapsOneToOneOntoAPersistentStoreUuid() {
val uuid = profileBrowserStoreUuid(ProfileId("p_0123456789abcdef0123456789abcdef"))
assertEquals("01234567-89ab-cdef-0123-456789abcdef", uuid)
assertEquals(uuid.uppercase(), NSUUID(uUIDString = uuid).UUIDString)
assertNotEquals(uuid, profileBrowserStoreUuid(ProfileId("p_0123456789abcdef0123456789abcdee")))
assertFailsWith<IllegalArgumentException> { profileBrowserStoreUuid(ProfileId.Default) }
}
}
Write composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/http/IsolatedBrowserHttpEngineTest.kt
Create this path in your reconstruction project. Source set: wasmJsTest. Exact file download.
The implementation below defines IsolatedBrowserHttpEngineTest, installFetchFixture, producedChunks, fixtureAborted, fixtureReleased, requestCredentials, requestCache, restoreFetch.
Read the setup, action and assertions in these cases before implementing their production paths:
largeResponseStreamsWithBackpressureAndOmitsAmbientCredentialscancellingTheConsumerAbortsAndJoinsTheNativeReader
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
package eu.friedcutlet.yokan.services.http
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.runTest
import kotlin.test.*
class IsolatedBrowserHttpEngineTest {
@Test fun largeResponseStreamsWithBackpressureAndOmitsAmbientCredentials() = runTest {
installFetchFixture(2100)
val service = KtorHttpService(IsolatedBrowserHttpEngine())
try {
var received = 0L
var maximumAhead = 0L
val response = service.stream(HttpRequest("https://browser-stream.test/large")) { chunk ->
assertTrue(chunk.all { it == 7.toByte() })
received += chunk.size
maximumAhead = maxOf(maximumAhead, producedChunks() * 32768L - received)
}
assertEquals(200, response.statusCode)
assertEquals(2100L * 32768, received)
assertTrue(received > 64L * 1024 * 1024)
assertTrue(maximumAhead < 8L * 32768, "Fetch must backpressure the consumer; ahead=$maximumAhead")
assertEquals("omit", requestCredentials())
assertEquals("no-store", requestCache())
assertTrue(fixtureAborted())
assertTrue(fixtureReleased())
} finally { service.closeAndJoin(); restoreFetch() }
}
@Test fun cancellingTheConsumerAbortsAndJoinsTheNativeReader() = runTest {
installFetchFixture(2100)
val service = KtorHttpService(IsolatedBrowserHttpEngine())
val entered = CompletableDeferred<Unit>()
try {
val transfer = async {
service.stream(HttpRequest("https://browser-stream.test/cancel")) {
entered.complete(Unit)
awaitCancellation()
}
}
entered.await()
transfer.cancelAndJoin()
service.closeAndJoin()
assertTrue(fixtureAborted())
assertTrue(fixtureReleased())
assertTrue(producedChunks() < 20)
} finally { service.closeAndJoin(); restoreFetch() }
}
}
private fun installFetchFixture(chunks: Int): Unit = js(
"""{
const original = globalThis.fetch;
const fixture = { original, produced: 0, aborted: false, cancelled: false, credentials: '', cache: '' };
globalThis.yokanFetchFixture = fixture;
globalThis.fetch = async (url, options) => {
fixture.credentials = options.credentials;
fixture.cache = options.cache;
let controller;
options.signal.addEventListener('abort', () => {
fixture.aborted = true;
if (controller && !fixture.cancelled && fixture.produced < chunks) controller.error(new DOMException('Aborted', 'AbortError'));
});
const body = new ReadableStream({
start(value) { controller = value; },
pull(value) {
if (fixture.produced === chunks) { value.close(); return; }
fixture.produced++;
value.enqueue(new Uint8Array(32768).fill(7));
},
cancel() { fixture.cancelled = true; }
});
fixture.body = body;
return new Response(body, { status: 200, headers: { 'Content-Type': 'application/octet-stream' } });
};
}""",
)
private fun producedChunks(): Int = js("globalThis.yokanFetchFixture.produced")
private fun fixtureAborted(): Boolean = js("globalThis.yokanFetchFixture.aborted")
private fun fixtureReleased(): Boolean = js("!globalThis.yokanFetchFixture.body.locked")
private fun requestCredentials(): String = js("globalThis.yokanFetchFixture.credentials")
private fun requestCache(): String = js("globalThis.yokanFetchFixture.cache")
private fun restoreFetch(): Unit = js("{ globalThis.fetch = globalThis.yokanFetchFixture.original; delete globalThis.yokanFetchFixture; }")
Write composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/http/IsolatedBrowserHttpTest.kt
Create this path in your reconstruction project. Source set: wasmJsTest. Exact file download.
The implementation below defines IsolatedBrowserHttpTest, capturedOptions, capturedCalls, installFetchProbe, removeFetchProbe.
Read the setup, action and assertions in these cases before implementing their production paths:
anonymousFetchRetainsExplicitAuthorizationAndBinaryResponsecookieAuthenticationIsRefusedBeforeCallingSharedBrowserTransport
Cross-chapter imports used by this file: ProfileId. Keep those contracts available as you connect this step.
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
package eu.friedcutlet.yokan.services.http
import eu.friedcutlet.yokan.domain.ProfileId
import kotlinx.coroutines.test.runTest
import kotlin.test.*
class IsolatedBrowserHttpTest {
@Test fun anonymousFetchRetainsExplicitAuthorizationAndBinaryResponse() = runTest {
installFetchProbe()
val client = createPlatformHttpService(Extra)
try {
val response = client.request(HttpRequest("https://example.test/data", headers = mapOf("Authorization" to "Bearer own-token")))
assertEquals(200, response.statusCode)
assertContentEquals(byteArrayOf(65, 0, 66), response.bodyBytes)
assertEquals("omit:no-store:Bearer own-token", capturedOptions())
} finally { client.closeAndJoin(); removeFetchProbe() }
}
@Test fun cookieAuthenticationIsRefusedBeforeCallingSharedBrowserTransport() = runTest {
installFetchProbe()
val client = createPlatformHttpService(Extra)
try {
assertFailsWith<IllegalStateException> { client.request(HttpRequest("https://example.test/data", headers = mapOf("Cookie" to "owner=extra"))) }
assertEquals(0, capturedCalls())
} finally { client.closeAndJoin(); removeFetchProbe() }
}
companion object { private val Extra = ProfileId("p_${"e".repeat(32)}") }
}
private fun capturedOptions(): String = js("globalThis.__yokanFetchProbe.options")
private fun capturedCalls(): Int = js("globalThis.__yokanFetchProbe.calls")
private fun installFetchProbe(): Unit = js(
"""
(() => {
globalThis.__yokanFetchProbe = { original: globalThis.fetch, calls: 0, options: '' };
globalThis.fetch = async (url, init) => {
const probe = globalThis.__yokanFetchProbe;
probe.calls++;
probe.options = init.credentials + ':' + init.cache + ':' + init.headers.Authorization;
return new Response(new Uint8Array([65, 0, 66]), {status: 200});
};
})()
""",
)
private fun removeFetchProbe(): Unit = js(
"""
(() => { globalThis.fetch = globalThis.__yokanFetchProbe.original; delete globalThis.__yokanFetchProbe; })()
""",
)
Completion record
- [ ] Every implementation/configuration and required asset shown above is present at its displayed path.
- [ ] Cross-chapter imports resolve against the intended contracts and platform source sets.
- [ ] The tests for this chapter pass in the rebuilt app; record the command, platform and result.
- [ ] Native, device, browser and live-service checks have evidence or an explicit “not run” entry. [chapter-content-end]: #
Gate: identical source requests work with a fake transport across platforms; a solved challenge retries once according to policy; no credentials cross profiles or leak into unrelated services; all client/engine/background jobs terminate on retirement.