DOMPurify

repository·main·Indexed 12 days ago

https://github.com/cure53/dompurify

A high-performance, DOM-only XSS sanitizer for HTML, MathML, and SVG. Version 3.4.13. It prevents cross-site scripting attacks by cleaning untrusted markup and works in all modern browsers and Node.js (via jsdom). Features include customizable configuration via ALLOWED_TAGS and KEEP_CONTENT, lifecycle hooks for extending functionality, and support for the Trusted Types API.

Tokens
13.2K
Snippets
33
Records
49
Agent score
97%

What's inside DOMPurify

  1. What is DOMPurify and what does it do?

    main
    DOMPurify is a fast, DOM-only XSS sanitizer for HTML, MathML, and SVG. It takes 'dirty' HTML strings containing potentially malicious code and returns 'clean' HTML by stripping out dangerous elements and attributes. It is designed to prevent XSS (Cross-Site Scripting) attacks while being highly tolerant of valid markup.
  2. Use DOMPurify hooks to extend functionality

    main

    Hooks allow you to execute custom logic at specific stages of the DOMPurify lifecycle. You can add a hook using DOMPurify.addHook(hookName, callback) and remove it using DOMPurify.removeHook(hookName).

    Common hook names mentioned in demos include:

    • beforeSanitizeAttributes: Triggered before attributes are sanitized.
    • afterSanitizeAttributes: Triggered after attributes are sanitized.
    • uponSanitizeElement: Triggered when an element is being sanitized.
    • uponSanitizeAttribute: Triggered when an attribute is being sanitized.
    // Add a hook to convert all text to capitals
    DOMPurify.addHook('beforeSanitizeAttributes', function (node) {
      // Set text node content to uppercase
      if (node.nodeName && node.nodeName === '#text') {
        node.textContent = node.textContent.toUpperCase();
      }
    });
    
    // Clean HTML string and write into our DIV
    const clean = DOMPurify.sanitize(dirty);
    
    // now let's remove the hook again
    DOMPurify.removeHook('beforeSanitizeAttributes');
  3. Security Warning: Avoid post-sanitization modification

    main

    A critical security rule: Do not modify the HTML after it has been sanitized.

    If you sanitize a string and then perform further manipulations (like using other libraries to change the DOM or manually editing the string), you may inadvertently re-introduce XSS vulnerabilities. Always ensure that any library receiving sanitized markup does not modify the structure in a way that bypasses the security checks.

  4. Automate Trusted Types enforcement with DOMFortify

    main
    If you want to apply a Trusted Types default policy across an entire page automatically (sanitizing all HTML sinks like innerHTML including third-party code), use DOMFortify. While DOMPurify is a focused sanitizer, DOMFortify acts as the document-wide enforcement layer.
  5. Install and use DOMPurify in the browser

    main

    You can include DOMPurify directly in your website using <script> tags.

    For development (includes source maps):

    <script type="text/javascript" src="dist/purify.js"></script>

    For production (minified):

    <script type="text/javascript" src="dist/purify.min.js"></script>

    Once included, use DOMPurify.sanitize(dirty) to clean your HTML strings.

    <script type="text/javascript" src="dist/purify.min.js"></script>
    <script>
      const clean = DOMPurify.sanitize(dirty);
    </script>
  6. Use isomorphic-dompurify for easier server/client compatibility

    main

    If you encounter difficulties setting up DOMPurify in an isomorphic (universal) environment, the isomorphic-dompurify package provides a simplified wrapper that works in both Node.js and the browser.

    npm install isomorphic-dompurify
    import DOMPurify from 'isomorphic-dompurify';
    
    const clean = DOMPurify.sanitize('<s>hello</s>');
  7. Run DOMPurify on the server with Node.js and jsdom

    main

    To run DOMPurify in a Node.js environment, you must provide a DOM implementation. The recommended tool is jsdom.

    Warning: Avoid using happy-dom as it is not considered safe for sanitization and may lead to XSS. Always use a recent version of jsdom to avoid known vulnerabilities in older versions.

    1. Install dependencies:
    npm install dompurify jsdom
    1. Initialize DOMPurify with a jsdom window:
    import { JSDOM } from 'jsdom';
    import DOMPurify from 'dompurify';
    
    const window = new JSDOM('').window;
    const purify = DOMPurify(window);
    const clean = purify.sanitize('<b>hello there</b>');
  8. Install and use DOMPurify with npm/ESM

    main

    For modern JavaScript environments (like Angular or React), install the package via npm and import it directly.

    npm install dompurify
    import DOMPurify from 'dompurify';
    
    const clean = DOMPurify.sanitize('<b>hello there</b>');
  9. Use DOMPurify inside a custom Trusted Types policy

    main

    When creating your own Trusted Types policy, you must configure DOMPurify to avoid circularity and type mismatches:

    1. Avoid Type Mismatches: Since createHTML expects a plain string, you must set RETURN_TRUSTED_TYPE: false when calling DOMPurify.sanitize inside your policy.
    2. Avoid Policy Creation Errors: To prevent DOMPurify from trying to create its own dompurify policy (which might be blocked by your CSP), set TRUSTED_TYPES_POLICY: null.

    Warning: Do not pass your own policy object into DOMPurify via setConfig({ TRUSTED_TYPES_POLICY: myPolicy }) if that policy calls DOMPurify.sanitize. This creates infinite recursion, and DOMPurify will throw a TypeError to prevent it.

    // Example: Creating a custom policy that uses DOMPurify
    window.trustedTypes.createPolicy('my-organization', {
      createHTML: (input) =>
        DOMPurify.sanitize(input, { 
          RETURN_TRUSTED_TYPE: false, 
          TRUSTED_TYPES_POLICY: null 
        }),
    });
  10. Run DOMPurify local tests

    main

    If you are contributing to the project or running it in a development environment, you can execute the test suite using npm scripts. The project uses Playwright for browser testing and jsdom for headless testing.

    npm run test
  11. Subscribe to DOMPurify security updates

    main

    To receive notifications regarding security-critical releases (such as fixes for discovered bypasses), you can subscribe to the DOMPurify security mailing list. Note that feature releases are not announced here.

    https://lists.ruhr-uni-bochum.de/mailman/listinfo/dompurify-security
  12. Use Trusted Types with DOMPurify

    main

    If your environment supports Trusted Types, DOMPurify can integrate with them.

    1. Internal Policy: DOMPurify creates its own internal policy to sign sanitized HTML.
    2. Custom Policy: You can provide your own TRUSTED_TYPES_POLICY in the configuration. This policy must implement both createHTML and createScriptURL hooks.
    3. Return Type: Setting RETURN_TRUSTED_TYPE: true will cause sanitize() to return a TrustedHTML object instead of a plain string.

    Warning: A configured TRUSTED_TYPES_POLICY callback must not call DOMPurify.sanitize, as this will cause infinite recursion.