const assert = require('assert'); const sinon = require('sinon'); describe('sanitizeHtml', function() { let sanitizeHtml; it('should be successfully initialized', function() { sanitizeHtml = require('../index.js'); }); it('should escape self closing tags', () => { assert.equal(sanitizeHtml('before after', { disallowedTagsMode: 'escape', allowedTags: [], allowedAttributes: false }), 'before <img src="test.png" /> after'); }); it('should handle numbers as strings', () => { assert.equal(sanitizeHtml(5, { allowedTags: [ 'b', 'em', 'i', 's', 'small', 'strong', 'sub', 'sup', 'time', 'u' ], allowedAttributes: {}, disallowedTagsMode: 'recursiveEscape' }), '5'); }); it('should pass through simple, well-formed markup', function() { assert.equal(sanitizeHtml('

Hello there

'), '

Hello there

'); }); it('should preserve col as a self closing tag', function() { assert.equal( sanitizeHtml( '
', { allowedTags: false, allowedAttributes: false } ), '
' ); }); it('should not pass through any text outside html tag boundary since html tag is found and option is ON', function() { assert.equal(sanitizeHtml('Text before html tag

Hello there

Text after html tag!P�X��[

paragraph after closing html

', { enforceHtmlBoundary: true } ), '

Hello there

'); }); it('should pass through text outside html tag boundary since option is OFF', function() { assert.equal(sanitizeHtml('Text before html tag

Hello there

Text after html tag!P�X��[

paragraph after closing html

', { enforceHtmlBoundary: false } ), 'Text before html tag

Hello there

Text after html tag!P�X��[

paragraph after closing html

'); }); it('should pass through text outside html tag boundary since option is ON but html tag is not found', function() { assert.equal(sanitizeHtml('Text before div tag

Hello there

Text after div tag!P�X��[

paragraph after closing div

', { enforceHtmlBoundary: true } ), 'Text before div tag

Hello there

Text after div tag!P�X��[

paragraph after closing div

'); }); it('should pass through all markup if allowedTags and allowedAttributes are set to false', function() { assert.equal(sanitizeHtml('
hello
', { allowedTags: false, allowedAttributes: false }), '
hello
'); }); it('should not pass through any markup if allowedTags is set to undefined (falsy but not exactly false)', function() { assert.equal(sanitizeHtml('
hello
', { allowedTags: undefined }), 'hello'); }); it('should not pass through any markup if allowedTags is set to 0 (falsy but not exactly false)', function() { assert.equal(sanitizeHtml('
hello
', { allowedTags: 0 }), 'hello'); }); it('should not pass through any markup if allowedTags is set to null (falsy but not exactly false)', function() { assert.equal(sanitizeHtml('
hello
', { allowedTags: null }), 'hello'); }); it('should not pass through any markup if allowedTags is set to empty string (falsy but not exactly false)', function() { assert.equal(sanitizeHtml('
hello
', { allowedTags: '' }), 'hello'); }); it('should respect text nodes at top level', function() { assert.equal(sanitizeHtml('Blah blah blah

Whee!

'), 'Blah blah blah

Whee!

'); }); it('should return an empty string when input is explicit "undefined"', function() { assert.equal(sanitizeHtml(undefined), ''); }); it('should return an empty string when input is explicit "null"', function() { assert.equal(sanitizeHtml(null), ''); }); it('should return an empty string when input is not provided', function() { assert.equal(sanitizeHtml(), ''); }); it('should return an empty string when input is an empty string', function() { assert.equal(sanitizeHtml(''), ''); }); it('should reject markup not allowlisted without destroying its text', function() { assert.equal(sanitizeHtml('
Hello
'), '
Hello
'); }); it('should escape markup not allowlisted', function() { assert.equal(sanitizeHtml('
Hello
', { disallowedTagsMode: 'escape' }), '
<wiggly>Hello</wiggly>
'); }); it('should accept a custom list of allowed tags', function() { assert.equal(sanitizeHtml('Cheese', { allowedTags: [ 'blue', 'green' ] }), 'Cheese'); }); it('should reject attributes not allowlisted', function() { assert.equal(sanitizeHtml('foo'), 'foo'); }); it('should accept a custom list of allowed attributes per element', function() { assert.equal(sanitizeHtml('foo', { allowedAttributes: { a: [ 'href', 'whizbang' ] } }), 'foo'); }); it('should clean up unclosed img tags and p tags', function() { assert.equal(sanitizeHtml('

Whee

Again

Wowcool', { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]) }), '

Whee

Again

Wowcool

'); }); it('should reject hrefs that are not relative, ftp, http, https or mailto', function() { assert.equal(sanitizeHtml('googlehttps googleftpmailtorelativejavascript'), 'googlehttps googleftpmailtorelativejavascript'); }); it('should cope identically with capitalized attributes and tags and should tolerate capitalized schemes', function() { assert.equal(sanitizeHtml('googlehttps googleftpmailtorelativejavascript'), 'googlehttps googleftpmailtorelativejavascript'); }); it('should drop the content of script elements', function() { assert.equal(sanitizeHtml('

Paragraph

'), '

Paragraph

'); }); it('should drop the content of style elements', function() { assert.equal(sanitizeHtml('

Paragraph

'), '

Paragraph

'); }); it('should drop the content of textarea elements', function() { assert.equal(sanitizeHtml('

Paragraph

'), '

Paragraph

'); }); it('should drop the content of option elements', function() { assert.equal(sanitizeHtml('

Paragraph

'), '

Paragraph

'); }); it('should drop the content of textarea elements but keep the closing parent tag, when nested', function() { assert.equal(sanitizeHtml('

Paragraph

'), '

Paragraph

'); }); it('should drop the content of disallowed xmp elements rather than re-emit it as live markup', function() { // Regression test for GHSA-rpr9-rxv7-x643: htmlparser2 parses the contents // of as raw text, so without xmp in nonTextTags the inner markup // would be re-emitted unescaped and become live HTML. assert.equal(sanitizeHtml('<xmp><script>alert(1)</script>'), ''); assert.equal(sanitizeHtml('<img src=x onerror=alert(1)>'), ''); assert.equal(sanitizeHtml('<svg><script>alert(1)</script></svg>'), ''); assert.equal(sanitizeHtml('before<script>alert(1)</script>after'), 'beforeafter'); }); it('should retain the content of fibble elements by default', function() { assert.equal(sanitizeHtml('Nifty

Paragraph

'), 'Nifty

Paragraph

'); }); it('should discard the content of fibble elements if specified for nonTextTags', function() { assert.equal(sanitizeHtml('Nifty

Paragraph

', { nonTextTags: [ 'fibble' ] }), '

Paragraph

'); }); it('should retain allowed tags within a fibble element if fibble is not specified for nonTextTags', function() { assert.equal(sanitizeHtml('Nifty

Paragraph

', {}), 'Nifty

Paragraph

'); }); it('should discard allowed tags within a fibble element if fibble is specified for nonTextTags', function() { assert.equal(sanitizeHtml('Nifty

Paragraph

', { nonTextTags: [ 'fibble' ] }), '

Paragraph

'); }); it('should preserve textarea content if textareas are allowed', function() { assert.equal(sanitizeHtml('

Paragraph

', { allowedTags: [ 'textarea', 'p' ] }), '

Paragraph

'); }); it('should preserve entities as such', function() { assert.equal(sanitizeHtml('<Kapow!>'), '<Kapow!>'); }); it('should dump closing tags which do not have any opening tags.', function() { assert.equal(sanitizeHtml('
/'); assert.equal(sanitizeHtml('/'); }); it('should tolerate not closed p tags', function() { assert.equal(sanitizeHtml('

inner text 1

inner text 2

inner text 3

'), '

inner text 1

inner text 2

inner text 3

'); }); it('should escape not closed p tags, if not in allowedTags array', function() { assert.equal(sanitizeHtml('

inner text 1

inner text 2

inner text 3

', { allowedTags: [ 'div' ] }), '
inner text 1inner text 2inner text 3
'); }); it('should dump comments', function() { assert.equal(sanitizeHtml('

Whee

'), '

Whee

'); }); it('should dump a sneaky encoded javascript url', function() { assert.equal(sanitizeHtml('Hax'), 'Hax'); }); it('should dump an uppercase javascript url', function() { assert.equal(sanitizeHtml('Hax'), 'Hax'); }); it('should dump a javascript URL with a comment in the middle (probably only respected by browsers in XML data islands, but just in case someone enables those)', function() { assert.equal(sanitizeHtml('Hax'), 'Hax'); }); it('should not mess up a hashcode with a : in it', function() { assert.equal(sanitizeHtml('Hi'), 'Hi'); }); it('should dump character codes 1-32 before testing scheme', function() { assert.equal(sanitizeHtml('Hax'), 'Hax'); }); it('should dump character codes 1-32 even when escaped with padding rather than trailing ;', function() { // htmlparser2 10.x correctly decodes zero-padded numeric entities. //  decodes to U+0001, which is stripped as a control char, // revealing the javascript: scheme assert.equal(sanitizeHtml('Hax'), 'Hax'); // � decodes to U+FFFD (replacement character per HTML spec), // which is not a control char, so the URL is preserved safely since // browsers don't interpret java�script: as javascript: assert.equal(sanitizeHtml('Hax'), 'Hax'); }); it('should still like nice schemes', function() { assert.equal(sanitizeHtml('Hi'), 'Hi'); }); it('should still like nice relative URLs', function() { assert.equal(sanitizeHtml('Hi'), 'Hi'); }); it('should replace ol to ul', function() { assert.equal(sanitizeHtml('
  1. Hello world
', { transformTags: { ol: 'ul' } }), ''); }); it('should replace ol to ul and add class attribute with foo value', function() { assert.equal(sanitizeHtml('
  1. Hello world
', { transformTags: { ol: sanitizeHtml.simpleTransform('ul', { class: 'foo' }) }, allowedAttributes: { ul: [ 'class' ] } }), ''); }); it('should replace ol to ul, left attributes foo and bar untouched, remove baz attribute and add class attributte with foo value', function() { assert.equal(sanitizeHtml('
  1. Hello world
', { transformTags: { ol: sanitizeHtml.simpleTransform('ul', { class: 'foo' }) }, allowedAttributes: { ul: [ 'foo', 'bar', 'class' ] } }), ''); }); it('should replace ol to ul and replace all attributes to class attribute with foo value', function() { assert.equal(sanitizeHtml('
  1. Hello world
', { transformTags: { ol: sanitizeHtml.simpleTransform('ul', { class: 'foo' }, false) }, allowedAttributes: { ul: [ 'foo', 'bar', 'class' ] } }), ''); }); it('should replace ol to ul and add attribute class with foo value and attribute bar with bar value', function() { assert.equal(sanitizeHtml('
  1. Hello world
', { transformTags: { ol: function(tagName, attribs) { attribs.class = 'foo'; attribs.bar = 'bar'; return { tagName: 'ul', attribs }; } }, allowedAttributes: { ul: [ 'bar', 'class' ] } }), ''); }); it('should replace text and attributes when they are changed by transforming function', function () { assert.equal(sanitizeHtml('some text', { transformTags: { a: function (tagName, attribs) { return { tagName, attribs, text: '' }; } } }), ''); }); it('should replace text and attributes when they are changed by transforming function and textFilter is set', function () { assert.equal(sanitizeHtml('some text', { transformTags: { a: function (tagName, attribs) { return { tagName, attribs, text: 'some text need"tofiltered' }; } }, textFilter: function (text, tagName) { return text.replace(/\s/g, '_'); } }), 'some_text_need"to<be>filtered'); }); it('should replace text and attributes when they are changed by transforming function and textFilter is not set', function () { assert.equal(sanitizeHtml('some text', { transformTags: { a: function (tagName, attribs) { return { tagName, attribs, text: 'some good text' }; } } }), 'some good text'); }); it('should preserve trailing text when replacing the tagName and adding new text via transforming function', function () { assert.equal(sanitizeHtml('

text before
text after

', { transformTags: { br: function (_tagName, _attribs) { return { tagName: 'span', text: ' ' }; } } }), '

text before text after

'); }); it('should add new text when not initially set and replace attributes when they are changed by transforming function', function () { assert.equal(sanitizeHtml('', { transformTags: { a: function (tagName, attribs) { return { tagName, attribs, text: 'some new text' }; } } }), 'some new text'); }); it('should add new text to an empty tag when transforming function sets it and an identity textFilter is present', function () { assert.equal(sanitizeHtml('', { allowedTags: [ 'a' ], textFilter: function (text) { return text; }, transformTags: { a: function (tagName, attribs) { return { tagName, attribs, text: 'some new text' }; } } }), 'some new text'); }); it('should preserve text when initially set and replace attributes when they are changed by transforming function', function () { assert.equal(sanitizeHtml('some initial text', { transformTags: { a: function (tagName, attribs) { return { tagName, attribs }; } } }), 'some initial text'); }); it('should skip an empty link', function() { assert.strictEqual( sanitizeHtml('

This is
Linux

', { exclusiveFilter: function (frame) { return frame.tag === 'a' && !frame.text.trim(); } }), '

This is
Linux

' ); }); it('Should expose a node\'s inner text and inner HTML to the filter', function() { assert.strictEqual( sanitizeHtml('

12
3

', { exclusiveFilter: function(frame) { if (frame.tag === 'p') { assert.strictEqual(frame.text, '124'); } else if (frame.tag === 'a') { assert.strictEqual(frame.text, '3'); return true; } else if (frame.tag === 'br') { assert.strictEqual(frame.text, ''); } else { assert.fail('p, a, br', frame.tag); } return false; } }), '

124

' ); }); it('Should collapse nested empty elements', function() { assert.strictEqual( sanitizeHtml('


', { exclusiveFilter: function(frame) { return (frame.tag === 'a' || frame.tag === 'p') && !frame.text.trim(); } }), '' ); }); it('Should find child media elements that are in allowedTags', function() { const markup = ''; const sansVideo = ''; const sanitizedMarkup = sanitizeHtml(markup, { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]), exclusiveFilter: function(frame) { if (frame.tag === 'a') { assert(frame.mediaChildren.length === 1); } return (frame.tag === 'a') && !frame.text.trim() && !frame.mediaChildren.length; } }); assert.strictEqual(sanitizedMarkup, sansVideo); }); it('Exclusive filter should not affect elements which do not match the filter condition', function () { assert.strictEqual( sanitizeHtml('I love Linux OS', { exclusiveFilter: function (frame) { return (frame.tag === 'a') && !frame.text.trim(); } }), 'I love Linux OS' ); }); it('Exclusive filter should not run for discarded tags', function () { assert.strictEqual( sanitizeHtml('this tag is discarded', { exclusiveFilter: function () { throw Error('this should not run'); } }), 'this tag is discarded' ); }); it('should keep inner text when exclusiveFilter returns "excludeTag"', function() { assert.strictEqual( sanitizeHtml('

These links hack more hack have disallowed href protocols

', { exclusiveFilter: function (frame) { return frame.tag === 'a' && !frame.attribs.src ? 'excludeTag' : false; } }), '

These links hack more hack have disallowed href protocols

' ); }); it('should keep inner tags when exclusiveFilter returns "excludeTag"', function() { assert.strictEqual( sanitizeHtml('This div is bad
but its content

should be kept as-is

.', { exclusiveFilter: function (frame) { return frame.tag === 'div' && frame.attribs.class && /\bbad\b/.test(frame.attribs.class) ? 'excludeTag' : false; } }), 'This div is bad but its content

should be kept as-is

.' ); }); it('should work with escaped tags when exclusiveFilter returns "excludeTag"', function () { assert.strictEqual( sanitizeHtml('hello there. General Kenobi!', { disallowedTagsMode: 'escape', exclusiveFilter: function (frame) { return frame.tag === 'wiggly' ? 'excludeTag' : false; } }), 'hello there. General Kenobi!' ); }); it('should disallow data URLs with default allowedSchemes', function() { assert.equal( sanitizeHtml( // teeny-tiny valid transparent GIF in a data URL '', { allowedTags: [ 'img' ] } ), '' ); }); it('should allow data URLs with custom allowedSchemes', function() { assert.equal( sanitizeHtml( // teeny-tiny valid transparent GIF in a data URL '', { allowedTags: [ 'img', 'p' ], allowedSchemes: [ 'data', 'http' ] } ), '' ); }); it('should allow specific classes when allowlisted with allowedClasses for a single tag', function() { assert.equal( sanitizeHtml( '

whee

', { allowedTags: [ 'p' ], allowedClasses: { p: [ 'nifty' ] } } ), '

whee

' ); }); it('should allow specific classes when allowlisted with allowedClasses for all tags', function() { assert.equal( sanitizeHtml( '

whee

', { allowedTags: [ 'p', 'div' ], allowedClasses: { '*': [ 'nifty' ] } } ), '

whee

' ); }); it('should allow all classes that are allowlisted for a single tag or all tags', function() { assert.equal( sanitizeHtml( '

whee

', { allowedTags: [ 'p', 'div' ], allowedClasses: { '*': [ 'simple' ], p: [ 'nifty' ], div: [ 'dippy' ] } } ), '

whee

' ); }); it('should allow classes that match wildcards for a single tag or all tags', function() { assert.equal( sanitizeHtml( '

whee

', { allowedTags: [ 'p' ], allowedClasses: { '*': [ 'dippy-*-simple' ], p: [ 'nifty-*' ] } } ), '

whee

' ); }); it('should allow all classes if `allowedClasses` contains a single `*`', function() { assert.equal( sanitizeHtml( '

whee

', { allowedTags: [ 'p' ], allowedClasses: { '*': [ '*' ] } } ), '

whee

' ); }); it('should allow all classes for a single tag if `allowedClasses` for the tag is false', function() { assert.equal( sanitizeHtml( '

whee

', { allowedTags: [ 'p' ], allowedClasses: { p: false } } ), '

whee

' ); }); it('should allow only classes that matches `allowedClasses` regex', function() { assert.equal( sanitizeHtml( '

whee

', { allowedTags: [ 'p' ], allowedClasses: { p: [ /^nifty\d{2}$/, /^d\w{4}$/ ] } } ), '

whee

' ); }); it('should allow classes that match `allowedClasses` regex for all tags', function() { assert.equal( sanitizeHtml( '

whee

', { allowedClasses: { '*': [ /^nifty\d{2}$/, /^d\w{4}$/ ] } } ), '

whee

' ); }); it('should allow defining schemes on a per-tag basis', function() { assert.equal( sanitizeHtml( // teeny-tiny valid transparent GIF in a data URL '', { allowedTags: [ 'img', 'a' ], allowedSchemes: [ 'http' ], allowedSchemesByTag: { img: [ 'data' ], a: [ 'https' ] } } ), '' ); assert.equal( sanitizeHtml( // teeny-tiny valid transparent GIF in a data URL '', { allowedTags: [ 'img', 'a' ], allowedSchemes: [ 'http' ], allowedSchemesByTag: { img: [], a: [ 'https' ] } } ), '' ); }); it('should not act weird when the class attribute is empty', function() { assert.equal( sanitizeHtml( '

whee

', { allowedTags: [ 'p' ], allowedClasses: { p: [ 'nifty' ] } } ), '

whee

' ); }); it('should not crash on bad markup', function() { assert.equal( sanitizeHtml( '

', { allowedTags: [ 'img' ], allowedAttributes: { img: [ 'src' ] } } ), // This is weird but not dangerous. Without the " there // would probably be some way to make it come out as a // separate attribute '' ); }); it('should deliver a warning if using vulnerable tags', function() { const spy = sinon.spy(console, 'warn'); const message = 'Your `allowedTags` option includes `style`, which is ' + 'inherently vulnerable to XSS attacks. Please remove it from ' + '`allowedTags`, or, to disable this warning, add the ' + '`allowVulnerableTags` option and ensure you are accounting for this ' + 'risk.'; sanitizeHtml( '', { allowedTags: [ 'style' ] } ); assert(spy.calledWith(message)); // Restore the spied-upon method /* eslint-disable-next-line no-console */ console.warn.restore(); }); it('should deliver warnings to the logger option instead of the console', function() { const spy = sinon.spy(console, 'warn'); const warnings = []; sanitizeHtml( '', { allowedTags: [ 'style' ], logger: { warn: (message) => warnings.push(message) } } ); assert.equal(warnings.length, 1); assert(warnings[0].includes('`style`')); assert(spy.notCalled); // Restore the spied-upon method /* eslint-disable-next-line no-console */ console.warn.restore(); }); it('should not deliver a warning if using the allowVulnerableTags option', function() { const spy = sinon.spy(console, 'warn'); sanitizeHtml( '', { allowVulnerableTags: true, allowedTags: [ 'style' ] } ); assert(spy.notCalled); // Restore the spied-upon method /* eslint-disable-next-line no-console */ console.warn.restore(); }); it('should allow only approved attributes, but to any tags, if tag is declared as "*"', function() { assert.equal( sanitizeHtml( 'not listed too
', { allowedTags: [ 'table', 'img' ], allowedAttributes: { '*': [ 'bgcolor', 'align', 'src' ] } } ), '
' ); }); it('should not filter if exclusive filter does not match after transforming tags', function() { assert.equal( sanitizeHtml( 'test', { allowedTags: [ 'a' ], allowedAttributes: { a: [ 'href', 'target' ] }, transformTags: { a: function (tagName, attribs) { if (!attribs.href) { return false; } return { tagName, attribs: { target: '_blank', href: attribs.href } }; } }, exclusiveFilter: function(frame) { return frame.tag === 'a' && frame.text.trim() === 'blah'; } } ), 'test' ); }); it('should filter if exclusive filter does match after transforming tags', function() { assert.equal( sanitizeHtml( 'blah', { allowedTags: [ 'a' ], allowedAttributes: { a: [ 'href', 'target' ] }, transformTags: { a: function (tagName, attribs) { if (!attribs.href) { return false; } return { tagName, attribs: { target: '_blank', href: attribs.href } }; } }, exclusiveFilter: function(frame) { return frame.tag === 'a' && frame.text.trim() === 'blah'; } } ), '' ); }); it('should allow transform on all tags using \'*\'', function () { assert.equal( sanitizeHtml( '

Text

', { allowedTags: [ 'p' ], allowedAttributes: { p: [ 'style' ] }, transformTags: { '*': function (tagName, attribs) { return { tagName, attribs: { style: 'text-align: center' } }; } } } ), '

Text

' ); }); it('should not be faked out by double <', function() { assert.equal( sanitizeHtml('<img src="javascript:evil"/>' ), '<img src="javascript:evil"/>' ); assert.equal( sanitizeHtml('<a href="javascript:evil"/>' ), '<a href="javascript:evil"/>' ); }); it('should allow attributes to be specified as globs', function() { assert.equal( sanitizeHtml('click me', { allowedTags: [ 'a' ], allowedAttributes: { a: [ 'data-*' ] } }), 'click me' ); assert.equal( sanitizeHtml('click me', { allowedTags: [ 'a' ], allowedAttributes: { a: [ 'data-*-foo' ] } }), 'click me' ); }); it('should quote regex chars in attributes specified as globs', function() { assert.equal( sanitizeHtml('click me', { allowedTags: [ 'a' ], allowedAttributes: { a: [ 'data-b.*' ] } }), 'click me' ); }); it('should not escape inner content of script and style tags (when allowed)', function() { assert.equal( sanitizeHtml('
"normal text"
', { allowedTags: [ 'script' ] }), '"normal text"' ); assert.equal( sanitizeHtml('
"normal text"
', { allowedTags: [ 'style' ] }), '"normal text"' ); }); it('should not unescape escapes found inside script tags', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'script' ] } ), '' ); }); it('should process text nodes with provided function', function() { assert.equal( sanitizeHtml('"normal text this should be removed"', { textFilter: function(text, tagName) { return text.replace(' this should be removed', ''); } }), '"normal text"' ); }); it('should skip text nodes based on tagName', function() { assert.equal( sanitizeHtml('normal text this should be removednormal text this should be removed', { textFilter: function(text, tagName) { if (tagName === 'a') { return text; }; return text.replace(' this should be removed', ''); } }), 'normal text this should be removednormal text' ); }); it('should respect htmlparser2 options when passed in', function() { assert.equal( sanitizeHtml('I am', { allowedTags: false, allowedAttributes: false }), 'I am' ); assert.equal( sanitizeHtml('I am', { allowedTags: false, allowedAttributes: false, parser: { lowerCaseTags: false } }), 'I am' ); }); it('should not crash due to tag names that are properties of the universal Object prototype', function() { assert.equal( sanitizeHtml('!<__proto__>!'), '!<__proto__>!'); }); it('should correctly maintain escaping when allowing a nonTextTags tag other than script or style', function() { assert.equal( sanitizeHtml('!!', { allowedTags: [ 'textarea' ] } ), '!!' ); }); it('should not double-encode entities inside an allowed textarea element', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'textarea' ] } ), '' ); }); it('should allow protocol relative links by default', function() { assert.equal( sanitizeHtml('test'), 'test' ); }); it('should not allow protocol relative links when allowProtocolRelative is false', function() { assert.equal( sanitizeHtml('test', { allowProtocolRelative: false }), 'test' ); assert.equal( sanitizeHtml('test', { allowProtocolRelative: false }), 'test' ); assert.equal( sanitizeHtml('test', { allowProtocolRelative: false }), 'test' ); assert.equal( sanitizeHtml('test', { allowProtocolRelative: false }), 'test' ); }); it('should still allow regular relative URLs when allowProtocolRelative is false', function() { assert.equal( sanitizeHtml('test', { allowProtocolRelative: false }), 'test' ); }); it('should discard srcset by default', function() { assert.equal( sanitizeHtml('', { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]) }), '' ); }); it('should accept srcset if allowed', function() { assert.equal( sanitizeHtml('', { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]), allowedAttributes: { img: [ 'src', 'srcset' ] } }), '' ); assert.equal( sanitizeHtml('', { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]), allowedAttributes: { img: [ 'src', 'srcset' ] } }), '' ); }); it('should drop bogus srcset', function() { assert.equal( sanitizeHtml('', { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]), allowedAttributes: { img: [ 'src', 'srcset' ] } }), '' ); }); it('should accept srcset with urls containing commas', function() { assert.equal( sanitizeHtml('', { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]), allowedAttributes: { img: [ 'src', 'srcset' ] } }), '' ); }); it('should apply allowedSchemesByTag restrictions to srcset URLs', function() { assert.equal( sanitizeHtml('', { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]), allowedAttributes: { img: [ 'src', 'srcset' ] }, allowedSchemes: [ 'http', 'https' ], allowedSchemesByTag: { img: [] } }), '' ); }); it('should drop javascript: in form action', function() { assert.equal( sanitizeHtml('
', { allowedTags: [ 'form', 'button' ], allowedAttributes: { form: [ 'action' ] } }), '
' ); }); it('should allow http(s) in form action', function() { assert.equal( sanitizeHtml('
', { allowedTags: [ 'form', 'button' ], allowedAttributes: { form: [ 'action' ] } }), '
' ); }); it('should drop javascript: in button formaction', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'button' ], allowedAttributes: { button: [ 'formaction' ] } }), '' ); }); it('should allow http(s) in button formaction', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'button' ], allowedAttributes: { button: [ 'formaction' ] } }), '' ); }); it('should drop javascript: in object data', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'object' ], allowedAttributes: { object: [ 'data' ] } }), '' ); }); it('should allow http(s) in object data', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'object' ], allowedAttributes: { object: [ 'data' ] } }), '' ); }); it('should drop javascript: in SVG xlink:href', function() { assert.equal( sanitizeHtml('x', { allowedTags: [ 'svg', 'a', 'text' ], allowedAttributes: { a: [ 'xlink:href' ] } }), 'x' ); }); it('should allow http(s) in SVG xlink:href', function() { assert.equal( sanitizeHtml('x', { allowedTags: [ 'svg', 'a', 'text' ], allowedAttributes: { a: [ 'xlink:href' ] } }), 'x' ); }); it('should drop bogus imagesrcset', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'link' ], allowedAttributes: { link: [ 'rel', 'as', 'imagesrcset' ] }, selfClosing: [ 'link' ] }), '' ); }); it('should accept valid imagesrcset', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'link' ], allowedAttributes: { link: [ 'rel', 'as', 'imagesrcset' ] }, selfClosing: [ 'link' ] }), '' ); }); it('text from transformTags should not specify tags', function() { const input = ''; const want = '<script>alert(1)</script>'; // Runs the sanitizer with a policy that turns an attribute into // text. A policy like this might be used to turn inputs into // inline elements that look like the original but which do not // affect form submissions. const got = sanitizeHtml( input, { allowedTags: [ 'u' ], allowedAttributes: { '*': [ 'class' ] }, transformTags: { input: function (tagName, attribs) { return { tagName: 'u', attribs: { class: 'inlined-input' }, text: attribs.value }; } } }); assert.equal(got, want); }); it('drop attribute names with meta-characters', function() { assert.equal( sanitizeHtml('alert(1)//>', { allowedTags: [ 'span' ], allowedAttributes: { span: [ 'data-*' ] } }), 'alert(1)//>' ); }); it('should sanitize styles correctly', function() { const sanitizeString = '

bestetestestestestestsettestestest

  • test
  1. test
  2. test
  3. test
  4. test

test

TESTETESTESTES

'; const expected = '

bestetestestestestestsettestestest

  • test
  1. test
  2. test
  3. test
  4. test

test

TESTETESTESTES

'; assert.equal( sanitizeHtml(sanitizeString, { allowedTags: false, allowedAttributes: { '*': [ 'dir' ], p: [ 'dir', 'style' ], li: [ 'style' ], span: [ 'style' ] }, allowedStyles: { '*': { // Matches hex color: [ /#(0x)?[0-9a-f]+/i ], 'text-align': [ /left/, /right/, /center/, /justify/, /initial/, /inherit/ ], 'font-size': [ /36px/ ] } } }).replace(/ /g, ''), expected.replace(/ /g, '') ); }); it('Should remove empty style tags', function() { assert.equal( sanitizeHtml('', { allowedTags: false, allowedAttributes: false }), '' ); }); it('Should remove invalid styles', function() { assert.equal( sanitizeHtml('', { allowedTags: false, allowedAttributes: { span: [ 'style' ] }, allowedStyles: { span: { color: [ /blue/ ], 'text-align': [ /left/ ] } } }), '' ); }); it('Should ignore styles when options.parseStyleAttributes is false', function() { assert.equal( sanitizeHtml('', { allowedTags: false, allowedAttributes: { span: [ 'style' ] }, parseStyleAttributes: false }), '' ); }); it('Should throw an error if both allowedStyles is set and && parseStyleAttributes is set to false', function() { try { sanitizeHtml('', { allowedTags: false, allowedAttributes: { span: [ 'style' ] }, allowedStyles: { p: { 'text-align': [ /^justify$/ ] } }, parseStyleAttributes: false }); assert(false); } catch (err) { assert.equal(err.message, 'allowedStyles option cannot be used together with parseStyleAttributes: false.'); } }); it('Should support !important styles', function() { assert.equal( sanitizeHtml('', { allowedTags: false, allowedAttributes: { span: [ 'style' ] }, allowedStyles: { span: { color: [ /blue/ ] } } }), '' ); }); it('Should allow a specific style from global', function() { assert.equal( sanitizeHtml('', { allowedTags: false, allowedAttributes: { span: [ 'style' ] }, allowedStyles: { '*': { color: [ /yellow/ ], 'text-align': [ /center/ ] }, span: { color: [ /green/ ], 'font-family': [ /helvetica/ ] } } }), '' ); }); it('Should merge tag-specific and global styles without giving a __proto__ key special meaning', function() { // JSON.parse creates an own "__proto__" property, as configuration loaded // from a file would const allowedStyles = JSON.parse(`{ "*": { "color": [], "__proto__": [ "inherited" ] }, "span": { "__proto__": [ "inherited" ], "font-family": [] } }`); allowedStyles['*'].color.push(/yellow/); allowedStyles.span['font-family'].push(/helvetica/); assert.equal( sanitizeHtml('', { allowedTags: false, allowedAttributes: { span: [ 'style' ] }, allowedStyles }), '' ); assert.equal(({}).length, undefined); }); it('should delete the script tag', function() { assert.equal(sanitizeHtml('', { allowedTags: [ 'script' ], allowVulnerableTags: true, allowedAttributes: { script: [ 'src' ] }, allowedScriptHostnames: [ 'www.authorized.com' ] }), ''); }); it('should delete the script tag since src is not a valid URL', function() { assert.equal(sanitizeHtml('', { allowedTags: [ 'script' ], allowVulnerableTags: true, allowedAttributes: { script: [ 'src' ] }, allowedScriptHostnames: [ 'www.unauthorized.com' ] }), ''); }); it('Should allow domains in a script that are in allowedScriptDomains', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'script' ], allowedAttributes: { script: [ 'src' ] }, allowedScriptDomains: [ 'authorized.com' ] }), '' ); }); it('should delete the script tag content', function() { assert.equal(sanitizeHtml('', { allowedTags: [ 'script' ], allowVulnerableTags: true, allowedAttributes: { script: [ 'src' ] }, allowedScriptHostnames: [ 'www.authorized.com' ] }), ''); }); it('should delete the script tag content from script tags with no src when allowedScriptHostnames is present', function() { assert.equal(sanitizeHtml('', { allowedTags: [ 'script' ], allowVulnerableTags: true, allowedAttributes: { script: [ 'src' ] }, allowedScriptHostnames: [ 'www.authorized.com' ] }), ''); }); it('should delete the script tag content from script tags with no src when allowedScriptDomains is present', function() { assert.equal(sanitizeHtml('', { allowedTags: [ 'script' ], allowVulnerableTags: true, allowedAttributes: { script: [ 'src' ] }, allowedScriptDomains: [ 'www.authorized.com' ] }), ''); }); it('Should allow hostnames in a script that are in allowedScriptHostnames', function() { assert.equal(sanitizeHtml('', { allowedTags: [ 'script' ], allowVulnerableTags: true, allowedAttributes: { script: [ 'src' ] }, allowedScriptHostnames: [ 'www.authorized.com' ] }), ''); }); it('Should allow hostnames in an iframe that are in allowedIframeHostnames', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] }), '' ); }); it('Should remove iframe src urls that are not included in allowedIframeHostnames', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] }), '' ); }); it('Should not allow iframe urls that do not have proper hostname', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] }), '' ); }); it('Should allow iframe through if no hostname option is set', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] } }), '' ); }); it('Should allow domains in an iframe that are in allowedIframeDomains', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowedIframeDomains: [ 'zoom.us' ] }), '' ); }); it('Should allow second-level domains in an iframe that are in allowedIframeDomains', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowedIframeDomains: [ 'zoom.us' ] }), '' ); }); it('Should remove iframe src urls that are not included in allowedIframeDomains', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowedIframeDomains: [ 'vimeo.com' ] }), '' ); }); it('Should remove iframe src urls with host that ends as allowed domains but not preceded with a dot', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowedIframeDomains: [ 'zoom.us' ] }), '' ); }); it('Should allow hostnames in an iframe that are in allowedIframeHostnames and are not in allowedIframeDomains', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ], allowedIframeDomains: [ 'zoom.us' ] }), '' ); }); it('Should allow hostnames in an iframe that are not in allowedIframeHostnames ' + 'and are allowlisted in allowedIframeDomains', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ], allowedIframeDomains: [ 'zoom.us' ] }), '' ); }); it('Should allow relative URLs for iframes by default', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] } }), '' ); }); it('Should allow relative URLs for iframes', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowIframeRelativeUrls: true }), '' ); }); it('Should remove relative URLs for iframes', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowIframeRelativeUrls: false }), '' ); }); it('Should remove relative URLs for iframes when other hostnames are specified in allowedIframeHostnames', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com' ] }), '' ); }); it('Should allow relative and allowlisted hostname URLs for iframes', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowIframeRelativeUrls: true, allowedIframeHostnames: [ 'www.youtube.com' ] }), '' ); }); it('Should allow protocol-relative URLs for the right domain for iframes', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] }), '' ); }); it('Should not allow protocol-relative iframe urls that do not have proper hostname', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { iframe: [ 'src', 'href' ], a: [ 'src', 'href' ], img: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] }), '' ); }); it('Should only allow attributes to have any combination of specific values', function() { assert.equal( sanitizeHtml('', { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'iframe' ]), allowedAttributes: { iframe: [ { name: 'sandbox', multiple: true, values: [ 'allow-popups', 'allow-same-origin', 'allow-scripts' ] }, 'allowfullscreen' ] } }), ''); }); it('Should only allow attributes that match a specific value', function() { assert.equal( sanitizeHtml('', { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'iframe' ]), allowedAttributes: { iframe: [ { name: 'sandbox', multiple: false, values: [ 'allow-popups', 'allow-same-origin', 'allow-scripts' ] } ] } }), ''); } ); it('Should not allow cite urls that do not have an allowed scheme', function() { assert.equal( sanitizeHtml('HTTPHTTPSMAILTOTELms-calculatorFTPDATALDAPACROBATVBSCRIPTFILERLOGINWEBCALJAVASCRIPTMMS', { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'q' ]), allowedAttributes: { q: [ 'cite' ] }, allowedSchemes: sanitizeHtml.defaults.allowedSchemes.concat([ 'tel' ]) }), 'HTTPHTTPSMAILTOTELms-calculatorFTPDATALDAPACROBATVBSCRIPTFILERLOGINWEBCALJAVASCRIPTMMS'); }); it('Should encode &, <, > and where necessary, "', function() { assert.equal(sanitizeHtml('"< & >" cool', { allowedTags: [ 'span' ], allowedAttributes: { span: [ 'class' ] } }), '"< & >" cool'); }); it('Should not pass through &0; unescaped if decodeEntities is true (the default)', function() { assert.equal(sanitizeHtml('', { allowedTags: [ 'img' ] }), ''); }); it('Should not double encode ampersands on HTML entities if decodeEntities is false (TODO more tests, this is too loose to rely upon)', function() { const textIn = 'This & & that ® ± OK?'; const expectedResult = 'This & & that ® ± OK?'; const sanitizeHtmlOptions = { parser: { decodeEntities: false } }; assert.equal(sanitizeHtml(textIn, sanitizeHtmlOptions), expectedResult); }); it('Should not double encode ampersands on named HTML entities longer than 20 characters if decodeEntities is false', function() { assert.equal( sanitizeHtml('∳ &', { parser: { decodeEntities: false } }), '∳ &' ); }); // TODO: make this test and similar tests for entities that are not // strictly valid pass, at which point decodeEntities: false is safe // to use. // // it('Should not pass through &0; // (a bogus entity) unescaped if decodeEntities is false', function() { // assert.equal(sanitizeHtml( // '', { // allowedTags: ['img'], // parser: { // decodeEntities: false // } // }), ''); // }); it('should escape markup not allowlisted and all its children in recursive mode', function() { assert.equal( sanitizeHtml('
Hello

