@exortek/express-mongo-sanitize 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +269 -185
- package/index.js +255 -193
- package/package.json +7 -6
- package/types/index.d.ts +56 -38
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2024 Memet
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Memet
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,185 +1,269 @@
|
|
|
1
|
-
# @exortek/express-mongo-sanitize
|
|
2
|
-
|
|
3
|
-
A middleware designed
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
```
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
```
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
## Usage
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
##
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
##
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
##
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
1
|
+
# @exortek/express-mongo-sanitize
|
|
2
|
+
|
|
3
|
+
A comprehensive Express middleware designed to protect your No(n)SQL queries from injection attacks by sanitizing request data.
|
|
4
|
+
This middleware provides flexible sanitization options for request bodies and query strings, and an **optional handler for route parameters**.
|
|
5
|
+
|
|
6
|
+
## Compatibility
|
|
7
|
+
|
|
8
|
+
| Middleware version | Express version |
|
|
9
|
+
|--------------------|:---------------:|
|
|
10
|
+
| `^1.x` | `^4.x` |
|
|
11
|
+
| `^1.x` | `^5.x` |
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
- Automatic sanitization of `req.body` and `req.query` by default
|
|
16
|
+
- Supports deep/nested objects, arrays, and string transformation
|
|
17
|
+
- Allows custom sanitizer logic, key allow/deny lists, skip routes, and more
|
|
18
|
+
- **Route params (`req.params`) can be sanitized with an explicit helper** (see below)
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
yarn add @exortek/express-mongo-sanitize
|
|
26
|
+
# or
|
|
27
|
+
npm install @exortek/express-mongo-sanitize
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Usage
|
|
33
|
+
|
|
34
|
+
### Basic usage
|
|
35
|
+
|
|
36
|
+
```js
|
|
37
|
+
const express = require('express');
|
|
38
|
+
const expressMongoSanitize = require('@exortek/express-mongo-sanitize');
|
|
39
|
+
|
|
40
|
+
const app = express();
|
|
41
|
+
app.use(express.json());
|
|
42
|
+
|
|
43
|
+
// Body and query are sanitized automatically:
|
|
44
|
+
app.use(expressMongoSanitize());
|
|
45
|
+
|
|
46
|
+
app.post('/submit', (req, res) => {
|
|
47
|
+
res.json(req.body);
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
### Sanitizing Route Params (`req.params`)
|
|
54
|
+
|
|
55
|
+
By default, only `body` and `query` are sanitized.
|
|
56
|
+
**If you want to sanitize route parameters (`req.params`),**
|
|
57
|
+
use the exported `paramSanitizeHandler` with Express's `app.param` or `router.param`:
|
|
58
|
+
|
|
59
|
+
```js
|
|
60
|
+
// Route parameter sanitization (recommended way):
|
|
61
|
+
app.param('username', expressMongoSanitize.paramSanitizeHandler());
|
|
62
|
+
|
|
63
|
+
// Example route:
|
|
64
|
+
app.get('/user/:username', (req, res) => {
|
|
65
|
+
res.json({ username: req.params.username });
|
|
66
|
+
});
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
**Note:**
|
|
70
|
+
- You can attach this for any route param, e.g. `'id'`, `'slug'`, etc.
|
|
71
|
+
- This gives you full control and doesn't require the middleware to know your routes.
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## Options
|
|
76
|
+
|
|
77
|
+
| Option | Type | Default | Description |
|
|
78
|
+
|-------------------|----------|-------------------------------------|---------------------------------------------------------------------|
|
|
79
|
+
| `replaceWith` | string | `''` | String to replace matched patterns |
|
|
80
|
+
| `removeMatches` | boolean | `false` | Remove values matching patterns entirely |
|
|
81
|
+
| `sanitizeObjects` | string[] | `['body', 'query']` | List of request objects to sanitize |
|
|
82
|
+
| `mode` | string | `'auto'` | `'auto'` for automatic, `'manual'` for explicit req.sanitize() call |
|
|
83
|
+
| `skipRoutes` | string[] | `[]` | List of paths to skip (e.g. ['/health']) |
|
|
84
|
+
| `customSanitizer` | function | `null` | Custom sanitizer function, overrides built-in sanitizer |
|
|
85
|
+
| `recursive` | boolean | `true` | Recursively sanitize nested values |
|
|
86
|
+
| `removeEmpty` | boolean | `false` | Remove empty values after sanitization |
|
|
87
|
+
| `patterns` | RegExp[] | See source code | Patterns to match for sanitization |
|
|
88
|
+
| `allowedKeys` | string[] | `[]` | Only allow these keys (all if empty) |
|
|
89
|
+
| `deniedKeys` | string[] | `[]` | Remove these keys (none if empty) |
|
|
90
|
+
| `stringOptions` | object | See below | String transform options (trim, lowercase, maxLength) |
|
|
91
|
+
| `arrayOptions` | object | See below | Array handling options (filterNull, distinct) |
|
|
92
|
+
| `debug` | object | `{ enabled: false, level: "info" }` | Enables debug logging for middleware internals. |
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
#### `stringOptions` default:
|
|
96
|
+
|
|
97
|
+
```js
|
|
98
|
+
{
|
|
99
|
+
trim: false,
|
|
100
|
+
lowercase: false,
|
|
101
|
+
maxLength: null
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
#### `arrayOptions` default:
|
|
106
|
+
|
|
107
|
+
```js
|
|
108
|
+
{
|
|
109
|
+
filterNull: false,
|
|
110
|
+
distinct: false
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## Manual Mode
|
|
117
|
+
|
|
118
|
+
If you set `mode: 'manual'`, the middleware will not sanitize automatically.
|
|
119
|
+
Call `req.sanitize()` manually in your route:
|
|
120
|
+
|
|
121
|
+
```js
|
|
122
|
+
app.use(expressMongoSanitize({ mode: 'manual' }));
|
|
123
|
+
|
|
124
|
+
app.post('/manual', (req, res) => {
|
|
125
|
+
req.sanitize({ replaceWith: '_' }); // custom options are supported here
|
|
126
|
+
res.json(req.body);
|
|
127
|
+
});
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
## Skipping Routes
|
|
133
|
+
|
|
134
|
+
Skip certain routes by adding their paths to `skipRoutes`:
|
|
135
|
+
|
|
136
|
+
```js
|
|
137
|
+
app.use(expressMongoSanitize({ skipRoutes: ['/skip', '/status'] }));
|
|
138
|
+
|
|
139
|
+
// These routes will NOT be sanitized
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## Custom Sanitizer
|
|
145
|
+
|
|
146
|
+
Use a completely custom sanitizer function:
|
|
147
|
+
|
|
148
|
+
```js
|
|
149
|
+
app.use(expressMongoSanitize({
|
|
150
|
+
customSanitizer: (data, options) => {
|
|
151
|
+
// Your custom logic
|
|
152
|
+
return data;
|
|
153
|
+
}
|
|
154
|
+
}));
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
## Route Parameter Sanitization
|
|
160
|
+
|
|
161
|
+
> By default, only `body` and `query` are sanitized.
|
|
162
|
+
> If you want to sanitize route parameters (`req.params`),
|
|
163
|
+
> use the helper function with `app.param` or `router.param`:
|
|
164
|
+
>
|
|
165
|
+
> ```js
|
|
166
|
+
> app.param('username', expressMongoSanitize.paramSanitizeHandler());
|
|
167
|
+
> ```
|
|
168
|
+
>
|
|
169
|
+
> This ensures that, for example, `/user/$admin` will be returned as `{ username: 'admin' }`
|
|
170
|
+
> in your handler.
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
## TypeScript
|
|
175
|
+
|
|
176
|
+
Type definitions are included.
|
|
177
|
+
You can use this plugin in both CommonJS and ESM projects.
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
## Advanced Usage
|
|
182
|
+
|
|
183
|
+
### Custom Sanitizer per Route
|
|
184
|
+
|
|
185
|
+
You can override sanitizer options or use a completely custom sanitizer per route:
|
|
186
|
+
|
|
187
|
+
```js
|
|
188
|
+
app.post('/profile', (req, res, next) => {
|
|
189
|
+
req.sanitize({
|
|
190
|
+
customSanitizer: (data) => {
|
|
191
|
+
// For example, redact all strings:
|
|
192
|
+
if (typeof data === 'string') return '[REDACTED]';
|
|
193
|
+
return data;
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
res.json(req.body);
|
|
197
|
+
});
|
|
198
|
+
```
|
|
199
|
+
## Debugging & Logging
|
|
200
|
+
|
|
201
|
+
You can enable debug logs to see the internal operation of the middleware.
|
|
202
|
+
Useful for troubleshooting or when tuning sanitization behavior.
|
|
203
|
+
|
|
204
|
+
```js
|
|
205
|
+
app.use(
|
|
206
|
+
expressMongoSanitize({
|
|
207
|
+
debug: {
|
|
208
|
+
enabled: true, // Turn on debug logs
|
|
209
|
+
level: 'debug', // Log level: 'error' | 'warn' | 'info' | 'debug' | 'trace'
|
|
210
|
+
logSkippedRoutes: true // (optional) Log when routes are skipped
|
|
211
|
+
},
|
|
212
|
+
// ...other options
|
|
213
|
+
})
|
|
214
|
+
);
|
|
215
|
+
```
|
|
216
|
+
### Logging Levels
|
|
217
|
+
| Level | Description |
|
|
218
|
+
|---------|--------------------------------------|
|
|
219
|
+
| `error` | Logs only errors |
|
|
220
|
+
| `warn` | Logs warnings and errors |
|
|
221
|
+
| `info` | Logs informational messages |
|
|
222
|
+
| `debug` | Logs detailed debug information |
|
|
223
|
+
| `trace` | Logs very detailed trace information |
|
|
224
|
+
|
|
225
|
+
### Using with Router
|
|
226
|
+
|
|
227
|
+
```js
|
|
228
|
+
const router = express.Router();
|
|
229
|
+
router.use(expressMongoSanitize());
|
|
230
|
+
// You can use paramSanitizeHandler on router params as well:
|
|
231
|
+
router.param('userId', expressMongoSanitize.paramSanitizeHandler());
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
---
|
|
235
|
+
|
|
236
|
+
## Troubleshooting
|
|
237
|
+
|
|
238
|
+
### Route parameters are not being sanitized
|
|
239
|
+
|
|
240
|
+
By default, only `body` and `query` are sanitized.
|
|
241
|
+
To sanitize route parameters, use:
|
|
242
|
+
|
|
243
|
+
```js
|
|
244
|
+
app.param('username', expressMongoSanitize.paramSanitizeHandler());
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
### Skipping specific routes doesn't work as expected
|
|
248
|
+
|
|
249
|
+
Make sure you use the exact path as in your route definition,
|
|
250
|
+
and that you apply the middleware before your routes.
|
|
251
|
+
|
|
252
|
+
---
|
|
253
|
+
|
|
254
|
+
### My request is not being sanitized
|
|
255
|
+
|
|
256
|
+
- Ensure your route handler is after the middleware in the stack.
|
|
257
|
+
- If you are using `mode: 'manual'`, you **must** call `req.sanitize()` yourself.
|
|
258
|
+
|
|
259
|
+
---
|
|
260
|
+
|
|
261
|
+
For more troubleshooting, open an issue at [Github Issues](https://github.com/ExorTek/express-mongo-sanitize/issues)
|
|
262
|
+
|
|
263
|
+
---
|
|
264
|
+
|
|
265
|
+
## License
|
|
266
|
+
|
|
267
|
+
**[MIT](https://github.com/ExorTek/express-mongo-sanitize/blob/master/LICENSE)**<br>
|
|
268
|
+
|
|
269
|
+
Copyright © 2025 ExorTek
|
package/index.js
CHANGED
|
@@ -1,116 +1,188 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* Regular expression patterns used for sanitizing input data.
|
|
5
|
+
* These patterns match common MongoDB injection attack vectors.
|
|
6
|
+
* @constant {ReadonlyArray<RegExp>}
|
|
6
7
|
*/
|
|
7
8
|
const PATTERNS = Object.freeze([
|
|
8
|
-
|
|
9
|
-
/\./g,
|
|
10
|
-
/[\\\/{}.(*+?|[\]^)]/g,
|
|
11
|
-
/[\u0000-\u001F\u007F-\u009F]/g,
|
|
12
|
-
/\{\s*\$|\$?\{(.|\r?\n)*\}/g,
|
|
9
|
+
/\$/g,
|
|
10
|
+
/\./g,
|
|
11
|
+
/[\\\/{}.(*+?|[\]^)]/g,
|
|
12
|
+
/[\u0000-\u001F\u007F-\u009F]/g,
|
|
13
|
+
/\{\s*\$|\$?\{(.|\r?\n)*\}/g,
|
|
13
14
|
]);
|
|
14
15
|
|
|
15
16
|
/**
|
|
16
|
-
* Default configuration options for the
|
|
17
|
+
* Default configuration options for the sanitizer.
|
|
17
18
|
* @constant {Object}
|
|
19
|
+
* @property {string} replaceWith - String to replace sanitized content with
|
|
20
|
+
* @property {boolean} removeMatches - Whether to remove matches entirely
|
|
21
|
+
* @property {string[]} sanitizeObjects - Request objects to sanitize
|
|
22
|
+
* @property {string} mode - Operation mode ('auto' or 'manual')
|
|
23
|
+
* @property {string[]} skipRoutes - Routes to skip sanitization
|
|
24
|
+
* @property {Function|null} customSanitizer - Custom sanitization function
|
|
25
|
+
* @property {boolean} recursive - Whether to sanitize recursively
|
|
26
|
+
* @property {boolean} removeEmpty - Whether to remove empty values
|
|
27
|
+
* @property {RegExp[]} patterns - Patterns to match for sanitization
|
|
28
|
+
* @property {string[]} allowedKeys - Keys that are allowed
|
|
29
|
+
* @property {string[]} deniedKeys - Keys that are denied
|
|
30
|
+
* @property {Object} stringOptions - String-specific options
|
|
31
|
+
* @property {Object} arrayOptions - Array-specific options
|
|
32
|
+
* @property {Object} debug - Debug configuration
|
|
18
33
|
*/
|
|
19
34
|
const DEFAULT_OPTIONS = Object.freeze({
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
patterns: PATTERNS, // An array of patterns to match. Default is an array of patterns that match illegal characters and sequences. You can specify your own patterns if you want to match different characters or sequences. Each pattern must be a regular expression.
|
|
32
|
-
allowedKeys: [], // An array of allowed keys. Default is array. If you want to allow only certain keys in the object, you can specify the keys here. The keys must be strings. If a key is not in the allowedKeys array, it will be removed.
|
|
33
|
-
deniedKeys: [], // An array of denied keys. Default is array. If you want to deny certain keys in the object, you can specify the keys here. The keys must be strings. If a key is in the deniedKeys array, it will be removed.
|
|
35
|
+
replaceWith: '',
|
|
36
|
+
removeMatches: false,
|
|
37
|
+
sanitizeObjects: ['body', 'query'],
|
|
38
|
+
mode: 'auto',
|
|
39
|
+
skipRoutes: [],
|
|
40
|
+
customSanitizer: null,
|
|
41
|
+
recursive: true,
|
|
42
|
+
removeEmpty: false,
|
|
43
|
+
patterns: PATTERNS,
|
|
44
|
+
allowedKeys: [],
|
|
45
|
+
deniedKeys: [],
|
|
34
46
|
stringOptions: {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
maxLength: null, // Maximum length. Default is null. If you want to limit the maximum length of the string, you can set this option to a number. If the string length exceeds the maximum length, it will be truncated.
|
|
47
|
+
trim: false,
|
|
48
|
+
lowercase: false,
|
|
49
|
+
maxLength: null,
|
|
39
50
|
},
|
|
40
51
|
arrayOptions: {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
52
|
+
filterNull: false,
|
|
53
|
+
distinct: false,
|
|
54
|
+
},
|
|
55
|
+
debug: {
|
|
56
|
+
enabled: false,
|
|
57
|
+
level: 'info',
|
|
58
|
+
logSkippedRoutes: false,
|
|
44
59
|
},
|
|
45
60
|
});
|
|
46
61
|
|
|
47
62
|
/**
|
|
48
|
-
*
|
|
63
|
+
* Log level priority mapping for filtering debug output.
|
|
64
|
+
* @constant {Object<string, number>}
|
|
65
|
+
*/
|
|
66
|
+
const LOG_LEVELS = Object.freeze({
|
|
67
|
+
silent: 0,
|
|
68
|
+
error: 1,
|
|
69
|
+
warn: 2,
|
|
70
|
+
info: 3,
|
|
71
|
+
debug: 4,
|
|
72
|
+
trace: 5,
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* ANSI color codes for console output formatting.
|
|
77
|
+
* @constant {Object<string, string>}
|
|
78
|
+
*/
|
|
79
|
+
const LOG_COLORS = Object.freeze({
|
|
80
|
+
error: '\x1b[31m',
|
|
81
|
+
warn: '\x1b[33m',
|
|
82
|
+
info: '\x1b[36m',
|
|
83
|
+
debug: '\x1b[90m',
|
|
84
|
+
trace: '\x1b[35m',
|
|
85
|
+
reset: '\x1b[0m',
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Logs debug messages with colored output and formatting.
|
|
90
|
+
* @param {Object} debugOpts - Debug configuration options
|
|
91
|
+
* @param {string} level - Log level (error, warn, info, debug, trace)
|
|
92
|
+
* @param {string} context - Context identifier for the log message
|
|
93
|
+
* @param {string} message - Main log message
|
|
94
|
+
* @param {*} [data=null] - Optional data to include in the log
|
|
95
|
+
*/
|
|
96
|
+
const log = (debugOpts, level, context, message, data = null) => {
|
|
97
|
+
if (!debugOpts?.enabled || LOG_LEVELS[debugOpts.level || 'silent'] < LOG_LEVELS[level]) return;
|
|
98
|
+
const color = LOG_COLORS[level] || '';
|
|
99
|
+
const reset = LOG_COLORS.reset;
|
|
100
|
+
const timestamp = new Date().toISOString();
|
|
101
|
+
let logMessage = `${color}[mongo-sanitize:${level.toUpperCase()}]${reset} ${timestamp} [${context}] ${message}`;
|
|
102
|
+
if (data !== null) {
|
|
103
|
+
if (typeof data === 'object') {
|
|
104
|
+
console.log(logMessage);
|
|
105
|
+
console.log(`${color}Data:${reset}`, JSON.stringify(data, null, 2));
|
|
106
|
+
} else {
|
|
107
|
+
console.log(logMessage, data);
|
|
108
|
+
}
|
|
109
|
+
} else {
|
|
110
|
+
console.log(logMessage);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Checks if a value is a string.
|
|
49
116
|
* @param {*} value - Value to check
|
|
50
|
-
* @returns {boolean} True if value is string
|
|
117
|
+
* @returns {boolean} True if value is a string
|
|
51
118
|
*/
|
|
52
119
|
const isString = (value) => typeof value === 'string';
|
|
53
120
|
|
|
54
121
|
/**
|
|
55
|
-
*
|
|
56
|
-
* @param {
|
|
57
|
-
* @returns {boolean} True if value is a valid email
|
|
122
|
+
* Validates if a string is a valid email address.
|
|
123
|
+
* @param {*} val - Value to validate
|
|
124
|
+
* @returns {boolean} True if value is a valid email
|
|
58
125
|
*/
|
|
59
126
|
const isEmail = (val) =>
|
|
60
127
|
isString(val) &&
|
|
61
|
-
// RFC 5322 compliant email regex
|
|
62
128
|
/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i.test(
|
|
63
129
|
val
|
|
64
130
|
);
|
|
65
131
|
|
|
66
132
|
/**
|
|
67
|
-
* Checks if value is a plain object
|
|
133
|
+
* Checks if a value is a plain object (not array, date, etc.).
|
|
68
134
|
* @param {*} obj - Value to check
|
|
69
|
-
* @returns {boolean} True if value is plain object
|
|
135
|
+
* @returns {boolean} True if value is a plain object
|
|
70
136
|
*/
|
|
71
137
|
const isPlainObject = (obj) => !!obj && Object.prototype.toString.call(obj) === '[object Object]';
|
|
72
138
|
|
|
139
|
+
/**
|
|
140
|
+
* Checks if an object is empty (has no own properties).
|
|
141
|
+
* @param {*} obj - Object to check
|
|
142
|
+
* @returns {boolean} True if object is empty
|
|
143
|
+
*/
|
|
73
144
|
const isObjectEmpty = (obj) => {
|
|
74
145
|
if (!isPlainObject(obj)) return false;
|
|
75
146
|
return !Object.hasOwn(obj, Object.keys(obj)[0]);
|
|
76
147
|
};
|
|
77
148
|
|
|
78
149
|
/**
|
|
79
|
-
* Checks if value is an array
|
|
150
|
+
* Checks if a value is an array.
|
|
80
151
|
* @param {*} value - Value to check
|
|
81
|
-
* @returns {boolean} True if value is array
|
|
152
|
+
* @returns {boolean} True if value is an array
|
|
82
153
|
*/
|
|
83
154
|
const isArray = (value) => Array.isArray(value);
|
|
84
155
|
|
|
85
156
|
/**
|
|
86
|
-
* Checks if value is a primitive (null,
|
|
157
|
+
* Checks if a value is a primitive type (null, boolean, number).
|
|
87
158
|
* @param {*} value - Value to check
|
|
88
159
|
* @returns {boolean} True if value is primitive
|
|
89
160
|
*/
|
|
90
161
|
const isPrimitive = (value) => value == null || typeof value === 'boolean' || typeof value === 'number';
|
|
91
162
|
|
|
92
163
|
/**
|
|
93
|
-
* Checks if value is a Date object
|
|
164
|
+
* Checks if a value is a Date object.
|
|
94
165
|
* @param {*} value - Value to check
|
|
95
|
-
* @returns {boolean} True if value is Date
|
|
166
|
+
* @returns {boolean} True if value is a Date
|
|
96
167
|
*/
|
|
97
168
|
const isDate = (value) => value instanceof Date;
|
|
98
169
|
|
|
99
170
|
/**
|
|
100
|
-
* Checks if value is a function
|
|
171
|
+
* Checks if a value is a function.
|
|
101
172
|
* @param {*} value - Value to check
|
|
102
|
-
* @returns {boolean} True if value is function
|
|
173
|
+
* @returns {boolean} True if value is a function
|
|
103
174
|
*/
|
|
104
175
|
const isFunction = (value) => typeof value === 'function';
|
|
105
176
|
|
|
106
177
|
/**
|
|
107
|
-
*
|
|
178
|
+
* Custom error class for express-mongo-sanitize specific errors.
|
|
179
|
+
* @extends Error
|
|
108
180
|
*/
|
|
109
181
|
class ExpressMongoSanitizeError extends Error {
|
|
110
182
|
/**
|
|
111
|
-
* Creates a new ExpressMongoSanitizeError
|
|
183
|
+
* Creates a new ExpressMongoSanitizeError.
|
|
112
184
|
* @param {string} message - Error message
|
|
113
|
-
* @param {string} [type='generic'] - Error type
|
|
185
|
+
* @param {string} [type='generic'] - Error type identifier
|
|
114
186
|
*/
|
|
115
187
|
constructor(message, type = 'generic') {
|
|
116
188
|
super(message);
|
|
@@ -121,90 +193,107 @@ class ExpressMongoSanitizeError extends Error {
|
|
|
121
193
|
}
|
|
122
194
|
|
|
123
195
|
/**
|
|
124
|
-
*
|
|
125
|
-
* @param {string} message - Warning message
|
|
126
|
-
* @returns {void}
|
|
127
|
-
*/
|
|
128
|
-
const createColorizedWarningMessage = (message) => console.log(`\x1b[33m%s\x1b[0m`, message);
|
|
129
|
-
|
|
130
|
-
/**
|
|
131
|
-
* Sanitizes a string value according to provided options
|
|
196
|
+
* Sanitizes a string by removing or replacing dangerous patterns.
|
|
132
197
|
* @param {string} str - String to sanitize
|
|
133
198
|
* @param {Object} options - Sanitization options
|
|
134
|
-
* @param {boolean} isValue - Whether
|
|
199
|
+
* @param {boolean} [isValue=false] - Whether this is a value (affects length limits)
|
|
135
200
|
* @returns {string} Sanitized string
|
|
136
201
|
*/
|
|
137
202
|
const sanitizeString = (str, options, isValue = false) => {
|
|
138
|
-
|
|
139
|
-
|
|
203
|
+
const { debug } = options;
|
|
204
|
+
if (!isString(str) || isEmail(str)) {
|
|
205
|
+
log(debug, 'trace', 'STRING', `Skipping: not a string or is email`, str);
|
|
206
|
+
return str;
|
|
207
|
+
}
|
|
140
208
|
const { replaceWith, patterns, stringOptions } = options;
|
|
141
|
-
|
|
142
209
|
const combinedPattern = new RegExp(patterns.map((pattern) => pattern.source).join('|'), 'g');
|
|
143
|
-
|
|
210
|
+
const original = str;
|
|
144
211
|
let result = str.replace(combinedPattern, replaceWith);
|
|
145
|
-
|
|
146
212
|
if (stringOptions.trim) result = result.trim();
|
|
147
213
|
if (stringOptions.lowercase) result = result.toLowerCase();
|
|
148
214
|
if (stringOptions.maxLength && isValue) result = result.slice(0, stringOptions.maxLength);
|
|
149
|
-
|
|
215
|
+
if (debug?.enabled && original !== result) {
|
|
216
|
+
log(debug, 'debug', 'STRING', `Sanitized string`, { original, result });
|
|
217
|
+
}
|
|
150
218
|
return result;
|
|
151
219
|
};
|
|
152
220
|
|
|
153
221
|
/**
|
|
154
|
-
* Sanitizes an array
|
|
222
|
+
* Sanitizes an array by processing each element and applying array-specific options.
|
|
155
223
|
* @param {Array} arr - Array to sanitize
|
|
156
224
|
* @param {Object} options - Sanitization options
|
|
157
225
|
* @returns {Array} Sanitized array
|
|
158
226
|
* @throws {ExpressMongoSanitizeError} If input is not an array
|
|
159
227
|
*/
|
|
160
228
|
const sanitizeArray = (arr, options) => {
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
229
|
+
const { debug } = options;
|
|
230
|
+
if (!isArray(arr)) {
|
|
231
|
+
log(debug, 'error', 'ARRAY', `Input is not array`, arr);
|
|
232
|
+
throw new ExpressMongoSanitizeError('Input must be an array', 'type_error');
|
|
233
|
+
}
|
|
234
|
+
log(debug, 'trace', 'ARRAY', `Sanitizing array of length ${arr.length}`);
|
|
164
235
|
let result = arr.map((item) => sanitizeValue(item, options, true));
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
236
|
+
if (options.arrayOptions.filterNull) {
|
|
237
|
+
const before = result.length;
|
|
238
|
+
result = result.filter(Boolean);
|
|
239
|
+
log(debug, 'debug', 'ARRAY', `Filtered nulls: ${before} → ${result.length}`);
|
|
240
|
+
}
|
|
241
|
+
if (options.arrayOptions.distinct) {
|
|
242
|
+
const before = result.length;
|
|
243
|
+
result = [...new Set(result)];
|
|
244
|
+
log(debug, 'debug', 'ARRAY', `Removed duplicates: ${before} → ${result.length}`);
|
|
245
|
+
}
|
|
168
246
|
return result;
|
|
169
247
|
};
|
|
170
248
|
|
|
171
249
|
/**
|
|
172
|
-
* Sanitizes an object according to
|
|
250
|
+
* Sanitizes an object by processing keys and values according to configuration.
|
|
173
251
|
* @param {Object} obj - Object to sanitize
|
|
174
252
|
* @param {Object} options - Sanitization options
|
|
175
253
|
* @returns {Object} Sanitized object
|
|
176
254
|
* @throws {ExpressMongoSanitizeError} If input is not an object
|
|
177
255
|
*/
|
|
178
256
|
const sanitizeObject = (obj, options) => {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
257
|
+
const { debug, removeEmpty, allowedKeys, deniedKeys, removeMatches, patterns } = options;
|
|
258
|
+
if (!isPlainObject(obj)) {
|
|
259
|
+
log(debug, 'error', 'OBJECT', `Input is not object`, obj);
|
|
260
|
+
throw new ExpressMongoSanitizeError('Input must be an object', 'type_error');
|
|
261
|
+
}
|
|
262
|
+
log(debug, 'trace', 'OBJECT', `Sanitizing object with keys: ${Object.keys(obj)}`);
|
|
182
263
|
return Object.entries(obj).reduce((acc, [key, val]) => {
|
|
183
|
-
if ((allowedKeys.size && !allowedKeys.has(key)) || deniedKeys.has(key))
|
|
184
|
-
|
|
264
|
+
if ((allowedKeys.size && !allowedKeys.has(key)) || deniedKeys.has(key)) {
|
|
265
|
+
log(debug, 'debug', 'OBJECT', `Key '${key}' removed (allowed/denied filter)`);
|
|
266
|
+
return acc;
|
|
267
|
+
}
|
|
185
268
|
const sanitizedKey = sanitizeString(key, options);
|
|
186
|
-
if (removeMatches && patterns.some((pattern) => pattern.test(key)))
|
|
187
|
-
|
|
188
|
-
|
|
269
|
+
if (removeMatches && patterns.some((pattern) => pattern.test(key))) {
|
|
270
|
+
log(debug, 'debug', 'OBJECT', `Key '${key}' matches removal pattern`);
|
|
271
|
+
return acc;
|
|
272
|
+
}
|
|
273
|
+
if (removeEmpty && !sanitizedKey) {
|
|
274
|
+
log(debug, 'debug', 'OBJECT', `Key '${key}' removed (empty after sanitize)`);
|
|
275
|
+
return acc;
|
|
276
|
+
}
|
|
189
277
|
if (isEmail(val) && deniedKeys.has(key)) {
|
|
190
278
|
acc[sanitizedKey] = val;
|
|
279
|
+
log(debug, 'trace', 'OBJECT', `Email field preserved: ${key}`);
|
|
280
|
+
return acc;
|
|
281
|
+
}
|
|
282
|
+
if (removeMatches && isString(val) && patterns.some((pattern) => pattern.test(val))) {
|
|
283
|
+
log(debug, 'debug', 'OBJECT', `Value for key '${key}' matches removal pattern`);
|
|
191
284
|
return acc;
|
|
192
285
|
}
|
|
193
|
-
|
|
194
|
-
if (removeMatches && isString(val) && patterns.some((pattern) => pattern.test(val))) return acc;
|
|
195
|
-
|
|
196
286
|
const sanitizedValue = sanitizeValue(val, options, true);
|
|
197
287
|
if (!removeEmpty || sanitizedValue) acc[sanitizedKey] = sanitizedValue;
|
|
198
|
-
|
|
199
288
|
return acc;
|
|
200
289
|
}, {});
|
|
201
290
|
};
|
|
202
291
|
|
|
203
292
|
/**
|
|
204
|
-
*
|
|
293
|
+
* Main sanitization function that routes values to appropriate sanitizers.
|
|
205
294
|
* @param {*} value - Value to sanitize
|
|
206
295
|
* @param {Object} options - Sanitization options
|
|
207
|
-
* @param {boolean} [isValue=false] - Whether
|
|
296
|
+
* @param {boolean} [isValue=false] - Whether this is a value context
|
|
208
297
|
* @returns {*} Sanitized value
|
|
209
298
|
*/
|
|
210
299
|
const sanitizeValue = (value, options, isValue = false) => {
|
|
@@ -215,15 +304,12 @@ const sanitizeValue = (value, options, isValue = false) => {
|
|
|
215
304
|
};
|
|
216
305
|
|
|
217
306
|
/**
|
|
218
|
-
* Validates
|
|
307
|
+
* Validates the provided options object against expected schema.
|
|
219
308
|
* @param {Object} options - Options to validate
|
|
220
309
|
* @throws {ExpressMongoSanitizeError} If any option is invalid
|
|
221
310
|
*/
|
|
222
311
|
const validateOptions = (options) => {
|
|
223
312
|
const validators = {
|
|
224
|
-
app: (value) => !value || isFunction(value),
|
|
225
|
-
router: (value) => !value || isFunction(value),
|
|
226
|
-
routerBasePath: isString,
|
|
227
313
|
replaceWith: isString,
|
|
228
314
|
removeMatches: isPrimitive,
|
|
229
315
|
sanitizeObjects: isArray,
|
|
@@ -238,7 +324,6 @@ const validateOptions = (options) => {
|
|
|
238
324
|
stringOptions: isPlainObject,
|
|
239
325
|
arrayOptions: isPlainObject,
|
|
240
326
|
};
|
|
241
|
-
|
|
242
327
|
for (const [key, validate] of Object.entries(validators)) {
|
|
243
328
|
if (!validate(options[key])) {
|
|
244
329
|
throw new ExpressMongoSanitizeError(`Invalid configuration: "${key}" with value "${options[key]}"`, 'type_error');
|
|
@@ -247,86 +332,67 @@ const validateOptions = (options) => {
|
|
|
247
332
|
};
|
|
248
333
|
|
|
249
334
|
/**
|
|
250
|
-
*
|
|
335
|
+
* Checks if a property is writable on an object or its prototype chain.
|
|
336
|
+
* @param {Object} obj - Object to check
|
|
337
|
+
* @param {string} prop - Property name to check
|
|
338
|
+
* @returns {boolean} True if property is writable
|
|
339
|
+
*/
|
|
340
|
+
const isWritable = (obj, prop) => {
|
|
341
|
+
let cur = obj;
|
|
342
|
+
while (cur) {
|
|
343
|
+
const descriptor = Object.getOwnPropertyDescriptor(cur, prop);
|
|
344
|
+
if (descriptor) return !!descriptor.writable;
|
|
345
|
+
cur = Object.getPrototypeOf(cur);
|
|
346
|
+
}
|
|
347
|
+
return true;
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Handles sanitization of Express request objects.
|
|
251
352
|
* @param {Object} request - Express request object
|
|
252
353
|
* @param {Object} options - Sanitization options
|
|
253
354
|
*/
|
|
254
355
|
const handleRequest = (request, options) => {
|
|
255
|
-
const { sanitizeObjects, customSanitizer } = options;
|
|
256
|
-
|
|
257
|
-
|
|
356
|
+
const { sanitizeObjects, customSanitizer, debug } = options;
|
|
357
|
+
log(debug, 'info', 'REQUEST', `Sanitizing request`, { url: request.originalUrl || request.url });
|
|
358
|
+
sanitizeObjects.forEach((sanitizeObject) => {
|
|
258
359
|
const requestObject = request[sanitizeObject];
|
|
259
360
|
if (requestObject && !isObjectEmpty(requestObject)) {
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
361
|
+
log(debug, 'debug', 'REQUEST', `Sanitizing '${sanitizeObject}'`, requestObject);
|
|
362
|
+
const originalRequest = Object.assign(Array.isArray(requestObject) ? [] : {}, requestObject);
|
|
363
|
+
const sanitized = customSanitizer
|
|
263
364
|
? customSanitizer(originalRequest, options)
|
|
264
365
|
: sanitizeValue(originalRequest, options);
|
|
366
|
+
if (debug?.enabled && JSON.stringify(originalRequest) !== JSON.stringify(sanitized)) {
|
|
367
|
+
log(debug, 'debug', 'REQUEST', `'${sanitizeObject}' sanitized`, {
|
|
368
|
+
before: originalRequest,
|
|
369
|
+
after: sanitized,
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
if (isWritable(request, sanitizeObject)) {
|
|
373
|
+
request[sanitizeObject] = sanitized;
|
|
374
|
+
} else if (typeof request[sanitizeObject] === 'object' && request[sanitizeObject] !== null) {
|
|
375
|
+
Object.keys(request[sanitizeObject]).forEach((k) => delete request[sanitizeObject][k]);
|
|
376
|
+
Object.assign(request[sanitizeObject], sanitized);
|
|
377
|
+
}
|
|
265
378
|
}
|
|
266
|
-
|
|
267
|
-
return acc;
|
|
268
|
-
}, {});
|
|
379
|
+
});
|
|
269
380
|
};
|
|
270
381
|
|
|
271
382
|
/**
|
|
272
|
-
*
|
|
273
|
-
* @param {
|
|
274
|
-
* @
|
|
275
|
-
* @returns {string[]} All route parameters in the Express app
|
|
383
|
+
* Cleans and normalizes a URL path for comparison.
|
|
384
|
+
* @param {string} url - URL to clean
|
|
385
|
+
* @returns {string|null} Cleaned URL path or null if invalid
|
|
276
386
|
*/
|
|
277
|
-
const
|
|
278
|
-
|
|
279
|
-
const
|
|
280
|
-
const
|
|
281
|
-
|
|
282
|
-
while (pathStack.length > 0) {
|
|
283
|
-
const { currentStack, basePath } = pathStack.pop();
|
|
284
|
-
|
|
285
|
-
for (let i = 0; i < currentStack.length; i++) {
|
|
286
|
-
const middleware = currentStack[i];
|
|
287
|
-
|
|
288
|
-
if (cache.has(middleware)) {
|
|
289
|
-
const cachedPath = cache.get(middleware);
|
|
290
|
-
if (cachedPath) uniqueParams.add(...cachedPath);
|
|
291
|
-
continue;
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
if (middleware.route) {
|
|
295
|
-
const routePath = basePath + middleware.route.path;
|
|
296
|
-
const paramRegex = /:([^/]+)/g;
|
|
297
|
-
const params = [];
|
|
298
|
-
let paramMatch;
|
|
299
|
-
|
|
300
|
-
while ((paramMatch = paramRegex.exec(routePath))) {
|
|
301
|
-
params.push(paramMatch[1]);
|
|
302
|
-
uniqueParams.add(paramMatch[1]);
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
cache.set(middleware, params);
|
|
306
|
-
} else if (middleware.name === 'router' && middleware.handle?.stack) {
|
|
307
|
-
let newBasePath = '';
|
|
308
|
-
|
|
309
|
-
if (middleware.regexp) {
|
|
310
|
-
const regexpStr = middleware.regexp.toString();
|
|
311
|
-
const match = regexpStr.match(/^\/\^\\\/\?((?:[^\\]|\\.)*)\\\/\?\$\/$/);
|
|
312
|
-
|
|
313
|
-
if (match?.[1]) {
|
|
314
|
-
newBasePath = match[1].replace(/\\\//g, '/');
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
pathStack.push({
|
|
318
|
-
currentStack: middleware.handle.stack,
|
|
319
|
-
basePath: basePath + newBasePath,
|
|
320
|
-
});
|
|
321
|
-
cache.set(middleware, null);
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
return [...uniqueParams];
|
|
387
|
+
const cleanUrl = (url) => {
|
|
388
|
+
if (typeof url !== 'string' || !url) return null;
|
|
389
|
+
const [path] = url.split(/[?#]/);
|
|
390
|
+
const trimmed = path.replace(/^\/+|\/+$/g, '');
|
|
391
|
+
return trimmed ? '/' + trimmed : '/';
|
|
326
392
|
};
|
|
327
393
|
|
|
328
394
|
/**
|
|
329
|
-
*
|
|
395
|
+
* Main middleware factory function for Express MongoDB sanitization.
|
|
330
396
|
* @param {Object} [options={}] - Configuration options
|
|
331
397
|
* @returns {Function} Express middleware function
|
|
332
398
|
* @throws {ExpressMongoSanitizeError} If options are invalid
|
|
@@ -334,11 +400,7 @@ const getAllRouteParams = (stack, basePath) => {
|
|
|
334
400
|
const expressMongoSanitize = (options = {}) => {
|
|
335
401
|
if (!isPlainObject(options)) throw new ExpressMongoSanitizeError('Options must be an object', 'type_error');
|
|
336
402
|
|
|
337
|
-
const userOpts = {
|
|
338
|
-
...DEFAULT_OPTIONS,
|
|
339
|
-
...options,
|
|
340
|
-
};
|
|
341
|
-
|
|
403
|
+
const userOpts = { ...DEFAULT_OPTIONS, ...options };
|
|
342
404
|
validateOptions(userOpts);
|
|
343
405
|
|
|
344
406
|
const opts = {
|
|
@@ -346,53 +408,51 @@ const expressMongoSanitize = (options = {}) => {
|
|
|
346
408
|
skipRoutes: new Set(options.skipRoutes || DEFAULT_OPTIONS.skipRoutes),
|
|
347
409
|
allowedKeys: new Set(options.allowedKeys || DEFAULT_OPTIONS.allowedKeys),
|
|
348
410
|
deniedKeys: new Set(options.deniedKeys || DEFAULT_OPTIONS.deniedKeys),
|
|
411
|
+
debug: { ...DEFAULT_OPTIONS.debug, ...(options.debug || {}) },
|
|
349
412
|
};
|
|
350
413
|
|
|
351
|
-
const { mode, app, router, routerBasePath } = opts;
|
|
352
|
-
|
|
353
|
-
if (!app)
|
|
354
|
-
createColorizedWarningMessage(
|
|
355
|
-
'ExpressMongoSanitizer: You must provide an Express app instance to sanitize route parameters. Skipping route parameter sanitization.'
|
|
356
|
-
);
|
|
357
|
-
|
|
358
|
-
if (!router)
|
|
359
|
-
createColorizedWarningMessage(
|
|
360
|
-
'ExpressMongoSanitizer: You must provide an Express router instance to sanitize route parameters. Skipping route parameter sanitization.'
|
|
361
|
-
);
|
|
362
|
-
|
|
363
414
|
return (req, res, next) => {
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
});
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
if (router) {
|
|
375
|
-
const allRouteParams = getAllRouteParams(app._router.stack, routerBasePath);
|
|
376
|
-
while (allRouteParams.length) {
|
|
377
|
-
const param = allRouteParams.pop();
|
|
378
|
-
router.param(param, (req, res, next, value, name) => {
|
|
379
|
-
req.params[name] = sanitizeString(value, opts);
|
|
380
|
-
next();
|
|
381
|
-
});
|
|
382
|
-
}
|
|
415
|
+
log(opts.debug, 'trace', 'MIDDLEWARE', `Incoming request`, { url: req.originalUrl || req.url, method: req.method });
|
|
416
|
+
const cleanedRequestPath = cleanUrl(req.path || req.url);
|
|
417
|
+
const shouldSkip = Array.from(opts.skipRoutes).some((skipPath) => cleanUrl(skipPath) === cleanedRequestPath);
|
|
418
|
+
if (shouldSkip) {
|
|
419
|
+
if (opts.debug?.logSkippedRoutes)
|
|
420
|
+
log(opts.debug, 'info', 'SKIP', `Skipped route: ${req.method} ${cleanedRequestPath}`);
|
|
421
|
+
return next();
|
|
383
422
|
}
|
|
384
|
-
|
|
385
|
-
|
|
423
|
+
if (opts.mode === 'auto') {
|
|
424
|
+
log(opts.debug, 'trace', 'MIDDLEWARE', `Auto mode: running sanitizer`);
|
|
386
425
|
handleRequest(req, opts);
|
|
387
426
|
}
|
|
388
|
-
|
|
389
|
-
|
|
427
|
+
if (opts.mode === 'manual') {
|
|
428
|
+
log(opts.debug, 'trace', 'MIDDLEWARE', `Manual mode: exposing req.sanitize`);
|
|
390
429
|
req.sanitize = (customOpts) => {
|
|
391
430
|
const finalOpts = { ...opts, ...customOpts };
|
|
392
431
|
handleRequest(req, finalOpts);
|
|
393
432
|
};
|
|
394
433
|
}
|
|
434
|
+
next();
|
|
435
|
+
};
|
|
436
|
+
};
|
|
395
437
|
|
|
438
|
+
/**
|
|
439
|
+
* Creates a parameter sanitization handler for Express route parameters.
|
|
440
|
+
* @param {Object} [options={}] - Configuration options
|
|
441
|
+
* @returns {Function} Express parameter handler function
|
|
442
|
+
*/
|
|
443
|
+
const paramSanitizeHandler = (options = {}) => {
|
|
444
|
+
const opts = {
|
|
445
|
+
...DEFAULT_OPTIONS,
|
|
446
|
+
...options,
|
|
447
|
+
debug: { ...DEFAULT_OPTIONS.debug, ...(options.debug || {}) },
|
|
448
|
+
};
|
|
449
|
+
return function (req, res, next, value, paramName) {
|
|
450
|
+
const key = paramName || this?.name;
|
|
451
|
+
if (key && req.params && isString(value)) {
|
|
452
|
+
const before = req.params[key];
|
|
453
|
+
req.params[key] = sanitizeString(value, opts, true);
|
|
454
|
+
log(opts.debug, 'debug', 'PARAM', `Sanitized param '${key}'`, { before, after: req.params[key] });
|
|
455
|
+
}
|
|
396
456
|
next();
|
|
397
457
|
};
|
|
398
458
|
};
|
|
@@ -400,3 +460,5 @@ const expressMongoSanitize = (options = {}) => {
|
|
|
400
460
|
module.exports = expressMongoSanitize;
|
|
401
461
|
module.exports.default = expressMongoSanitize;
|
|
402
462
|
module.exports.expressMongoSanitize = expressMongoSanitize;
|
|
463
|
+
module.exports.paramSanitizeHandler = paramSanitizeHandler;
|
|
464
|
+
exports.default = expressMongoSanitize;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@exortek/express-mongo-sanitize",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "A comprehensive Express middleware designed to protect your No(n)SQL queries from injection attacks by sanitizing request data. This middleware provides flexible sanitization options for request bodies, parameters, and query strings.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"type": "commonjs",
|
|
@@ -41,12 +41,13 @@
|
|
|
41
41
|
"publishConfig": {
|
|
42
42
|
"access": "public"
|
|
43
43
|
},
|
|
44
|
-
"packageManager": "yarn@4.
|
|
44
|
+
"packageManager": "yarn@4.9.2",
|
|
45
45
|
"devDependencies": {
|
|
46
|
-
"@types/express": "^5.0.
|
|
47
|
-
"express": "
|
|
48
|
-
"
|
|
49
|
-
"
|
|
46
|
+
"@types/express": "^5.0.3",
|
|
47
|
+
"express": "npm:express@5.1.0",
|
|
48
|
+
"express4": "npm:express@4.21.2",
|
|
49
|
+
"prettier": "^3.5.3",
|
|
50
|
+
"tsd": "^0.32.0"
|
|
50
51
|
},
|
|
51
52
|
"files": [
|
|
52
53
|
"index.js",
|
package/types/index.d.ts
CHANGED
|
@@ -1,62 +1,80 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { RequestHandler, RequestParamHandler } from 'express';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
export interface
|
|
3
|
+
/**
|
|
4
|
+
* String-specific sanitizer options.
|
|
5
|
+
*/
|
|
6
|
+
export interface StringOptions {
|
|
7
|
+
/** Trim whitespace from strings */
|
|
7
8
|
trim?: boolean;
|
|
9
|
+
/** Convert strings to lowercase */
|
|
8
10
|
lowercase?: boolean;
|
|
11
|
+
/** Truncate strings to a maximum length (null = unlimited) */
|
|
9
12
|
maxLength?: number | null;
|
|
10
13
|
}
|
|
11
14
|
|
|
12
|
-
|
|
15
|
+
/**
|
|
16
|
+
* Array-specific sanitizer options.
|
|
17
|
+
*/
|
|
18
|
+
export interface ArrayOptions {
|
|
19
|
+
/** Remove null values from arrays */
|
|
13
20
|
filterNull?: boolean;
|
|
21
|
+
/** Remove duplicate values from arrays */
|
|
14
22
|
distinct?: boolean;
|
|
15
23
|
}
|
|
16
24
|
|
|
25
|
+
export interface DebugOptions {
|
|
26
|
+
/** Enable debug logging */
|
|
27
|
+
enabled?: boolean;
|
|
28
|
+
/** Log level (e.g., 'silent' | 'error' | 'warn' | 'info' | 'debug' | 'trace') */
|
|
29
|
+
level?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Main options for expressMongoSanitize middleware.
|
|
34
|
+
*/
|
|
17
35
|
export interface ExpressMongoSanitizeOptions {
|
|
18
|
-
/** Express application instance */
|
|
19
|
-
app?: Application | null;
|
|
20
|
-
/** Express router instance */
|
|
21
|
-
router?: Router | null;
|
|
22
|
-
/** Base path for the router */
|
|
23
|
-
routerBasePath?: string | 'api';
|
|
24
36
|
/** String to replace matched patterns with */
|
|
25
37
|
replaceWith?: string;
|
|
26
|
-
/**
|
|
38
|
+
/** Remove values matching patterns */
|
|
27
39
|
removeMatches?: boolean;
|
|
28
|
-
/** Request objects to sanitize */
|
|
29
|
-
sanitizeObjects?:
|
|
30
|
-
/**
|
|
31
|
-
mode?:
|
|
32
|
-
/**
|
|
40
|
+
/** Request objects to sanitize (default: ['body', 'query']) */
|
|
41
|
+
sanitizeObjects?: Array<'body' | 'query'>;
|
|
42
|
+
/** Automatic or manual mode */
|
|
43
|
+
mode?: 'auto' | 'manual';
|
|
44
|
+
/** Paths to skip sanitizing */
|
|
33
45
|
skipRoutes?: string[];
|
|
34
|
-
/**
|
|
35
|
-
customSanitizer?: (
|
|
36
|
-
/**
|
|
46
|
+
/** Completely custom sanitizer function */
|
|
47
|
+
customSanitizer?: (data: any, options: ExpressMongoSanitizeOptions) => any;
|
|
48
|
+
/** Recursively sanitize nested objects */
|
|
37
49
|
recursive?: boolean;
|
|
38
|
-
/**
|
|
50
|
+
/** Remove empty values after sanitizing */
|
|
39
51
|
removeEmpty?: boolean;
|
|
40
52
|
/** Patterns to match for sanitization */
|
|
41
53
|
patterns?: RegExp[];
|
|
42
|
-
/**
|
|
43
|
-
allowedKeys?: string[]
|
|
44
|
-
/**
|
|
45
|
-
deniedKeys?: string[]
|
|
46
|
-
/** String
|
|
47
|
-
stringOptions?:
|
|
48
|
-
/** Array
|
|
49
|
-
arrayOptions?:
|
|
54
|
+
/** Only allow these keys in sanitized objects */
|
|
55
|
+
allowedKeys?: string[];
|
|
56
|
+
/** Remove these keys from sanitized objects */
|
|
57
|
+
deniedKeys?: string[];
|
|
58
|
+
/** String sanitizer options */
|
|
59
|
+
stringOptions?: StringOptions;
|
|
60
|
+
/** Array sanitizer options */
|
|
61
|
+
arrayOptions?: ArrayOptions;
|
|
62
|
+
/** Debugging options */
|
|
63
|
+
debug?: DebugOptions;
|
|
50
64
|
}
|
|
51
65
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
66
|
+
/**
|
|
67
|
+
* Middleware for automatic sanitization of request objects.
|
|
68
|
+
*/
|
|
69
|
+
declare function expressMongoSanitize(options?: ExpressMongoSanitizeOptions): RequestHandler;
|
|
57
70
|
|
|
58
|
-
|
|
71
|
+
/**
|
|
72
|
+
* Middleware for sanitizing individual route parameters.
|
|
73
|
+
*/
|
|
74
|
+
declare function paramSanitizeHandler(options?: ExpressMongoSanitizeOptions): RequestParamHandler;
|
|
59
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Main export for express-mongo-sanitize middleware.
|
|
78
|
+
*/
|
|
60
79
|
export default expressMongoSanitize;
|
|
61
|
-
|
|
62
|
-
export { ExpressMongoSanitizeError, expressMongoSanitize };
|
|
80
|
+
export { expressMongoSanitize, paramSanitizeHandler };
|