@exortek/fastify-mongo-sanitize 1.2.0 → 1.2.1
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/FastifyMongoSanitizeError.js +18 -0
- package/constants.js +78 -0
- package/helpers.js +172 -0
- package/package.json +5 -2
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error class for FastifyMongoSanitize
|
|
3
|
+
*/
|
|
4
|
+
class FastifyMongoSanitizeError extends Error {
|
|
5
|
+
/**
|
|
6
|
+
* Creates a new FastifyMongoSanitizeError
|
|
7
|
+
* @param {string} message - Error message
|
|
8
|
+
* @param {string} [type='generic'] - Error type
|
|
9
|
+
*/
|
|
10
|
+
constructor(message, type = 'generic') {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = 'FastifyMongoSanitizeError';
|
|
13
|
+
this.type = type;
|
|
14
|
+
Error.captureStackTrace(this, this.constructor);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
module.exports = FastifyMongoSanitizeError;
|
package/constants.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Collection of regular expression patterns used for sanitization
|
|
3
|
+
* @constant {RegExp[]}
|
|
4
|
+
*/
|
|
5
|
+
const PATTERNS = Object.freeze([
|
|
6
|
+
/[\$]/g, // Finds all '$' (dollar) characters in the text.
|
|
7
|
+
/\./g, // Finds all '.' (dot) characters in the text.
|
|
8
|
+
/[\\\/{}.(*+?|[\]^)]/g, // Finds special characters (\, /, {, }, (, ., *, +, ?, |, [, ], ^, )) that need to be escaped.
|
|
9
|
+
/[\u0000-\u001F\u007F-\u009F]/g, // Finds ASCII control characters (0x00-0x1F and 0x7F-0x9F range).
|
|
10
|
+
/\{\s*\$|\$?\{(.|\r?\n)*\}/g, // Finds placeholders or variables in the format `${...}` or `{ $... }`.
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Log levels for debugging
|
|
15
|
+
*/
|
|
16
|
+
const LOG_LEVELS = Object.freeze({
|
|
17
|
+
silent: 0,
|
|
18
|
+
error: 1,
|
|
19
|
+
warn: 2,
|
|
20
|
+
info: 3,
|
|
21
|
+
debug: 4,
|
|
22
|
+
trace: 5,
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Colors used for logging messages in the console
|
|
27
|
+
*/
|
|
28
|
+
const LOG_COLORS = Object.freeze({
|
|
29
|
+
error: '\x1b[31m', // Red
|
|
30
|
+
warn: '\x1b[33m', // Yellow
|
|
31
|
+
info: '\x1b[36m', // Cyan
|
|
32
|
+
debug: '\x1b[90m', // Gray
|
|
33
|
+
trace: '\x1b[35m', // Magenta
|
|
34
|
+
reset: '\x1b[0m', // Reset
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Default configuration options for the plugin
|
|
39
|
+
* @constant {Object}
|
|
40
|
+
*/
|
|
41
|
+
const DEFAULT_OPTIONS = Object.freeze({
|
|
42
|
+
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.
|
|
43
|
+
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.
|
|
44
|
+
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.
|
|
45
|
+
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.
|
|
46
|
+
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'].
|
|
47
|
+
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.
|
|
48
|
+
recursive: true, // Enable recursive sanitization. Default is true. If you want to recursively sanitize the nested objects, you can set this option to true.
|
|
49
|
+
removeEmpty: false, // Remove empty values. Default is false. If you want to remove empty values after sanitization, you can set this option to true.
|
|
50
|
+
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.
|
|
51
|
+
allowedKeys: null, // An array of allowed keys. 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.
|
|
52
|
+
deniedKeys: null, // An array of denied keys. 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.
|
|
53
|
+
stringOptions: {
|
|
54
|
+
// String sanitization options.
|
|
55
|
+
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.
|
|
56
|
+
lowercase: false, // Convert to lowercase. Default is false. If you want to convert the string to lowercase, you can set this option to true.
|
|
57
|
+
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.
|
|
58
|
+
},
|
|
59
|
+
arrayOptions: {
|
|
60
|
+
// Array sanitization options.
|
|
61
|
+
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.
|
|
62
|
+
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.
|
|
63
|
+
},
|
|
64
|
+
debug: {
|
|
65
|
+
enabled: false,
|
|
66
|
+
level: 'info', // 'silent' | 'error' | 'warn' | 'info' | 'debug' | 'trace'
|
|
67
|
+
logPatternMatches: false, // Log when patterns are matched
|
|
68
|
+
logSanitizedValues: false, // Log before/after values
|
|
69
|
+
logSkippedRoutes: false, // Log when routes are skipped
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
module.exports = {
|
|
74
|
+
PATTERNS,
|
|
75
|
+
LOG_LEVELS,
|
|
76
|
+
LOG_COLORS,
|
|
77
|
+
DEFAULT_OPTIONS,
|
|
78
|
+
};
|
package/helpers.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
const { LOG_LEVELS, LOG_COLORS } = require('./constants');
|
|
2
|
+
const FastifyMongoSanitizeError = require('./FastifyMongoSanitizeError');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Enhanced logging function with timing and context
|
|
6
|
+
* @param {Object} debugOpts - Debug options containing enabled status and log level
|
|
7
|
+
* @param {string} level - Log level (error, warn, info, debug, trace)
|
|
8
|
+
* @param {string} context - Context information (e.g., function name, operation)
|
|
9
|
+
* @param {string} message - Log message
|
|
10
|
+
* @param {*} data - Optional data to log
|
|
11
|
+
*/
|
|
12
|
+
const log = (debugOpts, level, context, message, data = null) => {
|
|
13
|
+
if (!debugOpts?.enabled || LOG_LEVELS[debugOpts.level || 'silent'] < LOG_LEVELS[level]) return;
|
|
14
|
+
|
|
15
|
+
const color = LOG_COLORS[level] || '';
|
|
16
|
+
const reset = LOG_COLORS.reset;
|
|
17
|
+
const timestamp = new Date().toISOString();
|
|
18
|
+
|
|
19
|
+
let logMessage = `${color}[mongo-sanitize:${level.toUpperCase()}]${reset} ${timestamp} [${context}] ${message}`;
|
|
20
|
+
|
|
21
|
+
if (data !== null) {
|
|
22
|
+
if (typeof data === 'object') {
|
|
23
|
+
console.log(logMessage);
|
|
24
|
+
console.log(`${color}Data:${reset}`, JSON.stringify(data, null, 2));
|
|
25
|
+
} else {
|
|
26
|
+
console.log(logMessage, data);
|
|
27
|
+
}
|
|
28
|
+
} else {
|
|
29
|
+
console.log(logMessage);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Performance timing utility
|
|
35
|
+
* @param {Object} debugOpts - Debug options
|
|
36
|
+
* @param {string} operation - Operation name
|
|
37
|
+
* @returns {Function} End timing function
|
|
38
|
+
*/
|
|
39
|
+
const startTiming = (debugOpts, operation) => {
|
|
40
|
+
const start = process.hrtime();
|
|
41
|
+
log(debugOpts, 'trace', 'TIMING', `Started: ${operation}`);
|
|
42
|
+
|
|
43
|
+
return () => {
|
|
44
|
+
const [seconds, nanoseconds] = process.hrtime(start);
|
|
45
|
+
const milliseconds = seconds * 1000 + nanoseconds / 1000000;
|
|
46
|
+
log(debugOpts, 'trace', 'TIMING', `Completed: ${operation} in ${milliseconds.toFixed(2)}ms`);
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Checks if value is a valid email address
|
|
52
|
+
* @param {string} val - Value to check
|
|
53
|
+
* @returns {boolean} True if value is a valid email address
|
|
54
|
+
*/
|
|
55
|
+
const isEmail = (val) => /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/i.test(val);
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Checks if value is a string
|
|
59
|
+
* @param {*} value - Value to check
|
|
60
|
+
* @returns {boolean} True if value is string
|
|
61
|
+
*/
|
|
62
|
+
const isString = (value) => typeof value === 'string';
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Checks if value is a plain object
|
|
66
|
+
* @param {*} obj - Value to check
|
|
67
|
+
* @returns {boolean} True if value is plain object
|
|
68
|
+
*/
|
|
69
|
+
const isPlainObject = (obj) => !!obj && Object.prototype.toString.call(obj) === '[object Object]';
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Checks if value is an array
|
|
73
|
+
* @param {*} value - Value to check
|
|
74
|
+
* @returns {boolean} True if value is array
|
|
75
|
+
*/
|
|
76
|
+
const isArray = (value) => Array.isArray(value);
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Checks if value is a primitive (null, number, or boolean)
|
|
80
|
+
* @param {*} value - Value to check
|
|
81
|
+
* @returns {boolean} True if value is primitive
|
|
82
|
+
*/
|
|
83
|
+
const isPrimitive = (value) => value === null || ['number', 'boolean'].includes(typeof value);
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Checks if value is a Date object
|
|
87
|
+
* @param {*} value - Value to check
|
|
88
|
+
* @returns {boolean} True if value is Date
|
|
89
|
+
*/
|
|
90
|
+
const isDate = (value) => value instanceof Date;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Checks if value is a function
|
|
94
|
+
* @param {*} value - Value to check
|
|
95
|
+
* @returns {boolean} True if value is function
|
|
96
|
+
*/
|
|
97
|
+
const isFunction = (value) => typeof value === 'function';
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Cleans a URL by removing leading and trailing slashes
|
|
101
|
+
* @param {string} url - URL to clean
|
|
102
|
+
* @returns {string|null} Cleaned URL or null if input is invalid
|
|
103
|
+
*/
|
|
104
|
+
const cleanUrl = (url) => {
|
|
105
|
+
if (typeof url !== 'string' || !url) return null;
|
|
106
|
+
const [path] = url.split(/[?#]/);
|
|
107
|
+
const trimmed = path.replace(/^\/+|\/+$/g, '');
|
|
108
|
+
return trimmed ? '/' + trimmed : null;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Validators for plugin options
|
|
113
|
+
* @constant {Object}
|
|
114
|
+
* @property {Function} replaceWith - Validates that replaceWith is a string
|
|
115
|
+
* @property {Function} removeMatches - Validates that removeMatches is a primitive (boolean or null)
|
|
116
|
+
* @property {Function} sanitizeObjects - Validates that sanitizeObjects is an array
|
|
117
|
+
* @property {Function} mode - Validates that mode is either 'auto' or 'manual'
|
|
118
|
+
* @property {Function} skipRoutes - Validates that skipRoutes is an array
|
|
119
|
+
* @property {Function} customSanitizer - Validates that customSanitizer is either null or a function
|
|
120
|
+
* @property {Function} recursive - Validates that recursive is a primitive (boolean or null)
|
|
121
|
+
* @property {Function} removeEmpty - Validates that removeEmpty is a primitive (boolean or null)
|
|
122
|
+
* @property {Function} patterns - Validates that patterns is an array
|
|
123
|
+
* @property {Function} allowedKeys - Validates that allowedKeys is either null or an array
|
|
124
|
+
* @property {Function} deniedKeys - Validates that deniedKeys is either null or an array
|
|
125
|
+
* @property {Function} stringOptions - Validates that stringOptions is a plain object
|
|
126
|
+
* @property {Function} arrayOptions - Validates that arrayOptions is a plain object
|
|
127
|
+
* @property {Function} debug - Validates that debug is a plain object with expected properties
|
|
128
|
+
* @returns {Object} Object containing validation functions for each option
|
|
129
|
+
*/
|
|
130
|
+
const validators = Object.freeze({
|
|
131
|
+
replaceWith: isString,
|
|
132
|
+
removeMatches: isPrimitive,
|
|
133
|
+
sanitizeObjects: isArray,
|
|
134
|
+
mode: (value) => ['auto', 'manual'].includes(value),
|
|
135
|
+
skipRoutes: isArray,
|
|
136
|
+
customSanitizer: (value) => value === null || isFunction(value),
|
|
137
|
+
recursive: isPrimitive,
|
|
138
|
+
removeEmpty: isPrimitive,
|
|
139
|
+
patterns: isArray,
|
|
140
|
+
allowedKeys: (value) => value === null || isArray(value),
|
|
141
|
+
deniedKeys: (value) => value === null || isArray(value),
|
|
142
|
+
stringOptions: isPlainObject,
|
|
143
|
+
arrayOptions: isPlainObject,
|
|
144
|
+
debug: isPlainObject,
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Validates plugin options
|
|
149
|
+
* @param {Object} options - Options to validate
|
|
150
|
+
* @throws {FastifyMongoSanitizeError} If any option is invalid
|
|
151
|
+
*/
|
|
152
|
+
const validateOptions = (options) => {
|
|
153
|
+
for (const [key, validate] of Object.entries(validators)) {
|
|
154
|
+
if (!validate(options[key])) {
|
|
155
|
+
throw new FastifyMongoSanitizeError(`Invalid configuration: ${key}`, 'type_error');
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
module.exports = {
|
|
161
|
+
log,
|
|
162
|
+
startTiming,
|
|
163
|
+
isEmail,
|
|
164
|
+
isString,
|
|
165
|
+
isPlainObject,
|
|
166
|
+
isArray,
|
|
167
|
+
isPrimitive,
|
|
168
|
+
isDate,
|
|
169
|
+
isFunction,
|
|
170
|
+
cleanUrl,
|
|
171
|
+
validateOptions,
|
|
172
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@exortek/fastify-mongo-sanitize",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.1",
|
|
4
4
|
"description": "MongoDB query sanitizer for Fastify",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"type": "commonjs",
|
|
@@ -54,6 +54,9 @@
|
|
|
54
54
|
},
|
|
55
55
|
"files": [
|
|
56
56
|
"index.js",
|
|
57
|
-
"types/index.d.ts"
|
|
57
|
+
"types/index.d.ts",
|
|
58
|
+
"constants.js",
|
|
59
|
+
"helpers.js",
|
|
60
|
+
"FastifyMongoSanitizeError.js"
|
|
58
61
|
]
|
|
59
62
|
}
|