Fix /browse query redirects

This commit is contained in:
Michael Jackson 2019-08-08 09:46:12 -07:00
parent 8aa619727e
commit a718d90549
4 changed files with 43 additions and 2 deletions

View File

@ -45,4 +45,16 @@ describe('A request to browse a directory', () => {
});
});
});
describe('with invalid query params', () => {
it('strips them from the query string', done => {
request(server)
.get('/browse/react@16.8.0/umd/?invalid')
.end((err, res) => {
expect(res.statusCode).toBe(302);
expect(res.headers.location).toEqual('/browse/react@16.8.0/umd/');
done();
});
});
});
});

View File

@ -31,4 +31,18 @@ describe('A request to browse a file', () => {
});
});
});
describe('when the URL contains invalid query params', () => {
it('strips them from the URL', done => {
request(server)
.get('/browse/react@16.8.0/react.production.min.js?invalid')
.end((err, res) => {
expect(res.statusCode).toBe(302);
expect(res.headers.location).toBe(
'/browse/react@16.8.0/react.production.min.js'
);
done();
});
});
});
});

View File

@ -12,6 +12,7 @@ import serveModule from './actions/serveModule.js';
import serveStats from './actions/serveStats.js';
import findEntry from './middleware/findEntry.js';
import noQuery from './middleware/noQuery.js';
import redirectLegacyURLs from './middleware/redirectLegacyURLs.js';
import requestLog from './middleware/requestLog.js';
import staticFiles from './middleware/staticFiles.js';
@ -60,18 +61,18 @@ export default function createServer() {
app.get(
'*/',
noQuery(),
validatePackageURL,
validatePackageName,
validateQuery,
validateVersion,
serveDirectoryBrowser
);
app.get(
'*',
noQuery(),
validatePackageURL,
validatePackageName,
validateQuery,
validateVersion,
serveFileBrowser
);

View File

@ -0,0 +1,14 @@
/**
* Strips all query params from the URL to increase cache hit rates.
*/
export default function noQuery() {
return (req, res, next) => {
const keys = Object.keys(req.query);
if (keys.length) {
return res.redirect(302, req.baseUrl + req.path);
}
next();
};
}