@bymax-one/nest-realtime 1.1.2 → 1.2.1

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.
@@ -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, parseCookieHeader, resolveAuthTenant, assertIdentityIsNotBlank, 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
 
@@ -104,7 +104,12 @@ var WebSocketTransport = class {
104
104
  connectedAt,
105
105
  subject: null,
106
106
  close$: null,
107
- originalAuth: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
107
+ originalAuth: {
108
+ userId: auth.userId,
109
+ tenantId: auth.tenantId,
110
+ roles: auth.roles,
111
+ metadata: auth.metadata
112
+ }
108
113
  });
109
114
  await socket.join(`${ROOM_PREFIXES.USER}:${auth.userId}`);
110
115
  if (auth.tenantId) await socket.join(`${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
@@ -117,6 +122,7 @@ var WebSocketTransport = class {
117
122
  userId: auth.userId,
118
123
  tenantId: auth.tenantId,
119
124
  roles: auth.roles,
125
+ metadata: auth.metadata,
120
126
  transport: "websocket",
121
127
  ip: socket.handshake.address,
122
128
  userAgent: socket.handshake.headers["user-agent"],
@@ -142,6 +148,7 @@ var WebSocketTransport = class {
142
148
  userId: record.userId,
143
149
  tenantId: record.tenantId,
144
150
  roles: record.originalAuth.roles,
151
+ metadata: record.originalAuth.metadata,
145
152
  transport: "websocket",
146
153
  ip: record.ip,
147
154
  userAgent: record.userAgent,
@@ -421,34 +428,54 @@ var RealtimeGateway = class {
421
428
  * Fail-closed: any thrown error disconnects the socket immediately so it cannot
422
429
  * linger in an unregistered state and receive broadcast events.
423
430
  */
431
+ /**
432
+ * Map a Socket.IO handshake onto the transport-agnostic auth context.
433
+ *
434
+ * Socket.IO carries credentials in three places and the authenticator sees one
435
+ * shape: `handshake.auth` is merged into the headers and query it stands in for,
436
+ * and a repeated `ticket` parameter is collapsed to its first value, because the
437
+ * ticket pattern is single-valued and an array reaching an authenticator that
438
+ * expects a string is a bug at the far end.
439
+ *
440
+ * @param socket - The connecting Socket.IO socket.
441
+ * @returns The context handed to `IConnectionAuthenticator.authenticate`.
442
+ */
443
+ buildAuthContext(socket) {
444
+ const { handshake } = socket;
445
+ const headers = this.normalizeHeaders(handshake.headers);
446
+ const query = { ...handshake.query };
447
+ const handshakeAuth = handshake.auth;
448
+ if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
449
+ if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
450
+ const ticket = firstQueryValue(query["ticket"]);
451
+ if (ticket !== void 0) query["ticket"] = ticket;
452
+ return {
453
+ cookies: parseCookieHeader(handshake.headers.cookie ?? ""),
454
+ headers,
455
+ query,
456
+ ip: handshake.address,
457
+ userAgent: handshake.headers["user-agent"],
458
+ transport: "websocket"
459
+ };
460
+ }
424
461
  async handleConnection(socket) {
425
462
  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: 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);
463
+ const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
443
464
  if (!auth) {
444
465
  socket.disconnect(true);
445
466
  return;
446
467
  }
447
- await this.transport.registerSocket(socket, auth);
468
+ const resolvedAuth = resolveAuthTenant(this.options, auth);
469
+ assertIdentityIsNotBlank(resolvedAuth);
470
+ await this.transport.registerSocket(socket, resolvedAuth);
448
471
  if (this.options.websocket?.emitConnectionEvent !== false) {
449
472
  socket.emit(RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
450
473
  connectionId: socket.id,
451
- traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
474
+ traits: {
475
+ userId: resolvedAuth.userId,
476
+ tenantId: resolvedAuth.tenantId,
477
+ roles: resolvedAuth.roles
478
+ }
452
479
  });
453
480
  }
454
481
  } catch (err) {
@@ -488,7 +515,6 @@ RealtimeGateway = __decorateClass([
488
515
  ], RealtimeGateway);
489
516
 
490
517
  // src/websocket/websocket-wiring.ts
491
- var DEFAULT_ASYNC_ENDPOINT = "/events";
492
518
  var webSocketWiring = {
493
519
  modes: ["websocket", "both"],
494
520
  build(resolved) {
@@ -515,7 +541,7 @@ var webSocketWiring = {
515
541
  gateways: [RealtimeGateway]
516
542
  };
517
543
  },
518
- buildAsync(mode) {
544
+ buildAsync({ mode, sseEndpoint }) {
519
545
  if (mode === "websocket") {
520
546
  return {
521
547
  providers: [
@@ -536,7 +562,7 @@ var webSocketWiring = {
536
562
  RealtimePubSubSubscriber,
537
563
  { provide: REALTIME_TRANSPORT_TOKEN, useExisting: CompositeTransport }
538
564
  ],
539
- controllers: [createSseController(DEFAULT_ASYNC_ENDPOINT)]
565
+ controllers: [createSseController(sseEndpoint)]
540
566
  };
541
567
  }
542
568
  };
@@ -567,9 +593,12 @@ var BymaxRealtimeWebSocketModule = class {
567
593
  * Configure the module asynchronously so options — and the authenticator —
568
594
  * can be resolved through DI.
569
595
  *
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.
596
+ * Controllers are registered at decoration time, so under `'both'` the SSE
597
+ * route comes from `sseEndpoint` on the registration rather than from the
598
+ * `sse.endpoint` the factory resolves — the factory has not run yet when the
599
+ * controller is built. It defaults to `/events`, and a factory that resolves
600
+ * a disagreeing `sse.endpoint` is rejected at bootstrap. `'websocket'`
601
+ * registers no SSE controller, so `sseEndpoint` is rejected there outright.
573
602
  *
574
603
  * @throws when no factory pattern is given, more than one is, or the factory
575
604
  * resolves a transport other than the one declared.
@@ -577,6 +606,7 @@ var BymaxRealtimeWebSocketModule = class {
577
606
  * ```ts
578
607
  * BymaxRealtimeWebSocketModule.forRootAsync({
579
608
  * transport: 'both',
609
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
580
610
  * imports: [ConfigModule],
581
611
  * inject: [ConfigService],
582
612
  * useFactory: (cfg: ConfigService) => ({
@@ -601,7 +631,7 @@ BymaxRealtimeWebSocketModule = __decorateClass([
601
631
  Module({})
602
632
  ], BymaxRealtimeWebSocketModule);
603
633
  var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
604
- logger = new Logger(_RealtimeIoAdapter.name);
634
+ adapterLogger = new Logger(_RealtimeIoAdapter.name);
605
635
  options;
606
636
  constructor(app) {
607
637
  super(app);
@@ -661,11 +691,11 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
661
691
  const pub = pubClient;
662
692
  const sub = pub.duplicate();
663
693
  server.adapter(createAdapter(pub, sub));
664
- this.logger.log(
694
+ this.adapterLogger.log(
665
695
  "Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
666
696
  );
667
697
  } catch (err) {
668
- this.logger.error(
698
+ this.adapterLogger.error(
669
699
  `Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
670
700
  );
671
701
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.1.2",
3
+ "version": "1.2.1",
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",