1from __future__ import annotations
2
3from collections.abc import Callable
4from contextlib import suppress
5import re
6from urllib.parse import quote, unquote, urlparse, urlunparse # noqa: F401
7
8import mdurl
9
10from .. import _punycode
11
12RECODE_HOSTNAME_FOR = ("http:", "https:", "mailto:")
13
14
15def normalizeLink(url: str) -> str:
16 """Normalize destination URLs in links
17
18 ::
19
20 [label]: destination 'title'
21 ^^^^^^^^^^^
22 """
23 parsed = mdurl.parse(url, slashes_denote_host=True)
24
25 # Encode hostnames in urls like:
26 # `http://host/`, `https://host/`, `mailto:user@host`, `//host/`
27 #
28 # We don't encode unknown schemas, because it's likely that we encode
29 # something we shouldn't (e.g. `skype:name` treated as `skype:host`)
30 #
31 if parsed.hostname and (
32 not parsed.protocol or parsed.protocol in RECODE_HOSTNAME_FOR
33 ):
34 with suppress(Exception):
35 parsed = parsed._replace(hostname=_punycode.to_ascii(parsed.hostname))
36
37 if not parsed.hostname or ":" not in parsed.hostname:
38 return mdurl.encode(mdurl.format(parsed))
39
40 # Encode components before format() adds the IPv6 host brackets.
41 return mdurl.format(
42 parsed._replace(
43 protocol=parsed.protocol and mdurl.encode(parsed.protocol),
44 auth=parsed.auth and mdurl.encode(parsed.auth),
45 hostname=mdurl.encode(parsed.hostname),
46 pathname=parsed.pathname and mdurl.encode(parsed.pathname),
47 search=parsed.search and mdurl.encode(parsed.search),
48 hash=parsed.hash and mdurl.encode(parsed.hash),
49 )
50 )
51
52
53def normalizeLinkText(url: str) -> str:
54 """Normalize autolink content
55
56 ::
57
58 <destination>
59 ~~~~~~~~~~~
60 """
61 parsed = mdurl.parse(url, slashes_denote_host=True)
62
63 # Encode hostnames in urls like:
64 # `http://host/`, `https://host/`, `mailto:user@host`, `//host/`
65 #
66 # We don't encode unknown schemas, because it's likely that we encode
67 # something we shouldn't (e.g. `skype:name` treated as `skype:host`)
68 #
69 if parsed.hostname and (
70 not parsed.protocol or parsed.protocol in RECODE_HOSTNAME_FOR
71 ):
72 with suppress(Exception):
73 parsed = parsed._replace(hostname=_punycode.to_unicode(parsed.hostname))
74
75 # add '%' to exclude list because of https://github.com/markdown-it/markdown-it/issues/720
76 return mdurl.decode(mdurl.format(parsed), mdurl.DECODE_DEFAULT_CHARS + "%")
77
78
79BAD_PROTO_RE = re.compile(r"^(vbscript|javascript|file|data):")
80GOOD_DATA_RE = re.compile(r"^data:image\/(gif|png|jpeg|webp);")
81
82
83def validateLink(url: str, validator: Callable[[str], bool] | None = None) -> bool:
84 """Validate URL link is allowed in output.
85
86 This validator can prohibit more than really needed to prevent XSS.
87 It's a tradeoff to keep code simple and to be secure by default.
88
89 Note: url should be normalized at this point, and existing entities decoded.
90 """
91 if validator is not None:
92 return validator(url)
93 url = url.strip().lower()
94 return bool(GOOD_DATA_RE.search(url)) if BAD_PROTO_RE.search(url) else True