首页 > 解决方案 > How to display escaped HTML inside a code tag generated from markdown sanitized source?

问题描述

I'm developing an app that collects feedbacks from customers. The input interface enables them to use markdown for more organized inputs. I'm implementing a preview feature that parses the markdown to HTML and displays it in a div.

I'm using the DOMPurify package to sanitize the user input before parsing the markdown with the Marked JS library. We are only allowing markdown, so HTML inputs are by default escaped. The exception is that the users can include code snippets in their feedbacks; they can use the code example syntax from markdown.

We are escaping every HTML tag that is entered before parsing, because when the markdown is parsed then the escaped HTML parts are not showing properly inside the <code> tag.

How can I manage to display escaped HTML inside the <code> tag? Is there a better way to block this kind of XSS?

JS code that is generating and displaying the parsed markdown input:

function showMarkdownPreview(sourceHtmlComponentId, targetHtmlComponentId) {
    let sourceElement = document.getElementById(sourceHtmlComponentId);
    let targetElement = document.getElementById(targetHtmlComponentId);
    let san = sanitizeHTML(sourceElement.value);

    targetElement.innerHTML = DOMPurify.sanitize(marked(san), { USE_PROFILES: { html: true } });
}

var sanitizeHTML = function (str) {
    let regex = /[&|<|>|"|']/g;
    let htmlString = str.replace(regex, function (match) {
        if (match === "&") {
            return "&amp;";
        } else if (match === "<") {
            return "&lt;"
        } else if (match === ">") {
            return "&gt;";
        } else if (match === '"') {
            return "&quot;";
        } else {
            return "&apos;";
        }
    });

    return htmlString;
};

This is what the affected part looks like of the parsed HTML:

<pre>
    <code>&amp;lt;p&amp;gt;dfsfsdfsdf&amp;lt;/p&amp;gt;</code>
</pre>

The example input of the parser:

Output of the parser:

标签: javascripthtmlmarkdownxss

解决方案


推荐阅读