Security Features Documentation
This document provides a comprehensive overview of all security features implemented in the SkillSpark Backend API.
The API implements a multi-layered security approach with the following components:
- HTTP Security Headers (Helmet.js)
- Rate Limiting (express-rate-limit)
- Input Validation & Sanitization (express-validator)
- CORS Protection (cors)
- Request Sanitization (Custom middleware)
- Comprehensive Logging (Morgan + Custom logger)
- Error Handling (Secure error responses)
Purpose: Protects against common web vulnerabilities by setting secure HTTP headers.
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"], // Only allow resources from same origin
styleSrc: ["'self'", "'unsafe-inline'"], // Allow inline styles (needed for some frameworks)
scriptSrc: ["'self'"], // Only allow scripts from same origin
imgSrc: ["'self'", "data:", "https:"], // Allow images from same origin, data URLs, and HTTPS
connectSrc: ["'self'", "https://generativelanguage.googleapis.com", "https://www.googleapis.com"],
fontSrc: ["'self'"], // Only allow fonts from same origin
objectSrc: ["'none'"], // Block all object/embed/applet elements
mediaSrc: ["'self'"], // Only allow media from same origin
frameSrc: ["'none'"], // Block all iframe elements
}
}Protection Against:
- Cross-Site Scripting (XSS) attacks
- Data injection attacks
- Clickjacking
- Code injection
hsts: {
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true, // Apply to all subdomains
preload: true // Include in browser preload lists
}Protection Against:
- Man-in-the-middle attacks
- Protocol downgrade attacks
- Cookie hijacking
- X-Content-Type-Options:
nosniff- Prevents MIME type sniffing - X-Frame-Options:
DENY- Prevents clickjacking - X-XSS-Protection:
1; mode=block- Enables XSS filtering - Referrer-Policy: Controls referrer information sent
Purpose: Prevents API abuse, DoS attacks, and ensures fair usage.
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // 100 requests per IP per 15 minuteswindowMs: 60 * 1000, // 1 minute
max: 5 // 5 requests per IP per minutewindowMs: 60 * 1000, // 1 minute
max: 10 // 10 requests per IP per minute{
"success": false,
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Too many requests from this IP, please try again later.",
"details": "Rate limit exceeded"
}
}Protection Against:
- Denial of Service (DoS) attacks
- API abuse and resource exhaustion
- Brute force attacks
- Automated scraping
RateLimit-Limit: Maximum requests allowedRateLimit-Remaining: Requests remaining in current windowRateLimit-Reset: Time when the rate limit resets
Purpose: Ensures all user input is valid, safe, and properly formatted.
body("topic")
.trim() // Remove whitespace
.isLength({ min: 1, max: 500 }) // Length constraints
.withMessage("Topic must be between 1 and 500 characters");body("pointTitle")
.trim() // Remove whitespace
.isLength({ min: 1, max: 500 }) // Length constraints
.withMessage("Point title must be between 1 and 500 characters");- Simple Length Validation: Only checks minimum and maximum length
- Whitespace Trimming: Removes leading/trailing spaces
- Generous Limits: 500 characters allow for comprehensive topics
- No Character Restrictions: Accepts all Unicode characters including symbols, emojis, and special characters
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": "topic: Topic must be between 1 and 200 characters"
}
}Protection Against:
- SQL Injection
- NoSQL Injection
- Command Injection
- Cross-Site Scripting (XSS)
- Path Traversal attacks
Purpose: Controls which domains can access the API from browsers.
const corsOptions = {
origin: process.env.ALLOWED_ORIGINS
? process.env.ALLOWED_ORIGINS.split(",").map((origin) => origin.trim())
: true, // Allow all origins in development
credentials: true, // Allow cookies/credentials
optionsSuccessStatus: 200, // Support legacy browsers
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization", "x-api-key"],
};ALLOWED_ORIGINS=https://yourdomain.com,https://app.yourdomain.comProtection Against:
- Cross-Origin Request Forgery (CSRF)
- Unauthorized cross-origin access
- Data theft from malicious websites
Purpose: Removes malicious content from user input.
export const sanitizeRequest = (req, res, next) => {
if (req.body) {
const sanitize = (obj) => {
for (const key in obj) {
if (typeof obj[key] === "string") {
obj[key] = obj[key].replace(/\0/g, ""); // Remove null bytes
} else if (typeof obj[key] === "object" && obj[key] !== null) {
sanitize(obj[key]); // Recursively sanitize nested objects
}
}
};
sanitize(req.body);
}
next();
};- Null bytes (
\0) - Often used in injection attacks - Nested objects - Recursively cleaned
- All string values - Processed for malicious content
Protection Against:
- Null byte injection
- Binary data injection
- Format string attacks
Purpose: Tracks security events, API usage, and potential threats.
// Development: Detailed console output
morgan("dev");
// Production: File-based logging with custom format
(':real-ip - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" :response-time-ms');appLogger.info("Generating roadmap", {
topic,
ip: req.ip,
userAgent: req.get("user-agent"),
});
appLogger.error("Error generating roadmap", error, {
topic: req.body?.topic,
processingTime: `${processingTime}ms`,
ip: req.ip,
userAgent: req.get("user-agent"),
});// Automatic error logging with stack traces
const timestamp = new Date().toISOString();
const logEntry = `${timestamp} - ERROR - ${req.method} ${req.url} - ${err.message}\n${err.stack}\n\n`;logs/access.log- All HTTP requestslogs/error.log- Errors and exceptions- Console output - Development logging
- Failed requests and their sources
- Rate limit violations
- Invalid input attempts
- Error patterns and frequencies
- User agent analysis for bot detection
Benefits:
- Security incident detection
- Performance monitoring
- Debugging and troubleshooting
- Compliance and audit trails
Purpose: Prevents information disclosure while providing useful feedback.
{
"success": false,
"error": {
"code": "ERROR_CODE", // Standardized error code
"message": "User-friendly message",
"details": "Additional context"
}
}// Production: Generic error messages
details: NODE_ENV === "production" ? "Please try again later" : error.message;
// Development: Detailed error information
details: error.message;VALIDATION_ERROR- Input validation failuresRATE_LIMIT_EXCEEDED- Rate limiting violationsGENERATION_FAILED- AI service failuresINTERNAL_SERVER_ERROR- Unexpected errorsNOT_FOUND- Route not found
Protection Against:
- Information disclosure
- Stack trace leakage
- Internal system exposure
- Database schema revelation
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true, limit: "10mb" }));app.use(compression()); // Reduces bandwidth and improves performanceapp.set("trust proxy", 1); // For accurate IP detection behind reverse proxiesMultiple layers of security rather than relying on a single mechanism.
Only necessary permissions and access are granted.
Secure configurations by default, requiring explicit actions to reduce security.
All user input is validated and sanitized before processing.
Comprehensive logging for security monitoring and incident response.
Secure error responses that don't leak sensitive information.
The included test.js file includes security tests:
- Rate Limiting Test: Verifies rate limits are enforced
- Input Validation Test: Tests invalid input handling
- Error Response Test: Ensures proper error formatting
- CORS Test: Validates cross-origin policies
node test.js- Set
NODE_ENV=production - Configure
ALLOWED_ORIGINSfor CORS - Set up reverse proxy with SSL/TLS
- Configure log rotation
- Set up monitoring and alerting
- Regular security updates
- Backup and disaster recovery
- Security scanning and penetration testing
- High error rates
- Rate limit violations
- Unusual traffic patterns
- Failed validation attempts
- Geographic anomalies
- Check logs for attack patterns
- Implement IP blocking if necessary
- Scale rate limits down temporarily
- Review and update security rules
- Document and analyze the incident
This comprehensive security implementation provides enterprise-level protection while maintaining API usability and performance.