CsrfCookieMiddleware: Automated Security Cookie Provisioning in Xeno
What Is CsrfCookieMiddleware?
Section titled âWhat Is CsrfCookieMiddleware?âCsrfCookieMiddleware is a specialized presentation-layer middleware in Xeno responsible for automating the lifecycle of security cookiesâspecifically, Cross-Site Request Routing Protection (CSRF) cookies.
While incoming request headers and cookies are parsed and mapped into the request context via extractors (such as HttpCookieExtractor), CsrfCookieMiddleware operates proactively on the outgoing response stream. It ensures that once a user successfully establishes an authenticated session, a secure, cryptographically bound CSRF token cookie is automatically provisioned and sent back to the browser.
How It Works Under the Hood
Section titled âHow It Works Under the HoodâUnlike traditional middlewares that evaluate incoming payloads before they reach the controller, CsrfCookieMiddleware leverages a post-processing pattern. Here is how the execution flow operates step by step:
- Awaiting Downstream Execution:
The middleware first yields control to the rest of the execution chain by awaiting
await next(). This ensures that the controller, business handlers, and upstream authentication checks (likeAuthenticationMiddleware) have already executed and populated the activeRequestContext. - Identity & Context Inspection:
Once the downstream response is returned, the middleware queries the
RequestContextviaIContextAccessorto inspect two critical parameters:
identity.userId: Confirms whether the user is actively authenticated. If no user ID is present (i.e., the user is aGUEST), the middleware bypasses cookie injection entirely, preserving public routing performance.network.csrfCookie: Checks if a valid CSRF cookie was already supplied by the incoming request. If it already exists, the middleware avoids redundant token generation.
- **Token Generation via
ICsrfTokenService**: If the user is authenticated and lacks an active client cookie, the middleware delegates token creation to the injectedICsrfTokenService, generating a unique, user-scoped cryptographic token. - Secure Cookie Construction & Header Appending:
It formats the cookie string using enterprise security best practices (enforcing
Path=/,Secure, configurableSameSitepolicies, and expiration bounds) and appends it to theSet-Cookiearray withinResponseDto.headers, ensuring any existing cookies are safely preserved.
Relationship with Cookie Extractors
Section titled âRelationship with Cookie ExtractorsâThe cookie workflow in Xeno bridges inbound parsing and outbound provisioning:
- Inbound (
HttpCookieExtractor): When a browser sends a subsequent state-changing request (POST,PUT,DELETE), the low-levelHttpCookieExtractorscans the rawCookieheader string, isolates the target cookie (e.g.,__Host-xeno-csrf), decodes it safely usingdecodeURIComponent, and maps it intonetwork.csrfCookie. - Outbound (
CsrfCookieMiddleware): If that cookie is missing during an authenticated session lifecycle,CsrfCookieMiddlewaresteps in to generate and set it viaSet-Cookie.
How to Configure It via AppBuilder
Section titled âHow to Configure It via AppBuilderâCsrfCookieMiddleware is not instantiated manually; instead, it is provisioned automatically by the framework when you configure the csrf security block inside your applicationâs bootstrap file using .addMiddlewares():
import { AppBuilder } from '@xeno-js/core'import type { AppRegistry } from './registry'
const builder = new AppBuilder<AppRegistry>()
builder .addContext() .addMiddlewares((config, env) => { // Activating the CSRF subsystem automatically queues CsrfMiddleware and CsrfCookieMiddleware config.csrf = { secret: env.getOrThrow('CSRF_SECRET'), cookieName: '__Host-xeno-csrf', cookieMaxAgeSeconds: 3600, // 1 hour expiration headerName: 'x-csrf-token', sameSite: 'lax', // 'strict', 'lax', or 'none' } })
const container = await builder.build()Architectural Safeguards During Bootstrap
Section titled âArchitectural Safeguards During BootstrapâWhen config.csrf is defined, MiddlewareModule performs the following automated wiring:
- Registers the
CsrfTokenServicebinding it to the internal cryptographic engine (CRYPTO_SERVICE). - Mounts
CsrfCookieMiddlewareinto the composite execution stack to handle outgoing cookie issuance. - Mounts
CsrfMiddlewareto validate incoming state-changing requests against the issued tokens.
Dependencies and Constraints
Section titled âDependencies and Constraintsâ- Dependency Injection: Requires an active
IContextAccessor, an implementation ofICsrfTokenService, and validMiddlewareConfig['csrf']parameters. - State Dependency: Relies on
AuthenticationMiddlewarehaving previously resolved and populated the userâsuserIdinside the request context. - Transport Independence: Operates entirely on the unified
ResponseDto.headersstructure, leaving actual header flushing to the underlying transport adapter (e.g., Fastify, Hono, or Vercel).
Support Us
Section titled âSupport UsâXeno is an MIT-licensed open source project. It can grow thanks to the support of these awesome people. If youâd like to join them, please read more at support section