Skip to content

Commit 861e0e9

Browse files
authored
Merge pull request from GHSA-p6vg-p826-qp3v
* fix redirect * add missing domain
1 parent 521b641 commit 861e0e9

File tree

2 files changed

+39
-7
lines changed

2 files changed

+39
-7
lines changed

index.js

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
'use strict'
22

33
const path = require('path')
4-
const url = require('url')
54
const statSync = require('fs').statSync
65
const { PassThrough } = require('readable-stream')
76
const glob = require('glob')
@@ -152,9 +151,7 @@ async function fastifyStatic (fastify, opts) {
152151
}
153152

154153
if (opts.redirect === true) {
155-
/* eslint node/no-deprecated-api: "off" */
156-
const parsed = url.parse(request.raw.url)
157-
reply.redirect(301, parsed.pathname + '/' + (parsed.search || ''))
154+
reply.redirect(301, getRedirectUrl(request.raw.url))
158155
} else {
159156
reply.callNotFound()
160157
}
@@ -275,9 +272,7 @@ async function fastifyStatic (fastify, opts) {
275272
})
276273
if (opts.redirect === true && prefix !== opts.prefix) {
277274
fastify.get(opts.prefix, routeOpts, function (req, reply) {
278-
/* eslint node/no-deprecated-api: "off" */
279-
const parsed = url.parse(req.raw.url)
280-
reply.redirect(301, parsed.pathname + '/' + (parsed.search || ''))
275+
reply.redirect(301, getRedirectUrl(req.raw.url))
281276
})
282277
}
283278
} else {
@@ -436,6 +431,11 @@ function getEncodingExtension (encoding) {
436431
}
437432
}
438433

434+
function getRedirectUrl (url) {
435+
const parsed = new URL(url, 'http://localhost.com/')
436+
return parsed.pathname + (parsed.pathname[parsed.pathname.length - 1] !== '/' ? '/' : '') + (parsed.search || '')
437+
}
438+
439439
module.exports = fp(fastifyStatic, {
440440
fastify: '3.x',
441441
name: 'fastify-static'

test/static.test.js

+32
Original file line numberDiff line numberDiff line change
@@ -3262,3 +3262,35 @@ t.test(
32623262
t.end()
32633263
}
32643264
)
3265+
3266+
t.test('should not redirect to protocol-relative locations', { only: 1 }, (t) => {
3267+
const urls = [
3268+
['//google.com/%2e%2e', '/', 301],
3269+
['//users/%2e%2e', '/', 301],
3270+
['//users', null, 404]
3271+
]
3272+
3273+
t.plan(1 + urls.length * 2)
3274+
const fastify = Fastify()
3275+
fastify.register(fastifyStatic, {
3276+
root: path.join(__dirname, '/static'),
3277+
redirect: true
3278+
})
3279+
t.teardown(fastify.close.bind(fastify))
3280+
fastify.listen(0, (err, address) => {
3281+
t.error(err)
3282+
urls.forEach(([testUrl, expected, status]) => {
3283+
const req = http.request(url.parse(address + testUrl), res => {
3284+
t.equal(res.statusCode, status, `status ${testUrl}`)
3285+
3286+
if (expected) {
3287+
t.equal(res.headers.location, expected)
3288+
} else {
3289+
t.notOk(res.headers.location)
3290+
}
3291+
})
3292+
req.on('error', t.error)
3293+
req.end()
3294+
})
3295+
})
3296+
})

0 commit comments

Comments
 (0)