@bymax-one/nest-realtime 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +87 -1
- package/README.md +19 -14
- package/dist/internal/index.cjs +1621 -0
- package/dist/internal/index.d.cts +1407 -0
- package/dist/internal/index.d.ts +1407 -0
- package/dist/internal/index.mjs +1601 -0
- package/dist/server/index.cjs +73 -2271
- package/dist/server/index.d.cts +1 -1437
- package/dist/server/index.d.ts +1 -1437
- package/dist/server/index.mjs +1 -2260
- package/dist/websocket/index.cjs +675 -0
- package/dist/websocket/index.d.cts +402 -0
- package/dist/websocket/index.d.ts +402 -0
- package/dist/websocket/index.mjs +673 -0
- package/package.json +31 -3
|
@@ -0,0 +1,675 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var common = require('@nestjs/common');
|
|
4
|
+
var internal = require('@bymax-one/nest-realtime/internal');
|
|
5
|
+
var websockets = require('@nestjs/websockets');
|
|
6
|
+
var platformSocket_io = require('@nestjs/platform-socket.io');
|
|
7
|
+
|
|
8
|
+
var __defProp = Object.defineProperty;
|
|
9
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
10
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
11
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
12
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
13
|
+
}) : x)(function(x) {
|
|
14
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
15
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
16
|
+
});
|
|
17
|
+
var __decorateClass = (decorators, target, key, kind) => {
|
|
18
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
19
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
20
|
+
if (decorator = decorators[i])
|
|
21
|
+
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
22
|
+
if (kind && result) __defProp(target, key, result);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
26
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
|
|
27
|
+
var CONNECTION_ROOM_PREFIX = "connection";
|
|
28
|
+
exports.WebSocketTransport = class WebSocketTransport {
|
|
29
|
+
constructor(connections, rooms, auth, hooks, options) {
|
|
30
|
+
this.connections = connections;
|
|
31
|
+
this.rooms = rooms;
|
|
32
|
+
this.auth = auth;
|
|
33
|
+
this.hooks = hooks;
|
|
34
|
+
this.options = options;
|
|
35
|
+
}
|
|
36
|
+
connections;
|
|
37
|
+
rooms;
|
|
38
|
+
auth;
|
|
39
|
+
hooks;
|
|
40
|
+
options;
|
|
41
|
+
kind = "websocket";
|
|
42
|
+
logger = new common.Logger(exports.WebSocketTransport.name);
|
|
43
|
+
/** Nullable until the gateway's afterInit wires the instance. */
|
|
44
|
+
server = null;
|
|
45
|
+
/**
|
|
46
|
+
* Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
|
|
47
|
+
*
|
|
48
|
+
* All emit methods silently no-op until this is called, so the transport is
|
|
49
|
+
* safe to construct before the HTTP server is ready.
|
|
50
|
+
*
|
|
51
|
+
* @param server - The live Socket.IO `Server` instance from the NestJS gateway.
|
|
52
|
+
*/
|
|
53
|
+
setServer(server) {
|
|
54
|
+
this.server = server;
|
|
55
|
+
this.logger.log("Socket.IO server wired to WebSocketTransport");
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Resolve the map of locally-connected sockets, tolerating both server shapes.
|
|
59
|
+
*
|
|
60
|
+
* A root Socket.IO `Server` exposes the socket map at `.sockets.sockets` (its
|
|
61
|
+
* `.sockets` is the root `Namespace`). When `websocket.namespace` is configured,
|
|
62
|
+
* `RealtimeIoAdapter` wires the gateway to a `Namespace` instead, whose own
|
|
63
|
+
* `.sockets` IS the socket map. Per-socket lookups (join/leave/disconnect) use
|
|
64
|
+
* this indirection so they work under either shape.
|
|
65
|
+
*/
|
|
66
|
+
localSockets() {
|
|
67
|
+
const server = this.server;
|
|
68
|
+
if (!server) return void 0;
|
|
69
|
+
const sockets = server.sockets;
|
|
70
|
+
return sockets instanceof Map ? sockets : sockets.sockets;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Expose the configured authenticator to the gateway.
|
|
74
|
+
*
|
|
75
|
+
* The gateway uses this to avoid a circular injection: `RealtimeGateway` →
|
|
76
|
+
* `WebSocketTransport` → authenticator, rather than injecting the token
|
|
77
|
+
* directly in the gateway.
|
|
78
|
+
*
|
|
79
|
+
* @returns The consumer-provided `IConnectionAuthenticator` instance.
|
|
80
|
+
*/
|
|
81
|
+
authenticator() {
|
|
82
|
+
return this.auth;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Register a freshly-authenticated WebSocket connection.
|
|
86
|
+
*
|
|
87
|
+
* Stores the connection record in `ConnectionRegistry` (with `subject: null` —
|
|
88
|
+
* WS connections have no RxJS stream), auto-joins the canonical rooms, mirrors
|
|
89
|
+
* membership into `RoomRegistry`, and fires the `onConnect` lifecycle hook.
|
|
90
|
+
*
|
|
91
|
+
* Cross-instance fan-out is handled by `@socket.io/redis-adapter`; this method
|
|
92
|
+
* does not publish to `IRealtimePubSub`.
|
|
93
|
+
*
|
|
94
|
+
* @param socket - The authenticated Socket.IO socket instance.
|
|
95
|
+
* @param auth - The resolved authentication result containing userId, tenantId, and roles.
|
|
96
|
+
*/
|
|
97
|
+
async registerSocket(socket, auth) {
|
|
98
|
+
const connectedAt = /* @__PURE__ */ new Date();
|
|
99
|
+
this.connections.register({
|
|
100
|
+
connectionId: socket.id,
|
|
101
|
+
userId: auth.userId,
|
|
102
|
+
tenantId: auth.tenantId,
|
|
103
|
+
transport: "websocket",
|
|
104
|
+
ip: socket.handshake.address,
|
|
105
|
+
userAgent: socket.handshake.headers["user-agent"],
|
|
106
|
+
connectedAt,
|
|
107
|
+
subject: null,
|
|
108
|
+
close$: null,
|
|
109
|
+
originalAuth: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
|
|
110
|
+
});
|
|
111
|
+
await socket.join(`${internal.ROOM_PREFIXES.USER}:${auth.userId}`);
|
|
112
|
+
if (auth.tenantId) await socket.join(`${internal.ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
|
|
113
|
+
await socket.join(`${CONNECTION_ROOM_PREFIX}:${socket.id}`);
|
|
114
|
+
this.rooms.join(socket.id, `${internal.ROOM_PREFIXES.USER}:${auth.userId}`);
|
|
115
|
+
if (auth.tenantId) this.rooms.join(socket.id, `${internal.ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
|
|
116
|
+
await this.evictBeyondLimit(auth.userId);
|
|
117
|
+
await this.hooks.onConnect?.({
|
|
118
|
+
connectionId: socket.id,
|
|
119
|
+
userId: auth.userId,
|
|
120
|
+
tenantId: auth.tenantId,
|
|
121
|
+
transport: "websocket",
|
|
122
|
+
ip: socket.handshake.address,
|
|
123
|
+
userAgent: socket.handshake.headers["user-agent"],
|
|
124
|
+
connectedAt
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Unregister a disconnected WebSocket connection.
|
|
129
|
+
*
|
|
130
|
+
* Removes the record from `ConnectionRegistry`, clears all room membership
|
|
131
|
+
* from `RoomRegistry`, and fires the `onDisconnect` lifecycle hook with the
|
|
132
|
+
* computed `durationMs`.
|
|
133
|
+
*
|
|
134
|
+
* @param connectionId - The Socket.IO socket `id` of the disconnected connection.
|
|
135
|
+
* @param reason - Optional reason string forwarded to the `onDisconnect` hook.
|
|
136
|
+
*/
|
|
137
|
+
async unregisterSocket(connectionId, reason) {
|
|
138
|
+
const record = this.connections.unregister(connectionId);
|
|
139
|
+
if (!record) return;
|
|
140
|
+
this.rooms.leaveAll(connectionId);
|
|
141
|
+
const disconnectMeta = {
|
|
142
|
+
connectionId,
|
|
143
|
+
userId: record.userId,
|
|
144
|
+
tenantId: record.tenantId,
|
|
145
|
+
transport: "websocket",
|
|
146
|
+
ip: record.ip,
|
|
147
|
+
userAgent: record.userAgent,
|
|
148
|
+
connectedAt: record.connectedAt,
|
|
149
|
+
durationMs: Date.now() - record.connectedAt.getTime(),
|
|
150
|
+
...reason !== void 0 ? { reason } : {}
|
|
151
|
+
};
|
|
152
|
+
await this.hooks.onDisconnect?.(disconnectMeta);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Send an event to every connection of a user (uses `user:{userId}` room).
|
|
156
|
+
*
|
|
157
|
+
* @param userId - Target user identifier.
|
|
158
|
+
* @param event - Event name to emit.
|
|
159
|
+
* @param data - Payload forwarded to all matching connections.
|
|
160
|
+
*/
|
|
161
|
+
async emitToUser(userId, event, data) {
|
|
162
|
+
this.server?.to(`${internal.ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Send an event to every connection within a tenant (uses `tenant:{tenantId}` room).
|
|
166
|
+
*
|
|
167
|
+
* @param tenantId - Target tenant identifier.
|
|
168
|
+
* @param event - Event name to emit.
|
|
169
|
+
* @param data - Payload forwarded to all matching connections.
|
|
170
|
+
*/
|
|
171
|
+
async emitToTenant(tenantId, event, data) {
|
|
172
|
+
this.server?.to(`${internal.ROOM_PREFIXES.TENANT}:${tenantId}`).emit(event, data);
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Send an event to every connection in an arbitrary room.
|
|
176
|
+
*
|
|
177
|
+
* @param roomId - The fully-qualified room identifier (e.g., `user:u-1`, `tenant:t-1`).
|
|
178
|
+
* @param event - Event name to emit.
|
|
179
|
+
* @param data - Payload forwarded to all connections in the room.
|
|
180
|
+
*/
|
|
181
|
+
async emitToRoom(roomId, event, data) {
|
|
182
|
+
this.server?.to(roomId).emit(event, data);
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Broadcast an event to all connected clients.
|
|
186
|
+
*
|
|
187
|
+
* @param event - Event name to emit.
|
|
188
|
+
* @param data - Payload forwarded to every connected socket.
|
|
189
|
+
*/
|
|
190
|
+
async broadcast(event, data) {
|
|
191
|
+
this.server?.emit(event, data);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Join a connection to an additional room (updates both Socket.IO and `RoomRegistry`).
|
|
195
|
+
*
|
|
196
|
+
* @param connectionId - The socket `id` of the connection to join.
|
|
197
|
+
* @param roomId - The room to join.
|
|
198
|
+
*/
|
|
199
|
+
async joinRoom(connectionId, roomId) {
|
|
200
|
+
const socket = this.localSockets()?.get(connectionId);
|
|
201
|
+
if (socket) {
|
|
202
|
+
await socket.join(roomId);
|
|
203
|
+
this.rooms.join(connectionId, roomId);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Remove a connection from a room (updates both Socket.IO and `RoomRegistry`).
|
|
208
|
+
*
|
|
209
|
+
* @param connectionId - The socket `id` of the connection to remove.
|
|
210
|
+
* @param roomId - The room to leave.
|
|
211
|
+
*/
|
|
212
|
+
async leaveRoom(connectionId, roomId) {
|
|
213
|
+
const socket = this.localSockets()?.get(connectionId);
|
|
214
|
+
if (socket) {
|
|
215
|
+
await socket.leave(roomId);
|
|
216
|
+
this.rooms.leave(connectionId, roomId);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Force-disconnect a specific connection — adapter-aware, so revocation works
|
|
221
|
+
* across nodes.
|
|
222
|
+
*
|
|
223
|
+
* A socket local to this node is closed directly as a fast path. Regardless,
|
|
224
|
+
* `disconnectSockets` is broadcast to the connection's `connection:{id}` room:
|
|
225
|
+
* under `@socket.io/redis-adapter` this fans out to remote nodes, so a
|
|
226
|
+
* connection pinned to another instance is still force-closed. The local socket
|
|
227
|
+
* has already left the room by then, so the broadcast does not double-close it.
|
|
228
|
+
*
|
|
229
|
+
* @param connectionId - The socket `id` of the connection to disconnect.
|
|
230
|
+
* @param _reason - Optional reason string (unused at the Socket.IO level; passed to `unregisterSocket`).
|
|
231
|
+
*/
|
|
232
|
+
async disconnect(connectionId, _reason) {
|
|
233
|
+
const server = this.server;
|
|
234
|
+
if (!server) return;
|
|
235
|
+
const local = this.localSockets()?.get(connectionId);
|
|
236
|
+
if (local) local.disconnect(true);
|
|
237
|
+
server.in(`${CONNECTION_ROOM_PREFIX}:${connectionId}`).disconnectSockets(true);
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Evict the user's oldest WebSocket connections (FIFO) when over
|
|
241
|
+
* `websocket.maxConnectionsPerUser`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
|
|
242
|
+
* as the disconnect reason — never rejects the new connection with HTTP 429.
|
|
243
|
+
*/
|
|
244
|
+
async evictBeyondLimit(userId) {
|
|
245
|
+
const max = this.options.websocket?.maxConnectionsPerUser;
|
|
246
|
+
if (max === void 0 || max <= 0) return;
|
|
247
|
+
let userConnections = this.connections.byUser(userId, "websocket");
|
|
248
|
+
while (userConnections.length > max) {
|
|
249
|
+
const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
|
|
250
|
+
await this.disconnect(oldest.connectionId, internal.REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
|
|
251
|
+
await this.unregisterSocket(oldest.connectionId, internal.REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
|
|
252
|
+
userConnections = this.connections.byUser(userId, "websocket");
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
exports.WebSocketTransport = __decorateClass([
|
|
257
|
+
common.Injectable(),
|
|
258
|
+
__decorateParam(0, common.Inject(internal.ConnectionRegistry)),
|
|
259
|
+
__decorateParam(1, common.Inject(internal.RoomRegistry)),
|
|
260
|
+
__decorateParam(2, common.Inject(internal.REALTIME_AUTHENTICATOR_TOKEN)),
|
|
261
|
+
__decorateParam(3, common.Inject(internal.REALTIME_HOOKS_TOKEN)),
|
|
262
|
+
__decorateParam(4, common.Inject(internal.REALTIME_OPTIONS_TOKEN))
|
|
263
|
+
], exports.WebSocketTransport);
|
|
264
|
+
|
|
265
|
+
// src/websocket/transports/composite/composite.transport.ts
|
|
266
|
+
exports.CompositeTransport = class CompositeTransport {
|
|
267
|
+
constructor(sse, ws) {
|
|
268
|
+
this.sse = sse;
|
|
269
|
+
this.ws = ws;
|
|
270
|
+
}
|
|
271
|
+
sse;
|
|
272
|
+
ws;
|
|
273
|
+
kind = "sse";
|
|
274
|
+
logger = new common.Logger(exports.CompositeTransport.name);
|
|
275
|
+
/**
|
|
276
|
+
* Emit to all connections of a user across both transports.
|
|
277
|
+
*
|
|
278
|
+
* @param userId - Target user identifier.
|
|
279
|
+
* @param event - Event name to emit.
|
|
280
|
+
* @param data - Payload forwarded to all matching connections.
|
|
281
|
+
*/
|
|
282
|
+
async emitToUser(userId, event, data) {
|
|
283
|
+
await this.fanOut(
|
|
284
|
+
"emitToUser",
|
|
285
|
+
() => this.sse.emitToUser(userId, event, data),
|
|
286
|
+
() => this.ws.emitToUser(userId, event, data)
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Emit to all connections within a tenant across both transports.
|
|
291
|
+
*
|
|
292
|
+
* @param tenantId - Target tenant identifier.
|
|
293
|
+
* @param event - Event name to emit.
|
|
294
|
+
* @param data - Payload forwarded to all matching connections.
|
|
295
|
+
*/
|
|
296
|
+
async emitToTenant(tenantId, event, data) {
|
|
297
|
+
await this.fanOut(
|
|
298
|
+
"emitToTenant",
|
|
299
|
+
() => this.sse.emitToTenant(tenantId, event, data),
|
|
300
|
+
() => this.ws.emitToTenant(tenantId, event, data)
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Emit to all connections in a room across both transports.
|
|
305
|
+
*
|
|
306
|
+
* @param roomId - The fully-qualified room identifier.
|
|
307
|
+
* @param event - Event name to emit.
|
|
308
|
+
* @param data - Payload forwarded to all connections in the room.
|
|
309
|
+
*/
|
|
310
|
+
async emitToRoom(roomId, event, data) {
|
|
311
|
+
await this.fanOut(
|
|
312
|
+
"emitToRoom",
|
|
313
|
+
() => this.sse.emitToRoom(roomId, event, data),
|
|
314
|
+
() => this.ws.emitToRoom(roomId, event, data)
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Broadcast to all connected clients across both transports.
|
|
319
|
+
*
|
|
320
|
+
* @param event - Event name to emit.
|
|
321
|
+
* @param data - Payload forwarded to every connected client.
|
|
322
|
+
*/
|
|
323
|
+
async broadcast(event, data) {
|
|
324
|
+
await this.fanOut(
|
|
325
|
+
"broadcast",
|
|
326
|
+
() => this.sse.broadcast(event, data),
|
|
327
|
+
() => this.ws.broadcast(event, data)
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Join a connection to a room.
|
|
332
|
+
*
|
|
333
|
+
* Both transports are attempted; only the one that owns the connection
|
|
334
|
+
* succeeds. The other's failure is expected and swallowed.
|
|
335
|
+
*/
|
|
336
|
+
async joinRoom(connectionId, roomId) {
|
|
337
|
+
await Promise.all([
|
|
338
|
+
this.sse.joinRoom(connectionId, roomId).catch(() => void 0),
|
|
339
|
+
this.ws.joinRoom(connectionId, roomId).catch(() => void 0)
|
|
340
|
+
]);
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Remove a connection from a room.
|
|
344
|
+
*
|
|
345
|
+
* Both transports are attempted tolerantly — one will succeed, the other
|
|
346
|
+
* may fail silently.
|
|
347
|
+
*/
|
|
348
|
+
async leaveRoom(connectionId, roomId) {
|
|
349
|
+
await Promise.all([
|
|
350
|
+
this.sse.leaveRoom(connectionId, roomId).catch(() => void 0),
|
|
351
|
+
this.ws.leaveRoom(connectionId, roomId).catch(() => void 0)
|
|
352
|
+
]);
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Disconnect a specific connection.
|
|
356
|
+
*
|
|
357
|
+
* Both transports are attempted; the one owning the connection disconnects it.
|
|
358
|
+
*/
|
|
359
|
+
async disconnect(connectionId, reason) {
|
|
360
|
+
await Promise.all([
|
|
361
|
+
this.sse.disconnect(connectionId, reason).catch(() => void 0),
|
|
362
|
+
this.ws.disconnect(connectionId, reason).catch(() => void 0)
|
|
363
|
+
]);
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Run two transport tasks in parallel via `Promise.allSettled`.
|
|
367
|
+
*
|
|
368
|
+
* A rejection in either task is logged as a warning and does not propagate,
|
|
369
|
+
* ensuring one failing transport never blocks delivery on the other.
|
|
370
|
+
*/
|
|
371
|
+
async fanOut(op, ...tasks) {
|
|
372
|
+
const results = await Promise.allSettled(tasks.map((t) => t()));
|
|
373
|
+
for (const result of results) {
|
|
374
|
+
if (result.status === "rejected") {
|
|
375
|
+
this.logger.warn(
|
|
376
|
+
`Composite ${op} partially failed: ${result.reason.message ?? result.reason}`
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
exports.CompositeTransport = __decorateClass([
|
|
383
|
+
common.Injectable(),
|
|
384
|
+
__decorateParam(0, common.Inject(internal.SseTransport)),
|
|
385
|
+
__decorateParam(1, common.Inject(exports.WebSocketTransport))
|
|
386
|
+
], exports.CompositeTransport);
|
|
387
|
+
function firstQueryValue(value) {
|
|
388
|
+
return Array.isArray(value) ? value[0] : value;
|
|
389
|
+
}
|
|
390
|
+
exports.RealtimeGateway = class RealtimeGateway {
|
|
391
|
+
constructor(transport, options) {
|
|
392
|
+
this.transport = transport;
|
|
393
|
+
this.options = options;
|
|
394
|
+
}
|
|
395
|
+
transport;
|
|
396
|
+
options;
|
|
397
|
+
logger = new common.Logger(exports.RealtimeGateway.name);
|
|
398
|
+
server;
|
|
399
|
+
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
400
|
+
afterInit(server) {
|
|
401
|
+
this.transport.setServer(server);
|
|
402
|
+
this.logger.log("RealtimeGateway initialized");
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Handle a new WebSocket connection.
|
|
406
|
+
*
|
|
407
|
+
* Builds a `ConnectionAuthContext` from the Socket.IO handshake, merging the
|
|
408
|
+
* three supported auth patterns (spec §8.1):
|
|
409
|
+
* - Cookie HttpOnly — extracted via `parseCookieHeader`.
|
|
410
|
+
* - Ticket — available in `ctx.query.ticket` or via `auth.ticket`.
|
|
411
|
+
* - Bearer header — available in `headers.authorization` or via `auth.token`.
|
|
412
|
+
*
|
|
413
|
+
* `socket.handshake.auth.token` and `.ticket` are the Socket.IO-idiomatic paths
|
|
414
|
+
* (set via `io(url, { auth: { token } })`); the gateway normalizes them into the
|
|
415
|
+
* context so the authenticator sees a single unified shape regardless of client.
|
|
416
|
+
*
|
|
417
|
+
* Query values follow the Node `ParsedUrlQuery` shape (`string | string[] |
|
|
418
|
+
* undefined`); the single-value `ticket` parameter is collapsed to its first
|
|
419
|
+
* element so the authenticator receives a well-defined string.
|
|
420
|
+
*
|
|
421
|
+
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
422
|
+
* linger in an unregistered state and receive broadcast events.
|
|
423
|
+
*/
|
|
424
|
+
async handleConnection(socket) {
|
|
425
|
+
try {
|
|
426
|
+
const { handshake } = socket;
|
|
427
|
+
const headers = this.normalizeHeaders(handshake.headers);
|
|
428
|
+
const query = { ...handshake.query };
|
|
429
|
+
const handshakeAuth = handshake.auth;
|
|
430
|
+
if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
|
|
431
|
+
if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
|
|
432
|
+
const ticket = firstQueryValue(query["ticket"]);
|
|
433
|
+
if (ticket !== void 0) query["ticket"] = ticket;
|
|
434
|
+
const ctx = {
|
|
435
|
+
cookies: internal.parseCookieHeader(handshake.headers.cookie ?? ""),
|
|
436
|
+
headers,
|
|
437
|
+
query,
|
|
438
|
+
ip: handshake.address,
|
|
439
|
+
userAgent: handshake.headers["user-agent"],
|
|
440
|
+
transport: "websocket"
|
|
441
|
+
};
|
|
442
|
+
const auth = await this.transport.authenticator().authenticate(ctx);
|
|
443
|
+
if (!auth) {
|
|
444
|
+
socket.disconnect(true);
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
await this.transport.registerSocket(socket, auth);
|
|
448
|
+
if (this.options.websocket?.emitConnectionEvent !== false) {
|
|
449
|
+
socket.emit(internal.RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
|
|
450
|
+
connectionId: socket.id,
|
|
451
|
+
traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
} catch (err) {
|
|
455
|
+
this.logger.error(
|
|
456
|
+
`handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${err.message}`
|
|
457
|
+
);
|
|
458
|
+
socket.disconnect(true);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
/** Handle a WebSocket disconnection — unregister the connection. */
|
|
462
|
+
async handleDisconnect(socket) {
|
|
463
|
+
await this.transport.unregisterSocket(socket.id, "CLIENT_DISCONNECT");
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Normalize raw Socket.IO handshake headers into a plain lowercase-keyed map.
|
|
467
|
+
*
|
|
468
|
+
* Array header values (e.g. `Set-Cookie`) are joined with `,` to produce a
|
|
469
|
+
* single string, matching the shape expected by `ConnectionAuthContext.headers`.
|
|
470
|
+
*/
|
|
471
|
+
normalizeHeaders(input) {
|
|
472
|
+
const out = {};
|
|
473
|
+
for (const [k, v] of Object.entries(input)) {
|
|
474
|
+
out[k.toLowerCase()] = Array.isArray(v) ? v.join(",") : v;
|
|
475
|
+
}
|
|
476
|
+
return out;
|
|
477
|
+
}
|
|
478
|
+
};
|
|
479
|
+
__decorateClass([
|
|
480
|
+
websockets.WebSocketServer()
|
|
481
|
+
], exports.RealtimeGateway.prototype, "server", 2);
|
|
482
|
+
exports.RealtimeGateway = __decorateClass([
|
|
483
|
+
websockets.WebSocketGateway({
|
|
484
|
+
cors: { origin: false }
|
|
485
|
+
}),
|
|
486
|
+
__decorateParam(0, common.Inject(exports.WebSocketTransport)),
|
|
487
|
+
__decorateParam(1, common.Inject(internal.REALTIME_OPTIONS_TOKEN))
|
|
488
|
+
], exports.RealtimeGateway);
|
|
489
|
+
|
|
490
|
+
// src/websocket/websocket-wiring.ts
|
|
491
|
+
var DEFAULT_ASYNC_ENDPOINT = "/events";
|
|
492
|
+
var webSocketWiring = {
|
|
493
|
+
modes: ["websocket", "both"],
|
|
494
|
+
build(resolved) {
|
|
495
|
+
if (resolved.transport === "websocket") {
|
|
496
|
+
return {
|
|
497
|
+
providers: [
|
|
498
|
+
exports.WebSocketTransport,
|
|
499
|
+
{ provide: internal.REALTIME_TRANSPORT_TOKEN, useExisting: exports.WebSocketTransport }
|
|
500
|
+
],
|
|
501
|
+
endpoints: [],
|
|
502
|
+
gateways: [exports.RealtimeGateway]
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
return {
|
|
506
|
+
providers: [
|
|
507
|
+
internal.SseTransport,
|
|
508
|
+
exports.WebSocketTransport,
|
|
509
|
+
exports.CompositeTransport,
|
|
510
|
+
internal.SseSubscriptionHandler,
|
|
511
|
+
internal.RealtimePubSubSubscriber,
|
|
512
|
+
{ provide: internal.REALTIME_TRANSPORT_TOKEN, useExisting: exports.CompositeTransport }
|
|
513
|
+
],
|
|
514
|
+
endpoints: [resolved.sse.endpoint],
|
|
515
|
+
gateways: [exports.RealtimeGateway]
|
|
516
|
+
};
|
|
517
|
+
},
|
|
518
|
+
buildAsync(mode) {
|
|
519
|
+
if (mode === "websocket") {
|
|
520
|
+
return {
|
|
521
|
+
providers: [
|
|
522
|
+
exports.WebSocketTransport,
|
|
523
|
+
exports.RealtimeGateway,
|
|
524
|
+
{ provide: internal.REALTIME_TRANSPORT_TOKEN, useExisting: exports.WebSocketTransport }
|
|
525
|
+
],
|
|
526
|
+
controllers: []
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
return {
|
|
530
|
+
providers: [
|
|
531
|
+
internal.SseTransport,
|
|
532
|
+
internal.SseSubscriptionHandler,
|
|
533
|
+
exports.WebSocketTransport,
|
|
534
|
+
exports.CompositeTransport,
|
|
535
|
+
exports.RealtimeGateway,
|
|
536
|
+
internal.RealtimePubSubSubscriber,
|
|
537
|
+
{ provide: internal.REALTIME_TRANSPORT_TOKEN, useExisting: exports.CompositeTransport }
|
|
538
|
+
],
|
|
539
|
+
controllers: [internal.createSseController(DEFAULT_ASYNC_ENDPOINT)]
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
|
|
544
|
+
// src/websocket/realtime-websocket.module.ts
|
|
545
|
+
exports.BymaxRealtimeWebSocketModule = class BymaxRealtimeWebSocketModule {
|
|
546
|
+
/**
|
|
547
|
+
* Configure the module synchronously.
|
|
548
|
+
*
|
|
549
|
+
* @throws when the options are invalid.
|
|
550
|
+
* @example
|
|
551
|
+
* ```ts
|
|
552
|
+
* BymaxRealtimeWebSocketModule.forRoot({
|
|
553
|
+
* transport: 'websocket',
|
|
554
|
+
* authenticator: new MyAuthenticator(),
|
|
555
|
+
* })
|
|
556
|
+
* ```
|
|
557
|
+
*/
|
|
558
|
+
static forRoot(options) {
|
|
559
|
+
return internal.composeForRoot(
|
|
560
|
+
exports.BymaxRealtimeWebSocketModule,
|
|
561
|
+
webSocketWiring,
|
|
562
|
+
exports.BymaxRealtimeWebSocketModule.logger,
|
|
563
|
+
options
|
|
564
|
+
);
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* Configure the module asynchronously so options — and the authenticator —
|
|
568
|
+
* can be resolved through DI.
|
|
569
|
+
*
|
|
570
|
+
* Controllers are registered at decoration time, so `'both'` binds the SSE
|
|
571
|
+
* controller to the default endpoint `/events`. A non-default endpoint needs
|
|
572
|
+
* `forRoot` with pre-resolved options.
|
|
573
|
+
*
|
|
574
|
+
* @throws when no factory pattern is given, more than one is, or the factory
|
|
575
|
+
* resolves a transport other than the one declared.
|
|
576
|
+
* @example
|
|
577
|
+
* ```ts
|
|
578
|
+
* BymaxRealtimeWebSocketModule.forRootAsync({
|
|
579
|
+
* transport: 'both',
|
|
580
|
+
* imports: [ConfigModule],
|
|
581
|
+
* inject: [ConfigService],
|
|
582
|
+
* useFactory: (cfg: ConfigService) => ({
|
|
583
|
+
* transport: 'both' as const,
|
|
584
|
+
* authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
|
|
585
|
+
* }),
|
|
586
|
+
* })
|
|
587
|
+
* ```
|
|
588
|
+
*/
|
|
589
|
+
static forRootAsync(asyncOptions) {
|
|
590
|
+
return internal.composeForRootAsync(
|
|
591
|
+
exports.BymaxRealtimeWebSocketModule,
|
|
592
|
+
webSocketWiring,
|
|
593
|
+
exports.BymaxRealtimeWebSocketModule.logger,
|
|
594
|
+
asyncOptions
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
};
|
|
598
|
+
__publicField(exports.BymaxRealtimeWebSocketModule, "logger", new common.Logger(exports.BymaxRealtimeWebSocketModule.name));
|
|
599
|
+
exports.BymaxRealtimeWebSocketModule = __decorateClass([
|
|
600
|
+
common.Global(),
|
|
601
|
+
common.Module({})
|
|
602
|
+
], exports.BymaxRealtimeWebSocketModule);
|
|
603
|
+
var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
|
|
604
|
+
logger = new common.Logger(_RealtimeIoAdapter.name);
|
|
605
|
+
options;
|
|
606
|
+
constructor(app) {
|
|
607
|
+
super(app);
|
|
608
|
+
this.options = app.get(internal.REALTIME_OPTIONS_TOKEN);
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Bind the gateway to `websocket.namespace` when configured.
|
|
612
|
+
*
|
|
613
|
+
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
614
|
+
* the module options resolve — so the namespace cannot be declared there.
|
|
615
|
+
* Instead we build the root server via `super.create` (which routes through the
|
|
616
|
+
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
617
|
+
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
618
|
+
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
619
|
+
* namespace leaves the root server untouched.
|
|
620
|
+
*/
|
|
621
|
+
create(port, options) {
|
|
622
|
+
const server = super.create(port, options);
|
|
623
|
+
const ns = this.options.websocket?.namespace;
|
|
624
|
+
if (ns && ns !== "/" && typeof server.of === "function") {
|
|
625
|
+
return server.of(ns);
|
|
626
|
+
}
|
|
627
|
+
return server;
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Create the Socket.IO server with merged WebSocket options.
|
|
631
|
+
*
|
|
632
|
+
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
633
|
+
* `@socket.io/redis-adapter` lazily (so the package stays an optional peer
|
|
634
|
+
* dep — its absence does not crash the lib).
|
|
635
|
+
*/
|
|
636
|
+
createIOServer(port, opts) {
|
|
637
|
+
const wsOpts = this.options.websocket ?? {};
|
|
638
|
+
const mergedOpts = {
|
|
639
|
+
...opts,
|
|
640
|
+
cors: wsOpts.cors ?? opts?.cors,
|
|
641
|
+
pingInterval: wsOpts.pingIntervalMs ?? 25e3,
|
|
642
|
+
pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
|
|
643
|
+
maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
|
|
644
|
+
};
|
|
645
|
+
const server = super.createIOServer(port, mergedOpts);
|
|
646
|
+
if (wsOpts.redisAdapter?.pubClient) {
|
|
647
|
+
this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
|
|
648
|
+
}
|
|
649
|
+
return server;
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* Lazily load and install `@socket.io/redis-adapter`.
|
|
653
|
+
*
|
|
654
|
+
* Uses a dynamic `require` so the package stays optional — absent peers do
|
|
655
|
+
* not crash the lib. A load or install failure is logged and tolerated;
|
|
656
|
+
* the lib degrades gracefully to single-instance mode.
|
|
657
|
+
*/
|
|
658
|
+
installRedisAdapter(server, pubClient) {
|
|
659
|
+
try {
|
|
660
|
+
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
661
|
+
const pub = pubClient;
|
|
662
|
+
const sub = pub.duplicate();
|
|
663
|
+
server.adapter(createAdapter(pub, sub));
|
|
664
|
+
this.logger.log(
|
|
665
|
+
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
666
|
+
);
|
|
667
|
+
} catch (err) {
|
|
668
|
+
this.logger.error(
|
|
669
|
+
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
};
|
|
674
|
+
|
|
675
|
+
exports.RealtimeIoAdapter = RealtimeIoAdapter;
|