@ordojs/security
Version:
Security package for OrdoJS with XSS, CSRF, and injection protection
89 lines • 2.85 kB
JavaScript
import createDOMPurify from 'dompurify';
import { JSDOM } from 'jsdom';
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);
/**
* Default sanitizer options with safe defaults
*/
const DEFAULT_OPTIONS = {
allowedTags: ['a', 'b', 'br', 'code', 'div', 'em', 'i', 'li', 'ol', 'p', 'pre', 'span', 'strong', 'ul'],
allowedAttributes: ['href', 'target', 'class', 'id', 'style'],
allowDataAttributes: false,
stripAllTags: false,
};
/**
* HTML Sanitizer class for preventing XSS attacks
* Uses DOMPurify under the hood with configurable options
*/
export class HtmlSanitizer {
options;
/**
* Create a new HtmlSanitizer instance
* @param options Sanitizer configuration options
*/
constructor(options = {}) {
this.options = { ...DEFAULT_OPTIONS, ...options };
}
/**
* Sanitize HTML content to prevent XSS attacks
* @param html HTML content to sanitize
* @returns Sanitized HTML
*/
sanitize(html) {
if (this.options.stripAllTags) {
return DOMPurify.sanitize(html, { ALLOWED_TAGS: [] });
}
const config = {
ALLOWED_TAGS: this.options.allowedTags,
ALLOW_DATA_ATTR: this.options.allowDataAttributes,
};
// Handle allowedAttributes which can be string[] or Record<string, string[]>
if (Array.isArray(this.options.allowedAttributes)) {
config.ALLOWED_ATTR = this.options.allowedAttributes;
}
else if (this.options.allowedAttributes) {
config.ALLOWED_ATTR = this.options.allowedAttributes;
}
return DOMPurify.sanitize(html, config);
}
/**
* Update sanitizer options
* @param options New sanitizer options
*/
updateOptions(options) {
this.options = { ...this.options, ...options };
}
/**
* Create a sanitizer with strict settings (minimal allowed tags)
* @returns A new HtmlSanitizer instance with strict settings
*/
static createStrict() {
return new HtmlSanitizer({
allowedTags: ['b', 'em', 'i', 'strong', 'span'],
allowedAttributes: ['class'],
allowDataAttributes: false,
});
}
/**
* Create a sanitizer that strips all HTML tags
* @returns A new HtmlSanitizer instance that strips all HTML
*/
static createTextOnly() {
return new HtmlSanitizer({
stripAllTags: true,
});
}
}
/**
* Create a default HTML sanitizer instance
*/
export const defaultSanitizer = new HtmlSanitizer();
/**
* Sanitize HTML content using the default sanitizer
* @param html HTML content to sanitize
* @returns Sanitized HTML
*/
export function sanitizeHtml(html) {
return defaultSanitizer.sanitize(html);
}
//# sourceMappingURL=html-sanitizer.js.map