From 13f372390b5f6d00a5e556366613b4d7bc18bb69 Mon Sep 17 00:00:00 2001 From: Mathis HERRIOT <197931332+0x485254@users.noreply.github.com> Date: Sat, 17 May 2025 10:33:38 +0200 Subject: [PATCH] feat(backend): add cookie parser and CSRF protection middleware --- backend/src/main.ts | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/backend/src/main.ts b/backend/src/main.ts index e748dc0..4edab91 100644 --- a/backend/src/main.ts +++ b/backend/src/main.ts @@ -2,6 +2,8 @@ import { NestFactory } from '@nestjs/core'; import { ValidationPipe } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; +import * as cookieParser from 'cookie-parser'; +import * as csurf from 'csurf'; import { AppModule } from './app.module'; async function bootstrap() { @@ -17,8 +19,34 @@ async function bootstrap() { }), ); - // Configuration CORS selon l'environnement + // Configure cookie parser + app.use(cookieParser()); + + // Get environment configuration const environment = configService.get('NODE_ENV', 'development'); + + // Configure CSRF protection + if (environment !== 'test') { // Skip CSRF in test environment + app.use(csurf({ + cookie: { + httpOnly: true, + sameSite: 'strict', + secure: environment === 'production' + } + })); + + // Add CSRF token to response + app.use((req, res, next) => { + res.cookie('XSRF-TOKEN', req.csrfToken?.() || '', { + httpOnly: false, // Client-side JavaScript needs to read this + sameSite: 'strict', + secure: environment === 'production' + }); + next(); + }); + } + + // Configuration CORS selon l'environnement const frontendUrl = configService.get('FRONTEND_URL', 'http://localhost:3001'); if (environment === 'development') {