@exortek/express-mongo-sanitize 1.0.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 -0
- package/README.md +185 -0
- package/index.js +402 -0
- package/package.json +55 -0
- package/types/index.d.ts +62 -0
package/LICENSE
ADDED
|
@@ -0,0 +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.
|
package/README.md
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
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
|
package/index.js
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Collection of regular expression patterns used for sanitization
|
|
5
|
+
* @constant {RegExp[]}
|
|
6
|
+
*/
|
|
7
|
+
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 `{ $... }`.
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Default configuration options for the plugin
|
|
17
|
+
* @constant {Object}
|
|
18
|
+
*/
|
|
19
|
+
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.
|
|
34
|
+
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.
|
|
39
|
+
},
|
|
40
|
+
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.
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Checks if value is a string
|
|
49
|
+
* @param {*} value - Value to check
|
|
50
|
+
* @returns {boolean} True if value is string
|
|
51
|
+
*/
|
|
52
|
+
const isString = (value) => typeof value === 'string';
|
|
53
|
+
|
|
54
|
+
/**
|
|
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
|
|
58
|
+
*/
|
|
59
|
+
const isEmail = (val) =>
|
|
60
|
+
isString(val) &&
|
|
61
|
+
// RFC 5322 compliant email regex
|
|
62
|
+
/^(?:[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
|
+
val
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Checks if value is a plain object
|
|
68
|
+
* @param {*} obj - Value to check
|
|
69
|
+
* @returns {boolean} True if value is plain object
|
|
70
|
+
*/
|
|
71
|
+
const isPlainObject = (obj) => !!obj && Object.prototype.toString.call(obj) === '[object Object]';
|
|
72
|
+
|
|
73
|
+
const isObjectEmpty = (obj) => {
|
|
74
|
+
if (!isPlainObject(obj)) return false;
|
|
75
|
+
return !Object.hasOwn(obj, Object.keys(obj)[0]);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Checks if value is an array
|
|
80
|
+
* @param {*} value - Value to check
|
|
81
|
+
* @returns {boolean} True if value is array
|
|
82
|
+
*/
|
|
83
|
+
const isArray = (value) => Array.isArray(value);
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Checks if value is a primitive (null, number, or boolean)
|
|
87
|
+
* @param {*} value - Value to check
|
|
88
|
+
* @returns {boolean} True if value is primitive
|
|
89
|
+
*/
|
|
90
|
+
const isPrimitive = (value) => value == null || typeof value === 'boolean' || typeof value === 'number';
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Checks if value is a Date object
|
|
94
|
+
* @param {*} value - Value to check
|
|
95
|
+
* @returns {boolean} True if value is Date
|
|
96
|
+
*/
|
|
97
|
+
const isDate = (value) => value instanceof Date;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Checks if value is a function
|
|
101
|
+
* @param {*} value - Value to check
|
|
102
|
+
* @returns {boolean} True if value is function
|
|
103
|
+
*/
|
|
104
|
+
const isFunction = (value) => typeof value === 'function';
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Error class for ExpressMongoSanitize
|
|
108
|
+
*/
|
|
109
|
+
class ExpressMongoSanitizeError extends Error {
|
|
110
|
+
/**
|
|
111
|
+
* Creates a new ExpressMongoSanitizeError
|
|
112
|
+
* @param {string} message - Error message
|
|
113
|
+
* @param {string} [type='generic'] - Error type
|
|
114
|
+
*/
|
|
115
|
+
constructor(message, type = 'generic') {
|
|
116
|
+
super(message);
|
|
117
|
+
this.name = 'ExpressMongoSanitizeError';
|
|
118
|
+
this.type = type;
|
|
119
|
+
Error.captureStackTrace(this, this.constructor);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
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
|
|
132
|
+
* @param {string} str - String to sanitize
|
|
133
|
+
* @param {Object} options - Sanitization options
|
|
134
|
+
* @param {boolean} isValue - Whether string is a value or key
|
|
135
|
+
* @returns {string} Sanitized string
|
|
136
|
+
*/
|
|
137
|
+
const sanitizeString = (str, options, isValue = false) => {
|
|
138
|
+
if (!isString(str) || isEmail(str)) return str;
|
|
139
|
+
|
|
140
|
+
const { replaceWith, patterns, stringOptions } = options;
|
|
141
|
+
|
|
142
|
+
const combinedPattern = new RegExp(patterns.map((pattern) => pattern.source).join('|'), 'g');
|
|
143
|
+
|
|
144
|
+
let result = str.replace(combinedPattern, replaceWith);
|
|
145
|
+
|
|
146
|
+
if (stringOptions.trim) result = result.trim();
|
|
147
|
+
if (stringOptions.lowercase) result = result.toLowerCase();
|
|
148
|
+
if (stringOptions.maxLength && isValue) result = result.slice(0, stringOptions.maxLength);
|
|
149
|
+
|
|
150
|
+
return result;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Sanitizes an array according to provided options
|
|
155
|
+
* @param {Array} arr - Array to sanitize
|
|
156
|
+
* @param {Object} options - Sanitization options
|
|
157
|
+
* @returns {Array} Sanitized array
|
|
158
|
+
* @throws {ExpressMongoSanitizeError} If input is not an array
|
|
159
|
+
*/
|
|
160
|
+
const sanitizeArray = (arr, options) => {
|
|
161
|
+
if (!isArray(arr)) throw new ExpressMongoSanitizeError('Input must be an array', 'type_error');
|
|
162
|
+
|
|
163
|
+
const { arrayOptions } = options;
|
|
164
|
+
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)];
|
|
168
|
+
return result;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Sanitizes an object according to provided options
|
|
173
|
+
* @param {Object} obj - Object to sanitize
|
|
174
|
+
* @param {Object} options - Sanitization options
|
|
175
|
+
* @returns {Object} Sanitized object
|
|
176
|
+
* @throws {ExpressMongoSanitizeError} If input is not an object
|
|
177
|
+
*/
|
|
178
|
+
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;
|
|
182
|
+
return Object.entries(obj).reduce((acc, [key, val]) => {
|
|
183
|
+
if ((allowedKeys.size && !allowedKeys.has(key)) || deniedKeys.has(key)) return acc;
|
|
184
|
+
|
|
185
|
+
const sanitizedKey = sanitizeString(key, options);
|
|
186
|
+
if (removeMatches && patterns.some((pattern) => pattern.test(key))) return acc;
|
|
187
|
+
if (removeEmpty && !sanitizedKey) return acc;
|
|
188
|
+
|
|
189
|
+
if (isEmail(val) && deniedKeys.has(key)) {
|
|
190
|
+
acc[sanitizedKey] = val;
|
|
191
|
+
return acc;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (removeMatches && isString(val) && patterns.some((pattern) => pattern.test(val))) return acc;
|
|
195
|
+
|
|
196
|
+
const sanitizedValue = sanitizeValue(val, options, true);
|
|
197
|
+
if (!removeEmpty || sanitizedValue) acc[sanitizedKey] = sanitizedValue;
|
|
198
|
+
|
|
199
|
+
return acc;
|
|
200
|
+
}, {});
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Sanitizes a value according to its type and provided options
|
|
205
|
+
* @param {*} value - Value to sanitize
|
|
206
|
+
* @param {Object} options - Sanitization options
|
|
207
|
+
* @param {boolean} [isValue=false] - Whether value is a value or key
|
|
208
|
+
* @returns {*} Sanitized value
|
|
209
|
+
*/
|
|
210
|
+
const sanitizeValue = (value, options, isValue = false) => {
|
|
211
|
+
if (!value || isPrimitive(value) || isDate(value)) return value;
|
|
212
|
+
if (Array.isArray(value)) return sanitizeArray(value, options);
|
|
213
|
+
if (isPlainObject(value)) return sanitizeObject(value, options);
|
|
214
|
+
return isString(value) ? sanitizeString(value, options, isValue) : value;
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Validates plugin options
|
|
219
|
+
* @param {Object} options - Options to validate
|
|
220
|
+
* @throws {ExpressMongoSanitizeError} If any option is invalid
|
|
221
|
+
*/
|
|
222
|
+
const validateOptions = (options) => {
|
|
223
|
+
const validators = {
|
|
224
|
+
app: (value) => !value || isFunction(value),
|
|
225
|
+
router: (value) => !value || isFunction(value),
|
|
226
|
+
routerBasePath: isString,
|
|
227
|
+
replaceWith: isString,
|
|
228
|
+
removeMatches: isPrimitive,
|
|
229
|
+
sanitizeObjects: isArray,
|
|
230
|
+
mode: (value) => ['auto', 'manual'].includes(value),
|
|
231
|
+
skipRoutes: isArray,
|
|
232
|
+
customSanitizer: (value) => value === null || isFunction(value),
|
|
233
|
+
recursive: isPrimitive,
|
|
234
|
+
removeEmpty: isPrimitive,
|
|
235
|
+
patterns: isArray,
|
|
236
|
+
allowedKeys: (value) => value === null || isArray(value),
|
|
237
|
+
deniedKeys: (value) => value === null || isArray(value),
|
|
238
|
+
stringOptions: isPlainObject,
|
|
239
|
+
arrayOptions: isPlainObject,
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
for (const [key, validate] of Object.entries(validators)) {
|
|
243
|
+
if (!validate(options[key])) {
|
|
244
|
+
throw new ExpressMongoSanitizeError(`Invalid configuration: "${key}" with value "${options[key]}"`, 'type_error');
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Handles request sanitization
|
|
251
|
+
* @param {Object} request - Express request object
|
|
252
|
+
* @param {Object} options - Sanitization options
|
|
253
|
+
*/
|
|
254
|
+
const handleRequest = (request, options) => {
|
|
255
|
+
const { sanitizeObjects, customSanitizer } = options;
|
|
256
|
+
|
|
257
|
+
return sanitizeObjects.reduce((acc, sanitizeObject) => {
|
|
258
|
+
const requestObject = request[sanitizeObject];
|
|
259
|
+
if (requestObject && !isObjectEmpty(requestObject)) {
|
|
260
|
+
const originalRequest = Object.assign({}, requestObject);
|
|
261
|
+
|
|
262
|
+
request[sanitizeObject] = customSanitizer
|
|
263
|
+
? customSanitizer(originalRequest, options)
|
|
264
|
+
: sanitizeValue(originalRequest, options);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return acc;
|
|
268
|
+
}, {});
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
/**
|
|
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
|
|
276
|
+
*/
|
|
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];
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Express middleware for sanitizing request objects
|
|
330
|
+
* @param {Object} [options={}] - Configuration options
|
|
331
|
+
* @returns {Function} Express middleware function
|
|
332
|
+
* @throws {ExpressMongoSanitizeError} If options are invalid
|
|
333
|
+
*/
|
|
334
|
+
const expressMongoSanitize = (options = {}) => {
|
|
335
|
+
if (!isPlainObject(options)) throw new ExpressMongoSanitizeError('Options must be an object', 'type_error');
|
|
336
|
+
|
|
337
|
+
const userOpts = {
|
|
338
|
+
...DEFAULT_OPTIONS,
|
|
339
|
+
...options,
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
validateOptions(userOpts);
|
|
343
|
+
|
|
344
|
+
const opts = {
|
|
345
|
+
...userOpts,
|
|
346
|
+
skipRoutes: new Set(options.skipRoutes || DEFAULT_OPTIONS.skipRoutes),
|
|
347
|
+
allowedKeys: new Set(options.allowedKeys || DEFAULT_OPTIONS.allowedKeys),
|
|
348
|
+
deniedKeys: new Set(options.deniedKeys || DEFAULT_OPTIONS.deniedKeys),
|
|
349
|
+
};
|
|
350
|
+
|
|
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
|
+
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
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
if (mode === 'auto') {
|
|
386
|
+
handleRequest(req, opts);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
if (mode === 'manual') {
|
|
390
|
+
req.sanitize = (customOpts) => {
|
|
391
|
+
const finalOpts = { ...opts, ...customOpts };
|
|
392
|
+
handleRequest(req, finalOpts);
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
next();
|
|
397
|
+
};
|
|
398
|
+
};
|
|
399
|
+
|
|
400
|
+
module.exports = expressMongoSanitize;
|
|
401
|
+
module.exports.default = expressMongoSanitize;
|
|
402
|
+
module.exports.expressMongoSanitize = expressMongoSanitize;
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@exortek/express-mongo-sanitize",
|
|
3
|
+
"version": "1.0.0",
|
|
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
|
+
"main": "index.js",
|
|
6
|
+
"type": "commonjs",
|
|
7
|
+
"types": "types/index.d.ts",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"format": "prettier --write \"**/*.{js,ts,json}\"",
|
|
10
|
+
"test:tsd": "tsd",
|
|
11
|
+
"test:node": "node --test"
|
|
12
|
+
},
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/ExorTek/express-mongo-sanitize.git"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"express",
|
|
19
|
+
"mongodb",
|
|
20
|
+
"sanitize",
|
|
21
|
+
"mongoose",
|
|
22
|
+
"express-middleware",
|
|
23
|
+
"data-validation",
|
|
24
|
+
"input-sanitization",
|
|
25
|
+
"security",
|
|
26
|
+
"web-application",
|
|
27
|
+
"nodejs",
|
|
28
|
+
"typescript",
|
|
29
|
+
"middleware",
|
|
30
|
+
"api-security",
|
|
31
|
+
"query-sanitization",
|
|
32
|
+
"no-sql",
|
|
33
|
+
"mongodb-sanitizer"
|
|
34
|
+
],
|
|
35
|
+
"author": "ExorTek - https://github.com/ExorTek",
|
|
36
|
+
"license": "MIT",
|
|
37
|
+
"bugs": {
|
|
38
|
+
"url": "https://github.com/ExorTek/express-mongo-sanitize/issues"
|
|
39
|
+
},
|
|
40
|
+
"homepage": "https://github.com/ExorTek/express-mongo-sanitize#readme",
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
},
|
|
44
|
+
"packageManager": "yarn@4.5.1",
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@types/express": "^5.0.0",
|
|
47
|
+
"express": "^4.21.1",
|
|
48
|
+
"prettier": "^3.3.3",
|
|
49
|
+
"tsd": "^0.31.2"
|
|
50
|
+
},
|
|
51
|
+
"files": [
|
|
52
|
+
"index.js",
|
|
53
|
+
"types/index.d.ts"
|
|
54
|
+
]
|
|
55
|
+
}
|
package/types/index.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Application, Router, Handler } from 'express';
|
|
2
|
+
|
|
3
|
+
export type SanitizeMode = 'auto' | 'manual';
|
|
4
|
+
export type SanitizeObject = 'body' | 'params' | 'query';
|
|
5
|
+
|
|
6
|
+
export interface StringSanitizeOptions {
|
|
7
|
+
trim?: boolean;
|
|
8
|
+
lowercase?: boolean;
|
|
9
|
+
maxLength?: number | null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface ArraySanitizeOptions {
|
|
13
|
+
filterNull?: boolean;
|
|
14
|
+
distinct?: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
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
|
+
/** String to replace matched patterns with */
|
|
25
|
+
replaceWith?: string;
|
|
26
|
+
/** Whether to remove matches instead of replacing them */
|
|
27
|
+
removeMatches?: boolean;
|
|
28
|
+
/** Request objects to sanitize */
|
|
29
|
+
sanitizeObjects?: SanitizeObject[];
|
|
30
|
+
/** Sanitization mode */
|
|
31
|
+
mode?: SanitizeMode;
|
|
32
|
+
/** Routes to skip sanitization */
|
|
33
|
+
skipRoutes?: string[];
|
|
34
|
+
/** Custom sanitizer function */
|
|
35
|
+
customSanitizer?: ((data: unknown, options: ExpressMongoSanitizeOptions) => unknown) | null;
|
|
36
|
+
/** Whether to recursively sanitize nested objects */
|
|
37
|
+
recursive?: boolean;
|
|
38
|
+
/** Whether to remove empty values after sanitization */
|
|
39
|
+
removeEmpty?: boolean;
|
|
40
|
+
/** Patterns to match for sanitization */
|
|
41
|
+
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;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
declare class ExpressMongoSanitizeError extends Error {
|
|
53
|
+
constructor(message: string, type?: string);
|
|
54
|
+
message: string;
|
|
55
|
+
type: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
declare const expressMongoSanitize: (options?: ExpressMongoSanitizeOptions) => Handler;
|
|
59
|
+
|
|
60
|
+
export default expressMongoSanitize;
|
|
61
|
+
|
|
62
|
+
export { ExpressMongoSanitizeError, expressMongoSanitize };
|