Yokan / rebuild
Course 1 8624561

CookieParser.kt

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

implementation213 lines
1package eu.friedcutlet.yokan.services.http.cookies23import eu.friedcutlet.yokan.util.nowMillis45/**6 * Parsed cookie record. Domain matching follows RFC 6265 §5.1.3: if the cookie7 * was issued with an explicit `Domain=`, that's used (with any leading dot8 * stripped) and the cookie applies to that host and any subdomain. With no9 * explicit `Domain`, the cookie is host-only and only matches the request host10 * exactly.11 */12internal data class ParsedCookie(13    val name: String,14    val value: String,15    val domain: String,16    val path: String,17    val hostOnly: Boolean,18    val expiresAt: Long?,19    val secure: Boolean,20    val httpOnly: Boolean,21)2223/**24 * Parse a single `Set-Cookie` header value as it appeared on the wire. Returns25 * null when the input has no `name=value` part. Unknown attributes are26 * ignored (Same-Site, Priority, etc.).27 *28 * Date attributes are parsed loosely — `Expires=` headers historically ship in29 * three different formats; we accept RFC 1123 (`Mon, 02 Jan 2006 15:04:05 GMT`),30 * RFC 850 (`Monday, 02-Jan-06 …`), and the Cookie Working Group's seven-token31 * variant. Anything we can't parse becomes a session cookie (no expiry).32 */33internal fun parseSetCookie(raw: String, requestHost: String): ParsedCookie? {34    val trimmed = raw.trim()35    if (trimmed.isEmpty()) return null36    val attrs = trimmed.split(';').map { it.trim() }.filter { it.isNotEmpty() }37    val pair = attrs.firstOrNull() ?: return null38    val nameEnd = pair.indexOf('=')39    if (nameEnd <= 0) return null40    val name = pair.substring(0, nameEnd).trim()41    val value = pair.substring(nameEnd + 1).trim()42    if (name.isEmpty()) return null4344    var domain = requestHost45    var hostOnly = true46    var path = "/"47    var expiresAt: Long? = null48    var maxAgeMillis: Long? = null49    var secure = false50    var httpOnly = false5152    for (attr in attrs.drop(1)) {53        val eq = attr.indexOf('=')54        val key = if (eq < 0) attr else attr.substring(0, eq)55        val attrValue = if (eq < 0) "" else attr.substring(eq + 1).trim()56        when (key.lowercase()) {57            "domain" -> {58                val v = attrValue.removePrefix(".").lowercase()59                if (v.isEmpty() || (requestHost != v && !requestHost.endsWith(".$v"))) return null60                domain = v61                hostOnly = false62            }63            "path" -> if (attrValue.isNotEmpty()) path = attrValue64            "expires" -> expiresAt = runCatching { parseCookieDate(attrValue) }.getOrNull()65            "max-age" -> {66                val seconds = attrValue.toLongOrNull()67                if (seconds != null) {68                    maxAgeMillis = if (seconds <= 0) -1L else seconds * 1_000L69                }70            }71            "secure" -> secure = true72            "httponly" -> httpOnly = true73        }74    }75    // RFC 6265: Max-Age trumps Expires when both are present.76    val finalExpiresAt = when {77        maxAgeMillis != null -> if (maxAgeMillis < 0) 0L else nowMillis() + maxAgeMillis78        else -> expiresAt79    }80    return ParsedCookie(81        name = name,82        value = value,83        domain = domain,84        path = path,85        hostOnly = hostOnly,86        expiresAt = finalExpiresAt,87        secure = secure,88        httpOnly = httpOnly,89    )90}9192/** Does this cookie's domain, path, and Secure flag match the request target? */93internal fun ParsedCookie.appliesTo(host: String, requestPath: String, requestSecure: Boolean): Boolean {94    val target = host.lowercase()95    val domainMatches = if (hostOnly) {96        target == domain97    } else {98        target == domain || target.endsWith(".$domain")99    }100    if (!domainMatches || (secure && !requestSecure)) return false101    val normalizedCookiePath = path.takeIf { it.startsWith('/') } ?: "/"102    if (!requestPath.startsWith(normalizedCookiePath)) return false103    return requestPath.length == normalizedCookiePath.length ||104        normalizedCookiePath.endsWith('/') ||105        requestPath.getOrNull(normalizedCookiePath.length) == '/'106}107108/** Cookie is expired or signalled for deletion. */109internal fun ParsedCookie.isExpired(now: Long = nowMillis()): Boolean =110    expiresAt != null && expiresAt <= now111112/**113 * Parse an HTTP cookie date — we accept the three common shapes plus the114 * Cookie Working Group's seven-token variant. Returns null when we can't115 * extract day/month/year/hour/min/sec.116 */117private fun parseCookieDate(input: String): Long? {118    val raw = input.replace(',', ' ').trim()119    if (raw.isEmpty()) return null120    val tokens = raw.split(Regex("\\s+"))121    var day = -1122    var month = -1123    var year = -1124    var hour = -1125    var minute = -1126    var second = -1127    for (token in tokens) {128        // dd-MMM-yy / dd-MMM-yyyy style ships month + day + year glued together.129        if (token.contains('-')) {130            val parts = token.split('-')131            if (parts.size == 3) {132                val maybeDay = parts[0].toIntOrNull()133                val maybeMonth = monthIndex(parts[1])134                val maybeYear = parts[2].toIntOrNull()135                if (maybeDay != null && maybeMonth >= 0 && maybeYear != null) {136                    day = maybeDay; month = maybeMonth; year = maybeYear137                    continue138                }139            }140        }141        // HH:MM:SS142        if (token.contains(':')) {143            val parts = token.split(':')144            if (parts.size >= 3) {145                hour = parts[0].toIntOrNull() ?: hour146                minute = parts[1].toIntOrNull() ?: minute147                second = parts[2].toIntOrNull() ?: second148                continue149            }150        }151        // Two-to-four digit numbers — day-of-month or year.152        token.toIntOrNull()?.let { n ->153            when {154                n in 1..31 && day < 0 -> day = n155                n in 1970..2099 && year < 0 -> year = n156                n in 0..99 && year < 0 -> year = if (n >= 70) 1900 + n else 2000 + n157            }158            return@let159        }160        // Three-letter month abbreviation.161        monthIndex(token).takeIf { it >= 0 }?.let { idx -> if (month < 0) month = idx }162    }163    if (day < 0 || month < 0 || year < 0 || hour < 0 || minute < 0 || second < 0) return null164    return epochUtcMillis(year, month, day, hour, minute, second)165}166167private fun monthIndex(token: String): Int {168    val s = token.lowercase()169    return when {170        s.startsWith("jan") -> 0171        s.startsWith("feb") -> 1172        s.startsWith("mar") -> 2173        s.startsWith("apr") -> 3174        s.startsWith("may") -> 4175        s.startsWith("jun") -> 5176        s.startsWith("jul") -> 6177        s.startsWith("aug") -> 7178        s.startsWith("sep") -> 8179        s.startsWith("oct") -> 9180        s.startsWith("nov") -> 10181        s.startsWith("dec") -> 11182        else -> -1183    }184}185186/**187 * Convert (year, monthIndex 0–11, day, hour, minute, second) at UTC to epoch188 * millis without a third-party date library. Handles leap years; doesn't189 * concern itself with leap seconds or sub-second precision.190 */191private fun epochUtcMillis(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): Long {192    require(month in 0..11)193    val y = year.toLong()194    val daysFromEpochToYearStart = run {195        // Counting from 1970-01-01.196        var d = 0L197        if (y >= 1970) {198            for (i in 1970 until y.toInt()) d += if (isLeap(i)) 366 else 365199        } else {200            for (i in (y.toInt()) until 1970) d -= if (isLeap(i)) 366 else 365201        }202        d203    }204    val monthDays = intArrayOf(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)205    if (isLeap(year)) monthDays[1] = 29206    var d = daysFromEpochToYearStart207    for (i in 0 until month) d += monthDays[i]208    d += (day - 1)209    val secondsOfDay = hour * 3600L + minute * 60L + second210    return d * 86_400L * 1_000L + secondsOfDay * 1_000L211}212213private fun isLeap(year: Int): Boolean = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0)214

Search chapters, reference and source filenames.