Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
sanitize-html
Advanced tools
Clean up user-submitted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis
The sanitize-html npm package is designed to clean up user-submitted HTML, preventing XSS attacks by sanitizing any HTML code input by users. It allows developers to specify a whitelist of HTML tags and attributes that are allowed, and it will strip out all other tags and attributes that are not explicitly allowed.
Sanitizing HTML
This feature allows you to remove any unwanted HTML tags and content that could lead to XSS attacks, leaving only the content that is deemed safe according to the specified rules.
const sanitizeHtml = require('sanitize-html');
const dirtyHtml = '<script>alert("XSS");</script><p>Valid content</p>';
const cleanHtml = sanitizeHtml(dirtyHtml);
console.log(cleanHtml); // Output: '<p>Valid content</p>'
Allowing a set of HTML tags
This feature lets you specify which HTML tags are allowed in the sanitized output, effectively filtering out all other tags that are not part of the whitelist.
const sanitizeHtml = require('sanitize-html');
const dirtyHtml = '<div><p>Some text</p><script>Bad script</script></div>';
const cleanHtml = sanitizeHtml(dirtyHtml, {
allowedTags: ['div', 'p']
});
console.log(cleanHtml); // Output: '<div><p>Some text</p></div>'
Configuring allowed attributes for tags
This feature allows you to configure which attributes are allowed for specific tags, providing fine-grained control over the sanitization process.
const sanitizeHtml = require('sanitize-html');
const dirtyHtml = '<a href="http://example.com" onclick="stealCookies()">Link</a>';
const cleanHtml = sanitizeHtml(dirtyHtml, {
allowedTags: ['a'],
allowedAttributes: {
'a': ['href']
}
});
console.log(cleanHtml); // Output: '<a href="http://example.com">Link</a>'
Transforming tags and attributes
This feature enables you to transform certain tags into other tags, or modify their attributes during the sanitization process.
const sanitizeHtml = require('sanitize-html');
const dirtyHtml = '<b>bold text</b>';
const cleanHtml = sanitizeHtml(dirtyHtml, {
transformTags: {
'b': sanitizeHtml.simpleTransform('strong')
}
});
console.log(cleanHtml); // Output: '<strong>bold text</strong>'
DOMPurify is a DOM-only XSS sanitizer for HTML, MathML, and SVG. It's similar to sanitize-html but works in a browser environment as well as server-side. It's also known for its speed and extensive configuration options.
The xss package is another HTML sanitizer that aims to filter input from users to prevent XSS attacks. It provides a range of options for customization and is similar to sanitize-html in its goals, but it has a different API and set of defaults.
sanitize-html
provides a simple HTML sanitizer with a clear API.
sanitize-html
is tolerant. It is well suited for cleaning up HTML fragments such as those created by ckeditor and other rich text editors. It is especially handy for removing unwanted CSS when copying and pasting from Word.
sanitize-html
allows you to specify the tags you want to permit, and the permitted attributes for each of those tags.
If a tag is not permitted, the contents of the tag are still kept, except for script and style tags.
The syntax of poorly closed p
and img
elements is cleaned up.
href
attributes are validated to ensure they only contain http
, https
, ftp
and mailto
URLs. Relative URLs are also allowed. Ditto for src
attributes.
HTML comments are not preserved.
sanitize-html
is intended for use with Node. That's pretty much it. All of its npm dependencies are pure JavaScript. sanitize-html
is built on the excellent htmlparser2
module.
npm install sanitize-html
var sanitizeHtml = require('sanitize-html');
var dirty = 'some really tacky HTML';
var clean = sanitizeHtml(dirty);
That will allow our default list of allowed tags and attributes through. It's a nice set, but probably not quite what you want. So:
// Allow only a super restricted set of tags and attributes
clean = sanitizeHtml(dirty, {
allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ],
allowedAttributes: {
'a': [ 'href' ]
}
});
Boom!
"I like your set but I want to add one more tag. Is there a convenient way?" Sure:
clean = sanitizeHtml(dirty, {
allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ])
});
If you do not specify allowedTags
or allowedAttributes
our default list is applied. So if you really want an empty list, specify one.
"What are the default options?"
allowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ],
allowedAttributes: {
a: [ 'href', 'name', 'target' ],
// We don't currently allow img itself by default, but this
// would make sense if we did
img: [ 'src' ]
},
// Lots of these won't come up by default because we don't allow them
selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ],
// URL schemes we permit
allowedSchemes: [ 'http', 'https', 'ftp', 'mailto' ],
// Be more specific about allowed schemes
// for a certain tag
allowedSchemesByTag: {
img: [ 'http' ]
}
"What if I want to allow all tags or all attributes?"
Simple! instead of leaving allowedTags
or allowedAttributes
out of the options, set either
one or both to false
:
allowedTags: false,
allowedAttributes: false
You can use the *
wildcard to allow all attributes with a certain prefix:
allowedAttributes: {
a: [ 'href', 'data-*' ]
}
What if you want to add or change an attribute? What if you want to transform one tag to another? No problem, it's simple!
The easiest way (will change all ol
tags to ul
tags):
clean = sanitizeHtml(dirty, {
transformTags: {
'ol': 'ul',
}
});
The most advanced usage:
clean = sanitizeHtml(dirty, {
transformTags: {
'ol': function(tagName, attribs) {
// My own custom magic goes here
return {
tagName: 'ul',
attribs: {
class: 'foo'
}
};
}
}
});
You can specify the *
wildcard instead of a tag name to transform all tags.
There is also a helper method which should be enough for simple cases in which you want to change the tag and/or add some attributes:
clean = sanitizeHtml(dirty, {
transformTags: {
'ol': sanitizeHtml.simpleTransform('ul', {class: 'foo'}),
}
});
The simpleTransform
helper method has 3 parameters:
simpleTransform(newTag, newAttributes, shouldMerge)
The last parameter (shouldMerge
) is set to true
by default. When true
, simpleTransform
will merge the current attributes with the new ones (newAttributes
). When false
, all existing attributes are discarded.
You can provide a filter function to remove unwanted tags. Let's suppose we need to remove empty a
tags like:
<a href="page.html"></a>
We can do that with the following filter:
sanitizeHtml(
'<p>This is <a href="http://www.linux.org"></a><br/>Linux</p>',
{
exclusiveFilter: function(frame) {
return frame.tag === 'a' && !frame.text.trim();
}
}
);
The frame
object supplied to the callback provides the following attributes:
tag
: The tag name, i.e. 'img'
.attribs
: The tag's attributes, i.e. { src: "/path/to/tux.png" }
.text
: The text content of the tag.tagPosition
: The index of the tag's position in the result string.You can also process all text content with a provided filter function. Let's say we want an ellipsis instead of three dots.
<p>some text...</p>
We can do that with the following filter:
sanitizeHtml(
'<p>some text...</p>',
{
textFilter: function(text) {
return text.replace(/\.\.\./, '…');
}
}
);
Note that the text passed to the textFilter
method is already escaped for safe display as HTML. You may add markup and use entity escape sequences in your textFilter
.
If you wish to allow specific CSS classes on a particular element, you can do so with the allowedClasses
option. Any other CSS classes are discarded.
This implies that the class
attribute is allowed on that element.
// Allow only a restricted set of CSS classes and only on the p tag
clean = sanitizeHtml(dirty, {
allowedTags: [ 'p', 'em', 'strong' ],
allowedClasses: {
'p': [ 'fancy', 'simple' ]
}
});
By default we allow the following URL schemes in cases where href
, src
, etc. are allowed:
[ 'http', 'https', 'ftp', 'mailto' ]
You can override this if you want to:
sanitizeHtml(
// teeny-tiny valid transparent GIF in a data URL
'<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />',
{
allowedTags: [ 'img', 'p' ],
allowedSchemes: [ 'data', 'http' ]
}
);
You can also allow a scheme for a particular tag only:
allowedSchemes: [ 'http', 'https' ],
allowedSchemesByTag: {
img: [ 'data' ]
}
1.8.0:
transformTags
now accepts the *
wildcard to transform all tags. Thanks to Jamy Timmermans.
Text that has been modified by transformTags
is then passed through textFilter
. Thanks to Pavlo Yurichuk.
Content inside textarea
is discarded if textarea
is not allowed. I don't know why it took me this long to see that this is just common sense. Thanks to David Frank.
1.7.2: removed array-includes
dependency in favor of indexOf
, which is a little more verbose but slightly faster and doesn't require a shim. Thanks again to Joseph Dykstra.
1.7.1: removed lodash dependency, adding lighter dependencies and polyfills in its place. Thanks to Joseph Dykstra.
1.7.0: introduced allowedSchemesByTag
option. Thanks to Cameron Will.
1.6.1: the string 'undefined'
(as opposed to undefined
) is perfectly valid text and shouldn't be expressly converted to the empty string.
1.6.0: added textFilter
option. Thanks to Csaba Palfi.
1.5.3: do not escape special characters inside a script or style element, if they are allowed. This is consistent with the way browsers parse them; nothing closes them except the appropriate closing tag for the entire element. Of course, this only comes into play if you actually choose to allow those tags. Thanks to aletorrado.
1.5.2: guard checks for allowed attributes correctly to avoid an undefined property error. Thanks to Zeke.
1.5.1: updated to htmlparser2 1.8.x. Started using the decodeEntities
option, which allows us to pass our filter evasion tests without the need to recursively invoke the filter.
1.5.0: support for *
wildcards in allowedAttributes. With tests. Thanks to Calvin Montgomery.
1.4.3: invokes itself recursively until the markup stops changing to guard against this issue. Bump to htmlparser2 version 3.7.x.
1.4.1, 1.4.2: more tests.
1.4.0: ability to allow all attributes or tags through by setting allowedAttributes
and/or allowedTags
to false. Thanks to Anand Thakker.
1.3.0: attribs
now available on frames passed to exclusive filter.
1.2.3: fixed another possible XSS attack vector; no definitive exploit was found but it looks possible. See this issue. Thanks to Jim O'Brien.
1.2.2: reject javascript:
URLs when disguised with an internal comment. This is probably not respected by browsers anyway except when inside an XML data island element, which you almost certainly are not allowing in your allowedTags
, but we aim to be thorough. Thanks to Jim O'Brien.
1.2.1: fixed crashing bug when presented with bad markup. The bug was in the exclusiveFilter
mechanism. Unit test added. Thanks to Ilya Kantor for catching it.
1.2.0:
The allowedClasses
option now allows you to permit CSS classes in a fine-grained way.
Text passed to your exclusiveFilter
function now includes the text of child elements, making it more useful for identifying elements that truly lack any inner text.
1.1.7: use he
for entity decoding, because it is more actively maintained.
1.1.6: allowedSchemes
option for those who want to permit data
URLs and such.
1.1.5: just a packaging thing.
1.1.4: custom exclusion filter.
1.1.3: moved to lodash. 1.1.2 pointed to the wrong version of lodash.
1.1.0: the transformTags
option was added. Thanks to kl3ryk.
1.0.3: fixed several more javascript URL attack vectors after studying the XSS filter evasion cheat sheet to better understand my enemy. Whitespace characters (codes from 0 to 32), which browsers ignore in URLs in certain cases allowing the "javascript" scheme to be snuck in, are now stripped out when checking for naughty URLs. Thanks again to pinpickle.
1.0.2: fixed a javascript URL attack vector. naughtyHref must entity-decode URLs and also check for mixed-case scheme names. Thanks to pinpickle.
1.0.1: Doc tweaks.
1.0.0: If the style tag is disallowed, then its content should be dumped, so that it doesn't appear as text. We were already doing this for script tags, however in both cases the content is now preserved if the tag is explicitly allowed.
We're rocking our tests and have been working great in production for months, so: declared 1.0.0 stable.
0.1.3: do not double-escape entities in attributes or text. Turns out the "text" provided by htmlparser2 is already escaped.
0.1.2: packaging error meant it wouldn't install properly.
0.1.1: discard the text of script tags.
0.1.0: initial release.
sanitize-html
was created at P'unk Avenue for use in Apostrophe, an open-source content management system built on node.js. If you like sanitize-html
you should definitely check out apostrophenow.org. Also be sure to visit us on github.
Feel free to open issues on github.
1.8.0:
transformTags
now accepts the *
wildcard to transform all tags. Thanks to Jamy Timmermans.
Text that has been modified by transformTags
is then passed through textFilter
. Thanks to Pavlo Yurichuk.
Content inside textarea
is discarded if textarea
is not allowed. I don't know why it took me this long to see that this is just common sense. Thanks to David Frank.
FAQs
Clean up user-submitted HTML, preserving allowlisted elements and allowlisted attributes on a per-element basis
The npm package sanitize-html receives a total of 898,948 weekly downloads. As such, sanitize-html popularity was classified as popular.
We found that sanitize-html demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 16 open source maintainers 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
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.