js-xss

by leizongmin

leizongmin / js-xss

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

3.7K Stars 495 Forks Last release: Not found Other 380 Commits 45 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:

NPM version build status 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)

For test code please refer to

benchmark
directory.

They are using xss module

  • nodeclub - A Node.js bbs using MongoDB - https://github.com/cnodejs/nodeclub
  • cnpmjs.org - Private npm registry and web for Enterprise - https://github.com/cnpm/cnpmjs.org

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('');
console.log(html);

On Browser

Shim mode (reference file

test/test.html
):

AMD mode - shim:


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

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

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:
// Hello
// would become:
// <i>Hello</i>

For the default whitelist, please refer

xss.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 
  // html is the HTML of this tag, e.g. '' for tag 
  // 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 
  //   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 
  // 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, ">");
}

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 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('');

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:

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:

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

would output filtered:

code: END

Examples

Allow attributes of whitelist tags start with
data-

var source = '
hello
'; 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:

hello
convert to:
hello

Allow tags start with
x-

var source = "hewwww";
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:

hewwww
convert to:
<x>hewwww

Parse images in HTML

var source =
  'abcd';
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 < 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 = "helloend";
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(雷宗民) 
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.

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.