@bymax-one/nest-realtime 1.2.0 → 1.2.2
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 +170 -1
- package/README.md +155 -22
- package/dist/internal/index.cjs +153 -13
- package/dist/internal/index.d.cts +144 -14
- package/dist/internal/index.d.ts +144 -14
- package/dist/internal/index.mjs +153 -15
- package/dist/websocket/index.cjs +158 -93
- package/dist/websocket/index.d.cts +20 -1
- package/dist/websocket/index.d.ts +20 -1
- package/dist/websocket/index.mjs +159 -94
- package/package.json +1 -1
package/dist/websocket/index.cjs
CHANGED
|
@@ -393,6 +393,86 @@ exports.CompositeTransport = __decorateClass([
|
|
|
393
393
|
__decorateParam(0, common.Inject(internal.SseTransport)),
|
|
394
394
|
__decorateParam(1, common.Inject(exports.WebSocketTransport))
|
|
395
395
|
], exports.CompositeTransport);
|
|
396
|
+
var realtimeServers = /* @__PURE__ */ new WeakSet();
|
|
397
|
+
function isRealtimeIoServer(server) {
|
|
398
|
+
return typeof server === "object" && server !== null && realtimeServers.has(server);
|
|
399
|
+
}
|
|
400
|
+
var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
|
|
401
|
+
adapterLogger = new common.Logger(_RealtimeIoAdapter.name);
|
|
402
|
+
options;
|
|
403
|
+
constructor(app) {
|
|
404
|
+
super(app);
|
|
405
|
+
this.options = app.get(internal.REALTIME_OPTIONS_TOKEN);
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Bind the gateway to `websocket.namespace` when configured.
|
|
409
|
+
*
|
|
410
|
+
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
411
|
+
* the module options resolve — so the namespace cannot be declared there.
|
|
412
|
+
* Instead we build the root server via `super.create` (which routes through the
|
|
413
|
+
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
414
|
+
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
415
|
+
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
416
|
+
* namespace leaves the root server untouched.
|
|
417
|
+
*/
|
|
418
|
+
create(port, options) {
|
|
419
|
+
const server = super.create(port, options);
|
|
420
|
+
const ns = this.options.websocket?.namespace;
|
|
421
|
+
if (ns && ns !== "/" && typeof server.of === "function") {
|
|
422
|
+
const namespace = server.of(ns);
|
|
423
|
+
realtimeServers.add(namespace);
|
|
424
|
+
return namespace;
|
|
425
|
+
}
|
|
426
|
+
return server;
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Create the Socket.IO server with merged WebSocket options.
|
|
430
|
+
*
|
|
431
|
+
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
432
|
+
* `@socket.io/redis-adapter` lazily (so the package stays an optional peer
|
|
433
|
+
* dep — its absence does not crash the lib).
|
|
434
|
+
*/
|
|
435
|
+
createIOServer(port, opts) {
|
|
436
|
+
const wsOpts = this.options.websocket ?? {};
|
|
437
|
+
const mergedOpts = {
|
|
438
|
+
...opts,
|
|
439
|
+
cors: wsOpts.cors ?? opts?.cors,
|
|
440
|
+
pingInterval: wsOpts.pingIntervalMs ?? 25e3,
|
|
441
|
+
pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
|
|
442
|
+
maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
|
|
443
|
+
};
|
|
444
|
+
const server = super.createIOServer(port, mergedOpts);
|
|
445
|
+
if (wsOpts.redisAdapter?.pubClient) {
|
|
446
|
+
this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
|
|
447
|
+
}
|
|
448
|
+
realtimeServers.add(server);
|
|
449
|
+
return server;
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Lazily load and install `@socket.io/redis-adapter`.
|
|
453
|
+
*
|
|
454
|
+
* Uses a dynamic `require` so the package stays optional — absent peers do
|
|
455
|
+
* not crash the lib. A load or install failure is logged and tolerated;
|
|
456
|
+
* the lib degrades gracefully to single-instance mode.
|
|
457
|
+
*/
|
|
458
|
+
installRedisAdapter(server, pubClient) {
|
|
459
|
+
try {
|
|
460
|
+
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
461
|
+
const pub = pubClient;
|
|
462
|
+
const sub = pub.duplicate();
|
|
463
|
+
server.adapter(createAdapter(pub, sub));
|
|
464
|
+
this.adapterLogger.log(
|
|
465
|
+
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
466
|
+
);
|
|
467
|
+
} catch (err) {
|
|
468
|
+
this.adapterLogger.error(
|
|
469
|
+
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
// src/websocket/transports/websocket/realtime.gateway.ts
|
|
396
476
|
function firstQueryValue(value) {
|
|
397
477
|
return Array.isArray(value) ? value[0] : value;
|
|
398
478
|
}
|
|
@@ -405,11 +485,43 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
405
485
|
options;
|
|
406
486
|
logger = new common.Logger(exports.RealtimeGateway.name);
|
|
407
487
|
server;
|
|
488
|
+
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
489
|
+
authenticated = /* @__PURE__ */ new WeakMap();
|
|
490
|
+
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
491
|
+
authenticateHandshake = async (socket, next) => {
|
|
492
|
+
try {
|
|
493
|
+
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
494
|
+
if (!auth) {
|
|
495
|
+
const refusal = new Error(internal.REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
496
|
+
refusal.data = { code: internal.REALTIME_ERROR_CODES.AUTH_FAILED };
|
|
497
|
+
next(refusal);
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
const resolvedAuth = internal.resolveAuthTenant(this.options, auth);
|
|
501
|
+
internal.assertIdentityIsNotBlank(resolvedAuth);
|
|
502
|
+
this.authenticated.set(socket, resolvedAuth);
|
|
503
|
+
next();
|
|
504
|
+
} catch (err) {
|
|
505
|
+
this.logger.error(
|
|
506
|
+
`handshake refused for socket ${socket.id}: ${err instanceof Error ? err.message : String(err)}`
|
|
507
|
+
);
|
|
508
|
+
next(new Error("Internal Server Error"));
|
|
509
|
+
}
|
|
510
|
+
};
|
|
408
511
|
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
409
512
|
afterInit(server) {
|
|
513
|
+
server.use(this.authenticateHandshake);
|
|
410
514
|
this.transport.setServer(server);
|
|
515
|
+
if (!isRealtimeIoServer(server)) this.reportMissingAdapter();
|
|
411
516
|
this.logger.log("RealtimeGateway initialized");
|
|
412
517
|
}
|
|
518
|
+
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
519
|
+
reportMissingAdapter() {
|
|
520
|
+
const configured = Object.keys(this.options.websocket ?? {});
|
|
521
|
+
this.logger.error(
|
|
522
|
+
"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
|
+
);
|
|
524
|
+
}
|
|
413
525
|
/**
|
|
414
526
|
* Handle a new WebSocket connection.
|
|
415
527
|
*
|
|
@@ -430,34 +542,58 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
430
542
|
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
431
543
|
* linger in an unregistered state and receive broadcast events.
|
|
432
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
|
+
buildAuthContext(socket) {
|
|
558
|
+
const { handshake } = socket;
|
|
559
|
+
const headers = this.normalizeHeaders(handshake.headers);
|
|
560
|
+
const query = { ...handshake.query };
|
|
561
|
+
const handshakeAuth = handshake.auth;
|
|
562
|
+
if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
|
|
563
|
+
if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
|
|
564
|
+
const ticket = firstQueryValue(query["ticket"]);
|
|
565
|
+
if (ticket !== void 0) query["ticket"] = ticket;
|
|
566
|
+
return {
|
|
567
|
+
cookies: internal.parseCookieHeader(handshake.headers.cookie ?? ""),
|
|
568
|
+
headers,
|
|
569
|
+
query,
|
|
570
|
+
ip: handshake.address,
|
|
571
|
+
userAgent: handshake.headers["user-agent"],
|
|
572
|
+
transport: "websocket"
|
|
573
|
+
};
|
|
574
|
+
}
|
|
433
575
|
async handleConnection(socket) {
|
|
434
576
|
try {
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
headers,
|
|
446
|
-
query,
|
|
447
|
-
ip: handshake.address,
|
|
448
|
-
userAgent: handshake.headers["user-agent"],
|
|
449
|
-
transport: "websocket"
|
|
450
|
-
};
|
|
451
|
-
const auth = await this.transport.authenticator().authenticate(ctx);
|
|
452
|
-
if (!auth) {
|
|
453
|
-
socket.disconnect(true);
|
|
454
|
-
return;
|
|
577
|
+
let resolvedAuth = this.authenticated.get(socket);
|
|
578
|
+
this.authenticated.delete(socket);
|
|
579
|
+
if (!resolvedAuth) {
|
|
580
|
+
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
581
|
+
if (!auth) {
|
|
582
|
+
socket.disconnect(true);
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
resolvedAuth = internal.resolveAuthTenant(this.options, auth);
|
|
586
|
+
internal.assertIdentityIsNotBlank(resolvedAuth);
|
|
455
587
|
}
|
|
456
|
-
await this.transport.registerSocket(socket,
|
|
588
|
+
await this.transport.registerSocket(socket, resolvedAuth);
|
|
457
589
|
if (this.options.websocket?.emitConnectionEvent !== false) {
|
|
458
590
|
socket.emit(internal.RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
|
|
459
591
|
connectionId: socket.id,
|
|
460
|
-
traits: {
|
|
592
|
+
traits: {
|
|
593
|
+
userId: resolvedAuth.userId,
|
|
594
|
+
tenantId: resolvedAuth.tenantId,
|
|
595
|
+
roles: resolvedAuth.roles
|
|
596
|
+
}
|
|
461
597
|
});
|
|
462
598
|
}
|
|
463
599
|
} catch (err) {
|
|
@@ -612,76 +748,5 @@ exports.BymaxRealtimeWebSocketModule = __decorateClass([
|
|
|
612
748
|
common.Global(),
|
|
613
749
|
common.Module({})
|
|
614
750
|
], exports.BymaxRealtimeWebSocketModule);
|
|
615
|
-
var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
|
|
616
|
-
logger = new common.Logger(_RealtimeIoAdapter.name);
|
|
617
|
-
options;
|
|
618
|
-
constructor(app) {
|
|
619
|
-
super(app);
|
|
620
|
-
this.options = app.get(internal.REALTIME_OPTIONS_TOKEN);
|
|
621
|
-
}
|
|
622
|
-
/**
|
|
623
|
-
* Bind the gateway to `websocket.namespace` when configured.
|
|
624
|
-
*
|
|
625
|
-
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
626
|
-
* the module options resolve — so the namespace cannot be declared there.
|
|
627
|
-
* Instead we build the root server via `super.create` (which routes through the
|
|
628
|
-
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
629
|
-
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
630
|
-
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
631
|
-
* namespace leaves the root server untouched.
|
|
632
|
-
*/
|
|
633
|
-
create(port, options) {
|
|
634
|
-
const server = super.create(port, options);
|
|
635
|
-
const ns = this.options.websocket?.namespace;
|
|
636
|
-
if (ns && ns !== "/" && typeof server.of === "function") {
|
|
637
|
-
return server.of(ns);
|
|
638
|
-
}
|
|
639
|
-
return server;
|
|
640
|
-
}
|
|
641
|
-
/**
|
|
642
|
-
* Create the Socket.IO server with merged WebSocket options.
|
|
643
|
-
*
|
|
644
|
-
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
645
|
-
* `@socket.io/redis-adapter` lazily (so the package stays an optional peer
|
|
646
|
-
* dep — its absence does not crash the lib).
|
|
647
|
-
*/
|
|
648
|
-
createIOServer(port, opts) {
|
|
649
|
-
const wsOpts = this.options.websocket ?? {};
|
|
650
|
-
const mergedOpts = {
|
|
651
|
-
...opts,
|
|
652
|
-
cors: wsOpts.cors ?? opts?.cors,
|
|
653
|
-
pingInterval: wsOpts.pingIntervalMs ?? 25e3,
|
|
654
|
-
pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
|
|
655
|
-
maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
|
|
656
|
-
};
|
|
657
|
-
const server = super.createIOServer(port, mergedOpts);
|
|
658
|
-
if (wsOpts.redisAdapter?.pubClient) {
|
|
659
|
-
this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
|
|
660
|
-
}
|
|
661
|
-
return server;
|
|
662
|
-
}
|
|
663
|
-
/**
|
|
664
|
-
* Lazily load and install `@socket.io/redis-adapter`.
|
|
665
|
-
*
|
|
666
|
-
* Uses a dynamic `require` so the package stays optional — absent peers do
|
|
667
|
-
* not crash the lib. A load or install failure is logged and tolerated;
|
|
668
|
-
* the lib degrades gracefully to single-instance mode.
|
|
669
|
-
*/
|
|
670
|
-
installRedisAdapter(server, pubClient) {
|
|
671
|
-
try {
|
|
672
|
-
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
673
|
-
const pub = pubClient;
|
|
674
|
-
const sub = pub.duplicate();
|
|
675
|
-
server.adapter(createAdapter(pub, sub));
|
|
676
|
-
this.logger.log(
|
|
677
|
-
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
678
|
-
);
|
|
679
|
-
} catch (err) {
|
|
680
|
-
this.logger.error(
|
|
681
|
-
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
682
|
-
);
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
};
|
|
686
751
|
|
|
687
752
|
exports.RealtimeIoAdapter = RealtimeIoAdapter;
|
|
@@ -226,8 +226,14 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
226
226
|
private readonly logger;
|
|
227
227
|
server: Server;
|
|
228
228
|
constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions);
|
|
229
|
+
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
230
|
+
private readonly authenticated;
|
|
231
|
+
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
232
|
+
private readonly authenticateHandshake;
|
|
229
233
|
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
230
234
|
afterInit(server: Server): void;
|
|
235
|
+
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
236
|
+
private reportMissingAdapter;
|
|
231
237
|
/**
|
|
232
238
|
* Handle a new WebSocket connection.
|
|
233
239
|
*
|
|
@@ -248,6 +254,19 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
248
254
|
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
249
255
|
* linger in an unregistered state and receive broadcast events.
|
|
250
256
|
*/
|
|
257
|
+
/**
|
|
258
|
+
* Map a Socket.IO handshake onto the transport-agnostic auth context.
|
|
259
|
+
*
|
|
260
|
+
* Socket.IO carries credentials in three places and the authenticator sees one
|
|
261
|
+
* shape: `handshake.auth` is merged into the headers and query it stands in for,
|
|
262
|
+
* and a repeated `ticket` parameter is collapsed to its first value, because the
|
|
263
|
+
* ticket pattern is single-valued and an array reaching an authenticator that
|
|
264
|
+
* expects a string is a bug at the far end.
|
|
265
|
+
*
|
|
266
|
+
* @param socket - The connecting Socket.IO socket.
|
|
267
|
+
* @returns The context handed to `IConnectionAuthenticator.authenticate`.
|
|
268
|
+
*/
|
|
269
|
+
private buildAuthContext;
|
|
251
270
|
handleConnection(socket: Socket): Promise<void>;
|
|
252
271
|
/** Handle a WebSocket disconnection — unregister the connection. */
|
|
253
272
|
handleDisconnect(socket: Socket): Promise<void>;
|
|
@@ -285,7 +304,7 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
285
304
|
* (spec §11.5).
|
|
286
305
|
*/
|
|
287
306
|
declare class RealtimeIoAdapter extends IoAdapter {
|
|
288
|
-
private readonly
|
|
307
|
+
private readonly adapterLogger;
|
|
289
308
|
private readonly options;
|
|
290
309
|
constructor(app: INestApplicationContext);
|
|
291
310
|
/**
|
|
@@ -226,8 +226,14 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
226
226
|
private readonly logger;
|
|
227
227
|
server: Server;
|
|
228
228
|
constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions);
|
|
229
|
+
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
230
|
+
private readonly authenticated;
|
|
231
|
+
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
232
|
+
private readonly authenticateHandshake;
|
|
229
233
|
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
230
234
|
afterInit(server: Server): void;
|
|
235
|
+
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
236
|
+
private reportMissingAdapter;
|
|
231
237
|
/**
|
|
232
238
|
* Handle a new WebSocket connection.
|
|
233
239
|
*
|
|
@@ -248,6 +254,19 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
248
254
|
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
249
255
|
* linger in an unregistered state and receive broadcast events.
|
|
250
256
|
*/
|
|
257
|
+
/**
|
|
258
|
+
* Map a Socket.IO handshake onto the transport-agnostic auth context.
|
|
259
|
+
*
|
|
260
|
+
* Socket.IO carries credentials in three places and the authenticator sees one
|
|
261
|
+
* shape: `handshake.auth` is merged into the headers and query it stands in for,
|
|
262
|
+
* and a repeated `ticket` parameter is collapsed to its first value, because the
|
|
263
|
+
* ticket pattern is single-valued and an array reaching an authenticator that
|
|
264
|
+
* expects a string is a bug at the far end.
|
|
265
|
+
*
|
|
266
|
+
* @param socket - The connecting Socket.IO socket.
|
|
267
|
+
* @returns The context handed to `IConnectionAuthenticator.authenticate`.
|
|
268
|
+
*/
|
|
269
|
+
private buildAuthContext;
|
|
251
270
|
handleConnection(socket: Socket): Promise<void>;
|
|
252
271
|
/** Handle a WebSocket disconnection — unregister the connection. */
|
|
253
272
|
handleDisconnect(socket: Socket): Promise<void>;
|
|
@@ -285,7 +304,7 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
285
304
|
* (spec §11.5).
|
|
286
305
|
*/
|
|
287
306
|
declare class RealtimeIoAdapter extends IoAdapter {
|
|
288
|
-
private readonly
|
|
307
|
+
private readonly adapterLogger;
|
|
289
308
|
private readonly options;
|
|
290
309
|
constructor(app: INestApplicationContext);
|
|
291
310
|
/**
|
package/dist/websocket/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Injectable, Inject, Logger, Global, Module } from '@nestjs/common';
|
|
2
|
-
import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, ROOM_PREFIXES, REALTIME_ERROR_CODES, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
|
|
2
|
+
import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, ROOM_PREFIXES, REALTIME_ERROR_CODES, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
|
|
3
3
|
import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
|
|
4
4
|
import { IoAdapter } from '@nestjs/platform-socket.io';
|
|
5
5
|
|
|
@@ -391,6 +391,86 @@ CompositeTransport = __decorateClass([
|
|
|
391
391
|
__decorateParam(0, Inject(SseTransport)),
|
|
392
392
|
__decorateParam(1, Inject(WebSocketTransport))
|
|
393
393
|
], CompositeTransport);
|
|
394
|
+
var realtimeServers = /* @__PURE__ */ new WeakSet();
|
|
395
|
+
function isRealtimeIoServer(server) {
|
|
396
|
+
return typeof server === "object" && server !== null && realtimeServers.has(server);
|
|
397
|
+
}
|
|
398
|
+
var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
399
|
+
adapterLogger = new Logger(_RealtimeIoAdapter.name);
|
|
400
|
+
options;
|
|
401
|
+
constructor(app) {
|
|
402
|
+
super(app);
|
|
403
|
+
this.options = app.get(REALTIME_OPTIONS_TOKEN);
|
|
404
|
+
}
|
|
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
|
+
create(port, options) {
|
|
417
|
+
const server = super.create(port, options);
|
|
418
|
+
const ns = this.options.websocket?.namespace;
|
|
419
|
+
if (ns && ns !== "/" && typeof server.of === "function") {
|
|
420
|
+
const namespace = server.of(ns);
|
|
421
|
+
realtimeServers.add(namespace);
|
|
422
|
+
return namespace;
|
|
423
|
+
}
|
|
424
|
+
return server;
|
|
425
|
+
}
|
|
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 (so the package stays an optional peer
|
|
431
|
+
* dep — its absence does not crash the lib).
|
|
432
|
+
*/
|
|
433
|
+
createIOServer(port, opts) {
|
|
434
|
+
const wsOpts = this.options.websocket ?? {};
|
|
435
|
+
const mergedOpts = {
|
|
436
|
+
...opts,
|
|
437
|
+
cors: wsOpts.cors ?? opts?.cors,
|
|
438
|
+
pingInterval: wsOpts.pingIntervalMs ?? 25e3,
|
|
439
|
+
pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
|
|
440
|
+
maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
|
|
441
|
+
};
|
|
442
|
+
const server = super.createIOServer(port, mergedOpts);
|
|
443
|
+
if (wsOpts.redisAdapter?.pubClient) {
|
|
444
|
+
this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
|
|
445
|
+
}
|
|
446
|
+
realtimeServers.add(server);
|
|
447
|
+
return server;
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Lazily load and install `@socket.io/redis-adapter`.
|
|
451
|
+
*
|
|
452
|
+
* Uses a dynamic `require` so the package stays optional — absent peers do
|
|
453
|
+
* not crash the lib. A load or install failure is logged and tolerated;
|
|
454
|
+
* the lib degrades gracefully to single-instance mode.
|
|
455
|
+
*/
|
|
456
|
+
installRedisAdapter(server, pubClient) {
|
|
457
|
+
try {
|
|
458
|
+
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
459
|
+
const pub = pubClient;
|
|
460
|
+
const sub = pub.duplicate();
|
|
461
|
+
server.adapter(createAdapter(pub, sub));
|
|
462
|
+
this.adapterLogger.log(
|
|
463
|
+
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
464
|
+
);
|
|
465
|
+
} catch (err) {
|
|
466
|
+
this.adapterLogger.error(
|
|
467
|
+
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
|
|
473
|
+
// src/websocket/transports/websocket/realtime.gateway.ts
|
|
394
474
|
function firstQueryValue(value) {
|
|
395
475
|
return Array.isArray(value) ? value[0] : value;
|
|
396
476
|
}
|
|
@@ -403,11 +483,43 @@ var RealtimeGateway = class {
|
|
|
403
483
|
options;
|
|
404
484
|
logger = new Logger(RealtimeGateway.name);
|
|
405
485
|
server;
|
|
486
|
+
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
487
|
+
authenticated = /* @__PURE__ */ new WeakMap();
|
|
488
|
+
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
489
|
+
authenticateHandshake = async (socket, next) => {
|
|
490
|
+
try {
|
|
491
|
+
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
492
|
+
if (!auth) {
|
|
493
|
+
const refusal = new Error(REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
494
|
+
refusal.data = { code: REALTIME_ERROR_CODES.AUTH_FAILED };
|
|
495
|
+
next(refusal);
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
499
|
+
assertIdentityIsNotBlank(resolvedAuth);
|
|
500
|
+
this.authenticated.set(socket, resolvedAuth);
|
|
501
|
+
next();
|
|
502
|
+
} catch (err) {
|
|
503
|
+
this.logger.error(
|
|
504
|
+
`handshake refused for socket ${socket.id}: ${err instanceof Error ? err.message : String(err)}`
|
|
505
|
+
);
|
|
506
|
+
next(new Error("Internal Server Error"));
|
|
507
|
+
}
|
|
508
|
+
};
|
|
406
509
|
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
407
510
|
afterInit(server) {
|
|
511
|
+
server.use(this.authenticateHandshake);
|
|
408
512
|
this.transport.setServer(server);
|
|
513
|
+
if (!isRealtimeIoServer(server)) this.reportMissingAdapter();
|
|
409
514
|
this.logger.log("RealtimeGateway initialized");
|
|
410
515
|
}
|
|
516
|
+
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
517
|
+
reportMissingAdapter() {
|
|
518
|
+
const configured = Object.keys(this.options.websocket ?? {});
|
|
519
|
+
this.logger.error(
|
|
520
|
+
"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'."
|
|
521
|
+
);
|
|
522
|
+
}
|
|
411
523
|
/**
|
|
412
524
|
* Handle a new WebSocket connection.
|
|
413
525
|
*
|
|
@@ -428,34 +540,58 @@ var RealtimeGateway = class {
|
|
|
428
540
|
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
429
541
|
* linger in an unregistered state and receive broadcast events.
|
|
430
542
|
*/
|
|
543
|
+
/**
|
|
544
|
+
* Map a Socket.IO handshake onto the transport-agnostic auth context.
|
|
545
|
+
*
|
|
546
|
+
* Socket.IO carries credentials in three places and the authenticator sees one
|
|
547
|
+
* shape: `handshake.auth` is merged into the headers and query it stands in for,
|
|
548
|
+
* and a repeated `ticket` parameter is collapsed to its first value, because the
|
|
549
|
+
* ticket pattern is single-valued and an array reaching an authenticator that
|
|
550
|
+
* expects a string is a bug at the far end.
|
|
551
|
+
*
|
|
552
|
+
* @param socket - The connecting Socket.IO socket.
|
|
553
|
+
* @returns The context handed to `IConnectionAuthenticator.authenticate`.
|
|
554
|
+
*/
|
|
555
|
+
buildAuthContext(socket) {
|
|
556
|
+
const { handshake } = socket;
|
|
557
|
+
const headers = this.normalizeHeaders(handshake.headers);
|
|
558
|
+
const query = { ...handshake.query };
|
|
559
|
+
const handshakeAuth = handshake.auth;
|
|
560
|
+
if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
|
|
561
|
+
if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
|
|
562
|
+
const ticket = firstQueryValue(query["ticket"]);
|
|
563
|
+
if (ticket !== void 0) query["ticket"] = ticket;
|
|
564
|
+
return {
|
|
565
|
+
cookies: parseCookieHeader(handshake.headers.cookie ?? ""),
|
|
566
|
+
headers,
|
|
567
|
+
query,
|
|
568
|
+
ip: handshake.address,
|
|
569
|
+
userAgent: handshake.headers["user-agent"],
|
|
570
|
+
transport: "websocket"
|
|
571
|
+
};
|
|
572
|
+
}
|
|
431
573
|
async handleConnection(socket) {
|
|
432
574
|
try {
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
headers,
|
|
444
|
-
query,
|
|
445
|
-
ip: handshake.address,
|
|
446
|
-
userAgent: handshake.headers["user-agent"],
|
|
447
|
-
transport: "websocket"
|
|
448
|
-
};
|
|
449
|
-
const auth = await this.transport.authenticator().authenticate(ctx);
|
|
450
|
-
if (!auth) {
|
|
451
|
-
socket.disconnect(true);
|
|
452
|
-
return;
|
|
575
|
+
let resolvedAuth = this.authenticated.get(socket);
|
|
576
|
+
this.authenticated.delete(socket);
|
|
577
|
+
if (!resolvedAuth) {
|
|
578
|
+
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
579
|
+
if (!auth) {
|
|
580
|
+
socket.disconnect(true);
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
584
|
+
assertIdentityIsNotBlank(resolvedAuth);
|
|
453
585
|
}
|
|
454
|
-
await this.transport.registerSocket(socket,
|
|
586
|
+
await this.transport.registerSocket(socket, resolvedAuth);
|
|
455
587
|
if (this.options.websocket?.emitConnectionEvent !== false) {
|
|
456
588
|
socket.emit(RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
|
|
457
589
|
connectionId: socket.id,
|
|
458
|
-
traits: {
|
|
590
|
+
traits: {
|
|
591
|
+
userId: resolvedAuth.userId,
|
|
592
|
+
tenantId: resolvedAuth.tenantId,
|
|
593
|
+
roles: resolvedAuth.roles
|
|
594
|
+
}
|
|
459
595
|
});
|
|
460
596
|
}
|
|
461
597
|
} catch (err) {
|
|
@@ -610,76 +746,5 @@ BymaxRealtimeWebSocketModule = __decorateClass([
|
|
|
610
746
|
Global(),
|
|
611
747
|
Module({})
|
|
612
748
|
], BymaxRealtimeWebSocketModule);
|
|
613
|
-
var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
614
|
-
logger = new Logger(_RealtimeIoAdapter.name);
|
|
615
|
-
options;
|
|
616
|
-
constructor(app) {
|
|
617
|
-
super(app);
|
|
618
|
-
this.options = app.get(REALTIME_OPTIONS_TOKEN);
|
|
619
|
-
}
|
|
620
|
-
/**
|
|
621
|
-
* Bind the gateway to `websocket.namespace` when configured.
|
|
622
|
-
*
|
|
623
|
-
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
624
|
-
* the module options resolve — so the namespace cannot be declared there.
|
|
625
|
-
* Instead we build the root server via `super.create` (which routes through the
|
|
626
|
-
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
627
|
-
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
628
|
-
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
629
|
-
* namespace leaves the root server untouched.
|
|
630
|
-
*/
|
|
631
|
-
create(port, options) {
|
|
632
|
-
const server = super.create(port, options);
|
|
633
|
-
const ns = this.options.websocket?.namespace;
|
|
634
|
-
if (ns && ns !== "/" && typeof server.of === "function") {
|
|
635
|
-
return server.of(ns);
|
|
636
|
-
}
|
|
637
|
-
return server;
|
|
638
|
-
}
|
|
639
|
-
/**
|
|
640
|
-
* Create the Socket.IO server with merged WebSocket options.
|
|
641
|
-
*
|
|
642
|
-
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
643
|
-
* `@socket.io/redis-adapter` lazily (so the package stays an optional peer
|
|
644
|
-
* dep — its absence does not crash the lib).
|
|
645
|
-
*/
|
|
646
|
-
createIOServer(port, opts) {
|
|
647
|
-
const wsOpts = this.options.websocket ?? {};
|
|
648
|
-
const mergedOpts = {
|
|
649
|
-
...opts,
|
|
650
|
-
cors: wsOpts.cors ?? opts?.cors,
|
|
651
|
-
pingInterval: wsOpts.pingIntervalMs ?? 25e3,
|
|
652
|
-
pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
|
|
653
|
-
maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
|
|
654
|
-
};
|
|
655
|
-
const server = super.createIOServer(port, mergedOpts);
|
|
656
|
-
if (wsOpts.redisAdapter?.pubClient) {
|
|
657
|
-
this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
|
|
658
|
-
}
|
|
659
|
-
return server;
|
|
660
|
-
}
|
|
661
|
-
/**
|
|
662
|
-
* Lazily load and install `@socket.io/redis-adapter`.
|
|
663
|
-
*
|
|
664
|
-
* Uses a dynamic `require` so the package stays optional — absent peers do
|
|
665
|
-
* not crash the lib. A load or install failure is logged and tolerated;
|
|
666
|
-
* the lib degrades gracefully to single-instance mode.
|
|
667
|
-
*/
|
|
668
|
-
installRedisAdapter(server, pubClient) {
|
|
669
|
-
try {
|
|
670
|
-
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
671
|
-
const pub = pubClient;
|
|
672
|
-
const sub = pub.duplicate();
|
|
673
|
-
server.adapter(createAdapter(pub, sub));
|
|
674
|
-
this.logger.log(
|
|
675
|
-
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
676
|
-
);
|
|
677
|
-
} catch (err) {
|
|
678
|
-
this.logger.error(
|
|
679
|
-
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
680
|
-
);
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
};
|
|
684
749
|
|
|
685
750
|
export { BymaxRealtimeWebSocketModule, CompositeTransport, RealtimeGateway, RealtimeIoAdapter, WebSocketTransport };
|
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.2",
|
|
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",
|