url_sanitizer.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. /**
  3. * @license
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. Object.defineProperty(exports, "__esModule", { value: true });
  7. exports.restrictivelySanitizeUrl = exports.unwrapUrlOrSanitize = exports.sanitizeJavascriptUrl = void 0;
  8. /**
  9. * @fileoverview Provides functions to enforce the SafeUrl contract at the sink
  10. * level.
  11. */
  12. require("../environment/dev");
  13. function extractScheme(url) {
  14. var parsedUrl;
  15. try {
  16. parsedUrl = new URL(url);
  17. }
  18. catch (e) {
  19. // According to https://url.spec.whatwg.org/#constructors, the URL
  20. // constructor with one parameter throws if `url` is not absolute. In this
  21. // case, we are sure that no explicit scheme (javascript: ) is set.
  22. // This can also be a URL parsing error, but in this case the URL won't be
  23. // run anyway.
  24. return 'https:';
  25. }
  26. return parsedUrl.protocol;
  27. }
  28. // We can't use an ES6 Set here because gws somehow depends on this code and
  29. // doesn't want to pay the cost of a polyfill.
  30. var ALLOWED_SCHEMES = ['data:', 'http:', 'https:', 'mailto:', 'ftp:'];
  31. /**
  32. * Checks that the URL scheme is not javascript.
  33. * The URL parsing relies on the URL API in browsers that support it.
  34. * @param url The URL to sanitize for a SafeUrl sink.
  35. * @return undefined if url has a javascript: scheme, the original URL
  36. * otherwise.
  37. */
  38. function sanitizeJavascriptUrl(url) {
  39. var parsedScheme = extractScheme(url);
  40. if (parsedScheme === 'javascript:') {
  41. if (process.env.NODE_ENV !== 'production') {
  42. console.error("A URL with content '".concat(url, "' was sanitized away."));
  43. }
  44. return undefined;
  45. }
  46. return url;
  47. }
  48. exports.sanitizeJavascriptUrl = sanitizeJavascriptUrl;
  49. /**
  50. * Adapter to sanitize string URLs in DOM sink wrappers.
  51. * @return undefined if the URL was sanitized.
  52. */
  53. function unwrapUrlOrSanitize(url) {
  54. return sanitizeJavascriptUrl(url);
  55. }
  56. exports.unwrapUrlOrSanitize = unwrapUrlOrSanitize;
  57. /**
  58. * Sanitizes a URL restrictively.
  59. * This sanitizer protects against XSS and potentially other uncommon and
  60. * undesirable schemes that an attacker could use for e.g. phishing (tel:,
  61. * callto: ssh: etc schemes). This sanitizer is primarily meant to be used by
  62. * the HTML sanitizer.
  63. */
  64. function restrictivelySanitizeUrl(url) {
  65. var parsedScheme = extractScheme(url);
  66. if (parsedScheme !== undefined &&
  67. ALLOWED_SCHEMES.indexOf(parsedScheme.toLowerCase()) !== -1) {
  68. return url;
  69. }
  70. return 'about:invalid#zClosurez';
  71. }
  72. exports.restrictivelySanitizeUrl = restrictivelySanitizeUrl;