isIPRange.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = isIPRange;
  6. var _assertString = _interopRequireDefault(require("./util/assertString"));
  7. var _isIP = _interopRequireDefault(require("./isIP"));
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9. var subnetMaybe = /^\d{1,3}$/;
  10. var v4Subnet = 32;
  11. var v6Subnet = 128;
  12. function isIPRange(str) {
  13. var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  14. (0, _assertString.default)(str);
  15. var parts = str.split('/'); // parts[0] -> ip, parts[1] -> subnet
  16. if (parts.length !== 2) {
  17. return false;
  18. }
  19. if (!subnetMaybe.test(parts[1])) {
  20. return false;
  21. } // Disallow preceding 0 i.e. 01, 02, ...
  22. if (parts[1].length > 1 && parts[1].startsWith('0')) {
  23. return false;
  24. }
  25. var isValidIP = (0, _isIP.default)(parts[0], version);
  26. if (!isValidIP) {
  27. return false;
  28. } // Define valid subnet according to IP's version
  29. var expectedSubnet = null;
  30. switch (String(version)) {
  31. case '4':
  32. expectedSubnet = v4Subnet;
  33. break;
  34. case '6':
  35. expectedSubnet = v6Subnet;
  36. break;
  37. default:
  38. expectedSubnet = (0, _isIP.default)(parts[0], '6') ? v6Subnet : v4Subnet;
  39. }
  40. return parts[1] <= expectedSubnet && parts[1] >= 0;
  41. }
  42. module.exports = exports.default;
  43. module.exports.default = exports.default;