forked from laggingreflex/socket.io-encrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
63 lines (53 loc) · 1.62 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
const Cryptr = require('cryptr');
const { emit, on } = require('./symbol');
const reservedEvents = require('./reserved-events');
module.exports = (secret) => (socket, next) => {
const cryptr = new Cryptr(secret);
const encrypt = args => {
const encrypted = [];
let ack;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (i === args.length - 1 && typeof arg === 'function') {
ack = arg;
} else {
encrypted.push(cryptr.encrypt(JSON.stringify(arg)));
}
}
if (!encrypted.length) return args;
args = [{ encrypted }];
if (ack) args.push(ack);
return args;
};
const decrypt = encrypted => {
try {
return encrypted.map(a => JSON.parse(cryptr.decrypt(a)));
} catch (e) {
const error = new Error(`Couldn't decrypt. Wrong secret used on client or invalid data sent. (${e.message})`);
error.code = 'ERR_DECRYPTION_ERROR';
throw error;
}
};
socket[emit] = socket.emit;
socket[on] = socket.on;
socket.emit = (event, ...args) => {
if (reservedEvents.includes(event)) return socket[emit](event, ...args);
return socket[emit](event, ...encrypt(args));
};
socket.on = (event, handler) => {
if (reservedEvents.includes(event)) return socket[on](event, handler);
return socket[on](event, function(...args) {
if (args[0] && args[0].encrypted) {
try {
args = decrypt(args[0].encrypted);
} catch (error) {
socket[emit]('error', error);
return;
}
}
return handler.call(this, ...args);
});
};
if (next) next();
return socket;
};