apostrophecms / sanitize-html

Clean up user-submitted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis. Built on htmlparser2 for speed and tolerance
MIT License
3.68k stars 349 forks source link

feat(parseStyleAttributes): add option to skip style parsing [fix 547] #596

Closed bertyhell closed 1 year ago

bertyhell commented 1 year ago

This will fix https://github.com/apostrophecms/sanitize-html/issues/547

This PR introduces a new option:

options.parseStyleAttributes: boolean

By default set to true, to match the current behavior. But a user can set it to false, to skip parsing style tags. This can avoid issues when the package is used in the browser.

  it('Should ignore styles when options.parseStyleAttributes is false', function() {
    assert.equal(
      sanitizeHtml('<span style=\'color: blue; text-align: justify\'></span>', {
        allowedTags: false,
        allowedAttributes: {
          span: [ 'style' ]
        },
        allowedStyles: {
          span: {
            color: [ /blue/ ],
            'text-align': [ /left/ ]
          }
        },
        parseStyleAttributes: false
      }), '<span style="color: blue; text-align: justify"></span>'
    );
  });
boutell commented 1 year ago

Thanks. Does allowedStyles still do anything when parseStyleAttributes is false? Is it misleading to suggest anything is done to sanitize styles in the presence of this setting?

bertyhell commented 1 year ago

@boutell Good point, i added some extra text in the readme to make the user aware of this:

When you disable the parsing of the style attribute, the allowedStyles option is automatically ignored, and all styles will be allowed.

boutell commented 1 year ago

Good stuff. I think we also should throw an error when allowedStyles is configured in the presence of this setting. Just to be safe.

bertyhell commented 1 year ago

@boutell fixed, when they are used together you get this error:

throw new Error('allowedStyles option cannot be used together with parseStyleAttributes: false.');
bertyhell commented 1 year ago

@boutell fixed

bertyhell commented 1 year ago

@boutell fixed

boutell commented 1 year ago

Thanks!