pkg

ctxcode/valk-web

Web middleware, sessions, signed cookies, CSRF, CORS and security headers for Valk

github.com/ctxcode/valk-web ↗
0.2.1 latest Valk ≥ 0.10.0

Install

vman install github.com/ctxcode/valk-web

Adds the package to your valk.json. To allow only some versions, add them: vman install github.com/ctxcode/valk-web 0.2.x

Documentation

Namespaces: main


main

Aliases for 'main'

type Handler (atomic fn(Request)(Response))
type Middleware (atomic fn(Request, atomic fn(Request)(Response))(Response))

Functions for 'main'

// Wraps `handler` with a single `middleware`, returning a new `Handler`.
+ fn apply(middleware: atomic fn(Request, atomic fn(Request)(Response))(Response), handler: atomic fn(Request)(Response)) atomic fn(Request)(Response)
// Wraps `handler` in `middlewares`, with the first middleware running outermost.
+ fn chain(handler: atomic fn(Request)(Response), middlewares: Array[atomic fn(Request, atomic fn(Request)(Response))(Response)]) atomic fn(Request)(Response)
// Expires cookie `name` on `res` using the path, domain, and flags from `options`.
+ fn clear_cookie(res: Response, name: String, options: ?CookieOptions (null)) void
// Creates a CORS middleware supporting exact origin lists, `"*"`, custom origin predicates, credentialed requests, `Vary: Origin`, and automatic `OPTIONS` preflight responses.
+ fn cors_middleware(options: ?CorsOptions (null)) atomic fn(Request, atomic fn(Request)(Response))(Response)
// Returns an HTML hidden input element carrying the request's CSRF token: `<input type="hidden" name="_csrf" value="...">`.
+ fn csrf_hidden_input(req: Request) String
// Creates a signed double-submit cookie CSRF protection middleware.
+ fn csrf_middleware(options: ?CsrfOptions (null)) atomic fn(Request, atomic fn(Request)(Response))(Response)
// Returns the CSRF token associated with `req` by `csrf_middleware`, or `null` if `csrf_middleware` is not active for this request.
+ fn csrf_token(req: Request) ?String
// Decrypts and verifies a token produced by `encrypt_cookie`.
+ fn decrypt_cookie(token: String, key: String, aad: String ("")) String !CookieError
// Encrypts and authenticates `value` with AES-256-GCM using a key derived from `key` and a fresh random 12-byte nonce, returning a cookie-safe base64url token.
+ fn encrypt_cookie(value: String, key: String, aad: String ("")) String !CookieError
// Formats a `Set-Cookie` header value for `name` and `value` with `options`.
+ fn format_set_cookie(name: String, value: String, options: ?CookieOptions (null)) String
// Reads and decrypts encrypted cookie `name` (with `name` as AAD) from `req`.
+ fn get_encrypted_cookie(req: Request, name: String, key: String) String !CookieError
// Reads and verifies signed cookie `name` from `req`.
+ fn get_signed_cookie(req: Request, name: String, secret: String) String !CookieError
// Parses a `Cookie` request header string into a `Map[String]` of cookie names to values.
+ fn parse_cookies(header: String) Map[String]
// Creates a thread-safe in-memory rate limiter middleware.
+ fn rate_limit_middleware(options: ?RateLimitOptions (null)) atomic fn(Request, atomic fn(Request)(Response))(Response)
// Creates a middleware that sets standard HTTP security headers on every response.
+ fn security_headers_middleware(options: ?SecurityHeaders (null)) atomic fn(Request, atomic fn(Request)(Response))(Response)
// Returns the active `Session` attached to `req` by `session_middleware`, or `null` if `session_middleware` is not active for this request.
+ fn session(req: Request) ?Session
// Creates a middleware that loads, exposes (via `session(req)`), and persists sessions using `store`.
+ fn session_middleware(store: $S, options: ?SessionOptions (null)) atomic fn(Request, atomic fn(Request)(Response))(Response)
// Attaches a `Set-Cookie` header to `res`.
+ fn set_cookie(res: Response, name: String, value: String, options: ?CookieOptions (null)) void
// Encrypts `value` with `key` (binding `name` as AAD) and attaches it to `res`.
+ fn set_encrypted_cookie(res: Response, name: String, value: String, key: String, options: ?CookieOptions (null)) void !CookieError
// Signs `value` with `secret` and attaches it as cookie `name` on `res`.
+ fn set_signed_cookie(res: Response, name: String, value: String, secret: String, options: ?CookieOptions (null)) void !CookieError
// Signs `value` with HMAC-SHA256 using `secret`, returning a cookie-safe base64url token of the form `<payload>.<signature>`.
+ fn sign_cookie(value: String, secret: String) String !CookieError
// Verifies a token produced by `sign_cookie` using constant-time HMAC-SHA256 comparison and returns the original value.
+ fn verify_cookie(signed: String, secret: String) String !CookieError

