@exortek/fastify-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 (3) hide show
  1. package/LICENSE +21 -21
  2. package/index.js +34 -29
  3. package/package.json +1 -1
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/index.js CHANGED
@@ -20,6 +20,7 @@ const PATTERNS = Object.freeze([
20
20
  */
21
21
  const DEFAULT_OPTIONS = Object.freeze({
22
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
+ 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.
23
24
  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
25
  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
26
  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'].
@@ -27,8 +28,8 @@ const DEFAULT_OPTIONS = Object.freeze({
27
28
  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
29
  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
30
  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.
31
+ 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.
32
+ 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.
32
33
  stringOptions: {
33
34
  // String sanitization options.
34
35
  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.
@@ -42,6 +43,13 @@ const DEFAULT_OPTIONS = Object.freeze({
42
43
  },
43
44
  });
44
45
 
46
+ /**
47
+ * Checks if value is a valid email address
48
+ * @param {string} val - Value to check
49
+ * @returns {boolean} True if value is a valid email address
50
+ */
51
+ const isEmail = (val) => /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/i.test(val);
52
+
45
53
  /**
46
54
  * Checks if value is a string
47
55
  * @param {*} value - Value to check
@@ -109,7 +117,7 @@ class FastifyMongoSanitizeError extends Error {
109
117
  * @returns {string} Sanitized string
110
118
  */
111
119
  const sanitizeString = (str, options, isValue = false) => {
112
- if (!isString(str)) return str;
120
+ if (!isString(str) || isEmail(str)) return str;
113
121
 
114
122
  const { replaceWith, patterns, stringOptions } = options;
115
123
 
@@ -117,8 +125,7 @@ const sanitizeString = (str, options, isValue = false) => {
117
125
 
118
126
  if (stringOptions.trim) result = result.trim();
119
127
  if (stringOptions.lowercase) result = result.toLowerCase();
120
- if (stringOptions.maxLength && result.length > stringOptions.maxLength && isValue)
121
- result = result.slice(0, stringOptions.maxLength);
128
+ if (stringOptions.maxLength && isValue) result = result.slice(0, stringOptions.maxLength);
122
129
 
123
130
  return result;
124
131
  };
@@ -152,16 +159,28 @@ const sanitizeArray = (arr, options) => {
152
159
  const sanitizeObject = (obj, options) => {
153
160
  if (!isPlainObject(obj)) throw new FastifyMongoSanitizeError('Input must be an object', 'type_error');
154
161
 
155
- const { removeEmpty, allowedKeys, deniedKeys } = options;
162
+ const { removeEmpty, allowedKeys, deniedKeys, removeMatches, patterns } = options;
156
163
 
157
164
  return Object.entries(obj).reduce((acc, [key, value]) => {
158
165
  if (allowedKeys?.length && !allowedKeys.includes(key)) return acc;
166
+
159
167
  if (deniedKeys?.length && deniedKeys.includes(key)) return acc;
160
168
 
161
169
  const sanitizedKey = sanitizeString(key, options, false);
170
+
171
+ if (isString(value) && isEmail(value)) {
172
+ acc[sanitizedKey] = value;
173
+ return acc;
174
+ }
175
+
176
+ if (removeMatches && patterns.some((pattern) => pattern.test(key))) return acc;
177
+
162
178
  if (removeEmpty && !sanitizedKey) return acc;
163
179
 
180
+ if (removeMatches && isString(value) && patterns.some((pattern) => pattern.test(value))) return acc;
181
+
164
182
  const sanitizedValue = sanitizeValue(value, options, true);
183
+
165
184
  if (removeEmpty && !sanitizedValue) return acc;
166
185
 
167
186
  acc[sanitizedKey] = sanitizedValue;
@@ -173,13 +192,11 @@ const sanitizeObject = (obj, options) => {
173
192
  * Sanitizes a value according to its type and provided options
174
193
  * @param {*} value - Value to sanitize
175
194
  * @param {Object} options - Sanitization options
176
- * @param {boolean} isValue - Whether value is a value or key
195
+ * @param {boolean} [isValue=false] - Whether value is a value or key
177
196
  * @returns {*} Sanitized value
178
197
  */
179
198
  const sanitizeValue = (value, options, isValue) => {
180
- if (!value) return value;
181
- if (isPrimitive(value)) return value;
182
- if (isDate(value)) return value;
199
+ if (!value || isPrimitive(value) || isDate(value)) return value;
183
200
  if (isPlainObject(value)) return sanitizeObject(value, options);
184
201
  if (isArray(value)) return sanitizeArray(value, options);
185
202
  if (isString(value)) return sanitizeString(value, options, isValue);
@@ -194,6 +211,7 @@ const sanitizeValue = (value, options, isValue) => {
194
211
  const validateOptions = (options) => {
195
212
  const validators = {
196
213
  replaceWith: isString,
214
+ removeMatches: isPrimitive,
197
215
  sanitizeObjects: isArray,
198
216
  mode: (value) => ['auto', 'manual'].includes(value),
199
217
  skipRoutes: isArray,
@@ -214,21 +232,6 @@ const validateOptions = (options) => {
214
232
  }
215
233
  };
216
234
 
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
235
  /**
233
236
  * Handles request sanitization
234
237
  * @param {Object} request - Fastify request object
@@ -237,10 +240,12 @@ const hasInjection = (value, patterns) => {
237
240
  const handleRequest = (request, options) => {
238
241
  const { sanitizeObjects, customSanitizer } = options;
239
242
 
240
- for (const sanitizeObject1 of sanitizeObjects) {
241
- if (request[sanitizeObject1]) {
242
- const originalData = request[sanitizeObject1];
243
- request[sanitizeObject1] = customSanitizer ? customSanitizer(originalData) : sanitizeValue(originalData, options);
243
+ for (const sanitizeObject of sanitizeObjects) {
244
+ if (request[sanitizeObject]) {
245
+ const originalRequest = Object.assign({}, request[sanitizeObject]);
246
+ request[sanitizeObject] = customSanitizer
247
+ ? customSanitizer(originalRequest)
248
+ : sanitizeValue(originalRequest, options);
244
249
  }
245
250
  }
246
251
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exortek/fastify-mongo-sanitize",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "MongoDB query sanitizer for Fastify",
5
5
  "main": "index.js",
6
6
  "type": "commonjs",