-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
310 lines (260 loc) · 9.76 KB
/
index.js
File metadata and controls
310 lines (260 loc) · 9.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
'use strict';
const fp = require('fastify-plugin');
const {
isString,
isArray,
isPlainObject,
isPrimitive,
isDate,
isEmail,
cleanUrl,
startTiming,
log,
validateOptions,
} = require('./helpers');
const FastifyMongoSanitizeError = require('./FastifyMongoSanitizeError');
const { DEFAULT_OPTIONS } = require('./constants');
/**
* Sanitizes a string value according to provided options
* @param {string} str - String to sanitize
* @param {Object} options - Sanitization options
* @param {boolean} isValue - Whether string is a value or key
* @returns {string} Sanitized string
*/
const sanitizeString = (str, options, isValue = false) => {
if (!isString(str) || isEmail(str)) {
log(options.debug, 'trace', 'STRING', `Skipping sanitization (not string or is email): ${typeof str}`);
return str;
}
const { replaceWith, patterns, stringOptions, debug } = options;
const originalStr = str;
let matchedPatterns = [];
let result = patterns.reduce((acc, pattern, index) => {
const matches = acc.match(pattern);
if (matches) {
matchedPatterns.push({ patternIndex: index, matches: matches.length });
log(debug, 'debug', 'STRING', `Pattern ${index} matched ${matches.length} times in string`);
}
return acc.replace(pattern, replaceWith);
}, str);
if (stringOptions.trim) result = result.trim();
if (stringOptions.lowercase) result = result.toLowerCase();
if (stringOptions.maxLength && isValue) result = result.slice(0, stringOptions.maxLength);
if (debug.logSanitizedValues && originalStr !== result) {
log(debug, 'debug', 'STRING', 'String sanitized', {
original: originalStr,
sanitized: result,
matchedPatterns,
});
}
if (debug.logPatternMatches && matchedPatterns.length > 0) {
log(debug, 'info', 'PATTERN', `Patterns matched in string`, matchedPatterns);
}
return result;
};
/**
* Sanitizes an array according to provided options
* @param {Array} arr - Array to sanitize
* @param {Object} options - Sanitization options
* @returns {Array} Sanitized array
* @throws {FastifyMongoSanitizeError} If input is not an array
*/
const sanitizeArray = (arr, options) => {
if (!isArray(arr)) {
const error = new FastifyMongoSanitizeError('Input must be an array', 'type_error');
log(options.debug, 'error', 'ARRAY', `Sanitization failed: ${error.message}`);
throw error;
}
const { arrayOptions, debug } = options;
const originalLength = arr.length;
log(debug, 'trace', 'ARRAY', `Sanitizing array with ${originalLength} items`);
let result = arr.map((item, index) => {
log(debug, 'trace', 'ARRAY', `Sanitizing item ${index}`);
return !options.recursive && (isPlainObject(item) || isArray(item)) ? item : sanitizeValue(item, options);
});
if (arrayOptions.filterNull) {
const beforeFilter = result.length;
result = result.filter(Boolean);
const filtered = beforeFilter - result.length;
if (filtered > 0) {
log(debug, 'debug', 'ARRAY', `Filtered ${filtered} null/falsy values`);
}
}
if (arrayOptions.distinct) {
const beforeDistinct = result.length;
result = [...new Set(result)];
const duplicates = beforeDistinct - result.length;
if (duplicates > 0) {
log(debug, 'debug', 'ARRAY', `Removed ${duplicates} duplicate values`);
}
}
log(debug, 'trace', 'ARRAY', `Array sanitization completed: ${originalLength} -> ${result.length} items`);
return result;
};
/**
* Sanitizes an object according to provided options
* @param {Object} obj - Object to sanitize
* @param {Object} options - Sanitization options
* @returns {Object} Sanitized object
* @throws {FastifyMongoSanitizeError} If input is not an object
*/
const sanitizeObject = (obj, options) => {
if (!isPlainObject(obj)) {
const error = new FastifyMongoSanitizeError('Input must be an object', 'type_error');
log(options.debug, 'error', 'OBJECT', `Sanitization failed: ${error.message}`);
throw error;
}
const { removeEmpty, allowedKeys, deniedKeys, removeMatches, patterns, debug } = options;
const originalKeys = Object.keys(obj);
log(debug, 'trace', 'OBJECT', `Sanitizing object with ${originalKeys.length} keys`);
const result = Object.entries(obj).reduce((acc, [key, value]) => {
if (allowedKeys && allowedKeys.length && !allowedKeys.includes(key)) {
log(debug, 'debug', 'OBJECT', `Key '${key}' not in allowedKeys, removing`);
return acc;
}
if (deniedKeys && deniedKeys.length && deniedKeys.includes(key)) {
log(debug, 'debug', 'OBJECT', `Key '${key}' in deniedKeys, removing`);
return acc;
}
const sanitizedKey = sanitizeString(key, options, false);
if (isString(value) && isEmail(value)) {
log(debug, 'trace', 'OBJECT', `Preserving email value for key '${key}'`);
acc[sanitizedKey] = value;
return acc;
}
if (
removeMatches &&
patterns.some((pattern) => {
const matches = pattern.test(key);
if (matches) {
log(debug, 'debug', 'OBJECT', `Key '${key}' matches removal pattern`);
}
return matches;
})
) {
return acc;
}
if (removeEmpty && !sanitizedKey) {
log(debug, 'debug', 'OBJECT', `Empty key removed after sanitization`);
return acc;
}
if (
removeMatches &&
isString(value) &&
patterns.some((pattern) => {
const matches = pattern.test(value);
if (matches) {
log(debug, 'debug', 'OBJECT', `Value for key '${key}' matches removal pattern`);
}
return matches;
})
) {
return acc;
}
const sanitizedValue =
!options.recursive && (isPlainObject(value) || isArray(value)) ? value : sanitizeValue(value, options, true);
if (removeEmpty && !sanitizedValue) {
log(debug, 'debug', 'OBJECT', `Empty value removed for key '${key}'`);
return acc;
}
acc[sanitizedKey] = sanitizedValue;
return acc;
}, {});
const finalKeys = Object.keys(result);
log(debug, 'trace', 'OBJECT', `Object sanitization completed: ${originalKeys.length} -> ${finalKeys.length} keys`);
return result;
};
/**
* Sanitizes a value according to its type and provided options
* @param {*} value - Value to sanitize
* @param {Object} options - Sanitization options
* @param {boolean} [isValue=false] - Whether value is a value or key
* @returns {*} Sanitized value
*/
const sanitizeValue = (value, options, isValue) => {
if (value == null || isPrimitive(value) || isDate(value)) return value;
if (isString(value)) return sanitizeString(value, options, isValue);
if (isArray(value)) return sanitizeArray(value, options);
if (isPlainObject(value)) return sanitizeObject(value, options);
return value;
};
/**
* Handles request sanitization
* @param {Object} request - Fastify request object
* @param {Object} options - Sanitization options
*/
const handleRequest = (request, options) => {
const { sanitizeObjects, customSanitizer, debug } = options;
const endTiming = startTiming(debug, 'Request Sanitization');
log(debug, 'info', 'REQUEST', `Sanitizing request: ${request.method} ${request.url}`);
for (const sanitizeObject of sanitizeObjects) {
if (request[sanitizeObject]) {
log(debug, 'debug', 'REQUEST', `Sanitizing ${sanitizeObject}`, request[sanitizeObject]);
const originalRequest = Object.assign({}, request[sanitizeObject]);
if (customSanitizer) {
log(debug, 'debug', 'REQUEST', `Using custom sanitizer for ${sanitizeObject}`);
request[sanitizeObject] = customSanitizer(originalRequest);
} else {
request[sanitizeObject] = sanitizeValue(originalRequest, options);
}
if (debug.logSanitizedValues) {
log(debug, 'debug', 'REQUEST', `${sanitizeObject} sanitized`, {
before: originalRequest,
after: request[sanitizeObject],
});
}
}
}
endTiming();
log(debug, 'info', 'REQUEST', `Request sanitization completed`);
};
/**
* Fastify plugin for MongoDB query sanitization
* @param {Object} fastify - Fastify instance
* @param {Object} options - Plugin options
* @param {Function} done - Callback to signal completion
*/
const fastifyMongoSanitize = (fastify, options, done) => {
const opt = { ...DEFAULT_OPTIONS, ...options };
log(opt.debug, 'info', 'PLUGIN', 'Initializing fastify-mongo-sanitize plugin', {
mode: opt.mode,
sanitizeObjects: opt.sanitizeObjects,
skipRoutes: opt.skipRoutes,
debugLevel: opt.debug.level,
});
validateOptions(opt);
const skipRoutes = new Set((opt.skipRoutes || []).map(cleanUrl));
log(opt.debug, 'debug', 'PLUGIN', `Skip routes configured: ${skipRoutes.size} routes`);
if (opt.mode === 'manual') {
log(opt.debug, 'info', 'PLUGIN', 'Manual mode enabled - decorating request with sanitize method');
fastify.decorateRequest('sanitize', function (options = {}) {
const mergedOptions = { ...opt, ...options };
log(mergedOptions.debug, 'info', 'MANUAL', 'Manual sanitization triggered');
handleRequest(this, mergedOptions);
});
}
if (opt.mode === 'auto') {
log(opt.debug, 'info', 'PLUGIN', 'Auto mode enabled - adding preHandler hook');
fastify.addHook('preHandler', (request, reply, done) => {
if (skipRoutes.size) {
const url = cleanUrl(request.url);
if (skipRoutes.has(url)) {
if (opt.debug.logSkippedRoutes) {
log(opt.debug, 'info', 'SKIP', `Route skipped: ${request.method} ${request.url}`);
}
return done();
}
}
handleRequest(request, opt);
done();
});
}
log(opt.debug, 'info', 'PLUGIN', 'Plugin initialization completed');
done();
};
module.exports = fp(fastifyMongoSanitize, {
name: 'fastify-mongo-sanitize',
fastify: '>=4.x.x',
});
module.exports.default = fastifyMongoSanitize;
module.exports.fastifyMongoSanitize = fastifyMongoSanitize;