Module: Cybertrain::Cookies

Defined in:
cybertrain/http/cookies.rb

Overview

Cookie header parsing and Set-Cookie serialization. Values round-trip through the same www-form percent-encoding Query uses, so a value with a space, “=” or “;” survives both directions. Unlike a query string, a cookie that does not decode is NOT a client fault: SessionStore parses every cookie on every request but reads only its own, so a foreign one (“promo=50%off”, set by another app on the parent domain) must not turn every dynamic page into a 400. Its raw value is kept, as Rack does.

In a controller, cookies (Controller#cookies, a CookieJar) is the way to read and write cookies, signed and encrypted ones included; it writes through Cookies.serialize and Response#replace_cookie. This module is the layer under it, for middleware and code without a controller.

Examples:

theme = Cybertrain::Cookies.parse(request.cookie_header)["theme"]
response.add_cookie(Cybertrain::Cookies.serialize("theme", "dark", max_age: 31_536_000))
response.add_cookie(Cybertrain::Cookies.serialize("theme", "", max_age: 0))   # delete

Class Method Summary collapse

Class Method Details

.parse(header) ⇒ Hash{String => String}

The cookies in a Cookie header, values decoded. The first of two cookies with one name wins.

Parameters:

Returns:

  • (Hash{String => String})


49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'cybertrain/http/cookies.rb', line 49

def self.parse(header)
  cookies = {}
  header.to_s.split(";").each do |pair|
    trimmed = pair.strip
    next if trimmed.empty?

    eq = trimmed.index("=")
    next if eq.nil?

    name = trimmed[0, eq]
    next if cookies.key?(name)

    value = trimmed[(eq + 1)..-1].to_s
    cookies[name] = decode(value)
  end
  cookies
end

.serialize(name, value, path: "/", max_age: -1,, http_only: true, same_site: "Lax", secure: false, partitioned: false, expires: NO_EXPIRES) ⇒ String

A Set-Cookie value for Response#add_cookie, the value percent-encoded. same_site "None" and partitioned both require Secure (browsers drop such a cookie without it), so either adds Secure whatever secure says, and Secure is written once.

Parameters:

  • name (String)
  • value (String)
  • path (String) (defaults to: "/")
  • max_age (Integer) (defaults to: -1,) —

    seconds; -1 leaves it out (a browser-session cookie), 0 deletes the cookie

  • http_only (Boolean) (defaults to: true)
  • same_site (String) (defaults to: "Lax") —

    "Lax", "Strict" or "None"

  • secure (Boolean) (defaults to: false)
  • partitioned (Boolean) (defaults to: false) —

    adds Partitioned (and Secure)

  • expires (Time, nil) (defaults to: NO_EXPIRES) —

    adds Expires= with the time as an HTTP date (Request.http_date); nil (or leaving it out) writes none

Returns:

  • (String)

Raises:

  • (ArgumentError) —

    name is not an RFC 6265 token, path holds “;”, CR or LF, or same_site is not Lax, Strict or None (any case)



156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'cybertrain/http/cookies.rb', line 156

def self.serialize(name, value, path: "/", max_age: -1, http_only: true, same_site: "Lax", secure: false,
                   partitioned: false, expires: NO_EXPIRES)
  Cookies.validate!(name, path, same_site)
  # value.to_s: a String for Query.plain?'s byte reads (see Html.escape)
  out = +"#{name}=#{Cookies.encoded_value(value.to_s)}"
  out << "; Path=#{path}"
  out << "; HttpOnly" if http_only
  out << "; SameSite=#{same_site}"
  out << "; Max-Age=#{max_age}" if max_age >= 0
  out << "; Expires=#{Request.http_date(expires)}" unless expires.nil? || expires.to_i == NO_EXPIRES_EPOCH
  out << "; Secure" if secure || partitioned || same_site.downcase == "none"
  out << "; Partitioned" if partitioned
  out
end

.token?(name) ⇒ Boolean

Whether name is an RFC 6265 token: one or more visible ASCII characters (0x21-0x7e) that are not separators.

Parameters:

  • name (String)

Returns:

  • (Boolean)


76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'cybertrain/http/cookies.rb', line 76

def self.token?(name)
  text = name.to_s # a fresh local for the byte reads (NOTES rule 62)
  return false if text.empty?

  i = 0
  n = text.bytesize
  while i < n
    b = text.getbyte(i)
    return false if b <= 32 || b >= 127
    return false if NAME_SEPARATORS.include?(text.byteslice(i, 1).to_s)

    i += 1
  end
  true
end