@bymax-one/nest-realtime 1.2.6 → 1.2.8
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 +145 -1
- package/README.md +84 -52
- package/dist/internal/index.cjs +296 -436
- package/dist/internal/index.d.cts +215 -45
- package/dist/internal/index.d.ts +215 -45
- package/dist/internal/index.mjs +295 -437
- package/dist/react/index.cjs +0 -2
- package/dist/react/index.d.cts +2 -1
- package/dist/react/index.d.ts +2 -1
- package/dist/react/index.mjs +0 -2
- package/dist/server/index.d.cts +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/shared/index.cjs +1 -0
- package/dist/shared/index.d.cts +3 -1
- package/dist/shared/index.d.ts +3 -1
- package/dist/shared/index.mjs +1 -0
- package/dist/websocket/index.cjs +60 -283
- package/dist/websocket/index.d.cts +30 -11
- package/dist/websocket/index.d.ts +30 -11
- package/dist/websocket/index.mjs +61 -284
- package/package.json +3 -3
package/dist/websocket/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
2
|
import { Injectable, Inject, Logger, Global, Module } from '@nestjs/common';
|
|
3
|
-
import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, ROOM_PREFIXES,
|
|
3
|
+
import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, unavailableError, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, describeError, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
|
|
4
4
|
import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
|
|
5
5
|
import { IoAdapter } from '@nestjs/platform-socket.io';
|
|
6
6
|
|
|
@@ -40,60 +40,30 @@ var WebSocketTransport = class {
|
|
|
40
40
|
options;
|
|
41
41
|
kind = "websocket";
|
|
42
42
|
logger = new Logger(WebSocketTransport.name);
|
|
43
|
-
/** Nullable until the gateway's afterInit wires the instance. */
|
|
44
43
|
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
|
-
*/
|
|
44
|
+
warnedUnattached = false;
|
|
53
45
|
setServer(server) {
|
|
54
46
|
this.server = server;
|
|
55
47
|
this.logger.log("Socket.IO server wired to WebSocketTransport");
|
|
56
48
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
49
|
+
attached(op) {
|
|
50
|
+
if (!this.server && !this.warnedUnattached) {
|
|
51
|
+
this.warnedUnattached = true;
|
|
52
|
+
this.logger.warn(
|
|
53
|
+
`${REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE} op=${op}: no WebSocket server is attached yet, so emits are dropped until the gateway initialises`
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
return this.server;
|
|
57
|
+
}
|
|
66
58
|
localSockets() {
|
|
67
59
|
const server = this.server;
|
|
68
60
|
if (!server) return void 0;
|
|
69
61
|
const sockets = server.sockets;
|
|
70
62
|
return sockets instanceof Map ? sockets : sockets.sockets;
|
|
71
63
|
}
|
|
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
64
|
authenticator() {
|
|
82
65
|
return this.auth;
|
|
83
66
|
}
|
|
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
67
|
async registerSocket(socket, auth) {
|
|
98
68
|
const connectedAt = /* @__PURE__ */ new Date();
|
|
99
69
|
this.connections.register({
|
|
@@ -131,16 +101,6 @@ var WebSocketTransport = class {
|
|
|
131
101
|
connectedAt
|
|
132
102
|
});
|
|
133
103
|
}
|
|
134
|
-
/**
|
|
135
|
-
* Unregister a disconnected WebSocket connection.
|
|
136
|
-
*
|
|
137
|
-
* Removes the record from `ConnectionRegistry`, clears all room membership
|
|
138
|
-
* from `RoomRegistry`, and fires the `onDisconnect` lifecycle hook with the
|
|
139
|
-
* computed `durationMs`.
|
|
140
|
-
*
|
|
141
|
-
* @param connectionId - The Socket.IO socket `id` of the disconnected connection.
|
|
142
|
-
* @param reason - Optional reason string forwarded to the `onDisconnect` hook.
|
|
143
|
-
*/
|
|
144
104
|
async unregisterSocket(connectionId, reason) {
|
|
145
105
|
const record = this.connections.unregister(connectionId);
|
|
146
106
|
if (!record) return;
|
|
@@ -160,51 +120,18 @@ var WebSocketTransport = class {
|
|
|
160
120
|
};
|
|
161
121
|
await this.hooks.onDisconnect?.(disconnectMeta);
|
|
162
122
|
}
|
|
163
|
-
/**
|
|
164
|
-
* Send an event to every connection of a user (uses `user:{userId}` room).
|
|
165
|
-
*
|
|
166
|
-
* @param userId - Target user identifier.
|
|
167
|
-
* @param event - Event name to emit.
|
|
168
|
-
* @param data - Payload forwarded to all matching connections.
|
|
169
|
-
*/
|
|
170
123
|
async emitToUser(userId, event, data) {
|
|
171
|
-
this.
|
|
172
|
-
}
|
|
173
|
-
/**
|
|
174
|
-
* Send an event to every connection within a tenant (uses `tenant:{tenantId}` room).
|
|
175
|
-
*
|
|
176
|
-
* @param tenantId - Target tenant identifier.
|
|
177
|
-
* @param event - Event name to emit.
|
|
178
|
-
* @param data - Payload forwarded to all matching connections.
|
|
179
|
-
*/
|
|
124
|
+
this.attached("emitToUser")?.to(`${ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
|
|
125
|
+
}
|
|
180
126
|
async emitToTenant(tenantId, event, data) {
|
|
181
|
-
this.
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Send an event to every connection in an arbitrary room.
|
|
185
|
-
*
|
|
186
|
-
* @param roomId - The fully-qualified room identifier (e.g., `user:u-1`, `tenant:t-1`).
|
|
187
|
-
* @param event - Event name to emit.
|
|
188
|
-
* @param data - Payload forwarded to all connections in the room.
|
|
189
|
-
*/
|
|
127
|
+
this.attached("emitToTenant")?.to(`${ROOM_PREFIXES.TENANT}:${tenantId}`).emit(event, data);
|
|
128
|
+
}
|
|
190
129
|
async emitToRoom(roomId, event, data) {
|
|
191
|
-
this.
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Broadcast an event to all connected clients.
|
|
195
|
-
*
|
|
196
|
-
* @param event - Event name to emit.
|
|
197
|
-
* @param data - Payload forwarded to every connected socket.
|
|
198
|
-
*/
|
|
130
|
+
this.attached("emitToRoom")?.to(roomId).emit(event, data);
|
|
131
|
+
}
|
|
199
132
|
async broadcast(event, data) {
|
|
200
|
-
this.
|
|
201
|
-
}
|
|
202
|
-
/**
|
|
203
|
-
* Join a connection to an additional room (updates both Socket.IO and `RoomRegistry`).
|
|
204
|
-
*
|
|
205
|
-
* @param connectionId - The socket `id` of the connection to join.
|
|
206
|
-
* @param roomId - The room to join.
|
|
207
|
-
*/
|
|
133
|
+
this.attached("broadcast")?.emit(event, data);
|
|
134
|
+
}
|
|
208
135
|
async joinRoom(connectionId, roomId) {
|
|
209
136
|
const socket = this.localSockets()?.get(connectionId);
|
|
210
137
|
if (socket) {
|
|
@@ -212,12 +139,6 @@ var WebSocketTransport = class {
|
|
|
212
139
|
this.rooms.join(connectionId, roomId);
|
|
213
140
|
}
|
|
214
141
|
}
|
|
215
|
-
/**
|
|
216
|
-
* Remove a connection from a room (updates both Socket.IO and `RoomRegistry`).
|
|
217
|
-
*
|
|
218
|
-
* @param connectionId - The socket `id` of the connection to remove.
|
|
219
|
-
* @param roomId - The room to leave.
|
|
220
|
-
*/
|
|
221
142
|
async leaveRoom(connectionId, roomId) {
|
|
222
143
|
const socket = this.localSockets()?.get(connectionId);
|
|
223
144
|
if (socket) {
|
|
@@ -225,31 +146,29 @@ var WebSocketTransport = class {
|
|
|
225
146
|
this.rooms.leave(connectionId, roomId);
|
|
226
147
|
}
|
|
227
148
|
}
|
|
228
|
-
/**
|
|
229
|
-
* Force-disconnect a specific connection — adapter-aware, so revocation works
|
|
230
|
-
* across nodes.
|
|
231
|
-
*
|
|
232
|
-
* A socket local to this node is closed directly as a fast path. Regardless,
|
|
233
|
-
* `disconnectSockets` is broadcast to the connection's `connection:{id}` room:
|
|
234
|
-
* under `@socket.io/redis-adapter` this fans out to remote nodes, so a
|
|
235
|
-
* connection pinned to another instance is still force-closed. The local socket
|
|
236
|
-
* has already left the room by then, so the broadcast does not double-close it.
|
|
237
|
-
*
|
|
238
|
-
* @param connectionId - The socket `id` of the connection to disconnect.
|
|
239
|
-
* @param _reason - Optional reason string (unused at the Socket.IO level; passed to `unregisterSocket`).
|
|
240
|
-
*/
|
|
241
149
|
async disconnect(connectionId, _reason) {
|
|
242
150
|
const server = this.server;
|
|
243
|
-
if (!server)
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
151
|
+
if (!server) {
|
|
152
|
+
throw unavailableError(
|
|
153
|
+
REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
|
|
154
|
+
WebSocketTransport.name,
|
|
155
|
+
`the WebSocket server is not attached, so ${connectionId} cannot be revoked`,
|
|
156
|
+
new Error("server not attached")
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
const local = this.localSockets()?.get(connectionId);
|
|
161
|
+
if (local) local.disconnect(true);
|
|
162
|
+
server.in(`${CONNECTION_ROOM_PREFIX}:${connectionId}`).disconnectSockets(true);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
throw unavailableError(
|
|
165
|
+
REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
|
|
166
|
+
WebSocketTransport.name,
|
|
167
|
+
`the revocation of ${connectionId} could not be sent`,
|
|
168
|
+
error
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
253
172
|
async evictBeyondLimit(userId) {
|
|
254
173
|
const max = this.options.websocket?.maxConnectionsPerUser;
|
|
255
174
|
if (max === void 0 || max <= 0) return;
|
|
@@ -281,13 +200,6 @@ var CompositeTransport = class {
|
|
|
281
200
|
ws;
|
|
282
201
|
kind = "sse";
|
|
283
202
|
logger = new Logger(CompositeTransport.name);
|
|
284
|
-
/**
|
|
285
|
-
* Emit to all connections of a user across both transports.
|
|
286
|
-
*
|
|
287
|
-
* @param userId - Target user identifier.
|
|
288
|
-
* @param event - Event name to emit.
|
|
289
|
-
* @param data - Payload forwarded to all matching connections.
|
|
290
|
-
*/
|
|
291
203
|
async emitToUser(userId, event, data) {
|
|
292
204
|
await this.fanOut(
|
|
293
205
|
"emitToUser",
|
|
@@ -295,13 +207,6 @@ var CompositeTransport = class {
|
|
|
295
207
|
() => this.ws.emitToUser(userId, event, data)
|
|
296
208
|
);
|
|
297
209
|
}
|
|
298
|
-
/**
|
|
299
|
-
* Emit to all connections within a tenant across both transports.
|
|
300
|
-
*
|
|
301
|
-
* @param tenantId - Target tenant identifier.
|
|
302
|
-
* @param event - Event name to emit.
|
|
303
|
-
* @param data - Payload forwarded to all matching connections.
|
|
304
|
-
*/
|
|
305
210
|
async emitToTenant(tenantId, event, data) {
|
|
306
211
|
await this.fanOut(
|
|
307
212
|
"emitToTenant",
|
|
@@ -309,13 +214,6 @@ var CompositeTransport = class {
|
|
|
309
214
|
() => this.ws.emitToTenant(tenantId, event, data)
|
|
310
215
|
);
|
|
311
216
|
}
|
|
312
|
-
/**
|
|
313
|
-
* Emit to all connections in a room across both transports.
|
|
314
|
-
*
|
|
315
|
-
* @param roomId - The fully-qualified room identifier.
|
|
316
|
-
* @param event - Event name to emit.
|
|
317
|
-
* @param data - Payload forwarded to all connections in the room.
|
|
318
|
-
*/
|
|
319
217
|
async emitToRoom(roomId, event, data) {
|
|
320
218
|
await this.fanOut(
|
|
321
219
|
"emitToRoom",
|
|
@@ -323,12 +221,6 @@ var CompositeTransport = class {
|
|
|
323
221
|
() => this.ws.emitToRoom(roomId, event, data)
|
|
324
222
|
);
|
|
325
223
|
}
|
|
326
|
-
/**
|
|
327
|
-
* Broadcast to all connected clients across both transports.
|
|
328
|
-
*
|
|
329
|
-
* @param event - Event name to emit.
|
|
330
|
-
* @param data - Payload forwarded to every connected client.
|
|
331
|
-
*/
|
|
332
224
|
async broadcast(event, data) {
|
|
333
225
|
await this.fanOut(
|
|
334
226
|
"broadcast",
|
|
@@ -336,47 +228,36 @@ var CompositeTransport = class {
|
|
|
336
228
|
() => this.ws.broadcast(event, data)
|
|
337
229
|
);
|
|
338
230
|
}
|
|
339
|
-
/**
|
|
340
|
-
* Join a connection to a room.
|
|
341
|
-
*
|
|
342
|
-
* Both transports are attempted; only the one that owns the connection
|
|
343
|
-
* succeeds. The other's failure is expected and swallowed.
|
|
344
|
-
*/
|
|
345
231
|
async joinRoom(connectionId, roomId) {
|
|
346
|
-
await
|
|
347
|
-
this.sse.joinRoom(connectionId, roomId)
|
|
348
|
-
this.ws.joinRoom(connectionId, roomId)
|
|
232
|
+
await this.settleBoth("joinRoom", connectionId, [
|
|
233
|
+
() => this.sse.joinRoom(connectionId, roomId),
|
|
234
|
+
() => this.ws.joinRoom(connectionId, roomId)
|
|
349
235
|
]);
|
|
350
236
|
}
|
|
351
|
-
/**
|
|
352
|
-
* Remove a connection from a room.
|
|
353
|
-
*
|
|
354
|
-
* Both transports are attempted tolerantly — one will succeed, the other
|
|
355
|
-
* may fail silently.
|
|
356
|
-
*/
|
|
357
237
|
async leaveRoom(connectionId, roomId) {
|
|
358
|
-
await
|
|
359
|
-
this.sse.leaveRoom(connectionId, roomId)
|
|
360
|
-
this.ws.leaveRoom(connectionId, roomId)
|
|
238
|
+
await this.settleBoth("leaveRoom", connectionId, [
|
|
239
|
+
() => this.sse.leaveRoom(connectionId, roomId),
|
|
240
|
+
() => this.ws.leaveRoom(connectionId, roomId)
|
|
361
241
|
]);
|
|
362
242
|
}
|
|
363
|
-
/**
|
|
364
|
-
* Disconnect a specific connection.
|
|
365
|
-
*
|
|
366
|
-
* Both transports are attempted; the one owning the connection disconnects it.
|
|
367
|
-
*/
|
|
368
243
|
async disconnect(connectionId, reason) {
|
|
369
|
-
await
|
|
370
|
-
this.sse.disconnect(connectionId, reason)
|
|
371
|
-
this.ws.disconnect(connectionId, reason)
|
|
244
|
+
await this.settleBoth("disconnect", connectionId, [
|
|
245
|
+
() => this.sse.disconnect(connectionId, reason),
|
|
246
|
+
() => this.ws.disconnect(connectionId, reason)
|
|
372
247
|
]);
|
|
373
248
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
249
|
+
async settleBoth(op, connectionId, tasks) {
|
|
250
|
+
const results = await Promise.allSettled(tasks.map((t) => t()));
|
|
251
|
+
const reasons = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
|
|
252
|
+
if (reasons.length === 0) return;
|
|
253
|
+
if (reasons.length === 1) throw reasons[0];
|
|
254
|
+
throw unavailableError(
|
|
255
|
+
REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
|
|
256
|
+
CompositeTransport.name,
|
|
257
|
+
`${op} of ${connectionId} failed on both transports`,
|
|
258
|
+
new AggregateError(reasons, reasons.map(describeError).join("; "))
|
|
259
|
+
);
|
|
260
|
+
}
|
|
380
261
|
async fanOut(op, ...tasks) {
|
|
381
262
|
const results = await Promise.allSettled(tasks.map((t) => t()));
|
|
382
263
|
for (const result of results) {
|
|
@@ -402,17 +283,6 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
|
402
283
|
super(app);
|
|
403
284
|
this.options = app.get(REALTIME_OPTIONS_TOKEN);
|
|
404
285
|
}
|
|
405
|
-
/**
|
|
406
|
-
* Bind the gateway to `websocket.namespace` when configured.
|
|
407
|
-
*
|
|
408
|
-
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
409
|
-
* the module options resolve — so the namespace cannot be declared there.
|
|
410
|
-
* Instead we build the root server via `super.create` (which routes through the
|
|
411
|
-
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
412
|
-
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
413
|
-
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
414
|
-
* namespace leaves the root server untouched.
|
|
415
|
-
*/
|
|
416
286
|
create(port, options) {
|
|
417
287
|
const server = super.create(port, options);
|
|
418
288
|
const ns = this.options.websocket?.namespace;
|
|
@@ -423,12 +293,6 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
|
423
293
|
}
|
|
424
294
|
return server;
|
|
425
295
|
}
|
|
426
|
-
/**
|
|
427
|
-
* Create the Socket.IO server with merged WebSocket options.
|
|
428
|
-
*
|
|
429
|
-
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
430
|
-
* `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
|
|
431
|
-
*/
|
|
432
296
|
createIOServer(port, opts) {
|
|
433
297
|
const wsOpts = this.options.websocket ?? {};
|
|
434
298
|
const mergedOpts = {
|
|
@@ -450,11 +314,6 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
|
450
314
|
realtimeServers.add(server);
|
|
451
315
|
return server;
|
|
452
316
|
}
|
|
453
|
-
/**
|
|
454
|
-
* Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
|
|
455
|
-
* silent single-instance server drops cross-node messages. An unreachable Redis
|
|
456
|
-
* is not one; reconnecting stays with the client.
|
|
457
|
-
*/
|
|
458
317
|
installRedisAdapter(server, pubClient) {
|
|
459
318
|
try {
|
|
460
319
|
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
@@ -487,9 +346,7 @@ var RealtimeGateway = class {
|
|
|
487
346
|
options;
|
|
488
347
|
logger = new Logger(RealtimeGateway.name);
|
|
489
348
|
server;
|
|
490
|
-
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
491
349
|
authenticated = /* @__PURE__ */ new WeakMap();
|
|
492
|
-
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
493
350
|
authenticateHandshake = async (socket, next) => {
|
|
494
351
|
try {
|
|
495
352
|
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
@@ -508,52 +365,18 @@ var RealtimeGateway = class {
|
|
|
508
365
|
next(new Error("Internal Server Error"));
|
|
509
366
|
}
|
|
510
367
|
};
|
|
511
|
-
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
512
368
|
afterInit(server) {
|
|
513
369
|
server.use(this.authenticateHandshake);
|
|
514
370
|
this.transport.setServer(server);
|
|
515
371
|
if (!isRealtimeIoServer(server)) this.reportMissingAdapter();
|
|
516
372
|
this.logger.log("RealtimeGateway initialized");
|
|
517
373
|
}
|
|
518
|
-
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
519
374
|
reportMissingAdapter() {
|
|
520
375
|
const configured = Object.keys(this.options.websocket ?? {});
|
|
521
376
|
this.logger.error(
|
|
522
377
|
"RealtimeIoAdapter is not the active WebSocket adapter, so the websocket options" + (configured.length > 0 ? ` (${configured.join(", ")})` : "") + " are ignored and the gateway CORS stays closed (origin: false): browsers on another origin cannot connect. Add app.useWebSocketAdapter(new RealtimeIoAdapter(app)) in main.ts, importing it from '@bymax-one/nest-realtime/websocket'."
|
|
523
378
|
);
|
|
524
379
|
}
|
|
525
|
-
/**
|
|
526
|
-
* Handle a new WebSocket connection.
|
|
527
|
-
*
|
|
528
|
-
* Builds a `ConnectionAuthContext` from the Socket.IO handshake, merging the
|
|
529
|
-
* three supported auth patterns (spec §8.1):
|
|
530
|
-
* - Cookie HttpOnly — extracted via `parseCookieHeader`.
|
|
531
|
-
* - Ticket — available in `ctx.query.ticket` or via `auth.ticket`.
|
|
532
|
-
* - Bearer header — available in `headers.authorization` or via `auth.token`.
|
|
533
|
-
*
|
|
534
|
-
* `socket.handshake.auth.token` and `.ticket` are the Socket.IO-idiomatic paths
|
|
535
|
-
* (set via `io(url, { auth: { token } })`); the gateway normalizes them into the
|
|
536
|
-
* context so the authenticator sees a single unified shape regardless of client.
|
|
537
|
-
*
|
|
538
|
-
* Query values follow the Node `ParsedUrlQuery` shape (`string | string[] |
|
|
539
|
-
* undefined`); the single-value `ticket` parameter is collapsed to its first
|
|
540
|
-
* element so the authenticator receives a well-defined string.
|
|
541
|
-
*
|
|
542
|
-
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
543
|
-
* linger in an unregistered state and receive broadcast events.
|
|
544
|
-
*/
|
|
545
|
-
/**
|
|
546
|
-
* Map a Socket.IO handshake onto the transport-agnostic auth context.
|
|
547
|
-
*
|
|
548
|
-
* Socket.IO carries credentials in three places and the authenticator sees one
|
|
549
|
-
* shape: `handshake.auth` is merged into the headers and query it stands in for,
|
|
550
|
-
* and a repeated `ticket` parameter is collapsed to its first value, because the
|
|
551
|
-
* ticket pattern is single-valued and an array reaching an authenticator that
|
|
552
|
-
* expects a string is a bug at the far end.
|
|
553
|
-
*
|
|
554
|
-
* @param socket - The connecting Socket.IO socket.
|
|
555
|
-
* @returns The context handed to `IConnectionAuthenticator.authenticate`.
|
|
556
|
-
*/
|
|
557
380
|
buildAuthContext(socket) {
|
|
558
381
|
const { handshake } = socket;
|
|
559
382
|
const headers = this.normalizeHeaders(handshake.headers);
|
|
@@ -604,16 +427,9 @@ var RealtimeGateway = class {
|
|
|
604
427
|
socket.disconnect(true);
|
|
605
428
|
}
|
|
606
429
|
}
|
|
607
|
-
/** Handle a WebSocket disconnection — unregister the connection. */
|
|
608
430
|
async handleDisconnect(socket) {
|
|
609
431
|
await this.transport.unregisterSocket(socket.id, "CLIENT_DISCONNECT");
|
|
610
432
|
}
|
|
611
|
-
/**
|
|
612
|
-
* Normalize raw Socket.IO handshake headers into a plain lowercase-keyed map.
|
|
613
|
-
*
|
|
614
|
-
* Array header values (e.g. `Set-Cookie`) are joined with `,` to produce a
|
|
615
|
-
* single string, matching the shape expected by `ConnectionAuthContext.headers`.
|
|
616
|
-
*/
|
|
617
433
|
normalizeHeaders(input) {
|
|
618
434
|
const out = {};
|
|
619
435
|
for (const [k, v] of Object.entries(input)) {
|
|
@@ -688,18 +504,6 @@ var webSocketWiring = {
|
|
|
688
504
|
|
|
689
505
|
// src/websocket/realtime-websocket.module.ts
|
|
690
506
|
var BymaxRealtimeWebSocketModule = class {
|
|
691
|
-
/**
|
|
692
|
-
* Configure the module synchronously.
|
|
693
|
-
*
|
|
694
|
-
* @throws when the options are invalid.
|
|
695
|
-
* @example
|
|
696
|
-
* ```ts
|
|
697
|
-
* BymaxRealtimeWebSocketModule.forRoot({
|
|
698
|
-
* transport: 'websocket',
|
|
699
|
-
* authenticator: new MyAuthenticator(),
|
|
700
|
-
* })
|
|
701
|
-
* ```
|
|
702
|
-
*/
|
|
703
507
|
static forRoot(options) {
|
|
704
508
|
return composeForRoot(
|
|
705
509
|
BymaxRealtimeWebSocketModule,
|
|
@@ -708,33 +512,6 @@ var BymaxRealtimeWebSocketModule = class {
|
|
|
708
512
|
options
|
|
709
513
|
);
|
|
710
514
|
}
|
|
711
|
-
/**
|
|
712
|
-
* Configure the module asynchronously so options — and the authenticator —
|
|
713
|
-
* can be resolved through DI.
|
|
714
|
-
*
|
|
715
|
-
* Controllers are registered at decoration time, so under `'both'` the SSE
|
|
716
|
-
* route comes from `sseEndpoint` on the registration rather than from the
|
|
717
|
-
* `sse.endpoint` the factory resolves — the factory has not run yet when the
|
|
718
|
-
* controller is built. It defaults to `/events`, and a factory that resolves
|
|
719
|
-
* a disagreeing `sse.endpoint` is rejected at bootstrap. `'websocket'`
|
|
720
|
-
* registers no SSE controller, so `sseEndpoint` is rejected there outright.
|
|
721
|
-
*
|
|
722
|
-
* @throws when no factory pattern is given, more than one is, or the factory
|
|
723
|
-
* resolves a transport other than the one declared.
|
|
724
|
-
* @example
|
|
725
|
-
* ```ts
|
|
726
|
-
* BymaxRealtimeWebSocketModule.forRootAsync({
|
|
727
|
-
* transport: 'both',
|
|
728
|
-
* sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
|
|
729
|
-
* imports: [ConfigModule],
|
|
730
|
-
* inject: [ConfigService],
|
|
731
|
-
* useFactory: (cfg: ConfigService) => ({
|
|
732
|
-
* transport: 'both' as const,
|
|
733
|
-
* authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
|
|
734
|
-
* }),
|
|
735
|
-
* })
|
|
736
|
-
* ```
|
|
737
|
-
*/
|
|
738
515
|
static forRootAsync(asyncOptions) {
|
|
739
516
|
return composeForRootAsync(
|
|
740
517
|
BymaxRealtimeWebSocketModule,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bymax-one/nest-realtime",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.8",
|
|
4
4
|
"description": "Realtime backend → frontend communication for NestJS — dual-transport SSE (default) and WebSocket (opt-in) with a unified server-side API.",
|
|
5
5
|
"author": "Bymax One <support@bymax.one>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -93,7 +93,7 @@
|
|
|
93
93
|
}
|
|
94
94
|
},
|
|
95
95
|
"scripts": {
|
|
96
|
-
"build": "pnpm clean && tsup",
|
|
96
|
+
"build": "pnpm clean && tsup && node scripts/strip-bundle-comments.mjs",
|
|
97
97
|
"check:exports": "attw --pack . --profile strict",
|
|
98
98
|
"check:mutants": "node scripts/check-mutation-directives.mjs",
|
|
99
99
|
"check:api": "node scripts/check-api-surface.mjs",
|
|
@@ -206,7 +206,7 @@
|
|
|
206
206
|
"ts-jest": "^29.4.12",
|
|
207
207
|
"ts-node": "^10.9.0",
|
|
208
208
|
"tslib": "^2.6.0",
|
|
209
|
-
"tsup": "^
|
|
209
|
+
"tsup": "^9.0.0",
|
|
210
210
|
"typescript": "^5.6.0"
|
|
211
211
|
},
|
|
212
212
|
"packageManager": "pnpm@11.20.0",
|