apply

Wraps handler with a single middleware, returning a new Handler.

Useful for applying middleware to individual valk.http.Router routes.

chain

Wraps handler in middlewares, with the first middleware running outermost.

Expires cookie name on res using the path, domain, and flags from options.

cors_middleware

Creates a CORS middleware supporting exact origin lists, "*", custom origin predicates,
credentialed requests, Vary: Origin, and automatic OPTIONS preflight responses.

csrf_hidden_input

Returns an HTML hidden input element carrying the request's CSRF token:
<input type="hidden" name="_csrf" value="...">.

Returns an empty string when csrf_middleware is not active for req.

csrf_middleware

Creates a signed double-submit cookie CSRF protection middleware.

Safe methods (GET, HEAD, OPTIONS, TRACE) pass through and ensure a signed CSRF
token cookie is set on the response. Unsafe methods (POST, PUT, PATCH, DELETE,
etc.) must submit the matching token in one of header_names (X-CSRF-Token /
X-XSRF-Token) or the form field field_name (_csrf), verified in constant time,
or receive 403 Forbidden.

csrf_token

Returns the CSRF token associated with req by csrf_middleware, or null if
csrf_middleware is not active for this request.

Decrypts and verifies a token produced by encrypt_cookie.

Throws key when key is empty, invalid when the token is not valid base64url,
and decrypt when the authentication tag, key, or aad does not match.

Encrypts and authenticates value with AES-256-GCM using a key derived from key and
a fresh random 12-byte nonce, returning a cookie-safe base64url token.

Optional aad binds additional authenticated data (such as a cookie name) to the
ciphertext; the exact same aad must be passed to decrypt_cookie.
Throws key when key is empty.

Formats a Set-Cookie header value for name and value with options.

Reads and decrypts encrypted cookie name (with name as AAD) from req.

Reads and verifies signed cookie name from req.

parse_cookies

Parses a Cookie request header string into a Map[String] of cookie names to values.

Preserves = inside values (such as base64), strips surrounding double quotes, and keeps
the first occurrence when a name appears more than once.

rate_limit_middleware

Creates a thread-safe in-memory rate limiter middleware.

Adds X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset to every
response. When a key exceeds max_requests in the window, responds with `429 Too Many
Requests and a Retry-After` header.

security_headers_middleware

Creates a middleware that sets standard HTTP security headers on every response.

session

Returns the active Session attached to req by session_middleware, or null if
session_middleware is not active for this request.

session_middleware

Creates a middleware that loads, exposes (via session(req)), and persists sessions
using store.

Works with MemorySessionStore, CookieSessionStore, or any thread-safe SessionStore.

Attaches a Set-Cookie header to res.

Encrypts value with key (binding name as AAD) and attaches it to res.

Signs value with secret and attaches it as cookie name on res.

Signs value with HMAC-SHA256 using secret, returning a cookie-safe base64url token
of the form <payload>.<signature>.

Throws key when secret is empty.

Verifies a token produced by sign_cookie using constant-time HMAC-SHA256 comparison
and returns the original value.

Throws key when secret is empty, invalid when the format or encoding is malformed,
and signature when verification fails.

Classes for 'main'

// Thrown when signing, verifying, encrypting, or decrypting a cookie fails.
+ union CookieError {
    invalid(String)
    signature(String)
    decrypt(String)
    key(String)

    // Returns the error description carried by any variant.
    + get message: String
    + fn to_string() String
}

CookieError

