WebsocketAddressManager.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import proxyaddr from 'proxy-addr'
  2. export default class WebsocketAddressManager {
  3. constructor(behindProxy, trustedProxyIps) {
  4. if (behindProxy) {
  5. // parse trustedProxyIps comma-separated list the same way as express
  6. this.trust = proxyaddr.compile(
  7. trustedProxyIps ? trustedProxyIps.split(/ *, */) : []
  8. )
  9. }
  10. }
  11. getRemoteIp(clientHandshake) {
  12. if (!clientHandshake) {
  13. return 'client-handshake-missing'
  14. } else if (this.trust) {
  15. // create a dummy req object using the client handshake and
  16. // connection.remoteAddress for the proxy-addr module to parse
  17. try {
  18. const addressPort = clientHandshake.address
  19. const req = {
  20. headers: {
  21. 'x-forwarded-for':
  22. clientHandshake.headers &&
  23. clientHandshake.headers['x-forwarded-for'],
  24. },
  25. connection: { remoteAddress: addressPort && addressPort.address },
  26. }
  27. // return the address parsed from x-forwarded-for
  28. return proxyaddr(req, this.trust)
  29. } catch (err) {
  30. return 'client-handshake-invalid'
  31. }
  32. } else {
  33. // return the address from the client handshake itself
  34. return clientHandshake.address && clientHandshake.address.address
  35. }
  36. }
  37. }