GithubHelp home page GithubHelp logo

fastify-helmet's Introduction

@fastify/helmet

CI NPM version js-standard-style

Important security headers for Fastify. It is a tiny wrapper around helmet.

Install

npm i @fastify/helmet

Usage

Simply require this plugin, and the basic security headers will be set.

const fastify = require('fastify')()
const helmet = require('@fastify/helmet')

fastify.register(
  helmet,
  // Example disables the `contentSecurityPolicy` middleware but keeps the rest.
  { contentSecurityPolicy: false }
)

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
})

How it works

@fastify/helmet is a tiny wrapper around helmet that adds an 'onRequest' hook and a reply.helmet decorator.

It accepts the same options as helmet, and you can see more in the helmet documentation.

Apply Helmet to all your application routes

By passing { global: true } into the options, @fastify/helmet allows you to register Helmet for all your application routes by default. If you want a more granular control on how to apply Helmet to your application you can choose to disable it on a global scope by passing { global: false } to the options. By default, this option is set to true.

Example - enable @fastify/helmet globally

fastify.register(helmet)
// or
fastify.register(helmet, { global: true })

Example - disable @fastify/helmet globally

// register the package with the `{ global: false }` option
fastify.register(helmet, { global: false })

fastify.get('/route-with-disabled-helmet', async (request, reply) => {
  return { message: 'helmet is not enabled here' }
})

fastify.get('/route-with-enabled-helmet', {
  // We enable and configure helmet for this route only
  helmet: {
    dnsPrefetchControl: {
      allow: true
    },
    frameguard: {
      action: 'foo'
    },
    referrerPolicy: false
  }
}, async (request, reply) => {
  return { message: 'helmet is enabled here' }
})

// helmet is disabled on this route but we have access to `reply.helmet` decorator
// that allows us to apply helmet conditionally
fastify.get('/here-we-use-helmet-reply-decorator', async (request, reply) => {
  if (condition) {
    // we apply the default options
    await reply.helmet()
  } else {
    // we apply customized options
    await reply.helmet({ frameguard: false })
  }

  return { 
    message: 'we use the helmet reply decorator to conditionally apply helmet middlewares'
  }
})

helmet route option

@fastify/helmet allows you to enable, disable, and customize helmet for each one of your application hooks by using the helmet shorthand route option when you register your application routes.

If you want to disable helmet for a specific endpoint you must pass { helmet: false } to your route options.

If you want to enable or customize helmet for a specific endpoint you must pass a helmet configuration object to your route options. E.g.: { helmet: { frameguard: false } }.

Example - @fastify/helmet configuration using the helmet shorthand route option

// register the package with the `{ global: true }` option
fastify.register(helmet, { global: true })

fastify.get('/route-with-disabled-helmet', { helmet: false }, async (request, reply) => {
  return { message: 'helmet is not enabled here' }
})

fastify.get('/route-with-enabled-helmet', async (request, reply) => {
  return { message: 'helmet is enabled by default here' }
})

fastify.get('/route-with-custom-helmet-configuration', {
  // We change the helmet configuration for this route only
  helmet: {
    enableCSPNonces: true,
    contentSecurityPolicy: {
      directives: {
        'directive-1': ['foo', 'bar']
      },
      reportOnly: true
    },
    dnsPrefetchControl: {
      allow: true
    },
    frameguard: {
      action: 'foo'
    },
    hsts: {
      maxAge: 1,
      includeSubDomains: true,
      preload: true
    },
    permittedCrossDomainPolicies: {
      permittedPolicies: 'foo'
    },
    referrerPolicy: false
  }
}, async (request, reply) => {
  return { message: 'helmet is enabled with a custom configuration on this route' }
})

Content-Security-Policy Nonce

@fastify/helmet provide a simple way for csp nonces generation. You can enable this behavior by passing { enableCSPNonces: true } into the options. Then, you can retrieve the nonces through reply.cspNonce.

Note: This feature is implemented inside this module. It is not a valid option or supported by helmet. If you need to use helmet feature only for csp nonce you can follow the example here.

Example - Generate by options

fastify.register(
  helmet,
  // enable csp nonces generation with default content-security-policy option
  { enableCSPNonces: true }
)

fastify.register(
  helmet,
  // customize content security policy with nonce generation
  { 
    enableCSPNonces: true,
    contentSecurityPolicy: {
      directives: {
        ...
      }
    }
  }
)

fastify.get('/', function(request, reply) {
  // retrieve script nonce
  reply.cspNonce.script
  // retrieve style nonce
  reply.cspNonce.style
})

Example - Generate by helmet

fastify.register(
  helmet,
  { 
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        scriptSrc: [
          function (req, res) {
            // "res" here is actually "reply.raw" in fastify
            res.scriptNonce = crypto.randomBytes(16).toString('hex')
            // make sure to return nonce-... directive to helmet, so it can be sent in the headers
            return `'nonce-${res.scriptNonce}'`
          }
        ],
        styleSrc: [
          function (req, res) {
            // "res" here is actually "reply.raw" in fastify
            res.styleNonce = crypto.randomBytes(16).toString('hex')
            // make sure to return nonce-... directive to helmet, so it can be sent in the headers
            return `'nonce-${res.styleNonce}'`
          }
        ]
      }
    }
  }
)

fastify.get('/', function(request, reply) {
  // you can access the generated nonce by "reply.raw"
  reply.raw.scriptNonce
  reply.raw.styleNonce
})

