A warning sign

Sanitization Warning

Security is a critical aspect of web development. When rendering user-provided Markdown, it's essential to understand the risks and take appropriate measures.

The Risk

Consider the following Markdown input from a malicious user:

[Click me!](javascript:alert('XSS Attack!'))

Or even more directly:

<script>alert('XSS Attack!');</script>

Without sanitization, this will render a link or script that executes arbitrary JavaScript in the user's browser. This can be used to steal session cookies, redirect users to phishing sites, or perform other malicious actions.

How to Protect Yourself

You must use a third-party HTML sanitizer library to clean the output from Markdown Maestro before rendering it in your application. One popular and well-maintained library is DOMPurify.

Example with DOMPurify

First, install DOMPurify:

npm install dompurify

Then, use it to sanitize the HTML output:

import { maestro } from 'markdown-maestro';
import DOMPurify from 'dompurify';

// Untrusted user input
const untrustedMarkdown = '<script>alert("XSS!");</script>';

// 1. Parse the Markdown
const dirtyHtml = maestro(untrustedMarkdown);

// 2. Sanitize the HTML
const cleanHtml = DOMPurify.sanitize(dirtyHtml);

// Now it's safe to render 'cleanHtml'
console.log(cleanHtml); // Output: (empty string)

By implementing a sanitization step, you ensure that any harmful code is stripped from the output, protecting both your application and your users.