@exortek/fastify-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 +134 -0
- package/index.js +283 -0
- package/package.json +59 -0
- package/types/index.d.ts +34 -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,134 @@
|
|
|
1
|
+
# @exortek/fastify-mongo-sanitize
|
|
2
|
+
|
|
3
|
+
A comprehensive Fastify plugin designed to protect your MongoDB queries from injection attacks by sanitizing request
|
|
4
|
+
data. This plugin provides flexible sanitization options for request bodies, parameters, and query strings.
|
|
5
|
+
|
|
6
|
+
### Compatibility
|
|
7
|
+
|
|
8
|
+
| Plugin version | Fastify version |
|
|
9
|
+
|----------------|:---------------:|
|
|
10
|
+
| `^1.x` | `^4.x` |
|
|
11
|
+
| `^1.x` | `^5.x` |
|
|
12
|
+
|
|
13
|
+
### Key Features
|
|
14
|
+
|
|
15
|
+
- Automatic sanitization of potentially dangerous MongoDB operators and special characters.
|
|
16
|
+
- Multiple operation modes (auto, manual)
|
|
17
|
+
- Customizable sanitization patterns and replacement strategies
|
|
18
|
+
- Support for nested objects and arrays
|
|
19
|
+
- Configurable string and array handling options
|
|
20
|
+
- Skip routes functionality
|
|
21
|
+
- Custom sanitizer support
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npm install @exortek/fastify-mongo-sanitize
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
OR
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
yarn add @exortek/fastify-mongo-sanitize
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
Register the plugin with Fastify and specify the desired options.
|
|
38
|
+
|
|
39
|
+
```javascript
|
|
40
|
+
const fastify = require('fastify')({ logger: true });
|
|
41
|
+
const fastifyMongoSanitize = require('@exortek/fastify-mongo-sanitize');
|
|
42
|
+
|
|
43
|
+
fastify.register(fastifyMongoSanitize);
|
|
44
|
+
|
|
45
|
+
fastify.listen(3000, (err, address) => {
|
|
46
|
+
if (err) {
|
|
47
|
+
fastify.log.error(err);
|
|
48
|
+
process.exit(1);
|
|
49
|
+
}
|
|
50
|
+
fastify.log.info(`Server listening on ${address}`);
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
# Configuration Options
|
|
55
|
+
|
|
56
|
+
The plugin accepts various configuration options to customize its behavior. Here's a detailed breakdown of all available
|
|
57
|
+
options:
|
|
58
|
+
|
|
59
|
+
## Core Options
|
|
60
|
+
|
|
61
|
+
| Option | Type | Default | Description |
|
|
62
|
+
|-------------------|----------------|----------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
63
|
+
| `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. |
|
|
64
|
+
| `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. |
|
|
65
|
+
| `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. |
|
|
66
|
+
| `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']`. |
|
|
67
|
+
| `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. |
|
|
68
|
+
| `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. |
|
|
69
|
+
| `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. |
|
|
70
|
+
| `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. |
|
|
71
|
+
| `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. |
|
|
72
|
+
| `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. |
|
|
73
|
+
| `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`. |
|
|
74
|
+
| `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`. |
|
|
75
|
+
|
|
76
|
+
## String Options
|
|
77
|
+
|
|
78
|
+
The `stringOptions` object controls string sanitization behavior:
|
|
79
|
+
|
|
80
|
+
```javascript
|
|
81
|
+
{
|
|
82
|
+
trim: false, // Whether to trim whitespace from start/end
|
|
83
|
+
lowercase: false, // Whether to convert strings to lowercase
|
|
84
|
+
maxLength: null // Maximum allowed string length (null for no limit)
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Array Options
|
|
89
|
+
|
|
90
|
+
The `arrayOptions` object controls array sanitization behavior:
|
|
91
|
+
|
|
92
|
+
```javascript
|
|
93
|
+
{
|
|
94
|
+
filterNull: false, // Whether to remove null/undefined values
|
|
95
|
+
distinct: false // Whether to remove duplicate values
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Example Configuration
|
|
100
|
+
|
|
101
|
+
```javascript
|
|
102
|
+
const fastify = require('fastify')();
|
|
103
|
+
|
|
104
|
+
fastify.register(require('fastify-mongo-sanitize'), {
|
|
105
|
+
replaceWith: '_',
|
|
106
|
+
mode: 'manual',
|
|
107
|
+
skipRoutes: ['/health', '/metrics'],
|
|
108
|
+
recursive: true,
|
|
109
|
+
removeEmpty: true,
|
|
110
|
+
stringOptions: {
|
|
111
|
+
trim: true,
|
|
112
|
+
maxLength: 100
|
|
113
|
+
},
|
|
114
|
+
arrayOptions: {
|
|
115
|
+
filterNull: true,
|
|
116
|
+
distinct: true
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Notes
|
|
122
|
+
|
|
123
|
+
- All options are optional and will use their default values if not specified
|
|
124
|
+
- Custom patterns must be valid RegExp objects
|
|
125
|
+
- When using `allowedKeys` or `deniedKeys`, make sure to include all necessary keys for your application
|
|
126
|
+
- The `customSanitizer` function should be thoroughly tested before use in production
|
|
127
|
+
- String length limiting (`maxLength`) only applies to string values, not keys
|
|
128
|
+
- Array options are applied after all other sanitization steps
|
|
129
|
+
|
|
130
|
+
## License
|
|
131
|
+
|
|
132
|
+
**[MIT](https://github.com/ExorTek/fastify-mongo-sanitize/blob/master/LICENSE)**<br>
|
|
133
|
+
|
|
134
|
+
Copyright © 2024 ExorTek
|
package/index.js
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Collection of regular expression patterns used for sanitization
|
|
7
|
+
* @constant {RegExp[]}
|
|
8
|
+
*/
|
|
9
|
+
const PATTERNS = Object.freeze([
|
|
10
|
+
/[\$]/g, // Finds all '$' (dollar) characters in the text.
|
|
11
|
+
/\./g, // Finds all '.' (dot) characters in the text.
|
|
12
|
+
/[\\\/{}.(*+?|[\]^)]/g, // Finds special characters (\, /, {, }, (, ., *, +, ?, |, [, ], ^, )) that need to be escaped.
|
|
13
|
+
/[\u0000-\u001F\u007F-\u009F]/g, // Finds ASCII control characters (0x00-0x1F and 0x7F-0x9F range).
|
|
14
|
+
/\{\s*\$|\$?\{(.|\r?\n)*\}/g, // Finds placeholders or variables in the format `${...}` or `{ $... }`.
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Default configuration options for the plugin
|
|
19
|
+
* @constant {Object}
|
|
20
|
+
*/
|
|
21
|
+
const DEFAULT_OPTIONS = Object.freeze({
|
|
22
|
+
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.
|
|
23
|
+
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.
|
|
24
|
+
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.
|
|
25
|
+
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'].
|
|
26
|
+
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.
|
|
27
|
+
recursive: true, // Enable recursive sanitization. Default is true. If you want to recursively sanitize the nested objects, you can set this option to true.
|
|
28
|
+
removeEmpty: false, // Remove empty values. Default is false. If you want to remove empty values after sanitization, you can set this option to true.
|
|
29
|
+
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.
|
|
30
|
+
allowedKeys: 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.
|
|
31
|
+
deniedKeys: 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.
|
|
32
|
+
stringOptions: {
|
|
33
|
+
// String sanitization options.
|
|
34
|
+
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.
|
|
35
|
+
lowercase: false, // Convert to lowercase. Default is false. If you want to convert the string to lowercase, you can set this option to true.
|
|
36
|
+
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.
|
|
37
|
+
},
|
|
38
|
+
arrayOptions: {
|
|
39
|
+
// Array sanitization options.
|
|
40
|
+
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.
|
|
41
|
+
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.
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Checks if value is a string
|
|
47
|
+
* @param {*} value - Value to check
|
|
48
|
+
* @returns {boolean} True if value is string
|
|
49
|
+
*/
|
|
50
|
+
const isString = (value) => typeof value === 'string';
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Checks if value is a plain object
|
|
54
|
+
* @param {*} obj - Value to check
|
|
55
|
+
* @returns {boolean} True if value is plain object
|
|
56
|
+
*/
|
|
57
|
+
const isPlainObject = (obj) => !!obj && Object.prototype.toString.call(obj) === '[object Object]';
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Checks if value is an array
|
|
61
|
+
* @param {*} value - Value to check
|
|
62
|
+
* @returns {boolean} True if value is array
|
|
63
|
+
*/
|
|
64
|
+
const isArray = (value) => Array.isArray(value);
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Checks if value is a primitive (null, number, or boolean)
|
|
68
|
+
* @param {*} value - Value to check
|
|
69
|
+
* @returns {boolean} True if value is primitive
|
|
70
|
+
*/
|
|
71
|
+
const isPrimitive = (value) => value === null || ['number', 'boolean'].includes(typeof value);
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Checks if value is a Date object
|
|
75
|
+
* @param {*} value - Value to check
|
|
76
|
+
* @returns {boolean} True if value is Date
|
|
77
|
+
*/
|
|
78
|
+
const isDate = (value) => value instanceof Date;
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Checks if value is a function
|
|
82
|
+
* @param {*} value - Value to check
|
|
83
|
+
* @returns {boolean} True if value is function
|
|
84
|
+
*/
|
|
85
|
+
const isFunction = (value) => typeof value === 'function';
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Error class for FastifyMongoSanitize
|
|
89
|
+
*/
|
|
90
|
+
class FastifyMongoSanitizeError extends Error {
|
|
91
|
+
/**
|
|
92
|
+
* Creates a new FastifyMongoSanitizeError
|
|
93
|
+
* @param {string} message - Error message
|
|
94
|
+
* @param {string} [type='generic'] - Error type
|
|
95
|
+
*/
|
|
96
|
+
constructor(message, type = 'generic') {
|
|
97
|
+
super(message);
|
|
98
|
+
this.name = 'FastifyMongoSanitizeError';
|
|
99
|
+
this.type = type;
|
|
100
|
+
Error.captureStackTrace(this, this.constructor);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Sanitizes a string value according to provided options
|
|
106
|
+
* @param {string} str - String to sanitize
|
|
107
|
+
* @param {Object} options - Sanitization options
|
|
108
|
+
* @param {boolean} isValue - Whether string is a value or key
|
|
109
|
+
* @returns {string} Sanitized string
|
|
110
|
+
*/
|
|
111
|
+
const sanitizeString = (str, options, isValue = false) => {
|
|
112
|
+
if (!isString(str)) return str;
|
|
113
|
+
|
|
114
|
+
const { replaceWith, patterns, stringOptions } = options;
|
|
115
|
+
|
|
116
|
+
let result = patterns.reduce((acc, pattern) => acc.replace(pattern, replaceWith), str);
|
|
117
|
+
|
|
118
|
+
if (stringOptions.trim) result = result.trim();
|
|
119
|
+
if (stringOptions.lowercase) result = result.toLowerCase();
|
|
120
|
+
if (stringOptions.maxLength && result.length > stringOptions.maxLength && isValue)
|
|
121
|
+
result = result.slice(0, stringOptions.maxLength);
|
|
122
|
+
|
|
123
|
+
return result;
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Sanitizes an array according to provided options
|
|
128
|
+
* @param {Array} arr - Array to sanitize
|
|
129
|
+
* @param {Object} options - Sanitization options
|
|
130
|
+
* @returns {Array} Sanitized array
|
|
131
|
+
* @throws {FastifyMongoSanitizeError} If input is not an array
|
|
132
|
+
*/
|
|
133
|
+
const sanitizeArray = (arr, options) => {
|
|
134
|
+
if (!isArray(arr)) throw new FastifyMongoSanitizeError('Input must be an array', 'type_error');
|
|
135
|
+
|
|
136
|
+
const { arrayOptions } = options;
|
|
137
|
+
let result = arr.map((item) => sanitizeValue(item, options));
|
|
138
|
+
|
|
139
|
+
if (arrayOptions.filterNull) result = result.filter(Boolean);
|
|
140
|
+
if (arrayOptions.distinct) result = [...new Set(result)];
|
|
141
|
+
|
|
142
|
+
return result;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Sanitizes an object according to provided options
|
|
147
|
+
* @param {Object} obj - Object to sanitize
|
|
148
|
+
* @param {Object} options - Sanitization options
|
|
149
|
+
* @returns {Object} Sanitized object
|
|
150
|
+
* @throws {FastifyMongoSanitizeError} If input is not an object
|
|
151
|
+
*/
|
|
152
|
+
const sanitizeObject = (obj, options) => {
|
|
153
|
+
if (!isPlainObject(obj)) throw new FastifyMongoSanitizeError('Input must be an object', 'type_error');
|
|
154
|
+
|
|
155
|
+
const { removeEmpty, allowedKeys, deniedKeys } = options;
|
|
156
|
+
|
|
157
|
+
return Object.entries(obj).reduce((acc, [key, value]) => {
|
|
158
|
+
if (allowedKeys?.length && !allowedKeys.includes(key)) return acc;
|
|
159
|
+
if (deniedKeys?.length && deniedKeys.includes(key)) return acc;
|
|
160
|
+
|
|
161
|
+
const sanitizedKey = sanitizeString(key, options, false);
|
|
162
|
+
if (removeEmpty && !sanitizedKey) return acc;
|
|
163
|
+
|
|
164
|
+
const sanitizedValue = sanitizeValue(value, options, true);
|
|
165
|
+
if (removeEmpty && !sanitizedValue) return acc;
|
|
166
|
+
|
|
167
|
+
acc[sanitizedKey] = sanitizedValue;
|
|
168
|
+
return acc;
|
|
169
|
+
}, {});
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Sanitizes a value according to its type and provided options
|
|
174
|
+
* @param {*} value - Value to sanitize
|
|
175
|
+
* @param {Object} options - Sanitization options
|
|
176
|
+
* @param {boolean} isValue - Whether value is a value or key
|
|
177
|
+
* @returns {*} Sanitized value
|
|
178
|
+
*/
|
|
179
|
+
const sanitizeValue = (value, options, isValue) => {
|
|
180
|
+
if (!value) return value;
|
|
181
|
+
if (isPrimitive(value)) return value;
|
|
182
|
+
if (isDate(value)) return value;
|
|
183
|
+
if (isPlainObject(value)) return sanitizeObject(value, options);
|
|
184
|
+
if (isArray(value)) return sanitizeArray(value, options);
|
|
185
|
+
if (isString(value)) return sanitizeString(value, options, isValue);
|
|
186
|
+
return value;
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Validates plugin options
|
|
191
|
+
* @param {Object} options - Options to validate
|
|
192
|
+
* @throws {FastifyMongoSanitizeError} If any option is invalid
|
|
193
|
+
*/
|
|
194
|
+
const validateOptions = (options) => {
|
|
195
|
+
const validators = {
|
|
196
|
+
replaceWith: isString,
|
|
197
|
+
sanitizeObjects: isArray,
|
|
198
|
+
mode: (value) => ['auto', 'manual'].includes(value),
|
|
199
|
+
skipRoutes: isArray,
|
|
200
|
+
customSanitizer: (value) => value === null || isFunction(value),
|
|
201
|
+
recursive: isPrimitive,
|
|
202
|
+
removeEmpty: isPrimitive,
|
|
203
|
+
patterns: isArray,
|
|
204
|
+
allowedKeys: (value) => value === null || isArray(value),
|
|
205
|
+
deniedKeys: (value) => value === null || isArray(value),
|
|
206
|
+
stringOptions: isPlainObject,
|
|
207
|
+
arrayOptions: isPlainObject,
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
for (const [key, validate] of Object.entries(validators)) {
|
|
211
|
+
if (!validate(options[key])) {
|
|
212
|
+
throw new FastifyMongoSanitizeError(`Invalid configuration: ${key}`, 'type_error');
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Checks if a value contains potentially malicious patterns
|
|
219
|
+
* @param {*} value - Value to check
|
|
220
|
+
* @param {RegExp[]} patterns - Patterns to check against
|
|
221
|
+
* @returns {boolean} True if injection attempt detected
|
|
222
|
+
*/
|
|
223
|
+
const hasInjection = (value, patterns) => {
|
|
224
|
+
if (isString(value)) return patterns.some((pattern) => pattern.test(value));
|
|
225
|
+
if (isArray(value)) return value.some((item) => hasInjection(item, patterns));
|
|
226
|
+
if (isPlainObject(value))
|
|
227
|
+
return Object.entries(value).some(([key, val]) => hasInjection(key, patterns) || hasInjection(val, patterns));
|
|
228
|
+
|
|
229
|
+
return false;
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Handles request sanitization
|
|
234
|
+
* @param {Object} request - Fastify request object
|
|
235
|
+
* @param {Object} options - Sanitization options
|
|
236
|
+
*/
|
|
237
|
+
const handleRequest = (request, options) => {
|
|
238
|
+
const { sanitizeObjects, customSanitizer } = options;
|
|
239
|
+
|
|
240
|
+
for (const sanitizeObject1 of sanitizeObjects) {
|
|
241
|
+
if (request[sanitizeObject1]) {
|
|
242
|
+
const originalData = request[sanitizeObject1];
|
|
243
|
+
request[sanitizeObject1] = customSanitizer ? customSanitizer(originalData) : sanitizeValue(originalData, options);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Fastify plugin for MongoDB query sanitization
|
|
250
|
+
* @param {Object} fastify - Fastify instance
|
|
251
|
+
* @param {Object} options - Plugin options
|
|
252
|
+
* @param {Function} done - Callback to signal completion
|
|
253
|
+
*/
|
|
254
|
+
const fastifyMongoSanitize = (fastify, options, done) => {
|
|
255
|
+
const opt = { ...DEFAULT_OPTIONS, ...options };
|
|
256
|
+
|
|
257
|
+
validateOptions(opt);
|
|
258
|
+
|
|
259
|
+
const skipRoutes = new Set(opt.skipRoutes);
|
|
260
|
+
|
|
261
|
+
if (opt.mode === 'manual') {
|
|
262
|
+
fastify.decorateRequest('sanitize', function (options) {
|
|
263
|
+
handleRequest(this, { ...opt, ...options });
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (opt.mode === 'auto') {
|
|
268
|
+
fastify.addHook('preHandler', (request, reply, done) => {
|
|
269
|
+
if (skipRoutes.has(request.url)) return done();
|
|
270
|
+
handleRequest(request, opt);
|
|
271
|
+
done();
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
done();
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
module.exports = fp(fastifyMongoSanitize, {
|
|
279
|
+
name: 'fastify-mongo-sanitize',
|
|
280
|
+
fastify: '>=4.x.x',
|
|
281
|
+
});
|
|
282
|
+
module.exports.default = fastifyMongoSanitize;
|
|
283
|
+
module.exports.fastifyMongoSanitize = fastifyMongoSanitize;
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@exortek/fastify-mongo-sanitize",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "MongoDB query sanitizer for Fastify",
|
|
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/fastify-mongo-sanitize.git"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"fastify",
|
|
19
|
+
"mongodb",
|
|
20
|
+
"sanitize",
|
|
21
|
+
"mongoose",
|
|
22
|
+
"fastify-plugin",
|
|
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
|
+
"fastify-middleware",
|
|
34
|
+
"mongodb-sanitizer"
|
|
35
|
+
],
|
|
36
|
+
"author": "ExorTek - https://github.com/ExorTek",
|
|
37
|
+
"license": "MIT",
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/ExorTek/fastify-mongo-sanitize/issues"
|
|
40
|
+
},
|
|
41
|
+
"homepage": "https://github.com/ExorTek/fastify-mongo-sanitize#readme",
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"packageManager": "yarn@4.5.1",
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"fastify": "npm:fastify@5.1.0",
|
|
48
|
+
"fastify4": "npm:fastify@4.28.1",
|
|
49
|
+
"prettier": "^3.3.3",
|
|
50
|
+
"tsd": "^0.31.2"
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"fastify-plugin": "^5.0.1"
|
|
54
|
+
},
|
|
55
|
+
"files": [
|
|
56
|
+
"index.js",
|
|
57
|
+
"types/index.d.ts"
|
|
58
|
+
]
|
|
59
|
+
}
|
package/types/index.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { FastifyPluginCallback } from 'fastify';
|
|
2
|
+
|
|
3
|
+
export interface FastifyMongoSanitizeOptions {
|
|
4
|
+
replaceWith?: string;
|
|
5
|
+
sanitizeObjects?: ('body' | 'params' | 'query')[];
|
|
6
|
+
mode?: 'auto' | 'manual';
|
|
7
|
+
skipRoutes?: string[];
|
|
8
|
+
customSanitizer?: ((data: any) => any) | null;
|
|
9
|
+
recursive?: boolean;
|
|
10
|
+
removeEmpty?: boolean;
|
|
11
|
+
patterns?: RegExp[];
|
|
12
|
+
allowedKeys?: string[] | null;
|
|
13
|
+
deniedKeys?: string[] | null;
|
|
14
|
+
stringOptions?: {
|
|
15
|
+
trim?: boolean;
|
|
16
|
+
lowercase?: boolean;
|
|
17
|
+
maxLength?: number | null;
|
|
18
|
+
};
|
|
19
|
+
arrayOptions?: {
|
|
20
|
+
filterNull?: boolean;
|
|
21
|
+
distinct?: boolean;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
declare class FastifyMongoSanitizeError extends Error {
|
|
26
|
+
constructor(message: string, type?: string);
|
|
27
|
+
name: string;
|
|
28
|
+
type: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
declare const fastifyMongoSanitize: FastifyPluginCallback<FastifyMongoSanitizeOptions>;
|
|
32
|
+
|
|
33
|
+
export default fastifyMongoSanitize;
|
|
34
|
+
export { FastifyMongoSanitizeError, fastifyMongoSanitize };
|