fastify / fastify-swagger

Swagger documentation generator for Fastify
MIT License
941 stars 209 forks source link

instance.swaggerCSP.script - swaggerCSP is undefined #689

Closed LuisBarroso37 closed 1 year ago

LuisBarroso37 commented 1 year ago

Prerequisites

Fastify version

4.9.2

Plugin version

8.1.0

Node.js version

18.12

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

Windows 10

Description

I get this error when I start running my server:

'script-src': ["'self'"].concat(instance.swaggerCSP.script),

          ^
TypeError: Cannot read properties of undefined (reading 'script')

I have checked the issues in this repository and apparently this was an issue in the past but it appeared to have been solved.

Can anyone help?

Steps to Reproduce

import helmet from '@fastify/helmet';
import swagger from '@fastify/swagger';

...

server.register(cors, {
    origin: config.server.frontendUrl,
    methods: ['GET', 'PUT', 'POST', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true,
  });
  server.register(swagger, {
   ...
  });
  server.register(helmet, (instance) => {
    return {
      contentSecurityPolicy: {
        directives: {
          ...helmet.contentSecurityPolicy.getDefaultDirectives(),
          'form-action': ["'self'"],
          'img-src': ["'self'", 'data:', 'validator.swagger.io'],
          'script-src': ["'self'"].concat(instance.swaggerCSP.script),
          'style-src': ["'self'", 'https:'].concat(instance.swaggerCSP.style),
        },
      },
    };
  });

Expected Behavior

No response

Uzlopak commented 1 year ago

swaggerCSP is part of @fastify/swagger-ui.

You have to register it after registering @fastify/swagger and before helmet

Uzlopak commented 1 year ago

See also https://github.com/fastify/fastify-swagger/blob/master/MIGRATION.md

LuisBarroso37 commented 1 year ago

Thanks @Uzlopak! That worked!