diff --git a/index.js b/index.js index f073c89..ad8531e 100644 --- a/index.js +++ b/index.js @@ -2,7 +2,7 @@ const path = require("path"); const express = require("express"); const dotenv = require("dotenv"); const morgan = require("morgan"); -// const mongoSanitize = require("express-mongo-sanitize"); +const mongoSanitize = require("express-mongo-sanitize"); const helmet = require("helmet"); // const xssClean = require("xss-clean"); const expressRateLimit = require("express-rate-limit"); @@ -85,8 +85,13 @@ if (process.env.NODE_ENV === "development") { //File Uploading ******************************************************* app.use(fileUpload()); -// Sanitize Data ******************************************************* -// app.use(mongoSanitize()); +// Sanitize Data (In-place sanitization compatible with Express 5 getter properties) +app.use((req, res, next) => { + if (req.body) mongoSanitize.sanitize(req.body); + if (req.params) mongoSanitize.sanitize(req.params); + if (req.query) mongoSanitize.sanitize(req.query); + next(); +}); //Set Security Headers ************************************************ app.use(helmet()); diff --git a/tests/mongoSanitize.test.js b/tests/mongoSanitize.test.js new file mode 100644 index 0000000..03145ab --- /dev/null +++ b/tests/mongoSanitize.test.js @@ -0,0 +1,25 @@ +const request = require("supertest"); +const app = require("../index"); + +describe("NoSQL Injection Prevention (mongoSanitize)", () => { + it("should sanitize $ operators from request body", async () => { + const agent = request.agent(app); + + // Fetch CSRF Token + const csrfRes = await agent.get("/api/v1/auth/csrf-token"); + const csrfToken = csrfRes.body.csrfToken; + + // Attempt login with NoSQL injection operator in email field + const res = await agent + .post("/api/v1/auth/login") + .set("x-csrf-token", csrfToken) + .send({ + email: { $gt: "" }, + password: "password123", + }); + + // Should fail with 400 or 401 instead of internal server error + expect(res.status).not.toBe(500); + expect(res.body.success).toBe(false); + }); +});