csrfProtection.js•1.44 kB
/**
* CSRF Protection middleware
* Protects against Cross-Site Request Forgery attacks
*/
const csrf = require('csurf');
const { AuthorizationError } = require('../utils/errorTypes');
const logger = require('../utils/logger');
// Create CSRF protection middleware
const csrfProtection = csrf({
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict'
}
});
/**
* CSRF error handler middleware
* Catches CSRF errors and returns a formatted error response
*/
const handleCsrfError = (err, req, res, next) => {
if (err.code !== 'EBADCSRFTOKEN') {
return next(err);
}
// Log CSRF attack attempt
logger.warn(`CSRF attack detected from IP: ${req.ip}`);
// Return authorization error
next(new AuthorizationError('Invalid CSRF token. Form has been tampered with.'));
};
/**
* Generate CSRF token and attach to response
* Use this middleware for routes that serve forms
*/
const generateCsrfToken = (req, res, next) => {
// Attach CSRF token to response locals for template rendering
res.locals.csrfToken = req.csrfToken();
next();
};
/**
* Middleware to disable CSRF protection for specific routes
* Use this for routes that don't need CSRF protection (e.g., webhooks)
*/
const disableCsrf = (req, res, next) => {
req.csrfToken = () => '';
next();
};
module.exports = {
csrfProtection,
handleCsrfError,
generateCsrfToken,
disableCsrf
};