editor.js icon indicating copy to clipboard operation
editor.js copied to clipboard

Question: How can I use sanitizer with 'paragraph' block?

Open ahmadx87 opened this issue 7 years ago • 2 comments

Hey there. Thanks for the cool project. In my project I want to use sanitizer for the paragraph block. I want to add rel="nofollow" to external links. All the examples I find in the documentation seems to be with custom blocks. How can I sanitize the paragraph blocks? Or third party blocks?

ahmadx87 avatar Oct 07 '19 11:10 ahmadx87

Hello @ahmadx87 i doing that on server side when render saved blocks For that i using sanitize-html package

import * as sanitizeHtml from 'sanitize-html';

const config = {
  b: [],
  strong: [],
  em: [],
  i: [],
  u: [],
  s: [],
  br: [],
  a: [
    'href',
    { name: 'target', values: ['_blank'] },
    { name: 'rel', values: ['noopener nofollow', 'noopener', 'nofollow'] },
  ],
  mark: [{ name: 'class', values: ['cdx-marker'] }],
  code: [{ name: 'class', values: ['inline-code'] }],
};

export function sanitizerFactory(origin) {
  return (html: string) => sanitize(html, origin);
}

export function sanitize(html: string, origin = 'example.com') {
  return sanitizeHtml(html, {
    allowedTags: Object.keys(config),
    allowedAttributes: config,
    transformTags: {
      a: function(tagName, attribs) {
        // always rel noopener
        let rel = ['noopener'];
        // target blank by default
        attribs.target = '_blank';
        // for external links rel nofollow
        if (origin && attribs.href.indexOf(origin) === -1) {
          rel.push('nofollow');
        }
        // all internal links must be https
        if (origin && attribs.href.startsWith('http://' + origin)) {
          attribs.href = attribs.href.replace('http://' + origin, 'https://' + origin);
        }
        // remove target for internal links
        if (origin && attribs.href.startsWith('https://' + origin)) {
          delete attribs.target;
        }
        return {
          tagName: 'a',
          attribs: {
            ...attribs,
            rel: rel.join(' '),
          },
        };
      },
    },
  });
}

igorivaniuk avatar Oct 10 '19 10:10 igorivaniuk

+1 Pen testing raised the ability to paste HTML into paragraphs as a XSS vulnerability. It would be nice if the library handled this internally.

JuampaProverbio avatar Jul 20 '23 02:07 JuampaProverbio