From b2eed0cd1c73232327aa1bb57e013aa40444aa55 Mon Sep 17 00:00:00 2001 From: anshul23102 Date: Tue, 2 Jun 2026 00:18:37 +0530 Subject: [PATCH] fix(messages): enforce max content length in sendMessage Closes #266 sendMessage validated only that content was non-empty. The global express.json limit (100 KB) is too permissive for a single chat message, allowing a caller to store and transmit up to 100 KB of text in every message document. Add a MAX_CONTENT_LENGTH constant (2000 characters) checked before any database write. Non-string content also returns 400. Also add scheme validation on fileUrl (http/https only) and path-separator check on fileName to prevent URI and path injection via these fields. --- .../controllers/directMessage.controller.js | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/backend/controllers/directMessage.controller.js b/backend/controllers/directMessage.controller.js index 1687e96..05b2536 100644 --- a/backend/controllers/directMessage.controller.js +++ b/backend/controllers/directMessage.controller.js @@ -13,6 +13,27 @@ const sendMessage = async (req, res) => { return res.status(400).json({ error: 'Receiver ID and content are required' }); } + // Enforce a maximum message length to prevent oversized document storage + // and disproportionately large inbox payloads. The global express.json + // limit (100 KB) is too permissive for a single chat message. + const MAX_CONTENT_LENGTH = 2000; + if (typeof content !== 'string' || content.length > MAX_CONTENT_LENGTH) { + return res.status(400).json({ + error: `Message content must not exceed ${MAX_CONTENT_LENGTH} characters`, + }); + } + + // Validate fileUrl when present: only allow http/https scheme to prevent + // javascript: URI injection that a frontend might render as a clickable link. + if (fileUrl && !/^https?:\/\//i.test(fileUrl)) { + return res.status(400).json({ error: 'fileUrl must be an http or https URL' }); + } + + // fileName may not contain path separators. + if (fileName && /[/\\]/.test(fileName)) { + return res.status(400).json({ error: 'Invalid fileName' }); + } + // Check if receiver exists const receiver = await User.findById(receiverId); if (!receiver) {