Thrown when signing, verifying, encrypting, or decrypting a cookie fails.

  • invalid(message): the cookie text is missing, malformed, or not valid base64url.
  • signature(message): the HMAC signature does not match the payload and secret.
  • decrypt(message): AEAD decryption or authentication tag verification failed.
  • key(message): the signing secret or encryption key is empty.

message

Returns the error description carried by any variant.

// Attributes used when formatting or attaching a `Set-Cookie` header.
+ class CookieOptions {
    // Optional `Domain` attribute.
    + domain: ?String
    // Marks the cookie `HttpOnly` so page scripts cannot read it; defaults to `true`.
    + http_only: bool
    // Cookie lifetime in seconds (`Max-Age`); `null` creates a browser session cookie.
    + max_age: ?int
    // Cookie `Path` attribute; defaults to `"/"`.
    + path: String
    // `SameSite` policy: `"Lax"`, `"Strict"`, or `"None"`; defaults to `"Lax"`.
    + same_site: String
    // Marks the cookie `Secure` so browsers send it over HTTPS only; defaults to `true`.
    + secure: bool

    // Returns a copy of these options.
    + fn clone() CookieOptions
    // Formats a `Set-Cookie` header value for `name` and `value` using these options.
    + fn format(name: String, value: String) String
    // Converts these options with `name` and `value` into a `valk.http.Cookie`.
    + fn to_http_cookie(name: String, value: String) Cookie
}

CookieOptions

Attributes used when formatting or attaching a Set-Cookie header.

Defaults follow safe browser settings (http_only: true, secure: true,
same_site: "Lax", path: "/"). Set secure: false for local plain-HTTP development.

domain

Optional Domain attribute.

http_only

Marks the cookie HttpOnly so page scripts cannot read it; defaults to true.

max_age

Cookie lifetime in seconds (Max-Age); null creates a browser session cookie.

path

Cookie Path attribute; defaults to "/".

same_site

SameSite policy: "Lax", "Strict", or "None"; defaults to "Lax".

secure

Marks the cookie Secure so browsers send it over HTTPS only; defaults to true.

clone

Returns a copy of these options.

format

Formats a Set-Cookie header value for name and value using these options.

Converts these options with name and value into a valk.http.Cookie.

// Stateless encrypted cookie `SessionStore` using AES-256-GCM.
+ class CookieSessionStore is SessionStore {
    // No-op for stateless cookie sessions; `session_middleware` clears the cookie on destroy.
    + fn delete(id: String) void
    // Encrypts `id`, `data`, and expiry (`ttl_seconds`) into a cookie value.
    + fn encode(id: String, data: Map[String], ttl_seconds: uint) String !CookieError
    // Decrypts `token` and returns its session data map, or `null` if invalid or expired.
    + fn load(id: String) ?Map[String]
    // Creates a stateless encrypted cookie session store using `key`.
    + static fn new(key: String) CookieSessionStore !CookieError
    // No-op for stateless cookie sessions; `session_middleware` writes the encrypted cookie.
    + fn save(id: String, data: Map[String], ttl_seconds: uint) void
}

CookieSessionStore

Stateless encrypted cookie SessionStore using AES-256-GCM.

Session data is serialized as JSON, sealed with AES-256-GCM, and stored directly inside
the browser cookie so no server-side session storage is required.

delete

No-op for stateless cookie sessions; session_middleware clears the cookie on destroy.

encode

Encrypts id, data, and expiry (ttl_seconds) into a cookie value.

load

Decrypts token and returns its session data map, or null if invalid or expired.

new

Creates a stateless encrypted cookie session store using key.

Throws CookieError.key when key is empty.

save

No-op for stateless cookie sessions; session_middleware writes the encrypted cookie.

// Configuration for `cors_middleware`.
+ class CorsOptions {
    // Whether `Access-Control-Allow-Credentials: true` is sent.
    + allow_credentials: bool
    // Optional predicate that decides whether a given `Origin` header is allowed.
    + allow_origin_fn: ?atomic fn(String)(bool)
    // Request headers allowed on CORS preflight requests; when empty, echoes `Access-Control-Request-Headers`.
    + allowed_headers: Array[String]
    // HTTP methods allowed on CORS requests.
    + allowed_methods: Array[String]
    // Allowed origins, or `{ "*" }` to allow any origin.
    + allowed_origins: Array[String]
    // Response headers exposed to browser JavaScript via `Access-Control-Expose-Headers`.
    + exposed_headers: Array[String]
    // Optional preflight cache duration in seconds (`Access-Control-Max-Age`).
    + max_age: ?uint
}

