Authentication & Security Middleware
Relevant source files
The following files were used as context for generating this wiki page:
- backend/src/services/auth.service.ts
- backend/src/middleware/auth.middleware.ts
- backend/src/middleware/rateLimit.middleware.ts
- backend/src/middleware/csrf.middleware.ts
- backend/src/utils/jwt.ts
- ARCHIVE/remaining-docs-consolidated-2026-02-13/TAMV-BACKEND-COMPLETE.md
- ARCHIVE/remaining-docs-consolidated-2026-02-13/IMPLEMENTATION-PROGRESS-REPORT.md
The Authentication and Security Middleware system in the TAMV project is a production-ready framework designed to secure the backend API through multiple defensive layers. It integrates JSON Web Token (JWT) authentication, Role-Based Access Control (RBAC), multi-tiered rate limiting, and Cross-Site Request Forgery (CSRF) protection to ensure data integrity and user sovereignty.
The core purpose of this module is to validate user identities, enforce permissions, and protect the infrastructure against common web vulnerabilities such as brute-force attacks, XSS, and unauthorized data extraction. By utilizing a "Zero Trust" approach, every request is verified through a chain of specialized middleware components before reaching the core business logic.
Sources: TAMV-BACKEND-COMPLETE.md, IMPLEMENTATION-PROGRESS-REPORT.md
Authentication System
The authentication layer utilizes a JWT-based strategy involving short-lived access tokens and long-lived refresh tokens. This architecture allows for secure session management without requiring the server to maintain state for every active user.
JWT Infrastructure
The system uses the jsonwebtoken library to generate and verify tokens. Access tokens are typically configured for a 15-minute lifespan, while refresh tokens last for 7 days. This separation ensures that even if an access token is compromised, its window of utility is limited.
Authentication Middleware
The auth.middleware.ts file provides two primary functions:
- requireAuth: A strict middleware that extracts the Bearer token from the Authorization header. If the token is missing, invalid, or expired, it returns a
401 Unauthorizederror. - optionalAuth: A lenient version that attempts to verify the token but allows the request to proceed if it is missing, simply leaving the user context empty.
Sources: backend/src/middleware/auth.middleware.ts
Security Middleware Layers
TAMV implements multiple security middlewares to harden the API against various attack vectors.
Multi-Tiered Rate Limiting
The system employs express-rate-limit to prevent abuse and brute-force attempts. Rate limits are applied at different tiers based on the sensitivity of the operation.
| Tier | Limit | Window | Purpose |
|---|---|---|---|
| API Limiter | 100 requests | 15 minutes | General API protection |
| Auth Limiter | 5 requests | 15 minutes | Brute-force prevention on Login/Register |
| Post Limiter | 10 posts | 1 hour | Spam prevention for social content |
| Upload Limiter | 20 uploads | 1 hour | Resource exhaustion protection |
Sources: backend/src/middleware/rateLimit.middleware.ts, TAMV-BACKEND-COMPLETE.md
CSRF Protection
The csrf.middleware.ts implements the Double-Submit Cookie pattern. It generates a CSRF token that must be sent in the request headers (e.g., X-CSRF-Token) for state-changing operations (POST, PUT, DELETE). This prevents malicious sites from executing actions on behalf of an authenticated user.
Sources: backend/src/middleware/csrf.middleware.ts
Role-Based Access Control (RBAC)
Beyond basic authentication, the authorization.middleware.ts manages granular permissions. Users are assigned roles (e.g., user, moderator, admin), and specific endpoints use helper functions like requireAdmin or requireModerator to restrict access.
Token Management & Session Logic
The auth.service.ts handles the business logic for session lifecycle, including login, logout, and token rotation.
Session Data Structure
The database maintains a sessions table to track refresh tokens, ensuring that the server can revoke sessions if security is compromised.
| Field | Type | Description |
|---|---|---|
id | UUID | Primary key |
user_id | UUID | Link to the user owner |
token | String | The refresh token string |
ip_address | String | Origin IP for audit |
user_agent | String | Client info for session tracking |
expires_at | DateTime | Expiry timestamp |
Sources: TAMV-BACKEND-COMPLETE.md, backend/src/services/auth.service.ts
Security Implementation Snippet
The following illustrates how JWTs are signed with specific algorithms and secrets:
// backend/src/utils/jwt.ts
import jwt from 'jsonwebtoken';
export const generateToken = (payload: object, secret: string, expires: string) => {
return jwt.sign(payload, secret, {
expiresIn: expires,
algorithm: 'HS256'
});
};
Sources: backend/src/utils/jwt.ts:5-10
Conclusion
The Authentication & Security Middleware system provides a unified defense-in-depth strategy for the TAMV platform. By combining JWT session management with multi-layered rate limiting and CSRF protection, the architecture ensures that user sovereignty and data privacy are maintained while the infrastructure remains resilient against automated attacks and unauthorized access.