@exortek/fastify-mongo-sanitize 1.2.1 → 2.0.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/README.md +57 -174
- package/package.json +42 -36
- package/src/index.js +43 -0
- package/types/index.d.ts +46 -43
- package/FastifyMongoSanitizeError.js +0 -18
- package/LICENSE +0 -21
- package/constants.js +0 -78
- package/helpers.js +0 -172
- package/index.js +0 -310
package/README.md
CHANGED
|
@@ -1,215 +1,98 @@
|
|
|
1
1
|
# @exortek/fastify-mongo-sanitize
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
<p align="center">
|
|
4
|
+
<img src="https://img.shields.io/npm/v/@exortek/fastify-mongo-sanitize?style=flat-square&color=000000" alt="npm version">
|
|
5
|
+
<img src="https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square" alt="license">
|
|
6
|
+
</p>
|
|
6
7
|
|
|
8
|
+
Fastify plugin for NoSQL injection prevention. Sanitizes request `body`, `params`, and `query` to protect MongoDB queries from operator injection attacks.
|
|
7
9
|
|
|
8
|
-
##
|
|
9
|
-
|
|
10
|
-
| Plugin version | Fastify version |
|
|
11
|
-
|----------------|:---------------:|
|
|
12
|
-
| `^1.x` | `^4.x` |
|
|
13
|
-
| `^1.x` | `^5.x` |
|
|
14
|
-
|
|
15
|
-
## Key Features
|
|
16
|
-
|
|
17
|
-
- Automatic sanitization of potentially dangerous MongoDB operators and special characters
|
|
18
|
-
- Multiple operation modes (**auto**, **manual**)
|
|
19
|
-
- **Recursive** or single-level sanitization control
|
|
20
|
-
- Customizable sanitization patterns and replacement strategies
|
|
21
|
-
- Configurable string and array handling options
|
|
22
|
-
- Skip routes functionality with normalization
|
|
23
|
-
- Allowed/denied key whitelisting/blacklisting
|
|
24
|
-
- **Custom sanitizer** function support
|
|
25
|
-
- Full TypeScript types & Fastify request augmentation
|
|
26
|
-
- Detailed debug and logging options
|
|
27
|
-
|
|
28
|
-
## Installation
|
|
10
|
+
## 📦 Installation
|
|
29
11
|
|
|
30
12
|
```bash
|
|
31
13
|
npm install @exortek/fastify-mongo-sanitize
|
|
32
14
|
```
|
|
33
|
-
|
|
34
|
-
OR
|
|
35
|
-
|
|
36
15
|
```bash
|
|
37
|
-
yarn
|
|
16
|
+
yarn install @exortek/fastify-mongo-sanitize
|
|
38
17
|
```
|
|
39
|
-
|
|
40
|
-
OR
|
|
41
|
-
|
|
42
18
|
```bash
|
|
43
|
-
pnpm
|
|
19
|
+
pnpm install @exortek/fastify-mongo-sanitize
|
|
44
20
|
```
|
|
45
21
|
|
|
46
|
-
##
|
|
22
|
+
## ⚡ Quick Start
|
|
47
23
|
|
|
48
|
-
|
|
24
|
+
```js
|
|
25
|
+
const fastify = require('fastify')();
|
|
26
|
+
const mongoSanitize = require('@exortek/fastify-mongo-sanitize');
|
|
49
27
|
|
|
50
|
-
|
|
51
|
-
const fastify = require('fastify')({ logger: true });
|
|
52
|
-
const fastifyMongoSanitize = require('@exortek/fastify-mongo-sanitize');
|
|
28
|
+
fastify.register(mongoSanitize);
|
|
53
29
|
|
|
54
|
-
fastify.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
// sanitized request.body, request.query, and request.params
|
|
58
|
-
return req.body;
|
|
30
|
+
fastify.post('/login', async (request) => {
|
|
31
|
+
// request.body is sanitized — { "$ne": "" } becomes { "ne": "" }
|
|
32
|
+
return request.body;
|
|
59
33
|
});
|
|
34
|
+
```
|
|
60
35
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
36
|
+
## ⚙️ Options
|
|
37
|
+
|
|
38
|
+
```js
|
|
39
|
+
fastify.register(mongoSanitize, {
|
|
40
|
+
replaceWith: '', // Replace matched chars with this string
|
|
41
|
+
removeMatches: false, // Remove entire key-value pair if pattern matches
|
|
42
|
+
sanitizeObjects: ['body', 'params', 'query'], // Fields to sanitize
|
|
43
|
+
contentTypes: ['application/json', 'application/x-www-form-urlencoded'],
|
|
44
|
+
mode: 'auto', // 'auto' | 'manual'
|
|
45
|
+
skipRoutes: [], // Routes to skip (string or RegExp)
|
|
46
|
+
recursive: true, // Sanitize nested objects
|
|
47
|
+
maxDepth: null, // Max recursion depth (null = unlimited)
|
|
48
|
+
onSanitize: ({ key, originalValue, sanitizedValue }) => {
|
|
49
|
+
fastify.log.warn(`Sanitized ${key}`);
|
|
65
50
|
}
|
|
66
|
-
fastify.log.info(`Server listening at ${address}`);
|
|
67
51
|
});
|
|
68
52
|
```
|
|
69
53
|
|
|
70
|
-
|
|
54
|
+
> For the full list of options, see the [Core README](../core/README.md#configuration-options).
|
|
71
55
|
|
|
72
|
-
|
|
73
|
-
import fastify from 'fastify';
|
|
74
|
-
import mongoSanitize from '@exortek/fastify-mongo-sanitize';
|
|
56
|
+
## 🛠 Features
|
|
75
57
|
|
|
76
|
-
|
|
58
|
+
### Manual Mode
|
|
77
59
|
|
|
78
|
-
|
|
79
|
-
recursive: false,
|
|
80
|
-
debug: { enabled: true, level: 'debug' },
|
|
81
|
-
});
|
|
60
|
+
If you need fine-grained control over when sanitization occurs:
|
|
82
61
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
return req.body;
|
|
86
|
-
});
|
|
87
|
-
```
|
|
62
|
+
```js
|
|
63
|
+
fastify.register(mongoSanitize, { mode: 'manual' });
|
|
88
64
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
## Core Options
|
|
95
|
-
|
|
96
|
-
| Option | Type | Default | Description |
|
|
97
|
-
|-------------------|----------------|----------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
98
|
-
| `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. |
|
|
99
|
-
| '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. |
|
|
100
|
-
| `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. |
|
|
101
|
-
| `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. |
|
|
102
|
-
| `skipRoutes` | array | `[]` | An array of routes to skip. All entries and incoming request paths are normalized (leading/trailing slashes removed, query and fragment ignored). For example, adding `'/health'` will skip `/health`, `/health/`, and `/health?ping=1`. | |
|
|
103
|
-
| `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. |
|
|
104
|
-
| `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. |
|
|
105
|
-
| `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. |
|
|
106
|
-
| `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. |
|
|
107
|
-
| `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. |
|
|
108
|
-
| `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. |
|
|
109
|
-
| `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`. |
|
|
110
|
-
| `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`. |
|
|
111
|
-
| `debug` | object | `{ enabled: false, level: 'info' }` | Logging/debug options. |
|
|
112
|
-
|
|
113
|
-
> **Note on skipRoutes matching:**
|
|
114
|
-
> All skipRoutes entries and request URLs are normalized before matching. This means:
|
|
115
|
-
> - Trailing and leading slashes (`/path`, `/path/`, `///path//`) are treated as the same.
|
|
116
|
-
> - Query strings and fragments are ignored (`/foo?bar=1`, `/foo#anchor` → `/foo`).
|
|
117
|
-
>
|
|
118
|
-
> For example, if you set `skipRoutes: ['/api/users']`, then all of the following will be skipped:
|
|
119
|
-
> - `/api/users`
|
|
120
|
-
> - `/api/users/`
|
|
121
|
-
> - `/api/users?role=admin`
|
|
122
|
-
> - `/api/users#tab`
|
|
123
|
-
>
|
|
124
|
-
> **Fastify's default behavior:**
|
|
125
|
-
> Fastify treats `/foo` and `/foo/` as different routes. This plugin normalizes skipRoutes for skipping purposes only.
|
|
126
|
-
> Make sure you have defined both routes in Fastify if you want both to respond.
|
|
127
|
-
|
|
128
|
-
## String Options
|
|
129
|
-
|
|
130
|
-
The `stringOptions` object controls string sanitization behavior:
|
|
131
|
-
|
|
132
|
-
```javascript
|
|
133
|
-
{
|
|
134
|
-
trim: false, // Whether to trim whitespace from start/end
|
|
135
|
-
lowercase: false, // Whether to convert strings to lowercase
|
|
136
|
-
maxLength: null // Maximum allowed string length (null for no limit)
|
|
137
|
-
}
|
|
65
|
+
fastify.post('/sensitive', async (request) => {
|
|
66
|
+
request.sanitize(); // Manually trigger sanitization
|
|
67
|
+
return request.body;
|
|
68
|
+
});
|
|
138
69
|
```
|
|
139
70
|
|
|
140
|
-
|
|
71
|
+
### Content-Type Guard
|
|
141
72
|
|
|
142
|
-
|
|
73
|
+
By default, only `application/json` and `application/x-www-form-urlencoded` bodies are sanitized. You can customize this:
|
|
143
74
|
|
|
144
|
-
```
|
|
145
|
-
{
|
|
146
|
-
filterNull: false, // Whether to remove null/undefined values
|
|
147
|
-
distinct: false // Whether to remove duplicate values
|
|
148
|
-
}
|
|
75
|
+
```js
|
|
76
|
+
fastify.register(mongoSanitize, { contentTypes: ['application/json', 'application/graphql'] });
|
|
149
77
|
```
|
|
150
78
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
### Mode: `auto`
|
|
154
|
-
Sanitization is performed automatically on every request for the configured properties `(body, params, query)`.
|
|
79
|
+
### TypeScript Support
|
|
155
80
|
|
|
156
|
-
|
|
81
|
+
Full TypeScript support is included out of the box, with request augmentation for the `sanitize` method:
|
|
157
82
|
|
|
158
|
-
```
|
|
159
|
-
fastify
|
|
83
|
+
```typescript
|
|
84
|
+
import fastify from 'fastify';
|
|
85
|
+
import mongoSanitize from '@exortek/fastify-mongo-sanitize';
|
|
160
86
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
// ...
|
|
164
|
-
});
|
|
165
|
-
```
|
|
87
|
+
const app = fastify();
|
|
88
|
+
app.register(mongoSanitize);
|
|
166
89
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
## Example Full Configuration
|
|
172
|
-
|
|
173
|
-
```javascript
|
|
174
|
-
fastify.register(require('@exortek/fastify-mongo-sanitize'), {
|
|
175
|
-
replaceWith: '_',
|
|
176
|
-
mode: 'manual',
|
|
177
|
-
skipRoutes: ['/health', '/metrics'],
|
|
178
|
-
recursive: true,
|
|
179
|
-
removeEmpty: true,
|
|
180
|
-
removeMatches: true, // Remove dangerous patterns completely
|
|
181
|
-
stringOptions: {
|
|
182
|
-
trim: true,
|
|
183
|
-
maxLength: 100,
|
|
184
|
-
},
|
|
185
|
-
arrayOptions: {
|
|
186
|
-
filterNull: true,
|
|
187
|
-
distinct: true,
|
|
188
|
-
},
|
|
189
|
-
debug: {
|
|
190
|
-
enabled: true,
|
|
191
|
-
level: 'debug',
|
|
192
|
-
logPatternMatches: true,
|
|
193
|
-
logSanitizedValues: true,
|
|
194
|
-
logSkippedRoutes: true,
|
|
195
|
-
}
|
|
90
|
+
app.post('/test', async (request) => {
|
|
91
|
+
request.sanitize?.();
|
|
92
|
+
return request.body;
|
|
196
93
|
});
|
|
197
94
|
```
|
|
198
95
|
|
|
199
|
-
##
|
|
200
|
-
|
|
201
|
-
- All options are optional and will use their default values if not specified
|
|
202
|
-
- Custom patterns must be valid RegExp objects
|
|
203
|
-
- When using `allowedKeys` or `deniedKeys`, make sure to include all necessary keys for your application
|
|
204
|
-
- The `customSanitizer` function should be thoroughly tested before use in production
|
|
205
|
-
- String length limiting (`maxLength`) only applies to string values, not keys
|
|
206
|
-
- Array options are applied after all other sanitization steps
|
|
207
|
-
|
|
208
|
-
> removeEmpty: Removes all falsy values ('', 0, false, null, undefined).
|
|
209
|
-
> Adjust this behavior if you need to preserve values like 0 or false.
|
|
210
|
-
|
|
211
|
-
## License
|
|
212
|
-
|
|
213
|
-
**[MIT](https://github.com/ExorTek/fastify-mongo-sanitize/blob/master/LICENSE)**<br>
|
|
96
|
+
## 📜 License
|
|
214
97
|
|
|
215
|
-
|
|
98
|
+
[MIT](../../LICENSE) — Created by **ExorTek**
|
package/package.json
CHANGED
|
@@ -1,62 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@exortek/fastify-mongo-sanitize",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
5
|
-
"main": "index.js",
|
|
3
|
+
"version": "2.0.1",
|
|
4
|
+
"description": "Fastify plugin for NoSQL injection prevention — sanitizes request data",
|
|
5
|
+
"main": "src/index.js",
|
|
6
6
|
"type": "commonjs",
|
|
7
7
|
"types": "types/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./src/index.js",
|
|
11
|
+
"require": "./src/index.js",
|
|
12
|
+
"types": "./types/index.d.ts"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
8
15
|
"scripts": {
|
|
9
|
-
"
|
|
10
|
-
"
|
|
11
|
-
"test:node": "node --test"
|
|
16
|
+
"test": "node --test test/*.test.js",
|
|
17
|
+
"prepublishOnly": "npm test"
|
|
12
18
|
},
|
|
13
19
|
"repository": {
|
|
14
20
|
"type": "git",
|
|
15
|
-
"url": "git+https://github.com/ExorTek/
|
|
21
|
+
"url": "git+https://github.com/ExorTek/nosql-sanitize.git",
|
|
22
|
+
"directory": "packages/fastify"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://github.com/ExorTek/nosql-sanitize/packages/fastify#readme",
|
|
25
|
+
"bugs": {
|
|
26
|
+
"url": "https://github.com/ExorTek/nosql-sanitize/issues"
|
|
16
27
|
},
|
|
17
28
|
"keywords": [
|
|
18
29
|
"fastify",
|
|
19
30
|
"mongodb",
|
|
20
31
|
"sanitize",
|
|
21
|
-
"
|
|
22
|
-
"fastify-plugin",
|
|
23
|
-
"data-validation",
|
|
24
|
-
"input-sanitization",
|
|
32
|
+
"nosql",
|
|
25
33
|
"security",
|
|
26
|
-
"
|
|
27
|
-
"
|
|
28
|
-
"
|
|
29
|
-
"middleware",
|
|
30
|
-
"api-security",
|
|
31
|
-
"query-sanitization",
|
|
32
|
-
"no-sql",
|
|
33
|
-
"fastify-middleware",
|
|
34
|
-
"mongodb-sanitizer"
|
|
34
|
+
"plugin",
|
|
35
|
+
"injection",
|
|
36
|
+
"backend"
|
|
35
37
|
],
|
|
36
38
|
"author": "ExorTek - https://github.com/ExorTek",
|
|
37
39
|
"license": "MIT",
|
|
38
|
-
"
|
|
39
|
-
"
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=18.0.0"
|
|
40
42
|
},
|
|
41
|
-
"homepage": "https://github.com/ExorTek/fastify-mongo-sanitize#readme",
|
|
42
43
|
"publishConfig": {
|
|
43
44
|
"access": "public"
|
|
44
45
|
},
|
|
45
|
-
"packageManager": "yarn@4.9.2",
|
|
46
|
-
"devDependencies": {
|
|
47
|
-
"fastify": "npm:fastify@5.3.3",
|
|
48
|
-
"fastify4": "npm:fastify@4.29.1",
|
|
49
|
-
"prettier": "^3.5.3",
|
|
50
|
-
"tsd": "^0.32.0"
|
|
51
|
-
},
|
|
52
46
|
"dependencies": {
|
|
53
|
-
"
|
|
47
|
+
"@exortek/nosql-sanitize-core": "^2.0.0",
|
|
48
|
+
"fastify-plugin": "^5.1.0"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"fastify": ">=4.0.0"
|
|
52
|
+
},
|
|
53
|
+
"peerDependenciesMeta": {
|
|
54
|
+
"fastify": {
|
|
55
|
+
"optional": false
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
"devDependencies": {
|
|
59
|
+
"fastify": "npm:fastify@5.7.4",
|
|
60
|
+
"fastify4": "npm:fastify@4.29.1"
|
|
54
61
|
},
|
|
55
62
|
"files": [
|
|
56
|
-
"
|
|
57
|
-
"types/
|
|
58
|
-
"
|
|
59
|
-
"
|
|
60
|
-
"FastifyMongoSanitizeError.js"
|
|
63
|
+
"src/",
|
|
64
|
+
"types/",
|
|
65
|
+
"README.md",
|
|
66
|
+
"LICENSE"
|
|
61
67
|
]
|
|
62
68
|
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
const { resolveOptions, handleRequest, shouldSkipRoute, log } = require('@exortek/nosql-sanitize-core');
|
|
5
|
+
|
|
6
|
+
const fastifyMongoSanitize = (fastify, options, done) => {
|
|
7
|
+
const opts = resolveOptions({
|
|
8
|
+
sanitizeObjects: ['body', 'params', 'query'],
|
|
9
|
+
...options,
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
log(opts.debug, 'info', 'PLUGIN', 'Initializing nosql-sanitize plugin', {
|
|
13
|
+
mode: opts.mode,
|
|
14
|
+
sanitizeObjects: [...opts.sanitizeObjects] || opts.sanitizeObjects,
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
if (opts.mode === 'manual') {
|
|
18
|
+
fastify.decorateRequest('sanitize', function (customOpts = {}) {
|
|
19
|
+
const finalOpts = Object.keys(customOpts).length ? resolveOptions({ ...options, ...customOpts }) : opts;
|
|
20
|
+
handleRequest(this, finalOpts);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (opts.mode === 'auto') {
|
|
25
|
+
fastify.addHook('preHandler', (request, reply, done) => {
|
|
26
|
+
if (shouldSkipRoute(request.url, opts.skipRoutes, opts.debug)) {
|
|
27
|
+
return done();
|
|
28
|
+
}
|
|
29
|
+
handleRequest(request, opts);
|
|
30
|
+
done();
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
log(opts.debug, 'info', 'PLUGIN', 'Plugin initialized');
|
|
35
|
+
done();
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
module.exports = fp(fastifyMongoSanitize, {
|
|
39
|
+
name: 'fastify-mongo-sanitize',
|
|
40
|
+
fastify: '>=4.x.x',
|
|
41
|
+
});
|
|
42
|
+
module.exports.default = fastifyMongoSanitize;
|
|
43
|
+
module.exports.fastifyMongoSanitize = fastifyMongoSanitize;
|
package/types/index.d.ts
CHANGED
|
@@ -1,51 +1,54 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
export interface FastifyMongoSanitizeOptions {
|
|
4
|
-
replaceWith?: string;
|
|
5
|
-
removeMatches?: boolean;
|
|
6
|
-
removeKeyMatches?: boolean;
|
|
7
|
-
removeValueMatches?: boolean;
|
|
8
|
-
sanitizeObjects?: string[];
|
|
9
|
-
mode?: 'auto' | 'manual';
|
|
10
|
-
skipRoutes?: string[];
|
|
11
|
-
customSanitizer?: (original: any, options: FastifyMongoSanitizeOptions) => any;
|
|
12
|
-
recursive?: boolean;
|
|
13
|
-
removeEmpty?: boolean;
|
|
14
|
-
patterns?: RegExp[];
|
|
15
|
-
allowedKeys?: string[] | null;
|
|
16
|
-
deniedKeys?: string[] | null;
|
|
17
|
-
stringOptions?: {
|
|
18
|
-
trim?: boolean;
|
|
19
|
-
lowercase?: boolean;
|
|
20
|
-
maxLength?: number | null;
|
|
21
|
-
};
|
|
22
|
-
arrayOptions?: {
|
|
23
|
-
filterNull?: boolean;
|
|
24
|
-
distinct?: boolean;
|
|
25
|
-
};
|
|
26
|
-
debug?: {
|
|
27
|
-
enabled?: boolean;
|
|
28
|
-
level?: 'silent' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
|
|
29
|
-
logPatternMatches?: boolean;
|
|
30
|
-
logSanitizedValues?: boolean;
|
|
31
|
-
logSkippedRoutes?: boolean;
|
|
32
|
-
};
|
|
33
|
-
}
|
|
1
|
+
/// <reference types="node" />
|
|
34
2
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
name: string;
|
|
38
|
-
type: string;
|
|
39
|
-
}
|
|
3
|
+
import { FastifyPluginCallback, FastifyRequest } from 'fastify';
|
|
4
|
+
import { SanitizeOptions, ResolvedOptions, SanitizeEvent } from '@exortek/nosql-sanitize-core';
|
|
40
5
|
|
|
41
|
-
import 'fastify';
|
|
42
6
|
declare module 'fastify' {
|
|
43
7
|
interface FastifyRequest {
|
|
44
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Available when `mode: 'manual'`.
|
|
10
|
+
* Call to sanitize `request.body`, `request.params`, and/or `request.query`.
|
|
11
|
+
* Optionally pass overrides for this specific call.
|
|
12
|
+
*/
|
|
13
|
+
sanitize?: (options?: fastifyMongoSanitize.SanitizeOptions) => void;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
type FastifyMongoSanitize = FastifyPluginCallback<fastifyMongoSanitize.FastifyMongoSanitizeOptions>;
|
|
18
|
+
|
|
19
|
+
declare namespace fastifyMongoSanitize {
|
|
20
|
+
export { SanitizeOptions, ResolvedOptions, SanitizeEvent };
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Fastify-specific options (extends SanitizeOptions).
|
|
24
|
+
* Default `sanitizeObjects`: `['body', 'params', 'query']`
|
|
25
|
+
* (includes `params`, unlike Express).
|
|
26
|
+
*/
|
|
27
|
+
export interface FastifyMongoSanitizeOptions extends SanitizeOptions {
|
|
28
|
+
/**
|
|
29
|
+
* Request fields to sanitize.
|
|
30
|
+
* @default ['body', 'params', 'query']
|
|
31
|
+
*/
|
|
32
|
+
sanitizeObjects?: string[];
|
|
45
33
|
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Fastify plugin for NoSQL injection prevention.
|
|
37
|
+
* Wrapped with `fastify-plugin` — no encapsulation.
|
|
38
|
+
*
|
|
39
|
+
* Uses `preHandler` hook in auto mode.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```js
|
|
43
|
+
* const mongoSanitize = require('@exortek/fastify-mongo-sanitize');
|
|
44
|
+
* fastify.register(mongoSanitize);
|
|
45
|
+
* fastify.register(mongoSanitize, { mode: 'manual', maxDepth: 5 });
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export const fastifyMongoSanitize: FastifyMongoSanitize;
|
|
49
|
+
export { fastifyMongoSanitize as default };
|
|
46
50
|
}
|
|
47
51
|
|
|
48
|
-
declare
|
|
52
|
+
declare function fastifyMongoSanitize(...params: Parameters<FastifyMongoSanitize>): ReturnType<FastifyMongoSanitize>;
|
|
49
53
|
|
|
50
|
-
export
|
|
51
|
-
export { FastifyMongoSanitizeError, fastifyMongoSanitize };
|
|
54
|
+
export = fastifyMongoSanitize;
|
|
@@ -1,18 +0,0 @@
|
|
|
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/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
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/constants.js
DELETED
|
@@ -1,78 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,172 +0,0 @@
|
|
|
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/index.js
DELETED
|
@@ -1,310 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const fp = require('fastify-plugin');
|
|
4
|
-
const {
|
|
5
|
-
isString,
|
|
6
|
-
isArray,
|
|
7
|
-
isPlainObject,
|
|
8
|
-
isPrimitive,
|
|
9
|
-
isDate,
|
|
10
|
-
isEmail,
|
|
11
|
-
cleanUrl,
|
|
12
|
-
startTiming,
|
|
13
|
-
log,
|
|
14
|
-
validateOptions,
|
|
15
|
-
} = require('./helpers');
|
|
16
|
-
const FastifyMongoSanitizeError = require('./FastifyMongoSanitizeError');
|
|
17
|
-
const { DEFAULT_OPTIONS } = require('./constants');
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Sanitizes a string value according to provided options
|
|
21
|
-
* @param {string} str - String to sanitize
|
|
22
|
-
* @param {Object} options - Sanitization options
|
|
23
|
-
* @param {boolean} isValue - Whether string is a value or key
|
|
24
|
-
* @returns {string} Sanitized string
|
|
25
|
-
*/
|
|
26
|
-
const sanitizeString = (str, options, isValue = false) => {
|
|
27
|
-
if (!isString(str) || isEmail(str)) {
|
|
28
|
-
log(options.debug, 'trace', 'STRING', `Skipping sanitization (not string or is email): ${typeof str}`);
|
|
29
|
-
return str;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const { replaceWith, patterns, stringOptions, debug } = options;
|
|
33
|
-
const originalStr = str;
|
|
34
|
-
let matchedPatterns = [];
|
|
35
|
-
|
|
36
|
-
let result = patterns.reduce((acc, pattern, index) => {
|
|
37
|
-
const matches = acc.match(pattern);
|
|
38
|
-
if (matches) {
|
|
39
|
-
matchedPatterns.push({ patternIndex: index, matches: matches.length });
|
|
40
|
-
log(debug, 'debug', 'STRING', `Pattern ${index} matched ${matches.length} times in string`);
|
|
41
|
-
}
|
|
42
|
-
return acc.replace(pattern, replaceWith);
|
|
43
|
-
}, str);
|
|
44
|
-
|
|
45
|
-
if (stringOptions.trim) result = result.trim();
|
|
46
|
-
if (stringOptions.lowercase) result = result.toLowerCase();
|
|
47
|
-
if (stringOptions.maxLength && isValue) result = result.slice(0, stringOptions.maxLength);
|
|
48
|
-
|
|
49
|
-
if (debug.logSanitizedValues && originalStr !== result) {
|
|
50
|
-
log(debug, 'debug', 'STRING', 'String sanitized', {
|
|
51
|
-
original: originalStr,
|
|
52
|
-
sanitized: result,
|
|
53
|
-
matchedPatterns,
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
if (debug.logPatternMatches && matchedPatterns.length > 0) {
|
|
58
|
-
log(debug, 'info', 'PATTERN', `Patterns matched in string`, matchedPatterns);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
return result;
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Sanitizes an array according to provided options
|
|
66
|
-
* @param {Array} arr - Array to sanitize
|
|
67
|
-
* @param {Object} options - Sanitization options
|
|
68
|
-
* @returns {Array} Sanitized array
|
|
69
|
-
* @throws {FastifyMongoSanitizeError} If input is not an array
|
|
70
|
-
*/
|
|
71
|
-
const sanitizeArray = (arr, options) => {
|
|
72
|
-
if (!isArray(arr)) {
|
|
73
|
-
const error = new FastifyMongoSanitizeError('Input must be an array', 'type_error');
|
|
74
|
-
log(options.debug, 'error', 'ARRAY', `Sanitization failed: ${error.message}`);
|
|
75
|
-
throw error;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
const { arrayOptions, debug } = options;
|
|
79
|
-
const originalLength = arr.length;
|
|
80
|
-
|
|
81
|
-
log(debug, 'trace', 'ARRAY', `Sanitizing array with ${originalLength} items`);
|
|
82
|
-
|
|
83
|
-
let result = arr.map((item, index) => {
|
|
84
|
-
log(debug, 'trace', 'ARRAY', `Sanitizing item ${index}`);
|
|
85
|
-
return !options.recursive && (isPlainObject(item) || isArray(item)) ? item : sanitizeValue(item, options);
|
|
86
|
-
});
|
|
87
|
-
|
|
88
|
-
if (arrayOptions.filterNull) {
|
|
89
|
-
const beforeFilter = result.length;
|
|
90
|
-
result = result.filter(Boolean);
|
|
91
|
-
const filtered = beforeFilter - result.length;
|
|
92
|
-
if (filtered > 0) {
|
|
93
|
-
log(debug, 'debug', 'ARRAY', `Filtered ${filtered} null/falsy values`);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
if (arrayOptions.distinct) {
|
|
98
|
-
const beforeDistinct = result.length;
|
|
99
|
-
result = [...new Set(result)];
|
|
100
|
-
const duplicates = beforeDistinct - result.length;
|
|
101
|
-
if (duplicates > 0) {
|
|
102
|
-
log(debug, 'debug', 'ARRAY', `Removed ${duplicates} duplicate values`);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
log(debug, 'trace', 'ARRAY', `Array sanitization completed: ${originalLength} -> ${result.length} items`);
|
|
107
|
-
|
|
108
|
-
return result;
|
|
109
|
-
};
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Sanitizes an object according to provided options
|
|
113
|
-
* @param {Object} obj - Object to sanitize
|
|
114
|
-
* @param {Object} options - Sanitization options
|
|
115
|
-
* @returns {Object} Sanitized object
|
|
116
|
-
* @throws {FastifyMongoSanitizeError} If input is not an object
|
|
117
|
-
*/
|
|
118
|
-
const sanitizeObject = (obj, options) => {
|
|
119
|
-
if (!isPlainObject(obj)) {
|
|
120
|
-
const error = new FastifyMongoSanitizeError('Input must be an object', 'type_error');
|
|
121
|
-
log(options.debug, 'error', 'OBJECT', `Sanitization failed: ${error.message}`);
|
|
122
|
-
throw error;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
const { removeEmpty, allowedKeys, deniedKeys, removeMatches, patterns, debug } = options;
|
|
126
|
-
const originalKeys = Object.keys(obj);
|
|
127
|
-
|
|
128
|
-
log(debug, 'trace', 'OBJECT', `Sanitizing object with ${originalKeys.length} keys`);
|
|
129
|
-
|
|
130
|
-
const result = Object.entries(obj).reduce((acc, [key, value]) => {
|
|
131
|
-
if (allowedKeys && allowedKeys.length && !allowedKeys.includes(key)) {
|
|
132
|
-
log(debug, 'debug', 'OBJECT', `Key '${key}' not in allowedKeys, removing`);
|
|
133
|
-
return acc;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
if (deniedKeys && deniedKeys.length && deniedKeys.includes(key)) {
|
|
137
|
-
log(debug, 'debug', 'OBJECT', `Key '${key}' in deniedKeys, removing`);
|
|
138
|
-
return acc;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
const sanitizedKey = sanitizeString(key, options, false);
|
|
142
|
-
|
|
143
|
-
if (isString(value) && isEmail(value)) {
|
|
144
|
-
log(debug, 'trace', 'OBJECT', `Preserving email value for key '${key}'`);
|
|
145
|
-
acc[sanitizedKey] = value;
|
|
146
|
-
return acc;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
if (
|
|
150
|
-
removeMatches &&
|
|
151
|
-
patterns.some((pattern) => {
|
|
152
|
-
const matches = pattern.test(key);
|
|
153
|
-
if (matches) {
|
|
154
|
-
log(debug, 'debug', 'OBJECT', `Key '${key}' matches removal pattern`);
|
|
155
|
-
}
|
|
156
|
-
return matches;
|
|
157
|
-
})
|
|
158
|
-
) {
|
|
159
|
-
return acc;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
if (removeEmpty && !sanitizedKey) {
|
|
163
|
-
log(debug, 'debug', 'OBJECT', `Empty key removed after sanitization`);
|
|
164
|
-
return acc;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
if (
|
|
168
|
-
removeMatches &&
|
|
169
|
-
isString(value) &&
|
|
170
|
-
patterns.some((pattern) => {
|
|
171
|
-
const matches = pattern.test(value);
|
|
172
|
-
if (matches) {
|
|
173
|
-
log(debug, 'debug', 'OBJECT', `Value for key '${key}' matches removal pattern`);
|
|
174
|
-
}
|
|
175
|
-
return matches;
|
|
176
|
-
})
|
|
177
|
-
) {
|
|
178
|
-
return acc;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
const sanitizedValue =
|
|
182
|
-
!options.recursive && (isPlainObject(value) || isArray(value)) ? value : sanitizeValue(value, options, true);
|
|
183
|
-
|
|
184
|
-
if (removeEmpty && !sanitizedValue) {
|
|
185
|
-
log(debug, 'debug', 'OBJECT', `Empty value removed for key '${key}'`);
|
|
186
|
-
return acc;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
acc[sanitizedKey] = sanitizedValue;
|
|
190
|
-
return acc;
|
|
191
|
-
}, {});
|
|
192
|
-
|
|
193
|
-
const finalKeys = Object.keys(result);
|
|
194
|
-
log(debug, 'trace', 'OBJECT', `Object sanitization completed: ${originalKeys.length} -> ${finalKeys.length} keys`);
|
|
195
|
-
|
|
196
|
-
return result;
|
|
197
|
-
};
|
|
198
|
-
|
|
199
|
-
/**
|
|
200
|
-
* Sanitizes a value according to its type and provided options
|
|
201
|
-
* @param {*} value - Value to sanitize
|
|
202
|
-
* @param {Object} options - Sanitization options
|
|
203
|
-
* @param {boolean} [isValue=false] - Whether value is a value or key
|
|
204
|
-
* @returns {*} Sanitized value
|
|
205
|
-
*/
|
|
206
|
-
const sanitizeValue = (value, options, isValue) => {
|
|
207
|
-
if (value == null || isPrimitive(value) || isDate(value)) return value;
|
|
208
|
-
if (isString(value)) return sanitizeString(value, options, isValue);
|
|
209
|
-
if (isArray(value)) return sanitizeArray(value, options);
|
|
210
|
-
if (isPlainObject(value)) return sanitizeObject(value, options);
|
|
211
|
-
return value;
|
|
212
|
-
};
|
|
213
|
-
|
|
214
|
-
/**
|
|
215
|
-
* Handles request sanitization
|
|
216
|
-
* @param {Object} request - Fastify request object
|
|
217
|
-
* @param {Object} options - Sanitization options
|
|
218
|
-
*/
|
|
219
|
-
const handleRequest = (request, options) => {
|
|
220
|
-
const { sanitizeObjects, customSanitizer, debug } = options;
|
|
221
|
-
const endTiming = startTiming(debug, 'Request Sanitization');
|
|
222
|
-
|
|
223
|
-
log(debug, 'info', 'REQUEST', `Sanitizing request: ${request.method} ${request.url}`);
|
|
224
|
-
|
|
225
|
-
for (const sanitizeObject of sanitizeObjects) {
|
|
226
|
-
if (request[sanitizeObject]) {
|
|
227
|
-
log(debug, 'debug', 'REQUEST', `Sanitizing ${sanitizeObject}`, request[sanitizeObject]);
|
|
228
|
-
|
|
229
|
-
const originalRequest = Object.assign({}, request[sanitizeObject]);
|
|
230
|
-
|
|
231
|
-
if (customSanitizer) {
|
|
232
|
-
log(debug, 'debug', 'REQUEST', `Using custom sanitizer for ${sanitizeObject}`);
|
|
233
|
-
request[sanitizeObject] = customSanitizer(originalRequest);
|
|
234
|
-
} else {
|
|
235
|
-
request[sanitizeObject] = sanitizeValue(originalRequest, options);
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
if (debug.logSanitizedValues) {
|
|
239
|
-
log(debug, 'debug', 'REQUEST', `${sanitizeObject} sanitized`, {
|
|
240
|
-
before: originalRequest,
|
|
241
|
-
after: request[sanitizeObject],
|
|
242
|
-
});
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
endTiming();
|
|
248
|
-
log(debug, 'info', 'REQUEST', `Request sanitization completed`);
|
|
249
|
-
};
|
|
250
|
-
|
|
251
|
-
/**
|
|
252
|
-
* Fastify plugin for MongoDB query sanitization
|
|
253
|
-
* @param {Object} fastify - Fastify instance
|
|
254
|
-
* @param {Object} options - Plugin options
|
|
255
|
-
* @param {Function} done - Callback to signal completion
|
|
256
|
-
*/
|
|
257
|
-
const fastifyMongoSanitize = (fastify, options, done) => {
|
|
258
|
-
const opt = { ...DEFAULT_OPTIONS, ...options };
|
|
259
|
-
|
|
260
|
-
log(opt.debug, 'info', 'PLUGIN', 'Initializing fastify-mongo-sanitize plugin', {
|
|
261
|
-
mode: opt.mode,
|
|
262
|
-
sanitizeObjects: opt.sanitizeObjects,
|
|
263
|
-
skipRoutes: opt.skipRoutes,
|
|
264
|
-
debugLevel: opt.debug.level,
|
|
265
|
-
});
|
|
266
|
-
|
|
267
|
-
validateOptions(opt);
|
|
268
|
-
|
|
269
|
-
const skipRoutes = new Set((opt.skipRoutes || []).map(cleanUrl));
|
|
270
|
-
log(opt.debug, 'debug', 'PLUGIN', `Skip routes configured: ${skipRoutes.size} routes`);
|
|
271
|
-
|
|
272
|
-
if (opt.mode === 'manual') {
|
|
273
|
-
log(opt.debug, 'info', 'PLUGIN', 'Manual mode enabled - decorating request with sanitize method');
|
|
274
|
-
|
|
275
|
-
fastify.decorateRequest('sanitize', function (options = {}) {
|
|
276
|
-
const mergedOptions = { ...opt, ...options };
|
|
277
|
-
log(mergedOptions.debug, 'info', 'MANUAL', 'Manual sanitization triggered');
|
|
278
|
-
handleRequest(this, mergedOptions);
|
|
279
|
-
});
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
if (opt.mode === 'auto') {
|
|
283
|
-
log(opt.debug, 'info', 'PLUGIN', 'Auto mode enabled - adding preHandler hook');
|
|
284
|
-
|
|
285
|
-
fastify.addHook('preHandler', (request, reply, done) => {
|
|
286
|
-
if (skipRoutes.size) {
|
|
287
|
-
const url = cleanUrl(request.url);
|
|
288
|
-
if (skipRoutes.has(url)) {
|
|
289
|
-
if (opt.debug.logSkippedRoutes) {
|
|
290
|
-
log(opt.debug, 'info', 'SKIP', `Route skipped: ${request.method} ${request.url}`);
|
|
291
|
-
}
|
|
292
|
-
return done();
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
handleRequest(request, opt);
|
|
297
|
-
done();
|
|
298
|
-
});
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
log(opt.debug, 'info', 'PLUGIN', 'Plugin initialization completed');
|
|
302
|
-
done();
|
|
303
|
-
};
|
|
304
|
-
|
|
305
|
-
module.exports = fp(fastifyMongoSanitize, {
|
|
306
|
-
name: 'fastify-mongo-sanitize',
|
|
307
|
-
fastify: '>=4.x.x',
|
|
308
|
-
});
|
|
309
|
-
module.exports.default = fastifyMongoSanitize;
|
|
310
|
-
module.exports.fastifyMongoSanitize = fastifyMongoSanitize;
|