or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdcore-sanitization.mdhooks.mdindex.mdvalidation-utilities.md
tile.json

core-sanitization.mddocs/

Core Sanitization

Primary sanitization functionality that removes dangerous content while preserving safe HTML, MathML, and SVG elements. DOMPurify's core sanitize function provides multiple output formats and comprehensive XSS protection.

Capabilities

Sanitize Function

The main sanitization function with multiple overloads for different output formats and use cases.

/**
 * Sanitize dirty HTML/XML input and return clean string
 * @param dirty - HTML string or DOM node to sanitize
 * @param cfg - Optional configuration object
 * @returns Clean HTML string
 */
function sanitize(dirty: string | Node, cfg?: Config): string;

/**
 * Sanitize and return DOM node instead of string
 * @param dirty - HTML string or DOM node to sanitize
 * @param cfg - Configuration with RETURN_DOM: true
 * @returns Clean DOM node (HTMLBodyElement or HTMLHtmlElement)
 */
function sanitize(dirty: string | Node, cfg: Config & { RETURN_DOM: true }): Node;

/**
 * Sanitize and return DocumentFragment
 * @param dirty - HTML string or DOM node to sanitize
 * @param cfg - Configuration with RETURN_DOM_FRAGMENT: true
 * @returns Clean DocumentFragment
 */
function sanitize(dirty: string | Node, cfg: Config & { RETURN_DOM_FRAGMENT: true }): DocumentFragment;

/**
 * Sanitize and return TrustedHTML object (when supported)
 * @param dirty - HTML string or DOM node to sanitize
 * @param cfg - Configuration with RETURN_TRUSTED_TYPE: true
 * @returns TrustedHTML object or string fallback
 */
function sanitize(dirty: string | Node, cfg: Config & { RETURN_TRUSTED_TYPE: true }): TrustedHTML;

/**
 * Sanitize a DOM node in-place for maximum performance
 * @param dirty - DOM node to sanitize in-place
 * @param cfg - Configuration with IN_PLACE: true
 * @returns The same node, sanitized in-place
 */
function sanitize(dirty: Node, cfg: Config & { IN_PLACE: true }): Node;

Usage Examples:

import DOMPurify from "dompurify";

// Basic string sanitization
const maliciousHTML = '<img src="x" onerror="alert(1)"><b>Hello</b>';
const clean = DOMPurify.sanitize(maliciousHTML);
// Result: "<b>Hello</b>"

// Return DOM node instead of string
const cleanNode = DOMPurify.sanitize('<p>Safe content</p>', { 
  RETURN_DOM: true 
}) as HTMLElement;
console.log(cleanNode.tagName); // "BODY"

// Return DocumentFragment for inserting into DOM
const fragment = DOMPurify.sanitize('<p>Para 1</p><p>Para 2</p>', { 
  RETURN_DOM_FRAGMENT: true 
});
document.body.appendChild(fragment);

// TrustedHTML support (in compatible browsers)
const trustedHTML = DOMPurify.sanitize('<b>Safe</b>', { 
  RETURN_TRUSTED_TYPE: true 
});

// In-place sanitization for performance
const existingNode = document.getElementById('content');
DOMPurify.sanitize(existingNode, { IN_PLACE: true });

String Input Processing

How DOMPurify handles different types of string input and converts them to DOM structures.

/**
 * String input is parsed into DOM structure before sanitization
 * - HTML strings are parsed as HTML documents
 * - Fragments without root elements are wrapped appropriately
 * - XML/XHTML content is handled based on PARSER_MEDIA_TYPE setting
 * - Empty or invalid input returns empty result
 */

Usage Examples:

// HTML fragment
const htmlFragment = DOMPurify.sanitize('<p>Hello</p><div>World</div>');

// Complete HTML document
const htmlDoc = DOMPurify.sanitize(`
  <!DOCTYPE html>
  <html><head><title>Test</title></head><body><p>Content</p></body></html>
`, { WHOLE_DOCUMENT: true });

// SVG content
const svgContent = DOMPurify.sanitize(`
  <svg xmlns="http://www.w3.org/2000/svg">
    <circle cx="50" cy="50" r="40" fill="blue"/>
  </svg>
`);

// MathML content
const mathContent = DOMPurify.sanitize(`
  <math xmlns="http://www.w3.org/1998/Math/MathML">
    <mi>x</mi><mo>=</mo><mn>42</mn>
  </math>
`);

Node Input Processing

Direct DOM node sanitization for maximum performance when working with existing DOM elements.

/**
 * DOM Node input is processed directly without string parsing
 * - Element nodes are traversed and sanitized recursively
 * - Text nodes are processed for template safety if configured
 * - Document fragments are handled with full DOM structure
 * - Node.cloneNode() is used unless IN_PLACE is true
 */

Usage Examples:

// Sanitize existing DOM element
const dangerousElement = document.createElement('div');
dangerousElement.innerHTML = '<script>alert("xss")</script><p>Safe content</p>';
const cleanElement = DOMPurify.sanitize(dangerousElement);

// In-place sanitization (modifies original node)
const element = document.getElementById('user-content');
DOMPurify.sanitize(element, { IN_PLACE: true });

// Sanitize document fragment
const fragment = document.createDocumentFragment();
const p1 = document.createElement('p');
p1.innerHTML = 'Safe content';
const script = document.createElement('script');
script.textContent = 'alert("xss")';
fragment.appendChild(p1);
fragment.appendChild(script);

const cleanFragment = DOMPurify.sanitize(fragment);
// Script element will be removed, paragraph preserved

Error Handling

How DOMPurify handles various error conditions and invalid input.

/**
 * Error handling behavior:
 * - Invalid HTML is parsed as best-effort by browser's DOMParser
 * - Null or undefined input is converted to empty string
 * - Non-string, non-Node input is converted via toString() if available
 * - Parsing errors result in empty or partial content, not exceptions
 * - Root node violations in IN_PLACE mode throw TypeError
 */

Usage Examples:

// Handles invalid HTML gracefully
const malformed = DOMPurify.sanitize('<div><p>Unclosed tags');
// Browser parser handles malformed HTML

// Empty input handling
const empty1 = DOMPurify.sanitize('');        // Returns ''
const empty2 = DOMPurify.sanitize(null);      // Returns ''
const empty3 = DOMPurify.sanitize(undefined); // Returns ''

// Object with toString method
const obj = { 
  toString: () => '<b>Object content</b>' 
};
const fromObject = DOMPurify.sanitize(obj); // Uses toString()

// IN_PLACE error handling
try {
  const forbiddenNode = document.createElement('script');
  DOMPurify.sanitize(forbiddenNode, { IN_PLACE: true });
} catch (error) {
  console.log('Root node forbidden for in-place sanitization');
}