mongo-express-sanitize v1.0.1
mongo-express-sanitize
An Express 4.x middleware who prevent NoSQL injection
Installation
npm install mongo-express-sanitize
Usage
Add as a piece of express middleware, after body-parser and before defining your routes.
var express = require('express'),
bodyParser = require('body-parser'),
mongoSanitize = require('mongo-express-sanitize');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// To remove data, use:
app.use(mongoSanitize());
Function
The middleware search into req.body
, req.query
and req.params
and delete all key than begin with $
. This is a recursive function, it will call itself each time a JSON is found.
Why?
Object keys starting with a $
is reserved for use by MongoDB as operator. Without this sanitization, malicious users could send an object containing a $
operator which could change the context of a database operation. Most notorious is the $where
operator, which can execute arbitrary JavaScript on the database.
The best way to prevent this is to sanitize the received data, and remove any offending keys.
Credits
Inspired by express-mongo-sanitize.
License
MIT