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
|
const express = require('express')
const app = express()
const rateLimit = require('express-rate-limit')
const helmet = require('helmet')
const bp = require('body-parser')
const cookieParser = require('cookie-parser')
const fs = require('fs')
const path = require('path')
const { readdirSync } = require('fs')
const session = require('./src/session')()
const mime = {
html: 'text/html',
txt: 'text/plain',
css: 'text/css',
xml: 'text/xml',
gif: 'image/gif',
jpg: 'image/jpeg',
png: 'image/png',
webp: 'image/webp',
avif: 'image/avif',
ico: 'image/ico',
svg: 'image/svg+xml',
js: 'application/javascript',
json: 'application/json',
mp4: 'video/mp4',
webm: 'video/webm',
ttf: 'application/x-font-truetype',
ttc: 'application/x-font-truetype',
otf: 'application/x-font-otf',
ots: 'application/x-font-otf',
woff: 'application/font-woff',
woff2: 'application/font-woff',
pfb: 'application/vnd.ms-fontbook',
pfm: 'application/vnd.ms-fontbook',
gsf: 'application/vnd.ms-fontbook',
swf: 'application/vnd.ms-fontbook'
}
const assetDir = () => {
return readdirSync(`${__dirname}/assets`, { withFileTypes: true })
.filter(dir => dir.isDirectory())
.map(dir => dir.name)
}
// ! Setup later
/*
const limiter = rateLimit({
windowMS: 30 * 1000,
max: 100,
message: '<h1>Rate Limit Exceeded</h1><p>You have exceeded the allowed number of requests. Please try again later.</p>'
})
*/
require('dotenv').config()
const sitemap = require('./src/sitemap')
const logger = require('./src/logger')({
baseURL: process.env.baseURL
})
const createLog = (req, res, next) => {
const { cookies } = req
const object = {
queryString: '',
exists: false
}
Object.entries(req.query).forEach(([key, value]) => {
if (object.exists === false) {
object.queryString += '?'
}
object.queryString += `${key}=${value}&`
object.exists = true
})
if (object.exists) object.queryString = object.queryString.slice(0, -1)
logger.Info(`${req.method} ${req.path}${object.queryString} from ${req.ip}:${cookies.session_id ? cookies.session_id.replace('session_id', '') : 'n/a'}`)
next()
}
const validateCookie = (req, res, next) => {
const { cookies } = req
if (cookies === undefined) {
res.cookie('session_id', session.Create())
} else {
if ('session_id' in cookies) {
if (session.Exists(cookies.session_id.replace('session_id', ''))) {
session.Expired()
} else {
res.clearCookie('session_id')
res.cookie('session_id', session.Create())
}
} else res.cookie('session_id', session.Create())
}
next()
}
const openFile = x => {
const data = {
path: x.filePath.split('/'),
exists: false,
data: {}
}
if (assetDir().includes(data.path[1])) {
this.path = `${__dirname}/assets/${data.path[1]}/${data.path[2]}`
data.exists = fs.existsSync(this.path)
data.data.mime = mime[path.extname(this.path).slice(1)] || 'text/plain'
data.data.file = fs.createReadStream(this.path)
.on('error', (err) => {
return
})
} else if (data.path[1] === 'favicon.ico' && (data.path.length === 2 || (data.path.length === 3 && data.path[2] === ''))) {
data.data.file = fs.createReadStream(`${__dirname}/config/favicon.ico`)
.on('error', (err) => {
logger.Error(`'favicon.ico' does not exist. Please add it to the config.`)
})
}
if (data.exists) {
x.res.set('Content-Type', data.data.mime)
data.data.file
.on('open', () => {
data.data.file.pipe(x.res)
})
.on('error', err => {
logger.Error(err)
})
} else {
x.res.set('Content-Type', mime.html)
x.res.status(404).send('File not found.')
}
}
app.use(bp.json())
app.use(cookieParser())
app.use((req, res, next) => {
let err = null
try {
decodeURIComponent(req.path)
} catch (e) {
err = e
}
if (err) {
return res.redirect(['http://', req.get('Host'), '/404'].join(''))
}
next()
})
const handleRoutes = (req, res, next) => {
this.path = {
split: req.path.split('/'),
string: req.path
}
if(routes.has(this.path.string)) {
const route = routes.get(this.path.string)
if (route.req === req.method) {
res.send(route.method())
} else {
next()
}
} else {
next()
}
}
const routeData = {
app: app,
validateCookie: validateCookie,
//log: createLog,
mime: mime,
session: session
}
const routeConfigData = routeData
routeConfigData.logger = logger
const controller = require('./src/controller')({
baseURL: process.env.baseURL,
app: app,
validateCookie: validateCookie,
log: createLog,
mime: mime,
session: session,
logger: logger,
mime: mime
})
app.route(/(.*)/)
.get(validateCookie, createLog, (req, res) => {
this.path = {
split: req.path.split('/'),
string: req.path
}
if (assetDir().includes(this.path.split[1])) {
openFile({
filePath: this.path.string,
res: res
})
} else {
switch (this.path.split[1]) {
case 'favicon.ico':
openFile({
filePath: this.path.string,
res: res
})
break
case 'sitemap.xml':
// ! Output as XML
const data = sitemap({baseURL: process.env.baseURL})
data.Sitemap().then(output => {
res.send(output)
})
break
case 'rss':
// ! Weird output
// ! Move to `routes`
rss({
baseURL: process.env.baseURL
})
break
case 'devlog':
break
case 'deverror':
break
default:
const temp = controller.Init({
req: req,
res: res,
path: this.path.string,
baseURL: process.env.baseURL,
routeData: routeConfigData
})
const response = temp.template
res.send(response)
break
}
}
})
.post(createLog, (req, res) => {})
.put(createLog, (req, res) => {})
.delete(createLog, (req, res) => {})
.patch(createLog, (req, res) => {})
/*
.all(createLog, (req, res) => {
res.set('Content-Type', mime.html)
res.status(404).send('You are not allowed to access this resource')
})
*/
app.listen(process.env.PORT, () => {
logger.Info(`Listening on: ${process.env.baseURL}`)
})
|