Convert Figma logo to code with AI

leizongmin logojs-xss

Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist

5,195
629
5,195
66

Top Related Projects

13,621

DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks. Demo:

Ruby HTML and CSS sanitizer.

Google's common JavaScript library

Clean up user-submitted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis. Built on htmlparser2 for speed and tolerance

Quick Overview

js-xss is a lightweight JavaScript library for filtering and sanitizing HTML to prevent XSS (Cross-Site Scripting) attacks. It provides a flexible and customizable way to clean user-generated content, ensuring that potentially malicious scripts are removed while preserving safe HTML elements and attributes.

Pros

  • Highly customizable with options to whitelist tags, attributes, and CSS properties
  • Lightweight and fast, with no external dependencies
  • Supports both browser and Node.js environments
  • Regularly maintained and updated

Cons

  • May require careful configuration to balance security and functionality
  • Some advanced XSS attack vectors might still bypass the filter if not properly configured
  • Limited built-in support for SVG and MathML elements

Code Examples

  1. Basic usage:
const xss = require('xss');

const html = '<script>alert("xss");</script>';
console.log(xss(html));
// Output: &lt;script&gt;alert("xss");&lt;/script&gt;
  1. Customizing allowed tags and attributes:
const xss = require('xss');

const options = {
  whiteList: {
    a: ['href', 'title'],
    img: ['src', 'alt']
  }
};

const html = '<a href="javascript:alert(1)" onclick="alert(1)">link</a>';
console.log(xss(html, options));
// Output: <a href="#">link</a>
  1. Using a custom whitelist:
const xss = require('xss');

const myXss = new xss.FilterXSS({
  whiteList: {
    p: ['class', 'id'],
    div: ['class'],
    span: []
  }
});

const html = '<div class="safe"><script>alert(1)</script><p>Hello</p></div>';
console.log(myXss.process(html));
// Output: <div class="safe">&lt;script&gt;alert(1)&lt;/script&gt;<p>Hello</p></div>

Getting Started

To use js-xss in your project, follow these steps:

  1. Install the package:

    npm install xss
    
  2. Import and use in your code:

    const xss = require('xss');
    
    const cleanHtml = xss('<script>alert("xss");</script>');
    console.log(cleanHtml);
    

For more advanced usage and configuration options, refer to the project's documentation on GitHub.

Competitor Comparisons

13,621

DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks. Demo:

Pros of DOMPurify

  • More comprehensive security coverage, including protection against DOM-based XSS attacks
  • Actively maintained with frequent updates and security patches
  • Supports a wider range of browsers and environments

Cons of DOMPurify

  • Larger file size, which may impact performance in some applications
  • More complex configuration options, potentially requiring a steeper learning curve

Code Comparison

DOMPurify:

import DOMPurify from 'dompurify';

const clean = DOMPurify.sanitize(dirty);

js-xss:

var xss = require("xss");

var html = xss('<script>alert("xss");</script>');

Key Differences

  • DOMPurify focuses on DOM-based sanitization, while js-xss primarily handles string-based sanitization
  • DOMPurify offers more flexibility in handling different types of content (HTML, SVG, MathML)
  • js-xss provides a simpler API and is more lightweight, making it easier to integrate into smaller projects

Use Cases

  • DOMPurify: Ideal for complex web applications with diverse content types and higher security requirements
  • js-xss: Better suited for simpler applications or when a lightweight solution is preferred

Community and Support

  • DOMPurify has a larger community and more frequent updates
  • js-xss has a stable codebase but less frequent updates

Both libraries are valuable tools for preventing XSS attacks, with the choice depending on specific project requirements and complexity.

Ruby HTML and CSS sanitizer.

Pros of Sanitize

  • Written in Ruby, offering native integration for Ruby-based projects
  • Provides more granular control over allowed elements and attributes
  • Supports custom transformers for advanced sanitization needs

