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)