Skip to content

Commit

Permalink
Add preserveEscapedAttributes option to allow attributes on escaped…
Browse files Browse the repository at this point in the history
… disallowed tags to be retained

Fixes apostrophecms#540
  • Loading branch information
benelliott authored and benelliottgsa committed Jul 9, 2024
1 parent 2e56d1c commit 871ef11
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
12 changes: 10 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,14 @@ function sanitizeHtml(html, options, _recursing) {
}
}

if (!allowedAttributesMap || has(allowedAttributesMap, name) || allowedAttributesMap['*']) {
const isBeingEscaped = skip && (options.disallowedTagsMode === 'escape' || options.disallowedTagsMode === 'recursiveEscape');
const shouldPreserveEscapedAttributes = isBeingEscaped && options.preserveEscapedAttributes;

if (shouldPreserveEscapedAttributes) {
each(attribs, function(value, a) {
result += ' ' + a + '="' + escapeHtml((value || ''), true) + '"';
});
} else if (!allowedAttributesMap || has(allowedAttributesMap, name) || allowedAttributesMap['*']) {
each(attribs, function(value, a) {
if (!VALID_HTML_ATTRIBUTE_NAME.test(a)) {
// This prevents part of an attribute name in the output from being
Expand Down Expand Up @@ -893,7 +900,8 @@ sanitizeHtml.defaults = {
allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ],
allowProtocolRelative: true,
enforceHtmlBoundary: false,
parseStyleAttributes: true
parseStyleAttributes: true,
preserveEscapedAttributes: false
};

sanitizeHtml.simpleTransform = function(newTagName, newAttribs, merge) {
Expand Down
22 changes: 22 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1693,6 +1693,28 @@ describe('sanitizeHtml', function() {
disallowedTagsMode: 'completelyDiscard'
});

assert.equal(sanitizedHtml, expectedOutput);
});
it('should not preserve attributes on escaped disallowed tags when `preserveEscapedAttributes` is false', () => {
const inputHtml = '<div class="foo">Some Text</div>';
const expectedOutput = '&lt;div&gt;Some Text&lt;/div&gt;';
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 = '<div class="foo">Some Text</div>';
const expectedOutput = '&lt;div class="foo"&gt;Some Text&lt;/div&gt;';
const sanitizedHtml = sanitizeHtml(inputHtml, {
allowedTags: [],
disallowedTagsMode: 'escape',
preserveEscapedAttributes: true
});

assert.equal(sanitizedHtml, expectedOutput);
});
});

0 comments on commit 871ef11

Please sign in to comment.