-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain.js
300 lines (278 loc) · 8.72 KB
/
main.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
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
"use strict";
require('./data.js').install();
require('./utils.js').installGlobals();
const assert = require('assert');
const connect = require('connect');
const cookie = require('cookie');
const cookieParser = require('cookie-parser');
const crypto = require('crypto');
const express = require('express');
const expressSession = require('express-session');
const fs = require('fs-extra');
const http = require('http');
const https = require('https');
const logger = require('./logger.js');
const async = require('./async.js')
const irc = require('./irc.js');
const users = require('./users.js');
const utils = require('./utils.js');
const wss = require('ws');
const sessionKey = 'sid';
// Randomize the session secret at startup
const sessionSecret = crypto.randomBytes(32).toString('base64');
async()
.add('config', function(cb) {
utils.readJsonFile('config.json', cb);
})
.add('initLogger', ['config'], function(config){
logger.init(config.logLevels.console, config.logLevels.file);
})
.add(['config', '@initLogger'], function(config, cb) {
async()
.add('usersInitialized', function(cb) {
users.initialize(cb);
})
.add('sessionStore', function() {
return new expressSession.MemoryStore();
})
.add('expressApp', ['sessionStore'], function(sessionStore) {
const app = express();
app.use(cookieParser());
app.use(expressSession({
store: sessionStore,
secret: sessionSecret,
maxAge: 24 * 60 * 60,
key: sessionKey,
resave: false,
saveUninitialized: true
}));
app.use(express.static(__dirname + '/static'));
return app;
})
.add('startWebListeners', ['expressApp', 'sessionStore', '@usersInitialized'], function(expressApp, sessionStore, cb) {
const a = async();
if (config.http && config.http.port) {
a.add(function(cb) {
createWebServer(config.http, expressApp, config, sessionStore, cb);
});
}
if (config.https && config.https.port) {
a.add(function(cb) {
createWebServer(config.https, expressApp, config, sessionStore, cb);
});
}
a.run(cb);
})
.add(['@usersInitialized', '@startWebListeners'], function() {
function getShutdownSignalHandler(sig) {
return function() {
logger.info(`Received ${sig} -- saving users and exiting`);
users.saveAndShutdown();
};
}
process.once('SIGINT', getShutdownSignalHandler('SIGINT'));
process.once('SIGTERM', getShutdownSignalHandler('SIGTERM'));
})
.run(check(
function(err) {
logger.error('Failed to start WebIRC:', err.toString());
process.exit(1);
},
function() {
logger.info('WebIRC started');
cb();
}
));
})
.run(function(err) {
if (err) {
console.error('Failed to start WebIRC', err);
process.exit(1);
}
});
function createWebServer(spec, expressApp, config, sessionStore, cb) {
let server;
let serverProtocol;
if (spec.keyFile && spec.certFile) {
server = https.createServer({
key: fs.readFileSync(spec.keyFile),
cert: fs.readFileSync(spec.certFile),
rejectUnauthorized: false
}, expressApp);
serverProtocol = 'https';
} else {
server = http.createServer(expressApp);
serverProtocol = 'http';
}
let serverHost = spec.host || '0.0.0.0';
server.listen(spec.port, serverHost, function() {
logger.info(`WebIRC is listening for ${serverProtocol} connections on port ${spec.port}`);
const wsServer = new wss.Server({
server: server
});
wsServer.on('connection', function(socket) {
const headers = socket.upgradeReq.headers;
if (typeof headers == 'object' && 'cookie' in headers) {
const parsedCookies = cookieParser.signedCookies(cookie.parse(headers.cookie), sessionSecret);
if (sessionKey in parsedCookies) {
sessionStore.get(parsedCookies[sessionKey], function(err, session) {
if (!err && session) {
processNewConnectionWithSessionId(socket, parsedCookies[sessionKey]);
} else {
console.warn('Session lookup failed -- invalid session ID received from client during WebSocket upgrade request');
socket.send('refresh');
socket.close();
}
});
} else {
console.warn('No sid in cookie');
socket.close();
}
} else {
console.warn('No cookie header or no headers');
socket.send('refresh');
socket.close();
}
});
cb();
});
server.on('error', function(err) {
cb(err);
});
}
function processNewConnectionWithSessionId(socket, sessionId) {
logger.info(`WebSocket connection established: ${sessionId}`);
socket.sendMessage = function(msgId, data) {
socket.send(JSON.stringify({
msgId: msgId,
data: data
}));
}
let user = users.getUserBySessionId(sessionId);
socket.on('message', function(rawMessage, flags) {
let message;
try {
message = JSON.parse(rawMessage);
} catch (e) {
logger.warn(`Failed to parse raw message from client: ${rawMessage}`);
return;
}
const msgId = message.msgId;
const data = message.data;
if (typeof data !== 'object') {
logger.warn(`Got a message with an invalid data field: ${data}`);
return;
}
// TODO: Clean up/standardize all of the parameter validations below
if (user === null) {
if (msgId === 'Login') {
user = users.getUserByCredentials(data.username, data.password);
if (user !== null) {
// add sessionId to loggedInSessions for user
user.loggedInSessions.push(sessionId);
handleSuccessfulLogin(user, socket, sessionId);
} else {
socket.sendMessage('LoginFailed', {});
}
} else {
logger.warn(`Unrecognized message type from an unidentified client: ${msgId}`);
}
} else {
switch (msgId) {
case 'ChatboxSend': {
logger.info('Chatbox send', data);
if (typeof data.entityId === 'number' && typeof data.exec == 'boolean') {
data.lines.forEach(function(line) {
irc.processChatboxLine(user, data.entityId, line, data.exec, sessionId);
});
} else {
logger.warn('Missing entityId/exec in ChatboxSend from client');
}
break;
}
case 'AddServer': {
const newServer = new Server({}, user.getNextEntityId.bind(user));
user.addServer(newServer);
newServer.showInfo('To connect: /server [host] [port] [password]');
user.setActiveEntity(newServer.entityId);
break;
}
case 'CloseWindow': {
if ('targetEntityId' in data) {
const targetEntity = user.getEntityById(data.targetEntityId);
if (targetEntity !== null) {
targetEntity.removeEntity();
} else {
logger.warn('Invalid targetEntityId in CloseWindow from client', data);
}
}
break;
}
case 'JoinChannelOnServer': {
if ('serverEntityId' in data && typeof data.serverEntityId === 'number' &&
'channelName' in data && typeof data.channelName === 'string') {
const server = user.getEntityById(data.serverEntityId);
if (server !== null) {
server.withChannel(data.channelName, check(
function (err) {
server.requireConnected(function() {
server.send('JOIN ' + data.channelName);
});
},
function (channel) {
user.setActiveEntity(channel.entityId);
}
));
} else {
logger.warn('Invalid serverEntityId in JoinChannelOnServer from client', data);
}
}
break;
}
case 'OpenServerOptions': {
if ('serverEntityId' in data && typeof data.serverEntityId === 'number') {
const server = user.getEntityById(data.serverEntityId);
if (server !== null) {
server.showInfo('Server options aren\'t quite ready yet :)');
} else {
logger.warn('Invalid serverEntityId in OpenServerOptions from client', data);
}
}
break;
}
case 'SetActiveEntity': {
if ('targetEntityId' in data && typeof data.targetEntityId === 'number') {
const targetEntity = user.getEntityById(data.targetEntityId);
if (targetEntity !== null) {
user.setActiveEntity(targetEntity.entityId);
} else {
logger.warn('Invalid targetEntityId in SetActiveEntity from client', data);
}
}
break;
}
}
}
});
socket.on('close', function() {
// TODO LOW: support connection timeouts
logger.info('WebSocket disconnected');
// remove the socket from activeWebSockets of the user
// nothing to remove if the socket was not yet logged in
if (user !== null) {
user.removeActiveWebSocket(socket);
}
});
// see if this socket belongs to a user who is already logged in
if (user !== null) {
handleSuccessfulLogin(user, socket, sessionId);
} else {
socket.sendMessage('NeedLogin', {});
}
}
function handleSuccessfulLogin(user, socket, sessionId) {
// TODO: combine activeWebSockets with loggedInSessions
user.activeWebSockets.push(socket);
const userCopy = users.copyStateForClient(user);
socket.sendMessage('CurrentState', userCopy);
}