scoop:scoop.http:0.1.0
src/cookie/rules.scoop
Selected production source · src/cookie/rules.scoop
1
package scoop.http3
import scoop.text.*4
import scoop.url.UrlHost5
import scoop.url.UrlOrigin7
/**8
* Pure helpers for schemeful site, domain, and cookie-path matching.9
*/10
public object HttpCookieRules {11
/**12
* Compares schemeful registrable domains using the suffix list; ws/wss map to http/https13
* respectively.14
*/15
public fun sameSite(first: UrlOrigin, second: UrlOrigin, suffixes: PublicSuffixList): Boolean {16
if (cookieSiteScheme(first.scheme) != cookieSiteScheme(second.scheme)) return false17
if (first.host == second.host) return true18
val left = suffixes.lookup(first) ?: return false19
val right = suffixes.lookup(second) ?: return false20
return (left.registrableDomain ?: left.domain) == (right.registrableDomain ?: right.domain)21
}23
/**24
* Checks an exact host or DNS suffix at a label boundary; IP hosts require exact equality.25
*/26
public fun domainMatches(host: UrlHost, domain: UrlHost): Boolean = when (host) {27
case Dns(val name) -> when (domain) {28
case Dns(val suffix) -> name == suffix || name.endsWith("." + suffix)29
else -> false30
}31
case Ipv4(_) -> host == domain32
case Ipv6(_) -> host == domain33
}35
/**36
* Derives the cookie default path from the request's encoded path, falling back to /.37
*/38
public fun defaultPath(encodedPath: List<Byte>): Array<Byte> {39
if (encodedPath.size == 0L || encodedPath[0L] != 47.toByte()) return "/".toByteArray()40
var last = 0L41
for (index in 1L..<encodedPath.size) if (encodedPath[index] == 47.toByte()) last = index42
if (last == 0L) return "/".toByteArray()43
return Array<Byte>(last) { index -> encodedPath[index] }44
}45
/**46
* Derives the cookie default path from the request's encoded path, falling back to /.47
*/48
public fun defaultPath(encodedPath: String): Array<Byte> = defaultPath(encodedPath.toByteArray())50
/**51
* Compares encoded paths with cookie slash-boundary semantics, without percent decoding.52
*/53
public fun pathMatches(requestPath: List<Byte>, cookiePath: List<Byte>): Boolean {54
if (cookiePath.size == 0L || requestPath.size < cookiePath.size) return false55
for (index in 0L..<cookiePath.size) if (requestPath[index] != cookiePath[index]) return false56
return requestPath.size == cookiePath.size || cookiePath[cookiePath.size - 1L] == 47.toByte() ||57
requestPath[cookiePath.size] == 47.toByte()58
}59
/**60
* Compares encoded paths with cookie slash-boundary semantics, without percent decoding.61
*/62
public fun pathMatches(requestPath: String, cookiePath: String): Boolean = pathMatches(requestPath.toByteArray(), cookiePath.toByteArray())63
}65
internal fun secureCookieScheme(scheme: String): Boolean = scheme == "https" || scheme == "wss"67
private fun cookieSiteScheme(scheme: String): String = when (scheme) {68
case "ws" -> "http"69
case "wss" -> "https"70
else -> scheme71
}