WebsocketAddressManager.js 1013 B

123456789101112131415161718192021222324252627282930
  1. const proxyaddr = require('proxy-addr')
  2. module.exports = 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 (this.trust) {
  13. // create a dummy req object using the client handshake and
  14. // connection.remoteAddress for the proxy-addr module to parse
  15. const addressPort = clientHandshake.address
  16. const req = Object.create(clientHandshake, {
  17. connection: {
  18. value: { remoteAddress: addressPort && addressPort.address },
  19. },
  20. })
  21. // return the address parsed from x-forwarded-for
  22. return proxyaddr(req, this.trust)
  23. } else {
  24. // return the address from the client handshake itself
  25. return clientHandshake.address && clientHandshake.address.address
  26. }
  27. }
  28. }