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=`) 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 = 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) = 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 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() 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) { 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) private fun readRows(): List { 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) { 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=`. 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): 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? { 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): 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 { 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") }