8
0

utils.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module link/utils
  7. */
  8. const ATTRIBUTE_WHITESPACES = /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g; // eslint-disable-line no-control-regex
  9. const SAFE_URL = /^(?:(?:https?|ftps?|mailto):|[^a-z]|[a-z+.-]+(?:[^a-z+.:-]|$))/i;
  10. /**
  11. * Returns `true` if a given view node is the link element.
  12. *
  13. * @param {module:engine/view/node~Node} node
  14. * @returns {Boolean}
  15. */
  16. export function isLinkElement( node ) {
  17. return node.is( 'attributeElement' ) && !!node.getCustomProperty( 'link' );
  18. }
  19. /**
  20. * Creates link {@link module:engine/view/attributeelement~AttributeElement} with provided `href` attribute.
  21. *
  22. * @param {String} href
  23. * @returns {module:engine/view/attributeelement~AttributeElement}
  24. */
  25. export function createLinkElement( href, writer ) {
  26. // Priority 5 - https://github.com/ckeditor/ckeditor5-link/issues/121.
  27. const linkElement = writer.createAttributeElement( 'a', { href }, { priority: 5 } );
  28. writer.setCustomProperty( 'link', true, linkElement );
  29. return linkElement;
  30. }
  31. /**
  32. * Returns a safe URL based on a given value.
  33. *
  34. * An URL is considered safe if it is safe for the user (does not contain any malicious code).
  35. *
  36. * If URL is considered unsafe, a simple `"#"` is returned.
  37. *
  38. * @protected
  39. * @param {*} url
  40. * @returns {String} Safe URL.
  41. */
  42. export function ensureSafeUrl( url ) {
  43. url = String( url );
  44. return isSafeUrl( url ) ? url : '#';
  45. }
  46. // Checks whether the given URL is safe for the user (does not contain any malicious code).
  47. //
  48. // @param {String} url URL to check.
  49. function isSafeUrl( url ) {
  50. const normalizedUrl = url.replace( ATTRIBUTE_WHITESPACES, '' );
  51. return normalizedUrl.match( SAFE_URL );
  52. }