Line data Source code
1 2356 : const SAFE_EXTERNAL_URL_SCHEMES = new Set(['http:', 'https:'])
2 :
3 : /** `URL.parse` for browsers that lack it (Chrome < 126, Safari < 18). */
4 6 : export function parseUrl(url: string, base?: string): URL | null {
5 6 : try {
6 6 : return new URL(url, base)
7 : } catch {
8 0 : return null
9 : }
10 : }
11 :
12 : /**
13 : * Checks that `url` is a syntactically valid URL using only an http(s)
14 : * scheme, for use wherever a URL is bound to a clickable `href` (e.g. an
15 : * `<a>` tag) and could otherwise come from untrusted data (such as a
16 : * third-party registry). Unlike a bare `new URL(url)` validity check, this
17 : * rejects `javascript:`, `data:`, and other schemes that parse without
18 : * throwing but execute or render content on click.
19 : */
20 6 : export function isSafeExternalUrl(url: string): boolean {
21 6 : try {
22 6 : return SAFE_EXTERNAL_URL_SCHEMES.has(new URL(url).protocol)
23 : } catch {
24 0 : return false
25 : }
26 : }
|