-
Notifications
You must be signed in to change notification settings - Fork 39
/
webserver.js
98 lines (77 loc) · 2.38 KB
/
webserver.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
90
91
92
93
94
95
96
97
98
#!/usr/bin/env node
require('../env').normalizeEnv()
const fs = require('fs')
const path = require('path')
const express = require('express')
const HttpProxy = require('http-proxy')
const https = require('https')
const http = require('http')
const url = require('url')
const env = process.env
const setupProxy = (path, target) => {
const proxy = HttpProxy.createProxyServer({
target,
ws: true
})
proxy.on('error', (error, req, res) => {
let json
if (error.code !== 'ECONNRESET' && error.code !== 'ECONNREFUSED') {
console.error('proxy error', error)
}
json = {error: 'server_error', reason: (path || 'client') + ' is unavailable', path, target}
res.end(JSON.stringify(json))
})
app.use('/' + path, (req, res) => {
proxy.web(req, res, { target })
})
return proxy
}
const setupWebsocket = server => {
server.on('upgrade', (req, socket, head) => {
let u = url.parse(req.url).pathname.split('/')[1]
const parsedUrl = url.parse(req.url)
if (u === 'api') {
parsedUrl.pathname = parsedUrl.pathname.replace('/api', '')
req.url = url.format(parsedUrl)
proxyA.ws(req, socket, head)
}
if (u === 'ledger') {
parsedUrl.pathname = parsedUrl.pathname.replace('/ledger', '')
req.url = url.format(parsedUrl)
proxyL.ws(req, socket, head)
}
})
}
const app = new express()
// Ledger proxy
const lUrl = 'http://' + env.LEDGER_HOSTNAME + ':' + env.LEDGER_PORT
const proxyL = setupProxy('ledger', lUrl)
// Api proxy
const aUrl = 'http://' + env.API_HOSTNAME + ':' + env.API_PORT
const proxyA = setupProxy('api', aUrl)
// Webfinger proxy
app.use('/.well-known/webfinger', (req, res) => {
proxyA.web(req, res, { target: aUrl + '/webfinger' })
})
if (env.NODE_ENV === 'production') {
// Static files (Web Client)
app.use(express.static(path.resolve(__dirname, '../client/build')))
} else {
// Client proxy
const cUrl = 'http://' + env.CLIENT_HOST + ':' + env.CLIENT_PORT
setupProxy('', cUrl)
}
// Servers
const cert = env.WALLET ? `./${env.WALLET}.com.pem` : './wallet1.com.pem'
const httpServer = http.createServer(app)
const httpsServer = https.createServer({
key: fs.readFileSync(cert),
cert: fs.readFileSync(cert)
}, app)
// WebSockets
setupWebsocket(httpServer)
setupWebsocket(httpsServer)
// Start
httpServer.listen(80)
httpsServer.listen(443)
console.log('Started a webserver on ports 80 and 443')