0

I was wondering if there is a programmatic way of sanitizing (user provided) URLs in AngularJs 1.5. I know there is $sanitize service, which is for sanitizing HTML but I can't find something that would work for URL.

Sample Good URL:

http://www.somedomain.com

Sample Dangerous URL:

javascript:document.write('Time for some fun');
Parth Shah
  • 2,060
  • 1
  • 23
  • 34

2 Answers2

0

There is undocumented $$sanitizeUri service that does this. It's basically a function that adds unsafe prefix to supplied URL. There's no need to use it for URLs are bound to href like

<a href="{{url}}">

because this is already done by compiler ($$sanitizeUri is used there).

For malformed URLs in general it may be better to process them by hand and possibly add http:// if it doesn't contain acceptable (http/https) protocol.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
0

I ended up performing the following regex test (inspired from $$sanitizeUri service) on the URLs and then performing a special operation whenever the check failed.

function navigateToUrl(url) {
    var safeWhiteListRegex = \^(https?|ftps?|file?):\/\/\gi;
    if (!safeWhiteListRegex.test(url)) {
        // url = ...;
    } else {
        $window.open(url, "_blank");
    }
}

Along the way, one of my friends also discovered the @braintree/sanitize-url Node Module, which I also think is something people can use for situations like this.

Parth Shah
  • 2,060
  • 1
  • 23
  • 34