zsanitizer
v1.1.2
Published
A robust, zero-dependency sanitizer for Node.js to prevent XSS and other attacks by safely cloning and cleaning input data with customizable rules.
Maintainers
Readme
zsanitizer 🛡️
A robust, zero-dependency sanitizer for Node.js to prevent XSS, path traversal, and other injection attacks by safely cloning and cleaning user input with customizable rules.
zsanitizer ensures that data processed by your application is safe. It deeply traverses objects and arrays, sanitizing strings, handling file-like objects (e.g., from Multer), and preventing common vulnerabilities. It never mutates the original input.
Features
- Deep Sanitization: Recursively sanitizes nested objects and arrays.
- Customizable Rules: Define your own sanitization logic for strings, numbers, and more.
- XSS Protection: Escapes HTML in strings to prevent Cross-Site Scripting.
- Path Traversal Prevention: Sanitizes filenames in file-like objects.
- Safe Cloning: Handles circular references gracefully and removes functions.
- Type Preservation: Correctly handles
Buffer,Date, andRegExpobjects. - Zero Dependencies: Lightweight and secure.
- TypeScript Native: Fully written in TypeScript with types included.
Installation
npm install zsanitizerBasic Usage
The simplest way to use the package is to import the default sanitize function, which uses sensible defaults.
import { sanitize } from "zsanitizer";
const maliciousInput = {
comment: '<script>alert("XSS")</script>',
attachment: {
originalname: '../../../../../etc/passwd',
buffer: Buffer.from('file content'),
},
};
const sanitized = sanitize(maliciousInput);
console.log(sanitized);
/*
{
comment: '<script>alert("XSS")</script>',
attachment: {
originalname: '.._.._.._.._.._etc_passwd',
buffer: <Buffer ...>
}
}
*/Advanced Usage
Defining Custom Sanitization Rules
For ultimate control, you can define your own sanitization logic for specific data types using the customSanitizers option.
Important: When you provide a custom sanitizer for a type (e.g., string), it replaces the built-in logic for that type (like trim and escapeHtml). This allows you to implement any logic you need, such as profanity filtering, custom formatting, or number clamping.
import { createSanitizer } from "zsanitizer";
// Custom rule to replace bad words in strings
const profanityFilter = (value: string): string => {
return value.trim().replace(/darn/gi, "****");
};
// Custom rule to ensure numbers are within a specific range (0-100)
const clampNumber = (value: number): number => {
return Math.max(0, Math.min(100, value));
};
const customSanitizer = createSanitizer({
escapeHtml: false, // Disable default escaping to let our filter run
customSanitizers: {
string: profanityFilter,
number: clampNumber,
},
});
const userInput = {
comment: " Well darn, this is some user input. ",
rating: 150,
score: -10,
age: 30,
};
const sanitized = customSanitizer.sanitize(userInput);
console.log(sanitized);
/*
{
comment: 'Well ****, this is some user input.',
rating: 100,
score: 0,
age: 30
}
*/Express + Multer Example
zsanitizer is perfect for cleaning req.body and req.file in an Express application.
import express from "express";
import multer from "multer";
import { sanitize } from "zsanitizer";
const app = express();
const upload = multer({ storage: multer.memoryStorage() });
// Middleware to sanitize all incoming data
app.use((req, res, next) => {
if (req.body) req.body = sanitize(req.body);
if (req.query) req.query = sanitize(req.query);
if (req.params) req.params = sanitize(req.params);
if (req.file) req.file = sanitize(req.file);
if (req.files) req.files = sanitize(req.files);
next();
});
app.post("/upload", upload.single("document"), (req, res) => {
// req.body and req.file are safely sanitized
res.json({
status: "success",
body: req.body,
file: req.file,
});
});
app.listen(3000, () => console.log("Server running on port 3000"));API Reference
sanitize(input: any): any
The default sanitizer instance with standard options.
createSanitizer(options?: SanitizationOptions): Sanitizer
Creates a new Sanitizer instance with custom options.
SanitizationOptions
| Option | Type | Default | Description |
| ------------------ | -----------------: | :-----: | ------------------------------------------------------------------------------------------------------------------- |
| trim | boolean | true | If true, trims leading/trailing whitespace from strings. (Ignored if a custom string sanitizer is provided.) |
| escapeHtml | boolean | true | If true, escapes HTML special characters. (Ignored if a custom string sanitizer is provided.) |
| allowNull | boolean | false | If false, null values are converted to empty strings (''). If true, null values are preserved. |
| sanitizeFiles | boolean | true | If true, detects and sanitizes file-like objects (e.g., from Multer). |
| maxStringLength | number | 10000 | The maximum allowed length for strings. (Ignored if a custom string sanitizer is provided.) |
| customSanitizers | CustomSanitizers | {} | An object with functions to handle specific types, replacing the default logic. Supported keys: string, number. |
Limitations
- This is not an antivirus. It does not scan file contents for malware.
- It is not a data validation library. It does not check if a string is a valid email or if a number is within a specific range. Use libraries like
zodorjoifor validation.
