Scoop API

scoop:scoop.http:0.1.0

src/cookie/rules.scoop

Selected production source · src/cookie/rules.scoop

1package scoop.http
3import scoop.text.*
4import scoop.url.UrlHost
5import scoop.url.UrlOrigin
7/**
8 * Pure helpers for schemeful site, domain, and cookie-path matching.
9 */
10public object HttpCookieRules {
11 /**
12 * Compares schemeful registrable domains using the suffix list; ws/wss map to http/https
13 * respectively.
14 */
15 public fun sameSite(first: UrlOrigin, second: UrlOrigin, suffixes: PublicSuffixList): Boolean {
16 if (cookieSiteScheme(first.scheme) != cookieSiteScheme(second.scheme)) return false
17 if (first.host == second.host) return true
18 val left = suffixes.lookup(first) ?: return false
19 val right = suffixes.lookup(second) ?: return false
20 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 -> false
30 }
31 case Ipv4(_) -> host == domain
32 case Ipv6(_) -> host == domain
33 }
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 = 0L
41 for (index in 1L..<encodedPath.size) if (encodedPath[index] == 47.toByte()) last = index
42 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 false
55 for (index in 0L..<cookiePath.size) if (requestPath[index] != cookiePath[index]) return false
56 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())
65internal fun secureCookieScheme(scheme: String): Boolean = scheme == "https" || scheme == "wss"
67private fun cookieSiteScheme(scheme: String): String = when (scheme) {
68 case "ws" -> "http"
69 case "wss" -> "https"
70 else -> scheme