-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
241 lines (200 loc) · 6.68 KB
/
server.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
'use strict'
const { createServer } = require('net')
const EventEmitter = require('events')
const debug = require('debug')('socket.io-monitor')
const protocol = require('./protocol')
/**
* Options:
* - server: boolean = true (start server ? Otherwise just expose the emitter)
* - port: number = 9042
* - host: string = 'localhost'
* - password: string? = null (server password)
*
* Output:
* - emitter: EventEmitter
* - server: Promise<net.Server>
*/
module.exports = (io, options = {}) => {
const { server = true } = options
const emitter = initEmitter(io)
return server
? { emitter, server: initServer(emitter, options) }
: { emitter, server: null }
}
const initServer = exports.initServer = (emitter, options = {}) => new Promise((resolve, reject) => {
const { port = 9042, host = 'localhost' } = options
const server = createServer()
server.listen(port, host)
server.once('listening', () => {
resolve(server)
server.on('connection', connHandler(emitter, options))
})
server.once('error', err => reject(err))
})
const monkeyPatch = (object, method, fn) => {
const orig = object[method]
object[method] = function (...args) {
fn.apply(this, args)
return orig.apply(this, args)
}
}
const initEmitter = exports.initEmitter = (io) => {
const e = new EventEmitter()
const { adapter } = io.sockets
// Monitor broadcasts
monkeyPatch(adapter, 'broadcast', (packet, { rooms = [], flags = {} }) => {
if (packet.type === 2) {
const [ name, ...args ] = packet.data
const flagsList = Object.keys(flags).filter(f => flags[f])
e.emit('broadcast', { name, args, rooms, flags: flagsList })
}
})
// Monitor rooms
monkeyPatch(adapter, 'addAll', (id, rooms) => {
if (rooms.length > 1 || !rooms.includes(id)) {
e.emit('join', { id, rooms })
}
})
monkeyPatch(adapter, 'del', (id, room) => {
e.emit('leave', { id, room })
})
monkeyPatch(adapter, 'delAll', id => {
e.emit('leaveAll', { id })
})
// Monitor connections
io.on('connection', ws => {
e.emit('connect', { id: ws.id })
// Monitor disconnections
ws.on('disconnect', () => e.emit('disconnect', { id: ws.id }))
// Monitor messages client → server
monkeyPatch(ws, 'emit', (name, ...args) => {
if (typeof args[args.length - 1] === 'function') {
args.pop()
}
e.emit('emit', { id: ws.id, name, args })
})
// Monitor messages server → client
monkeyPatch(ws, 'dispatch', ([ name, ...args ]) => {
if (typeof args[args.length - 1] === 'function') {
args.pop()
}
e.emit('recv', { id: ws.id, name, args })
})
})
e.getState = () => getState(io)
// Debug (oh look, a synthetic list of all events you could use as documentation)
if (debug.enabled) {
e
.on('string', ({ id, string }) => debug('string', id, string))
.on('broadcast', ({ name, args, rooms, flags }) => debug('broadcast', name, args, rooms, flags))
.on('join', ({ id, rooms }) => debug('join', id, rooms))
.on('leave', ({ id, room }) => debug('leave', id, room))
.on('leaveAll', ({ id }) => debug('leaveAll', id))
.on('connect', ({ id }) => debug('connect', id))
.on('disconnect', ({ id }) => debug('disconnect', id))
.on('emit', ({ id, name, args }) => debug('emit', id, name, args))
.on('recv', ({ id, name, args }) => debug('recv', id, name, args))
}
return e
}
const noop = () => {}
const connHandler = (emitter, options) => {
const { password = null, authTimeout = 1500, onError = noop } = options
// Store list of all bound protocols, avoids memory leak by binding too many handlers
let protos = []
const addProto = proto => {
protos = protos.concat([ proto ])
setImmediate(() => {
emitter.getState()
.then(data => {
proto.emit('init', data)
setImmediate(() => emitter.emit('client', { client: proto, state: data }))
})
.catch(err => proto.emit('error', err.message))
})
}
const removeProto = proto => {
protos = protos.filter(p => p !== proto)
proto.removeAllListeners()
}
const dispatch = name => data => {
protos.forEach(proto => proto.emit(name, data))
}
// Retransmit events
emitter
.on('string', dispatch('string'))
.on('broadcast', dispatch('broadcast'))
.on('join', dispatch('join'))
.on('leave', dispatch('leave'))
.on('leaveAll', dispatch('leaveAll'))
.on('connect', dispatch('connect'))
.on('disconnect', dispatch('disconnect'))
.on('emit', dispatch('emit'))
.on('recv', dispatch('recv'))
return socket => {
socket.on('error', err => debug('socket error', err))
socket.on('error', onError)
const proto = protocol.bindSocket(socket)
socket.on('close', () => removeProto(proto))
let authorized = false
// Plug TCP socket to local emitter
const init = () => {
authorized = true
addProto(proto)
}
// Authentication
let timeout = null
if (!password) {
proto.emit('reqAuth', false)
// Wait for an empty password though, to ensure roundtrip is complete
proto.once('password', () => init())
} else {
proto.emit('reqAuth', true)
// Auth timeout
const timeout = setTimeout(() => {
proto.emit('auth', { authorized: false, error: 'TIMEOUT' })
socket.end()
}, authTimeout)
proto.once('password', pwd => {
clearTimeout(timeout)
if (pwd === password) {
proto.emit('auth', { authorized: true })
init()
} else {
proto.emit('auth', { authorized: false, error: 'INVALID_PASSWORD' })
socket.end()
}
})
}
}
}
// Grab rooms & sockets data
const getState = io => Promise.resolve().then(() => {
// Aggregate data from rooms
const forEachRoom = (fn, initial) =>
Object.keys(io.sockets.adapter.rooms).reduce((data, name) => {
const info = io.sockets.adapter.rooms[name]
const sockets = Object.entries(io.sockets.sockets)
.map(([id, socket]) => ({ id, connectedAt: socket.handshake.issued }))
.filter(({ id }) => info.sockets[id] && io.sockets.sockets[id])
return fn(data, sockets, name)
}, initial)
// rooms: Array<{ name: string, sockets: Array<string> }>
const rooms = forEachRoom((rooms, sockets, name) => {
if (sockets.length === 1 && sockets[0].id === name) {
// A personal room, just skip it
return rooms
}
rooms.push({ name, sockets: sockets.map(s => s.id) })
return rooms
}, [])
// sockets: Array<{ id: string, connectedAt: number }>
const sockets = forEachRoom((arr, sockets) => {
// unique
sockets.forEach(s => {
if (!arr.find(({ id }) => s.id === id)) arr.push(s)
})
return arr
}, [])
return { rooms, sockets }
})