scorpion4dev-express-autosanitizer
Version:
automatic sanitization of req body fields, params and query. automatically does sanitization and escaping as middleware.
60 lines (47 loc) • 1.69 kB
Markdown
## Installation
```
npm i --save scorpion4dev-express-autosanitizer
```
## Usage
Import the module with this declaration at the top of the file:
```javascript
const sanitizer = require('scorpion4dev-express-autosanitizer')
```
Mount the middleware
```javascript
const options = {
body: Boolean, // default is true
params: Boolean, // default is true
query: Boolean, // default is true
cookies: Boolean, // default is false
headers: Boolean, // default is false
escapeHtml: Boolean, // default is false
replaceOriginal: Boolean, // will replace the dangerous input
replaceCustomValue: Object, // will replace input string with custom value
sanitizerFunction: Function // use your personnal sanitizing algorithm
}
app.use(sanitizer(options))
```
**Note:** if you use the body option, make sure you mount the sanitizer between the [body-parser](https://www.npmjs.com/package/body-parser)/[cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware and your routes declaration.
## Output
After the middleware has processed the input, the original version will be stored in the original place and the safe version will be stored in ```req.sanitized```.
```javascript
app.get('/', (req, res) => {
console.log(req.sanitized.query.exampleParam) // safe and sanitized
console.log(req.query.exampleParam) // potentially dangerous
})
```
Example for the replaceCustomValue option
```javascript
...
const options = {
replaceCustomValue: {
'$null': null
}
}
...
app.get('/', (req, res) => {
console.log(req.query.exampleParam) // assume the output is "$null"
console.log(req.sanitized.query.exampleParam) // output will be replace by null
})
```