Cons of Sanitize

  • Limited to Ruby ecosystem, not suitable for JavaScript-based applications
  • May have a steeper learning curve due to more configuration options
  • Less frequent updates and maintenance compared to js-xss

Code Comparison

js-xss:

const xss = require('xss');
const html = xss('<script>alert("xss");</script>');
console.log(html);

Sanitize:

require 'sanitize'

html = Sanitize.fragment('<script>alert("xss");</script>')
puts html

Key Differences

  • js-xss is JavaScript-based, while Sanitize is Ruby-based
  • js-xss offers a simpler API with fewer configuration options
  • Sanitize provides more fine-grained control over sanitization rules
  • js-xss has more recent updates and active maintenance
  • Sanitize has been around longer and is well-established in the Ruby community

Both libraries effectively sanitize HTML input to prevent XSS attacks, but their suitability depends on the project's programming language and specific requirements for customization and control over the sanitization process.

Google's common JavaScript library

Pros of closure-library

  • Comprehensive JavaScript library with a wide range of utilities and components
  • Robust and well-tested, backed by Google's engineering resources
  • Supports advanced optimization techniques for better performance

Cons of closure-library

  • Larger footprint and potentially steeper learning curve
  • May be overkill for projects only needing XSS protection
  • Less focused on XSS prevention specifically

Code Comparison

js-xss:

var xss = require("xss");
var html = xss('<script>alert("xss");</script>');
console.log(html);

closure-library:

goog.require('goog.string.html.HtmlSanitizer');
var sanitizer = new goog.string.html.HtmlSanitizer();
var html = sanitizer.sanitize('<script>alert("xss");</script>');
console.log(html);

Key Differences

  • js-xss is specifically designed for XSS prevention, while closure-library offers a broader set of tools
  • js-xss has a simpler API and is easier to integrate for basic XSS protection needs
  • closure-library provides more advanced features and optimizations but requires more setup and configuration

Use Cases

  • Choose js-xss for lightweight, focused XSS protection in smaller projects
  • Opt for closure-library when building large-scale applications that can benefit from its comprehensive feature set and optimization capabilities

Clean up user-submitted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis. Built on htmlparser2 for speed and tolerance

Pros of sanitize-html

  • More comprehensive configuration options for fine-tuning allowed tags and attributes
  • Better support for custom tag and attribute handling
  • Actively maintained with regular updates and bug fixes

Cons of sanitize-html

  • Slightly larger package size compared to js-xss
  • May have a steeper learning curve due to more configuration options

Code Comparison

sanitize-html:

const sanitizeHtml = require('sanitize-html');
const dirty = '<script>alert("xss")</script><p>Hello world!</p>';
const clean = sanitizeHtml(dirty, {
  allowedTags: ['p']
});

js-xss:

const xss = require('xss');
const dirty = '<script>alert("xss")</script><p>Hello world!</p>';
const clean = xss(dirty);

Both libraries effectively sanitize HTML input, but sanitize-html offers more granular control over allowed tags and attributes. js-xss provides a simpler API with fewer configuration options out of the box. sanitize-html is better suited for projects requiring detailed customization of sanitization rules, while js-xss may be preferable for simpler use cases or when a smaller package size is crucial.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

NPM version Node.js CI Test coverage David deps node version npm download npm license

Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist.

Greenkeeper badge

xss


xss is a module used to filter input from users to prevent XSS attacks. (What is XSS attack?)

Project Homepage: http://jsxss.com

Try Online: http://jsxss.com/en/try.html

中文版文档


Features

  • Specifies HTML tags and their attributes allowed with whitelist
  • Handle any tags or attributes using custom function.

Reference

Benchmark (for references only)

  • the xss module: 22.53 MB/s
  • xss() function from module validator@0.3.7: 6.9 MB/s

For test code please refer to benchmark directory.

They are using xss module

Install

NPM

npm install xss

Bower

bower install xss

Or

bower install https://github.com/leizongmin/js-xss.git

Usages

On Node.js

