Skip to content

Commit

Permalink
fix: checks if the helmet decorator exists before decorating reply
Browse files Browse the repository at this point in the history
  • Loading branch information
darkgl0w committed Jan 17, 2022
1 parent 8f43868 commit fb9afd4
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ function helmetPlugin (fastify, options, next) {

const isGlobal = typeof global === 'boolean' ? global : true

// We initialize the `helmet` reply decorator
fastify.decorateReply('helmet', null)
// We initialize the `helmet` reply decorator only if it does not already exists
if (!fastify.hasReplyDecorator('helmet')) {
fastify.decorateReply('helmet', null)
}

// We will add the onRequest helmet middleware functions through the onRoute hook if needed
fastify.addHook('onRoute', (routeOptions) => {
Expand Down
36 changes: 36 additions & 0 deletions test/global.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,42 @@ test('It should add the `helmet` reply decorator', async (t) => {
t.has(response.headers, expected)
})

test('It should not throw when trying to add the `helmet` reply decorator if it already exists', async (t) => {
t.plan(3)

const fastify = Fastify()

// We decorate the reply with helmet to trigger the existing check
fastify.decorateReply('helmet', null)

await fastify.register(helmet, { global: false })

fastify.get('/', async (request, reply) => {
t.ok(reply.helmet)
t.not(reply.helmet, null)

await reply.helmet()
return { message: 'ok' }
})

await fastify.ready()

const response = await fastify.inject({
method: 'GET',
path: '/'
})

const expected = {
'x-dns-prefetch-control': 'off',
'x-frame-options': 'SAMEORIGIN',
'x-download-options': 'noopen',
'x-content-type-options': 'nosniff',
'x-xss-protection': '0'
}

t.has(response.headers, expected)
})

test('It should be able to pass custom options to the `helmet` reply decorator', async (t) => {
t.plan(4)

Expand Down

0 comments on commit fb9afd4

Please sign in to comment.