Sanitizing Markdown with a Meteor package?

I’m currently trying to build a chat app, using the official markdown package (meteor add markdown) as well as underscore’s escape function, and my template contains something like this:

<span class="message-content">
    {{#markdown}}{{text}}{{/markdown}}
</span>

When I grab the text from the chat input box, I try to sanitize the input by escaping any HTML and also adding in line breaks. safeText is then inserted into the database and displayed in the above template.

rawText = $("#chat-input-textbox").val();
safeText = _.escape(rawText).replace(/(?:\r\n|\r|\n)/g, '\n\n');

I test with the following input:

    <script>alert("test")</script>
    ```
    alert('hello');
    ```
    This is _italics_!

Everything looks as expected, except the alert('hello'); has become alert(&#x27;hello&#x27;); instead. The <pre> blocks aren’t rendering the escaped characters, which makes sense. But the problem is, the underscore JS escape function escapes everything.

I would’ve thought this to be a common problem enough that there should be a package for it. What’s an easy way to get around this?

As long as the text is properly escaped, it should be as simple as:

<span class="message-content">
    {{#markdown}}{{{text}}}{{/markdown}}
</span>

Note the triple brace syntax for raw HTML.

I’ve tried that, but it yields exactly the same result. What could it be? It only happens inside the

 blocks.

Hmm. A quick scan of the package code looks like it already does its own escaping, so you may not need to. I suggest trying to feed it dangerous markdown/mixed HTML and seeing what comes out! :smile:

1 Like

Interesting.

So of course the stuff inside the pre blocks work again. But when I type <script>alert('hi')</script> it doesn’t show up because it tries to see it as html but you’re right in that the package does seem to strip it out completely.

Maybe I’ll just keep it like this and if any users ask about why their code isn’t showing up, I’ll tell them to wrap it in a code block.

Which btw seems to be how this forum works too.

Thanks!

Just come across this: http://themeteorchef.com/recipes/building-a-markdown-editor/, which may be interesting.

1 Like