-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsockets.js
141 lines (104 loc) · 4.41 KB
/
sockets.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
const http = require('http');
const https = require('https');
const WebSocket = require('ws');
const wallets = require('./wallets');
require('isomorphic-fetch');
const ecc = require('eosjs-ecc');
const sha256 = x => ecc.sha256(x);
const uuidv4 = require('uuid').v4;
const walletConnections = {};
const appConnections = {};
const queuedMessages = {};
const emit = async (socket, path, data) => {
if(!socket) return console.error('No socket found');
socket.send('42/scatter,' + JSON.stringify([path, data ? data : false]))
}
const socketHandler = (socket, req) => {
const ip = req.headers['x-forwarded-for'];
let device;
let origin = null, isWallet = false;
const socketId = Math.round(Math.random() * 999999999).toString();
socket.send("40");
socket.send("40/scatter");
socket.send(`42/scatter,["connected"]`);
// Just logging errors for debugging purposes (dev only)
socket.on('error', async request => console.log('error', request));
let interval = setInterval(() => {
socket.send(`42/scatter,["ping"]`);
}, 10000);
// Different clients send different message types for disconnect (ws vs socket.io)
const closeConnection = e => {
clearInterval(interval);
console.log('disconnected', isWallet ? 'wallet' : 'app', sha256(ip+device), e);
if(isWallet){
delete walletConnections[sha256(ip+device)];
delete wallets[sha256(ip+device)];
} else {
delete appConnections[origin+socketId]
}
};
socket.on('close', closeConnection);
socket.on('disconnect', closeConnection);
socket.on('message', msg => {
if(msg.indexOf('42/scatter') === -1) return false;
let [type, request] = JSON.parse(msg.replace('42/scatter,', ''));
if(request) device = request.device;
/************************************************/
/* WALLETS */
/************************************************/
if(type === 'wallet'){
isWallet = true;
console.log('wallet', sha256(ip+device), ip, device);
wallets[sha256(ip+device)] = uuidv4();
walletConnections[sha256(ip+device)] = socket;
return emit(socket, 'linked', {id:request.id, result:true});
}
if(type === 'wallet_response'){
if(!queuedMessages[request.id]) return;
return queuedMessages[request.id](request);
}
if(type === 'pong') return;
if(type === 'ping') return socket.send(`42/scatter,["pong"]`);
/************************************************/
/* APPS */
/************************************************/
const killRequest = () => emit(socket, 'api', {id:request.id, result:null});
if(!request.plugin || request.plugin.length > 100) return killRequest();
request.plugin = request.plugin.replace(/\s/g, "");
if(request.plugin.trim().toLowerCase() === 'Scatter') return killRequest();
if(request.data.hasOwnProperty('payload') && request.data.payload.origin.trim().toLowerCase() === 'Scatter') return killRequest();
let requestOrigin;
if(request.data.hasOwnProperty('payload')) requestOrigin = request.data.payload.origin;
else requestOrigin = request.data.origin;
if(!origin) origin = requestOrigin;
else if(origin && requestOrigin !== origin) return emit(socket, 'api', {id:request.id, result:null});
if(!appConnections.hasOwnProperty(origin+socketId)) appConnections[origin+socketId] = socket;
new Promise((resolve, reject) => {
queuedMessages[request.id] = resolve;
return emit(walletConnections[sha256(ip+device)], type, request);
}).then(result => {
emit(socket, result.type, result.data || false)
});
});
};
const getCerts = async () => {
return fetch('https://certs.get-scatter.com?rand='+Math.round(Math.random()*100 + 1))
.then(res => res.json())
.then(res => {
if(res.hasOwnProperty('key') && res.hasOwnProperty('cert')) return res;
PopupService.push(Popup.prompt("Couldn't fetch certificates", 'There was an issue trying to fetch the certificates which allow Scatter to run on SSL. This is usually caused by proxies, firewalls, and anti-viruses.'))
return null;
})
.catch(() => console.error('Could not fetch certs. Probably due to a proxy, vpn, or firewall.'));
};
const createSocket = async () => {
// const certs = await getCerts();
// const server = https.createServer(certs);
const server = http.createServer();
const websocket = new WebSocket.Server({ server });
websocket.on('connection', socketHandler)
server.listen(50005);
// server.listen(50006);
return websocket
}
module.exports = createSocket