@exortek/fastify-mongo-sanitize 1.2.0 → 2.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/README.md +57 -174
- package/package.json +41 -33
- package/src/index.js +43 -0
- package/types/index.d.ts +46 -43
- package/LICENSE +0 -21
- 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,59 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@exortek/fastify-mongo-sanitize",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
5
|
-
"main": "index.js",
|
|
3
|
+
"version": "2.0.0",
|
|
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
|
+
"require": "./src/index.js",
|
|
11
|
+
"types": "./types/index.d.ts"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
8
14
|
"scripts": {
|
|
9
|
-
"
|
|
10
|
-
"
|
|
11
|
-
"test:node": "node --test"
|
|
15
|
+
"test": "node --test test/*.test.js",
|
|
16
|
+
"prepublishOnly": "npm test"
|
|
12
17
|
},
|
|
13
18
|
"repository": {
|
|
14
19
|
"type": "git",
|
|
15
|
-
"url": "git+https://github.com/ExorTek/
|
|
20
|
+
"url": "git+https://github.com/ExorTek/nosql-sanitize.git",
|
|
21
|
+
"directory": "packages/fastify"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://github.com/ExorTek/nosql-sanitize/tree/main/packages/fastify#readme",
|
|
24
|
+
"bugs": {
|
|
25
|
+
"url": "https://github.com/ExorTek/nosql-sanitize/issues"
|
|
16
26
|
},
|
|
17
27
|
"keywords": [
|
|
18
28
|
"fastify",
|
|
19
29
|
"mongodb",
|
|
20
30
|
"sanitize",
|
|
21
|
-
"
|
|
22
|
-
"fastify-plugin",
|
|
23
|
-
"data-validation",
|
|
24
|
-
"input-sanitization",
|
|
31
|
+
"nosql",
|
|
25
32
|
"security",
|
|
26
|
-
"
|
|
27
|
-
"
|
|
28
|
-
"
|
|
29
|
-
"middleware",
|
|
30
|
-
"api-security",
|
|
31
|
-
"query-sanitization",
|
|
32
|
-
"no-sql",
|
|
33
|
-
"fastify-middleware",
|
|
34
|
-
"mongodb-sanitizer"
|
|
33
|
+
"plugin",
|
|
34
|
+
"injection",
|
|
35
|
+
"backend"
|
|
35
36
|
],
|
|
36
37
|
"author": "ExorTek - https://github.com/ExorTek",
|
|
37
38
|
"license": "MIT",
|
|
38
|
-
"
|
|
39
|
-
"
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=18.0.0"
|
|
40
41
|
},
|
|
41
|
-
"homepage": "https://github.com/ExorTek/fastify-mongo-sanitize#readme",
|
|
42
42
|
"publishConfig": {
|
|
43
43
|
"access": "public"
|
|
44
44
|
},
|
|
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
45
|
"dependencies": {
|
|
53
|
-
"
|
|
46
|
+
"@exortek/nosql-sanitize-core": "^2.0.0",
|
|
47
|
+
"fastify-plugin": "^5.1.0"
|
|
48
|
+
},
|
|
49
|
+
"peerDependencies": {
|
|
50
|
+
"fastify": ">=4.0.0"
|
|
51
|
+
},
|
|
52
|
+
"peerDependenciesMeta": {
|
|
53
|
+
"fastify": {
|
|
54
|
+
"optional": false
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"fastify": "npm:fastify@5.7.4",
|
|
59
|
+
"fastify4": "npm:fastify@4.29.1"
|
|
54
60
|
},
|
|
55
61
|
"files": [
|
|
56
|
-
"
|
|
57
|
-
"types/
|
|
62
|
+
"src/",
|
|
63
|
+
"types/",
|
|
64
|
+
"README.md",
|
|
65
|
+
"LICENSE"
|
|
58
66
|
]
|
|
59
67
|
}
|
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;
|
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/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;
|