Disable Default helmet Directives

By default, helmet will add a default set of CSP directives to the response. This behavior can be disabled by setting useDefaults: false in the contentSecurityPolicy configuration.

fastify.register(
  helmet,
  {
    contentSecurityPolicy: {
      useDefaults: false,
      directives: {
        'default-src': ["'self'"]
      }
    }
  }
)

License

MIT

fastify-helmet's People

Contributors

anderscan avatar cesarvspr avatar climba03003 avatar darkgl0w avatar delvedor avatar dependabot-preview[bot] avatar dependabot[bot] avatar eomm avatar evanshortiss avatar fdawgs avatar fox1t avatar fralonra avatar frikille avatar github-actions[bot] avatar greenkeeper[bot] avatar hpieters avatar jackzmc avatar jgiola avatar johann-s avatar jsumners avatar krainovsd avatar lependu avatar mcollina avatar pgbross avatar salmanm avatar thomasdingemanse avatar thomheymann avatar uzlopak avatar vidarc avatar zekth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastify-helmet's Issues

ChainAlert: npm package release (7.1.0) has no matching tag in this repo

Dear fastify-helmet maintainers,
Thank you for your contribution to the open-source community.

This issue was automatically created to inform you a new version (7.1.0) of fastify-helmet was published without a matching tag in this repo.

As part of our efforts to fight software supply chain attacks, we would like to verify this release is known and intended, and not a result of an unauthorized activity.

If you find this behavior legitimate, kindly close and ignore this issue. Read more

badge

Option enableCSPNonces should surround nonce with single quotation marks

πŸ› Bug Report

The nonces that are generated when the enableCSPNonces is enabled, should actually be surrounded with ' - in my tests the browsers were not able to interpret current enableCSPNonces script-src / style-src response headers and further more then also didn't load any inline resources - even when those resources included the nonce-attribute.

To Reproduce

Steps to reproduce the behavior:

app.register(fastifyHelmet, {
    enableCSPNonces: true,
    contentSecurityPolicy: {
      directives: {
        ...helmet.contentSecurityPolicy.getDefaultDirectives(),
        // its just an example, I know unsafe-XYZ is not ideal :D
        "script-src": ["'self'", "'unsafe-eval'", "'unsafe-inline'"],
        "script-src-attr": ["'unsafe-inline'"],
        "style-src": ["'self'", "'unsafe-inline'"],
      },
    },
  });

Expected behavior

The pushed nonce value should be surounded with '. And then scripts / style / link should be able to load in the browsers (when they have the proper nonce-attribute set.

Solution

Please check out the "Solution" from #119 - it actually includes a fix πŸ™ˆ

Your Environment

  • node version: v15.10.0
  • fastify version: ^3.10.1
  • helmet version: ^5.3.0
  • os: Linux

Error building project after Updating fasitfy-helmet to latest version 5.0.1

πŸ› Bug Report

Updating fasitfy-helmet to latest version 5.0.1

To Reproduce

Steps to reproduce the behavior:

  // -->Register: security policy and plugins
  fastify.register(require('fastify-helmet'), {
    hidePoweredBy: {
      setTo: 'PHP 7.4.0'
    }
  });

Expected behavior

Throws this error

node_modules/fastify-helmet/index.d.ts:2:8 - error TS1259: Module '"/lab/naologic-apps/bee11/node_modules/helmet/dist/index"' can only be default-imported using the 'esModuleInterop' flag

2 import helmet from "helmet";
         ~~~~~~

  node_modules/helmet/dist/index.d.ts:44:1
    44 export = helmet;
       ~~~~~~~~~~~~~~~~
    This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.

Cannot just enable esModuleInterop because it will trigger errors in many other modules.

Your Environment

  • node version: 12
  • fastify version: 3.4.0
  • os: Linux

Option enableCSPNonces will mutate users scriptSrc / styleSrc

πŸ› Bug Report

scriptSrc / styleSrc are mutated in place and grow with each request:

here when scriptSrc / styleSrc already are set by the library user, then the arrays will be mutated and every request will just add a new nonce at the end of the array here. So the array size will increase with every request.

To Reproduce

Steps to reproduce the behavior:

app.register(fastifyHelmet, {
    enableCSPNonces: true,
    contentSecurityPolicy: {
      directives: {
        ...helmet.contentSecurityPolicy.getDefaultDirectives(),
        // its just an example, I know unsafe-XYZ is not ideal :D
        "script-src": ["'self'", "'unsafe-eval'", "'unsafe-inline'"],
        "script-src-attr": ["'unsafe-inline'"],
        "style-src": ["'self'", "'unsafe-inline'"],
      },
    },
  });

Expected behavior

scriptSrc / styleSrc are mutated in place and grow with each request
If the user already has set a scriptSrc / styleSrc config, then it should be copied on each request, before the new nonce is pushed to the array.

Solution

Please check out the "Solution" from #119 - it actually includes a fix πŸ™ˆ

Your Environment

  • node version: v15.10.0
  • fastify version: ^3.10.1
  • helmet version: ^5.3.0
  • os: Linux

Error when building project after setting `moduleResolution: "Node16"`

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.10.0

Plugin version

10.0.2

Node.js version

19.0.1

Operating system

macOS

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

Ventura 13.0

Description

I recently switched my project's tsconfig to use moduleResolution: "Node16", because I was forced to do that (Got TS1452: 'resolution-mode' assertions are only supported when `moduleResolution` is `node16` or `nodenext`.)

