API Middleware & Audit Logging
Relevant source files
The following files were used as context for generating this wiki page:
The API Middleware and Audit Logging system within SweepBot provides a robust layer for request validation, authentication, and operational transparency. Utilizing the Fastify framework, these components ensure that every request to the backend is authenticated via Supabase JWTs and recorded for security auditing purposes.
This system serves as a critical security gate, enforcing user tiers and maintaining a detailed ledger of actions such as platform connections, session management, and sensitive user settings updates.
Sources: SWEEPBOT_DASHBOARD.html, AGENT_1_BACKEND_DATABASE.md
Authentication Middleware
Authentication is handled via a dedicated requireAuth Fastify hook. This middleware is responsible for extracting and verifying JSON Web Tokens (JWT) provided by Supabase.
JWT and Tier Enforcement
The middleware attaches user context to the request object, including the user's ID, email, and subscription tier. This tier information is used throughout the API to enforce feature gates and platform limits (e.g., Free vs. Pro limits on connected platforms).
Sources: SWEEPBOT_DASHBOARD.html, AGENTS.md
Error Handling in Auth
Authentication failures result in standardized error responses. If a token is missing, expired, or invalid, the middleware terminates the request early with a 401 Unauthorized status.
| Error Condition | HTTP Status | Response Code |
|---|---|---|
| Missing Token | 401 | UNAUTHORIZED |
| Invalid/Expired Token | 401 | INVALID_TOKEN |
| Insufficient Tier | 403 | INSUFFICIENT_PERMISSIONS |
Sources: PR_9_IMPLEMENTATION_GUIDE.md:92-105, CODEBASE_IMPROVEMENTS.md:40-48
Audit Logging System
The Audit Logging system is implemented as a Fastify plugin that hooks into the onResponse lifecycle event. This ensures that logs are captured after a request has been processed, allowing the system to record the resulting status code.
Data Capture Logic
The audit middleware captures several key data points for every tracked interaction:
- User Identity: The
userIdassociated with the request (if authenticated). - Action: The HTTP method and target URL.
- Client IP: The source IP address, extracted safely to prevent spoofing.
- User Agent: The browser or client string making the request.
- Status Code: The HTTP response code returned to the client.
IP Address Extraction and Security
To prevent IP spoofing via headers like x-forwarded-for, the system relies on Fastify's native request.ip parsing, which is configured to trust proxies only when explicitly defined in the server configuration. This is a critical security measure for applications deployed behind load balancers or services like Vercel.
| Field | Source | Security Consideration |
|---|---|---|
clientIp | request.ip | Validated against trustProxy config |
userId | request.user.id | Derived from verified JWT |
userAgent | request.headers['user-agent'] | Sanitized before storage |
Sources: PR_9_IMPLEMENTATION_GUIDE.md:120-135, PR_CODE_REVIEW_FIXES.md:85-91
Performance and Validation Middleware
In addition to security, middleware components handle cross-cutting concerns like input validation and rate limiting.
Zod Validation Middleware
SweepBot uses Zod schemas to validate all incoming request bodies and parameters. This prevents malformed data from reaching the database and provides the client with clear validation error messages.
Rate Limiting
The API utilizes @fastify/rate-limit. In production environments, this is backed by Redis (Upstash) to ensure distributed rate limiting across multiple API instances. This prevents brute-force attacks and resource exhaustion.
Summary
The API Middleware and Audit Logging framework provides the primary security and observability foundation for SweepBot. By combining JWT-based authentication with a post-response audit hook, the system ensures that every user action is both authorized and accounted for, while Zod validation and Redis-backed rate limiting maintain the stability and integrity of the API.