| import { Request, Response, NextFunction } from 'express';
|
| import crypto from 'crypto';
|
|
|
| |
| |
| |
|
|
| export const csrfProtection = (req: Request, res: Response, next: NextFunction) => {
|
|
|
| let token = req.cookies['csrf-token'];
|
|
|
| if (!token) {
|
| token = crypto.randomBytes(32).toString('hex');
|
| res.cookie('csrf-token', token, {
|
| httpOnly: false,
|
| sameSite: 'lax',
|
| secure: process.env.NODE_ENV === 'production',
|
| path: '/',
|
| });
|
| }
|
|
|
|
|
| (req as any).csrfToken = token;
|
|
|
|
|
| if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) {
|
| return next();
|
| }
|
|
|
|
|
| const clientToken = req.headers['x-csrf-token'];
|
|
|
| if (!clientToken || clientToken !== token) {
|
| return res.status(403).json({
|
| error: 'CSRF token missing or invalid',
|
| });
|
| }
|
|
|
| next();
|
| };
|
|
|
| |
| |
|
|
| export const getCsrfToken = (req: Request, res: Response) => {
|
| res.status(200).json({ csrfToken: (req as any).csrfToken });
|
| };
|
|
|