After switching I get the following message when using fastify-helmet:

node_modules/.pnpm/@[email protected]/node_modules/@fastify/helmet/types/index.d.ts:2:62 - error TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("helmet")' call instead.

2 import helmet, { contentSecurityPolicy, HelmetOptions } from 'helmet';
                                                               ~~~~~~~~


Found 1 error in node_modules/.pnpm/@[email protected]/node_modules/@fastify/helmet/types/index.d.ts:2

This is one of two packages where I had problems with switching. To be honest, I do not have an idea what's the problem here, ESM is still a bit of a blackbox for me.
Even when dynamically importing the package, this error still exists.

Update: In my tests, setting type: "module" in package.json of fastify-helmet resolves the issue, but I do not know if this has other unwanted side-effects.

Steps to Reproduce

  1. Create a new typescript project
  2. Use moduleResolution: "Node16" in tsconfig.json
  3. Ensure that skipLibCheck is not true
  4. Add @fastify/helmet as a dependency
  5. Import the dependency: import helmet from "@fastify/helmet"
  6. Build using latest typescript (currently 4.9.3)

Expected Behavior

No response

TypeError: Cannot read property 'setHeader' of undefined

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure it has not already been reported

Fastify version

2.15.3

Plugin version

1.6.1

Node.js version

v15.12.0

Operating system

Linux

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

Linux drip20 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2+deb10u2 (2019-11-11) x86_64 GNU/Linux

Description

fastify-helmet throws TypeError: Cannot read property 'setHeader' of undefined

Capture

Steps to Reproduce

  1. brand new app using https://www.npmjs.com/package/create-fastify-app
  2. yarn add fastify-helmet
  3. register fastify-helmet in accordance to docs
  4. Any HTTP request will print TypeError: Cannot read property 'setHeader' of undefined and crash the server with no further stack information.

Expected Behavior

No response

Broken types in v5

πŸ› Bug Report

@mcollina @EvanHahn The types are broken in fastify-hemlet@v5 in the sense that the options neither come up via IntelliSense, nor can one manually specify them because TypeScript throws the following error: Object literal may only specify known properties, and 'hidePoweredBy' does not exist in type '(RegisterOptions & FastifyHelmetOptions) | (() => RegisterOptions & FastifyHelmetOptions)'.ts(2769)

The issue is this line: https://github.com/helmetjs/helmet/blob/master/index.ts#L26 because the HelmetOptions interface is not exported which means this import resolves to nothing.

It should say export interface HelmetOptions. If it's not exported, it cannot be picked up by fastify-helmet.

Used in the nestjs (typescript) framework, the ts compiler tells you that the types do not match

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.10.2

Plugin version

10.1.0

Node.js version

16.17.0

Operating system

Windows

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

Windows 11

Description

Used in the nestjs (typescript) framework, the ts compiler tells you that the types do not match
image
as shown in the picture
I have to use type assertion like this

type FastifyAdapterParameters = Parameters<typeof adapter.register>;
type FastifyAdapterRegister = FastifyAdapterParameters[0];
const Helmet = fastifyHelmet as unknown as FastifyAdapterRegister;
await app.register(Helmet); // or await adapter.register(Helmet);

If I don't do this, I will get a type validation error

Argument of type 'FastifyHelmet' is not assignable to parameter of type 'FastifyPluginCallback<FastifyHelmetOptions, RawServerDefault, FastifyTypeProviderDefault> | FastifyPluginAsync<...> | Promise<...> | Promise<...>'.
Type 'FastifyHelmet' is not assignable to type 'FastifyPluginCallback<FastifyHelmetOptions, RawServerDefault, FastifyTypeProviderDefault>'.

Steps to Reproduce

npm i -g @nestjs/cli
nest new test_helmet
cd test_helmet
npm uninstall @nestjs/platform-express && npm install --save @nestjs/platform-fastify fastify @fastify/helmet

modify src/main.ts to

import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import fastifyHelmet from '@fastify/helmet';
import { AppModule } from './app.module';

async function bootstrap() {
  const adapter = new FastifyAdapter();
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    adapter,
  );
  app.register(fastifyHelmet);
  await app.listen(3000);
}
bootstrap();

you will get a type error
image

Expected Behavior

like readme to run

@fastify/helmet-9.0.0 requires fastify-4.0.0, but the latest npm published version is 3.29.0

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.29.0

Plugin version

3.0.1

Node.js version

16.13.1

Operating system

macOS

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

11.3.1

Description

@fastify/helmet-9.0.0 requires fastify-4.0.0, but the latest npm published version is 3.29.0

Steps to Reproduce

ncu -u
npm i
<run code using fastify and @fastify/helmet>

Expected Behavior

FastifyError: fastify-plugin: @fastify/helmet - expected '4.x' fastify version, '3.29.0' is installed

Additional middleware functions (contentSecurityPolicy)

I would like to enable Helmet contentSecurityPolicy directives.

You state that running the register will not include all middleware functions by default.

Is this simply a case of adding the required functions to the settings object like so:

fastify
    .register(require('fastify-helmet'), {
        noCache: true,
        csp: {
            directives: {
                defaultSrc: ["'self'"],
                scriptSrc: ["'self'"],
                styleSrc: ["'self'"]
            },
            loose: true,
            setAllHeaders: true,
            browserSniff: true
        }
    })

Or do I need to install additional helmet plugins and define these first?

