diff --git a/README.md b/README.md index 7cfa697..8df3140 100644 --- a/README.md +++ b/README.md @@ -120,3 +120,7 @@ bot.postMessageToUser('user', 'hi').always(function(data) { }) ``` +### HTTP Proxy Support + +This package can work behind a corporate proxy when the `HTTP_PROXY` environment variable is set, +ie: `HTTP_PROXY=http://10.60.10.1:3128` diff --git a/index.js b/index.js index 5c921b4..871c504 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,8 @@ var Vow = require('vow'); var extend = require('extend'); var WebSocket = require('ws'); var EventEmitter = require('events').EventEmitter; +var HttpsProxyAgent = require('https-proxy-agent'); +var Url = require('url'); var { setWsHeartbeat } = require('ws-heartbeat/client'); class Bot extends EventEmitter { @@ -21,6 +23,10 @@ class Bot extends EventEmitter { this.disconnect = params.disconnect; console.assert(params.token, 'token must be defined'); + + this._configureProxy(params.proxy || undefined); + + this.login(); if (!this.disconnect) { this.login(); } @@ -51,7 +57,7 @@ class Bot extends EventEmitter { * Establish a WebSocket connection */ connect() { - this.ws = new WebSocket(this.wsUrl); + this.ws = new WebSocket(this.wsUrl, {agent: this._agent}); setWsHeartbeat(this.ws, '{ "kind": "ping" }'); @@ -499,6 +505,34 @@ class Bot extends EventEmitter { }); }); } + + /** + * Use a HTTP Proxy is supplied in the params of the custructor, otherwise look at the environment vars + * for proxy configuration. We need to accomodate both uppercase and lowercase environment definitions. + * + * @param {string} proxy + * @private + */ + _configureProxy(proxy) { + if (!proxy && ((typeof process.env['http_proxy'] !== 'undefined' && process.env['http_proxy']) || (typeof process.env['HTTP_PROXY'] !== 'undefined' && process.env['HTTP_PROXY']))) { + proxy = process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + + this._agent = null; + if (proxy) { + try { + // Url.parse can throw it's own errors but strangely doesn't throw when the url is not really valid. + var proxyUrl = Url.parse(process.env['http_proxy'] || process.env['HTTP_PROXY']); + if (!proxyUrl.hostname) { + throw new Error('Invalid HTTP_PROXY environment variable value'); + } + + this._agent = new HttpsProxyAgent(proxyUrl); + } catch (e) { + console.error(e); + } + } + } } module.exports = Bot; diff --git a/package.json b/package.json index c0afa82..c04676f 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ }, "dependencies": { "extend": "^2.0.1", + "https-proxy-agent": "^2.1.1", "lodash": "^4.17.2", "request": "^2.56.0", "vow": "^0.4.9",