CorsOptions

Configuration for cors_middleware.

allow_credentials

Whether Access-Control-Allow-Credentials: true is sent.

When true, the exact matched Origin is echoed instead of "*".

allow_origin_fn

Optional predicate that decides whether a given Origin header is allowed.

When set, takes precedence over allowed_origins.

allowed_headers

Request headers allowed on CORS preflight requests; when empty, echoes
Access-Control-Request-Headers.

allowed_methods

HTTP methods allowed on CORS requests.

allowed_origins

Allowed origins, or { "*" } to allow any origin.

exposed_headers

Response headers exposed to browser JavaScript via Access-Control-Expose-Headers.

max_age

Optional preflight cache duration in seconds (Access-Control-Max-Age).

// Configuration for `csrf_middleware`.
+ class CsrfOptions {
    // Cookie attributes for the CSRF cookie.
    + cookie: CookieOptions
    // Name of the cookie holding the signed CSRF token; defaults to `"_csrf"`.
    + cookie_name: String
    // Exact request paths exempt from CSRF verification.
    + exempt_paths: Array[String]
    // Form field name inspected on unsafe requests; defaults to `"_csrf"`.
    + field_name: String
    // Request header names inspected on unsafe requests, in priority order.
    + header_names: Array[String]
    // HMAC secret used to sign the CSRF cookie.
    + secret: String
    // Number of random bytes used to generate each token; defaults to 32.
    + token_bytes: uint
}

CsrfOptions

Configuration for csrf_middleware.

Cookie attributes for the CSRF cookie.

Name of the cookie holding the signed CSRF token; defaults to "_csrf".

exempt_paths

Exact request paths exempt from CSRF verification.

field_name

Form field name inspected on unsafe requests; defaults to "_csrf".

header_names

Request header names inspected on unsafe requests, in priority order.

secret

HMAC secret used to sign the CSRF cookie.

Leave empty to generate a random per-process secret; set an explicit secret when
running multiple server instances behind a load balancer.

token_bytes

Number of random bytes used to generate each token; defaults to 32.

// Thread-safe in-memory `SessionStore` with automatic expiry cleanup.
+ class MemorySessionStore is SessionStore {
    // Removes all expired sessions and returns how many were removed.
    + fn cleanup() uint
    // Returns the number of currently stored (non-expired) sessions.
    + fn count() uint
    // Removes session `id` from memory.
    + fn delete(id: String) void
    // Loads session data for `id`, returning `null` if absent or expired.
    + fn load(id: String) ?Map[String]
    // Creates an empty in-memory session store.
    + static fn new() MemorySessionStore
    // Saves a copy of `data` under `id` with lifetime `ttl_seconds`.
    + fn save(id: String, data: Map[String], ttl_seconds: uint) void
}

MemorySessionStore

Thread-safe in-memory SessionStore with automatic expiry cleanup.

cleanup

Removes all expired sessions and returns how many were removed.

count

Returns the number of currently stored (non-expired) sessions.

delete

Removes session id from memory.

load

Loads session data for id, returning null if absent or expired.

new

Creates an empty in-memory session store.

save

Saves a copy of data under id with lifetime ttl_seconds.

// Configuration for `rate_limit_middleware`.
+ class RateLimitOptions {
    // Optional custom key extractor; defaults to the client's IP address.
    + key_fn: ?atomic fn(Request)(String)
    // Maximum number of requests allowed per key in each window; defaults to 100.
    + max_requests: uint
    // Response body sent when the limit is exceeded; defaults to `"Too Many Requests"`.
    + message: String
    // HTTP status code sent when the limit is exceeded; defaults to `429`.
    + status_code: u16
    // When true and no `key_fn` is set, uses the first IP in `X-Forwarded-For` before falling back to `req.peer_address`.
    + trust_proxy: bool
    // Optional window length in milliseconds (overrides `window_seconds` when set).
    + window_ms: ?uint
    // Window length in seconds; defaults to 60. Ignored when `window_ms` is set.
    + window_seconds: uint
}

RateLimitOptions

Configuration for rate_limit_middleware.

