-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
390 lines (304 loc) · 12.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _child_process = require('child_process');
var _events = require('events');
var _portfinder = require('portfinder');
var _portfinder2 = _interopRequireDefault(_portfinder);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/* AutoSSH class
*/
var AutoSSH = function (_EventEmitter) {
_inherits(AutoSSH, _EventEmitter);
/*
*/
function AutoSSH() {
var conf = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, AutoSSH);
var _this = _possibleConstructorReturn(this, (AutoSSH.__proto__ || Object.getPrototypeOf(AutoSSH)).call(this));
_this.configure(conf);
setImmediate(function () {
var confErrors = _this.getConfErrors(conf);
if (confErrors.length) return confErrors.forEach(function (confErr) {
return _this.emit('error', confErr);
});
return _this.connect(conf);
});
process.on('exit', function () {
_this.kill();
});
return _this;
}
_createClass(AutoSSH, [{
key: 'configure',
value: function configure(conf) {
this.host = conf.host;
this.localHost = conf.localHost || 'localhost';
this.reverse = conf.reverse === true || this.localHost !== 'localhost';
this.username = conf.username || 'root';
this.remotePort = conf.remotePort;
if (this.reverse) this.localPort = parseInt(conf.localPort) || 22;else this.localPort = conf.localPort || 'auto';
this.pollCount = 0;
this.maxPollCount = parseInt(conf.maxPollCount) || 30;
this.pollTimeout = parseInt(conf.pollTimeout) || 75;
this.serverAliveInterval = typeof conf.serverAliveInterval === 'number' ? conf.serverAliveInterval : 120;
this.serverAliveCountMax = typeof conf.serverAliveCountMax === 'number' ? conf.serverAliveCountMax : 1;
this.sshPort = conf.sshPort || 22;
this.privateKey = conf.privateKey || null;
}
/*
*/
}, {
key: 'connect',
value: function connect(conf) {
var _this2 = this;
var port = this.localPort === 'auto' ? this.generateRandomPort() : this.localPort;
if (this.reverse || this.localHost !== 'localhost') {
this.execTunnel(function () {
_this2.pollConnection();
});
} else {
_portfinder2.default.getPort({ port: port }, function (portfinderErr, freePort) {
if (_this2.killed) return;
if (portfinderErr) _this2.emit('error', 'Port error: ' + portfinderErr);
if (_this2.localPort !== 'auto' && _this2.localPort !== freePort) _this2.emit('error', 'Port ' + _this2.localPort + ' is not available');else {
_this2.localPort = freePort;
// creates tunnel and then polls port until connection is established
_this2.execTunnel(function () {
_this2.pollConnection();
});
}
});
}
}
/*
*/
}, {
key: 'getConnectionInfo',
value: function getConnectionInfo() {
var _this3 = this;
var infoObj = {
kill: function kill() {
return _this3.kill;
},
pid: null,
host: this.host || null,
localHost: this.localHost || null,
username: this.username || null,
remotePort: parseInt(this.remotePort),
localPort: parseInt(this.localPort),
execString: this.execString || null
};
if (this.currentProcess) infoObj.pid = this.currentProcess.pid;
if (!infoObj.localPort) infoObj.localPort = null;
if (!infoObj.remotePort) infoObj.remotePort = null;
return infoObj;
}
/* fired when connection established
*/
}, {
key: 'emitConnect',
value: function emitConnect() {
this.emit('connect', this.getConnectionInfo());
}
/* fired when timeout error occurs
*/
}, {
key: 'emitTimeout',
value: function emitTimeout() {
var _this4 = this;
this.emit('timeout', {
kill: function kill() {
return _this4.kill;
},
pid: this.currentProcess.pid,
host: this.host,
username: this.username,
remotePort: this.remotePort,
localPort: this.localPort,
execString: this.execString
});
}
/* starts polling the port to see if connection established
*/
}, {
key: 'pollConnection',
value: function pollConnection() {
var _this5 = this;
if (this.killed) return;
if (this.maxPollCount && this.pollCount >= this.maxPollCount) {
this.emit('error', 'Max poll count reached. Aborting...');
this.kill();
} else {
this.isConnectionEstablished(function (result) {
if (result) _this5.emitConnect();else {
setTimeout(function () {
_this5.pollCount++;
_this5.pollConnection();
}, _this5.pollTimeout);
}
});
}
}
/* checks if connection is established at port
*/
}, {
key: 'isConnectionEstablished',
value: function isConnectionEstablished(connEstablishedCb) {
var _this6 = this;
if (this.localHost !== 'localhost' || this.reverse) {
connEstablishedCb(true);
return;
}
_portfinder2.default.getPort({ port: this.localPort }, function (portfinderErr, freePort) {
if (portfinderErr) return connEstablishedCb(false);
if (_this6.localPort === freePort) return connEstablishedCb(false);else return connEstablishedCb(true);
});
return;
}
/* parses the conf for errors
*/
}, {
key: 'getConfErrors',
value: function getConfErrors(conf) {
var errors = [];
if (!conf.localPort) errors.push('Missing localPort');
if (conf.reverse === true && (conf.localPort === 'auto' || isNaN(parseInt(conf.localPort)))) errors.push('Invalid value for localPort');else if (isNaN(parseInt(conf.localPort)) && conf.localPort !== 'auto') errors.push('Invalid value for localPort');
if (!conf.host) errors.push('Missing host');else if (typeof conf.host !== 'string') {
errors.push('host must be type "string". was given "' + _typeof(conf.host) + '"');
}
if (!conf.username) errors.push('Missing username');else if (typeof conf.username !== 'string') {
errors.push('username must be type "string". was given "' + _typeof(conf.username) + '"');
}
if (!conf.remotePort) errors.push('Missing remotePort');else if (isNaN(parseInt(conf.remotePort))) {
errors.push('remotePort must be type "number". was given "' + _typeof(conf.remotePort) + '"');
}
if (conf.sshPort && isNaN(parseInt(conf.sshPort))) {
errors.push('sshPort must be type "number". was given "' + _typeof(conf.sshPort) + '"');
}
return errors;
}
/*
*/
}, {
key: 'generateRandomPort',
value: function generateRandomPort() {
var minPort = 3000;
var maxPort = 65535;
return Math.floor(Math.random() * (maxPort - minPort + 1)) + minPort;
}
/*
*/
}, {
key: 'generateDefaultOptions',
value: function generateDefaultOptions() {
var exitOnFailure = '-o ExitOnForwardFailure=yes';
var strictHostCheck = '-o StrictHostKeyChecking=no';
return exitOnFailure + ' ' + strictHostCheck;
}
/*
*/
}, {
key: 'generateServerAliveOptions',
value: function generateServerAliveOptions() {
var serverAliveInterval = '-o ServerAliveInterval=' + this.serverAliveInterval;
var serverAliveCountMax = '-o ServerAliveCountMax=' + this.serverAliveCountMax;
return serverAliveInterval + ' ' + serverAliveCountMax;
}
/*
*/
}, {
key: 'generateExecOptions',
value: function generateExecOptions() {
var serverAliveOpts = this.generateServerAliveOptions();
var defaultOpts = this.generateDefaultOptions();
var privateKey = this.privateKey ? '-i ' + this.privateKey : '';
var sshPort = this.sshPort === 22 ? '' : '-p ' + this.sshPort;
var gatewayPorts = this.localHost === 'localhost' ? '' : '-o GatewayPorts=yes';
return defaultOpts + ' ' + serverAliveOpts + ' ' + gatewayPorts + ' ' + privateKey + ' ' + sshPort;
}
/*
*/
}, {
key: 'generateExecString',
value: function generateExecString() {
var startPort = this.reverse ? this.remotePort : this.localPort;
var endPort = this.reverse ? this.localPort : this.remotePort;
var bindAddress = startPort + ':' + this.localHost + ':' + endPort;
var options = this.generateExecOptions();
var userAtHost = this.username + '@' + this.host;
var method = this.reverse ? 'R' : 'L';
return 'ssh -N' + method + ' ' + bindAddress + ' ' + options + ' ' + userAtHost;
}
/*
*/
}, {
key: 'execTunnel',
value: function execTunnel(execTunnelCb) {
var _this7 = this;
this.execString = this.generateExecString();
this.currentProcess = (0, _child_process.exec)(this.execString, function (execErr, stdout, stderr) {
if (_this7.killed) return;
if (/Address already in use/i.test(stderr)) {
_this7.kill();
_this7.emit('error', stderr);
return;
}
if (execErr) {
if (/(timeout)|(timed out)/i.test(stderr)) _this7.emitTimeout();else _this7.emit('error', execErr);
}
if (!_this7.killed) _this7.execTunnel(function () {
return console.log('Restarting autossh...');
});
});
if (typeof execTunnelCb === 'function') setImmediate(function () {
return execTunnelCb();
});
}
/*
*/
}, {
key: 'kill',
value: function kill() {
this.killed = true;
if (this.currentProcess && typeof this.currentProcess.kill === 'function') this.currentProcess.kill();
return this;
}
}]);
return AutoSSH;
}(_events.EventEmitter);
/* Export
*/
module.exports = function (conf) {
var autossh = new AutoSSH(conf);
/* Create interface object
A new object creates an abstraction from class implementation
*/
var autosshInterface = {
on: function on(evt) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
autossh.on.apply(autossh, [evt].concat(args));
return this;
},
kill: function kill() {
autossh.kill();
return this;
}
};
Object.defineProperty(autosshInterface, 'info', {
get: function get() {
return autossh.getConnectionInfo();
}
});
Object.defineProperty(autosshInterface, 'pid', {
get: function get() {
if (autossh.currentProcess) return autossh.currentProcess.pid;else return null;
}
});
return autosshInterface;
};