js-xss

repository·master·Indexed 26 days ago

https://github.com/leizongmin/js-xss

A high-performance HTML sanitization library designed to prevent Cross-Site Scripting (XSS) attacks by filtering untrusted input against a configurable whitelist. It supports Node.js, browser environments (Shim and AMD), and provides a command-line interface for processing files or running interactive tests. Key features include custom tag and attribute handlers, CSS filtering via the cssfilter module, and the FilterXSS class for reusable configurations.

Tokens
4.7K
Snippets
16
Records
29
Agent score
90%

What's inside js-xss

  1. Use xss in the Browser (Shim and AMD)

    master

    For browser environments, you can use the library via a <script> tag (Shim mode) or via an AMD loader like RequireJS.

    <!-- Shim mode -->
    <script src="https://rawgit.com/leizongmin/js-xss/master/dist/xss.js"></script>
    <script>
      var html = filterXSS('<script>alert("xss");</scr' + 'ipt>');
      alert(html);
    </script>
    
    <!-- AMD mode -->
    <script>
      require.config({
        baseUrl: "./",
        paths: {
          xss: "https://rawgit.com/leizongmin/js-xss/master/dist/xss.js",
        },
        shim: {
          xss: { exports: "filterXSS" },
        },
      });
      require(["xss"], function (xss) {
        var html = xss('<script>alert("xss");</scr' + 'ipt>');
        alert(html);
      });
    </script>
  2. Use xss in the Browser (Shim and AMD modes)

    master

    For browser environments, you can use the Shim pattern (global filterXSS function) or the AMD pattern (using require).

    Note: Do not use https://rawgit.com/leizongmin/js-xss/master/dist/xss.js in production environments.

    <!-- Shim Mode -->
    <script src="https://rawgit.com/leizongmin/js-xss/master/dist/xss.js"></script>
    <script>
      var html = filterXSS('<script>alert("xss");</scr' + 'ipt>');
      alert(html);
    </script>
    
    <!-- AMD Mode -->
    <script>
      require.config({
        baseUrl: "./",
        paths: {
          xss: "https://rawgit.com/leizongmin/js-xss/master/dist/xss.js",
        },
        shim: {
          xss: { exports: "filterXSS" },
        },
      });
      require(["xss"], function (xss) {
        var html = xss('<script>alert("xss");</scr' + 'ipt>');
        alert(html);
      });
    </script>
  3. Configure CSS filtering

    master

    If you allow the style attribute, you can use the css option to provide a whitelist for CSS properties via the cssfilter module. To disable CSS filtering entirely, set css: false.

    var myxss = new xss.FilterXSS({
      css: {
        whiteList: {
          position: /^fixed|relative$/,
          top: true,
          left: true,
        },
      },
    });
  4. Use quick configuration options for stripping tags and comments

    master

    Use these shorthand options to modify how non-whitelisted content is handled:

    • stripIgnoreTag:
      • true: Removes the tag itself but keeps the content inside.
      • false (default): Escapes the tag using the escape function.
    • stripIgnoreTagBody:
      • false|null|undefined (default): No special handling.
      • '*'|true: Removes both the tag and its entire inner content.
      • ['tag1', 'tag2']: Removes both the tag and its content only for specified tags.
    • allowCommentTag:
      • true: Keeps HTML comments.
      • false (default): Automatically removes HTML comments.
  5. Configure the whiteList option

    master

    The whiteList option defines which HTML tags and attributes are permitted. The format is {'tagName': ['attr1', 'attr2']}. Tags and attributes not in this list will be filtered.

    var options = {
      whiteList: {
        a: ["href", "title", "target"],
      },
    };
    // Input: <a href="#" onclick="hello()">大家好</a>
    // Output: <a href="#">大家好</a>
  6. Configure CSS filtering for style attributes

    master
    If the style attribute is allowed in your whitelist, you can control its filtering via the css option. It uses the js-css-filter module. You can either provide a custom whitelist or disable CSS filtering entirely by setting css: false.
  7. Configure Whitelist (whiteList or allowList)

    master

    Define which HTML tags and attributes are permitted. The format is { 'tagName': [ 'attr-1', 'attr-2' ] }. Tags and attributes not in this list will be filtered out.

    var options = {
      whiteList: {
        a: ["href", "title", "target"],
      },
    };
    // Input: <a href="#" onclick="hello()"><i>Hello</i></a>
    // Output: <a href="#">&lt;i&gt;Hello&lt;/i&gt;</a>
  8. Configure Quick Start filtering options

    master

    Use these parameters to quickly change how non-whitelisted content is handled:

    • stripIgnoreTag: If true, tags not in the whitelist are removed. If false (default), they are escaped.
    • stripIgnoreTagBody: If '*' or true, removes the tag AND its content. If an array ['tag1'], only removes the content of specified tags. If false (default), does nothing.
    • allowCommentTag: If false (default), HTML comments are filtered out. If true, they are preserved.
  9. Use xss on Node.js

    master

    In a Node.js environment, require the xss module and call it with the untrusted HTML string to get the sanitized version.

    var xss = require("xss");
    var html = xss('<script>alert("xss");</script>');
    console.log(html);
  10. Extract data like image sources during sanitization

    master

    Use the onTagAttr callback to intercept specific attributes (like src in img tags) during the sanitization process. You can use xss.friendlyAttrValue(value) to convert entities (like &lt;) into printable characters (like <) while collecting the values into a list.

    var source =
      '<img src="img1">a<img src="img2">b<img src="img3">c<img src="img4">d';
    var list = [];
    var html = xss(source, {
      onTagAttr: function (tag, name, value, isWhiteAttr) {
        if (tag === "img" && name === "src") {
          // Use the built-in friendlyAttrValue function to escape attribute
          // values. It supports converting entity tags such as &lt; to printable
          // characters such as <
          list.push(xss.friendlyAttrValue(value));
        }
        // Return nothing, means keep the default handling measure
      },
    });
    
    console.log("image list:\n%s", list.join(", "));
  11. Allow attributes starting with 'data-'

    master

    You can use the onIgnoreTagAttr option to permit custom attributes like data-*. Inside the callback, use xss.escapeAttrValue(value) to ensure the attribute value is safely escaped before returning the reconstructed attribute string.

    var source = '<div a="1" b="2" data-a="3" data-b="4">hello</div>';
    var html = xss(source, {
      onIgnoreTagAttr: function (tag, name, value, isWhiteAttr) {
        if (name.substr(0, 5) === "data-") {
          // Use the built-in escapeAttrValue function to escape the attribute value
          return name + '="' + xss.escapeAttrValue(value) + '"';
        }
      },
    });
    
    console.log("%s\nconvert to:\n%s", source, html);