Fastify CSRF does not create a header or cookie and does not check it

447 views Asked by At

I have a frontend in NextJS and a backend in NestJS. I noticed that the token is not checked on the back-end side, nor is any X-CSRF-TOKEN header or cookie created, even though the code is in accordance with the documentation. After researching and asking ChatGPT who said that I should work normally and add headers or create a cookie file, I decided to write here. Anyone know why the token isn't being created? I guess it's not due to a bug in the @fastify/csrf-protection types? Also, there is no error and also when there is no token, it normally loads routes which should not be the case and without the token you should not be able to access the page.

My Code:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { FastifyInstance } from 'fastify';
import fastifyCookie, { CookieSerializeOptions } from '@fastify/cookie';
import fastifyCsrf from '@fastify/csrf-protection';
import { randomBytes } from 'crypto';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  const fastifyInstance: FastifyInstance = app.getHttpAdapter().getInstance();
  fastifyInstance
    .addHook('onRequest', async (req, res) => {
      req.socket['encrypted'] = process.env.NODE_ENV === 'production';
      res.header('X-Powered-By', 'CyberSecurity');
    })
    .decorateReply('setHeader', function (name: string, value: unknown) {
      this.header(name, value);
    })
    .decorateReply('end', function () {
      this.send('');
    });
  const configService = app.get(ConfigService);
  const port = configService.get<string>('PORT', '');

  // Throttler - Protection
  app.enableCors({
    origin: '*',
    methods: 'GET, HEAD, PUT, PATCH, POST, DELETE',
    allowedHeaders: 'Content-Type, Authorization',
    credentials: true,
  });

  // XCSRF - Protection
  await app.register(fastifyCookie, {
    secret: randomBytes(32).toString('base64'),
  });
  await app.register(fastifyCsrf, {
    sessionPlugin: '@fastify/cookie',
    cookieKey: 'csrf-token',
    cookie: (cookieOptions: CookieSerializeOptions) => ({
      httpOnly: true,
      sameSite: 'strict',
      path: '/',
      secure: true,
      signed: false,
      ...cookieOptions,
    }),
    secret: randomBytes(32).toString('base64'),
  } as any);

  await app.listen(port);
}
bootstrap();

Here I am sending you my versions of packages:

@nestjs v9.4.0
@nestjs/platform-fastify v9.4.0
@fastify/cookie v8.3.0
@fastify/csrf-protection v6.3.0
0

There are 0 answers