From 05fc8ed5db983e351d715b6a7579d9cc59af0be3 Mon Sep 17 00:00:00 2001 From: Girish Ramakrishnan Date: Fri, 6 Jun 2025 16:30:43 +0200 Subject: [PATCH] Fix crash with express 5 express.json does not enforce json. this means it will pass it through but let req.body be undefined. this causes all our asserts to crash --- src/middleware/index.js | 1 + src/middleware/json.js | 18 ++++++++++++++++++ src/server.js | 2 +- 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 src/middleware/json.js diff --git a/src/middleware/index.js b/src/middleware/index.js index 98f8071ea..7abc815d9 100644 --- a/src/middleware/index.js +++ b/src/middleware/index.js @@ -3,6 +3,7 @@ exports = module.exports = { cookieParser: require('cookie-parser'), cors: require('./cors.js'), + json: require('./json.js'), lastMile: require('connect-lastmile'), multipart: require('./multipart.js'), timeout: require('connect-timeout') diff --git a/src/middleware/json.js b/src/middleware/json.js new file mode 100644 index 000000000..0f73ddd98 --- /dev/null +++ b/src/middleware/json.js @@ -0,0 +1,18 @@ +'use strict'; + +const express = require('express'); + +function _mime(req) { + const str = req.headers['content-type'] || ''; + return str.split(';')[0]; +} + +exports = module.exports = function (options) { + const json = express.json(options); + + return function (req, res, next) { + // enforce json body type. without this the json middleware will skip parsing and req.body might be undefined + if (_mime(req) !== 'application/json') return res.status(400).send('incorrect mime type. expecting application/json'); + json(req, res, next); + }; +}; diff --git a/src/server.js b/src/server.js index ef79598b4..798d52bf7 100644 --- a/src/server.js +++ b/src/server.js @@ -41,7 +41,7 @@ async function initializeExpressSync() { const REQUEST_TIMEOUT = 60000; // timeout for all requests (see also setTimeout on the httpServer) - const json = express.json({ strict: true, limit: QUERY_LIMIT }); // application/json + const json = middleware.json({ strict: true, limit: QUERY_LIMIT }); // forces json content-type app.set('json spaces', 2); // pretty json app.enable('trust proxy'); // trust the X-Forwarded-* headers