Skip to content

Instantly share code, notes, and snippets.

@median-man
Last active September 2, 2022 13:37
Show Gist options
  • Save median-man/e9a535d644f9b3457e9924d168b31a42 to your computer and use it in GitHub Desktop.
Save median-man/e9a535d644f9b3457e9924d168b31a42 to your computer and use it in GitHub Desktop.
safe_url_angular

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.

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