forked from socketio/socket.io-admin-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
407 lines (368 loc) · 11 KB
/
index.ts
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import { Namespace, RemoteSocket, Server, Socket } from "socket.io";
import {
ClientEvents,
Feature,
SerializedSocket,
ServerEvents,
} from "./typed-events";
import debugModule from "debug";
import { compare, getRounds } from "bcryptjs";
import { isWorker } from "cluster";
import { InMemoryStore, Store } from "./stores";
import os = require("os");
import { randomBytes } from "crypto";
const debug = debugModule("socket.io-admin");
const randomId = () => randomBytes(8).toString("hex");
interface BasicAuthentication {
type: "basic";
username: string;
password: string;
}
interface InstrumentOptions {
/**
* The name of the admin namespace
*
* @default "/admin"
*/
namespaceName: string;
/**
* The authentication method
*/
auth?: false | BasicAuthentication;
/**
* Whether updates are allowed
* @default false
*/
readonly: boolean;
/**
* The unique ID of the server
* @default `require("os").hostname()`
*/
serverId?: string;
/**
* The store
*/
store: Store;
}
const initAuthenticationMiddleware = (
namespace: Namespace<ClientEvents, ServerEvents>,
options: InstrumentOptions
) => {
if (options.auth === undefined) {
throw new Error(
"the `auth` option must be specified or explicitly set to `false`"
);
}
if (options.auth === false) {
debug("WARN: authentication is disabled, please use with caution");
} else if (options.auth?.type === "basic") {
debug("basic authentication is enabled");
const basicAuth = options.auth as BasicAuthentication;
try {
getRounds(basicAuth.password);
} catch (e) {
throw new Error("the `password` field must be a valid bcrypt hash");
}
namespace.use(async (socket, next) => {
const sessionId = socket.handshake.auth.sessionId;
if (sessionId && (await options.store.doesSessionExist(sessionId))) {
debug("authentication success with valid session ID");
return next();
}
if (socket.handshake.auth.username === basicAuth.username) {
const isMatching = await compare(
socket.handshake.auth.password,
basicAuth.password
);
if (isMatching) {
debug("authentication success with valid credentials");
const sessionId = randomId();
options.store.saveSession(sessionId);
socket.emit("session", sessionId);
return next();
}
}
debug("invalid credentials");
next(new Error("invalid credentials"));
});
} else {
throw new Error("invalid `auth` option, please check the documentation");
}
};
const computeServerId = (serverId: string | undefined) => {
if (serverId) {
return serverId;
} else if (isWorker) {
return `${os.hostname()}#${process.pid}`;
} else {
return os.hostname();
}
};
const initStatsEmitter = (
adminNamespace: Namespace<{}, ServerEvents>,
serverId: string | undefined
) => {
const baseStats = {
serverId: computeServerId(serverId),
hostname: os.hostname(),
pid: process.pid,
};
const emitStats = () => {
debug("emit stats");
// @ts-ignore private reference
const clientsCount = adminNamespace.server.engine.clientsCount;
adminNamespace.emit(
"server_stats",
Object.assign({}, baseStats, {
uptime: process.uptime(),
clientsCount,
})
);
};
const interval = setInterval(emitStats, 2000);
interval.unref(); // so that the timer does not prevent the process from exiting
emitStats();
};
const detectSupportedFeatures = (io: Server): Feature[] => {
const supportedFeatures = [
Feature.EMIT,
Feature.JOIN,
Feature.LEAVE,
Feature.DISCONNECT,
];
// added in Socket.IO v4.0.0
if (typeof io.socketsJoin === "function") {
supportedFeatures.push(Feature.MJOIN);
}
if (typeof io.socketsLeave === "function") {
supportedFeatures.push(Feature.MLEAVE);
}
if (typeof io.disconnectSockets === "function") {
supportedFeatures.push(Feature.MDISCONNECT);
}
return supportedFeatures;
};
const fetchAllSockets = async (io: Server): Promise<SerializedSocket[]> => {
if (typeof io.fetchSockets === "function") {
// Socket.IO v4
const promises: Promise<SerializedSocket[]>[] = [];
io._nsps.forEach((nsp) => {
const promise = nsp.fetchSockets().then((sockets) => {
return sockets.map((socket) => {
return serialize(socket, nsp.name);
});
});
promises.push(promise);
});
return (await Promise.all(promises)).reduce((acc, sockets) => {
acc.push(...sockets);
return acc;
}, []);
} else {
// Socket.IO v3
// Note: we only fetch local Socket instances, so this will not work with multiple Socket.IO servers
const sockets: SerializedSocket[] = [];
io._nsps.forEach((nsp) => {
nsp.sockets.forEach((socket) => {
sockets.push(serialize(socket, socket.nsp.name));
});
});
return sockets;
}
};
const registerFeatureHandlers = (
io: Server,
socket: Socket<ClientEvents, ServerEvents>,
supportedFeatures: Feature[]
) => {
if (supportedFeatures.includes(Feature.EMIT)) {
socket.on("emit", (nsp, filter, ev, ...args) => {
debug(
`emit ${ev} to all socket instances in namespace ${nsp} and room ${filter}`
);
if (filter) {
io.of(nsp)
.in(filter)
.emit(ev, ...args);
} else {
io.of(nsp).emit(ev, ...args);
}
});
}
if (supportedFeatures.includes(Feature.JOIN)) {
if (typeof io.socketsJoin === "function") {
// Socket.IO v4
socket.on("join", (nsp, room, filter) => {
if (filter) {
debug(
`make all socket instances in namespace ${nsp} and room ${filter} join room ${room}`
);
io.of(nsp).in(filter).socketsJoin(room);
} else {
debug(
`make all socket instances in namespace ${nsp} join room ${room}`
);
io.of(nsp).socketsJoin(room);
}
});
} else {
// Socket.IO v3
socket.on("join", (nsp, room, id) => {
if (id) {
debug(
`make socket instance ${id} in namespace ${nsp} join room ${room}`
);
const socket = io.of(nsp).sockets.get(id);
socket?.join(room);
}
});
}
}
if (supportedFeatures.includes(Feature.LEAVE)) {
if (typeof io.socketsLeave === "function") {
// Socket.IO v4
socket.on("leave", (nsp, room, filter) => {
if (filter) {
debug(
`make all socket instances in namespace ${nsp} and room ${filter} leave room ${room}`
);
io.of(nsp).in(filter).socketsLeave(room);
} else {
debug(
`make all socket instances in namespace ${nsp} leave room ${room}`
);
io.of(nsp).socketsLeave(room);
}
});
} else {
// Socket.IO v3
socket.on("leave", (nsp, room, id) => {
if (id) {
debug(
`make socket instance ${id} in namespace ${nsp} leave room ${room}`
);
const socket = io.of(nsp).sockets.get(id);
socket?.leave(room);
}
});
}
}
if (supportedFeatures.includes(Feature.DISCONNECT)) {
if (typeof io.disconnectSockets === "function") {
// Socket.IO v4
socket.on("_disconnect", (nsp, close, filter) => {
if (filter) {
debug(
`make all socket instances in namespace ${nsp} and room ${filter} disconnect`
);
io.of(nsp).in(filter).disconnectSockets(close);
} else {
debug(`make all socket instances in namespace ${nsp} disconnect`);
io.of(nsp).disconnectSockets(close);
}
});
} else {
// Socket.IO v3
socket.on("_disconnect", (nsp, close, id) => {
if (id) {
debug(`make socket instance ${id} in namespace ${nsp} disconnect`);
const socket = io.of(nsp).sockets.get(id);
socket?.disconnect(close);
}
});
}
}
};
const registerListeners = (
adminNamespace: Namespace<{}, ServerEvents>,
nsp: Namespace
) => {
nsp.on("connection", (socket) => {
// @ts-ignore
const clientId = socket.client.id;
socket.data = socket.data || {};
socket.data._admin = {
clientId: clientId.substring(0, 12), // this information is quite sensitive
transport: socket.conn.transport.name,
};
adminNamespace.emit("socket_connected", serialize(socket, nsp.name));
socket.conn.on("upgrade", (transport: any) => {
socket.data._admin.transport = transport.name;
adminNamespace.emit("socket_updated", {
id: socket.id,
nsp: nsp.name,
transport: transport.name,
});
});
socket.on("disconnect", (reason) => {
adminNamespace.emit("socket_disconnected", nsp.name, socket.id, reason);
});
});
nsp.adapter.on("join-room", (room: string, id: string) => {
adminNamespace.emit("room_joined", nsp.name, room, id);
});
nsp.adapter.on("leave-room", (room: string, id: string) => {
process.nextTick(() => {
adminNamespace.emit("room_left", nsp.name, room, id);
});
});
};
const serialize = (
socket: Socket | RemoteSocket<any>,
nsp: string
): SerializedSocket => {
const clientId = socket.data?._admin?.clientId;
const transport = socket.data?._admin?.transport;
const address =
socket.handshake.headers["cf-connecting-ip"] ||
socket.handshake.headers["x-forwarded-for"] ||
socket.handshake.address;
return {
id: socket.id,
clientId,
transport,
nsp,
handshake: {
address,
headers: socket.handshake.headers,
query: socket.handshake.query,
issued: socket.handshake.issued,
secure: socket.handshake.secure,
time: socket.handshake.time,
url: socket.handshake.url,
xdomain: socket.handshake.xdomain,
// ignore auth and other attributes like sessionStore
},
rooms: [...socket.rooms],
};
};
export function instrument(io: Server, opts: Partial<InstrumentOptions>) {
const options: InstrumentOptions = Object.assign(
{
namespaceName: "/admin",
auth: undefined,
readonly: false,
serverId: undefined,
store: new InMemoryStore(),
},
opts
);
debug("options: %j", options);
const adminNamespace: Namespace<ClientEvents, ServerEvents> = io.of(
options.namespaceName
);
initAuthenticationMiddleware(adminNamespace, options);
const supportedFeatures = options.readonly ? [] : detectSupportedFeatures(io);
debug("supported features: %j", supportedFeatures);
initStatsEmitter(adminNamespace, options.serverId);
adminNamespace.on("connection", async (socket) => {
registerFeatureHandlers(io, socket, supportedFeatures);
socket.emit("config", {
supportedFeatures,
});
socket.emit("all_sockets", await fetchAllSockets(io));
});
io._nsps.forEach((nsp) => registerListeners(adminNamespace, nsp));
io.on("new_namespace", (nsp) => registerListeners(adminNamespace, nsp));
}
export { InMemoryStore, RedisStore } from "./stores";