An in-range update of fastify is breaking the build 🚨

The devDependency fastify was updated from 1.13.3 to 1.13.4.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

fastify is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v1.13.4

Enhancements

  • move ECONNRESET log from error to debug - #1363

Fixes

  • Fix setting multiple cookies as multiple 'Set-Cookie' headers. - #1360
  • fix: #1353 ignore evaluation of $schema field in json-schema - #1354

Documentation

  • Update copyright year to 2019 - #1364
Commits

The new version differs by 6 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

How to disable helmet contentSecurityPolicy for specific reply? Or disable helmet?

πŸ’¬ Question here

Hi, need to disable helmet contentSecurityPolicy for a few specific replies:

    if (someCondition) { disable contentSecurityPolicy }
    reply.type('text/html') //otherwise it's plain text, instead of being interpreted as html
    reply.send(page) //this has a <script> which doesn't execute due to contentSecurityPolicy

helmet is added with register(), part of app.js, launched using fastify-cli

 fastify.register(helmet)

Found these, but didn't figure out a solution:
https://github.com/helmetjs/helmet/wiki/Conditionally-using-middleware

https://www.fastify.io/docs/latest/Reference/Middleware/#restrict-middleware-execution-to-certain-paths
(not using fastify.use(), but fastify.register())

#89

Tried also

//still uses helmet
    reply.raw.writeHead(200, { 'Content-Type': 'text/html' }) 
    reply.raw.write(page)
     reply.raw.end()

Thanks!

  • node version: 16
  • fastify version: 3
  • fastify-helmet: 4

using `@fastify/helmet` together with an extended `FastifyRequest` type leads to a type-error

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.18.0

Plugin version

10.1.0

Node.js version

v18.15.0

Operating system

macOS

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

13.4.1

Description

By using @fastify/helmet together with extending the FastifyRequest type with custom attributes (as described here) we get the following TS error:

error TS2769: No overload matches this call.
  Overload 1 of 3, '(plugin: FastifyPluginCallback<FastifyHelmetOptions, RawServerDefault, FastifyTypeProviderDefault, FastifyBaseLogger>, opts?: FastifyRegisterOptions<...> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error.
    Argument of type '{ contentSecurityPolicy: boolean; crossOriginEmbedderPolicy: boolean; crossOriginOpenerPolicy: boolean; crossOriginResourcePolicy: boolean; }' is not assignable to parameter of type 'FastifyRegisterOptions<FastifyHelmetOptions> | undefined'.
      Object literal may only specify known properties, and 'contentSecurityPolicy' does not exist in type 'FastifyRegisterOptions<FastifyHelmetOptions>'.
  Overload 2 of 3, '(plugin: FastifyPluginAsync<FastifyHelmetOptions, RawServerDefault, FastifyTypeProviderDefault, FastifyBaseLogger>, opts?: FastifyRegisterOptions<...> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error.
    Argument of type '{ contentSecurityPolicy: boolean; crossOriginEmbedderPolicy: boolean; crossOriginOpenerPolicy: boolean; crossOriginResourcePolicy: boolean; }' is not assignable to parameter of type 'FastifyRegisterOptions<FastifyHelmetOptions> | undefined'.
      Object literal may only specify known properties, and 'contentSecurityPolicy' does not exist in type 'FastifyRegisterOptions<FastifyHelmetOptions>'.
  Overload 3 of 3, '(plugin: FastifyPluginAsync<FastifyHelmetOptions, RawServerDefault, FastifyTypeProviderDefault, FastifyBaseLogger> | FastifyPluginCallback<...> | Promise<...> | Promise<...>, opts?: FastifyRegisterOptions<...> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error.
    Argument of type '{ contentSecurityPolicy: boolean; crossOriginEmbedderPolicy: boolean; crossOriginOpenerPolicy: boolean; crossOriginResourcePolicy: boolean; }' is not assignable to parameter of type 'FastifyRegisterOptions<FastifyHelmetOptions> | undefined'.
      Object literal may only specify known properties, and 'contentSecurityPolicy' does not exist in type 'FastifyRegisterOptions<FastifyHelmetOptions>'.

73     contentSecurityPolicy: false,

Relates to #216 (comment)

Steps to Reproduce

It should be enough to use the TypeScript (v4.9.5) with the following files:

index.ts:

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

const fastify = await setupFastify({ ... });

await fastify.register(helmet, {
  contentSecurityPolicy: false,
  crossOriginEmbedderPolicy: false,
  crossOriginOpenerPolicy: false,
  crossOriginResourcePolicy: false,
});

tsconfig.json:

{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "node",
    "rootDir": "./",
    "target": "ES2019",
  },
}

fastify.d.ts:

import 'fastify';

declare module 'fastify' {
  interface FastifyRequest {
    startTime: number;
  }
}

Expected Behavior

No response

Error: Cannot read property 'bind' of undefined

I'm using Fastify 1.13.4 and Fastify-helmet 3.0.0. I'm trying to integrate fastify-helmet but even when just using the basis setup used in the tests i recieve the following error:

const fastify = require('fastify');
const helmet = require('fastify-helmet');
const app = fastify();

app.register(helmet, { permittedCrossDomainPolicies: true });

The error I recieve is the following:

<path_to_the_project_dir>\node_modules\fastify\fastify.js:744
    instance._hooks.add(name, fn.bind(instance))
                                 ^

