-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproxy.js
More file actions
170 lines (149 loc) · 5.4 KB
/
Copy pathproxy.js
File metadata and controls
170 lines (149 loc) · 5.4 KB
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
'use strict'
let Meta = require('lsq-meta')
let routes = require('./routes')
let http = require('http')
let httpProxy = require('http-proxy')
let tooBusy = require('toobusy-js')
let Url = require('url')
let isIp = new RegExp(/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):?([0-9]{1,5})?$/)
class Proxy {
constructor () {
this._proxy = httpProxy.createProxyServer({'ws': true, 'xfwd': false})
this.updateConfig({})
this.startProxy()
}
updateConfig (config) {
this._page404 = config.page404 || `<html><head><style>h1{margin: auto; position: absolute; top: 0; left: 0; right: 0; bottom: 0; height: 100px; font-family: 'arial'; font-weight: 100; color: #555; text-align: center; }body{background:#000;}</style></head><body><h1>404 Not Found</h1></body></html>`
}
startProxy () {
this._serverHttp = http.createServer(this._proxyingWeb.bind(this))
this._serverHttp.on('upgrade', this._proxyingWebSockets.bind(this))
this._serverHttp.listen(process.env.PORT || 80)
console.log('listen on port ' + (process.env.PORT || 80))
return this._serverHttp
}
_isLocal (req, res) {
if (!isIp.test(req.headers.host) &&
req.headers.host !== (process.env.MYHOST || 'localhost') + ':' + process.env.PORT &&
req.headers.host !== (process.env.HOSTNAME || '') + ':' + process.env.PORT) return false
this._checkRoutes(req, res)
return true
}
_proxyingWeb (req, res) {
if (this._isLocal(req, res)) return
if (process.env.DEBUG) {
console.log('DEBUG :: _proxyingWeb : ', req.headers.host + req.url)
}
routes.getTarget('http://' + req.headers.host + req.url, req.headers)
.then(host=> this._replaceServerUrl(host), ()=> this._routePage404(req, res))
.done(host=> this._proxyWeb(req, res, host))
}
_proxyingWebSockets (req, res, socket, head) {
if (this._isLocal(req, res)) return
routes.getTarget('http://' + req.headers.host + req.url, req.headers)
.then(host=> this._replaceServerUrl(host), ()=> this._routePage404(req, res))
.done(host=> this._proxyWeb(req, res, host))
}
_proxyWebSockets (req, socket, head, opt, cb) {
req.headers.host = req.headers.host || ''
let url = Url.parse(opt.target)
req.headers.host = req.headers.host || ''
req.url = url.path
try {
req.headers['x-forwarded-for'] = req.connection.remoteAddress
this._proxy.ws(req, socket, head, opt, (err, d)=> {
if (err && err.code && err.code === 'ECONNREFUSED' && typeof cb === 'function') cb()
})
} catch (e) {}
}
_proxyWeb (req, res, opt, cb) {
if (!isObject(opt)) return this._checkRoutes(req, res)
let error = false
let url = Url.parse(opt.target)
req.headers.host = req.headers.host || ''
req.url = url.path
url.pathname = ''
opt.target = Url.format({ protocol: url.protocol, host: url.host})
if (process.env.DEBUG) {
console.log('DEBUG :: _proxyWeb : ', opt.target + req.url)
}
if (opt.redirect) return this._webRedirect(req, res, opt)
try {
this._setXHeaders(req)
if (opt.changeHost) req.headers['host'] = url.host
if (process.env.DEBUG_HEADERS) {
console.log('DEBUG :: headers : ', req.headers)
}
this._proxy.web(req, res, opt, (err, d)=> {
if (err && err.code) {
if (err.code === 'ECONNREFUSED' && typeof cb === 'function') cb()
else if (!error) this._routePage404(req, res)
}
})
} catch(e) {
error = true
this._routePage404(req, res)
}
}
_routeHealthCheck (req, res) {
res.end(tooBusy.lag() + '')
}
_routePage404 (req, res) {
this._sendWeb(res, this._page404 || '404', 404)
}
_checkRoutes (req, res) {
let theUrlis = Url.parse('http://' + req.headers.host + req.url)
switch (theUrlis.pathname) {
case '/health':
this._routeHealthCheck(req, res)
break
default:
this._routePage404(req, res)
}
}
_webRedirect (req, res, opt) {
req.headers['location'] = Url.resolve(opt.target, req.url)
res.writeHead(302, req.headers)
res.end()
}
_sendWeb (res, content, code) {
if (!res.headersSent) {
if (typeof code === 'number') res.writeHead(code)
res.end(content)
}
}
_replaceServerUrl (host) {
let url = Url.parse(host.target)
if (process.env.DEBUG) {
console.log('DEBUG :: _replaceServerUrl : ', url.hostname)
}
return Meta.service(url.hostname)
.then(service=> {
console.log(service)
url.host = service + ''
host.target = (service ? Url.format(url) : host.target)
if (process.env.DEBUG) {
console.log('DEBUG :: _replaceServerUrlSuccess : ', host)
}
return host
}, ()=> host)
}
_setXHeaders (req) {
req.headers['x-forwarded-for'] = req.connection.remoteAddress
req.headers['x-forwarded-host'] = req.headers.host
req.headers['x-forwarded-port'] = this._getPort(req)
req.headers['x-forwarded-proto'] = (req.isSpdy || this._hasEncryptedConnection(req)) ? 'https' : 'http'
}
_getPort (req) {
var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : ''
return res ? res[1] : this._hasEncryptedConnection(req) ? '443' : '80'
}
_hasEncryptedConnection (req) {
return Boolean(req.connection.encrypted || req.connection.pair)
}
}
function isObject(a) {
return typeof a === 'object'
}
let proxy = new Proxy()
module.exports = proxy