index.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. var parse = require('url-parse');
  3. /**
  4. * Transform an URL to a valid origin value.
  5. *
  6. * @param {String|Object} url URL to transform to it's origin.
  7. * @returns {String} The origin.
  8. * @api public
  9. */
  10. function origin(url) {
  11. if ('string' === typeof url) url = parse(url);
  12. //
  13. // 6.2. ASCII Serialization of an Origin
  14. // http://tools.ietf.org/html/rfc6454#section-6.2
  15. //
  16. if (!url.protocol || !url.hostname) return 'null';
  17. //
  18. // 4. Origin of a URI
  19. // http://tools.ietf.org/html/rfc6454#section-4
  20. //
  21. // States that url.scheme, host should be converted to lower case. This also
  22. // makes it easier to match origins as everything is just lower case.
  23. //
  24. return (url.protocol +'//'+ url.host).toLowerCase();
  25. }
  26. /**
  27. * Check if the origins are the same.
  28. *
  29. * @param {String} a URL or origin of a.
  30. * @param {String} b URL or origin of b.
  31. * @returns {Boolean}
  32. * @api public
  33. */
  34. origin.same = function same(a, b) {
  35. return origin(a) === origin(b);
  36. };
  37. //
  38. // Expose the origin
  39. //
  40. module.exports = origin;