TypeError: Cannot read property 'bind' of undefined
    at _addHook (<path_to_the_project_dir>\node_modules\fastify\fastify.js:744:34)
    at after (<path_to_the_project_dir>\node_modules\fastify\fastify.js:736:9)
    at Object._encapsulateThreeParam (<path_to_the_project_dir>\node_modules\avvio\boot.js:387:7)
    at Boot.callWithCbOrNextTick (<path_to_the_project_dir>\node_modules\avvio\boot.js:311:5)
    at Boot._after (<path_to_the_project_dir>\node_modules\avvio\boot.js:215:26)
    at Plugin.exec (<path_to_the_project_dir>\node_modules\avvio\plugin.js:82:17)
    at Boot.loadPlugin (<path_to_the_project_dir>\node_modules\avvio\plugin.js:166:10)
    at release (<path_to_the_project_dir>\node_modules\fastq\queue.js:127:16)
    at Object.resume (<path_to_the_project_dir>\node_modules\fastq\queue.js:61:7)
    at Plugin.finish (<path_to_the_project_dir>\node_modules\avvio\plugin.js:157:10)

Using Fastify 4.23.0 get deprecated "request.routeConfig" warnings

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.23.0

Plugin version

11.0.0

Node.js version

20.3.1

Operating system

Linux

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

Fedora 39

Description

With Fastify 4.23.0 get [FSTDEP016] FastifyDeprecation: You are accessing the deprecated "request.routeConfig" property. Use "request.routeOptions.config" instead. Property "req.routeConfig" will be removed in fastify@5` warnings.

This arises in `fastify.addHook('onRequest'...) where it looks for helmet specific config on the route.

Applying the suggested change in the deprecation warning eliminates the warning.

Steps to Reproduce

Simply require the @fastify/helmet plugin and observe the server messages in a terminal console.

Expected Behavior

No deprecation warnings.

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 11.11.6 to 11.11.7.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Documentation is lacking

I am attempting to add this to an application and I really don't have any idea how to configure it. For example, if I want to set the hsts maximum age to 30 minutes, how do I do that? This plugin needs documentation on how to configure it.

Reference error when using bitbucket pipelines

Reference require('./config') at "./index.js:4" does not default to "config.json" and instead results in failing on... Cannot find module './config' from 'index.js'

appending ".json" to "config" fixes the issue.

An in-range update of fastify is breaking the build 🚨

Version 1.11.1 of fastify was just published.

Branch Build failing 🚨
Dependency fastify
Current Version 1.11.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

fastify is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes v1.11.1
Commits

