|
1 | 1 | # Express Mongo Sanitize
|
2 | 2 |
|
3 |
| -Express 4.x middleware which sanitizes user-supplied data to prevent MongoDB Operator Injection. |
| 3 | +Express 5.x middleware which sanitizes user-supplied data to prevent MongoDB Operator Injection. |
| 4 | + |
| 5 | +For Express 4.x please use v2.2 of this package. |
4 | 6 |
|
5 | 7 | [](https://github.com/fiznool/express-mongo-sanitize/actions/workflows/nodejs.yml)
|
6 | 8 | [](https://www.npmjs.com/package/express-mongo-sanitize)
|
@@ -42,7 +44,7 @@ const bodyParser = require('body-parser');
|
42 | 44 | const mongoSanitize = require('express-mongo-sanitize');
|
43 | 45 |
|
44 | 46 | const app = express();
|
45 |
| - |
| 47 | +app.set('query parser', 'extended'); |
46 | 48 | app.use(bodyParser.urlencoded({ extended: true }));
|
47 | 49 | app.use(bodyParser.json());
|
48 | 50 |
|
@@ -110,6 +112,24 @@ app.use(
|
110 | 112 | );
|
111 | 113 | ```
|
112 | 114 |
|
| 115 | +### Sanitizing Nested Objects |
| 116 | + |
| 117 | +To sanitize nested objects in query strings, such as `/query?username[$gt]=foo&username[dotted.data]=some_data`, ensure that Express' `query parser` option is set to `extended`. This helps protect against nested query injection attacks through query parameters. |
| 118 | + |
| 119 | +If `replaceWith` is not set, the sanitized query parameter will appear as: |
| 120 | + |
| 121 | +```json |
| 122 | +{ "username": {} } |
| 123 | +``` |
| 124 | + |
| 125 | +However, if using Express v5's default `simple` query parser, the query parameter will remain as: |
| 126 | + |
| 127 | +```json |
| 128 | +{ "username[$gt]": "foo" } |
| 129 | +``` |
| 130 | + |
| 131 | +For sanitizing nested objects in the request body, configure `bodyParser.urlencoded({ extended: true })`. |
| 132 | + |
113 | 133 | ### Node Modules API
|
114 | 134 |
|
115 | 135 | You can also bypass the middleware and use the module directly:
|
@@ -148,6 +168,10 @@ const hasProhibited = mongoSanitize.has(payload);
|
148 | 168 | const hasProhibited = mongoSanitize.has(payload, true);
|
149 | 169 | ```
|
150 | 170 |
|
| 171 | +### `req.query` Being Readonly in Express v5 |
| 172 | + |
| 173 | +`req.query` is designed to be read only in Express v5; however, this middleware modifies `req.query`, which might be unexpected for some users. |
| 174 | + |
151 | 175 | ## Contributing
|
152 | 176 |
|
153 | 177 | 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.
|
|
0 commit comments