@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.
Files changed (5) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +269 -185
  3. package/index.js +255 -193
  4. package/package.json +7 -6
  5. 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 for sanitizing incoming requests to an Express application, particularly when working with
4
- MongoDB (NoSQL). It ensures that certain patterns, such as special characters or malicious input, are removed or
5
- replaced from the request body, query, and parameters, preventing potential injection attacks in NoSQL.
6
-
7
- ### Key Features
8
-
9
- - Automatic sanitization of potentially dangerous MongoDB operators and special characters.
10
- - Multiple operation modes (auto, manual)
11
- - Customizable sanitization patterns and replacement strategies
12
- - Support for nested objects and arrays
13
- - Configurable string and array handling options
14
- - Skip routes functionality
15
- - Custom sanitizer support
16
- - Email address preservation during sanitization
17
- - Option to remove matched patterns entirely
18
- - Enhanced security with request object cloning
19
-
20
- ## Installation
21
-
22
- ```bash
23
- npm install @exortek/express-mongo-sanitize
24
- ```
25
-
26
- OR
27
-
28
- ```bash
29
- yarn add @exortek/express-mongo-sanitize
30
- ```
31
-
32
- ## Usage
33
-
34
- Register the middleware in your Express application before defining your routes.
35
-
36
- ### App route example
37
-
38
- ```javascript
39
-
40
- const express = require('express');
41
- const expressMongoSanitize = require('@exortek/express-mongo-sanitize');
42
-
43
- const app = express();
44
-
45
- app.use(exppress.json());
46
-
47
- // Register the middleware
48
- app.use(expressMongoSanitize());
49
-
50
- // Define your routes
51
- app.get('/users', (req, res) => {
52
- // Your route logic here
53
- });
54
-
55
- app.post('/users', (req, res) => {
56
- // Your route logic here
57
- });
58
-
59
- app.listen(3000, () => {
60
- console.log('Server is running on port 3000');
61
- });
62
-
63
- ```
64
-
65
- ### Route-specific example
66
-
67
- ```javascript
68
-
69
- const express = require('express');
70
- const expressMongoSanitize = require('@exortek/express-mongo-sanitize');
71
- const router = require('./router');
72
-
73
- const app = express();
74
-
75
- app.use(express.json());
76
-
77
- // Register the middleware
78
- app.use(expressMongoSanitize());
79
-
80
- // Define your routes
81
- app.use('/api', router);
82
-
83
- app.listen(3000, () => {
84
- console.log('Server is running on port 3000');
85
- });
86
-
87
- ```
88
-
89
- # Configuration Options
90
-
91
- The middleware accepts various configuration options to customize its behavior. Here's a detailed breakdown of all
92
- available
93
- options:
94
-
95
- ## Core Options
96
-
97
- | Option | Type | Default | Description |
98
- |-------------------|----------------|----------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
99
- | `app` | Application | `null` | The Express app instance. Default is null. You can specify the app instance if you want to sanitize the params(Path variables) of the app. |
100
- | `router` | Router | `null` | The Express router instance. Default is null. You can specify the router instance if you want to sanitize the params(Path variables) of the router. |
101
- | `routerBasePath` | string | `api` | // The base path of the router. Default is an 'api'. You can specify the base path of the router. |
102
- | `replaceWith` | string | `''` | The string to replace the matched patterns with. Default is an empty string. If you want to replace the matched patterns with a different string, you can set this option. |
103
- | `removeMatches` | boolean | `false` | Remove the matched patterns. Default is false. If you want to remove the matched patterns instead of replacing them, you can set this option to true. |
104
- | `sanitizeObjects` | array | `['body', 'params', 'query']` | The request properties to sanitize. Default is `['body', 'params', 'query']`. You can specify any request property that you want to sanitize. It must be an object. |
105
- | `mode` | string | `'auto'` | The mode of operation. Default is 'auto'. You can set this option to 'auto', 'manual'. If you set it to 'auto', the plugin will automatically sanitize the request objects. If you set it to 'manual', you can sanitize the request objects manually using the request.sanitize() method. |
106
- | `skipRoutes` | array | `[]` | An array of routes to skip. Default is an empty array. If you want to skip certain routes from sanitization, you can specify the routes here. The routes must be in the format `/path`. For example, `['/health', '/metrics']`. |
107
- | `customSanitizer` | function\|null | `null` | A custom sanitizer function. Default is null. If you want to use a custom sanitizer function, you can specify it here. The function must accept two arguments: the original data and the options object. It must return the sanitized data. |
108
- | `recursive` | boolean | `true` | Enable recursive sanitization. Default is true. If you want to recursively sanitize the nested objects, you can set this option to true. |
109
- | `removeEmpty` | boolean | `false` | Remove empty values. Default is false. If you want to remove empty values after sanitization, you can set this option to true. |
110
- | `patterns` | array | `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. |
111
- | `allowedKeys` | array\|null | `null` | An array of allowed keys. Default is null. 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. |
112
- | `deniedKeys` | array\|null | `null` | An array of denied keys. Default is null. 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. |
113
- | `stringOptions` | object | `{ trim: false,lowercase: false,maxLength: null }` | An object that controls string sanitization behavior. Default is an empty object. You can specify the following options: `trim`, `lowercase`, `maxLength`. |
114
- | `arrayOptions` | object | `{ filterNull: false, distinct: false}` | An object that controls array sanitization behavior. Default is an empty object. You can specify the following options: `filterNull`, `distinct`. |
115
-
116
- ## String Options
117
-
118
- The `stringOptions` object controls string sanitization behavior:
119
-
120
- ```javascript
121
- {
122
- trim: false, // Whether to trim whitespace from start/end
123
- lowercase: false, // Whether to convert strings to lowercase
124
- maxLength: null // Maximum allowed string length (null for no limit)
125
- }
126
- ```
127
-
128
- ## Array Options
129
-
130
- The `arrayOptions` object controls array sanitization behavior:
131
-
132
- ```javascript
133
- {
134
- filterNull: false, // Whether to remove null/undefined values
135
- distinct: false // Whether to remove duplicate values
136
- }
137
- ```
138
-
139
- ## Example Configuration
140
-
141
- Here's an example of how you can configure the middleware with custom options:
142
-
143
- ```javascript
144
- app.use(expressMongoSanitize({
145
- app: app,
146
- router: router,
147
- routerBasePath: 'api',
148
- replaceWith: 'REPLACED',
149
- removeMatches: false,
150
- sanitizeObjects: ['body', 'params', 'query'],
151
- mode: 'auto',
152
- skipRoutes: ['/health', '/metrics'],
153
- customSanitizer: (data, options) => {
154
- // Custom sanitizer logic here
155
- return data;
156
- },
157
- recursive: true,
158
- removeEmpty: false,
159
- patterns: [/pattern1/, /pattern2/],
160
- allowedKeys: ['key1', 'key2'],
161
- deniedKeys: ['key3', 'key4'],
162
- stringOptions: {
163
- trim: true,
164
- lowercase: true,
165
- maxLength: 100
166
- },
167
- arrayOptions: {
168
- filterNull: true,
169
- distinct: true
170
- }
171
- }));
172
- ```
173
-
174
- ## Notes
175
-
176
- - The middleware is designed to work with Express applications and is not compatible with other frameworks.
177
- - If the app or router instances are not provided to the `@exortek/express-mongo-sanitize` middleware, the route parameters (path variables) cannot be sanitized. The middleware will skip sanitizing the route parameters and display a warning message indicating that sanitization was not performed for the path variables. Ensure that both the app and router instances are properly passed to the middleware to enable route parameter sanitization.
178
- - All options are optional and will use their default values if not specified.
179
- - Custom patterns must be valid RegExp objects
180
-
181
- ## License
182
-
183
- **[MIT](https://github.com/ExorTek/express-mongo-sanitize/blob/master/LICENSE)**<br>
184
-
185
- Copyright © 2024 ExorTek
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
- * Collection of regular expression patterns used for sanitization
5
- * @constant {RegExp[]}
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
- /[\$]/g, // Finds all '$' (dollar) characters in the text.
9
- /\./g, // Finds all '.' (dot) characters in the text.
10
- /[\\\/{}.(*+?|[\]^)]/g, // Finds special characters (\, /, {, }, (, ., *, +, ?, |, [, ], ^, )) that need to be escaped.
11
- /[\u0000-\u001F\u007F-\u009F]/g, // Finds ASCII control characters (0x00-0x1F and 0x7F-0x9F range).
12
- /\{\s*\$|\$?\{(.|\r?\n)*\}/g, // Finds placeholders or variables in the format `${...}` or `{ $... }`.
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 plugin
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
- app: null, // The Express app instance. Default is null. You can specify the app instance if you want to sanitize the params(Path variables) of the app.
21
- router: null, // The Express router instance. Default is null. You can specify the router instance if you want to sanitize the params(Path variables) of the router.
22
- routerBasePath: 'api', // The base path of the router. Default is an 'api'. You can specify the base path of the router.
23
- replaceWith: '', // The string to replace the matched patterns with. Default is an empty string. If you want to replace the matched patterns with a different string, you can set this option.
24
- removeMatches: false, // Remove the matched patterns. Default is false. If you want to remove the matched patterns instead of replacing them, you can set this option to true.
25
- sanitizeObjects: ['body', 'params', 'query'], // The request properties to sanitize. Default is ['body', 'params', 'query']. You can specify any request property that you want to sanitize. It must be an object.
26
- mode: 'auto', // The mode of operation. Default is 'auto'. You can set this option to 'auto', 'manual'. If you set it to 'auto', the plugin will automatically sanitize the request objects. If you set it to 'manual', you can sanitize the request objects manually using the request.sanitize() method.
27
- skipRoutes: [], // An array of routes to skip. Default is an empty array. If you want to skip certain routes from sanitization, you can specify the routes here. The routes must be in the format '/path'. For example, ['/health', '/metrics'].
28
- customSanitizer: null, // A custom sanitizer function. Default is null. If you want to use a custom sanitizer function, you can specify it here. The function must accept two arguments: the original data and the options object. It must return the sanitized data.
29
- recursive: true, // Enable recursive sanitization. Default is true. If you want to recursively sanitize the nested objects, you can set this option to true.
30
- removeEmpty: false, // Remove empty values. Default is false. If you want to remove empty values after sanitization, you can set this option to true.
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
- // String sanitization options.
36
- trim: false, // Trim whitespace. Default is false. If you want to trim leading and trailing whitespace from the string, you can set this option to true.
37
- lowercase: false, // Convert to lowercase. Default is false. If you want to convert the string to lowercase, you can set this option to true.
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
- // Array sanitization options.
42
- filterNull: false, // Filter null values. Default is false. If you want to remove null values from the array, you can set this option to true.
43
- distinct: false, // Remove duplicate values. Default is false. If you want to remove duplicate values from the array, you can set this option to true.
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
- * Checks if value is a string
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
- * Checks if value is a valid email address
56
- * @param {string} val - Value to check
57
- * @returns {boolean} True if value is a valid email address
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, number, or boolean)
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
- * Error class for ExpressMongoSanitize
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
- * Create a colorized warning message
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 string is a value or key
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
- if (!isString(str) || isEmail(str)) return str;
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 according to provided options
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
- if (!isArray(arr)) throw new ExpressMongoSanitizeError('Input must be an array', 'type_error');
162
-
163
- const { arrayOptions } = options;
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
- if (arrayOptions.filterNull) result = result.filter(Boolean);
167
- if (arrayOptions.distinct) result = [...new Set(result)];
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 provided options
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
- if (!isPlainObject(obj)) throw new ExpressMongoSanitizeError('Input must be an object', 'type_error');
180
-
181
- const { removeEmpty, allowedKeys, deniedKeys, removeMatches, patterns } = options;
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)) return acc;
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))) return acc;
187
- if (removeEmpty && !sanitizedKey) return acc;
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
- * Sanitizes a value according to its type and provided options
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 value is a value or key
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 plugin options
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
- * Handles request sanitization
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
- return sanitizeObjects.reduce((acc, sanitizeObject) => {
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
- const originalRequest = Object.assign({}, requestObject);
261
-
262
- request[sanitizeObject] = customSanitizer
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
- * Get all route parameters from the Express app
273
- * @param {Object[]} stack - Express app stack
274
- * @param {string} basePath - Base path of the router
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 getAllRouteParams = (stack, basePath) => {
278
- const uniqueParams = new Set();
279
- const pathStack = [{ currentStack: stack, basePath }];
280
- const cache = new Map();
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
- * Express middleware for sanitizing request objects
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
- if (opts.skipRoutes.has(req.url)) return next();
365
-
366
- if (app) {
367
- const allRouteParams = getAllRouteParams(app._router.stack, routerBasePath);
368
- app.param(allRouteParams, (req, res, next, value, name) => {
369
- req.params[name] = sanitizeString(value, opts);
370
- next();
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
- if (mode === 'auto') {
423
+ if (opts.mode === 'auto') {
424
+ log(opts.debug, 'trace', 'MIDDLEWARE', `Auto mode: running sanitizer`);
386
425
  handleRequest(req, opts);
387
426
  }
388
-
389
- if (mode === 'manual') {
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.0.0",
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.5.1",
44
+ "packageManager": "yarn@4.9.2",
45
45
  "devDependencies": {
46
- "@types/express": "^5.0.0",
47
- "express": "^4.21.1",
48
- "prettier": "^3.3.3",
49
- "tsd": "^0.31.2"
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 type { Application, Router, Handler } from 'express';
1
+ import { RequestHandler, RequestParamHandler } from 'express';
2
2
 
3
- export type SanitizeMode = 'auto' | 'manual';
4
- export type SanitizeObject = 'body' | 'params' | 'query';
5
-
6
- export interface StringSanitizeOptions {
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
- export interface ArraySanitizeOptions {
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
- /** Whether to remove matches instead of replacing them */
38
+ /** Remove values matching patterns */
27
39
  removeMatches?: boolean;
28
- /** Request objects to sanitize */
29
- sanitizeObjects?: SanitizeObject[];
30
- /** Sanitization mode */
31
- mode?: SanitizeMode;
32
- /** Routes to skip sanitization */
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
- /** Custom sanitizer function */
35
- customSanitizer?: ((data: unknown, options: ExpressMongoSanitizeOptions) => unknown) | null;
36
- /** Whether to recursively sanitize nested objects */
46
+ /** Completely custom sanitizer function */
47
+ customSanitizer?: (data: any, options: ExpressMongoSanitizeOptions) => any;
48
+ /** Recursively sanitize nested objects */
37
49
  recursive?: boolean;
38
- /** Whether to remove empty values after sanitization */
50
+ /** Remove empty values after sanitizing */
39
51
  removeEmpty?: boolean;
40
52
  /** Patterns to match for sanitization */
41
53
  patterns?: RegExp[];
42
- /** Allowed keys in objects */
43
- allowedKeys?: string[] | null;
44
- /** Denied keys in objects */
45
- deniedKeys?: string[] | null;
46
- /** String sanitization options */
47
- stringOptions?: StringSanitizeOptions;
48
- /** Array sanitization options */
49
- arrayOptions?: ArraySanitizeOptions;
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
- declare class ExpressMongoSanitizeError extends Error {
53
- constructor(message: string, type?: string);
54
- message: string;
55
- type: string;
56
- }
66
+ /**
67
+ * Middleware for automatic sanitization of request objects.
68
+ */
69
+ declare function expressMongoSanitize(options?: ExpressMongoSanitizeOptions): RequestHandler;
57
70
 
58
- declare const expressMongoSanitize: (options?: ExpressMongoSanitizeOptions) => Handler;
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 };