key_fn

Optional custom key extractor; defaults to the client's IP address.

max_requests

Maximum number of requests allowed per key in each window; defaults to 100.

message

Response body sent when the limit is exceeded; defaults to "Too Many Requests".

status_code

HTTP status code sent when the limit is exceeded; defaults to 429.

trust_proxy

When true and no key_fn is set, uses the first IP in X-Forwarded-For before
falling back to req.peer_address.

window_ms

Optional window length in milliseconds (overrides window_seconds when set).

window_seconds

Window length in seconds; defaults to 60. Ignored when window_ms is set.

// Outcome of a single `RateLimiter.check` call.
+ class RateLimitResult {
    // True when the request is within the allowed quota.
    + allowed: bool
    // Configured maximum requests per window.
    + limit: uint
    // Remaining requests in the current window.
    + remaining: uint
    // Unix timestamp (seconds) when the current window resets.
    + reset_unix_seconds: uint
    // Seconds to wait before retrying (0 when allowed, at least 1 when blocked).
    + retry_after_seconds: uint
}

RateLimitResult

Outcome of a single RateLimiter.check call.

allowed

True when the request is within the allowed quota.

limit

Configured maximum requests per window.

remaining

Remaining requests in the current window.

reset_unix_seconds

Unix timestamp (seconds) when the current window resets.

retry_after_seconds

Seconds to wait before retrying (0 when allowed, at least 1 when blocked).

// Thread-safe in-memory fixed-window rate limiter.
+ class RateLimiter {
    // Consumes one unit of quota for `key` and returns the resulting allowance and headers info.
    + fn check(key: String) RateLimitResult
    // Removes expired buckets and returns how many were removed.
    + fn cleanup() uint
    // Clears all tracked keys.
    + fn clear() void
    // Creates a rate limiter allowing `max_requests` requests per `window_ms` milliseconds.
    + static fn new(max_requests: uint, window_ms: uint) RateLimiter
    // Resets the counter for `key`.
    + fn reset(key: String) void
}

RateLimiter

Thread-safe in-memory fixed-window rate limiter.

check

Consumes one unit of quota for key and returns the resulting allowance and headers info.

cleanup

Removes expired buckets and returns how many were removed.

clear

Clears all tracked keys.

new

Creates a rate limiter allowing max_requests requests per window_ms milliseconds.

reset

Resets the counter for key.

// Configuration for `security_headers_middleware`.
+ class SecurityHeaders {
    // Optional `Content-Security-Policy` header value; omitted when empty.
    + content_security_policy: String
    // `X-Content-Type-Options` header value; defaults to `"nosniff"`.
    + content_type_options: String
    // Optional `Cross-Origin-Opener-Policy` header value; omitted when empty.
    + cross_origin_opener_policy: String
    // `X-Frame-Options` header value; defaults to `"DENY"`.
    + frame_options: String
    // Optional `Permissions-Policy` header value; omitted when empty.
    + permissions_policy: String
    // `Referrer-Policy` header value; defaults to `"strict-origin-when-cross-origin"`.
    + referrer_policy: String
    // `Strict-Transport-Security` header value; defaults to `"max-age=31536000; includeSubDomains"`.
    + strict_transport_security: String
}

SecurityHeaders

Configuration for security_headers_middleware.

Any field set to "" omits that header. Existing headers already set by a handler are
preserved so individual routes can override defaults.

content_security_policy

Optional Content-Security-Policy header value; omitted when empty.

content_type_options

X-Content-Type-Options header value; defaults to "nosniff".

cross_origin_opener_policy

Optional Cross-Origin-Opener-Policy header value; omitted when empty.

frame_options

X-Frame-Options header value; defaults to "DENY".

permissions_policy

Optional Permissions-Policy header value; omitted when empty.

referrer_policy

Referrer-Policy header value; defaults to "strict-origin-when-cross-origin".

strict_transport_security

Strict-Transport-Security header value; defaults to "max-age=31536000; includeSubDomains".

