Security
Introduction
Section titled “Introduction”Xeno.JS provides security controls at two different boundaries:
- the HTTP boundary, where incoming requests are inspected and authenticated;
- the application boundary, where authenticated identities are authorized to execute application requests.
These responsibilities are deliberately separate.
HTTP request │ ├── Request context / metadata │ ├── Origin validation │ ├── OPTIONS handling │ ├── HTTP method validation │ ├── CORS │ ├── Rate limiting │ ├── Authentication │ └── credential → Identity │ ├── CSRF validation │ ▼Application request │ └── Authorization ├── user ID ├── tenant ID ├── roles ├── permissions └── custom strategiesThe security documentation therefore follows the same separation:
security/├── authentication/├── authorization/├── middleware/└── helpers/Configure security
Section titled “Configure security”How do I enable Xeno.JS security middleware?
Section titled “How do I enable Xeno.JS security middleware?”The HTTP security layer is enabled through AppBuilder.addMiddlewares().
A minimal authenticated application looks like this:
import { XenoAppBuilder } from '@xeno-js/core'import { withSupabase } from '@xeno-js/supabase'
const app = new XenoAppBuilder()
app.addAuth(withSupabase((options, config) => { options.url = config.get('SUPABASE_URL')! options.key = config.get('SUPABASE_KEY')!}))
app.addMiddlewares()
const application = await app.build()There are two important calls:
app.addAuth(...)configures the authentication service.
app.addMiddlewares(...)installs the HTTP middleware stack and connects it to the authentication service when authentication has been configured.
If addMiddlewares() is called without addAuth(), Xeno configures the authentication middleware with a NoAuthGateKeeper, which returns a guest identity instead of authenticating credentials.
Authentication vs authorization
Section titled “Authentication vs authorization”These two mechanisms solve different problems.
Authentication
Section titled “Authentication”Authentication answers:
Who is making this request?
The HTTP authentication middleware:
- extracts a credential;
- passes it to the configured gatekeeper;
- authenticates the credential;
- maps the resulting claims to an identity;
- stores the identity in the request context.
The flow is:
HTTP credential │ ▼Token extractor │ ▼AuthenticationMiddleware │ ▼GateKeeper │ ▼Authentication service │ ▼Identity │ ▼Request contextIf authentication fails, AuthenticationMiddleware returns an error response instead of continuing the middleware chain, using the authentication error’s status or 401 Unauthorized by default.
See:
Authorization
Section titled “Authorization”Authorization answers:
Is this authenticated identity allowed to execute this application request?
Authorization is configured through the CQRS pipeline:
import { withAuthZ } from '@xeno-js/core'
app.addPipeline(withAuthZ((opts) => { opts.policies = { CreateInvoice: { userId: true, tenantId: true, roles: ['admin', 'billing'], permissions: ['invoice:create'], }, }}))The authorization pipeline evaluates the configured strategies before passing the request to the next application pipeline stage.
Authenticated Identity │ ▼AuthorizationPipeline │ ├── user ID strategy ├── tenant ID strategy ├── role strategy ├── permission strategy └── custom strategies │ ▼Application handlerStrategies run sequentially. If one fails, the authorization pipeline stops and returns that failure.
See:
HTTP security middleware
Section titled “HTTP security middleware”addMiddlewares() builds a composite HTTP middleware containing the security controls configured for the application.
The current middleware composition is:
Request context │ ▼SSR cookie response handling (when isSSR is enabled) │ ▼Origin validation │ ▼OPTIONS handling (when CORS preflight is enabled and routes are configured) │ ▼HTTP method checks (when routes are configured) │ ▼CORS (when enabled) │ ▼Rate limiting │ ▼Authentication │ ▼CSRF cookie generation and validation (when csrf is configured) │ ▼Application executionSome stages are conditional.
| Control | Enable by |
|---|---|
| Request context | addMiddlewares() |
| Origin validation | addMiddlewares() |
| OPTIONS handling | cors.enablePreflight: true and routes configured |
| CORS | cors.enabled: true |
| HTTP method checks | Routes supplied through addRoutes() |
| Authentication | addMiddlewares(); addAuth() supplies a real authentication service |
| Rate limiting | rateLimit.enabled: true |
| CSRF | csrf configuration |
| SSR cookie response | isSSR: true |
The exact middleware chain is built by Xeno when the middleware module is configured.
Default security configuration
Section titled “Default security configuration”XenoAppBuilder starts with the following relevant middleware defaults:
{ isSSR: false,
rateLimit: { enabled: true, maxRequests: 100, windowSeconds: 60, },
csrf: undefined,
cors: { enabled: true, enablePreflight: true, withCredentials: true, allowOrigins: [], allowHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept', 'Origin'], },
trustedIpHeader: undefined,
trustedProxies: [],
authCookieName: 'sb-access-token',}This means that some security behavior is already active without additional configuration.
In particular:
- CORS is enabled;
- CORS preflight handling is enabled when routes are configured;
- credentials are enabled;
- origin validation is enabled;
- rate limiting has a default configuration;
- CSRF is not enabled until configured;
- route-specific method checks are enabled when routes are supplied through
addRoutes(); isSSRenables the SSR cookie response middleware; it does not select an authentication token extractor.
Configure authentication
Section titled “Configure authentication”Authentication is configured independently from the other HTTP controls.
For the built-in Supabase integration:
app.addAuth(withSupabase((options, config) => { options.url = config.get('SUPABASE_URL')! options.key = config.get('SUPABASE_KEY')!}))The authentication service is registered before the middleware module is configured.
When addAuth() has been called, addMiddlewares() connects AuthenticationMiddleware to the configured authentication service.
Without addAuth(), the middleware uses NoAuthGateKeeper.
Configure CORS and origins
Section titled “Configure CORS and origins”Allowed origins
Section titled “Allowed origins”The middleware configuration accepts an explicit origin list:
app.addMiddlewares((options) => { options.cors = { allowOrigins: ['https://app.example.com'], }})If options.cors.allowOrigins is empty, Xeno derives the default origin from:
APP_URL, when configured;- otherwise
http://localhost:<PORT>.
The origin is checked independently by the origin middleware.
Therefore:
options.cors.allowOriginscontrols which request origins are accepted, while:
options.cors.enabledcontrols whether CORS response handling is enabled.
These are related but separate concerns.
Credentials
Section titled “Credentials”Credentials are enabled by default:
options.cors = { withCredentials: true,}Avoid a wildcard allow-origin list when credentials are enabled. Xeno’s origin check accepts '*'; the CORS middleware responds with the requesting origin and credentials enabled rather than rejecting that configuration. Prefer an explicit allowlist:
options.cors = { allowOrigins: ['https://app.example.com'], withCredentials: true,}Use explicit origins when browser credentials are enabled.
Configure CSRF protection
Section titled “Configure CSRF protection”CSRF protection is opt-in.
Enable it by supplying csrf configuration:
app.addMiddlewares((options, config) => { options.csrf = { secret: config.get('CSRF_SECRET')!, cookieName: '__Host-xeno-csrf', headerName: 'x-csrf-token', cookieMaxAgeSeconds: 3600, sameSite: 'lax', }})The CSRF configuration supports:
interface CsrfConfig { secret: string cookieName?: string headerName?: string cookieMaxAgeSeconds?: number sameSite?: 'strict' | 'lax' | 'none'}When enabled, Xeno uses two middleware stages:
CsrfCookieMiddleware │ └── creates a user-bound CSRF cookie
CsrfMiddleware │ └── validates state-changing requestsThe CSRF middleware checks POST, PUT, DELETE, and PATCH requests. A matching route policy with withCsrf: false exempts that route.
For these methods it requires:
- a CSRF token in the configured request header;
- a CSRF token in the configured cookie;
- matching header and cookie values;
- a valid token associated with the authenticated user.
The default cookie name is:
__Host-xeno-csrfThe default token lifetime is 3600 seconds.
CSRF protection therefore complements authentication. The authentication credential identifies the caller; the CSRF token protects cookie-authenticated state-changing requests from forged requests.
See CSRF Protection.
Configure rate limiting
Section titled “Configure rate limiting”Rate limiting is configured through:
app.addMiddlewares((options) => { options.rateLimit = { maxRequests: 30, windowSeconds: 60, }})The configuration controls:
maxRequests— maximum number of requests;windowSeconds— duration of the rate-limit window.
When the limit is exceeded, the middleware returns:
429 Too Many Requestsand includes:
Retry-After: <window-seconds>Rate limiting uses the configured atomic cache and a rate-limit key derived from the request context and request path.
The default configuration is:
{ enabled: true, maxRequests: 100, windowSeconds: 60,}Change this explicitly for production workloads according to the expected traffic pattern.
See Rate Limiting.
Restrict HTTP methods
Section titled “Restrict HTTP methods”Route-specific method validation is derived from the route definitions supplied through addRoutes():
app.addRoutes(routes)When routes are configured, Xeno checks incoming methods against the methods declared for each route.
OPTIONS preflight handling is configured under cors and is enabled by default:
app.addMiddlewares((options) => { options.cors = { enablePreflight: true, }})This is useful when browser clients require CORS preflight handling.
See HTTP Methods.
Configure trusted client IP information
Section titled “Configure trusted client IP information”Xeno can be configured to use a trusted IP header:
app.addMiddlewares((options) => { options.trustedIpHeader = 'x-forwarded-for' options.trustedProxies = [ '10.0.0.10', ]})These settings affect how client IP information is resolved in the request context.
Only configure proxy/header trust when the application infrastructure actually controls the corresponding proxy path.
Do not blindly trust arbitrary client-supplied forwarding headers.
SSR authentication
Section titled “SSR authentication”For server-side rendering applications, enable SSR behavior:
app.addMiddlewares((options) => { options.isSSR = true})isSSR enables the SSR cookie response middleware. It does not change the default authentication extractor. Supabase SSR cookie extraction is configured by the Supabase authentication integration; see Supabase Authentication.
The normal extractor is:
Authorization: Bearer <token> │ ▼BearerTokenExtractorThe Supabase SSR integration can process:
Authorization header +Supabase authentication cookiesincluding chunked authentication cookies.
Custom authentication
Section titled “Custom authentication”The authentication integration can be replaced with a custom authentication service and credential extractor.
app.addAuth((options) => { options.tokenExtractor = (_scope) => new MyTokenExtractor() options.authService = (_scope) => new MyAuthService()})authService is required and is created per service scope. tokenExtractor is optional and defaults to the bearer-and-cookie extractor; a custom extractor factory is registered as a singleton.
The two components have separate responsibilities:
Token extractor = "Where does the credential come from?"
Authentication service = "How is the credential authenticated?"The resulting authenticated claims are mapped to the request identity.
Configure authorization
Section titled “Configure authorization”Authorization belongs to the application pipeline.
For example:
app.addPipeline(withAuthZ((opts) => { opts.policies = { CreateInvoice: { userId: true, tenantId: true, roles: ['admin', 'billing'], permissions: ['invoice:create'], }, }}))The policy can combine multiple strategy types.
CreateInvoice │ ├── user ID ├── tenant ID ├── roles └── permissionsXeno creates only the strategy types required by the configured policies.
Custom authorization strategies can also be supplied.
Authorization runs in the CQRS/application pipeline, not in the HTTP middleware stack.
User and tenant identity
Section titled “User and tenant identity”Authentication creates the request identity.
Authorization strategies can then consume identity fields such as:
userIdtenantIdrolespermissionsA policy such as:
{ CreateInvoice: { tenantId: true, },}is an authorization check against the authenticated identity.
It should not be interpreted as automatic resource ownership checking.
For example, requiring a tenant ID does not by itself mean that Xeno compares:
identity.tenantIdwith:
invoice.tenantIdApplication-specific ownership rules belong in application authorization logic or custom authorization strategies.
An intent without a matching policy requirement is not denied by default. Configure a policy for each operation that must be restricted.
Execute HTTP requests through the middleware stack
Section titled “Execute HTTP requests through the middleware stack”To execute a controller operation through the configured HTTP middleware, use the application’s handle() method:
const response = await app.handle(request, controllerToken, input)controllerToken must be the registry key for a registered controller. handle() dispatches through the HTTP middleware and requires middleware and an HTTP adapter to have been registered. The chain applies HTTP concerns such as:
- authentication;
- CORS;
- origin validation;
- method checks;
- rate limiting;
- CSRF;
- request context.
Conceptually:
HTTP request │ ▼app.handle(...) │ ▼configured middleware │ ▼application actionDo not bypass the configured middleware chain when an operation depends on HTTP security behavior.
See Middleware Execution.
Security boundaries
Section titled “Security boundaries”Xeno’s security features should be understood as separate controls.
| Mechanism | Protects |
|---|---|
| Authentication | Establishes caller identity |
| Authorization | Controls application request access |
| Origin validation | Restricts request origins |
| CORS | Controls browser cross-origin response behavior |
| HTTP method checks | Restricts methods available for registered routes |
| CSRF | Protects state-changing cookie-authenticated requests |
| Rate limiting | Limits request frequency |
| Trusted proxy configuration | Controls which infrastructure may provide client-IP metadata |
| Sanitization | Produces safer representations of untrusted values |
| IP masking | Reduces exposure of client IP information in logs/metadata |
No single mechanism replaces the others.
For example:
Authentication ≠ AuthorizationAuthentication ≠ CSRFCORS ≠ CSRFSanitization ≠ ValidationRate limiting ≠ AuthorizationRecommended configuration
Section titled “Recommended configuration”A typical secured application can compose the controls explicitly:
import { XenoAppBuilder, withAuthZ } from '@xeno-js/core'import { withSupabase } from '@xeno-js/supabase'
const app = new XenoAppBuilder()
app.addAuth(withSupabase((options, config) => { options.url = config.get('SUPABASE_URL')! options.key = config.get('SUPABASE_KEY')!
options.redirectTo = config.get('APP_URL')
options.ssr = { cookieOptions: { path: '/', httpOnly: true, sameSite: 'lax', secure: true, }, }}))
app.addMiddlewares((options, config) => { options.isSSR = true options.cors = { allowOrigins: [config.get('APP_URL')!], withCredentials: true, }
options.rateLimit = { maxRequests: 30, windowSeconds: 60 }
options.csrf = { secret: config.get('CSRF_SECRET')!, cookieName: '__Host-xeno-csrf', headerName: 'x-csrf-token', cookieMaxAgeSeconds: 3600, sameSite: 'lax', }})
app.addPipeline(withAuthZ((opts) => { opts.policies = { CreateInvoice: { userId: true, tenantId: true, permissions: ['invoice:create'], }, }}))
const application = await app.build()This produces a security flow of:
HTTP request │ ▼SSR cookie response (when enabled) │ ▼Origin validation │ ▼OPTIONS handling, method checks, then CORS │ ▼Rate limiting │ ▼Authentication │ ▼CSRF validation │ ▼Request identity │ ▼Authorization │ ▼Application handlerThe exact controls used by an application should match its authentication transport, browser usage, proxy topology, and application authorization requirements.
Troubleshooting
Section titled “Troubleshooting”Authentication is not being enforced
Section titled “Authentication is not being enforced”Check that both calls exist:
app.addAuth(...)app.addMiddlewares(...)addAuth() registers the authentication service.
addMiddlewares() installs the HTTP authentication middleware.
If addAuth() is omitted, Xeno uses NoAuthGateKeeper.
If application code uses the authentication service without HTTP middleware, register it with addAuth() and resolve it from an active service scope. The service is scoped; resolving it directly from the root container is not valid.
CSRF protection is not running
Section titled “CSRF protection is not running”Check that csrf is configured:
app.addMiddlewares((options) => { options.csrf = { secret: '...', }})CSRF is not enabled merely because authentication is enabled.
CORS rejects the request
Section titled “CORS rejects the request”Check:
options.cors?.allowOriginsand:
options.cors?.withCredentialsPrefer explicit allowed origins when credentials are enabled.
If cors.allowOrigins is empty, check APP_URL and PORT, because Xeno derives a default origin from them.
Requests are unexpectedly rate limited
Section titled “Requests are unexpectedly rate limited”Check:
options.rateLimitThe default is:
{ enabled: true, maxRequests: 100, windowSeconds: 60,}For a higher-throughput API, configure the limit explicitly.
Authorization does not run
Section titled “Authorization does not run”Authentication and authorization are separate.
Make sure the application has configured the pipeline:
app.addPipeline(withAuthZ((opts) => { opts.policies = { CreateInvoice: { roles: ['admin'], }, }}))Authentication alone creates an identity; it does not automatically authorize every application request.
Security documentation
Section titled “Security documentation”Docs Authentication
Section titled “Docs Authentication”Docs Authorization
Section titled “Docs Authorization”HTTP middleware
Section titled “HTTP middleware”- Middleware Overview
- Authentication Middleware
- CSRF Protection
- CORS
- HTTP Methods
- Rate Limiting
- Extractors
- Middleware Execution
Helpers
Section titled “Helpers”Support Us
Section titled “Support Us”Xeno.JS 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
