@exortek/fastify-mongo-sanitize
v2.0.2
Published
Fastify plugin for NoSQL injection prevention — sanitizes request data
Maintainers
Readme
@exortek/fastify-mongo-sanitize
Fastify plugin for NoSQL injection prevention. Sanitizes request body, params, and query to protect MongoDB queries from operator injection attacks.
📦 Installation
npm install @exortek/fastify-mongo-sanitizeyarn install @exortek/fastify-mongo-sanitizepnpm install @exortek/fastify-mongo-sanitize⚡ Quick Start
const fastify = require('fastify')();
const mongoSanitize = require('@exortek/fastify-mongo-sanitize');
fastify.register(mongoSanitize);
fastify.post('/login', async (request) => {
// request.body is sanitized — { "$ne": "" } becomes { "ne": "" }
return request.body;
});⚙️ Options
fastify.register(mongoSanitize, {
replaceWith: '', // Replace matched chars with this string
removeMatches: false, // Remove entire key-value pair if pattern matches
sanitizeObjects: ['body', 'params', 'query'], // Fields to sanitize
contentTypes: ['application/json', 'application/x-www-form-urlencoded'],
mode: 'auto', // 'auto' | 'manual'
skipRoutes: [], // Routes to skip (string or RegExp)
recursive: true, // Sanitize nested objects
maxDepth: null, // Max recursion depth (null = unlimited)
onSanitize: ({ key, originalValue, sanitizedValue }) => {
fastify.log.warn(`Sanitized ${key}`);
}
});For the full list of options, see the Core README.
🛠 Features
Manual Mode
If you need fine-grained control over when sanitization occurs:
fastify.register(mongoSanitize, { mode: 'manual' });
fastify.post('/sensitive', async (request) => {
request.sanitize(); // Manually trigger sanitization
return request.body;
});Content-Type Guard
By default, only application/json and application/x-www-form-urlencoded bodies are sanitized. You can customize this:
fastify.register(mongoSanitize, { contentTypes: ['application/json', 'application/graphql'] });TypeScript Support
Full TypeScript support is included out of the box, with request augmentation for the sanitize method:
import fastify from 'fastify';
import mongoSanitize from '@exortek/fastify-mongo-sanitize';
const app = fastify();
app.register(mongoSanitize);
app.post('/test', async (request) => {
request.sanitize?.();
return request.body;
});📜 License
MIT — Created by ExorTek
