-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
219 lines (202 loc) · 5.55 KB
/
server.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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/env node
const { config, execute, restartOrbitron } = require('./lib')
const http = require('http')
const https = require('https')
const fs = require('fs')
const path = require('path')
const getListeners = []
const postListeners = []
function addGETListener(callback){
getListeners.push(callback)
}
function addPOSTListener(callback){
postListeners.push(callback)
}
function getContentType(filePath){
let extname = path.extname(filePath)
let contentType = 'text/html'
switch (extname) {
case '.js':
contentType = 'text/javascript'
break;
case '.css':
contentType = 'text/css'
break;
case '.json':
contentType = 'application/json'
break;
case '.png':
contentType = 'image/png'
break;
case '.jpg':
contentType = 'image/jpg'
break;
case '.svg':
contentType = 'image/svg+xml'
break;
case '.ico':
contentType = 'image/x-icon'
break;
case '.wav':
contentType = 'audio/wav'
break;
case '.zip':
contentType = 'application/zip'
break;
case '.oft':
contentType = 'font/otf'
break;
}
//console.log(filePath, extname, contentType)
return contentType
}
function respondWithFile(response, filePath){
filePath = `${__dirname}${filePath}`
let contentType = getContentType(filePath)
fs.readFile(filePath, async function(error, content) {
if (error) {
if(error.code == 'ENOENT'){
response.writeHead(404, { 'Content-Type': 'text/html' })
response.end(await fs.promises.readFile("controller/instructions.html"), 'utf-8')
}
else {
response.writeHead(500)
response.end('Sorry, check with the site admin for error: '+error.code+' ..\n')
}
}
else {
response.writeHead(200, { 'Content-Type': contentType })
response.end(content, 'utf-8')
}
});
}
async function serverHandler(request, response) {
// Github webhook to restart pm2 after a push
if (request.method === 'POST') {
let body = ''
request.on('data', function(data) {
body += data
})
request.on('end', async function() {
let handled = false
for (const listener of postListeners) {
handled = await listener(response, body)
if(handled) break
}
if(!handled){
console.error("UNHANDLED SERVER POST: ", request.url)
response.writeHead(500)
response.end('unhandled post')
}
})
return
}
// http GET stuff
let [filePath, search] = request.url.split("?")
let queryParams = {}
if (search) {
const searchParams = new URLSearchParams(search)
for (const [key, value] of searchParams) {
queryParams[key] = value
}
}
if(filePath.endsWith('/'))
filePath = filePath.substring(0,filePath.length-1)
let handled = false
let processed = filePath.split("/")
let orbID = processed.length > 1 ? processed[1] : ''
orbID = orbID.toLowerCase()
orbID = config.reverseAliases[orbID] ?? orbID
for (const listener of getListeners) {
handled = await listener(response, orbID, filePath, queryParams)
if(handled) break
}
if(!handled){
respondWithFile(response, filePath)
}
}
const rootServerPort = config.HTTP_SERVER_PORT || 1337
let redirectServer
let rootServer
let certLastUpdatedFile = `${require('os').homedir()}/certLastUpdated.json`
if(config.HAS_EMULATION || config.IS_RELAY){
if(rootServerPort == 443){
runServerWithRedirect()
} else {
openRootServer()
}
}
async function runServerWithRedirect(){
let certUpdateTime = Date.now()
if(fs.existsSync(certLastUpdatedFile)){
let json = JSON.parse(fs.readFileSync(certLastUpdatedFile).toString())
certUpdateTime = json.time + 1000 * 60 * 60 * 24 * 10 // try every 10 days
}
let delay = certUpdateTime - Date.now()
if(delay <= 0){
await updateCert()
} else {
setTimeout(updateCert, delay)
await openRootServer()
await openRedirectServer()
}
}
async function updateCert(){
console.log("UPDATING SSL CERT")
await closeRootServer()
await closeRedirectServer()
let result = (await execute("certbot renew"))
console.log("Certbot renew output: ", result)
let lastUpdated = {
time: Date.now()
}
fs.writeFileSync(certLastUpdatedFile, JSON.stringify(lastUpdated))
console.log("RESTARTING AFTER CERT UPDATE")
await restartOrbitron()
}
async function openRootServer(){
await closeRootServer()
if (config.DEV_MODE) {
rootServer = http.createServer(config, serverHandler)
} else {
rootServer = https.createServer(config.httpsOptions, serverHandler)
}
rootServer.listen(rootServerPort, "0.0.0.0",()=>{console.log("Root server listening on port " + rootServerPort)})
}
async function closeRootServer(){
return new Promise((resolve, reject) =>{
if(rootServer){
rootServer.closeAllConnections()
rootServer.close(()=>{
rootServer = null
resolve()
})
} else {
resolve()
}
})
}
async function openRedirectServer(){
await closeRedirectServer()
redirectServer = http.createServer((req, res)=>{
res.writeHead(301,{Location: `https://${req.headers.host}${req.url}`})
res.end()
})
redirectServer.listen(80,"0.0.0.0",()=>{console.log("Redirect server listening on port 80")})
}
async function closeRedirectServer(){
return new Promise((resolve, reject) =>{
if(redirectServer){
redirectServer.closeAllConnections()
redirectServer.close(()=>{
redirectServer = null
resolve()
})
} else {
resolve()
}
})
}
module.exports = {
addGETListener, addPOSTListener, respondWithFile
}