How to use the sanitize-html.defaults function in sanitize-html

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 sourcegraph / sourcegraph / shared / src / util / markdown.ts View on Github external
gfm: true,
        breaks: true,
        sanitize: false,
        highlight: (code, language) => 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 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();
  }
};
github johnjones4 / Standard-Notes-Clipper / src / background / background.js View on Github external
const doClip = async (tab, _content) => {
  try {
    await checkForUser()
    await syncInfo()
    const tags = await getTagStrings()
    const editors = await getEditors()
    const editor = await getPreferredEditor()
    const content = await sendMessagePromise(tab.id, 'clip', {
      content: _content,
      tags,
      editors,
      editor: editor ? editor.uuid : null
    })
    content.text = sanitizeHtml(content.text, {
      allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img'])
    })
    const item = await saveClipping(content)
    const updatedContent = await sendMessagePromise(tab.id, 'saved', null)
    if (updatedContent) {
      item.content.title = updatedContent.title
      await updateClipping(item, updatedContent.tags, updatedContent.editor)
    }
    await sendMessagePromise(tab.id, 'done')
  } catch (err) {
    console.error(err)
    await sendMessagePromise(tab.id, 'error', { error: err.message })
  }
}
github pubpub / pubpub / src / components / Markdown / MarkdownComponents / MarkdownHTML.jsx View on Github external
render: function() {

		const dirtyHTML = this.props.children;
		const cleanHTML = sanitizeHtml(dirtyHTML, {
		  allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]),
			allowedAttributes: {
			  a: [ 'href', 'name', 'target' ],
			  img: [ 'src' ]
			},
		});
		return (
			<div>
		);
	}
});</div>
github PacktPublishing / Building-Enterprise-JavaScript-Applications / Chapter10 / hobnob / docs / src / core / components / providers / markdown.jsx View on Github external
}

    return (
        <div></div>
    )
}

Markdown.propTypes = {
    source: PropTypes.string.isRequired,
    className: PropTypes.string.isRequired
}

export default Markdown

const sanitizeOptions = {
    allowedTags: sanitize.defaults.allowedTags.concat([ "h1", "h2", "img", "span" ]),
    allowedAttributes: {
        ...sanitize.defaults.allowedAttributes,
        "img": sanitize.defaults.allowedAttributes.img.concat(["title"]),
        "td": [ "colspan" ],
        "*": [ "class" ]
    },
    allowedSchemesByTag: { img: [ "http", "https", "data" ] },
    textFilter: function(text) {
        return text.replace(/"/g, "\"")
    }
}

export function sanitizer(str) {
    return sanitize(str, sanitizeOptions)
}
github calzoneman / sync / src / xss.js View on Github external
for (var key in ATTRIBUTE_MAP) {
    ALLOWED_ATTRIBUTES.forEach(function (attr) {
        ATTRIBUTE_MAP[key].push(attr);
    });
}

sanitizeHTML.defaults.allowedTags.concat(ALLOWED_TAGS).forEach(function (tag) {
    if (!(tag in ATTRIBUTE_MAP)) {
        ATTRIBUTE_MAP[tag] = ALLOWED_ATTRIBUTES;
    }
});

const SETTINGS = {
    allowedSchemes: sanitizeHTML.defaults.allowedSchemes.concat(ALLOWED_SCHEMES),
    allowedTags: sanitizeHTML.defaults.allowedTags.concat(ALLOWED_TAGS),
    allowedAttributes: ATTRIBUTE_MAP
};

function looseSanitizeText(str) {
    str = str.replace(/&amp;/g, "&amp;")
        .replace(//g, "&gt;")
        .replace(/"/g, """);
    return str;
}

function sanitizeText(str) {
    str = str.replace(/&amp;/g, "&amp;")
             .replace(//g, "&gt;")
             .replace(/"/g, """)
github eclipse-theia / theia / packages / extension-manager / src / node / node-extension-server.ts View on Github external
protected async compileDocumentation(extensionPackage: ExtensionPackage): Promise {
        const markdownConverter = new showdown.Converter({
            noHeaderId: true,
            strikethrough: true,
            headerLevelStart: 2
        });
        const readme = await extensionPackage.getReadme();
        const readmeHtml = markdownConverter.makeHtml(readme);
        return sanitize(readmeHtml, {
            allowedTags: sanitize.defaults.allowedTags.concat(['h1', 'h2', 'img'])
        });
    }
github daichirata / vue-sanitize / index.js View on Github external
const sanitizeHtml = require("sanitize-html");

const VueSanitize = {
  install(Vue, options) {
    const defaultOptions = options;

    Vue.prototype.$sanitize = (dirty, opts = null) =>
      sanitizeHtml(dirty, opts || defaultOptions);
  },

  defaults: sanitizeHtml.defaults
};

export default VueSanitize;

sanitize-html

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

MIT
Latest version published 2 months ago

Package Health Score

91 / 100
Full package analysis