-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (78 loc) · 2.1 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
'use strict';
const gcloudSsh = require('gcloud-ssh');
const net = require('net');
class GcloudSshTunnel {
constructor({ remotePort, localPort, ...sshOptions }) {
this.remotePort = remotePort;
this.localPort = localPort;
this.sshOptions = sshOptions;
this.connections = [];
this.result = {
close: () => this.close(),
};
}
start() {
let promise = this.promise();
Object.assign(promise, this.result);
return promise;
}
close() {
if (this.clientPromise) this.clientPromise.end();
if (this.server) this.server.close();
for (let connection of this.connections) {
connection.end().unref();
}
}
async promise() {
await this.ssh();
try {
await this.listen();
} catch (err) {
this.client.end();
throw err;
}
return {
port: this.localPort,
client: this.client,
server: this.server,
close: () => this.close(),
};
}
async ssh() {
this.clientPromise = gcloudSsh(this.sshOptions);
this.client = await this.clientPromise;
this.client.on('close', () => this.close());
}
listen() {
return new Promise((resolve, reject) => {
this.server = net.createServer().unref();
this.server
.on('listening', () => {
this.localPort = this.server.address().port;
resolve();
})
.on('error', err => {
this.close();
reject(err);
})
.on('connection', connection => {
this.connections.push(connection);
connection.on('close', () => {
this.connections.splice(this.connections.indexOf(connection), 1)
});
this.client.forwardOut('localhost', this.remotePort, 'localhost', this.remotePort, (err, stream) => {
if (err) {
connection.end();
return;
}
connection.pipe(stream).pipe(connection);
});
});
this.server.listen(this.localPort, 'localhost');
});
}
}
function gcloudSshTunnel(options) {
return new GcloudSshTunnel(options).start();
}
module.exports = gcloudSshTunnel;