-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
278 lines (263 loc) · 8.41 KB
/
main.js
File metadata and controls
278 lines (263 loc) · 8.41 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { createServer } from 'http'
import { Buffer } from 'buffer'
import { promises, existsSync } from 'fs'
import qs from 'querystring'
import { URL } from 'url'
import * as pathModule from 'path'
import { fileURLToPath } from 'url'
const __dirname = pathModule.dirname(fileURLToPath(import.meta.url))
/**
* HTML escape a string
* @param {String} s string to HTML escape
* @returns {String} escaped string
*/
const escapeHTML = s =>
s.replace(/[^0-9A-Za-z ]/g, c => '&#' + c.charCodeAt(0) + ';')
/**
* HTML escape an object
* @param {Object} obj object to HTML escape
* @returns {Object} object with HTML escaped strings
*/
const objEscapeHTML = obj =>
Object.entries(obj).reduce((obj, e) => {
obj[e[0]] = escapeHTML(e[1])
return obj
}, {})
/**
* Flatten an array and return the first non-array element
* @param {Array} a
* @returns {any}
*/
const arrToFlat = a => (Array.isArray(a) ? arrToFlat(a[0]) : a)
/**
* flatten arrays in an object - returns the first non-array element for each value in the object
* @param {Object<Array>} obj object with arrays to flatten as values
* @returns {Object<Array>} object with flattened arrays as values
*/
const flatten = obj =>
Object.entries(obj).reduce((obj, e) => {
obj[e[0]] = arrToFlat(e[1])
return obj
}, {})
const cachedFiles = {}
/**
* @param {String} filePath
* @returns {Promise<Buffer>}
*/
async function getFile(filePath) {
if (!cachedFiles[filePath])
cachedFiles[filePath] = await promises.readFile(filePath)
return cachedFiles[filePath]
}
let htmlPagePath = pathModule.join(__dirname, 'page.html')
let htmlPageText = (await promises.readFile(htmlPagePath)).toString('utf8')
const preRenderedPages = {}
async function getRenderedPage(path, vars) {
if (!preRenderedPages[path])
preRenderedPages[path] = htmlPageText
.replace(
'/*=-title-=*/',
path == '/index' ? 'Home' : path.split('/').at(-1)
)
.replace('/*=-path-=*/', path.split('/').at(-1))
return preRenderedPages[path].replace('/*=-vars-=*/', JSON.stringify(vars))
}
/**
* @param {RunningRequest} rr
*/
async function render(rr) {
let path = rr.path == '/' ? '/index' : rr.path
if (path.split('/').at(-1).includes('.')) {
if (
(path.startsWith('/pages/') || path.startsWith('/components/')) &&
path.endsWith('.js')
) {
let filePath = pathModule.join(__dirname, path)
return getFile(filePath)
}
let filePath = pathModule.join(__dirname, 'static', path)
return getFile(filePath)
} else {
rr.mimeType = getMIMEtype('.html')
let serverPath = pathModule.join(__dirname, 'server', path + '.js')
let pagePath = pathModule.join(__dirname, 'pages', path + '.js')
if (!existsSync(pagePath)) throw new Error(`no page at ${path}`)
let vars = {}
if (existsSync(serverPath)) {
let callback = (await import(`./server${path}.js`)).flami
vars = await callback(rr)
if (!rr.active) return false
if (serverPath.includes('api')) return JSON.stringify(vars)
}
return getRenderedPage(path, vars)
}
}
/** @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/plain'
)
}
export class RunningRequest {
/**
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
*/
constructor(req, res) {
this.active = true
this.req = req
this.res = res
this.ip = req.socket.remoteAddress
this.url = new URL(req.url, `http://${req.headers.host}`)
this.path = this.url.pathname
this.params = flatten(
Object.fromEntries(this.url.searchParams.entries())
)
this.mimeType = getMIMEtype(this.path)
this.escapeHTML = escapeHTML
this.objEscapeHTML = objEscapeHTML
this.flatten = flatten
}
/** @returns {Promise<qs.ParsedUrlQuery>} post data */
async getPostData() {
const buffers = []
for await (const chunk of this.req) {
buffers.push(chunk)
}
const data = Buffer.concat(buffers).toString()
return qs.parse(data)
}
/**
* @param {String} name
* @returns {Promise<String>} cookie value
*/
async getCookie(name) {
const cookies = this.req.headers.cookie
if (!cookies) return null
const cookie = cookies
.split(';')
.find(c => c.trim().startsWith(name + '='))
if (!cookie) return null
const cookieSplit = cookie.split('=')
cookieSplit.shift()
return cookieSplit.join('=')
}
async setCookie(
name,
value,
expires = null,
path = null,
secure = false,
httpOnly = true,
domain = null,
maxAge = null,
sameSite = null
) {
let cookie =
`${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}` : '')
this.res.setHeader('Set-Cookie', cookie)
}
/** @param {String} location */
async redirect(location) {
this.res.writeHead(302, {
Location: location
})
this.res.end()
this.active = false
}
}
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.DDOStimeoutMinutes * 60 * 1000
}
isInvalid() {
return this.timeoutUntil && this.timeoutUntil > Date.now()
}
}
const reqIPs = {}
/** @param {http.IncomingMessage} req @param {http.ServerResponse} res */
async function handleReq(req, res) {
if (!reqIPs[req.socket.remoteAddress])
reqIPs[req.socket.remoteAddress] = new RequestCounter()
reqIPs[req.socket.remoteAddress].tick()
if (reqIPs[req.socket.remoteAddress].isInvalid()) {
console.log(`access denied to ${req.socket.remoteAddress} for spamming`)
res.writeHead(429, {
'Retry-After': serverOptions.DDOStimeoutMinutes / 60
})
res.end()
return
}
const rr = new RunningRequest(req, res)
try {
let response = await render(rr)
if (!response) return
res.writeHead(200, {
'Content-Type': rr.mimeType + '; charset=utf-8'
})
res.end(response)
} catch (err) {
console.error(err)
res.writeHead(404)
res.end()
}
}
export const serverOptions = {
maxRequestsPerSecond: 100,
DDOStimeoutMinutes: 5,
port: 80
}
function start() {
let httpServer = createServer(handleReq)
httpServer.listen(serverOptions.port, () =>
console.log(
`listening on ${httpServer.address().address}:${
httpServer.address().port
}`
)
)
}
start()