• Stars
    star
    213
  • Rank 184,375 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Sanitize your express payload to prevent MongoDB operator injection.

Express Mongo Sanitize

Express 4.x middleware which sanitizes user-supplied data to prevent MongoDB Operator Injection.

Build Status npm version npm downloads per week Dependency Status

What is this module for?

This module searches for any keys in objects that begin with a $ sign or contain a ., from req.body, req.query, req.headers or req.params. It can then either:

  • completely remove these keys and associated data from the object, or
  • replace the prohibited characters with another allowed character.

The behaviour is governed by the passed option, replaceWith. Set this option to have the sanitizer replace the prohibited characters with the character passed in.

The config option allowDots can be used to allow dots in the user-supplied data. In this case, only instances of $ will be sanitized.

See the spec file for more examples.

Why is it needed?

Object keys starting with a $ or containing a . are reserved for use by MongoDB as operators. Without this sanitization, malicious users could send an object containing a $ operator, or including a ., 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, or replace the characters with a 'safe' one.

Installation

npm install express-mongo-sanitize

Usage

Add as a piece of express middleware, before defining your routes.

const express = require('express');
const bodyParser = require('body-parser');
const mongoSanitize = require('express-mongo-sanitize');

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// By default, $ and . characters are removed completely from user-supplied input in the following places:
// - req.body
// - req.query
// - req.params
// - req.headers

// To remove data using these defaults:
app.use(mongoSanitize());

// Or, to replace these prohibited characters with _, use:
app.use(
  mongoSanitize({
    replaceWith: '_',
  }),
);

// Or, to sanitize data that only contains $, without .(dot)
// Can be useful for letting data pass that is meant for querying nested documents.
// NOTE: This may cause some problems on older versions of MongoDb
// READ MORE: https://github.com/fiznool/express-mongo-sanitize/issues/36
app.use(
  mongoSanitize({
    allowDots: true,
  }),
);

// Both allowDots and replaceWith
app.use(
  mongoSanitize({
    allowDots: true,
    replaceWith: '_',
  }),
);

onSanitize

onSanitize callback is called after the request's value was sanitized.

app.use(
  mongoSanitize({
    onSanitize: ({ req, key }) => {
      console.warn(`This request[${key}] is sanitized`, req);
    },
  }),
);

dryRun

You can run this middleware as dry run mode.

app.use(
  mongoSanitize({
    dryRun: true,
    onSanitize: ({ req, key }) => {
      console.warn(`[DryRun] This request[${key}] will be sanitized`, req);
    },
  }),
);

Node Modules API

You can also bypass the middleware and use the module directly:

const mongoSanitize = require('express-mongo-sanitize');

const payload = {...};

// Remove any keys containing prohibited characters
mongoSanitize.sanitize(payload);

// Replace any prohibited characters in keys
mongoSanitize.sanitize(payload, {
  replaceWith: '_'
});

// Exclude sanitization of . (dot), only sanitize data that contains $.
// NOTE: This may cause some problems on older versions of MongoDb
// READ MORE: https://github.com/fiznool/express-mongo-sanitize/issues/36
mongoSanitize.sanitize(payload, {
  allowDots: true
});

// Both allowDots and replaceWith
mongoSanitize.sanitize(payload, {
  allowDots: true,
  replaceWith: '_'
});

// Check if the payload has keys with prohibited characters
const hasProhibited = mongoSanitize.has(payload);

// Check if the payload has keys with prohibited characters (`.` is excluded).
// If the payload only has `.` it will return false (since it doesn't see the data with `.` as malicious)
const hasProhibited = mongoSanitize.has(payload, true);

Contributing

PRs are welcome! Please add test coverage for any new features or bugfixes, and make sure to run npm run prettier before submitting a PR to ensure code consistency.

Credits

Inspired by mongo-sanitize.

License

MIT

More Repositories

1

passport-oauth2-refresh

A passport.js add-on to provide automatic OAuth 2.0 token refreshing.
JavaScript
189
star
2

backbone.basicauth

HTTP Basic Authentication for Backbone.
JavaScript
105
star
3

ng-elastic

Angular/Ionic 2 directive to auto expand textareas according to their contents.
TypeScript
49
star
4

body-parser-xml

XML parser middleware for express.js.
JavaScript
37
star
5

tappivate

A small library to help make your mobile web buttons and lists feel a little more app-y.
JavaScript
33
star
6

sugar-date

A customised build of sugar.js containing only the date functions.
JavaScript
12
star
7

poirot

A simple repo to showcase private repository deployment.
Shell
11
star
8

ng-imgcache

TypeScript
6
star
9

mean-docker-example

JavaScript
5
star
10

stimulus-typescript-starter

A humble blank slate for a modest JavaScript framework
JavaScript
2
star
11

GumtreeScraper

Java
2
star
12

Alinea-iPad-Demo

A demo iPad app to showcase retail-specific features.
JavaScript
2
star
13

backbone.sentry

Protect your Backbone Routes like a Sentry.
JavaScript
2
star
14

SweepBook

JavaScript
2
star
15

phonegap-animated-ios

Objective-C
2
star
16

no-rest-for-the-whippet

A tutorial for creating a test-driven REST API using Mongoose, Express, Node and Supertest. And dogs.
JavaScript
2
star
17

passportjs-example

JavaScript
1
star
18

ionic-prod-flag-tester

CSS
1
star
19

Recognizr

A small library to detect capabilities of mobile browsers.
JavaScript
1
star
20

Backbone-ZombieNation

A small library which helps to manage bindings and subviews in a Backbone Application.
JavaScript
1
star
21

SafariApps-Prototype

Prototype for SafariApps.
JavaScript
1
star
22

tomspencer.dev

Astro
1
star
23

norrisbot

JavaScript
1
star
24

ng-component-router-example

JavaScript
1
star
25

catinator

JavaScript
1
star