From 3c97d3d03b0b5d7211fe69ff893a42ef4872cf7b Mon Sep 17 00:00:00 2001 From: Timo Tijhof Date: Sun, 8 Sep 2024 19:42:33 -0700 Subject: [PATCH] Fix open redirect abuse via "strip trailing slash" middleware Fixes https://github.com/gruntjs/gruntjs.com/issues/231. --- package.json | 2 +- server.js | 12 ++++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index f90c499..5f04ad1 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "date-utils": "~1.2.21", "ent": "~2.2.0", "errorhandler": "~1.5.0", - "express": "~4.16.3", + "express": "~4.19.2", "grunt": "~1.6.1", "grunt-autoprefixer": "~3.0.4", "grunt-contrib-clean": "~1.1.0", diff --git a/server.js b/server.js index da3ad24..2f05401 100644 --- a/server.js +++ b/server.js @@ -35,9 +35,17 @@ app.use(bodyParser.json()); app.set('views', path.join(__dirname, 'src', 'tmpl')); app.set('view engine', 'pug'); -// strip slashes +/** + * Strip trailing slashes + * + * Redirect "/foo/" to "/foo". Browsers interpret absolute paths in Location + * as relative to the current origin. + * + * Avoid redirecting to a paths that browsers may interpret as URLs to other sites, + * such as "//foo" or "http://". https://github.com/gruntjs/gruntjs.com/issues/231 + */ app.use(function (req, res, next) { - if (req.url.substr(-1) === '/' && req.url.length > 1) { + if (req.url.startsWith('/') && !req.url.startsWith('//') && req.url.length >= 2 && req.url.slice(-1) === '/') { res.redirect(301, req.url.slice(0, -1)); } else { next();