World

', { disallowedTagsMode: 'recursiveEscape' }), '
<wiggly>Hello<p>World</p></wiggly>
' ); }); it('should escape markup not allowlisted and but not its children', function() { assert.equal( sanitizeHtml('
Hello

World

', { disallowedTagsMode: 'escape' }), '
<wiggly>Hello

World

</wiggly>
' ); }); it('should escape markup even when decodeEntities is false', function() { assert.equal( sanitizeHtml('Hello', { disallowedTagsMode: 'escape', parser: { decodeEntities: false } }), '<wiggly>Hello</wiggly>' ); }); it('should escape markup not allowlisted even within allowed markup', function() { assert.equal( sanitizeHtml('
Hello

World

JS
', { disallowedTagsMode: 'recursiveEscape' }), '
<wiggly>Hello<p>World</p><tiggly>JS</tiggly></wiggly>
' ); }); it('should escape markup not allowlisted even within allowed markup, but not the allowed markup itself', function() { assert.equal( sanitizeHtml('
Hello

World

JS
', { disallowedTagsMode: 'escape' }), '
<wiggly>Hello

World

<tiggly>JS</tiggly></wiggly>
' ); }); it('allows markup of depth 6 with a nestingLimit of depth 6', function() { assert.equal( sanitizeHtml('
', { nestingLimit: 6 }), '
' ); }); it('disallows markup of depth 7 with a nestingLimit of depth 6', function() { assert.equal( // 7 divs here sanitizeHtml('
nested text
', { nestingLimit: 6 }), // only 6 kept '
nested text
' ); }); it('should not allow simple append attacks on iframe hostname validation', function() { assert.equal( sanitizeHtml('' ); }); it('should not allow IDNA (Internationalized Domain Name) iframe validation bypass attacks', function() { assert.equal( sanitizeHtml('' ); }); it('should parse path-rooted relative URLs sensibly', function() { assert.equal( sanitizeHtml(''), '' ); }); it('should parse bare relative URLs sensibly', function() { assert.equal( sanitizeHtml(''), '' ); }); it('should parse ../ relative URLs sensibly', function() { assert.equal( sanitizeHtml(''), '' ); }); it('should parse protocol relative URLs sensibly', function() { assert.equal( sanitizeHtml(''), '' ); }); it('should reject attempts to hack our use of a relative: protocol in our test base URL', function() { assert.equal( sanitizeHtml('' ); }); it('Should prevent hostname bypass using protocol-relative src', function () { assert.strictEqual( sanitizeHtml('', { allowedTags: [ 'iframe' ], allowedAttributes: { iframe: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com' ], allowIframeRelativeUrls: true }), '' ); assert.strictEqual( sanitizeHtml('', { allowedTags: [ 'iframe' ], allowedAttributes: { iframe: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com' ], allowIframeRelativeUrls: true }), '' ); const linefeed = decodeURIComponent('%0A'); assert.strictEqual( sanitizeHtml('', { allowedTags: [ 'iframe' ], allowedAttributes: { iframe: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com' ], allowIframeRelativeUrls: true }), '' ); const creturn = decodeURIComponent('%0D'); assert.strictEqual( sanitizeHtml('', { allowedTags: [ 'iframe' ], allowedAttributes: { iframe: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com' ], allowIframeRelativeUrls: true }), '' ); const tab = decodeURIComponent('%09'); assert.strictEqual( sanitizeHtml('', { allowedTags: [ 'iframe' ], allowedAttributes: { iframe: [ 'src' ] }, allowedIframeHostnames: [ 'www.youtube.com' ], allowIframeRelativeUrls: true }), '' ); }); it('Should allow protocol-relative URLs for script tag', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'script' ], allowedAttributes: { script: [ 'src' ] } }), '' ); }); it('should not automatically attach close tag for escaped tags in escape mode', function() { assert.equal(sanitizeHtml('Hello', { disallowedTagsMode: 'escape' }), '<test>Hello'); }); it('should not automatically attach close tag for escaped tags in recursiveEscape mode', function() { assert.equal(sanitizeHtml('Hello', { disallowedTagsMode: 'recursiveEscape' }), '<test><test><test><test><test>Hello'); }); it('should discard unclosed disallowed tags', function() { assert.equal(sanitizeHtml('Hello', { disallowedTagsMode: 'discard' }), 'Hello'); }); it('should escape unclosed tags without closing bracket in escape mode', function() { assert.equal(sanitizeHtml('hello', { }), 'hello'); }); it('should not remove non-boolean attributes that are empty when disabled', function() { assert.equal(sanitizeHtml('hello', { nonBooleanAttributes: [] }), 'hello'); }); it('should not remove boolean attributes that are empty', function() { assert.equal(sanitizeHtml('', { allowedTags: 'input', allowedAttributes: { input: [ 'checked', 'form', 'type' ] } }), ''); }); it('should remove boolean attributes that are empty when wildcard * passed in', function() { assert.equal(sanitizeHtml('', { allowedTags: 'input', allowedAttributes: { input: [ 'checked', 'form', 'type' ] }, nonBooleanAttributes: [ '*' ] }), ''); }); it('should not remove empty alt attribute value by default', function() { assert.equal(sanitizeHtml('', { allowedAttributes: { img: [ 'alt', 'src' ] }, allowedTags: [ 'img' ] }), ''); }); it('should convert the implicit empty alt attribute value to be an empty string by default', function() { assert.equal(sanitizeHtml('', { allowedAttributes: { img: [ 'alt', 'src' ] }, allowedTags: [ 'img' ] }), ''); }); it('should not remove empty alt attribute value by default when an empty nonBooleanAttributes option passed in', function() { assert.equal(sanitizeHtml('', { allowedAttributes: { img: [ 'alt', 'src' ] }, allowedTags: [ 'img' ], nonBooleanAttributes: [] }), ''); }); it('should not remove the empty attributes specified in allowedEmptyAttributes option', function() { assert.equal(sanitizeHtml('', { allowedAttributes: { img: [ 'alt', 'src' ] }, allowedTags: [ 'img' ], allowedEmptyAttributes: [ 'alt', 'src' ] }), ''); }); it('should remove all the empty attributes when an empty allowedEmptyAttributes option passed in', function() { assert.equal(sanitizeHtml('', { allowedAttributes: { img: [ 'alt', 'src' ] }, allowedTags: [ 'img' ], allowedEmptyAttributes: [] }), ''); }); it('should support SVG tags', () => { assert.equal(sanitizeHtml('', { allowedTags: [ 'svg', 'g', 'defs', 'linearGradient', 'stop', 'circle' ], allowedAttributes: false, parser: { lowerCaseTags: false, lowerCaseAttributeNames: false } }), ''); }); it('should not process style sourceMappingURL with postCSS', () => { assert.equal(sanitizeHtml('', { allowedAttributes: { ...sanitizeHtml.defaults.allowedAttributes, a: [ 'style' ] } }), ''); }); it('should completely remove disallowed tags with nested content', () => { const inputHtml = '
Some Text

Allowed content

More allowed content Another Text
'; const expectedOutput = '

Allowed content

More allowed content'; const sanitizedHtml = sanitizeHtml(inputHtml, { allowedTags: [ 'p', 'span' ], disallowedTagsMode: 'completelyDiscard' }); assert.equal(sanitizedHtml, expectedOutput); }); it('should remove top level tag\'s content', () => { const inputHtml = 'Some Text

paragraph content

content'; const expectedOutput = '

paragraph content

'; const sanitizedHtml = sanitizeHtml(inputHtml, { allowedTags: [ 'p' ], disallowedTagsMode: 'completelyDiscard' }); assert.equal(sanitizedHtml, expectedOutput); }); it('should completely remove disallowed tag with unclosed tag', () => { const inputHtml = '
Some Text

paragraph content

some text'; const expectedOutput = '

paragraph content

'; const sanitizedHtml = sanitizeHtml(inputHtml, { allowedTags: [ 'p' ], disallowedTagsMode: 'completelyDiscard' }); assert.equal(sanitizedHtml, expectedOutput); }); it('should transform text content of tags even if they originally had none', () => { const inputHtml = '
'; const expectedOutput = 'new content'; const sanitizedHtml = sanitizeHtml(inputHtml, { allowedTags: [], transformTags: { div: () => ({ text: 'new content' }) } }); assert.equal(sanitizedHtml, expectedOutput); }); it('should call onOpenTag and onCloseTag callbacks', () => { const onOpenTag = sinon.spy(); const onCloseTag = sinon.spy(); const inputHtml = '
Some Text

paragraph content

some text

'; sanitizeHtml(inputHtml, { allowedTags: [ 'p' ], onOpenTag, onCloseTag }); assert.equal(onOpenTag.callCount, 3); assert.equal(onOpenTag.getCall(0).calledWith('div', { id: 'one' }), true); assert.equal(onOpenTag.getCall(1).calledWith('p', { id: 'two' }), true); assert.equal(onOpenTag.getCall(2).calledWith('p', { id: 'three' }), true); assert.equal(onCloseTag.callCount, 3); assert.equal(onCloseTag.getCall(0).calledWith('p', false), true); assert.equal(onCloseTag.getCall(1).calledWith('p', true), true); assert.equal(onCloseTag.getCall(2).calledWith('div', false), true); }); it('should insert spaces between removed tags whose content we keep', () => { const inputHtml = 'Text's here
it's here

it's there

and also here'; const expectedOutput = 'Text\'s here it\'s here it\'s there and also here'; const allowedTags = [ 'b' ]; let addSpace = false; const sanitizedHtml = sanitizeHtml( inputHtml, { allowedTags, onOpenTag: (tag) => { addSpace = !allowedTags.includes(tag); }, onCloseTag: (tag) => { addSpace = !allowedTags.includes(tag); }, textFilter: (text) => { if (addSpace) { addSpace = false; return ' ' + text; } return text; } } ); assert.equal(sanitizedHtml, expectedOutput); }); it('should not preserve attributes on escaped disallowed tags when `preserveEscapedAttributes` is false', () => { const inputHtml = '
Some Text
'; const expectedOutput = '<div>Some Text</div>'; const sanitizedHtml = sanitizeHtml(inputHtml, { allowedTags: [], disallowedTagsMode: 'escape', preserveEscapedAttributes: false }); assert.equal(sanitizedHtml, expectedOutput); }); it('should preserve attributes on escaped disallowed tags when `preserveEscapedAttributes` is true', () => { const inputHtml = '
Some Text
'; const expectedOutput = '<div class="foo">Some Text</div>'; const sanitizedHtml = sanitizeHtml(inputHtml, { allowedTags: [], disallowedTagsMode: 'escape', preserveEscapedAttributes: true }); assert.equal(sanitizedHtml, expectedOutput); }); it('should ignore the `preserveEscapedAttributes` option when discarding diallowed tags (rather than escaping)', () => { const inputHtml = '
Some Text
'; const sanitizedHtmlPreservedAttrsTrue = sanitizeHtml(inputHtml, { allowedTags: [], disallowedTagsMode: 'discard', preserveEscapedAttributes: true }); const sanitizedHtmlPreservedAttrsFalse = sanitizeHtml(inputHtml, { allowedTags: [], disallowedTagsMode: 'discard', preserveEscapedAttributes: false }); assert.equal(sanitizedHtmlPreservedAttrsTrue, sanitizedHtmlPreservedAttrsFalse); }); it('should not allow script tag injection via escaped entities in option tag', () => { const inputHtml = ''; const result = sanitizeHtml(inputHtml, { allowedTags: [ 'option' ] }); assert.strictEqual(result, ''); }); it('should not double-encode entities inside an allowed option element', function() { assert.equal( sanitizeHtml('', { allowedTags: [ 'option' ] } ), '' ); }); it('should not double-encode entities inside an allowed xmp element', function() { assert.equal( sanitizeHtml('&lt;div&gt;hello&lt;/div&gt;&amp;amp;', { allowedTags: [ 'xmp' ] } ), '&lt;div&gt;hello&lt;/div&gt;&amp;amp;' ); }); it('should correctly maintain escaping when allowing an xmp element', function() { assert.equal( sanitizeHtml('!&lt;/xmp&gt;&lt;svg/onload=prompt`xs`&gt;!', { allowedTags: [ 'xmp' ] } ), '!&lt;/xmp&gt;&lt;svg/onload=prompt`xs`&gt;!' ); }); it('should sanitize away disallowed iframe without escaping fallback html', function() { // Regression for #5550: htmlparser2 treats iframe as raw-text, so an // unclosed iframe's following markup arrives as text and must be // re-sanitized rather than escaped when the iframe is discarded. assert.equal( sanitizeHtml(''), 'test' ); }); it('should not allow XSS via disallowed iframe fallback markup', function() { assert.equal( sanitizeHtml('