// A per-request web session with key-value storage and one-time flash messages.
+ class Session {
    // Underlying key-value store.
    + data: Map[String]
    // True when `destroy` has been called; the middleware deletes the session and clears its cookie.
    + destroyed: bool
    // True when the session has been modified and must be saved.
    + dirty: bool
    // The session identifier.
    + id: String
    // True when no existing session was loaded for this request.
    + is_new: bool

    // Removes all keys and flash messages from the session and marks it dirty.
    + fn clear() void
    // Marks the session for deletion and clears its data.
    + fn destroy() void
    // Stores a one-time flash message under `key`.
    + fn flash(key: String, value: String) void
    // Reads and immediately removes all pending flash messages.
    + fn flashes() Map[String]
    // Returns the value stored under `key`, or `null` when absent.
    + fn get(key: String) ?String
    // Reads and immediately removes the flash message stored under `key`.
    + fn get_flash(key: String) ?String
    // Returns whether `key` exists in the session.
    + fn has(key: String) bool
    // Creates a new empty session with a random cryptographically secure ID.
    + static fn new(id: ?String (null)) Session
    // Assigns a fresh random session ID while preserving session data.
    + fn regenerate_id() String
    // Removes `key` from the session and marks it dirty if the key existed.
    + fn remove(key: String) void
    // Stores `value` under `key` and marks the session dirty.
    + fn set(key: String, value: String) void
}

Session

A per-request web session with key-value storage and one-time flash messages.

Mutating methods automatically mark dirty = true so session_middleware knows to
persist changes and send an updated Set-Cookie header when needed.

data

Underlying key-value store.

destroyed

True when destroy has been called; the middleware deletes the session and clears its cookie.

dirty

True when the session has been modified and must be saved.

id

The session identifier.

is_new

True when no existing session was loaded for this request.

clear

Removes all keys and flash messages from the session and marks it dirty.

destroy

Marks the session for deletion and clears its data.

session_middleware removes the session from its store and sends an expired cookie.

flash

Stores a one-time flash message under key.

flashes

Reads and immediately removes all pending flash messages.

get

Returns the value stored under key, or null when absent.

get_flash

Reads and immediately removes the flash message stored under key.

Returns null when no flash message exists for key.

has

Returns whether key exists in the session.

new

Creates a new empty session with a random cryptographically secure ID.

regenerate_id

Assigns a fresh random session ID while preserving session data.

Call after login or privilege changes to prevent session fixation; the middleware
deletes the previous session ID from the store and writes a new cookie.

remove

Removes key from the session and marks it dirty if the key existed.

set

Stores value under key and marks the session dirty.

// Configuration for `session_middleware`.
+ class SessionOptions {
    // Cookie attributes for the session cookie.
    + cookie: CookieOptions
    // Cookie name used to carry the session ID or encrypted session payload; defaults to `"valk_session"`.
    + cookie_name: String
    // When true, refreshes session expiry and cookie on every request.
    + rolling: bool
    // When true, saves and sets a cookie even for untouched new sessions.
    + save_uninitialized: bool
    // Optional HMAC secret to sign server-side session ID cookies (ignored by `CookieSessionStore`).
    + secret: String
    // Session lifetime in seconds; defaults to 86400 (24 hours).
    + ttl_seconds: uint
}

SessionOptions

Configuration for session_middleware.

Cookie attributes for the session cookie.

Cookie name used to carry the session ID or encrypted session payload; defaults to "valk_session".

rolling

When true, refreshes session expiry and cookie on every request.

save_uninitialized

When true, saves and sets a cookie even for untouched new sessions.

secret

Optional HMAC secret to sign server-side session ID cookies (ignored by CookieSessionStore).

ttl_seconds

Session lifetime in seconds; defaults to 86400 (24 hours).

// Pluggable backend interface for storing server-side sessions.
+ interface SessionStore {
    // Deletes the session identified by `id`.
    + fn delete(id: String) void
    // Loads session data for `id`, or `null` when missing or expired.
    + fn load(id: String) ?Map[String]
    // Persists `data` under `id` for `ttl_seconds` seconds.
    + fn save(id: String, data: Map[String], ttl_seconds: uint) void
}

SessionStore

Pluggable backend interface for storing server-side sessions.

Implement this interface on an $atomic class with @threadsafe methods (for example
backed by core.Lock, Redis, or SQLite) to plug custom persistence into session_middleware.

delete

Deletes the session identified by id.

load

Loads session data for id, or null when missing or expired.

save

Persists data under id for ttl_seconds seconds.