|
| 1 | +# |
| 2 | +# Copyright © Michal Čihař <michal@weblate.org> |
| 3 | +# |
| 4 | +# This file is part of Weblate <https://weblate.org/> |
| 5 | +# |
| 6 | +# This program is free software: you can redistribute it and/or modify |
| 7 | +# it under the terms of the GNU General Public License as published by |
| 8 | +# the Free Software Foundation, either version 3 of the License, or |
| 9 | +# (at your option) any later version. |
| 10 | +# |
| 11 | +# This program is distributed in the hope that it will be useful, |
| 12 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | +# GNU General Public License for more details. |
| 15 | +# |
| 16 | +# You should have received a copy of the GNU General Public License |
| 17 | +# along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 18 | +# |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +import html |
| 23 | + |
| 24 | +# pylint: disable=protected-access |
| 25 | +import re |
| 26 | + |
| 27 | +import mistletoe |
| 28 | +from django.utils.html import linebreaks |
| 29 | +from mistletoe import span_token |
| 30 | + |
| 31 | + |
| 32 | +class SkipHtmlSpan(span_token.HtmlSpan): |
| 33 | + """Strip raw HTML tags from Markdown input.""" |
| 34 | + |
| 35 | + pattern = re.compile( # pylint: disable=protected-access |
| 36 | + f"{span_token._open_tag}|{span_token._closing_tag}" |
| 37 | + ) |
| 38 | + parse_inner = False |
| 39 | + content: str |
| 40 | + |
| 41 | + def __init__(self, match) -> None: |
| 42 | + super().__init__(match) |
| 43 | + self.content = "" |
| 44 | + |
| 45 | + |
| 46 | +class PlainAutoLink(span_token.AutoLink): |
| 47 | + """Autolink only plain HTTP(S) URLs.""" |
| 48 | + |
| 49 | + pattern = re.compile( |
| 50 | + r"\b(https?://[A-Za-z0-9.!#$%&'*+/=?^_`{|}()~:-]*" |
| 51 | + r"[A-Za-z0-9/#%&=+_~:-])(?=\W|$)" |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +class SafeHtmlRenderer(mistletoe.HtmlRenderer): |
| 56 | + """Render Markdown while rejecting raw HTML and unsafe URLs.""" |
| 57 | + |
| 58 | + _allowed_url_re = re.compile(r"^https?://", re.IGNORECASE) |
| 59 | + _allowed_email_re = re.compile( |
| 60 | + r"^(mailto:)?[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$" |
| 61 | + ) |
| 62 | + |
| 63 | + def __init__(self) -> None: |
| 64 | + super().__init__(SkipHtmlSpan, PlainAutoLink, process_html_tokens=False) |
| 65 | + |
| 66 | + def render_skip_html_span(self, token: SkipHtmlSpan) -> str: |
| 67 | + return token.content |
| 68 | + |
| 69 | + def render_plain_auto_link(self, token: PlainAutoLink) -> str: |
| 70 | + return self.render_auto_link(token) |
| 71 | + |
| 72 | + def render_link(self, token: span_token.Link) -> str: |
| 73 | + if self.check_url(token.target): |
| 74 | + return super().render_link(token) |
| 75 | + return self.escape_html_text(f"[{self.render_to_plain(token)}]({token.target})") |
| 76 | + |
| 77 | + def render_auto_link(self, token: span_token.AutoLink | PlainAutoLink) -> str: |
| 78 | + if self.check_url(token.target) or self.check_email(token.target): |
| 79 | + return super().render_auto_link(token) |
| 80 | + return self.escape_html_text(f"<{token.target}>") |
| 81 | + |
| 82 | + def render_image(self, token: span_token.Image) -> str: |
| 83 | + if self.check_url(token.src): |
| 84 | + title = f' title="{html.escape(token.title)}"' if token.title else "" |
| 85 | + return ( |
| 86 | + f'<img src="{self.escape_url(token.src)}" ' |
| 87 | + f'alt="{self.render_to_plain(token)}"{title} />' |
| 88 | + ) |
| 89 | + return self.escape_html_text(f"") |
| 90 | + |
| 91 | + def check_url(self, url: str) -> bool: |
| 92 | + return bool(self._allowed_url_re.match(url)) |
| 93 | + |
| 94 | + def check_email(self, email: str) -> bool: |
| 95 | + return bool(self._allowed_email_re.match(email)) |
| 96 | + |
| 97 | + |
| 98 | +def render_markdown(text: str) -> str: |
| 99 | + """Render Markdown as safe HTML.""" |
| 100 | + try: |
| 101 | + with SafeHtmlRenderer() as renderer: |
| 102 | + return renderer.render(mistletoe.Document(text)) |
| 103 | + except Exception: # pylint: disable=broad-exception-caught |
| 104 | + return linebreaks(text, autoescape=True) |
0 commit comments