-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
372 lines (321 loc) · 12.9 KB
/
index.js
File metadata and controls
372 lines (321 loc) · 12.9 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
(async () => {
"use strict";
// Dependencies
const client = await require("./modules/mongodb.js")
const cookieParser = require("cookie-parser")
const compression = require("compression")
const sAES256 = require("simple-aes-256")
const requestIP = require("request-ip")
const { parse } = require("smol-toml")
const { filterXSS } = require("xss")
const express = require("express")
const hashJS = require("hash.js")
const helmet = require("helmet")
const cryptr = require("cryptr")
const axios = require("axios")
const path = require("path")
const fs = require("fs")
// Variables
const config = parse(fs.readFileSync("./config.toml", "utf8"))
const cT = new cryptr(config.security.cookieMasterKey, { encoding: config.security.cookieEncoding, pbkdf2Iterations: config.security.cookiePBKDF2Iterations, saltLength: config.security.cookieSaltLength })
const web = express()
const database = client.db(config.database.databaseName)
const users = database.collection(config.database.usersCollection)
const lowKeys = database.collection(config.database.lowKeysCollection)
const cooldown = database.collection(config.database.cooldownCollection)
// Functions
const SHA512 = (string) => { return hashJS.sha512().update(string).digest("hex") }
const setCookie = (res, data) => {
res.cookie("d", data, {
maxAge: 12 * 60 * 60 * 1000, // 12 hours
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict"
})
}
const dS = async (session) => {
try {
const sessionData = JSON.parse(cT.decrypt(session.d))
return sessionData
} catch { return false }
}
const sAES256E = (password, string) => {
return sAES256.encrypt(password, string).toString("hex")
}
const sAES256D = (password, string) => {
return sAES256.decrypt(password, Buffer.from(string, "hex")).toString("utf8")
}
const promptAI = async (data) => {
// Variablse
const promptPayload = `Your task is to assess if the given message is not gibberish, not a threat and likewise. This is for protection. If it is a threat or gibberish or otherwise unsafe, respond ONLY with: [NOT ALLOWED]. Otherwise respond with: [ALLOWED]. Message: ${data}`
// Core
try {
const response = await axios.post("https://public-api.firstdecree.org/api/v1.0/ai/chatgptroute",
{ system: "You are a strict content moderation AI.", data: promptPayload },
{
headers: { "x-key": "All Hail Decree!" },
timeout: 25000
}
)
if (response.data.includes("[NOT ALLOWED]")) return true
return false
} catch {
return false
}
}
const checkCooldown = async (req, type, user) => {
/**
* ! AUDITED (2026-03-29)
* ! A cooldown to prevent spamming.
* ! If more than 5 counts, it is blocked.
* ! resetDate is only set if it's been 5 count.
* ! Then it's 1 day before resetDate is removed and count is set to 1 again.
*/
// Variables
const ip = requestIP.getClientIp(req)
const hashedIP = user ? SHA512(`${ip}:${type}:${user}`) : SHA512(`${ip}:${type}`)
const record = await cooldown.findOne({ ip: hashedIP })
// Core
if (!record) {
await cooldown.insertOne({ ip: hashedIP, count: 1 })
return false
}
if (record.resetDate) {
if (new Date() > record.resetDate) {
await cooldown.updateOne({ ip: hashedIP }, {
$set: { count: 1 },
$unset: { resetDate: "" }
})
return false
}
return true
}
const newCount = record.count + 1
const update = { $set: { count: newCount } }
if (newCount >= 5) update.$set.resetDate = new Date(Date.now() + 86400000)
await cooldown.updateOne({ ip: hashedIP }, update)
return false
}
// Configurations
//* Express
web.use(compression({ level: 1 }))
web.use(helmet({ contentSecurityPolicy: false }))
web.use(express.json({ limit: "15mb" }))
web.use(cookieParser())
web.set("views", path.join(__dirname, "views"))
web.set("view engine", "ejs")
// Main
web.use((req, res, next) => {
if (req.path.endsWith(".html")) return res.redirect(req.path.replace(/.html$/, ""))
next()
})
web.get("/login", async (req, res, next) => {
if ((await dS(req.cookies))) return res.redirect("/dashboard")
next()
})
web.get("/register", async (req, res, next) => {
if ((await dS(req.cookies))) return res.redirect("/dashboard")
next()
})
web.use(express.static(path.join(__dirname, "public"), { extensions: ["html"] }))
web.get("/logout", (req, res) => res.clearCookie("d").redirect("/"))
web.get("/delete-account", async (req, res) => {
/**
* ! AUDITED (2026-03-29)
* ! We base the account deletion on the user cookie, hence it cannot be exploited.
*/
// Variables
const userData = await dS(req.cookies)
if (!userData) return res.redirect("/")
// Core
await users.deleteOne({ hashedUsername: SHA512(userData.username) })
await lowKeys.deleteMany({ owner: SHA512(userData.username) })
res.clearCookie("d").redirect("/")
})
//* API
web.post("/api/login", async (req, res) => {
/**
* ! AUDITED (2026-03-29)
* ! Username (POST BODY)
* ! - If empty, invalidated.
* ! - If has any special characters, invalidated.
* ! - If more than 25 characters, invalidated.
*
* ! Password (POST BODY)
* ! - If empty, invalidated.
* ! - If more than 1000 characters, invalidated.
*
* ! If account does not exist, invalidated.
*/
// Variables
const { username, password } = req.body
// Validations
if (!username || !password) return res.send("0")
if (/[^A-Za-z0-9]/.test(username)) return res.send("0")
if (username.length > 25) return res.send("0")
if (password.length > 1000) return res.send("0")
const accountData = await users.findOne({
hashedUsername: SHA512(username.toLowerCase()),
password: SHA512(password)
})
if (!accountData) return res.send("0")
// Core
setCookie(res, cT.encrypt(JSON.stringify({
username: username
})))
res.send("1")
})
web.post("/api/register", async (req, res) => {
/**
* ! AUDITED (2026-03-29)
* ! Username (POST BODY)
* ! - If empty, invalidated.
* ! - If has any special characters, invalidated.
* ! - If more than 25 characters, invalidated.
*
* ! Password (POST BODY)
* ! - If empty, invalidated.
* ! - If more than 1000 characters, invalidated.
*
* ! If account already exists, invalidated.
*/
// Variables
const { username, password } = req.body
// Validations
if (!username || !password) return res.send("0")
if (/[^A-Za-z0-9]/.test(username)) return res.send("0")
if (username.length > 25) return res.send("0")
if (password.length > 1000) return res.send("0")
const accountData = await users.findOne({
hashedUsername: SHA512(username)
})
if (accountData) return res.send("0")
// Cooldown
if (await checkCooldown(req, "register")) return res.send("2")
// Core
await users.insertOne({
hashedUsername: SHA512(username.toLowerCase()),
username: sAES256E(password, username),
password: SHA512(password),
profilePicture: "/assets/img/logo.png" // Default is LowKey logo.
})
res.send("1")
})
web.post("/api/send-lowkey", async (req, res) => {
/**
* ! AUDITED (2026-03-29)
* ! Username (POST BODY)
* ! - If empty, invalidated.
* ! - If contains special characters, invalidated.
* ! - If more than 25 characters, invalidated.
* ! - If user does not exist, invalidated.
*
* ! Lowkey (POST BODY)
* ! - If empty, invalidated.
* ! - If more than 200 characters, invalidated.
* ! - Serialize to ensure protection against XSS attacks.
* ! - Lowkey is processed to an AI to block all threats, slurs and etc.
*/
// Variables
const { username, lowkey } = req.body
// Validations
if (!username || !lowkey) return res.send("0")
if (/[^A-Za-z0-9]/.test(username)) return res.send("0")
if (username.length > 25) return res.send("0")
if (lowkey.length > 200) return res.send("0")
// Cooldown
if (await checkCooldown(req, "lowkey", username)) return res.send("2")
const accountData = await users.findOne({
hashedUsername: SHA512(username.toLowerCase())
})
if (!accountData) return res.send("0")
const isBlocked = await promptAI(lowkey) // AI Moderation
if (isBlocked) return res.send("0")
// Core
await lowKeys.insertOne({
owner: SHA512(username.toLowerCase()),
content: sAES256E(config.security.SSEMasterKey, filterXSS(lowkey)),
createdAt: new Date()
})
res.send("1")
})
web.post("/api/update-profile-picture", async (req, res) => {
/**
* ! AUDITED (2026-03-29)
* ! - General
* ! - If not login, invalidated.
*
* ! - Image (POST BODY)
* ! - If empty, invalidated.
* ! - If more than 2.5MB, invalidated.
* ! - If it's not a png, jpeg, or webp, invalidated.
*/
// Variables
const userData = await dS(req.cookies)
const { image } = req.body
// Validations
if (!userData) return res.send("0")
if (!image) return res.send("0")
if (image.length > 3500000) return res.send("0") // ~2.5MB base64
if (!image.startsWith("data:image/png") && !image.startsWith("data:image/jpeg") && !image.startsWith("data:image/webp")) return res.send("0")
// Core
await users.updateOne({ hashedUsername: SHA512(userData.username.toLowerCase()) }, {
$set: { profilePicture: image }
})
setCookie(res, cT.encrypt(JSON.stringify({
username: userData.username
})))
res.send("1")
})
//* EJS
web.get("/dashboard", async (req, res) => {
// Variables
const userData = await dS(req.cookies)
// Validations
if (!userData) return res.redirect("/login")
// Core
const accountData = await users.findOne({ hashedUsername: SHA512(userData.username.toLowerCase()) })
if (!accountData) return res.redirect("/logout")
const userLowKeys = (await lowKeys.find({ owner: SHA512(userData.username.toLowerCase()) }).toArray()).map((d) => {
return {
owner: d.owner,
content: sAES256D(config.security.SSEMasterKey, d.content),
createdAt: d.createdAt
}
})
userData.lowKeys = userLowKeys
userData.profilePicture = accountData.profilePicture
res.render("dashboard", userData)
})
web.get("/:username", async (req, res) => {
/**
* ! AUDITED (2026-03-29)
* ! Username (POST BODY)
* ! - If empty, invalidated.
* ! - If has any other special characters other than @, invalidated.
* ! - If doesn't have @, redirect with @.
* ! - If specified username account does not exist, invalidated.
* ! - If more than 25 characters (@ excluded), invalidated.
*/
// Variables
var { username } = req.params
// Validations
if (!username) return res.redirect("/")
if (/[^A-Za-z0-9@]/.test(username)) return res.redirect("/")
if (username.replace("@", "").length > 25) return res.redirect("/")
if (!username.includes("@")) return res.redirect(`/@${username}`)
username = username.replace("@", "")
const accountData = await users.findOne({
hashedUsername: SHA512(username.toLowerCase())
})
if (!accountData) return res.redirect("/")
// Core
res.render("create", {
profilePicture: accountData.profilePicture,
username: username
})
})
//* Others
web.use("/{*any}", (req, res) => res.redirect("/"))
web.listen(config.web.port, () => console.log(`Lowkey is running at port ${config.web.port}`))
})()