API Middleware
Relevant source files
The following files were used as context for generating this wiki page:
The API Middleware layer in the Subito project provides essential cross-cutting concerns including security, authentication, request tracing, and traffic control. Built primarily on the Hono framework, these middlewares ensure that incoming requests are validated, authorized, and rate-limited before reaching the application's business logic.
This layer handles critical security tasks such as JWT verification, role-based access control (RBAC), and protection against brute-force attacks via Redis-backed rate limiting. It also integrates with infrastructure logging to provide traceability for every request across the system.
Sources: apps/api/src/app.ts:1-70, apps/api/src/middleware/auth.ts:1-118
Global Request Pipeline
All requests entering the Subito API pass through a series of global middlewares defined in the main application entry point. This pipeline initializes request context and enforces standard security headers.
Standard Pipeline Components
The following middlewares are applied to every route (*):
- Request ID & Timing: Generates a unique
requestIdand tracks execution duration. - Secure Headers: Implements security best practices (e.g., HSTS, XSS protection).
- CORS: Manages cross-origin resource sharing based on environment-specific allow-lists.
- Logging: Captures request metadata including method, path, status, and custom client headers like
X-PlatformandX-App-Version.
Sources: apps/api/src/app.ts:40-70
Request Flow Diagram
The diagram below illustrates the sequence of global middlewares processed for a typical API request.
Sources: apps/api/src/app.ts:40-80
Authentication and Authorization
Authentication middleware manages user identity through Bearer tokens and validates sessions against a blacklist. The system distinguishes between mandatory and optional authentication contexts.
Authentication Middlewares
| Middleware | Purpose | Behavior |
|---|---|---|
requireAuth | Mandatory Auth | Throws UnauthorizedError if token is missing, invalid, or blacklisted. |
optionalAuth | Permissive Auth | Sets user context if a valid token exists, but allows the request to proceed if missing. |
requireRole | RBAC | Validates the user's role against required values (customer, partner, admin). |
Sources: apps/api/src/middleware/auth.ts:14-118
JWT Verification Logic
The authentication middleware performs several checks:
- Blacklist Check: Calls
isTokenBlacklistedto ensure the token hasn't been revoked. - Payload Validation: Verifies the JWT signature and expiration using
verifyToken. - Device Integrity: Compares the
deviceIdin the JWT against theX-Device-IDrequest header. - Session Refresh: Updates the session activity via
touchSessionFromPayload.
Sources: apps/api/src/middleware/auth.ts:25-50, apps/api/src/lib/jwt.ts:100-120
Role-Based Access Control (RBAC) Flow
The RBAC middleware restricts access to specific endpoints based on user roles defined in the database schema.
Rate Limiting
Rate limiting is implemented using an atomic Redis script to prevent race conditions (TOCTOU) when incrementing request counters. It identifies users based on their userId (if authenticated) or their IP address.
Rate Limit Configuration
The system defines several pre-configured rate limit tiers:
| Policy | Window | Max Requests | Key Prefix |
|---|---|---|---|
authRateLimit | 60s | 10 | ratelimit:auth |
apiRateLimit | 60s | 100 | ratelimit:api |
checkoutRateLimit | 60s | 5 | ratelimit:checkout |
Sources: apps/api/src/middleware/rate-limit.ts:65-80
Redis Lua Script Implementation
The middleware uses a Lua script to ensure that the increment and expiration setting are performed in a single atomic operation.
// apps/api/src/middleware/rate-limit.ts:15-23
const RATE_LIMIT_SCRIPT = `
local key = KEYS[1]
local window = tonumber(ARGV[1])
local current = redis.call('INCR', key)
if current == 1 then
redis.call('EXPIRE', key, window)
end
local ttl = redis.call('TTL', key)
return {current, ttl}
`
Sources: apps/api/src/middleware/rate-limit.ts:15-23
Error Handling
A centralized errorHandler middleware is registered to catch all exceptions thrown during the request lifecycle. It ensures that internal errors do not leak sensitive information and provides a consistent JSON error format.
Standardized Error Response
When an error occurs (such as a 404 or an UnauthorizedError), the API returns a structured response:
success: Boolean false.error: Object containing a stringcodeand a descriptivemessage.
Sources: apps/api/src/app.ts:82-105
Summary
The API Middleware layer serves as the primary security and stability gatekeeper for the Subito API. By chaining global tracing, Redis-backed rate limiting, and strict JWT-based role validation, the system maintains high observability and prevents unauthorized access to sensitive service endpoints.
Sources: apps/api/src/app.ts, apps/api/src/middleware/auth.ts