var xss = require("xss");
var html = xss('<script>alert("xss");</script>');
console.log(html);

On Browser

Shim mode (reference file test/test.html):

<script src="https://rawgit.com/leizongmin/js-xss/master/dist/xss.js"></script>
<script>
  // apply function filterXSS in the same way
  var html = filterXSS('<script>alert("xss");</scr' + "ipt>");
  alert(html);
</script>

AMD mode - shim:

<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>

Notes: please don't use the URL https://rawgit.com/leizongmin/js-xss/master/dist/xss.js in production environment.

Command Line Tool

Process File

You can use the xss command line tool to process a file. Usage:

xss -i <input_file> -o <output_file>

Example:

xss -i origin.html -o target.html

Active Test

Run the following command, them you can type HTML code in the command-line, and check the filtered output:

xss -t

For more details, please run $ xss -h to see it.

Custom filter rules

When using the xss() function, the second parameter could be used to specify custom rules:

options = {}; // Custom rules
html = xss('<script>alert("xss");</script>', options);

To avoid passing options every time, you can also do it in a faster way by creating a FilterXSS instance:

options = {}; // Custom rules
myxss = new xss.FilterXSS(options);
// then apply myxss.process()
html = myxss.process('<script>alert("xss");</script>');

Details of parameters in options would be described below.

Whitelist

By specifying a whiteList, e.g. { 'tagName': [ 'attr-1', 'attr-2' ] }. Tags and attributes not in the whitelist would be filter out. For example:

// only tag a and its attributes href, title, target are allowed
var options = {
  whiteList: {
    a: ["href", "title", "target"],
  },
};
// With the configuration specified above, the following HTML:
// <a href="#" onclick="hello()"><i>Hello</i></a>
// would become:
// <a href="#">&lt;i&gt;Hello&lt;/i&gt;</a>

For the default whitelist, please refer xss.whiteList.

allowList is also supported, and has the same function as whiteList.

Customize the handler function for matched tags

By specifying the handler function with onTag:

function onTag(tag, html, options) {
  // tag is the name of current tag, e.g. 'a' for tag <a>
  // html is the HTML of this tag, e.g. '<a>' for tag <a>
  // options is some addition informations:
  //   isWhite    boolean, whether the tag is in whitelist
  //   isClosing  boolean, whether the tag is a closing tag, e.g. true for </a>
  //   position        integer, the position of the tag in output result
  //   sourcePosition  integer, the position of the tag in input HTML source
  // If a string is returned, the current tag would be replaced with the string
  // If return nothing, the default measure would be taken:
  //   If in whitelist: filter attributes using onTagAttr, as described below
  //   If not in whitelist: handle by onIgnoreTag, as described below
}

Customize the handler function for attributes of matched tags

By specifying the handler function with onTagAttr:

function onTagAttr(tag, name, value, isWhiteAttr) {
  // tag is the name of current tag, e.g. 'a' for tag <a>
  // name is the name of current attribute, e.g. 'href' for href="#"
  // isWhiteAttr whether the attribute is in whitelist
  // If a string is returned, the attribute would be replaced with the string
  // If return nothing, the default measure would be taken:
  //   If in whitelist: filter the value using safeAttrValue as described below
  //   If not in whitelist: handle by onIgnoreTagAttr, as described below
}

Customize the handler function for tags not in the whitelist

By specifying the handler function with onIgnoreTag:

function onIgnoreTag(tag, html, options) {
  // Parameters are the same with onTag
  // If a string is returned, the tag would be replaced with the string
  // If return nothing, the default measure would be taken (specifies using
  // escape, as described below)
}

Customize the handler function for attributes not in the whitelist

By specifying the handler function with onIgnoreTagAttr:

function onIgnoreTagAttr(tag, name, value, isWhiteAttr) {
  // Parameters are the same with onTagAttr
  // If a string is returned, the value would be replaced with this string
  // If return nothing, then keep default (remove the attribute)
}

Customize escaping function for HTML

