Auth.Csrf

Auth

Double-submit CSRF cookies for browser apps.

Issue a token on bootstrap (HTML or API), set it with setCookie (readable by JS when httpOnly = False), and have the client echo it in the configured request header (default x-csrf-token) on mutating requests. protect skips safe methods (GET / HEAD / OPTIONS).

Types

Config

type Config = Config { cookieName : String
, headerName : String
, attrs : { httpOnly : Bool
, secure : Bool
, path : String
, sameSite : String
, maxAge : Maybe Int
}
}

CSRF cookie configuration.

Examples

Auth.Csrf.config { cookieName = "_csrf" }

Error

type Error
= MissingToken
| Mismatch

Why CSRF verification failed.

Examples

Err Auth.Csrf.Mismatch

Values

config

config : { cookieName : String } -> Config

Build CSRF config. Default cookie attrs are Path=/, SameSite=Lax, **not** HttpOnly (so JS can mirror the value into a header).

Examples

csrf =
    Auth.Csrf.config { cookieName = "_csrf" }

withAttrs

withAttrs : { httpOnly : Bool , secure : Bool , path : String , sameSite : String , maxAge : Maybe Int } -> Config -> Config

Override cookie attributes.

Examples

Auth.Csrf.withAttrs { Cookies.defaults | secure = True, httpOnly = False } csrf

withHeaderName

withHeaderName : String -> Config -> Config

Override the request header name (default x-csrf-token).

Examples

Auth.Csrf.withHeaderName "x-xsrf-token" csrf

token

token : String

Mint a cryptographically random CSRF token.

Examples

let t = Auth.Csrf.token in
Auth.Csrf.setCookie csrf t

setCookie

setCookie : Config -> String -> Header

Set the CSRF cookie to value.

Examples

Auth.Csrf.setCookie csrf Auth.Csrf.token

verify

verify : Config -> Request -> Result Error ()

Compare the CSRF cookie to the request header.

Examples

Auth.Csrf.verify csrf req

protect

protect : Config -> Middleware

Reject unsafe methods when CSRF verification fails (403).

Examples

Server.Middleware.stack [ Auth.Csrf.protect csrf ] handle

errorToString

errorToString : Error -> String

Human-readable form of an Error for logs.

Examples

Auth.Csrf.errorToString MissingToken