From 10e77707d06e39f6562f9a6ad479a34749eb48ea Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Fri, 28 Sep 2018 02:18:41 +0300 Subject: [PATCH] Fix HTML escaping in command reply markdown parser --- mautrix_telegram/commands/handler.py | 25 +++++++++++++++++++++++-- mautrix_telegram/commands/portal.py | 6 ++---- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/mautrix_telegram/commands/handler.py b/mautrix_telegram/commands/handler.py index 5be4d4fd..fd013c63 100644 --- a/mautrix_telegram/commands/handler.py +++ b/mautrix_telegram/commands/handler.py @@ -36,6 +36,27 @@ SECTION_MISC = HelpSection("Miscellaneous", 40, "") SECTION_ADMIN = HelpSection("Administration", 50, "") +class HtmlEscapingRenderer(commonmark.HtmlRenderer): + def __init__(self, allow_html: bool = False): + super().__init__() + self.allow_html = allow_html + + def lit(self, s): + if self.allow_html: + return super().lit(s) + return super().lit(s.replace("<", "<").replace(">", ">")) + + def image(self, node, entering): + prev = self.allow_html + self.allow_html = True + super().image(node, entering) + self.allow_html = prev + + +md_parser = commonmark.Parser() +md_renderer = HtmlEscapingRenderer() + + class CommandEvent: def __init__(self, processor: 'CommandProcessor', room: MatrixRoomID, sender: u.User, command: str, args: List[str], is_management: bool, is_portal: bool) -> None: @@ -60,8 +81,8 @@ class CommandEvent: message = message.replace("$cmdprefix", self.command_prefix) html = None if render_markdown: - html = commonmark.commonmark(message if allow_html else - message.replace("<", "<").replace(">", ">")) + md_renderer.allow_html = allow_html + html = md_renderer.render(md_parser.parse(message)) elif allow_html: html = message return self.az.intent.send_notice(self.room_id, message, html=html) diff --git a/mautrix_telegram/commands/portal.py b/mautrix_telegram/commands/portal.py index ede472e3..e4e7b30e 100644 --- a/mautrix_telegram/commands/portal.py +++ b/mautrix_telegram/commands/portal.py @@ -442,8 +442,7 @@ def config_help(evt: CommandEvent) -> Awaitable[Dict]: def config_view(evt: CommandEvent, portal: po.Portal) -> Awaitable[Dict]: stream = StringIO() yaml.dump(portal.local_config, stream) - return evt.reply(f"Room-specific config:\n\n```yaml\n{stream.getvalue()}```", - allow_html=True) + return evt.reply(f"Room-specific config:\n\n```yaml\n{stream.getvalue()}```") def config_defaults(evt: CommandEvent) -> Awaitable[Dict]: @@ -460,8 +459,7 @@ def config_defaults(evt: CommandEvent) -> Awaitable[Dict]: "message_formats": evt.config["bridge.message_formats"], "state_event_formats": evt.config["bridge.state_event_formats"], }, stream) - return evt.reply(f"Bridge instance wide config:\n\n```yaml\n{stream.getvalue()}```", - allow_html=True) + return evt.reply(f"Bridge instance wide config:\n\n```yaml\n{stream.getvalue()}```") def config_set(evt: CommandEvent, portal: po.Portal, key: str, value: str) -> Awaitable[Dict]: