Skip to content

Commit

Permalink
Merge pull request from GHSA-p6vg-p826-qp3v
Browse files Browse the repository at this point in the history
* fix redirect

* add missing domain
  • Loading branch information
Eomm authored Oct 5, 2021
1 parent 521b641 commit 861e0e9
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 7 deletions.
14 changes: 7 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use strict'

const path = require('path')
const url = require('url')
const statSync = require('fs').statSync
const { PassThrough } = require('readable-stream')
const glob = require('glob')
Expand Down Expand Up @@ -152,9 +151,7 @@ async function fastifyStatic (fastify, opts) {
}

if (opts.redirect === true) {
/* eslint node/no-deprecated-api: "off" */
const parsed = url.parse(request.raw.url)
reply.redirect(301, parsed.pathname + '/' + (parsed.search || ''))
reply.redirect(301, getRedirectUrl(request.raw.url))
} else {
reply.callNotFound()
}
Expand Down Expand Up @@ -275,9 +272,7 @@ async function fastifyStatic (fastify, opts) {
})
if (opts.redirect === true && prefix !== opts.prefix) {
fastify.get(opts.prefix, routeOpts, function (req, reply) {
/* eslint node/no-deprecated-api: "off" */
const parsed = url.parse(req.raw.url)
reply.redirect(301, parsed.pathname + '/' + (parsed.search || ''))
reply.redirect(301, getRedirectUrl(req.raw.url))
})
}
} else {
Expand Down Expand Up @@ -436,6 +431,11 @@ function getEncodingExtension (encoding) {
}
}

function getRedirectUrl (url) {
const parsed = new URL(url, 'http://localhost.com/')
return parsed.pathname + (parsed.pathname[parsed.pathname.length - 1] !== '/' ? '/' : '') + (parsed.search || '')
}

module.exports = fp(fastifyStatic, {
fastify: '3.x',
name: 'fastify-static'
Expand Down
32 changes: 32 additions & 0 deletions test/static.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3262,3 +3262,35 @@ t.test(
t.end()
}
)

t.test('should not redirect to protocol-relative locations', { only: 1 }, (t) => {
const urls = [
['//google.com/%2e%2e', '/', 301],
['//users/%2e%2e', '/', 301],
['//users', null, 404]
]

t.plan(1 + urls.length * 2)
const fastify = Fastify()
fastify.register(fastifyStatic, {
root: path.join(__dirname, '/static'),
redirect: true
})
t.teardown(fastify.close.bind(fastify))
fastify.listen(0, (err, address) => {
t.error(err)
urls.forEach(([testUrl, expected, status]) => {
const req = http.request(url.parse(address + testUrl), res => {
t.equal(res.statusCode, status, `status ${testUrl}`)

if (expected) {
t.equal(res.headers.location, expected)
} else {
t.notOk(res.headers.location)
}
})
req.on('error', t.error)
req.end()
})
})
})

0 comments on commit 861e0e9

Please sign in to comment.