senbei-1.0.0: src/Senbei.hs
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module: Senbei
-- Description: A safe HTTP cookie library.
-- Copyright: (c) ix, 2026
-- Maintainer: rose@empty.town
-- Stability: Stable
-- License: MIT
module Senbei
( CookieDomain
, CookieName
, CookieOctet
, CookiePath
, CookieSettings (..)
, defaultCookieSettings
, DictFor
, ExpiryError (..)
, Expiry (Expires, Session)
, mkMaxAge
, HasCookie (..)
, NonEmptyRestrictedText
, mkNonEmptyRestrictedText
, fromNonEmptyRestrictedText
, Partitioning (..)
, RestrictedText
, mkRestrictedText
, fromRestrictedText
, RestrictedTextError (..)
, SameSite (..)
, Security (..)
, FindCookieError (..)
, findCookieByName
, toSetCookie
, toSetCookieWithDefaults
, simpleSetCookie
, simpleSetCookieWithDefaults
, SerializeCookieError (..)
)
where
import Data.Bifunctor (first)
import Data.Bool
import Data.List
import Data.Maybe
import Data.Proxy
import Data.Text (Text)
import Data.Time
import GHC.TypeLits
import Data.ByteString qualified as BS
import Data.Text qualified as T
import Data.Text.Encoding qualified as T
{-# INLINEABLE MAX_COOKIE_LENGTH_BYTES #-}
pattern MAX_COOKIE_LENGTH_BYTES :: Int
pattern MAX_COOKIE_LENGTH_BYTES = 4096
-- | RestrictedText, which is some Text tied to a phantom dictionary
-- type denoting the characters allowable within.
newtype RestrictedText (dict :: Symbol)
= MkRestrictedText {unRestrictedText :: Text}
deriving newtype (Eq, Show)
-- | Deconstruct RestrictedText, producing a plain Text.
fromRestrictedText :: RestrictedText dict -> Text
fromRestrictedText = unRestrictedText
-- | A variant of RestrictedText which must be non-empty at construction.
newtype NonEmptyRestrictedText (dict :: Symbol)
= MkNonEmptyRestrictedText {unNonEmptyRestrictedText :: RestrictedText dict}
deriving newtype (Eq, Show)
-- | Deconstruct NonEmptyRestrictedText, producing a plain Text.
fromNonEmptyRestrictedText :: NonEmptyRestrictedText dict -> Text
fromNonEmptyRestrictedText = unRestrictedText . unNonEmptyRestrictedText
-- | Errors that arise when constructing RestrictedText or NonEmptyRestrictedText.
data RestrictedTextError = Empty | InvalidChar Char
deriving (Eq, Show)
-- | Attempt to construct a NonEmptyRestrictedText from some Text.
-- If the string is empty or contains a character disallowed by the dictionary,
-- then a RestrictedTextError will be returned as the Left variant of Either.
mkNonEmptyRestrictedText ::
forall dict.
KnownSymbol dict =>
Text
-> Either RestrictedTextError (NonEmptyRestrictedText dict)
mkNonEmptyRestrictedText t
| T.null t = Left Empty
| otherwise = MkNonEmptyRestrictedText <$> mkRestrictedText t
-- | Attempt to construct a RestrictedText from some Text.
-- If the string contains a character disallowed by the dictionary,
-- then a RestrictedTextError will be returned as the Left variant of Either.
{-# INLINEABLE mkRestrictedText #-}
mkRestrictedText ::
forall dict.
KnownSymbol dict =>
Text
-> Either RestrictedTextError (RestrictedText dict)
mkRestrictedText t = case T.find (not . isAccepted) t of
Nothing -> Right $ MkRestrictedText t
Just unacceptable -> Left $ InvalidChar unacceptable
where
dictionary :: [Char]
dictionary = symbolVal (Proxy @dict)
isAccepted :: Char -> Bool
isAccepted = (`elem` dictionary)
-- | Errors that arise while serializing a value as a cookie.
data SerializeCookieError = SizeLimitExceeded | InvalidValue RestrictedTextError
deriving (Eq, Show)
-- | Errors that arise while trying to locate a cookie in a cookie string.
data FindCookieError = CookieMissing | CookieUnparseable Text
deriving (Eq, Show)
-- | Errors that arise when attempting to construct an Expiry value.
data ExpiryError = NegativeMaxAge Integer
deriving (Eq, Show)
-- | Values for the Expiry and MaxAge attributes of a cookie.
data Expiry = Expires UTCTime | MaxAge Integer | Session
deriving (Eq, Show)
-- | Max-Age must be >= 0, so this smart constructor is used to construct it.
mkMaxAge :: Integer -> Either ExpiryError Expiry
mkMaxAge delta
| delta < 0 = Left $ NegativeMaxAge delta
| otherwise = Right $ MaxAge delta
-- | The Secure attribute, or lack of it.
data Security = Secure | Insecure
deriving (Eq, Show)
-- | The Partitioned attribute, or lack of it.
-- Practically speaking, this is set only on cookies SameSite=None.
-- Since Secure is forced on SameSite=None cookies, that will be present too.
data Partitioning = Partitioned | Unpartitioned
deriving (Eq, Show)
-- | The SameSite attribute.
-- 'None' must be used with the 'Secure' attribute, so it's set automatically.
data SameSite = Lax Security | Strict Security | None Partitioning
deriving (Eq, Show)
type CookieOctetDict =
"!#$%&'()*+-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~"
-- | An abstraction over Text for handling cookie values, or octets.
-- See [RFC6265](https://www.rfc-editor.org/info/rfc6265/#page-9).
type CookieOctet = RestrictedText CookieOctetDict
type CookiePathDict =
"!\"#$%&'()*+,-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
-- | An abstraction over Text for handling the Path attribute.
-- See [RFC6265](https://www.rfc-editor.org/info/rfc6265/#page-9).
type CookiePath = NonEmptyRestrictedText CookiePathDict
type CookieNameDict =
"!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
-- | An abstraction over Text for handling cookie names.
-- See [RFC9110](https://www.rfc-editor.org/info/rfc9110/#section-5.6.2).
type CookieName = NonEmptyRestrictedText CookieNameDict
type CookieDomainDict =
"-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
-- | An abstraction over Text for handling cookie Domain attributes.
-- See [RFC1034](https://www.rfc-editor.org/info/rfc1034/#page-11).
type CookieDomain = NonEmptyRestrictedText CookieDomainDict
-- | An open type family that associates types with their dictionary symbols.
type family DictFor t :: Symbol
type instance DictFor CookieDomain = CookieDomainDict
type instance DictFor CookieName = CookieNameDict
type instance DictFor CookieOctet = CookieOctetDict
type instance DictFor CookiePath = CookiePathDict
-- | Settings (attributes) to be used when serializing a cookie.
data CookieSettings = MkCookieSettings
{ cookieDomain :: Maybe CookieDomain
-- ^ The domain to which the cookie applies.
, cookiePath :: Maybe CookiePath
-- ^ The path to which the cookie applies.
, cookieExpiry :: Expiry
-- ^ The expiry - or max age - of the cookie.
, cookieHttpOnly :: Bool
-- ^ Whether JavaScript is able to access the cookie.
, cookieSameSite :: SameSite
-- ^ The SameSite policy for the cookie.
}
deriving (Eq, Show)
-- | Sensible defaults for CookieSettings.
defaultCookieSettings :: CookieSettings
defaultCookieSettings =
MkCookieSettings
{ cookieDomain = Nothing
, cookiePath = Nothing
, cookieExpiry = Session
, cookieHttpOnly = True
, cookieSameSite = Lax Secure
}
-- | A class encoding how to serialize and deserialize a type as a cookie value.
class HasCookie t where
toCookieValue :: t -> Text
fromCookieValue :: Text -> Either Text t
-- | The time format used in Expiry attributes.
-- [MDN source](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Date).
cookieTimeFormat :: String
cookieTimeFormat = "%a, %d %b %0Y %H:%M:%S GMT"
-- | Given CookieSettings, attempt to serialize a type t to a cookie.
-- If this fails, then SerializeCookieError is returned.
--
-- This is the verbose form of this function, it expects the user to
-- provide explicit settings and a validated CookieName.
--
-- For a more friendly alternative, consider simpleSetCookie or simpleSetCookieWithDefaults.
toSetCookie ::
HasCookie t =>
CookieSettings -> CookieName -> t -> Either SerializeCookieError Text
toSetCookie MkCookieSettings {..} name value = do
octet <-
first InvalidValue $ mkRestrictedText @CookieOctetDict (toCookieValue value)
let expiry = case cookieExpiry of
MaxAge d -> Just $ mconcat ["Max-Age=", T.show d]
Expires t ->
Just
$ mconcat ["Expires=", T.pack $ formatTime defaultTimeLocale cookieTimeFormat t]
Session -> Nothing
sameSite =
Just
$ mconcat
[ "SameSite="
, case cookieSameSite of
Strict _ -> "Strict"
Lax _ -> "Lax"
None _ -> "None"
]
secure = case cookieSameSite of
Lax Secure -> Just "Secure"
Strict Secure -> Just "Secure"
None _ -> Just "Secure"
_ -> Nothing
partitioned = case cookieSameSite of
None Partitioned -> Just "Partitioned"
_ -> Nothing
let serialized =
T.intercalate "; "
$ catMaybes
[ Just $ mconcat [fromNonEmptyRestrictedText name, "=", fromRestrictedText octet]
, fmap
(\domain -> mconcat ["Domain=", fromNonEmptyRestrictedText domain])
cookieDomain
, fmap (\path -> mconcat ["Path=", fromNonEmptyRestrictedText path]) cookiePath
, expiry
, bool Nothing (Just "HttpOnly") cookieHttpOnly
, sameSite
, secure
, partitioned
]
if BS.length (T.encodeUtf8 serialized) > MAX_COOKIE_LENGTH_BYTES then
Left SizeLimitExceeded
else
Right serialized
-- | A variant of toSetCookie that uses defaultCookieSettings.
toSetCookieWithDefaults ::
HasCookie t => CookieName -> t -> Either SerializeCookieError Text
toSetCookieWithDefaults = toSetCookie defaultCookieSettings
-- | A variant of toSetCookie that accepts CookieSettings but performs validation of the Text
-- given to it as a cookie name as opposed to expecting it to be done beforehand.
simpleSetCookie ::
HasCookie t => CookieSettings -> Text -> t -> Either SerializeCookieError Text
simpleSetCookie settings rawName value =
either (Left . InvalidValue) (\name -> toSetCookie settings name value)
$ mkNonEmptyRestrictedText rawName
-- | A variant of toSetCookie that is the most permissive. It uses defaultCookieSettings
-- and accepts Text as the cookie name instead of requiring it to be validated upfront.
simpleSetCookieWithDefaults ::
HasCookie t => Text -> t -> Either SerializeCookieError Text
simpleSetCookieWithDefaults = simpleSetCookie defaultCookieSettings
-- | Attempt to parse out a type t from a cookie string (by name).
findCookieByName ::
HasCookie t => CookieName -> Text -> Either FindCookieError t
findCookieByName (fromNonEmptyRestrictedText -> name) cookies =
case find ((== name) . fst) pairs of
Nothing -> Left CookieMissing
Just (_, v) -> first CookieUnparseable $ fromCookieValue v
where
sanitize :: (Text, Text) -> (Text, Text)
sanitize (k, v) = (T.strip k, T.strip $ T.drop 1 v)
pairs :: [(Text, Text)]
pairs =
map (sanitize . T.span (/= '='))
$ T.splitOn ";" cookies