
Security News
NVD Concedes Inability to Keep Pace with Surging CVE Disclosures in 2025
Security experts warn that recent classification changes obscure the true scope of the NVD backlog as CVE volume hits all-time highs.
Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist. 根据白名单过滤HTML(防止XSS攻击)
The xss npm package is a library designed to sanitize input from users to prevent Cross-Site Scripting (XSS) attacks. It filters input from the user and escapes or removes any potentially malicious scripts, ensuring that the output is safe to display on web pages.
HTML Filtering
This feature allows you to filter out any HTML tags and content that could lead to XSS attacks, leaving only the safe content.
const xss = require('xss');
let html = '<script>alert("xss");</script><div>safe content</div>';
let safeHtml = xss(html);
console.log(safeHtml); // Output: '<div>safe content</div>'
Custom Rule Configuration
This feature allows you to define custom rules for what HTML tags and attributes are allowed, giving you fine-grained control over the sanitization process.
const xss = require('xss');
let options = {
whiteList: {
a: ['href', 'title', 'target'],
p: [],
div: []
},
stripIgnoreTag: true
};
let html = '<a href="http://example.com" onclick="stealCookies()">Link</a>';
let safeHtml = xss(html, options);
console.log(safeHtml); // Output: '<a href="http://example.com">Link</a>'
Escape HTML
This feature provides a method to escape HTML, converting HTML special characters to their corresponding entities, which is useful when you want to display the original HTML code on the web page without rendering it.
const xss = require('xss');
let html = '<div>hello</div>';
let escapedHtml = xss.escapeHtml(html);
console.log(escapedHtml); // Output: '<div>hello</div>'
sanitize-html is another popular HTML sanitization library that allows you to specify allowed tags and attributes. It is similar to xss but offers a different API and additional options for sanitization.
dompurify is a DOM-only XSS sanitizer for HTML, MathML, and SVG. It's different from xss in that it works in the browser and uses the DOM to sanitize input, which can be more effective in some cases.
xss
is a module used to filter input from users to prevent XSS attacks.
(What is XSS attack?)
This module is needed for situations that allows users to input HTML for typesetting or formatting, including fourms, blogs, e-shops, etc.
The xss
module controls the usage of tags and their attributes, according to
the whitelist. It is also extendable with a series of APIs privided, which make
it become more flexible, compares with other modules.
Project Homepage: http://jsxss.com
Try Online: http://jsxss.com/en/try.html
xss()
function from module validator@0.3.7
: 4.4 MB/sFor test code please refer to benchmark
directory.
Run npm test
command in the source directary.
$ npm install xss
$ bower install xss
Or
$ bower install https://github.com/leizongmin/js-xss.git
var xss = require('xss');
var html = xss('<script>alert("xss");</script>');
console.log(html);
Shim mode (reference file test/test.html
):
<script src="https://raw.github.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://raw.github.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>
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
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.
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.
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="#">Hello</a>
For the default whitelist, please refer xss.whiteList
.
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
}
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 tag 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
}
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)
}
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)
}
By specifying the handler function with escapeHtml
. Following is the default
function (Modification is not recommended):
function escapeHtml (html) {
return html.replace(/</g, '<').replace(/>/g, '>');
}
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
}
By using stripIgnoreTag
parameter:
true
filter out tags not in the whitelistfalse
: by default: escape the tag using configured escape
functionExample:
If stripIgnoreTag = true
is set, the following code:
code:<script>alert(/xss/);</script>
would output filtered:
code:alert(/xss/);
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 whitelistExample:
If stripIgnoreTagBody = ['script']
is set, the following code:
code:<script>alert(/xss/);</script>
would output filtered:
code:
By using allowCommentTag
parameter:
true
: do nothingfalse
by default: filter out HTML commentsExample:
If allowCommentTag = false
is set, the following code:
code:<!-- something --> END
would output filtered:
code: END
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>
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:
<x><x-1>he<x-2 checked></x-2>wwww</x-1><a>
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 < 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
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 whilelist
stripIgnoreTagBody: ['script'] // the script tag is a special case, we need
// to filter out its content
});
console.log('text: %s', html);
Result:
text: helloend
Copyright (c) 2012-2015 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.
FAQs
Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist
The npm package xss receives a total of 1,730,440 weekly downloads. As such, xss popularity was classified as popular.
We found that xss demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Security experts warn that recent classification changes obscure the true scope of the NVD backlog as CVE volume hits all-time highs.
Security Fundamentals
Attackers use obfuscation to hide malware in open source packages. Learn how to spot these techniques across npm, PyPI, Maven, and more.
Security News
Join Socket for exclusive networking events, rooftop gatherings, and one-on-one meetings during BSidesSF and RSA 2025 in San Francisco.