From 986acfac3830539793b32f38a8425fb0965c9b46 Mon Sep 17 00:00:00 2001 From: retoor Date: Fri, 25 Jul 2025 17:17:45 +0200 Subject: [PATCH] Update. --- src/snek/service/channel_message.py | 4 +++- src/snek/system/template.py | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/snek/service/channel_message.py b/src/snek/service/channel_message.py index 9c66af7..aae68b9 100644 --- a/src/snek/service/channel_message.py +++ b/src/snek/service/channel_message.py @@ -1,5 +1,5 @@ from snek.system.service import BaseService -from snek.system.template import whitelist_attributes +from snek.system.template import sanitize_html import time class ChannelMessageService(BaseService): @@ -72,6 +72,7 @@ class ChannelMessageService(BaseService): try: template = self.app.jinja2_env.get_template("message.html") model["html"] = template.render(**context) + model['html'] = sanitize_html(model['html']) except Exception as ex: print(ex, flush=True) @@ -128,6 +129,7 @@ class ChannelMessageService(BaseService): ) template = self.app.jinja2_env.get_template("message.html") model["html"] = template.render(**context) + model['html'] = sanitize_html(model['html']) return await super().save(model) async def offset(self, channel_uid, page=0, timestamp=None, page_size=30): diff --git a/src/snek/system/template.py b/src/snek/system/template.py index 4af7e8d..cd3fd51 100644 --- a/src/snek/system/template.py +++ b/src/snek/system/template.py @@ -82,6 +82,32 @@ emoji.EMOJI_DATA[ ALLOWED_TAGS = list(bleach.sanitizer.ALLOWED_TAGS) + ["picture"] def sanitize_html(value): + + soup = BeautifulSoup(value, 'html.parser') + + for script in soup.find_all('script'): + script.decompose() + + for iframe in soup.find_all('iframe'): + iframe.decompose() + + for tag in soup.find_all(['object', 'embed']): + tag.decompose() + + for tag in soup.find_all(): + event_attributes = ['onclick', 'onerror', 'onload', 'onmouseover', 'onfocus'] + for attr in event_attributes: + if attr in tag.attrs: + del tag[attr] + + for img in soup.find_all('img'): + if 'onerror' in img.attrs: + img.decompose() + + return soup.prettify() + + +def sanitize_html2(value): return bleach.clean( value, protocols=list(bleach.sanitizer.ALLOWED_PROTOCOLS) + ["data"],