Orbit Framework 2.0.0
A high-performance asynchronous C++20 HTTP server framework.
Loading...
Searching...
No Matches
orbit::middleware Namespace Reference

Namespaces

namespace  detail
 

Classes

struct  AccessLogOptions
 Options for access_log(). More...
 
struct  CompressOptions
 Options for compress(). More...
 
struct  CorsOptions
 Options for configuring CORS (Cross-Origin Resource Sharing). More...
 
class  Csrf
 Cross-Site Request Forgery (CSRF) protection middleware. More...
 
class  DistributedRateLimiter
 Fixed-window rate limiter shared across instances through Redis. More...
 
class  IpNetwork
 An IPv4 or IPv6 network ("10.0.0.0/8", "::1", "fd00::/8"). IPv4 addresses are stored IPv4-mapped, so one comparison handles both. More...
 
struct  JwtOptions
 Verification settings for jwt_auth(). Configure at least one key: secret, public_key_pem or jwks_url (several may be combined). More...
 
struct  LoadBalancerOptions
 Options for LoadBalancer middleware. More...
 
class  MemorySessionStore
 In-process store. Fine for a single server; sessions are lost on restart and not shared between instances (use RedisSessionStore). More...
 
class  Metrics
 Middleware for tracking HTTP request metrics. More...
 
class  OAuth2
 Authorization-code flow helper. More...
 
struct  OAuth2Config
 Provider endpoints, client credentials and flow settings for OAuth2. More...
 
struct  ProxyOptions
 Options for Proxy middleware. More...
 
class  RateLimiter
 Token-bucket rate limiter keyed by client. More...
 
struct  RateLimitOptions
 Settings for the in-memory rate limiter. More...
 
struct  RequestIdOptions
 Options for request_id(). More...
 
struct  SchemaField
 Represents a field in a validation schema. More...
 
struct  SecurityHeadersOptions
 Options for security_headers(). An empty string leaves that header out. More...
 
class  Session
 The current request's session (req.session). More...
 
class  SessionManager
 Loads or creates the session for each request (req.session, req.session_id) and saves it when the response is sent. More...
 
struct  SessionOptions
 
class  SessionStore
 Where sessions live. Implementations must be thread-safe. More...
 
struct  Span
 A finished request, as reported to TracingOptions::on_span_end. More...
 
struct  StaticFilesOptions
 Options for static_files(). More...
 
struct  TargetNode
 A target node for the load balancer. More...
 
struct  TracingOptions
 Options for tracing(). More...
 
struct  TrustedProxyOptions
 Options for trusted_proxies(). More...
 

Typedefs

using GraphQLExecutor = std::function< nlohmann::json(const std::string &query, const std::string &operation_name, const nlohmann::json &variables)>
 Signature for a GraphQL executor function. Takes the query string, operation name (optional), and variables (optional), and returns a JSON response (which should have "data" or "errors").
 
using SessionData = std::unordered_map< std::string, std::string >
 Key/value data kept for one session.
 

Enumerations

enum class  ContentCoding { Identity , Gzip , Brotli , Zstd }
 A response content coding (RFC 9110 section 8.4.1). More...
 
enum class  JsonType {
  JsonType::STRING , JsonType::NUMBER , JsonType::BOOLEAN , JsonType::OBJECT ,
  JsonType::ARRAY
}
 Enumeration of JSON data types. More...
 

Functions

routing::Middleware compress (CompressOptions options={})
 Returns a middleware that compresses response bodies with brotli, zstd or gzip, whichever the client accepts and the server prefers.
 
ContentCoding negotiate_coding (std::string_view accept_encoding, const std::vector< ContentCoding > &preference, bool only_available=true)
 Chooses the coding for a response.
 
bool coding_available (ContentCoding coding)
 True if this build can produce coding.
 
std::string_view coding_name (ContentCoding coding)
 The Content-Encoding token for coding ("gzip", "br", "zstd"; "" for identity).
 
bool compress_body (ContentCoding coding, const std::string &in, std::string &out, const CompressOptions &options={})
 Compresses in with coding at the levels in options.
 
