Security & Middleware
Relevant source files
The following files were used as context for generating this wiki page:
The Security and Middleware layer of the SoulSeer API provides a robust defense-in-depth strategy to protect spiritual consultations, financial transactions, and user data. This system integrates standardized security headers, granular rate limiting, strict request validation, and centralized error handling to ensure platform integrity and availability.
Middleware is implemented as a series of functions that intercept requests before they reach business logic handlers. These components work together to sanitize input, prevent denial-of-service (DoS) attacks, and maintain a consistent response format for clients.
Request Pipeline and Security Headers
SoulSeer utilizes a multi-layered middleware pipeline for every incoming request. High-level security is enforced using helmet for HTTP headers and cors for Cross-Origin Resource Sharing.
Security Configurations
The platform configures helmet with a strict Content Security Policy (CSP) to allow only trusted sources for scripts, styles, and connections. This is particularly critical for Agora (RTC/RTM) and Stripe integrations.
This diagram illustrates the sequential flow of a request through the middleware stack.
Sources: server/src/index.ts:31-64, server/src/production.ts:24-34
| Component | Function | Configuration Detail |
|---|---|---|
| Helmet | HTTP Header Security | Configures CSP for Agora, Stripe, and Fonts; sets HSTS (1 year). |
| CORS | Cross-Origin Policy | Restricted to config.corsOrigin with support for credentials and specific methods. |
| Pino-HTTP | Request Logging | Automatic logging of requests, excluding health checks (/api/health). |
| JSON Parser | Payload Handling | Limits JSON bodies to 2MB; supports raw bodies for webhooks. |
Sources: server/src/index.ts:31-90, server/src/production.ts:24-43
Rate Limiting
The API implements three distinct levels of rate limiting to balance user experience with system protection. These are configured using express-rate-limit.
- General Limiter: Applied globally to all routes to prevent broad abuse.
- Strict Limiter: Applied to sensitive endpoints such as authentication, payment intent creation, and balance top-ups.
- Webhook Limiter: Specific to Stripe webhook endpoints to handle high-volume event notifications safely.
Sources: server/src/index.ts:85-104, server/src/routes/payments.ts:161-165
Request Validation
SoulSeer employs a "parse, don't validate" approach using the zod library. Validation middleware ensures that the API only processes data that conforms to the expected schema, stripping unknown fields to prevent mass assignment vulnerabilities.
Validation Logic
The validate middleware (also aliased as validateBody) and validateQuery are used to check request payloads and URL parameters against shared schemas.
Sequence showing how Zod schemas act as a gatekeeper for route handlers.
Sources: server/src/middleware/validate.ts, server/src/middleware/tests/validate.test.ts:47-81
Shared Validators
Validation schemas are defined in a shared package to ensure consistency between the client and server.
| Schema Name | Target Entity | Key Constraints |
|---|---|---|
userSyncSchema | Auth0 Integration | Requires auth0Id, email. |
createReadingSchema | Sessions | Validates readerId and type (chat, voice, video). |
createTopUpSchema | Payments | Minimum $5.00 (500 cents), Maximum $10,000. |
createForumPostSchema | Community | Title (max 200), Content (max 10,000), valid category. |
Sources: shared/src/validators.ts:40-45, shared/src/validators.ts:74-77, shared/src/validators.ts:83-85, shared/src/validators.ts:104-108
Error Handling
A centralized globalErrorHandler is mounted as the final middleware in the Express application. It ensures that all errors, whether synchronous or asynchronous (via next(err)), result in a consistent JSON response.
Error Response Structure
The handler categorizes errors into known types (like Validation or Auth) and provides a safe fallback for internal server errors to avoid leaking sensitive stack traces in production.
// Conceptual structure based on implementation usage
{
error: string; // Human readable message
code: string; // Machine readable error code (e.g., 'VALIDATION_ERROR')
details?: Array<{ // Optional array of specific field errors
path: string;
message: string;
}>;
}
Sources: server/src/middleware/error-handler.ts, server/src/middleware/tests/validate.test.ts:71-80, server/src/index.ts:153-154
Production & SPA Middleware
In a production environment (deployed on Fly.io), the middleware stack includes additional logic to serve static client assets and handle Single Page Application (SPA) routing.
- Static Assets: Served from
client/dist. - SPA Fallback: All non-API requests (
!req.path.startsWith('/api')) are redirected toindex.htmlto allow client-side routing. - Stripe Compatibility: The JSON parser is explicitly bypassed for the
/api/payments/webhookpath to preserve the raw body required for Stripe signature verification.
Sources: server/src/production.ts:37-65, server/src/index.ts:93-97
Summary
The Security & Middleware system in SoulSeer serves as the platform's first line of defense. By combining helmet for browser-level security, zod for rigorous data integrity, and tiered rate limiting for availability, the architecture ensures a secure environment for spiritual guidance and financial transactions. The centralized error handling and production-specific routing further enhance the maintainability and reliability of the service.