-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
226 lines (191 loc) · 6.78 KB
/
index.js
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
const uuid = require('uuid');
const bcrypt = require('bcrypt');
const cookieParser = require('cookie-parser');
const express = require('express');
const expressWs = require(`@wll8/express-ws`)
const { app, wsRoute } = expressWs(express())
// Load Database Hooks
const DB = require('./database.js')
// Default to port 4000 if not given on command line
const port = process.argv.length > 2 ? process.argv[2] : 4000;
// Middleware
app.use(express.json()); // JSON Body Parsing
app.use(cookieParser()); // Cookie Parsing
app.use(express.static('public')); // Static Files
// API Endpoints
var apiRouter = express.Router();
app.use('/api', apiRouter);
// Create Session token and account entry for new user
apiRouter.post('/auth/create', async (req, res) => {
if (await DB.getUser(req.body.username)) {
res.status(409).send({ msg: 'Existing user' });
} else {
const user = await DB.createUser(req.body.username, req.body.password);
console.log(user.session);
setAuthCookie(res, user.session); // Set Auth Cookie
res.send({});
}
});
// Get session token for the provided credentials
apiRouter.post('/auth/login', async (req, res) => {
const user = await DB.getUser(req.body.username);
console.log(user.session);
if (user) {
if (await bcrypt.compare(req.body.password, user.password)) {
setAuthCookie(res, user.session);
res.send({});
return;
}
}
res.status(401).send({ msg: 'Incorrect Credentials' });
});
// Logout; Remove session token if stored in cookie
apiRouter.delete('/auth/logout', (_req, res) => {
res.clearCookie('session');
res.status(204).end();
});
// Get Authentication state for a given user
apiRouter.get('/user/:username', async (req, res) => {
const user = await DB.getUser(req.params.username);
if (user) {
const sessionToken = req?.cookies.session;
res.send({ username: user.username, authenticated: sessionToken === user.session });
return;
}
res.status(404).send({ msg: 'Unknown' });
});
// Secure Routing for authenticated endpoints
var secureRouter = express.Router();
apiRouter.use(secureRouter);
secureRouter.use(async (req, res, next) => {
const session = req.cookies['session'];
const user = await DB.getUserBySession(session);
if (user) {
next();
} else {
res.status(401).send({ msg: 'Unauthorized' });
}
});
// Websocket connections
let ws_connections = []
// Keep connections alive until they do not respond to ping attempts
setInterval(() => {
ws_connections.forEach((connection) => {
if (!connection.alive) {
connection.ws.terminate();
} else {
connection.alive = false;
connection.ws.ping();
}
})
}, 10000);
// Websocket Endpoints
app.ws('/ws', async (ws, req) => {
// Handle Authentication - manually parse cookies
const cookies = req.headers.cookie.split('; ').reduce((prev, current) => {
const [name, ...value] = current.split('=');
prev[name] = value.join('=');
return prev;
}, {});
const session = cookies['session'];
const user = await DB.getUserBySession(session);
const connection = { id: uuid.v4(), alive: true, ws: ws, user: user };
ws_connections.push(connection);
// Log pong messages
ws.on('pong', () => {
connection.alive = true;
});
// Remove closed connections
ws.on('close', () => {
ws_connections.findIndex((obj, index) => {
if (obj.id === connection.id) {
ws_connections.splice(index, 1);
return true;
}
});
});
// Kill connections that are not authenticated
if (!user) {
ws.send(JSON.stringify({ type: 'error', msg: 'Not Authenticated' }));
connection.terminate();
}
// Handle Messages from clients
ws.on('message', async (data) => {
message = JSON.parse(data);
if (!message?.type) {
console.log(`Recieved invalid Websocket Request: ${data}`);
return
}
switch (message.type) {
case 'message_new':
const messageTypes = await DB.createMessage(user.username, message.anonymous, message.content, Date.now())
const clientMessage = messageTypes[0];
const anonymousMessage = messageTypes[1];
// Package JSON so that it only needs to be stringified once and not for each active client
const anonymizedPackage = JSON.stringify(
{
type: 'message',
messages: [
message.anonymous ? anonymousMessage : clientMessage
]
}
);
const userPackage = JSON.stringify(
{
type: 'message',
messages: [
clientMessage
]
}
)
// Send message to live peers
ws_connections.forEach((peer) => {
if (peer === connection) {
peer.ws.send(userPackage);
} else if (message.anonymous) {
peer.ws.send(anonymizedPackage)
} else {
peer.ws.send(userPackage);
}
});
break;
case 'message_request':
const messages = JSON.parse(JSON.stringify(await DB.getMessages(message?.num)));
for (const requestedMessage of messages) {
if (requestedMessage.anonymous == true && requestedMessage.username !== user.username) {
requestedMessage.username = 'Anonymous';
}
}
connection.ws.send(JSON.stringify(
{
type: 'message',
messages: messages.reverse()
}
));
break;
default:
console.log(`Invalid Websocket Message Type: ${message.type}`);
return;
}
});
});
// Default Error Handler
app.use(function (err, req, res, next) {
res.status(500).send({ type: err.name, message: err.message });
});
// Default to homepage if route DNE
app.use((_req, res) => {
res.sendFile('index.html', { root: 'public' });
});
// setAuthCookie in the HTTP response
function setAuthCookie(res, sessionToken) {
res.cookie('session', sessionToken, {
secure: true,
httpOnly: true,
sameSite: 'strict',
});
}
// Start HTTP Service
const service = app.listen(port, () => {
console.log(`Listening on Port ${port}`);
});