rDrama/files/helpers/sanitize.py

328 lines
13 KiB
Python
Raw Normal View History

2021-10-15 14:08:27 +00:00
import bleach
from bs4 import BeautifulSoup
2022-04-17 20:20:40 +00:00
from bleach.linkifier import LinkifyFilter, build_url_re
2021-10-15 14:08:27 +00:00
from functools import partial
from .get import *
from os import path, environ
import re
2022-01-13 00:24:23 +00:00
from mistletoe import markdown
2022-01-12 03:16:49 +00:00
from json import loads, dump
2022-02-11 23:32:14 +00:00
from random import random, choice
2022-02-17 01:30:59 +00:00
import signal
import time
2022-03-22 15:19:16 +00:00
import requests
2022-02-11 23:32:14 +00:00
2022-04-29 15:17:14 +00:00
TLDS = ('ac','ad','ae','aero','af','ag','ai','al','am','an','ao','aq','ar','arpa','as','asia','at','au','aw','ax','az','ba','bb','bd','be','bf','bg','bh','bi','biz','bj','bm','bn','bo','br','bs','bt','bv','bw','by','bz','ca','cafe','cat','cc','cd','cf','cg','ch','ci','ck','cl','club','cm','cn','co','com','coop','cr','cu','cv','cx','cy','cz','de','dj','dk','dm','do','dz','ec','edu','ee','eg','er','es','et','eu','fi','fj','fk','fm','fo','fr','ga','gb','gd','ge','gf','gg','gh','gi','gl','gm','gn','gov','gp','gq','gr','gs','gt','gu','gw','gy','hk','hm','hn','hr','ht','hu','id','ie','il','im','in','info','int','io','iq','ir','is','it','je','jm','jo','jobs','jp','ke','kg','kh','ki','km','kn','kp','kr','kw','ky','kz','la','lb','lc','li','lk','lr','ls','lt','lu','lv','ly','ma','mc','md','me','mg','mh','mil','mk','ml','mm','mn','mo','mobi','mp','mq','mr','ms','mt','mu','museum','mv','mw','mx','my','mz','na','name','nc','ne','net','nf','ng','ni','nl','no','np','nr','nu','nz','om','org','pa','pe','pf','pg','ph','pk','pl','pm','pn','post','pr','pro','ps','pt','pw','py','qa','re','ro','rs','ru','rw','sa','sb','sc','sd','se','sg','sh','si','sj','sk','sl','sm','sn','so','social','sr','ss','st','su','sv','sx','sy','sz','tc','td','tel','tf','tg','th','tj','tk','tl','tm','tn','to','tp','tr','travel','tt','tv','tw','tz','ua','ug','uk','us','uy','uz','va','vc','ve','vg','vi','vn','vu','wf','win','ws','xn','xxx','xyz','ye','yt','yu','za','zm','zw')
2022-04-17 20:20:40 +00:00
2022-04-19 19:13:36 +00:00
allowed_tags = ('b','blockquote','br','code','del','em','h1','h2','h3','h4','h5','h6','hr','i','li','ol','p','pre','strong','sub','sup','table','tbody','th','thead','td','tr','ul','marquee','a','span','ruby','rp','rt','spoiler','img','lite-youtube','video','source')
2022-04-17 20:20:40 +00:00
def allowed_attributes(tag, name, value):
if name == 'style': return True
if tag == 'marquee':
if name in ['direction', 'behavior', 'scrollamount']: return True
if name in {'height', 'width'}:
try: value = int(value.replace('px', ''))
except: return False
if 0 < value <= 250: return True
return False
if tag == 'a':
if name == 'href': return True
if name == 'rel' and value == 'nofollow noopener noreferrer': return True
if name == 'target' and value == '_blank': return True
return False
if tag == 'img':
if name in ['src','data-src']:
2022-04-18 16:01:03 +00:00
if value.startswith('/') or value.startswith(f'{SITE_FULL}/') or embed_fullmatch_regex.fullmatch(value): return True
2022-04-17 20:20:40 +00:00
else: return False
if name == 'loading' and value == 'lazy': return True
if name == 'referrpolicy' and value == 'no-referrer': return True
if name == 'data-bs-toggle' and value == 'tooltip': return True
if name in ['alt','title','g','b','pat']: return True
if name == 'class' and value == 'pat-hand': return True
2022-04-17 20:20:40 +00:00
return False
if tag == 'lite-youtube':
if name == 'params' and value.startswith('autoplay=1&modestbranding=1'): return True
if name == 'videoid': return True
return False
if tag == 'video':
if name == 'controls' and value == '': return True
if name == 'preload' and value == 'none': return True
return False
if tag == 'source':
2022-04-18 16:01:03 +00:00
if name == 'src' and embed_fullmatch_regex.fullmatch(value): return True
2022-04-17 20:20:40 +00:00
return False
if tag == 'p':
if name == 'class' and value == 'mb-0': return True
return False
if tag == 'span':
if name == 'class' and value in ['pat-container', 'pat-hand']: return True
if name == 'data-bs-toggle' and value == 'tooltip': return True
if name == 'title': return True
if name == 'alt': return True
return False
2022-04-17 20:20:40 +00:00
url_re = build_url_re(tlds=TLDS, protocols=['http', 'https'])
2022-04-16 23:06:53 +00:00
2022-04-16 23:00:21 +00:00
def callback(attrs, new=False):
href = attrs[(None, "href")]
2022-04-17 21:46:29 +00:00
if not href.startswith('/') and not href.startswith(f'{SITE_FULL}/'):
2022-04-16 23:00:21 +00:00
attrs[(None, "target")] = "_blank"
attrs[(None, "rel")] = "nofollow noopener noreferrer"
return attrs
2022-02-17 01:30:59 +00:00
2022-04-16 23:06:53 +00:00
def handler(signum, frame):
print("Timeout!")
raise Exception("Timeout")
def render_emoji(html, regexp, edit, marseys_used=set(), b=False):
emojis = list(regexp.finditer(html))
captured = set()
for i in emojis:
if i.group(0) in captured: continue
captured.add(i.group(0))
emoji = i.group(1).lower()
attrs = ''
if b: attrs += ' b'
if not edit and len(emojis) <= 20 and random() < 0.0025 and ('marsey' in emoji or emoji in marseys_const2): attrs += ' g'
old = emoji
emoji = emoji.replace('!','').replace('#','')
if emoji == 'marseyrandom': emoji = choice(marseys_const2)
2022-04-27 23:16:24 +00:00
emoji_partial_pat = '<img loading="lazy" alt=":{0}:" src="{1}"{2}>'
emoji_partial = '<img loading="lazy" data-bs-toggle="tooltip" alt=":{0}:" title=":{0}:" src="{1}"{2}>'
emoji_html = None
2022-04-27 16:28:00 +00:00
if emoji.endswith('pat'):
if path.isfile(f"files/assets/images/emojis/{emoji.replace('pat','')}.webp"):
2022-04-27 15:03:25 +00:00
attrs += ' pat'
2022-04-27 23:16:24 +00:00
emoji_html = f'<span class="pat-container" data-bs-toggle="tooltip" alt=":{old}:" title=":{old}:"><img src="/assets/images/hand.webp" class="pat-hand">{emoji_partial_pat.format(old, f"/e/{emoji[:-3]}.webp", attrs)}</span>'
elif emoji.startswith('@'):
if u := get_user(emoji[1:-3], graceful=True):
attrs += ' pat'
2022-04-27 23:16:24 +00:00
emoji_html = f'<span class="pat-container" data-bs-toggle="tooltip" alt=":{old}:" title=":{old}:"><img src="/assets/images/hand.webp" class="pat-hand">{emoji_partial_pat.format(old, f"/pp/{u.id}", attrs)}</span>'
2022-04-27 16:28:00 +00:00
elif path.isfile(f'files/assets/images/emojis/{emoji}.webp'):
emoji_html = emoji_partial.format(old, f'/e/{emoji}.webp', attrs)
if emoji_html:
html = re.sub(f'(?<!"){i.group(0)}', emoji_html, html)
return html
2022-04-16 23:06:53 +00:00
2022-04-17 20:20:40 +00:00
def sanitize(sanitized, alert=False, comment=False, edit=False):
2022-04-15 22:39:17 +00:00
2022-02-17 01:30:59 +00:00
signal.signal(signal.SIGALRM, handler)
2022-02-23 05:19:57 +00:00
signal.alarm(1)
2022-04-15 22:39:17 +00:00
2022-04-22 15:17:10 +00:00
sanitized = linefeeds_regex.sub(r'\1\n\n\2', sanitized)
2022-04-25 14:51:40 +00:00
sanitized = image_regex.sub(r'\1![](\2)\4', sanitized)
2022-03-19 18:12:14 +00:00
sanitized = image_check_regex.sub(r'\1', sanitized)
2022-01-11 19:46:50 +00:00
sanitized = markdown(sanitized)
2022-03-06 19:03:50 +00:00
sanitized = strikethrough_regex.sub(r'<del>\1</del>', sanitized)
2022-04-15 22:39:17 +00:00
sanitized = sanitized.replace('','').replace('','').replace("\ufeff", "").replace("𒐪","")
2022-01-11 19:46:50 +00:00
if alert:
2022-02-28 23:30:44 +00:00
captured = []
2022-02-28 23:01:57 +00:00
for i in mention_regex2.finditer(sanitized):
2022-02-28 23:30:44 +00:00
if i.group(0) in captured: continue
captured.append(i.group(0))
2022-01-11 19:46:50 +00:00
u = get_user(i.group(1), graceful=True)
if u:
2022-04-15 23:06:13 +00:00
sanitized = sanitized.replace(i.group(0), f'''<p><a href="/id/{u.id}"><img loading="lazy" src="/pp/{u.id}">@{u.username}</a>''')
2022-01-11 19:46:50 +00:00
else:
2022-02-28 23:01:57 +00:00
sanitized = reddit_regex.sub(r'\1<a href="https://old.reddit.com/\2" rel="nofollow noopener noreferrer">/\2</a>', sanitized)
2022-01-11 19:46:50 +00:00
2022-03-21 20:56:43 +00:00
sanitized = sub_regex.sub(r'\1<a href="/\2">/\2</a>', sanitized)
2022-02-05 18:47:21 +00:00
2022-02-28 23:30:44 +00:00
captured = []
2022-02-26 19:56:58 +00:00
for i in mention_regex.finditer(sanitized):
2022-02-28 23:30:44 +00:00
if i.group(0) in captured: continue
captured.append(i.group(0))
2022-01-11 19:46:50 +00:00
u = get_user(i.group(2), graceful=True)
2022-04-19 22:24:43 +00:00
if u and (not (g.v and g.v.any_block_exists(u)) or g.v.admin_level > 1):
2022-04-16 00:18:41 +00:00
sanitized = sanitized.replace(i.group(0), f'''{i.group(1)}<a href="/id/{u.id}"><img loading="lazy" src="/pp/{u.id}">@{u.username}</a>''')
2021-10-15 14:08:27 +00:00
2022-02-28 23:01:57 +00:00
sanitized = imgur_regex.sub(r'\1_d.webp?maxwidth=9999&fidelity=high', sanitized)
2021-10-15 14:08:27 +00:00
2022-02-24 08:28:13 +00:00
soup = BeautifulSoup(sanitized, 'lxml')
2021-10-15 14:08:27 +00:00
for tag in soup.find_all("img"):
2022-03-21 20:56:43 +00:00
if tag.get("src") and not tag["src"].startswith('/pp/'):
2021-10-15 14:08:27 +00:00
tag["loading"] = "lazy"
2021-12-05 01:30:06 +00:00
tag["data-src"] = tag["src"]
2022-03-31 16:28:53 +00:00
tag["src"] = "/assets/images/loading.webp"
2022-01-13 21:15:36 +00:00
tag['alt'] = f'![]({tag["data-src"]})'
2022-02-24 09:24:22 +00:00
tag['referrerpolicy'] = "no-referrer"
2021-10-15 14:08:27 +00:00
2022-04-16 23:00:21 +00:00
for tag in soup.find_all("a"):
if tag.get("href") and fishylinks_regex.fullmatch(str(tag.string)):
tag.string = tag["href"]
2022-03-02 00:05:30 +00:00
2021-10-15 14:08:27 +00:00
sanitized = str(soup)
2022-04-15 22:39:17 +00:00
sanitized = spoiler_regex.sub(r'<spoiler>\1</spoiler>', sanitized)
2021-10-15 14:08:27 +00:00
marseys_used = set()
2022-01-12 03:16:49 +00:00
2022-02-28 23:30:44 +00:00
emojis = list(emoji_regex.finditer(sanitized))
2022-01-21 21:13:52 +00:00
if len(emojis) > 20: edit = True
2022-02-24 08:28:13 +00:00
captured = []
2022-01-21 20:56:56 +00:00
for i in emojis:
2022-02-24 08:28:13 +00:00
if i.group(0) in captured: continue
captured.append(i.group(0))
2021-10-15 14:08:27 +00:00
old = i.group(0)
2022-04-16 15:30:35 +00:00
if 'marseylong1' in old or 'marseylong2' in old or 'marseyllama1' in old or 'marseyllama2' in old: new = old.lower().replace(">", " class='mb-0'>")
else: new = old.lower()
2022-04-15 22:39:17 +00:00
new = render_emoji(new, emoji_regex2, edit, marseys_used, True)
2022-03-22 15:15:19 +00:00
2021-10-15 14:08:27 +00:00
sanitized = sanitized.replace(old, new)
2022-04-27 23:16:24 +00:00
emojis = list(emoji_regex2.finditer(sanitized))
2022-01-21 21:13:52 +00:00
if len(emojis) > 20: edit = True
2022-02-24 08:28:13 +00:00
2022-04-27 23:16:24 +00:00
sanitized = render_emoji(sanitized, emoji_regex2, edit, marseys_used)
2022-03-19 11:37:43 +00:00
2022-04-10 18:46:55 +00:00
for rd in ["://reddit.com", "://new.reddit.com", "://www.reddit.com", "://redd.it", "://libredd.it", "://teddit.net"]:
2022-03-19 11:37:43 +00:00
sanitized = sanitized.replace(rd, "://old.reddit.com")
sanitized = sanitized.replace("nitter.net", "twitter.com").replace("old.reddit.com/gallery", "reddit.com/gallery").replace("https://youtu.be/", "https://youtube.com/watch?v=").replace("https://music.youtube.com/watch?v=", "https://youtube.com/watch?v=").replace("https://streamable.com/", "https://streamable.com/e/").replace("https://youtube.com/shorts/", "https://youtube.com/watch?v=").replace("https://mobile.twitter", "https://twitter").replace("https://m.facebook", "https://facebook").replace("m.wikipedia.org", "wikipedia.org").replace("https://m.youtube", "https://youtube").replace("https://www.youtube", "https://youtube").replace("https://www.twitter", "https://twitter").replace("https://www.instagram", "https://instagram").replace("https://www.tiktok", "https://tiktok")
2022-03-17 18:38:14 +00:00
if "https://youtube.com/watch?v=" in sanitized: sanitized = sanitized.replace("?t=", "&t=")
2022-02-28 23:30:44 +00:00
captured = []
2022-02-28 23:01:57 +00:00
for i in youtube_regex.finditer(sanitized):
2022-04-18 16:01:03 +00:00
if i.group(0) in captured: continue
captured.append(i.group(0))
2021-12-05 16:44:09 +00:00
2022-04-18 16:01:03 +00:00
params = parse_qs(urlparse(i.group(2).replace('&amp;','&')).query)
2021-12-05 16:44:09 +00:00
t = params.get('t', params.get('start', [0]))[0]
if isinstance(t, str): t = t.replace('s','')
2022-04-18 16:01:03 +00:00
htmlsource = f'{i.group(1)}<lite-youtube videoid="{i.group(3)}" params="autoplay=1&modestbranding=1'
2021-12-05 16:44:09 +00:00
if t: htmlsource += f'&start={t}'
htmlsource += '"></lite-youtube>'
2022-04-18 16:01:03 +00:00
sanitized = sanitized.replace(i.group(0), htmlsource)
2022-01-18 11:19:32 +00:00
2022-04-18 16:01:03 +00:00
sanitized = video_sub_regex.sub(r'\1<video controls preload="none"><source src="\2"></video>', sanitized)
2021-10-15 14:08:27 +00:00
2022-01-13 23:44:55 +00:00
if comment:
2022-01-23 23:06:34 +00:00
for marsey in g.db.query(Marsey).filter(Marsey.name.in_(marseys_used)).all():
marsey.count += 1
g.db.add(marsey)
2022-01-12 03:16:49 +00:00
2022-03-24 19:44:12 +00:00
if '#fortune' in sanitized:
sanitized = sanitized.replace('#fortune', '')
2022-03-26 11:38:31 +00:00
sanitized += '\n\n<p>' + choice(FORTUNE_REPLIES) + '</p>'
2022-03-24 19:44:12 +00:00
2022-03-27 14:34:56 +00:00
sanitized = sanitized.replace('&amp;','&')
sanitized = utm_regex.sub('', sanitized)
sanitized = utm_regex2.sub('', sanitized)
2022-04-15 22:39:17 +00:00
sanitized = sanitized.replace('<html><body>','').replace('</body></html>','')
2022-04-16 23:22:48 +00:00
2022-04-15 22:39:17 +00:00
sanitized = bleach.Cleaner(tags=allowed_tags,
attributes=allowed_attributes,
protocols=['http', 'https'],
2022-04-16 20:16:09 +00:00
styles=['color', 'background-color', 'font-weight', 'text-align'],
2022-04-17 20:20:40 +00:00
filters=[partial(LinkifyFilter, skip_tags=["pre"], parse_email=False, callbacks=[callback], url_re=url_re)]
2022-04-15 22:39:17 +00:00
).clean(sanitized)
2022-04-18 18:25:14 +00:00
soup = BeautifulSoup(sanitized, 'lxml')
links = soup.find_all("a")
domain_list = set()
for link in links:
href = link.get("href")
if not href: continue
url = urlparse(href)
domain = url.netloc
2022-04-18 18:45:18 +00:00
url_path = url.path
domain_list.add(domain+url_path)
2022-04-18 18:25:14 +00:00
parts = domain.split(".")
for i in range(len(parts)):
new_domain = parts[i]
for j in range(i + 1, len(parts)):
new_domain += "." + parts[j]
domain_list.add(new_domain)
bans = g.db.query(BannedDomain.domain).filter(BannedDomain.domain.in_(list(domain_list))).all()
if bans: abort(403, description=f"Remove the banned domains {bans} and try again!")
2022-02-17 01:30:59 +00:00
signal.alarm(0)
2021-10-15 14:08:27 +00:00
return sanitized
2021-10-21 20:50:00 +00:00
2022-04-15 22:39:17 +00:00
2022-01-19 06:20:05 +00:00
2022-04-17 20:20:40 +00:00
def allowed_attributes_emojis(tag, name, value):
2022-04-16 23:06:53 +00:00
if tag == 'img':
if name == 'loading' and value == 'lazy': return True
if name == 'data-bs-toggle' and value == 'tooltip': return True
if name in ['src','alt','title','g']: return True
2022-04-17 20:20:40 +00:00
return False
2021-12-07 23:18:06 +00:00
2022-04-16 23:06:53 +00:00
def filter_emojis_only(title, edit=False, graceful=False):
2022-04-15 22:39:17 +00:00
signal.signal(signal.SIGALRM, handler)
2022-02-23 05:19:57 +00:00
signal.alarm(1)
2022-02-18 19:12:14 +00:00
2022-04-15 22:39:17 +00:00
title = title.replace('','').replace('','').replace("\ufeff", "").replace("𒐪","").replace("\n", "").replace("\r", "").replace("\t", "").replace("&", "&amp;").replace('<','&lt;').replace('>','&gt;').replace('"', '&quot;').replace("'", "&#039;").strip()
2021-10-21 20:50:00 +00:00
2022-04-27 23:16:24 +00:00
title = render_emoji(title, emoji_regex3, edit)
2022-01-12 03:16:49 +00:00
2022-02-28 23:01:57 +00:00
title = strikethrough_regex.sub(r'<del>\1</del>', title)
2022-02-22 13:00:41 +00:00
2022-04-17 20:20:40 +00:00
sanitized = bleach.clean(title, tags=['img','del'], attributes=allowed_attributes_emojis, protocols=['http','https'])
2022-04-15 22:39:17 +00:00
2022-02-18 19:12:14 +00:00
signal.alarm(0)
2022-02-14 02:33:27 +00:00
if len(title) > 1500 and not graceful: abort(400)
2022-05-04 03:14:14 +00:00
else: return title