|
| 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 | +}; |
0 commit comments