Angular style url "whitelist" pattern. I found this snippet while reading Preventing XSS in React. The snippet is sournced from Angular which has an "MIT style" license.
Last active
September 2, 2022 13:37
-
-
Save median-man/e9a535d644f9b3457e9924d168b31a42 to your computer and use it in GitHub Desktop.
safe_url_angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file|sms):|[^&:/?#]*(?:[/?#]|$))/gi; | |
/** A pattern that matches safe data URLs. It only matches image, video, and audio types. */ | |
const DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+\/]+=*$/i; | |
function _sanitizeUrl(url: string): string { | |
url = String(url); | |
if (url === "null" || url.length === 0 || url === "about:blank") return "about:blank"; | |
if (url.match(SAFE_URL_PATTERN) || url.match(DATA_URL_PATTERN)) return url; | |
return `unsafe:${url}`; | |
} | |
export function sanitizeUrl(url = "about:blank"): string { | |
return _sanitizeUrl(String(url).trim()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment