Yokan / rebuild
Course 1 8624561

CookieJar.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/cookies/CookieJar.kt

implementation307 lines
1package eu.friedcutlet.yokan.services.http.cookies23import eu.friedcutlet.yokan.database.DbCookie4import eu.friedcutlet.yokan.database.YokanDatabase5import eu.friedcutlet.yokan.domain.ProfileId6import eu.friedcutlet.yokan.util.PlatformLock7import eu.friedcutlet.yokan.services.http.EnhancedHttpService8import eu.friedcutlet.yokan.util.nowMillis910/**11 * Persistent cookie jar. Backed by `DbSettings.cookiesList`.12 *13 * Each [DbCookie] row stores a single host (`host-only`) or registered domain14 * (`subdomain-match`) and a rendered `name=value; name2=value2; …` string for15 * fast injection into outgoing requests. Attribute metadata (`Domain`, `Path`,16 * `Expires`, `Max-Age`, `Secure`, `HttpOnly`) is encoded into a sibling JSON17 * sidecar so we can drop expired cookies and respect subdomain matching18 * without parsing the cookie name/value blob each request.19 *20 * The sidecar is stashed inside the same `DbCookie.cookie` field with a sentinel21 * suffix (` |meta=<json>`) so adding it doesn't require a schema migration. If22 * the sidecar is missing — which is the case for jars persisted by an earlier23 * Yokan build — the jar treats the row as a session-only host-bound cookie.24 *25 * The jar is intentionally synchronous: it never blocks on network IO, only on26 * the lightweight `database.updateSettings(…)` write that the rest of the app27 * already routes through.28 */29class CookieJar(30    private val database: YokanDatabase,31    val profileId: ProfileId = ProfileId.Default,32    private val isOpen: () -> Boolean = { true },33) {34    private val lock = PlatformLock()35    private var sessionUserAgents: Map<String, String> = emptyMap()3637    val isAvailable: Boolean get() = lock.withLock { isOpen() }3839    /** Native/browser stores: Default uses the platform's shared store; extras need a per-profile platform store. */40    val canUseBrowserStorage: Boolean41        get() = lock.withLock { isOpen() && (profileId == ProfileId.Default || platformBrowserIsolation) }4243    fun rememberUserAgent(url: String, userAgent: String) = whileOpen(Unit) { storeUserAgent(url, userAgent) }44    fun userAgent(url: String): String? = whileOpen(null) { lookupUserAgent(url) }45    fun cookieHeader(url: String): String? = whileOpen(null) { buildCookieHeader(url) }46    fun setFromResponse(url: String, rawSetCookies: List<String>) = whileOpen(Unit) { persistResponseCookies(url, rawSetCookies) }47    fun put(host: String, cookieString: String) = whileOpen(Unit) { persistCookieHeader(host, cookieString) }48    fun rawCookieFor(host: String): String? = whileOpen(null) { lookupRawCookie(host) }49    fun clear(host: String? = null) = whileOpen(Unit) { clearCookies(host) }5051    private fun <T> whileOpen(fallback: T, action: () -> T): T = lock.withLock {52        if (isOpen()) action() else fallback53    }5455    private fun storeUserAgent(url: String, userAgent: String) {56        val host = parseHost(url) ?: return57        if (userAgent.isBlank()) return58        sessionUserAgents = sessionUserAgents + (host to userAgent)59    }6061    private fun lookupUserAgent(url: String): String? {62        val host = parseHost(url) ?: return null63        return sessionUserAgents.entries64            .filter { (domain) -> host == domain || host.endsWith(".$domain") }65            .maxByOrNull { (domain) -> domain.length }66            ?.value67    }6869    /**70     * Build a `Cookie: name=value; name2=value2; …` header for [url], merging71     * every persisted row whose domain matches the URL host. Returns null when72     * nothing applies so callers can decide whether to send no Cookie header73     * at all rather than send an empty one (some hosts treat the two74     * differently).75     */76    private fun buildCookieHeader(url: String): String? {77        val target = parseCookieRequest(url) ?: return null78        val rows = readRows()79        if (rows.isEmpty()) return null80        val now = nowMillis()81        val matching = rows.flatMap { row ->82            row.cookies.filter { cookie ->83                cookie.appliesTo(target.host, target.path, target.secure) && !cookie.isExpired(now)84            }85        }86        if (matching.isEmpty()) return null87        // Deduplicate by name (later entries win) so a Set-Cookie on a parent88        // domain doesn't shadow one set later on a subdomain.89        val byName = linkedMapOf<String, ParsedCookie>()90        matching.forEach { byName[it.name] = it }91        return byName.values.joinToString("; ") { "${it.name}=${it.value}" }92    }9394    /**95     * Persist a freshly-received list of `Set-Cookie` headers issued by [url].96     * Expired cookies in the list will displace any matching row, which is how97     * servers signal a logout (e.g. `Set-Cookie: SID=; Max-Age=0`).98     */99    private fun persistResponseCookies(url: String, rawSetCookies: List<String>) {100        if (rawSetCookies.isEmpty()) return101        val host = parseHost(url) ?: return102        val parsed = rawSetCookies.mapNotNull { parseSetCookie(it, host) }103        if (parsed.isEmpty()) return104        val rows = readRows().associateBy { it.host }.toMutableMap()105        for (cookie in parsed) {106            val row = rows[cookie.domain] ?: HostRow(cookie.domain, mutableListOf())107            val rebuilt = row.cookies.filterNot { it.name == cookie.name && it.domain == cookie.domain && it.path == cookie.path }108                .toMutableList()109            if (!cookie.isExpired()) rebuilt += cookie110            if (rebuilt.isEmpty()) rows.remove(cookie.domain)111            else rows[cookie.domain] = HostRow(cookie.domain, rebuilt)112        }113        writeRows(rows.values.toList())114    }115116    /**117     * Explicitly seed the jar from a `name=value; name2=value2; …` string —118     * used when the user pastes in a cookie from an external session, or when119     * a tracker callback hands one back. Domain defaults to [host] and the120     * cookies are host-only.121     */122    private fun persistCookieHeader(host: String, cookieString: String) {123        if (cookieString.isBlank()) return124        val normalisedHost = host.lowercase()125        val cookies = cookieString.split(';').mapNotNull { entry ->126            val trimmed = entry.trim()127            val eq = trimmed.indexOf('=')128            if (eq <= 0) return@mapNotNull null129            ParsedCookie(130                name = trimmed.substring(0, eq).trim(),131                value = trimmed.substring(eq + 1).trim(),132                domain = normalisedHost,133                path = "/",134                hostOnly = true,135                expiresAt = null,136                secure = false,137                httpOnly = false,138            )139        }140        if (cookies.isEmpty()) return141        val rows = readRows().associateBy { it.host }.toMutableMap()142        val row = rows[normalisedHost] ?: HostRow(normalisedHost, mutableListOf())143        val rebuilt = row.cookies.filterNot { c -> cookies.any { it.name == c.name } }.toMutableList()144        rebuilt += cookies145        rows[normalisedHost] = HostRow(normalisedHost, rebuilt)146        writeRows(rows.values.toList())147    }148149    /**150     * Lookup the persisted cookie string for [host] exactly — useful for code151     * paths (e.g. the WebView bridge or the QuarkUc extractor) that want the152     * legacy "render whatever cookie was stored on this host" semantic without153     * subdomain matching.154     */155    private fun lookupRawCookie(host: String): String? {156        val target = host.lowercase()157        val now = nowMillis()158        val cookies = readRows()159            .firstOrNull { it.host == target }160            ?.cookies161            ?.filter { !it.isExpired(now) }162            ?: return null163        if (cookies.isEmpty()) return null164        return cookies.joinToString("; ") { "${it.name}=${it.value}" }165    }166167    /** Wipe the jar (no argument) or just one host. */168    private fun clearCookies(host: String?) {169        if (host == null) {170            sessionUserAgents = emptyMap()171            val settings = database.settings()172            database.updateSettings(settings.copy(cookiesList = emptyList()))173            return174        }175        val target = host.lowercase()176        sessionUserAgents = sessionUserAgents - target177        val rows = readRows().filterNot { it.host == target }178        writeRows(rows)179    }180181    // ─────────────────────────────────────────────────────────────────────────182    // Storage internals183184    private data class HostRow(val host: String, val cookies: List<ParsedCookie>)185186    private fun readRows(): List<HostRow> {187        val raw = database.settings().cookiesList.orEmpty()188        return raw.mapNotNull { row ->189            val host = row.host?.lowercase() ?: return@mapNotNull null190            val cookies = decode(host, row.cookie.orEmpty()) ?: return@mapNotNull null191            HostRow(host, cookies)192        }193    }194195    private fun writeRows(rows: List<HostRow>) {196        val settings = database.settings()197        val encoded = rows.mapNotNull { row ->198            if (row.cookies.isEmpty()) return@mapNotNull null199            DbCookie(host = row.host, cookie = encode(row.cookies))200        }201        database.updateSettings(settings.copy(cookiesList = encoded))202    }203204    /**205     * Encode a list of cookies into the persistent string format:206     * `name=value; name=value | meta=<json>`. The `| meta=` sentinel keeps the207     * left half compatible with the old EnhancedHttpService format so a208     * downgrade can still ship a Cookie header (it just loses attributes).209     */210    private fun encode(cookies: List<ParsedCookie>): String {211        val pairs = cookies.joinToString("; ") { "${it.name}=${it.value}" }212        val meta = encodeMeta(cookies)213        return if (meta.isBlank()) pairs else "$pairs $META_SEPARATOR$meta"214    }215216    private fun decode(host: String, raw: String): List<ParsedCookie>? {217        if (raw.isBlank()) return emptyList()218        val sepIndex = raw.lastIndexOf(META_SEPARATOR)219        val pairsPart = if (sepIndex < 0) raw else raw.substring(0, sepIndex).trimEnd()220        val metaPart = if (sepIndex < 0) null else raw.substring(sepIndex + META_SEPARATOR.length).trim()221        val pairs = pairsPart.split(';').mapNotNull { entry ->222            val trimmed = entry.trim()223            val eq = trimmed.indexOf('=')224            if (eq <= 0) return@mapNotNull null225            trimmed.substring(0, eq).trim() to trimmed.substring(eq + 1).trim()226        }227        val meta = metaPart?.let(::decodeMeta).orEmpty()228        return pairs.map { (name, value) ->229            val m = meta[name]230            ParsedCookie(231                name = name,232                value = value,233                domain = m?.domain ?: host,234                path = m?.path ?: "/",235                hostOnly = m?.hostOnly ?: true,236                expiresAt = m?.expiresAt,237                secure = m?.secure ?: false,238                httpOnly = m?.httpOnly ?: false,239            )240        }241    }242243    private data class StoredMeta(244        val domain: String,245        val path: String,246        val hostOnly: Boolean,247        val expiresAt: Long?,248        val secure: Boolean,249        val httpOnly: Boolean,250    )251252    private fun encodeMeta(cookies: List<ParsedCookie>): String {253        val entries = cookies.joinToString(",") { c ->254            // name=value attributes are already in the legacy half; encode only the255            // metadata fields we need to honour on the next request.256            val expires = c.expiresAt?.toString().orEmpty()257            "${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"}"258        }259        return entries260    }261262    private fun decodeMeta(raw: String): Map<String, StoredMeta> {263        if (raw.isEmpty()) return emptyMap()264        return raw.split(',').mapNotNull { entry ->265            val parts = entry.split('|')266            if (parts.size < 7) return@mapNotNull null267            val name = parts[0].unescapeMeta()268            name to StoredMeta(269                domain = parts[1].unescapeMeta(),270                path = parts[2].unescapeMeta(),271                hostOnly = parts[3] == "1",272                expiresAt = parts[4].toLongOrNull(),273                secure = parts[5] == "1",274                httpOnly = parts[6] == "1",275            )276        }.toMap()277    }278279    private fun String.escapeMeta(): String = replace("\\", "\\\\").replace("|", "\\1").replace(",", "\\2")280    private fun String.unescapeMeta(): String = replace("\\2", ",").replace("\\1", "|").replace("\\\\", "\\")281282    private companion object {283        const val META_SEPARATOR = "|meta="284    }285}286287/** Whether this platform can give each extra profile its own isolated browser cookie/data store. */288internal expect val platformBrowserIsolation: Boolean289290/** Strip scheme + path + port off a URL to leave only the lowercase host. */291internal fun parseHost(url: String): String? {292    val noProtocol = url.substringAfter("://", url)293    val hostEnd = noProtocol.indexOfFirst { it == '/' || it == '?' || it == '#' }294    val hostPort = if (hostEnd == -1) noProtocol else noProtocol.substring(0, hostEnd)295    if (hostPort.isBlank()) return null296    return hostPort.substringBefore(':').lowercase()297}298299private data class CookieRequest(val host: String, val path: String, val secure: Boolean)300301private fun parseCookieRequest(url: String): CookieRequest? {302    val host = parseHost(url) ?: return null303    val scheme = url.substringBefore("://", "").lowercase()304    val afterAuthority = url.substringAfter("://", url).substringAfter('/', "")305    val path = if (afterAuthority.isEmpty()) "/" else "/" + afterAuthority.substringBefore('?').substringBefore('#')306    return CookieRequest(host = host, path = path, secure = scheme == "https")307}308

Search chapters, reference and source filenames.