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

valk-web

Web-application middleware and utilities for Valk built on valk.http and valk.crypto: signed and encrypted cookies, pluggable sessions with flash messages, CSRF protection, CORS, security headers, and rate limiting. Purely written in Valk, with no external dependencies.

Requires Valk 0.9.1 or newer.

Install

vman install github.com/ctxcode/valk-web

Quick Start

use web
use valk.http

let store = web.MemorySessionStore.new()

let server = http.Server.new("127.0.0.1", 8080, fn(req: http.Request) http.Response {
    let sess = web.session(req) ?! return http.Response.empty(500)
    if req.method == "POST" && req.path == "/login" {
        sess.regenerate_id()
        sess.set("user", "alice")
        sess.flash("notice", "Welcome back!")
        return http.Response.text("ok")
    }
    let user = sess.get("user") ?? "guest"
    let notice = sess.get_flash("notice") ?? ""
    return http.Response.html(user + " " + notice + web.csrf_hidden_input(req))
})

server.add_middleware(web.security_headers_middleware())
server.add_middleware(web.cors_middleware(web.CorsOptions {
    allowed_origins: .{ "https://app.example.com" }
    allow_credentials: true
}))
server.add_middleware(web.rate_limit_middleware(web.RateLimitOptions {
    max_requests: 100
    window_seconds: 60
}))
server.add_middleware(web.session_middleware(store, web.SessionOptions {
    secret: "change-me-in-production"
}))
server.add_middleware(web.csrf_middleware(web.CsrfOptions {
    secret: "change-me-too"
}))

You can also compose middleware directly around any http.Router handler with web.apply(mw, handler) or web.chain(handler, middlewares).

Features

Signed & Encrypted Cookies

  • sign_cookie(value, secret) / verify_cookie(signed, secret) — HMAC-SHA256 + base64url + constant-time verification.
  • encrypt_cookie(value, key, aad) / decrypt_cookie(token, key, aad) — AES-256-GCM authenticated encryption with random 12-byte nonces and optional AAD binding.
  • CookieOptions, format_set_cookie, parse_cookies, plus http.Request / http.Response helpers (set_cookie, clear_cookie, set_signed_cookie, get_signed_cookie, set_encrypted_cookie, get_encrypted_cookie).
let signed = web.sign_cookie("user=alice", secret) ! panic("%{E.message}")
let value = web.verify_cookie(signed, secret) ! panic("%{E.message}")

let sealed = web.encrypt_cookie("{\"id\":42}", enc_key) ! panic("%{E.message}")
let plain = web.decrypt_cookie(sealed, enc_key) ! panic("%{E.message}")

Sessions & Flash Messages

  • Session with id, data, dirty, destroyed, is_new, helpers (get, set, remove, has, clear, destroy, regenerate_id), and one-time flash messages (flash, get_flash, flashes).
  • Built-in thread-safe MemorySessionStore (in-memory with automatic expiry cleanup).
  • Built-in stateless CookieSessionStore (AES-256-GCM encrypted cookie sessions — no server storage required).
  • Pluggable interface SessionStore (load, save, delete) for Redis, SQLite, or any custom backend.
// Stateless encrypted cookie sessions:
let store = web.CookieSessionStore.new(session_key) ! panic("%{E.message}")
server.add_middleware(web.session_middleware(store))

CSRF Protection

Signed double-submit cookie middleware (csrf_middleware):

  • Safe methods (GET, HEAD, OPTIONS, TRACE) pass through and set a signed CSRF cookie.
  • Unsafe methods (POST, PUT, PATCH, DELETE, etc.) verify the token from X-CSRF-Token, X-XSRF-Token, or the _csrf form/JSON field in constant time, returning 403 Forbidden on mismatch.
  • Helpers csrf_token(req) and csrf_hidden_input(req) (<input type="hidden" name="_csrf" value="...">).

CORS & Security Headers

  • cors_middleware(CorsOptions) — exact allowed origins, "*", or a custom allow_origin_fn predicate; allowed_methods, allowed_headers, exposed_headers, allow_credentials, max_age, automatic OPTIONS preflight responses, and Vary: Origin.
  • security_headers_middleware(SecurityHeaders) — sets X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: strict-origin-when-cross-origin, Strict-Transport-Security, plus optional Content-Security-Policy, Permissions-Policy, and Cross-Origin-Opener-Policy. Route-level headers are preserved.

Rate Limiter

  • rate_limit_middleware(RateLimitOptions) and RateLimiter — thread-safe in-memory fixed-window rate limiter keying by client IP (req.peer_address, optional X-Forwarded-For with trust_proxy: true) or custom key_fn.
  • Adds X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, and returns 429 Too Many Requests with Retry-After when exceeded.

API Reference

Generated API docs live in docs/api.md and docs/api-full.md.

Development

make test runs the test suite, make lint checks sources with --deny-warnings, make example runs the example, and make docs regenerates the API documentation.