HTTPS support, Promise API, modern ES syntax

* Add support for tunneling a local HTTPS server.
* Return a Promise from localtunnel.
This commit is contained in:
Gert Hengeveld
2019-09-16 16:30:13 +02:00
committed by Roman Shtylman
parent d7330a7121
commit 2a74d6be9f
16 changed files with 719 additions and 663 deletions

View File

@@ -1,39 +1,23 @@
var stream = require('stream');
var util = require('util');
const { Transform } = require('stream');
var Transform = stream.Transform;
class HeaderHostTransformer extends Transform {
constructor(opts = {}) {
super(opts);
this.host = opts.host || 'localhost';
this.replaced = false;
}
var HeaderHostTransformer = function(opts) {
if (!(this instanceof HeaderHostTransformer)) {
return new HeaderHostTransformer(opts);
}
opts = opts || {}
Transform.call(this, opts);
var self = this;
self.host = opts.host || 'localhost';
self.replaced = false;
_transform(data, encoding, callback) {
callback(
null,
this.replaced // after replacing the first instance of the Host header we just become a regular passthrough
? data
: data.toString().replace(/(\r\n[Hh]ost: )\S+/, (match, $1) => {
this.replaced = true;
return $1 + this.host;
})
);
}
}
util.inherits(HeaderHostTransformer, Transform);
HeaderHostTransformer.prototype._transform = function (chunk, enc, cb) {
var self = this;
// after replacing the first instance of the Host header
// we just become a regular passthrough
if (!self.replaced) {
chunk = chunk.toString();
self.push(chunk.replace(/(\r\n[Hh]ost: )\S+/, function(match, $1) {
self.replaced = true;
return $1 + self.host;
}));
}
else {
self.push(chunk);
}
cb();
};
module.exports = HeaderHostTransformer;

View File

@@ -1,158 +1,163 @@
var url = require('url');
var EventEmitter = require('events').EventEmitter;
var axios = require('axios');
var debug = require('debug')('localtunnel:client');
/* eslint-disable consistent-return, no-underscore-dangle */
var TunnelCluster = require('./TunnelCluster');
const { parse } = require('url');
const { EventEmitter } = require('events');
const axios = require('axios');
const debug = require('debug')('localtunnel:client');
var Tunnel = function(opt) {
if (!(this instanceof Tunnel)) {
return new Tunnel(opt);
const TunnelCluster = require('./TunnelCluster');
module.exports = class Tunnel extends EventEmitter {
constructor(opts = {}) {
super(opts);
this.opts = opts;
this.closed = false;
if (!this.opts.host) {
this.opts.host = 'https://localtunnel.me';
}
}
var self = this;
self._closed = false;
self._opt = opt || {};
_getInfo(body) {
/* eslint-disable camelcase */
const { id, ip, port, url, cached_url, max_conn_count } = body;
const { host, port: local_port, local_host } = this.opts;
const { local_https, local_cert, local_key, local_ca, allow_invalid_cert } = this.opts;
return {
name: id,
url,
cached_url,
max_conn: max_conn_count || 1,
remote_host: parse(host).hostname,
remote_ip: ip,
remote_port: port,
local_port,
local_host,
local_https,
local_cert,
local_key,
local_ca,
allow_invalid_cert,
};
/* eslint-enable camelcase */
}
self._opt.host = self._opt.host || 'https://localtunnel.me';
};
// initialize connection
// callback with connection info
_init(cb) {
const opt = this.opts;
const getInfo = this._getInfo.bind(this);
Tunnel.prototype.__proto__ = EventEmitter.prototype;
// initialize connection
// callback with connection info
Tunnel.prototype._init = function(cb) {
var self = this;
var opt = self._opt;
var params = {
responseType: 'json'
const params = {
responseType: 'json',
};
var base_uri = opt.host + '/';
// optionally override the upstream server
var upstream = url.parse(opt.host);
const baseUri = `${opt.host}/`;
// no subdomain at first, maybe use requested domain
var assigned_domain = opt.subdomain;
const assignedDomain = opt.subdomain;
// where to quest
var uri = base_uri + ((assigned_domain) ? assigned_domain : '?new');
const uri = baseUri + (assignedDomain || '?new');
(function get_url() {
axios.get(uri, params)
.then(function(res){
var body = res.data;
if (res.status !== 200) {
var err = new Error((body && body.message) || 'localtunnel server returned an error, please try again');
return cb(err);
}
var port = body.port;
var host = upstream.hostname;
var max_conn = body.max_conn_count || 1;
cb(null, {
remote_host: upstream.hostname,
remote_port: body.port,
name: body.id,
url: body.url,
max_conn: max_conn
});
})
.catch(function(err){
// TODO (shtylman) don't print to stdout?
console.log('tunnel server offline: ' + err.message + ', retry 1s');
return setTimeout(get_url, 1000);
(function getUrl() {
axios
.get(uri, params)
.then(res => {
const body = res.data;
debug('got tunnel information', res.data);
if (res.status !== 200) {
const err = new Error(
(body && body.message) || 'localtunnel server returned an error, please try again'
);
return cb(err);
}
cb(null, getInfo(body));
})
.catch(err => {
debug(`tunnel server offline: ${err.message}, retry 1s`);
return setTimeout(getUrl, 1000);
});
})();
};
Tunnel.prototype._establish = function(info) {
var self = this;
var opt = self._opt;
}
_establish(info) {
// increase max event listeners so that localtunnel consumers don't get
// warning messages as soon as they setup even one listener. See #71
self.setMaxListeners(info.max_conn + (EventEmitter.defaultMaxListeners || 10));
this.setMaxListeners(info.max_conn + (EventEmitter.defaultMaxListeners || 10));
info.local_host = opt.local_host;
info.local_port = opt.port;
var tunnels = self.tunnel_cluster = TunnelCluster(info);
this.tunnelCluster = new TunnelCluster(info);
// only emit the url the first time
tunnels.once('open', function() {
self.emit('url', info.url);
this.tunnelCluster.once('open', () => {
this.emit('url', info.url);
});
// re-emit socket error
tunnels.on('error', function(err) {
self.emit('error', err);
this.tunnelCluster.on('error', err => {
debug('got socket error', err.message);
this.emit('error', err);
});
var tunnel_count = 0;
let tunnelCount = 0;
// track open count
tunnels.on('open', function(tunnel) {
tunnel_count++;
debug('tunnel open [total: %d]', tunnel_count);
this.tunnelCluster.on('open', tunnel => {
tunnelCount++;
debug('tunnel open [total: %d]', tunnelCount);
var close_handler = function() {
tunnel.destroy();
};
const closeHandler = () => {
tunnel.destroy();
};
if (self._closed) {
return close_handler();
}
if (this.closed) {
return closeHandler();
}
self.once('close', close_handler);
tunnel.once('close', function() {
self.removeListener('close', close_handler);
});
this.once('close', closeHandler);
tunnel.once('close', () => {
this.removeListener('close', closeHandler);
});
});
// when a tunnel dies, open a new one
tunnels.on('dead', function(tunnel) {
tunnel_count--;
debug('tunnel dead [total: %d]', tunnel_count);
if (self._closed) {
return;
}
tunnels.open();
this.tunnelCluster.on('dead', () => {
tunnelCount--;
debug('tunnel dead [total: %d]', tunnelCount);
if (this.closed) {
return;
}
this.tunnelCluster.open();
});
tunnels.on('request', function(info) {
self.emit('request', info);
this.tunnelCluster.on('request', req => {
this.emit('request', req);
});
// establish as many tunnels as allowed
for (var count = 0 ; count < info.max_conn ; ++count) {
tunnels.open();
for (let count = 0; count < info.max_conn; ++count) {
this.tunnelCluster.open();
}
};
}
Tunnel.prototype.open = function(cb) {
var self = this;
open(cb) {
this._init((err, info) => {
if (err) {
return cb(err);
}
self._init(function(err, info) {
if (err) {
return cb(err);
}
this.clientId = info.name;
this.url = info.url;
self.url = info.url;
self._establish(info);
cb();
// `cached_url` is only returned by proxy servers that support resource caching.
if (info.cached_url) {
this.cachedUrl = info.cached_url;
}
this._establish(info);
cb();
});
}
close() {
this.closed = true;
this.emit('close');
}
};
// shutdown tunnels
Tunnel.prototype.close = function() {
var self = this;
self._closed = true;
self.emit('close');
};
module.exports = Tunnel;

View File

@@ -1,133 +1,152 @@
var EventEmitter = require('events').EventEmitter;
var debug = require('debug')('localtunnel:client');
var net = require('net');
const { EventEmitter } = require('events');
const debug = require('debug')('localtunnel:client');
const fs = require('fs');
const net = require('net');
const tls = require('tls');
var HeaderHostTransformer = require('./HeaderHostTransformer');
const HeaderHostTransformer = require('./HeaderHostTransformer');
// manages groups of tunnels
var TunnelCluster = function(opt) {
if (!(this instanceof TunnelCluster)) {
return new TunnelCluster(opt);
}
module.exports = class TunnelCluster extends EventEmitter {
constructor(opts = {}) {
super(opts);
this.opts = opts;
}
var self = this;
self._opt = opt;
open() {
const opt = this.opts;
EventEmitter.call(self);
};
// Prefer IP if returned by the server
const remoteHostOrIp = opt.remote_ip || opt.remote_host;
const remotePort = opt.remote_port;
const localHost = opt.local_host || 'localhost';
const localPort = opt.local_port;
const localProtocol = opt.local_https ? 'https' : 'http';
const allowInvalidCert = opt.allow_invalid_cert;
TunnelCluster.prototype.__proto__ = EventEmitter.prototype;
// establish a new tunnel
TunnelCluster.prototype.open = function() {
var self = this;
var opt = self._opt || {};
var remote_host = opt.remote_host;
var remote_port = opt.remote_port;
var local_host = opt.local_host || 'localhost';
var local_port = opt.local_port;
debug('establishing tunnel %s:%s <> %s:%s', local_host, local_port, remote_host, remote_port);
debug(
'establishing tunnel %s://%s:%s <> %s:%s',
localProtocol,
localHost,
localPort,
remoteHostOrIp,
remotePort
);
// connection to localtunnel server
var remote = net.connect({
host: remote_host,
port: remote_port
const remote = net.connect({
host: remoteHostOrIp,
port: remotePort,
});
remote.setKeepAlive(true);
remote.on('error', function(err) {
// emit connection refused errors immediately, because they
// indicate that the tunnel can't be established.
if (err.code === 'ECONNREFUSED') {
self.emit('error', new Error('connection refused: ' + remote_host + ':' + remote_port + ' (check your firewall settings)'));
}
remote.on('error', err => {
debug('got remote connection error', err.message);
remote.end();
// emit connection refused errors immediately, because they
// indicate that the tunnel can't be established.
if (err.code === 'ECONNREFUSED') {
this.emit(
'error',
new Error(
`connection refused: ${remoteHostOrIp}:${remotePort} (check your firewall settings)`
)
);
}
remote.end();
});
function conn_local() {
if (remote.destroyed) {
debug('remote destroyed');
self.emit('dead');
return;
const connLocal = () => {
if (remote.destroyed) {
debug('remote destroyed');
this.emit('dead');
return;
}
debug('connecting locally to %s://%s:%d', localProtocol, localHost, localPort);
remote.pause();
if (allowInvalidCert) {
debug('allowing invalid certificates');
}
const getLocalCertOpts = () =>
allowInvalidCert
? { rejectUnauthorized: false }
: {
cert: fs.readFileSync(opt.local_cert),
key: fs.readFileSync(opt.local_key),
ca: opt.local_ca ? [fs.readFileSync(opt.local_ca)] : undefined,
};
// connection to local http server
const local = opt.local_https
? tls.connect({ host: localHost, port: localPort, ...getLocalCertOpts() })
: net.connect({ host: localHost, port: localPort });
const remoteClose = () => {
debug('remote close');
this.emit('dead');
local.end();
};
remote.once('close', remoteClose);
// TODO some languages have single threaded servers which makes opening up
// multiple local connections impossible. We need a smarter way to scale
// and adjust for such instances to avoid beating on the door of the server
local.once('error', err => {
debug('local error %s', err.message);
local.end();
remote.removeListener('close', remoteClose);
if (err.code !== 'ECONNREFUSED') {
return remote.end();
}
debug('connecting locally to %s:%d', local_host, local_port);
remote.pause();
// retrying connection to local server
setTimeout(connLocal, 1000);
});
// connection to local http server
var local = net.connect({
host: local_host,
port: local_port
});
local.once('connect', () => {
debug('connected locally');
remote.resume();
function remote_close() {
debug('remote close');
self.emit('dead');
local.end();
};
let stream = remote;
remote.once('close', remote_close);
// TODO some languages have single threaded servers which makes opening up
// multiple local connections impossible. We need a smarter way to scale
// and adjust for such instances to avoid beating on the door of the server
local.once('error', function(err) {
debug('local error %s', err.message);
local.end();
remote.removeListener('close', remote_close);
if (err.code !== 'ECONNREFUSED') {
return remote.end();
}
// retrying connection to local server
setTimeout(conn_local, 1000);
});
local.once('connect', function() {
debug('connected locally');
remote.resume();
var stream = remote;
// if user requested specific local host
// then we use host header transform to replace the host header
if (opt.local_host) {
debug('transform Host header to %s', opt.local_host);
stream = remote.pipe(HeaderHostTransformer({ host: opt.local_host }));
}
stream.pipe(local).pipe(remote);
// when local closes, also get a new remote
local.once('close', function(had_error) {
debug('local connection closed [%s]', had_error);
});
});
}
remote.on('data', function(data) {
const match = data.toString().match(/^(\w+) (\S+)/);
if (match) {
self.emit('request', {
method: match[1],
path: match[2],
});
// if user requested specific local host
// then we use host header transform to replace the host header
if (opt.local_host) {
debug('transform Host header to %s', opt.local_host);
stream = remote.pipe(new HeaderHostTransformer({ host: opt.local_host }));
}
stream.pipe(local).pipe(remote);
// when local closes, also get a new remote
local.once('close', hadError => {
debug('local connection closed [%s]', hadError);
});
});
};
remote.on('data', data => {
const match = data.toString().match(/^(\w+) (\S+)/);
if (match) {
this.emit('request', {
method: match[1],
path: match[2],
});
}
});
// tunnel is considered open when remote connects
remote.once('connect', function() {
self.emit('open', remote);
conn_local();
remote.once('connect', () => {
this.emit('open', remote);
connLocal();
});
}
};
module.exports = TunnelCluster;