How to use sanitize-html - 10 common examples

To help you get started, we’ve selected a few sanitize-html examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aaroncox / chainbb-frontend / src / utils / MarkdownViewer.js View on Github external
}

        // Strip out HTML comments. "JS-DOS" bug.
        text = text.replace(/|$)/g, '(html comment removed: $1)')

        let renderedText = html ? text : remarkable.render(text)
        // Embed videos, link mentions and hashtags, etc...
        if(renderedText) renderedText = HtmlReady(renderedText).html

        // Complete removal of javascript and other dangerous tags..
        // The must remain as close as possible to dangerouslySetInnerHTML
        let cleanText = renderedText
        if (this.props.allowDangerousHTML === true) {
            console.log('WARN\tMarkdownViewer rendering unsanitized content')
        } else {
            cleanText = sanitize(renderedText, sanitizeConfig({large, highQualityPost, noImage: noImage && allowNoImage}))
        }

        if(/<\s*script/ig.test(cleanText)) {
            // Not meant to be complete checking, just a secondary trap and red flag (code can change)
            console.error('Refusing to render script tag in post text', cleanText)
            return <div></div>
        }

        const noImageActive = cleanText.indexOf(noImageText) !== -1

        // In addition to inserting the youtube compoennt, this allows react to compare separately preventing excessive re-rendering.
        let idx = 0
        const sections = []

        // HtmlReady inserts ~~~ embed:${id} type ~~~
        for(let section of cleanText.split('~~~ embed:')) {
github OpenBazaar / openbazaar-desktop / js / models / chat / ChatMessage.js View on Github external
// emoji unicode characters.
      const emojiPlaceholderRegEx = new RegExp(':.+?:', 'g');
      const matches = attrs.message.match(emojiPlaceholderRegEx, 'g');

      if (matches) {
        matches.forEach(match => {
          const emoji = getEmojiByName(match);

          if (emoji && emoji.char) {
            attrs.message = attrs.message.replace(match, emoji.char);
          }
        });
      }

      // sanitize the message
      attrs.message = sanitizeHtml(attrs.message);

      // Generate a processed message with changes to the message that are specific to our UI.
      attrs.processedMessage = processMessage(attrs.message);
    } else {
      // The processedMessage is automatically derived from the message and should not
      // be set directly.
      delete attrs.processedMessage;
    }

    return super.set(attrs, opts);
  }