By specifying the handler function with escapeHtml. Following is the default function (Modification is not recommended):

function escapeHtml(html) {
  return html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

Customize escaping function for value of attributes

By specifying the handler function with safeAttrValue:

function safeAttrValue(tag, name, value) {
  // Parameters are the same with onTagAttr (without options)
  // Return the value as a string
}

Customize output attribute value syntax for HTML

By specifying a singleQuotedAttributeValue. Use true for '. Otherwise default " will be used

var options = {
  singleQuotedAttributeValue: true,
};
// With the configuration specified above, the following HTML:
// <a href="#">Hello</a>
// would become:
// <a href='#'>Hello</a>

Customize CSS filter

If you allow the attribute style, the value will be processed by cssfilter module. The cssfilter module includes a default css whitelist. You can specify the options for cssfilter module like this:

myxss = new xss.FilterXSS({
  css: {
    whiteList: {
      position: /^fixed|relative$/,
      top: true,
      left: true,
    },
  },
});
html = myxss.process('<script>alert("xss");</script>');

If you don't want to filter out the style content, just specify false to the css option:

myxss = new xss.FilterXSS({
  css: false,
});

For more help, please see https://github.com/leizongmin/js-css-filter

Quick Start

Filter out tags not in the whitelist

By using stripIgnoreTag parameter:

  • true filter out tags not in the whitelist
  • false: by default: escape the tag using configured escape function

Example:

If stripIgnoreTag = true is set, the following code:

code:
<script>
  alert(/xss/);
</script>

would output filtered:

code:alert(/xss/);

Filter out tags and tag bodies not in the whitelist

By using stripIgnoreTagBody parameter:

  • false|null|undefined by default: do nothing
  • '*'|true: filter out all tags not in the whitelist
  • ['tag1', 'tag2']: filter out only specified tags not in the whitelist

Example:

If stripIgnoreTagBody = ['script'] is set, the following code:

code:
<script>
  alert(/xss/);
</script>

would output filtered:

code:

Filter out HTML comments

By using allowCommentTag parameter:

  • true: do nothing
  • false by default: filter out HTML comments

Example:

If allowCommentTag = false is set, the following code:

code:<!-- something -->
END

would output filtered:

code: END

Examples

Allow attributes of whitelist tags start with data-

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-") {
      // escape its value using built-in escapeAttrValue function
      return name + '="' + xss.escapeAttrValue(value) + '"';
    }
  },
});

console.log("%s\nconvert to:\n%s", source, html);

Result:

<div a="1" b="2" data-a="3" data-b="4">hello</div>
convert to:
<div data-a="3" data-b="4">hello</div>

Allow tags start with x-

var source = "<x><x-1>he<x-2 checked></x-2>wwww</x-1><a>";
var html = xss(source, {
  onIgnoreTag: function (tag, html, options) {
    if (tag.substr(0, 2) === "x-") {
      // do not filter its attributes
      return html;
    }
  },
});

console.log("%s\nconvert to:\n%s", source, html);

Result:

<x
  ><x-1>he<x-2 checked></x-2>wwww</x-1
  ><a>
    convert to: &lt;x&gt;<x-1>he<x-2 checked></x-2>wwww</x-1><a></a></a
></x>

Parse images in HTML

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(", "));

Result:

image list: img1, img2, img3, img4

Filter out HTML tags (keeps only plain text)

var source = "<strong>hello</strong><script>alert(/xss/);</script>end";
var html = xss(source, {
  whiteList: {}, // empty, means filter out all tags
  stripIgnoreTag: true, // filter out all HTML not in the whitelist
  stripIgnoreTagBody: ["script"], // the script tag is a special case, we need
  // to filter out its content
});

console.log("text: %s", html);

Result:

text: helloend

License

Copyright (c) 2012-2018 Zongmin Lei(雷宗民) <leizongmin@gmail.com>
http://ucdok.com

The MIT License

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

NPM DownloadsLast 30 Days