-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
255 lines (238 loc) · 7.52 KB
/
main.js
File metadata and controls
255 lines (238 loc) · 7.52 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
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#!/usr/bin/env node
import { createServer } from 'http'
import { Buffer } from 'buffer'
import { promises, existsSync } from 'fs'
import qs from 'querystring'
import { URL } from 'url'
import { spawn } from 'child_process'
import process from 'process'
import * as pathModule from 'path'
let serverDirName = './'
let args = process.argv
if (args[2]) serverDirName = args[2]
const flattenValues = obj =>
Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v.flat()]))
let htmlPagePath = pathModule.join(serverDirName, 'page.html')
let htmlPageText = (await promises.readFile(htmlPagePath)).toString('utf8')
const renderHtml = (path, vars) =>
htmlPageText
.replace(
'/*=-title-=*/',
path == '/index' ? 'Home' : path.split('/').at(-1)
)
.replace('/*=-path-=*/', path.split('/').at(-1))
.replace('/*=-vars-=*/', JSON.stringify(vars))
const cachedFiles = {}
/**
* @param {String} filePath
* @returns {Promise<Buffer>}
*/
async function getFile(filePath) {
if (!cachedFiles[filePath]) {
let file = await promises.readFile(filePath).catch(() => '')
if (file) cachedFiles[filePath] = file
else return null
}
return cachedFiles[filePath]
}
/**
* @param {String} path
*/
async function render(path) {
path = path == '/' ? '/index' : path
if (path.startsWith('/pages/') || path.startsWith('/components/')) {
if (!path.endsWith('.js')) return null
let fullPath = pathModule.join(serverDirName, path)
let file = await getFile(fullPath)
if (!file) return null
return { content: file }
}
if (path.startsWith('/static/')) {
let fullPath = pathModule.join(serverDirName, path)
let file = await getFile(fullPath)
if (!file) return null
return { content: file }
}
let pagePath = pathModule.join(serverDirName, 'pages', path + '.js')
if (!existsSync(pagePath)) return null
let serverPath = pathModule.join(serverDirName, 'server', path)
let serverResponse = ''
const dirContents = await promises.readdir(pathModule.dirname(serverPath))
const basePath = pathModule.basename(serverPath)
const serverFileExtension = dirContents
.find(e => e.startsWith(basePath))
?.slice(basePath.length)
if (serverFileExtension) {
const serverProgram = spawn(
pathModule.join(
serverDirName,
'server',
`${path}${serverFileExtension}`
),
['']
)
serverResponse = await new Promise((resolve, reject) => {
serverProgram.stdout.on('data', data => resolve(data.toString()))
serverProgram.stderr.on('data', data => reject(data.toString()))
})
}
let response = {}
try {
response = JSON.parse(serverResponse)
} catch {
response.content = serverResponse
}
if (!path.includes('api'))
response.content = renderHtml(path, response.content)
return response
}
/** @param {string} path */
function getMIMEtype(path) {
return (
{
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.json': 'application/json',
'.pdf': 'application/pdf',
'.txt': 'text/plain',
'.mp4': 'video/mp4',
'.webm': 'video/webm',
'.mp3': 'audio/mpeg',
'.wav': 'audio/wav',
'.ogg': 'audio/ogg',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'font/opentype',
'.ttf': 'font/truetype',
'.zip': 'application/zip',
'.rar': 'application/x-rar-compressed',
'.7z': 'application/x-7z-compressed',
'.tar': 'application/x-tar',
'.gz': 'application/x-gzip',
'.bz2': 'application/x-bzip2',
'.xz': 'application/x-xz'
}[path.slice(path.lastIndexOf('.'))] || 'text/html'
)
}
class RequestCounter extends Array {
tick() {
this.push(Date.now())
while (this[0] < Date.now() - 1000) this.shift()
if (this.length > serverOptions.maxRequestsPerSecond)
this.timeoutUntil =
Date.now() + serverOptions.timeoutMinutes * 60 * 1000
}
isInvalid() {
return this.timeoutUntil && this.timeoutUntil > Date.now()
}
}
const reqIPs = {}
async function getPostData(req) {
const buffers = []
for await (const chunk of req) {
buffers.push(chunk)
}
const data = Buffer.concat(buffers).toString()
return qs.parse(data)
}
function getCookies(req) {
const cookies = req.headers.cookie
if (!cookies) return {}
return Object.fromEntries(
cookies.split(';').map(e => {
let splits = e.split('=')
return [splits.shift(), splits.join('=')]
})
)
}
const createCookie = async ({
name,
value,
expires = null,
path = null,
secure = false,
httpOnly = true,
domain = null,
maxAge = null,
sameSite = null
}) =>
`${name || ''}=${value || ''}` +
(expires != null ? `; Expires=${new Date(expires).toUTCString()}` : '') +
(maxAge != null ? `; Max-Age=${maxAge}` : '') +
(domain != null ? `; Domain=${domain}` : '') +
(path != null ? `; Path=${path}` : '') +
(secure ? '; Secure' : '') +
(httpOnly ? '; HttpOnly' : '') +
(sameSite != null ? `; SameSite=${sameSite}` : '')
/** @param {http.IncomingMessage} req @param {http.ServerResponse} res */
async function handleReq(req, res) {
let ip = req.socket.remoteAddress
if (!reqIPs[ip]) reqIPs[ip] = new RequestCounter()
reqIPs[ip].tick()
if (reqIPs[ip].isInvalid()) {
/* global console */
console.log(`access denied to ${ip} for spamming`)
res.writeHead(429, {
'Retry-After': serverOptions.timeoutMinutes / 60
})
res.end()
return
}
let url = new URL(req.url, `http://${req.headers.host}`)
let path = url.pathname
let searchParams = flattenValues(
Object.fromEntries(url.searchParams.entries())
)
let postData = await getPostData(req)
let cookies = getCookies(req)
let mimeType = getMIMEtype(path)
try {
let response = await render(path, { searchParams, postData, cookies })
if (!response) return
if (response.redirect) {
this.res.writeHead(302, {
Location: response.redirect
})
this.res.end()
return
}
if (response.cookies) {
response.cookies.forEach(cookie =>
res.setHeader('Set-Cookie', createCookie(cookie))
)
}
res.writeHead(200, {
'Content-Type': mimeType + '; charset=utf-8',
...(response.headers ?? {})
})
res.end(response.content)
} catch (err) {
console.error(err)
res.writeHead(404)
res.end()
}
}
export const serverOptions = {
maxRequestsPerSecond: 100,
timeoutMinutes: 5,
port: 8000
}
function start() {
let httpServer = createServer(handleReq)
httpServer.listen(serverOptions.port, () =>
console.log(
`listening on ${httpServer.address().address}:${
httpServer.address().port
}`
)
)
}
start()