github burtonator / polar-bookshelf / web / js / highlights / text / selection / HTMLSanitizer.ts View on Github external
public static sanitize(html: string) {

        return sanitizeHtml(html, {

            // TODO: add all of these below.. to allowedAttributes.
            allowedTags: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote',
                           'cite', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i',
                           'strong', 'em', 'strike', 'code', 'hr', 'br', 'div',
                           'table', 'thead', 'caption', 'tbody', 'tr', 'th',
                           'td', 'pre', 'iframe' ],

            allowedAttributes: {

                'pre': ["style"],
                'ul': ["style"],
                'ol': ["style"],
                'li': ["style"],
                'ni': ["style"],
                'code': ["style"],
github Human-Connection / Human-Connection / backend / src / middleware / xssMiddleware.js View on Github external
function clean(dirty) {
  if (!dirty) {
    return dirty
  }

  // Convert embeds to a-tags
  dirty = embedToAnchor(dirty)
  dirty = linkifyHtml(dirty)
  dirty = sanitizeHtml(dirty, {
    allowedTags: [
      'iframe',
      'img',
      'p',
      'h3',
      'h4',
      'br',
      'hr',
      'b',
      'i',
      'em',
      'strong',
      'a',
      'pre',
      'ul',
      'li',
github sourcegraph / sourcegraph / shared / src / util / markdown.ts View on Github external
gfm: true,
        breaks: true,
        sanitize: false,
        highlight: (code, language) =&gt; highlightCodeSafe(code, language),
    })
    return sanitize(
        rendered,
        options.plainText
            ? { allowedTags: [], allowedAttributes: {} }
            : {
                  // Defaults: https://sourcegraph.com/github.com/punkave/sanitize-html@90aac2665011be6fa21a8864d21c604ee984294f/-/blob/src/index.js#L571-589

                  // Allow highligh.js styles, e.g.
                  // <span class="hljs-keyword">
                  // <code class="language-javascript">
                  allowedTags: [...without(sanitize.defaults.allowedTags, 'iframe'), 'h1', 'h2', 'span', 'img'],
                  allowedAttributes: {
                      ...sanitize.defaults.allowedAttributes,
                      span: ['class'],
                      code: ['class'],
                      h1: ['id'],
                      h2: ['id'],
                      h3: ['id'],
                      h4: ['id'],
                      h5: ['id'],
                      h6: ['id'],
                  },
              }
    )
}
</code></span>
github vck3000 / ProAvalon / routes / forum / forumThreadCommentReplyRoutes.js View on Github external
router.put('/:id/:comment_id/:reply_id', checkForumThreadCommentReplyOwnership, asyncMiddleware(async (req, res) => {
    const foundReply = await forumThreadCommentReply.findById(req.params.reply_id).exec();
    if (foundReply.disabled) {
        req.flash('error', 'You cannot edit a deleted reply.');
        res.redirect('back');
        return;
    }
    foundReply.text = sanitizeHtml(req.body.reply.text, {
        allowedTags: sanitizeHtml.defaults.allowedTags.concat(sanitizeHtmlAllowedTagsForumThread),
        allowedAttributes: sanitizeHtmlAllowedAttributesForumThread,
    });
    foundReply.edited = true;
    foundReply.timeLastEdit = new Date();
    await foundReply.save();

    // forumThread.findById(req.params.id)
    const foundForumThreadComment = await forumThreadComment.findById(req.params.comment_id).populate('replies').exec();
    foundForumThreadComment.markModified('replies');
    // update time last edited
    foundForumThreadComment.timeLastEdit = new Date();
    await foundForumThreadComment.save();

    // forumThread.findById(req.params.id)
    const foundForumThread = await forumThread.findById(req.params.id).populate('comments').exec();
    foundForumThread.markModified('comments');
github CoderDojo / cp-dojos-service / service.js View on Github external
const _ = require('lodash');
const store = require('seneca-postgresql-store');
const storeQuery = require('seneca-store-query');
const dgram = require('dgram');
const service = 'cp-dojos-service';
const log = require('cp-logs-lib')({ name: service, level: 'warn' });
const sanitizeHtml = require('sanitize-html');
config.log = log.log;
// logger creates a circular JSON
if (process.env.NODE_ENV !== 'production') {
  seneca.log.info('using config', JSON.stringify(config, null, 4));
}

seneca.options(config);
seneca.options.sanitizeTextArea = {
  allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']),
  allowedAttributes: _.assign({}, sanitizeHtml.defaults.allowedAttributes, {
    /**
     * Allowing everything here since within ckeditor you have the option of setting the following:
     *
     *   * styles such as border, width, and height.
     *   * alt text
     *
     * However ng-bind-html strips the style tag, so you won't actually see custom styling.
     */
    img: ['*']
  })
};
seneca.decorate('customValidatorLogFormatter', require('./lib/custom-validator-log-formatter'));
seneca.use(store, config['postgresql-store']);
seneca.use(storeQuery);
if (process.env.MAILDEV_ENABLED === 'true') {
github jupyterlab / jupyterlab / packages / apputils / src / sanitizer.ts View on Github external
visibility: [CssProp.VISIBILITY],
        volume: [CssProp.VOLUME],
        'white-space': [CssProp.WHITE_SPACE],
        width: [CssProp.WIDTH],
        'word-break': [CssProp.WORD_BREAK],
        'word-spacing': [CssProp.WORD_SPACING],
        'word-wrap': [CssProp.WORD_WRAP],
        'z-index': [CssProp.Z_INDEX],
        zoom: [CssProp.ZOOM]
      }
    },
    transformTags: {
      // Set the "rel" attribute for <a> tags to "nofollow".
      a: sanitize.simpleTransform('a', { rel: 'nofollow' }),
      // Set the "disabled" attribute for <input> tags.
      input: sanitize.simpleTransform('input', { disabled: 'disabled' })
    },
    allowedSchemesByTag: {
      // Allow 'attachment:' img src (used for markdown cell attachments).
      img: sanitize.defaults.allowedSchemes.concat(['attachment'])
    },
    // Override of the default option, so we can skip 'src' attribute validation.
    // 'src' Attributes are validated to be URIs, which does not allow for embedded (image) data.
    // Since embedded data is no longer deemed to be a threat, validation can be skipped.
    // See https://github.com/jupyterlab/jupyterlab/issues/5183
    allowedSchemesAppliedToAttributes: ['href', 'cite']
  };
}

/**
 * The default instance of an `ISanitizer` meant for use by user code.
 */</a>
github vector-im / riot-web / src / HtmlUtils.js View on Github external
// custom ones first:
        font: [ 'color' ], // custom to matrix
        a: [ 'href', 'name', 'target' ], // remote target: custom to matrix
        // We don't currently allow img itself by default, but this
        // would make sense if we did
        img: [ 'src' ],
    },
    // Lots of these won't come up by default because we don't allow them
    selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ],
    // URL schemes we permit
    allowedSchemes: [ 'http', 'https', 'ftp', 'mailto' ],
    allowedSchemesByTag: {},
    
    transformTags: { // custom to matrix
        // add blank targets to all hyperlinks
        'a': sanitizeHtml.simpleTransform('a', { target: '_blank'} )
    },
};

module.exports = {
    bodyToHtml: function(content, searchTerm) {
        var originalBody = content.body;
        var body;

        if (searchTerm) {
            var lastOffset = 0;
            var bodyList = [];
            var k = 0;
            var offset;

            // XXX: rather than searching for the search term in the body,
            // we should be looking at the match delimiters returned by the FTS engine
github DefinitelyTyped / DefinitelyTyped / sanitize-html / sanitize-html-tests.ts View on Github external
import * as sanitize from 'sanitize-html';

let options: sanitize.IOptions = {
  allowedTags: sanitize.defaults.allowedTags.concat('h1', 'h2', 'img'),
  allowedAttributes: {
    'a': sanitize.defaults.allowedAttributes['a'].concat('rel'),
    'img': ['src', 'height', 'width', 'alt']
  },
	transformTags: { 
    'a': sanitize.simpleTransform('a', { 'rel': 'nofollow' }),
    'img': (tagName: string, attribs: sanitize.Attributes) => {
      let img = { tagName, attribs };
      img.attribs['alt'] = 'transformed' ;
      return img;
    }
  },
  exclusiveFilter: function(frame: sanitize.IFrame) {
    return frame.tag === 'a' && !frame.text.trim();
  }
};

sanitize-html

Clean up user-submitted HTML, preserving allowlisted elements and allowlisted attributes on a per-element basis

MIT
Latest version published 3 days ago

Package Health Score

94 / 100
Full package analysis