Skip to content

Commit

Permalink
Tweak escape behaviour to preserve escaped attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
benelliott authored and benelliottgsa committed Jul 8, 2024
1 parent f47281e commit 9934500
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
11 changes: 10 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,17 @@ function sanitizeHtml(html, options, _recursing) {
}
}

if (!allowedAttributesMap || has(allowedAttributesMap, name) || allowedAttributesMap['*']) {
const willEscape = skip;

if (willEscape || !allowedAttributesMap || has(allowedAttributesMap, name) || allowedAttributesMap['*']) {
each(attribs, function(value, a) {
if (willEscape) {
result += ' ' + a;
value = value || '';
result += '="' + escapeHtml(value, true) + '"';
return;
}

if (!VALID_HTML_ATTRIBUTE_NAME.test(a)) {
// This prevents part of an attribute name in the output from being
// interpreted as the end of an attribute, or end of a tag.
Expand Down
12 changes: 12 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ describe('sanitizeHtml', function() {
allowedAttributes: false
}), 'before <img src="test.png" /> after');
});
it('should preserve all attributes in escaped tags', () => {
assert.equal(sanitizeHtml('before <img src="test.png" foo="bar baz boo" style="color: red" /> after', {
disallowedTagsMode: 'escape',
allowedTags: []
}), 'before &lt;img src="test.png" foo="bar baz boo" style="color: red" /&gt; after');
});
it('should preserve all attributes in unrecognised escaped tags', () => {
assert.equal(sanitizeHtml('before <vimg src="test.png" foo="bar baz boo" style="color: red" /> after', {
disallowedTagsMode: 'escape',
allowedTags: []
}), 'before &lt;vimg src="test.png" foo="bar baz boo" style="color: red"&gt; after');
});
it('should handle numbers as strings', () => {
assert.equal(sanitizeHtml(5, {
allowedTags: [ 'b', 'em', 'i', 's', 'small', 'strong', 'sub', 'sup', 'time', 'u' ],
Expand Down

0 comments on commit 9934500

Please sign in to comment.