bool accepts_gzip (std::string_view accept_encoding)
 Whether an Accept-Encoding header value allows gzip.
 
routing::Middleware cors (CorsOptions options=CorsOptions{})
 Returns a middleware that handles CORS.
 
routing::Middleware require_origin (std::vector< std::string > allowed_origins)
 Rejects browser requests from origins that are not listed.
 
auto csrf_protection (const std::string &cookie_name="csrf_token", const std::string &header_name="X-CSRF-Token")
 Helper to create a CSRF protection middleware handler.
 
auto distributed_rate_limit (const std::string &redis_host, int redis_port, size_t max_requests, std::chrono::seconds window, DistributedRateLimiter::KeyFunction key=nullptr, bool allow_when_unavailable=false)
 Creates a DistributedRateLimiter middleware; see its constructor for parameters.
 
std::function< bool(http::HttpRequest &, std::shared_ptr< http::ResponseWriter >)> graphql (GraphQLExecutor executor)
 Creates a middleware handler for GraphQL endpoints. It parses the incoming GET or POST request according to the GraphQL over HTTP spec, extracts the query, operationName, and variables, and invokes the provided executor.
 
routing::Middleware jwt_auth (JwtOptions options)
 Verifies an Authorization: Bearer JWT and stores its claims in req.user.
 
routing::Middleware jwt_auth (const std::string &secret_key)
 Shorthand for an HS256-only jwt_auth() with this secret.
 
routing::Middleware request_id (RequestIdOptions options={})
 Gives every request an ID (req.request_id) and echoes it in the response header, so a client report can be matched to server logs.
 
routing::Middleware tracing (TracingOptions options={})
 W3C Trace Context: continues the trace from an incoming traceparent header (or starts a new one), sets req.trace_id and req.span_id, and reports each request as a Span.
 
routing::Middleware access_log (AccessLogOptions options={})
 Logs one line per request when its response is sent: method, path, status, response bytes, duration, client IP, user agent, and the request/trace IDs when request_id() / tracing() are used. In JSON log format these are separate fields.
 
routing::Middleware proxy (ProxyOptions options)
 Returns a middleware that proxies requests to a single target URL (ip/hostname and port).
 
routing::Middleware proxy (const std::string &target_host, int target_port)
 Returns a middleware that proxies requests to a single target URL.
 
routing::Middleware load_balancer (LoadBalancerOptions options)
 Returns a middleware that load-balances requests across multiple upstream nodes.
 
routing::Middleware load_balancer (const std::vector< TargetNode > &nodes)
 Returns a middleware that load-balances requests across multiple upstream nodes.
 
auto rate_limit (RateLimitOptions options)
 
auto rate_limit (size_t max_requests, std::chrono::seconds window)
 
routing::Middleware security_headers (SecurityHeadersOptions options={})
 Adds common security response headers (HSTS, nosniff, frame and referrer policies, COOP, optional CSP). They are defaults: a handler that sets the same header keeps its own value.
 
auto session (std::shared_ptr< SessionStore > store, SessionOptions options={})
 Session middleware over any store, e.g. std::make_shared<MemorySessionStore>().
 
routing::Middleware static_files (const std::string &directory, StaticFilesOptions options={})
 Returns a middleware that serves static files from a directory.
 
std::string_view mime_type_for_extension (std::string_view extension)
 Returns the Content-Type for a file extension such as ".svg" (case-insensitive), or "application/octet-stream" if unknown.
 
routing::Middleware trusted_proxies (TrustedProxyOptions options)
 Sets req.client_ip from forwarding headers, but only for requests that arrive from a trusted proxy.
 
routing::Middleware validate_json (const std::vector< SchemaField > &schema)
 Returns a middleware that parses and validates a JSON request body.
 

Typedef Documentation

◆ GraphQLExecutor

using orbit::middleware::GraphQLExecutor = typedef std::function<nlohmann::json(const std::string& query, const std::string& operation_name, const nlohmann::json& variables)>

Signature for a GraphQL executor function. Takes the query string, operation name (optional), and variables (optional), and returns a JSON response (which should have "data" or "errors").

