This document describes the comprehensive security enhancements implemented for the Verinode API to protect against common web vulnerabilities and attacks.
Purpose: Prevent abuse and DoS attacks by limiting request rates.
Features:
- Multiple rate limiters for different endpoints:
- General API: 100 requests per 15 minutes
- Authentication: 5 attempts per 15 minutes
- GraphQL queries: 60 per minute
- GraphQL mutations: 30 per minute
- File uploads: 10 per hour
- IP-based tracking with X-Forwarded-For support
- Configurable windows and limits
- Proper 429 status responses with retry information
Usage:
import { strictRateLimiter, authRateLimiter } from './middleware/rateLimiter';
app.use('/graphql', strictRateLimiter);
app.use('/auth', authRateLimiter);Purpose: Validate and sanitize all incoming data to prevent injection attacks.
Features:
- Custom validation system without external dependencies
- Support for required fields, length limits, pattern matching
- Built-in validation rules for common fields (email, username, password)
- Automatic request body sanitization
- Content-Type validation
- Payload size limits (10MB default)
Usage:
import { validateBody, commonValidationRules } from './middleware/inputValidation';
app.use('/api', validateBody(commonValidationRules.email));Purpose: Control cross-origin requests to prevent unauthorized access.
Features:
- Environment-specific CORS policies
- Production mode with whitelisted origins
- Strict CORS for sensitive endpoints
- Development mode with relaxed restrictions
- Proper preflight handling
Configuration:
- Development: Allows localhost origins
- Production: Restricted to configured domains
- Strict mode: Limited methods and headers
Purpose: Add comprehensive security headers to prevent client-side attacks.
Headers Implemented:
X-Content-Type-Options: nosniffX-Frame-Options: DENYX-XSS-Protection: 1; mode=blockReferrer-Policy: strict-origin-when-cross-originPermissions-Policy: Restricts browser featuresContent-Security-Policy: Comprehensive CSP in productionStrict-Transport-Security: HSTS in production
Purpose: Monitor and log all requests for security analysis.
Features:
- Unique request ID tracking
- Security flag detection (XSS, SQL injection, suspicious patterns)
- IP-based monitoring
- User agent analysis
- Error and attack logging
- Configurable log retention
- Security alerting for high-severity events
Security Flags Detected:
- SQL injection attempts
- XSS attempts
- Suspicious user agents
- Large payloads
- Authentication failures
- Rate limit violations
Purpose: Clean and sanitize input data to remove dangerous content.
Features:
- String sanitization (removes HTML tags, JavaScript, CSS expressions)
- HTML sanitization (removes scripts and dangerous elements)
- SQL injection prevention (removes dangerous characters)
- Recursive object sanitization
- Key sanitization to prevent injection
Purpose: Detect and prevent Cross-Site Scripting attacks.
Features:
- XSS pattern detection
- HTML tag filtering
- Event handler removal
- JavaScript URL removal
- Configurable allowed tags and attributes
- Output sanitization middleware
Centralized security configuration with environment-specific settings:
module.exports = {
rateLimiting: { /* rate limit configs */ },
cors: { /* CORS configs */ },
securityHeaders: { /* header configs */ },
validation: { /* validation rules */ },
xssProtection: { /* XSS settings */ },
logging: { /* logging configuration */ },
// ... more security settings
};Automated security auditing tool that checks:
- File permissions
- Environment variables
- Dependency vulnerabilities
- Code security patterns
- Configuration security
- Default secrets usage
Usage:
npm run security:auditThe security middleware is integrated in a specific order in src/graphql/server.ts:
- Request logging (first to capture everything)
- Security headers
- CORS configuration
- Rate limiting
- Content validation
- XSS protection and input sanitization
- Body parsing
GET /health
Returns server health status.
GET /security-status
Returns current security feature status.
Comprehensive security tests are available in src/test/security.test.ts:
- Rate limiting tests
- CORS validation tests
- Security header verification
- Input validation tests
- XSS protection tests
- SQL injection prevention tests
Run security tests:
npm run test:securityRun full security check:
npm run security:checkRequired for production:
NODE_ENV=productionJWT_SECRET(strong, random secret)SESSION_SECRET(strong, random secret)ALLOWED_ORIGINS(comma-separated list of allowed domains)
Recommended:
LOG_LEVEL=infoLOG_TO_FILE=trueLOG_FILE_PATH=./logs/security.log
- Defense in Depth: Multiple layers of security controls
- Principle of Least Privilege: Minimal required permissions
- Fail Securely: Secure defaults when errors occur
- Input Validation: Validate all inputs at multiple layers
- Output Encoding: Encode all outputs to prevent injection
- Logging and Monitoring: Comprehensive security logging
- Regular Auditing: Automated security audit script
- Environment Separation: Different configs for dev/prod
The system automatically:
- Logs all security events
- Detects attack patterns
- Generates alerts for high-severity events
- Tracks suspicious IP addresses
- Monitors authentication failures
✅ Rate limiting: Returns 429 status when limits exceeded
✅ Input validation: Malicious input is sanitized and rejected
✅ CORS policy: Properly enforced based on environment
✅ Security headers: All recommended headers present
✅ Attack detection: Logged and blocked automatically
✅ SQL injection prevention: Pattern detection and sanitization
✅ XSS protection: Detection and removal of XSS content
✅ Request logging: Comprehensive logging with security monitoring
- Set strong secrets for JWT and session
- Configure proper CORS origins
- Enable production security headers
- Set up log rotation for security logs
- Monitor security alerts
- Run regular security audits
- Keep dependencies updated
- Redis-based rate limiting for distributed systems
- Web Application Firewall (WAF) integration
- Advanced bot detection
- API key authentication
- Request signing
- IP whitelisting/blacklisting
- Advanced anomaly detection