nport 1.0.6 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- The MIT License
2
-
3
- Copyright (c) 2016 Noop Labs LLC http://nooplabs.com
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in
13
- all copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
- THE SOFTWARE.
package/bin/client DELETED
@@ -1,43 +0,0 @@
1
- #!/usr/bin/env node
2
- const optimist = require('optimist');
3
-
4
- let argv = optimist
5
- .usage('Usage: $0 --server [string] --subdomain [string] --hostname [string] --port [number]')
6
- .options('se', {
7
- alias: 'server',
8
- default: 'https://server.nport.link',
9
- describe: 'Tunnel server endpoint'
10
- })
11
- .options('s', {
12
- alias: 'subdomain',
13
- describe: '(Required) Public URL the tunnel server is forwarding to us'
14
- })
15
- .options('h', {
16
- alias: 'hostname',
17
- default: '127.0.0.1',
18
- describe: 'Address of local server for forwarding over socket-tunnel'
19
- })
20
- .options('p', {
21
- alias: 'port',
22
- describe: '(Required) Port of local server for forwarding over socket-tunnel'
23
- })
24
- .argv;
25
-
26
- if (argv.help) {
27
- optimist.showHelp();
28
- process.exit();
29
- }
30
-
31
- if (!argv['server'] || !argv['subdomain'] || !argv['port']) {
32
- for (var key in ['server', 'subdomain', 'port']) {
33
- if (argv[key]) continue;
34
-
35
- console.log('Error: Required option, but nothing found');
36
-
37
- optimist.showHelp();
38
-
39
- process.exit();
40
- }
41
- }
42
-
43
- require('../client.js')(argv);
package/bin/server DELETED
@@ -1,28 +0,0 @@
1
- #!/usr/bin/env node
2
- var optimist = require('optimist');
3
-
4
- var argv = optimist
5
- .usage('Usage: $0 --hostname [string] --port [number] --subdomain [string]')
6
- .options('h', {
7
- alias: 'hostname',
8
- default: '0.0.0.0',
9
- describe: 'Accept connections on this hostname'
10
- })
11
- .options('p', {
12
- alias: 'port',
13
- default: 3000,
14
- describe: 'Server daemon port'
15
- })
16
- .options('s', {
17
- alias: 'subdomain',
18
- default: '',
19
- describe: 'Name of subdomain used. Required when server listens on a subdomain (leave blank otherwise)'
20
- })
21
- .argv;
22
-
23
- if (argv.help) {
24
- optimist.showHelp();
25
- process.exit();
26
- }
27
-
28
- require('../server.js')(argv);
package/client.js DELETED
@@ -1,69 +0,0 @@
1
- 'use strict';
2
-
3
- const IDLE_SOCKET_TIMEOUT_MILLISECONDS = 1000 * 30;
4
-
5
- module.exports = (options) => {
6
- return new Promise((resolve, reject) => {
7
- // require the things we need
8
- const net = require('net');
9
- const ss = require('socket.io-stream');
10
- let socket = require('socket.io-client')(options['server']);
11
-
12
- socket.on('connect', () => {
13
- console.log(new Date() + ': connected');
14
- console.log(new Date() + ': requesting subdomain ' + options['subdomain'] + ' via ' + options['server']);
15
-
16
- socket.emit('createTunnel', options['subdomain'], (err) => {
17
- if (err) {
18
- console.log(new Date() + ': [error] ' + err);
19
-
20
- reject(err);
21
- } else {
22
- console.log(new Date() + ': registered with server successfully');
23
- console.log(new Date() + ': your domain is: https://' + options['subdomain'] + '.nport.link');
24
-
25
- // clean and concat requested url
26
- let url;
27
- let subdomain = options['subdomain'].toString();
28
- let server = options['server'].toString();
29
-
30
- if (server.includes('https://')) {
31
- url = `https://${subdomain}.${server.slice(8)}`;
32
- } else if (server.includes('http://')) {
33
- url = `http://${subdomain}.${server.slice(7)}`;
34
- } else {
35
- url = `https://${subdomain}.${server}`;
36
- }
37
-
38
- // resolve promise with requested URL
39
- resolve(url);
40
- }
41
- });
42
- });
43
-
44
- socket.on('incomingClient', (clientId) => {
45
- let client = net.connect(options['port'], options['hostname'], () => {
46
- let s = ss.createStream();
47
- s.pipe(client).pipe(s);
48
-
49
- s.on('end', () => {
50
- client.destroy();
51
- });
52
-
53
- ss(socket).emit(clientId, s);
54
- });
55
-
56
- client.setTimeout(IDLE_SOCKET_TIMEOUT_MILLISECONDS);
57
- client.on('timeout', () => {
58
- client.end();
59
- });
60
-
61
- client.on('error', () => {
62
- // handle connection refusal (create a stream and immediately close it)
63
- let s = ss.createStream();
64
- ss(socket).emit(clientId, s);
65
- s.end();
66
- });
67
- });
68
- });
69
- };
package/examples/api.js DELETED
@@ -1,9 +0,0 @@
1
- const socketTunnel = require('../lib/api');
2
-
3
- socketTunnel.connect('https://domain.example', 'deviceSubdomain', '2222')
4
- .then((url) => {
5
- console.log(url);
6
- })
7
- .catch((err) => {
8
- console.error(err);
9
- });
package/lib/api.js DELETED
@@ -1,22 +0,0 @@
1
- // client api
2
- const client = require('../client');
3
-
4
- let api = {
5
- connect: (server, subdomain, port, hostname = '127.0.0.1') => {
6
- if (!server || !subdomain || !port || !hostname) {
7
- return Promise.reject(new Error('One or more options were not provided'));
8
- }
9
-
10
- let options = {
11
- server: server,
12
- subdomain: subdomain.toString(),
13
- port: port.toString(),
14
- hostname: hostname
15
- };
16
-
17
- // client returns a promise
18
- return client(options);
19
- }
20
- };
21
-
22
- module.exports = api;
package/nginx.conf.sample DELETED
@@ -1,33 +0,0 @@
1
- # Example of nginx config for proxying requests to socket-tunnel server
2
-
3
- server {
4
- listen *:80;
5
- server_name subdomain.example.com *.subdomain.example.com;
6
- rewrite ^ https://$host$request_uri? permanent;
7
- }
8
-
9
- server {
10
- listen *:443;
11
-
12
- server_name subdomain.example.com *.subdomain.example.com;
13
-
14
- ssl on;
15
- ssl_certificate /path/to/certificate/file.crt;
16
- ssl_certificate_key /path/to/key/file.key;
17
- ssl_prefer_server_ciphers on;
18
-
19
- location / {
20
- proxy_pass http://127.0.0.1:3000/;
21
-
22
- proxy_set_header X-Real-IP $remote_addr;
23
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
24
- proxy_set_header Host $http_host;
25
- proxy_http_version 1.1;
26
- proxy_set_header X-Forwarded-Proto https;
27
- proxy_set_header X-NginX-Proxy true;
28
- proxy_set_header Upgrade $http_upgrade;
29
- proxy_set_header Connection 'upgrade';
30
-
31
- proxy_redirect off;
32
- }
33
- }
package/server.js DELETED
@@ -1,200 +0,0 @@
1
- 'use strict';
2
-
3
- module.exports = (options) => {
4
- // libs
5
- const http = require('http');
6
- const tldjs = require('tldjs');
7
- const ss = require('socket.io-stream');
8
- const uuid = require('uuid/v4');
9
- const isValidDomain = require('is-valid-domain');
10
-
11
- // association between subdomains and socket.io sockets
12
- let socketsBySubdomain = {};
13
-
14
- // bounce incoming http requests to socket.io
15
- let server = http.createServer(async (req, res) => {
16
- getTunnelClientStreamForReq(req).then((tunnelClientStream) => {
17
- const reqBodyChunks = [];
18
-
19
- req.on('error', (err) => {
20
- console.error(err.stack);
21
- });
22
-
23
- // collect body chunks
24
- req.on('data', (bodyChunk) => {
25
- reqBodyChunks.push(bodyChunk);
26
- });
27
-
28
- // proxy finalized request to tunnel stream
29
- req.on('end', () => {
30
- // make sure the client didn't die on us
31
- if (req.complete) {
32
- const reqLine = getReqLineFromReq(req);
33
- const headers = getHeadersFromReq(req);
34
-
35
- let reqBody = null;
36
- if (reqBodyChunks.length > 0) {
37
- reqBody = Buffer.concat(reqBodyChunks);
38
- }
39
-
40
- streamResponse(reqLine, headers, reqBody, tunnelClientStream);
41
- }
42
- });
43
- }).catch((subdomainErr) => {
44
- res.statusCode = 502;
45
- return res.end(subdomainErr.message);
46
- });
47
- });
48
-
49
- // HTTP upgrades (i.e. websockets) are NOT currently supported because socket.io relies on them
50
- // server.on('upgrade', (req, socket, head) => {
51
- // getTunnelClientStreamForReq(req).then((tunnelClientStream) => {
52
- // tunnelClientStream.on('error', () => {
53
- // req.destroy();
54
- // socket.destroy();
55
- // tunnelClientStream.destroy();
56
- // });
57
-
58
- // // get the upgrade request and send it to the tunnel client
59
- // let messageParts = getHeaderPartsForReq(req);
60
-
61
- // messageParts.push(''); // Push delimiter
62
-
63
- // let message = messageParts.join('\r\n');
64
- // tunnelClientStream.write(message);
65
-
66
- // // pipe data between ingress socket and tunnel client
67
- // tunnelClientStream.pipe(socket).pipe(tunnelClientStream);
68
- // }).catch((subdomainErr) => {
69
- // // if we get an invalid subdomain, this socket is most likely being handled by the root socket.io server
70
- // if (!subdomainErr.message.includes('Invalid subdomain')) {
71
- // socket.end();
72
- // }
73
- // });
74
- // });
75
-
76
- function getTunnelClientStreamForReq (req) {
77
- return new Promise((resolve, reject) => {
78
- // without a hostname, we won't know who the request is for
79
- let hostname = req.headers.host;
80
- if (!hostname) {
81
- return reject(new Error('Invalid hostname'));
82
- }
83
-
84
- // make sure we received a subdomain
85
- let subdomain = tldjs.getSubdomain(hostname).toLowerCase();
86
- if (!subdomain) {
87
- return reject(new Error('Invalid subdomain: Please visit https://github.com/tuanngocptn/nport for more information'));
88
- }
89
-
90
- // tldjs library return subdomain as all subdomain path from the main domain.
91
- // Example:
92
- // 1. super.example.com = super
93
- // 2. my.super.example.com = my.super
94
- // 3. If we are running the tunnel server on a subdomain, we must strip it from the provided hostname
95
- if (options.subdomain) {
96
- subdomain = subdomain.replace(`.${options.subdomain}`, '');
97
- }
98
-
99
- let subdomainSocket = socketsBySubdomain[subdomain];
100
- if (!subdomainSocket) {
101
- return reject(new Error(`${subdomain} is currently unregistered or offline.`));
102
- }
103
-
104
- if (req.connection.tunnelClientStream !== undefined && !req.connection.tunnelClientStream.destroyed && req.connection.subdomain === subdomain) {
105
- return resolve(req.connection.tunnelClientStream);
106
- }
107
-
108
- let requestGUID = uuid();
109
- ss(subdomainSocket).once(requestGUID, (tunnelClientStream) => {
110
- req.connection.subdomain = subdomain;
111
- req.connection.tunnelClientStream = tunnelClientStream;
112
-
113
- // Pipe all data from tunnel stream to requesting connection
114
- tunnelClientStream.pipe(req.connection);
115
-
116
- resolve(tunnelClientStream);
117
- });
118
-
119
- subdomainSocket.emit('incomingClient', requestGUID);
120
- });
121
- }
122
-
123
- function getReqLineFromReq (req) {
124
- return `${req.method} ${req.url} HTTP/${req.httpVersion}`;
125
- }
126
-
127
- function getHeadersFromReq (req) {
128
- const headers = [];
129
-
130
- for (let i = 0; i < (req.rawHeaders.length - 1); i += 2) {
131
- headers.push(req.rawHeaders[i] + ': ' + req.rawHeaders[i + 1]);
132
- }
133
-
134
- return headers;
135
- }
136
-
137
- function streamResponse (reqLine, headers, reqBody, tunnelClientStream) {
138
- tunnelClientStream.write(reqLine);
139
- tunnelClientStream.write('\r\n');
140
- tunnelClientStream.write(headers.join('\r\n'));
141
- tunnelClientStream.write('\r\n\r\n');
142
- if (reqBody) {
143
- tunnelClientStream.write(reqBody);
144
- }
145
- }
146
-
147
- // socket.io instance
148
- let io = require('socket.io')(server);
149
- io.on('connection', (socket) => {
150
- socket.on('createTunnel', (requestedName, responseCb) => {
151
- if (socket.requestedName) {
152
- // tunnel has already been created
153
- return;
154
- }
155
-
156
- // domains are case insensitive
157
- let reqNameNormalized = requestedName.toString().toLowerCase().replace(/[^0-9a-z-.]/g, '');
158
-
159
- // make sure the client is requesting a valid subdomain
160
- if (reqNameNormalized.length === 0 || !isValidDomain(`${reqNameNormalized}.example.com`)) {
161
- console.log(new Date() + ': ' + reqNameNormalized + ' -- bad subdomain. disconnecting client.');
162
- if (responseCb) {
163
- responseCb('bad subdomain');
164
- }
165
- return socket.disconnect();
166
- }
167
-
168
- // make sure someone else hasn't claimed this subdomain
169
- if (socketsBySubdomain[reqNameNormalized]) {
170
- console.log(new Date() + ': ' + reqNameNormalized + ' requested but already claimed. disconnecting client.');
171
- if (responseCb) {
172
- responseCb('subdomain already claimed');
173
- }
174
- return socket.disconnect();
175
- }
176
-
177
- // store a reference to this socket by the subdomain claimed
178
- socketsBySubdomain[reqNameNormalized] = socket;
179
- socket.requestedName = reqNameNormalized;
180
- console.log(new Date() + ': ' + reqNameNormalized + ' registered successfully');
181
-
182
- if (responseCb) {
183
- responseCb(null);
184
- }
185
- });
186
-
187
- // when a client disconnects, we need to remove their association
188
- socket.on('disconnect', () => {
189
- if (socket.requestedName) {
190
- delete socketsBySubdomain[socket.requestedName];
191
- console.log(new Date() + ': ' + socket.requestedName + ' unregistered');
192
- }
193
- });
194
- });
195
-
196
- // http server
197
- server.listen(options.port, options.hostname);
198
-
199
- console.log(`${new Date()}: socket-tunnel server started on ${options.hostname}:${options.port}`);
200
- };