forked from Unitendo/aurorachat-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
315 lines (276 loc) · 9.57 KB
/
Copy pathserver.js
File metadata and controls
315 lines (276 loc) · 9.57 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
const express = require('express');
const session = require('express-session');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const websocket = require('ws');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const censor = require('./censor');
const admin = require("./admin");
const { readUsers, writeUsers } = require("./db")
const { TOKEN_SECRET, SESSION_SECRET, PORT, ROOMS, USERNAME_LIMIT, HISTORY_LIMIT, MESSAGE_LIMIT } = require('./config');
const userMessageTimes = {};
const userRecentMessages = {};
const app = express(); // Create the http server
app.use(express.json());
app.use(cors({
origin: '*',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'User-Agent']
}));
/**
* @type { Object.<string,{ username: string, message: string }[]> }
*/
const chatHistory = {};
// Initialize an empty history array for every single room
for(const room of ROOMS) {
chatHistory[room] = []
}
// The amount of rooms the client should parse (calculate dynamically in the future when user-created rooms exist)
const roomCount = ROOMS.length;
// Verify the JWT token provided by the client
function verifyToken(req, res, next) {
const token = req.headers.authorization;
if (!token) {
console.log(`[${req.ip}]: Error: Invalid Token.`);
console.log(token)
return res.send({"error": "Invalid token"});
}
try {
const decoded = jwt.verify(token, TOKEN_SECRET);
req.user = decoded;
next();
} catch (err) {
console.log(`Token error: ${err}`);
return res.send({"error": "Token verification error"});
}
}
// Check if an IP is banned
function checkBan(req, res, next) {
const users = readUsers();
const user = users.users.find(user => user.ip === req.ip);
if (user) {
if (user.banned == true) {
console.log(`Banned user attempted access: ${user.username}`);
const reason = user.banReason || "No reason specified";
return res.send({"error": "Banned", "reason": reason});
} else {
next();
}
} else {
next();
}
}
// web version
app.use('/web', checkBan, express.static('web'));
app.get('/', checkBan, (req, res) => {
return res.redirect("/web");
})
// Unused, simple API test
app.get('/api/test', checkBan, (req, res) => {
res.set('Content-Type', 'application/json');
res.status(200).send({"result": "Online"});
console.log(`${req.ip} requested API status`);
});
// Grab rooms
app.get('/api/rooms', verifyToken, checkBan, (req, res) => {
res.set('Content-Type', 'application/json');
res.status(200).send(ROOMS);
console.log("Sent room list");
});
// {"room": "general", "content": "test", "platform": "Web", "img": "[image url]"}
app.post('/api/chat', verifyToken, checkBan, async (req, res) => {
var data = req.body
if (!ROOMS.includes(data.room)) {
return res.status(200).send({"error": "Room not found"});
}
const users = readUsers();
const user = users.users.find(user => user.username === req.user.username);
if (data.room == "announcements") {
console.log("Message in announcements:");
if (user) {
if (!user.admin) {
console.log("Not enough rights");
return res.send({"error": "No permission"});
}
}
}
if (user) {
if (user.banned) {
const reason = user.banReason || "No reason specified";
return res.status(200).send({"error": "Banned", "reason": reason});
}
if (user.muted) {
console.log(`Muted user ${req.user.username} tried to chat.`);
return res.status(200).send({"error": "Muted"});
}
} else {
return res.status(404).send({"error": "User not found"});
}
if (data.content.length > MESSAGE_LIMIT) {
return res.status(200).send({"error": "Message too long", "limit": MESSAGE_LIMIT});
}
console.log(`[${req.ip}] ${req.user.username}: ${JSON.stringify(req.body)}`);
var censored = censor(data.content)
var result = {
"author": req.user.username,
"content": censored,
"room": data.room,
"pfp": "img/pfp.png", // placeholder
"platform": "img/plt/web.png" // placeholder
}
if (chatHistory[data.room]) {
chatHistory[data.room].push(result);
// drop the oldest message if we exceed it
if (chatHistory[data.room].length > HISTORY_LIMIT) {
chatHistory[data.room].splice(0, chatHistory[data.room].length - HISTORY_LIMIT)
}
}
console.log("sent",JSON.stringify(result))
ws_server.clients.forEach(client => {
client.send(JSON.stringify(result));
});
return res.status(200).send({"result": "Success"});
});
// {"username": "orstando", "password": "wowsopassword"}
app.post('/api/signup', checkBan, async (req, res) => {
const data = req.body
const username = data.username;
const password = data.password;
if (!username || !password) {
console.log("Signup: missing fields");
return res.send({"error": "Missing fields"});
}
if (username.length > USERNAME_LIMIT) {
console.log("Signup: Username too long");
return res.send({"error": "Username too long", "limit": USERNAME_LIMIT});
}
const users = readUsers();
if (users.users.find(user => user.username === username)) {
console.log("Signup: account already in use");
return res.send({"error": "Username unavailable"});
}
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = { id: Date.now().toString(), username, password: hashedPassword, ip: req.ip };
users.users.push(newUser);
writeUsers(users);
const token = jwt.sign({ id: newUser.id, username }, TOKEN_SECRET, { expiresIn: '1h' });
console.log("Account created!");
return res.status(200).send({"token": token});
});
// {"username": "orstando", "password": "wowsopassword"}
app.post('/api/login', checkBan, async (req, res) => {
const data = req.body
const username = data.username;
const password = data.password;
const users = readUsers();
const user = users.users.find(user => user.username === username);
if (!user || !(await bcrypt.compare(password, user.password))) {
console.log("Wrong password");
return res.send({"error": "Incorrect username or password"});
}
if (user.banned) {
const reason = user.banReason || "No reason specified";
return res.status(200).send({"error": "Banned", "reason": reason});
}
const token = jwt.sign({ id: user.id, username }, TOKEN_SECRET, { expiresIn: '1h' });
console.log("Client logged in!");
return res.status(200).send({"token": token});
});
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session({
secret: SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { secure: false }
}));
app.use(express.text());
app.get('/api/rules', async (req, res) => {
const filePath = path.join(__dirname, 'data', 'rules.txt');
res.sendFile(filePath, (err) => {
if (err) {
console.error(err);
if (!res.headersSent) {
res.status(404).send('An error occurred while fetching rules.');
}
}
});
});
app.get('/api/faq', async (req, res) => {
const filePath = path.join(__dirname, 'data', 'faq.txt');
res.sendFile(filePath, (err) => {
if (err) {
console.error(err);
if (!res.headersSent) {
res.status(404).send('An error occurred while fetching FAQ.');
}
}
});
});
app.get('/api/changelog', async (req, res) => {
const filePath = path.join(__dirname, 'data', 'changelog.txt');
res.sendFile(filePath, (err) => {
if (err) {
console.error(err);
if (!res.headersSent) {
res.status(404).send('An error occurred while fetching changelog.');
}
}
});
});
app.use(express.json());
app.get('/api/online', async (req, res) => {
room = req.query.room;
// get online count for room, currently placeholder
res.status(200).send({"count": 1})
})
app.get('/api/isadmin', async (req, res) => {
const username = req.query.username;
const users = readUsers();
const user = users.users.find(user => user.username === username);
if (!user) {
return res.status(404).send("Invalid user.");
}
res.status(200).send({"result": user.admin})
});
app.get('/api/history', verifyToken, checkBan, async (req, res) => {
const room = req.query.room;
let messages = []
if(room) {
const history = chatHistory[room]
if(history) {
for(const msg of history) {
messages.push(msg);
}
}
} else {
console.log(`${req.ip} requested message history for nonexistent room (${data.room})`)
return res.status(404).send({
"error": "Room not found"
});
}
res.status(200).send(messages)
console.log(`${req.ip} requested message history`)
return
})
app.use("/admin", admin); // admin panel
server = app.listen(PORT, '0.0.0.0', () => {
console.log(`ChatterHTTP running on port ${PORT}`);
});
// Websocket server
const ws_server = new websocket.Server({ server: server, clientTracking: true });
// WSS connection handling
ws_server.on('connection', (ws, req) => {
console.log(`[${req.socket.remoteAddress}] Client connected`);
ws.on('message', (data) => {
console.log(`${req.socket.remoteAddress} tried sending data: ${data}`);
});
ws.on('close', (code, reason) => {
console.log(`[${req.socket.remoteAddress}] Client disconnected`);
});
ws.on('error', (err) => {
console.log(`[${req.socket.remoteAddress}] error: ${err.message}`);
});
});