netUtils.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ipIsPrivateV4Address = exports.upgradeSocket = exports.describeAddress = exports.describeTLS = void 0;
  4. const tls_1 = require("tls");
  5. /**
  6. * Returns a string describing the encryption on a given socket instance.
  7. */
  8. function describeTLS(socket) {
  9. if (socket instanceof tls_1.TLSSocket) {
  10. const protocol = socket.getProtocol();
  11. return protocol ? protocol : "Server socket or disconnected client socket";
  12. }
  13. return "No encryption";
  14. }
  15. exports.describeTLS = describeTLS;
  16. /**
  17. * Returns a string describing the remote address of a socket.
  18. */
  19. function describeAddress(socket) {
  20. if (socket.remoteFamily === "IPv6") {
  21. return `[${socket.remoteAddress}]:${socket.remotePort}`;
  22. }
  23. return `${socket.remoteAddress}:${socket.remotePort}`;
  24. }
  25. exports.describeAddress = describeAddress;
  26. /**
  27. * Upgrade a socket connection with TLS.
  28. */
  29. function upgradeSocket(socket, options) {
  30. return new Promise((resolve, reject) => {
  31. const tlsOptions = Object.assign({}, options, {
  32. socket
  33. });
  34. const tlsSocket = (0, tls_1.connect)(tlsOptions, () => {
  35. const expectCertificate = tlsOptions.rejectUnauthorized !== false;
  36. if (expectCertificate && !tlsSocket.authorized) {
  37. reject(tlsSocket.authorizationError);
  38. }
  39. else {
  40. // Remove error listener added below.
  41. tlsSocket.removeAllListeners("error");
  42. resolve(tlsSocket);
  43. }
  44. }).once("error", error => {
  45. reject(error);
  46. });
  47. });
  48. }
  49. exports.upgradeSocket = upgradeSocket;
  50. /**
  51. * Returns true if an IP is a private address according to https://tools.ietf.org/html/rfc1918#section-3.
  52. * This will handle IPv4-mapped IPv6 addresses correctly but return false for all other IPv6 addresses.
  53. *
  54. * @param ip The IP as a string, e.g. "192.168.0.1"
  55. */
  56. function ipIsPrivateV4Address(ip = "") {
  57. // Handle IPv4-mapped IPv6 addresses like ::ffff:192.168.0.1
  58. if (ip.startsWith("::ffff:")) {
  59. ip = ip.substr(7); // Strip ::ffff: prefix
  60. }
  61. const octets = ip.split(".").map(o => parseInt(o, 10));
  62. return octets[0] === 10 // 10.0.0.0 - 10.255.255.255
  63. || (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) // 172.16.0.0 - 172.31.255.255
  64. || (octets[0] === 192 && octets[1] === 168) // 192.168.0.0 - 192.168.255.255
  65. || ip === "127.0.0.1";
  66. }
  67. exports.ipIsPrivateV4Address = ipIsPrivateV4Address;