From d3ee7d8f5548a12d13a06984b4e396df90e1135a Mon Sep 17 00:00:00 2001 From: Joonas Rouhiainen Date: Wed, 22 Aug 2018 23:13:14 +0300 Subject: [PATCH] Use 400 error on URI decode failure instead of 500 closes #85 closes #88 --- HISTORY.md | 1 + index.js | 24 ++++++++++++++++++++++-- test/test.js | 8 ++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index a3a66f6..eaca0ea 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -2,6 +2,7 @@ unreleased ========== * Show font icon for more font types + * Use 400 error on URI decode failure instead of 500 * deps: accepts@~1.3.5 - deps: mime-types@~2.1.18 * deps: http-errors@~1.7.2 diff --git a/index.js b/index.js index e707bbc..0ee0e1a 100644 --- a/index.js +++ b/index.js @@ -107,10 +107,14 @@ function serveIndex(root, options) { return; } + // get dir + var dir = getRequestedDir(req) + + // bad request + if (dir === null) return next(createError(400)) + // parse URLs - var url = parseUrl(req); var originalUrl = parseUrl.original(req); - var dir = decodeURIComponent(url.pathname); var originalDir = decodeURIComponent(originalUrl.pathname); // join / normalize from root dir @@ -327,6 +331,22 @@ function fileSort(a, b) { String(a.name).toLocaleLowerCase().localeCompare(String(b.name).toLocaleLowerCase()); } +/** + * Get the requested directory from request. + * + * @param req + * @return {string} + * @api private + */ + +function getRequestedDir (req) { + try { + return decodeURIComponent(parseUrl(req).pathname) + } catch (e) { + return null + } +} + /** * Map html `dir`, returning a linked path. */ diff --git a/test/test.js b/test/test.js index 283aad5..d16f834 100644 --- a/test/test.js +++ b/test/test.js @@ -76,6 +76,14 @@ describe('serveIndex(root)', function () { .expect(400, done) }) + it('should deny path that does not decode', function (done) { + var server = createServer() + + request(server) + .head('/%FF') + .expect(400, done) + }) + it('should deny path outside root', function (done) { var server = createServer()