The new version differs by 10 commits.

  • e8ae197 Bumped v1.11.1
  • 45fb2f4 Revert "Log error after customErrorHandler (#1073)" (#1119)
  • 288d9ec Added eslint-import-resolver-node (#1118)
  • cef8814 Fix decorate{Request, Reply} not recognizing getter/setter config (#1114)
  • d99cd61 chore(package): update snazzy to version 8.0.0 (#1112)
  • f1007bb Add test for trust proxy with ip addresses (#1111)
  • da89735 Add test for trust proxy with number (#1110)
  • 4bcc1f6 Refactor trust-proxy tests (#1103)
  • ebee8d4 Augment types available for https server options (#1109)
  • 4bffcf9 Update Ecosystem.md (#1106)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Unwanted disabling of other security modules due to incorrect early return

Hi guys,

The bug happens at this line:

if (option === false) { return }

I arrived here from your Fastify Plugin Guide to see how a plugin should be written, and intended to install the package for my app.

After reading your code and cross-checking your previous commits, I believe the intention here is to disable a particular middleware if its name is set to false in the plugin option.

The "return" in the line of code above will disable all subsequent plugins too. This bug is probably a consequence of moving from

middlewares.forEach(function () {
...
return;
...
})

to

for (const middleware of middlewares) {
...
return; // should be "continue;"
...
}

Please close this issue if I get your intention wrong!

Thanks and cheers!

TS1479, helmet typings issue

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.10.2

Plugin version

10.1.0

Node.js version

16.17.0

Operating system

Linux

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

22.04

Description

It seems that we get typescript errors, because the typings from helmet are ecmascript and not commonjs

uzlopak@Battlestation:~/workspace/nodenext-mvce$ npm run build

> nodenext-test@1.0.0 build
> tsc -p .

node_modules/@fastify/helmet/types/index.d.ts:2:62 - error TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("helmet")' call instead.

2 import helmet, { contentSecurityPolicy, HelmetOptions } from 'helmet';
                                                               ~~~~~~~~


Found 1 error in node_modules/@fastify/helmet/types/index.d.ts:2

Steps to Reproduce

clone https://github.com/Uzlopak/nodenext-mvce/tree/helmet-issue
npm run build

Expected Behavior

Should not throw

Support for Http2 out of the box for the helmet plugin

πŸš€ Feature Proposal

The current helmet plugin takes in the middleware with HttpServer, req and response. As we move towards Http2, could I propose the plugin to accept both http and http2 depending upon the protocol set by default while creating fastify?

Motivation

The reason for asking a proposal is to make sure that it supports modern protocol.

Example

Hi,

There are some security solutions as Auth0 or passwordless...

Do you know if any example are available with an external security process ?

Thx

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.12.9 to 12.12.10.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Headers not set on error thrown from fastify-bearer-auth

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.25.3

Plugin version

7.0.0

Node.js version

16.13.2

Operating system

Windows

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

10

Description

On upgrading from 6.0.0 to 7.0.0, the helmet headers are no longer present in the error response returned by fastify/fastify-bearer-auth.

Steps to Reproduce

Stand up server instance with both fastify-helmet and fastify-bearer-auth registered to the server:

const fastify = require("fastify")();

// Import plugins
const helmet = require("fastify-helmet");
const bearer = require("fastify-bearer-auth");

/**
 * @description test function
 */
async function server() {
	fastify
		.register(helmet)
		.register(bearer, { keys: new Set(["a-super-secret-key1"]) })
		.route({
			method: "GET",
			url: "/foo",
			handler: (req, res) => {
				res.send("ok");
			},
		});
	await fastify.listen({ port: 8000 });
}

server();

Make a GET request with an invalid bearer token:

> GET /foo HTTP/1.1
> Host: localhost:8000
> User-Agent: insomnia/2021.7.2
> Authorization: Bearer a-super-secret-key12
> Accept: */*

Response:

< HTTP/1.1 401 Unauthorized
< content-type: application/json; charset=utf-8
< content-length: 40
< Date: Mon, 17 Jan 2022 14:48:36 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5

Expected Behavior

Response of:

< HTTP/1.1 401 Unauthorized
< Content-Security-Policy: default-src 'self';base-uri 'self';block-all-mixed-content;font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
< Cross-Origin-Embedder-Policy: require-corp
< Cross-Origin-Opener-Policy: same-origin
< Cross-Origin-Resource-Policy: same-origin
< X-DNS-Prefetch-Control: off
< Expect-CT: max-age=0
< X-Frame-Options: SAMEORIGIN
< Strict-Transport-Security: max-age=15552000; includeSubDomains
< X-Download-Options: noopen
< X-Content-Type-Options: nosniff
< Origin-Agent-Cluster: ?1
< X-Permitted-Cross-Domain-Policies: none
< Referrer-Policy: no-referrer
< X-XSS-Protection: 0
< content-type: application/json; charset=utf-8
< content-length: 40
< Date: Mon, 17 Jan 2022 14:58:22 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5

Bundling ESM project with this package is not working

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.24.3

Plugin version

11.1.1

Node.js version

20.4

Operating system

Windows

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

11

Description

While including this package in an ESM project that esbuild bundler is used it will throw error on runtime Error: Dynamic require of "node:crypto" is not supported

Steps to Reproduce

  1. Setup new Fastify project
  2. Add esbuild and output ESM (it will work until this step)
  3. Add this plguin npm i @fastify/helmet and use it
  4. Build using esbuild again (it will fail at runtime on this stage)

Expected Behavior

This package should provide ESM version as well so bundlers like esbuild will work with it

Missing example of how to use upgraded fastify-helmet with a style/script nonce

It used to be straightforward using a nonce with fastify-helmet by doing the following:

fastify.register(helmet, {
  contentSecurityPolicy: {
    directives: {
      scriptSrc: [
        "'self'", 
        (req, res) => {
            // set nonce value on raw request
           const nonce = crypto.randomBytes(16).toString('base64');
           res.locals = { scriptNonce: nonce };

           return `'nonce-${nonce}'`;
        }
      ],
    },
  },
});

and then when rendering with something like point-of-view

// inside route "handler"

reply.render('mypage', { nonce: reply.raw.locals.scriptNonce });

I get that the fastify api changed to using .raw, helmet package no longer supports a middleware function as part of a directive, and that this probably wasn't the best way to do this to begin with, but it did achieve the result as intended previously.
That being said, I feel like a CSP that uses nonced styles and scripts is very common and i feel like it is less clear than ever on how to achieve this with fastify-helmet. It feels like it would almost be easier just using helmet by itself. That being said,

I figured the point of the fastify-helmet package is to make the ecosystem of fastify more robust by helping people easily achieve what they want. I'm sure someone else has done this with the latest fastify-helmet package upgrade so I figured I'd reach out for help :)

First, can someone help me out by recommending a better approach since my "old way" no longer works 🀣 (yes I know it wasn't that great of a way anyways).

Second, what can we add (even if it's just some documentation) to help others with this issue?

Thanks in advance for any help!!

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.12.0 to 12.12.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 10.12.8 to 10.12.9.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Release new version?

πŸš€ Feature Proposal

Please consider releasing a new version of fastify-helmet to update dependency versions. In particular, to bump fastify-plugin to v3.

Motivation

To remove the "fastify not found, proceeding anyway" log messages.

Example

N/A

Jquery Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src-attr 'none'".

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Hi ,
Below is helmet configuration

contentSecurityPolicy: {
  directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'","https://cdnjs.cloudflare.com/","https://code.highcharts.com/","'unsafe-inline'"],
      styleSrc: ["'self'", 'https://fonts.googleapis.com', "'unsafe-inline'"],
      imgSrc: ["'self'", 'https://*.com'],
      fontSrc: ["'self'", 'https://*.com', 'data:']
  },

However i am getting error below
error

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src-attr 'none'".

image

The cdn which i have used is below
cdn
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js

How to resolve this issue

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 11.11.2 to 11.11.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

type check failed when register the plugin

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.14.1

Plugin version

10.1.0

Node.js version

v18.12.0

Operating system

Linux

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

Ubuntu 22.04.2

Description

Argument of type 'FastifyHelmet' is not assignable to parameter of type 'FastifyPluginCallback<FastifyHelmetOptions, RawServerDefault, FastifyTypeProviderDefault, FastifyBaseLogger> | FastifyPluginAsync<...> | Promise<...> | Promise<...>'.
  Type 'FastifyHelmet' is not assignable to type 'FastifyPluginCallback<FastifyHelmetOptions, RawServerDefault, FastifyTypeProviderDefault, FastifyBaseLogger>'.
    Types of parameters 'instance' and 'instance' are incompatible.
      Type 'import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/instance").FastifyInstance<import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/utils").RawServerDefault, import("http").IncomingMessage, import("http").ServerRes...' is not assignable to type 'import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/instance").FastifyInstance<import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/utils").RawServerDefault, import("http").IncomingMessage, import("http").ServerRes...'.
        The types returned by 'withTypeProvider().after()' are incompatible between these types.
          Type 'import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/instance").FastifyInstance<import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/utils").RawServerDefault, import("http").IncomingMessage, import("http").ServerRes...' is not assignable to type 'import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/instance").FastifyInstance<import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/utils").RawServerDefault, import("http").IncomingMessage, import("http").ServerRes...'.
            Type 'FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, Provider> & PromiseLike<...>' is not assignable to type 'FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, Provider>'.
              Types of property 'decorateReply' are incompatible.
                Type '<T>(property: string | symbol, value: T extends (...args: any[]) => any ? (this: import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/reply").FastifyReply<import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/utils")...' is not assignable to type '<T>(property: string | symbol, value: T extends (...args: any[]) => any ? (this: import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/reply").FastifyReply<import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/utils")...'.
                  Types of parameters 'value' and 'value' are incompatible.
                    Type 'T extends (...args: any[]) => any ? (this: import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/reply").FastifyReply<import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/utils").RawServerDefault, ... 6 more ..., unk...' is not assignable to type 'T extends (...args: any[]) => any ? (this: import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/reply").FastifyReply<import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/utils").RawServerDefault, ... 6 more ..., unk...'.
                      Type 'T | ((this: FastifyReply<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, ... 4 more ..., unknown>, ...args: Parameters<T>) => ReturnType<...>)' is not assignable to type 'T extends (...args: any[]) => any ? (this: FastifyReply<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, ... 4 more ..., unknown>, ...args: Parameters<T>) => ReturnType<...> : T'.
                        Type 'T' is not assignable to type 'T extends (...args: any[]) => any ? (this: FastifyReply<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, ... 4 more ..., unknown>, ...args: Parameters<T>) => ReturnType<...> : T'.
                          Type '(this: import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/reply").FastifyReply<import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/utils").RawServerDefault, ... 6 more ..., unknown>, ...args: Parameters<T>) => Re...' is not assignable to type '(this: import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/reply").FastifyReply<import("/home/ian/templates/lambda-nestify/node_modules/.pnpm/[email protected]/node_modules/fastify/types/utils").RawServerDefault, ... 6 more ..., unknown>, ...args: Parameters<T>) => Re...'.
                            The 'this' types of each signature are incompatible.
                              Type 'FastifyReply<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, RouteGenericInterface, unknown, FastifySchema, FastifyTypeProviderDefault, unknown>' is missing the following properties from type 'FastifyReply<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, RouteGenericInterface, unknown, FastifySchema, FastifyTypeProviderDefault, unknown>': cspNonce, helmetts(2345)
instance.d.ts(124, 17): This type parameter might need an `extends T extends (...args: any[]) => any ? (this: FastifyReply<RawServerDefault, http.IncomingMessage, http.ServerResponse<http.IncomingMessage>, ... 4 more ..., unknown>, ...args: Parameters<T>) => ReturnType<...> : T` constraint.

Steps to Reproduce

https://docs.nestjs.com/security/helmet#use-with-fastify

Expected Behavior

No response

Improve TypeScript types

I've been looking at the types provided by fastify-helmet and compared them to the types of helmet

It is clear that FastifyHelmetOptions contains far less typing information than IHelmetConfiguration.

From reading the documentation, FastifyHelmetOptions and IHelmetConfiguration should be equivalent.

fastify-helmet accept the same options of Helmet, and you can see more in the helmet documentation.

Would it be possible to import IHelmetConfiguration from @types/helmet and extend FastifyHelmetOptions with it? Or is there some reason why this wouldn't work/be desirable?

I can submit a PR if wanted.

An in-range update of tap is breaking the build 🚨

The devDependency tap was updated from 12.1.3 to 12.1.4.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

tap is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 3 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of fastify is breaking the build 🚨

The devDependency fastify was updated from 1.14.0 to 1.14.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

fastify is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v1.14.1

Fixes

  • Allow override of the default content-type parser inside a plugin - #1434
Commits

The new version differs by 2 commits.

  • 4e1e008 Bumped v1.14.1
  • 7bd2a45 Add test for content-type overriding inside a plugin (#1434)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

No helmet.contentSecurityPolicy.getDefaultDirectives() method

πŸ› Bug Report

The helmet documentation, section reference, under helmet.contentSecurityPolicy(options), gives the following information:

If no directives are supplied, the following policy is set (whitespace added for readability):

default-src 'self';
base-uri 'self';
block-all-mixed-content;
font-src 'self' https: data:;
frame-ancestors 'self';
img-src 'self' data:;
object-src 'none';
script-src 'self';
script-src-attr 'none';
style-src 'self' https: 'unsafe-inline';
upgrade-insecure-requests

You can fetch this default with helmet.contentSecurityPolicy.getDefaultDirectives().

I've tried doing this with fastify-helmet, but I get the following error:

    ...fastifyHelmet.contentSecurityPolicy.getDefaultDirectives(),
                                           ^
TypeError: Cannot read property 'getDefaultDirectives' of undefined

To Reproduce

Steps to reproduce the behavior:

Create a fastify server and register the fastify-helmet plugin. Try to reference the getDefaultDirectives() method in the options object. Start the server to see the error message.

const fastify = require('fastify')({ logger: true })
const helmet= require('fastify-helmet')

fastify.get('/', function (request, reply) {
  reply.send({ hello: 'world' })
})

fastify.register(helmet, {
  contentSecurityPolicy: {
    directives: {
      ...helmet.contentSecurityPolicy.getDefaultDirectives()
    }
  }
})

fastify.listen(3000, function (err, address) {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
  fastify.log.info(`server listening on ${address}`)
})

A workaround for this issue is to specify all of the CSP defaults manually, in addition to any custom modifications. However, it would be a much more elegant solution if this worked as described in the helmet documentation. I think adding a contentSecurityPolicy object with a getDefaultDirectives() method that just calls the original helmet.contentSecurityPolicy.getDefaultDirectives() and returns the result should solve this, but I'm not sure how additional exports can be defined for fastify plugins.

Expected behavior

I expected the server to start normally without throwing any errors. Fastify-helmet should have a contentSecurityPolicy.getDefaultDirectives() method that behaves the same as it does in helmet.

Your Environment

  • node version: 14.15.1
  • fastify version: 3.9.2
  • fastify-helmet version: 5.1.0
  • os: Windows

Option enableCSPNonces accesses scriptSrc / styleSrc inconsistently

πŸ› Bug Report

scriptKey is not consistently used throughout the code:

here it is checked if some config already is existing, but at later lines there are many "static" occurences of scriptSrc / styleSrc. In turn this can result into helmet throwing an error because it detects "script-src" and "scriptSrc" in the directives.

To Reproduce

Steps to reproduce the behavior:

app.register(fastifyHelmet, {
    enableCSPNonces: true,
    contentSecurityPolicy: {
      directives: {
        ...helmet.contentSecurityPolicy.getDefaultDirectives(),
        // its just an example, I know unsafe-XYZ is not ideal :D
        "script-src": ["'self'", "'unsafe-eval'", "'unsafe-inline'"],
        "script-src-attr": ["'unsafe-inline'"],
        "style-src": ["'self'", "'unsafe-inline'"],
      },
    },
  });

Expected behavior

Use scriptKey across the enableCSPNonces hook.

Solution

I was able to solve this issue, #118 and XYZ with these changes:

--- index.js    2021-03-14 20:05:37.049985620 +0100
+++ index2.js   2021-03-14 20:06:26.419985419 +0100
@@ -28,17 +28,17 @@
         style: crypto.randomBytes(16).toString('hex')
       }
 
+      const directives = {...cspDirectives}
+
       // push nonce to csp
       // allow both script-src or scriptSrc syntax
-      const scriptKey = Array.isArray(cspDirectives['script-src']) ? 'script-src' : 'scriptSrc'
-      cspDirectives[scriptKey] = Array.isArray(cspDirectives.scriptSrc) ? cspDirectives.scriptSrc : []
-      cspDirectives[scriptKey].push('nonce-' + reply.cspNonce.script)
+      const scriptKey = Array.isArray(directives['script-src']) ? 'script-src' : 'scriptSrc'
+      directives[scriptKey] = [...(directives[scriptKey] || []), `'nonce-${reply.cspNonce.script}'`]
       // allow both style-src or styleSrc syntax
-      const styleKey = Array.isArray(cspDirectives['style-src']) ? 'style-src' : 'styleSrc'
-      cspDirectives[styleKey] = Array.isArray(cspDirectives.styleSrc) ? cspDirectives.styleSrc : []
-      cspDirectives[styleKey].push('nonce-' + reply.cspNonce.style)
+      const styleKey = Array.isArray(directives['style-src']) ? 'style-src' : 'styleSrc'
+      directives[styleKey] = [...(directives[styleKey] || []), `'nonce-${reply.cspNonce.style}'`]
 
-      const cspMiddleware = helmet.contentSecurityPolicy({ directives: cspDirectives, reportOnly: cspReportOnly })
+      const cspMiddleware = helmet.contentSecurityPolicy({ directives, reportOnly: cspReportOnly })
       cspMiddleware(req.raw, reply.raw, next)
     })
   

If you like this solution i am open to create a pull request with this (splitting it up into 3 commits for #118, #119 and #120)

Your Environment

  • node version: v15.10.0
  • fastify version: ^3.10.1
  • helmet version: ^5.3.0
  • os: Linux

hidePoweredBy flag doesnt work

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.27.4

Plugin version

7.0.1

Node.js version

v16.13.0

Operating system

Windows

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

21H1

Description

server.register(helmetPlugin, {
    hidePoweredBy: true,
});

makes no effect. There is always 'x-powered-by: Express' header in all requests

Steps to Reproduce

Run your plugin and try

Expected Behavior

'x-powered-by: Express' header must gone when hidePoweredBy is true

An in-range update of tap is breaking the build 🚨

Version 10.7.2 of tap just got published.

Branch Build failing 🚨
Dependency tap
Current Version 10.7.1
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As tap is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 2 commits.

  • 9e51611 v10.7.2
  • 52d5983 t.rejects: handle getting expected error but not options

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.