◆ SessionData

using orbit::middleware::SessionData = typedef std::unordered_map<std::string, std::string>

Key/value data kept for one session.

Enumeration Type Documentation

◆ ContentCoding

A response content coding (RFC 9110 section 8.4.1).

Enumerator
Identity 

No compression.

Gzip 

"gzip" (zlib, always available).

Brotli 

"br" (needs ORBIT_ENABLE_BROTLI).

Zstd 

"zstd" (needs ORBIT_ENABLE_ZSTD, RFC 8878).

Function Documentation

◆ accepts_gzip()

bool orbit::middleware::accepts_gzip ( std::string_view  accept_encoding)

Whether an Accept-Encoding header value allows gzip.

◆ coding_available()

bool orbit::middleware::coding_available ( ContentCoding  coding)

True if this build can produce coding.

◆ coding_name()

std::string_view orbit::middleware::coding_name ( ContentCoding  coding)

The Content-Encoding token for coding ("gzip", "br", "zstd"; "" for identity).

◆ compress_body()

bool orbit::middleware::compress_body ( ContentCoding  coding,
const std::string &  in,
std::string &  out,
const CompressOptions &  options = {} 
)

Compresses in with coding at the levels in options.

Returns
False if the coding is unavailable or compression failed.

◆ distributed_rate_limit()

auto orbit::middleware::distributed_rate_limit ( const std::string &  redis_host,
int  redis_port,
size_t  max_requests,
std::chrono::seconds  window,
DistributedRateLimiter::KeyFunction  key = nullptr,
bool  allow_when_unavailable = false 
)
inline

Creates a DistributedRateLimiter middleware; see its constructor for parameters.

◆ graphql()

std::function< bool(http::HttpRequest &, std::shared_ptr< http::ResponseWriter >)> orbit::middleware::graphql ( GraphQLExecutor  executor)
inline

Creates a middleware handler for GraphQL endpoints. It parses the incoming GET or POST request according to the GraphQL over HTTP spec, extracts the query, operationName, and variables, and invokes the provided executor.

Parameters
executorThe user-provided GraphQL execution engine function.

◆ mime_type_for_extension()

std::string_view orbit::middleware::mime_type_for_extension ( std::string_view  extension)

Returns the Content-Type for a file extension such as ".svg" (case-insensitive), or "application/octet-stream" if unknown.

◆ negotiate_coding()

ContentCoding orbit::middleware::negotiate_coding ( std::string_view  accept_encoding,
const std::vector< ContentCoding > &  preference,
bool  only_available = true 
)

Chooses the coding for a response.

The acceptable coding with the highest q-value wins; ties go to the first in preference. An explicit entry overrides "*", "x-gzip" counts as "gzip", and q=0 refuses a coding (RFC 9110 section 12.5.3). Codings not available in this build are never chosen, unless only_available is false (the body is already compressed, e.g. a precompressed file).

Returns
The coding to use, or Identity if none is acceptable.

◆ rate_limit() [1/2]

auto orbit::middleware::rate_limit ( RateLimitOptions  options)
inline

◆ rate_limit() [2/2]

auto orbit::middleware::rate_limit ( size_t  max_requests,
std::chrono::seconds  window 
)
inline

◆ require_origin()

routing::Middleware orbit::middleware::require_origin ( std::vector< std::string >  allowed_origins)

Rejects browser requests from origins that are not listed.

Requests carrying an Origin header that is not in allowed_origins get 403 Forbidden. Requests without an Origin header (non-browser clients) pass. Use it on WebSocket routes to prevent cross-site WebSocket hijacking, since browsers do not apply CORS to WebSocket handshakes:

app.ws("/chat", {middleware::require_origin({"https://app.example.com"})}, handler);
routing::Middleware require_origin(std::vector< std::string > allowed_origins)
Rejects browser requests from origins that are not listed.

◆ session()

auto orbit::middleware::session ( std::shared_ptr< SessionStore >  store,
SessionOptions  options = {} 
)
inline

Session middleware over any store, e.g. std::make_shared<MemorySessionStore>().